light.py 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516
  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. _LOGGER.debug(
  257. "Setting brightness via WHITE parameter to %d",
  258. bright,
  259. )
  260. r = self._brightness_dps.range(self._device)
  261. if r:
  262. bright = color_util.brightness_to_value(r, bright)
  263. settings = {
  264. **settings,
  265. **self._brightness_dps.get_values_to_set(
  266. self._device,
  267. bright,
  268. ),
  269. }
  270. elif self._color_temp_dps and ATTR_COLOR_TEMP_KELVIN in params:
  271. if self.color_mode != ColorMode.COLOR_TEMP:
  272. color_mode = ColorMode.COLOR_TEMP
  273. color_temp = params.get(ATTR_COLOR_TEMP_KELVIN)
  274. # Light groups use the widest range from the lights in the
  275. # group, so we are expected to silently handle out of range values
  276. if color_temp < self.min_color_temp_kelvin:
  277. color_temp = self.min_color_temp_kelvin
  278. if color_temp > self.max_color_temp_kelvin:
  279. color_temp = self.max_color_temp_kelvin
  280. _LOGGER.debug("Setting color temp to %d", color_temp)
  281. settings = {
  282. **settings,
  283. **self._color_temp_dps.get_values_to_set(
  284. self._device,
  285. color_temp,
  286. ),
  287. }
  288. elif self._rgbhsv_dps and (
  289. ATTR_HS_COLOR in params
  290. or (ATTR_BRIGHTNESS in params and self._brightness_control_by_hsv())
  291. ):
  292. if self.color_mode != ColorMode.HS:
  293. color_mode = ColorMode.HS
  294. hs = params.get(ATTR_HS_COLOR, self.hs_color or (0, 0))
  295. brightness = params.get(ATTR_BRIGHTNESS, self.brightness or 255)
  296. fmt = self._rgbhsv_dps.format
  297. if hs and fmt:
  298. rgb = color_util.color_hsv_to_RGB(*hs, brightness / 2.55)
  299. rgbhsv = {
  300. "r": rgb[0],
  301. "g": rgb[1],
  302. "b": rgb[2],
  303. "h": hs[0],
  304. "s": hs[1],
  305. "v": brightness,
  306. }
  307. _LOGGER.debug(
  308. "Setting color as R:%d,G:%d,B:%d,H:%d,S:%d,V:%d",
  309. rgb[0],
  310. rgb[1],
  311. rgb[2],
  312. hs[0],
  313. hs[1],
  314. brightness,
  315. )
  316. current = self._unpacked_rgbhsv
  317. ordered = []
  318. idx = 0
  319. for n in fmt["names"]:
  320. if n in rgbhsv:
  321. r = fmt["ranges"][idx]
  322. scale = 1
  323. if n == "s":
  324. scale = r["max"] / 100
  325. elif n == "h":
  326. scale = r["max"] / 360
  327. else:
  328. scale = r["max"] / 255
  329. val = round(rgbhsv[n] * scale)
  330. if val < r["min"]:
  331. _LOGGER.warning(
  332. "%s/%s: Color data %s=%d constrained to be above %d",
  333. self._config._device.config,
  334. self.name or "light",
  335. n,
  336. val,
  337. r["min"],
  338. )
  339. val = r["min"]
  340. else:
  341. val = current[n]
  342. ordered.append(val)
  343. idx += 1
  344. binary = pack(fmt["format"], *ordered)
  345. settings = {
  346. **settings,
  347. **self._rgbhsv_dps.get_values_to_set(
  348. self._device,
  349. self._rgbhsv_dps.encode_value(binary),
  350. ),
  351. }
  352. elif self._named_color_dps and ATTR_HS_COLOR in params:
  353. if self.color_mode != ColorMode.HS:
  354. color_mode = ColorMode.HS
  355. hs = params.get(ATTR_HS_COLOR, self.hs_color or (0, 0))
  356. brightness = params.get(ATTR_BRIGHTNESS, self.brightness or 255)
  357. best_match = self.named_color_from_hsv(hs, brightness)
  358. _LOGGER.debug("Setting color to %s", best_match)
  359. if best_match:
  360. settings = {
  361. **settings,
  362. **self._named_color_dps.get_values_to_set(
  363. self._device,
  364. best_match,
  365. ),
  366. }
  367. if self._color_mode_dps:
  368. if color_mode:
  369. _LOGGER.debug("Auto setting color mode to %s", color_mode)
  370. settings = {
  371. **settings,
  372. **self._color_mode_dps.get_values_to_set(
  373. self._device,
  374. color_mode,
  375. ),
  376. }
  377. elif not self._effect_dps:
  378. effect = params.get(ATTR_EFFECT)
  379. if effect and effect != self.effect:
  380. if effect == EFFECT_OFF:
  381. # Turn off the effect. Ideally this should keep the
  382. # previous mode, but since the mode is shared with
  383. # effect, use the default, or first in the list
  384. effect = (
  385. self._color_mode_dps.default
  386. or self._color_mode_dps.values(self._device)[0]
  387. )
  388. _LOGGER.debug(
  389. "Emulating effect using color mode of %s",
  390. effect,
  391. )
  392. settings = {
  393. **settings,
  394. **self._color_mode_dps.get_values_to_set(
  395. self._device,
  396. effect,
  397. ),
  398. }
  399. if (
  400. ATTR_BRIGHTNESS in params
  401. and not self._brightness_control_by_hsv(color_mode)
  402. and self._brightness_dps
  403. ):
  404. bright = params.get(ATTR_BRIGHTNESS)
  405. _LOGGER.debug("Setting brightness to %s", bright)
  406. r = self._brightness_dps.range(self._device)
  407. if r:
  408. bright = color_util.brightness_to_value(r, bright)
  409. settings = {
  410. **settings,
  411. **self._brightness_dps.get_values_to_set(
  412. self._device,
  413. bright,
  414. ),
  415. }
  416. if self._effect_dps:
  417. effect = params.get(ATTR_EFFECT, None)
  418. if effect:
  419. _LOGGER.debug("Setting effect to %s", effect)
  420. settings = {
  421. **settings,
  422. **self._effect_dps.get_values_to_set(
  423. self._device,
  424. effect,
  425. ),
  426. }
  427. if self._switch_dps and not self.is_on:
  428. if (
  429. self._switch_dps.readonly
  430. and self._effect_dps
  431. and "on" in self._effect_dps.values(self._device)
  432. ):
  433. # Special case for motion sensor lights with readonly switch
  434. # that have tristate switch available as effect
  435. if self._effect_dps.id not in settings:
  436. settings = settings | self._effect_dps.get_values_to_set(
  437. self._device, "on"
  438. )
  439. else:
  440. settings = settings | self._switch_dps.get_values_to_set(
  441. self._device, True
  442. )
  443. elif self._brightness_dps and not self.is_on:
  444. bright = 255
  445. r = self._brightness_dps.range(self._device)
  446. if r:
  447. bright = color_util.brightness_to_value(r, bright)
  448. settings = settings | self._brightness_dps.get_values_to_set(
  449. self._device, bright
  450. )
  451. if settings:
  452. await self._device.async_set_properties(settings)
  453. async def async_turn_off(self):
  454. if self._switch_dps:
  455. if (
  456. self._switch_dps.readonly
  457. and self._effect_dps
  458. and "off" 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. await self._effect_dps.async_set_value(self._device, "off")
  463. else:
  464. await self._switch_dps.async_set_value(self._device, False)
  465. elif self._brightness_dps:
  466. await self._brightness_dps.async_set_value(self._device, 0)
  467. else:
  468. raise NotImplementedError()
  469. async def async_toggle(self):
  470. disp_on = self.is_on
  471. await (self.async_turn_on() if not disp_on else self.async_turn_off())