Home Assistant Unofficial Reference 2024.12.1
coordinator.py
Go to the documentation of this file.
1 """Electric Kiwi coordinators."""
2 
3 import asyncio
4 from collections import OrderedDict
5 from datetime import timedelta
6 import logging
7 
8 from electrickiwi_api import ElectricKiwiApi
9 from electrickiwi_api.exceptions import ApiException, AuthException
10 from electrickiwi_api.model import AccountBalance, Hop, HopIntervals
11 
12 from homeassistant.core import HomeAssistant
13 from homeassistant.exceptions import ConfigEntryAuthFailed
14 from homeassistant.helpers.update_coordinator import DataUpdateCoordinator, UpdateFailed
15 
16 _LOGGER = logging.getLogger(__name__)
17 
18 ACCOUNT_SCAN_INTERVAL = timedelta(hours=6)
19 HOP_SCAN_INTERVAL = timedelta(minutes=20)
20 
21 
23  """ElectricKiwi Account Data object."""
24 
25  def __init__(self, hass: HomeAssistant, ek_api: ElectricKiwiApi) -> None:
26  """Initialize ElectricKiwiAccountDataCoordinator."""
27  super().__init__(
28  hass,
29  _LOGGER,
30  name="Electric Kiwi Account Data",
31  update_interval=ACCOUNT_SCAN_INTERVAL,
32  )
33  self._ek_api_ek_api = ek_api
34 
35  async def _async_update_data(self) -> AccountBalance:
36  """Fetch data from Account balance API endpoint."""
37  try:
38  async with asyncio.timeout(60):
39  return await self._ek_api_ek_api.get_account_balance()
40  except AuthException as auth_err:
41  raise ConfigEntryAuthFailed from auth_err
42  except ApiException as api_err:
43  raise UpdateFailed(
44  f"Error communicating with EK API: {api_err}"
45  ) from api_err
46 
47 
49  """ElectricKiwi HOP Data object."""
50 
51  def __init__(self, hass: HomeAssistant, ek_api: ElectricKiwiApi) -> None:
52  """Initialize ElectricKiwiAccountDataCoordinator."""
53  super().__init__(
54  hass,
55  _LOGGER,
56  # Name of the data. For logging purposes.
57  name="Electric Kiwi HOP Data",
58  # Polling interval. Will only be polled if there are subscribers.
59  update_interval=HOP_SCAN_INTERVAL,
60  )
61  self._ek_api_ek_api = ek_api
62  self.hop_intervalshop_intervals: HopIntervals | None = None
63 
64  def get_hop_options(self) -> dict[str, int]:
65  """Get the hop interval options for selection."""
66  if self.hop_intervalshop_intervals is not None:
67  return {
68  f"{v.start_time} - {v.end_time}": k
69  for k, v in self.hop_intervalshop_intervals.intervals.items()
70  }
71  return {}
72 
73  async def async_update_hop(self, hop_interval: int) -> Hop:
74  """Update selected hop and data."""
75  try:
76  self.async_set_updated_dataasync_set_updated_data(await self._ek_api_ek_api.post_hop(hop_interval))
77  except AuthException as auth_err:
78  raise ConfigEntryAuthFailed from auth_err
79  except ApiException as api_err:
80  raise UpdateFailed(
81  f"Error communicating with EK API: {api_err}"
82  ) from api_err
83 
84  return self.datadata
85 
86  async def _async_update_data(self) -> Hop:
87  """Fetch data from API endpoint.
88 
89  filters the intervals to remove ones that are not active
90  """
91  try:
92  async with asyncio.timeout(60):
93  if self.hop_intervalshop_intervals is None:
94  hop_intervals: HopIntervals = await self._ek_api_ek_api.get_hop_intervals()
95  hop_intervals.intervals = OrderedDict(
96  filter(
97  lambda pair: pair[1].active == 1,
98  hop_intervals.intervals.items(),
99  )
100  )
101 
102  self.hop_intervalshop_intervals = hop_intervals
103  return await self._ek_api_ek_api.get_hop()
104  except AuthException as auth_err:
105  raise ConfigEntryAuthFailed from auth_err
106  except ApiException as api_err:
107  raise UpdateFailed(
108  f"Error communicating with EK API: {api_err}"
109  ) from api_err
None __init__(self, HomeAssistant hass, ElectricKiwiApi ek_api)
Definition: coordinator.py:25
None __init__(self, HomeAssistant hass, ElectricKiwiApi ek_api)
Definition: coordinator.py:51