Home Assistant Unofficial Reference 2024.12.1
coordinator.py
Go to the documentation of this file.
1 """Define an object to manage fetching AirGradient data."""
2 
3 from __future__ import annotations
4 
5 from dataclasses import dataclass
6 from datetime import timedelta
7 from typing import TYPE_CHECKING
8 
9 from airgradient import AirGradientClient, AirGradientError, Config, Measures
10 
11 from homeassistant.core import HomeAssistant
12 from homeassistant.helpers import device_registry as dr
13 from homeassistant.helpers.update_coordinator import DataUpdateCoordinator, UpdateFailed
14 
15 from .const import DOMAIN, LOGGER
16 
17 if TYPE_CHECKING:
18  from . import AirGradientConfigEntry
19 
20 
21 @dataclass
23  """Class for AirGradient data."""
24 
25  measures: Measures
26  config: Config
27 
28 
30  """Class to manage fetching AirGradient data."""
31 
32  config_entry: AirGradientConfigEntry
33  _current_version: str
34 
35  def __init__(self, hass: HomeAssistant, client: AirGradientClient) -> None:
36  """Initialize coordinator."""
37  super().__init__(
38  hass,
39  logger=LOGGER,
40  name=f"AirGradient {client.host}",
41  update_interval=timedelta(minutes=1),
42  )
43  self.clientclient = client
44  assert self.config_entryconfig_entry.unique_id
45  self.serial_numberserial_number = self.config_entryconfig_entry.unique_id
46 
47  async def _async_setup(self) -> None:
48  """Set up the coordinator."""
49  self._current_version_current_version = (
50  await self.clientclient.get_current_measures()
51  ).firmware_version
52 
53  async def _async_update_data(self) -> AirGradientData:
54  try:
55  measures = await self.clientclient.get_current_measures()
56  config = await self.clientclient.get_config()
57  except AirGradientError as error:
58  raise UpdateFailed(error) from error
59  if measures.firmware_version != self._current_version_current_version:
60  device_registry = dr.async_get(self.hasshass)
61  device_entry = device_registry.async_get_device(
62  identifiers={(DOMAIN, self.serial_numberserial_number)}
63  )
64  assert device_entry
65  device_registry.async_update_device(
66  device_entry.id,
67  sw_version=measures.firmware_version,
68  )
69  self._current_version_current_version = measures.firmware_version
70  return AirGradientData(measures, config)
None __init__(self, HomeAssistant hass, AirGradientClient client)
Definition: coordinator.py:35