|
| 1 | +"""DataUpdateCoordinator for Essent integration.""" |
| 2 | + |
| 3 | +from __future__ import annotations |
| 4 | + |
| 5 | +from collections.abc import Callable |
| 6 | +from datetime import datetime, timedelta |
| 7 | +import logging |
| 8 | + |
| 9 | +from essent_dynamic_pricing import ( |
| 10 | + EssentClient, |
| 11 | + EssentConnectionError, |
| 12 | + EssentDataError, |
| 13 | + EssentError, |
| 14 | + EssentPrices, |
| 15 | + EssentResponseError, |
| 16 | +) |
| 17 | + |
| 18 | +from homeassistant.config_entries import ConfigEntry |
| 19 | +from homeassistant.core import HomeAssistant, callback |
| 20 | +from homeassistant.helpers.aiohttp_client import async_get_clientsession |
| 21 | +from homeassistant.helpers.event import async_track_point_in_utc_time |
| 22 | +from homeassistant.helpers.update_coordinator import DataUpdateCoordinator, UpdateFailed |
| 23 | +from homeassistant.util import dt as dt_util |
| 24 | + |
| 25 | +from .const import DOMAIN, UPDATE_INTERVAL |
| 26 | + |
| 27 | +_LOGGER = logging.getLogger(__name__) |
| 28 | +type EssentConfigEntry = ConfigEntry[EssentDataUpdateCoordinator] |
| 29 | + |
| 30 | + |
| 31 | +class EssentDataUpdateCoordinator(DataUpdateCoordinator[EssentPrices]): |
| 32 | + """Class to manage fetching Essent data.""" |
| 33 | + |
| 34 | + config_entry: EssentConfigEntry |
| 35 | + |
| 36 | + def __init__(self, hass: HomeAssistant, config_entry: EssentConfigEntry) -> None: |
| 37 | + """Initialize.""" |
| 38 | + super().__init__( |
| 39 | + hass, |
| 40 | + _LOGGER, |
| 41 | + config_entry=config_entry, |
| 42 | + name=DOMAIN, |
| 43 | + update_interval=UPDATE_INTERVAL, |
| 44 | + ) |
| 45 | + self._client = EssentClient(async_get_clientsession(hass)) |
| 46 | + self._unsub_listener: Callable[[], None] | None = None |
| 47 | + |
| 48 | + def start_listener_schedule(self) -> None: |
| 49 | + """Start listener tick schedule after first successful data fetch.""" |
| 50 | + if self.config_entry.pref_disable_polling: |
| 51 | + _LOGGER.debug("Polling disabled by config entry, not starting listener") |
| 52 | + return |
| 53 | + if self._unsub_listener: |
| 54 | + return |
| 55 | + _LOGGER.info("Starting listener updates on the hour") |
| 56 | + self._schedule_listener_tick() |
| 57 | + |
| 58 | + async def async_shutdown(self) -> None: |
| 59 | + """Cancel any scheduled call, and ignore new runs.""" |
| 60 | + await super().async_shutdown() |
| 61 | + if self._unsub_listener: |
| 62 | + self._unsub_listener() |
| 63 | + self._unsub_listener = None |
| 64 | + |
| 65 | + def _schedule_listener_tick(self) -> None: |
| 66 | + """Schedule listener updates on the hour to advance cached tariffs.""" |
| 67 | + if self._unsub_listener: |
| 68 | + self._unsub_listener() |
| 69 | + |
| 70 | + now = dt_util.utcnow() |
| 71 | + next_hour = now + timedelta(hours=1) |
| 72 | + next_run = datetime( |
| 73 | + next_hour.year, |
| 74 | + next_hour.month, |
| 75 | + next_hour.day, |
| 76 | + next_hour.hour, |
| 77 | + tzinfo=dt_util.UTC, |
| 78 | + ) |
| 79 | + |
| 80 | + _LOGGER.debug("Scheduling next listener tick for %s", next_run) |
| 81 | + |
| 82 | + @callback |
| 83 | + def _handle(_: datetime) -> None: |
| 84 | + """Handle the scheduled listener tick to update sensors.""" |
| 85 | + self._unsub_listener = None |
| 86 | + _LOGGER.debug("Listener tick fired, updating sensors with cached data") |
| 87 | + self.async_update_listeners() |
| 88 | + self._schedule_listener_tick() |
| 89 | + |
| 90 | + self._unsub_listener = async_track_point_in_utc_time( |
| 91 | + self.hass, |
| 92 | + _handle, |
| 93 | + next_run, |
| 94 | + ) |
| 95 | + |
| 96 | + async def _async_update_data(self) -> EssentPrices: |
| 97 | + """Fetch data from API.""" |
| 98 | + try: |
| 99 | + return await self._client.async_get_prices() |
| 100 | + except EssentConnectionError as err: |
| 101 | + raise UpdateFailed(f"Error communicating with API: {err}") from err |
| 102 | + except EssentResponseError as err: |
| 103 | + raise UpdateFailed(str(err)) from err |
| 104 | + except EssentDataError as err: |
| 105 | + _LOGGER.debug("Invalid data received: %s", err) |
| 106 | + raise UpdateFailed(str(err)) from err |
| 107 | + except EssentError as err: |
| 108 | + raise UpdateFailed("Unexpected Essent error") from err |
0 commit comments