Home Assistant Unofficial Reference 2024.12.1
light.py
Go to the documentation of this file.
1 """Support for LiteJet lights."""
2 
3 from __future__ import annotations
4 
5 from typing import Any
6 
7 from pylitejet import LiteJet, LiteJetError
8 
10  ATTR_BRIGHTNESS,
11  ATTR_TRANSITION,
12  ColorMode,
13  LightEntity,
14  LightEntityFeature,
15 )
16 from homeassistant.config_entries import ConfigEntry
17 from homeassistant.core import HomeAssistant
18 from homeassistant.exceptions import HomeAssistantError
19 from homeassistant.helpers.device_registry import DeviceInfo
20 from homeassistant.helpers.entity_platform import AddEntitiesCallback
21 
22 from .const import CONF_DEFAULT_TRANSITION, DOMAIN
23 
24 ATTR_NUMBER = "number"
25 
26 
28  hass: HomeAssistant,
29  config_entry: ConfigEntry,
30  async_add_entities: AddEntitiesCallback,
31 ) -> None:
32  """Set up entry."""
33 
34  system: LiteJet = hass.data[DOMAIN]
35 
36  entities = []
37  for index in system.loads():
38  name = await system.get_load_name(index)
39  entities.append(LiteJetLight(config_entry, system, index, name))
40 
41  async_add_entities(entities, True)
42 
43 
45  """Representation of a single LiteJet light."""
46 
47  _attr_color_mode = ColorMode.BRIGHTNESS
48  _attr_should_poll = False
49  _attr_supported_color_modes = {ColorMode.BRIGHTNESS}
50  _attr_supported_features = LightEntityFeature.TRANSITION
51  _attr_has_entity_name = True
52  _attr_name = None
53 
54  def __init__(
55  self, config_entry: ConfigEntry, system: LiteJet, index: int, name: str
56  ) -> None:
57  """Initialize a LiteJet light."""
58  self._config_entry_config_entry = config_entry
59  self._lj_lj = system
60  self._index_index = index
61  self._attr_brightness_attr_brightness = 0
62  self._attr_is_on_attr_is_on = False
63  self._attr_unique_id_attr_unique_id = f"{config_entry.entry_id}_{index}"
64  self._attr_extra_state_attributes_attr_extra_state_attributes = {ATTR_NUMBER: self._index_index}
65  self._attr_device_info_attr_device_info = DeviceInfo(
66  identifiers={(DOMAIN, f"{config_entry.entry_id}_light_{index}")},
67  name=name,
68  via_device=(DOMAIN, f"{config_entry.entry_id}_mcp"),
69  )
70 
71  async def async_added_to_hass(self) -> None:
72  """Run when this Entity has been added to HA."""
73  self._lj_lj.on_load_activated(self._index_index, self._on_load_changed_on_load_changed)
74  self._lj_lj.on_load_deactivated(self._index_index, self._on_load_changed_on_load_changed)
75  self._lj_lj.on_connected_changed(self._on_connected_changed_on_connected_changed)
76 
77  async def async_will_remove_from_hass(self) -> None:
78  """Entity being removed from hass."""
79  self._lj_lj.unsubscribe(self._on_load_changed_on_load_changed)
80  self._lj_lj.unsubscribe(self._on_connected_changed_on_connected_changed)
81 
82  def _on_load_changed(self, level: int | None) -> None:
83  """Handle state changes."""
84  self.schedule_update_ha_stateschedule_update_ha_state(True)
85 
86  def _on_connected_changed(self, connected: bool, reason: str) -> None:
87  """Handle connected changes."""
88  self.schedule_update_ha_stateschedule_update_ha_state(True)
89 
90  async def async_turn_on(self, **kwargs: Any) -> None:
91  """Turn on the light."""
92 
93  # If neither attribute is specified then the simple activate load
94  # LiteJet API will use the per-light default brightness and
95  # transition values programmed in the LiteJet system.
96  if ATTR_BRIGHTNESS not in kwargs and ATTR_TRANSITION not in kwargs:
97  try:
98  await self._lj_lj.activate_load(self._index_index)
99  except LiteJetError as exc:
100  raise HomeAssistantError from exc
101  return
102 
103  # If either attribute is specified then Home Assistant must
104  # control both values.
105  default_transition = self._config_entry_config_entry.options.get(CONF_DEFAULT_TRANSITION, 0)
106  transition = kwargs.get(ATTR_TRANSITION, default_transition)
107  brightness = int(kwargs.get(ATTR_BRIGHTNESS, 255) / 255 * 99)
108 
109  try:
110  await self._lj_lj.activate_load_at(self._index_index, brightness, int(transition))
111  except LiteJetError as exc:
112  raise HomeAssistantError from exc
113 
114  async def async_turn_off(self, **kwargs: Any) -> None:
115  """Turn off the light."""
116  if ATTR_TRANSITION in kwargs:
117  try:
118  await self._lj_lj.activate_load_at(self._index_index, 0, kwargs[ATTR_TRANSITION])
119  except LiteJetError as exc:
120  raise HomeAssistantError from exc
121  return
122 
123  # If transition attribute is not specified then the simple
124  # deactivate load LiteJet API will use the per-light default
125  # transition value programmed in the LiteJet system.
126  try:
127  await self._lj_lj.deactivate_load(self._index_index)
128  except LiteJetError as exc:
129  raise HomeAssistantError from exc
130 
131  async def async_update(self) -> None:
132  """Retrieve the light's brightness from the LiteJet system."""
133  self._attr_available_attr_available = self._lj_lj.connected
134 
135  if not self.availableavailable:
136  return
137 
138  self._attr_brightness_attr_brightness = int(
139  await self._lj_lj.get_load_level(self._index_index) / 99 * 255
140  )
141  self._attr_is_on_attr_is_on = self.brightnessbrightness != 0
None _on_connected_changed(self, bool connected, str reason)
Definition: light.py:86
None _on_load_changed(self, int|None level)
Definition: light.py:82
None __init__(self, ConfigEntry config_entry, LiteJet system, int index, str name)
Definition: light.py:56
None schedule_update_ha_state(self, bool force_refresh=False)
Definition: entity.py:1244
None async_setup_entry(HomeAssistant hass, ConfigEntry config_entry, AddEntitiesCallback async_add_entities)
Definition: light.py:31