|
| 1 | +"""DataUpdateCoordinator for iotty.""" |
| 2 | + |
| 3 | +from __future__ import annotations |
| 4 | + |
| 5 | +from dataclasses import dataclass |
| 6 | +from datetime import timedelta |
| 7 | +import logging |
| 8 | + |
| 9 | +from iottycloud.device import Device |
| 10 | +from iottycloud.verbs import RESULT, STATUS |
| 11 | + |
| 12 | +from homeassistant.config_entries import ConfigEntry |
| 13 | +from homeassistant.core import HomeAssistant |
| 14 | +from homeassistant.helpers import aiohttp_client, device_registry as dr |
| 15 | +from homeassistant.helpers.config_entry_oauth2_flow import OAuth2Session |
| 16 | +from homeassistant.helpers.entity import Entity |
| 17 | +from homeassistant.helpers.update_coordinator import DataUpdateCoordinator |
| 18 | + |
| 19 | +from . import api |
| 20 | +from .const import DOMAIN |
| 21 | + |
| 22 | +_LOGGER = logging.getLogger(__name__) |
| 23 | + |
| 24 | +UPDATE_INTERVAL = timedelta(seconds=30) |
| 25 | + |
| 26 | + |
| 27 | +@dataclass |
| 28 | +class IottyData: |
| 29 | + """iotty data stored in the DataUpdateCoordinator.""" |
| 30 | + |
| 31 | + devices: list[Device] |
| 32 | + |
| 33 | + |
| 34 | +class IottyDataUpdateCoordinator(DataUpdateCoordinator[IottyData]): |
| 35 | + """Class to manage fetching Iotty data.""" |
| 36 | + |
| 37 | + config_entry: ConfigEntry |
| 38 | + _entities: dict[str, Entity] |
| 39 | + _devices: list[Device] |
| 40 | + _device_registry: dr.DeviceRegistry |
| 41 | + |
| 42 | + def __init__( |
| 43 | + self, hass: HomeAssistant, entry: ConfigEntry, session: OAuth2Session |
| 44 | + ) -> None: |
| 45 | + """Initialize the coordinator.""" |
| 46 | + _LOGGER.debug("Initializing iotty data update coordinator") |
| 47 | + |
| 48 | + super().__init__( |
| 49 | + hass, |
| 50 | + _LOGGER, |
| 51 | + name=f"{DOMAIN}_coordinator", |
| 52 | + update_interval=UPDATE_INTERVAL, |
| 53 | + ) |
| 54 | + |
| 55 | + self.config_entry = entry |
| 56 | + self._entities = {} |
| 57 | + self._devices = [] |
| 58 | + self.iotty = api.IottyProxy( |
| 59 | + hass, aiohttp_client.async_get_clientsession(hass), session |
| 60 | + ) |
| 61 | + self._device_registry = dr.async_get(hass) |
| 62 | + |
| 63 | + async def async_config_entry_first_refresh(self) -> None: |
| 64 | + """Override the first refresh to also fetch iotty devices list.""" |
| 65 | + _LOGGER.debug("Fetching devices list from iottyCloud") |
| 66 | + self._devices = await self.iotty.get_devices() |
| 67 | + _LOGGER.debug("There are %d devices", len(self._devices)) |
| 68 | + |
| 69 | + await super().async_config_entry_first_refresh() |
| 70 | + |
| 71 | + async def _async_update_data(self) -> IottyData: |
| 72 | + """Fetch data from iottyCloud device.""" |
| 73 | + _LOGGER.debug("Fetching devices status from iottyCloud") |
| 74 | + |
| 75 | + current_devices = await self.iotty.get_devices() |
| 76 | + |
| 77 | + removed_devices = [ |
| 78 | + d |
| 79 | + for d in self._devices |
| 80 | + if not any(x.device_id == d.device_id for x in current_devices) |
| 81 | + ] |
| 82 | + |
| 83 | + for removed_device in removed_devices: |
| 84 | + device_to_remove = self._device_registry.async_get_device( |
| 85 | + {(DOMAIN, removed_device.device_id)} |
| 86 | + ) |
| 87 | + if device_to_remove is not None: |
| 88 | + self._device_registry.async_remove_device(device_to_remove.id) |
| 89 | + |
| 90 | + self._devices = current_devices |
| 91 | + |
| 92 | + for device in self._devices: |
| 93 | + res = await self.iotty.get_status(device.device_id) |
| 94 | + json = res.get(RESULT, {}) |
| 95 | + if ( |
| 96 | + not isinstance(res, dict) |
| 97 | + or RESULT not in res |
| 98 | + or not isinstance(json := res[RESULT], dict) |
| 99 | + or not (status := json.get(STATUS)) |
| 100 | + ): |
| 101 | + _LOGGER.warning("Unable to read status for device %s", device.device_id) |
| 102 | + else: |
| 103 | + _LOGGER.debug( |
| 104 | + "Retrieved status: '%s' for device %s", status, device.device_id |
| 105 | + ) |
| 106 | + device.update_status(status) |
| 107 | + |
| 108 | + return IottyData(self._devices) |
0 commit comments