Home Assistant Unofficial Reference 2024.12.1
coordinator.py
Go to the documentation of this file.
1 """DataUpdateCoordinator for the srp_energy integration."""
2 
3 from __future__ import annotations
4 
5 import asyncio
6 from datetime import timedelta
7 
8 from srpenergy.client import SrpEnergyClient
9 
10 from homeassistant.config_entries import ConfigEntry
11 from homeassistant.core import HomeAssistant
12 from homeassistant.helpers.update_coordinator import DataUpdateCoordinator, UpdateFailed
13 from homeassistant.util import dt as dt_util
14 
15 from .const import DOMAIN, LOGGER, MIN_TIME_BETWEEN_UPDATES, PHOENIX_TIME_ZONE
16 
17 TIMEOUT = 10
18 PHOENIX_ZONE_INFO = dt_util.get_time_zone(PHOENIX_TIME_ZONE)
19 
20 
22  """A srp_energy Data Update Coordinator."""
23 
24  config_entry: ConfigEntry
25 
26  def __init__(
27  self, hass: HomeAssistant, client: SrpEnergyClient, is_time_of_use: bool
28  ) -> None:
29  """Initialize the srp_energy data coordinator."""
30  self._client_client = client
31  self._is_time_of_use_is_time_of_use = is_time_of_use
32  super().__init__(
33  hass,
34  LOGGER,
35  name=DOMAIN,
36  update_interval=MIN_TIME_BETWEEN_UPDATES,
37  )
38 
39  async def _async_update_data(self) -> float:
40  """Fetch data from API endpoint.
41 
42  This is the place to pre-process the data to lookup tables
43  so entities can quickly look up their data.
44  """
45  LOGGER.debug("async_update_data enter")
46  # Fetch srp_energy data
47  end_date = dt_util.now(PHOENIX_ZONE_INFO)
48  start_date = end_date - timedelta(days=1)
49  try:
50  async with asyncio.timeout(TIMEOUT):
51  hourly_usage = await self.hasshass.async_add_executor_job(
52  self._client_client.usage,
53  start_date,
54  end_date,
55  self._is_time_of_use_is_time_of_use,
56  )
57  except (ValueError, TypeError) as err:
58  raise UpdateFailed(f"Error communicating with API: {err}") from err
59 
60  LOGGER.debug(
61  "async_update_data: Received %s record(s) from %s to %s",
62  len(hourly_usage) if hourly_usage else "None",
63  start_date,
64  end_date,
65  )
66 
67  previous_daily_usage = 0.0
68  for _, _, _, kwh, _ in hourly_usage:
69  previous_daily_usage += float(kwh)
70 
71  LOGGER.debug(
72  "async_update_data: previous_daily_usage %s",
73  previous_daily_usage,
74  )
75 
76  return previous_daily_usage
None __init__(self, HomeAssistant hass, SrpEnergyClient client, bool is_time_of_use)
Definition: coordinator.py:28