4
0

light.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375
  1. """
  2. Setup for different kinds of Tuya light devices
  3. """
  4. from homeassistant.components.light import (
  5. ATTR_BRIGHTNESS,
  6. ATTR_COLOR_MODE,
  7. ATTR_COLOR_TEMP,
  8. ATTR_EFFECT,
  9. ATTR_RGBW_COLOR,
  10. ATTR_WHITE,
  11. ColorMode,
  12. LightEntity,
  13. LightEntityFeature,
  14. )
  15. import homeassistant.util.color as color_util
  16. import logging
  17. from struct import pack, unpack
  18. from .device import TuyaLocalDevice
  19. from .helpers.config import async_tuya_setup_platform
  20. from .helpers.device_config import TuyaEntityConfig
  21. from .helpers.mixin import TuyaLocalEntity
  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. 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. @property
  50. def supported_color_modes(self):
  51. """Return the supported color modes for this light."""
  52. if self._color_mode_dps:
  53. return [
  54. ColorMode(mode)
  55. for mode in self._color_mode_dps.values(self._device)
  56. if mode and hasattr(ColorMode, mode.upper())
  57. ]
  58. else:
  59. try:
  60. mode = ColorMode(self.color_mode)
  61. if mode and mode != ColorMode.UNKNOWN:
  62. return [mode]
  63. except ValueError:
  64. _LOGGER.warning(f"Unrecognised color mode {self.color_mode} ignored")
  65. return []
  66. @property
  67. def supported_features(self):
  68. """Return the supported features for this light."""
  69. if self.effect_list:
  70. return LightEntityFeature.EFFECT
  71. else:
  72. return 0
  73. @property
  74. def color_mode(self):
  75. """Return the color mode of the light"""
  76. from_dp = self.raw_color_mode
  77. if from_dp:
  78. return from_dp
  79. if self._rgbhsv_dps:
  80. return ColorMode.RGBW
  81. elif self._color_temp_dps:
  82. return ColorMode.COLOR_TEMP
  83. elif self._brightness_dps:
  84. return ColorMode.BRIGHTNESS
  85. elif self._switch_dps:
  86. return ColorMode.ONOFF
  87. else:
  88. return ColorMode.UNKNOWN
  89. @property
  90. def raw_color_mode(self):
  91. """Return the color_mode as set from the dps."""
  92. if self._color_mode_dps:
  93. mode = self._color_mode_dps.get_value(self._device)
  94. if mode and hasattr(ColorMode, mode.upper()):
  95. return ColorMode(mode)
  96. @property
  97. def color_temp(self):
  98. """Return the color temperature in mireds"""
  99. if self._color_temp_dps:
  100. unscaled = self._color_temp_dps.get_value(self._device)
  101. r = self._color_temp_dps.range(self._device)
  102. if r and isinstance(unscaled, (int, float)):
  103. return round(unscaled * 347 / (r["max"] - r["min"]) + 153 - r["min"])
  104. else:
  105. return unscaled
  106. @property
  107. def is_on(self):
  108. """Return the current state."""
  109. if self._switch_dps:
  110. return self._switch_dps.get_value(self._device)
  111. elif self._brightness_dps:
  112. b = self.brightness
  113. return isinstance(b, int) and b > 0
  114. else:
  115. # There shouldn't be lights without control, but if there are,
  116. # assume always on if they are responding
  117. return self.available
  118. @property
  119. def brightness(self):
  120. """Get the current brightness of the light"""
  121. if self._brightness_dps:
  122. return self._brightness_dps.get_value(self._device)
  123. @property
  124. def rgbw_color(self):
  125. """Get the current RGBW color of the light"""
  126. if self._rgbhsv_dps:
  127. # color data in hex format RRGGBBHHHHSSVV (14 digit hex)
  128. # can also be base64 encoded.
  129. # Either RGB or HSV can be used.
  130. color = self._rgbhsv_dps.decoded_value(self._device)
  131. fmt = self._rgbhsv_dps.format
  132. if fmt and color:
  133. vals = unpack(fmt.get("format"), color)
  134. rgbhsv = {}
  135. idx = 0
  136. for v in vals:
  137. # Range in HA is 0-100 for s, 0-255 for rgb and v, 0-360
  138. # for h
  139. n = fmt["names"][idx]
  140. r = fmt["ranges"][idx]
  141. if r["min"] != 0:
  142. raise AttributeError(
  143. f"Unhandled minimum range for {n} in RGBW value"
  144. )
  145. mx = r["max"]
  146. scale = 1
  147. if n == "h":
  148. scale = 360 / mx
  149. elif n == "s":
  150. scale = 100 / mx
  151. else:
  152. scale = 255 / mx
  153. rgbhsv[n] = round(scale * v)
  154. idx += 1
  155. if "h" in rgbhsv and "s" in rgbhsv and "v" in rgbhsv:
  156. h = rgbhsv["h"]
  157. s = rgbhsv["s"]
  158. # convert RGB from H and S to seperate out the V component
  159. r, g, b = color_util.color_hs_to_RGB(h, s)
  160. w = rgbhsv["v"]
  161. else:
  162. r = rgbhsv.get("r")
  163. g = rgbhsv.get("g")
  164. b = rgbhsv.get("b")
  165. w = self.brightness
  166. return (r, g, b, w)
  167. @property
  168. def effect_list(self):
  169. """Return the list of valid effects for the light"""
  170. if self._effect_dps:
  171. return self._effect_dps.values(self._device)
  172. elif self._color_mode_dps:
  173. return [
  174. effect
  175. for effect in self._color_mode_dps.values(self._device)
  176. if effect and not hasattr(ColorMode, effect.upper())
  177. ]
  178. @property
  179. def effect(self):
  180. """Return the current effect setting of this light"""
  181. if self._effect_dps:
  182. return self._effect_dps.get_value(self._device)
  183. elif self._color_mode_dps:
  184. mode = self._color_mode_dps.get_value(self._device)
  185. if mode and not hasattr(ColorMode, mode.upper()):
  186. return mode
  187. async def async_turn_on(self, **params):
  188. settings = {}
  189. color_mode = None
  190. if self._color_mode_dps and ATTR_WHITE in params:
  191. if self.color_mode != ColorMode.WHITE:
  192. color_mode = ColorMode.WHITE
  193. if ATTR_BRIGHTNESS not in params and self._brightness_dps:
  194. bright = params.get(ATTR_WHITE)
  195. _LOGGER.debug(f"Setting brightness via WHITE parameter to {bright}")
  196. settings = {
  197. **settings,
  198. **self._brightness_dps.get_values_to_set(
  199. self._device,
  200. bright,
  201. ),
  202. }
  203. elif self._color_temp_dps and ATTR_COLOR_TEMP in params:
  204. if self.color_mode != ColorMode.COLOR_TEMP:
  205. color_mode = ColorMode.COLOR_TEMP
  206. color_temp = params.get(ATTR_COLOR_TEMP)
  207. r = self._color_temp_dps.range(self._device)
  208. if r and color_temp:
  209. color_temp = round(
  210. (color_temp - 153 + r["min"]) * (r["max"] - r["min"]) / 347
  211. )
  212. _LOGGER.debug(f"Setting color temp to {color_temp}")
  213. settings = {
  214. **settings,
  215. **self._color_temp_dps.get_values_to_set(self._device, color_temp),
  216. }
  217. elif self._rgbhsv_dps and (
  218. ATTR_RGBW_COLOR in params
  219. or (ATTR_BRIGHTNESS in params and self.raw_color_mode == ColorMode.RGBW)
  220. ):
  221. if self.raw_color_mode != ColorMode.RGBW:
  222. color_mode = ColorMode.RGBW
  223. rgbw = params.get(ATTR_RGBW_COLOR, self.rgbw_color or (0, 0, 0, 0))
  224. brightness = params.get(ATTR_BRIGHTNESS, self.brightness or 255)
  225. fmt = self._rgbhsv_dps.format
  226. if rgbw and fmt:
  227. rgb = (rgbw[0], rgbw[1], rgbw[2])
  228. hs = color_util.color_RGB_to_hs(rgbw[0], rgbw[1], rgbw[2])
  229. rgbhsv = {
  230. "r": rgb[0],
  231. "g": rgb[1],
  232. "b": rgb[2],
  233. "h": hs[0],
  234. "s": hs[1],
  235. "v": brightness,
  236. }
  237. _LOGGER.debug(
  238. f"Setting RGBW as {rgb[0]},{rgb[1]},{rgb[2]},{hs[0]},{hs[1]},{brightness}"
  239. )
  240. ordered = []
  241. idx = 0
  242. for n in fmt["names"]:
  243. r = fmt["ranges"][idx]
  244. scale = 1
  245. if n == "s":
  246. scale = r["max"] / 100
  247. elif n == "h":
  248. scale = r["max"] / 360
  249. else:
  250. scale = r["max"] / 255
  251. ordered.append(round(rgbhsv[n] * scale))
  252. idx += 1
  253. binary = pack(fmt["format"], *ordered)
  254. settings = {
  255. **settings,
  256. **self._rgbhsv_dps.get_values_to_set(
  257. self._device,
  258. self._rgbhsv_dps.encode_value(binary),
  259. ),
  260. }
  261. if self._color_mode_dps:
  262. if color_mode:
  263. _LOGGER.debug(f"Auto setting color mode to {color_mode}")
  264. settings = {
  265. **settings,
  266. **self._color_mode_dps.get_values_to_set(self._device, color_mode),
  267. }
  268. elif not self._effect_dps:
  269. effect = params.get(ATTR_EFFECT)
  270. if effect:
  271. _LOGGER.debug(f"Emulating effect using color mode of {effect}")
  272. settings = {
  273. **settings,
  274. **self._color_mode_dps.get_values_to_set(
  275. self._device,
  276. effect,
  277. ),
  278. }
  279. if (
  280. ATTR_BRIGHTNESS in params
  281. and self.raw_color_mode != ColorMode.RGBW
  282. and self._brightness_dps
  283. ):
  284. bright = params.get(ATTR_BRIGHTNESS)
  285. _LOGGER.debug(f"Setting brightness to {bright}")
  286. settings = {
  287. **settings,
  288. **self._brightness_dps.get_values_to_set(
  289. self._device,
  290. bright,
  291. ),
  292. }
  293. if self._effect_dps:
  294. effect = params.get(ATTR_EFFECT, None)
  295. if effect:
  296. _LOGGER.debug(f"Setting effect to {effect}")
  297. settings = {
  298. **settings,
  299. **self._effect_dps.get_values_to_set(
  300. self._device,
  301. effect,
  302. ),
  303. }
  304. if self._switch_dps and not self.is_on:
  305. if (
  306. self._switch_dps.readonly
  307. and self._effect_dps
  308. and "on" in self._effect_dps.values(self._device)
  309. ):
  310. # Special case for motion sensor lights with readonly switch
  311. # that have tristate switch available as effect
  312. if self._effect_dps.id not in settings:
  313. settings = settings | self._effect_dps.get_values_to_set(
  314. self._device, "on"
  315. )
  316. else:
  317. settings = settings | self._switch_dps.get_values_to_set(
  318. self._device, True
  319. )
  320. if settings:
  321. await self._device.async_set_properties(settings)
  322. async def async_turn_off(self):
  323. if self._switch_dps:
  324. if (
  325. self._switch_dps.readonly
  326. and self._effect_dps
  327. and "off" in self._effect_dps.values(self._device)
  328. ):
  329. # Special case for motion sensor lights with readonly switch
  330. # that have tristate switch available as effect
  331. await self._effect_dps.async_set_value(self._device, "off")
  332. else:
  333. await self._switch_dps.async_set_value(self._device, False)
  334. elif self._brightness_dps:
  335. await self._brightness_dps.async_set_value(self._device, 0)
  336. else:
  337. raise NotImplementedError()
  338. async def async_toggle(self):
  339. disp_on = self.is_on
  340. await (self.async_turn_on() if not disp_on else self.async_turn_off())