Home Assistant Unofficial Reference 2024.12.1
helpers.py
Go to the documentation of this file.
1 """Helper functions for Homematicip Cloud Integration."""
2 
3 from __future__ import annotations
4 
5 from collections.abc import Callable, Coroutine
6 from functools import wraps
7 import json
8 import logging
9 from typing import Any, Concatenate, TypeGuard
10 
11 from homematicip.base.enums import FunctionalChannelType
12 from homematicip.device import Device
13 
14 from homeassistant.exceptions import HomeAssistantError
15 
16 from .entity import HomematicipGenericEntity
17 
18 _LOGGER = logging.getLogger(__name__)
19 
20 
21 def is_error_response(response: Any) -> TypeGuard[dict[str, Any]]:
22  """Response from async call contains errors or not."""
23  if isinstance(response, dict):
24  return response.get("errorCode") not in ("", None)
25 
26  return False
27 
28 
29 def handle_errors[_HomematicipGenericEntityT: HomematicipGenericEntity, **_P](
30  func: Callable[
31  Concatenate[_HomematicipGenericEntityT, _P], Coroutine[Any, Any, Any]
32  ],
33 ) -> Callable[Concatenate[_HomematicipGenericEntityT, _P], Coroutine[Any, Any, Any]]:
34  """Handle async errors."""
35 
36  @wraps(func)
37  async def inner(
38  self: _HomematicipGenericEntityT, *args: _P.args, **kwargs: _P.kwargs
39  ) -> None:
40  """Handle errors from async call."""
41  result = await func(self, *args, **kwargs)
42  if is_error_response(result):
43  _LOGGER.error(
44  "Error while execute function %s: %s",
45  __name__,
46  json.dumps(result),
47  )
48  raise HomeAssistantError(
49  f"Error while execute function {func.__name__}: {result.get('errorCode')}. See log for more information."
50  )
51 
52  return inner
53 
54 
55 def get_channels_from_device(device: Device, channel_type: FunctionalChannelType):
56  """Get all channels matching with channel_type from device."""
57  return [
58  ch
59  for ch in device.functionalChannels
60  if ch.functionalChannelType == channel_type
61  ]
TypeGuard[dict[str, Any]] is_error_response(Any response)
Definition: helpers.py:21
def get_channels_from_device(Device device, FunctionalChannelType channel_type)
Definition: helpers.py:55