From d7e9409156fb7e5ad72f5c3aef2228ac9861468a Mon Sep 17 00:00:00 2001 From: Eric Bell Date: Sun, 22 Nov 2026 09:41:06 -0500 Subject: [PATCH] after turn 1 --- .../components/template/light.py | 451 ++++++++---------- 1 file changed, 197 insertions(+), 254 deletions(-) diff --git a/home-assistant/homeassistant/components/template/light.py b/home-assistant/homeassistant/components/template/light.py index 9391e368..6b2a7c93 100644 --- a/home-assistant/homeassistant/components/template/light.py +++ b/home-assistant/homeassistant/components/template/light.py @@ -2,6 +2,8 @@ from __future__ import annotations +from collections.abc import Callable +from dataclasses import dataclass import logging from typing import Any @@ -40,6 +42,7 @@ from homeassistant.helpers import config_validation as cv from homeassistant.helpers.entity import async_generate_entity_id from homeassistant.helpers.entity_platform import AddEntitiesCallback from homeassistant.helpers.script import Script +from homeassistant.helpers.template import Template from homeassistant.helpers.typing import ConfigType, DiscoveryInfoType from homeassistant.util import color as color_util @@ -157,6 +160,35 @@ async def async_setup_platform( async_add_entities(await _async_create_entities(hass, config)) +@dataclass(slots=True) +class ColorModeHandler: + """Describe how one color mode of a template light is configured and wired. + + A handler exists for every color mode that has a script or a template + configured. A mode is supported only when it has a script; a mode is + optimistic only when it has no template. + """ + + color_mode: ColorMode + # LightEntity property exposing the value. It is also the turn_on kwarg + # carrying the value, e.g. "rgb_color" (ATTR_RGB_COLOR). + property_name: str + # Entity attribute holding the current value, e.g. "_rgb_color". + state_attr: str + # Script variable receiving the whole value, e.g. "rgb". + script_attr: str + script: Script | None + template: Template | None + # Parses a template render and stores the result in state_attr. + update_callback: Callable[[Any], None] + # Script variables receiving each component of the value as int, + # e.g. ("r", "g", "b"). + component_names: tuple[str, ...] = () + # Converts the turn_on kwarg into the stored/script value, + # e.g. Kelvin to mireds for color temperature. + value_converter: Callable[[Any], Any] | None = None + + class LightTemplate(TemplateEntity, LightEntity): """Representation of a templated Light, including dimmable.""" @@ -184,32 +216,6 @@ class LightTemplate(TemplateEntity, LightEntity): if (level_action := config.get(CONF_LEVEL_ACTION)) is not None: self._level_script = Script(hass, level_action, friendly_name, DOMAIN) self._level_template = config.get(CONF_LEVEL_TEMPLATE) - self._temperature_script = None - if (temperature_action := config.get(CONF_TEMPERATURE_ACTION)) is not None: - self._temperature_script = Script( - hass, temperature_action, friendly_name, DOMAIN - ) - self._temperature_template = config.get(CONF_TEMPERATURE_TEMPLATE) - self._color_script = None - if (color_action := config.get(CONF_COLOR_ACTION)) is not None: - self._color_script = Script(hass, color_action, friendly_name, DOMAIN) - self._color_template = config.get(CONF_COLOR_TEMPLATE) - self._hs_script = None - if (hs_action := config.get(CONF_HS_ACTION)) is not None: - self._hs_script = Script(hass, hs_action, friendly_name, DOMAIN) - self._hs_template = config.get(CONF_HS_TEMPLATE) - self._rgb_script = None - if (rgb_action := config.get(CONF_RGB_ACTION)) is not None: - self._rgb_script = Script(hass, rgb_action, friendly_name, DOMAIN) - self._rgb_template = config.get(CONF_RGB_TEMPLATE) - self._rgbw_script = None - if (rgbw_action := config.get(CONF_RGBW_ACTION)) is not None: - self._rgbw_script = Script(hass, rgbw_action, friendly_name, DOMAIN) - self._rgbw_template = config.get(CONF_RGBW_TEMPLATE) - self._rgbww_script = None - if (rgbww_action := config.get(CONF_RGBWW_ACTION)) is not None: - self._rgbww_script = Script(hass, rgbww_action, friendly_name, DOMAIN) - self._rgbww_template = config.get(CONF_RGBWW_TEMPLATE) self._effect_script = None if (effect_action := config.get(CONF_EFFECT_ACTION)) is not None: self._effect_script = Script(hass, effect_action, friendly_name, DOMAIN) @@ -232,29 +238,16 @@ class LightTemplate(TemplateEntity, LightEntity): self._max_mireds = None self._min_mireds = None self._supports_transition = False - self._supported_color_modes = None - color_modes = {ColorMode.ONOFF} - if self._level_script is not None: - color_modes.add(ColorMode.BRIGHTNESS) - if self._temperature_script is not None: - color_modes.add(ColorMode.COLOR_TEMP) - if self._hs_script is not None: - color_modes.add(ColorMode.HS) - if self._color_script is not None: - color_modes.add(ColorMode.HS) - if self._rgb_script is not None: - color_modes.add(ColorMode.RGB) - if self._rgbw_script is not None: - color_modes.add(ColorMode.RGBW) - if self._rgbww_script is not None: - color_modes.add(ColorMode.RGBWW) + self._color_mode_handlers = self._create_color_mode_handlers( + hass, config, friendly_name + ) - self._supported_color_modes = filter_supported_color_modes(color_modes) - if len(self._supported_color_modes) > 1: + supported_color_modes = self.supported_color_modes + if len(supported_color_modes) > 1: self._color_mode = ColorMode.UNKNOWN - if len(self._supported_color_modes) == 1: - self._color_mode = next(iter(self._supported_color_modes)) + if len(supported_color_modes) == 1: + self._color_mode = next(iter(supported_color_modes)) self._attr_supported_features = LightEntityFeature(0) if self._effect_script is not None: @@ -262,6 +255,89 @@ class LightTemplate(TemplateEntity, LightEntity): if self._supports_transition is True: self._attr_supported_features |= LightEntityFeature.TRANSITION + def _create_color_mode_handlers( + self, hass: HomeAssistant, config: ConfigType, friendly_name: str + ) -> list[ColorModeHandler]: + """Create a handler for each color mode with a script or template. + + The list order matches the legacy template registration order, so the + color mode set by the last rendered template is unchanged. turn_on + receives at most one color attribute per call, so the order does not + change which script runs. + """ + + def script(*action_keys: str) -> Script | None: + for key in action_keys: + if (action := config.get(key)) is not None: + return Script(hass, action, friendly_name, DOMAIN) + return None + + def template(*template_keys: str) -> Template | None: + for key in template_keys: + if (value := config.get(key)) is not None: + return value + return None + + candidates = [ + ColorModeHandler( + color_mode=ColorMode.COLOR_TEMP, + property_name=ATTR_COLOR_TEMP_KELVIN, + state_attr="_temperature", + script_attr="color_temp", + script=script(CONF_TEMPERATURE_ACTION), + template=template(CONF_TEMPERATURE_TEMPLATE), + update_callback=self._update_temperature, + value_converter=color_util.color_temperature_kelvin_to_mired, + ), + # The legacy set_color/color_template keys are exclusive with + # set_hs/hs_template and share the HS color mode. + ColorModeHandler( + color_mode=ColorMode.HS, + property_name=ATTR_HS_COLOR, + state_attr="_hs_color", + script_attr="hs", + script=script(CONF_COLOR_ACTION, CONF_HS_ACTION), + template=template(CONF_COLOR_TEMPLATE, CONF_HS_TEMPLATE), + update_callback=self._update_hs, + component_names=("h", "s"), + ), + ColorModeHandler( + color_mode=ColorMode.RGB, + property_name=ATTR_RGB_COLOR, + state_attr="_rgb_color", + script_attr="rgb", + script=script(CONF_RGB_ACTION), + template=template(CONF_RGB_TEMPLATE), + update_callback=self._update_rgb, + component_names=("r", "g", "b"), + ), + ColorModeHandler( + color_mode=ColorMode.RGBW, + property_name=ATTR_RGBW_COLOR, + state_attr="_rgbw_color", + script_attr="rgbw", + script=script(CONF_RGBW_ACTION), + template=template(CONF_RGBW_TEMPLATE), + update_callback=self._update_rgbw, + component_names=("r", "g", "b", "w"), + ), + ColorModeHandler( + color_mode=ColorMode.RGBWW, + property_name=ATTR_RGBWW_COLOR, + state_attr="_rgbww_color", + script_attr="rgbww", + script=script(CONF_RGBWW_ACTION), + template=template(CONF_RGBWW_TEMPLATE), + update_callback=self._update_rgbww, + component_names=("r", "g", "b", "cw", "ww"), + ), + ] + return [ + handler + for handler in candidates + if handler.script is not None or handler.template is not None + ] + @property def brightness(self) -> int | None: """Return the brightness of the light.""" @@ -326,9 +402,17 @@ class LightTemplate(TemplateEntity, LightEntity): return self._color_mode @property - def supported_color_modes(self): - """Flag supported color modes.""" - return self._supported_color_modes + def supported_color_modes(self) -> set[ColorMode]: + """Flag supported color modes, derived from the configured scripts.""" + color_modes = {ColorMode.ONOFF} + if self._level_script is not None: + color_modes.add(ColorMode.BRIGHTNESS) + color_modes.update( + handler.color_mode + for handler in self._color_mode_handlers + if handler.script is not None + ) + return filter_supported_color_modes(color_modes) @property def is_on(self) -> bool | None: @@ -366,54 +450,15 @@ class LightTemplate(TemplateEntity, LightEntity): self._update_min_mireds, none_on_template_error=True, ) - if self._temperature_template: - self.add_template_attribute( - "_temperature", - self._temperature_template, - None, - self._update_temperature, - none_on_template_error=True, - ) - if self._color_template: - self.add_template_attribute( - "_hs_color", - self._color_template, - None, - self._update_hs, - none_on_template_error=True, - ) - if self._hs_template: - self.add_template_attribute( - "_hs_color", - self._hs_template, - None, - self._update_hs, - none_on_template_error=True, - ) - if self._rgb_template: - self.add_template_attribute( - "_rgb_color", - self._rgb_template, - None, - self._update_rgb, - none_on_template_error=True, - ) - if self._rgbw_template: - self.add_template_attribute( - "_rgbw_color", - self._rgbw_template, - None, - self._update_rgbw, - none_on_template_error=True, - ) - if self._rgbww_template: - self.add_template_attribute( - "_rgbww_color", - self._rgbww_template, - None, - self._update_rgbww, - none_on_template_error=True, - ) + for handler in self._color_mode_handlers: + if handler.template: + self.add_template_attribute( + handler.state_attr, + handler.template, + None, + handler.update_callback, + none_on_template_error=True, + ) if self._effect_list_template: self.add_template_attribute( "_effect_list", @@ -455,96 +500,17 @@ class LightTemplate(TemplateEntity, LightEntity): self._brightness = kwargs[ATTR_BRIGHTNESS] optimistic_set = True - if self._temperature_template is None and ATTR_COLOR_TEMP_KELVIN in kwargs: - color_temp = color_util.color_temperature_kelvin_to_mired( - kwargs[ATTR_COLOR_TEMP_KELVIN] - ) - _LOGGER.debug( - "Optimistically setting color temperature to %s", - color_temp, - ) - self._color_mode = ColorMode.COLOR_TEMP - self._temperature = color_temp - if self._hs_template is None and self._color_template is None: - self._hs_color = None - if self._rgb_template is None: - self._rgb_color = None - if self._rgbw_template is None: - self._rgbw_color = None - if self._rgbww_template is None: - self._rgbww_color = None - optimistic_set = True - - if ( - self._hs_template is None - and self._color_template is None - and ATTR_HS_COLOR in kwargs - ): - _LOGGER.debug( - "Optimistically setting hs color to %s", - kwargs[ATTR_HS_COLOR], - ) - self._color_mode = ColorMode.HS - self._hs_color = kwargs[ATTR_HS_COLOR] - if self._temperature_template is None: - self._temperature = None - if self._rgb_template is None: - self._rgb_color = None - if self._rgbw_template is None: - self._rgbw_color = None - if self._rgbww_template is None: - self._rgbww_color = None - optimistic_set = True - - if self._rgb_template is None and ATTR_RGB_COLOR in kwargs: - _LOGGER.debug( - "Optimistically setting rgb color to %s", - kwargs[ATTR_RGB_COLOR], - ) - self._color_mode = ColorMode.RGB - self._rgb_color = kwargs[ATTR_RGB_COLOR] - if self._temperature_template is None: - self._temperature = None - if self._hs_template is None and self._color_template is None: - self._hs_color = None - if self._rgbw_template is None: - self._rgbw_color = None - if self._rgbww_template is None: - self._rgbww_color = None - optimistic_set = True - - if self._rgbw_template is None and ATTR_RGBW_COLOR in kwargs: - _LOGGER.debug( - "Optimistically setting rgbw color to %s", - kwargs[ATTR_RGBW_COLOR], - ) - self._color_mode = ColorMode.RGBW - self._rgbw_color = kwargs[ATTR_RGBW_COLOR] - if self._temperature_template is None: - self._temperature = None - if self._hs_template is None and self._color_template is None: - self._hs_color = None - if self._rgb_template is None: - self._rgb_color = None - if self._rgbww_template is None: - self._rgbww_color = None - optimistic_set = True - - if self._rgbww_template is None and ATTR_RGBWW_COLOR in kwargs: - _LOGGER.debug( - "Optimistically setting rgbww color to %s", - kwargs[ATTR_RGBWW_COLOR], - ) - self._color_mode = ColorMode.RGBWW - self._rgbww_color = kwargs[ATTR_RGBWW_COLOR] - if self._temperature_template is None: - self._temperature = None - if self._hs_template is None and self._color_template is None: - self._hs_color = None - if self._rgb_template is None: - self._rgb_color = None - if self._rgbw_template is None: - self._rgbw_color = None + for handler in self._color_mode_handlers: + if handler.template is not None or handler.property_name not in kwargs: + continue + value = self._service_value(handler, kwargs) + _LOGGER.debug("Optimistically setting %s to %s", handler.script_attr, value) + self._color_mode = handler.color_mode + setattr(self, handler.state_attr, value) + # Colors of other optimistic modes no longer apply + for other in self._color_mode_handlers: + if other is not handler and other.template is None: + setattr(self, other.state_attr, None) optimistic_set = True common_params = {} @@ -555,17 +521,31 @@ class LightTemplate(TemplateEntity, LightEntity): if ATTR_TRANSITION in kwargs and self._supports_transition is True: common_params["transition"] = kwargs[ATTR_TRANSITION] - if ATTR_COLOR_TEMP_KELVIN in kwargs and self._temperature_script: - common_params["color_temp"] = color_util.color_temperature_kelvin_to_mired( - kwargs[ATTR_COLOR_TEMP_KELVIN] - ) + effect_requested = ATTR_EFFECT in kwargs and self._effect_script is not None + color_handler = next( + ( + handler + for handler in self._color_mode_handlers + if handler.script is not None and handler.property_name in kwargs + ), + None, + ) + # Script precedence: color temperature, effect, other colors, level, on + if color_handler is not None and ( + color_handler.color_mode == ColorMode.COLOR_TEMP or not effect_requested + ): + common_params.update( + self._script_variables( + color_handler, self._service_value(color_handler, kwargs) + ) + ) await self.async_run_script( - self._temperature_script, + color_handler.script, run_variables=common_params, context=self._context, ) - elif ATTR_EFFECT in kwargs and self._effect_script: + elif effect_requested: effect = kwargs[ATTR_EFFECT] if effect not in self._effect_list: _LOGGER.error( @@ -581,67 +561,6 @@ class LightTemplate(TemplateEntity, LightEntity): await self.async_run_script( self._effect_script, run_variables=common_params, context=self._context ) - elif ATTR_HS_COLOR in kwargs and self._color_script: - hs_value = kwargs[ATTR_HS_COLOR] - common_params["hs"] = hs_value - common_params["h"] = int(hs_value[0]) - common_params["s"] = int(hs_value[1]) - - await self.async_run_script( - self._color_script, run_variables=common_params, context=self._context - ) - elif ATTR_HS_COLOR in kwargs and self._hs_script: - hs_value = kwargs[ATTR_HS_COLOR] - common_params["hs"] = hs_value - common_params["h"] = int(hs_value[0]) - common_params["s"] = int(hs_value[1]) - - await self.async_run_script( - self._hs_script, run_variables=common_params, context=self._context - ) - elif ATTR_RGBWW_COLOR in kwargs and self._rgbww_script: - rgbww_value = kwargs[ATTR_RGBWW_COLOR] - common_params["rgbww"] = rgbww_value - common_params["rgb"] = ( - int(rgbww_value[0]), - int(rgbww_value[1]), - int(rgbww_value[2]), - ) - common_params["r"] = int(rgbww_value[0]) - common_params["g"] = int(rgbww_value[1]) - common_params["b"] = int(rgbww_value[2]) - common_params["cw"] = int(rgbww_value[3]) - common_params["ww"] = int(rgbww_value[4]) - - await self.async_run_script( - self._rgbww_script, run_variables=common_params, context=self._context - ) - elif ATTR_RGBW_COLOR in kwargs and self._rgbw_script: - rgbw_value = kwargs[ATTR_RGBW_COLOR] - common_params["rgbw"] = rgbw_value - common_params["rgb"] = ( - int(rgbw_value[0]), - int(rgbw_value[1]), - int(rgbw_value[2]), - ) - common_params["r"] = int(rgbw_value[0]) - common_params["g"] = int(rgbw_value[1]) - common_params["b"] = int(rgbw_value[2]) - common_params["w"] = int(rgbw_value[3]) - - await self.async_run_script( - self._rgbw_script, run_variables=common_params, context=self._context - ) - elif ATTR_RGB_COLOR in kwargs and self._rgb_script: - rgb_value = kwargs[ATTR_RGB_COLOR] - common_params["rgb"] = rgb_value - common_params["r"] = int(rgb_value[0]) - common_params["g"] = int(rgb_value[1]) - common_params["b"] = int(rgb_value[2]) - - await self.async_run_script( - self._rgb_script, run_variables=common_params, context=self._context - ) elif ATTR_BRIGHTNESS in kwargs and self._level_script: await self.async_run_script( self._level_script, run_variables=common_params, context=self._context @@ -654,6 +573,30 @@ class LightTemplate(TemplateEntity, LightEntity): if optimistic_set: self.async_write_ha_state() + @staticmethod + def _service_value(handler: ColorModeHandler, kwargs: dict[str, Any]) -> Any: + """Return the turn_on value for a color mode, converted for storage.""" + value = kwargs[handler.property_name] + if handler.value_converter is not None: + return handler.value_converter(value) + return value + + @staticmethod + def _script_variables(handler: ColorModeHandler, value: Any) -> dict[str, Any]: + """Return the script variables for a color mode value.""" + variables: dict[str, Any] = {handler.script_attr: value} + if not handler.component_names: + return variables + components = [int(component) for component in value] + variables.update(zip(handler.component_names, components, strict=False)) + # RGBW and RGBWW scripts also receive the plain RGB part + if ( + handler.component_names[:3] == ("r", "g", "b") + and handler.script_attr != "rgb" + ): + variables["rgb"] = tuple(components[:3]) + return variables + async def async_turn_off(self, **kwargs: Any) -> None: """Turn the light off.""" if ATTR_TRANSITION in kwargs and self._supports_transition is True: