Home Assistant Unofficial Reference 2024.12.1
__init__.py
Go to the documentation of this file.
1 """UK Environment Agency Flood Monitoring Integration."""
2 
3 import asyncio
4 from datetime import timedelta
5 import logging
6 from typing import Any
7 
8 from aioeafm import get_station
9 
10 from homeassistant.config_entries import ConfigEntry
11 from homeassistant.const import Platform
12 from homeassistant.core import HomeAssistant
13 from homeassistant.helpers.aiohttp_client import async_get_clientsession
14 from homeassistant.helpers.update_coordinator import DataUpdateCoordinator
15 
16 from .const import DOMAIN
17 
18 PLATFORMS = [Platform.SENSOR]
19 
20 _LOGGER = logging.getLogger(__name__)
21 
22 
23 def get_measures(station_data):
24  """Force measure key to always be a list."""
25  if "measures" not in station_data:
26  return []
27  if isinstance(station_data["measures"], dict):
28  return [station_data["measures"]]
29  return station_data["measures"]
30 
31 
32 async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
33  """Set up flood monitoring sensors for this config entry."""
34  station_key = entry.data["station"]
35  session = async_get_clientsession(hass=hass)
36 
37  async def _async_update_data() -> dict[str, dict[str, Any]]:
38  # DataUpdateCoordinator will handle aiohttp ClientErrors and timeouts
39  async with asyncio.timeout(30):
40  data = await get_station(session, station_key)
41 
42  measures = get_measures(data)
43  # Turn data.measures into a dict rather than a list so easier for entities to
44  # find themselves.
45  data["measures"] = {measure["@id"]: measure for measure in measures}
46  return data
47 
48  coordinator = DataUpdateCoordinator[dict[str, dict[str, Any]]](
49  hass,
50  _LOGGER,
51  config_entry=entry,
52  name="sensor",
53  update_method=_async_update_data,
54  update_interval=timedelta(seconds=15 * 60),
55  )
56  await coordinator.async_config_entry_first_refresh()
57  hass.data.setdefault(DOMAIN, {})[entry.entry_id] = coordinator
58  await hass.config_entries.async_forward_entry_setups(entry, PLATFORMS)
59  return True
60 
61 
62 async def async_unload_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
63  """Unload flood monitoring sensors."""
64  return await hass.config_entries.async_unload_platforms(entry, PLATFORMS)
def get_measures(station_data)
Definition: __init__.py:23
bool async_setup_entry(HomeAssistant hass, ConfigEntry entry)
Definition: __init__.py:32
bool async_unload_entry(HomeAssistant hass, ConfigEntry entry)
Definition: __init__.py:62
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)