Home Assistant Unofficial Reference 2024.12.1
light.py
Go to the documentation of this file.
1 """Support for Niko Home Control."""
2 
3 from __future__ import annotations
4 
5 from datetime import timedelta
6 import logging
7 from typing import Any
8 
9 import nikohomecontrol
10 import voluptuous as vol
11 
13  ATTR_BRIGHTNESS,
14  PLATFORM_SCHEMA as LIGHT_PLATFORM_SCHEMA,
15  ColorMode,
16  LightEntity,
17  brightness_supported,
18 )
19 from homeassistant.const import CONF_HOST
20 from homeassistant.core import HomeAssistant
21 from homeassistant.exceptions import PlatformNotReady
23 from homeassistant.helpers.entity_platform import AddEntitiesCallback
24 from homeassistant.helpers.typing import ConfigType, DiscoveryInfoType
25 from homeassistant.util import Throttle
26 
27 _LOGGER = logging.getLogger(__name__)
28 MIN_TIME_BETWEEN_UPDATES = timedelta(seconds=1)
29 SCAN_INTERVAL = timedelta(seconds=30)
30 
31 PLATFORM_SCHEMA = LIGHT_PLATFORM_SCHEMA.extend({vol.Required(CONF_HOST): cv.string})
32 
33 
35  hass: HomeAssistant,
36  config: ConfigType,
37  async_add_entities: AddEntitiesCallback,
38  discovery_info: DiscoveryInfoType | None = None,
39 ) -> None:
40  """Set up the Niko Home Control light platform."""
41  host = config[CONF_HOST]
42 
43  try:
44  nhc = nikohomecontrol.NikoHomeControl(
45  {"ip": host, "port": 8000, "timeout": 20000}
46  )
47  niko_data = NikoHomeControlData(hass, nhc)
48  await niko_data.async_update()
49  except OSError as err:
50  _LOGGER.error("Unable to access %s (%s)", host, err)
51  raise PlatformNotReady from err
52 
54  [NikoHomeControlLight(light, niko_data) for light in nhc.list_actions()], True
55  )
56 
57 
59  """Representation of an Niko Light."""
60 
61  def __init__(self, light, data):
62  """Set up the Niko Home Control light platform."""
63  self._data_data = data
64  self._light_light = light
65  self._attr_unique_id_attr_unique_id = f"light-{light.id}"
66  self._attr_name_attr_name = light.name
67  self._attr_is_on_attr_is_on = light.is_on
68  self._attr_color_mode_attr_color_mode = ColorMode.ONOFF
69  self._attr_supported_color_modes_attr_supported_color_modes = {ColorMode.ONOFF}
70  if light._state["type"] == 2: # noqa: SLF001
71  self._attr_color_mode_attr_color_mode = ColorMode.BRIGHTNESS
72  self._attr_supported_color_modes_attr_supported_color_modes = {ColorMode.BRIGHTNESS}
73 
74  def turn_on(self, **kwargs: Any) -> None:
75  """Instruct the light to turn on."""
76  _LOGGER.debug("Turn on: %s", self.namename)
77  self._light_light.turn_on(kwargs.get(ATTR_BRIGHTNESS, 255) / 2.55)
78 
79  def turn_off(self, **kwargs: Any) -> None:
80  """Instruct the light to turn off."""
81  _LOGGER.debug("Turn off: %s", self.namename)
82  self._light_light.turn_off()
83 
84  async def async_update(self) -> None:
85  """Get the latest data from NikoHomeControl API."""
86  await self._data_data.async_update()
87  state = self._data_data.get_state(self._light_light.id)
88  self._attr_is_on_attr_is_on = state != 0
89  if brightness_supported(self.supported_color_modessupported_color_modes):
90  self._attr_brightness_attr_brightness = state * 2.55
91 
92 
94  """The class for handling data retrieval."""
95 
96  def __init__(self, hass, nhc):
97  """Set up Niko Home Control Data object."""
98  self._nhc_nhc = nhc
99  self.hasshass = hass
100  self.availableavailable = True
101  self.datadata = {}
102  self._system_info_system_info = None
103 
104  @Throttle(MIN_TIME_BETWEEN_UPDATES)
105  async def async_update(self):
106  """Get the latest data from the NikoHomeControl API."""
107  _LOGGER.debug("Fetching async state in bulk")
108  try:
109  self.datadata = await self.hasshass.async_add_executor_job(
110  self._nhc_nhc.list_actions_raw
111  )
112  self.availableavailable = True
113  except OSError as ex:
114  _LOGGER.error("Unable to retrieve data from Niko, %s", str(ex))
115  self.availableavailable = False
116 
117  def get_state(self, aid):
118  """Find and filter state based on action id."""
119  for state in self.datadata:
120  if state["id"] == aid:
121  return state["value1"]
122  _LOGGER.error("Failed to retrieve state off unknown light")
123  return None
set[ColorMode]|set[str]|None supported_color_modes(self)
Definition: __init__.py:1302
str|UndefinedType|None name(self)
Definition: entity.py:738
str|float get_state(dict[str, float] data, str key)
Definition: sensor.py:26
bool brightness_supported(Iterable[ColorMode|str]|None color_modes)
Definition: __init__.py:155
None async_setup_platform(HomeAssistant hass, ConfigType config, AddEntitiesCallback async_add_entities, DiscoveryInfoType|None discovery_info=None)
Definition: light.py:39