Home Assistant Unofficial Reference 2024.12.1
coordinator.py
Go to the documentation of this file.
1 """DataUpdateCoordinator for WeatherKit integration."""
2 
3 from __future__ import annotations
4 
5 from datetime import timedelta
6 
7 from apple_weatherkit import DataSetType
8 from apple_weatherkit.client import WeatherKitApiClient, WeatherKitApiClientError
9 
10 from homeassistant.config_entries import ConfigEntry
11 from homeassistant.const import CONF_LATITUDE, CONF_LONGITUDE
12 from homeassistant.core import HomeAssistant
13 from homeassistant.helpers.update_coordinator import DataUpdateCoordinator, UpdateFailed
14 
15 from .const import DOMAIN, LOGGER
16 
17 REQUESTED_DATA_SETS = [
18  DataSetType.CURRENT_WEATHER,
19  DataSetType.DAILY_FORECAST,
20  DataSetType.HOURLY_FORECAST,
21 ]
22 
23 
25  """Class to manage fetching data from the API."""
26 
27  config_entry: ConfigEntry
28  supported_data_sets: list[DataSetType] | None = None
29 
30  def __init__(
31  self,
32  hass: HomeAssistant,
33  client: WeatherKitApiClient,
34  ) -> None:
35  """Initialize."""
36  self.clientclient = client
37  super().__init__(
38  hass=hass,
39  logger=LOGGER,
40  name=DOMAIN,
41  update_interval=timedelta(minutes=5),
42  )
43 
44  async def update_supported_data_sets(self):
45  """Obtain the supported data sets for this location and store them."""
46  supported_data_sets = await self.clientclient.get_availability(
47  self.config_entryconfig_entry.data[CONF_LATITUDE],
48  self.config_entryconfig_entry.data[CONF_LONGITUDE],
49  )
50 
51  self.supported_data_setssupported_data_sets = [
52  data_set
53  for data_set in REQUESTED_DATA_SETS
54  if data_set in supported_data_sets
55  ]
56 
57  LOGGER.debug("Supported data sets: %s", self.supported_data_setssupported_data_sets)
58 
59  async def _async_update_data(self):
60  """Update the current weather and forecasts."""
61  try:
62  if not self.supported_data_setssupported_data_sets:
63  await self.update_supported_data_setsupdate_supported_data_sets()
64 
65  return await self.clientclient.get_weather_data(
66  self.config_entryconfig_entry.data[CONF_LATITUDE],
67  self.config_entryconfig_entry.data[CONF_LONGITUDE],
68  self.supported_data_setssupported_data_sets,
69  )
70  except WeatherKitApiClientError as exception:
71  raise UpdateFailed(exception) from exception
None __init__(self, HomeAssistant hass, WeatherKitApiClient client)
Definition: coordinator.py:34