light.py 20 KB

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