Home Assistant Unofficial Reference 2024.12.1
schema_template.py
Go to the documentation of this file.
1 """Support for MQTT Template lights."""
2 
3 from __future__ import annotations
4 
5 from collections.abc import Callable
6 import logging
7 from typing import Any
8 
9 import voluptuous as vol
10 
12  ATTR_BRIGHTNESS,
13  ATTR_COLOR_TEMP,
14  ATTR_EFFECT,
15  ATTR_FLASH,
16  ATTR_HS_COLOR,
17  ATTR_TRANSITION,
18  ENTITY_ID_FORMAT,
19  ColorMode,
20  LightEntity,
21  LightEntityFeature,
22  filter_supported_color_modes,
23 )
24 from homeassistant.const import (
25  CONF_NAME,
26  CONF_OPTIMISTIC,
27  CONF_STATE_TEMPLATE,
28  STATE_OFF,
29  STATE_ON,
30 )
31 from homeassistant.core import callback
33 from homeassistant.helpers.restore_state import RestoreEntity
34 from homeassistant.helpers.service_info.mqtt import ReceivePayloadType
35 from homeassistant.helpers.typing import ConfigType, TemplateVarsType, VolSchemaType
36 import homeassistant.util.color as color_util
37 
38 from .. import subscription
39 from ..config import MQTT_RW_SCHEMA
40 from ..const import CONF_COMMAND_TOPIC, CONF_STATE_TOPIC, PAYLOAD_NONE
41 from ..entity import MqttEntity
42 from ..models import (
43  MqttCommandTemplate,
44  MqttValueTemplate,
45  PublishPayloadType,
46  ReceiveMessage,
47 )
48 from ..schemas import MQTT_ENTITY_COMMON_SCHEMA
49 from .schema import MQTT_LIGHT_SCHEMA_SCHEMA
50 from .schema_basic import MQTT_LIGHT_ATTRIBUTES_BLOCKED
51 
52 _LOGGER = logging.getLogger(__name__)
53 
54 DOMAIN = "mqtt_template"
55 
56 DEFAULT_NAME = "MQTT Template Light"
57 
58 CONF_BLUE_TEMPLATE = "blue_template"
59 CONF_BRIGHTNESS_TEMPLATE = "brightness_template"
60 CONF_COLOR_TEMP_TEMPLATE = "color_temp_template"
61 CONF_COMMAND_OFF_TEMPLATE = "command_off_template"
62 CONF_COMMAND_ON_TEMPLATE = "command_on_template"
63 CONF_EFFECT_LIST = "effect_list"
64 CONF_EFFECT_TEMPLATE = "effect_template"
65 CONF_GREEN_TEMPLATE = "green_template"
66 CONF_MAX_MIREDS = "max_mireds"
67 CONF_MIN_MIREDS = "min_mireds"
68 CONF_RED_TEMPLATE = "red_template"
69 
70 COMMAND_TEMPLATES = (CONF_COMMAND_ON_TEMPLATE, CONF_COMMAND_OFF_TEMPLATE)
71 VALUE_TEMPLATES = (
72  CONF_BLUE_TEMPLATE,
73  CONF_BRIGHTNESS_TEMPLATE,
74  CONF_COLOR_TEMP_TEMPLATE,
75  CONF_EFFECT_TEMPLATE,
76  CONF_GREEN_TEMPLATE,
77  CONF_RED_TEMPLATE,
78  CONF_STATE_TEMPLATE,
79 )
80 
81 PLATFORM_SCHEMA_MODERN_TEMPLATE = (
82  MQTT_RW_SCHEMA.extend(
83  {
84  vol.Optional(CONF_BLUE_TEMPLATE): cv.template,
85  vol.Optional(CONF_BRIGHTNESS_TEMPLATE): cv.template,
86  vol.Optional(CONF_COLOR_TEMP_TEMPLATE): cv.template,
87  vol.Required(CONF_COMMAND_OFF_TEMPLATE): cv.template,
88  vol.Required(CONF_COMMAND_ON_TEMPLATE): cv.template,
89  vol.Optional(CONF_EFFECT_LIST): vol.All(cv.ensure_list, [cv.string]),
90  vol.Optional(CONF_EFFECT_TEMPLATE): cv.template,
91  vol.Optional(CONF_GREEN_TEMPLATE): cv.template,
92  vol.Optional(CONF_MAX_MIREDS): cv.positive_int,
93  vol.Optional(CONF_MIN_MIREDS): cv.positive_int,
94  vol.Optional(CONF_NAME): vol.Any(cv.string, None),
95  vol.Optional(CONF_RED_TEMPLATE): cv.template,
96  vol.Optional(CONF_STATE_TEMPLATE): cv.template,
97  }
98  )
99  .extend(MQTT_ENTITY_COMMON_SCHEMA.schema)
100  .extend(MQTT_LIGHT_SCHEMA_SCHEMA.schema)
101 )
102 
103 DISCOVERY_SCHEMA_TEMPLATE = vol.All(
104  PLATFORM_SCHEMA_MODERN_TEMPLATE.extend({}, extra=vol.REMOVE_EXTRA),
105 )
106 
107 
109  """Representation of a MQTT Template light."""
110 
111  _default_name = DEFAULT_NAME
112  _entity_id_format = ENTITY_ID_FORMAT
113  _attributes_extra_blocked = MQTT_LIGHT_ATTRIBUTES_BLOCKED
114  _optimistic: bool
115  _command_templates: dict[
116  str, Callable[[PublishPayloadType, TemplateVarsType], PublishPayloadType]
117  ]
118  _value_templates: dict[str, Callable[[ReceivePayloadType], ReceivePayloadType]]
119  _fixed_color_mode: ColorMode | str | None
120  _topics: dict[str, str | None]
121 
122  @staticmethod
123  def config_schema() -> VolSchemaType:
124  """Return the config schema."""
125  return DISCOVERY_SCHEMA_TEMPLATE
126 
127  def _setup_from_config(self, config: ConfigType) -> None:
128  """(Re)Setup the entity."""
129  self._attr_max_mireds_attr_max_mireds = config.get(CONF_MAX_MIREDS, super().max_mireds)
130  self._attr_min_mireds_attr_min_mireds = config.get(CONF_MIN_MIREDS, super().min_mireds)
131  self._attr_effect_list_attr_effect_list = config.get(CONF_EFFECT_LIST)
132 
133  self._topics_topics = {
134  key: config.get(key) for key in (CONF_STATE_TOPIC, CONF_COMMAND_TOPIC)
135  }
136  self._command_templates_command_templates = {
137  key: MqttCommandTemplate(config[key], entity=self).async_render
138  for key in COMMAND_TEMPLATES
139  }
140  self._value_templates_value_templates = {
141  key: MqttValueTemplate(
142  config.get(key), entity=self
143  ).async_render_with_possible_json_value
144  for key in VALUE_TEMPLATES
145  }
146  optimistic: bool = config[CONF_OPTIMISTIC]
147  self._optimistic_optimistic = (
148  optimistic
149  or self._topics_topics[CONF_STATE_TOPIC] is None
150  or CONF_STATE_TEMPLATE not in self._config_config
151  )
152  self._attr_assumed_state_attr_assumed_state = bool(self._optimistic_optimistic)
153 
154  color_modes = {ColorMode.ONOFF}
155  if CONF_BRIGHTNESS_TEMPLATE in config:
156  color_modes.add(ColorMode.BRIGHTNESS)
157  if CONF_COLOR_TEMP_TEMPLATE in config:
158  color_modes.add(ColorMode.COLOR_TEMP)
159  if (
160  CONF_RED_TEMPLATE in config
161  and CONF_GREEN_TEMPLATE in config
162  and CONF_BLUE_TEMPLATE in config
163  ):
164  color_modes.add(ColorMode.HS)
165  self._attr_supported_color_modes_attr_supported_color_modes = filter_supported_color_modes(color_modes)
166  self._fixed_color_mode_fixed_color_mode = None
167  if self.supported_color_modessupported_color_modes and len(self.supported_color_modessupported_color_modes) == 1:
168  self._fixed_color_mode_fixed_color_mode = next(iter(self.supported_color_modessupported_color_modes))
169  self._attr_color_mode_attr_color_mode = self._fixed_color_mode_fixed_color_mode
170 
171  features = LightEntityFeature.FLASH | LightEntityFeature.TRANSITION
172  if config.get(CONF_EFFECT_LIST) is not None:
173  features = features | LightEntityFeature.EFFECT
174  self._attr_supported_features_attr_supported_features = features
175 
176  def _update_color_mode(self) -> None:
177  """Update the color_mode attribute."""
178  if self._fixed_color_mode_fixed_color_mode:
179  return
180  # Support for ct + hs, prioritize hs
181  self._attr_color_mode_attr_color_mode = ColorMode.HS if self.hs_colorhs_color else ColorMode.COLOR_TEMP
182 
183  @callback
184  def _state_received(self, msg: ReceiveMessage) -> None:
185  """Handle new MQTT messages."""
186  state = self._value_templates_value_templates[CONF_STATE_TEMPLATE](msg.payload)
187  if state == STATE_ON:
188  self._attr_is_on_attr_is_on = True
189  elif state == STATE_OFF:
190  self._attr_is_on_attr_is_on = False
191  elif state == PAYLOAD_NONE:
192  self._attr_is_on_attr_is_on = None
193  else:
194  _LOGGER.warning("Invalid state value received")
195 
196  if CONF_BRIGHTNESS_TEMPLATE in self._config_config:
197  try:
198  if brightness := int(
199  self._value_templates_value_templates[CONF_BRIGHTNESS_TEMPLATE](msg.payload)
200  ):
201  self._attr_brightness_attr_brightness = brightness
202  else:
203  _LOGGER.debug(
204  "Ignoring zero brightness value for entity %s",
205  self.entity_identity_id,
206  )
207 
208  except ValueError:
209  _LOGGER.warning("Invalid brightness value received from %s", msg.topic)
210 
211  if CONF_COLOR_TEMP_TEMPLATE in self._config_config:
212  try:
213  color_temp = self._value_templates_value_templates[CONF_COLOR_TEMP_TEMPLATE](
214  msg.payload
215  )
216  self._attr_color_temp_attr_color_temp = (
217  int(color_temp) if color_temp != "None" else None
218  )
219  except ValueError:
220  _LOGGER.warning("Invalid color temperature value received")
221 
222  if (
223  CONF_RED_TEMPLATE in self._config_config
224  and CONF_GREEN_TEMPLATE in self._config_config
225  and CONF_BLUE_TEMPLATE in self._config_config
226  ):
227  try:
228  red = self._value_templates_value_templates[CONF_RED_TEMPLATE](msg.payload)
229  green = self._value_templates_value_templates[CONF_GREEN_TEMPLATE](msg.payload)
230  blue = self._value_templates_value_templates[CONF_BLUE_TEMPLATE](msg.payload)
231  if red == "None" and green == "None" and blue == "None":
232  self._attr_hs_color_attr_hs_color = None
233  else:
234  self._attr_hs_color_attr_hs_color = color_util.color_RGB_to_hs(
235  int(red), int(green), int(blue)
236  )
237  self._update_color_mode_update_color_mode()
238  except ValueError:
239  _LOGGER.warning("Invalid color value received")
240 
241  if CONF_EFFECT_TEMPLATE in self._config_config:
242  effect = str(self._value_templates_value_templates[CONF_EFFECT_TEMPLATE](msg.payload))
243  if (
244  effect_list := self._config_config[CONF_EFFECT_LIST]
245  ) and effect in effect_list:
246  self._attr_effect_attr_effect = effect
247  else:
248  _LOGGER.warning("Unsupported effect value received")
249 
250  @callback
251  def _prepare_subscribe_topics(self) -> None:
252  """(Re)Subscribe to topics."""
253  self.add_subscriptionadd_subscription(
254  CONF_STATE_TOPIC,
255  self._state_received_state_received,
256  {
257  "_attr_brightness",
258  "_attr_color_mode",
259  "_attr_color_temp",
260  "_attr_effect",
261  "_attr_hs_color",
262  "_attr_is_on",
263  },
264  )
265 
266  async def _subscribe_topics(self) -> None:
267  """(Re)Subscribe to topics."""
268  subscription.async_subscribe_topics_internal(self.hasshasshass, self._sub_state_sub_state)
269 
270  last_state = await self.async_get_last_stateasync_get_last_state()
271  if self._optimistic_optimistic and last_state:
272  self._attr_is_on_attr_is_on = last_state.state == STATE_ON
273  if last_state.attributes.get(ATTR_BRIGHTNESS):
274  self._attr_brightness_attr_brightness = last_state.attributes.get(ATTR_BRIGHTNESS)
275  if last_state.attributes.get(ATTR_HS_COLOR):
276  self._attr_hs_color_attr_hs_color = last_state.attributes.get(ATTR_HS_COLOR)
277  self._update_color_mode_update_color_mode()
278  if last_state.attributes.get(ATTR_COLOR_TEMP):
279  self._attr_color_temp_attr_color_temp = last_state.attributes.get(ATTR_COLOR_TEMP)
280  if last_state.attributes.get(ATTR_EFFECT):
281  self._attr_effect_attr_effect = last_state.attributes.get(ATTR_EFFECT)
282 
283  async def async_turn_on(self, **kwargs: Any) -> None:
284  """Turn the entity on.
285 
286  This method is a coroutine.
287  """
288  values: dict[str, Any] = {"state": True}
289  if self._optimistic_optimistic:
290  self._attr_is_on_attr_is_on = True
291 
292  if ATTR_BRIGHTNESS in kwargs:
293  values["brightness"] = int(kwargs[ATTR_BRIGHTNESS])
294 
295  if self._optimistic_optimistic:
296  self._attr_brightness_attr_brightness = kwargs[ATTR_BRIGHTNESS]
297 
298  if ATTR_COLOR_TEMP in kwargs:
299  values["color_temp"] = int(kwargs[ATTR_COLOR_TEMP])
300 
301  if self._optimistic_optimistic:
302  self._attr_color_temp_attr_color_temp = kwargs[ATTR_COLOR_TEMP]
303  self._attr_hs_color_attr_hs_color = None
304  self._update_color_mode_update_color_mode()
305 
306  if ATTR_HS_COLOR in kwargs:
307  hs_color = kwargs[ATTR_HS_COLOR]
308 
309  # If there's a brightness topic set, we don't want to scale the RGB
310  # values given using the brightness.
311  if CONF_BRIGHTNESS_TEMPLATE in self._config_config:
312  brightness = 255
313  else:
314  brightness = kwargs.get(
315  ATTR_BRIGHTNESS,
316  self._attr_brightness_attr_brightness if self._attr_brightness_attr_brightness is not None else 255,
317  )
318  rgb = color_util.color_hsv_to_RGB(
319  hs_color[0], hs_color[1], brightness / 255 * 100
320  )
321  values["red"] = rgb[0]
322  values["green"] = rgb[1]
323  values["blue"] = rgb[2]
324  values["hue"] = hs_color[0]
325  values["sat"] = hs_color[1]
326 
327  if self._optimistic_optimistic:
328  self._attr_color_temp_attr_color_temp = None
329  self._attr_hs_color_attr_hs_color = kwargs[ATTR_HS_COLOR]
330  self._update_color_mode_update_color_mode()
331 
332  if ATTR_EFFECT in kwargs:
333  values["effect"] = kwargs.get(ATTR_EFFECT)
334 
335  if self._optimistic_optimistic:
336  self._attr_effect_attr_effect = kwargs[ATTR_EFFECT]
337 
338  if ATTR_FLASH in kwargs:
339  values["flash"] = kwargs.get(ATTR_FLASH)
340 
341  if ATTR_TRANSITION in kwargs:
342  values["transition"] = kwargs[ATTR_TRANSITION]
343 
344  await self.async_publish_with_configasync_publish_with_config(
345  str(self._topics_topics[CONF_COMMAND_TOPIC]),
346  self._command_templates_command_templates[CONF_COMMAND_ON_TEMPLATE](None, values),
347  )
348 
349  if self._optimistic_optimistic:
350  self.async_write_ha_stateasync_write_ha_state()
351 
352  async def async_turn_off(self, **kwargs: Any) -> None:
353  """Turn the entity off.
354 
355  This method is a coroutine.
356  """
357  values: dict[str, Any] = {"state": False}
358  if self._optimistic_optimistic:
359  self._attr_is_on_attr_is_on = False
360 
361  if ATTR_TRANSITION in kwargs:
362  values["transition"] = kwargs[ATTR_TRANSITION]
363 
364  await self.async_publish_with_configasync_publish_with_config(
365  str(self._topics_topics[CONF_COMMAND_TOPIC]),
366  self._command_templates_command_templates[CONF_COMMAND_OFF_TEMPLATE](None, values),
367  )
368 
369  if self._optimistic_optimistic:
370  self.async_write_ha_stateasync_write_ha_state()
set[ColorMode]|set[str]|None supported_color_modes(self)
Definition: __init__.py:1302
tuple[float, float]|None hs_color(self)
Definition: __init__.py:947
None async_publish_with_config(self, str topic, PublishPayloadType payload)
Definition: entity.py:1377
bool add_subscription(self, str state_topic_config_key, Callable[[ReceiveMessage], None] msg_callback, set[str]|None tracked_attributes, bool disable_encoding=False)
Definition: entity.py:1484
set[ColorMode] filter_supported_color_modes(Iterable[ColorMode] color_modes)
Definition: __init__.py:122