Home Assistant Unofficial Reference 2024.12.1
helpers.py
Go to the documentation of this file.
1 """Helpers for Toon."""
2 
3 from __future__ import annotations
4 
5 from collections.abc import Callable, Coroutine
6 import logging
7 from typing import Any, Concatenate
8 
9 from toonapi import ToonConnectionError, ToonError
10 
11 from .entity import ToonEntity
12 
13 _LOGGER = logging.getLogger(__name__)
14 
15 
16 def toon_exception_handler[_ToonEntityT: ToonEntity, **_P](
17  func: Callable[Concatenate[_ToonEntityT, _P], Coroutine[Any, Any, None]],
18 ) -> Callable[Concatenate[_ToonEntityT, _P], Coroutine[Any, Any, None]]:
19  """Decorate Toon calls to handle Toon exceptions.
20 
21  A decorator that wraps the passed in function, catches Toon errors,
22  and handles the availability of the device in the data coordinator.
23  """
24 
25  async def handler(self: _ToonEntityT, *args: _P.args, **kwargs: _P.kwargs) -> None:
26  try:
27  await func(self, *args, **kwargs)
28  self.coordinator.async_update_listeners()
29 
30  except ToonConnectionError as error:
31  _LOGGER.error("Error communicating with API: %s", error)
32  self.coordinator.last_update_success = False
33  self.coordinator.async_update_listeners()
34 
35  except ToonError as error:
36  _LOGGER.error("Invalid response from API: %s", error)
37 
38  return handler