light.py 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472
  1. """
  2. Setup for different kinds of Tuya light devices
  3. """
  4. import logging
  5. from struct import pack, unpack
  6. import homeassistant.util.color as color_util
  7. from homeassistant.components.light import (
  8. ATTR_BRIGHTNESS,
  9. ATTR_COLOR_TEMP_KELVIN,
  10. ATTR_EFFECT,
  11. ATTR_HS_COLOR,
  12. ATTR_WHITE,
  13. EFFECT_OFF,
  14. ColorMode,
  15. LightEntity,
  16. LightEntityFeature,
  17. )
  18. from .device import TuyaLocalDevice
  19. from .helpers.config import async_tuya_setup_platform
  20. from .helpers.device_config import TuyaEntityConfig
  21. from .helpers.mixin import TuyaLocalEntity
  22. _LOGGER = logging.getLogger(__name__)
  23. async def async_setup_entry(hass, config_entry, async_add_entities):
  24. config = {**config_entry.data, **config_entry.options}
  25. await async_tuya_setup_platform(
  26. hass,
  27. async_add_entities,
  28. config,
  29. "light",
  30. TuyaLocalLight,
  31. )
  32. class TuyaLocalLight(TuyaLocalEntity, LightEntity):
  33. """Representation of a Tuya WiFi-connected light."""
  34. def __init__(self, device: TuyaLocalDevice, config: TuyaEntityConfig):
  35. """
  36. Initialize the light.
  37. Args:
  38. device (TuyaLocalDevice): The device API instance.
  39. config (TuyaEntityConfig): The configuration for this entity.
  40. """
  41. super().__init__()
  42. dps_map = self._init_begin(device, config)
  43. self._switch_dps = dps_map.pop("switch", None)
  44. self._brightness_dps = dps_map.pop("brightness", None)
  45. self._color_mode_dps = dps_map.pop("color_mode", None)
  46. self._color_temp_dps = dps_map.pop("color_temp", None)
  47. self._rgbhsv_dps = dps_map.pop("rgbhsv", None)
  48. self._effect_dps = dps_map.pop("effect", None)
  49. self._init_end(dps_map)
  50. # Set min and max color temp
  51. if self._color_temp_dps:
  52. m = self._color_temp_dps._find_map_for_dps(0)
  53. if m:
  54. tr = m.get("target_range")
  55. if tr:
  56. self._attr_min_color_temp_kelvin = tr.get("min")
  57. self._attr_max_color_temp_kelvin = tr.get("max")
  58. @property
  59. def supported_color_modes(self):
  60. """Return the supported color modes for this light."""
  61. if self._color_mode_dps:
  62. return {
  63. ColorMode(mode)
  64. for mode in self._color_mode_dps.values(self._device)
  65. if mode and hasattr(ColorMode, mode.upper())
  66. }
  67. else:
  68. try:
  69. mode = ColorMode(self.color_mode)
  70. if mode and mode != ColorMode.UNKNOWN:
  71. return {mode}
  72. except ValueError:
  73. _LOGGER.warning(
  74. "%s/%s: Unrecognised color mode %s ignored",
  75. self._config._device.config,
  76. self.name or "light",
  77. self.color_mode,
  78. )
  79. return set()
  80. @property
  81. def supported_features(self):
  82. """Return the supported features for this light."""
  83. if self.effect_list:
  84. return LightEntityFeature.EFFECT
  85. else:
  86. return LightEntityFeature(0)
  87. @property
  88. def color_mode(self):
  89. """Return the color mode of the light"""
  90. from_dp = self.raw_color_mode
  91. if from_dp:
  92. return from_dp
  93. if self._rgbhsv_dps:
  94. return ColorMode.HS
  95. elif self._color_temp_dps:
  96. return ColorMode.COLOR_TEMP
  97. elif self._brightness_dps:
  98. return ColorMode.BRIGHTNESS
  99. elif self._switch_dps:
  100. return ColorMode.ONOFF
  101. else:
  102. return ColorMode.UNKNOWN
  103. @property
  104. def raw_color_mode(self):
  105. """Return the color_mode as set from the dps."""
  106. if self._color_mode_dps:
  107. mode = self._color_mode_dps.get_value(self._device)
  108. if mode and hasattr(ColorMode, mode.upper()):
  109. return ColorMode(mode)
  110. @property
  111. def color_temp_kelvin(self):
  112. """Return the color temperature in kelvin."""
  113. if self._color_temp_dps:
  114. return self._color_temp_dps.get_value(self._device)
  115. @property
  116. def is_on(self):
  117. """Return the current state."""
  118. if self._switch_dps:
  119. return self._switch_dps.get_value(self._device)
  120. elif self._brightness_dps:
  121. b = self.brightness
  122. return isinstance(b, int) and b > 0
  123. else:
  124. # There shouldn't be lights without control, but if there are,
  125. # assume always on if they are responding
  126. return self.available
  127. @property
  128. def _brightness_control_by_hsv(self):
  129. """Return whether brightness is controlled by HSV."""
  130. v_available = self._rgbhsv_dps and "v" in self._rgbhsv_dps.format["names"]
  131. b_available = self._brightness_dps is not None
  132. current_raw_mode = self.raw_color_mode
  133. current_mode = self.color_mode
  134. if current_raw_mode == ColorMode.HS and v_available:
  135. return True
  136. if current_raw_mode is None and current_mode == ColorMode.HS and v_available:
  137. return True
  138. if b_available:
  139. return False
  140. if v_available:
  141. return True
  142. return False
  143. @property
  144. def brightness(self):
  145. """Get the current brightness of the light"""
  146. if self._brightness_control_by_hsv:
  147. return self._hsv_brightness
  148. return self._white_brightness
  149. @property
  150. def _white_brightness(self):
  151. if self._brightness_dps:
  152. r = self._brightness_dps.range(self._device)
  153. val = self._brightness_dps.get_value(self._device)
  154. if r and val is not None:
  155. val = color_util.value_to_brightness(r, val)
  156. return val
  157. @property
  158. def _unpacked_rgbhsv(self):
  159. """Get the unpacked rgbhsv data"""
  160. if self._rgbhsv_dps:
  161. color = self._rgbhsv_dps.decoded_value(self._device)
  162. fmt = self._rgbhsv_dps.format
  163. if fmt and color:
  164. vals = unpack(fmt.get("format"), color)
  165. idx = 0
  166. rgbhsv = {}
  167. for v in vals:
  168. # HA range: s = 0-100, rgbv = 0-255, h = 0-360
  169. n = fmt["names"][idx]
  170. r = fmt["ranges"][idx]
  171. mx = r["max"]
  172. scale = 1
  173. if n == "h":
  174. scale = 360 / mx
  175. elif n == "s":
  176. scale = 100 / mx
  177. else:
  178. scale = 255 / mx
  179. rgbhsv[n] = round(scale * v)
  180. idx += 1
  181. return rgbhsv
  182. @property
  183. def _hsv_brightness(self):
  184. """Get the colour mode brightness from the light"""
  185. rgbhsv = self._unpacked_rgbhsv
  186. if rgbhsv:
  187. return rgbhsv.get("v", self._white_brightness)
  188. return self._white_brightness
  189. @property
  190. def hs_color(self):
  191. """Get the current hs color of the light"""
  192. rgbhsv = self._unpacked_rgbhsv
  193. if rgbhsv:
  194. if "h" in rgbhsv and "s" in rgbhsv:
  195. hs = (rgbhsv["h"], rgbhsv["s"])
  196. else:
  197. r = rgbhsv.get("r")
  198. g = rgbhsv.get("g")
  199. b = rgbhsv.get("b")
  200. hs = color_util.color_RGB_to_hs(r, g, b)
  201. return hs
  202. @property
  203. def effect_list(self):
  204. """Return the list of valid effects for the light"""
  205. if self._effect_dps:
  206. return self._effect_dps.values(self._device)
  207. elif self._color_mode_dps:
  208. effects = [
  209. effect
  210. for effect in self._color_mode_dps.values(self._device)
  211. if effect and not hasattr(ColorMode, effect.upper())
  212. ]
  213. effects.append(EFFECT_OFF)
  214. return effects
  215. @property
  216. def effect(self):
  217. """Return the current effect setting of this light"""
  218. if self._effect_dps:
  219. return self._effect_dps.get_value(self._device)
  220. elif self._color_mode_dps:
  221. mode = self._color_mode_dps.get_value(self._device)
  222. if mode and not hasattr(ColorMode, mode.upper()):
  223. return mode
  224. return EFFECT_OFF
  225. async def async_turn_on(self, **params):
  226. settings = {}
  227. color_mode = None
  228. if self._color_mode_dps and ATTR_WHITE in params:
  229. if self.color_mode != ColorMode.WHITE:
  230. color_mode = ColorMode.WHITE
  231. if ATTR_BRIGHTNESS not in params and self._brightness_dps:
  232. bright = params.get(ATTR_WHITE)
  233. _LOGGER.debug(
  234. "Setting brightness via WHITE parameter to %d",
  235. bright,
  236. )
  237. r = self._brightness_dps.range(self._device)
  238. if r:
  239. bright = color_util.brightness_to_value(r, bright)
  240. settings = {
  241. **settings,
  242. **self._brightness_dps.get_values_to_set(
  243. self._device,
  244. bright,
  245. ),
  246. }
  247. elif self._color_temp_dps and ATTR_COLOR_TEMP_KELVIN in params:
  248. if self.color_mode != ColorMode.COLOR_TEMP:
  249. color_mode = ColorMode.COLOR_TEMP
  250. color_temp = params.get(ATTR_COLOR_TEMP_KELVIN)
  251. # Light groups use the widest range from the lights in the
  252. # group, so we are expected to silently handle out of range values
  253. if color_temp < self.min_color_temp_kelvin:
  254. color_temp = self.min_color_temp_kelvin
  255. if color_temp > self.max_color_temp_kelvin:
  256. color_temp = self.max_color_temp_kelvin
  257. _LOGGER.debug("Setting color temp to %d", color_temp)
  258. settings = {
  259. **settings,
  260. **self._color_temp_dps.get_values_to_set(
  261. self._device,
  262. color_temp,
  263. ),
  264. }
  265. elif self._rgbhsv_dps and (
  266. ATTR_HS_COLOR in params
  267. or (ATTR_BRIGHTNESS in params and self._brightness_control_by_hsv)
  268. ):
  269. if self.color_mode != ColorMode.HS:
  270. color_mode = ColorMode.HS
  271. hs = params.get(ATTR_HS_COLOR, self.hs_color or (0, 0))
  272. brightness = params.get(ATTR_BRIGHTNESS, self.brightness or 255)
  273. fmt = self._rgbhsv_dps.format
  274. if hs and fmt:
  275. rgb = color_util.color_hsv_to_RGB(*hs, brightness / 2.55)
  276. rgbhsv = {
  277. "r": rgb[0],
  278. "g": rgb[1],
  279. "b": rgb[2],
  280. "h": hs[0],
  281. "s": hs[1],
  282. "v": brightness,
  283. }
  284. _LOGGER.debug(
  285. "Setting color as R:%d,G:%d,B:%d,H:%d,S:%d,V:%d",
  286. rgb[0],
  287. rgb[1],
  288. rgb[2],
  289. hs[0],
  290. hs[1],
  291. brightness,
  292. )
  293. ordered = []
  294. idx = 0
  295. for n in fmt["names"]:
  296. r = fmt["ranges"][idx]
  297. scale = 1
  298. if n == "s":
  299. scale = r["max"] / 100
  300. elif n == "h":
  301. scale = r["max"] / 360
  302. else:
  303. scale = r["max"] / 255
  304. val = round(rgbhsv[n] * scale)
  305. if val < r["min"]:
  306. _LOGGER.warning(
  307. "%s/%s: Color data %s=%d constrained to be above %d",
  308. self._config._device.config,
  309. self.name or "light",
  310. n,
  311. val,
  312. r["min"],
  313. )
  314. val = r["min"]
  315. ordered.append(val)
  316. idx += 1
  317. binary = pack(fmt["format"], *ordered)
  318. settings = {
  319. **settings,
  320. **self._rgbhsv_dps.get_values_to_set(
  321. self._device,
  322. self._rgbhsv_dps.encode_value(binary),
  323. ),
  324. }
  325. if self._color_mode_dps:
  326. if color_mode:
  327. _LOGGER.debug("Auto setting color mode to %s", color_mode)
  328. settings = {
  329. **settings,
  330. **self._color_mode_dps.get_values_to_set(
  331. self._device,
  332. color_mode,
  333. ),
  334. }
  335. elif not self._effect_dps:
  336. effect = params.get(ATTR_EFFECT)
  337. if effect:
  338. if effect == EFFECT_OFF:
  339. # Turn off the effect. Ideally this should keep the
  340. # previous mode, but since the mode is shared with
  341. # effect, use the default, or first in the list
  342. effect = (
  343. self._color_mode_dps.default
  344. or self._color_mode_dps.values(self._device)[0]
  345. )
  346. _LOGGER.debug(
  347. "Emulating effect using color mode of %s",
  348. effect,
  349. )
  350. settings = {
  351. **settings,
  352. **self._color_mode_dps.get_values_to_set(
  353. self._device,
  354. effect,
  355. ),
  356. }
  357. if (
  358. ATTR_BRIGHTNESS in params
  359. and not self._brightness_control_by_hsv
  360. and self._brightness_dps
  361. ):
  362. bright = params.get(ATTR_BRIGHTNESS)
  363. _LOGGER.debug("Setting brightness to %s", bright)
  364. r = self._brightness_dps.range(self._device)
  365. if r:
  366. bright = color_util.brightness_to_value(r, bright)
  367. settings = {
  368. **settings,
  369. **self._brightness_dps.get_values_to_set(
  370. self._device,
  371. bright,
  372. ),
  373. }
  374. if self._effect_dps:
  375. effect = params.get(ATTR_EFFECT, None)
  376. if effect:
  377. _LOGGER.debug("Setting effect to %s", effect)
  378. settings = {
  379. **settings,
  380. **self._effect_dps.get_values_to_set(
  381. self._device,
  382. effect,
  383. ),
  384. }
  385. if self._switch_dps and not self.is_on:
  386. if (
  387. self._switch_dps.readonly
  388. and self._effect_dps
  389. and "on" in self._effect_dps.values(self._device)
  390. ):
  391. # Special case for motion sensor lights with readonly switch
  392. # that have tristate switch available as effect
  393. if self._effect_dps.id not in settings:
  394. settings = settings | self._effect_dps.get_values_to_set(
  395. self._device, "on"
  396. )
  397. else:
  398. settings = settings | self._switch_dps.get_values_to_set(
  399. self._device, True
  400. )
  401. elif self._brightness_dps and not self.is_on:
  402. bright = 255
  403. r = self._brightness_dps.range(self._device)
  404. if r:
  405. bright = color_util.brightness_to_value(r, bright)
  406. settings = settings | self._brightness_dps.get_values_to_set(
  407. self._device, bright
  408. )
  409. if settings:
  410. await self._device.async_set_properties(settings)
  411. async def async_turn_off(self):
  412. if self._switch_dps:
  413. if (
  414. self._switch_dps.readonly
  415. and self._effect_dps
  416. and "off" in self._effect_dps.values(self._device)
  417. ):
  418. # Special case for motion sensor lights with readonly switch
  419. # that have tristate switch available as effect
  420. await self._effect_dps.async_set_value(self._device, "off")
  421. else:
  422. await self._switch_dps.async_set_value(self._device, False)
  423. elif self._brightness_dps:
  424. await self._brightness_dps.async_set_value(self._device, 0)
  425. else:
  426. raise NotImplementedError()
  427. async def async_toggle(self):
  428. disp_on = self.is_on
  429. await (self.async_turn_on() if not disp_on else self.async_turn_off())