Home Assistant Unofficial Reference 2024.12.1
coordinator.py
Go to the documentation of this file.
1 """DataUpdateCoordinator for Ista EcoTrend integration."""
2 
3 from __future__ import annotations
4 
5 from datetime import timedelta
6 import logging
7 from typing import Any
8 
9 from pyecotrend_ista import KeycloakError, LoginError, PyEcotrendIsta, ServerError
10 
11 from homeassistant.config_entries import ConfigEntry
12 from homeassistant.const import CONF_EMAIL
13 from homeassistant.core import HomeAssistant
14 from homeassistant.exceptions import ConfigEntryAuthFailed
15 from homeassistant.helpers.update_coordinator import DataUpdateCoordinator, UpdateFailed
16 
17 from .const import DOMAIN
18 
19 _LOGGER = logging.getLogger(__name__)
20 
21 
22 class IstaCoordinator(DataUpdateCoordinator[dict[str, Any]]):
23  """Ista EcoTrend data update coordinator."""
24 
25  config_entry: ConfigEntry
26 
27  def __init__(self, hass: HomeAssistant, ista: PyEcotrendIsta) -> None:
28  """Initialize ista EcoTrend data update coordinator."""
29  super().__init__(
30  hass,
31  _LOGGER,
32  name=DOMAIN,
33  update_interval=timedelta(days=1),
34  )
35  self.istaista = ista
36  self.detailsdetails: dict[str, Any] = {}
37 
38  async def _async_update_data(self):
39  """Fetch ista EcoTrend data."""
40 
41  try:
42  await self.hasshass.async_add_executor_job(self.istaista.login)
43 
44  if not self.detailsdetails:
45  self.detailsdetails = await self.async_get_detailsasync_get_details()
46 
47  return await self.hasshass.async_add_executor_job(self.get_consumption_dataget_consumption_data)
48 
49  except ServerError as e:
50  raise UpdateFailed(
51  "Unable to connect and retrieve data from ista EcoTrend, try again later"
52  ) from e
53  except (LoginError, KeycloakError) as e:
55  translation_domain=DOMAIN,
56  translation_key="authentication_exception",
57  translation_placeholders={
58  CONF_EMAIL: self.config_entryconfig_entry.data[CONF_EMAIL]
59  },
60  ) from e
61 
62  def get_consumption_data(self) -> dict[str, Any]:
63  """Get raw json data for all consumption units."""
64 
65  return {
66  consumption_unit: self.istaista.get_consumption_data(consumption_unit)
67  for consumption_unit in self.istaista.get_uuids()
68  }
69 
70  async def async_get_details(self) -> dict[str, Any]:
71  """Retrieve details of consumption units."""
72 
73  result = await self.hasshass.async_add_executor_job(
74  self.istaista.get_consumption_unit_details
75  )
76 
77  return {
78  consumption_unit: next(
79  details
80  for details in result["consumptionUnits"]
81  if details["id"] == consumption_unit
82  )
83  for consumption_unit in self.istaista.get_uuids()
84  }
None __init__(self, HomeAssistant hass, PyEcotrendIsta ista)
Definition: coordinator.py:27