light.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413
  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. "Unrecognised color mode %s ignored",
  74. self.color_mode,
  75. )
  76. return []
  77. @property
  78. def supported_features(self):
  79. """Return the supported features for this light."""
  80. if self.effect_list:
  81. return LightEntityFeature.EFFECT
  82. else:
  83. return 0
  84. @property
  85. def color_mode(self):
  86. """Return the color mode of the light"""
  87. from_dp = self.raw_color_mode
  88. if from_dp:
  89. return from_dp
  90. if self._rgbhsv_dps:
  91. return ColorMode.HS
  92. elif self._color_temp_dps:
  93. return ColorMode.COLOR_TEMP
  94. elif self._brightness_dps:
  95. return ColorMode.BRIGHTNESS
  96. elif self._switch_dps:
  97. return ColorMode.ONOFF
  98. else:
  99. return ColorMode.UNKNOWN
  100. @property
  101. def raw_color_mode(self):
  102. """Return the color_mode as set from the dps."""
  103. if self._color_mode_dps:
  104. mode = self._color_mode_dps.get_value(self._device)
  105. if mode and hasattr(ColorMode, mode.upper()):
  106. return ColorMode(mode)
  107. @property
  108. def color_temp_kelvin(self):
  109. """Return the color temperature in kelvin."""
  110. if self._color_temp_dps:
  111. return self._color_temp_dps.get_value(self._device)
  112. @property
  113. def is_on(self):
  114. """Return the current state."""
  115. if self._switch_dps:
  116. return self._switch_dps.get_value(self._device)
  117. elif self._brightness_dps:
  118. b = self.brightness
  119. return isinstance(b, int) and b > 0
  120. else:
  121. # There shouldn't be lights without control, but if there are,
  122. # assume always on if they are responding
  123. return self.available
  124. @property
  125. def brightness(self):
  126. """Get the current brightness of the light"""
  127. if self.raw_color_mode == ColorMode.HS and self._rgbhsv_dps:
  128. return self._hsv_brightness
  129. return self._white_brightness
  130. @property
  131. def _white_brightness(self):
  132. if self._brightness_dps:
  133. return self._brightness_dps.get_value(self._device)
  134. @property
  135. def _unpacked_rgbhsv(self):
  136. """Get the unpacked rgbhsv data"""
  137. if self._rgbhsv_dps:
  138. color = self._rgbhsv_dps.decoded_value(self._device)
  139. fmt = self._rgbhsv_dps.format
  140. if fmt and color:
  141. vals = unpack(fmt.get("format"), color)
  142. idx = 0
  143. rgbhsv = {}
  144. for v in vals:
  145. # HA range: s = 0-100, rgbv = 0-255, h = 0-360
  146. n = fmt["names"][idx]
  147. r = fmt["ranges"][idx]
  148. mx = r["max"]
  149. scale = 1
  150. if n == "h":
  151. scale = 360 / mx
  152. elif n == "s":
  153. scale = 100 / mx
  154. else:
  155. scale = 255 / mx
  156. rgbhsv[n] = round(scale * v)
  157. idx += 1
  158. return rgbhsv
  159. @property
  160. def _hsv_brightness(self):
  161. """Get the colour mode brightness from the light"""
  162. rgbhsv = self._unpacked_rgbhsv
  163. if rgbhsv:
  164. return rgbhsv.get("v", self._white_brightness)
  165. return self._white_brightness
  166. @property
  167. def hs_color(self):
  168. """Get the current hs color of the light"""
  169. rgbhsv = self._unpacked_rgbhsv
  170. if rgbhsv:
  171. if "h" in rgbhsv and "s" in rgbhsv:
  172. hs = (rgbhsv["h"], rgbhsv["s"])
  173. else:
  174. r = rgbhsv.get("r")
  175. g = rgbhsv.get("g")
  176. b = rgbhsv.get("b")
  177. hs = color_util.color_RGB_to_hs(r, g, b)
  178. return hs
  179. @property
  180. def effect_list(self):
  181. """Return the list of valid effects for the light"""
  182. if self._effect_dps:
  183. return self._effect_dps.values(self._device)
  184. elif self._color_mode_dps:
  185. return [
  186. effect
  187. for effect in self._color_mode_dps.values(self._device)
  188. if effect and not hasattr(ColorMode, effect.upper())
  189. ]
  190. @property
  191. def effect(self):
  192. """Return the current effect setting of this light"""
  193. if self._effect_dps:
  194. return self._effect_dps.get_value(self._device)
  195. elif self._color_mode_dps:
  196. mode = self._color_mode_dps.get_value(self._device)
  197. if mode and not hasattr(ColorMode, mode.upper()):
  198. return mode
  199. async def async_turn_on(self, **params):
  200. settings = {}
  201. color_mode = None
  202. if self._color_mode_dps and ATTR_WHITE in params:
  203. if self.color_mode != ColorMode.WHITE:
  204. color_mode = ColorMode.WHITE
  205. if ATTR_BRIGHTNESS not in params and self._brightness_dps:
  206. bright = params.get(ATTR_WHITE)
  207. _LOGGER.debug(
  208. "Setting brightness via WHITE parameter to %d",
  209. bright,
  210. )
  211. settings = {
  212. **settings,
  213. **self._brightness_dps.get_values_to_set(
  214. self._device,
  215. bright,
  216. ),
  217. }
  218. elif self._color_temp_dps and ATTR_COLOR_TEMP_KELVIN in params:
  219. if self.color_mode != ColorMode.COLOR_TEMP:
  220. color_mode = ColorMode.COLOR_TEMP
  221. color_temp = params.get(ATTR_COLOR_TEMP_KELVIN)
  222. _LOGGER.debug("Setting color temp to %d", color_temp)
  223. settings = {
  224. **settings,
  225. **self._color_temp_dps.get_values_to_set(
  226. self._device,
  227. color_temp,
  228. ),
  229. }
  230. elif self._rgbhsv_dps and (
  231. ATTR_HS_COLOR in params
  232. or (ATTR_BRIGHTNESS in params and self.raw_color_mode == ColorMode.HS)
  233. ):
  234. if self.raw_color_mode != ColorMode.HS:
  235. color_mode = ColorMode.HS
  236. hs = params.get(ATTR_HS_COLOR, self.hs_color or (0, 0))
  237. brightness = params.get(ATTR_BRIGHTNESS, self.brightness or 255)
  238. fmt = self._rgbhsv_dps.format
  239. if hs and fmt:
  240. rgb = color_util.color_hsv_to_RGB(*hs, brightness / 2.55)
  241. rgbhsv = {
  242. "r": rgb[0],
  243. "g": rgb[1],
  244. "b": rgb[2],
  245. "h": hs[0],
  246. "s": hs[1],
  247. "v": brightness,
  248. }
  249. _LOGGER.debug(
  250. "Setting color as R:%d,G:%d,B:%d,H:%d,S:%d,V:%d",
  251. rgb[0],
  252. rgb[1],
  253. rgb[2],
  254. hs[0],
  255. hs[1],
  256. brightness,
  257. )
  258. ordered = []
  259. idx = 0
  260. for n in fmt["names"]:
  261. r = fmt["ranges"][idx]
  262. scale = 1
  263. if n == "s":
  264. scale = r["max"] / 100
  265. elif n == "h":
  266. scale = r["max"] / 360
  267. else:
  268. scale = r["max"] / 255
  269. val = round(rgbhsv[n] * scale)
  270. if val < r["min"]:
  271. _LOGGER.warning(
  272. "Color data %s=%d constrained to be above %d",
  273. n,
  274. val,
  275. r["min"],
  276. )
  277. val = r["min"]
  278. ordered.append(val)
  279. idx += 1
  280. binary = pack(fmt["format"], *ordered)
  281. settings = {
  282. **settings,
  283. **self._rgbhsv_dps.get_values_to_set(
  284. self._device,
  285. self._rgbhsv_dps.encode_value(binary),
  286. ),
  287. }
  288. if self._color_mode_dps:
  289. if color_mode:
  290. _LOGGER.debug("Auto setting color mode to %s", color_mode)
  291. settings = {
  292. **settings,
  293. **self._color_mode_dps.get_values_to_set(
  294. self._device,
  295. color_mode,
  296. ),
  297. }
  298. elif not self._effect_dps:
  299. effect = params.get(ATTR_EFFECT)
  300. if effect:
  301. _LOGGER.debug(
  302. "Emulating effect using color mode of %s",
  303. effect,
  304. )
  305. settings = {
  306. **settings,
  307. **self._color_mode_dps.get_values_to_set(
  308. self._device,
  309. effect,
  310. ),
  311. }
  312. if (
  313. ATTR_BRIGHTNESS in params
  314. and self.raw_color_mode != ColorMode.HS
  315. and self._brightness_dps
  316. ):
  317. bright = params.get(ATTR_BRIGHTNESS)
  318. _LOGGER.debug("Setting brightness to %s", bright)
  319. settings = {
  320. **settings,
  321. **self._brightness_dps.get_values_to_set(
  322. self._device,
  323. bright,
  324. ),
  325. }
  326. if self._effect_dps:
  327. effect = params.get(ATTR_EFFECT, None)
  328. if effect:
  329. _LOGGER.debug("Setting effect to %s", effect)
  330. settings = {
  331. **settings,
  332. **self._effect_dps.get_values_to_set(
  333. self._device,
  334. effect,
  335. ),
  336. }
  337. if self._switch_dps and not self.is_on:
  338. if (
  339. self._switch_dps.readonly
  340. and self._effect_dps
  341. and "on" in self._effect_dps.values(self._device)
  342. ):
  343. # Special case for motion sensor lights with readonly switch
  344. # that have tristate switch available as effect
  345. if self._effect_dps.id not in settings:
  346. settings = settings | self._effect_dps.get_values_to_set(
  347. self._device, "on"
  348. )
  349. else:
  350. settings = settings | self._switch_dps.get_values_to_set(
  351. self._device, True
  352. )
  353. elif self._brightness_dps and not self.is_on:
  354. settings = settings | self._brightness_dps.get_values_to_set(
  355. self._device, 255
  356. )
  357. if settings:
  358. await self._device.async_set_properties(settings)
  359. async def async_turn_off(self):
  360. if self._switch_dps:
  361. if (
  362. self._switch_dps.readonly
  363. and self._effect_dps
  364. and "off" in self._effect_dps.values(self._device)
  365. ):
  366. # Special case for motion sensor lights with readonly switch
  367. # that have tristate switch available as effect
  368. await self._effect_dps.async_set_value(self._device, "off")
  369. else:
  370. await self._switch_dps.async_set_value(self._device, False)
  371. elif self._brightness_dps:
  372. await self._brightness_dps.async_set_value(self._device, 0)
  373. else:
  374. raise NotImplementedError()
  375. async def async_toggle(self):
  376. disp_on = self.is_on
  377. await (self.async_turn_on() if not disp_on else self.async_turn_off())