Home Assistant Unofficial Reference 2024.12.1
light.py
Go to the documentation of this file.
1 """Support for Decora dimmers."""
2 
3 from __future__ import annotations
4 
5 from collections.abc import Callable
6 import copy
7 from functools import wraps
8 import logging
9 import time
10 from typing import TYPE_CHECKING, Any, Concatenate
11 
12 from bluepy.btle import BTLEException
13 import decora
14 import voluptuous as vol
15 
16 from homeassistant import util
18  ATTR_BRIGHTNESS,
19  PLATFORM_SCHEMA as LIGHT_PLATFORM_SCHEMA,
20  ColorMode,
21  LightEntity,
22 )
23 from homeassistant.const import CONF_API_KEY, CONF_DEVICES, CONF_NAME
25 
26 if TYPE_CHECKING:
27  from homeassistant.core import HomeAssistant
28  from homeassistant.helpers.entity_platform import AddEntitiesCallback
29  from homeassistant.helpers.typing import ConfigType, DiscoveryInfoType
30 
31 
32 _LOGGER = logging.getLogger(__name__)
33 
34 
35 def _name_validator(config):
36  """Validate the name."""
37  config = copy.deepcopy(config)
38  for address, device_config in config[CONF_DEVICES].items():
39  if CONF_NAME not in device_config:
40  device_config[CONF_NAME] = util.slugify(address)
41 
42  return config
43 
44 
45 DEVICE_SCHEMA = vol.Schema(
46  {vol.Optional(CONF_NAME): cv.string, vol.Required(CONF_API_KEY): cv.string}
47 )
48 
49 PLATFORM_SCHEMA = vol.Schema(
50  vol.All(
51  LIGHT_PLATFORM_SCHEMA.extend(
52  {vol.Optional(CONF_DEVICES, default={}): {cv.string: DEVICE_SCHEMA}}
53  ),
54  _name_validator,
55  )
56 )
57 
58 
59 def retry[_DecoraLightT: DecoraLight, **_P, _R](
60  method: Callable[Concatenate[_DecoraLightT, _P], _R],
61 ) -> Callable[Concatenate[_DecoraLightT, _P], _R | None]:
62  """Retry bluetooth commands."""
63 
64  @wraps(method)
65  def wrapper_retry(
66  device: _DecoraLightT, *args: _P.args, **kwargs: _P.kwargs
67  ) -> _R | None:
68  """Try send command and retry on error."""
69 
70  initial = time.monotonic()
71  while True:
72  if time.monotonic() - initial >= 10:
73  return None
74  try:
75  return method(device, *args, **kwargs)
76  except (decora.decoraException, AttributeError, BTLEException):
77  _LOGGER.warning(
78  "Decora connect error for device %s. Reconnecting",
79  device.name,
80  )
81  device._switch.connect() # noqa: SLF001
82 
83  return wrapper_retry
84 
85 
87  hass: HomeAssistant,
88  config: ConfigType,
89  add_entities: AddEntitiesCallback,
90  discovery_info: DiscoveryInfoType | None = None,
91 ) -> None:
92  """Set up an Decora switch."""
93  lights = []
94  for address, device_config in config[CONF_DEVICES].items():
95  device = {}
96  device["name"] = device_config[CONF_NAME]
97  device["key"] = device_config[CONF_API_KEY]
98  device["address"] = address
99  light = DecoraLight(device)
100  lights.append(light)
101 
102  add_entities(lights)
103 
104 
106  """Representation of an Decora light."""
107 
108  _attr_color_mode = ColorMode.BRIGHTNESS
109  _attr_supported_color_modes = {ColorMode.BRIGHTNESS}
110 
111  def __init__(self, device: dict[str, Any]) -> None:
112  """Initialize the light."""
113 
114  self._attr_name_attr_name = device["name"]
115  self._attr_unique_id_attr_unique_id = device["address"]
116  self._key_key = device["key"]
117  self._switch_switch = decora.decora(device["address"], self._key_key)
118  self._attr_brightness_attr_brightness = 0
119  self._attr_is_on_attr_is_on = False
120 
121  @retry
122  def set_state(self, brightness: int) -> None:
123  """Set the state of this lamp to the provided brightness."""
124  self._switch_switch.set_brightness(int(brightness / 2.55))
125  self._attr_brightness_attr_brightness = brightness
126 
127  @retry
128  def turn_on(self, **kwargs: Any) -> None:
129  """Turn the specified or all lights on."""
130  brightness = kwargs.get(ATTR_BRIGHTNESS)
131  self._switch_switch.on()
132  self._attr_is_on_attr_is_on = True
133 
134  if brightness is not None:
135  self.set_stateset_state(brightness)
136 
137  @retry
138  def turn_off(self, **kwargs: Any) -> None:
139  """Turn the specified or all lights off."""
140  self._switch_switch.off()
141  self._attr_is_on_attr_is_on = False
142 
143  @retry
144  def update(self) -> None:
145  """Synchronise internal state with the actual light state."""
146  self._attr_brightness_attr_brightness = self._switch_switch.get_brightness() * 2.55
147  self._attr_is_on_attr_is_on = self._switch_switch.get_on()
None set_state(self, int brightness)
Definition: light.py:122
None __init__(self, dict[str, Any] device)
Definition: light.py:111
None add_entities(AsusWrtRouter router, AddEntitiesCallback async_add_entities, set[str] tracked)
None setup_platform(HomeAssistant hass, ConfigType config, AddEntitiesCallback add_entities, DiscoveryInfoType|None discovery_info=None)
Definition: light.py:91