Home Assistant Unofficial Reference 2024.12.1
__init__.py
Go to the documentation of this file.
1 """The Airthings integration."""
2 
3 from __future__ import annotations
4 
5 from datetime import timedelta
6 import logging
7 
8 from airthings import Airthings, AirthingsDevice, AirthingsError
9 
10 from homeassistant.config_entries import ConfigEntry
11 from homeassistant.const import CONF_ID, 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, UpdateFailed
15 
16 from .const import CONF_SECRET, DOMAIN
17 
18 _LOGGER = logging.getLogger(__name__)
19 
20 PLATFORMS: list[Platform] = [Platform.SENSOR]
21 SCAN_INTERVAL = timedelta(minutes=6)
22 
23 type AirthingsDataCoordinatorType = DataUpdateCoordinator[dict[str, AirthingsDevice]]
24 type AirthingsConfigEntry = ConfigEntry[AirthingsDataCoordinatorType]
25 
26 
27 async def async_setup_entry(hass: HomeAssistant, entry: AirthingsConfigEntry) -> bool:
28  """Set up Airthings from a config entry."""
29  airthings = Airthings(
30  entry.data[CONF_ID],
31  entry.data[CONF_SECRET],
33  )
34 
35  async def _update_method() -> dict[str, AirthingsDevice]:
36  """Get the latest data from Airthings."""
37  try:
38  return await airthings.update_devices() # type: ignore[no-any-return]
39  except AirthingsError as err:
40  raise UpdateFailed(f"Unable to fetch data: {err}") from err
41 
42  coordinator = DataUpdateCoordinator(
43  hass,
44  _LOGGER,
45  config_entry=entry,
46  name=DOMAIN,
47  update_method=_update_method,
48  update_interval=SCAN_INTERVAL,
49  )
50  await coordinator.async_config_entry_first_refresh()
51 
52  entry.runtime_data = coordinator
53 
54  await hass.config_entries.async_forward_entry_setups(entry, PLATFORMS)
55 
56  return True
57 
58 
59 async def async_unload_entry(hass: HomeAssistant, entry: AirthingsConfigEntry) -> bool:
60  """Unload a config entry."""
61  return await hass.config_entries.async_unload_platforms(entry, PLATFORMS)
bool async_setup_entry(HomeAssistant hass, AirthingsConfigEntry entry)
Definition: __init__.py:27
bool async_unload_entry(HomeAssistant hass, AirthingsConfigEntry entry)
Definition: __init__.py:59
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)