light.py 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584
  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 _white_brightness(self):
  166. if self._brightness_dps:
  167. r = self._brightness_dps.range(self._device)
  168. val = self._brightness_dps.get_value(self._device)
  169. if r and val:
  170. val = color_util.value_to_brightness(r, val)
  171. return val
  172. @property
  173. def _unpacked_rgbhsv(self):
  174. """Get the unpacked rgbhsv data"""
  175. if self._rgbhsv_dps:
  176. color = self._rgbhsv_dps.decoded_value(self._device)
  177. fmt = self._rgbhsv_dps.format
  178. if fmt and color:
  179. vals = unpack(fmt.get("format"), color)
  180. idx = 0
  181. rgbhsv = {}
  182. for v in vals:
  183. # HA range: s = 0-100, rgbv = 0-255, h = 0-360
  184. n = fmt["names"][idx]
  185. r = fmt["ranges"][idx]
  186. mx = r["max"]
  187. scale = 1
  188. if n == "h":
  189. scale = 360 / mx
  190. elif n == "s":
  191. scale = 100 / mx
  192. elif n in ["v", "r", "g", "b"]:
  193. scale = 255 / mx
  194. rgbhsv[n] = round(scale * v)
  195. idx += 1
  196. return rgbhsv
  197. elif self._named_color_dps:
  198. colour = self._named_color_dps.get_value(self._device)
  199. if colour:
  200. rgb = color_util.color_name_to_rgb(colour)
  201. return {"r": rgb[0], "g": rgb[1], "b": rgb[2]}
  202. @property
  203. def _hsv_brightness(self):
  204. """Get the colour mode brightness from the light"""
  205. rgbhsv = self._unpacked_rgbhsv
  206. if rgbhsv:
  207. return rgbhsv.get("v", self._white_brightness)
  208. return self._white_brightness
  209. @property
  210. def hs_color(self):
  211. """Get the current hs color of the light"""
  212. rgbhsv = self._unpacked_rgbhsv
  213. if rgbhsv:
  214. if "h" in rgbhsv and "s" in rgbhsv:
  215. hs = (rgbhsv["h"], rgbhsv["s"])
  216. else:
  217. r = rgbhsv.get("r")
  218. g = rgbhsv.get("g")
  219. b = rgbhsv.get("b")
  220. hs = color_util.color_RGB_to_hs(r, g, b)
  221. return hs
  222. @property
  223. def effect_list(self):
  224. """Return the list of valid effects for the light"""
  225. if self._effect_dps:
  226. return self._effect_dps.values(self._device)
  227. elif self._color_mode_dps:
  228. effects = [
  229. effect
  230. for effect in self._color_mode_dps.values(self._device)
  231. if effect and not hasattr(ColorMode, effect.upper())
  232. ]
  233. effects.append(EFFECT_OFF)
  234. return effects
  235. @property
  236. def effect(self):
  237. """Return the current effect setting of this light"""
  238. if self._effect_dps:
  239. return self._effect_dps.get_value(self._device)
  240. elif self._color_mode_dps:
  241. mode = self._color_mode_dps.get_value(self._device)
  242. if mode and not hasattr(ColorMode, mode.upper()):
  243. return mode
  244. return EFFECT_OFF
  245. def named_color_from_hsv(self, hs, brightness):
  246. """Get the named color from the rgb value"""
  247. if self._named_color_dps:
  248. palette = self._named_color_dps.values(self._device)
  249. xy = color_util.color_hs_to_xy(*hs)
  250. distance = float("inf")
  251. best_match = None
  252. for entry in palette:
  253. rgb = color_util.color_name_to_rgb(entry)
  254. xy_entry = color_util.color_RGB_to_xy(*rgb)
  255. d = color_util.get_distance_between_two_points(
  256. color_util.XYPoint(*xy),
  257. color_util.XYPoint(*xy_entry),
  258. )
  259. if d < distance:
  260. distance = d
  261. best_match = entry
  262. return best_match
  263. async def async_turn_on(self, **params):
  264. settings = {}
  265. color_mode = None
  266. _LOGGER.debug("Light turn_on: %s", params)
  267. if self._color_mode_dps and ATTR_WHITE in params:
  268. if self.color_mode != ColorMode.WHITE:
  269. color_mode = ColorMode.WHITE
  270. if ATTR_BRIGHTNESS not in params and self._brightness_dps:
  271. bright = params.get(ATTR_WHITE)
  272. r = self._brightness_dps.range(self._device)
  273. if r:
  274. bright = _ha_brightness_to_dp_value(bright, r)
  275. _LOGGER.info(
  276. "%s setting white brightness to %d", self._config.config_id, bright
  277. )
  278. settings = {
  279. **settings,
  280. **self._brightness_dps.get_values_to_set(
  281. self._device,
  282. bright,
  283. settings,
  284. ),
  285. }
  286. elif self._color_temp_dps and ATTR_COLOR_TEMP_KELVIN in params:
  287. if self.color_mode != ColorMode.COLOR_TEMP:
  288. color_mode = ColorMode.COLOR_TEMP
  289. color_temp = params.get(ATTR_COLOR_TEMP_KELVIN)
  290. # Light groups use the widest range from the lights in the
  291. # group, so we are expected to silently handle out of range values
  292. if color_temp < self.min_color_temp_kelvin:
  293. color_temp = self.min_color_temp_kelvin
  294. if color_temp > self.max_color_temp_kelvin:
  295. color_temp = self.max_color_temp_kelvin
  296. _LOGGER.info(
  297. "%s setting color temp to %d", self._config.config_id, color_temp
  298. )
  299. settings = {
  300. **settings,
  301. **self._color_temp_dps.get_values_to_set(
  302. self._device,
  303. color_temp,
  304. settings,
  305. ),
  306. }
  307. elif self._rgbhsv_dps and (
  308. ATTR_HS_COLOR in params
  309. or (ATTR_BRIGHTNESS in params and self._brightness_control_by_hsv())
  310. ):
  311. if self.color_mode != ColorMode.HS:
  312. color_mode = ColorMode.HS
  313. hs = params.get(ATTR_HS_COLOR, self.hs_color or (0, 0))
  314. brightness = params.get(ATTR_BRIGHTNESS, self.brightness or 255)
  315. fmt = self._rgbhsv_dps.format
  316. if hs and fmt:
  317. rgb = color_util.color_hsv_to_RGB(*hs, brightness / 2.55)
  318. rgbhsv = {
  319. "r": rgb[0],
  320. "g": rgb[1],
  321. "b": rgb[2],
  322. "h": hs[0],
  323. "s": hs[1],
  324. "v": brightness,
  325. }
  326. _LOGGER.debug(
  327. "Setting color as R:%d,G:%d,B:%d,H:%d,S:%d,V:%d",
  328. rgb[0],
  329. rgb[1],
  330. rgb[2],
  331. hs[0],
  332. hs[1],
  333. brightness,
  334. )
  335. current = self._unpacked_rgbhsv
  336. ordered = []
  337. idx = 0
  338. for n in fmt["names"]:
  339. if n in rgbhsv:
  340. r = fmt["ranges"][idx]
  341. scale = 1
  342. if n == "s":
  343. scale = r["max"] / 100
  344. elif n == "h":
  345. scale = r["max"] / 360
  346. else:
  347. scale = r["max"] / 255
  348. val = round(rgbhsv[n] * scale)
  349. if val < r["min"]:
  350. _LOGGER.warning(
  351. "%s/%s: Color data %s=%d constrained to be above %d",
  352. self._config._device.config,
  353. self.name or "light",
  354. n,
  355. val,
  356. r["min"],
  357. )
  358. val = r["min"]
  359. else:
  360. val = current[n]
  361. ordered.append(val)
  362. idx += 1
  363. binary = pack(fmt["format"], *ordered)
  364. encoded = self._rgbhsv_dps.encode_value(binary)
  365. _LOGGER.info("%s setting color to %s", self._config.config_id, encoded)
  366. settings = {
  367. **settings,
  368. **self._rgbhsv_dps.get_values_to_set(
  369. self._device,
  370. encoded,
  371. settings,
  372. ),
  373. }
  374. elif self._named_color_dps and ATTR_HS_COLOR in params:
  375. if self.color_mode != ColorMode.HS:
  376. color_mode = ColorMode.HS
  377. hs = params.get(ATTR_HS_COLOR, self.hs_color or (0, 0))
  378. brightness = params.get(ATTR_BRIGHTNESS, self.brightness or 255)
  379. best_match = self.named_color_from_hsv(hs, brightness)
  380. _LOGGER.debug("Setting color to %s", best_match)
  381. if best_match:
  382. _LOGGER.info(
  383. "%s setting named color to %s", self._config.config_id, best_match
  384. )
  385. settings = {
  386. **settings,
  387. **self._named_color_dps.get_values_to_set(
  388. self._device,
  389. best_match,
  390. settings,
  391. ),
  392. }
  393. if self._color_mode_dps:
  394. if color_mode:
  395. _LOGGER.info(
  396. "%s auto setting color mode to %s",
  397. self._config.config_id,
  398. color_mode,
  399. )
  400. settings = {
  401. **settings,
  402. **self._color_mode_dps.get_values_to_set(
  403. self._device,
  404. color_mode,
  405. settings,
  406. ),
  407. }
  408. elif not self._effect_dps:
  409. effect = params.get(ATTR_EFFECT)
  410. if effect and effect != self.effect:
  411. if effect == EFFECT_OFF:
  412. # Turn off the effect. Ideally this should keep the
  413. # previous mode, but since the mode is shared with
  414. # effect, use the default, or first in the list
  415. effect = (
  416. self._color_mode_dps.default
  417. or self._color_mode_dps.values(self._device)[0]
  418. )
  419. _LOGGER.info(
  420. "%s emulating effect using color mode of %s",
  421. self._config.config_id,
  422. effect,
  423. )
  424. settings = {
  425. **settings,
  426. **self._color_mode_dps.get_values_to_set(
  427. self._device,
  428. effect,
  429. settings,
  430. ),
  431. }
  432. if (
  433. ATTR_BRIGHTNESS in params
  434. and not self._brightness_control_by_hsv(color_mode)
  435. and self._brightness_dps
  436. ):
  437. bright = params.get(ATTR_BRIGHTNESS)
  438. r = self._brightness_dps.range(self._device)
  439. if r:
  440. bright = _ha_brightness_to_dp_value(bright, r)
  441. _LOGGER.info("%s setting brightness to %d", self._config.config_id, bright)
  442. settings = {
  443. **settings,
  444. **self._brightness_dps.get_values_to_set(
  445. self._device,
  446. bright,
  447. settings,
  448. ),
  449. }
  450. if self._effect_dps:
  451. effect = params.get(ATTR_EFFECT, None)
  452. if effect:
  453. _LOGGER.info("%s setting effect to %s", self._config.config_id, effect)
  454. settings = {
  455. **settings,
  456. **self._effect_dps.get_values_to_set(
  457. self._device,
  458. effect,
  459. settings,
  460. ),
  461. }
  462. # On packed dps where switch / brightness / effect all share the same
  463. # dp id (e.g. dp 51 with different masks), the original `id not in
  464. # settings` check incorrectly skipped the switch-on merge once any
  465. # other masked sub-field had populated settings. For masked dps it's
  466. # always safe to merge — get_values_to_set with pending_map=settings
  467. # will OR onto the existing pending value.
  468. if (
  469. self._switch_dps
  470. and not self._switch_dps.readonly
  471. and not self.is_on
  472. and (
  473. self._switch_dps.mask is not None or self._switch_dps.id not in settings
  474. )
  475. ):
  476. _LOGGER.info("%s turning light on", self._config.config_id)
  477. settings = settings | self._switch_dps.get_values_to_set(
  478. self._device, True, settings
  479. )
  480. elif (
  481. self._brightness_dps
  482. and not self.is_on
  483. and (
  484. self._brightness_dps.mask is not None
  485. or self._brightness_dps.id not in settings
  486. )
  487. ):
  488. bright = 255
  489. r = self._brightness_dps.range(self._device)
  490. if r:
  491. bright = color_util.brightness_to_value(r, bright)
  492. _LOGGER.info(
  493. "%s turning light on to brightness %d",
  494. self._config.config_id,
  495. bright,
  496. )
  497. settings = settings | self._brightness_dps.get_values_to_set(
  498. self._device, bright, settings
  499. )
  500. elif (
  501. self._effect_dps
  502. and not self.is_on
  503. and "off" in self._effect_dps.values(self._device)
  504. and (
  505. self._effect_dps.mask is not None or self._effect_dps.id not in settings
  506. )
  507. ):
  508. # Special case for lights with effect that has off state, but no switch or brightness
  509. on_value = self._effect_dps.default
  510. if on_value is None and "on" in self._effect_dps.values(self._device):
  511. on_value = "on"
  512. if on_value:
  513. _LOGGER.info(
  514. "%s turning light on using %s effect",
  515. self._config.config_id,
  516. on_value,
  517. )
  518. settings = settings | self._effect_dps.get_values_to_set(
  519. self._device, on_value, settings
  520. )
  521. if settings:
  522. await self._device.async_set_properties(settings)
  523. async def async_turn_off(self):
  524. await self._async_turn_off_locked()
  525. async def _async_turn_off_locked(self):
  526. if self._switch_dps and not self._switch_dps.readonly:
  527. _LOGGER.info("%s turning light off", self._config.config_id)
  528. await self._switch_dps.async_set_value(self._device, False)
  529. elif self._brightness_dps:
  530. _LOGGER.info(
  531. "%s turning light off by setting brightness to 0",
  532. self._config.config_id,
  533. )
  534. await self._brightness_dps.async_set_value(self._device, 0)
  535. elif self._effect_dps and "off" in self._effect_dps.values(self._device):
  536. # off by effect
  537. _LOGGER.info("%s turning light off using effect", self._config.config_id)
  538. await self._effect_dps.async_set_value(self._device, "off")
  539. else:
  540. raise NotImplementedError()