Home Assistant Unofficial Reference 2024.12.1
util.py
Go to the documentation of this file.
1 """Define Guardian-specific utilities."""
2 
3 from __future__ import annotations
4 
5 from collections.abc import Callable, Coroutine, Iterable
6 from dataclasses import dataclass
7 from datetime import timedelta
8 from functools import wraps
9 from typing import TYPE_CHECKING, Any, Concatenate
10 
11 from aioguardian.errors import GuardianError
12 
13 from homeassistant.config_entries import ConfigEntry
14 from homeassistant.core import HomeAssistant, callback
15 from homeassistant.exceptions import HomeAssistantError
16 from homeassistant.helpers import entity_registry as er
17 
18 from .const import LOGGER
19 
20 if TYPE_CHECKING:
21  from .entity import GuardianEntity
22 
23 DEFAULT_UPDATE_INTERVAL = timedelta(seconds=30)
24 
25 SIGNAL_REBOOT_REQUESTED = "guardian_reboot_requested_{0}"
26 
27 
28 @dataclass
30  """Define an entity replacement."""
31 
32  old_domain: str
33  old_unique_id: str
34 
35 
36 @callback
38  hass: HomeAssistant,
39  entry: ConfigEntry,
40  entity_replacement_strategies: Iterable[EntityDomainReplacementStrategy],
41 ) -> None:
42  """Remove old entities and create a repairs issue with info on their replacement."""
43  ent_reg = er.async_get(hass)
44  for strategy in entity_replacement_strategies:
45  try:
46  [registry_entry] = [
47  registry_entry
48  for registry_entry in er.async_entries_for_config_entry(
49  ent_reg, entry.entry_id
50  )
51  if registry_entry.domain == strategy.old_domain
52  and registry_entry.unique_id == strategy.old_unique_id
53  ]
54  except ValueError:
55  continue
56 
57  old_entity_id = registry_entry.entity_id
58  LOGGER.debug('Removing old entity: "%s"', old_entity_id)
59  ent_reg.async_remove(old_entity_id)
60 
61 
62 @callback
63 def convert_exceptions_to_homeassistant_error[_GuardianEntityT: GuardianEntity, **_P](
64  func: Callable[Concatenate[_GuardianEntityT, _P], Coroutine[Any, Any, Any]],
65 ) -> Callable[Concatenate[_GuardianEntityT, _P], Coroutine[Any, Any, None]]:
66  """Decorate to handle exceptions from the Guardian API."""
67 
68  @wraps(func)
69  async def wrapper(
70  entity: _GuardianEntityT, *args: _P.args, **kwargs: _P.kwargs
71  ) -> None:
72  """Wrap the provided function."""
73  try:
74  await func(entity, *args, **kwargs)
75  except GuardianError as err:
76  raise HomeAssistantError(
77  f"Error while calling {func.__name__}: {err}"
78  ) from err
79 
80  return wrapper
None async_finish_entity_domain_replacements(HomeAssistant hass, ConfigEntry entry, Iterable[EntityDomainReplacementStrategy] entity_replacement_strategies)
Definition: util.py:41