From 6e07a5581f5950901a862832d8d83e8cec1ee74a Mon Sep 17 00:00:00 2001 From: ultratoto14 Date: Mon, 9 Nov 2020 11:07:55 +0100 Subject: [PATCH] First try to add scenes. --- README.md | 34 ++-- custom_components/localtuya/const.py | 3 + custom_components/localtuya/light.py | 176 +++++++++++++++--- .../localtuya/translations/en.json | 8 +- 4 files changed, 174 insertions(+), 47 deletions(-) diff --git a/README.md b/README.md index e9087b18b..273a86469 100644 --- a/README.md +++ b/README.md @@ -12,7 +12,7 @@ The following Tuya device types are currently supported: * Fans * Climates (soon) -Energy monitoring (voltage, current, watts, etc.) is supported for compatible devices. +Energy monitoring (voltage, current, watts, etc.) is supported for compatible devices. This repository's development has substantially started by utilizing and merging code from NameLessJedi, mileperhour and TradeFace, and then was deeply refactored to provide proper integration with Home Assistant environment, adding config flow and other features. Refer to the "Thanks to" section below. @@ -56,7 +56,7 @@ localtuya: currpos_dps: 3 # Optional, required only for "position" mode setpos_dps: 4 # Optional, required only for "position" mode span_time: 25 # Full movement time: Optional, required only for "fake" mode - + - platform: fan friendly_name: Device Fan id: 3 @@ -67,11 +67,13 @@ localtuya: color_mode: 21 # Optional, usually 2 or 21, default: "none" brightness: 22 # Optional, usually 3 or 22, default: "none" color_temp: 23 # Optional, usually 4 or 23, default: "none" - color: 24 # Optional, usually 5 (RGB_HSV) or 24(HSV), default: "none" + color: 24 # Optional, usually 5 (RGB_HSV) or 24 (HSV), default: "none" brightness_lower: 29 # Optional, usually 0 or 29, default: 29 brightness_upper: 1000 # Optional, usually 255 or 1000, default: 1000 color_temp_min_kelvin: 2700 # Optional, default: 2700 color_temp_max_kelvin: 6500 # Optional, default: 6500 + scene: 25 # Optional, usually 6 (RGB_HSV) or 25 (HSV), default: "none" + music_mode: False # Optional, some use internal mic, others, phone mic. Only internal mic is supported, default: "False" - platform: sensor @@ -88,7 +90,7 @@ localtuya: current_consumption: 19 # Optional voltage: 20 # Optional ``` - + Note that a single device can contain several different entities. Some examples: - a cover device might have 1 (or many) cover entities, plus a switch to control backlight - a multi-gang switch will contain several switch entities, one for each gang controlled @@ -98,12 +100,12 @@ Restart Home Assistant when finished editing. # 2. Using config flow Start by going to Configuration - Integration and pressing the "+" button to create a new Integration, then select LocalTuya in the drop-down menu. -Wait for 6 seconds for the scanning of the devices in your LAN. Then, a drop-down menu will appear containing the list of detectes devices: you can +Wait for 6 seconds for the scanning of the devices in your LAN. Then, a drop-down menu will appear containing the list of detectes devices: you can select one of these, or manually input all the parameters. ![discovery](https://github.com/rospogrigio/localtuya-homeassistant/blob/master/img/1-discovery.png) -If you have selected one entry, you just have to input the Friendly Name of the Device, and the localKey. +If you have selected one entry, you just have to input the Friendly Name of the Device, and the localKey. Once you press "Submit", the connection will be tested to check that everything works, in order to proceed. ![device](https://github.com/rospogrigio/localtuya-homeassistant/blob/master/img/2-device.png) @@ -113,8 +115,8 @@ After you have defined all the needed entities leave the "Do not add more entiti ![entity_type](https://github.com/rospogrigio/localtuya-homeassistant/blob/master/img/3-entity_type.png) -For each entity, the associated DP has to be selected. All the options requiring to select a DP will provide a drop-down menu showing -all the avaliable DPs found on the device (with their current status!!) for an easy identification. Each entity type has different options +For each entity, the associated DP has to be selected. All the options requiring to select a DP will provide a drop-down menu showing +all the avaliable DPs found on the device (with their current status!!) for an easy identification. Each entity type has different options to be configured, here is an example for the "switch" entity: ![entity](https://github.com/rospogrigio/localtuya-homeassistant/blob/master/img/4-entity.png) @@ -130,23 +132,23 @@ Energy monitoring (voltage, current...) values can be obtained in two different 1) creating individual sensors, each one with the desired name. Note: Voltage and Consumption usually include the first decimal, so 0.1 as "scaling" parameter shall be used in order to get the correct values. 2) accessing the voltage/current/current_consumption attributes of a switch, and then defining template sensors like this (please note that in this case the values are already divided by 10 for Voltage and Consumption): -``` +``` sensor: - platform: template sensors: tuya-sw01_voltage: value_template: >- {{ states.switch.sw01.attributes.voltage }} - unit_of_measurement: 'V' + unit_of_measurement: 'V' tuya-sw01_current: - value_template: >- + value_template: >- {{ states.switch.sw01.attributes.current }} - unit_of_measurement: 'mA' + unit_of_measurement: 'mA' tuya-sw01_current_consumption: value_template: >- {{ states.switch.sw01.attributes.current_consumption }} - unit_of_measurement: 'W' -``` + unit_of_measurement: 'W' +``` # Debugging @@ -165,9 +167,9 @@ logger: # To-do list: -* Create a (good and precise) sensor (counter) for Energy (kWh) -not just Power, but based on it-. +* Create a (good and precise) sensor (counter) for Energy (kWh) -not just Power, but based on it-. Ideas: Use: https://www.home-assistant.io/components/integration/ and https://www.home-assistant.io/components/utility_meter/ - + * Everything listed in https://github.com/rospogrigio/localtuya-homeassistant/issues/15 # Thanks to: diff --git a/custom_components/localtuya/const.py b/custom_components/localtuya/const.py index 942d42fb9..943356640 100644 --- a/custom_components/localtuya/const.py +++ b/custom_components/localtuya/const.py @@ -15,6 +15,9 @@ CONF_COLOR_MODE = "color_mode" CONF_COLOR_TEMP_MIN_KELVIN = "color_temp_min_kelvin" CONF_COLOR_TEMP_MAX_KELVIN = "color_temp_max_kelvin" +CONF_SCENES = "scenes" +CONF_SCENE_DATA = "scene_data" +CONF_MUSIC_MODE = "music_mode" # switch CONF_CURRENT = "current" diff --git a/custom_components/localtuya/light.py b/custom_components/localtuya/light.py index 96bc5bad9..ab7b8f7e0 100644 --- a/custom_components/localtuya/light.py +++ b/custom_components/localtuya/light.py @@ -4,18 +4,25 @@ from functools import partial import homeassistant.util.color as color_util + import voluptuous as vol from homeassistant.components.light import ( ATTR_BRIGHTNESS, ATTR_COLOR_TEMP, + ATTR_EFFECT, ATTR_HS_COLOR, DOMAIN, SUPPORT_BRIGHTNESS, SUPPORT_COLOR, SUPPORT_COLOR_TEMP, + SUPPORT_EFFECT, LightEntity, ) -from homeassistant.const import CONF_BRIGHTNESS, CONF_COLOR_TEMP +from homeassistant.const import ( + CONF_BRIGHTNESS, + CONF_COLOR_TEMP, + CONF_SCENE, +) from .common import LocalTuyaEntity, async_setup_entry from .const import ( @@ -25,6 +32,7 @@ CONF_COLOR_MODE, CONF_COLOR_TEMP_MAX_KELVIN, CONF_COLOR_TEMP_MIN_KELVIN, + CONF_MUSIC_MODE, ) _LOGGER = logging.getLogger(__name__) @@ -36,6 +44,40 @@ DEFAULT_LOWER_BRIGHTNESS = 29 DEFAULT_UPPER_BRIGHTNESS = 1000 +WHITE_MODE = "white" +COLOR_MODE = "colour" +SCENE_MODE = "scene" +MUSIC_MODE = "music" +CUSTOM_SCENE = "Custom" + +MUSIC_SCENE = "Music" + +SCENE_LIST_1 = { + "Night": "000e0d0000000000000000c80000", + "Read": "010e0d0000000000000003e801f4", + "Meeting": "020e0d0000000000000003e803e8", + "Leasure": "030e0d0000000000000001f401f4", + "Soft": "04464602007803e803e800000000464602007803e8000a00000000", + "Rainbow": "05464601000003e803e800000000464601007803e803e80000000046460100f003e803" + + "e800000000", + "Shine": "06464601000003e803e800000000464601007803e803e80000000046460100f003e803e8" + + "00000000", + "Beautiful": "07464602000003e803e800000000464602007803e803e80000000046460200f003e8" + + "03e800000000464602003d03e803e80000000046460200ae03e803e800000000464602011303e80" + + "3e800000000", +} + +SCENE_LIST_2 = { + "Night": "bd76000168ffff", + "Read": "fffcf70168ffff", + "Meeting": "cf38000168ffff", + "Leasure": "3855b40168ffff", + "Scenario 1": "scene_1", + "Scenario 2": "scene_2", + "Scenario 3": "scene_3", + "Scenario 4": "scene_4", +} + def map_range(value, from_lower, from_upper, to_lower, to_upper): """Map a value in one range to another.""" @@ -64,6 +106,10 @@ def flow_schema(dps): vol.Optional(CONF_COLOR_TEMP_MAX_KELVIN, default=DEFAULT_MAX_KELVIN): vol.All( vol.Coerce(int), vol.Range(min=1500, max=8000) ), + vol.Optional(CONF_SCENE): vol.In(dps), + vol.Optional( + CONF_MUSIC_MODE, default=False, description={"suggested_value": False} + ): bool, } @@ -97,8 +143,18 @@ def __init__( MIRED_TO_KELVIN_CONST / self._config.get(CONF_COLOR_TEMP_MAX_KELVIN, DEFAULT_MAX_KELVIN) ) - self._is_white_mode = True # Hopefully sane default self._hs = None + self._effect = None + self._effect_list = [] + self._scenes = None + if self._config.get(CONF_SCENE) is not None: + self._scenes = ( + SCENE_LIST_1 if self._config.get(CONF_SCENE) > 20 else SCENE_LIST_2 + ) + for scene in self._scenes: + self._effect_list.append(scene) + if self._config.get(CONF_MUSIC_MODE): + self._effect_list.append(MUSIC_SCENE) @property def is_on(self): @@ -108,21 +164,23 @@ def is_on(self): @property def brightness(self): """Return the brightness of the light.""" - return map_range( - self._brightness, self._lower_brightness, self._upper_brightness, 0, 255 - ) + if self.__is_color_mode() or self.__is_white_mode(): + return map_range( + self._brightness, self._lower_brightness, self._upper_brightness, 0, 255 + ) + return None @property def hs_color(self): """Return the hs color value.""" - if self._is_white_mode: - return None - return self._hs + if self.__is_color_mode(): + return self._hs + return None @property def color_temp(self): """Return the color_temp of the light.""" - if self.has_config(CONF_COLOR_TEMP) and self._is_white_mode: + if self.has_config(CONF_COLOR_TEMP) and self.__is_white_mode(): return int( self._max_mired - ( @@ -142,6 +200,18 @@ def max_mireds(self): """Return color temperature max mireds.""" return self._max_mired + @property + def effect(self): + """Return the current effect for this light.""" + if self.__is_scene_mode() or self.__is_music_mode(): + return self._effect + return None + + @property + def effect_list(self): + """Return the list of supported effects for this light.""" + return self._effect_list + @property def supported_features(self): """Flag supported features.""" @@ -152,16 +222,51 @@ def supported_features(self): supports |= SUPPORT_COLOR_TEMP if self.has_config(CONF_COLOR): supports |= SUPPORT_COLOR | SUPPORT_BRIGHTNESS + if self.has_config(CONF_SCENE) or self.has_config(CONF_MUSIC_MODE): + supports |= SUPPORT_EFFECT return supports def __is_color_rgb_encoded(self): return len(self.dps_conf(CONF_COLOR)) > 12 + def __is_white_mode(self): + color_mode = self.dps_conf(CONF_COLOR_MODE) + return color_mode is None or color_mode == WHITE_MODE + + def __is_color_mode(self): + color_mode = self.dps_conf(CONF_COLOR_MODE) + return color_mode is not None and color_mode == COLOR_MODE + + def __is_scene_mode(self): + color_mode = self.dps_conf(CONF_COLOR_MODE) + return color_mode is not None and color_mode.startswith(SCENE_MODE) + + def __is_music_mode(self): + color_mode = self.dps_conf(CONF_COLOR_MODE) + return color_mode is not None and color_mode == MUSIC_MODE + + def __find_scene_by_scene_data(self, data): + return next( + (item for item in self._scenes if self._scenes[item] == data), CUSTOM_SCENE + ) + async def async_turn_on(self, **kwargs): """Turn on or control the light.""" states = {} states[self._dp_id] = True features = self.supported_features + brightness = None + if ATTR_EFFECT in kwargs and (features & SUPPORT_EFFECT): + scene = self._scenes.get(kwargs[ATTR_EFFECT]) + if scene is not None: + if scene.startswith(SCENE_MODE): + states[self._config.get(CONF_COLOR_MODE)] = scene + else: + states[self._config.get(CONF_COLOR_MODE)] = SCENE_MODE + states[self._config.get(CONF_SCENE)] = scene + elif kwargs[ATTR_EFFECT] == MUSIC_SCENE: + states[self._config.get(CONF_COLOR_MODE)] = MUSIC_MODE + if ATTR_BRIGHTNESS in kwargs and (features & SUPPORT_BRIGHTNESS): brightness = map_range( int(kwargs[ATTR_BRIGHTNESS]), @@ -170,9 +275,8 @@ async def async_turn_on(self, **kwargs): self._lower_brightness, self._upper_brightness, ) - if self._is_white_mode: + if self.__is_white_mode(): states[self._config.get(CONF_BRIGHTNESS)] = brightness - else: if self.__is_color_rgb_encoded(): rgb = color_util.color_hsv_to_RGB( @@ -195,10 +299,12 @@ async def async_turn_on(self, **kwargs): states[self._config.get(CONF_COLOR)] = color if ATTR_HS_COLOR in kwargs and (features & SUPPORT_COLOR): + if brightness is None: + brightness = self._brightness hs = kwargs[ATTR_HS_COLOR] if self.__is_color_rgb_encoded(): rgb = color_util.color_hsv_to_RGB( - hs[0], hs[1], int(self._brightness * 100 / self._upper_brightness) + hs[0], hs[1], int(brightness * 100 / self._upper_brightness) ) color = "{:02x}{:02x}{:02x}{:04x}{:02x}{:02x}".format( round(rgb[0]), @@ -206,27 +312,26 @@ async def async_turn_on(self, **kwargs): round(rgb[2]), round(hs[0]), round(hs[1] * 255 / 100), - self._brightness, + brightness, ) else: color = "{:04x}{:04x}{:04x}".format( - round(hs[0]), round(hs[1] * 10.0), self._brightness + round(hs[0]), round(hs[1] * 10.0), brightness ) states[self._config.get(CONF_COLOR)] = color - if self._is_white_mode: - states[self._config.get(CONF_COLOR_MODE)] = "colour" + states[self._config.get(CONF_COLOR_MODE)] = COLOR_MODE if ATTR_COLOR_TEMP in kwargs and (features & SUPPORT_COLOR_TEMP): + if brightness is None: + brightness = self._brightness color_temp = int( self._upper_color_temp - (self._upper_color_temp / (self._max_mired - self._min_mired)) * (int(kwargs[ATTR_COLOR_TEMP]) - self._min_mired) ) - if not self._is_white_mode: - states[self._config.get(CONF_COLOR_MODE)] = "white" - states[self._config.get(CONF_BRIGHTNESS)] = self._brightness + states[self._config.get(CONF_COLOR_MODE)] = WHITE_MODE + states[self._config.get(CONF_BRIGHTNESS)] = brightness states[self._config.get(CONF_COLOR_TEMP)] = color_temp - await self._device.set_dps(states) async def async_turn_off(self, **kwargs): @@ -237,16 +342,11 @@ def status_updated(self): """Device status was updated.""" self._state = self.dps(self._dp_id) supported = self.supported_features + self._effect = None + if supported & SUPPORT_BRIGHTNESS: + self._brightness = self.dps_conf(CONF_BRIGHTNESS) - if supported & SUPPORT_COLOR: - self._is_white_mode = self.dps_conf(CONF_COLOR_MODE) == "white" - if self._is_white_mode: - self._hs = None - - if self._is_white_mode: - if supported & SUPPORT_BRIGHTNESS: - self._brightness = self.dps_conf(CONF_BRIGHTNESS) - else: + if self.__is_color_mode(): color = self.dps_conf(CONF_COLOR) if color is not None: if self.__is_color_rgb_encoded(): @@ -265,5 +365,23 @@ def status_updated(self): if supported & SUPPORT_COLOR_TEMP: self._color_temp = self.dps_conf(CONF_COLOR_TEMP) + if self.__is_scene_mode() and supported & SUPPORT_EFFECT: + if self.dps_conf(CONF_COLOR_MODE) != SCENE_MODE: + self._effect = self.__find_scene_by_scene_data( + self.dps_conf(CONF_COLOR_MODE) + ) + else: + self._effect = self.__find_scene_by_scene_data( + self.dps_conf(CONF_SCENE) + ) + if self._effect == CUSTOM_SCENE: + if CUSTOM_SCENE not in self._effect_list: + self._effect_list.append(CUSTOM_SCENE) + elif CUSTOM_SCENE in self._effect_list: + self._effect_list.remove(CUSTOM_SCENE) + + if self.__is_music_mode() and supported & SUPPORT_EFFECT: + self._effect = MUSIC_SCENE + async_setup_entry = partial(async_setup_entry, DOMAIN, LocaltuyaLight, flow_schema) diff --git a/custom_components/localtuya/translations/en.json b/custom_components/localtuya/translations/en.json index 9e87bf2dc..5012420b5 100644 --- a/custom_components/localtuya/translations/en.json +++ b/custom_components/localtuya/translations/en.json @@ -63,7 +63,9 @@ "color": "Color", "color_mode": "Color Mode", "color_temp_min_kelvin": "Minimum Color Temperature in K", - "color_temp_max_kelvin": "Maximum Color Temperature in K" + "color_temp_max_kelvin": "Maximum Color Temperature in K", + "music_mode": "Music mode available", + "scene": "Scene" } } } @@ -107,7 +109,9 @@ "color": "Color", "color_mode": "Color Mode", "color_temp_min_kelvin": "Minimum Color Temperature in K", - "color_temp_max_kelvin": "Maximum Color Temperature in K" + "color_temp_max_kelvin": "Maximum Color Temperature in K", + "music_mode": "Music mode available", + "scene": "Scene" } }, "yaml_import": {