Home Assistant Unofficial Reference 2024.12.1
light.py
Go to the documentation of this file.
1 """Support for Hue lights."""
2 
3 from __future__ import annotations
4 
5 from functools import partial
6 from typing import Any
7 
8 from aiohue import HueBridgeV2
9 from aiohue.v2.controllers.events import EventType
10 from aiohue.v2.controllers.lights import LightsController
11 from aiohue.v2.models.feature import EffectStatus, TimedEffectStatus
12 from aiohue.v2.models.light import Light
13 
15  ATTR_BRIGHTNESS,
16  ATTR_COLOR_TEMP,
17  ATTR_EFFECT,
18  ATTR_FLASH,
19  ATTR_TRANSITION,
20  ATTR_XY_COLOR,
21  FLASH_SHORT,
22  ColorMode,
23  LightEntity,
24  LightEntityDescription,
25  LightEntityFeature,
26  filter_supported_color_modes,
27 )
28 from homeassistant.config_entries import ConfigEntry
29 from homeassistant.core import HomeAssistant, callback
30 from homeassistant.helpers.entity_platform import AddEntitiesCallback
31 
32 from ..bridge import HueBridge
33 from ..const import DOMAIN
34 from .entity import HueBaseEntity
35 from .helpers import (
36  normalize_hue_brightness,
37  normalize_hue_colortemp,
38  normalize_hue_transition,
39 )
40 
41 EFFECT_NONE = "None"
42 FALLBACK_MIN_MIREDS = 153 # 6500 K
43 FALLBACK_MAX_MIREDS = 500 # 2000 K
44 FALLBACK_MIREDS = 173 # halfway
45 
46 
48  hass: HomeAssistant,
49  config_entry: ConfigEntry,
50  async_add_entities: AddEntitiesCallback,
51 ) -> None:
52  """Set up Hue Light from Config Entry."""
53  bridge: HueBridge = hass.data[DOMAIN][config_entry.entry_id]
54  api: HueBridgeV2 = bridge.api
55  controller: LightsController = api.lights
56  make_light_entity = partial(HueLight, bridge, controller)
57 
58  @callback
59  def async_add_light(event_type: EventType, resource: Light) -> None:
60  """Add Hue Light."""
61  async_add_entities([make_light_entity(resource)])
62 
63  # add all current items in controller
64  async_add_entities(make_light_entity(light) for light in controller)
65  # register listener for new lights
66  config_entry.async_on_unload(
67  controller.subscribe(async_add_light, event_filter=EventType.RESOURCE_ADDED)
68  )
69 
70 
71 # pylint: disable-next=hass-enforce-class-module
73  """Representation of a Hue light."""
74 
75  _fixed_color_mode: ColorMode | None = None
76  entity_description = LightEntityDescription(
77  key="hue_light", has_entity_name=True, name=None
78  )
79 
80  def __init__(
81  self, bridge: HueBridge, controller: LightsController, resource: Light
82  ) -> None:
83  """Initialize the light."""
84  super().__init__(bridge, controller, resource)
85  if self.resourceresourceresource.alert and self.resourceresourceresource.alert.action_values:
86  self._attr_supported_features |= LightEntityFeature.FLASH
87  self.resourceresourceresource = resource
88  self.controllercontrollercontroller = controller
89  supported_color_modes = {ColorMode.ONOFF}
90  if self.resourceresourceresource.supports_color:
91  supported_color_modes.add(ColorMode.XY)
92  if self.resourceresourceresource.supports_color_temperature:
93  supported_color_modes.add(ColorMode.COLOR_TEMP)
94  if self.resourceresourceresource.supports_dimming:
95  supported_color_modes.add(ColorMode.BRIGHTNESS)
96  # support transition if brightness control
97  self._attr_supported_features |= LightEntityFeature.TRANSITION
98  supported_color_modes = filter_supported_color_modes(supported_color_modes)
99  self._attr_supported_color_modes_attr_supported_color_modes = supported_color_modes
100  if len(self._attr_supported_color_modes_attr_supported_color_modes) == 1:
101  # If the light supports only a single color mode, set it now
102  self._fixed_color_mode_fixed_color_mode = next(iter(self._attr_supported_color_modes_attr_supported_color_modes))
103  self._last_brightness_last_brightness: float | None = None
104  self._color_temp_active_color_temp_active: bool = False
105  # get list of supported effects (combine effects and timed_effects)
106  self._attr_effect_list_attr_effect_list = []
107  if effects := resource.effects:
108  self._attr_effect_list_attr_effect_list = [
109  x.value for x in effects.status_values if x != EffectStatus.NO_EFFECT
110  ]
111  if timed_effects := resource.timed_effects:
112  self._attr_effect_list_attr_effect_list += [
113  x.value
114  for x in timed_effects.status_values
115  if x != TimedEffectStatus.NO_EFFECT
116  ]
117  if len(self._attr_effect_list_attr_effect_list) > 0:
118  self._attr_effect_list_attr_effect_list.insert(0, EFFECT_NONE)
119  self._attr_supported_features |= LightEntityFeature.EFFECT
120 
121  @property
122  def brightness(self) -> int | None:
123  """Return the brightness of this light between 0..255."""
124  if dimming := self.resourceresourceresource.dimming:
125  # Hue uses a range of [0, 100] to control brightness.
126  return round((dimming.brightness / 100) * 255)
127  return None
128 
129  @property
130  def is_on(self) -> bool:
131  """Return true if device is on (brightness above 0)."""
132  return self.resourceresourceresource.on.on
133 
134  @property
135  def color_mode(self) -> ColorMode:
136  """Return the color mode of the light."""
137  if self._fixed_color_mode_fixed_color_mode:
138  # The light supports only a single color mode, return it
139  return self._fixed_color_mode_fixed_color_mode
140 
141  # The light supports both color temperature and XY, determine which
142  # mode the light is in
143  if self.color_temp_activecolor_temp_active:
144  return ColorMode.COLOR_TEMP
145  return ColorMode.XY
146 
147  @property
148  def color_temp_active(self) -> bool:
149  """Return if the light is in Color Temperature mode."""
150  color_temp = self.resourceresourceresource.color_temperature
151  if color_temp is None or color_temp.mirek is None:
152  return False
153  # Official Hue lights return `mirek_valid` to indicate CT is active
154  # while non-official lights do not.
155  if self.devicedevice.product_data.certified:
156  return self.resourceresourceresource.color_temperature.mirek_valid
157  return self._color_temp_active_color_temp_active
158 
159  @property
160  def xy_color(self) -> tuple[float, float] | None:
161  """Return the xy color."""
162  if color := self.resourceresourceresource.color:
163  return (color.xy.x, color.xy.y)
164  return None
165 
166  @property
167  def color_temp(self) -> int:
168  """Return the color temperature."""
169  if color_temp := self.resourceresourceresource.color_temperature:
170  return color_temp.mirek
171  # return a fallback value to prevent issues with mired->kelvin conversions
172  return FALLBACK_MIREDS
173 
174  @property
175  def min_mireds(self) -> int:
176  """Return the coldest color_temp that this light supports."""
177  if color_temp := self.resourceresourceresource.color_temperature:
178  return color_temp.mirek_schema.mirek_minimum
179  # return a fallback value to prevent issues with mired->kelvin conversions
180  return FALLBACK_MIN_MIREDS
181 
182  @property
183  def max_mireds(self) -> int:
184  """Return the warmest color_temp that this light supports."""
185  if color_temp := self.resourceresourceresource.color_temperature:
186  return color_temp.mirek_schema.mirek_maximum
187  # return a fallback value to prevent issues with mired->kelvin conversions
188  return FALLBACK_MAX_MIREDS
189 
190  @property
191  def extra_state_attributes(self) -> dict[str, str] | None:
192  """Return the optional state attributes."""
193  return {
194  "mode": self.resourceresourceresource.mode.value,
195  "dynamics": self.resourceresourceresource.dynamics.status.value,
196  }
197 
198  @property
199  def effect(self) -> str | None:
200  """Return the current effect."""
201  if effects := self.resourceresourceresource.effects:
202  if effects.status != EffectStatus.NO_EFFECT:
203  return effects.status.value
204  if timed_effects := self.resourceresourceresource.timed_effects:
205  if timed_effects.status != TimedEffectStatus.NO_EFFECT:
206  return timed_effects.status.value
207  return EFFECT_NONE
208 
209  async def async_turn_on(self, **kwargs: Any) -> None:
210  """Turn the device on."""
211  transition = normalize_hue_transition(kwargs.get(ATTR_TRANSITION))
212  xy_color = kwargs.get(ATTR_XY_COLOR)
213  color_temp = normalize_hue_colortemp(kwargs.get(ATTR_COLOR_TEMP))
214  brightness = normalize_hue_brightness(kwargs.get(ATTR_BRIGHTNESS))
215  if self._last_brightness_last_brightness and brightness is None:
216  # The Hue bridge sets the brightness to 1% when turning on a bulb
217  # when a transition was used to turn off the bulb.
218  # This issue has been reported on the Hue forum several times:
219  # https://developers.meethue.com/forum/t/brightness-turns-down-to-1-automatically-shortly-after-sending-off-signal-hue-bug/5692
220  # https://developers.meethue.com/forum/t/lights-turn-on-with-lowest-brightness-via-siri-if-turned-off-via-api/6700
221  # https://developers.meethue.com/forum/t/using-transitiontime-with-on-false-resets-bri-to-1/4585
222  # https://developers.meethue.com/forum/t/bri-value-changing-in-switching-lights-on-off/6323
223  # https://developers.meethue.com/forum/t/fade-in-fade-out/6673
224  brightness = self._last_brightness_last_brightness
225  self._last_brightness_last_brightness = None
226  self._color_temp_active_color_temp_active = color_temp is not None
227  flash = kwargs.get(ATTR_FLASH)
228  effect = effect_str = kwargs.get(ATTR_EFFECT)
229  if effect_str in (EFFECT_NONE, EFFECT_NONE.lower()):
230  # ignore effect if set to "None" and we have no effect active
231  # the special effect "None" is only used to stop an active effect
232  # but sending it while no effect is active can actually result in issues
233  # https://github.com/home-assistant/core/issues/122165
234  effect = None if self.effecteffecteffecteffect == EFFECT_NONE else EffectStatus.NO_EFFECT
235  elif effect_str is not None:
236  # work out if we got a regular effect or timed effect
237  effect = EffectStatus(effect_str)
238  if effect == EffectStatus.UNKNOWN:
239  effect = TimedEffectStatus(effect_str)
240  if transition is None:
241  # a transition is required for timed effect, default to 10 minutes
242  transition = 600000
243  # we need to clear color values if an effect is applied
244  color_temp = None
245  xy_color = None
246 
247  if flash is not None:
248  await self.async_set_flashasync_set_flash(flash)
249  # flash cannot be sent with other commands at the same time or result will be flaky
250  # Hue's default behavior is that a light returns to its previous state for short
251  # flash (identify) and the light is kept turned on for long flash (breathe effect)
252  # Why is this flash alert/effect hidden in the turn_on/off commands ?
253  return
254 
255  await self.bridgebridge.async_request_call(
256  self.controllercontrollercontroller.set_state,
257  id=self.resourceresourceresource.id,
258  on=True,
259  brightness=brightness,
260  color_xy=xy_color,
261  color_temp=color_temp,
262  transition_time=transition,
263  effect=effect,
264  )
265 
266  async def async_turn_off(self, **kwargs: Any) -> None:
267  """Turn the light off."""
268  transition = normalize_hue_transition(kwargs.get(ATTR_TRANSITION))
269  if transition is not None and self.resourceresourceresource.dimming:
270  self._last_brightness_last_brightness = self.resourceresourceresource.dimming.brightness
271  flash = kwargs.get(ATTR_FLASH)
272 
273  if flash is not None:
274  await self.async_set_flashasync_set_flash(flash)
275  # flash cannot be sent with other commands at the same time or result will be flaky
276  # Hue's default behavior is that a light returns to its previous state for short
277  # flash (identify) and the light is kept turned on for long flash (breathe effect)
278  return
279 
280  await self.bridgebridge.async_request_call(
281  self.controllercontrollercontroller.set_state,
282  id=self.resourceresourceresource.id,
283  on=False,
284  transition_time=transition,
285  )
286 
287  async def async_set_flash(self, flash: str) -> None:
288  """Send flash command to light."""
289  await self.bridgebridge.async_request_call(
290  self.controllercontrollercontroller.set_flash,
291  id=self.resourceresourceresource.id,
292  short=flash == FLASH_SHORT,
293  )
None async_turn_off(self, **Any kwargs)
Definition: light.py:266
tuple[float, float]|None xy_color(self)
Definition: light.py:160
None __init__(self, HueBridge bridge, LightsController controller, Light resource)
Definition: light.py:82
None async_turn_on(self, **Any kwargs)
Definition: light.py:209
dict[str, str]|None extra_state_attributes(self)
Definition: light.py:191
float|None normalize_hue_brightness(float|None brightness)
Definition: helpers.py:6
float|None normalize_hue_transition(float|None transition)
Definition: helpers.py:15
int|None normalize_hue_colortemp(int|None colortemp)
Definition: helpers.py:24
None async_setup_entry(HomeAssistant hass, ConfigEntry config_entry, AddEntitiesCallback async_add_entities)
Definition: light.py:51
set[ColorMode] filter_supported_color_modes(Iterable[ColorMode] color_modes)
Definition: __init__.py:122