Home Assistant Unofficial Reference 2024.12.1
coordinator.py
Go to the documentation of this file.
1 """DataUpdateCoordinator for the Ambient Weather Network integration."""
2 
3 from __future__ import annotations
4 
5 from datetime import datetime, timedelta
6 from typing import Any, cast
7 
8 from aioambient import OpenAPI
9 from aioambient.errors import RequestError
10 
11 from homeassistant.config_entries import ConfigEntry
12 from homeassistant.const import CONF_MAC
13 from homeassistant.core import HomeAssistant
14 from homeassistant.helpers.update_coordinator import DataUpdateCoordinator, UpdateFailed
15 from homeassistant.util import dt as dt_util
16 
17 from .const import API_LAST_DATA, DOMAIN, LOGGER
18 from .helper import get_station_name
19 
20 SCAN_INTERVAL = timedelta(minutes=5)
21 
22 
24  """The Ambient Network Data Update Coordinator."""
25 
26  config_entry: ConfigEntry
27  station_name: str
28  last_measured: datetime | None = None
29 
30  def __init__(self, hass: HomeAssistant, api: OpenAPI) -> None:
31  """Initialize the coordinator."""
32  super().__init__(hass, LOGGER, name=DOMAIN, update_interval=SCAN_INTERVAL)
33  self.apiapi = api
34 
35  async def _async_update_data(self) -> dict[str, Any]:
36  """Fetch the latest data from the Ambient Network."""
37 
38  try:
39  response = await self.apiapi.get_device_details(
40  self.config_entryconfig_entry.data[CONF_MAC]
41  )
42  except RequestError as ex:
43  raise UpdateFailed("Cannot connect to Ambient Network") from ex
44 
45  self.station_namestation_name = get_station_name(response)
46 
47  if (last_data := response.get(API_LAST_DATA)) is None:
48  raise UpdateFailed(
49  f"Station '{self.config_entry.title}' did not report any data"
50  )
51 
52  # Some stations do not report a "created_at" or "dateutc".
53  # See https://github.com/home-assistant/core/issues/116917
54  if (ts := last_data.get("created_at")) is not None or (
55  ts := last_data.get("dateutc")
56  ) is not None:
57  self.last_measuredlast_measured = datetime.fromtimestamp(
58  ts / 1000, tz=dt_util.DEFAULT_TIME_ZONE
59  )
60 
61  return cast(dict[str, Any], last_data)
str get_station_name(dict[str, Any] station)
Definition: helper.py:17