Initial Visquitto MQTT release

This commit is contained in:
Saman Sajedi
2026-11-03 15:18:38 +03:30
commit 7bbb3e5dfd
66 changed files with 27673 additions and 0 deletions
+82
View File
@@ -0,0 +1,82 @@
"""Support for MQTT lights."""
from typing import Any
import probatio
from homeassistant.components import light
from homeassistant.config_entries import ConfigEntry
from homeassistant.core import HomeAssistant
from homeassistant.helpers.entity_platform import AddConfigEntryEntitiesCallback
from homeassistant.helpers.typing import ConfigType, VolSchemaType
from ..entity import async_setup_entity_entry_helper
from .schema import CONF_SCHEMA, MQTT_LIGHT_SCHEMA_SCHEMA
from .schema_basic import (
DISCOVERY_SCHEMA_BASIC,
PLATFORM_SCHEMA_MODERN_BASIC,
MqttLight,
)
from .schema_json import (
DISCOVERY_SCHEMA_JSON,
PLATFORM_SCHEMA_MODERN_JSON,
MqttLightJson,
)
from .schema_template import (
DISCOVERY_SCHEMA_TEMPLATE,
PLATFORM_SCHEMA_MODERN_TEMPLATE,
MqttLightTemplate,
)
PARALLEL_UPDATES = 0
def validate_mqtt_light_discovery(config_value: dict[str, Any]) -> ConfigType:
"""Validate MQTT light schema for discovery."""
schemas: dict[str, VolSchemaType] = {
"basic": DISCOVERY_SCHEMA_BASIC,
"json": DISCOVERY_SCHEMA_JSON,
"template": DISCOVERY_SCHEMA_TEMPLATE,
}
config: ConfigType = schemas[config_value[CONF_SCHEMA]](config_value)
return config
def validate_mqtt_light_modern(config_value: dict[str, Any]) -> ConfigType:
"""Validate MQTT light schema for setup from configuration.yaml."""
schemas: dict[str, VolSchemaType] = {
"basic": PLATFORM_SCHEMA_MODERN_BASIC,
"json": PLATFORM_SCHEMA_MODERN_JSON,
"template": PLATFORM_SCHEMA_MODERN_TEMPLATE,
}
config: ConfigType = schemas[config_value[CONF_SCHEMA]](config_value)
return config
DISCOVERY_SCHEMA = probatio.All(
MQTT_LIGHT_SCHEMA_SCHEMA.extend({}, extra=probatio.ALLOW_EXTRA),
validate_mqtt_light_discovery,
)
PLATFORM_SCHEMA_MODERN = probatio.All(
MQTT_LIGHT_SCHEMA_SCHEMA.extend({}, extra=probatio.ALLOW_EXTRA),
validate_mqtt_light_modern,
)
async def async_setup_entry(
hass: HomeAssistant,
config_entry: ConfigEntry,
async_add_entities: AddConfigEntryEntitiesCallback,
) -> None:
"""Set up MQTT lights through YAML and through MQTT discovery."""
async_setup_entity_entry_helper(
hass,
config_entry,
None,
light.DOMAIN,
async_add_entities,
DISCOVERY_SCHEMA,
PLATFORM_SCHEMA_MODERN,
{"basic": MqttLight, "json": MqttLightJson, "template": MqttLightTemplate},
)
+13
View File
@@ -0,0 +1,13 @@
"""Shared schema code."""
import probatio
from ..const import CONF_SCHEMA
MQTT_LIGHT_SCHEMA_SCHEMA = probatio.Schema(
{
probatio.Optional(CONF_SCHEMA, default="basic"): probatio.All(
probatio.Lower, probatio.Any("basic", "json", "template")
)
}
)
@@ -0,0 +1,889 @@
"""Support for MQTT lights."""
from collections.abc import Callable
import logging
from typing import Any, cast, override
import probatio
from homeassistant.components.light import (
ATTR_BRIGHTNESS,
ATTR_COLOR_MODE,
ATTR_COLOR_TEMP_KELVIN,
ATTR_EFFECT,
ATTR_HS_COLOR,
ATTR_RGB_COLOR,
ATTR_RGBW_COLOR,
ATTR_RGBWW_COLOR,
ATTR_WHITE,
ATTR_XY_COLOR,
DEFAULT_MAX_KELVIN,
DEFAULT_MIN_KELVIN,
ENTITY_ID_FORMAT,
ColorMode,
LightEntity,
LightEntityCapabilityAttribute,
LightEntityFeature,
LightEntityStateAttribute,
valid_supported_color_modes,
)
from homeassistant.const import (
CONF_NAME,
CONF_OPTIMISTIC,
CONF_PAYLOAD_OFF,
CONF_PAYLOAD_ON,
STATE_ON,
)
from homeassistant.core import callback
from homeassistant.helpers import config_validation as cv
from homeassistant.helpers.restore_state import RestoreEntity
from homeassistant.helpers.service_info.mqtt import ReceivePayloadType
from homeassistant.helpers.typing import ConfigType, VolSchemaType
from homeassistant.util import color as color_util
from .. import subscription
from ..config import MQTT_RW_SCHEMA
from ..const import (
CONF_BRIGHTNESS_COMMAND_TEMPLATE,
CONF_BRIGHTNESS_COMMAND_TOPIC,
CONF_BRIGHTNESS_SCALE,
CONF_BRIGHTNESS_STATE_TOPIC,
CONF_BRIGHTNESS_VALUE_TEMPLATE,
CONF_COLOR_MODE_STATE_TOPIC,
CONF_COLOR_MODE_VALUE_TEMPLATE,
CONF_COLOR_TEMP_COMMAND_TEMPLATE,
CONF_COLOR_TEMP_COMMAND_TOPIC,
CONF_COLOR_TEMP_KELVIN,
CONF_COLOR_TEMP_STATE_TOPIC,
CONF_COLOR_TEMP_VALUE_TEMPLATE,
CONF_COMMAND_TOPIC,
CONF_EFFECT_COMMAND_TEMPLATE,
CONF_EFFECT_COMMAND_TOPIC,
CONF_EFFECT_LIST,
CONF_EFFECT_STATE_TOPIC,
CONF_EFFECT_VALUE_TEMPLATE,
CONF_HS_COMMAND_TEMPLATE,
CONF_HS_COMMAND_TOPIC,
CONF_HS_STATE_TOPIC,
CONF_HS_VALUE_TEMPLATE,
CONF_MAX_KELVIN,
CONF_MAX_MIREDS,
CONF_MIN_KELVIN,
CONF_MIN_MIREDS,
CONF_ON_COMMAND_TYPE,
CONF_RGB_COMMAND_TEMPLATE,
CONF_RGB_COMMAND_TOPIC,
CONF_RGB_STATE_TOPIC,
CONF_RGB_VALUE_TEMPLATE,
CONF_RGBW_COMMAND_TEMPLATE,
CONF_RGBW_COMMAND_TOPIC,
CONF_RGBW_STATE_TOPIC,
CONF_RGBW_VALUE_TEMPLATE,
CONF_RGBWW_COMMAND_TEMPLATE,
CONF_RGBWW_COMMAND_TOPIC,
CONF_RGBWW_STATE_TOPIC,
CONF_RGBWW_VALUE_TEMPLATE,
CONF_STATE_TOPIC,
CONF_STATE_VALUE_TEMPLATE,
CONF_WHITE_COMMAND_TOPIC,
CONF_WHITE_SCALE,
CONF_XY_COMMAND_TEMPLATE,
CONF_XY_COMMAND_TOPIC,
CONF_XY_STATE_TOPIC,
CONF_XY_VALUE_TEMPLATE,
DEFAULT_BRIGHTNESS_SCALE,
DEFAULT_ON_COMMAND_TYPE,
DEFAULT_PAYLOAD_OFF,
DEFAULT_PAYLOAD_ON,
DEFAULT_WHITE_SCALE,
PAYLOAD_NONE,
VALUES_ON_COMMAND_TYPE,
)
from ..entity import MqttEntity
from ..models import (
MqttCommandTemplate,
MqttValueTemplate,
PayloadSentinel,
PublishPayloadType,
ReceiveMessage,
TemplateVarsType,
)
from ..schemas import MQTT_ENTITY_COMMON_SCHEMA
from ..util import valid_publish_topic, valid_subscribe_topic
from .schema import MQTT_LIGHT_SCHEMA_SCHEMA
_LOGGER = logging.getLogger(__name__)
DEFAULT_NAME = "MQTT LightEntity"
MQTT_LIGHT_ATTRIBUTES_BLOCKED = frozenset(
{
LightEntityCapabilityAttribute.EFFECT_LIST,
LightEntityCapabilityAttribute.MAX_COLOR_TEMP_KELVIN,
LightEntityCapabilityAttribute.MIN_COLOR_TEMP_KELVIN,
LightEntityCapabilityAttribute.SUPPORTED_COLOR_MODES,
LightEntityStateAttribute.BRIGHTNESS,
LightEntityStateAttribute.COLOR_MODE,
LightEntityStateAttribute.COLOR_TEMP_KELVIN,
LightEntityStateAttribute.EFFECT,
LightEntityStateAttribute.HS_COLOR,
LightEntityStateAttribute.RGB_COLOR,
LightEntityStateAttribute.RGBW_COLOR,
LightEntityStateAttribute.RGBWW_COLOR,
LightEntityStateAttribute.XY_COLOR,
}
)
COMMAND_TEMPLATE_KEYS = [
CONF_BRIGHTNESS_COMMAND_TEMPLATE,
CONF_COLOR_TEMP_COMMAND_TEMPLATE,
CONF_EFFECT_COMMAND_TEMPLATE,
CONF_HS_COMMAND_TEMPLATE,
CONF_RGB_COMMAND_TEMPLATE,
CONF_RGBW_COMMAND_TEMPLATE,
CONF_RGBWW_COMMAND_TEMPLATE,
CONF_XY_COMMAND_TEMPLATE,
]
VALUE_TEMPLATE_KEYS = [
CONF_BRIGHTNESS_VALUE_TEMPLATE,
CONF_COLOR_MODE_VALUE_TEMPLATE,
CONF_COLOR_TEMP_VALUE_TEMPLATE,
CONF_EFFECT_VALUE_TEMPLATE,
CONF_HS_VALUE_TEMPLATE,
CONF_RGB_VALUE_TEMPLATE,
CONF_RGBW_VALUE_TEMPLATE,
CONF_RGBWW_VALUE_TEMPLATE,
CONF_STATE_VALUE_TEMPLATE,
CONF_XY_VALUE_TEMPLATE,
]
PLATFORM_SCHEMA_MODERN_BASIC = (
MQTT_RW_SCHEMA.extend(
{
probatio.Optional(CONF_BRIGHTNESS_COMMAND_TEMPLATE): cv.template,
probatio.Optional(CONF_BRIGHTNESS_COMMAND_TOPIC): valid_publish_topic,
probatio.Optional(
CONF_BRIGHTNESS_SCALE, default=DEFAULT_BRIGHTNESS_SCALE
): probatio.All(probatio.Coerce(int), probatio.Range(min=1)),
probatio.Optional(CONF_BRIGHTNESS_STATE_TOPIC): valid_subscribe_topic,
probatio.Optional(CONF_BRIGHTNESS_VALUE_TEMPLATE): cv.template,
probatio.Optional(CONF_COLOR_MODE_STATE_TOPIC): valid_subscribe_topic,
probatio.Optional(CONF_COLOR_MODE_VALUE_TEMPLATE): cv.template,
probatio.Optional(CONF_COLOR_TEMP_COMMAND_TEMPLATE): cv.template,
probatio.Optional(CONF_COLOR_TEMP_COMMAND_TOPIC): valid_publish_topic,
probatio.Optional(CONF_COLOR_TEMP_STATE_TOPIC): valid_subscribe_topic,
probatio.Optional(CONF_COLOR_TEMP_VALUE_TEMPLATE): cv.template,
probatio.Optional(CONF_COLOR_TEMP_KELVIN, default=False): cv.boolean,
probatio.Optional(CONF_EFFECT_COMMAND_TEMPLATE): cv.template,
probatio.Optional(CONF_EFFECT_COMMAND_TOPIC): valid_publish_topic,
probatio.Optional(CONF_EFFECT_LIST): probatio.All(
probatio.EnsureList(), [cv.string]
),
probatio.Optional(CONF_EFFECT_STATE_TOPIC): valid_subscribe_topic,
probatio.Optional(CONF_EFFECT_VALUE_TEMPLATE): cv.template,
probatio.Optional(CONF_HS_COMMAND_TEMPLATE): cv.template,
probatio.Optional(CONF_HS_COMMAND_TOPIC): valid_publish_topic,
probatio.Optional(CONF_HS_STATE_TOPIC): valid_subscribe_topic,
probatio.Optional(CONF_HS_VALUE_TEMPLATE): cv.template,
probatio.Optional(CONF_MAX_MIREDS): cv.positive_int,
probatio.Optional(CONF_MIN_MIREDS): cv.positive_int,
probatio.Optional(CONF_MAX_KELVIN): cv.positive_int,
probatio.Optional(CONF_MIN_KELVIN): cv.positive_int,
probatio.Optional(CONF_NAME): probatio.Any(cv.string, None),
probatio.Optional(
CONF_ON_COMMAND_TYPE, default=DEFAULT_ON_COMMAND_TYPE
): probatio.In(VALUES_ON_COMMAND_TYPE),
probatio.Optional(CONF_PAYLOAD_OFF, default=DEFAULT_PAYLOAD_OFF): cv.string,
probatio.Optional(CONF_PAYLOAD_ON, default=DEFAULT_PAYLOAD_ON): cv.string,
probatio.Optional(CONF_RGB_COMMAND_TEMPLATE): cv.template,
probatio.Optional(CONF_RGB_COMMAND_TOPIC): valid_publish_topic,
probatio.Optional(CONF_RGB_STATE_TOPIC): valid_subscribe_topic,
probatio.Optional(CONF_RGB_VALUE_TEMPLATE): cv.template,
probatio.Optional(CONF_RGBW_COMMAND_TEMPLATE): cv.template,
probatio.Optional(CONF_RGBW_COMMAND_TOPIC): valid_publish_topic,
probatio.Optional(CONF_RGBW_STATE_TOPIC): valid_subscribe_topic,
probatio.Optional(CONF_RGBW_VALUE_TEMPLATE): cv.template,
probatio.Optional(CONF_RGBWW_COMMAND_TEMPLATE): cv.template,
probatio.Optional(CONF_RGBWW_COMMAND_TOPIC): valid_publish_topic,
probatio.Optional(CONF_RGBWW_STATE_TOPIC): valid_subscribe_topic,
probatio.Optional(CONF_RGBWW_VALUE_TEMPLATE): cv.template,
probatio.Optional(CONF_STATE_VALUE_TEMPLATE): cv.template,
probatio.Optional(CONF_WHITE_COMMAND_TOPIC): valid_publish_topic,
probatio.Optional(
CONF_WHITE_SCALE, default=DEFAULT_WHITE_SCALE
): probatio.All(probatio.Coerce(int), probatio.Range(min=1)),
probatio.Optional(CONF_XY_COMMAND_TEMPLATE): cv.template,
probatio.Optional(CONF_XY_COMMAND_TOPIC): valid_publish_topic,
probatio.Optional(CONF_XY_STATE_TOPIC): valid_subscribe_topic,
probatio.Optional(CONF_XY_VALUE_TEMPLATE): cv.template,
},
)
.extend(MQTT_ENTITY_COMMON_SCHEMA.schema)
.extend(MQTT_LIGHT_SCHEMA_SCHEMA.schema)
)
DISCOVERY_SCHEMA_BASIC = probatio.All(
PLATFORM_SCHEMA_MODERN_BASIC.extend({}, extra=probatio.REMOVE_EXTRA),
)
class MqttLight(MqttEntity, LightEntity, RestoreEntity):
"""Representation of a MQTT light."""
_default_name = DEFAULT_NAME
_entity_id_format = ENTITY_ID_FORMAT
_attributes_extra_blocked = MQTT_LIGHT_ATTRIBUTES_BLOCKED
_topic: dict[str, str | None]
_payload: dict[str, str]
_color_temp_kelvin: bool
_command_templates: dict[
str, Callable[[PublishPayloadType, TemplateVarsType], PublishPayloadType]
]
_value_templates: dict[
str, Callable[[ReceivePayloadType, ReceivePayloadType], ReceivePayloadType]
]
_optimistic: bool
_optimistic_brightness: bool
_optimistic_color_mode: bool
_optimistic_color_temp_kelvin: bool
_optimistic_effect: bool
_optimistic_hs_color: bool
_optimistic_rgb_color: bool
_optimistic_rgbw_color: bool
_optimistic_rgbww_color: bool
_optimistic_xy_color: bool
@staticmethod
@override
def config_schema() -> VolSchemaType:
"""Return the config schema."""
return DISCOVERY_SCHEMA_BASIC
@override
def _setup_from_config(self, config: ConfigType) -> None:
"""(Re)Setup the entity."""
self._color_temp_kelvin = config[CONF_COLOR_TEMP_KELVIN]
self._attr_min_color_temp_kelvin = (
color_util.color_temperature_mired_to_kelvin(max_mireds)
if (max_mireds := config.get(CONF_MAX_MIREDS))
else config.get(CONF_MIN_KELVIN, DEFAULT_MIN_KELVIN)
)
self._attr_max_color_temp_kelvin = (
color_util.color_temperature_mired_to_kelvin(min_mireds)
if (min_mireds := config.get(CONF_MIN_MIREDS))
else config.get(CONF_MAX_KELVIN, DEFAULT_MAX_KELVIN)
)
self._attr_effect_list = config.get(CONF_EFFECT_LIST)
topic: dict[str, str | None] = {
key: config.get(key)
for key in (
CONF_BRIGHTNESS_COMMAND_TOPIC,
CONF_BRIGHTNESS_STATE_TOPIC,
CONF_COLOR_MODE_STATE_TOPIC,
CONF_COLOR_TEMP_COMMAND_TOPIC,
CONF_COLOR_TEMP_STATE_TOPIC,
CONF_COMMAND_TOPIC,
CONF_EFFECT_COMMAND_TOPIC,
CONF_EFFECT_STATE_TOPIC,
CONF_HS_COMMAND_TOPIC,
CONF_HS_STATE_TOPIC,
CONF_RGB_COMMAND_TOPIC,
CONF_RGB_STATE_TOPIC,
CONF_RGBW_COMMAND_TOPIC,
CONF_RGBW_STATE_TOPIC,
CONF_RGBWW_COMMAND_TOPIC,
CONF_RGBWW_STATE_TOPIC,
CONF_STATE_TOPIC,
CONF_WHITE_COMMAND_TOPIC,
CONF_XY_COMMAND_TOPIC,
CONF_XY_STATE_TOPIC,
)
}
self._topic = topic
self._payload = {"on": config[CONF_PAYLOAD_ON], "off": config[CONF_PAYLOAD_OFF]}
self._value_templates = {
key: MqttValueTemplate(
config.get(key), entity=self
).async_render_with_possible_json_value
for key in VALUE_TEMPLATE_KEYS
}
self._command_templates = {
key: MqttCommandTemplate(config.get(key), entity=self).async_render
for key in COMMAND_TEMPLATE_KEYS
}
optimistic: bool = config[CONF_OPTIMISTIC]
self._optimistic_color_mode = (
optimistic or topic[CONF_COLOR_MODE_STATE_TOPIC] is None
)
self._optimistic = optimistic or topic[CONF_STATE_TOPIC] is None
self._attr_assumed_state = bool(self._optimistic)
self._optimistic_rgb_color = optimistic or topic[CONF_RGB_STATE_TOPIC] is None
self._optimistic_rgbw_color = optimistic or topic[CONF_RGBW_STATE_TOPIC] is None
self._optimistic_rgbww_color = (
optimistic or topic[CONF_RGBWW_STATE_TOPIC] is None
)
self._optimistic_brightness = (
optimistic
or (
topic[CONF_BRIGHTNESS_COMMAND_TOPIC] is not None
and topic[CONF_BRIGHTNESS_STATE_TOPIC] is None
)
or (
topic[CONF_BRIGHTNESS_COMMAND_TOPIC] is None
and topic[CONF_RGB_STATE_TOPIC] is None
)
)
self._optimistic_color_temp_kelvin = (
optimistic or topic[CONF_COLOR_TEMP_STATE_TOPIC] is None
)
self._optimistic_effect = optimistic or topic[CONF_EFFECT_STATE_TOPIC] is None
self._optimistic_hs_color = optimistic or topic[CONF_HS_STATE_TOPIC] is None
self._optimistic_xy_color = optimistic or topic[CONF_XY_STATE_TOPIC] is None
supported_color_modes: set[ColorMode] = set()
if topic[CONF_COLOR_TEMP_COMMAND_TOPIC] is not None:
supported_color_modes.add(ColorMode.COLOR_TEMP)
self._attr_color_mode = ColorMode.COLOR_TEMP
if topic[CONF_HS_COMMAND_TOPIC] is not None:
supported_color_modes.add(ColorMode.HS)
self._attr_color_mode = ColorMode.HS
if topic[CONF_RGB_COMMAND_TOPIC] is not None:
supported_color_modes.add(ColorMode.RGB)
self._attr_color_mode = ColorMode.RGB
if topic[CONF_RGBW_COMMAND_TOPIC] is not None:
supported_color_modes.add(ColorMode.RGBW)
self._attr_color_mode = ColorMode.RGBW
if topic[CONF_RGBWW_COMMAND_TOPIC] is not None:
supported_color_modes.add(ColorMode.RGBWW)
self._attr_color_mode = ColorMode.RGBWW
if topic[CONF_WHITE_COMMAND_TOPIC] is not None:
supported_color_modes.add(ColorMode.WHITE)
if topic[CONF_XY_COMMAND_TOPIC] is not None:
supported_color_modes.add(ColorMode.XY)
self._attr_color_mode = ColorMode.XY
if len(supported_color_modes) > 1:
self._attr_color_mode = ColorMode.UNKNOWN
if not supported_color_modes:
if topic[CONF_BRIGHTNESS_COMMAND_TOPIC] is not None:
self._attr_color_mode = ColorMode.BRIGHTNESS
supported_color_modes.add(ColorMode.BRIGHTNESS)
else:
self._attr_color_mode = ColorMode.ONOFF
supported_color_modes.add(ColorMode.ONOFF)
# Validate the color_modes configuration
self._attr_supported_color_modes = valid_supported_color_modes(
supported_color_modes
)
self._attr_supported_features = LightEntityFeature(0)
if topic[CONF_EFFECT_COMMAND_TOPIC] is not None:
self._attr_supported_features |= LightEntityFeature.EFFECT
def _is_optimistic(self, attribute: str) -> bool:
"""Return True if the attribute is optimistically updated."""
attr: bool = getattr(self, f"_optimistic_{attribute}")
return attr
@callback
def _state_received(self, msg: ReceiveMessage) -> None:
"""Handle new MQTT messages."""
payload = self._value_templates[CONF_STATE_VALUE_TEMPLATE](
msg.payload, PayloadSentinel.NONE
)
if not payload:
_LOGGER.debug("Ignoring empty state message from '%s'", msg.topic)
return
if payload == self._payload["on"]:
self._attr_is_on = True
elif payload == self._payload["off"]:
self._attr_is_on = False
elif payload == PAYLOAD_NONE:
self._attr_is_on = None
@callback
def _brightness_received(self, msg: ReceiveMessage) -> None:
"""Handle new MQTT messages for the brightness."""
payload = self._value_templates[CONF_BRIGHTNESS_VALUE_TEMPLATE](
msg.payload, PayloadSentinel.DEFAULT
)
if payload is PayloadSentinel.DEFAULT or not payload:
_LOGGER.debug("Ignoring empty brightness message from '%s'", msg.topic)
return
device_value = float(payload)
if device_value == 0:
_LOGGER.debug("Ignoring zero brightness from '%s'", msg.topic)
return
percent_bright = device_value / self._config[CONF_BRIGHTNESS_SCALE]
self._attr_brightness = min(round(percent_bright * 255), 255)
@callback
def _rgbx_received(
self,
msg: ReceiveMessage,
template: str,
color_mode: ColorMode,
convert_color: Callable[..., tuple[int, ...]],
) -> tuple[int, ...] | None:
"""Process MQTT messages for RGBW and RGBWW."""
payload = self._value_templates[template](msg.payload, PayloadSentinel.DEFAULT)
if payload is PayloadSentinel.DEFAULT or not payload:
_LOGGER.debug("Ignoring empty %s message from '%s'", color_mode, msg.topic)
return None
color = tuple(int(val) for val in str(payload).split(","))
if self._optimistic_color_mode:
self._attr_color_mode = color_mode
if self._topic[CONF_BRIGHTNESS_STATE_TOPIC] is None:
rgb = convert_color(*color)
brightness = max(rgb)
if brightness == 0:
_LOGGER.debug(
"Ignoring %s message with zero rgb brightness from '%s'",
color_mode,
msg.topic,
)
return None
self._attr_brightness = brightness
# Normalize the color to 100% brightness
color = tuple(
min(round(channel / brightness * 255), 255) for channel in color
)
return color
@callback
def _rgb_received(self, msg: ReceiveMessage) -> None:
"""Handle new MQTT messages for RGB."""
rgb = self._rgbx_received(
msg, CONF_RGB_VALUE_TEMPLATE, ColorMode.RGB, lambda *x: x
)
if rgb is None:
return
self._attr_rgb_color = cast(tuple[int, int, int], rgb)
@callback
def _rgbw_received(self, msg: ReceiveMessage) -> None:
"""Handle new MQTT messages for RGBW."""
rgbw = self._rgbx_received(
msg,
CONF_RGBW_VALUE_TEMPLATE,
ColorMode.RGBW,
color_util.color_rgbw_to_rgb,
)
if rgbw is None:
return
self._attr_rgbw_color = cast(tuple[int, int, int, int], rgbw)
@callback
def _rgbww_received(self, msg: ReceiveMessage) -> None:
"""Handle new MQTT messages for RGBWW."""
@callback
def _converter(
r: int, g: int, b: int, cw: int, ww: int
) -> tuple[int, int, int]:
return color_util.color_rgbww_to_rgb(
r, g, b, cw, ww, self.min_color_temp_kelvin, self.max_color_temp_kelvin
)
rgbww = self._rgbx_received(
msg,
CONF_RGBWW_VALUE_TEMPLATE,
ColorMode.RGBWW,
_converter,
)
if rgbww is None:
return
self._attr_rgbww_color = cast(tuple[int, int, int, int, int], rgbww)
@callback
def _color_mode_received(self, msg: ReceiveMessage) -> None:
"""Handle new MQTT messages for color mode."""
payload = self._value_templates[CONF_COLOR_MODE_VALUE_TEMPLATE](
msg.payload, PayloadSentinel.DEFAULT
)
if payload is PayloadSentinel.DEFAULT or not payload:
_LOGGER.debug("Ignoring empty color mode message from '%s'", msg.topic)
return
self._attr_color_mode = ColorMode(str(payload))
@callback
def _color_temp_received(self, msg: ReceiveMessage) -> None:
"""Handle new MQTT messages for color temperature."""
payload = self._value_templates[CONF_COLOR_TEMP_VALUE_TEMPLATE](
msg.payload, PayloadSentinel.DEFAULT
)
if payload is PayloadSentinel.DEFAULT or not payload:
_LOGGER.debug("Ignoring empty color temp message from '%s'", msg.topic)
return
if self._optimistic_color_mode:
self._attr_color_mode = ColorMode.COLOR_TEMP
if self._color_temp_kelvin:
self._attr_color_temp_kelvin = int(payload)
return
self._attr_color_temp_kelvin = color_util.color_temperature_mired_to_kelvin(
int(payload)
)
@callback
def _effect_received(self, msg: ReceiveMessage) -> None:
"""Handle new MQTT messages for effect."""
payload = self._value_templates[CONF_EFFECT_VALUE_TEMPLATE](
msg.payload, PayloadSentinel.DEFAULT
)
if payload is PayloadSentinel.DEFAULT or not payload:
_LOGGER.debug("Ignoring empty effect message from '%s'", msg.topic)
return
self._attr_effect = str(payload)
@callback
def _hs_received(self, msg: ReceiveMessage) -> None:
"""Handle new MQTT messages for hs color."""
payload = self._value_templates[CONF_HS_VALUE_TEMPLATE](
msg.payload, PayloadSentinel.DEFAULT
)
if payload is PayloadSentinel.DEFAULT or not payload:
_LOGGER.debug("Ignoring empty hs message from '%s'", msg.topic)
return
try:
hs_color = tuple(float(val) for val in str(payload).split(",", 2))
if self._optimistic_color_mode:
self._attr_color_mode = ColorMode.HS
self._attr_hs_color = cast(tuple[float, float], hs_color)
except ValueError:
_LOGGER.warning("Failed to parse hs state update: '%s'", payload)
@callback
def _xy_received(self, msg: ReceiveMessage) -> None:
"""Handle new MQTT messages for xy color."""
payload = self._value_templates[CONF_XY_VALUE_TEMPLATE](
msg.payload, PayloadSentinel.DEFAULT
)
if payload is PayloadSentinel.DEFAULT or not payload:
_LOGGER.debug("Ignoring empty xy-color message from '%s'", msg.topic)
return
xy_color = tuple(float(val) for val in str(payload).split(",", 2))
if self._optimistic_color_mode:
self._attr_color_mode = ColorMode.XY
self._attr_xy_color = cast(tuple[float, float], xy_color)
@callback
@override
def _prepare_subscribe_topics(self) -> None:
"""(Re)Subscribe to topics."""
self.add_subscription(CONF_STATE_TOPIC, self._state_received, {"_attr_is_on"})
self.add_subscription(
CONF_BRIGHTNESS_STATE_TOPIC, self._brightness_received, {"_attr_brightness"}
)
self.add_subscription(
CONF_RGB_STATE_TOPIC,
self._rgb_received,
{"_attr_brightness", "_attr_color_mode", "_attr_rgb_color"},
)
self.add_subscription(
CONF_RGBW_STATE_TOPIC,
self._rgbw_received,
{"_attr_brightness", "_attr_color_mode", "_attr_rgbw_color"},
)
self.add_subscription(
CONF_RGBWW_STATE_TOPIC,
self._rgbww_received,
{"_attr_brightness", "_attr_color_mode", "_attr_rgbww_color"},
)
self.add_subscription(
CONF_COLOR_MODE_STATE_TOPIC, self._color_mode_received, {"_attr_color_mode"}
)
self.add_subscription(
CONF_COLOR_TEMP_STATE_TOPIC,
self._color_temp_received,
{"_attr_color_mode", "_attr_color_temp_kelvin"},
)
self.add_subscription(
CONF_EFFECT_STATE_TOPIC, self._effect_received, {"_attr_effect"}
)
self.add_subscription(
CONF_HS_STATE_TOPIC,
self._hs_received,
{"_attr_color_mode", "_attr_hs_color"},
)
self.add_subscription(
CONF_XY_STATE_TOPIC,
self._xy_received,
{"_attr_color_mode", "_attr_xy_color"},
)
@override
async def _subscribe_topics(self) -> None:
"""(Re)Subscribe to topics."""
subscription.async_subscribe_topics_internal(self.hass, self._sub_state)
last_state = await self.async_get_last_state()
def restore_state(
attribute: str, condition_attribute: str | None = None
) -> None:
"""Restore a state attribute."""
if condition_attribute is None:
condition_attribute = attribute
optimistic = self._is_optimistic(condition_attribute)
if optimistic and last_state and last_state.attributes.get(attribute):
setattr(self, f"_attr_{attribute}", last_state.attributes[attribute])
if self._topic[CONF_STATE_TOPIC] is None and self._optimistic and last_state:
self._attr_is_on = last_state.state == STATE_ON
restore_state(ATTR_BRIGHTNESS)
restore_state(ATTR_RGB_COLOR)
restore_state(ATTR_HS_COLOR, ATTR_RGB_COLOR)
restore_state(ATTR_RGBW_COLOR)
restore_state(ATTR_RGBWW_COLOR)
restore_state(ATTR_COLOR_MODE)
restore_state(ATTR_COLOR_TEMP_KELVIN)
restore_state(ATTR_EFFECT)
restore_state(ATTR_HS_COLOR)
restore_state(ATTR_XY_COLOR)
restore_state(ATTR_HS_COLOR, ATTR_XY_COLOR)
@override
async def async_turn_on(self, **kwargs: Any) -> None: # noqa: C901
"""Turn the device on.
This method is a coroutine.
"""
should_update = False
on_command_type: str = self._config[CONF_ON_COMMAND_TYPE]
async def publish(topic: str, payload: PublishPayloadType) -> None:
"""Publish an MQTT message."""
await self.async_publish_with_config(str(self._topic[topic]), payload)
def scale_rgbx(
color: tuple[int, ...],
brightness: int | None = None,
) -> tuple[int, ...]:
"""Scale RGBx for brightness."""
if brightness is None:
# If there's a brightness topic set, we don't want to scale the RGBx
# values given using the brightness.
if self._topic[CONF_BRIGHTNESS_COMMAND_TOPIC] is not None:
brightness = 255
else:
brightness = kwargs.get(ATTR_BRIGHTNESS) or self.brightness or 255
return tuple(int(channel * brightness / 255) for channel in color)
def render_rgbx(
color: tuple[int, ...],
template: str,
color_mode: ColorMode,
) -> PublishPayloadType:
"""Render RGBx payload."""
rgb_color_str = ",".join(str(channel) for channel in color)
keys = ["red", "green", "blue"]
if color_mode == ColorMode.RGBW:
keys.append("white")
elif color_mode == ColorMode.RGBWW:
keys.extend(["cold_white", "warm_white"])
variables = dict(zip(keys, color, strict=False))
return self._command_templates[template](rgb_color_str, variables)
def set_optimistic(
attribute: str,
value: Any,
color_mode: ColorMode | None = None,
condition_attribute: str | None = None,
) -> bool:
"""Optimistically update a state attribute."""
if condition_attribute is None:
condition_attribute = attribute
if not self._is_optimistic(condition_attribute):
return False
if color_mode and self._optimistic_color_mode:
self._attr_color_mode = color_mode
setattr(self, f"_attr_{attribute}", value)
return True
if on_command_type == "first":
await publish(CONF_COMMAND_TOPIC, self._payload["on"])
should_update = True
# If brightness is being used instead of an on command, make sure
# there is a brightness input. Either set the brightness to our
# saved value or the maximum value if this is the first call
elif (
on_command_type == "brightness"
and ATTR_BRIGHTNESS not in kwargs
and ATTR_WHITE not in kwargs
):
kwargs[ATTR_BRIGHTNESS] = self.brightness or 255
hs_color: str | None = kwargs.get(ATTR_HS_COLOR)
if hs_color and self._topic[CONF_HS_COMMAND_TOPIC] is not None:
device_hs_payload = self._command_templates[CONF_HS_COMMAND_TEMPLATE](
f"{hs_color[0]},{hs_color[1]}",
{"hue": hs_color[0], "sat": hs_color[1]},
)
await publish(CONF_HS_COMMAND_TOPIC, device_hs_payload)
should_update |= set_optimistic(ATTR_HS_COLOR, hs_color, ColorMode.HS)
rgb: tuple[int, int, int] | None
if (rgb := kwargs.get(ATTR_RGB_COLOR)) and self._topic[
CONF_RGB_COMMAND_TOPIC
] is not None:
scaled = scale_rgbx(rgb)
rgb_s = render_rgbx(scaled, CONF_RGB_COMMAND_TEMPLATE, ColorMode.RGB)
await publish(CONF_RGB_COMMAND_TOPIC, rgb_s)
should_update |= set_optimistic(ATTR_RGB_COLOR, rgb, ColorMode.RGB)
rgbw: tuple[int, int, int, int] | None
if (rgbw := kwargs.get(ATTR_RGBW_COLOR)) and self._topic[
CONF_RGBW_COMMAND_TOPIC
] is not None:
scaled = scale_rgbx(rgbw)
rgbw_s = render_rgbx(scaled, CONF_RGBW_COMMAND_TEMPLATE, ColorMode.RGBW)
await publish(CONF_RGBW_COMMAND_TOPIC, rgbw_s)
should_update |= set_optimistic(ATTR_RGBW_COLOR, rgbw, ColorMode.RGBW)
rgbww: tuple[int, int, int, int, int] | None
if (rgbww := kwargs.get(ATTR_RGBWW_COLOR)) and self._topic[
CONF_RGBWW_COMMAND_TOPIC
] is not None:
scaled = scale_rgbx(rgbww)
rgbww_s = render_rgbx(scaled, CONF_RGBWW_COMMAND_TEMPLATE, ColorMode.RGBWW)
await publish(CONF_RGBWW_COMMAND_TOPIC, rgbww_s)
should_update |= set_optimistic(ATTR_RGBWW_COLOR, rgbww, ColorMode.RGBWW)
xy_color: tuple[float, float] | None
if (xy_color := kwargs.get(ATTR_XY_COLOR)) and self._topic[
CONF_XY_COMMAND_TOPIC
] is not None:
device_xy_payload = self._command_templates[CONF_XY_COMMAND_TEMPLATE](
f"{xy_color[0]},{xy_color[1]}",
{"x": xy_color[0], "y": xy_color[1]},
)
await publish(CONF_XY_COMMAND_TOPIC, device_xy_payload)
should_update |= set_optimistic(ATTR_XY_COLOR, xy_color, ColorMode.XY)
if (
ATTR_BRIGHTNESS in kwargs
and self._topic[CONF_BRIGHTNESS_COMMAND_TOPIC] is not None
):
brightness_normalized: float = kwargs[ATTR_BRIGHTNESS] / 255
brightness_scale: int = self._config[CONF_BRIGHTNESS_SCALE]
device_brightness = min(
round(brightness_normalized * brightness_scale), brightness_scale
)
# Make sure the brightness is not rounded down to 0
device_brightness = max(device_brightness, 1)
command_tpl = self._command_templates[CONF_BRIGHTNESS_COMMAND_TEMPLATE]
device_brightness_payload = command_tpl(device_brightness, None)
await publish(CONF_BRIGHTNESS_COMMAND_TOPIC, device_brightness_payload)
should_update |= set_optimistic(ATTR_BRIGHTNESS, kwargs[ATTR_BRIGHTNESS])
elif (
ATTR_BRIGHTNESS in kwargs
and ATTR_RGB_COLOR not in kwargs
and self._topic[CONF_RGB_COMMAND_TOPIC] is not None
):
rgb_color = self.rgb_color or (255,) * 3
rgb_scaled = scale_rgbx(rgb_color, kwargs[ATTR_BRIGHTNESS])
rgb_s = render_rgbx(rgb_scaled, CONF_RGB_COMMAND_TEMPLATE, ColorMode.RGB)
await publish(CONF_RGB_COMMAND_TOPIC, rgb_s)
should_update |= set_optimistic(ATTR_BRIGHTNESS, kwargs[ATTR_BRIGHTNESS])
elif (
ATTR_BRIGHTNESS in kwargs
and ATTR_RGBW_COLOR not in kwargs
and self._topic[CONF_RGBW_COMMAND_TOPIC] is not None
):
rgbw_color = self.rgbw_color or (255,) * 4
rgbw_b = scale_rgbx(rgbw_color, kwargs[ATTR_BRIGHTNESS])
rgbw_s = render_rgbx(rgbw_b, CONF_RGBW_COMMAND_TEMPLATE, ColorMode.RGBW)
await publish(CONF_RGBW_COMMAND_TOPIC, rgbw_s)
should_update |= set_optimistic(ATTR_BRIGHTNESS, kwargs[ATTR_BRIGHTNESS])
elif (
ATTR_BRIGHTNESS in kwargs
and ATTR_RGBWW_COLOR not in kwargs
and self._topic[CONF_RGBWW_COMMAND_TOPIC] is not None
):
rgbww_color = self.rgbww_color or (255,) * 5
rgbww_b = scale_rgbx(rgbww_color, kwargs[ATTR_BRIGHTNESS])
rgbww_s = render_rgbx(rgbww_b, CONF_RGBWW_COMMAND_TEMPLATE, ColorMode.RGBWW)
await publish(CONF_RGBWW_COMMAND_TOPIC, rgbww_s)
should_update |= set_optimistic(ATTR_BRIGHTNESS, kwargs[ATTR_BRIGHTNESS])
if (
ATTR_COLOR_TEMP_KELVIN in kwargs
and self._topic[CONF_COLOR_TEMP_COMMAND_TOPIC] is not None
):
ct_command_tpl = self._command_templates[CONF_COLOR_TEMP_COMMAND_TEMPLATE]
color_temp = ct_command_tpl(
kwargs[ATTR_COLOR_TEMP_KELVIN]
if self._color_temp_kelvin
else color_util.color_temperature_kelvin_to_mired(
kwargs[ATTR_COLOR_TEMP_KELVIN]
),
None,
)
await publish(CONF_COLOR_TEMP_COMMAND_TOPIC, color_temp)
should_update |= set_optimistic(
ATTR_COLOR_TEMP_KELVIN,
kwargs[ATTR_COLOR_TEMP_KELVIN],
ColorMode.COLOR_TEMP,
)
if (
ATTR_EFFECT in kwargs
and self._topic[CONF_EFFECT_COMMAND_TOPIC] is not None
and CONF_EFFECT_LIST in self._config
):
if kwargs[ATTR_EFFECT] in self._config[CONF_EFFECT_LIST]:
eff_command_tpl = self._command_templates[CONF_EFFECT_COMMAND_TEMPLATE]
effect = eff_command_tpl(kwargs[ATTR_EFFECT], None)
await publish(CONF_EFFECT_COMMAND_TOPIC, effect)
should_update |= set_optimistic(ATTR_EFFECT, kwargs[ATTR_EFFECT])
if ATTR_WHITE in kwargs and self._topic[CONF_WHITE_COMMAND_TOPIC] is not None:
percent_white = float(kwargs[ATTR_WHITE]) / 255
white_scale: int = self._config[CONF_WHITE_SCALE]
device_white_value = min(round(percent_white * white_scale), white_scale)
await publish(CONF_WHITE_COMMAND_TOPIC, device_white_value)
should_update |= set_optimistic(
ATTR_BRIGHTNESS,
kwargs[ATTR_WHITE],
ColorMode.WHITE,
)
if on_command_type == "last":
await publish(CONF_COMMAND_TOPIC, self._payload["on"])
should_update = True
if self._optimistic:
# Optimistically assume that the light has changed state.
self._attr_is_on = True
should_update = True
if should_update:
self.async_write_ha_state()
@override
async def async_turn_off(self, **kwargs: Any) -> None:
"""Turn the device off.
This method is a coroutine.
"""
await self.async_publish_with_config(
str(self._topic[CONF_COMMAND_TOPIC]), self._payload["off"]
)
if self._optimistic:
# Optimistically assume that the light has changed state.
self._attr_is_on = False
self.async_write_ha_state()
@@ -0,0 +1,531 @@
"""Support for MQTT JSON lights."""
from contextlib import suppress
import logging
from typing import TYPE_CHECKING, Any, cast, override
import probatio
from homeassistant.components.light import (
ATTR_BRIGHTNESS,
ATTR_COLOR_MODE,
ATTR_COLOR_TEMP_KELVIN,
ATTR_EFFECT,
ATTR_FLASH,
ATTR_HS_COLOR,
ATTR_RGB_COLOR,
ATTR_RGBW_COLOR,
ATTR_RGBWW_COLOR,
ATTR_TRANSITION,
ATTR_WHITE,
ATTR_XY_COLOR,
DEFAULT_MAX_KELVIN,
DEFAULT_MIN_KELVIN,
ENTITY_ID_FORMAT,
FLASH_LONG,
FLASH_SHORT,
VALID_COLOR_MODES,
ColorMode,
LightEntity,
LightEntityFeature,
brightness_supported,
valid_supported_color_modes,
)
from homeassistant.const import (
CONF_BRIGHTNESS,
CONF_EFFECT,
CONF_NAME,
CONF_OPTIMISTIC,
STATE_ON,
)
from homeassistant.core import callback
from homeassistant.helpers import config_validation as cv
from homeassistant.helpers.json import json_dumps
from homeassistant.helpers.restore_state import RestoreEntity
from homeassistant.helpers.typing import ConfigType, VolSchemaType
from homeassistant.util import color as color_util
from homeassistant.util.json import json_loads_object
from .. import subscription
from ..config import DEFAULT_QOS, DEFAULT_RETAIN, MQTT_RW_SCHEMA
from ..const import (
CONF_COLOR_TEMP_KELVIN,
CONF_COMMAND_TOPIC,
CONF_EFFECT_LIST,
CONF_FLASH,
CONF_FLASH_TIME_LONG,
CONF_FLASH_TIME_SHORT,
CONF_MAX_KELVIN,
CONF_MAX_MIREDS,
CONF_MIN_KELVIN,
CONF_MIN_MIREDS,
CONF_QOS,
CONF_RETAIN,
CONF_STATE_TOPIC,
CONF_SUPPORTED_COLOR_MODES,
CONF_TRANSITION,
DEFAULT_BRIGHTNESS,
DEFAULT_BRIGHTNESS_SCALE,
DEFAULT_EFFECT,
DEFAULT_FLASH_TIME_LONG,
DEFAULT_FLASH_TIME_SHORT,
DEFAULT_WHITE_SCALE,
)
from ..entity import MqttEntity
from ..models import ReceiveMessage
from ..schemas import MQTT_ENTITY_COMMON_SCHEMA
from ..util import valid_subscribe_topic
from .schema import MQTT_LIGHT_SCHEMA_SCHEMA
from .schema_basic import (
CONF_BRIGHTNESS_SCALE,
CONF_WHITE_SCALE,
MQTT_LIGHT_ATTRIBUTES_BLOCKED,
)
_LOGGER = logging.getLogger(__name__)
DEFAULT_NAME = "MQTT JSON Light"
DEFAULT_FLASH = True
DEFAULT_TRANSITION = True
PLATFORM_SCHEMA_MODERN_JSON = (
MQTT_RW_SCHEMA.extend(
{
probatio.Optional(CONF_BRIGHTNESS, default=DEFAULT_BRIGHTNESS): cv.boolean,
probatio.Optional(
CONF_BRIGHTNESS_SCALE, default=DEFAULT_BRIGHTNESS_SCALE
): probatio.All(probatio.Coerce(int), probatio.Range(min=1)),
probatio.Optional(CONF_COLOR_TEMP_KELVIN, default=False): cv.boolean,
probatio.Optional(CONF_EFFECT, default=DEFAULT_EFFECT): cv.boolean,
probatio.Optional(CONF_EFFECT_LIST): probatio.All(
probatio.EnsureList(), [cv.string]
),
probatio.Optional(CONF_FLASH, default=DEFAULT_FLASH): cv.boolean,
probatio.Optional(
CONF_FLASH_TIME_LONG, default=DEFAULT_FLASH_TIME_LONG
): cv.positive_int,
probatio.Optional(
CONF_FLASH_TIME_SHORT, default=DEFAULT_FLASH_TIME_SHORT
): cv.positive_int,
probatio.Optional(CONF_MAX_MIREDS): cv.positive_int,
probatio.Optional(CONF_MIN_MIREDS): cv.positive_int,
probatio.Optional(CONF_MAX_KELVIN): cv.positive_int,
probatio.Optional(CONF_MIN_KELVIN): cv.positive_int,
probatio.Optional(CONF_NAME): probatio.Any(cv.string, None),
probatio.Optional(CONF_QOS, default=DEFAULT_QOS): probatio.All(
probatio.Coerce(int), probatio.In([0, 1, 2])
),
probatio.Optional(CONF_RETAIN, default=DEFAULT_RETAIN): cv.boolean,
probatio.Optional(CONF_STATE_TOPIC): valid_subscribe_topic,
probatio.Optional(CONF_SUPPORTED_COLOR_MODES): probatio.All(
probatio.EnsureList(),
[probatio.In(VALID_COLOR_MODES)],
probatio.Unique(),
valid_supported_color_modes,
),
probatio.Optional(CONF_TRANSITION, default=DEFAULT_TRANSITION): cv.boolean,
probatio.Optional(
CONF_WHITE_SCALE, default=DEFAULT_WHITE_SCALE
): probatio.All(probatio.Coerce(int), probatio.Range(min=1)),
},
)
.extend(MQTT_ENTITY_COMMON_SCHEMA.schema)
.extend(MQTT_LIGHT_SCHEMA_SCHEMA.schema)
)
DISCOVERY_SCHEMA_JSON = probatio.All(
PLATFORM_SCHEMA_MODERN_JSON.extend({}, extra=probatio.REMOVE_EXTRA),
)
class MqttLightJson(MqttEntity, LightEntity, RestoreEntity):
"""Representation of a MQTT JSON light."""
_default_name = DEFAULT_NAME
_entity_id_format = ENTITY_ID_FORMAT
_attributes_extra_blocked = MQTT_LIGHT_ATTRIBUTES_BLOCKED
_flash_times: dict[str, int | None]
_topic: dict[str, str | None]
_optimistic: bool
@staticmethod
@override
def config_schema() -> VolSchemaType:
"""Return the config schema."""
return DISCOVERY_SCHEMA_JSON
@override
def _setup_from_config(self, config: ConfigType) -> None:
"""(Re)Setup the entity."""
self._color_temp_kelvin = config[CONF_COLOR_TEMP_KELVIN]
self._attr_min_color_temp_kelvin = (
color_util.color_temperature_mired_to_kelvin(max_mireds)
if (max_mireds := config.get(CONF_MAX_MIREDS))
else config.get(CONF_MIN_KELVIN, DEFAULT_MIN_KELVIN)
)
self._attr_max_color_temp_kelvin = (
color_util.color_temperature_mired_to_kelvin(min_mireds)
if (min_mireds := config.get(CONF_MIN_MIREDS))
else config.get(CONF_MAX_KELVIN, DEFAULT_MAX_KELVIN)
)
self._attr_effect_list = config.get(CONF_EFFECT_LIST)
self._topic = {
key: config.get(key) for key in (CONF_STATE_TOPIC, CONF_COMMAND_TOPIC)
}
optimistic: bool = config[CONF_OPTIMISTIC]
self._optimistic = optimistic or self._topic[CONF_STATE_TOPIC] is None
self._attr_assumed_state = bool(self._optimistic)
self._flash_times = {
key: config.get(key)
for key in (CONF_FLASH_TIME_SHORT, CONF_FLASH_TIME_LONG)
}
self._attr_supported_features |= (
config[CONF_EFFECT] and LightEntityFeature.EFFECT
)
self._attr_supported_features |= config[CONF_FLASH] and LightEntityFeature.FLASH
self._attr_supported_features |= (
config[CONF_TRANSITION] and LightEntityFeature.TRANSITION
)
self._attr_color_mode = ColorMode.UNKNOWN
if supported_color_modes := self._config.get(CONF_SUPPORTED_COLOR_MODES):
self._attr_supported_color_modes = supported_color_modes
if self.supported_color_modes and len(self.supported_color_modes) == 1:
self._attr_color_mode = next(iter(self.supported_color_modes))
else:
self._attr_color_mode = ColorMode.UNKNOWN
elif config.get(CONF_BRIGHTNESS):
# Brightness is supported and no supported_color_modes are set,
# so set brightness as the supported color mode.
self._attr_supported_color_modes = {ColorMode.BRIGHTNESS}
self._attr_color_mode = ColorMode.BRIGHTNESS
else:
self._attr_supported_color_modes = {ColorMode.ONOFF}
self._attr_color_mode = ColorMode.ONOFF
def _update_color(self, values: dict[str, Any]) -> None:
color_mode: str = values["color_mode"]
if not self._supports_color_mode(color_mode):
_LOGGER.warning(
"Invalid color mode '%s' received for entity %s",
color_mode,
self.entity_id,
)
return
try:
if color_mode == ColorMode.COLOR_TEMP:
self._attr_color_temp_kelvin = (
values["color_temp"]
if self._color_temp_kelvin
else color_util.color_temperature_mired_to_kelvin(
values["color_temp"]
)
)
self._attr_color_mode = ColorMode.COLOR_TEMP
elif color_mode == ColorMode.HS:
hue = float(values["color"]["h"])
saturation = float(values["color"]["s"])
self._attr_color_mode = ColorMode.HS
self._attr_hs_color = (hue, saturation)
elif color_mode == ColorMode.RGB:
r = int(values["color"]["r"])
g = int(values["color"]["g"])
b = int(values["color"]["b"])
self._attr_color_mode = ColorMode.RGB
self._attr_rgb_color = (r, g, b)
elif color_mode == ColorMode.RGBW:
r = int(values["color"]["r"])
g = int(values["color"]["g"])
b = int(values["color"]["b"])
w = int(values["color"]["w"])
self._attr_color_mode = ColorMode.RGBW
self._attr_rgbw_color = (r, g, b, w)
elif color_mode == ColorMode.RGBWW:
r = int(values["color"]["r"])
g = int(values["color"]["g"])
b = int(values["color"]["b"])
c = int(values["color"]["c"])
w = int(values["color"]["w"])
self._attr_color_mode = ColorMode.RGBWW
self._attr_rgbww_color = (r, g, b, c, w)
elif color_mode == ColorMode.WHITE:
self._attr_color_mode = ColorMode.WHITE
elif color_mode == ColorMode.XY:
x = float(values["color"]["x"])
y = float(values["color"]["y"])
self._attr_color_mode = ColorMode.XY
self._attr_xy_color = (x, y)
except KeyError, TypeError, ValueError:
_LOGGER.warning(
"Invalid or incomplete color value '%s' received for entity %s",
values,
self.entity_id,
)
@callback
def _state_received(self, msg: ReceiveMessage) -> None:
"""Handle new MQTT messages."""
values = json_loads_object(msg.payload)
if values["state"] == "ON":
self._attr_is_on = True
elif values["state"] == "OFF":
self._attr_is_on = False
elif values["state"] is None:
self._attr_is_on = None
if "color_mode" in values:
self._update_color(values)
if brightness_supported(self.supported_color_modes):
try:
if brightness := values["brightness"]:
if TYPE_CHECKING:
assert isinstance(brightness, float)
self._attr_brightness = color_util.value_to_brightness(
(1, self._config[CONF_BRIGHTNESS_SCALE]), brightness
)
else:
_LOGGER.debug(
"Ignoring zero brightness value for entity %s",
self.entity_id,
)
except KeyError:
pass
except TypeError, ValueError:
_LOGGER.warning(
"Invalid brightness value '%s' received for entity %s",
values["brightness"],
self.entity_id,
)
if self.supported_features and LightEntityFeature.EFFECT:
with suppress(KeyError):
self._attr_effect = cast(str, values["effect"])
@callback
@override
def _prepare_subscribe_topics(self) -> None:
"""(Re)Subscribe to topics."""
self.add_subscription(
CONF_STATE_TOPIC,
self._state_received,
{
"_attr_brightness",
"_attr_color_temp_kelvin",
"_attr_effect",
"_attr_hs_color",
"_attr_is_on",
"_attr_rgb_color",
"_attr_rgbw_color",
"_attr_rgbww_color",
"_attr_xy_color",
"color_mode",
},
)
@override
async def _subscribe_topics(self) -> None:
"""(Re)Subscribe to topics."""
subscription.async_subscribe_topics_internal(self.hass, self._sub_state)
last_state = await self.async_get_last_state()
if self._optimistic and last_state:
self._attr_is_on = last_state.state == STATE_ON
last_attributes = last_state.attributes
self._attr_brightness = last_attributes.get(
ATTR_BRIGHTNESS, self.brightness
)
self._attr_color_mode = (
last_attributes.get(ATTR_COLOR_MODE) or self.color_mode
)
self._attr_color_temp_kelvin = last_attributes.get(
ATTR_COLOR_TEMP_KELVIN, self.color_temp_kelvin
)
self._attr_effect = last_attributes.get(ATTR_EFFECT, self.effect)
self._attr_hs_color = last_attributes.get(ATTR_HS_COLOR, self.hs_color)
self._attr_rgb_color = last_attributes.get(ATTR_RGB_COLOR, self.rgb_color)
self._attr_rgbw_color = last_attributes.get(
ATTR_RGBW_COLOR, self.rgbw_color
)
self._attr_rgbww_color = last_attributes.get(
ATTR_RGBWW_COLOR, self.rgbww_color
)
self._attr_xy_color = last_attributes.get(ATTR_XY_COLOR, self.xy_color)
def _set_flash_and_transition(self, message: dict[str, Any], **kwargs: Any) -> None:
if ATTR_TRANSITION in kwargs:
message["transition"] = kwargs[ATTR_TRANSITION]
if ATTR_FLASH in kwargs:
flash: str = kwargs[ATTR_FLASH]
if flash == FLASH_LONG:
message["flash"] = self._flash_times[CONF_FLASH_TIME_LONG]
elif flash == FLASH_SHORT:
message["flash"] = self._flash_times[CONF_FLASH_TIME_SHORT]
def _scale_rgbxx(self, rgbxx: tuple[int, ...], kwargs: Any) -> tuple[int, ...]:
# If brightness is supported, we don't want to scale the
# RGBxx values given using the brightness and
# we pop the brightness, to omit it from the payload
brightness: int
if self._config[CONF_BRIGHTNESS]:
brightness = 255
else:
brightness = kwargs.pop(ATTR_BRIGHTNESS, 255)
return tuple(round(i / 255 * brightness) for i in rgbxx)
def _supports_color_mode(self, color_mode: ColorMode | str) -> bool:
"""Return True if the light natively supports a color mode."""
return (
self.supported_color_modes is not None
and color_mode in self.supported_color_modes
)
@override
async def async_turn_on(self, **kwargs: Any) -> None:
"""Turn the device on.
This method is a coroutine.
"""
should_update = False
hs_color: tuple[float, float]
message: dict[str, Any] = {"state": "ON"}
rgb: tuple[int, ...]
rgbw: tuple[int, ...]
rgbcw: tuple[int, ...]
xy_color: tuple[float, float]
if ATTR_HS_COLOR in kwargs and self._supports_color_mode(ColorMode.HS):
hs_color = kwargs[ATTR_HS_COLOR]
message["color"] = {"h": hs_color[0], "s": hs_color[1]}
if self._optimistic:
self._attr_color_mode = ColorMode.HS
self._attr_hs_color = hs_color
should_update = True
if ATTR_RGB_COLOR in kwargs and self._supports_color_mode(ColorMode.RGB):
rgb = self._scale_rgbxx(kwargs[ATTR_RGB_COLOR], kwargs)
message["color"] = {"r": rgb[0], "g": rgb[1], "b": rgb[2]}
if self._optimistic:
self._attr_color_mode = ColorMode.RGB
self._attr_rgb_color = cast(tuple[int, int, int], rgb)
should_update = True
if ATTR_RGBW_COLOR in kwargs and self._supports_color_mode(ColorMode.RGBW):
rgbw = self._scale_rgbxx(kwargs[ATTR_RGBW_COLOR], kwargs)
message["color"] = {"r": rgbw[0], "g": rgbw[1], "b": rgbw[2], "w": rgbw[3]}
if self._optimistic:
self._attr_color_mode = ColorMode.RGBW
self._attr_rgbw_color = cast(tuple[int, int, int, int], rgbw)
should_update = True
if ATTR_RGBWW_COLOR in kwargs and self._supports_color_mode(ColorMode.RGBWW):
rgbcw = self._scale_rgbxx(kwargs[ATTR_RGBWW_COLOR], kwargs)
message["color"] = {
"r": rgbcw[0],
"g": rgbcw[1],
"b": rgbcw[2],
"c": rgbcw[3],
"w": rgbcw[4],
}
if self._optimistic:
self._attr_color_mode = ColorMode.RGBWW
self._attr_rgbww_color = cast(tuple[int, int, int, int, int], rgbcw)
should_update = True
if ATTR_XY_COLOR in kwargs and self._supports_color_mode(ColorMode.XY):
xy_color = kwargs[ATTR_XY_COLOR]
message["color"] = {"x": xy_color[0], "y": xy_color[1]}
if self._optimistic:
self._attr_color_mode = ColorMode.XY
self._attr_xy_color = xy_color
should_update = True
self._set_flash_and_transition(message, **kwargs)
if ATTR_BRIGHTNESS in kwargs and brightness_supported(
self.supported_color_modes
):
device_brightness = color_util.brightness_to_value(
(1, self._config[CONF_BRIGHTNESS_SCALE]),
kwargs[ATTR_BRIGHTNESS],
)
# Make sure the brightness is not rounded down to 0
device_brightness = max(round(device_brightness), 1)
message["brightness"] = device_brightness
if self._optimistic:
self._attr_brightness = kwargs[ATTR_BRIGHTNESS]
should_update = True
if ATTR_COLOR_TEMP_KELVIN in kwargs:
message["color_temp"] = (
kwargs[ATTR_COLOR_TEMP_KELVIN]
if self._color_temp_kelvin
else color_util.color_temperature_kelvin_to_mired(
kwargs[ATTR_COLOR_TEMP_KELVIN]
)
)
if self._optimistic:
self._attr_color_mode = ColorMode.COLOR_TEMP
self._attr_color_temp_kelvin = kwargs[ATTR_COLOR_TEMP_KELVIN]
self._attr_hs_color = None
should_update = True
if ATTR_EFFECT in kwargs:
message["effect"] = kwargs[ATTR_EFFECT]
if self._optimistic:
self._attr_effect = kwargs[ATTR_EFFECT]
should_update = True
if ATTR_WHITE in kwargs and self._supports_color_mode(ColorMode.WHITE):
white_normalized = kwargs[ATTR_WHITE] / DEFAULT_WHITE_SCALE
white_scale = self._config[CONF_WHITE_SCALE]
device_white_level = min(round(white_normalized * white_scale), white_scale)
# Make sure the brightness is not rounded down to 0
device_white_level = max(device_white_level, 1)
message["white"] = device_white_level
if self._optimistic:
self._attr_color_mode = ColorMode.WHITE
self._attr_brightness = kwargs[ATTR_WHITE]
should_update = True
await self.async_publish_with_config(
str(self._topic[CONF_COMMAND_TOPIC]), json_dumps(message)
)
if self._optimistic:
# Optimistically assume that the light has changed state.
self._attr_is_on = True
should_update = True
if should_update:
self.async_write_ha_state()
@override
async def async_turn_off(self, **kwargs: Any) -> None:
"""Turn the device off.
This method is a coroutine.
"""
message: dict[str, Any] = {"state": "OFF"}
self._set_flash_and_transition(message, **kwargs)
await self.async_publish_with_config(
str(self._topic[CONF_COMMAND_TOPIC]), json_dumps(message)
)
if self._optimistic:
# Optimistically assume that the light has changed state.
self._attr_is_on = False
self.async_write_ha_state()
@@ -0,0 +1,478 @@
"""Support for MQTT Template lights."""
from collections.abc import Callable
import logging
from typing import Any, override
import probatio
from homeassistant.components.light import (
ATTR_BRIGHTNESS,
ATTR_COLOR_TEMP_KELVIN,
ATTR_EFFECT,
ATTR_FLASH,
ATTR_HS_COLOR,
ATTR_TRANSITION,
DEFAULT_MAX_KELVIN,
DEFAULT_MIN_KELVIN,
ENTITY_ID_FORMAT,
ColorMode,
LightEntity,
LightEntityFeature,
LightEntityStateAttribute,
filter_supported_color_modes,
)
from homeassistant.const import (
CONF_NAME,
CONF_OPTIMISTIC,
CONF_STATE_TEMPLATE,
STATE_OFF,
STATE_ON,
)
from homeassistant.core import callback
from homeassistant.helpers import config_validation as cv
from homeassistant.helpers.restore_state import RestoreEntity
from homeassistant.helpers.service_info.mqtt import ReceivePayloadType
from homeassistant.helpers.typing import ConfigType, TemplateVarsType, VolSchemaType
from homeassistant.util import color as color_util
from .. import subscription
from ..config import MQTT_RW_SCHEMA
from ..const import (
CONF_BLUE_TEMPLATE,
CONF_BRIGHTNESS_TEMPLATE,
CONF_COLOR_TEMP_KELVIN,
CONF_COLOR_TEMP_TEMPLATE,
CONF_COMMAND_OFF_TEMPLATE,
CONF_COMMAND_ON_TEMPLATE,
CONF_COMMAND_TOPIC,
CONF_EFFECT_LIST,
CONF_EFFECT_TEMPLATE,
CONF_GREEN_TEMPLATE,
CONF_MAX_KELVIN,
CONF_MAX_MIREDS,
CONF_MIN_KELVIN,
CONF_MIN_MIREDS,
CONF_RED_TEMPLATE,
CONF_STATE_TOPIC,
PAYLOAD_NONE,
)
from ..entity import MqttEntity
from ..models import (
MqttCommandTemplate,
MqttValueTemplate,
PayloadSentinel,
PublishPayloadType,
ReceiveMessage,
)
from ..schemas import MQTT_ENTITY_COMMON_SCHEMA
from .schema import MQTT_LIGHT_SCHEMA_SCHEMA
from .schema_basic import MQTT_LIGHT_ATTRIBUTES_BLOCKED
_LOGGER = logging.getLogger(__name__)
DOMAIN = "mqtt_template"
DEFAULT_NAME = "MQTT Template Light"
COMMAND_TEMPLATES = (CONF_COMMAND_ON_TEMPLATE, CONF_COMMAND_OFF_TEMPLATE)
VALUE_TEMPLATES = (
CONF_BLUE_TEMPLATE,
CONF_BRIGHTNESS_TEMPLATE,
CONF_COLOR_TEMP_TEMPLATE,
CONF_EFFECT_TEMPLATE,
CONF_GREEN_TEMPLATE,
CONF_RED_TEMPLATE,
CONF_STATE_TEMPLATE,
)
PLATFORM_SCHEMA_MODERN_TEMPLATE = (
MQTT_RW_SCHEMA.extend(
{
probatio.Optional(CONF_BLUE_TEMPLATE): cv.template,
probatio.Optional(CONF_BRIGHTNESS_TEMPLATE): cv.template,
probatio.Optional(CONF_COLOR_TEMP_KELVIN, default=False): cv.boolean,
probatio.Optional(CONF_COLOR_TEMP_TEMPLATE): cv.template,
probatio.Required(CONF_COMMAND_OFF_TEMPLATE): cv.template,
probatio.Required(CONF_COMMAND_ON_TEMPLATE): cv.template,
probatio.Optional(CONF_EFFECT_LIST): probatio.All(
probatio.EnsureList(), [cv.string]
),
probatio.Optional(CONF_EFFECT_TEMPLATE): cv.template,
probatio.Optional(CONF_GREEN_TEMPLATE): cv.template,
probatio.Optional(CONF_MAX_KELVIN): cv.positive_int,
probatio.Optional(CONF_MIN_KELVIN): cv.positive_int,
probatio.Optional(CONF_MAX_MIREDS): cv.positive_int,
probatio.Optional(CONF_MIN_MIREDS): cv.positive_int,
probatio.Optional(CONF_NAME): probatio.Any(cv.string, None),
probatio.Optional(CONF_RED_TEMPLATE): cv.template,
probatio.Optional(CONF_STATE_TEMPLATE): cv.template,
}
)
.extend(MQTT_ENTITY_COMMON_SCHEMA.schema)
.extend(MQTT_LIGHT_SCHEMA_SCHEMA.schema)
)
DISCOVERY_SCHEMA_TEMPLATE = probatio.All(
PLATFORM_SCHEMA_MODERN_TEMPLATE.extend({}, extra=probatio.REMOVE_EXTRA),
)
class MqttLightTemplate(MqttEntity, LightEntity, RestoreEntity):
"""Representation of a MQTT Template light."""
_default_name = DEFAULT_NAME
_entity_id_format = ENTITY_ID_FORMAT
_attributes_extra_blocked = MQTT_LIGHT_ATTRIBUTES_BLOCKED
_optimistic: bool
_command_templates: dict[
str, Callable[[PublishPayloadType, TemplateVarsType], PublishPayloadType]
]
_value_templates: dict[
str, Callable[[ReceivePayloadType, ReceivePayloadType], ReceivePayloadType]
]
_fixed_color_mode: ColorMode | str | None
_topics: dict[str, str | None]
@staticmethod
@override
def config_schema() -> VolSchemaType:
"""Return the config schema."""
return DISCOVERY_SCHEMA_TEMPLATE
@override
def _setup_from_config(self, config: ConfigType) -> None:
"""(Re)Setup the entity."""
self._color_temp_kelvin = config[CONF_COLOR_TEMP_KELVIN]
self._attr_min_color_temp_kelvin = (
color_util.color_temperature_mired_to_kelvin(max_mireds)
if (max_mireds := config.get(CONF_MAX_MIREDS))
else config.get(CONF_MIN_KELVIN, DEFAULT_MIN_KELVIN)
)
self._attr_max_color_temp_kelvin = (
color_util.color_temperature_mired_to_kelvin(min_mireds)
if (min_mireds := config.get(CONF_MIN_MIREDS))
else config.get(CONF_MAX_KELVIN, DEFAULT_MAX_KELVIN)
)
self._attr_effect_list = config.get(CONF_EFFECT_LIST)
self._topics = {
key: config.get(key) for key in (CONF_STATE_TOPIC, CONF_COMMAND_TOPIC)
}
self._command_templates = {
key: MqttCommandTemplate(config[key], entity=self).async_render
for key in COMMAND_TEMPLATES
}
self._value_templates = {
key: MqttValueTemplate(
config.get(key), entity=self
).async_render_with_possible_json_value
for key in VALUE_TEMPLATES
}
optimistic: bool = config[CONF_OPTIMISTIC]
self._optimistic = (
optimistic
or self._topics[CONF_STATE_TOPIC] is None
or CONF_STATE_TEMPLATE not in self._config
)
self._attr_assumed_state = bool(self._optimistic)
color_modes = {ColorMode.ONOFF}
if CONF_BRIGHTNESS_TEMPLATE in config:
color_modes.add(ColorMode.BRIGHTNESS)
if CONF_COLOR_TEMP_TEMPLATE in config:
color_modes.add(ColorMode.COLOR_TEMP)
if (
CONF_RED_TEMPLATE in config
and CONF_GREEN_TEMPLATE in config
and CONF_BLUE_TEMPLATE in config
):
color_modes.add(ColorMode.HS)
self._attr_supported_color_modes = filter_supported_color_modes(color_modes)
self._fixed_color_mode = None
self._attr_color_mode = ColorMode.UNKNOWN
if self.supported_color_modes and len(self.supported_color_modes) == 1:
self._fixed_color_mode = next(iter(self.supported_color_modes))
self._attr_color_mode = self._fixed_color_mode
features = LightEntityFeature.FLASH | LightEntityFeature.TRANSITION
if config.get(CONF_EFFECT_LIST) is not None:
features = features | LightEntityFeature.EFFECT
self._attr_supported_features = features
def _update_color_mode(self) -> None:
"""Update the color_mode attribute."""
if self._fixed_color_mode:
return
# Support for ct + hs, prioritize hs
self._attr_color_mode = ColorMode.HS if self.hs_color else ColorMode.COLOR_TEMP
@callback
def _state_received(self, msg: ReceiveMessage) -> None:
"""Handle new MQTT messages."""
state_value = self._value_templates[CONF_STATE_TEMPLATE](
msg.payload,
PayloadSentinel.NONE,
)
if not state_value:
_LOGGER.debug(
"Ignoring message from '%s' with empty state value", msg.topic
)
elif state_value == STATE_ON:
self._attr_is_on = True
elif state_value == STATE_OFF:
self._attr_is_on = False
elif state_value == PAYLOAD_NONE:
self._attr_is_on = None
else:
_LOGGER.warning(
"Invalid state value '%s' received from %s",
state_value,
msg.topic,
)
if CONF_BRIGHTNESS_TEMPLATE in self._config:
brightness_value = self._value_templates[CONF_BRIGHTNESS_TEMPLATE](
msg.payload,
PayloadSentinel.NONE,
)
if not brightness_value:
_LOGGER.debug(
"Ignoring message from '%s' with empty brightness value",
msg.topic,
)
else:
try:
if brightness := int(brightness_value):
self._attr_brightness = brightness
else:
_LOGGER.debug(
"Ignoring zero brightness value for entity %s",
self.entity_id,
)
except ValueError:
_LOGGER.warning(
"Invalid brightness value '%s' received from %s",
brightness_value,
msg.topic,
)
if CONF_COLOR_TEMP_TEMPLATE in self._config:
color_temp_value = self._value_templates[CONF_COLOR_TEMP_TEMPLATE](
msg.payload,
PayloadSentinel.NONE,
)
if not color_temp_value:
_LOGGER.debug(
"Ignoring message from '%s' with empty color temperature value",
msg.topic,
)
else:
try:
self._attr_color_temp_kelvin = (
int(color_temp_value)
if self._color_temp_kelvin
else color_util.color_temperature_mired_to_kelvin(
int(color_temp_value)
)
if color_temp_value != "None"
else None
)
self._update_color_mode()
except ValueError:
_LOGGER.warning(
"Invalid color temperature value '%s' received from %s",
color_temp_value,
msg.topic,
)
if (
CONF_RED_TEMPLATE in self._config
and CONF_GREEN_TEMPLATE in self._config
and CONF_BLUE_TEMPLATE in self._config
):
red_value = self._value_templates[CONF_RED_TEMPLATE](
msg.payload,
PayloadSentinel.NONE,
)
green_value = self._value_templates[CONF_GREEN_TEMPLATE](
msg.payload,
PayloadSentinel.NONE,
)
blue_value = self._value_templates[CONF_BLUE_TEMPLATE](
msg.payload,
PayloadSentinel.NONE,
)
if not red_value or not green_value or not blue_value:
_LOGGER.debug(
"Ignoring message from '%s' with empty color value", msg.topic
)
elif red_value == "None" and green_value == "None" and blue_value == "None":
self._attr_hs_color = None
self._update_color_mode()
else:
try:
self._attr_hs_color = color_util.color_RGB_to_hs(
int(red_value), int(green_value), int(blue_value)
)
self._update_color_mode()
except ValueError:
_LOGGER.warning("Invalid color value received from %s", msg.topic)
if CONF_EFFECT_TEMPLATE in self._config:
effect_value = self._value_templates[CONF_EFFECT_TEMPLATE](
msg.payload,
PayloadSentinel.NONE,
)
if not effect_value:
_LOGGER.debug(
"Ignoring message from '%s' with empty effect value", msg.topic
)
elif (effect_list := self._config[CONF_EFFECT_LIST]) and str(
effect_value
) in effect_list:
self._attr_effect = str(effect_value)
else:
_LOGGER.warning(
"Unsupported effect value '%s' received from %s",
effect_value,
msg.topic,
)
@callback
@override
def _prepare_subscribe_topics(self) -> None:
"""(Re)Subscribe to topics."""
self.add_subscription(
CONF_STATE_TOPIC,
self._state_received,
{
"_attr_brightness",
"_attr_color_mode",
"_attr_color_temp_kelvin",
"_attr_effect",
"_attr_hs_color",
"_attr_is_on",
},
)
@override
async def _subscribe_topics(self) -> None:
"""(Re)Subscribe to topics."""
subscription.async_subscribe_topics_internal(self.hass, self._sub_state)
last_state = await self.async_get_last_state()
if self._optimistic and last_state:
self._attr_is_on = last_state.state == STATE_ON
if brightness := last_state.attributes.get(
LightEntityStateAttribute.BRIGHTNESS
):
self._attr_brightness = brightness
if hs_color := last_state.attributes.get(
LightEntityStateAttribute.HS_COLOR
):
self._attr_hs_color = hs_color
self._update_color_mode()
if color_temp_kelvin := last_state.attributes.get(
LightEntityStateAttribute.COLOR_TEMP_KELVIN
):
self._attr_color_temp_kelvin = color_temp_kelvin
if effect := last_state.attributes.get(LightEntityStateAttribute.EFFECT):
self._attr_effect = effect
@override
async def async_turn_on(self, **kwargs: Any) -> None:
"""Turn the entity on.
This method is a coroutine.
"""
values: dict[str, Any] = {"state": True}
if self._optimistic:
self._attr_is_on = True
if ATTR_BRIGHTNESS in kwargs:
values["brightness"] = int(kwargs[ATTR_BRIGHTNESS])
if self._optimistic:
self._attr_brightness = kwargs[ATTR_BRIGHTNESS]
if ATTR_COLOR_TEMP_KELVIN in kwargs:
values["color_temp"] = (
kwargs[ATTR_COLOR_TEMP_KELVIN]
if self._color_temp_kelvin
else color_util.color_temperature_kelvin_to_mired(
kwargs[ATTR_COLOR_TEMP_KELVIN]
)
)
if self._optimistic:
self._attr_color_temp_kelvin = kwargs[ATTR_COLOR_TEMP_KELVIN]
self._attr_hs_color = None
self._update_color_mode()
if ATTR_HS_COLOR in kwargs:
hs_color = kwargs[ATTR_HS_COLOR]
# If there's a brightness topic set, we don't want to scale the RGB
# values given using the brightness.
if CONF_BRIGHTNESS_TEMPLATE in self._config:
brightness = 255
else:
brightness = kwargs.get(
ATTR_BRIGHTNESS,
self._attr_brightness if self._attr_brightness is not None else 255,
)
rgb = color_util.color_hsv_to_RGB(
hs_color[0], hs_color[1], brightness / 255 * 100
)
values["red"] = rgb[0]
values["green"] = rgb[1]
values["blue"] = rgb[2]
values["hue"] = hs_color[0]
values["sat"] = hs_color[1]
if self._optimistic:
self._attr_color_temp_kelvin = None
self._attr_hs_color = kwargs[ATTR_HS_COLOR]
self._update_color_mode()
if ATTR_EFFECT in kwargs:
values["effect"] = kwargs.get(ATTR_EFFECT)
if self._optimistic:
self._attr_effect = kwargs[ATTR_EFFECT]
if ATTR_FLASH in kwargs:
values["flash"] = kwargs.get(ATTR_FLASH)
if ATTR_TRANSITION in kwargs:
values["transition"] = kwargs[ATTR_TRANSITION]
await self.async_publish_with_config(
str(self._topics[CONF_COMMAND_TOPIC]),
self._command_templates[CONF_COMMAND_ON_TEMPLATE](None, values),
)
if self._optimistic:
self.async_write_ha_state()
@override
async def async_turn_off(self, **kwargs: Any) -> None:
"""Turn the entity off.
This method is a coroutine.
"""
values: dict[str, Any] = {"state": False}
if self._optimistic:
self._attr_is_on = False
if ATTR_TRANSITION in kwargs:
values["transition"] = kwargs[ATTR_TRANSITION]
await self.async_publish_with_config(
str(self._topics[CONF_COMMAND_TOPIC]),
self._command_templates[CONF_COMMAND_OFF_TEMPLATE](None, values),
)
if self._optimistic:
self.async_write_ha_state()