Home Assistant Unofficial Reference 2024.12.1
helpers.py
Go to the documentation of this file.
1 """Helpers for HomeWizard."""
2 
3 from __future__ import annotations
4 
5 from collections.abc import Callable, Coroutine
6 from typing import Any, Concatenate
7 
8 from homewizard_energy.errors import DisabledError, RequestError
9 
10 from homeassistant.exceptions import HomeAssistantError
11 
12 from .const import DOMAIN
13 from .entity import HomeWizardEntity
14 
15 
16 def homewizard_exception_handler[_HomeWizardEntityT: HomeWizardEntity, **_P](
17  func: Callable[Concatenate[_HomeWizardEntityT, _P], Coroutine[Any, Any, Any]],
18 ) -> Callable[Concatenate[_HomeWizardEntityT, _P], Coroutine[Any, Any, None]]:
19  """Decorate HomeWizard Energy calls to handle HomeWizardEnergy exceptions.
20 
21  A decorator that wraps the passed in function, catches HomeWizardEnergy errors,
22  and reloads the integration when the API was disabled so the reauth flow is
23  triggered.
24  """
25 
26  async def handler(
27  self: _HomeWizardEntityT, *args: _P.args, **kwargs: _P.kwargs
28  ) -> None:
29  try:
30  await func(self, *args, **kwargs)
31  except RequestError as ex:
32  raise HomeAssistantError(
33  translation_domain=DOMAIN,
34  translation_key="communication_error",
35  ) from ex
36  except DisabledError as ex:
37  await self.hass.config_entries.async_reload(
38  self.coordinator.config_entry.entry_id
39  )
40  raise HomeAssistantError(
41  translation_domain=DOMAIN,
42  translation_key="api_disabled",
43  ) from ex
44 
45  return handler