Home Assistant Unofficial Reference 2024.12.1
helpers.py
Go to the documentation of this file.
1 """Helpers for LaMetric."""
2 
3 from __future__ import annotations
4 
5 from collections.abc import Callable, Coroutine
6 from typing import Any, Concatenate
7 
8 from demetriek import LaMetricConnectionError, LaMetricError
9 
10 from homeassistant.core import HomeAssistant, callback
11 from homeassistant.exceptions import HomeAssistantError
12 from homeassistant.helpers import device_registry as dr
13 
14 from .const import DOMAIN
15 from .coordinator import LaMetricDataUpdateCoordinator
16 from .entity import LaMetricEntity
17 
18 
19 def lametric_exception_handler[_LaMetricEntityT: LaMetricEntity, **_P](
20  func: Callable[Concatenate[_LaMetricEntityT, _P], Coroutine[Any, Any, Any]],
21 ) -> Callable[Concatenate[_LaMetricEntityT, _P], Coroutine[Any, Any, None]]:
22  """Decorate LaMetric calls to handle LaMetric exceptions.
23 
24  A decorator that wraps the passed in function, catches LaMetric errors,
25  and handles the availability of the device in the data coordinator.
26  """
27 
28  async def handler(
29  self: _LaMetricEntityT, *args: _P.args, **kwargs: _P.kwargs
30  ) -> None:
31  try:
32  await func(self, *args, **kwargs)
33  self.coordinator.async_update_listeners()
34 
35  except LaMetricConnectionError as error:
36  self.coordinator.last_update_success = False
37  self.coordinator.async_update_listeners()
38  raise HomeAssistantError(
39  "Error communicating with the LaMetric device"
40  ) from error
41 
42  except LaMetricError as error:
43  raise HomeAssistantError(
44  "Invalid response from the LaMetric device"
45  ) from error
46 
47  return handler
48 
49 
50 @callback
52  hass: HomeAssistant, device_id: str
53 ) -> LaMetricDataUpdateCoordinator:
54  """Get the LaMetric coordinator for this device ID."""
55  device_registry = dr.async_get(hass)
56 
57  if (device_entry := device_registry.async_get(device_id)) is None:
58  raise ValueError(f"Unknown LaMetric device ID: {device_id}")
59 
60  for entry_id in device_entry.config_entries:
61  if (
62  (entry := hass.config_entries.async_get_entry(entry_id))
63  and entry.domain == DOMAIN
64  and entry.entry_id in hass.data[DOMAIN]
65  ):
66  coordinator: LaMetricDataUpdateCoordinator = hass.data[DOMAIN][
67  entry.entry_id
68  ]
69  return coordinator
70 
71  raise ValueError(f"No coordinator for device ID: {device_id}")
LaMetricDataUpdateCoordinator async_get_coordinator_by_device_id(HomeAssistant hass, str device_id)
Definition: helpers.py:53