Home Assistant Unofficial Reference 2024.12.1
coordinator.py
Go to the documentation of this file.
1 """DataUpdateCoordinator for the BSB-Lan integration."""
2 
3 from dataclasses import dataclass
4 from datetime import timedelta
5 from random import randint
6 
7 from bsblan import BSBLAN, BSBLANConnectionError, HotWaterState, Sensor, State
8 
9 from homeassistant.config_entries import ConfigEntry
10 from homeassistant.const import CONF_HOST
11 from homeassistant.core import HomeAssistant
12 from homeassistant.helpers.update_coordinator import DataUpdateCoordinator, UpdateFailed
13 
14 from .const import DOMAIN, LOGGER, SCAN_INTERVAL
15 
16 
17 @dataclass
19  """BSBLan data stored in the Home Assistant data object."""
20 
21  state: State
22  sensor: Sensor
23  dhw: HotWaterState
24 
25 
26 class BSBLanUpdateCoordinator(DataUpdateCoordinator[BSBLanCoordinatorData]):
27  """The BSB-Lan update coordinator."""
28 
29  config_entry: ConfigEntry
30 
31  def __init__(
32  self,
33  hass: HomeAssistant,
34  config_entry: ConfigEntry,
35  client: BSBLAN,
36  ) -> None:
37  """Initialize the BSB-Lan coordinator."""
38  super().__init__(
39  hass,
40  logger=LOGGER,
41  name=f"{DOMAIN}_{config_entry.data[CONF_HOST]}",
42  update_interval=self._get_update_interval_get_update_interval(),
43  )
44  self.clientclient = client
45 
46  def _get_update_interval(self) -> timedelta:
47  """Get the update interval with a random offset.
48 
49  Use the default scan interval and add a random number of seconds to avoid timeouts when
50  the BSB-Lan device is already/still busy retrieving data,
51  e.g. for MQTT or internal logging.
52  """
53  return SCAN_INTERVAL + timedelta(seconds=randint(1, 8))
54 
55  async def _async_update_data(self) -> BSBLanCoordinatorData:
56  """Get state and sensor data from BSB-Lan device."""
57  try:
58  # initialize the client, this is cached and will only be called once
59  await self.clientclient.initialize()
60 
61  state = await self.clientclient.state()
62  sensor = await self.clientclient.sensor()
63  dhw = await self.clientclient.hot_water_state()
64  except BSBLANConnectionError as err:
65  host = self.config_entryconfig_entry.data[CONF_HOST] if self.config_entryconfig_entry else "unknown"
66  raise UpdateFailed(
67  f"Error while establishing connection with BSB-Lan device at {host}"
68  ) from err
69 
71  return BSBLanCoordinatorData(state=state, sensor=sensor, dhw=dhw)
None __init__(self, HomeAssistant hass, ConfigEntry config_entry, BSBLAN client)
Definition: coordinator.py:36
bool state(HomeAssistant hass, str|State|None entity, Any req_state, timedelta|None for_period=None, str|None attribute=None, TemplateVarsType variables=None)
Definition: condition.py:551