light.py 15 KB

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