light.py 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593
  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 .entity import TuyaLocalEntity
  20. from .helpers.config import async_tuya_setup_platform
  21. from .helpers.device_config import TuyaEntityConfig
  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. def _ha_brightness_to_dp_value(ha_brightness, dp_range):
  33. """Convert HA brightness to a clamped device DP value."""
  34. if ha_brightness == 1 and dp_range[0] != 0:
  35. return dp_range[0]
  36. dp_value = color_util.brightness_to_value(dp_range, ha_brightness)
  37. return max(dp_range[0], dp_value)
  38. class TuyaLocalLight(TuyaLocalEntity, LightEntity):
  39. """Representation of a Tuya WiFi-connected light."""
  40. def __init__(self, device: TuyaLocalDevice, config: TuyaEntityConfig):
  41. """
  42. Initialize the light.
  43. Args:
  44. device (TuyaLocalDevice): The device API instance.
  45. config (TuyaEntityConfig): The configuration for this entity.
  46. """
  47. super().__init__()
  48. dps_map = self._init_begin(device, config)
  49. self._switch_dps = dps_map.pop("switch", None)
  50. self._brightness_dps = dps_map.pop("brightness", None)
  51. self._color_mode_dps = dps_map.pop("color_mode", None)
  52. self._color_temp_dps = dps_map.pop("color_temp", None)
  53. self._rgbhsv_dps = dps_map.pop("rgbhsv", None)
  54. self._named_color_dps = dps_map.pop("named_color", None)
  55. self._effect_dps = dps_map.pop("effect", None)
  56. self._init_end(dps_map)
  57. # Set min and max color temp
  58. if self._color_temp_dps:
  59. range_set = False
  60. m = self._color_temp_dps._find_map_for_dps(0, self._device)
  61. if m:
  62. tr = m.get("target_range")
  63. if tr:
  64. self._attr_min_color_temp_kelvin = tr.get("min")
  65. self._attr_max_color_temp_kelvin = tr.get("max")
  66. range_set = True
  67. if not range_set:
  68. r = self._color_temp_dps.range(self._device)
  69. if r:
  70. # For lights that use K natively, use range
  71. self._attr_min_color_temp_kelvin = r[0]
  72. self._attr_max_color_temp_kelvin = r[1]
  73. @property
  74. def supported_color_modes(self):
  75. """Return the supported color modes for this light."""
  76. if self._color_mode_dps:
  77. return {
  78. ColorMode(mode)
  79. for mode in self._color_mode_dps.values(self._device)
  80. if mode and hasattr(ColorMode, mode.upper())
  81. }
  82. else:
  83. try:
  84. mode = ColorMode(self.color_mode)
  85. if mode and mode != ColorMode.UNKNOWN:
  86. return {mode}
  87. except ValueError:
  88. _LOGGER.warning(
  89. "%s/%s: Unrecognised color mode %s ignored",
  90. self._config._device.config,
  91. self.name or "light",
  92. self.color_mode,
  93. )
  94. @property
  95. def supported_features(self):
  96. """Return the supported features for this light."""
  97. if self.effect_list:
  98. return LightEntityFeature.EFFECT
  99. else:
  100. return LightEntityFeature(0)
  101. @property
  102. def color_mode(self):
  103. """Return the color mode of the light"""
  104. from_dp = self.raw_color_mode
  105. if from_dp:
  106. return from_dp
  107. if self._rgbhsv_dps:
  108. return ColorMode.HS
  109. elif self._named_color_dps:
  110. return ColorMode.HS
  111. elif self._color_temp_dps:
  112. return ColorMode.COLOR_TEMP
  113. elif self._brightness_dps:
  114. return ColorMode.BRIGHTNESS
  115. elif self._switch_dps:
  116. return ColorMode.ONOFF
  117. else:
  118. return ColorMode.UNKNOWN
  119. @property
  120. def raw_color_mode(self):
  121. """Return the color_mode as set from the dps."""
  122. if self._color_mode_dps:
  123. mode = self._color_mode_dps.get_value(self._device)
  124. if mode and hasattr(ColorMode, mode.upper()):
  125. return ColorMode(mode)
  126. @property
  127. def color_temp_kelvin(self):
  128. """Return the color temperature in kelvin."""
  129. if self._color_temp_dps and self.color_mode != ColorMode.HS:
  130. return self._color_temp_dps.get_value(self._device)
  131. @property
  132. def is_on(self):
  133. """Return the current state."""
  134. if self._switch_dps:
  135. return self._switch_dps.get_value(self._device)
  136. elif self._brightness_dps:
  137. b = self.brightness
  138. return isinstance(b, int) and b > 0
  139. elif self._effect_dps and "off" in self._effect_dps.values(self._device):
  140. return self._effect_dps.get_value(self._device) != "off"
  141. else:
  142. # There shouldn't be lights without control, but if there are,
  143. # assume always on if they are responding
  144. return self.available
  145. def _brightness_control_by_hsv(self, target_mode=None):
  146. """Return whether brightness is controlled by HSV."""
  147. v_available = self._rgbhsv_dps and "v" in self._rgbhsv_dps.format["names"]
  148. b_available = self._brightness_dps is not None
  149. current_raw_mode = target_mode or self.raw_color_mode
  150. current_mode = target_mode or self.color_mode
  151. if current_raw_mode == ColorMode.HS and v_available:
  152. return True
  153. if current_raw_mode is None and current_mode == ColorMode.HS and v_available:
  154. return True
  155. if b_available:
  156. return False
  157. return v_available
  158. @property
  159. def brightness(self):
  160. """Get the current brightness of the light"""
  161. if self._brightness_control_by_hsv():
  162. return self._hsv_brightness
  163. return self._white_brightness
  164. @property
  165. def _effective_brightness_range(self):
  166. """Get the effective brightness range of the light"""
  167. if self._brightness_dps:
  168. r = self._brightness_dps.range(self._device)
  169. if r:
  170. if self._switch_dps is None and r[0] == 0:
  171. # If the light has no switch, and the brightness range starts
  172. # at 0, the effective minimum brightness is 1
  173. return (self._brightness_dps.step(self._device, False), r[1])
  174. return r
  175. @property
  176. def _white_brightness(self):
  177. if self._brightness_dps:
  178. r = self._effective_brightness_range
  179. val = self._brightness_dps.get_value(self._device)
  180. if r and val:
  181. val = color_util.value_to_brightness(r, val)
  182. return val
  183. @property
  184. def _unpacked_rgbhsv(self):
  185. """Get the unpacked rgbhsv data"""
  186. if self._rgbhsv_dps:
  187. color = self._rgbhsv_dps.decoded_value(self._device)
  188. fmt = self._rgbhsv_dps.format
  189. if fmt and color:
  190. vals = unpack(fmt.get("format"), color)
  191. idx = 0
  192. rgbhsv = {}
  193. for v in vals:
  194. # HA range: s = 0-100, rgbv = 0-255, h = 0-360
  195. n = fmt["names"][idx]
  196. r = fmt["ranges"][idx]
  197. mx = r["max"]
  198. scale = 1
  199. if n == "h":
  200. scale = 360 / mx
  201. elif n == "s":
  202. scale = 100 / mx
  203. elif n in ["v", "r", "g", "b"]:
  204. scale = 255 / mx
  205. rgbhsv[n] = round(scale * v)
  206. idx += 1
  207. return rgbhsv
  208. elif self._named_color_dps:
  209. colour = self._named_color_dps.get_value(self._device)
  210. if colour:
  211. rgb = color_util.color_name_to_rgb(colour)
  212. return {"r": rgb[0], "g": rgb[1], "b": rgb[2]}
  213. @property
  214. def _hsv_brightness(self):
  215. """Get the colour mode brightness from the light"""
  216. rgbhsv = self._unpacked_rgbhsv
  217. if rgbhsv:
  218. return rgbhsv.get("v", self._white_brightness)
  219. return self._white_brightness
  220. @property
  221. def hs_color(self):
  222. """Get the current hs color of the light"""
  223. rgbhsv = self._unpacked_rgbhsv
  224. if rgbhsv:
  225. if "h" in rgbhsv and "s" in rgbhsv:
  226. hs = (rgbhsv["h"], rgbhsv["s"])
  227. else:
  228. r = rgbhsv.get("r")
  229. g = rgbhsv.get("g")
  230. b = rgbhsv.get("b")
  231. hs = color_util.color_RGB_to_hs(r, g, b)
  232. return hs
  233. @property
  234. def effect_list(self):
  235. """Return the list of valid effects for the light"""
  236. if self._effect_dps:
  237. return self._effect_dps.values(self._device)
  238. elif self._color_mode_dps:
  239. effects = [
  240. effect
  241. for effect in self._color_mode_dps.values(self._device)
  242. if effect and not hasattr(ColorMode, effect.upper())
  243. ]
  244. effects.append(EFFECT_OFF)
  245. return effects
  246. @property
  247. def effect(self):
  248. """Return the current effect setting of this light"""
  249. if self._effect_dps:
  250. return self._effect_dps.get_value(self._device)
  251. elif self._color_mode_dps:
  252. mode = self._color_mode_dps.get_value(self._device)
  253. if mode and not hasattr(ColorMode, mode.upper()):
  254. return mode
  255. return EFFECT_OFF
  256. def named_color_from_hsv(self, hs, brightness):
  257. """Get the named color from the rgb value"""
  258. if self._named_color_dps:
  259. palette = self._named_color_dps.values(self._device)
  260. xy = color_util.color_hs_to_xy(*hs)
  261. distance = float("inf")
  262. best_match = None
  263. for entry in palette:
  264. rgb = color_util.color_name_to_rgb(entry)
  265. xy_entry = color_util.color_RGB_to_xy(*rgb)
  266. d = color_util.get_distance_between_two_points(
  267. color_util.XYPoint(*xy),
  268. color_util.XYPoint(*xy_entry),
  269. )
  270. if d < distance:
  271. distance = d
  272. best_match = entry
  273. return best_match
  274. async def async_turn_on(self, **params):
  275. settings = {}
  276. color_mode = None
  277. _LOGGER.debug("Light turn_on: %s", params)
  278. if self._color_mode_dps and ATTR_WHITE in params:
  279. if self.color_mode != ColorMode.WHITE:
  280. color_mode = ColorMode.WHITE
  281. if ATTR_BRIGHTNESS not in params and self._brightness_dps:
  282. bright = params.get(ATTR_WHITE)
  283. r = self._effective_brightness_range
  284. if r:
  285. bright = _ha_brightness_to_dp_value(bright, r)
  286. _LOGGER.info(
  287. "%s setting white brightness to %d", self._config.config_id, bright
  288. )
  289. settings = {
  290. **settings,
  291. **self._brightness_dps.get_values_to_set(
  292. self._device,
  293. bright,
  294. settings,
  295. ),
  296. }
  297. elif self._color_temp_dps and ATTR_COLOR_TEMP_KELVIN in params:
  298. if self.color_mode != ColorMode.COLOR_TEMP:
  299. color_mode = ColorMode.COLOR_TEMP
  300. color_temp = params.get(ATTR_COLOR_TEMP_KELVIN)
  301. # Light groups use the widest range from the lights in the
  302. # group, so we are expected to silently handle out of range values
  303. if color_temp < self.min_color_temp_kelvin:
  304. color_temp = self.min_color_temp_kelvin
  305. if color_temp > self.max_color_temp_kelvin:
  306. color_temp = self.max_color_temp_kelvin
  307. _LOGGER.info(
  308. "%s setting color temp to %d", self._config.config_id, color_temp
  309. )
  310. settings = {
  311. **settings,
  312. **self._color_temp_dps.get_values_to_set(
  313. self._device,
  314. color_temp,
  315. settings,
  316. ),
  317. }
  318. elif self._rgbhsv_dps and (
  319. ATTR_HS_COLOR in params
  320. or (ATTR_BRIGHTNESS in params and self._brightness_control_by_hsv())
  321. ):
  322. if self.color_mode != ColorMode.HS:
  323. color_mode = ColorMode.HS
  324. hs = params.get(ATTR_HS_COLOR, self.hs_color or (0, 0))
  325. brightness = params.get(ATTR_BRIGHTNESS, self.brightness or 255)
  326. fmt = self._rgbhsv_dps.format
  327. if hs and fmt:
  328. rgb = color_util.color_hsv_to_RGB(*hs, brightness / 2.55)
  329. rgbhsv = {
  330. "r": rgb[0],
  331. "g": rgb[1],
  332. "b": rgb[2],
  333. "h": hs[0],
  334. "s": hs[1],
  335. "v": brightness,
  336. }
  337. _LOGGER.debug(
  338. "Setting color as R:%d,G:%d,B:%d,H:%d,S:%d,V:%d",
  339. rgb[0],
  340. rgb[1],
  341. rgb[2],
  342. hs[0],
  343. hs[1],
  344. brightness,
  345. )
  346. current = self._unpacked_rgbhsv
  347. ordered = []
  348. idx = 0
  349. for n in fmt["names"]:
  350. if n in rgbhsv:
  351. r = fmt["ranges"][idx]
  352. scale = 1
  353. if n == "s":
  354. scale = r["max"] / 100
  355. elif n == "h":
  356. scale = r["max"] / 360
  357. else:
  358. scale = r["max"] / 255
  359. val = round(rgbhsv[n] * scale)
  360. if val < r["min"]:
  361. _LOGGER.warning(
  362. "%s/%s: Color data %s=%d constrained to be above %d",
  363. self._config._device.config,
  364. self.name or "light",
  365. n,
  366. val,
  367. r["min"],
  368. )
  369. val = r["min"]
  370. else:
  371. val = current[n]
  372. ordered.append(val)
  373. idx += 1
  374. binary = pack(fmt["format"], *ordered)
  375. encoded = self._rgbhsv_dps.encode_value(binary)
  376. _LOGGER.info("%s setting color to %s", self._config.config_id, encoded)
  377. settings = {
  378. **settings,
  379. **self._rgbhsv_dps.get_values_to_set(
  380. self._device,
  381. encoded,
  382. settings,
  383. ),
  384. }
  385. elif self._named_color_dps and ATTR_HS_COLOR in params:
  386. if self.color_mode != ColorMode.HS:
  387. color_mode = ColorMode.HS
  388. hs = params.get(ATTR_HS_COLOR, self.hs_color or (0, 0))
  389. brightness = params.get(ATTR_BRIGHTNESS, self.brightness or 255)
  390. best_match = self.named_color_from_hsv(hs, brightness)
  391. _LOGGER.debug("Setting color to %s", best_match)
  392. if best_match:
  393. _LOGGER.info(
  394. "%s setting named color to %s", self._config.config_id, best_match
  395. )
  396. settings = {
  397. **settings,
  398. **self._named_color_dps.get_values_to_set(
  399. self._device,
  400. best_match,
  401. settings,
  402. ),
  403. }
  404. if self._color_mode_dps:
  405. if color_mode:
  406. _LOGGER.info(
  407. "%s auto setting color mode to %s",
  408. self._config.config_id,
  409. color_mode,
  410. )
  411. settings = {
  412. **settings,
  413. **self._color_mode_dps.get_values_to_set(
  414. self._device,
  415. color_mode,
  416. settings,
  417. ),
  418. }
  419. elif not self._effect_dps:
  420. effect = params.get(ATTR_EFFECT)
  421. if effect and effect != self.effect:
  422. if effect == EFFECT_OFF:
  423. # Turn off the effect. Ideally this should keep the
  424. # previous mode, but since the mode is shared with
  425. # effect, use the default, or first in the list
  426. effect = (
  427. self._color_mode_dps.default
  428. or self._color_mode_dps.values(self._device)[0]
  429. )
  430. _LOGGER.info(
  431. "%s emulating effect using color mode of %s",
  432. self._config.config_id,
  433. effect,
  434. )
  435. settings = {
  436. **settings,
  437. **self._color_mode_dps.get_values_to_set(
  438. self._device,
  439. effect,
  440. settings,
  441. ),
  442. }
  443. if (
  444. ATTR_BRIGHTNESS in params
  445. and not self._brightness_control_by_hsv(color_mode)
  446. and self._brightness_dps
  447. ):
  448. bright = params.get(ATTR_BRIGHTNESS)
  449. r = self._effective_brightness_range
  450. if r:
  451. bright = _ha_brightness_to_dp_value(bright, r)
  452. _LOGGER.info("%s setting brightness to %d", self._config.config_id, bright)
  453. settings = {
  454. **settings,
  455. **self._brightness_dps.get_values_to_set(
  456. self._device,
  457. bright,
  458. settings,
  459. ),
  460. }
  461. if self._effect_dps:
  462. effect = params.get(ATTR_EFFECT, None)
  463. if effect:
  464. _LOGGER.info("%s setting effect to %s", self._config.config_id, effect)
  465. settings = {
  466. **settings,
  467. **self._effect_dps.get_values_to_set(
  468. self._device,
  469. effect,
  470. settings,
  471. ),
  472. }
  473. # On packed dps where switch / brightness / effect all share the same
  474. # dp id (e.g. dp 51 with different masks), the original `id not in
  475. # settings` check incorrectly skipped the switch-on merge once any
  476. # other masked sub-field had populated settings. For masked dps it's
  477. # always safe to merge — get_values_to_set with pending_map=settings
  478. # will OR onto the existing pending value.
  479. if (
  480. self._switch_dps
  481. and not self._switch_dps.readonly
  482. and not self.is_on
  483. and (
  484. self._switch_dps.mask is not None or self._switch_dps.id not in settings
  485. )
  486. ):
  487. _LOGGER.info("%s turning light on", self._config.config_id)
  488. settings = settings | self._switch_dps.get_values_to_set(
  489. self._device, True, settings
  490. )
  491. elif (
  492. self._brightness_dps
  493. and not self.is_on
  494. and (
  495. self._brightness_dps.mask is not None
  496. or self._brightness_dps.id not in settings
  497. )
  498. ):
  499. bright = 255
  500. r = self._effective_brightness_range
  501. if r:
  502. bright = color_util.brightness_to_value(r, bright)
  503. _LOGGER.info(
  504. "%s turning light on to brightness %d",
  505. self._config.config_id,
  506. bright,
  507. )
  508. settings = settings | self._brightness_dps.get_values_to_set(
  509. self._device, bright, settings
  510. )
  511. elif (
  512. self._effect_dps
  513. and not self.is_on
  514. and "off" in self._effect_dps.values(self._device)
  515. and (
  516. self._effect_dps.mask is not None or self._effect_dps.id not in settings
  517. )
  518. ):
  519. # Special case for lights with effect that has off state, but no switch or brightness
  520. on_value = self._effect_dps.default
  521. if on_value is None and "on" in self._effect_dps.values(self._device):
  522. on_value = "on"
  523. if on_value:
  524. _LOGGER.info(
  525. "%s turning light on using %s effect",
  526. self._config.config_id,
  527. on_value,
  528. )
  529. settings = settings | self._effect_dps.get_values_to_set(
  530. self._device, on_value, settings
  531. )
  532. if settings:
  533. await self._device.async_set_properties(settings)
  534. async def async_turn_off(self):
  535. if self._switch_dps and not self._switch_dps.readonly:
  536. _LOGGER.info("%s turning light off", self._config.config_id)
  537. await self._switch_dps.async_set_value(self._device, False)
  538. elif self._brightness_dps:
  539. _LOGGER.info(
  540. "%s turning light off by setting brightness to 0",
  541. self._config.config_id,
  542. )
  543. await self._brightness_dps.async_set_value(self._device, 0)
  544. elif self._effect_dps and "off" in self._effect_dps.values(self._device):
  545. # off by effect
  546. _LOGGER.info("%s turning light off using effect", self._config.config_id)
  547. await self._effect_dps.async_set_value(self._device, "off")
  548. else:
  549. raise NotImplementedError()