Migrate microsoft_face to EntityComponent (#94338)

This commit is contained in:
Erik Montnemery 2023-06-09 13:15:35 +02:00 committed by GitHub
parent c984604a6c
commit 239e2d9820
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

View File

@ -17,6 +17,7 @@ from homeassistant.exceptions import HomeAssistantError
from homeassistant.helpers.aiohttp_client import async_get_clientsession
import homeassistant.helpers.config_validation as cv
from homeassistant.helpers.entity import Entity
from homeassistant.helpers.entity_component import EntityComponent
from homeassistant.helpers.typing import ConfigType
from homeassistant.util import slugify
@ -73,12 +74,16 @@ SCHEMA_TRAIN_SERVICE = vol.Schema({vol.Required(ATTR_GROUP): cv.slugify})
async def async_setup(hass: HomeAssistant, config: ConfigType) -> bool:
"""Set up Microsoft Face."""
component = EntityComponent[MicrosoftFaceGroupEntity](
logging.getLogger(__name__), DOMAIN, hass
)
entities: dict[str, MicrosoftFaceGroupEntity] = {}
face = MicrosoftFace(
hass,
config[DOMAIN].get(CONF_AZURE_REGION),
config[DOMAIN].get(CONF_API_KEY),
config[DOMAIN].get(CONF_TIMEOUT),
component,
entities,
)
@ -99,9 +104,12 @@ async def async_setup(hass: HomeAssistant, config: ConfigType) -> bool:
try:
await face.call_api("put", f"persongroups/{g_id}", {"name": name})
face.store[g_id] = {}
old_entity = entities.pop(g_id, None)
if old_entity:
await component.async_remove_entity(old_entity.entity_id)
entities[g_id] = MicrosoftFaceGroupEntity(hass, face, g_id, name)
entities[g_id].async_write_ha_state()
await component.async_add_entities([entities[g_id]])
except HomeAssistantError as err:
_LOGGER.error("Can't create group '%s' with error: %s", g_id, err)
@ -118,7 +126,7 @@ async def async_setup(hass: HomeAssistant, config: ConfigType) -> bool:
face.store.pop(g_id)
entity = entities.pop(g_id)
hass.states.async_remove(entity.entity_id, service.context)
await component.async_remove_entity(entity.entity_id)
except HomeAssistantError as err:
_LOGGER.error("Can't delete group '%s' with error: %s", g_id, err)
@ -244,7 +252,7 @@ class MicrosoftFaceGroupEntity(Entity):
class MicrosoftFace:
"""Microsoft Face api for Home Assistant."""
def __init__(self, hass, server_loc, api_key, timeout, entities):
def __init__(self, hass, server_loc, api_key, timeout, component, entities):
"""Initialize Microsoft Face api."""
self.hass = hass
self.websession = async_get_clientsession(hass)
@ -252,6 +260,7 @@ class MicrosoftFace:
self._api_key = api_key
self._server_url = f"https://{server_loc}.{FACE_API_URL}"
self._store = {}
self._component: EntityComponent[MicrosoftFaceGroupEntity] = component
self._entities = entities
@property
@ -263,25 +272,30 @@ class MicrosoftFace:
"""Load all group/person data into local store."""
groups = await self.call_api("get", "persongroups")
tasks = []
remove_tasks = []
new_entities = []
for group in groups:
g_id = group["personGroupId"]
self._store[g_id] = {}
old_entity = self._entities.pop(g_id, None)
if old_entity:
remove_tasks.append(
self._component.async_remove_entity(old_entity.entity_id)
)
self._entities[g_id] = MicrosoftFaceGroupEntity(
self.hass, self, g_id, group["name"]
)
new_entities.append(self._entities[g_id])
persons = await self.call_api("get", f"persongroups/{g_id}/persons")
for person in persons:
self._store[g_id][person["name"]] = person["personId"]
tasks.append(
asyncio.create_task(self._entities[g_id].async_update_ha_state())
)
if tasks:
await asyncio.wait(tasks)
if remove_tasks:
await asyncio.gather(remove_tasks)
await self._component.async_add_entities(new_entities)
async def call_api(self, method, function, data=None, binary=False, params=None):
"""Make an api call."""