Home Assistant Unofficial Reference 2024.12.1
helpers.py
Go to the documentation of this file.
1 """Helpers for WLED."""
2 
3 from __future__ import annotations
4 
5 from collections.abc import Callable, Coroutine
6 from typing import Any, Concatenate
7 
8 from wled import WLEDConnectionError, WLEDError
9 
10 from homeassistant.exceptions import HomeAssistantError
11 
12 from .entity import WLEDEntity
13 
14 
15 def wled_exception_handler[_WLEDEntityT: WLEDEntity, **_P](
16  func: Callable[Concatenate[_WLEDEntityT, _P], Coroutine[Any, Any, Any]],
17 ) -> Callable[Concatenate[_WLEDEntityT, _P], Coroutine[Any, Any, None]]:
18  """Decorate WLED calls to handle WLED exceptions.
19 
20  A decorator that wraps the passed in function, catches WLED errors,
21  and handles the availability of the device in the data coordinator.
22  """
23 
24  async def handler(self: _WLEDEntityT, *args: _P.args, **kwargs: _P.kwargs) -> None:
25  try:
26  await func(self, *args, **kwargs)
27  self.coordinator.async_update_listeners()
28 
29  except WLEDConnectionError as error:
30  self.coordinator.last_update_success = False
31  self.coordinator.async_update_listeners()
32  raise HomeAssistantError("Error communicating with WLED API") from error
33 
34  except WLEDError as error:
35  raise HomeAssistantError("Invalid response from WLED API") from error
36 
37  return handler
38 
39 
40 def kelvin_to_255(k: int, min_k: int, max_k: int) -> int:
41  """Map color temperature in K from minK-maxK to 0-255."""
42  return int((k - min_k) / (max_k - min_k) * 255)
43 
44 
45 def kelvin_to_255_reverse(v: int, min_k: int, max_k: int) -> int:
46  """Map color temperature from 0-255 to minK-maxK K."""
47  return int(v / 255 * (max_k - min_k) + min_k)
int kelvin_to_255(int k, int min_k, int max_k)
Definition: helpers.py:40
int kelvin_to_255_reverse(int v, int min_k, int max_k)
Definition: helpers.py:45