Home Assistant Unofficial Reference 2024.12.1
coordinator.py
Go to the documentation of this file.
1 """DataUpdateCoordinator for the Trafikverket Weather integration."""
2 
3 from __future__ import annotations
4 
5 from datetime import timedelta
6 import logging
7 from typing import TYPE_CHECKING
8 
9 from pytrafikverket.exceptions import (
10  InvalidAuthentication,
11  MultipleWeatherStationsFound,
12  NoWeatherStationFound,
13 )
14 from pytrafikverket.models import WeatherStationInfoModel
15 from pytrafikverket.trafikverket_weather import TrafikverketWeather
16 
17 from homeassistant.const import CONF_API_KEY
18 from homeassistant.core import HomeAssistant
19 from homeassistant.exceptions import ConfigEntryAuthFailed
20 from homeassistant.helpers.aiohttp_client import async_get_clientsession
21 from homeassistant.helpers.update_coordinator import DataUpdateCoordinator, UpdateFailed
22 
23 from .const import CONF_STATION, DOMAIN
24 
25 if TYPE_CHECKING:
26  from . import TVWeatherConfigEntry
27 
28 _LOGGER = logging.getLogger(__name__)
29 TIME_BETWEEN_UPDATES = timedelta(minutes=10)
30 
31 
32 class TVDataUpdateCoordinator(DataUpdateCoordinator[WeatherStationInfoModel]):
33  """A Sensibo Data Update Coordinator."""
34 
35  config_entry: TVWeatherConfigEntry
36 
37  def __init__(self, hass: HomeAssistant) -> None:
38  """Initialize the Sensibo coordinator."""
39  super().__init__(
40  hass,
41  _LOGGER,
42  name=DOMAIN,
43  update_interval=TIME_BETWEEN_UPDATES,
44  )
45  self._weather_api_weather_api = TrafikverketWeather(
46  async_get_clientsession(hass), self.config_entryconfig_entry.data[CONF_API_KEY]
47  )
48  self._station_station = self.config_entryconfig_entry.data[CONF_STATION]
49 
50  async def _async_update_data(self) -> WeatherStationInfoModel:
51  """Fetch data from Trafikverket."""
52  try:
53  weatherdata = await self._weather_api_weather_api.async_get_weather(self._station_station)
54  except InvalidAuthentication as error:
55  raise ConfigEntryAuthFailed from error
56  except (NoWeatherStationFound, MultipleWeatherStationsFound) as error:
57  raise UpdateFailed from error
58  return weatherdata
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)