Home Assistant Unofficial Reference 2024.12.1
coordinator.py
Go to the documentation of this file.
1 """Define Guardian-specific utilities."""
2 
3 from __future__ import annotations
4 
5 import asyncio
6 from collections.abc import Callable, Coroutine
7 from datetime import timedelta
8 from typing import Any, cast
9 
10 from aioguardian import Client
11 from aioguardian.errors import GuardianError
12 
13 from homeassistant.config_entries import ConfigEntry
14 from homeassistant.core import HomeAssistant, callback
15 from homeassistant.helpers.dispatcher import async_dispatcher_connect
16 from homeassistant.helpers.update_coordinator import DataUpdateCoordinator, UpdateFailed
17 
18 from .const import LOGGER
19 
20 DEFAULT_UPDATE_INTERVAL = timedelta(seconds=30)
21 
22 SIGNAL_REBOOT_REQUESTED = "guardian_reboot_requested_{0}"
23 
24 
26  """Define an extended DataUpdateCoordinator with some Guardian goodies."""
27 
28  config_entry: ConfigEntry
29 
30  def __init__(
31  self,
32  hass: HomeAssistant,
33  *,
34  entry: ConfigEntry,
35  client: Client,
36  api_name: str,
37  api_coro: Callable[[], Coroutine[Any, Any, dict[str, Any]]],
38  api_lock: asyncio.Lock,
39  valve_controller_uid: str,
40  ) -> None:
41  """Initialize."""
42  super().__init__(
43  hass,
44  LOGGER,
45  name=f"{valve_controller_uid}_{api_name}",
46  update_interval=DEFAULT_UPDATE_INTERVAL,
47  )
48 
49  self._api_coro_api_coro = api_coro
50  self._api_lock_api_lock = api_lock
51  self._client_client = client
52 
53  self.config_entryconfig_entryconfig_entry = entry
54  self.signal_reboot_requestedsignal_reboot_requested = SIGNAL_REBOOT_REQUESTED.format(
55  self.config_entryconfig_entryconfig_entry.entry_id
56  )
57 
58  async def _async_update_data(self) -> dict[str, Any]:
59  """Execute a "locked" API request against the valve controller."""
60  async with self._api_lock_api_lock, self._client_client:
61  try:
62  resp = await self._api_coro_api_coro()
63  except GuardianError as err:
64  raise UpdateFailed(err) from err
65  return cast(dict[str, Any], resp["data"])
66 
67  async def async_initialize(self) -> None:
68  """Initialize the coordinator."""
69 
70  @callback
71  def async_reboot_requested() -> None:
72  """Respond to a reboot request."""
73  self.last_update_successlast_update_successlast_update_success = False
74  self.async_update_listenersasync_update_listeners()
75 
76  self.config_entryconfig_entryconfig_entry.async_on_unload(
78  self.hasshass, self.signal_reboot_requestedsignal_reboot_requested, async_reboot_requested
79  )
80  )
None __init__(self, HomeAssistant hass, *ConfigEntry entry, Client client, str api_name, Callable[[], Coroutine[Any, Any, dict[str, Any]]] api_coro, asyncio.Lock api_lock, str valve_controller_uid)
Definition: coordinator.py:40
Callable[[], None] async_dispatcher_connect(HomeAssistant hass, str signal, Callable[..., Any] target)
Definition: dispatcher.py:103