Home Assistant Unofficial Reference 2024.12.1
coordinator.py
Go to the documentation of this file.
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.shutter import Shutter
11 from iottycloud.verbs import OPEN_PERCENTAGE, RESULT, STATUS
12 
13 from homeassistant.config_entries import ConfigEntry
14 from homeassistant.core import HomeAssistant
15 from homeassistant.helpers import aiohttp_client, device_registry as dr
16 from homeassistant.helpers.config_entry_oauth2_flow import OAuth2Session
17 from homeassistant.helpers.entity import Entity
18 from homeassistant.helpers.update_coordinator import DataUpdateCoordinator
19 
20 from . import api
21 from .const import DOMAIN
22 
23 _LOGGER = logging.getLogger(__name__)
24 
25 UPDATE_INTERVAL = timedelta(seconds=30)
26 
27 
28 @dataclass
29 class IottyData:
30  """iotty data stored in the DataUpdateCoordinator."""
31 
32  devices: list[Device]
33 
34 
36  """Class to manage fetching Iotty data."""
37 
38  config_entry: ConfigEntry
39  _entities: dict[str, Entity]
40  _devices: list[Device]
41  _device_registry: dr.DeviceRegistry
42 
43  def __init__(
44  self, hass: HomeAssistant, entry: ConfigEntry, session: OAuth2Session
45  ) -> None:
46  """Initialize the coordinator."""
47  _LOGGER.debug("Initializing iotty data update coordinator")
48 
49  super().__init__(
50  hass,
51  _LOGGER,
52  name=f"{DOMAIN}_coordinator",
53  update_interval=UPDATE_INTERVAL,
54  )
55 
56  self.config_entryconfig_entryconfig_entry = entry
57  self._entities_entities = {}
58  self._devices_devices = []
59  self.iottyiotty = api.IottyProxy(
60  hass, aiohttp_client.async_get_clientsession(hass), session
61  )
62  self._device_registry_device_registry = dr.async_get(hass)
63 
64  async def _async_setup(self) -> None:
65  """Get devices."""
66  _LOGGER.debug("Fetching devices list from iottyCloud")
67  self._devices_devices = await self.iottyiotty.get_devices()
68  _LOGGER.debug("There are %d devices", len(self._devices_devices))
69 
70  async def _async_update_data(self) -> IottyData:
71  """Fetch data from iottyCloud device."""
72  _LOGGER.debug("Fetching devices status from iottyCloud")
73 
74  current_devices = await self.iottyiotty.get_devices()
75 
76  removed_devices = [
77  d
78  for d in self._devices_devices
79  if not any(x.device_id == d.device_id for x in current_devices)
80  ]
81 
82  for removed_device in removed_devices:
83  device_to_remove = self._device_registry_device_registry.async_get_device(
84  {(DOMAIN, removed_device.device_id)}
85  )
86  if device_to_remove is not None:
87  self._device_registry_device_registry.async_remove_device(device_to_remove.id)
88 
89  self._devices_devices = current_devices
90 
91  for device in self._devices_devices:
92  res = await self.iottyiotty.get_status(device.device_id)
93  json = res.get(RESULT, {})
94  if (
95  not isinstance(res, dict)
96  or RESULT not in res
97  or not isinstance(json := res[RESULT], dict)
98  or not (status := json.get(STATUS))
99  ):
100  _LOGGER.warning("Unable to read status for device %s", device.device_id)
101  else:
102  _LOGGER.debug(
103  "Retrieved status: '%s' for device %s", status, device.device_id
104  )
105  device.update_status(status)
106  if isinstance(device, Shutter) and isinstance(
107  percentage := json.get(OPEN_PERCENTAGE), int
108  ):
109  device.update_percentage(percentage)
110 
111  return IottyData(self._devices_devices)
None __init__(self, HomeAssistant hass, ConfigEntry entry, OAuth2Session session)
Definition: coordinator.py:45
def get_status(hass, host, port)
Definition: panel.py:387