Home Assistant Unofficial Reference 2024.12.1
coordinator.py
Go to the documentation of this file.
1 """Define an object to manage fetching Touchline SL data."""
2 
3 from __future__ import annotations
4 
5 from dataclasses import dataclass
6 from datetime import timedelta
7 import logging
8 
9 from pytouchlinesl import Module, Zone
10 from pytouchlinesl.client import RothAPIError
11 from pytouchlinesl.client.models import GlobalScheduleModel
12 
13 from homeassistant.core import HomeAssistant
14 from homeassistant.exceptions import ConfigEntryAuthFailed
15 from homeassistant.helpers.update_coordinator import DataUpdateCoordinator, UpdateFailed
16 
17 _LOGGER = logging.getLogger(__name__)
18 
19 
20 @dataclass
22  """Provide type safe way of accessing module data from the coordinator."""
23 
24  module: Module
25  zones: dict[int, Zone]
26  schedules: dict[str, GlobalScheduleModel]
27 
28 
30  """A coordinator to manage the fetching of Touchline SL data."""
31 
32  def __init__(self, hass: HomeAssistant, module: Module) -> None:
33  """Initialize coordinator."""
34  super().__init__(
35  hass,
36  logger=_LOGGER,
37  name=f"Touchline SL ({module.name})",
38  update_interval=timedelta(seconds=30),
39  )
40 
41  self.modulemodule = module
42 
43  async def _async_update_data(self) -> TouchlineSLModuleData:
44  """Fetch data from the upstream API and pre-process into the right format."""
45  try:
46  zones = await self.modulemodule.zones()
47  schedules = await self.modulemodule.schedules()
48  except RothAPIError as error:
49  if error.status == 401:
50  # Trigger a reauthentication if the data update fails due to
51  # bad authentication.
52  raise ConfigEntryAuthFailed from error
53  raise UpdateFailed(error) from error
54 
55  return TouchlineSLModuleData(
56  module=self.modulemodule,
57  zones={z.id: z for z in zones},
58  schedules={s.name: s for s in schedules},
59  )