Home Assistant Unofficial Reference 2024.12.1
coordinator.py
Go to the documentation of this file.
1 """The Airthings BLE integration."""
2 
3 from __future__ import annotations
4 
5 from datetime import timedelta
6 import logging
7 
8 from airthings_ble import AirthingsBluetoothDeviceData, AirthingsDevice
9 from bleak.backends.device import BLEDevice
10 from bleak_retry_connector import close_stale_connections_by_address
11 
12 from homeassistant.components import bluetooth
13 from homeassistant.config_entries import ConfigEntry
14 from homeassistant.core import HomeAssistant
15 from homeassistant.exceptions import ConfigEntryNotReady
16 from homeassistant.helpers.update_coordinator import DataUpdateCoordinator, UpdateFailed
17 from homeassistant.util.unit_system import METRIC_SYSTEM
18 
19 from .const import DEFAULT_SCAN_INTERVAL, DOMAIN
20 
21 _LOGGER = logging.getLogger(__name__)
22 
23 type AirthingsBLEConfigEntry = ConfigEntry[AirthingsBLEDataUpdateCoordinator]
24 
25 
27  """Class to manage fetching Airthings BLE data."""
28 
29  ble_device: BLEDevice
30  config_entry: AirthingsBLEConfigEntry
31 
32  def __init__(self, hass: HomeAssistant, entry: AirthingsBLEConfigEntry) -> None:
33  """Initialize the coordinator."""
34  self.airthingsairthings = AirthingsBluetoothDeviceData(
35  _LOGGER, hass.config.units is METRIC_SYSTEM
36  )
37  super().__init__(
38  hass,
39  _LOGGER,
40  config_entry=entry,
41  name=DOMAIN,
42  update_interval=timedelta(seconds=DEFAULT_SCAN_INTERVAL),
43  )
44 
45  async def _async_setup(self) -> None:
46  """Set up the coordinator."""
47  address = self.config_entryconfig_entry.unique_id
48 
49  assert address is not None
50 
51  await close_stale_connections_by_address(address)
52 
53  ble_device = bluetooth.async_ble_device_from_address(self.hasshass, address)
54 
55  if not ble_device:
56  raise ConfigEntryNotReady(
57  f"Could not find Airthings device with address {address}"
58  )
59  self.ble_deviceble_device = ble_device
60 
61  async def _async_update_data(self) -> AirthingsDevice:
62  """Get data from Airthings BLE."""
63  try:
64  data = await self.airthingsairthings.update_device(self.ble_deviceble_device)
65  except Exception as err:
66  raise UpdateFailed(f"Unable to fetch data: {err}") from err
67 
68  return data
None __init__(self, HomeAssistant hass, AirthingsBLEConfigEntry entry)
Definition: coordinator.py:32
str|None update_device(HomeAssistant hass, ConfigEntry config_entry, ConfigType config)
Definition: entity.py:1512