Home Assistant Unofficial Reference 2024.12.1
coordinator.py
Go to the documentation of this file.
1 """DataUpdateCoordinator for the Nord Pool integration."""
2 
3 from __future__ import annotations
4 
5 from collections.abc import Callable
6 from datetime import datetime, timedelta
7 from typing import TYPE_CHECKING
8 
9 from pynordpool import (
10  Currency,
11  DeliveryPeriodData,
12  NordPoolClient,
13  NordPoolEmptyResponseError,
14  NordPoolError,
15  NordPoolResponseError,
16 )
17 
18 from homeassistant.const import CONF_CURRENCY
19 from homeassistant.core import HomeAssistant
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
23 from homeassistant.util import dt as dt_util
24 
25 from .const import CONF_AREAS, DOMAIN, LOGGER
26 
27 if TYPE_CHECKING:
28  from . import NordPoolConfigEntry
29 
30 
32  """A Nord Pool Data Update Coordinator."""
33 
34  config_entry: NordPoolConfigEntry
35 
36  def __init__(self, hass: HomeAssistant, config_entry: NordPoolConfigEntry) -> None:
37  """Initialize the Nord Pool coordinator."""
38  super().__init__(
39  hass,
40  LOGGER,
41  config_entry=config_entry,
42  name=DOMAIN,
43  )
44  self.clientclient = NordPoolClient(session=async_get_clientsession(hass))
45  self.unsubunsub: Callable[[], None] | None = None
46 
47  def get_next_interval(self, now: datetime) -> datetime:
48  """Compute next time an update should occur."""
49  next_hour = dt_util.utcnow() + timedelta(hours=1)
50  next_run = datetime(
51  next_hour.year,
52  next_hour.month,
53  next_hour.day,
54  next_hour.hour,
55  tzinfo=dt_util.UTC,
56  )
57  LOGGER.debug("Next update at %s", next_run)
58  return next_run
59 
60  async def async_shutdown(self) -> None:
61  """Cancel any scheduled call, and ignore new runs."""
62  await super().async_shutdown()
63  if self.unsubunsub:
64  self.unsubunsub()
65  self.unsubunsub = None
66 
67  async def fetch_data(self, now: datetime) -> None:
68  """Fetch data from Nord Pool."""
70  self.hasshass, self.fetch_datafetch_data, self.get_next_intervalget_next_interval(dt_util.utcnow())
71  )
72  try:
73  data = await self.clientclient.async_get_delivery_period(
74  dt_util.now(),
75  Currency(self.config_entryconfig_entry.data[CONF_CURRENCY]),
76  self.config_entryconfig_entry.data[CONF_AREAS],
77  )
78  except NordPoolEmptyResponseError as error:
79  LOGGER.debug("Empty response error: %s", error)
80  self.async_set_update_errorasync_set_update_error(error)
81  return
82  except NordPoolResponseError as error:
83  LOGGER.debug("Response error: %s", error)
84  self.async_set_update_errorasync_set_update_error(error)
85  return
86  except NordPoolError as error:
87  LOGGER.debug("Connection error: %s", error)
88  self.async_set_update_errorasync_set_update_error(error)
89  return
90 
91  self.async_set_updated_dataasync_set_updated_data(data)
None __init__(self, HomeAssistant hass, NordPoolConfigEntry config_entry)
Definition: coordinator.py:36
aiohttp.ClientSession async_get_clientsession(HomeAssistant hass, bool verify_ssl=True, socket.AddressFamily family=socket.AF_UNSPEC, ssl_util.SSLCipherList ssl_cipher=ssl_util.SSLCipherList.PYTHON_DEFAULT)
CALLBACK_TYPE async_track_point_in_utc_time(HomeAssistant hass, HassJob[[datetime], Coroutine[Any, Any, None]|None]|Callable[[datetime], Coroutine[Any, Any, None]|None] action, datetime point_in_time)
Definition: event.py:1542