Home Assistant Unofficial Reference 2024.12.1
coordinator.py
Go to the documentation of this file.
1 """The Things Network's integration DataUpdateCoordinator."""
2 
3 from datetime import timedelta
4 import logging
5 
6 from ttn_client import TTNAuthError, TTNClient
7 
8 from homeassistant.config_entries import ConfigEntry
9 from homeassistant.const import CONF_API_KEY, CONF_HOST
10 from homeassistant.core import HomeAssistant
11 from homeassistant.exceptions import ConfigEntryAuthFailed
12 from homeassistant.helpers.update_coordinator import DataUpdateCoordinator
13 
14 from .const import CONF_APP_ID, POLLING_PERIOD_S
15 
16 _LOGGER = logging.getLogger(__name__)
17 
18 
19 class TTNCoordinator(DataUpdateCoordinator[TTNClient.DATA_TYPE]):
20  """TTN coordinator."""
21 
22  def __init__(self, hass: HomeAssistant, entry: ConfigEntry) -> None:
23  """Initialize my coordinator."""
24  super().__init__(
25  hass,
26  _LOGGER,
27  # Name of the data. For logging purposes.
28  name=f"TheThingsNetwork_{entry.data[CONF_APP_ID]}",
29  # Polling interval. Will only be polled if there are subscribers.
30  update_interval=timedelta(
31  seconds=POLLING_PERIOD_S,
32  ),
33  )
34 
35  self._client_client = TTNClient(
36  entry.data[CONF_HOST],
37  entry.data[CONF_APP_ID],
38  entry.data[CONF_API_KEY],
39  push_callback=self._push_callback_push_callback,
40  )
41 
42  async def _async_update_data(self) -> TTNClient.DATA_TYPE:
43  """Fetch data from API endpoint.
44 
45  This is the place to pre-process the data to lookup tables
46  so entities can quickly look up their data.
47  """
48  try:
49  # Note: asyncio.TimeoutError and aiohttp.ClientError are already
50  # handled by the data update coordinator.
51  measurements = await self._client_client.fetch_data()
52  except TTNAuthError as err:
53  # Raising ConfigEntryAuthFailed will cancel future updates
54  # and start a config flow with SOURCE_REAUTH (async_step_reauth)
55  _LOGGER.error("TTNAuthError")
56  raise ConfigEntryAuthFailed from err
57  else:
58  # Return measurements
59  _LOGGER.debug("fetched data: %s", measurements)
60  return measurements
61 
62  async def _push_callback(self, data: TTNClient.DATA_TYPE) -> None:
63  _LOGGER.debug("pushed data: %s", data)
64 
65  # Push data to entities
66  self.async_set_updated_dataasync_set_updated_data(data)
None __init__(self, HomeAssistant hass, ConfigEntry entry)
Definition: coordinator.py:22
MetOfficeData fetch_data(datapoint.Manager connection, Site site, str mode)
Definition: helpers.py:32