core/homeassistant/components/wled/helpers.py

41 lines
1.3 KiB
Python
Raw Normal View History

2021-06-09 18:15:46 +00:00
"""Helpers for WLED."""
2022-08-26 08:25:33 +00:00
from __future__ import annotations
2021-06-09 18:15:46 +00:00
2022-08-26 08:25:33 +00:00
from collections.abc import Callable, Coroutine
from typing import Any, TypeVar
from typing_extensions import Concatenate, ParamSpec
2021-06-09 18:15:46 +00:00
from wled import WLEDConnectionError, WLEDError
2022-05-24 14:30:41 +00:00
from homeassistant.exceptions import HomeAssistantError
2021-06-09 18:15:46 +00:00
2022-08-26 08:25:33 +00:00
from .models import WLEDEntity
_WLEDEntityT = TypeVar("_WLEDEntityT", bound=WLEDEntity)
_P = ParamSpec("_P")
2021-06-09 18:15:46 +00:00
2022-08-26 08:25:33 +00:00
def wled_exception_handler(
func: Callable[Concatenate[_WLEDEntityT, _P], Coroutine[Any, Any, Any]]
) -> Callable[Concatenate[_WLEDEntityT, _P], Coroutine[Any, Any, None]]:
2021-06-09 18:15:46 +00:00
"""Decorate WLED calls to handle WLED exceptions.
A decorator that wraps the passed in function, catches WLED errors,
and handles the availability of the device in the data coordinator.
"""
2022-08-26 08:25:33 +00:00
async def handler(self: _WLEDEntityT, *args: _P.args, **kwargs: _P.kwargs) -> None:
2021-06-09 18:15:46 +00:00
try:
await func(self, *args, **kwargs)
self.coordinator.async_update_listeners()
2021-06-09 18:15:46 +00:00
except WLEDConnectionError as error:
self.coordinator.last_update_success = False
self.coordinator.async_update_listeners()
2022-05-24 14:30:41 +00:00
raise HomeAssistantError("Error communicating with WLED API") from error
2021-06-09 18:15:46 +00:00
except WLEDError as error:
2022-05-24 14:30:41 +00:00
raise HomeAssistantError("Invalid response from WLED API") from error
2021-06-09 18:15:46 +00:00
return handler