Home Assistant Unofficial Reference 2024.12.1
light.py
Go to the documentation of this file.
1 """YoLink Dimmer."""
2 
3 from __future__ import annotations
4 
5 from typing import Any
6 
7 from yolink.client_request import ClientRequest
8 from yolink.const import ATTR_DEVICE_DIMMER
9 
10 from homeassistant.components.light import ATTR_BRIGHTNESS, ColorMode, LightEntity
11 from homeassistant.config_entries import ConfigEntry
12 from homeassistant.core import HomeAssistant, callback
13 from homeassistant.helpers.entity_platform import AddEntitiesCallback
14 
15 from .const import DOMAIN
16 from .coordinator import YoLinkCoordinator
17 from .entity import YoLinkEntity
18 
19 
21  hass: HomeAssistant,
22  config_entry: ConfigEntry,
23  async_add_entities: AddEntitiesCallback,
24 ) -> None:
25  """Set up YoLink Dimmer from a config entry."""
26  device_coordinators = hass.data[DOMAIN][config_entry.entry_id].device_coordinators
27  entities = [
28  YoLinkDimmerEntity(config_entry, device_coordinator)
29  for device_coordinator in device_coordinators.values()
30  if device_coordinator.device.device_type == ATTR_DEVICE_DIMMER
31  ]
32  async_add_entities(entities)
33 
34 
36  """YoLink Dimmer Entity."""
37 
38  _attr_color_mode = ColorMode.BRIGHTNESS
39  _attr_name = None
40  _attr_supported_color_modes: set[ColorMode] = {ColorMode.BRIGHTNESS}
41 
42  def __init__(
43  self,
44  config_entry: ConfigEntry,
45  coordinator: YoLinkCoordinator,
46  ) -> None:
47  """Init YoLink Dimmer entity."""
48  super().__init__(config_entry, coordinator)
49  self._attr_unique_id_attr_unique_id = f"{coordinator.device.device_id}"
50 
51  @callback
52  def update_entity_state(self, state: dict[str, Any]) -> None:
53  """Update HA Entity State."""
54  if (dimmer_state := state.get("state")) is not None:
55  # update _attr_is_on when device report it's state
56  self._attr_is_on_attr_is_on = dimmer_state == "open"
57  if (brightness := state.get("brightness")) is not None:
58  self._attr_brightness_attr_brightness = round(255 * brightness / 100)
59  self.async_write_ha_stateasync_write_ha_state()
60 
61  async def toggle_light_state(self, state: str, brightness: int | None) -> None:
62  """Toggle light state."""
63  params: dict[str, Any] = {"state": state}
64  if brightness is not None:
65  self._attr_brightness_attr_brightness = brightness
66  params["brightness"] = round(brightness / 255, 2) * 100
67  await self.call_devicecall_device(ClientRequest("setState", params))
68  self._attr_is_on_attr_is_on = state == "open"
69  self.async_write_ha_stateasync_write_ha_state()
70 
71  async def async_turn_on(self, **kwargs: Any) -> None:
72  """Turn on light."""
73  brightness = kwargs.get(ATTR_BRIGHTNESS)
74  await self.toggle_light_statetoggle_light_state("open", brightness)
75 
76  async def async_turn_off(self, **kwargs: Any) -> None:
77  """Turn off light."""
78  await self.toggle_light_statetoggle_light_state("close", None)