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
+34
View File
@@ -0,0 +1,34 @@
# Visquitto MQTT
A custom Home Assistant MQTT integration based on the official Home Assistant MQTT integration.
Visquitto MQTT provides a separate MQTT integration under the `vmqtt` domain, allowing it to coexist with the official MQTT integration.
## Installation
Copy the `custom_components/vmqtt` directory into your Home Assistant configuration directory:
```text
/config/custom_components/vmqtt/
```
Restart Home Assistant.
Then go to **Settings → Devices & services → Add integration** and search for **Visquitto MQTT**.
## Updates
Updates are published as versioned releases.
## Upstream
This integration is derived from the official Home Assistant MQTT integration:
https://github.com/home-assistant/core/tree/dev/homeassistant/components/mqtt
The project maintains its own modifications while periodically incorporating upstream changes.
## License
Based on Home Assistant Core. See the accompanying license information.
+13
View File
@@ -0,0 +1,13 @@
# Multi MQTT
A separate custom integration based on the Home Assistant Core MQTT integration source from Core 2026.10.4.
- Integration domain: `vmqtt`
- One broker connection / one config entry
- Keeps the upstream MQTT entity platforms and discovery implementation
- Uses an independent client, data keys, services, websocket command namespace, and trigger platform identity
- MQTT protocol discovery prefix remains `homeassistant` by default; it is independent from the integration domain
This is an initial port, not yet runtime-validated inside Home Assistant. Install under `custom_components/vmqtt`, restart Home Assistant, then add **Multi MQTT** from Settings → Devices & services.
Source base: Home Assistant Core 2026.10.4, MQTT integration. Home Assistant Core is licensed under Apache License 2.0; retain applicable notices and license terms when redistributing.
+739
View File
@@ -0,0 +1,739 @@
"""Support for MQTT message handling."""
import asyncio
from collections.abc import Callable
from datetime import datetime
import logging
from typing import Any, cast
import probatio
from homeassistant import config as conf_util
from homeassistant.components import websocket_api
from homeassistant.config_entries import ConfigEntry
from homeassistant.const import (
CONF_DISCOVERY,
CONF_PLATFORM,
CONF_PORT,
CONF_PROTOCOL,
SERVICE_RELOAD,
)
from homeassistant.core import HomeAssistant, ServiceCall, callback
from homeassistant.exceptions import (
ConfigValidationError,
ServiceValidationError,
Unauthorized,
)
from homeassistant.helpers import (
config_validation as cv,
entity_registry as er,
event as ev,
issue_registry as ir,
)
from homeassistant.helpers.device_registry import AnyDeviceEntry
from homeassistant.helpers.dispatcher import async_dispatcher_connect
from homeassistant.helpers.entity_platform import async_get_platforms
from homeassistant.helpers.issue_registry import IssueSeverity, async_create_issue
from homeassistant.helpers.reload import async_integration_yaml_config
from homeassistant.helpers.service import async_register_admin_service
from homeassistant.helpers.typing import ConfigType
from homeassistant.loader import async_get_integration, async_get_loaded_integration
from homeassistant.setup import SetupPhases, async_pause_setup
from homeassistant.util.async_ import create_eager_task
# Loading the config flow file will register the flow
from . import debug_info, discovery
from .client import (
MQTT,
async_on_subscribe_done,
async_publish,
async_subscribe,
async_subscribe_internal,
publish,
subscribe,
try_connection,
)
from .config import MQTT_BASE_SCHEMA, MQTT_RO_SCHEMA, MQTT_RW_SCHEMA
from .config_integration import CONFIG_SCHEMA_BASE
from .const import (
ATTR_MESSAGE_EXPIRY_INTERVAL,
ATTR_PAYLOAD,
ATTR_QOS,
ATTR_RETAIN,
ATTR_TOPIC,
CONF_BIRTH_MESSAGE,
CONF_BROKER,
CONF_CERTIFICATE,
CONF_CLIENT_CERT,
CONF_CLIENT_KEY,
CONF_COMMAND_TOPIC,
CONF_DISCOVERY_PREFIX,
CONF_KEEPALIVE,
CONF_QOS,
CONF_STATE_TOPIC,
CONF_TLS_INSECURE,
CONF_TOPIC,
CONF_TRANSPORT,
CONF_WILL_MESSAGE,
CONF_WS_HEADERS,
CONF_WS_PATH,
CONFIG_ENTRY_MINOR_VERSION,
CONFIG_ENTRY_VERSION,
DEFAULT_DISCOVERY,
DEFAULT_ENCODING,
DEFAULT_PORT,
DEFAULT_PREFIX,
DEFAULT_QOS,
DEFAULT_RETAIN,
DOMAIN,
ENTITY_PLATFORMS,
MQTT_CONNECTION_STATE,
PROTOCOL_5,
PROTOCOL_311,
TEMPLATE_ERRORS,
Platform,
)
from .models import (
DATA_MQTT,
DATA_MQTT_AVAILABLE,
MqttCommandTemplate,
MqttData,
MqttValueTemplate,
PayloadSentinel,
PublishPayloadType,
ReceiveMessage,
convert_outgoing_mqtt_payload,
)
from .subscription import (
EntitySubscription,
async_prepare_subscribe_topics,
async_subscribe_topics,
async_unsubscribe_topics,
)
from .util import (
async_create_certificate_temp_files,
async_forward_entry_setup_and_setup_discovery,
async_wait_for_mqtt_client,
mqtt_config_entry_enabled,
platforms_from_config,
valid_publish_topic,
valid_qos_schema,
valid_subscribe_topic,
)
__all__ = [
"ATTR_PAYLOAD",
"ATTR_QOS",
"ATTR_RETAIN",
"ATTR_TOPIC",
"CONFIG_ENTRY_MINOR_VERSION",
"CONFIG_ENTRY_VERSION",
"CONF_BIRTH_MESSAGE",
"CONF_BROKER",
"CONF_CERTIFICATE",
"CONF_CLIENT_CERT",
"CONF_CLIENT_KEY",
"CONF_COMMAND_TOPIC",
"CONF_DISCOVERY_PREFIX",
"CONF_KEEPALIVE",
"CONF_QOS",
"CONF_STATE_TOPIC",
"CONF_TLS_INSECURE",
"CONF_TOPIC",
"CONF_TRANSPORT",
"CONF_WILL_MESSAGE",
"CONF_WS_HEADERS",
"CONF_WS_PATH",
"DATA_MQTT",
"DATA_MQTT_AVAILABLE",
"DEFAULT_DISCOVERY",
"DEFAULT_ENCODING",
"DEFAULT_PREFIX",
"DEFAULT_QOS",
"DEFAULT_RETAIN",
"DOMAIN",
"ENTITY_PLATFORMS",
"MQTT",
"MQTT_BASE_SCHEMA",
"MQTT_CONNECTION_STATE",
"MQTT_RO_SCHEMA",
"MQTT_RW_SCHEMA",
"SERVICE_RELOAD",
"TEMPLATE_ERRORS",
"EntitySubscription",
"MqttCommandTemplate",
"MqttData",
"MqttValueTemplate",
"PayloadSentinel",
"PublishPayloadType",
"ReceiveMessage",
"SetupPhases",
"async_check_config_schema",
"async_create_certificate_temp_files",
"async_forward_entry_setup_and_setup_discovery",
"async_migrate_entry",
"async_on_subscribe_done",
"async_prepare_subscribe_topics",
"async_publish",
"async_remove_config_entry_device",
"async_subscribe",
"async_subscribe_connection_status",
"async_subscribe_topics",
"async_unsubscribe_topics",
"async_wait_for_mqtt_client",
"convert_outgoing_mqtt_payload",
"create_eager_task",
"is_connected",
"mqtt_config_entry_enabled",
"platforms_from_config",
"publish",
"subscribe",
"valid_publish_topic",
"valid_qos_schema",
"valid_subscribe_topic",
"websocket_mqtt_info",
"websocket_subscribe",
]
_LOGGER = logging.getLogger(__name__)
SERVICE_PUBLISH = "publish"
SERVICE_DUMP = "dump"
ATTR_EVALUATE_PAYLOAD = "evaluate_payload"
MAX_RECONNECT_WAIT = 300 # seconds
CONNECTION_SUCCESS = "connection_success"
CONNECTION_FAILED = "connection_failed"
CONNECTION_FAILED_RECOVERABLE = "connection_failed_recoverable"
# We accept 2 schemes for configuring manual MQTT items
#
# Preferred style:
#
# mqtt:
# - {domain}:
# name: ""
# ...
# - {domain}:
# name: ""
# ...
# ```
#
# Legacy supported style:
#
# mqtt:
# {domain}:
# - name: ""
# ...
# - name: ""
# ...
CONFIG_SCHEMA = probatio.Schema(
{
DOMAIN: probatio.All(
probatio.EnsureList(),
cv.remove_falsy,
[CONFIG_SCHEMA_BASE],
)
},
extra=probatio.ALLOW_EXTRA,
)
# Publish action call validation schema
MQTT_PUBLISH_SCHEMA = probatio.Schema(
{
probatio.Required(ATTR_TOPIC): valid_publish_topic,
probatio.Required(ATTR_PAYLOAD, default=None): probatio.Any(cv.string, None),
probatio.Optional(ATTR_EVALUATE_PAYLOAD): cv.boolean,
probatio.Optional(ATTR_QOS, default=DEFAULT_QOS): valid_qos_schema,
probatio.Optional(ATTR_RETAIN, default=DEFAULT_RETAIN): cv.boolean,
probatio.Optional(ATTR_MESSAGE_EXPIRY_INTERVAL): cv.positive_time_period_dict,
},
required=True,
)
async def _async_config_entry_updated(hass: HomeAssistant, entry: ConfigEntry) -> None:
"""Handle signals of config entry being updated.
Causes for this is config entry options changing.
"""
hass.config_entries.async_schedule_reload(entry.entry_id)
@callback
def _async_remove_mqtt_issues(hass: HomeAssistant, mqtt_data: MqttData) -> None:
"""Unregister open config issues."""
issue_registry = ir.async_get(hass)
open_issues = [
issue_id
for (domain, issue_id), issue_entry in issue_registry.issues.items()
if domain == DOMAIN and issue_entry.translation_key == "invalid_platform_config"
]
for issue in open_issues:
ir.async_delete_issue(hass, DOMAIN, issue)
async def async_check_config_schema(
hass: HomeAssistant, config_yaml: ConfigType
) -> None:
"""Validate manually configured MQTT items."""
mqtt_data = hass.data[DATA_MQTT]
mqtt_config: list[dict[str, list[ConfigType]]] = config_yaml.get(DOMAIN, {})
for mqtt_config_item in mqtt_config:
for domain, config_items in mqtt_config_item.items():
schema = mqtt_data.reload_schema[domain]
for config in config_items:
try:
schema(config)
except probatio.Invalid as exc:
integration = await async_get_integration(hass, DOMAIN)
message = conf_util.format_schema_error(
hass, exc, domain, config, integration.documentation
)
raise ServiceValidationError(
translation_domain=DOMAIN,
translation_key="invalid_platform_config_message",
translation_placeholders={
"domain": domain,
"message": message,
},
) from exc
def _platforms_in_use(hass: HomeAssistant, entry: ConfigEntry) -> set[str | Platform]:
"""Return a set of platforms in use."""
domains: set[str | Platform] = {
entry.domain
for entry in er.async_entries_for_config_entry(
er.async_get(hass), entry.entry_id
)
}
# Update with domains from subentries
for subentry in entry.subentries.values():
components = subentry.data["components"].values()
domains.update(component[CONF_PLATFORM] for component in components)
return domains
async def async_setup(hass: HomeAssistant, config: ConfigType) -> bool:
"""Set up the actions and websocket API for the MQTT component."""
if config.get(DOMAIN) and not mqtt_config_entry_enabled(hass):
issue_registry = ir.async_get(hass)
issue_registry.async_get_or_create(
DOMAIN,
"yaml_setup_without_active_setup",
is_fixable=False,
is_persistent=False,
severity=ir.IssueSeverity.WARNING,
learn_more_url="https://www.home-assistant.io/integrations/mqtt/"
"#configuration",
translation_key="yaml_setup_without_active_setup",
)
websocket_api.async_register_command(hass, websocket_subscribe)
websocket_api.async_register_command(hass, websocket_mqtt_info)
async def async_publish_service(call: ServiceCall) -> None:
"""Handle MQTT publish service calls."""
msg_topic: str = call.data[ATTR_TOPIC]
if not mqtt_config_entry_enabled(hass):
raise ServiceValidationError(
translation_key="mqtt_not_setup_cannot_publish",
translation_domain=DOMAIN,
translation_placeholders={"topic": msg_topic},
)
mqtt_data = hass.data[DATA_MQTT]
payload: PublishPayloadType = call.data[ATTR_PAYLOAD]
evaluate_payload: bool = call.data.get(ATTR_EVALUATE_PAYLOAD, False)
qos: int = call.data[ATTR_QOS]
retain: bool = call.data[ATTR_RETAIN]
message_expiry_interval: int | None = (
int(call.data[ATTR_MESSAGE_EXPIRY_INTERVAL].total_seconds())
if ATTR_MESSAGE_EXPIRY_INTERVAL in call.data
else None
)
if evaluate_payload:
# Convert quoted binary literal to raw data
payload = convert_outgoing_mqtt_payload(payload)
await mqtt_data.client.async_publish(
msg_topic,
payload,
qos,
retain,
message_expiry_interval=message_expiry_interval,
)
async_register_admin_service(
hass, DOMAIN, SERVICE_PUBLISH, async_publish_service, MQTT_PUBLISH_SCHEMA
)
async def async_dump_service(call: ServiceCall) -> None:
"""Handle MQTT dump service calls."""
messages: list[tuple[str, str]] = []
@callback
def collect_msg(msg: ReceiveMessage) -> None:
messages.append((msg.topic, str(msg.payload).replace("\n", "")))
unsub = async_subscribe_internal(hass, call.data["topic"], collect_msg)
def write_dump() -> None:
with open(hass.config.path("vmqtt_dump.txt"), "w", encoding="utf8") as fp:
fp.writelines([",".join(msg) + "\n" for msg in messages])
async def finish_dump(_: datetime) -> None:
"""Write dump to file."""
unsub()
await hass.async_add_executor_job(write_dump)
ev.async_call_later(hass, call.data["duration"], finish_dump)
async_register_admin_service(
hass,
DOMAIN,
SERVICE_DUMP,
async_dump_service,
schema=probatio.Schema(
{
probatio.Required("topic"): valid_subscribe_topic,
probatio.Optional("duration", default=5): int,
}
),
)
async def _reload_config(call: ServiceCall) -> None:
"""Reload the platforms."""
if not mqtt_config_entry_enabled(hass):
_LOGGER.debug(
"Skipped reloading MQTT integration, "
"the MQTT config entry is not enabled"
)
return
entry: ConfigEntry = next(iter(hass.config_entries.async_entries(DOMAIN)))
mqtt_data = hass.data[DATA_MQTT]
# Fetch updated manually configured items and validate
try:
config_yaml = await async_integration_yaml_config(
hass, DOMAIN, raise_on_failure=True
)
except ConfigValidationError as ex:
raise ServiceValidationError(
translation_domain=ex.translation_domain,
translation_key=ex.translation_key,
translation_placeholders=ex.translation_placeholders,
) from ex
new_config: list[ConfigType] = config_yaml.get(DOMAIN, [])
platforms_used = platforms_from_config(new_config)
new_platforms = platforms_used - mqtt_data.platforms_loaded
await async_forward_entry_setup_and_setup_discovery(hass, entry, new_platforms)
# Check the schema before continuing reload
await async_check_config_schema(hass, config_yaml)
# Remove repair issues
_async_remove_mqtt_issues(hass, mqtt_data)
mqtt_data.config = new_config
# Reload the modern yaml platforms
mqtt_platforms = async_get_platforms(hass, DOMAIN)
tasks = [
create_eager_task(entity.async_remove())
for mqtt_platform in mqtt_platforms
for entity in list(mqtt_platform.entities.values())
if getattr(entity, "_discovery_data", None) is None
and mqtt_platform.config_entry
and mqtt_platform.domain in ENTITY_PLATFORMS
]
await asyncio.gather(*tasks)
for component in mqtt_data.reload_handlers.values():
component()
# Fire event
hass.bus.async_fire(f"event_{DOMAIN}_reloaded", context=call.context)
async_register_admin_service(hass, DOMAIN, SERVICE_RELOAD, _reload_config)
return True
async def async_migrate_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
"""Migrate the config entry to the latest version."""
_LOGGER.debug("Migrating from version %s.%s", entry.version, entry.minor_version)
data: dict[str, Any] = dict(entry.data)
options: dict[str, Any] = dict(entry.options)
if entry.version == 1 and entry.minor_version < 2:
for key in (
CONF_DISCOVERY,
CONF_DISCOVERY_PREFIX,
"birth_message",
"will_message",
):
if key not in data:
continue
options[key] = data.pop(key)
# Bump config entry to version 2.1
hass.config_entries.async_update_entry(
entry,
data=data,
options=options,
version=2,
minor_version=1,
)
_LOGGER.debug(
"Migration to version %s.%s successful", entry.version, entry.minor_version
)
return True
async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
"""Load a config entry."""
mqtt_data: MqttData
if (protocol := entry.data.get(CONF_PROTOCOL, PROTOCOL_311)) != PROTOCOL_5:
# Automatically migrate the broker protocol to v5 if possible
# Can be removed with HA Core 2027.1
new_entry_data = entry.data.copy()
new_entry_data[CONF_PROTOCOL] = PROTOCOL_5
# Create temporary certificate files from entry
await async_create_certificate_temp_files(hass, new_entry_data)
# Try the connection with protocol version 5
# And update the protocol if successful
if await hass.async_add_executor_job(
try_connection,
{CONF_PORT: DEFAULT_PORT} | new_entry_data,
):
hass.config_entries.async_update_entry(
entry,
data=new_entry_data,
)
ir.async_delete_issue(hass, DOMAIN, "protocol_5_migration")
_LOGGER.info(
"The MQTT protocol version was successfully updated to version 5"
)
else:
broker: str = entry.data[CONF_BROKER]
async_create_issue(
hass,
DOMAIN,
"protocol_5_migration",
issue_domain=DOMAIN,
is_fixable=False,
breaks_in_ha_version="2027.1.0",
severity=IssueSeverity.WARNING,
learn_more_url="https://www.home-assistant.io/integrations/mqtt/"
"#mqtt-protocol",
data={
"entry_id": entry.entry_id,
"broker": broker,
"protocol": protocol,
},
translation_placeholders={"broker": broker, "protocol": protocol},
translation_key="protocol_5_migration",
)
async def _setup_client() -> tuple[MqttData, dict[str, Any]]:
"""Set up the MQTT client."""
# Fetch configuration
conf = dict(entry.data | entry.options)
hass_config = await conf_util.async_hass_config_yaml(hass)
mqtt_yaml = CONFIG_SCHEMA(hass_config).get(DOMAIN, [])
await async_create_certificate_temp_files(hass, conf)
client = MQTT(hass, entry, conf)
if DOMAIN in hass.data:
mqtt_data = hass.data[DATA_MQTT]
mqtt_data.config = mqtt_yaml
mqtt_data.client = client
else:
# Initial setup
hass.data[DATA_MQTT] = mqtt_data = MqttData(config=mqtt_yaml, client=client)
await client.async_start(mqtt_data)
# Restore saved subscriptions
if mqtt_data.subscriptions_to_restore:
mqtt_data.client.async_restore_tracked_subscriptions(
mqtt_data.subscriptions_to_restore
)
mqtt_data.subscriptions_to_restore = set()
mqtt_data.reload_dispatchers.append(
entry.add_update_listener(_async_config_entry_updated)
)
return (mqtt_data, conf)
client_available: asyncio.Future[bool]
if DATA_MQTT_AVAILABLE not in hass.data:
client_available = hass.data[DATA_MQTT_AVAILABLE] = hass.loop.create_future()
else:
client_available = hass.data[DATA_MQTT_AVAILABLE]
mqtt_data, conf = await _setup_client()
platforms_used = platforms_from_config(mqtt_data.config)
platforms_used.update(_platforms_in_use(hass, entry))
integration = async_get_loaded_integration(hass, DOMAIN)
# Preload platforms we know we are going to use so
# discovery can setup each platform synchronously
# and avoid creating a flood of tasks at startup
# while waiting for the the imports to complete
if not integration.platforms_are_loaded(platforms_used):
with async_pause_setup(hass, SetupPhases.WAIT_IMPORT_PLATFORMS):
await integration.async_get_platforms(platforms_used)
# Wait to connect until the platforms are loaded so
# we can be sure discovery does not have to wait for
# each platform to load when we get the flood of retained
# messages on connect
await mqtt_data.client.async_connect(client_available)
# setup platforms and discovery
await async_forward_entry_setup_and_setup_discovery(hass, entry, platforms_used)
# Setup discovery
if conf.get(CONF_DISCOVERY, DEFAULT_DISCOVERY):
await discovery.async_start(
hass, conf.get(CONF_DISCOVERY_PREFIX, DEFAULT_PREFIX), entry
)
return True
@websocket_api.websocket_command(
{
probatio.Required("type"): "vmqtt/device/debug_info",
probatio.Required("device_id"): str,
}
)
@callback
def websocket_mqtt_info(
hass: HomeAssistant, connection: websocket_api.ActiveConnection, msg: dict[str, Any]
) -> None:
"""Get MQTT debug info for device."""
device_id = msg["device_id"]
mqtt_info = debug_info.info_for_device(hass, device_id)
connection.send_result(msg["id"], mqtt_info)
@websocket_api.websocket_command(
{
probatio.Required("type"): "vmqtt/subscribe",
probatio.Required("topic"): valid_subscribe_topic,
probatio.Optional("qos"): valid_qos_schema,
}
)
@websocket_api.async_response
async def websocket_subscribe(
hass: HomeAssistant, connection: websocket_api.ActiveConnection, msg: dict[str, Any]
) -> None:
"""Subscribe to a MQTT topic."""
if not connection.user.is_admin:
raise Unauthorized
@callback
def forward_messages(mqttmsg: ReceiveMessage) -> None:
"""Forward events to websocket."""
try:
payload = cast(bytes, mqttmsg.payload).decode(
DEFAULT_ENCODING
) # not str because encoding is set to None
except (AttributeError, UnicodeDecodeError):
# Convert non UTF-8 payload to a string presentation
payload = str(mqttmsg.payload)
connection.send_message(
websocket_api.event_message(
msg["id"],
{
"topic": mqttmsg.topic,
"payload": payload,
"qos": mqttmsg.qos,
"retain": mqttmsg.retain,
},
)
)
# Perform UTF-8 decoding directly in callback routine
qos: int = msg.get("qos", DEFAULT_QOS)
connection.subscriptions[msg["id"]] = async_subscribe_internal(
hass, msg["topic"], forward_messages, encoding=None, qos=qos
)
connection.send_message(websocket_api.result_message(msg["id"]))
type ConnectionStatusCallback = Callable[[bool], None]
@callback
def async_subscribe_connection_status(
hass: HomeAssistant, connection_status_callback: ConnectionStatusCallback
) -> Callable[[], None]:
"""Subscribe to MQTT connection changes."""
return async_dispatcher_connect(
hass, MQTT_CONNECTION_STATE, connection_status_callback
)
def is_connected(hass: HomeAssistant) -> bool:
"""Return if MQTT client is connected."""
mqtt_data = hass.data[DATA_MQTT]
return mqtt_data.client.connected
async def async_remove_config_entry_device(
hass: HomeAssistant, config_entry: ConfigEntry, device_entry: AnyDeviceEntry
) -> bool:
"""Remove MQTT config entry from a device."""
from . import device_automation # noqa: PLC0415
await device_automation.async_removed_from_device(hass, device_entry.id)
return True
async def async_unload_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
"""Unload MQTT dump and publish service when the config entry is unloaded."""
mqtt_data = hass.data[DATA_MQTT]
mqtt_client = mqtt_data.client
# Stop the discovery
await discovery.async_stop(hass)
# Unload the platforms
await hass.config_entries.async_unload_platforms(entry, mqtt_data.platforms_loaded)
mqtt_data.platforms_loaded = set()
await asyncio.sleep(0)
# Unsubscribe reload dispatchers
while reload_dispatchers := mqtt_data.reload_dispatchers:
reload_dispatchers.pop()()
# Cleanup listeners
mqtt_client.cleanup()
# Cleanup entity registry hooks
registry_hooks = mqtt_data.discovery_registry_hooks
while registry_hooks:
registry_hooks.popitem()[1]()
# Wait for all ACKs, stop the loop and disconnect the client
await mqtt_client.async_disconnect(disconnect_paho_client=True)
# Cleanup MQTT client availability
hass.data.pop(DATA_MQTT_AVAILABLE, None)
# Store remaining subscriptions to be able to restore or reload them
# when the entry is set up again
if subscriptions := mqtt_client.subscriptions:
mqtt_data.subscriptions_to_restore = subscriptions
# Remove repair issues
_async_remove_mqtt_issues(hass, mqtt_data)
return True
+299
View File
@@ -0,0 +1,299 @@
"""Abbreviations supported by MQTT discovery."""
ABBREVIATIONS = {
"act_t": "action_topic",
"act_tpl": "action_template",
"act_stat_t": "activity_state_topic",
"act_val_tpl": "activity_value_template",
"atype": "automation_type",
"av_tones": "available_tones",
"avty": "availability",
"avty_mode": "availability_mode",
"avty_t": "availability_topic",
"avty_tpl": "availability_template",
"b_tpl": "blue_template",
"bri_cmd_tpl": "brightness_command_template",
"bri_cmd_t": "brightness_command_topic",
"bri_scl": "brightness_scale",
"bri_stat_t": "brightness_state_topic",
"bri_tpl": "brightness_template",
"bri_val_tpl": "brightness_value_template",
"cln_segmnts_cmd_t": "clean_segments_command_topic",
"cln_segmnts_cmd_tpl": "clean_segments_command_template",
"clr_temp_cmd_tpl": "color_temp_command_template",
"clrm_stat_t": "color_mode_state_topic",
"clrm_val_tpl": "color_mode_value_template",
"clr_temp_cmd_t": "color_temp_command_topic",
"clr_temp_k": "color_temp_kelvin",
"clr_temp_stat_t": "color_temp_state_topic",
"clr_temp_tpl": "color_temp_template",
"clr_temp_val_tpl": "color_temp_value_template",
"cmd_off_tpl": "command_off_template",
"cmd_on_tpl": "command_on_template",
"cmd_t": "command_topic",
"cmd_tpl": "command_template",
"cmps": "components",
"cod_arm_req": "code_arm_required",
"cod_dis_req": "code_disarm_required",
"cod_form": "code_format",
"cod_trig_req": "code_trigger_required",
"cont_type": "content_type",
"curr_hum_t": "current_humidity_topic",
"curr_hum_tpl": "current_humidity_template",
"curr_temp_t": "current_temperature_topic",
"curr_temp_tpl": "current_temperature_template",
"def_ent_id": "default_entity_id",
"dev": "device",
"dev_cla": "device_class",
"dir_cmd_t": "direction_command_topic",
"dir_cmd_tpl": "direction_command_template",
"dir_stat_t": "direction_state_topic",
"dir_val_tpl": "direction_value_template",
"dsp_prc": "display_precision",
"dock_cmd_t": "dock_command_topic",
"dock_cmd_tpl": "dock_command_template",
"e": "encoding",
"en": "enabled_by_default",
"ent_cat": "entity_category",
"ent_pic": "entity_picture",
"evt_typ": "event_types",
"fanspd_lst": "fan_speed_list",
"flsh": "flash",
"flsh_tlng": "flash_time_long",
"flsh_tsht": "flash_time_short",
"fx_cmd_tpl": "effect_command_template",
"fx_cmd_t": "effect_command_topic",
"fx_list": "effect_list",
"fx_stat_t": "effect_state_topic",
"fx_tpl": "effect_template",
"fx_val_tpl": "effect_value_template",
"exp_aft": "expire_after",
"fan_mode_cmd_tpl": "fan_mode_command_template",
"fan_mode_cmd_t": "fan_mode_command_topic",
"fan_mode_stat_tpl": "fan_mode_state_template",
"fan_mode_stat_t": "fan_mode_state_topic",
"frc_upd": "force_update",
"g_tpl": "green_template",
"grp": "group",
"hs_cmd_t": "hs_command_topic",
"hs_cmd_tpl": "hs_command_template",
"hs_stat_t": "hs_state_topic",
"hs_val_tpl": "hs_value_template",
"ic": "icon",
"img_e": "image_encoding",
"img_t": "image_topic",
"init": "initial",
"hum_cmd_t": "target_humidity_command_topic",
"hum_cmd_tpl": "target_humidity_command_template",
"hum_stat_t": "target_humidity_state_topic",
"hum_state_tpl": "target_humidity_state_template",
"json_attr": "json_attributes",
"json_attr_t": "json_attributes_topic",
"json_attr_tpl": "json_attributes_template",
"lrst_val_tpl": "last_reset_value_template",
"max": "max",
"min": "min",
"max_hum": "max_humidity",
"min_hum": "min_humidity",
"max_mirs": "max_mireds",
"min_mirs": "min_mireds",
"max_k": "max_kelvin",
"min_k": "min_kelvin",
"max_temp": "max_temp",
"min_temp": "min_temp",
"migr_discvry": "migrate_discovery",
"mode": "mode",
"mode_cmd_tpl": "mode_command_template",
"mode_cmd_t": "mode_command_topic",
"mode_stat_t": "mode_state_topic",
"mode_stat_tpl": "mode_state_template",
"modes": "modes",
"msg_exp_int": "message_expiry_interval",
"name": "name",
"o": "origin",
"off_dly": "off_delay",
"on_cmd_type": "on_command_type",
"ops": "options",
"opt": "optimistic",
"osc_cmd_t": "oscillation_command_topic",
"osc_cmd_tpl": "oscillation_command_template",
"osc_stat_t": "oscillation_state_topic",
"osc_val_tpl": "oscillation_value_template",
"p": "platform",
"pause_cmd_t": "pause_command_topic",
"pause_mw_cmd_tpl": "pause_command_template",
"pct_cmd_t": "percentage_command_topic",
"pct_cmd_tpl": "percentage_command_template",
"pct_stat_t": "percentage_state_topic",
"pct_val_tpl": "percentage_value_template",
"pl": "payload",
"pl_arm_away": "payload_arm_away",
"pl_arm_home": "payload_arm_home",
"pl_arm_nite": "payload_arm_night",
"pl_arm_vacation": "payload_arm_vacation",
"pl_arm_custom_b": "payload_arm_custom_bypass",
"pl_avail": "payload_available",
"pl_cln_sp": "payload_clean_spot",
"pl_cls": "payload_close",
"pl_disarm": "payload_disarm",
"pl_home": "payload_home",
"pl_lock": "payload_lock",
"pl_loc": "payload_locate",
"pl_not_avail": "payload_not_available",
"pl_not_home": "payload_not_home",
"pl_off": "payload_off",
"pl_on": "payload_on",
"pl_open": "payload_open",
"pl_osc_off": "payload_oscillation_off",
"pl_osc_on": "payload_oscillation_on",
"pl_paus": "payload_pause",
"pl_prs": "payload_press",
"pl_rst": "payload_reset",
"pl_rst_hum": "payload_reset_humidity",
"pl_rst_mode": "payload_reset_mode",
"pl_rst_pct": "payload_reset_percentage",
"pl_rst_pr_mode": "payload_reset_preset_mode",
"pl_stop": "payload_stop",
"pl_stop_tilt": "payload_stop_tilt",
"pl_strt": "payload_start",
"pl_ret": "payload_return_to_base",
"pl_toff": "payload_turn_off",
"pl_ton": "payload_turn_on",
"pl_trig": "payload_trigger",
"pl_unlk": "payload_unlock",
"pos": "reports_position",
"pos_clsd": "position_closed",
"pos_open": "position_open",
"pow_cmd_t": "power_command_topic",
"pow_cmd_tpl": "power_command_template",
"pr_mode_cmd_t": "preset_mode_command_topic",
"pr_mode_cmd_tpl": "preset_mode_command_template",
"pr_mode_stat_t": "preset_mode_state_topic",
"pr_mode_val_tpl": "preset_mode_value_template",
"pr_modes": "preset_modes",
"ptrn": "pattern",
"r_tpl": "red_template",
"rel_s": "release_summary",
"rel_u": "release_url",
"ret": "retain",
"rgb_cmd_tpl": "rgb_command_template",
"rgb_cmd_t": "rgb_command_topic",
"rgb_stat_t": "rgb_state_topic",
"rgb_val_tpl": "rgb_value_template",
"rgbw_cmd_tpl": "rgbw_command_template",
"rgbw_cmd_t": "rgbw_command_topic",
"rgbw_stat_t": "rgbw_state_topic",
"rgbw_val_tpl": "rgbw_value_template",
"rgbww_cmd_tpl": "rgbww_command_template",
"rgbww_cmd_t": "rgbww_command_topic",
"rgbww_stat_t": "rgbww_state_topic",
"rgbww_val_tpl": "rgbww_value_template",
"send_cmd_t": "send_command_topic",
"send_if_off": "send_if_off",
"set_fan_spd_t": "set_fan_speed_topic",
"set_pos_tpl": "set_position_template",
"set_pos_t": "set_position_topic",
"pos_t": "position_topic",
"pos_tpl": "position_template",
"spd_rng_min": "speed_range_min",
"spd_rng_max": "speed_range_max",
"src_type": "source_type",
"stat_cla": "state_class",
"stat_clsd": "state_closed",
"stat_closing": "state_closing",
"stat_jam": "state_jammed",
"stat_off": "state_off",
"stat_on": "state_on",
"stat_open": "state_open",
"stat_opening": "state_opening",
"stat_stopped": "state_stopped",
"stat_locked": "state_locked",
"stat_locking": "state_locking",
"stat_unlocked": "state_unlocked",
"stat_unlocking": "state_unlocking",
"stat_t": "state_topic",
"stat_tpl": "state_template",
"stat_val_tpl": "state_value_template",
"step": "step",
"stop_cmd_t": "stop_command_topic",
"stop_cmd_tpl": "stop_command_template",
"strt_mw_cmd_t": "start_mowing_command_topic",
"strt_mw_cmd_tpl": "start_mowing_command_template",
"stype": "subtype",
"sug_dsp_prc": "suggested_display_precision",
"sup_dur": "support_duration",
"sup_vol": "support_volume_set",
"sup_feat": "supported_features",
"sup_clrm": "supported_color_modes",
"swing_h_mode_cmd_tpl": "swing_horizontal_mode_command_template",
"swing_h_mode_cmd_t": "swing_horizontal_mode_command_topic",
"swing_h_mode_stat_tpl": "swing_horizontal_mode_state_template",
"swing_h_mode_stat_t": "swing_horizontal_mode_state_topic",
"swing_h_modes": "swing_horizontal_modes",
"swing_mode_cmd_tpl": "swing_mode_command_template",
"swing_mode_cmd_t": "swing_mode_command_topic",
"swing_mode_stat_tpl": "swing_mode_state_template",
"swing_mode_stat_t": "swing_mode_state_topic",
"swing_modes": "swing_modes",
"temp_cmd_tpl": "temperature_command_template",
"temp_cmd_t": "temperature_command_topic",
"temp_hi_cmd_tpl": "temperature_high_command_template",
"temp_hi_cmd_t": "temperature_high_command_topic",
"temp_hi_stat_tpl": "temperature_high_state_template",
"temp_hi_stat_t": "temperature_high_state_topic",
"temp_lo_cmd_tpl": "temperature_low_command_template",
"temp_lo_cmd_t": "temperature_low_command_topic",
"temp_lo_stat_tpl": "temperature_low_state_template",
"temp_lo_stat_t": "temperature_low_state_topic",
"temp_stat_tpl": "temperature_state_template",
"temp_stat_t": "temperature_state_topic",
"temp_unit": "temperature_unit",
"tilt_clsd_val": "tilt_closed_value",
"tilt_cmd_t": "tilt_command_topic",
"tilt_cmd_tpl": "tilt_command_template",
"tilt_max": "tilt_max",
"tilt_min": "tilt_min",
"tilt_opnd_val": "tilt_opened_value",
"tilt_opt": "tilt_optimistic",
"tilt_status_t": "tilt_status_topic",
"tilt_status_tpl": "tilt_status_template",
"tit": "title",
"t": "topic",
"trns": "transition",
"tz": "timezone",
"uniq_id": "unique_id",
"unit_of_meas": "unit_of_measurement",
"url_t": "url_topic",
"url_tpl": "url_template",
"val_tpl": "value_template",
"whit_cmd_t": "white_command_topic",
"whit_scl": "white_scale",
"xy_cmd_t": "xy_command_topic",
"xy_cmd_tpl": "xy_command_template",
"xy_stat_t": "xy_state_topic",
"xy_val_tpl": "xy_value_template",
"l_ver_t": "latest_version_topic",
"l_ver_tpl": "latest_version_template",
"pl_inst": "payload_install",
"vis": "visible_by_default",
}
DEVICE_ABBREVIATIONS = {
"cns": "connections",
"cu": "configuration_url",
"ids": "identifiers",
"name": "name",
"mf": "manufacturer",
"mdl": "model",
"mdl_id": "model_id",
"hw": "hw_version",
"sw": "sw_version",
"sa": "suggested_area",
"sn": "serial_number",
}
ORIGIN_ABBREVIATIONS = {
"name": "name",
"sw": "sw_version",
"url": "support_url",
}
+20
View File
@@ -0,0 +1,20 @@
"""Provide MQTT add-on management.
Currently only supports the official mosquitto add-on.
"""
from homeassistant.components.hassio import AddonManager
from homeassistant.core import HomeAssistant, callback
from homeassistant.helpers.singleton import singleton
from .const import DOMAIN, LOGGER
ADDON_SLUG = "core_mosquitto"
DATA_ADDON_MANAGER = f"{DOMAIN}_addon_manager"
@singleton(DATA_ADDON_MANAGER)
@callback
def get_addon_manager(hass: HomeAssistant) -> AddonManager:
"""Get the add-on manager."""
return AddonManager(hass, LOGGER, "Mosquitto Mqtt Broker", ADDON_SLUG)
@@ -0,0 +1,313 @@
"""Control a MQTT alarm."""
import logging
from typing import override
import probatio
from homeassistant.components import alarm_control_panel as alarm
from homeassistant.components.alarm_control_panel import (
AlarmControlPanelEntityStateAttribute,
AlarmControlPanelState,
)
from homeassistant.config_entries import ConfigEntry
from homeassistant.const import CONF_CODE, CONF_NAME, CONF_VALUE_TEMPLATE
from homeassistant.core import HomeAssistant, callback
from homeassistant.helpers import config_validation as cv
from homeassistant.helpers.entity_platform import AddConfigEntryEntitiesCallback
from homeassistant.helpers.typing import ConfigType
from . import subscription
from .config import DEFAULT_RETAIN, MQTT_BASE_SCHEMA
from .const import (
ALARM_CONTROL_PANEL_SUPPORTED_FEATURES,
CONF_CODE_ARM_REQUIRED,
CONF_CODE_DISARM_REQUIRED,
CONF_CODE_TRIGGER_REQUIRED,
CONF_COMMAND_TEMPLATE,
CONF_COMMAND_TOPIC,
CONF_PAYLOAD_ARM_AWAY,
CONF_PAYLOAD_ARM_CUSTOM_BYPASS,
CONF_PAYLOAD_ARM_HOME,
CONF_PAYLOAD_ARM_NIGHT,
CONF_PAYLOAD_ARM_VACATION,
CONF_PAYLOAD_DISARM,
CONF_PAYLOAD_TRIGGER,
CONF_RETAIN,
CONF_STATE_TOPIC,
CONF_SUPPORTED_FEATURES,
DEFAULT_ALARM_CONTROL_PANEL_COMMAND_TEMPLATE,
DEFAULT_PAYLOAD_ARM_AWAY,
DEFAULT_PAYLOAD_ARM_CUSTOM_BYPASS,
DEFAULT_PAYLOAD_ARM_HOME,
DEFAULT_PAYLOAD_ARM_NIGHT,
DEFAULT_PAYLOAD_ARM_VACATION,
DEFAULT_PAYLOAD_DISARM,
DEFAULT_PAYLOAD_TRIGGER,
PAYLOAD_NONE,
REMOTE_CODE,
REMOTE_CODE_TEXT,
)
from .entity import MqttEntity, async_setup_entity_entry_helper
from .models import MqttCommandTemplate, MqttValueTemplate, ReceiveMessage
from .schemas import MQTT_ENTITY_COMMON_SCHEMA
from .util import valid_publish_topic, valid_subscribe_topic
_LOGGER = logging.getLogger(__name__)
PARALLEL_UPDATES = 0
MQTT_ALARM_ATTRIBUTES_BLOCKED = frozenset(
{
AlarmControlPanelEntityStateAttribute.CHANGED_BY,
AlarmControlPanelEntityStateAttribute.CODE_ARM_REQUIRED,
AlarmControlPanelEntityStateAttribute.CODE_FORMAT,
}
)
DEFAULT_NAME = "MQTT Alarm"
PLATFORM_SCHEMA_MODERN = MQTT_BASE_SCHEMA.extend(
{
probatio.Optional(
CONF_SUPPORTED_FEATURES,
default=list(ALARM_CONTROL_PANEL_SUPPORTED_FEATURES),
): [probatio.In(ALARM_CONTROL_PANEL_SUPPORTED_FEATURES)],
probatio.Optional(CONF_CODE): cv.string,
probatio.Optional(CONF_CODE_ARM_REQUIRED, default=True): cv.boolean,
probatio.Optional(CONF_CODE_DISARM_REQUIRED, default=True): cv.boolean,
probatio.Optional(CONF_CODE_TRIGGER_REQUIRED, default=True): cv.boolean,
probatio.Optional(
CONF_COMMAND_TEMPLATE, default=DEFAULT_ALARM_CONTROL_PANEL_COMMAND_TEMPLATE
): cv.template,
probatio.Required(CONF_COMMAND_TOPIC): valid_publish_topic,
probatio.Optional(CONF_NAME): probatio.Any(cv.string, None),
probatio.Optional(
CONF_PAYLOAD_ARM_AWAY, default=DEFAULT_PAYLOAD_ARM_AWAY
): cv.string,
probatio.Optional(
CONF_PAYLOAD_ARM_HOME, default=DEFAULT_PAYLOAD_ARM_HOME
): cv.string,
probatio.Optional(
CONF_PAYLOAD_ARM_NIGHT, default=DEFAULT_PAYLOAD_ARM_NIGHT
): cv.string,
probatio.Optional(
CONF_PAYLOAD_ARM_VACATION, default=DEFAULT_PAYLOAD_ARM_VACATION
): cv.string,
probatio.Optional(
CONF_PAYLOAD_ARM_CUSTOM_BYPASS, default=DEFAULT_PAYLOAD_ARM_CUSTOM_BYPASS
): cv.string,
probatio.Optional(
CONF_PAYLOAD_DISARM, default=DEFAULT_PAYLOAD_DISARM
): cv.string,
probatio.Optional(
CONF_PAYLOAD_TRIGGER, default=DEFAULT_PAYLOAD_TRIGGER
): cv.string,
probatio.Optional(CONF_RETAIN, default=DEFAULT_RETAIN): cv.boolean,
probatio.Required(CONF_STATE_TOPIC): valid_subscribe_topic,
probatio.Optional(CONF_VALUE_TEMPLATE): cv.template,
}
).extend(MQTT_ENTITY_COMMON_SCHEMA.schema)
DISCOVERY_SCHEMA = PLATFORM_SCHEMA_MODERN.extend({}, extra=probatio.REMOVE_EXTRA)
async def async_setup_entry(
hass: HomeAssistant,
config_entry: ConfigEntry,
async_add_entities: AddConfigEntryEntitiesCallback,
) -> None:
"""Set up MQTT alarm control panel through YAML and through MQTT discovery."""
async_setup_entity_entry_helper(
hass,
config_entry,
MqttAlarm,
alarm.DOMAIN,
async_add_entities,
DISCOVERY_SCHEMA,
PLATFORM_SCHEMA_MODERN,
)
class MqttAlarm(MqttEntity, alarm.AlarmControlPanelEntity):
"""Representation of a MQTT alarm status."""
_default_name = DEFAULT_NAME
_entity_id_format = alarm.ENTITY_ID_FORMAT
_attributes_extra_blocked = MQTT_ALARM_ATTRIBUTES_BLOCKED
@staticmethod
@override
def config_schema() -> probatio.Schema:
"""Return the config schema."""
return DISCOVERY_SCHEMA
@override
def _setup_from_config(self, config: ConfigType) -> None:
"""(Re)Setup the entity."""
self._value_template = MqttValueTemplate(
config.get(CONF_VALUE_TEMPLATE),
entity=self,
).async_render_with_possible_json_value
self._command_template = MqttCommandTemplate(
config[CONF_COMMAND_TEMPLATE], entity=self
).async_render
for feature in self._config[CONF_SUPPORTED_FEATURES]:
self._attr_supported_features |= ALARM_CONTROL_PANEL_SUPPORTED_FEATURES[
feature
]
if (code := self._config.get(CONF_CODE)) is None:
self._attr_code_format = None
elif code == REMOTE_CODE or str(code).isdigit():
self._attr_code_format = alarm.CodeFormat.NUMBER
else:
self._attr_code_format = alarm.CodeFormat.TEXT
self._attr_code_arm_required = bool(self._config[CONF_CODE_ARM_REQUIRED])
def _state_message_received(self, msg: ReceiveMessage) -> None:
"""Run when new MQTT message has been received."""
payload = self._value_template(msg.payload)
if not payload.strip(): # No output from template, ignore
_LOGGER.debug(
"Ignoring empty payload '%s' after rendering for topic %s",
payload,
msg.topic,
)
return
if payload == PAYLOAD_NONE:
self._attr_alarm_state = None
return
if payload not in (
AlarmControlPanelState.DISARMED,
AlarmControlPanelState.ARMED_HOME,
AlarmControlPanelState.ARMED_AWAY,
AlarmControlPanelState.ARMED_NIGHT,
AlarmControlPanelState.ARMED_VACATION,
AlarmControlPanelState.ARMED_CUSTOM_BYPASS,
AlarmControlPanelState.PENDING,
AlarmControlPanelState.ARMING,
AlarmControlPanelState.DISARMING,
AlarmControlPanelState.TRIGGERED,
):
_LOGGER.warning("Received unexpected payload: %s", msg.payload)
return
assert isinstance(payload, str)
self._attr_alarm_state = AlarmControlPanelState(payload)
@callback
@override
def _prepare_subscribe_topics(self) -> None:
"""(Re)Subscribe to topics."""
self.add_subscription(
CONF_STATE_TOPIC, self._state_message_received, {"_attr_alarm_state"}
)
@override
async def _subscribe_topics(self) -> None:
"""(Re)Subscribe to topics."""
subscription.async_subscribe_topics_internal(self.hass, self._sub_state)
@override
async def async_alarm_disarm(self, code: str | None = None) -> None:
"""Send disarm command.
This method is a coroutine.
"""
code_required: bool = self._config[CONF_CODE_DISARM_REQUIRED]
if code_required and not self._validate_code(code, "disarming"):
return
payload: str = self._config[CONF_PAYLOAD_DISARM]
await self._publish(code, payload)
@override
async def async_alarm_arm_home(self, code: str | None = None) -> None:
"""Send arm home command.
This method is a coroutine.
"""
code_required: bool = self._config[CONF_CODE_ARM_REQUIRED]
if code_required and not self._validate_code(code, "arming home"):
return
action: str = self._config[CONF_PAYLOAD_ARM_HOME]
await self._publish(code, action)
@override
async def async_alarm_arm_away(self, code: str | None = None) -> None:
"""Send arm away command.
This method is a coroutine.
"""
code_required: bool = self._config[CONF_CODE_ARM_REQUIRED]
if code_required and not self._validate_code(code, "arming away"):
return
action: str = self._config[CONF_PAYLOAD_ARM_AWAY]
await self._publish(code, action)
@override
async def async_alarm_arm_night(self, code: str | None = None) -> None:
"""Send arm night command.
This method is a coroutine.
"""
code_required: bool = self._config[CONF_CODE_ARM_REQUIRED]
if code_required and not self._validate_code(code, "arming night"):
return
action: str = self._config[CONF_PAYLOAD_ARM_NIGHT]
await self._publish(code, action)
@override
async def async_alarm_arm_vacation(self, code: str | None = None) -> None:
"""Send arm vacation command.
This method is a coroutine.
"""
code_required: bool = self._config[CONF_CODE_ARM_REQUIRED]
if code_required and not self._validate_code(code, "arming vacation"):
return
action: str = self._config[CONF_PAYLOAD_ARM_VACATION]
await self._publish(code, action)
@override
async def async_alarm_arm_custom_bypass(self, code: str | None = None) -> None:
"""Send arm custom bypass command.
This method is a coroutine.
"""
code_required: bool = self._config[CONF_CODE_ARM_REQUIRED]
if code_required and not self._validate_code(code, "arming custom bypass"):
return
action: str = self._config[CONF_PAYLOAD_ARM_CUSTOM_BYPASS]
await self._publish(code, action)
@override
async def async_alarm_trigger(self, code: str | None = None) -> None:
"""Send trigger command.
This method is a coroutine.
"""
code_required: bool = self._config[CONF_CODE_TRIGGER_REQUIRED]
if code_required and not self._validate_code(code, "triggering"):
return
action: str = self._config[CONF_PAYLOAD_TRIGGER]
await self._publish(code, action)
async def _publish(self, code: str | None, action: str) -> None:
"""Publish via mqtt."""
variables = {"action": action, "code": code}
payload = self._command_template(None, variables=variables)
await self.async_publish_with_config(self._config[CONF_COMMAND_TOPIC], payload)
def _validate_code(self, code: str | None, state: str) -> bool:
"""Validate given code."""
conf_code: str | None = self._config.get(CONF_CODE)
check = bool(
conf_code is None
or code == conf_code
or (conf_code == REMOTE_CODE and code)
or (conf_code == REMOTE_CODE_TEXT and code)
)
if not check:
_LOGGER.warning("Wrong code entered for %s", state)
return check
+71
View File
@@ -0,0 +1,71 @@
"""Async wrappings for mqtt client."""
from functools import lru_cache
from types import TracebackType
from typing import Self
from paho.mqtt.client import (
CallbackOnConnect_v2,
CallbackOnDisconnect_v2,
CallbackOnPublish_v2,
CallbackOnSubscribe_v2,
CallbackOnUnsubscribe_v2,
Client as MQTTClient,
)
_MQTT_LOCK_COUNT = 7
class NullLock:
"""Null lock."""
@lru_cache(maxsize=_MQTT_LOCK_COUNT)
def __enter__(self) -> Self:
"""Enter the lock."""
return self
@lru_cache(maxsize=_MQTT_LOCK_COUNT)
def __exit__(
self,
exc_type: type[BaseException] | None,
exc_value: BaseException | None,
traceback: TracebackType | None,
) -> None:
"""Exit the lock."""
@lru_cache(maxsize=_MQTT_LOCK_COUNT)
def acquire(self, blocking: bool = False, timeout: int = -1) -> None:
"""Acquire the lock."""
@lru_cache(maxsize=_MQTT_LOCK_COUNT)
def release(self) -> None:
"""Release the lock."""
class AsyncMQTTClient(MQTTClient):
"""Async MQTT Client.
Wrapper around paho.mqtt.client.Client to remove the locking
that is not needed since we are running in an async event loop.
"""
on_connect: CallbackOnConnect_v2
on_disconnect: CallbackOnDisconnect_v2
on_publish: CallbackOnPublish_v2
on_subscribe: CallbackOnSubscribe_v2
on_unsubscribe: CallbackOnUnsubscribe_v2
def setup(self) -> None:
"""Set up the client.
All the threading locks are replaced with NullLock
since the client is running in an async event loop
and will never run in multiple threads.
"""
self._in_callback_mutex = NullLock() # type: ignore[assignment]
self._callback_mutex = NullLock() # type: ignore[assignment]
self._msgtime_mutex = NullLock() # type: ignore[assignment]
self._out_message_mutex = NullLock() # type: ignore[assignment]
self._in_message_mutex = NullLock() # type: ignore[assignment]
self._reconnect_delay_mutex = NullLock() # type: ignore[assignment]
self._mid_generate_mutex = NullLock() # type: ignore[assignment]
+262
View File
@@ -0,0 +1,262 @@
"""Support for MQTT binary sensors."""
from datetime import datetime, timedelta
import logging
from typing import Any, override
import probatio
from homeassistant.components import binary_sensor
from homeassistant.components.binary_sensor import (
DEVICE_CLASSES_SCHEMA,
BinarySensorEntity,
)
from homeassistant.config_entries import ConfigEntry
from homeassistant.const import (
CONF_DEVICE_CLASS,
CONF_FORCE_UPDATE,
CONF_NAME,
CONF_PAYLOAD_OFF,
CONF_PAYLOAD_ON,
CONF_VALUE_TEMPLATE,
STATE_ON,
STATE_UNAVAILABLE,
STATE_UNKNOWN,
)
from homeassistant.core import CALLBACK_TYPE, HomeAssistant, callback
from homeassistant.helpers import config_validation as cv, event as evt
from homeassistant.helpers.entity_platform import AddConfigEntryEntitiesCallback
from homeassistant.helpers.event import async_call_later
from homeassistant.helpers.restore_state import RestoreEntity
from homeassistant.helpers.typing import ConfigType
from homeassistant.util import dt as dt_util
from . import subscription
from .config import MQTT_RO_SCHEMA
from .const import CONF_OFF_DELAY, CONF_STATE_TOPIC, PAYLOAD_NONE
from .entity import MqttAvailabilityMixin, MqttEntity, async_setup_entity_entry_helper
from .models import MqttValueTemplate, ReceiveMessage
from .schemas import MQTT_ENTITY_COMMON_SCHEMA
_LOGGER = logging.getLogger(__name__)
PARALLEL_UPDATES = 0
DEFAULT_NAME = "MQTT Binary sensor"
DEFAULT_PAYLOAD_OFF = "OFF"
DEFAULT_PAYLOAD_ON = "ON"
DEFAULT_FORCE_UPDATE = False
CONF_EXPIRE_AFTER = "expire_after"
PLATFORM_SCHEMA_MODERN = MQTT_RO_SCHEMA.extend(
{
probatio.Optional(CONF_DEVICE_CLASS): probatio.Any(DEVICE_CLASSES_SCHEMA, None),
probatio.Optional(CONF_EXPIRE_AFTER): cv.positive_int,
probatio.Optional(CONF_FORCE_UPDATE, default=DEFAULT_FORCE_UPDATE): cv.boolean,
probatio.Optional(CONF_NAME): probatio.Any(cv.string, None),
probatio.Optional(CONF_OFF_DELAY): cv.positive_int,
probatio.Optional(CONF_PAYLOAD_OFF, default=DEFAULT_PAYLOAD_OFF): cv.string,
probatio.Optional(CONF_PAYLOAD_ON, default=DEFAULT_PAYLOAD_ON): cv.string,
}
).extend(MQTT_ENTITY_COMMON_SCHEMA.schema)
DISCOVERY_SCHEMA = PLATFORM_SCHEMA_MODERN.extend({}, extra=probatio.REMOVE_EXTRA)
async def async_setup_entry(
hass: HomeAssistant,
config_entry: ConfigEntry,
async_add_entities: AddConfigEntryEntitiesCallback,
) -> None:
"""Set up MQTT binary sensor through YAML and through MQTT discovery."""
async_setup_entity_entry_helper(
hass,
config_entry,
MqttBinarySensor,
binary_sensor.DOMAIN,
async_add_entities,
DISCOVERY_SCHEMA,
PLATFORM_SCHEMA_MODERN,
)
class MqttBinarySensor(MqttEntity, BinarySensorEntity, RestoreEntity):
"""Representation a binary sensor that is updated by MQTT."""
_default_name = DEFAULT_NAME
_delay_listener: CALLBACK_TYPE | None = None
_entity_id_format = binary_sensor.ENTITY_ID_FORMAT
_expired: bool | None
_expire_after: int | None
_expiration_trigger: CALLBACK_TYPE | None = None
@override
async def mqtt_async_added_to_hass(self) -> None:
"""Restore state for entities with expire_after set."""
if (
self._expire_after
and (last_state := await self.async_get_last_state()) is not None
and last_state.state not in [STATE_UNKNOWN, STATE_UNAVAILABLE]
# We might have set up a trigger already after subscribing from
# MqttEntity.async_added_to_hass(), then we should not restore state
and not self._expiration_trigger
):
expiration_at: datetime = last_state.last_changed + timedelta(
seconds=self._expire_after
)
remain_seconds = (expiration_at - dt_util.utcnow()).total_seconds()
if remain_seconds <= 0:
# Skip reactivating the binary_sensor
_LOGGER.debug("Skip state recovery after reload for %s", self.entity_id)
return
self._expired = False
self._attr_is_on = last_state.state == STATE_ON
self._expiration_trigger = async_call_later(
self.hass, remain_seconds, self._value_is_expired
)
_LOGGER.debug(
(
"State recovered after reload for %s, remaining time before"
" expiring %s"
),
self.entity_id,
remain_seconds,
)
@override
async def async_will_remove_from_hass(self) -> None:
"""Clean up expire triggers."""
if self._expiration_trigger:
_LOGGER.debug("Clean up expire after trigger for %s", self.entity_id)
self._expiration_trigger()
self._expiration_trigger = None
self._expired = False
await super().async_will_remove_from_hass()
@staticmethod
@override
def config_schema() -> probatio.Schema:
"""Return the config schema."""
return DISCOVERY_SCHEMA
@override
def _setup_from_config(self, config: ConfigType) -> None:
"""(Re)Setup the entity."""
self._expire_after = config.get(CONF_EXPIRE_AFTER)
if self._expire_after:
self._expired = True
else:
self._expired = None
self._attr_force_update = config[CONF_FORCE_UPDATE]
self._attr_device_class = config.get(CONF_DEVICE_CLASS)
self._value_template = MqttValueTemplate(
self._config.get(CONF_VALUE_TEMPLATE),
entity=self,
).async_render_with_possible_json_value
@callback
def _off_delay_listener(self, now: datetime) -> None:
"""Switch device off after a delay."""
self._delay_listener = None
self._attr_is_on = False
self.async_write_ha_state()
def _state_message_received(self, msg: ReceiveMessage) -> None:
"""Handle a new received MQTT state message."""
# auto-expire enabled?
if self._expire_after:
# When expire_after is set, and we receive a message, assume device is
# not expired since it has to be to receive the message
self._expired = False
# Reset old trigger
if self._expiration_trigger:
self._expiration_trigger()
# Set new trigger
self._expiration_trigger = async_call_later(
self.hass, self._expire_after, self._value_is_expired
)
payload = self._value_template(msg.payload)
if not payload.strip(): # No output from template, ignore
_LOGGER.debug(
(
"Empty template output for entity: %s with state topic: %s."
" Payload: '%s', with value template '%s'"
),
self.entity_id,
self._config[CONF_STATE_TOPIC],
msg.payload,
self._config.get(CONF_VALUE_TEMPLATE),
)
return
if payload == self._config[CONF_PAYLOAD_ON]:
self._attr_is_on = True
elif payload == self._config[CONF_PAYLOAD_OFF]:
self._attr_is_on = False
elif payload == PAYLOAD_NONE:
self._attr_is_on = None
else: # Payload is not for this entity
template_info = ""
if self._config.get(CONF_VALUE_TEMPLATE) is not None:
template_info = (
f", template output: '{payload!s}', with value template"
f" '{self._config.get(CONF_VALUE_TEMPLATE)!s}'"
)
_LOGGER.info(
(
"No matching payload found for entity: %s with state topic: %s."
" Payload: '%s'%s"
),
self.entity_id,
self._config[CONF_STATE_TOPIC],
msg.payload,
template_info,
)
return
if self._delay_listener is not None:
self._delay_listener()
self._delay_listener = None
off_delay: int | None = self._config.get(CONF_OFF_DELAY)
if self._attr_is_on and off_delay is not None:
self._delay_listener = evt.async_call_later(
self.hass, off_delay, self._off_delay_listener
)
@callback
@override
def _prepare_subscribe_topics(self) -> None:
"""(Re)Subscribe to topics."""
self.add_subscription(
CONF_STATE_TOPIC, self._state_message_received, {"_attr_is_on", "_expired"}
)
@override
async def _subscribe_topics(self) -> None:
"""(Re)Subscribe to topics."""
subscription.async_subscribe_topics_internal(self.hass, self._sub_state)
@callback
def _value_is_expired(self, *_: Any) -> None:
"""Triggered when value is expired."""
self._expiration_trigger = None
self._expired = True
self.async_write_ha_state()
@property
@override
def available(self) -> bool:
"""Return true if the device is available and value has not expired."""
# mypy doesn't know about fget: https://github.com/python/mypy/issues/6185
return MqttAvailabilityMixin.available.fget(self) and ( # type: ignore[attr-defined]
self._expire_after is None or not self._expired
)
+100
View File
@@ -0,0 +1,100 @@
"""Support for MQTT buttons."""
from typing import override
import probatio
from homeassistant.components import button
from homeassistant.components.button import DEVICE_CLASSES_SCHEMA, ButtonEntity
from homeassistant.config_entries import ConfigEntry
from homeassistant.const import CONF_DEVICE_CLASS, CONF_NAME
from homeassistant.core import HomeAssistant, callback
from homeassistant.helpers import config_validation as cv
from homeassistant.helpers.entity_platform import AddConfigEntryEntitiesCallback
from homeassistant.helpers.typing import ConfigType
from .config import DEFAULT_RETAIN, MQTT_BASE_SCHEMA
from .const import (
CONF_COMMAND_TEMPLATE,
CONF_COMMAND_TOPIC,
CONF_PAYLOAD_PRESS,
CONF_RETAIN,
DEFAULT_PAYLOAD_PRESS,
)
from .entity import MqttEntity, async_setup_entity_entry_helper
from .models import MqttCommandTemplate
from .schemas import MQTT_ENTITY_COMMON_SCHEMA
from .util import valid_publish_topic
PARALLEL_UPDATES = 0
DEFAULT_NAME = "MQTT Button"
PLATFORM_SCHEMA_MODERN = MQTT_BASE_SCHEMA.extend(
{
probatio.Optional(CONF_COMMAND_TEMPLATE): cv.template,
probatio.Required(CONF_COMMAND_TOPIC): valid_publish_topic,
probatio.Optional(CONF_DEVICE_CLASS): probatio.Any(DEVICE_CLASSES_SCHEMA, None),
probatio.Optional(CONF_NAME): probatio.Any(cv.string, None),
probatio.Optional(CONF_PAYLOAD_PRESS, default=DEFAULT_PAYLOAD_PRESS): cv.string,
probatio.Optional(CONF_RETAIN, default=DEFAULT_RETAIN): cv.boolean,
}
).extend(MQTT_ENTITY_COMMON_SCHEMA.schema)
DISCOVERY_SCHEMA = PLATFORM_SCHEMA_MODERN.extend({}, extra=probatio.REMOVE_EXTRA)
async def async_setup_entry(
hass: HomeAssistant,
config_entry: ConfigEntry,
async_add_entities: AddConfigEntryEntitiesCallback,
) -> None:
"""Set up MQTT button through YAML and through MQTT discovery."""
async_setup_entity_entry_helper(
hass,
config_entry,
MqttButton,
button.DOMAIN,
async_add_entities,
DISCOVERY_SCHEMA,
PLATFORM_SCHEMA_MODERN,
)
class MqttButton(MqttEntity, ButtonEntity):
"""Representation of a switch that can be toggled using MQTT."""
_default_name = DEFAULT_NAME
_entity_id_format = button.ENTITY_ID_FORMAT
@staticmethod
@override
def config_schema() -> probatio.Schema:
"""Return the config schema."""
return DISCOVERY_SCHEMA
@override
def _setup_from_config(self, config: ConfigType) -> None:
"""(Re)Setup the entity."""
self._command_template = MqttCommandTemplate(
config.get(CONF_COMMAND_TEMPLATE), entity=self
).async_render
self._attr_device_class = self._config.get(CONF_DEVICE_CLASS)
@callback
@override
def _prepare_subscribe_topics(self) -> None:
"""(Re)Subscribe to topics."""
@override
async def _subscribe_topics(self) -> None:
"""(Re)Subscribe to topics."""
@override
async def async_press(self) -> None:
"""Turn the device on.
This method is a coroutine.
"""
payload = self._command_template(self._config[CONF_PAYLOAD_PRESS])
await self.async_publish_with_config(self._config[CONF_COMMAND_TOPIC], payload)
+129
View File
@@ -0,0 +1,129 @@
"""Camera that loads a picture from an MQTT topic."""
from base64 import b64decode
import logging
from typing import TYPE_CHECKING, override
import probatio
from homeassistant.components import camera
from homeassistant.components.camera import Camera, CameraEntityStateAttribute
from homeassistant.config_entries import ConfigEntry
from homeassistant.const import CONF_NAME
from homeassistant.core import HomeAssistant, callback
from homeassistant.helpers import config_validation as cv
from homeassistant.helpers.entity_platform import AddConfigEntryEntitiesCallback
from homeassistant.helpers.typing import ConfigType, DiscoveryInfoType
from . import subscription
from .config import MQTT_BASE_SCHEMA
from .const import CONF_TOPIC
from .entity import MqttEntity, async_setup_entity_entry_helper
from .models import ReceiveMessage
from .schemas import MQTT_ENTITY_COMMON_SCHEMA
from .util import valid_subscribe_topic
_LOGGER = logging.getLogger(__name__)
PARALLEL_UPDATES = 0
CONF_IMAGE_ENCODING = "image_encoding"
DEFAULT_NAME = "MQTT Camera"
MQTT_CAMERA_ATTRIBUTES_BLOCKED = frozenset(
{
CameraEntityStateAttribute.ACCESS_TOKEN,
CameraEntityStateAttribute.BRAND,
CameraEntityStateAttribute.MODEL_NAME,
CameraEntityStateAttribute.MOTION_DETECTION,
}
)
PLATFORM_SCHEMA_BASE = MQTT_BASE_SCHEMA.extend(
{
probatio.Optional(CONF_NAME): probatio.Any(cv.string, None),
probatio.Required(CONF_TOPIC): valid_subscribe_topic,
probatio.Optional(CONF_IMAGE_ENCODING): "b64",
}
).extend(MQTT_ENTITY_COMMON_SCHEMA.schema)
PLATFORM_SCHEMA_MODERN = probatio.All(
PLATFORM_SCHEMA_BASE.schema,
)
DISCOVERY_SCHEMA = PLATFORM_SCHEMA_BASE.extend({}, extra=probatio.REMOVE_EXTRA)
async def async_setup_entry(
hass: HomeAssistant,
config_entry: ConfigEntry,
async_add_entities: AddConfigEntryEntitiesCallback,
) -> None:
"""Set up MQTT camera through YAML and through MQTT discovery."""
async_setup_entity_entry_helper(
hass,
config_entry,
MqttCamera,
camera.DOMAIN,
async_add_entities,
DISCOVERY_SCHEMA,
PLATFORM_SCHEMA_MODERN,
)
class MqttCamera(MqttEntity, Camera):
"""representation of a MQTT camera."""
_default_name = DEFAULT_NAME
_entity_id_format: str = camera.ENTITY_ID_FORMAT
_attributes_extra_blocked: frozenset[str] = MQTT_CAMERA_ATTRIBUTES_BLOCKED
_last_image: bytes | None = None
def __init__(
self,
hass: HomeAssistant,
config: ConfigType,
config_entry: ConfigEntry,
discovery_data: DiscoveryInfoType | None,
) -> None:
"""Initialize the MQTT Camera."""
Camera.__init__(self)
MqttEntity.__init__(self, hass, config, config_entry, discovery_data)
@staticmethod
@override
def config_schema() -> probatio.Schema:
"""Return the config schema."""
return DISCOVERY_SCHEMA
@callback
def _image_received(self, msg: ReceiveMessage) -> None:
"""Handle new MQTT messages."""
if CONF_IMAGE_ENCODING in self._config:
self._last_image = b64decode(msg.payload)
else:
if TYPE_CHECKING:
assert isinstance(msg.payload, bytes)
self._last_image = msg.payload
@callback
@override
def _prepare_subscribe_topics(self) -> None:
"""(Re)Subscribe to topics."""
self.add_subscription(
CONF_TOPIC, self._image_received, None, disable_encoding=True
)
@override
async def _subscribe_topics(self) -> None:
"""(Re)Subscribe to topics."""
subscription.async_subscribe_topics_internal(self.hass, self._sub_state)
@override
async def async_camera_image(
self, width: int | None = None, height: int | None = None
) -> bytes | None:
"""Return image response."""
return self._last_image
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
+46
View File
@@ -0,0 +1,46 @@
"""Support for MQTT message handling."""
import probatio
from homeassistant.const import CONF_OPTIMISTIC, CONF_VALUE_TEMPLATE
from homeassistant.helpers import config_validation as cv
from .const import (
CONF_COMMAND_TOPIC,
CONF_ENCODING,
CONF_GROUP,
CONF_QOS,
CONF_RETAIN,
CONF_STATE_TOPIC,
DEFAULT_ENCODING,
DEFAULT_OPTIMISTIC,
DEFAULT_QOS,
DEFAULT_RETAIN,
)
from .util import valid_publish_topic, valid_qos_schema, valid_subscribe_topic
SCHEMA_BASE = {
probatio.Optional(CONF_QOS, default=DEFAULT_QOS): valid_qos_schema,
probatio.Optional(CONF_ENCODING, default=DEFAULT_ENCODING): cv.string,
probatio.Optional(CONF_GROUP): probatio.All(probatio.EnsureList(), [cv.string]),
}
MQTT_BASE_SCHEMA = probatio.Schema(SCHEMA_BASE)
# Sensor type platforms subscribe to MQTT events
MQTT_RO_SCHEMA = MQTT_BASE_SCHEMA.extend(
{
probatio.Required(CONF_STATE_TOPIC): valid_subscribe_topic,
probatio.Optional(CONF_VALUE_TEMPLATE): cv.template,
}
)
# Switch type platforms publish to MQTT and may subscribe
MQTT_RW_SCHEMA = MQTT_BASE_SCHEMA.extend(
{
probatio.Required(CONF_COMMAND_TOPIC): valid_publish_topic,
probatio.Optional(CONF_OPTIMISTIC, default=DEFAULT_OPTIMISTIC): cv.boolean,
probatio.Optional(CONF_RETAIN, default=DEFAULT_RETAIN): cv.boolean,
probatio.Optional(CONF_STATE_TOPIC): valid_subscribe_topic,
}
)
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,40 @@
"""Support for MQTT platform config setup."""
import probatio
from homeassistant.const import Platform
CONFIG_SCHEMA_BASE = probatio.Schema(
{
Platform.ALARM_CONTROL_PANEL.value: probatio.All(probatio.EnsureList(), [dict]),
Platform.BINARY_SENSOR.value: probatio.All(probatio.EnsureList(), [dict]),
Platform.BUTTON.value: probatio.All(probatio.EnsureList(), [dict]),
Platform.CAMERA.value: probatio.All(probatio.EnsureList(), [dict]),
Platform.CLIMATE.value: probatio.All(probatio.EnsureList(), [dict]),
Platform.COVER.value: probatio.All(probatio.EnsureList(), [dict]),
Platform.DATE.value: probatio.All(probatio.EnsureList(), [dict]),
Platform.DATETIME.value: probatio.All(probatio.EnsureList(), [dict]),
Platform.DEVICE_TRACKER.value: probatio.All(probatio.EnsureList(), [dict]),
Platform.EVENT.value: probatio.All(probatio.EnsureList(), [dict]),
Platform.FAN.value: probatio.All(probatio.EnsureList(), [dict]),
Platform.HUMIDIFIER.value: probatio.All(probatio.EnsureList(), [dict]),
Platform.IMAGE.value: probatio.All(probatio.EnsureList(), [dict]),
Platform.INFRARED.value: probatio.All(probatio.EnsureList(), [dict]),
Platform.LAWN_MOWER.value: probatio.All(probatio.EnsureList(), [dict]),
Platform.LIGHT.value: probatio.All(probatio.EnsureList(), [dict]),
Platform.LOCK.value: probatio.All(probatio.EnsureList(), [dict]),
Platform.NOTIFY.value: probatio.All(probatio.EnsureList(), [dict]),
Platform.NUMBER.value: probatio.All(probatio.EnsureList(), [dict]),
Platform.SCENE.value: probatio.All(probatio.EnsureList(), [dict]),
Platform.SELECT.value: probatio.All(probatio.EnsureList(), [dict]),
Platform.SENSOR.value: probatio.All(probatio.EnsureList(), [dict]),
Platform.SIREN.value: probatio.All(probatio.EnsureList(), [dict]),
Platform.SWITCH.value: probatio.All(probatio.EnsureList(), [dict]),
Platform.TEXT.value: probatio.All(probatio.EnsureList(), [dict]),
Platform.TIME.value: probatio.All(probatio.EnsureList(), [dict]),
Platform.UPDATE.value: probatio.All(probatio.EnsureList(), [dict]),
Platform.VACUUM.value: probatio.All(probatio.EnsureList(), [dict]),
Platform.VALVE.value: probatio.All(probatio.EnsureList(), [dict]),
Platform.WATER_HEATER.value: probatio.All(probatio.EnsureList(), [dict]),
}
)
+456
View File
@@ -0,0 +1,456 @@
"""Constants used by multiple MQTT modules."""
import logging
import jinja2
from homeassistant.components.alarm_control_panel import AlarmControlPanelEntityFeature
from homeassistant.const import CONF_PAYLOAD, Platform
from homeassistant.exceptions import TemplateError
ATTR_DISCOVERY_HASH = "discovery_hash"
ATTR_DISCOVERY_PAYLOAD = "discovery_payload"
ATTR_DISCOVERY_TOPIC = "discovery_topic"
ATTR_MESSAGE_EXPIRY_INTERVAL = "message_expiry_interval"
ATTR_PAYLOAD = "payload"
ATTR_QOS = "qos"
ATTR_RETAIN = "retain"
ATTR_TOPIC = "topic"
AVAILABILITY_ALL = "all"
AVAILABILITY_ANY = "any"
AVAILABILITY_LATEST = "latest"
AVAILABILITY_MODES = [AVAILABILITY_ALL, AVAILABILITY_ANY, AVAILABILITY_LATEST]
CONF_PAYLOAD_AVAILABLE = "payload_available"
CONF_PAYLOAD_NOT_AVAILABLE = "payload_not_available"
CONF_AVAILABILITY = "availability"
CONF_AVAILABILITY_MODE = "availability_mode"
CONF_AVAILABILITY_TEMPLATE = "availability_template"
CONF_AVAILABILITY_TOPIC = "availability_topic"
CONF_AVAILABLE_TONES = "available_tones"
CONF_BROKER = "broker"
CONF_BIRTH_MESSAGE = "birth_message"
CONF_CODE_ARM_REQUIRED = "code_arm_required"
CONF_CODE_DISARM_REQUIRED = "code_disarm_required"
CONF_CODE_FORMAT = "code_format"
CONF_CODE_TRIGGER_REQUIRED = "code_trigger_required"
CONF_COMMAND_TEMPLATE = "command_template"
CONF_COMMAND_TOPIC = "command_topic"
CONF_CONTENT_TYPE = "content_type"
CONF_DEFAULT_ENTITY_ID = "default_entity_id"
CONF_DISCOVERY_PREFIX = "discovery_prefix"
CONF_DISCOVERY_QOS = "discovery_qos"
CONF_ENCODING = "encoding"
CONF_IMAGE_ENCODING = "image_encoding"
CONF_IMAGE_TOPIC = "image_topic"
CONF_JSON_ATTRS_TOPIC = "json_attributes_topic"
CONF_JSON_ATTRS_TEMPLATE = "json_attributes_template"
CONF_KEEPALIVE = "keepalive"
CONF_MESSAGE_EXPIRY_INTERVAL = "message_expiry_interval"
CONF_ORIGIN = "origin"
CONF_QOS = ATTR_QOS
CONF_RETAIN = ATTR_RETAIN
CONF_SCHEMA = "schema"
CONF_STATE_TOPIC = "state_topic"
CONF_STATE_VALUE_TEMPLATE = "state_value_template"
CONF_TIMEZONE = "timezone"
CONF_TOPIC = "topic"
CONF_TRANSPORT = "transport"
CONF_WS_PATH = "ws_path"
CONF_WS_HEADERS = "ws_headers"
CONF_WILL_MESSAGE = "will_message"
CONF_PAYLOAD_RESET = "payload_reset"
CONF_SUPPORTED_FEATURES = "supported_features"
CONF_ACTION_TEMPLATE = "action_template"
CONF_ACTION_TOPIC = "action_topic"
CONF_BLUE_TEMPLATE = "blue_template"
CONF_BRIGHTNESS_COMMAND_TEMPLATE = "brightness_command_template"
CONF_BRIGHTNESS_COMMAND_TOPIC = "brightness_command_topic"
CONF_BRIGHTNESS_SCALE = "brightness_scale"
CONF_BRIGHTNESS_STATE_TOPIC = "brightness_state_topic"
CONF_BRIGHTNESS_TEMPLATE = "brightness_template"
CONF_BRIGHTNESS_VALUE_TEMPLATE = "brightness_value_template"
CONF_COLOR_MODE_STATE_TOPIC = "color_mode_state_topic"
CONF_COLOR_MODE_VALUE_TEMPLATE = "color_mode_value_template"
CONF_COLOR_TEMP_COMMAND_TEMPLATE = "color_temp_command_template"
CONF_COLOR_TEMP_COMMAND_TOPIC = "color_temp_command_topic"
CONF_COLOR_TEMP_KELVIN = "color_temp_kelvin"
CONF_COLOR_TEMP_TEMPLATE = "color_temp_template"
CONF_COLOR_TEMP_STATE_TOPIC = "color_temp_state_topic"
CONF_COLOR_TEMP_VALUE_TEMPLATE = "color_temp_value_template"
CONF_COMMAND_OFF_TEMPLATE = "command_off_template"
CONF_COMMAND_ON_TEMPLATE = "command_on_template"
CONF_CURRENT_HUMIDITY_TEMPLATE = "current_humidity_template"
CONF_CURRENT_HUMIDITY_TOPIC = "current_humidity_topic"
CONF_CURRENT_TEMP_TEMPLATE = "current_temperature_template"
CONF_CURRENT_TEMP_TOPIC = "current_temperature_topic"
CONF_DIRECTION_COMMAND_TEMPLATE = "direction_command_template"
CONF_DIRECTION_COMMAND_TOPIC = "direction_command_topic"
CONF_DIRECTION_STATE_TOPIC = "direction_state_topic"
CONF_DIRECTION_VALUE_TEMPLATE = "direction_value_template"
CONF_ENABLED_BY_DEFAULT = "enabled_by_default"
CONF_EFFECT_COMMAND_TEMPLATE = "effect_command_template"
CONF_EFFECT_COMMAND_TOPIC = "effect_command_topic"
CONF_EFFECT_LIST = "effect_list"
CONF_EFFECT_STATE_TOPIC = "effect_state_topic"
CONF_EFFECT_TEMPLATE = "effect_template"
CONF_EFFECT_VALUE_TEMPLATE = "effect_value_template"
CONF_ENTITY_PICTURE = "entity_picture"
CONF_EXPIRE_AFTER = "expire_after"
CONF_FAN_MODE_COMMAND_TEMPLATE = "fan_mode_command_template"
CONF_FAN_MODE_COMMAND_TOPIC = "fan_mode_command_topic"
CONF_FAN_MODE_LIST = "fan_modes"
CONF_FAN_MODE_STATE_TEMPLATE = "fan_mode_state_template"
CONF_FAN_MODE_STATE_TOPIC = "fan_mode_state_topic"
CONF_FLASH = "flash"
CONF_FLASH_TIME_LONG = "flash_time_long"
CONF_FLASH_TIME_SHORT = "flash_time_short"
CONF_GET_POSITION_TEMPLATE = "position_template"
CONF_GET_POSITION_TOPIC = "position_topic"
CONF_GREEN_TEMPLATE = "green_template"
CONF_GROUP = "group"
CONF_HS_COMMAND_TEMPLATE = "hs_command_template"
CONF_HS_COMMAND_TOPIC = "hs_command_topic"
CONF_HS_STATE_TOPIC = "hs_state_topic"
CONF_HS_VALUE_TEMPLATE = "hs_value_template"
CONF_HUMIDITY_COMMAND_TEMPLATE = "target_humidity_command_template"
CONF_HUMIDITY_COMMAND_TOPIC = "target_humidity_command_topic"
CONF_HUMIDITY_STATE_TEMPLATE = "target_humidity_state_template"
CONF_HUMIDITY_STATE_TOPIC = "target_humidity_state_topic"
CONF_HUMIDITY_MAX = "max_humidity"
CONF_HUMIDITY_MIN = "min_humidity"
CONF_LAST_RESET_VALUE_TEMPLATE = "last_reset_value_template"
CONF_MAX = "max"
CONF_MAX_KELVIN = "max_kelvin"
CONF_MAX_MIREDS = "max_mireds"
CONF_MIN = "min"
CONF_MIN_KELVIN = "min_kelvin"
CONF_MIN_MIREDS = "min_mireds"
CONF_MODE_COMMAND_TEMPLATE = "mode_command_template"
CONF_MODE_COMMAND_TOPIC = "mode_command_topic"
CONF_MODE_LIST = "modes"
CONF_MODE_STATE_TEMPLATE = "mode_state_template"
CONF_MODE_STATE_TOPIC = "mode_state_topic"
CONF_OFF_DELAY = "off_delay"
CONF_ON_COMMAND_TYPE = "on_command_type"
CONF_OSCILLATION_COMMAND_TOPIC = "oscillation_command_topic"
CONF_OSCILLATION_COMMAND_TEMPLATE = "oscillation_command_template"
CONF_OSCILLATION_STATE_TOPIC = "oscillation_state_topic"
CONF_OSCILLATION_VALUE_TEMPLATE = "oscillation_value_template"
CONF_PATTERN = "pattern"
CONF_PAYLOAD_ARM_AWAY = "payload_arm_away"
CONF_PAYLOAD_ARM_CUSTOM_BYPASS = "payload_arm_custom_bypass"
CONF_PAYLOAD_ARM_HOME = "payload_arm_home"
CONF_PAYLOAD_ARM_NIGHT = "payload_arm_night"
CONF_PAYLOAD_ARM_VACATION = "payload_arm_vacation"
CONF_PAYLOAD_CLOSE = "payload_close"
CONF_PAYLOAD_DISARM = "payload_disarm"
CONF_PAYLOAD_LOCK = "payload_lock"
CONF_PAYLOAD_OPEN = "payload_open"
CONF_PAYLOAD_OSCILLATION_OFF = "payload_oscillation_off"
CONF_PAYLOAD_OSCILLATION_ON = "payload_oscillation_on"
CONF_PAYLOAD_PRESS = "payload_press"
CONF_PAYLOAD_RESET_PERCENTAGE = "payload_reset_percentage"
CONF_PAYLOAD_RESET_PRESET_MODE = "payload_reset_preset_mode"
CONF_PAYLOAD_STOP = "payload_stop"
CONF_PAYLOAD_STOP_TILT = "payload_stop_tilt"
CONF_PAYLOAD_TRIGGER = "payload_trigger"
CONF_PAYLOAD_UNLOCK = "payload_unlock"
CONF_PERCENTAGE_COMMAND_TEMPLATE = "percentage_command_template"
CONF_PERCENTAGE_COMMAND_TOPIC = "percentage_command_topic"
CONF_PERCENTAGE_STATE_TOPIC = "percentage_state_topic"
CONF_PERCENTAGE_VALUE_TEMPLATE = "percentage_value_template"
CONF_POSITION_CLOSED = "position_closed"
CONF_POSITION_OPEN = "position_open"
CONF_POWER_COMMAND_TOPIC = "power_command_topic"
CONF_POWER_COMMAND_TEMPLATE = "power_command_template"
CONF_PRECISION = "precision"
CONF_PRESET_MODE_COMMAND_TEMPLATE = "preset_mode_command_template"
CONF_PRESET_MODE_COMMAND_TOPIC = "preset_mode_command_topic"
CONF_PRESET_MODES_LIST = "preset_modes"
CONF_PRESET_MODE_STATE_TOPIC = "preset_mode_state_topic"
CONF_PRESET_MODE_VALUE_TEMPLATE = "preset_mode_value_template"
CONF_RED_TEMPLATE = "red_template"
CONF_REPORTS_POSITION = "reports_position"
CONF_RGB_COMMAND_TEMPLATE = "rgb_command_template"
CONF_RGB_COMMAND_TOPIC = "rgb_command_topic"
CONF_RGB_STATE_TOPIC = "rgb_state_topic"
CONF_RGB_VALUE_TEMPLATE = "rgb_value_template"
CONF_RGBW_COMMAND_TEMPLATE = "rgbw_command_template"
CONF_RGBW_COMMAND_TOPIC = "rgbw_command_topic"
CONF_RGBW_STATE_TOPIC = "rgbw_state_topic"
CONF_RGBW_VALUE_TEMPLATE = "rgbw_value_template"
CONF_RGBWW_COMMAND_TEMPLATE = "rgbww_command_template"
CONF_RGBWW_COMMAND_TOPIC = "rgbww_command_topic"
CONF_RGBWW_STATE_TOPIC = "rgbww_state_topic"
CONF_RGBWW_VALUE_TEMPLATE = "rgbww_value_template"
CONF_SET_POSITION_TEMPLATE = "set_position_template"
CONF_SET_POSITION_TOPIC = "set_position_topic"
CONF_SPEED_RANGE_MAX = "speed_range_max"
CONF_SPEED_RANGE_MIN = "speed_range_min"
CONF_STATE_CLOSED = "state_closed"
CONF_STATE_CLOSING = "state_closing"
CONF_STATE_JAMMED = "state_jammed"
CONF_STATE_LOCKED = "state_locked"
CONF_STATE_LOCKING = "state_locking"
CONF_STATE_OFF = "state_off"
CONF_STATE_ON = "state_on"
CONF_STATE_OPEN = "state_open"
CONF_STATE_OPENING = "state_opening"
CONF_STATE_STOPPED = "state_stopped"
CONF_STATE_UNLOCKED = "state_unlocked"
CONF_STATE_UNLOCKING = "state_unlocking"
CONF_STEP = "step"
CONF_SUGGESTED_DISPLAY_PRECISION = "suggested_display_precision"
CONF_SUPPORT_DURATION = "support_duration"
CONF_SUPPORT_VOLUME_SET = "support_volume_set"
CONF_SUPPORTED_COLOR_MODES = "supported_color_modes"
CONF_SWING_HORIZONTAL_MODE_COMMAND_TEMPLATE = "swing_horizontal_mode_command_template"
CONF_SWING_HORIZONTAL_MODE_COMMAND_TOPIC = "swing_horizontal_mode_command_topic"
CONF_SWING_HORIZONTAL_MODE_LIST = "swing_horizontal_modes"
CONF_SWING_HORIZONTAL_MODE_STATE_TEMPLATE = "swing_horizontal_mode_state_template"
CONF_SWING_HORIZONTAL_MODE_STATE_TOPIC = "swing_horizontal_mode_state_topic"
CONF_SWING_MODE_COMMAND_TEMPLATE = "swing_mode_command_template"
CONF_SWING_MODE_COMMAND_TOPIC = "swing_mode_command_topic"
CONF_SWING_MODE_LIST = "swing_modes"
CONF_SWING_MODE_STATE_TEMPLATE = "swing_mode_state_template"
CONF_SWING_MODE_STATE_TOPIC = "swing_mode_state_topic"
CONF_TEMP_COMMAND_TEMPLATE = "temperature_command_template"
CONF_TEMP_COMMAND_TOPIC = "temperature_command_topic"
CONF_TEMP_HIGH_COMMAND_TEMPLATE = "temperature_high_command_template"
CONF_TEMP_HIGH_COMMAND_TOPIC = "temperature_high_command_topic"
CONF_TEMP_HIGH_STATE_TEMPLATE = "temperature_high_state_template"
CONF_TEMP_HIGH_STATE_TOPIC = "temperature_high_state_topic"
CONF_TEMP_INITIAL = "initial"
CONF_TEMP_LOW_COMMAND_TEMPLATE = "temperature_low_command_template"
CONF_TEMP_LOW_COMMAND_TOPIC = "temperature_low_command_topic"
CONF_TEMP_LOW_STATE_TEMPLATE = "temperature_low_state_template"
CONF_TEMP_LOW_STATE_TOPIC = "temperature_low_state_topic"
CONF_TEMP_MAX = "max_temp"
CONF_TEMP_MIN = "min_temp"
CONF_TEMP_STATE_TEMPLATE = "temperature_state_template"
CONF_TEMP_STATE_TOPIC = "temperature_state_topic"
CONF_TEMP_STEP = "temp_step"
CONF_TILT_COMMAND_TEMPLATE = "tilt_command_template"
CONF_TILT_COMMAND_TOPIC = "tilt_command_topic"
CONF_TILT_STATUS_TOPIC = "tilt_status_topic"
CONF_TILT_STATUS_TEMPLATE = "tilt_status_template"
CONF_TILT_CLOSED_POSITION = "tilt_closed_value"
CONF_TILT_MAX = "tilt_max"
CONF_TILT_MIN = "tilt_min"
CONF_TILT_OPEN_POSITION = "tilt_opened_value"
CONF_TILT_STATE_OPTIMISTIC = "tilt_optimistic"
CONF_TRANSITION = "transition"
CONF_URL_TEMPLATE = "url_template"
CONF_URL_TOPIC = "url_topic"
CONF_VISIBLE_BY_DEFAULT = "visible_by_default"
CONF_XY_COMMAND_TEMPLATE = "xy_command_template"
CONF_XY_COMMAND_TOPIC = "xy_command_topic"
CONF_XY_STATE_TOPIC = "xy_state_topic"
CONF_XY_VALUE_TEMPLATE = "xy_value_template"
CONF_WHITE_COMMAND_TOPIC = "white_command_topic"
CONF_WHITE_SCALE = "white_scale"
# Config flow constants
CONF_CERTIFICATE = "certificate"
CONF_CLIENT_KEY = "client_key"
CONF_CLIENT_CERT = "client_cert"
CONF_COMPONENTS = "components"
CONF_TLS_INSECURE = "tls_insecure"
# Device and integration info options
CONF_IDENTIFIERS = "identifiers"
CONF_CONNECTIONS = "connections"
CONF_MANUFACTURER = "manufacturer"
CONF_HW_VERSION = "hw_version"
CONF_SW_VERSION = "sw_version"
CONF_SERIAL_NUMBER = "serial_number"
CONF_VIA_DEVICE = "via_device"
CONF_DEPRECATED_VIA_HUB = "via_hub"
CONF_SUGGESTED_AREA = "suggested_area"
CONF_CONFIGURATION_URL = "configuration_url"
CONF_SUPPORT_URL = "support_url"
DEFAULT_ALARM_CONTROL_PANEL_COMMAND_TEMPLATE = "{{action}}"
DEFAULT_BRIGHTNESS = False
DEFAULT_BRIGHTNESS_SCALE = 255
DEFAULT_CLIMATE_INITIAL_TEMPERATURE = 21.0
DEFAULT_PREFIX = "vmqtt"
DEFAULT_BIRTH_WILL_TOPIC = DEFAULT_PREFIX + "/status"
DEFAULT_DISCOVERY = True
DEFAULT_EFFECT = False
DEFAULT_ENCODING = "utf-8"
DEFAULT_FLASH_TIME_LONG = 10
DEFAULT_FLASH_TIME_SHORT = 2
DEFAULT_OPTIMISTIC = False
DEFAULT_ON_COMMAND_TYPE = "last"
DEFAULT_QOS = 0
DEFAULT_PAYLOAD_ARM_AWAY = "ARM_AWAY"
DEFAULT_PAYLOAD_ARM_CUSTOM_BYPASS = "ARM_CUSTOM_BYPASS"
DEFAULT_PAYLOAD_ARM_HOME = "ARM_HOME"
DEFAULT_PAYLOAD_ARM_NIGHT = "ARM_NIGHT"
DEFAULT_PAYLOAD_ARM_VACATION = "ARM_VACATION"
DEFAULT_PAYLOAD_AVAILABLE = "online"
DEFAULT_PAYLOAD_CLOSE = "CLOSE"
DEFAULT_PAYLOAD_DISARM = "DISARM"
DEFAULT_PAYLOAD_LOCK = "LOCK"
DEFAULT_PAYLOAD_NOT_AVAILABLE = "offline"
DEFAULT_PAYLOAD_OFF = "OFF"
DEFAULT_PAYLOAD_ON = "ON"
DEFAULT_PAYLOAD_OPEN = "OPEN"
DEFAULT_PAYLOAD_OSCILLATE_OFF = "oscillate_off"
DEFAULT_PAYLOAD_OSCILLATE_ON = "oscillate_on"
DEFAULT_PAYLOAD_PRESS = "PRESS"
DEFAULT_PAYLOAD_RESET = "None"
DEFAULT_PAYLOAD_STOP = "STOP"
DEFAULT_PAYLOAD_TRIGGER = "TRIGGER"
DEFAULT_PAYLOAD_UNLOCK = "UNLOCK"
DEFAULT_RETAIN = False
DEFAULT_TILT_CLOSED_POSITION = 0
DEFAULT_TILT_MAX = 100
DEFAULT_TILT_MIN = 0
DEFAULT_TILT_OPEN_POSITION = 100
DEFAULT_TILT_OPTIMISTIC = False
DEFAULT_WS_PATH = "/"
DEFAULT_POSITION_CLOSED = 0
DEFAULT_POSITION_OPEN = 100
DEFAULT_SPEED_RANGE_MAX = 100
DEFAULT_SPEED_RANGE_MIN = 1
DEFAULT_STATE_LOCKED = "LOCKED"
DEFAULT_STATE_LOCKING = "LOCKING"
DEFAULT_STATE_OPEN = "OPEN"
DEFAULT_STATE_OPENING = "OPENING"
DEFAULT_STATE_STOPPED = "stopped"
DEFAULT_STATE_UNLOCKED = "UNLOCKED"
DEFAULT_STATE_UNLOCKING = "UNLOCKING"
DEFAULT_STATE_JAMMED = "JAMMED"
DEFAULT_WHITE_SCALE = 255
COVER_PAYLOAD = "cover"
TILT_PAYLOAD = "tilt"
VALUES_ON_COMMAND_TYPE = ["first", "last", "brightness"]
ALARM_CONTROL_PANEL_SUPPORTED_FEATURES = {
"arm_home": AlarmControlPanelEntityFeature.ARM_HOME,
"arm_away": AlarmControlPanelEntityFeature.ARM_AWAY,
"arm_night": AlarmControlPanelEntityFeature.ARM_NIGHT,
"arm_vacation": AlarmControlPanelEntityFeature.ARM_VACATION,
"arm_custom_bypass": AlarmControlPanelEntityFeature.ARM_CUSTOM_BYPASS,
"trigger": AlarmControlPanelEntityFeature.TRIGGER,
}
REMOTE_CODE = "REMOTE_CODE"
REMOTE_CODE_TEXT = "REMOTE_CODE_TEXT"
PROTOCOL_31 = "3.1"
PROTOCOL_311 = "3.1.1"
PROTOCOL_5 = "5"
SUPPORTED_PROTOCOLS = [PROTOCOL_5, PROTOCOL_311, PROTOCOL_31]
TRANSPORT_TCP = "tcp"
TRANSPORT_WEBSOCKETS = "websockets"
DEFAULT_PORT = 1883
DEFAULT_KEEPALIVE = 60
DEFAULT_PROTOCOL = PROTOCOL_5
DEFAULT_TRANSPORT = TRANSPORT_TCP
DEFAULT_BIRTH = {
ATTR_TOPIC: DEFAULT_BIRTH_WILL_TOPIC,
CONF_PAYLOAD: DEFAULT_PAYLOAD_AVAILABLE,
ATTR_QOS: DEFAULT_QOS,
ATTR_RETAIN: DEFAULT_RETAIN,
}
DEFAULT_WILL = {
ATTR_TOPIC: DEFAULT_BIRTH_WILL_TOPIC,
CONF_PAYLOAD: DEFAULT_PAYLOAD_NOT_AVAILABLE,
ATTR_QOS: DEFAULT_QOS,
ATTR_RETAIN: DEFAULT_RETAIN,
}
DOMAIN = "vmqtt"
LOGGER = logging.getLogger(__package__)
MQTT_CONNECTION_STATE = "vmqtt_connection_state"
MQTT_PROCESSED_SUBSCRIPTIONS = "vmqtt_processed_subscriptions"
PAYLOAD_EMPTY_JSON = "{}"
PAYLOAD_NONE = "None"
CONFIG_ENTRY_VERSION = 2
CONFIG_ENTRY_MINOR_VERSION = 1
ENTITY_PLATFORMS = [
Platform.ALARM_CONTROL_PANEL,
Platform.BINARY_SENSOR,
Platform.BUTTON,
Platform.CAMERA,
Platform.CLIMATE,
Platform.COVER,
Platform.DATE,
Platform.DATETIME,
Platform.DEVICE_TRACKER,
Platform.EVENT,
Platform.FAN,
Platform.HUMIDIFIER,
Platform.IMAGE,
Platform.INFRARED,
Platform.LIGHT,
Platform.LAWN_MOWER,
Platform.LOCK,
Platform.NOTIFY,
Platform.NUMBER,
Platform.SCENE,
Platform.SELECT,
Platform.SENSOR,
Platform.SIREN,
Platform.SWITCH,
Platform.TEXT,
Platform.TIME,
Platform.UPDATE,
Platform.VACUUM,
Platform.VALVE,
Platform.WATER_HEATER,
]
TEMPLATE_ERRORS = (jinja2.TemplateError, TemplateError, TypeError, ValueError)
SUPPORTED_COMPONENTS = (
"alarm_control_panel",
"binary_sensor",
"button",
"camera",
"climate",
"cover",
"date",
"datetime",
"device_automation",
"device_tracker",
"event",
"fan",
"humidifier",
"image",
"infrared",
"lawn_mower",
"light",
"lock",
"notify",
"number",
"scene",
"siren",
"select",
"sensor",
"switch",
"tag",
"text",
"time",
"update",
"vacuum",
"valve",
"water_heater",
)
+673
View File
@@ -0,0 +1,673 @@
"""Support for MQTT cover devices."""
from contextlib import suppress
import logging
from typing import Any, override
import probatio
from homeassistant.components import cover
from homeassistant.components.cover import (
ATTR_POSITION,
ATTR_TILT_POSITION,
DEVICE_CLASSES_SCHEMA,
CoverEntity,
CoverEntityFeature,
CoverEntityStateAttribute,
CoverState,
)
from homeassistant.config_entries import ConfigEntry
from homeassistant.const import (
CONF_DEVICE_CLASS,
CONF_NAME,
CONF_OPTIMISTIC,
CONF_VALUE_TEMPLATE,
STATE_CLOSED,
STATE_CLOSING,
STATE_OPEN,
STATE_OPENING,
)
from homeassistant.core import HomeAssistant, callback
from homeassistant.helpers import config_validation as cv
from homeassistant.helpers.entity_platform import AddConfigEntryEntitiesCallback
from homeassistant.helpers.service_info.mqtt import ReceivePayloadType
from homeassistant.helpers.typing import ConfigType, VolSchemaType
from homeassistant.util.json import JSON_DECODE_EXCEPTIONS, json_loads
from homeassistant.util.percentage import (
percentage_to_ranged_value,
ranged_value_to_percentage,
)
from . import subscription
from .config import MQTT_BASE_SCHEMA
from .const import (
CONF_COMMAND_TOPIC,
CONF_GET_POSITION_TEMPLATE,
CONF_GET_POSITION_TOPIC,
CONF_PAYLOAD_CLOSE,
CONF_PAYLOAD_OPEN,
CONF_PAYLOAD_STOP,
CONF_PAYLOAD_STOP_TILT,
CONF_POSITION_CLOSED,
CONF_POSITION_OPEN,
CONF_RETAIN,
CONF_SET_POSITION_TEMPLATE,
CONF_SET_POSITION_TOPIC,
CONF_STATE_CLOSED,
CONF_STATE_CLOSING,
CONF_STATE_OPEN,
CONF_STATE_OPENING,
CONF_STATE_STOPPED,
CONF_STATE_TOPIC,
CONF_TILT_CLOSED_POSITION,
CONF_TILT_COMMAND_TEMPLATE,
CONF_TILT_COMMAND_TOPIC,
CONF_TILT_MAX,
CONF_TILT_MIN,
CONF_TILT_OPEN_POSITION,
CONF_TILT_STATE_OPTIMISTIC,
CONF_TILT_STATUS_TEMPLATE,
CONF_TILT_STATUS_TOPIC,
DEFAULT_OPTIMISTIC,
DEFAULT_PAYLOAD_CLOSE,
DEFAULT_PAYLOAD_OPEN,
DEFAULT_PAYLOAD_STOP,
DEFAULT_POSITION_CLOSED,
DEFAULT_POSITION_OPEN,
DEFAULT_RETAIN,
DEFAULT_STATE_STOPPED,
DEFAULT_TILT_CLOSED_POSITION,
DEFAULT_TILT_MAX,
DEFAULT_TILT_MIN,
DEFAULT_TILT_OPEN_POSITION,
DEFAULT_TILT_OPTIMISTIC,
PAYLOAD_NONE,
)
from .entity import MqttEntity, async_setup_entity_entry_helper
from .models import MqttCommandTemplate, MqttValueTemplate, ReceiveMessage
from .schemas import MQTT_ENTITY_COMMON_SCHEMA
from .util import valid_publish_topic, valid_subscribe_topic
_LOGGER = logging.getLogger(__name__)
PARALLEL_UPDATES = 0
DEFAULT_NAME = "MQTT Cover"
TILT_FEATURES = (
CoverEntityFeature.OPEN_TILT
| CoverEntityFeature.CLOSE_TILT
| CoverEntityFeature.STOP_TILT
| CoverEntityFeature.SET_TILT_POSITION
)
MQTT_COVER_ATTRIBUTES_BLOCKED = frozenset(
{
CoverEntityStateAttribute.CURRENT_POSITION,
CoverEntityStateAttribute.CURRENT_TILT_POSITION,
}
)
def validate_options(config: ConfigType) -> ConfigType:
"""Validate options.
If set position topic is set then get position topic is set as well.
"""
if CONF_SET_POSITION_TOPIC in config and CONF_GET_POSITION_TOPIC not in config:
raise probatio.Invalid(
f"'{CONF_SET_POSITION_TOPIC}' must be set together with"
f" '{CONF_GET_POSITION_TOPIC}'."
)
# if templates are set make sure the topic for the template is also set
if CONF_VALUE_TEMPLATE in config and CONF_STATE_TOPIC not in config:
raise probatio.Invalid(
f"'{CONF_VALUE_TEMPLATE}' must be set together with '{CONF_STATE_TOPIC}'."
)
if CONF_GET_POSITION_TEMPLATE in config and CONF_GET_POSITION_TOPIC not in config:
raise probatio.Invalid(
f"'{CONF_GET_POSITION_TEMPLATE}' must be set together with"
f" '{CONF_GET_POSITION_TOPIC}'."
)
if CONF_SET_POSITION_TEMPLATE in config and CONF_SET_POSITION_TOPIC not in config:
raise probatio.Invalid(
f"'{CONF_SET_POSITION_TEMPLATE}' must be set together with"
f" '{CONF_SET_POSITION_TOPIC}'."
)
if CONF_TILT_COMMAND_TEMPLATE in config and CONF_TILT_COMMAND_TOPIC not in config:
raise probatio.Invalid(
f"'{CONF_TILT_COMMAND_TEMPLATE}' must be set together with"
f" '{CONF_TILT_COMMAND_TOPIC}'."
)
if CONF_TILT_STATUS_TEMPLATE in config and CONF_TILT_STATUS_TOPIC not in config:
raise probatio.Invalid(
f"'{CONF_TILT_STATUS_TEMPLATE}' must be set together with"
f" '{CONF_TILT_STATUS_TOPIC}'."
)
return config
_PLATFORM_SCHEMA_BASE = MQTT_BASE_SCHEMA.extend(
{
probatio.Optional(CONF_COMMAND_TOPIC): valid_publish_topic,
probatio.Optional(CONF_DEVICE_CLASS): probatio.Any(DEVICE_CLASSES_SCHEMA, None),
probatio.Optional(CONF_GET_POSITION_TOPIC): valid_subscribe_topic,
probatio.Optional(CONF_NAME): probatio.Any(cv.string, None),
probatio.Optional(CONF_OPTIMISTIC, default=DEFAULT_OPTIMISTIC): cv.boolean,
probatio.Optional(
CONF_PAYLOAD_CLOSE, default=DEFAULT_PAYLOAD_CLOSE
): probatio.Any(cv.string, None),
probatio.Optional(
CONF_PAYLOAD_OPEN, default=DEFAULT_PAYLOAD_OPEN
): probatio.Any(cv.string, None),
probatio.Optional(
CONF_PAYLOAD_STOP, default=DEFAULT_PAYLOAD_STOP
): probatio.Any(cv.string, None),
probatio.Optional(CONF_POSITION_CLOSED, default=DEFAULT_POSITION_CLOSED): int,
probatio.Optional(CONF_POSITION_OPEN, default=DEFAULT_POSITION_OPEN): int,
probatio.Optional(CONF_RETAIN, default=DEFAULT_RETAIN): cv.boolean,
probatio.Optional(CONF_SET_POSITION_TEMPLATE): cv.template,
probatio.Optional(CONF_SET_POSITION_TOPIC): valid_publish_topic,
probatio.Optional(CONF_STATE_CLOSED, default=STATE_CLOSED): cv.string,
probatio.Optional(CONF_STATE_CLOSING, default=STATE_CLOSING): cv.string,
probatio.Optional(CONF_STATE_OPEN, default=STATE_OPEN): cv.string,
probatio.Optional(CONF_STATE_OPENING, default=STATE_OPENING): cv.string,
probatio.Optional(CONF_STATE_STOPPED, default=DEFAULT_STATE_STOPPED): cv.string,
probatio.Optional(CONF_STATE_TOPIC): valid_subscribe_topic,
probatio.Optional(
CONF_TILT_CLOSED_POSITION, default=DEFAULT_TILT_CLOSED_POSITION
): int,
probatio.Optional(CONF_TILT_COMMAND_TOPIC): valid_publish_topic,
probatio.Optional(CONF_TILT_MAX, default=DEFAULT_TILT_MAX): int,
probatio.Optional(CONF_TILT_MIN, default=DEFAULT_TILT_MIN): int,
probatio.Optional(
CONF_TILT_OPEN_POSITION, default=DEFAULT_TILT_OPEN_POSITION
): int,
probatio.Optional(
CONF_TILT_STATE_OPTIMISTIC, default=DEFAULT_TILT_OPTIMISTIC
): cv.boolean,
probatio.Optional(CONF_TILT_STATUS_TOPIC): valid_subscribe_topic,
probatio.Optional(CONF_TILT_STATUS_TEMPLATE): cv.template,
probatio.Optional(CONF_VALUE_TEMPLATE): cv.template,
probatio.Optional(CONF_GET_POSITION_TEMPLATE): cv.template,
probatio.Optional(CONF_TILT_COMMAND_TEMPLATE): cv.template,
probatio.Optional(
CONF_PAYLOAD_STOP_TILT, default=DEFAULT_PAYLOAD_STOP
): probatio.Any(cv.string, None),
}
).extend(MQTT_ENTITY_COMMON_SCHEMA.schema)
PLATFORM_SCHEMA_MODERN = probatio.All(
_PLATFORM_SCHEMA_BASE,
validate_options,
)
DISCOVERY_SCHEMA = probatio.All(
_PLATFORM_SCHEMA_BASE.extend({}, extra=probatio.REMOVE_EXTRA),
validate_options,
)
async def async_setup_entry(
hass: HomeAssistant,
config_entry: ConfigEntry,
async_add_entities: AddConfigEntryEntitiesCallback,
) -> None:
"""Set up MQTT cover through YAML and through MQTT discovery."""
async_setup_entity_entry_helper(
hass,
config_entry,
MqttCover,
cover.DOMAIN,
async_add_entities,
DISCOVERY_SCHEMA,
PLATFORM_SCHEMA_MODERN,
)
class MqttCover(MqttEntity, CoverEntity):
"""Representation of a cover that can be controlled using MQTT."""
_attr_is_closed: bool | None = None
_attributes_extra_blocked: frozenset[str] = MQTT_COVER_ATTRIBUTES_BLOCKED
_default_name = DEFAULT_NAME
_entity_id_format: str = cover.ENTITY_ID_FORMAT
_optimistic: bool
_tilt_optimistic: bool
_tilt_closed_percentage: int
_tilt_open_percentage: int
_pos_range: tuple[int, int]
_tilt_range: tuple[int, int]
@staticmethod
@override
def config_schema() -> VolSchemaType:
"""Return the config schema."""
return DISCOVERY_SCHEMA
@override
def _setup_from_config(self, config: ConfigType) -> None:
"""Set up cover from config."""
self._pos_range = (config[CONF_POSITION_CLOSED] + 1, config[CONF_POSITION_OPEN])
self._tilt_range = (config[CONF_TILT_MIN] + 1, config[CONF_TILT_MAX])
self._tilt_closed_percentage = ranged_value_to_percentage(
self._tilt_range, config[CONF_TILT_CLOSED_POSITION]
)
self._tilt_open_percentage = ranged_value_to_percentage(
self._tilt_range, config[CONF_TILT_OPEN_POSITION]
)
no_position = (
config.get(CONF_SET_POSITION_TOPIC) is None
and config.get(CONF_GET_POSITION_TOPIC) is None
)
no_state = (
config.get(CONF_COMMAND_TOPIC) is None
and config.get(CONF_STATE_TOPIC) is None
)
no_tilt = (
config.get(CONF_TILT_COMMAND_TOPIC) is None
and config.get(CONF_TILT_STATUS_TOPIC) is None
)
optimistic_position = (
config.get(CONF_SET_POSITION_TOPIC) is not None
and config.get(CONF_GET_POSITION_TOPIC) is None
)
optimistic_state = (
config.get(CONF_COMMAND_TOPIC) is not None
and config.get(CONF_STATE_TOPIC) is None
)
optimistic_tilt = (
config.get(CONF_TILT_COMMAND_TOPIC) is not None
and config.get(CONF_TILT_STATUS_TOPIC) is None
)
self._optimistic = config[CONF_OPTIMISTIC] or (
(no_position or optimistic_position)
and (no_state or optimistic_state)
and (no_tilt or optimistic_tilt)
)
self._attr_assumed_state = self._optimistic
self._tilt_optimistic = (
config[CONF_TILT_STATE_OPTIMISTIC]
or config.get(CONF_TILT_STATUS_TOPIC) is None
)
template_config_attributes = {
"position_open": config[CONF_POSITION_OPEN],
"position_closed": config[CONF_POSITION_CLOSED],
"tilt_min": config[CONF_TILT_MIN],
"tilt_max": config[CONF_TILT_MAX],
}
self._value_template = MqttValueTemplate(
config.get(CONF_VALUE_TEMPLATE), entity=self
).async_render_with_possible_json_value
self._set_position_template = MqttCommandTemplate(
config.get(CONF_SET_POSITION_TEMPLATE), entity=self
).async_render
self._get_position_template = MqttValueTemplate(
config.get(CONF_GET_POSITION_TEMPLATE),
entity=self,
config_attributes=template_config_attributes,
).async_render_with_possible_json_value
self._set_tilt_template = MqttCommandTemplate(
self._config.get(CONF_TILT_COMMAND_TEMPLATE), entity=self
).async_render
self._tilt_status_template = MqttValueTemplate(
self._config.get(CONF_TILT_STATUS_TEMPLATE),
entity=self,
config_attributes=template_config_attributes,
).async_render_with_possible_json_value
self._attr_device_class = self._config.get(CONF_DEVICE_CLASS)
supported_features = CoverEntityFeature(0)
if self._config.get(CONF_COMMAND_TOPIC) is not None:
if self._config.get(CONF_PAYLOAD_OPEN) is not None:
supported_features |= CoverEntityFeature.OPEN
if self._config.get(CONF_PAYLOAD_CLOSE) is not None:
supported_features |= CoverEntityFeature.CLOSE
if self._config.get(CONF_PAYLOAD_STOP) is not None:
supported_features |= CoverEntityFeature.STOP
if self._config.get(CONF_SET_POSITION_TOPIC) is not None:
supported_features |= CoverEntityFeature.SET_POSITION
if self._config.get(CONF_TILT_COMMAND_TOPIC) is not None:
supported_features |= TILT_FEATURES
self._attr_supported_features = supported_features
@callback
def _update_state(self, state: str | None) -> None:
"""Update the cover state."""
if state is None:
# Reset the state to `unknown`
self._attr_is_closed = None
else:
self._attr_is_closed = state == CoverState.CLOSED
self._attr_is_opening = state == CoverState.OPENING
self._attr_is_closing = state == CoverState.CLOSING
@callback
def _tilt_message_received(self, msg: ReceiveMessage) -> None:
"""Handle tilt updates."""
payload = self._tilt_status_template(msg.payload)
if not payload:
_LOGGER.debug("Ignoring empty tilt message from '%s'", msg.topic)
return
self.tilt_payload_received(payload)
@callback
def _state_message_received(self, msg: ReceiveMessage) -> None:
"""Handle new MQTT state messages."""
payload = self._value_template(msg.payload)
if not payload:
_LOGGER.debug("Ignoring empty state message from '%s'", msg.topic)
return
state: str | None
if payload == self._config[CONF_STATE_STOPPED]:
if self._config.get(CONF_GET_POSITION_TOPIC) is not None:
state = (
CoverState.CLOSED
if self._attr_current_cover_position == DEFAULT_POSITION_CLOSED
else CoverState.OPEN
)
else:
state = (
CoverState.CLOSED
if self.state in [CoverState.CLOSED, CoverState.CLOSING]
else CoverState.OPEN
)
elif payload == self._config[CONF_STATE_OPENING]:
state = CoverState.OPENING
elif payload == self._config[CONF_STATE_CLOSING]:
state = CoverState.CLOSING
elif payload == self._config[CONF_STATE_OPEN]:
state = CoverState.OPEN
elif payload == self._config[CONF_STATE_CLOSED]:
state = CoverState.CLOSED
elif payload == PAYLOAD_NONE:
state = None
else:
_LOGGER.warning(
(
"Payload is not supported (e.g. open, closed, opening, closing,"
" stopped): %s"
),
payload,
)
return
self._update_state(state)
@callback
def _position_message_received(self, msg: ReceiveMessage) -> None:
"""Handle new MQTT position messages."""
payload: ReceivePayloadType = self._get_position_template(msg.payload)
payload_dict: Any = None
if not payload:
_LOGGER.debug("Ignoring empty position message from '%s'", msg.topic)
return
with suppress(*JSON_DECODE_EXCEPTIONS):
payload_dict = json_loads(payload)
if payload_dict and isinstance(payload_dict, dict):
if "position" not in payload_dict:
_LOGGER.warning(
"Template (position_template) returned JSON without position"
" attribute"
)
return
if "tilt_position" in payload_dict:
if not self._config.get(CONF_TILT_STATE_OPTIMISTIC):
# reset forced set tilt optimistic
self._tilt_optimistic = False
self.tilt_payload_received(payload_dict["tilt_position"])
payload = payload_dict["position"]
try:
percentage_payload = ranged_value_to_percentage(
self._pos_range, float(payload)
)
except ValueError:
_LOGGER.warning("Payload '%s' is not numeric", payload)
return
self._attr_current_cover_position = min(100, max(0, percentage_payload))
if self._config.get(CONF_STATE_TOPIC) is None:
self._update_state(
CoverState.CLOSED
if self.current_cover_position == 0
else CoverState.OPEN
)
@callback
@override
def _prepare_subscribe_topics(self) -> None:
"""(Re)Subscribe to topics."""
self.add_subscription(
CONF_GET_POSITION_TOPIC,
self._position_message_received,
{
"_attr_current_cover_position",
"_attr_current_cover_tilt_position",
"_attr_is_closed",
"_attr_is_closing",
"_attr_is_opening",
},
)
self.add_subscription(
CONF_STATE_TOPIC,
self._state_message_received,
{"_attr_is_closed", "_attr_is_closing", "_attr_is_opening"},
)
self.add_subscription(
CONF_TILT_STATUS_TOPIC,
self._tilt_message_received,
{"_attr_current_cover_tilt_position"},
)
@override
async def _subscribe_topics(self) -> None:
"""(Re)Subscribe to topics."""
subscription.async_subscribe_topics_internal(self.hass, self._sub_state)
@override
async def async_open_cover(self, **kwargs: Any) -> None:
"""Move the cover up.
This method is a coroutine.
"""
await self.async_publish_with_config(
self._config[CONF_COMMAND_TOPIC], self._config[CONF_PAYLOAD_OPEN]
)
if self._optimistic:
# Optimistically assume that cover has changed state.
self._update_state(CoverState.OPEN)
if self._config.get(CONF_GET_POSITION_TOPIC):
self._attr_current_cover_position = 100
self.async_write_ha_state()
@override
async def async_close_cover(self, **kwargs: Any) -> None:
"""Move the cover down.
This method is a coroutine.
"""
await self.async_publish_with_config(
self._config[CONF_COMMAND_TOPIC], self._config[CONF_PAYLOAD_CLOSE]
)
if self._optimistic:
# Optimistically assume that cover has changed state.
self._update_state(CoverState.CLOSED)
if self._config.get(CONF_GET_POSITION_TOPIC):
self._attr_current_cover_position = 0
self.async_write_ha_state()
@override
async def async_stop_cover(self, **kwargs: Any) -> None:
"""Stop the device.
This method is a coroutine.
"""
await self.async_publish_with_config(
self._config[CONF_COMMAND_TOPIC], self._config[CONF_PAYLOAD_STOP]
)
@override
async def async_open_cover_tilt(self, **kwargs: Any) -> None:
"""Tilt the cover open."""
tilt_open_position = self._config[CONF_TILT_OPEN_POSITION]
variables = {
"tilt_position": tilt_open_position,
"entity_id": self.entity_id,
"position_open": self._config.get(CONF_POSITION_OPEN),
"position_closed": self._config.get(CONF_POSITION_CLOSED),
"tilt_min": self._config.get(CONF_TILT_MIN),
"tilt_max": self._config.get(CONF_TILT_MAX),
}
tilt_payload = self._set_tilt_template(tilt_open_position, variables=variables)
await self.async_publish_with_config(
self._config[CONF_TILT_COMMAND_TOPIC], tilt_payload
)
if self._tilt_optimistic:
self._attr_current_cover_tilt_position = self._tilt_open_percentage
self.async_write_ha_state()
@override
async def async_close_cover_tilt(self, **kwargs: Any) -> None:
"""Tilt the cover closed."""
tilt_closed_position = self._config[CONF_TILT_CLOSED_POSITION]
variables = {
"tilt_position": tilt_closed_position,
"entity_id": self.entity_id,
"position_open": self._config.get(CONF_POSITION_OPEN),
"position_closed": self._config.get(CONF_POSITION_CLOSED),
"tilt_min": self._config.get(CONF_TILT_MIN),
"tilt_max": self._config.get(CONF_TILT_MAX),
}
tilt_payload = self._set_tilt_template(
tilt_closed_position, variables=variables
)
await self.async_publish_with_config(
self._config[CONF_TILT_COMMAND_TOPIC], tilt_payload
)
if self._tilt_optimistic:
self._attr_current_cover_tilt_position = self._tilt_closed_percentage
self.async_write_ha_state()
@override
async def async_set_cover_tilt_position(self, **kwargs: Any) -> None:
"""Move the cover tilt to a specific position."""
tilt_percentage = kwargs[ATTR_TILT_POSITION]
tilt_ranged = round(
percentage_to_ranged_value(self._tilt_range, tilt_percentage)
)
# Handover the tilt after calculated from percent would make it more
# consistent with receiving templates
variables = {
"tilt_position": tilt_percentage,
"entity_id": self.entity_id,
"position_open": self._config.get(CONF_POSITION_OPEN),
"position_closed": self._config.get(CONF_POSITION_CLOSED),
"tilt_min": self._config.get(CONF_TILT_MIN),
"tilt_max": self._config.get(CONF_TILT_MAX),
}
tilt_rendered = self._set_tilt_template(tilt_ranged, variables=variables)
await self.async_publish_with_config(
self._config[CONF_TILT_COMMAND_TOPIC], tilt_rendered
)
if self._tilt_optimistic:
_LOGGER.debug("Set tilt value optimistic")
self._attr_current_cover_tilt_position = tilt_percentage
self.async_write_ha_state()
@override
async def async_stop_cover_tilt(self, **kwargs: Any) -> None:
"""Stop moving the cover tilt."""
await self.async_publish_with_config(
self._config[CONF_TILT_COMMAND_TOPIC], self._config[CONF_PAYLOAD_STOP_TILT]
)
@override
async def async_set_cover_position(self, **kwargs: Any) -> None:
"""Move the cover to a specific position."""
position_percentage = kwargs[ATTR_POSITION]
position_ranged = round(
percentage_to_ranged_value(self._pos_range, position_percentage)
)
variables = {
"position": position_percentage,
"entity_id": self.entity_id,
"position_open": self._config[CONF_POSITION_OPEN],
"position_closed": self._config[CONF_POSITION_CLOSED],
"tilt_min": self._config[CONF_TILT_MIN],
"tilt_max": self._config[CONF_TILT_MAX],
}
position_rendered = self._set_position_template(
position_ranged, variables=variables
)
await self.async_publish_with_config(
self._config[CONF_SET_POSITION_TOPIC], position_rendered
)
if self._optimistic:
self._update_state(
CoverState.CLOSED
if position_percentage <= self._config[CONF_POSITION_CLOSED]
else CoverState.OPEN
)
self._attr_current_cover_position = position_percentage
self.async_write_ha_state()
@override
async def async_toggle_tilt(self, **kwargs: Any) -> None:
"""Toggle the entity."""
if (
self.current_cover_tilt_position is not None
and self.current_cover_tilt_position <= self._tilt_closed_percentage
):
await self.async_open_cover_tilt(**kwargs)
else:
await self.async_close_cover_tilt(**kwargs)
@callback
def tilt_payload_received(self, _payload: Any) -> None:
"""Set the tilt value."""
try:
payload = round(float(_payload))
except ValueError:
_LOGGER.warning("Payload '%s' is not numeric", _payload)
return
if (
self._config[CONF_TILT_MIN] <= payload <= self._config[CONF_TILT_MAX]
or self._config[CONF_TILT_MAX] <= payload <= self._config[CONF_TILT_MIN]
):
level = ranged_value_to_percentage(self._tilt_range, payload)
self._attr_current_cover_tilt_position = level
else:
_LOGGER.warning(
"Payload '%s' is out of range, must be between '%s' and '%s' inclusive",
payload,
self._config[CONF_TILT_MIN],
self._config[CONF_TILT_MAX],
)
+159
View File
@@ -0,0 +1,159 @@
"""Support for MQTT date platform."""
from collections.abc import Callable
import datetime
import logging
from typing import Any, override
from dateutil.parser import ParserError, parse
import probatio
from homeassistant.components import date
from homeassistant.components.date import DateEntity
from homeassistant.config_entries import ConfigEntry
from homeassistant.const import CONF_NAME, CONF_OPTIMISTIC, CONF_VALUE_TEMPLATE
from homeassistant.core import HomeAssistant, callback
from homeassistant.helpers import config_validation as cv
from homeassistant.helpers.entity_platform import AddConfigEntryEntitiesCallback
from homeassistant.helpers.service_info.mqtt import ReceivePayloadType
from homeassistant.helpers.typing import ConfigType, VolSchemaType
from . import subscription
from .config import MQTT_RW_SCHEMA
from .const import (
CONF_COMMAND_TEMPLATE,
CONF_COMMAND_TOPIC,
CONF_STATE_TOPIC,
PAYLOAD_NONE,
)
from .entity import MqttEntity, async_setup_entity_entry_helper
from .models import (
MqttCommandTemplate,
MqttValueTemplate,
PublishPayloadType,
ReceiveMessage,
)
from .schemas import MQTT_ENTITY_COMMON_SCHEMA
_LOGGER = logging.getLogger(__name__)
PARALLEL_UPDATES = 0
DEFAULT_NAME = "MQTT Date"
MQTT_TIME_ATTRIBUTES_BLOCKED: frozenset[str] = frozenset()
PLATFORM_SCHEMA_MODERN = MQTT_RW_SCHEMA.extend(
{
probatio.Optional(CONF_COMMAND_TEMPLATE): cv.template,
probatio.Optional(CONF_NAME): probatio.Any(cv.string, None),
probatio.Optional(CONF_VALUE_TEMPLATE): cv.template,
},
).extend(MQTT_ENTITY_COMMON_SCHEMA.schema)
DISCOVERY_SCHEMA = PLATFORM_SCHEMA_MODERN.extend({}, extra=probatio.REMOVE_EXTRA)
async def async_setup_entry(
hass: HomeAssistant,
config_entry: ConfigEntry,
async_add_entities: AddConfigEntryEntitiesCallback,
) -> None:
"""Set up MQTT date through YAML and through MQTT discovery."""
async_setup_entity_entry_helper(
hass,
config_entry,
MqttDateEntity,
date.DOMAIN,
async_add_entities,
DISCOVERY_SCHEMA,
PLATFORM_SCHEMA_MODERN,
)
class MqttDateEntity(MqttEntity, DateEntity):
"""Representation of the MQTT date entity."""
_attr_native_value: datetime.date | None = None
_attributes_extra_blocked = MQTT_TIME_ATTRIBUTES_BLOCKED
_default_name = DEFAULT_NAME
_entity_id_format = date.ENTITY_ID_FORMAT
_optimistic: bool
_command_template: Callable[
[PublishPayloadType, dict[str, Any]], PublishPayloadType
]
_value_template: Callable[[ReceivePayloadType], ReceivePayloadType]
@staticmethod
@override
def config_schema() -> VolSchemaType:
"""Return the config schema."""
return DISCOVERY_SCHEMA
@override
def _setup_from_config(self, config: ConfigType) -> None:
"""(Re)Setup the entity."""
self._command_template = MqttCommandTemplate(
config.get(CONF_COMMAND_TEMPLATE),
entity=self,
).async_render
self._value_template = MqttValueTemplate(
config.get(CONF_VALUE_TEMPLATE),
entity=self,
).async_render_with_possible_json_value
optimistic: bool = config[CONF_OPTIMISTIC]
self._optimistic = optimistic or config.get(CONF_STATE_TOPIC) is None
self._attr_assumed_state = bool(self._optimistic)
@callback
def _handle_state_message_received(self, msg: ReceiveMessage) -> None:
"""Handle receiving state message via MQTT."""
payload = str(self._value_template(msg.payload))
if payload == PAYLOAD_NONE:
self._attr_native_value = None
return
if payload == "":
_LOGGER.debug(
"Ignoring empty state payload on topic %s for entity %s",
msg.topic,
self.entity_id,
)
return
try:
value = parse(payload)
except ParserError:
_LOGGER.warning(
"Invalid received date expression on topic %s for entity %s, got %s",
msg.topic,
self.entity_id,
msg.payload,
)
else:
self._attr_native_value = value.date()
@callback
@override
def _prepare_subscribe_topics(self) -> None:
"""(Re)Subscribe to topics."""
self.add_subscription(
CONF_STATE_TOPIC,
self._handle_state_message_received,
{"_attr_native_value"},
)
@override
async def _subscribe_topics(self) -> None:
"""(Re)Subscribe to topics."""
subscription.async_subscribe_topics_internal(self.hass, self._sub_state)
@override
async def async_set_value(self, value: datetime.date) -> None:
"""Change the date."""
payload = self._command_template(value.isoformat(), {"value": value})
await self.async_publish_with_config(self._config[CONF_COMMAND_TOPIC], payload)
if self._optimistic:
self._attr_native_value = value
self.async_write_ha_state()
+205
View File
@@ -0,0 +1,205 @@
"""Support for MQTT datetime platform."""
from collections.abc import Callable
import datetime as datetime_library
import logging
from typing import Any, override
from zoneinfo import ZoneInfo
from dateutil.parser import ParserError, parse
from dateutil.tz import UTC
import probatio
from homeassistant.components import datetime
from homeassistant.components.datetime import DateTimeEntity
from homeassistant.config_entries import ConfigEntry
from homeassistant.const import CONF_NAME, CONF_OPTIMISTIC, CONF_VALUE_TEMPLATE
from homeassistant.core import HomeAssistant, callback
from homeassistant.helpers import config_validation as cv
from homeassistant.helpers.entity_platform import AddConfigEntryEntitiesCallback
from homeassistant.helpers.service_info.mqtt import ReceivePayloadType
from homeassistant.helpers.typing import ConfigType, VolSchemaType
from homeassistant.util.dt import async_get_time_zone
from . import subscription
from .config import MQTT_RW_SCHEMA
from .const import (
CONF_COMMAND_TEMPLATE,
CONF_COMMAND_TOPIC,
CONF_STATE_TOPIC,
CONF_TIMEZONE,
PAYLOAD_NONE,
)
from .entity import MqttEntity, async_setup_entity_entry_helper
from .models import (
MqttCommandTemplate,
MqttValueTemplate,
PublishPayloadType,
ReceiveMessage,
)
from .schemas import MQTT_ENTITY_COMMON_SCHEMA
_LOGGER = logging.getLogger(__name__)
PARALLEL_UPDATES = 0
DEFAULT_NAME = "MQTT Date/Time"
MQTT_DATETIME_ATTRIBUTES_BLOCKED: frozenset[str] = frozenset()
PLATFORM_SCHEMA_MODERN = MQTT_RW_SCHEMA.extend(
{
probatio.Optional(CONF_COMMAND_TEMPLATE): cv.template,
probatio.Optional(CONF_NAME): probatio.Any(cv.string, None),
probatio.Optional(CONF_TIMEZONE): str,
probatio.Optional(CONF_VALUE_TEMPLATE): cv.template,
},
).extend(MQTT_ENTITY_COMMON_SCHEMA.schema)
DISCOVERY_SCHEMA = PLATFORM_SCHEMA_MODERN.extend({}, extra=probatio.REMOVE_EXTRA)
async def async_setup_entry(
hass: HomeAssistant,
config_entry: ConfigEntry,
async_add_entities: AddConfigEntryEntitiesCallback,
) -> None:
"""Set up MQTT datetime through YAML and through MQTT discovery."""
async_setup_entity_entry_helper(
hass,
config_entry,
MqttDateTime,
datetime.DOMAIN,
async_add_entities,
DISCOVERY_SCHEMA,
PLATFORM_SCHEMA_MODERN,
)
class MqttDateTime(MqttEntity, DateTimeEntity):
"""Representation of the MQTT datetime entity."""
_attr_native_value: datetime_library.datetime | None = None
_attributes_extra_blocked = MQTT_DATETIME_ATTRIBUTES_BLOCKED
_default_name = DEFAULT_NAME
_entity_id_format = datetime.ENTITY_ID_FORMAT
_zone_info: ZoneInfo | None = None
_time_zone_delta: datetime_library.timedelta | None
_optimistic: bool
_command_template: Callable[
[PublishPayloadType, dict[str, Any]], PublishPayloadType
]
_value_template: Callable[[ReceivePayloadType], ReceivePayloadType]
@staticmethod
@override
def config_schema() -> VolSchemaType:
"""Return the config schema."""
return DISCOVERY_SCHEMA
@override
def _setup_from_config(self, config: ConfigType) -> None:
"""(Re)Setup the entity."""
self._timezone_config = config.get(CONF_TIMEZONE)
self._command_template = MqttCommandTemplate(
config.get(CONF_COMMAND_TEMPLATE),
entity=self,
).async_render
self._value_template = MqttValueTemplate(
config.get(CONF_VALUE_TEMPLATE),
entity=self,
).async_render_with_possible_json_value
optimistic: bool = config[CONF_OPTIMISTIC]
self._optimistic = optimistic or config.get(CONF_STATE_TOPIC) is None
self._attr_assumed_state = bool(self._optimistic)
@override
async def _async_finish_update_config(self) -> None:
"""Called after added to hass and after discovery update."""
self._zone_info = None
if timezone := self._config.get(CONF_TIMEZONE):
self._zone_info = await async_get_time_zone(timezone)
if not self._zone_info:
_LOGGER.warning(
"Ignoring invalid timezone identifier for entity %s, got '%s'",
self.entity_id,
timezone,
)
@callback
def _handle_state_message_received(self, msg: ReceiveMessage) -> None:
"""Handle receiving state message via MQTT."""
payload = str(self._value_template(msg.payload))
if payload == PAYLOAD_NONE:
self._attr_native_value = None
return
if payload == "":
_LOGGER.debug(
"Ignoring empty state payload on topic %s for entity %s",
msg.topic,
self.entity_id,
)
return
try:
value = parse(payload)
except ParserError:
_LOGGER.warning(
"Invalid received date/time expression on topic"
" %s for entity %s, got %s",
msg.topic,
self.entity_id,
msg.payload,
)
return
if self._zone_info is not None:
if value.tzinfo is None:
# Convert to UTC
value = value.replace(tzinfo=self._zone_info).astimezone(UTC)
else:
_LOGGER.warning(
"Date/time expression on topic %s for entity %s was not expected "
"to have timezone info, as this is configured explicitly, got %s",
msg.topic,
self.entity_id,
msg.payload,
)
return
elif value.tzinfo is None:
_LOGGER.warning(
"Date/time expression without required timezone info received "
"on topic %s for entity %s, got %s",
msg.topic,
self.entity_id,
msg.payload,
)
return
self._attr_native_value = value
@callback
@override
def _prepare_subscribe_topics(self) -> None:
"""(Re)Subscribe to topics."""
self.add_subscription(
CONF_STATE_TOPIC,
self._handle_state_message_received,
{"_attr_native_value"},
)
@override
async def _subscribe_topics(self) -> None:
"""(Re)Subscribe to topics."""
subscription.async_subscribe_topics_internal(self.hass, self._sub_state)
@override
async def async_set_value(self, value: datetime_library.datetime) -> None:
"""Change the date and time."""
payload = self._command_template(value.isoformat(), {"value": value})
await self.async_publish_with_config(self._config[CONF_COMMAND_TOPIC], payload)
if self._optimistic:
self._attr_native_value = value
self.async_write_ha_state()
+260
View File
@@ -0,0 +1,260 @@
"""Helper to handle a set of topics to subscribe to."""
from collections import deque
from dataclasses import dataclass
import datetime as dt
import time
from typing import TYPE_CHECKING, Any
from homeassistant.core import HomeAssistant
from homeassistant.helpers import entity_registry as er
from homeassistant.helpers.typing import DiscoveryInfoType
from homeassistant.util import dt as dt_util
from .const import ATTR_DISCOVERY_PAYLOAD, ATTR_DISCOVERY_TOPIC
from .models import DATA_MQTT, PublishPayloadType
STORED_MESSAGES = 10
@dataclass(frozen=True, slots=True)
class TimestampedPublishMessage:
"""MQTT Message."""
topic: str
payload: PublishPayloadType
qos: int
retain: bool
timestamp: float
encoding: str | None
kwargs: dict[str, Any]
def log_message(
hass: HomeAssistant,
entity_id: str,
topic: str,
payload: PublishPayloadType,
qos: int,
retain: bool,
encoding: str | None,
**kwargs: Any,
) -> None:
"""Log an outgoing MQTT message."""
entity_info = hass.data[DATA_MQTT].debug_info_entities.setdefault(
entity_id, {"subscriptions": {}, "discovery_data": {}, "transmitted": {}}
)
if topic not in entity_info["transmitted"]:
entity_info["transmitted"][topic] = {
"messages": deque(maxlen=STORED_MESSAGES),
}
msg = TimestampedPublishMessage(
topic,
payload,
qos,
retain,
timestamp=time.monotonic(),
encoding=encoding,
kwargs=kwargs,
)
entity_info["transmitted"][topic]["messages"].append(msg)
def add_subscription(
hass: HomeAssistant, subscription: str, entity_id: str | None
) -> None:
"""Prepare debug data for subscription."""
if entity_id:
entity_info = hass.data[DATA_MQTT].debug_info_entities.setdefault(
entity_id, {"subscriptions": {}, "discovery_data": {}, "transmitted": {}}
)
if subscription not in entity_info["subscriptions"]:
entity_info["subscriptions"][subscription] = {
"count": 1,
"messages": deque(maxlen=STORED_MESSAGES),
}
else:
entity_info["subscriptions"][subscription]["count"] += 1
def remove_subscription(
hass: HomeAssistant, subscription: str, entity_id: str | None
) -> None:
"""Remove debug data for subscription if it exists."""
if entity_id and entity_id in (
debug_info_entities := hass.data[DATA_MQTT].debug_info_entities
):
subscriptions = debug_info_entities[entity_id]["subscriptions"]
subscriptions[subscription]["count"] -= 1
if not subscriptions[subscription]["count"]:
del subscriptions[subscription]
def add_entity_discovery_data(
hass: HomeAssistant, discovery_data: DiscoveryInfoType, entity_id: str
) -> None:
"""Add discovery data."""
entity_info = hass.data[DATA_MQTT].debug_info_entities.setdefault(
entity_id, {"subscriptions": {}, "discovery_data": {}, "transmitted": {}}
)
entity_info["discovery_data"] = discovery_data
def update_entity_discovery_data(
hass: HomeAssistant, discovery_payload: DiscoveryInfoType, entity_id: str
) -> None:
"""Update discovery data."""
discovery_data = hass.data[DATA_MQTT].debug_info_entities[entity_id][
"discovery_data"
]
if TYPE_CHECKING:
assert discovery_data is not None
discovery_data[ATTR_DISCOVERY_PAYLOAD] = discovery_payload
def remove_entity_data(hass: HomeAssistant, entity_id: str) -> None:
"""Remove discovery data."""
if entity_id in (debug_info_entities := hass.data[DATA_MQTT].debug_info_entities):
del debug_info_entities[entity_id]
def add_trigger_discovery_data(
hass: HomeAssistant,
discovery_hash: tuple[str, str],
discovery_data: DiscoveryInfoType,
device_id: str,
) -> None:
"""Add discovery data."""
hass.data[DATA_MQTT].debug_info_triggers[discovery_hash] = {
"device_id": device_id,
"discovery_data": discovery_data,
}
def update_trigger_discovery_data(
hass: HomeAssistant,
discovery_hash: tuple[str, str],
discovery_payload: DiscoveryInfoType,
) -> None:
"""Update discovery data."""
hass.data[DATA_MQTT].debug_info_triggers[discovery_hash]["discovery_data"][
ATTR_DISCOVERY_PAYLOAD
] = discovery_payload
def remove_trigger_discovery_data(
hass: HomeAssistant, discovery_hash: tuple[str, str]
) -> None:
"""Remove discovery data."""
hass.data[DATA_MQTT].debug_info_triggers.pop(discovery_hash, None)
def _info_for_entity(hass: HomeAssistant, entity_id: str) -> dict[str, Any]:
entity_info = hass.data[DATA_MQTT].debug_info_entities[entity_id]
monotonic_time_diff = time.time() - time.monotonic()
subscriptions = [
{
"topic": topic,
"messages": [
{
"payload": str(msg.payload),
"qos": msg.qos,
"retain": msg.retain,
"time": dt_util.utc_from_timestamp(
msg.timestamp + monotonic_time_diff,
tz=dt.UTC,
),
"topic": msg.topic,
}
for msg in subscription["messages"]
],
}
for topic, subscription in entity_info["subscriptions"].items()
]
transmitted = [
{
"topic": topic,
"messages": [
{
"payload": str(msg.payload),
"qos": msg.qos,
"retain": msg.retain,
"time": dt_util.utc_from_timestamp(
msg.timestamp + monotonic_time_diff,
tz=dt.UTC,
),
"topic": msg.topic,
}
for msg in subscription["messages"]
],
}
for topic, subscription in entity_info["transmitted"].items()
]
discovery_data = {
"topic": entity_info["discovery_data"].get(ATTR_DISCOVERY_TOPIC, ""),
"payload": entity_info["discovery_data"].get(ATTR_DISCOVERY_PAYLOAD, ""),
}
return {
"entity_id": entity_id,
"subscriptions": subscriptions,
"discovery_data": discovery_data,
"transmitted": transmitted,
}
def _info_for_trigger(
hass: HomeAssistant, trigger_key: tuple[str, str]
) -> dict[str, Any]:
trigger = hass.data[DATA_MQTT].debug_info_triggers[trigger_key]
discovery_data = None
if trigger["discovery_data"] is not None:
discovery_data = {
"topic": trigger["discovery_data"][ATTR_DISCOVERY_TOPIC],
"payload": trigger["discovery_data"][ATTR_DISCOVERY_PAYLOAD],
}
return {"discovery_data": discovery_data, "trigger_key": trigger_key}
def info_for_config_entry(hass: HomeAssistant) -> dict[str, list[Any]]:
"""Get debug info for all entities and triggers."""
mqtt_data = hass.data[DATA_MQTT]
mqtt_info: dict[str, list[Any]] = {"entities": [], "triggers": []}
mqtt_info["entities"].extend(
_info_for_entity(hass, entity_id) for entity_id in mqtt_data.debug_info_entities
)
mqtt_info["triggers"].extend(
_info_for_trigger(hass, trigger_key)
for trigger_key in mqtt_data.debug_info_triggers
)
return mqtt_info
def info_for_device(hass: HomeAssistant, device_id: str) -> dict[str, list[Any]]:
"""Get debug info for a device."""
mqtt_data = hass.data[DATA_MQTT]
mqtt_info: dict[str, list[Any]] = {"entities": [], "triggers": []}
entity_registry = er.async_get(hass)
entries = er.async_entries_for_device(
entity_registry, device_id, include_disabled_entities=True
)
mqtt_info["entities"].extend(
_info_for_entity(hass, entry.entity_id)
for entry in entries
if entry.entity_id in mqtt_data.debug_info_entities
)
mqtt_info["triggers"].extend(
_info_for_trigger(hass, trigger_key)
for trigger_key, trigger in mqtt_data.debug_info_triggers.items()
if trigger["device_id"] == device_id
)
return mqtt_info
@@ -0,0 +1,52 @@
"""Provides device automations for MQTT."""
import functools
import probatio
from homeassistant.config_entries import ConfigEntry
from homeassistant.core import HomeAssistant
from homeassistant.helpers.typing import ConfigType, DiscoveryInfoType
from . import device_trigger
from .config import MQTT_BASE_SCHEMA
from .entity import async_setup_non_entity_entry_helper
AUTOMATION_TYPE_TRIGGER = "trigger"
AUTOMATION_TYPES = [AUTOMATION_TYPE_TRIGGER]
AUTOMATION_TYPES_SCHEMA = probatio.In(AUTOMATION_TYPES)
CONF_AUTOMATION_TYPE = "automation_type"
DISCOVERY_SCHEMA = MQTT_BASE_SCHEMA.extend(
{probatio.Required(CONF_AUTOMATION_TYPE): AUTOMATION_TYPES_SCHEMA},
extra=probatio.ALLOW_EXTRA,
)
async def async_setup_mqtt_device_automation_entry(
hass: HomeAssistant, config_entry: ConfigEntry
) -> None:
"""Set up MQTT device automation dynamically through MQTT discovery."""
setup = functools.partial(_async_setup_automation, hass, config_entry=config_entry)
async_setup_non_entity_entry_helper(
hass, "device_automation", setup, DISCOVERY_SCHEMA
)
async def _async_setup_automation(
hass: HomeAssistant,
config: ConfigType,
config_entry: ConfigEntry,
discovery_data: DiscoveryInfoType,
) -> None:
"""Set up an MQTT device automation."""
if config[CONF_AUTOMATION_TYPE] == AUTOMATION_TYPE_TRIGGER:
await device_trigger.async_setup_trigger(
hass, config, config_entry, discovery_data
)
async def async_removed_from_device(hass: HomeAssistant, device_id: str) -> None:
"""Handle Mqtt removed from a device."""
await device_trigger.async_removed_from_device(hass, device_id)
+225
View File
@@ -0,0 +1,225 @@
"""Support for tracking MQTT enabled devices identified."""
from collections.abc import Callable
import logging
from typing import TYPE_CHECKING, Any, override
import probatio
from homeassistant.components import device_tracker
from homeassistant.components.device_tracker import (
SourceType,
TrackerEntity,
TrackerEntityStateAttribute,
)
from homeassistant.config_entries import ConfigEntry
from homeassistant.const import (
CONF_NAME,
CONF_VALUE_TEMPLATE,
STATE_HOME,
STATE_NOT_HOME,
EntityStateAttribute,
)
from homeassistant.core import HomeAssistant, callback
from homeassistant.helpers import config_validation as cv
from homeassistant.helpers.entity_platform import AddConfigEntryEntitiesCallback
from homeassistant.helpers.service_info.mqtt import ReceivePayloadType
from homeassistant.helpers.typing import ConfigType, VolSchemaType
from . import subscription
from .config import MQTT_BASE_SCHEMA
from .const import (
CONF_JSON_ATTRS_TEMPLATE,
CONF_JSON_ATTRS_TOPIC,
CONF_PAYLOAD_RESET,
CONF_STATE_TOPIC,
)
from .entity import MqttEntity, async_setup_entity_entry_helper
from .models import MqttValueTemplate, ReceiveMessage
from .schemas import MQTT_ENTITY_COMMON_SCHEMA
from .util import valid_subscribe_topic
_LOGGER = logging.getLogger(__name__)
PARALLEL_UPDATES = 0
CONF_PAYLOAD_HOME = "payload_home"
CONF_PAYLOAD_NOT_HOME = "payload_not_home"
CONF_SOURCE_TYPE = "source_type"
DEFAULT_PAYLOAD_RESET = "None"
DEFAULT_SOURCE_TYPE = SourceType.GPS
def valid_config(config: ConfigType) -> ConfigType:
"""Check if there is a state topic or json_attributes_topic."""
if CONF_STATE_TOPIC not in config and CONF_JSON_ATTRS_TOPIC not in config:
raise probatio.Invalid(
f"Invalid device tracker config, missing"
f" {CONF_STATE_TOPIC} or"
f" {CONF_JSON_ATTRS_TOPIC}, got: {config}"
)
return config
PLATFORM_SCHEMA_MODERN_BASE = MQTT_BASE_SCHEMA.extend(
{
probatio.Optional(CONF_STATE_TOPIC): valid_subscribe_topic,
probatio.Optional(CONF_VALUE_TEMPLATE): cv.template,
probatio.Optional(CONF_NAME): probatio.Any(cv.string, None),
probatio.Optional(CONF_PAYLOAD_HOME, default=STATE_HOME): cv.string,
probatio.Optional(CONF_PAYLOAD_NOT_HOME, default=STATE_NOT_HOME): cv.string,
probatio.Optional(CONF_PAYLOAD_RESET, default=DEFAULT_PAYLOAD_RESET): cv.string,
probatio.Optional(
CONF_SOURCE_TYPE, default=DEFAULT_SOURCE_TYPE
): probatio.Coerce(SourceType),
},
).extend(MQTT_ENTITY_COMMON_SCHEMA.schema)
PLATFORM_SCHEMA_MODERN = probatio.All(PLATFORM_SCHEMA_MODERN_BASE, valid_config)
DISCOVERY_SCHEMA = probatio.All(
PLATFORM_SCHEMA_MODERN_BASE.extend({}, extra=probatio.REMOVE_EXTRA), valid_config
)
async def async_setup_entry(
hass: HomeAssistant,
config_entry: ConfigEntry,
async_add_entities: AddConfigEntryEntitiesCallback,
) -> None:
"""Set up MQTT event through YAML and through MQTT discovery."""
async_setup_entity_entry_helper(
hass,
config_entry,
MqttDeviceTracker,
device_tracker.DOMAIN,
async_add_entities,
DISCOVERY_SCHEMA,
PLATFORM_SCHEMA_MODERN,
)
class MqttDeviceTracker(MqttEntity, TrackerEntity):
"""Representation of a device tracker using MQTT."""
_default_name = None
_entity_id_format = device_tracker.ENTITY_ID_FORMAT
_location_name: str | None = None
_value_template: Callable[[ReceivePayloadType], ReceivePayloadType]
@staticmethod
@override
def config_schema() -> VolSchemaType:
"""Return the config schema."""
return DISCOVERY_SCHEMA
@override
def _setup_from_config(self, config: ConfigType) -> None:
"""(Re)Setup the entity."""
self._value_template = MqttValueTemplate(
config.get(CONF_VALUE_TEMPLATE), entity=self
).async_render_with_possible_json_value
self._attr_source_type = self._config[CONF_SOURCE_TYPE]
@callback
def _tracker_message_received(self, msg: ReceiveMessage) -> None:
"""Handle new MQTT messages."""
payload = self._value_template(msg.payload)
if not payload.strip(): # No output from template, ignore
_LOGGER.debug(
"Ignoring empty payload '%s' after rendering for topic %s",
payload,
msg.topic,
)
return
if payload == self._config[CONF_PAYLOAD_HOME]:
self._attr_location_name = STATE_HOME
elif payload == self._config[CONF_PAYLOAD_NOT_HOME]:
self._attr_location_name = STATE_NOT_HOME
elif payload == self._config[CONF_PAYLOAD_RESET]:
self._attr_location_name = None
else:
if TYPE_CHECKING:
assert isinstance(msg.payload, str)
self._attr_location_name = msg.payload
@callback
@override
def _prepare_subscribe_topics(self) -> None:
"""(Re)Subscribe to topics."""
self.add_subscription(
CONF_STATE_TOPIC, self._tracker_message_received, {"_attr_location_name"}
)
@override
async def _subscribe_topics(self) -> None:
"""(Re)Subscribe to topics."""
subscription.async_subscribe_topics_internal(self.hass, self._sub_state)
@callback
@override
def _process_update_extra_state_attributes(
self, extra_state_attributes: dict[str, Any]
) -> None:
"""Extract the location from the extra state attributes."""
if (
EntityStateAttribute.LATITUDE in extra_state_attributes
or EntityStateAttribute.LONGITUDE in extra_state_attributes
):
latitude: float | None
longitude: float | None
gps_accuracy: float
if isinstance(
latitude := extra_state_attributes.get(EntityStateAttribute.LATITUDE),
(int, float),
) and isinstance(
longitude := extra_state_attributes.get(EntityStateAttribute.LONGITUDE),
(int, float),
):
self._attr_latitude = latitude
self._attr_longitude = longitude
else:
# Invalid or incomplete coordinates, reset location
self._attr_latitude = None
self._attr_longitude = None
_LOGGER.warning(
"Extra state attributes received at %s and template %s "
"contain invalid or incomplete location info. Got %s",
self._config.get(CONF_JSON_ATTRS_TOPIC),
self._config.get(CONF_JSON_ATTRS_TEMPLATE),
extra_state_attributes,
)
if TrackerEntityStateAttribute.GPS_ACCURACY in extra_state_attributes:
if isinstance(
gps_accuracy := extra_state_attributes[
TrackerEntityStateAttribute.GPS_ACCURACY
],
(int, float),
):
self._attr_location_accuracy = gps_accuracy
else:
_LOGGER.warning(
"Extra state attributes received at %s and template %s "
"contain invalid GPS accuracy setting, "
"gps_accuracy was set to 0 as the default. Got %s",
self._config.get(CONF_JSON_ATTRS_TOPIC),
self._config.get(CONF_JSON_ATTRS_TEMPLATE),
extra_state_attributes,
)
self._attr_location_accuracy = 0
else:
self._attr_location_accuracy = 0
self._attr_extra_state_attributes = {
attribute: value
for attribute, value in extra_state_attributes.items()
if attribute
not in {
TrackerEntityStateAttribute.GPS_ACCURACY,
EntityStateAttribute.LATITUDE,
EntityStateAttribute.LONGITUDE,
}
}
+415
View File
@@ -0,0 +1,415 @@
"""Provides device automations for MQTT."""
from collections.abc import Callable
from dataclasses import dataclass, field
import logging
from typing import TYPE_CHECKING, Any, override
import probatio
from homeassistant.components.device_automation import DEVICE_TRIGGER_BASE_SCHEMA
from homeassistant.config_entries import ConfigEntry
from homeassistant.const import (
CONF_DEVICE,
CONF_DEVICE_ID,
CONF_DOMAIN,
CONF_PLATFORM,
CONF_TYPE,
CONF_VALUE_TEMPLATE,
)
from homeassistant.core import CALLBACK_TYPE, HomeAssistant, callback
from homeassistant.exceptions import HomeAssistantError
from homeassistant.helpers import config_validation as cv
from homeassistant.helpers.trigger import TriggerActionType, TriggerInfo
from homeassistant.helpers.typing import ConfigType, DiscoveryInfoType
from . import debug_info, trigger as mqtt_trigger
from .config import MQTT_BASE_SCHEMA
from .const import (
ATTR_DISCOVERY_HASH,
CONF_ENCODING,
CONF_PAYLOAD,
CONF_QOS,
CONF_TOPIC,
DOMAIN,
)
from .discovery import MQTTDiscoveryPayload, clear_discovery_hash
from .entity import MqttDiscoveryDeviceUpdateMixin, send_discovery_done, update_device
from .models import DATA_MQTT
from .schemas import MQTT_ENTITY_DEVICE_INFO_SCHEMA
_LOGGER = logging.getLogger(__name__)
CONF_AUTOMATION_TYPE = "automation_type"
CONF_DISCOVERY_ID = "discovery_id"
CONF_SUBTYPE = "subtype"
DEFAULT_ENCODING = "utf-8"
DEVICE = "device"
MQTT_TRIGGER_BASE = {
# Trigger when MQTT message is received
CONF_PLATFORM: DEVICE,
CONF_DOMAIN: DOMAIN,
}
TRIGGER_SCHEMA = DEVICE_TRIGGER_BASE_SCHEMA.extend(
{
probatio.Required(CONF_PLATFORM): DEVICE,
probatio.Required(CONF_DOMAIN): DOMAIN,
probatio.Required(CONF_DEVICE_ID): str,
# The use of CONF_DISCOVERY_ID was deprecated in HA Core 2024.2.
# By default, a MQTT device trigger now will be referenced by
# device_id, type and subtype instead.
probatio.Optional(CONF_DISCOVERY_ID): str,
probatio.Required(CONF_TYPE): cv.string,
probatio.Required(CONF_SUBTYPE): cv.string,
},
)
TRIGGER_DISCOVERY_SCHEMA = MQTT_BASE_SCHEMA.extend(
{
probatio.Required(CONF_AUTOMATION_TYPE): str,
probatio.Required(CONF_DEVICE): MQTT_ENTITY_DEVICE_INFO_SCHEMA,
probatio.Optional(CONF_PAYLOAD, default=None): probatio.Any(None, cv.string),
probatio.Required(CONF_SUBTYPE): cv.string,
probatio.Required(CONF_TOPIC): cv.string,
probatio.Required(CONF_TYPE): cv.string,
probatio.Optional(CONF_VALUE_TEMPLATE, default=None): probatio.Any(
None, cv.string
),
},
extra=probatio.REMOVE_EXTRA,
)
LOG_NAME = "Device trigger"
@dataclass(slots=True)
class TriggerInstance:
"""Attached trigger settings."""
action: TriggerActionType
trigger_info: TriggerInfo
trigger: Trigger
remove: CALLBACK_TYPE | None = None
async def async_attach_trigger(self) -> None:
"""Attach MQTT trigger."""
mqtt_config: dict[str, Any] = {
CONF_PLATFORM: DOMAIN,
CONF_TOPIC: self.trigger.topic,
CONF_ENCODING: DEFAULT_ENCODING,
CONF_QOS: self.trigger.qos,
}
if self.trigger.payload:
mqtt_config[CONF_PAYLOAD] = self.trigger.payload
if self.trigger.value_template:
mqtt_config[CONF_VALUE_TEMPLATE] = self.trigger.value_template
mqtt_config = mqtt_trigger.TRIGGER_SCHEMA(mqtt_config)
if self.remove:
self.remove()
self.remove = await mqtt_trigger.async_attach_trigger(
self.trigger.hass,
mqtt_config,
self.action,
self.trigger_info,
)
@dataclass(slots=True, kw_only=True)
class Trigger:
"""Device trigger settings."""
device_id: str
discovery_data: DiscoveryInfoType | None = None
discovery_id: str | None = None
hass: HomeAssistant
payload: str | None
qos: int | None
subtype: str
topic: str | None
type: str
value_template: str | None
trigger_instances: list[TriggerInstance] = field(default_factory=list)
async def add_trigger(
self, action: TriggerActionType, trigger_info: TriggerInfo
) -> Callable[[], None]:
"""Add MQTT trigger."""
instance = TriggerInstance(action, trigger_info, self)
self.trigger_instances.append(instance)
if self.topic is not None:
# If we know about the trigger, subscribe to MQTT topic
await instance.async_attach_trigger()
@callback
def async_remove() -> None:
"""Remove trigger."""
if instance not in self.trigger_instances:
raise HomeAssistantError(
translation_domain=DOMAIN,
translation_key="mqtt_trigger_cannot_remove_twice",
)
if instance.remove:
instance.remove()
self.trigger_instances.remove(instance)
return async_remove
async def update_trigger(self, config: ConfigType) -> None:
"""Update MQTT device trigger."""
self.type = config[CONF_TYPE]
self.subtype = config[CONF_SUBTYPE]
self.payload = config[CONF_PAYLOAD]
self.qos = config[CONF_QOS]
topic_changed = self.topic != config[CONF_TOPIC]
self.topic = config[CONF_TOPIC]
self.value_template = config[CONF_VALUE_TEMPLATE]
# Unsubscribe+subscribe if this trigger is in use and topic has changed
# If topic is same unsubscribe+subscribe will execute in the wrong order
# because unsubscribe is done with help of async_create_task
if topic_changed:
for trig in self.trigger_instances:
await trig.async_attach_trigger()
def detach_trigger(self) -> None:
"""Remove MQTT device trigger."""
# Mark trigger as unknown
self.topic = None
# Unsubscribe if this trigger is in use
for trig in self.trigger_instances:
if trig.remove:
trig.remove()
trig.remove = None
class MqttDeviceTrigger(MqttDiscoveryDeviceUpdateMixin):
"""Setup a MQTT device trigger with auto discovery."""
def __init__(
self,
hass: HomeAssistant,
config: ConfigType,
device_id: str,
discovery_data: DiscoveryInfoType,
config_entry: ConfigEntry,
) -> None:
"""Initialize."""
self._config = config
self._config_entry = config_entry
self.device_id = device_id
self.discovery_data = discovery_data
self.hass = hass
self._mqtt_data = hass.data[DATA_MQTT]
self.trigger_id = f"{device_id}_{config[CONF_TYPE]}_{config[CONF_SUBTYPE]}"
MqttDiscoveryDeviceUpdateMixin.__init__(
self,
hass,
discovery_data,
device_id,
config_entry,
LOG_NAME,
)
async def async_setup(self) -> None:
"""Initialize the device trigger."""
discovery_hash = self.discovery_data[ATTR_DISCOVERY_HASH]
discovery_id = discovery_hash[1]
# The use of CONF_DISCOVERY_ID was deprecated in HA Core 2024.2.
# To make sure old automation keep working we determine the trigger_id
# based on the discovery_id if it is set.
for trigger_id, trigger in self._mqtt_data.device_triggers.items():
if trigger.discovery_id == discovery_id:
self.trigger_id = trigger_id
break
if self.trigger_id not in self._mqtt_data.device_triggers:
self._mqtt_data.device_triggers[self.trigger_id] = Trigger(
hass=self.hass,
device_id=self.device_id,
discovery_data=self.discovery_data,
discovery_id=discovery_id,
type=self._config[CONF_TYPE],
subtype=self._config[CONF_SUBTYPE],
topic=self._config[CONF_TOPIC],
payload=self._config[CONF_PAYLOAD],
qos=self._config[CONF_QOS],
value_template=self._config[CONF_VALUE_TEMPLATE],
)
else:
await self._mqtt_data.device_triggers[self.trigger_id].update_trigger(
self._config
)
debug_info.add_trigger_discovery_data(
self.hass, discovery_hash, self.discovery_data, self.device_id
)
@override
async def async_update(self, discovery_data: MQTTDiscoveryPayload) -> None:
"""Handle MQTT device trigger discovery updates."""
discovery_hash = self.discovery_data[ATTR_DISCOVERY_HASH]
debug_info.update_trigger_discovery_data(
self.hass, discovery_hash, discovery_data
)
config = TRIGGER_DISCOVERY_SCHEMA(discovery_data)
new_trigger_id = f"{self.device_id}_{config[CONF_TYPE]}_{config[CONF_SUBTYPE]}"
if new_trigger_id != self.trigger_id:
mqtt_data = self.hass.data[DATA_MQTT]
if new_trigger_id in mqtt_data.device_triggers:
_LOGGER.error(
"Cannot update device trigger %s due to an existing duplicate "
"device trigger with the same device_id, "
"type and subtype. Got: %s",
discovery_hash,
config,
)
return
# Update trigger_id based index after update of type or subtype
mqtt_data.device_triggers[new_trigger_id] = mqtt_data.device_triggers.pop(
self.trigger_id
)
self.trigger_id = new_trigger_id
update_device(self.hass, self._config_entry, config)
device_trigger: Trigger = self._mqtt_data.device_triggers[self.trigger_id]
await device_trigger.update_trigger(config)
@override
async def async_tear_down(self) -> None:
"""Cleanup device trigger."""
discovery_hash = self.discovery_data[ATTR_DISCOVERY_HASH]
if self.trigger_id in self._mqtt_data.device_triggers:
_LOGGER.info("Removing trigger: %s", discovery_hash)
trigger: Trigger = self._mqtt_data.device_triggers[self.trigger_id]
trigger.discovery_data = None
trigger.detach_trigger()
debug_info.remove_trigger_discovery_data(self.hass, discovery_hash)
async def async_setup_trigger(
hass: HomeAssistant,
config: ConfigType,
config_entry: ConfigEntry,
discovery_data: DiscoveryInfoType,
) -> None:
"""Set up the MQTT device trigger."""
config = TRIGGER_DISCOVERY_SCHEMA(config)
# We update the device based on the trigger config to obtain the device_id.
# In all cases the setup will lead to device entry to be created or updated.
# If the trigger is a duplicate, trigger creation will be cancelled but we allow
# the device data to be updated to not add additional complexity to the code.
device_id = update_device(hass, config_entry, config)
discovery_id = discovery_data[ATTR_DISCOVERY_HASH][1]
trigger_type = config[CONF_TYPE]
trigger_subtype = config[CONF_SUBTYPE]
trigger_id = f"{device_id}_{trigger_type}_{trigger_subtype}"
mqtt_data = hass.data[DATA_MQTT]
if (
trigger_id in mqtt_data.device_triggers
and mqtt_data.device_triggers[trigger_id].discovery_data is not None
):
_LOGGER.error(
"Config for device trigger %s conflicts with existing "
"device trigger, cannot set up trigger, got: %s",
discovery_id,
config,
)
send_discovery_done(hass, discovery_data)
clear_discovery_hash(hass, discovery_data[ATTR_DISCOVERY_HASH])
return
if TYPE_CHECKING:
assert isinstance(device_id, str)
mqtt_device_trigger = MqttDeviceTrigger(
hass, config, device_id, discovery_data, config_entry
)
await mqtt_device_trigger.async_setup()
send_discovery_done(hass, discovery_data)
async def async_removed_from_device(hass: HomeAssistant, device_id: str) -> None:
"""Handle Mqtt removed from a device."""
mqtt_data = hass.data[DATA_MQTT]
triggers = await async_get_triggers(hass, device_id)
for trig in triggers:
trigger_id = f"{device_id}_{trig[CONF_TYPE]}_{trig[CONF_SUBTYPE]}"
if trigger_id in mqtt_data.device_triggers:
device_trigger = mqtt_data.device_triggers.pop(trigger_id)
device_trigger.detach_trigger()
discovery_data = device_trigger.discovery_data
if TYPE_CHECKING:
assert discovery_data is not None
discovery_hash = discovery_data[ATTR_DISCOVERY_HASH]
debug_info.remove_trigger_discovery_data(hass, discovery_hash)
async def async_get_triggers(
hass: HomeAssistant, device_id: str
) -> list[dict[str, str]]:
"""List device triggers for MQTT devices."""
mqtt_data = hass.data[DATA_MQTT]
if not mqtt_data.device_triggers:
return []
return [
{
**MQTT_TRIGGER_BASE,
"device_id": device_id,
"type": trig.type,
"subtype": trig.subtype,
}
for trig in mqtt_data.device_triggers.values()
if trig.device_id == device_id and trig.topic is not None
]
async def async_attach_trigger(
hass: HomeAssistant,
config: ConfigType,
action: TriggerActionType,
trigger_info: TriggerInfo,
) -> CALLBACK_TYPE:
"""Attach a trigger."""
trigger_id: str | None = None
mqtt_data = hass.data[DATA_MQTT]
device_id = config[CONF_DEVICE_ID]
# The use of CONF_DISCOVERY_ID was deprecated in HA Core 2024.2.
# In case CONF_DISCOVERY_ID is still used in an automation,
# we reference the device trigger by discovery_id instead of
# referencing it by device_id, type and subtype, which is the default.
discovery_id: str | None = config.get(CONF_DISCOVERY_ID)
if discovery_id is not None:
for trig_id, trig in mqtt_data.device_triggers.items():
if trig.discovery_id == discovery_id:
trigger_id = trig_id
break
# Reference the device trigger by device_id, type and subtype.
if trigger_id is None:
trigger_type = config[CONF_TYPE]
trigger_subtype = config[CONF_SUBTYPE]
trigger_id = f"{device_id}_{trigger_type}_{trigger_subtype}"
if trigger_id not in mqtt_data.device_triggers:
mqtt_data.device_triggers[trigger_id] = Trigger(
hass=hass,
device_id=device_id,
discovery_data=None,
discovery_id=discovery_id,
type=config[CONF_TYPE],
subtype=config[CONF_SUBTYPE],
topic=None,
payload=None,
qos=None,
value_template=None,
)
return await mqtt_data.device_triggers[trigger_id].add_trigger(action, trigger_info)
+128
View File
@@ -0,0 +1,128 @@
"""Diagnostics support for MQTT."""
from typing import Any
from homeassistant.components import device_tracker
from homeassistant.components.diagnostics import async_redact_data
from homeassistant.config_entries import ConfigEntry
from homeassistant.const import CONF_PASSWORD, CONF_USERNAME, EntityStateAttribute
from homeassistant.core import HomeAssistant, callback
from homeassistant.helpers import device_registry as dr, entity_registry as er
from homeassistant.helpers.device_registry import AnyDeviceEntry
from . import debug_info, is_connected
REDACT_CONFIG = {CONF_PASSWORD, CONF_USERNAME}
REDACT_STATE_DEVICE_TRACKER = {
EntityStateAttribute.LATITUDE,
EntityStateAttribute.LONGITUDE,
}
async def async_get_config_entry_diagnostics(
hass: HomeAssistant, entry: ConfigEntry
) -> dict[str, Any]:
"""Return diagnostics for a config entry."""
return _async_get_diagnostics(hass, entry)
async def async_get_device_diagnostics(
hass: HomeAssistant, entry: ConfigEntry, device: AnyDeviceEntry
) -> dict[str, Any]:
"""Return diagnostics for a device entry."""
return _async_get_diagnostics(hass, entry, device)
@callback
def _async_get_diagnostics(
hass: HomeAssistant,
entry: ConfigEntry,
device: AnyDeviceEntry | None = None,
) -> dict[str, Any]:
"""Return diagnostics for a config entry."""
redacted_config = {
"data": async_redact_data(dict(entry.data), REDACT_CONFIG),
"options": dict(entry.options),
}
data = {
"connected": is_connected(hass),
"mqtt_config": redacted_config,
}
if device:
data["device"] = _async_device_as_dict(hass, device)
data["mqtt_debug_info"] = debug_info.info_for_device(hass, device.id)
else:
device_registry = dr.async_get(hass)
data.update(
devices=[
_async_device_as_dict(hass, device)
for device in dr.async_entries_for_config_entry(
device_registry, entry.entry_id
)
],
mqtt_debug_info=debug_info.info_for_config_entry(hass),
)
return data
@callback
def _async_device_as_dict(
hass: HomeAssistant, device: AnyDeviceEntry
) -> dict[str, Any]:
"""Represent an MQTT device as a dictionary."""
# Gather information how this MQTT device is represented in Home Assistant
entity_registry = er.async_get(hass)
data: dict[str, Any] = {
"id": device.id,
"name": device.name,
"name_by_user": device.name_by_user,
"disabled": device.disabled,
"disabled_by": device.disabled_by,
"entities": [],
}
entities = er.async_entries_for_device(
entity_registry,
device_id=device.id,
include_disabled_entities=True,
)
def _state_dict(entity_entry: er.RegistryEntry) -> dict[str, Any] | None:
state = hass.states.get(entity_entry.entity_id)
if not state:
return None
state_dict = dict(state.as_dict())
# The context doesn't provide useful information in this case.
state_dict.pop("context", None)
# Retract some sensitive state attributes
if state.domain == device_tracker.DOMAIN:
state_dict["attributes"] = async_redact_data(
state_dict["attributes"], REDACT_STATE_DEVICE_TRACKER
)
return state_dict
data["entities"].extend(
{
"device_class": entity_entry.device_class,
"disabled_by": entity_entry.disabled_by,
"disabled": entity_entry.disabled,
"entity_category": entity_entry.entity_category,
"entity_id": entity_entry.entity_id,
"icon": entity_entry.icon,
"original_device_class": entity_entry.original_device_class,
"original_icon": entity_entry.original_icon,
"state": state_dict,
"unit_of_measurement": entity_entry.unit_of_measurement,
}
for entity_entry in entities
if (state_dict := _state_dict(entity_entry)) is not None
)
return data
+733
View File
@@ -0,0 +1,733 @@
"""Support for MQTT discovery."""
import asyncio
from collections import deque
from dataclasses import dataclass
import functools
from itertools import chain
import logging
import re
import time
from typing import TYPE_CHECKING, Any
import probatio
from homeassistant.config_entries import (
SOURCE_MQTT,
ConfigEntry,
signal_discovered_config_entry_removed,
)
from homeassistant.const import CONF_DEVICE, CONF_PLATFORM
from homeassistant.core import HassJobType, HomeAssistant, callback
from homeassistant.helpers import discovery_flow, entity_registry as er
from homeassistant.helpers.dispatcher import (
async_dispatcher_connect,
async_dispatcher_send,
)
from homeassistant.helpers.service_info.mqtt import MqttServiceInfo, ReceivePayloadType
from homeassistant.helpers.typing import DiscoveryInfoType
from homeassistant.loader import async_get_mqtt
from homeassistant.util.json import json_loads_object
from homeassistant.util.signal_type import SignalTypeFormat
from .abbreviations import ABBREVIATIONS, DEVICE_ABBREVIATIONS, ORIGIN_ABBREVIATIONS
from .client import async_subscribe_internal
from .const import (
ATTR_DISCOVERY_HASH,
ATTR_DISCOVERY_PAYLOAD,
ATTR_DISCOVERY_TOPIC,
CONF_AVAILABILITY,
CONF_COMPONENTS,
CONF_DISCOVERY_QOS,
CONF_ORIGIN,
CONF_TOPIC,
DOMAIN,
SUPPORTED_COMPONENTS,
)
from .models import DATA_MQTT, MqttComponentConfig, MqttOriginInfo, ReceiveMessage
from .schemas import DEVICE_DISCOVERY_SCHEMA, MQTT_ORIGIN_INFO_SCHEMA, SHARED_OPTIONS
from .util import (
async_cleanup_device_registry,
async_forward_entry_setup_and_setup_discovery,
)
ABBREVIATIONS_SET = set(ABBREVIATIONS)
DEVICE_ABBREVIATIONS_SET = set(DEVICE_ABBREVIATIONS)
ORIGIN_ABBREVIATIONS_SET = set(ORIGIN_ABBREVIATIONS)
_LOGGER = logging.getLogger(__name__)
TOPIC_MATCHER = re.compile(
r"(?P<component>\w+)/(?:(?P<node_id>[a-zA-Z0-9_-]+)/)"
r"?(?P<object_id>[a-zA-Z0-9_-]+)/config"
)
MQTT_DISCOVERY_UPDATED: SignalTypeFormat[MQTTDiscoveryPayload] = SignalTypeFormat(
"vmqtt_discovery_updated_{}_{}"
)
MQTT_DISCOVERY_NEW: SignalTypeFormat[MQTTDiscoveryPayload] = SignalTypeFormat(
"vmqtt_discovery_new_{}_{}"
)
MQTT_DISCOVERY_DONE: SignalTypeFormat[Any] = SignalTypeFormat(
"vmqtt_discovery_done_{}_{}"
)
TOPIC_BASE = "~"
CONF_MIGRATE_DISCOVERY = "migrate_discovery"
MIGRATE_DISCOVERY_SCHEMA = probatio.Schema(
{probatio.Optional(CONF_MIGRATE_DISCOVERY): True},
)
class MQTTDiscoveryPayload(dict[str, Any]):
"""Class to hold and MQTT discovery payload and discovery data."""
device_discovery: bool = False
migrate_discovery: bool = False
discovery_data: DiscoveryInfoType
@dataclass(frozen=True)
class MQTTIntegrationDiscoveryConfig:
"""Class to hold an integration discovery playload."""
integration: str
msg: ReceiveMessage
@callback
def _async_process_discovery_migration(payload: MQTTDiscoveryPayload) -> bool:
"""Process a discovery migration request in the discovery payload."""
# Allow abbreviation
if migr_discvry := (payload.pop("migr_discvry", None)):
payload[CONF_MIGRATE_DISCOVERY] = migr_discvry
if CONF_MIGRATE_DISCOVERY in payload:
try:
MIGRATE_DISCOVERY_SCHEMA(payload)
except probatio.Invalid as exc:
_LOGGER.warning(exc)
return False
payload.migrate_discovery = True
payload.clear()
return True
return False
def clear_discovery_hash(hass: HomeAssistant, discovery_hash: tuple[str, str]) -> None:
"""Clear entry from already discovered list."""
hass.data[DATA_MQTT].discovery_already_discovered.discard(discovery_hash)
def set_discovery_hash(hass: HomeAssistant, discovery_hash: tuple[str, str]) -> None:
"""Add entry to already discovered list."""
hass.data[DATA_MQTT].discovery_already_discovered.add(discovery_hash)
@callback
def get_origin_log_string(
discovery_payload: MQTTDiscoveryPayload, *, include_url: bool
) -> str:
"""Get the origin information from a discovery payload for logging."""
if CONF_ORIGIN not in discovery_payload:
return ""
origin_info: MqttOriginInfo = discovery_payload[CONF_ORIGIN]
sw_version_log = ""
if sw_version := origin_info.get("sw_version"):
sw_version_log = f", version: {sw_version}"
support_url_log = ""
if include_url and (support_url := get_origin_support_url(discovery_payload)):
support_url_log = f", support URL: {support_url}"
return (
" from external application "
f"{origin_info['name']}{sw_version_log}{support_url_log}"
)
@callback
def get_origin_support_url(discovery_payload: MQTTDiscoveryPayload) -> str | None:
"""Get the origin information support URL from a discovery payload."""
if CONF_ORIGIN not in discovery_payload:
return ""
origin_info: MqttOriginInfo = discovery_payload[CONF_ORIGIN]
return origin_info.get("support_url")
@callback
def async_log_discovery_origin_info(
message: str, discovery_payload: MQTTDiscoveryPayload
) -> None:
"""Log information about the discovery and origin."""
if not _LOGGER.isEnabledFor(logging.DEBUG):
# bail out early if debug logging is disabled
return
_LOGGER.debug(
"%s%s", message, get_origin_log_string(discovery_payload, include_url=True)
)
@callback
def _replace_abbreviations(
payload: dict[str, Any] | str,
abbreviations: dict[str, str],
abbreviations_set: set[str],
) -> None:
"""Replace abbreviations in an MQTT discovery payload."""
if not isinstance(payload, dict):
return
for key in abbreviations_set.intersection(payload):
payload[abbreviations[key]] = payload.pop(key)
@callback
def _replace_all_abbreviations(
discovery_payload: dict[str, Any], component_only: bool = False
) -> None:
"""Replace all abbreviations in an MQTT discovery payload."""
_replace_abbreviations(discovery_payload, ABBREVIATIONS, ABBREVIATIONS_SET)
if CONF_AVAILABILITY in discovery_payload:
for availability_conf in probatio.EnsureList()(
discovery_payload[CONF_AVAILABILITY]
):
_replace_abbreviations(availability_conf, ABBREVIATIONS, ABBREVIATIONS_SET)
if component_only:
return
if CONF_ORIGIN in discovery_payload:
_replace_abbreviations(
discovery_payload[CONF_ORIGIN],
ORIGIN_ABBREVIATIONS,
ORIGIN_ABBREVIATIONS_SET,
)
if CONF_DEVICE in discovery_payload:
_replace_abbreviations(
discovery_payload[CONF_DEVICE],
DEVICE_ABBREVIATIONS,
DEVICE_ABBREVIATIONS_SET,
)
if CONF_COMPONENTS in discovery_payload:
if not isinstance(discovery_payload[CONF_COMPONENTS], dict):
return
for comp_conf in discovery_payload[CONF_COMPONENTS].values():
_replace_all_abbreviations(comp_conf, component_only=True)
@callback
def _replace_topic_base(discovery_payload: MQTTDiscoveryPayload) -> None:
"""Replace topic base in MQTT discovery data."""
base = discovery_payload.pop(TOPIC_BASE)
for key, value in discovery_payload.items():
if isinstance(value, str) and value:
if value[0] == TOPIC_BASE and key.endswith("topic"):
discovery_payload[key] = f"{base}{value[1:]}"
if value[-1] == TOPIC_BASE and key.endswith("topic"):
discovery_payload[key] = f"{value[:-1]}{base}"
if discovery_payload.get(CONF_AVAILABILITY):
for availability_conf in probatio.EnsureList()(
discovery_payload[CONF_AVAILABILITY]
):
if not isinstance(availability_conf, dict):
continue
if topic := str(availability_conf.get(CONF_TOPIC)):
if topic[0] == TOPIC_BASE:
availability_conf[CONF_TOPIC] = f"{base}{topic[1:]}"
if topic[-1] == TOPIC_BASE:
availability_conf[CONF_TOPIC] = f"{topic[:-1]}{base}"
@callback
def _generate_device_config(
hass: HomeAssistant,
object_id: str,
node_id: str | None,
migrate_discovery: bool = False,
) -> MQTTDiscoveryPayload:
"""Generate a cleanup or discovery migration message on device cleanup.
If an empty payload, or a migrate discovery request is received for a device,
we forward an empty payload for all previously discovered components.
"""
mqtt_data = hass.data[DATA_MQTT]
device_node_id: str = f"{node_id} {object_id}" if node_id else object_id
config = MQTTDiscoveryPayload({CONF_DEVICE: {}, CONF_COMPONENTS: {}})
config.migrate_discovery = migrate_discovery
comp_config = config[CONF_COMPONENTS]
for platform, discover_id in mqtt_data.discovery_already_discovered:
ids = discover_id.split(" ")
component_node_id = f"{ids.pop(1)} {ids.pop(0)}" if len(ids) > 2 else ids.pop(0)
component_object_id = " ".join(ids)
if not ids:
continue
if device_node_id == component_node_id:
comp_config[component_object_id] = {CONF_PLATFORM: platform}
return config if comp_config else MQTTDiscoveryPayload({})
@callback
def _parse_device_payload(
hass: HomeAssistant,
payload: ReceivePayloadType,
object_id: str,
node_id: str | None,
) -> MQTTDiscoveryPayload:
"""Parse a device discovery payload.
The device discovery payload is translated info the config payloads for every single
component inside the device based configuration.
An empty payload is translated in a cleanup, which forwards an empty payload to all
removed components.
"""
device_payload = MQTTDiscoveryPayload()
if payload == "":
if not (device_payload := _generate_device_config(hass, object_id, node_id)):
_LOGGER.warning(
"No device components to cleanup for %s, node_id '%s'",
object_id,
node_id,
)
return device_payload
try:
device_payload = MQTTDiscoveryPayload(json_loads_object(payload))
except ValueError:
_LOGGER.warning("Unable to parse JSON %s: '%s'", object_id, payload)
return device_payload
if _async_process_discovery_migration(device_payload):
return _generate_device_config(hass, object_id, node_id, migrate_discovery=True)
_replace_all_abbreviations(device_payload)
try:
DEVICE_DISCOVERY_SCHEMA(device_payload)
except probatio.Invalid as exc:
_LOGGER.warning(
"Invalid MQTT device discovery payload for %s, %s: '%s'",
object_id,
exc,
payload,
)
return MQTTDiscoveryPayload({})
return device_payload
@callback
def _valid_origin_info(discovery_payload: MQTTDiscoveryPayload) -> bool:
"""Parse and validate origin info from a single component discovery payload."""
if CONF_ORIGIN not in discovery_payload:
return True
try:
MQTT_ORIGIN_INFO_SCHEMA(discovery_payload[CONF_ORIGIN])
except Exception as exc: # noqa:BLE001
_LOGGER.warning(
"Unable to parse origin information from discovery message: %s, got %s",
exc,
discovery_payload[CONF_ORIGIN],
)
return False
return True
@callback
def _merge_common_device_options(
component_config: MQTTDiscoveryPayload, device_config: dict[str, Any]
) -> None:
"""Merge common device options with the component config options.
Common options are:
CONF_AVAILABILITY,
CONF_AVAILABILITY_MODE,
CONF_AVAILABILITY_TEMPLATE,
CONF_AVAILABILITY_TOPIC,
CONF_COMMAND_TOPIC,
CONF_ENCODING,
CONF_PAYLOAD_AVAILABLE,
CONF_PAYLOAD_NOT_AVAILABLE,
CONF_STATE_TOPIC,
CONF_QOS
Common options in the body of the device based config are inherited into
the component. Unless the option is explicitly specified at component level,
in that case the option at component level will override the common option.
"""
for option in SHARED_OPTIONS:
if option in device_config and option not in component_config:
component_config[option] = device_config.get(option)
async def async_start( # noqa: C901
hass: HomeAssistant, discovery_topic: str, config_entry: ConfigEntry
) -> None:
"""Start MQTT Discovery."""
mqtt_data = hass.data[DATA_MQTT]
platform_setup_lock: dict[str, asyncio.Lock] = {}
integration_discovery_messages: dict[str, MQTTIntegrationDiscoveryConfig] = {}
@callback
def _async_add_component(discovery_payload: MQTTDiscoveryPayload) -> None:
"""Add a component from a discovery message."""
discovery_hash = discovery_payload.discovery_data[ATTR_DISCOVERY_HASH]
component, discovery_id = discovery_hash
message = f"Found new component: {component} {discovery_id}"
async_log_discovery_origin_info(message, discovery_payload)
mqtt_data.discovery_already_discovered.add(discovery_hash)
async_dispatcher_send(
hass, MQTT_DISCOVERY_NEW.format(component, "mqtt"), discovery_payload
)
async def _async_component_setup(
component: str, discovery_payload: MQTTDiscoveryPayload
) -> None:
"""Perform component set up."""
async with platform_setup_lock.setdefault(component, asyncio.Lock()):
if component not in mqtt_data.platforms_loaded:
await async_forward_entry_setup_and_setup_discovery(
hass, config_entry, {component}
)
_async_add_component(discovery_payload)
@callback
def async_discovery_message_received(msg: ReceiveMessage) -> None:
"""Process the received message."""
mqtt_data.last_discovery = msg.timestamp
payload = msg.payload
topic = msg.topic
topic_trimmed = topic.replace(f"{discovery_topic}/", "", 1)
if not (match := TOPIC_MATCHER.match(topic_trimmed)):
if topic_trimmed.endswith("config"):
_LOGGER.warning(
(
"Received message on illegal discovery topic '%s'. The topic"
" contains non allowed characters. For more information see "
"https://www.home-assistant.io/integrations/mqtt/#discovery-topic"
),
topic,
)
return
component, node_id, object_id = match.groups()
discovered_components: list[MqttComponentConfig] = []
if component == CONF_DEVICE:
# Process device based discovery message and regenerate
# cleanup config for the all the components that are being removed.
# This is done when a component in the device config is omitted and detected
# as being removed, or when the device config update payload is empty.
# In that case this will regenerate a cleanup message for all every already
# discovered components that were linked to the initial device discovery.
device_discovery_payload = _parse_device_payload(
hass, payload, object_id, node_id
)
if not device_discovery_payload:
return
device_config: dict[str, Any]
origin_config: dict[str, Any] | None
component_configs: dict[str, dict[str, Any]]
device_config = device_discovery_payload[CONF_DEVICE]
origin_config = device_discovery_payload.get(CONF_ORIGIN)
component_configs = device_discovery_payload[CONF_COMPONENTS]
for component_id, config in component_configs.items():
component = config.pop(CONF_PLATFORM)
# The object_id in the device discovery topic is the unique identifier.
# It is used as node_id for the components it contains.
component_node_id = object_id
# The component_id in the discovery playload is used as object_id
# If we have an additional node_id in the discovery topic,
# we extend the component_id with it.
component_object_id = (
f"{node_id} {component_id}" if node_id else component_id
)
# We add wrapper to the discovery payload with the discovery data.
# If the dict is empty after removing the platform, the payload is
# assumed to remove the existing config and we do not want to add
# device or orig or shared availability attributes.
if discovery_payload := MQTTDiscoveryPayload(config):
discovery_payload[CONF_DEVICE] = device_config
discovery_payload[CONF_ORIGIN] = origin_config
# Only assign shared config options
# when they are not set at entity level
_merge_common_device_options(
discovery_payload, device_discovery_payload
)
discovery_payload.device_discovery = True
discovery_payload.migrate_discovery = (
device_discovery_payload.migrate_discovery
)
discovered_components.append(
MqttComponentConfig(
component,
component_object_id,
component_node_id,
discovery_payload,
)
)
_LOGGER.debug(
"Process device discovery payload %s", device_discovery_payload
)
device_discovery_id = f"{node_id} {object_id}" if node_id else object_id
message = f"Processing device discovery for '{device_discovery_id}'"
async_log_discovery_origin_info(
message, MQTTDiscoveryPayload(device_discovery_payload)
)
else:
# Process component based discovery message
try:
discovery_payload = MQTTDiscoveryPayload(
json_loads_object(payload) if payload else {}
)
except ValueError:
_LOGGER.warning("Unable to parse JSON %s: '%s'", object_id, payload)
return
if not _async_process_discovery_migration(discovery_payload):
_replace_all_abbreviations(discovery_payload)
if not _valid_origin_info(discovery_payload):
return
discovered_components.append(
MqttComponentConfig(component, object_id, node_id, discovery_payload)
)
discovery_pending_discovered = mqtt_data.discovery_pending_discovered
for component_config in discovered_components:
component = component_config.component
node_id = component_config.node_id
object_id = component_config.object_id
discovery_payload = component_config.discovery_payload
if TOPIC_BASE in discovery_payload:
_replace_topic_base(discovery_payload)
# If present, the node_id will be included in the discovery_id.
discovery_id = f"{node_id} {object_id}" if node_id else object_id
discovery_hash = (component, discovery_id)
# Attach MQTT topic to the payload, used for debug prints
discovery_payload.discovery_data = {
ATTR_DISCOVERY_HASH: discovery_hash,
ATTR_DISCOVERY_PAYLOAD: discovery_payload,
ATTR_DISCOVERY_TOPIC: topic,
}
if discovery_hash in discovery_pending_discovered:
pending = discovery_pending_discovered[discovery_hash]["pending"]
pending.appendleft(discovery_payload)
_LOGGER.debug(
"Component has already been discovered: %s %s, queuing update",
component,
discovery_id,
)
return
async_process_discovery_payload(component, discovery_id, discovery_payload)
@callback
def async_process_discovery_payload(
component: str, discovery_id: str, payload: MQTTDiscoveryPayload
) -> None:
"""Process the payload of a new discovery."""
_LOGGER.debug("Process component discovery payload %s", payload)
discovery_hash = (component, discovery_id)
already_discovered = discovery_hash in mqtt_data.discovery_already_discovered
if (
already_discovered or payload
) and discovery_hash not in mqtt_data.discovery_pending_discovered:
discovery_pending_discovered = mqtt_data.discovery_pending_discovered
@callback
def discovery_done(_: Any) -> None:
pending = discovery_pending_discovered[discovery_hash]["pending"]
_LOGGER.debug("Pending discovery for %s: %s", discovery_hash, pending)
if not pending:
discovery_pending_discovered[discovery_hash]["unsub"]()
discovery_pending_discovered.pop(discovery_hash)
else:
payload = pending.pop()
async_process_discovery_payload(component, discovery_id, payload)
discovery_pending_discovered[discovery_hash] = {
"unsub": async_dispatcher_connect(
hass,
MQTT_DISCOVERY_DONE.format(*discovery_hash),
discovery_done,
),
"pending": deque(),
}
if component not in mqtt_data.platforms_loaded and payload:
# Load component first
config_entry.async_create_task(
hass, _async_component_setup(component, payload)
)
elif already_discovered:
# Dispatch update
message = (
f"Component has already been discovered:"
f" {component} {discovery_id}, sending update"
)
async_log_discovery_origin_info(message, payload)
async_dispatcher_send(
hass, MQTT_DISCOVERY_UPDATED.format(*discovery_hash), payload
)
elif payload:
_async_add_component(payload)
else:
entity_registry = er.async_get(hass)
if (
(
entity_hash := mqtt_data.discovery_discovered_and_disabled.pop(
discovery_hash, None
)
)
and (entity_id := entity_registry.entities.get_entity_id(entity_hash))
and (entity_entry := entity_registry.async_get(entity_id))
):
# Cleanup discovered disabled entity / device
entity_registry.async_remove(entity_id)
hass.async_create_task(
async_cleanup_device_registry(
hass,
device_id=entity_entry.device_id,
config_entry_id=entity_entry.config_entry_id,
),
name=f"Check for cleanup device registry for {entity_id}",
)
# Finish handling discovery message
async_dispatcher_send(
hass, MQTT_DISCOVERY_DONE.format(*discovery_hash), None
)
discovery_qos: int = config_entry.options.get(CONF_DISCOVERY_QOS, 0)
mqtt_data.discovery_unsubscribe = [
async_subscribe_internal(
hass,
topic,
async_discovery_message_received,
discovery_qos,
job_type=HassJobType.Callback,
)
# Subscribe first for platform discovery wildcard topics first,
# and then subscribe device discovery wildcard topics.
for topic in chain(
(
f"{discovery_topic}/{component}/+/config"
for component in SUPPORTED_COMPONENTS
),
(
f"{discovery_topic}/{component}/+/+/config"
for component in SUPPORTED_COMPONENTS
),
(
f"{discovery_topic}/device/+/config",
f"{discovery_topic}/device/+/+/config",
),
)
]
mqtt_data.last_discovery = time.monotonic()
mqtt_integrations = await async_get_mqtt(hass)
integration_unsubscribe = mqtt_data.integration_unsubscribe
async def _async_handle_config_entry_removed(entry: ConfigEntry) -> None:
"""Handle integration config entry changes."""
for discovery_key in entry.discovery_keys[DOMAIN]:
if (
discovery_key.version != 1
or not isinstance(discovery_key.key, str)
or discovery_key.key not in integration_discovery_messages
):
continue
topic = discovery_key.key
discovery_message = integration_discovery_messages[topic]
del integration_discovery_messages[topic]
_LOGGER.debug("Rediscover service on topic %s", topic)
# Initiate re-discovery
await async_integration_message_received(
discovery_message.integration, discovery_message.msg
)
mqtt_data.discovery_unsubscribe.append(
async_dispatcher_connect(
hass,
signal_discovered_config_entry_removed(DOMAIN),
_async_handle_config_entry_removed,
)
)
async def async_integration_message_received(
integration: str, msg: ReceiveMessage
) -> None:
"""Process the received message."""
if (
msg.topic in integration_discovery_messages
and integration_discovery_messages[msg.topic].msg.payload == msg.payload
):
_LOGGER.debug(
"Ignoring already processed discovery message for '%s' on topic %s: %s",
integration,
msg.topic,
msg.payload,
)
return
if TYPE_CHECKING:
assert mqtt_data.data_config_flow_lock
# Lock to prevent initiating many parallel config flows.
# Note: The lock is not intended to prevent a race, only for performance
async with mqtt_data.data_config_flow_lock:
data = MqttServiceInfo(
topic=msg.topic,
payload=msg.payload,
qos=msg.qos,
retain=msg.retain,
subscribed_topic=msg.subscribed_topic,
timestamp=msg.timestamp,
)
discovery_key = discovery_flow.DiscoveryKey(
domain=DOMAIN, key=msg.topic, version=1
)
discovery_flow.async_create_flow(
hass,
integration,
{"source": SOURCE_MQTT},
data,
discovery_key=discovery_key,
)
if msg.payload:
# Update the last discovered config message
integration_discovery_messages[msg.topic] = (
MQTTIntegrationDiscoveryConfig(integration=integration, msg=msg)
)
elif msg.topic in integration_discovery_messages:
# Cleanup cache if discovery payload is empty
del integration_discovery_messages[msg.topic]
integration_unsubscribe.update(
{
f"{integration}_{topic}": async_subscribe_internal(
hass,
topic,
functools.partial(async_integration_message_received, integration),
discovery_qos,
job_type=HassJobType.Coroutinefunction,
)
for integration, topics in mqtt_integrations.items()
for topic in topics
}
)
async def async_stop(hass: HomeAssistant) -> None:
"""Stop MQTT Discovery."""
mqtt_data = hass.data[DATA_MQTT]
for unsub in mqtt_data.discovery_unsubscribe:
unsub()
mqtt_data.discovery_unsubscribe = []
for key, unsub in list(mqtt_data.integration_unsubscribe.items()):
unsub()
mqtt_data.integration_unsubscribe.pop(key)
File diff suppressed because it is too large Load Diff
+198
View File
@@ -0,0 +1,198 @@
"""Support for MQTT events."""
from collections.abc import Callable
import logging
from typing import Any, override
import probatio
from homeassistant.components import event
from homeassistant.components.event import (
ENTITY_ID_FORMAT,
EventDeviceClass,
EventEntity,
EventEntityCapabilityAttribute,
EventEntityStateAttribute,
)
from homeassistant.config_entries import ConfigEntry
from homeassistant.const import CONF_DEVICE_CLASS, CONF_NAME, CONF_VALUE_TEMPLATE
from homeassistant.core import HomeAssistant, callback
from homeassistant.helpers import config_validation as cv
from homeassistant.helpers.entity_platform import AddConfigEntryEntitiesCallback
from homeassistant.helpers.service_info.mqtt import ReceivePayloadType
from homeassistant.helpers.typing import ConfigType, VolSchemaType
from homeassistant.util.json import JSON_DECODE_EXCEPTIONS, json_loads_object
from . import subscription
from .config import MQTT_RO_SCHEMA
from .const import CONF_STATE_TOPIC, PAYLOAD_EMPTY_JSON, PAYLOAD_NONE
from .entity import MqttEntity, async_setup_entity_entry_helper
from .models import (
DATA_MQTT,
MqttValueTemplate,
MqttValueTemplateException,
PayloadSentinel,
ReceiveMessage,
)
from .schemas import MQTT_ENTITY_COMMON_SCHEMA
_LOGGER = logging.getLogger(__name__)
PARALLEL_UPDATES = 0
CONF_EVENT_TYPES = "event_types"
MQTT_EVENT_ATTRIBUTES_BLOCKED = frozenset(
{
EventEntityStateAttribute.EVENT_TYPE,
EventEntityCapabilityAttribute.EVENT_TYPES,
}
)
DEFAULT_NAME = "MQTT Event"
DEFAULT_FORCE_UPDATE = False
DEVICE_CLASS_SCHEMA = probatio.All(probatio.Lower, probatio.Coerce(EventDeviceClass))
_PLATFORM_SCHEMA_BASE = MQTT_RO_SCHEMA.extend(
{
probatio.Optional(CONF_DEVICE_CLASS): DEVICE_CLASS_SCHEMA,
probatio.Optional(CONF_NAME): probatio.Any(None, cv.string),
probatio.Required(CONF_EVENT_TYPES): probatio.All(
probatio.EnsureList(), [cv.string]
),
}
).extend(MQTT_ENTITY_COMMON_SCHEMA.schema)
PLATFORM_SCHEMA_MODERN = probatio.All(
_PLATFORM_SCHEMA_BASE,
)
DISCOVERY_SCHEMA = probatio.All(
_PLATFORM_SCHEMA_BASE.extend({}, extra=probatio.REMOVE_EXTRA),
)
async def async_setup_entry(
hass: HomeAssistant,
config_entry: ConfigEntry,
async_add_entities: AddConfigEntryEntitiesCallback,
) -> None:
"""Set up MQTT event through YAML and through MQTT discovery."""
async_setup_entity_entry_helper(
hass,
config_entry,
MqttEvent,
event.DOMAIN,
async_add_entities,
DISCOVERY_SCHEMA,
PLATFORM_SCHEMA_MODERN,
)
class MqttEvent(MqttEntity, EventEntity):
"""Representation of an event that can be updated using MQTT."""
_default_name = DEFAULT_NAME
_entity_id_format = ENTITY_ID_FORMAT
_attributes_extra_blocked = MQTT_EVENT_ATTRIBUTES_BLOCKED
_template: Callable[[ReceivePayloadType, PayloadSentinel], ReceivePayloadType]
@staticmethod
@override
def config_schema() -> VolSchemaType:
"""Return the config schema."""
return DISCOVERY_SCHEMA
@override
def _setup_from_config(self, config: ConfigType) -> None:
"""(Re)Setup the entity."""
self._attr_device_class = config.get(CONF_DEVICE_CLASS)
self._attr_event_types = config[CONF_EVENT_TYPES]
self._template = MqttValueTemplate(
self._config.get(CONF_VALUE_TEMPLATE), entity=self
).async_render_with_possible_json_value
@callback
def _event_received(self, msg: ReceiveMessage) -> None:
"""Handle new MQTT messages."""
if msg.retain:
_LOGGER.debug(
"Ignoring event trigger from replayed retained"
" payload '%s' on topic %s",
msg.payload,
msg.topic,
)
return
event_attributes: dict[str, Any] = {}
event_type: str
try:
payload = self._template(msg.payload, PayloadSentinel.DEFAULT)
except MqttValueTemplateException as exc:
_LOGGER.warning(exc)
return
if (
not payload
or payload is PayloadSentinel.DEFAULT
or payload in (PAYLOAD_NONE, PAYLOAD_EMPTY_JSON)
):
_LOGGER.debug(
"Ignoring empty payload '%s' after rendering for topic %s",
payload,
msg.topic,
)
return
try:
event_attributes = json_loads_object(payload)
event_type = str(event_attributes.pop(event.ATTR_EVENT_TYPE))
_LOGGER.debug(
(
"JSON event data detected after processing payload '%s' on"
" topic %s, type %s, attributes %s"
),
payload,
msg.topic,
event_type,
event_attributes,
)
except KeyError:
_LOGGER.warning(
"`event_type` missing in JSON event payload, '%s' on topic %s",
payload,
msg.topic,
)
return
except JSON_DECODE_EXCEPTIONS:
_LOGGER.warning(
(
"No valid JSON event payload detected, "
"value after processing payload"
" '%s' on topic %s"
),
payload,
msg.topic,
)
return
try:
self._trigger_event(event_type, event_attributes)
except ValueError:
_LOGGER.warning(
"Invalid event type %s for %s received on topic %s, payload %s",
event_type,
self.entity_id,
msg.topic,
payload,
)
return
mqtt_data = self.hass.data[DATA_MQTT]
mqtt_data.state_write_requests.write_state_request(self)
@callback
@override
def _prepare_subscribe_topics(self) -> None:
"""(Re)Subscribe to topics."""
self.add_subscription(CONF_STATE_TOPIC, self._event_received, None)
@override
async def _subscribe_topics(self) -> None:
"""(Re)Subscribe to topics."""
subscription.async_subscribe_topics_internal(self.hass, self._sub_state)
+572
View File
@@ -0,0 +1,572 @@
"""Support for MQTT fans."""
from collections.abc import Callable
import logging
import math
from typing import Any, override
import probatio
from homeassistant.components import fan
from homeassistant.components.fan import (
ATTR_DIRECTION,
ATTR_OSCILLATING,
ATTR_PERCENTAGE,
ATTR_PRESET_MODE,
FanEntity,
FanEntityCapabilityAttribute,
FanEntityFeature,
FanEntityStateAttribute,
)
from homeassistant.config_entries import ConfigEntry
from homeassistant.const import (
CONF_NAME,
CONF_OPTIMISTIC,
CONF_PAYLOAD_OFF,
CONF_PAYLOAD_ON,
CONF_STATE,
)
from homeassistant.core import HomeAssistant, callback
from homeassistant.helpers import config_validation as cv
from homeassistant.helpers.entity_platform import AddConfigEntryEntitiesCallback
from homeassistant.helpers.service_info.mqtt import ReceivePayloadType
from homeassistant.helpers.template import Template
from homeassistant.helpers.typing import ConfigType, VolSchemaType
from homeassistant.util.percentage import (
percentage_to_ranged_value,
ranged_value_to_percentage,
)
from homeassistant.util.scaling import int_states_in_range
from . import subscription
from .config import MQTT_RW_SCHEMA
from .const import (
CONF_COMMAND_TEMPLATE,
CONF_COMMAND_TOPIC,
CONF_DIRECTION_COMMAND_TEMPLATE,
CONF_DIRECTION_COMMAND_TOPIC,
CONF_DIRECTION_STATE_TOPIC,
CONF_DIRECTION_VALUE_TEMPLATE,
CONF_OSCILLATION_COMMAND_TEMPLATE,
CONF_OSCILLATION_COMMAND_TOPIC,
CONF_OSCILLATION_STATE_TOPIC,
CONF_OSCILLATION_VALUE_TEMPLATE,
CONF_PAYLOAD_OSCILLATION_OFF,
CONF_PAYLOAD_OSCILLATION_ON,
CONF_PAYLOAD_RESET_PERCENTAGE,
CONF_PAYLOAD_RESET_PRESET_MODE,
CONF_PERCENTAGE_COMMAND_TEMPLATE,
CONF_PERCENTAGE_COMMAND_TOPIC,
CONF_PERCENTAGE_STATE_TOPIC,
CONF_PERCENTAGE_VALUE_TEMPLATE,
CONF_PRESET_MODE_COMMAND_TEMPLATE,
CONF_PRESET_MODE_COMMAND_TOPIC,
CONF_PRESET_MODE_STATE_TOPIC,
CONF_PRESET_MODE_VALUE_TEMPLATE,
CONF_PRESET_MODES_LIST,
CONF_SPEED_RANGE_MAX,
CONF_SPEED_RANGE_MIN,
CONF_STATE_TOPIC,
CONF_STATE_VALUE_TEMPLATE,
DEFAULT_PAYLOAD_OFF,
DEFAULT_PAYLOAD_ON,
DEFAULT_PAYLOAD_OSCILLATE_OFF,
DEFAULT_PAYLOAD_OSCILLATE_ON,
DEFAULT_PAYLOAD_RESET,
DEFAULT_SPEED_RANGE_MAX,
DEFAULT_SPEED_RANGE_MIN,
PAYLOAD_NONE,
)
from .entity import MqttEntity, async_setup_entity_entry_helper
from .models import (
MqttCommandTemplate,
MqttValueTemplate,
PublishPayloadType,
ReceiveMessage,
)
from .schemas import MQTT_ENTITY_COMMON_SCHEMA
from .util import valid_publish_topic, valid_subscribe_topic
PARALLEL_UPDATES = 0
DEFAULT_NAME = "MQTT Fan"
MQTT_FAN_ATTRIBUTES_BLOCKED = frozenset(
{
FanEntityStateAttribute.DIRECTION,
FanEntityStateAttribute.OSCILLATING,
FanEntityStateAttribute.PERCENTAGE_STEP,
FanEntityStateAttribute.PERCENTAGE,
FanEntityStateAttribute.PRESET_MODE,
FanEntityCapabilityAttribute.PRESET_MODES,
}
)
_LOGGER = logging.getLogger(__name__)
def valid_speed_range_configuration(config: ConfigType) -> ConfigType:
"""Validate that the fan speed_range configuration is valid, throws if it isn't."""
if config[CONF_SPEED_RANGE_MIN] == 0:
raise probatio.Invalid("speed_range_min must be > 0")
if config[CONF_SPEED_RANGE_MIN] >= config[CONF_SPEED_RANGE_MAX]:
raise probatio.Invalid("speed_range_max must be > speed_range_min")
return config
def valid_preset_mode_configuration(config: ConfigType) -> ConfigType:
"""Validate that the preset mode reset payload is not one of the preset modes."""
if config[CONF_PAYLOAD_RESET_PRESET_MODE] in config[CONF_PRESET_MODES_LIST]:
raise probatio.Invalid(
"preset_modes must not contain payload_reset_preset_mode"
)
return config
_PLATFORM_SCHEMA_BASE = MQTT_RW_SCHEMA.extend(
{
probatio.Optional(CONF_NAME): probatio.Any(cv.string, None),
probatio.Optional(CONF_COMMAND_TEMPLATE): cv.template,
probatio.Optional(CONF_DIRECTION_COMMAND_TOPIC): valid_publish_topic,
probatio.Optional(CONF_DIRECTION_COMMAND_TEMPLATE): cv.template,
probatio.Optional(CONF_DIRECTION_STATE_TOPIC): valid_subscribe_topic,
probatio.Optional(CONF_DIRECTION_VALUE_TEMPLATE): cv.template,
probatio.Optional(CONF_OSCILLATION_COMMAND_TOPIC): valid_publish_topic,
probatio.Optional(CONF_OSCILLATION_COMMAND_TEMPLATE): cv.template,
probatio.Optional(CONF_OSCILLATION_STATE_TOPIC): valid_subscribe_topic,
probatio.Optional(CONF_OSCILLATION_VALUE_TEMPLATE): cv.template,
probatio.Optional(CONF_PERCENTAGE_COMMAND_TOPIC): valid_publish_topic,
probatio.Optional(CONF_PERCENTAGE_COMMAND_TEMPLATE): cv.template,
probatio.Optional(CONF_PERCENTAGE_STATE_TOPIC): valid_subscribe_topic,
probatio.Optional(CONF_PERCENTAGE_VALUE_TEMPLATE): cv.template,
# CONF_PRESET_MODE_COMMAND_TOPIC and CONF_PRESET_MODES_LIST
# must be used together
probatio.Inclusive(
CONF_PRESET_MODE_COMMAND_TOPIC, "preset_modes"
): valid_publish_topic,
probatio.Inclusive(
CONF_PRESET_MODES_LIST, "preset_modes", default=[]
): probatio.EnsureList(),
probatio.Optional(CONF_PRESET_MODE_COMMAND_TEMPLATE): cv.template,
probatio.Optional(CONF_PRESET_MODE_STATE_TOPIC): valid_subscribe_topic,
probatio.Optional(CONF_PRESET_MODE_VALUE_TEMPLATE): cv.template,
probatio.Optional(
CONF_SPEED_RANGE_MIN, default=DEFAULT_SPEED_RANGE_MIN
): cv.positive_int,
probatio.Optional(
CONF_SPEED_RANGE_MAX, default=DEFAULT_SPEED_RANGE_MAX
): cv.positive_int,
probatio.Optional(
CONF_PAYLOAD_RESET_PERCENTAGE, default=DEFAULT_PAYLOAD_RESET
): cv.string,
probatio.Optional(
CONF_PAYLOAD_RESET_PRESET_MODE, default=DEFAULT_PAYLOAD_RESET
): cv.string,
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_PAYLOAD_OSCILLATION_OFF, default=DEFAULT_PAYLOAD_OSCILLATE_OFF
): cv.string,
probatio.Optional(
CONF_PAYLOAD_OSCILLATION_ON, default=DEFAULT_PAYLOAD_OSCILLATE_ON
): cv.string,
probatio.Optional(CONF_STATE_VALUE_TEMPLATE): cv.template,
}
).extend(MQTT_ENTITY_COMMON_SCHEMA.schema)
PLATFORM_SCHEMA_MODERN = probatio.All(
_PLATFORM_SCHEMA_BASE,
valid_speed_range_configuration,
valid_preset_mode_configuration,
)
DISCOVERY_SCHEMA = probatio.All(
_PLATFORM_SCHEMA_BASE.extend({}, extra=probatio.REMOVE_EXTRA),
valid_speed_range_configuration,
valid_preset_mode_configuration,
)
async def async_setup_entry(
hass: HomeAssistant,
config_entry: ConfigEntry,
async_add_entities: AddConfigEntryEntitiesCallback,
) -> None:
"""Set up MQTT fan through YAML and through MQTT discovery."""
async_setup_entity_entry_helper(
hass,
config_entry,
MqttFan,
fan.DOMAIN,
async_add_entities,
DISCOVERY_SCHEMA,
PLATFORM_SCHEMA_MODERN,
)
class MqttFan(MqttEntity, FanEntity):
"""A MQTT fan component."""
_attr_percentage: int | None = None
_attr_preset_mode: str | None = None
_default_name = DEFAULT_NAME
_entity_id_format = fan.ENTITY_ID_FORMAT
_attributes_extra_blocked = MQTT_FAN_ATTRIBUTES_BLOCKED
_command_templates: dict[str, Callable[[PublishPayloadType], PublishPayloadType]]
_value_templates: dict[str, Callable[[ReceivePayloadType], ReceivePayloadType]]
_feature_percentage: bool
_feature_preset_mode: bool
_topic: dict[str, Any]
_optimistic: bool
_optimistic_direction: bool
_optimistic_oscillation: bool
_optimistic_percentage: bool
_optimistic_preset_mode: bool
_payload: dict[str, Any]
_speed_range: tuple[int, int]
@staticmethod
@override
def config_schema() -> VolSchemaType:
"""Return the config schema."""
return DISCOVERY_SCHEMA
@override
def _setup_from_config(self, config: ConfigType) -> None:
"""(Re)Setup the entity."""
self._speed_range = (
config[CONF_SPEED_RANGE_MIN],
config[CONF_SPEED_RANGE_MAX],
)
self._topic = {
key: config.get(key)
for key in (
CONF_STATE_TOPIC,
CONF_COMMAND_TOPIC,
CONF_DIRECTION_STATE_TOPIC,
CONF_DIRECTION_COMMAND_TOPIC,
CONF_PERCENTAGE_STATE_TOPIC,
CONF_PERCENTAGE_COMMAND_TOPIC,
CONF_PRESET_MODE_STATE_TOPIC,
CONF_PRESET_MODE_COMMAND_TOPIC,
CONF_OSCILLATION_STATE_TOPIC,
CONF_OSCILLATION_COMMAND_TOPIC,
)
}
self._payload = {
"STATE_ON": config[CONF_PAYLOAD_ON],
"STATE_OFF": config[CONF_PAYLOAD_OFF],
"OSCILLATE_ON_PAYLOAD": config[CONF_PAYLOAD_OSCILLATION_ON],
"OSCILLATE_OFF_PAYLOAD": config[CONF_PAYLOAD_OSCILLATION_OFF],
"PERCENTAGE_RESET": config[CONF_PAYLOAD_RESET_PERCENTAGE],
"PRESET_MODE_RESET": config[CONF_PAYLOAD_RESET_PRESET_MODE],
}
self._feature_percentage = CONF_PERCENTAGE_COMMAND_TOPIC in config
self._feature_preset_mode = CONF_PRESET_MODE_COMMAND_TOPIC in config
if self._feature_preset_mode:
self._attr_preset_modes = config[CONF_PRESET_MODES_LIST]
else:
self._attr_preset_modes = []
self._attr_speed_count = (
min(int_states_in_range(self._speed_range), 100)
if self._feature_percentage
else 100
)
optimistic = config[CONF_OPTIMISTIC]
self._optimistic = optimistic or self._topic[CONF_STATE_TOPIC] is None
self._attr_assumed_state = bool(self._optimistic)
self._optimistic_direction = (
optimistic or self._topic[CONF_DIRECTION_STATE_TOPIC] is None
)
self._optimistic_oscillation = (
optimistic or self._topic[CONF_OSCILLATION_STATE_TOPIC] is None
)
self._optimistic_percentage = (
optimistic or self._topic[CONF_PERCENTAGE_STATE_TOPIC] is None
)
self._optimistic_preset_mode = (
optimistic or self._topic[CONF_PRESET_MODE_STATE_TOPIC] is None
)
self._attr_supported_features = (
FanEntityFeature.TURN_OFF | FanEntityFeature.TURN_ON
)
self._attr_supported_features |= (
self._topic[CONF_OSCILLATION_COMMAND_TOPIC] is not None
and FanEntityFeature.OSCILLATE
)
self._attr_supported_features |= (
self._topic[CONF_DIRECTION_COMMAND_TOPIC] is not None
and FanEntityFeature.DIRECTION
)
if self._feature_percentage:
self._attr_supported_features |= FanEntityFeature.SET_SPEED
if self._feature_preset_mode:
self._attr_supported_features |= FanEntityFeature.PRESET_MODE
command_templates: dict[str, Template | None] = {
CONF_STATE: config.get(CONF_COMMAND_TEMPLATE),
ATTR_DIRECTION: config.get(CONF_DIRECTION_COMMAND_TEMPLATE),
ATTR_PERCENTAGE: config.get(CONF_PERCENTAGE_COMMAND_TEMPLATE),
ATTR_PRESET_MODE: config.get(CONF_PRESET_MODE_COMMAND_TEMPLATE),
ATTR_OSCILLATING: config.get(CONF_OSCILLATION_COMMAND_TEMPLATE),
}
self._command_templates = {
key: MqttCommandTemplate(tpl, entity=self).async_render
for key, tpl in command_templates.items()
}
value_templates: dict[str, Template | None] = {
CONF_STATE: config.get(CONF_STATE_VALUE_TEMPLATE),
ATTR_DIRECTION: config.get(CONF_DIRECTION_VALUE_TEMPLATE),
ATTR_PERCENTAGE: config.get(CONF_PERCENTAGE_VALUE_TEMPLATE),
ATTR_PRESET_MODE: config.get(CONF_PRESET_MODE_VALUE_TEMPLATE),
ATTR_OSCILLATING: config.get(CONF_OSCILLATION_VALUE_TEMPLATE),
}
self._value_templates = {
key: MqttValueTemplate(
tpl, entity=self
).async_render_with_possible_json_value
for key, tpl in value_templates.items()
}
@callback
def _state_received(self, msg: ReceiveMessage) -> None:
"""Handle new received MQTT message."""
payload = self._value_templates[CONF_STATE](msg.payload)
if not payload:
_LOGGER.debug("Ignoring empty state from '%s'", msg.topic)
return
if payload == self._payload["STATE_ON"]:
self._attr_is_on = True
elif payload == self._payload["STATE_OFF"]:
self._attr_is_on = False
elif payload == PAYLOAD_NONE:
self._attr_is_on = None
@callback
def _percentage_received(self, msg: ReceiveMessage) -> None:
"""Handle new received MQTT message for the percentage."""
rendered_percentage_payload = self._value_templates[ATTR_PERCENTAGE](
msg.payload
)
if not rendered_percentage_payload:
_LOGGER.debug("Ignoring empty speed from '%s'", msg.topic)
return
if rendered_percentage_payload == self._payload["PERCENTAGE_RESET"]:
self._attr_percentage = None
return
try:
percentage = ranged_value_to_percentage(
self._speed_range, int(rendered_percentage_payload)
)
except ValueError:
_LOGGER.warning(
(
"'%s' received on topic %s. '%s' is not a valid speed within"
" the speed range"
),
msg.payload,
msg.topic,
rendered_percentage_payload,
)
return
if percentage < 0 or percentage > 100:
_LOGGER.warning(
(
"'%s' received on topic %s. '%s' is not a valid speed within"
" the speed range"
),
msg.payload,
msg.topic,
rendered_percentage_payload,
)
return
self._attr_percentage = percentage
@callback
def _preset_mode_received(self, msg: ReceiveMessage) -> None:
"""Handle new received MQTT message for preset mode."""
preset_mode = str(self._value_templates[ATTR_PRESET_MODE](msg.payload))
if preset_mode == self._payload["PRESET_MODE_RESET"]:
self._attr_preset_mode = None
return
if not preset_mode:
_LOGGER.debug("Ignoring empty preset_mode from '%s'", msg.topic)
return
if not self.preset_modes or preset_mode not in self.preset_modes:
_LOGGER.warning(
"'%s' received on topic %s. '%s' is not a valid preset mode",
msg.payload,
msg.topic,
preset_mode,
)
return
self._attr_preset_mode = preset_mode
@callback
def _oscillation_received(self, msg: ReceiveMessage) -> None:
"""Handle new received MQTT message for the oscillation."""
payload = self._value_templates[ATTR_OSCILLATING](msg.payload)
if not payload:
_LOGGER.debug("Ignoring empty oscillation from '%s'", msg.topic)
return
if payload == self._payload["OSCILLATE_ON_PAYLOAD"]:
self._attr_oscillating = True
elif payload == self._payload["OSCILLATE_OFF_PAYLOAD"]:
self._attr_oscillating = False
@callback
def _direction_received(self, msg: ReceiveMessage) -> None:
"""Handle new received MQTT message for the direction."""
direction = self._value_templates[ATTR_DIRECTION](msg.payload)
if not direction:
_LOGGER.debug("Ignoring empty direction from '%s'", msg.topic)
return
self._attr_current_direction = str(direction)
@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_PERCENTAGE_STATE_TOPIC, self._percentage_received, {"_attr_percentage"}
)
self.add_subscription(
CONF_PRESET_MODE_STATE_TOPIC,
self._preset_mode_received,
{"_attr_preset_mode"},
)
if self.add_subscription(
CONF_OSCILLATION_STATE_TOPIC,
self._oscillation_received,
{"_attr_oscillating"},
):
self._attr_oscillating = False
self.add_subscription(
CONF_DIRECTION_STATE_TOPIC,
self._direction_received,
{"_attr_current_direction"},
)
@override
async def _subscribe_topics(self) -> None:
"""(Re)Subscribe to topics."""
subscription.async_subscribe_topics_internal(self.hass, self._sub_state)
@property
@override
def is_on(self) -> bool | None:
"""Return true if device is on."""
# The default for FanEntity is to compute it based on percentage
return self._attr_is_on
@override
async def async_turn_on(
self,
percentage: int | None = None,
preset_mode: str | None = None,
**kwargs: Any,
) -> None:
"""Turn on the entity.
This method is a coroutine.
"""
mqtt_payload = self._command_templates[CONF_STATE](self._payload["STATE_ON"])
await self.async_publish_with_config(
self._config[CONF_COMMAND_TOPIC], mqtt_payload
)
if percentage:
await self.async_set_percentage(percentage)
if preset_mode:
await self.async_set_preset_mode(preset_mode)
if self._optimistic:
self._attr_is_on = True
self.async_write_ha_state()
@override
async def async_turn_off(self, **kwargs: Any) -> None:
"""Turn off the entity.
This method is a coroutine.
"""
mqtt_payload = self._command_templates[CONF_STATE](self._payload["STATE_OFF"])
await self.async_publish_with_config(
self._config[CONF_COMMAND_TOPIC], mqtt_payload
)
if self._optimistic:
self._attr_is_on = False
self.async_write_ha_state()
@override
async def async_set_percentage(self, percentage: int) -> None:
"""Set the percentage of the fan.
This method is a coroutine.
"""
percentage_payload = math.ceil(
percentage_to_ranged_value(self._speed_range, percentage)
)
mqtt_payload = self._command_templates[ATTR_PERCENTAGE](percentage_payload)
await self.async_publish_with_config(
self._config[CONF_PERCENTAGE_COMMAND_TOPIC], mqtt_payload
)
if self._optimistic_percentage:
self._attr_percentage = percentage
self.async_write_ha_state()
@override
async def async_set_preset_mode(self, preset_mode: str) -> None:
"""Set the preset mode of the fan.
This method is a coroutine.
"""
mqtt_payload = self._command_templates[ATTR_PRESET_MODE](preset_mode)
await self.async_publish_with_config(
self._config[CONF_PRESET_MODE_COMMAND_TOPIC], mqtt_payload
)
if self._optimistic_preset_mode:
self._attr_preset_mode = preset_mode
self.async_write_ha_state()
@override
async def async_oscillate(self, oscillating: bool) -> None:
"""Set oscillation.
This method is a coroutine.
"""
if oscillating:
mqtt_payload = self._command_templates[ATTR_OSCILLATING](
self._payload["OSCILLATE_ON_PAYLOAD"]
)
else:
mqtt_payload = self._command_templates[ATTR_OSCILLATING](
self._payload["OSCILLATE_OFF_PAYLOAD"]
)
await self.async_publish_with_config(
self._config[CONF_OSCILLATION_COMMAND_TOPIC], mqtt_payload
)
if self._optimistic_oscillation:
self._attr_oscillating = oscillating
self.async_write_ha_state()
@override
async def async_set_direction(self, direction: str) -> None:
"""Set direction.
This method is a coroutine.
"""
mqtt_payload = self._command_templates[ATTR_DIRECTION](direction)
await self.async_publish_with_config(
self._config[CONF_DIRECTION_COMMAND_TOPIC], mqtt_payload
)
if self._optimistic_direction:
self._attr_current_direction = direction
self.async_write_ha_state()
+487
View File
@@ -0,0 +1,487 @@
"""Support for MQTT humidifiers."""
from collections.abc import Callable
import logging
from typing import Any, override
import probatio
from homeassistant.components import humidifier
from homeassistant.components.humidifier import (
ATTR_ACTION,
ATTR_CURRENT_HUMIDITY,
ATTR_HUMIDITY,
ATTR_MODE,
DEFAULT_MAX_HUMIDITY,
DEFAULT_MIN_HUMIDITY,
HumidifierAction,
HumidifierDeviceClass,
HumidifierEntity,
HumidifierEntityCapabilityAttribute,
HumidifierEntityFeature,
HumidifierEntityStateAttribute,
)
from homeassistant.config_entries import ConfigEntry
from homeassistant.const import (
CONF_DEVICE_CLASS,
CONF_NAME,
CONF_OPTIMISTIC,
CONF_PAYLOAD_OFF,
CONF_PAYLOAD_ON,
CONF_STATE,
)
from homeassistant.core import HomeAssistant, callback
from homeassistant.helpers import config_validation as cv
from homeassistant.helpers.entity_platform import AddConfigEntryEntitiesCallback
from homeassistant.helpers.service_info.mqtt import ReceivePayloadType
from homeassistant.helpers.template import Template
from homeassistant.helpers.typing import ConfigType, VolSchemaType
from . import subscription
from .config import MQTT_RW_SCHEMA
from .const import (
CONF_ACTION_TEMPLATE,
CONF_ACTION_TOPIC,
CONF_COMMAND_TEMPLATE,
CONF_COMMAND_TOPIC,
CONF_CURRENT_HUMIDITY_TEMPLATE,
CONF_CURRENT_HUMIDITY_TOPIC,
CONF_STATE_TOPIC,
CONF_STATE_VALUE_TEMPLATE,
PAYLOAD_NONE,
)
from .entity import MqttEntity, async_setup_entity_entry_helper
from .models import (
MqttCommandTemplate,
MqttValueTemplate,
PublishPayloadType,
ReceiveMessage,
)
from .schemas import MQTT_ENTITY_COMMON_SCHEMA
from .util import valid_publish_topic, valid_subscribe_topic
PARALLEL_UPDATES = 0
CONF_AVAILABLE_MODES_LIST = "modes"
CONF_MODE_COMMAND_TEMPLATE = "mode_command_template"
CONF_MODE_COMMAND_TOPIC = "mode_command_topic"
CONF_MODE_STATE_TOPIC = "mode_state_topic"
CONF_MODE_STATE_TEMPLATE = "mode_state_template"
CONF_PAYLOAD_RESET_MODE = "payload_reset_mode"
CONF_PAYLOAD_RESET_HUMIDITY = "payload_reset_humidity"
CONF_TARGET_HUMIDITY_COMMAND_TEMPLATE = "target_humidity_command_template"
CONF_TARGET_HUMIDITY_COMMAND_TOPIC = "target_humidity_command_topic"
CONF_TARGET_HUMIDITY_MIN = "min_humidity"
CONF_TARGET_HUMIDITY_MAX = "max_humidity"
CONF_TARGET_HUMIDITY_STATE_TEMPLATE = "target_humidity_state_template"
CONF_TARGET_HUMIDITY_STATE_TOPIC = "target_humidity_state_topic"
DEFAULT_NAME = "MQTT Humidifier"
DEFAULT_PAYLOAD_ON = "ON"
DEFAULT_PAYLOAD_OFF = "OFF"
DEFAULT_PAYLOAD_RESET = "None"
MQTT_HUMIDIFIER_ATTRIBUTES_BLOCKED = frozenset(
{
HumidifierEntityStateAttribute.HUMIDITY,
HumidifierEntityCapabilityAttribute.MAX_HUMIDITY,
HumidifierEntityCapabilityAttribute.MIN_HUMIDITY,
HumidifierEntityStateAttribute.MODE,
HumidifierEntityCapabilityAttribute.AVAILABLE_MODES,
}
)
_LOGGER = logging.getLogger(__name__)
def valid_mode_configuration(config: ConfigType) -> ConfigType:
"""Validate that the mode reset payload is not one of the available modes."""
if config[CONF_PAYLOAD_RESET_MODE] in config[CONF_AVAILABLE_MODES_LIST]:
raise probatio.Invalid("modes must not contain payload_reset_mode")
return config
def valid_humidity_range_configuration(config: ConfigType) -> ConfigType:
"""Validate humidity range.
Ensures that the target_humidity range configuration is valid,
throws if it isn't.
"""
if config[CONF_TARGET_HUMIDITY_MIN] >= config[CONF_TARGET_HUMIDITY_MAX]:
raise probatio.Invalid("target_humidity_max must be > target_humidity_min")
if config[CONF_TARGET_HUMIDITY_MAX] > 100:
raise probatio.Invalid("max_humidity must be <= 100")
return config
_PLATFORM_SCHEMA_BASE = MQTT_RW_SCHEMA.extend(
{
probatio.Optional(CONF_ACTION_TEMPLATE): cv.template,
probatio.Optional(CONF_ACTION_TOPIC): valid_subscribe_topic,
# CONF_AVAIALABLE_MODES_LIST and CONF_MODE_COMMAND_TOPIC must be used together
probatio.Inclusive(
CONF_AVAILABLE_MODES_LIST, "available_modes", default=[]
): probatio.EnsureList(),
probatio.Inclusive(
CONF_MODE_COMMAND_TOPIC, "available_modes"
): valid_publish_topic,
probatio.Optional(CONF_COMMAND_TEMPLATE): cv.template,
probatio.Optional(CONF_CURRENT_HUMIDITY_TEMPLATE): cv.template,
probatio.Optional(CONF_CURRENT_HUMIDITY_TOPIC): valid_subscribe_topic,
probatio.Optional(
CONF_DEVICE_CLASS, default=HumidifierDeviceClass.HUMIDIFIER
): probatio.In(
[HumidifierDeviceClass.HUMIDIFIER, HumidifierDeviceClass.DEHUMIDIFIER, None]
),
probatio.Optional(CONF_MODE_COMMAND_TEMPLATE): cv.template,
probatio.Optional(CONF_MODE_STATE_TOPIC): valid_subscribe_topic,
probatio.Optional(CONF_MODE_STATE_TEMPLATE): cv.template,
probatio.Optional(CONF_NAME): probatio.Any(cv.string, None),
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_STATE_VALUE_TEMPLATE): cv.template,
probatio.Required(CONF_TARGET_HUMIDITY_COMMAND_TOPIC): valid_publish_topic,
probatio.Optional(CONF_TARGET_HUMIDITY_COMMAND_TEMPLATE): cv.template,
probatio.Optional(
CONF_TARGET_HUMIDITY_MAX, default=DEFAULT_MAX_HUMIDITY
): cv.positive_float,
probatio.Optional(
CONF_TARGET_HUMIDITY_MIN, default=DEFAULT_MIN_HUMIDITY
): cv.positive_float,
probatio.Optional(CONF_TARGET_HUMIDITY_STATE_TEMPLATE): cv.template,
probatio.Optional(CONF_TARGET_HUMIDITY_STATE_TOPIC): valid_subscribe_topic,
probatio.Optional(
CONF_PAYLOAD_RESET_HUMIDITY, default=DEFAULT_PAYLOAD_RESET
): cv.string,
probatio.Optional(
CONF_PAYLOAD_RESET_MODE, default=DEFAULT_PAYLOAD_RESET
): cv.string,
}
).extend(MQTT_ENTITY_COMMON_SCHEMA.schema)
PLATFORM_SCHEMA_MODERN = probatio.All(
_PLATFORM_SCHEMA_BASE,
valid_humidity_range_configuration,
valid_mode_configuration,
)
DISCOVERY_SCHEMA = probatio.All(
_PLATFORM_SCHEMA_BASE.extend({}, extra=probatio.REMOVE_EXTRA),
valid_humidity_range_configuration,
valid_mode_configuration,
)
TOPICS = (
CONF_ACTION_TOPIC,
CONF_STATE_TOPIC,
CONF_COMMAND_TOPIC,
CONF_CURRENT_HUMIDITY_TOPIC,
CONF_TARGET_HUMIDITY_STATE_TOPIC,
CONF_TARGET_HUMIDITY_COMMAND_TOPIC,
CONF_MODE_STATE_TOPIC,
CONF_MODE_COMMAND_TOPIC,
)
async def async_setup_entry(
hass: HomeAssistant,
config_entry: ConfigEntry,
async_add_entities: AddConfigEntryEntitiesCallback,
) -> None:
"""Set up MQTT humidifier through YAML and through MQTT discovery."""
async_setup_entity_entry_helper(
hass,
config_entry,
MqttHumidifier,
humidifier.DOMAIN,
async_add_entities,
DISCOVERY_SCHEMA,
PLATFORM_SCHEMA_MODERN,
)
class MqttHumidifier(MqttEntity, HumidifierEntity):
"""A MQTT humidifier component."""
_attr_mode: str | None = None
_default_name = DEFAULT_NAME
_entity_id_format = humidifier.ENTITY_ID_FORMAT
_attributes_extra_blocked = MQTT_HUMIDIFIER_ATTRIBUTES_BLOCKED
_command_templates: dict[str, Callable[[PublishPayloadType], PublishPayloadType]]
_value_templates: dict[str, Callable[[ReceivePayloadType], ReceivePayloadType]]
_optimistic: bool
_optimistic_target_humidity: bool
_optimistic_mode: bool
_payload: dict[str, str]
_topic: dict[str, Any]
@staticmethod
@override
def config_schema() -> VolSchemaType:
"""Return the config schema."""
return DISCOVERY_SCHEMA
@override
def _setup_from_config(self, config: ConfigType) -> None:
"""(Re)Setup the entity."""
self._attr_device_class = config.get(CONF_DEVICE_CLASS)
self._attr_min_humidity = config[CONF_TARGET_HUMIDITY_MIN]
self._attr_max_humidity = config[CONF_TARGET_HUMIDITY_MAX]
self._topic = {key: config.get(key) for key in TOPICS}
self._payload = {
"STATE_ON": config[CONF_PAYLOAD_ON],
"STATE_OFF": config[CONF_PAYLOAD_OFF],
"HUMIDITY_RESET": config[CONF_PAYLOAD_RESET_HUMIDITY],
"MODE_RESET": config[CONF_PAYLOAD_RESET_MODE],
}
if CONF_MODE_COMMAND_TOPIC in config and CONF_AVAILABLE_MODES_LIST in config:
self._attr_available_modes = config[CONF_AVAILABLE_MODES_LIST]
else:
self._attr_available_modes = []
if self._attr_available_modes:
self._attr_supported_features = HumidifierEntityFeature.MODES
if CONF_MODE_STATE_TOPIC in config:
self._attr_mode = None
optimistic: bool = config[CONF_OPTIMISTIC]
self._optimistic = optimistic or self._topic[CONF_STATE_TOPIC] is None
self._attr_assumed_state = bool(self._optimistic)
self._optimistic_target_humidity = (
optimistic or self._topic[CONF_TARGET_HUMIDITY_STATE_TOPIC] is None
)
self._optimistic_mode = optimistic or self._topic[CONF_MODE_STATE_TOPIC] is None
command_templates: dict[str, Template | None] = {
CONF_STATE: config.get(CONF_COMMAND_TEMPLATE),
ATTR_HUMIDITY: config.get(CONF_TARGET_HUMIDITY_COMMAND_TEMPLATE),
ATTR_MODE: config.get(CONF_MODE_COMMAND_TEMPLATE),
}
self._command_templates = {
key: MqttCommandTemplate(tpl, entity=self).async_render
for key, tpl in command_templates.items()
}
value_templates: dict[str, Template | None] = {
ATTR_ACTION: config.get(CONF_ACTION_TEMPLATE),
ATTR_CURRENT_HUMIDITY: config.get(CONF_CURRENT_HUMIDITY_TEMPLATE),
CONF_STATE: config.get(CONF_STATE_VALUE_TEMPLATE),
ATTR_HUMIDITY: config.get(CONF_TARGET_HUMIDITY_STATE_TEMPLATE),
ATTR_MODE: config.get(CONF_MODE_STATE_TEMPLATE),
}
self._value_templates = {
key: MqttValueTemplate(
tpl,
entity=self,
).async_render_with_possible_json_value
for key, tpl in value_templates.items()
}
@callback
def _state_received(self, msg: ReceiveMessage) -> None:
"""Handle new received MQTT message."""
payload = self._value_templates[CONF_STATE](msg.payload)
if not payload:
_LOGGER.debug("Ignoring empty state from '%s'", msg.topic)
return
if payload == self._payload["STATE_ON"]:
self._attr_is_on = True
elif payload == self._payload["STATE_OFF"]:
self._attr_is_on = False
elif payload == PAYLOAD_NONE:
self._attr_is_on = None
@callback
def _action_received(self, msg: ReceiveMessage) -> None:
"""Handle new received MQTT message."""
action_payload = self._value_templates[ATTR_ACTION](msg.payload)
if not action_payload or action_payload == PAYLOAD_NONE:
_LOGGER.debug("Ignoring empty action from '%s'", msg.topic)
return
try:
self._attr_action = HumidifierAction(str(action_payload))
except ValueError:
_LOGGER.error(
"'%s' received on topic %s. '%s' is not a valid action",
msg.payload,
msg.topic,
action_payload,
)
return
@callback
def _current_humidity_received(self, msg: ReceiveMessage) -> None:
"""Handle new received MQTT message for the current humidity."""
rendered_current_humidity_payload = self._value_templates[
ATTR_CURRENT_HUMIDITY
](msg.payload)
if rendered_current_humidity_payload == self._payload["HUMIDITY_RESET"]:
self._attr_current_humidity = None
return
if not rendered_current_humidity_payload:
_LOGGER.debug("Ignoring empty current humidity from '%s'", msg.topic)
return
try:
current_humidity = round(float(rendered_current_humidity_payload))
except ValueError:
_LOGGER.warning(
"'%s' received on topic %s. '%s' is not a valid humidity",
msg.payload,
msg.topic,
rendered_current_humidity_payload,
)
return
if current_humidity < 0 or current_humidity > 100:
_LOGGER.warning(
"'%s' received on topic %s. '%s' is not a valid humidity",
msg.payload,
msg.topic,
rendered_current_humidity_payload,
)
return
self._attr_current_humidity = current_humidity
@callback
def _target_humidity_received(self, msg: ReceiveMessage) -> None:
"""Handle new received MQTT message for the target humidity."""
rendered_target_humidity_payload = self._value_templates[ATTR_HUMIDITY](
msg.payload
)
if not rendered_target_humidity_payload:
_LOGGER.debug("Ignoring empty target humidity from '%s'", msg.topic)
return
if rendered_target_humidity_payload == self._payload["HUMIDITY_RESET"]:
self._attr_target_humidity = None
return
try:
target_humidity = round(float(rendered_target_humidity_payload))
except ValueError:
_LOGGER.warning(
"'%s' received on topic %s. '%s' is not a valid target humidity",
msg.payload,
msg.topic,
rendered_target_humidity_payload,
)
return
if (
target_humidity < self._attr_min_humidity
or target_humidity > self._attr_max_humidity
):
_LOGGER.warning(
"'%s' received on topic %s. '%s' is not a valid target humidity",
msg.payload,
msg.topic,
rendered_target_humidity_payload,
)
return
self._attr_target_humidity = target_humidity
@callback
def _mode_received(self, msg: ReceiveMessage) -> None:
"""Handle new received MQTT message for mode."""
mode = str(self._value_templates[ATTR_MODE](msg.payload))
if mode == self._payload["MODE_RESET"]:
self._attr_mode = None
return
if not mode:
_LOGGER.debug("Ignoring empty mode from '%s'", msg.topic)
return
if not self.available_modes or mode not in self.available_modes:
_LOGGER.warning(
"'%s' received on topic %s. '%s' is not a valid mode",
msg.payload,
msg.topic,
mode,
)
return
self._attr_mode = mode
@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_ACTION_TOPIC, self._action_received, {"_attr_action"}
)
self.add_subscription(
CONF_CURRENT_HUMIDITY_TOPIC,
self._current_humidity_received,
{"_attr_current_humidity"},
)
self.add_subscription(
CONF_TARGET_HUMIDITY_STATE_TOPIC,
self._target_humidity_received,
{"_attr_target_humidity"},
)
self.add_subscription(
CONF_MODE_STATE_TOPIC, self._mode_received, {"_attr_mode"}
)
@override
async def _subscribe_topics(self) -> None:
"""(Re)Subscribe to topics."""
subscription.async_subscribe_topics_internal(self.hass, self._sub_state)
@override
async def async_turn_on(self, **kwargs: Any) -> None:
"""Turn on the entity.
This method is a coroutine.
"""
mqtt_payload = self._command_templates[CONF_STATE](self._payload["STATE_ON"])
await self.async_publish_with_config(
self._config[CONF_COMMAND_TOPIC], mqtt_payload
)
if self._optimistic:
self._attr_is_on = True
self.async_write_ha_state()
@override
async def async_turn_off(self, **kwargs: Any) -> None:
"""Turn off the entity.
This method is a coroutine.
"""
mqtt_payload = self._command_templates[CONF_STATE](self._payload["STATE_OFF"])
await self.async_publish_with_config(
self._config[CONF_COMMAND_TOPIC], mqtt_payload
)
if self._optimistic:
self._attr_is_on = False
self.async_write_ha_state()
@override
async def async_set_humidity(self, humidity: float) -> None:
"""Set the target humidity of the humidifier.
This method is a coroutine.
"""
mqtt_payload = self._command_templates[ATTR_HUMIDITY](humidity)
await self.async_publish_with_config(
self._config[CONF_TARGET_HUMIDITY_COMMAND_TOPIC], mqtt_payload
)
if self._optimistic_target_humidity:
self._attr_target_humidity = humidity
self.async_write_ha_state()
@override
async def async_set_mode(self, mode: str) -> None:
"""Set the mode of the fan.
This method is a coroutine.
"""
if not self.available_modes or mode not in self.available_modes:
_LOGGER.warning("'%s'is not a valid mode", mode)
return
mqtt_payload = self._command_templates[ATTR_MODE](mode)
await self.async_publish_with_config(
self._config[CONF_MODE_COMMAND_TOPIC], mqtt_payload
)
if self._optimistic_mode:
self._attr_mode = mode
self.async_write_ha_state()
+18
View File
@@ -0,0 +1,18 @@
{
"services": {
"dump": {
"service": "mdi:database-export"
},
"publish": {
"service": "mdi:publish"
},
"reload": {
"service": "mdi:reload"
}
},
"triggers": {
"_": {
"trigger": "mdi:swap-horizontal"
}
}
}
+209
View File
@@ -0,0 +1,209 @@
"""Support for MQTT images."""
from base64 import b64decode
import binascii
from collections.abc import Callable
import logging
from typing import TYPE_CHECKING, Any, override
import httpx
import probatio
from homeassistant.components import image
from homeassistant.components.image import DEFAULT_CONTENT_TYPE, ImageEntity
from homeassistant.config_entries import ConfigEntry
from homeassistant.const import CONF_NAME
from homeassistant.core import HomeAssistant, callback
from homeassistant.helpers import config_validation as cv
from homeassistant.helpers.entity_platform import AddConfigEntryEntitiesCallback
from homeassistant.helpers.httpx_client import get_async_client
from homeassistant.helpers.service_info.mqtt import ReceivePayloadType
from homeassistant.helpers.typing import ConfigType, DiscoveryInfoType, VolSchemaType
from homeassistant.util import dt as dt_util
from . import subscription
from .config import MQTT_BASE_SCHEMA
from .const import (
CONF_CONTENT_TYPE,
CONF_IMAGE_ENCODING,
CONF_IMAGE_TOPIC,
CONF_URL_TEMPLATE,
CONF_URL_TOPIC,
)
from .entity import MqttEntity, async_setup_entity_entry_helper
from .models import (
DATA_MQTT,
MqttValueTemplate,
MqttValueTemplateException,
ReceiveMessage,
)
from .schemas import MQTT_ENTITY_COMMON_SCHEMA
from .util import valid_subscribe_topic
_LOGGER = logging.getLogger(__name__)
PARALLEL_UPDATES = 0
DEFAULT_NAME = "MQTT Image"
GET_IMAGE_TIMEOUT = 10
def validate_topic_required(config: ConfigType) -> ConfigType:
"""Ensure at least one subscribe topic is configured."""
if CONF_IMAGE_TOPIC not in config and CONF_URL_TOPIC not in config:
raise probatio.Invalid("Expected one of [`image_topic`, `url_topic`], got none")
if CONF_CONTENT_TYPE in config and CONF_URL_TOPIC in config:
raise probatio.Invalid(
"Option `content_type` can not be used together with `url_topic`"
)
return config
PLATFORM_SCHEMA_BASE = MQTT_BASE_SCHEMA.extend(
{
probatio.Optional(CONF_CONTENT_TYPE): cv.string,
probatio.Optional(CONF_NAME): probatio.Any(cv.string, None),
probatio.Exclusive(CONF_URL_TOPIC, "image_topic"): valid_subscribe_topic,
probatio.Exclusive(CONF_IMAGE_TOPIC, "image_topic"): valid_subscribe_topic,
probatio.Optional(CONF_IMAGE_ENCODING): probatio.In({"b64", "raw"}),
probatio.Optional(CONF_URL_TEMPLATE): cv.template,
}
).extend(MQTT_ENTITY_COMMON_SCHEMA.schema)
PLATFORM_SCHEMA_MODERN = probatio.All(
PLATFORM_SCHEMA_BASE.schema, validate_topic_required
)
DISCOVERY_SCHEMA = probatio.All(
PLATFORM_SCHEMA_BASE.extend({}, extra=probatio.REMOVE_EXTRA),
validate_topic_required,
)
async def async_setup_entry(
hass: HomeAssistant,
config_entry: ConfigEntry,
async_add_entities: AddConfigEntryEntitiesCallback,
) -> None:
"""Set up MQTT image through YAML and through MQTT discovery."""
async_setup_entity_entry_helper(
hass,
config_entry,
MqttImage,
image.DOMAIN,
async_add_entities,
DISCOVERY_SCHEMA,
PLATFORM_SCHEMA_MODERN,
)
class MqttImage(MqttEntity, ImageEntity):
"""representation of a MQTT image."""
_default_name = DEFAULT_NAME
_entity_id_format: str = image.ENTITY_ID_FORMAT
_last_image: bytes | None = None
_client: httpx.AsyncClient
_url_template: Callable[[ReceivePayloadType], ReceivePayloadType]
_topic: dict[str, Any]
def __init__(
self,
hass: HomeAssistant,
config: ConfigType,
config_entry: ConfigEntry,
discovery_data: DiscoveryInfoType | None,
) -> None:
"""Initialize the MQTT Image."""
self._client = get_async_client(hass)
ImageEntity.__init__(self, hass)
MqttEntity.__init__(self, hass, config, config_entry, discovery_data)
@staticmethod
@override
def config_schema() -> VolSchemaType:
"""Return the config schema."""
return DISCOVERY_SCHEMA
@override
def _setup_from_config(self, config: ConfigType) -> None:
"""(Re)Setup the entity."""
self._topic = {
key: config.get(key)
for key in (
CONF_IMAGE_TOPIC,
CONF_URL_TOPIC,
)
}
if CONF_IMAGE_TOPIC in config:
self._attr_content_type = config.get(
CONF_CONTENT_TYPE, DEFAULT_CONTENT_TYPE
)
if CONF_URL_TOPIC in config:
self._attr_image_url = None
self._url_template = MqttValueTemplate(
config.get(CONF_URL_TEMPLATE), entity=self
).async_render_with_possible_json_value
@callback
def _image_data_received(self, msg: ReceiveMessage) -> None:
"""Handle new MQTT messages."""
try:
if self._config.get(CONF_IMAGE_ENCODING) == "b64":
self._last_image = b64decode(msg.payload)
else:
if TYPE_CHECKING:
assert isinstance(msg.payload, bytes)
self._last_image = msg.payload
except (binascii.Error, ValueError, AssertionError) as err:
_LOGGER.error(
"Error processing image data received at topic %s: %s",
msg.topic,
err,
)
self._last_image = None
self._attr_image_last_updated = dt_util.utcnow()
self.hass.data[DATA_MQTT].state_write_requests.write_state_request(self)
@callback
def _image_from_url_request_received(self, msg: ReceiveMessage) -> None:
"""Handle new MQTT messages."""
try:
url = cv.url(self._url_template(msg.payload))
self._attr_image_url = url
except MqttValueTemplateException as exc:
_LOGGER.warning(exc)
return
except probatio.Invalid:
_LOGGER.error(
"Invalid image URL '%s' received at topic %s",
msg.payload,
msg.topic,
)
self._attr_image_last_updated = dt_util.utcnow()
self._cached_image = None
self.hass.data[DATA_MQTT].state_write_requests.write_state_request(self)
@callback
@override
def _prepare_subscribe_topics(self) -> None:
"""(Re)Subscribe to topics."""
self.add_subscription(
CONF_IMAGE_TOPIC, self._image_data_received, None, disable_encoding=True
)
self.add_subscription(
CONF_URL_TOPIC, self._image_from_url_request_received, None
)
@override
async def _subscribe_topics(self) -> None:
"""(Re)Subscribe to topics."""
subscription.async_subscribe_topics_internal(self.hass, self._sub_state)
@override
async def async_image(self) -> bytes | None:
"""Return bytes of image."""
if CONF_IMAGE_TOPIC in self._config:
return self._last_image
return await super().async_image()
+263
View File
@@ -0,0 +1,263 @@
"""Support for MQTT infrared platform."""
from collections.abc import Callable
import logging
from typing import Any, override
import orjson
import probatio
from homeassistant.components import infrared
from homeassistant.components.infrared import (
InfraredCommand,
InfraredEmitterEntity,
InfraredReceivedSignal,
InfraredReceiverEntity,
)
from homeassistant.config_entries import ConfigEntry
from homeassistant.const import CONF_NAME, CONF_VALUE_TEMPLATE
from homeassistant.core import HomeAssistant, callback
from homeassistant.helpers import config_validation as cv
from homeassistant.helpers.entity_platform import AddConfigEntryEntitiesCallback
from homeassistant.helpers.service_info.mqtt import ReceivePayloadType
from homeassistant.helpers.typing import ConfigType, VolSchemaType
from homeassistant.util.json import JSON_DECODE_EXCEPTIONS, json_loads_object
from . import subscription
from .config import MQTT_BASE_SCHEMA
from .const import (
CONF_COMMAND_TEMPLATE,
CONF_COMMAND_TOPIC,
CONF_RETAIN,
CONF_SCHEMA,
CONF_STATE_TOPIC,
DEFAULT_RETAIN,
PAYLOAD_NONE,
)
from .entity import MqttEntity, async_setup_entity_entry_helper
from .models import (
MqttCommandTemplate,
MqttValueTemplate,
PublishPayloadType,
ReceiveMessage,
)
from .schemas import MQTT_ENTITY_COMMON_SCHEMA
from .util import valid_publish_topic, valid_subscribe_topic
_LOGGER = logging.getLogger(__name__)
PARALLEL_UPDATES = 0
DEFAULT_EMITTER_NAME = "MQTT Infrared emitter"
DEFAULT_RECEIVER_NAME = "MQTT Infrared receiver"
MQTT_INFRARED_ATTRIBUTES_BLOCKED: frozenset[str] = frozenset()
SIGNAL_SCHEMA = probatio.Schema(
{
probatio.Required("timings"): probatio.All([int], probatio.Length(min=1)),
probatio.Optional("modulation"): probatio.Any(int, None),
},
extra=probatio.REMOVE_EXTRA,
)
def validate_mqtt_infrared_config(config_value: dict[str, Any]) -> ConfigType:
"""Validate MQTT infrared entity config schema."""
schemas: dict[str, VolSchemaType] = {
"emitter": EMITTER_SCHEMA,
"receiver": RECEIVER_SCHEMA,
}
config: ConfigType = schemas[config_value[CONF_SCHEMA]](config_value)
return config
def validate_mqtt_infrared_discovery(config_value: dict[str, Any]) -> ConfigType:
"""Validate MQTT infrared entity discovery schema."""
config: ConfigType = DISCOVERY_SCHEMA_MAPPING[config_value[CONF_SCHEMA]](
config_value
)
return config
INFRARED_BASE_SCHEMA = probatio.Schema(
{probatio.Required(CONF_SCHEMA): probatio.Any("emitter", "receiver")},
extra=probatio.ALLOW_EXTRA,
)
EMITTER_SCHEMA = MQTT_BASE_SCHEMA.extend(
{
probatio.Required(CONF_SCHEMA): "emitter",
probatio.Required(CONF_COMMAND_TOPIC): valid_publish_topic,
probatio.Optional(CONF_COMMAND_TEMPLATE): cv.template,
probatio.Optional(CONF_RETAIN, default=DEFAULT_RETAIN): cv.boolean,
probatio.Optional(CONF_NAME): probatio.Any(cv.string, None),
}
).extend(MQTT_ENTITY_COMMON_SCHEMA.schema)
RECEIVER_SCHEMA = MQTT_BASE_SCHEMA.extend(
{
probatio.Required(CONF_SCHEMA): "receiver",
probatio.Required(CONF_STATE_TOPIC): valid_subscribe_topic,
probatio.Optional(CONF_VALUE_TEMPLATE): cv.template,
probatio.Optional(CONF_NAME): probatio.Any(cv.string, None),
}
).extend(MQTT_ENTITY_COMMON_SCHEMA.schema)
DISCOVERY_SCHEMA_MAPPING: dict[str, VolSchemaType] = {
"emitter": EMITTER_SCHEMA.extend({}, extra=probatio.REMOVE_EXTRA),
"receiver": RECEIVER_SCHEMA.extend({}, extra=probatio.REMOVE_EXTRA),
}
PLATFORM_SCHEMA_MODERN = probatio.All(
INFRARED_BASE_SCHEMA,
validate_mqtt_infrared_config,
)
DISCOVERY_SCHEMA = probatio.All(
INFRARED_BASE_SCHEMA,
validate_mqtt_infrared_discovery,
)
async def async_setup_entry(
hass: HomeAssistant,
config_entry: ConfigEntry,
async_add_entities: AddConfigEntryEntitiesCallback,
) -> None:
"""Set up MQTT infrared device through YAML and through MQTT discovery."""
async_setup_entity_entry_helper(
hass,
config_entry,
None,
infrared.DOMAIN,
async_add_entities,
DISCOVERY_SCHEMA,
PLATFORM_SCHEMA_MODERN,
schema_class_mapping={
"emitter": MqttInfraredEmitterEntity,
"receiver": MqttInfraredReceiverEntity,
},
)
class MqttInfraredEmitterEntity(MqttEntity, InfraredEmitterEntity):
"""Representation of the MQTT infrared emitter entity."""
_attributes_extra_blocked = MQTT_INFRARED_ATTRIBUTES_BLOCKED
_default_name = DEFAULT_EMITTER_NAME
_entity_id_format = infrared.ENTITY_ID_FORMAT
_command_template: Callable[
[PublishPayloadType, dict[str, Any]], PublishPayloadType
]
@staticmethod
@override
def config_schema() -> VolSchemaType:
"""Return the config schema."""
return DISCOVERY_SCHEMA_MAPPING["emitter"]
@override
def _setup_from_config(self, config: ConfigType) -> None:
"""(Re)Setup the entity."""
self._command_template = MqttCommandTemplate(
config.get(CONF_COMMAND_TEMPLATE),
entity=self,
).async_render
@callback
@override
def _prepare_subscribe_topics(self) -> None:
"""(Re)Subscribe to topics."""
@override
async def _subscribe_topics(self) -> None:
"""(Re)Subscribe to topics."""
@override
async def async_send_command(self, command: InfraredCommand) -> None:
"""Send an IR command via MQTT."""
command_vars: dict[str, Any] = {
"timings": command.get_raw_timings(),
"modulation": command.modulation,
"repeat_count": command.repeat_count,
}
payload = self._command_template(
orjson.dumps(command_vars).decode(), command_vars
)
await self.async_publish_with_config(self._config[CONF_COMMAND_TOPIC], payload)
class MqttInfraredReceiverEntity(MqttEntity, InfraredReceiverEntity):
"""Representation of the MQTT infrared receiver entity."""
_attributes_extra_blocked = MQTT_INFRARED_ATTRIBUTES_BLOCKED
_default_name = DEFAULT_RECEIVER_NAME
_entity_id_format = infrared.ENTITY_ID_FORMAT
_value_template: Callable[[ReceivePayloadType], ReceivePayloadType]
@staticmethod
@override
def config_schema() -> VolSchemaType:
"""Return the config schema."""
return DISCOVERY_SCHEMA_MAPPING["receiver"]
@override
def _setup_from_config(self, config: ConfigType) -> None:
"""(Re)Setup the entity."""
self._value_template = MqttValueTemplate(
config.get(CONF_VALUE_TEMPLATE),
entity=self,
).async_render_with_possible_json_value
@callback
def _handle_state_message_received(self, msg: ReceiveMessage) -> None:
"""Handle receiving state message via MQTT."""
if msg.retain:
_LOGGER.debug("Ignoring retained infrared signal on topic %s", msg.topic)
return
payload = self._value_template(msg.payload)
if not payload or payload in (PAYLOAD_NONE, "null", '""'):
_LOGGER.debug(
"Ignoring payload for %s on topic %s, with template %s",
self.entity_id,
self._config[CONF_STATE_TOPIC],
self._config.get(CONF_VALUE_TEMPLATE),
)
return
try:
payload_dict = SIGNAL_SCHEMA(json_loads_object(payload))
except (*JSON_DECODE_EXCEPTIONS, probatio.Invalid, TypeError, ValueError):
_LOGGER.warning(
"Invalid message received for %s on topic %s, with template %s. "
"Message is not a valid signal JSON message. Got %s",
self.entity_id,
self._config[CONF_STATE_TOPIC],
self._config.get(CONF_VALUE_TEMPLATE),
msg.payload,
)
else:
self._handle_received_signal(
InfraredReceivedSignal(
timings=payload_dict["timings"],
modulation=payload_dict.get("modulation"),
)
)
@callback
@override
def _prepare_subscribe_topics(self) -> None:
"""(Re)Subscribe to topics."""
self.add_subscription(
CONF_STATE_TOPIC,
self._handle_state_message_received,
None,
)
@override
async def _subscribe_topics(self) -> None:
"""(Re)Subscribe to topics."""
subscription.async_subscribe_topics_internal(self.hass, self._sub_state)
+232
View File
@@ -0,0 +1,232 @@
"""Support for MQTT lawn mowers."""
from collections.abc import Callable
import contextlib
import logging
from typing import override
import probatio
from homeassistant.components import lawn_mower
from homeassistant.components.lawn_mower import (
ENTITY_ID_FORMAT,
LawnMowerActivity,
LawnMowerEntity,
LawnMowerEntityFeature,
)
from homeassistant.config_entries import ConfigEntry
from homeassistant.const import CONF_NAME, CONF_OPTIMISTIC
from homeassistant.core import HomeAssistant, callback
from homeassistant.helpers import config_validation as cv
from homeassistant.helpers.entity_platform import AddConfigEntryEntitiesCallback
from homeassistant.helpers.restore_state import RestoreEntity
from homeassistant.helpers.service_info.mqtt import ReceivePayloadType
from homeassistant.helpers.typing import ConfigType, VolSchemaType
from . import subscription
from .config import MQTT_BASE_SCHEMA
from .const import CONF_RETAIN, DEFAULT_OPTIMISTIC, DEFAULT_RETAIN
from .entity import MqttEntity, async_setup_entity_entry_helper
from .models import (
MqttCommandTemplate,
MqttValueTemplate,
PublishPayloadType,
ReceiveMessage,
)
from .schemas import MQTT_ENTITY_COMMON_SCHEMA
from .util import valid_publish_topic, valid_subscribe_topic
_LOGGER = logging.getLogger(__name__)
PARALLEL_UPDATES = 0
CONF_ACTIVITY_STATE_TOPIC = "activity_state_topic"
CONF_ACTIVITY_VALUE_TEMPLATE = "activity_value_template"
CONF_DOCK_COMMAND_TOPIC = "dock_command_topic"
CONF_DOCK_COMMAND_TEMPLATE = "dock_command_template"
CONF_PAUSE_COMMAND_TOPIC = "pause_command_topic"
CONF_PAUSE_COMMAND_TEMPLATE = "pause_command_template"
CONF_START_MOWING_COMMAND_TOPIC = "start_mowing_command_topic"
CONF_START_MOWING_COMMAND_TEMPLATE = "start_mowing_command_template"
CONF_STOP_COMMAND_TOPIC = "stop_command_topic"
CONF_STOP_COMMAND_TEMPLATE = "stop_command_template"
DEFAULT_NAME = "MQTT Lawn Mower"
MQTT_LAWN_MOWER_ATTRIBUTES_BLOCKED: frozenset[str] = frozenset()
FEATURE_DOCK = "dock"
FEATURE_PAUSE = "pause"
FEATURE_START_MOWING = "start_mowing"
FEATURE_STOP = "stop"
PLATFORM_SCHEMA_MODERN = MQTT_BASE_SCHEMA.extend(
{
probatio.Optional(CONF_ACTIVITY_VALUE_TEMPLATE): cv.template,
probatio.Optional(CONF_ACTIVITY_STATE_TOPIC): valid_subscribe_topic,
probatio.Optional(CONF_DOCK_COMMAND_TEMPLATE): cv.template,
probatio.Optional(CONF_DOCK_COMMAND_TOPIC): valid_publish_topic,
probatio.Optional(CONF_NAME): probatio.Any(cv.string, None),
probatio.Optional(CONF_OPTIMISTIC, default=DEFAULT_OPTIMISTIC): cv.boolean,
probatio.Optional(CONF_PAUSE_COMMAND_TEMPLATE): cv.template,
probatio.Optional(CONF_PAUSE_COMMAND_TOPIC): valid_publish_topic,
probatio.Optional(CONF_RETAIN, default=DEFAULT_RETAIN): cv.boolean,
probatio.Optional(CONF_START_MOWING_COMMAND_TEMPLATE): cv.template,
probatio.Optional(CONF_START_MOWING_COMMAND_TOPIC): valid_publish_topic,
probatio.Optional(CONF_STOP_COMMAND_TEMPLATE): cv.template,
probatio.Optional(CONF_STOP_COMMAND_TOPIC): valid_publish_topic,
},
).extend(MQTT_ENTITY_COMMON_SCHEMA.schema)
DISCOVERY_SCHEMA = probatio.All(
PLATFORM_SCHEMA_MODERN.extend({}, extra=probatio.REMOVE_EXTRA)
)
async def async_setup_entry(
hass: HomeAssistant,
config_entry: ConfigEntry,
async_add_entities: AddConfigEntryEntitiesCallback,
) -> None:
"""Set up MQTT lawn mower through YAML and through MQTT discovery."""
async_setup_entity_entry_helper(
hass,
config_entry,
MqttLawnMower,
lawn_mower.DOMAIN,
async_add_entities,
DISCOVERY_SCHEMA,
PLATFORM_SCHEMA_MODERN,
)
class MqttLawnMower(MqttEntity, LawnMowerEntity, RestoreEntity):
"""Representation of an MQTT lawn mower."""
_default_name = DEFAULT_NAME
_entity_id_format = ENTITY_ID_FORMAT
_attributes_extra_blocked = MQTT_LAWN_MOWER_ATTRIBUTES_BLOCKED
_command_templates: dict[str, Callable[[PublishPayloadType], PublishPayloadType]]
_command_topics: dict[str, str]
_value_template: Callable[[ReceivePayloadType], ReceivePayloadType]
@staticmethod
@override
def config_schema() -> VolSchemaType:
"""Return the config schema."""
return DISCOVERY_SCHEMA
@override
def _setup_from_config(self, config: ConfigType) -> None:
"""(Re)Setup the entity."""
self._attr_assumed_state = config[CONF_OPTIMISTIC]
self._value_template = MqttValueTemplate(
config.get(CONF_ACTIVITY_VALUE_TEMPLATE), entity=self
).async_render_with_possible_json_value
supported_features = LawnMowerEntityFeature(0)
self._command_topics = {}
if CONF_DOCK_COMMAND_TOPIC in config:
self._command_topics[FEATURE_DOCK] = config[CONF_DOCK_COMMAND_TOPIC]
supported_features |= LawnMowerEntityFeature.DOCK
if CONF_PAUSE_COMMAND_TOPIC in config:
self._command_topics[FEATURE_PAUSE] = config[CONF_PAUSE_COMMAND_TOPIC]
supported_features |= LawnMowerEntityFeature.PAUSE
if CONF_START_MOWING_COMMAND_TOPIC in config:
self._command_topics[FEATURE_START_MOWING] = config[
CONF_START_MOWING_COMMAND_TOPIC
]
supported_features |= LawnMowerEntityFeature.START_MOWING
if CONF_STOP_COMMAND_TOPIC in config:
self._command_topics[FEATURE_STOP] = config[CONF_STOP_COMMAND_TOPIC]
supported_features |= LawnMowerEntityFeature.STOP
self._attr_supported_features = supported_features
self._command_templates = {}
self._command_templates[FEATURE_DOCK] = MqttCommandTemplate(
config.get(CONF_DOCK_COMMAND_TEMPLATE), entity=self
).async_render
self._command_templates[FEATURE_PAUSE] = MqttCommandTemplate(
config.get(CONF_PAUSE_COMMAND_TEMPLATE), entity=self
).async_render
self._command_templates[FEATURE_START_MOWING] = MqttCommandTemplate(
config.get(CONF_START_MOWING_COMMAND_TEMPLATE), entity=self
).async_render
self._command_templates[FEATURE_STOP] = MqttCommandTemplate(
config.get(CONF_STOP_COMMAND_TEMPLATE), entity=self
).async_render
@callback
def _message_received(self, msg: ReceiveMessage) -> None:
"""Handle new MQTT messages."""
payload = str(self._value_template(msg.payload))
if not payload:
_LOGGER.debug(
"Invalid empty activity payload from topic %s, for entity %s",
msg.topic,
self.entity_id,
)
return
if payload.lower() == "none":
self._attr_activity = None
return
try:
self._attr_activity = LawnMowerActivity(payload)
except ValueError:
_LOGGER.error(
"Invalid activity for %s: '%s' (valid activities: %s)",
self.entity_id,
payload,
[option.value for option in LawnMowerActivity],
)
return
@callback
@override
def _prepare_subscribe_topics(self) -> None:
"""(Re)Subscribe to topics."""
if not self.add_subscription(
CONF_ACTIVITY_STATE_TOPIC, self._message_received, {"_attr_activity"}
):
# Force into optimistic mode.
self._attr_assumed_state = True
return
@override
async def _subscribe_topics(self) -> None:
"""(Re)Subscribe to topics."""
subscription.async_subscribe_topics_internal(self.hass, self._sub_state)
if self._attr_assumed_state and (
last_state := await self.async_get_last_state()
):
with contextlib.suppress(ValueError):
self._attr_activity = LawnMowerActivity(last_state.state)
async def _async_operate(self, option: str, activity: LawnMowerActivity) -> None:
"""Execute operation."""
payload = self._command_templates[option](option)
if self._attr_assumed_state:
self._attr_activity = activity
self.async_write_ha_state()
await self.async_publish_with_config(self._command_topics[option], payload)
@override
async def async_start_mowing(self) -> None:
"""Start or resume mowing."""
await self._async_operate("start_mowing", LawnMowerActivity.MOWING)
@override
async def async_dock(self) -> None:
"""Dock the mower."""
await self._async_operate("dock", LawnMowerActivity.DOCKED)
@override
async def async_pause(self) -> None:
"""Pause the lawn mower."""
await self._async_operate("pause", LawnMowerActivity.PAUSED)
@override
async def async_stop(self) -> None:
"""Stop the lawn mower."""
await self._async_operate("stop", LawnMowerActivity.IDLE)
+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()
+281
View File
@@ -0,0 +1,281 @@
"""Support for MQTT locks."""
from collections.abc import Callable
import logging
import re
from typing import Any, override
import probatio
from homeassistant.components import lock
from homeassistant.components.lock import (
LockEntity,
LockEntityFeature,
LockEntityStateAttribute,
)
from homeassistant.config_entries import ConfigEntry
from homeassistant.const import (
ATTR_CODE,
CONF_NAME,
CONF_OPTIMISTIC,
CONF_VALUE_TEMPLATE,
)
from homeassistant.core import HomeAssistant, callback
from homeassistant.helpers import config_validation as cv
from homeassistant.helpers.entity_platform import AddConfigEntryEntitiesCallback
from homeassistant.helpers.service_info.mqtt import ReceivePayloadType
from homeassistant.helpers.typing import ConfigType, TemplateVarsType
from . import subscription
from .config import MQTT_RW_SCHEMA
from .const import (
CONF_CODE_FORMAT,
CONF_COMMAND_TEMPLATE,
CONF_COMMAND_TOPIC,
CONF_PAYLOAD_LOCK,
CONF_PAYLOAD_OPEN,
CONF_PAYLOAD_RESET,
CONF_PAYLOAD_UNLOCK,
CONF_STATE_JAMMED,
CONF_STATE_LOCKED,
CONF_STATE_LOCKING,
CONF_STATE_OPEN,
CONF_STATE_OPENING,
CONF_STATE_TOPIC,
CONF_STATE_UNLOCKED,
CONF_STATE_UNLOCKING,
DEFAULT_PAYLOAD_LOCK,
DEFAULT_PAYLOAD_RESET,
DEFAULT_PAYLOAD_UNLOCK,
DEFAULT_STATE_JAMMED,
DEFAULT_STATE_LOCKED,
DEFAULT_STATE_LOCKING,
DEFAULT_STATE_OPEN,
DEFAULT_STATE_OPENING,
DEFAULT_STATE_UNLOCKED,
DEFAULT_STATE_UNLOCKING,
)
from .entity import MqttEntity, async_setup_entity_entry_helper
from .models import (
MqttCommandTemplate,
MqttValueTemplate,
PublishPayloadType,
ReceiveMessage,
)
from .schemas import MQTT_ENTITY_COMMON_SCHEMA
_LOGGER = logging.getLogger(__name__)
PARALLEL_UPDATES = 0
DEFAULT_NAME = "MQTT Lock"
MQTT_LOCK_ATTRIBUTES_BLOCKED = frozenset(
{
LockEntityStateAttribute.CHANGED_BY,
LockEntityStateAttribute.CODE_FORMAT,
}
)
PLATFORM_SCHEMA_MODERN = MQTT_RW_SCHEMA.extend(
{
probatio.Optional(CONF_CODE_FORMAT): cv.is_regex,
probatio.Optional(CONF_COMMAND_TEMPLATE): cv.template,
probatio.Optional(CONF_NAME): probatio.Any(cv.string, None),
probatio.Optional(CONF_PAYLOAD_LOCK, default=DEFAULT_PAYLOAD_LOCK): cv.string,
probatio.Optional(
CONF_PAYLOAD_UNLOCK, default=DEFAULT_PAYLOAD_UNLOCK
): cv.string,
probatio.Optional(CONF_PAYLOAD_OPEN): cv.string,
probatio.Optional(CONF_PAYLOAD_RESET, default=DEFAULT_PAYLOAD_RESET): cv.string,
probatio.Optional(CONF_STATE_JAMMED, default=DEFAULT_STATE_JAMMED): cv.string,
probatio.Optional(CONF_STATE_LOCKED, default=DEFAULT_STATE_LOCKED): cv.string,
probatio.Optional(CONF_STATE_LOCKING, default=DEFAULT_STATE_LOCKING): cv.string,
probatio.Optional(CONF_STATE_OPEN, default=DEFAULT_STATE_OPEN): cv.string,
probatio.Optional(CONF_STATE_OPENING, default=DEFAULT_STATE_OPENING): cv.string,
probatio.Optional(
CONF_STATE_UNLOCKED, default=DEFAULT_STATE_UNLOCKED
): cv.string,
probatio.Optional(
CONF_STATE_UNLOCKING, default=DEFAULT_STATE_UNLOCKING
): cv.string,
probatio.Optional(CONF_VALUE_TEMPLATE): cv.template,
}
).extend(MQTT_ENTITY_COMMON_SCHEMA.schema)
DISCOVERY_SCHEMA = PLATFORM_SCHEMA_MODERN.extend({}, extra=probatio.REMOVE_EXTRA)
STATE_CONFIG_KEYS = [
CONF_STATE_JAMMED,
CONF_STATE_LOCKED,
CONF_STATE_LOCKING,
CONF_STATE_OPEN,
CONF_STATE_OPENING,
CONF_STATE_UNLOCKED,
CONF_STATE_UNLOCKING,
]
async def async_setup_entry(
hass: HomeAssistant,
config_entry: ConfigEntry,
async_add_entities: AddConfigEntryEntitiesCallback,
) -> None:
"""Set up MQTT lock through YAML and through MQTT discovery."""
async_setup_entity_entry_helper(
hass,
config_entry,
MqttLock,
lock.DOMAIN,
async_add_entities,
DISCOVERY_SCHEMA,
PLATFORM_SCHEMA_MODERN,
)
class MqttLock(MqttEntity, LockEntity):
"""Representation of a lock that can be toggled using MQTT."""
_default_name = DEFAULT_NAME
_entity_id_format = lock.ENTITY_ID_FORMAT
_attributes_extra_blocked = MQTT_LOCK_ATTRIBUTES_BLOCKED
_compiled_pattern: re.Pattern[Any] | None
_optimistic: bool
_valid_states: list[str]
_command_template: Callable[
[PublishPayloadType, TemplateVarsType], PublishPayloadType
]
_value_template: Callable[[ReceivePayloadType], ReceivePayloadType]
@staticmethod
@override
def config_schema() -> probatio.Schema:
"""Return the config schema."""
return DISCOVERY_SCHEMA
@override
def _setup_from_config(self, config: ConfigType) -> None:
"""(Re)Setup the entity."""
if (
optimistic := config[CONF_OPTIMISTIC]
or config.get(CONF_STATE_TOPIC) is None
):
self._attr_is_locked = False
self._optimistic = optimistic
self._attr_assumed_state = bool(optimistic)
self._compiled_pattern = config.get(CONF_CODE_FORMAT)
self._attr_code_format = (
self._compiled_pattern.pattern if self._compiled_pattern else None
)
self._command_template = MqttCommandTemplate(
config.get(CONF_COMMAND_TEMPLATE), entity=self
).async_render
self._value_template = MqttValueTemplate(
config.get(CONF_VALUE_TEMPLATE),
entity=self,
).async_render_with_possible_json_value
self._attr_supported_features = LockEntityFeature(0)
if CONF_PAYLOAD_OPEN in config:
self._attr_supported_features |= LockEntityFeature.OPEN
self._valid_states = [config[state] for state in STATE_CONFIG_KEYS]
@callback
def _message_received(self, msg: ReceiveMessage) -> None:
"""Handle new lock state messages."""
payload = self._value_template(msg.payload)
if not payload.strip(): # No output from template, ignore
_LOGGER.debug(
"Ignoring empty payload '%s' after rendering for topic %s",
payload,
msg.topic,
)
return
if payload == self._config[CONF_PAYLOAD_RESET]:
# Reset the state to `unknown`
self._attr_is_locked = self._attr_is_locking = None
self._attr_is_unlocking = None
self._attr_is_open = self._attr_is_opening = None
self._attr_is_jammed = None
elif payload in self._valid_states:
self._attr_is_locked = payload == self._config[CONF_STATE_LOCKED]
self._attr_is_locking = payload == self._config[CONF_STATE_LOCKING]
self._attr_is_open = payload == self._config[CONF_STATE_OPEN]
self._attr_is_opening = payload == self._config[CONF_STATE_OPENING]
self._attr_is_unlocking = payload == self._config[CONF_STATE_UNLOCKING]
self._attr_is_jammed = payload == self._config[CONF_STATE_JAMMED]
@callback
@override
def _prepare_subscribe_topics(self) -> None:
"""(Re)Subscribe to topics."""
self.add_subscription(
CONF_STATE_TOPIC,
self._message_received,
{
"_attr_is_jammed",
"_attr_is_locked",
"_attr_is_locking",
"_attr_is_open",
"_attr_is_opening",
"_attr_is_unlocking",
},
)
@override
async def _subscribe_topics(self) -> None:
"""(Re)Subscribe to topics."""
subscription.async_subscribe_topics_internal(self.hass, self._sub_state)
@override
async def async_lock(self, **kwargs: Any) -> None:
"""Lock the device.
This method is a coroutine.
"""
tpl_vars: TemplateVarsType = {
ATTR_CODE: kwargs.get(ATTR_CODE) if kwargs else None
}
payload = self._command_template(self._config[CONF_PAYLOAD_LOCK], tpl_vars)
await self.async_publish_with_config(self._config[CONF_COMMAND_TOPIC], payload)
if self._optimistic:
# Optimistically assume that the lock has changed state.
self._attr_is_locked = True
self.async_write_ha_state()
@override
async def async_unlock(self, **kwargs: Any) -> None:
"""Unlock the device.
This method is a coroutine.
"""
tpl_vars: TemplateVarsType = {
ATTR_CODE: kwargs.get(ATTR_CODE) if kwargs else None
}
payload = self._command_template(self._config[CONF_PAYLOAD_UNLOCK], tpl_vars)
await self.async_publish_with_config(self._config[CONF_COMMAND_TOPIC], payload)
if self._optimistic:
# Optimistically assume that the lock has changed state.
self._attr_is_locked = False
self.async_write_ha_state()
@override
async def async_open(self, **kwargs: Any) -> None:
"""Open the door latch.
This method is a coroutine.
"""
tpl_vars: TemplateVarsType = {
ATTR_CODE: kwargs.get(ATTR_CODE) if kwargs else None
}
payload = self._command_template(self._config[CONF_PAYLOAD_OPEN], tpl_vars)
await self.async_publish_with_config(self._config[CONF_COMMAND_TOPIC], payload)
if self._optimistic:
# Optimistically assume that the lock unlocks when opened.
self._attr_is_open = True
self.async_write_ha_state()
+20
View File
@@ -0,0 +1,20 @@
{
"domain": "vmqtt",
"name": "Visquitto MQTT",
"version": "0.1.0",
"after_dependencies": [
"hassio"
],
"config_flow": true,
"dependencies": [
"file_upload",
"http"
],
"documentation": "https://www.home-assistant.io/integrations/mqtt/",
"integration_type": "service",
"iot_class": "local_push",
"requirements": [
"paho-mqtt==2.1.0"
],
"single_config_entry": true
}
+560
View File
@@ -0,0 +1,560 @@
"""Models used by multiple MQTT modules."""
from ast import literal_eval
import asyncio
from collections import deque
from collections.abc import Callable
from dataclasses import dataclass, field
from enum import StrEnum
import logging
from typing import TYPE_CHECKING, Any, TypedDict, override
from paho.mqtt.client import MQTTMessage
from homeassistant.const import ATTR_ENTITY_ID, ATTR_NAME, Platform
from homeassistant.core import CALLBACK_TYPE, callback
from homeassistant.exceptions import (
HomeAssistantError,
ServiceValidationError,
TemplateError,
)
from homeassistant.helpers import template
from homeassistant.helpers.entity import Entity
from homeassistant.helpers.service_info.mqtt import ReceivePayloadType
from homeassistant.helpers.typing import (
ConfigType,
DiscoveryInfoType,
TemplateVarsType,
VolSchemaType,
)
from homeassistant.util.hass_dict import HassKey
if TYPE_CHECKING:
from .client import MQTT, Subscription
from .debug_info import TimestampedPublishMessage
from .device_trigger import Trigger
from .discovery import MQTTDiscoveryPayload
from .tag import MQTTTagScanner
from .const import DOMAIN, TEMPLATE_ERRORS
class PayloadSentinel(StrEnum):
"""Sentinel for `async_render_with_possible_json_value`."""
NONE = "none"
DEFAULT = "default"
MAX_28BIT: int = 268435455
class SubscriptionID:
"""ID generator for wildcard subscriptions."""
_next_id: int = 2
_used_ids: set[int]
_available_ids: set[int]
_registered_subscriptions: dict[str, int] # topic, subscription_id
def __init__(self) -> None:
"""Initialize the Subscription Identifier generator."""
self._used_ids = set()
self._available_ids = set()
self._registered_subscriptions = {}
def _generate(self, topic: str) -> int:
"""Generate a new subscription ID."""
if self._available_ids:
subscription_id = self._available_ids.pop()
self._used_ids.add(subscription_id)
self._registered_subscriptions[topic] = subscription_id
return subscription_id
subscription_id = self._next_id
if subscription_id > MAX_28BIT:
raise HomeAssistantError(
translation_domain=DOMAIN,
translation_key="mqtt_max_subscription_id_reached",
)
self._used_ids.add(subscription_id)
self._next_id += 1
self._registered_subscriptions[topic] = subscription_id
return subscription_id
def get_subscription_id(self, topic: str) -> int:
"""Get a registered subscription ID."""
return self._registered_subscriptions[topic]
def get_or_generate(self, topic: str) -> int:
"""Get an existing or generate a new subscription ID.
ID 0 is reserved.
ID 1 is used for non wildcard topics.
Generator starts at ID 2.
"""
if topic in self._registered_subscriptions:
return self._registered_subscriptions[topic]
return self._generate(topic)
def release(self, topic: str) -> None:
"""Release a Subscription Identifier to allow reuse."""
if (
(subscription_id := self._registered_subscriptions.pop(topic, None))
is not None
and subscription_id
and subscription_id in self._used_ids
):
self._used_ids.remove(subscription_id)
self._available_ids.add(subscription_id)
_LOGGER = logging.getLogger(__name__)
ATTR_THIS = "this"
type PublishPayloadType = str | bytes | int | float | None
def convert_outgoing_mqtt_payload(
payload: PublishPayloadType,
) -> PublishPayloadType:
"""Ensure correct raw MQTT payload is passed as bytes for publishing."""
if isinstance(payload, str) and payload.startswith(("b'", 'b"')):
try:
native_object = literal_eval(payload)
except ValueError, TypeError, SyntaxError, MemoryError:
pass
else:
if isinstance(native_object, bytes):
return native_object
return payload
@dataclass
class PublishMessage:
"""MQTT Message for publishing."""
topic: str
payload: PublishPayloadType
qos: int
retain: bool
# eq=False so we use the id() of the object for comparison
# since client will only generate one instance of this object
# per messages/subscribed_topic.
@dataclass(slots=True, frozen=True, eq=False)
class ReceiveMessage:
"""MQTT Message received."""
topic: str
payload: ReceivePayloadType
qos: int
retain: bool
subscribed_topic: str
timestamp: float
type MessageCallbackType = Callable[[ReceiveMessage], None]
class SubscriptionDebugInfo(TypedDict):
"""Class for holding subscription debug info."""
messages: deque[ReceiveMessage]
count: int
class EntityDebugInfo(TypedDict):
"""Class for holding entity based debug info."""
subscriptions: dict[str, SubscriptionDebugInfo]
discovery_data: DiscoveryInfoType
transmitted: dict[str, dict[str, deque[TimestampedPublishMessage]]]
class TriggerDebugInfo(TypedDict):
"""Class for holding trigger based debug info."""
device_id: str
discovery_data: DiscoveryInfoType
class PendingDiscovered(TypedDict):
"""Pending discovered items."""
pending: deque[MQTTDiscoveryPayload]
unsub: CALLBACK_TYPE
class MqttOriginInfo(TypedDict, total=False):
"""Integration info of discovered entity."""
name: str
manufacturer: str
sw_version: str
hw_version: str
support_url: str
class MqttCommandTemplateException(ServiceValidationError):
"""Handle MqttCommandTemplate exceptions."""
_message: str
def __init__(
self,
*args: object,
base_exception: Exception,
command_template: str,
value: PublishPayloadType,
entity_id: str | None = None,
) -> None:
"""Initialize exception."""
super().__init__(base_exception, *args)
value_log = str(value)
self.translation_domain = DOMAIN
self.translation_key = "command_template_error"
self.translation_placeholders = {
"error": str(base_exception),
"entity_id": str(entity_id),
"command_template": command_template,
}
entity_id_log = "" if entity_id is None else f" for entity '{entity_id}'"
self._message = (
f"{type(base_exception).__name__}:"
f" {base_exception} rendering"
f" template{entity_id_log}"
f", template: '{command_template}'"
f" and payload: {value_log}"
)
@override
def __str__(self) -> str:
"""Return exception message string."""
return self._message
class MqttCommandTemplate:
"""Class for rendering MQTT payload with command templates."""
def __init__(
self,
command_template: template.Template | None,
*,
entity: Entity | None = None,
) -> None:
"""Instantiate a command template."""
self._template_state: template.TemplateStateFromEntityId | None = None
self._command_template = command_template
self._entity = entity
@callback
def async_render(
self,
value: PublishPayloadType = None,
variables: TemplateVarsType = None,
) -> PublishPayloadType:
"""Render or convert the command template with given value or variables."""
if self._command_template is None:
return value
values: dict[str, Any] = {"value": value}
if self._entity:
values[ATTR_ENTITY_ID] = self._entity.entity_id
values[ATTR_NAME] = self._entity.name
if not self._template_state and self._command_template.hass is not None:
self._template_state = template.TemplateStateFromEntityId(
self._entity.hass, self._entity.entity_id
)
values[ATTR_THIS] = self._template_state
if variables is not None:
values.update(variables)
_LOGGER.debug(
"Rendering outgoing payload with variables %s and %s",
values,
self._command_template,
)
try:
return convert_outgoing_mqtt_payload(
self._command_template.async_render(values, parse_result=False)
)
except TemplateError as exc:
raise MqttCommandTemplateException(
base_exception=exc,
command_template=self._command_template.template,
value=value,
entity_id=self._entity.entity_id if self._entity is not None else None,
) from exc
class MqttValueTemplateException(TemplateError):
"""Handle MqttValueTemplate exceptions."""
_message: str
def __init__(
self,
*args: object,
base_exception: Exception,
value_template: str,
default: ReceivePayloadType | PayloadSentinel,
payload: ReceivePayloadType,
entity_id: str | None = None,
) -> None:
"""Initialize exception."""
super().__init__(base_exception, *args)
entity_id_log = "" if entity_id is None else f" for entity '{entity_id}'"
default_log = str(default)
default_payload_log = (
"" if default is PayloadSentinel.NONE else f", default value: {default_log}"
)
payload_log = str(payload)
self._message = (
f"{type(base_exception).__name__}:"
f" {base_exception} rendering"
f" template{entity_id_log}"
f", template: '{value_template}'"
f"{default_payload_log}"
f" and payload: {payload_log}"
)
@override
def __str__(self) -> str:
"""Return exception message string."""
return self._message
class MqttValueTemplate:
"""Class for rendering MQTT value template with possible json values."""
def __init__(
self,
value_template: template.Template | None,
*,
entity: Entity | None = None,
config_attributes: TemplateVarsType = None,
) -> None:
"""Instantiate a value template."""
self._template_state: template.TemplateStateFromEntityId | None = None
self._value_template = value_template
self._config_attributes = config_attributes
self._entity = entity
@callback
def async_render_with_possible_json_value(
self,
payload: ReceivePayloadType,
default: ReceivePayloadType | PayloadSentinel = PayloadSentinel.NONE,
variables: TemplateVarsType = None,
) -> ReceivePayloadType:
"""Render with possible json value or pass-though a received MQTT value."""
rendered_payload: ReceivePayloadType
if self._value_template is None:
return payload
values: dict[str, Any] = {}
if variables is not None:
values.update(variables)
if self._config_attributes is not None:
values.update(self._config_attributes)
if self._entity:
values[ATTR_ENTITY_ID] = self._entity.entity_id
values[ATTR_NAME] = self._entity.name
if not self._template_state and self._value_template.hass:
self._template_state = template.TemplateStateFromEntityId(
self._value_template.hass, self._entity.entity_id
)
values[ATTR_THIS] = self._template_state
if default is PayloadSentinel.NONE:
_LOGGER.debug(
"Rendering incoming payload '%s' with variables %s and %s",
payload,
values,
self._value_template,
)
try:
rendered_payload = (
self._value_template.async_render_with_possible_json_value(
payload, variables=values
)
)
except TEMPLATE_ERRORS as exc:
raise MqttValueTemplateException(
base_exception=exc,
value_template=self._value_template.template,
default=default,
payload=payload,
entity_id=self._entity.entity_id if self._entity else None,
) from exc
return rendered_payload
_LOGGER.debug(
(
"Rendering incoming payload '%s' with variables %s with default value"
" '%s' and %s"
),
payload,
values,
default,
self._value_template,
)
try:
rendered_payload = (
self._value_template.async_render_with_possible_json_value(
payload, default, variables=values
)
)
except TEMPLATE_ERRORS as exc:
raise MqttValueTemplateException(
base_exception=exc,
value_template=self._value_template.template,
default=default,
payload=payload,
entity_id=self._entity.entity_id if self._entity else None,
) from exc
return rendered_payload
class EntityTopicState:
"""Manage entity state write requests for subscribed topics."""
def __init__(self) -> None:
"""Register topic."""
self.subscribe_calls: dict[str, Entity] = {}
@callback
def process_write_state_requests(self, msg: MQTTMessage) -> None:
"""Process the write state requests."""
while self.subscribe_calls:
entity_id, entity = self.subscribe_calls.popitem()
try:
entity.async_write_ha_state()
except ValueError as exc:
_LOGGER.error(
"Value error while updating state of %s, topic: "
"'%s' with payload: %s: %s",
entity_id,
msg.topic,
msg.payload,
exc,
)
except Exception:
_LOGGER.exception(
"Exception raised while updating state of %s, topic: "
"'%s' with payload: %s",
entity_id,
msg.topic,
msg.payload,
)
@callback
def write_state_request(self, entity: Entity) -> None:
"""Register write state request."""
self.subscribe_calls[entity.entity_id] = entity
@dataclass
class MqttData:
"""Keep the MQTT entry data."""
client: MQTT
config: list[ConfigType]
debug_info_entities: dict[str, EntityDebugInfo] = field(default_factory=dict)
debug_info_triggers: dict[tuple[str, str], TriggerDebugInfo] = field(
default_factory=dict
)
device_triggers: dict[str, Trigger] = field(default_factory=dict)
data_config_flow_lock: asyncio.Lock = field(default_factory=asyncio.Lock)
# Attribute `discovery_discovered_and_disabled` maps a discovery hash to
# the entity registry index, which is a tuple (entity_platform, "mqtt", unique_id)
# It allows to cleanup disabled entities when an empty payload is received.
discovery_discovered_and_disabled: dict[tuple[str, str], tuple[str, str, str]] = (
field(default_factory=dict)
)
discovery_already_discovered: set[tuple[str, str]] = field(default_factory=set)
discovery_pending_discovered: dict[tuple[str, str], PendingDiscovered] = field(
default_factory=dict
)
discovery_registry_hooks: dict[tuple[str, str], CALLBACK_TYPE] = field(
default_factory=dict
)
discovery_unsubscribe: list[CALLBACK_TYPE] = field(default_factory=list)
integration_unsubscribe: dict[str, CALLBACK_TYPE] = field(default_factory=dict)
last_discovery: float = 0.0
platforms_loaded: set[Platform | str] = field(default_factory=set)
reload_dispatchers: list[CALLBACK_TYPE] = field(default_factory=list)
reload_handlers: dict[str, CALLBACK_TYPE] = field(default_factory=dict)
reload_schema: dict[str, VolSchemaType] = field(default_factory=dict)
state_write_requests: EntityTopicState = field(default_factory=EntityTopicState)
subscriptions_to_restore: set[Subscription] = field(default_factory=set)
tags: dict[str, dict[str, MQTTTagScanner]] = field(default_factory=dict)
subscription_id_generator: SubscriptionID = field(default_factory=SubscriptionID)
@dataclass(slots=True)
class MqttComponentConfig:
"""(component, object_id, node_id, discovery_payload)."""
component: str
object_id: str
node_id: str | None
discovery_payload: MQTTDiscoveryPayload
class MessageExpiryInterval(TypedDict, total=False):
"""Hold the Message Expiry Interval."""
days: float
hours: float
minutes: float
seconds: float
class DeviceMqttOptions(TypedDict, total=False):
"""Hold the shared MQTT specific options for an MQTT device."""
qos: int
message_expiry_interval: MessageExpiryInterval
class MqttDeviceData(TypedDict, total=False):
"""Hold the data for an MQTT device."""
name: str
identifiers: str
configuration_url: str
sw_version: str
hw_version: str
model: str
model_id: str
mqtt_settings: DeviceMqttOptions
class MqttAvailabilityData(TypedDict, total=False):
"""Hold the availability configuration for a device."""
availability_topic: str
availability_template: str
payload_available: str
payload_not_available: str
class MqttSubentryData(TypedDict, total=False):
"""Hold the data for a MQTT subentry."""
device: MqttDeviceData
components: dict[str, dict[str, Any]]
availability: MqttAvailabilityData
DATA_MQTT: HassKey[MqttData] = HassKey("vmqtt")
DATA_MQTT_AVAILABLE: HassKey[asyncio.Future[bool]] = HassKey("vmqtt_client_available")
+88
View File
@@ -0,0 +1,88 @@
"""Support for MQTT notify."""
from typing import override
import probatio
from homeassistant.components import notify
from homeassistant.components.notify import NotifyEntity
from homeassistant.config_entries import ConfigEntry
from homeassistant.const import CONF_NAME
from homeassistant.core import HomeAssistant, callback
from homeassistant.helpers import config_validation as cv
from homeassistant.helpers.entity_platform import AddConfigEntryEntitiesCallback
from homeassistant.helpers.typing import ConfigType
from .config import DEFAULT_RETAIN, MQTT_BASE_SCHEMA
from .const import CONF_COMMAND_TEMPLATE, CONF_COMMAND_TOPIC, CONF_RETAIN
from .entity import MqttEntity, async_setup_entity_entry_helper
from .models import MqttCommandTemplate
from .schemas import MQTT_ENTITY_COMMON_SCHEMA
from .util import valid_publish_topic
PARALLEL_UPDATES = 0
DEFAULT_NAME = "MQTT notify"
PLATFORM_SCHEMA_MODERN = MQTT_BASE_SCHEMA.extend(
{
probatio.Optional(CONF_COMMAND_TEMPLATE): cv.template,
probatio.Required(CONF_COMMAND_TOPIC): valid_publish_topic,
probatio.Optional(CONF_NAME): probatio.Any(cv.string, None),
probatio.Optional(CONF_RETAIN, default=DEFAULT_RETAIN): cv.boolean,
}
).extend(MQTT_ENTITY_COMMON_SCHEMA.schema)
DISCOVERY_SCHEMA = PLATFORM_SCHEMA_MODERN.extend({}, extra=probatio.REMOVE_EXTRA)
async def async_setup_entry(
hass: HomeAssistant,
config_entry: ConfigEntry,
async_add_entities: AddConfigEntryEntitiesCallback,
) -> None:
"""Set up MQTT notify through YAML and through MQTT discovery."""
async_setup_entity_entry_helper(
hass,
config_entry,
MqttNotify,
notify.DOMAIN,
async_add_entities,
DISCOVERY_SCHEMA,
PLATFORM_SCHEMA_MODERN,
)
class MqttNotify(MqttEntity, NotifyEntity):
"""Notification entity that can send messages using MQTT."""
_default_name = DEFAULT_NAME
_entity_id_format = notify.ENTITY_ID_FORMAT
@staticmethod
@override
def config_schema() -> probatio.Schema:
"""Return the config schema."""
return DISCOVERY_SCHEMA
@override
def _setup_from_config(self, config: ConfigType) -> None:
"""(Re)Setup the entity."""
self._command_template = MqttCommandTemplate(
config.get(CONF_COMMAND_TEMPLATE), entity=self
).async_render
@callback
@override
def _prepare_subscribe_topics(self) -> None:
"""(Re)Subscribe to topics."""
@override
async def _subscribe_topics(self) -> None:
"""(Re)Subscribe to topics."""
@override
async def async_send_message(self, message: str, title: str | None = None) -> None:
"""Send a message."""
payload = self._command_template(message)
await self.async_publish_with_config(self._config[CONF_COMMAND_TOPIC], payload)
+238
View File
@@ -0,0 +1,238 @@
"""Configure number in a device through MQTT topic."""
from collections.abc import Callable
import logging
from typing import override
import probatio
from homeassistant.components import number
from homeassistant.components.number import (
DEFAULT_MAX_VALUE,
DEFAULT_MIN_VALUE,
DEFAULT_STEP,
NumberDeviceClass,
NumberEntityCapabilityAttribute,
NumberMode,
RestoreNumber,
)
from homeassistant.components.sensor import AMBIGUOUS_UNITS
from homeassistant.config_entries import ConfigEntry
from homeassistant.const import (
CONF_DEVICE_CLASS,
CONF_MODE,
CONF_NAME,
CONF_OPTIMISTIC,
CONF_UNIT_OF_MEASUREMENT,
CONF_VALUE_TEMPLATE,
)
from homeassistant.core import HomeAssistant, callback
from homeassistant.helpers import config_validation as cv
from homeassistant.helpers.entity_platform import AddConfigEntryEntitiesCallback
from homeassistant.helpers.service_info.mqtt import ReceivePayloadType
from homeassistant.helpers.typing import ConfigType, VolSchemaType
from . import subscription
from .config import MQTT_RW_SCHEMA
from .const import (
CONF_COMMAND_TEMPLATE,
CONF_COMMAND_TOPIC,
CONF_MAX,
CONF_MIN,
CONF_PAYLOAD_RESET,
CONF_STATE_TOPIC,
CONF_STEP,
DEFAULT_PAYLOAD_RESET,
)
from .entity import MqttEntity, async_setup_entity_entry_helper
from .models import (
MqttCommandTemplate,
MqttValueTemplate,
PublishPayloadType,
ReceiveMessage,
)
from .schemas import MQTT_ENTITY_COMMON_SCHEMA
_LOGGER = logging.getLogger(__name__)
PARALLEL_UPDATES = 0
DEFAULT_NAME = "MQTT Number"
MQTT_NUMBER_ATTRIBUTES_BLOCKED = frozenset(
{
NumberEntityCapabilityAttribute.MAX,
NumberEntityCapabilityAttribute.MIN,
NumberEntityCapabilityAttribute.STEP,
}
)
def validate_config(config: ConfigType) -> ConfigType:
"""Validate that the configuration is valid, throws if it isn't."""
if (
CONF_UNIT_OF_MEASUREMENT in config
and (unit_of_measurement := config[CONF_UNIT_OF_MEASUREMENT]) in AMBIGUOUS_UNITS
):
config[CONF_UNIT_OF_MEASUREMENT] = AMBIGUOUS_UNITS[unit_of_measurement]
if config[CONF_MIN] > config[CONF_MAX]:
raise probatio.Invalid(f"{CONF_MAX} must be >= {CONF_MIN}")
return config
_PLATFORM_SCHEMA_BASE = MQTT_RW_SCHEMA.extend(
{
probatio.Optional(CONF_COMMAND_TEMPLATE): cv.template,
probatio.Optional(CONF_DEVICE_CLASS): probatio.Any(
probatio.All(probatio.Lower, probatio.Coerce(NumberDeviceClass)), None
),
probatio.Optional(CONF_MAX, default=DEFAULT_MAX_VALUE): probatio.Coerce(float),
probatio.Optional(CONF_MIN, default=DEFAULT_MIN_VALUE): probatio.Coerce(float),
probatio.Optional(CONF_MODE, default=NumberMode.AUTO): probatio.Coerce(
NumberMode
),
probatio.Optional(CONF_NAME): probatio.Any(cv.string, None),
probatio.Optional(CONF_PAYLOAD_RESET, default=DEFAULT_PAYLOAD_RESET): cv.string,
probatio.Optional(CONF_STEP, default=DEFAULT_STEP): probatio.All(
probatio.Coerce(float), probatio.Range(min=1e-3)
),
probatio.Optional(CONF_UNIT_OF_MEASUREMENT): probatio.Any(cv.string, None),
probatio.Optional(CONF_VALUE_TEMPLATE): cv.template,
},
).extend(MQTT_ENTITY_COMMON_SCHEMA.schema)
PLATFORM_SCHEMA_MODERN = probatio.All(
_PLATFORM_SCHEMA_BASE,
validate_config,
)
DISCOVERY_SCHEMA = probatio.All(
_PLATFORM_SCHEMA_BASE.extend({}, extra=probatio.REMOVE_EXTRA),
validate_config,
)
async def async_setup_entry(
hass: HomeAssistant,
config_entry: ConfigEntry,
async_add_entities: AddConfigEntryEntitiesCallback,
) -> None:
"""Set up MQTT number through YAML and through MQTT discovery."""
async_setup_entity_entry_helper(
hass,
config_entry,
MqttNumber,
number.DOMAIN,
async_add_entities,
DISCOVERY_SCHEMA,
PLATFORM_SCHEMA_MODERN,
)
class MqttNumber(MqttEntity, RestoreNumber):
"""representation of an MQTT number."""
_default_name = DEFAULT_NAME
_entity_id_format = number.ENTITY_ID_FORMAT
_attributes_extra_blocked = MQTT_NUMBER_ATTRIBUTES_BLOCKED
_optimistic: bool
_command_template: Callable[[PublishPayloadType], PublishPayloadType]
_value_template: Callable[[ReceivePayloadType], ReceivePayloadType]
@staticmethod
@override
def config_schema() -> VolSchemaType:
"""Return the config schema."""
return DISCOVERY_SCHEMA
@override
def _setup_from_config(self, config: ConfigType) -> None:
"""(Re)Setup the entity."""
self._config = config
self._attr_assumed_state = config[CONF_OPTIMISTIC]
self._command_template = MqttCommandTemplate(
config.get(CONF_COMMAND_TEMPLATE), entity=self
).async_render
self._value_template = MqttValueTemplate(
config.get(CONF_VALUE_TEMPLATE),
entity=self,
).async_render_with_possible_json_value
self._attr_device_class = config.get(CONF_DEVICE_CLASS)
self._attr_mode = config[CONF_MODE]
self._attr_native_max_value = config[CONF_MAX]
self._attr_native_min_value = config[CONF_MIN]
self._attr_native_step = config[CONF_STEP]
self._attr_native_unit_of_measurement = config.get(CONF_UNIT_OF_MEASUREMENT)
@callback
def _message_received(self, msg: ReceiveMessage) -> None:
"""Handle new MQTT messages."""
num_value: int | float | None
payload = str(self._value_template(msg.payload))
if not payload.strip():
_LOGGER.debug("Ignoring empty state update from '%s'", msg.topic)
return
try:
if payload == self._config[CONF_PAYLOAD_RESET]:
num_value = None
elif payload.isnumeric():
num_value = int(payload)
else:
num_value = float(payload)
except ValueError:
_LOGGER.warning("Payload '%s' is not a Number", msg.payload)
return
if num_value is not None and (
num_value < self.native_min_value or num_value > self.native_max_value
):
_LOGGER.error(
"Invalid value for %s: %s (range %s - %s)",
self.entity_id,
num_value,
self.native_min_value,
self.native_max_value,
)
return
self._attr_native_value = num_value
@callback
@override
def _prepare_subscribe_topics(self) -> None:
"""(Re)Subscribe to topics."""
if not self.add_subscription(
CONF_STATE_TOPIC, self._message_received, {"_attr_native_value"}
):
# Force into optimistic mode.
self._attr_assumed_state = True
return
@override
async def _subscribe_topics(self) -> None:
"""(Re)Subscribe to topics."""
subscription.async_subscribe_topics_internal(self.hass, self._sub_state)
if self._attr_assumed_state and (
last_number_data := await self.async_get_last_number_data()
):
self._attr_native_value = last_number_data.native_value
@override
async def async_set_native_value(self, value: float) -> None:
"""Update the current value."""
current_number = value
if value.is_integer():
current_number = int(value)
payload = self._command_template(current_number)
if self._attr_assumed_state:
self._attr_native_value = current_number
self.async_write_ha_state()
await self.async_publish_with_config(self._config[CONF_COMMAND_TOPIC], payload)
+133
View File
@@ -0,0 +1,133 @@
rules:
# Bronze
action-setup: done
appropriate-polling: done
brands: done
common-modules: done
config-flow-test-coverage: done
config-flow: done
dependency-transparency: done
docs-actions: done
docs-conditions:
status: exempt
comment: This integration does not have any conditions.
docs-high-level-description: done
docs-installation-instructions: done
docs-removal-instructions: done
docs-triggers: done
entity-event-setup:
status: done
comment: >
Entities are updated through dispatchers, and these are
cleaned up when the integration unloads.
entity-unique-id:
status: exempt
comment: >
This is user configurable, but not required.
It is required though when a user wants to use device based discovery.
has-entity-name: done
runtime-data:
status: exempt
comment: >
Runtime data is not used, as the mqtt entry data is only used to set up the
MQTT broker, this happens during integration setup,
and only one config entry is allowed.
test-before-configure: done
test-before-setup:
status: exempt
comment: >
We choose to early exit the entry as it can take some time for the client
to connect. Waiting for the client would increase the overall setup time.
unique-config-entry: done
# Silver
config-entry-unloading: done
log-when-unavailable: done
entity-unavailable:
status: done
comment: |
Only supported for entities the user has assigned a unique_id.
action-exceptions: done
reauthentication-flow: done
parallel-updates: done
test-coverage: done
integration-owner: done
docs-installation-parameters: done
docs-configuration-parameters: done
# Gold
entity-translations:
status: exempt
comment: >
This is not possible because the integrations generates entities
based on a user supplied config or discovery.
entity-device-class:
status: done
comment: An entity device class can be configured by the user for each entity.
devices:
status: done
comment: >
A device context can be configured by the user for each entity.
It is not required though, except when using device based discovery.
entity-category:
status: done
comment: An entity category can be configured by the user for each entity.
entity-disabled-by-default:
status: done
comment: >
The user can configure this through YAML or discover
entities that are disabled by default.
discovery:
status: done
comment: >
When the Mosquitto MQTT broker add on is installed,
a MQTT config flow allows an automatic setup from its discovered settings.
stale-devices:
status: exempt
comment: >
This is is only supported for entities that are configured through MQTT discovery.
Users must manually cleanup stale entities that were set up though YAML.
diagnostics: done
exception-translations: done
icon-translations:
status: exempt
comment: >
This is not possible because the integrations generates entities
based on a user supplied config or discovery.
reconfiguration-flow: done
dynamic-devices:
status: done
comment: |
MQTT allow to dynamically create and remove devices through MQTT discovery.
discovery-update-info:
status: done
comment: >
If the Mosquitto broker add-on is used to set up MQTT from discovery,
and the broker add-on is re-installed,
MQTT will automatically update from the new brokers credentials.
repair-issues:
status: done
comment: >
This integration uses repair-issues when entities are set up through YAML.
To avoid user panic, discovery deprecation issues are logged only.
It is the responsibility of the maintainer or the service or device to
correct the discovery messages. Extra options are allowed
in MQTT messages to avoid breaking issues.
docs-use-cases: done
docs-supported-devices: done
docs-supported-functions: done
docs-data-update: done
docs-known-limitations: done
docs-troubleshooting: done
docs-examples: done
# Platinum
async-dependency: done
inject-websession:
status: exempt
comment: |
This integration does not use web sessions.
strict-typing:
status: done
comment: >
Typing for 'paho-mqtt==1.6.1' supported via 'types-paho-mqtt==1.6.0.20240321'
(requirements_test.txt).
+71
View File
@@ -0,0 +1,71 @@
"""Repairs for MQTT."""
from typing import TYPE_CHECKING
import probatio
from homeassistant.components.repairs import RepairsFlow, RepairsFlowResult
from homeassistant.core import HomeAssistant
from homeassistant.helpers import device_registry as dr
from .const import DOMAIN
URL_MQTT_BROKER_CONFIGURATION = (
"https://www.home-assistant.io/integrations/mqtt/#broker-configuration"
)
class MQTTDeviceEntryMigration(RepairsFlow):
"""Handler to remove subentry for migrated MQTT device."""
def __init__(self, entry_id: str, subentry_id: str, name: str) -> None:
"""Initialize the flow."""
self.entry_id = entry_id
self.subentry_id = subentry_id
self.name = name
async def async_step_init(
self, user_input: dict[str, str] | None = None
) -> RepairsFlowResult:
"""Handle the first step of a fix flow."""
return await self.async_step_confirm()
async def async_step_confirm(
self, user_input: dict[str, str] | None = None
) -> RepairsFlowResult:
"""Handle the confirm step of a fix flow."""
if user_input is not None:
device_registry = dr.async_get(self.hass)
subentry_device = device_registry.async_get_device_by_identifier(
(DOMAIN, self.subentry_id), self.entry_id
)
entry = self.hass.config_entries.async_get_entry(self.entry_id)
if TYPE_CHECKING:
assert entry is not None
assert subentry_device is not None
self.hass.config_entries.async_remove_subentry(entry, self.subentry_id)
return self.async_create_entry(data={})
return self.async_show_form(
step_id="confirm",
data_schema=probatio.Schema({}),
description_placeholders={"name": self.name},
)
async def async_create_fix_flow(
hass: HomeAssistant,
issue_id: str,
data: dict[str, str | int | float | None] | None,
) -> RepairsFlow:
"""Create flow."""
if TYPE_CHECKING:
assert data is not None
entry_id: str = data["entry_id"] # type: ignore[assignment]
subentry_id: str = data["subentry_id"] # type: ignore[assignment]
name: str = data["name"] # type: ignore[assignment]
return MQTTDeviceEntryMigration(
entry_id=entry_id,
subentry_id=subentry_id,
name=name,
)
+94
View File
@@ -0,0 +1,94 @@
"""Support for MQTT scenes."""
from typing import Any, override
import probatio
from homeassistant.components import scene
from homeassistant.components.scene import Scene
from homeassistant.config_entries import ConfigEntry
from homeassistant.const import CONF_NAME, CONF_PAYLOAD_ON
from homeassistant.core import HomeAssistant, callback
from homeassistant.helpers import config_validation as cv
from homeassistant.helpers.entity_platform import AddConfigEntryEntitiesCallback
from homeassistant.helpers.typing import ConfigType
from .config import MQTT_BASE_SCHEMA
from .const import CONF_COMMAND_TOPIC, CONF_RETAIN
from .entity import MqttEntity, async_setup_entity_entry_helper
from .schemas import MQTT_ENTITY_COMMON_SCHEMA
from .util import valid_publish_topic
PARALLEL_UPDATES = 0
DEFAULT_NAME = "MQTT Scene"
DEFAULT_RETAIN = False
ENTITY_ID_FORMAT = scene.DOMAIN + ".{}"
PLATFORM_SCHEMA_MODERN = MQTT_BASE_SCHEMA.extend(
{
probatio.Required(CONF_COMMAND_TOPIC): valid_publish_topic,
probatio.Optional(CONF_NAME): probatio.Any(cv.string, None),
probatio.Optional(CONF_PAYLOAD_ON): cv.string,
probatio.Optional(CONF_RETAIN, default=DEFAULT_RETAIN): cv.boolean,
}
).extend(MQTT_ENTITY_COMMON_SCHEMA.schema)
DISCOVERY_SCHEMA = PLATFORM_SCHEMA_MODERN.extend({}, extra=probatio.REMOVE_EXTRA)
async def async_setup_entry(
hass: HomeAssistant,
config_entry: ConfigEntry,
async_add_entities: AddConfigEntryEntitiesCallback,
) -> None:
"""Set up MQTT scene through YAML and through MQTT discovery."""
async_setup_entity_entry_helper(
hass,
config_entry,
MqttScene,
scene.DOMAIN,
async_add_entities,
DISCOVERY_SCHEMA,
PLATFORM_SCHEMA_MODERN,
)
class MqttScene(
MqttEntity,
Scene,
):
"""Representation of a scene that can be activated using MQTT."""
_default_name = DEFAULT_NAME
_entity_id_format = scene.DOMAIN + ".{}"
@staticmethod
@override
def config_schema() -> probatio.Schema:
"""Return the config schema."""
return DISCOVERY_SCHEMA
@override
def _setup_from_config(self, config: ConfigType) -> None:
"""(Re)Setup the entity."""
@callback
@override
def _prepare_subscribe_topics(self) -> None:
"""(Re)Subscribe to topics."""
@override
async def _subscribe_topics(self) -> None:
"""(Re)Subscribe to topics."""
@override
async def async_activate(self, **kwargs: Any) -> None:
"""Activate the scene.
This method is a coroutine.
"""
await self.async_publish_with_config(
self._config[CONF_COMMAND_TOPIC], self._config[CONF_PAYLOAD_ON]
)
+227
View File
@@ -0,0 +1,227 @@
"""Shared schemas for MQTT discovery and YAML config items."""
from typing import Any
import probatio
from homeassistant.const import (
CONF_DEVICE,
CONF_ENTITY_CATEGORY,
CONF_ICON,
CONF_MODEL,
CONF_MODEL_ID,
CONF_NAME,
CONF_PLATFORM,
CONF_UNIQUE_ID,
CONF_VALUE_TEMPLATE,
)
from homeassistant.helpers import config_validation as cv
from homeassistant.helpers.entity import ENTITY_CATEGORIES_SCHEMA
from homeassistant.helpers.typing import ConfigType
from .const import (
AVAILABILITY_LATEST,
AVAILABILITY_MODES,
CONF_AVAILABILITY,
CONF_AVAILABILITY_MODE,
CONF_AVAILABILITY_TEMPLATE,
CONF_AVAILABILITY_TOPIC,
CONF_COMMAND_TOPIC,
CONF_COMPONENTS,
CONF_CONFIGURATION_URL,
CONF_CONNECTIONS,
CONF_DEFAULT_ENTITY_ID,
CONF_DEPRECATED_VIA_HUB,
CONF_ENABLED_BY_DEFAULT,
CONF_ENCODING,
CONF_ENTITY_PICTURE,
CONF_HW_VERSION,
CONF_IDENTIFIERS,
CONF_JSON_ATTRS_TEMPLATE,
CONF_JSON_ATTRS_TOPIC,
CONF_MANUFACTURER,
CONF_MESSAGE_EXPIRY_INTERVAL,
CONF_ORIGIN,
CONF_PAYLOAD_AVAILABLE,
CONF_PAYLOAD_NOT_AVAILABLE,
CONF_QOS,
CONF_SERIAL_NUMBER,
CONF_STATE_TOPIC,
CONF_SUGGESTED_AREA,
CONF_SUPPORT_URL,
CONF_SW_VERSION,
CONF_TOPIC,
CONF_VIA_DEVICE,
CONF_VISIBLE_BY_DEFAULT,
DEFAULT_PAYLOAD_AVAILABLE,
DEFAULT_PAYLOAD_NOT_AVAILABLE,
ENTITY_PLATFORMS,
SUPPORTED_COMPONENTS,
)
from .util import valid_publish_topic, valid_qos_schema, valid_subscribe_topic
# Device discovery options that are also available at entity component level
SHARED_OPTIONS = [
CONF_AVAILABILITY,
CONF_AVAILABILITY_MODE,
CONF_AVAILABILITY_TEMPLATE,
CONF_AVAILABILITY_TOPIC,
CONF_COMMAND_TOPIC,
CONF_ENCODING,
CONF_MESSAGE_EXPIRY_INTERVAL,
CONF_PAYLOAD_AVAILABLE,
CONF_PAYLOAD_NOT_AVAILABLE,
CONF_STATE_TOPIC,
CONF_QOS,
]
_MQTT_AVAILABILITY_SINGLE_SCHEMA = probatio.Schema(
{
probatio.Exclusive(
CONF_AVAILABILITY_TOPIC, "availability"
): valid_subscribe_topic,
probatio.Optional(CONF_AVAILABILITY_TEMPLATE): cv.template,
probatio.Optional(
CONF_PAYLOAD_AVAILABLE, default=DEFAULT_PAYLOAD_AVAILABLE
): cv.string,
probatio.Optional(
CONF_PAYLOAD_NOT_AVAILABLE, default=DEFAULT_PAYLOAD_NOT_AVAILABLE
): cv.string,
}
)
_MQTT_AVAILABILITY_LIST_SCHEMA = probatio.Schema(
{
probatio.Optional(
CONF_AVAILABILITY_MODE, default=AVAILABILITY_LATEST
): probatio.All(cv.string, probatio.In(AVAILABILITY_MODES)),
probatio.Exclusive(CONF_AVAILABILITY, "availability"): probatio.All(
probatio.EnsureList(),
[
{
probatio.Required(CONF_TOPIC): valid_subscribe_topic,
probatio.Optional(
CONF_PAYLOAD_AVAILABLE, default=DEFAULT_PAYLOAD_AVAILABLE
): cv.string,
probatio.Optional(
CONF_PAYLOAD_NOT_AVAILABLE,
default=DEFAULT_PAYLOAD_NOT_AVAILABLE,
): cv.string,
probatio.Optional(CONF_VALUE_TEMPLATE): cv.template,
}
],
),
}
)
_MQTT_AVAILABILITY_SCHEMA = _MQTT_AVAILABILITY_SINGLE_SCHEMA.extend(
_MQTT_AVAILABILITY_LIST_SCHEMA.schema
)
def validate_device_has_at_least_one_identifier(value: ConfigType) -> ConfigType:
"""Validate that a device info entry has at least one identifying value."""
if value.get(CONF_IDENTIFIERS) or value.get(CONF_CONNECTIONS):
return value
raise probatio.Invalid(
"Device must have at least one identifying value in "
"'identifiers' and/or 'connections'"
)
MQTT_ENTITY_DEVICE_INFO_SCHEMA = probatio.All(
cv.deprecated(CONF_DEPRECATED_VIA_HUB, CONF_VIA_DEVICE),
probatio.Schema(
{
probatio.Optional(CONF_IDENTIFIERS, default=list): probatio.All(
probatio.EnsureList(), [cv.string]
),
probatio.Optional(CONF_CONNECTIONS, default=list): probatio.All(
probatio.EnsureList(), [probatio.All(probatio.Length(2), [cv.string])]
),
probatio.Optional(CONF_MANUFACTURER): cv.string,
probatio.Optional(CONF_MODEL): cv.string,
probatio.Optional(CONF_MODEL_ID): cv.string,
probatio.Optional(CONF_NAME): cv.string,
probatio.Optional(CONF_HW_VERSION): cv.string,
probatio.Optional(CONF_SERIAL_NUMBER): cv.string,
probatio.Optional(CONF_SW_VERSION): cv.string,
probatio.Optional(CONF_VIA_DEVICE): cv.string,
probatio.Optional(CONF_SUGGESTED_AREA): cv.string,
probatio.Optional(CONF_CONFIGURATION_URL): cv.configuration_url,
}
),
validate_device_has_at_least_one_identifier,
)
MQTT_ORIGIN_INFO_SCHEMA = probatio.All(
probatio.Schema(
{
probatio.Required(CONF_NAME): cv.string,
probatio.Optional(CONF_SW_VERSION): cv.string,
probatio.Optional(CONF_SUPPORT_URL): cv.configuration_url,
}
),
)
def valid_message_expiry_interval(value: Any) -> int:
"""Return Message Expiry Interval in seconds."""
if isinstance(value, int):
return cv.positive_int(value)
return int(cv.positive_time_period_dict(value).total_seconds())
MQTT_ENTITY_COMMON_SCHEMA = _MQTT_AVAILABILITY_SCHEMA.extend(
{
probatio.Optional(CONF_DEVICE): MQTT_ENTITY_DEVICE_INFO_SCHEMA,
probatio.Optional(CONF_ENTITY_PICTURE): cv.url,
probatio.Optional(CONF_ORIGIN): MQTT_ORIGIN_INFO_SCHEMA,
probatio.Optional(CONF_ENABLED_BY_DEFAULT, default=True): cv.boolean,
probatio.Optional(CONF_ENTITY_CATEGORY): ENTITY_CATEGORIES_SCHEMA,
probatio.Optional(CONF_ICON): cv.icon,
probatio.Optional(CONF_JSON_ATTRS_TOPIC): valid_subscribe_topic,
probatio.Optional(CONF_JSON_ATTRS_TEMPLATE): cv.template,
probatio.Optional(CONF_DEFAULT_ENTITY_ID): cv.string,
probatio.Optional(CONF_MESSAGE_EXPIRY_INTERVAL): valid_message_expiry_interval,
probatio.Optional(CONF_UNIQUE_ID): cv.string,
probatio.Optional(CONF_VISIBLE_BY_DEFAULT, default=True): cv.boolean,
}
)
_UNIQUE_ID_SCHEMA = probatio.Schema(
{probatio.Required(CONF_UNIQUE_ID): cv.string},
).extend({}, extra=True)
def check_unique_id(config: dict[str, Any]) -> dict[str, Any]:
"""Check if a unique ID is set in case an entity platform is configured."""
platform = config[CONF_PLATFORM]
if platform in ENTITY_PLATFORMS and len(config.keys()) > 1:
_UNIQUE_ID_SCHEMA(config)
return config
_COMPONENT_CONFIG_SCHEMA = probatio.All(
probatio.Schema(
{probatio.Required(CONF_PLATFORM): probatio.In(SUPPORTED_COMPONENTS)},
).extend({}, extra=True),
check_unique_id,
)
DEVICE_DISCOVERY_SCHEMA = _MQTT_AVAILABILITY_SCHEMA.extend(
{
probatio.Required(CONF_DEVICE): MQTT_ENTITY_DEVICE_INFO_SCHEMA,
probatio.Required(CONF_COMPONENTS): probatio.Schema(
{str: _COMPONENT_CONFIG_SCHEMA}
),
probatio.Required(CONF_ORIGIN): MQTT_ORIGIN_INFO_SCHEMA,
probatio.Optional(CONF_STATE_TOPIC): valid_subscribe_topic,
probatio.Optional(CONF_COMMAND_TOPIC): valid_publish_topic,
probatio.Optional(CONF_MESSAGE_EXPIRY_INTERVAL): valid_message_expiry_interval,
probatio.Optional(CONF_QOS): valid_qos_schema,
probatio.Optional(CONF_ENCODING): cv.string,
}
)
+168
View File
@@ -0,0 +1,168 @@
"""Configure select in a device through MQTT topic."""
from collections.abc import Callable
import logging
from typing import override
import probatio
from homeassistant.components import select
from homeassistant.components.select import (
SelectEntity,
SelectEntityCapabilityAttribute,
)
from homeassistant.config_entries import ConfigEntry
from homeassistant.const import (
CONF_NAME,
CONF_OPTIMISTIC,
CONF_OPTIONS,
CONF_VALUE_TEMPLATE,
)
from homeassistant.core import HomeAssistant, callback
from homeassistant.helpers import config_validation as cv
from homeassistant.helpers.entity_platform import AddConfigEntryEntitiesCallback
from homeassistant.helpers.restore_state import RestoreEntity
from homeassistant.helpers.service_info.mqtt import ReceivePayloadType
from homeassistant.helpers.typing import ConfigType, VolSchemaType
from . import subscription
from .config import MQTT_RW_SCHEMA
from .const import CONF_COMMAND_TEMPLATE, CONF_COMMAND_TOPIC, CONF_STATE_TOPIC
from .entity import MqttEntity, async_setup_entity_entry_helper
from .models import (
MqttCommandTemplate,
MqttValueTemplate,
PublishPayloadType,
ReceiveMessage,
)
from .schemas import MQTT_ENTITY_COMMON_SCHEMA
_LOGGER = logging.getLogger(__name__)
PARALLEL_UPDATES = 0
DEFAULT_NAME = "MQTT Select"
MQTT_SELECT_ATTRIBUTES_BLOCKED = frozenset(
{
SelectEntityCapabilityAttribute.OPTIONS,
}
)
PLATFORM_SCHEMA_MODERN = MQTT_RW_SCHEMA.extend(
{
probatio.Optional(CONF_COMMAND_TEMPLATE): cv.template,
probatio.Optional(CONF_NAME): probatio.Any(cv.string, None),
probatio.Required(CONF_OPTIONS): probatio.EnsureList(),
probatio.Optional(CONF_VALUE_TEMPLATE): cv.template,
},
).extend(MQTT_ENTITY_COMMON_SCHEMA.schema)
DISCOVERY_SCHEMA = probatio.All(
PLATFORM_SCHEMA_MODERN.extend({}, extra=probatio.REMOVE_EXTRA)
)
async def async_setup_entry(
hass: HomeAssistant,
config_entry: ConfigEntry,
async_add_entities: AddConfigEntryEntitiesCallback,
) -> None:
"""Set up MQTT select through YAML and through MQTT discovery."""
async_setup_entity_entry_helper(
hass,
config_entry,
MqttSelect,
select.DOMAIN,
async_add_entities,
DISCOVERY_SCHEMA,
PLATFORM_SCHEMA_MODERN,
)
class MqttSelect(MqttEntity, SelectEntity, RestoreEntity):
"""representation of an MQTT select."""
_attr_current_option: str | None = None
_default_name = DEFAULT_NAME
_entity_id_format = select.ENTITY_ID_FORMAT
_attributes_extra_blocked = MQTT_SELECT_ATTRIBUTES_BLOCKED
_command_template: Callable[[PublishPayloadType], PublishPayloadType]
_value_template: Callable[[ReceivePayloadType], ReceivePayloadType]
_optimistic: bool = False
@staticmethod
@override
def config_schema() -> VolSchemaType:
"""Return the config schema."""
return DISCOVERY_SCHEMA
@override
def _setup_from_config(self, config: ConfigType) -> None:
"""(Re)Setup the entity."""
self._attr_assumed_state = config[CONF_OPTIMISTIC]
self._attr_options = config[CONF_OPTIONS]
self._command_template = MqttCommandTemplate(
config.get(CONF_COMMAND_TEMPLATE),
entity=self,
).async_render
self._value_template = MqttValueTemplate(
config.get(CONF_VALUE_TEMPLATE), entity=self
).async_render_with_possible_json_value
@callback
def _message_received(self, msg: ReceiveMessage) -> None:
"""Handle new MQTT messages."""
payload = str(self._value_template(msg.payload))
if not payload.strip(): # No output from template, ignore
_LOGGER.debug(
"Ignoring empty payload '%s' after rendering for topic %s",
payload,
msg.topic,
)
return
if payload.lower() == "none":
self._attr_current_option = None
return
if payload not in self.options:
_LOGGER.error(
"Invalid option for %s: '%s' (valid options: %s)",
self.entity_id,
payload,
self.options,
)
return
self._attr_current_option = payload
@callback
@override
def _prepare_subscribe_topics(self) -> None:
"""(Re)Subscribe to topics."""
if not self.add_subscription(
CONF_STATE_TOPIC, self._message_received, {"_attr_current_option"}
):
# Force into optimistic mode.
self._attr_assumed_state = True
return
@override
async def _subscribe_topics(self) -> None:
"""(Re)Subscribe to topics."""
subscription.async_subscribe_topics_internal(self.hass, self._sub_state)
if self._attr_assumed_state and (
last_state := await self.async_get_last_state()
):
self._attr_current_option = last_state.state
@override
async def async_select_option(self, option: str) -> None:
"""Update the current value."""
payload = self._command_template(option)
if self._attr_assumed_state:
self._attr_current_option = option
self.async_write_ha_state()
await self.async_publish_with_config(self._config[CONF_COMMAND_TOPIC], payload)
+408
View File
@@ -0,0 +1,408 @@
"""Support for MQTT sensors."""
from collections.abc import Callable
from datetime import datetime, timedelta
import logging
from typing import override
import probatio
from homeassistant.components import sensor
from homeassistant.components.sensor import (
AMBIGUOUS_UNITS,
CONF_STATE_CLASS,
DEVICE_CLASS_UNITS,
DEVICE_CLASSES_SCHEMA,
ENTITY_ID_FORMAT,
STATE_CLASS_UNITS,
STATE_CLASSES_SCHEMA,
RestoreSensor,
SensorDeviceClass,
SensorEntityCapabilityAttribute,
SensorEntityStateAttribute,
SensorExtraStoredData,
SensorStateClass,
)
from homeassistant.config_entries import ConfigEntry
from homeassistant.const import (
CONF_DEVICE_CLASS,
CONF_FORCE_UPDATE,
CONF_NAME,
CONF_OPTIONS,
CONF_UNIT_OF_MEASUREMENT,
CONF_VALUE_TEMPLATE,
STATE_UNAVAILABLE,
STATE_UNKNOWN,
)
from homeassistant.core import CALLBACK_TYPE, HomeAssistant, State, callback
from homeassistant.helpers import config_validation as cv
from homeassistant.helpers.entity_platform import AddConfigEntryEntitiesCallback
from homeassistant.helpers.event import async_call_later
from homeassistant.helpers.service_info.mqtt import ReceivePayloadType
from homeassistant.helpers.typing import ConfigType, VolSchemaType
from homeassistant.util import dt as dt_util
from . import subscription
from .config import MQTT_RO_SCHEMA
from .const import (
CONF_EXPIRE_AFTER,
CONF_LAST_RESET_VALUE_TEMPLATE,
CONF_STATE_TOPIC,
CONF_SUGGESTED_DISPLAY_PRECISION,
PAYLOAD_NONE,
)
from .entity import MqttAvailabilityMixin, MqttEntity, async_setup_entity_entry_helper
from .models import MqttValueTemplate, PayloadSentinel, ReceiveMessage
from .schemas import MQTT_ENTITY_COMMON_SCHEMA
from .util import check_state_too_long
_LOGGER = logging.getLogger(__name__)
PARALLEL_UPDATES = 0
MQTT_SENSOR_ATTRIBUTES_BLOCKED = frozenset(
{
SensorEntityStateAttribute.LAST_RESET,
SensorEntityCapabilityAttribute.STATE_CLASS,
}
)
DEFAULT_NAME = "MQTT Sensor"
DEFAULT_FORCE_UPDATE = False
URL_DOCS_SUPPORTED_SENSOR_UOM = (
"https://www.home-assistant.io/integrations/sensor/#device-class"
)
_PLATFORM_SCHEMA_BASE = MQTT_RO_SCHEMA.extend(
{
probatio.Optional(CONF_DEVICE_CLASS): probatio.Any(DEVICE_CLASSES_SCHEMA, None),
probatio.Optional(CONF_EXPIRE_AFTER): cv.positive_int,
probatio.Optional(CONF_FORCE_UPDATE, default=DEFAULT_FORCE_UPDATE): cv.boolean,
probatio.Optional(CONF_LAST_RESET_VALUE_TEMPLATE): cv.template,
probatio.Optional(CONF_NAME): probatio.Any(cv.string, None),
probatio.Optional(CONF_OPTIONS): probatio.EnsureList(),
probatio.Optional(CONF_SUGGESTED_DISPLAY_PRECISION): cv.positive_int,
probatio.Optional(CONF_STATE_CLASS): probatio.Any(STATE_CLASSES_SCHEMA, None),
probatio.Optional(CONF_UNIT_OF_MEASUREMENT): probatio.Any(cv.string, None),
}
).extend(MQTT_ENTITY_COMMON_SCHEMA.schema)
def validate_sensor_state_and_device_class_config(config: ConfigType) -> ConfigType:
"""Validate the sensor options, state and device class config."""
if (
CONF_LAST_RESET_VALUE_TEMPLATE in config
and (state_class := config.get(CONF_STATE_CLASS)) != SensorStateClass.TOTAL
):
raise probatio.Invalid(
f"The option `{CONF_LAST_RESET_VALUE_TEMPLATE}` cannot be used "
f"together with state class `{state_class}`"
)
unit_of_measurement: str | None
if (
unit_of_measurement := config.get(CONF_UNIT_OF_MEASUREMENT)
) is not None and not unit_of_measurement.strip():
config.pop(CONF_UNIT_OF_MEASUREMENT)
# Only allow `options` to be set for `enum` sensors
# to limit the possible sensor values
if (options := config.get(CONF_OPTIONS)) is not None:
if not options:
raise probatio.Invalid("An empty options list is not allowed")
if config.get(CONF_STATE_CLASS) or config.get(CONF_UNIT_OF_MEASUREMENT):
raise probatio.Invalid(
f"Specifying `{CONF_OPTIONS}` is not allowed together with "
f"the `{CONF_STATE_CLASS}` or `{CONF_UNIT_OF_MEASUREMENT}` option"
)
if (device_class := config.get(CONF_DEVICE_CLASS)) != SensorDeviceClass.ENUM:
raise probatio.Invalid(
f"The option `{CONF_OPTIONS}` must be used "
f"together with device class `{SensorDeviceClass.ENUM}`, "
f"got `{CONF_DEVICE_CLASS}` '{device_class}'"
)
if (
(state_class := config.get(CONF_STATE_CLASS)) is not None
and state_class in STATE_CLASS_UNITS
and (unit_of_measurement := config.get(CONF_UNIT_OF_MEASUREMENT))
not in STATE_CLASS_UNITS[state_class]
):
raise probatio.Invalid(
f"The unit of measurement '{unit_of_measurement}' is not valid "
f"together with state class '{state_class}'"
)
if (unit_of_measurement := config.get(CONF_UNIT_OF_MEASUREMENT)) is None:
return config
unit_of_measurement = config[CONF_UNIT_OF_MEASUREMENT] = AMBIGUOUS_UNITS.get(
unit_of_measurement, unit_of_measurement
)
if (device_class := config.get(CONF_DEVICE_CLASS)) is None:
return config
if (
device_class in DEVICE_CLASS_UNITS
and unit_of_measurement not in DEVICE_CLASS_UNITS[device_class]
):
raise probatio.Invalid(
f"The unit of measurement `{unit_of_measurement}` is not valid "
f"together with device class `{device_class}`",
)
return config
PLATFORM_SCHEMA_MODERN = probatio.All(
_PLATFORM_SCHEMA_BASE,
validate_sensor_state_and_device_class_config,
)
DISCOVERY_SCHEMA = probatio.All(
_PLATFORM_SCHEMA_BASE.extend({}, extra=probatio.REMOVE_EXTRA),
validate_sensor_state_and_device_class_config,
)
async def async_setup_entry(
hass: HomeAssistant,
config_entry: ConfigEntry,
async_add_entities: AddConfigEntryEntitiesCallback,
) -> None:
"""Set up MQTT sensor through YAML and through MQTT discovery."""
async_setup_entity_entry_helper(
hass,
config_entry,
MqttSensor,
sensor.DOMAIN,
async_add_entities,
DISCOVERY_SCHEMA,
PLATFORM_SCHEMA_MODERN,
)
class MqttSensor(MqttEntity, RestoreSensor):
"""Representation of a sensor that can be updated using MQTT."""
_default_name = DEFAULT_NAME
_entity_id_format = ENTITY_ID_FORMAT
_attr_last_reset: datetime | None = None
_attributes_extra_blocked = MQTT_SENSOR_ATTRIBUTES_BLOCKED
_expiration_trigger: CALLBACK_TYPE | None = None
_expire_after: int | None
_expired: bool | None
_template: (
Callable[[ReceivePayloadType, PayloadSentinel], ReceivePayloadType] | None
) = None
_last_reset_template: Callable[[ReceivePayloadType], ReceivePayloadType] | None = (
None
)
@override
async def mqtt_async_added_to_hass(self) -> None:
"""Restore state for entities with expire_after set."""
last_state: State | None
last_sensor_data: SensorExtraStoredData | None
if (
(_expire_after := self._expire_after) is not None
and _expire_after > 0
and (last_state := await self.async_get_last_state()) is not None
and last_state.state not in [STATE_UNKNOWN, STATE_UNAVAILABLE]
and (last_sensor_data := await self.async_get_last_sensor_data())
is not None
# We might have set up a trigger already after subscribing from
# MqttEntity.async_added_to_hass(), then we should not restore state
and not self._expiration_trigger
):
expiration_at = last_state.last_changed + timedelta(seconds=_expire_after)
remain_seconds = (expiration_at - dt_util.utcnow()).total_seconds()
if remain_seconds <= 0:
# Skip reactivating the sensor
_LOGGER.debug("Skip state recovery after reload for %s", self.entity_id)
return
self._expired = False
self._attr_native_value = last_sensor_data.native_value
self._expiration_trigger = async_call_later(
self.hass, remain_seconds, self._value_is_expired
)
_LOGGER.debug(
(
"State recovered after reload for %s, remaining time before"
" expiring %s"
),
self.entity_id,
remain_seconds,
)
@override
async def async_will_remove_from_hass(self) -> None:
"""Remove expire triggers."""
if self._expiration_trigger:
_LOGGER.debug("Clean up expire after trigger for %s", self.entity_id)
self._expiration_trigger()
self._expiration_trigger = None
self._expired = False
await super().async_will_remove_from_hass()
@staticmethod
@override
def config_schema() -> VolSchemaType:
"""Return the config schema."""
return DISCOVERY_SCHEMA
@override
def _setup_from_config(self, config: ConfigType) -> None:
"""(Re)Setup the entity."""
self._attr_device_class = config.get(CONF_DEVICE_CLASS)
self._attr_force_update = config[CONF_FORCE_UPDATE]
self._attr_suggested_display_precision = config.get(
CONF_SUGGESTED_DISPLAY_PRECISION
)
self._attr_native_unit_of_measurement = config.get(CONF_UNIT_OF_MEASUREMENT)
self._attr_options = config.get(CONF_OPTIONS)
self._attr_state_class = config.get(CONF_STATE_CLASS)
self._expire_after = config.get(CONF_EXPIRE_AFTER)
if self._expire_after is not None and self._expire_after > 0:
self._expired = True
else:
self._expired = None
if value_template := config.get(CONF_VALUE_TEMPLATE):
self._template = MqttValueTemplate(
value_template, entity=self
).async_render_with_possible_json_value
if last_reset_template := config.get(CONF_LAST_RESET_VALUE_TEMPLATE):
self._last_reset_template = MqttValueTemplate(
last_reset_template, entity=self
).async_render_with_possible_json_value
@callback
def _update_state(self, msg: ReceiveMessage) -> None:
# auto-expire enabled?
if self._expire_after is not None and self._expire_after > 0:
# When self._expire_after is set, and we receive a message, assume
# device is not expired since it has to be to receive the message
self._expired = False
# Reset old trigger
if self._expiration_trigger:
self._expiration_trigger()
# Set new trigger
self._expiration_trigger = async_call_later(
self.hass, self._expire_after, self._value_is_expired
)
if template := self._template:
payload = template(msg.payload, PayloadSentinel.DEFAULT)
else:
payload = msg.payload
if payload is PayloadSentinel.DEFAULT:
return
if not isinstance(payload, str):
_LOGGER.warning(
"Invalid undecoded state message '%s' received from '%s'",
payload,
msg.topic,
)
return
if payload == PAYLOAD_NONE:
self._attr_native_value = None
return
if self._numeric_state_expected:
if payload == "":
_LOGGER.debug("Ignore empty state from '%s'", msg.topic)
else:
self._attr_native_value = payload
return
if self.options and payload not in self.options:
_LOGGER.warning(
"Ignoring invalid option received on topic '%s', got '%s', allowed: %s",
msg.topic,
payload,
", ".join(self.options),
)
return
if self.device_class in {
None,
SensorDeviceClass.ENUM,
} and not check_state_too_long(_LOGGER, payload, self.entity_id, msg):
self._attr_native_value = payload
return
try:
if (payload_datetime := dt_util.parse_datetime(payload)) is None:
raise ValueError # noqa: TRY301
except ValueError:
_LOGGER.warning("Invalid state message '%s' from '%s'", payload, msg.topic)
self._attr_native_value = None
return
if self.device_class == SensorDeviceClass.DATE:
self._attr_native_value = payload_datetime.date()
return
self._attr_native_value = payload_datetime
@callback
def _update_last_reset(self, msg: ReceiveMessage) -> None:
template = self._last_reset_template
payload = msg.payload if template is None else template(msg.payload)
if not payload:
_LOGGER.debug("Ignoring empty last_reset message from '%s'", msg.topic)
return
try:
last_reset = dt_util.parse_datetime(str(payload))
if last_reset is None:
raise ValueError # noqa: TRY301
self._attr_last_reset = last_reset
except ValueError:
_LOGGER.warning(
"Invalid last_reset message '%s' from '%s'", msg.payload, msg.topic
)
@callback
def _state_message_received(self, msg: ReceiveMessage) -> None:
"""Handle new MQTT state messages."""
self._update_state(msg)
if CONF_LAST_RESET_VALUE_TEMPLATE in self._config:
self._update_last_reset(msg)
@callback
@override
def _prepare_subscribe_topics(self) -> None:
"""(Re)Subscribe to topics."""
self.add_subscription(
CONF_STATE_TOPIC,
self._state_message_received,
{"_attr_native_value", "_attr_last_reset", "_expired"},
)
@override
async def _subscribe_topics(self) -> None:
"""(Re)Subscribe to topics."""
subscription.async_subscribe_topics_internal(self.hass, self._sub_state)
@callback
def _value_is_expired(self, *_: datetime) -> None:
"""Triggered when value is expired."""
self._expiration_trigger = None
self._expired = True
self.async_write_ha_state()
@property
@override
def available(self) -> bool:
"""Return true if the device is available and value has not expired."""
# mypy doesn't know about fget: https://github.com/python/mypy/issues/6185
return MqttAvailabilityMixin.available.fget(self) and ( # type: ignore[attr-defined]
self._expire_after is None or not self._expired
)
+51
View File
@@ -0,0 +1,51 @@
# Describes the format for available MQTT services
publish:
fields:
topic:
required: true
example: /homeassistant/hello
selector:
text:
payload:
example: "The temperature is {{ states('sensor.temperature') }}"
selector:
template:
publish_options:
collapsed: true
fields:
evaluate_payload:
default: false
selector:
boolean:
qos:
default: "0"
selector:
select:
options:
- "0"
- "1"
- "2"
retain:
default: false
selector:
boolean:
message_expiry_interval:
selector:
duration:
enable_day: true
dump:
fields:
topic:
example: "OpenZWave/#"
selector:
text:
duration:
default: 5
selector:
number:
min: 1
max: 300
unit_of_measurement: "seconds"
reload:
+357
View File
@@ -0,0 +1,357 @@
"""Support for MQTT sirens."""
from collections.abc import Callable
import logging
from typing import Any, cast, override
import probatio
from homeassistant.components import siren
from homeassistant.components.siren import (
ATTR_DURATION,
ATTR_TONE,
ATTR_VOLUME_LEVEL,
TURN_ON_SCHEMA,
SirenEntity,
SirenEntityCapabilityAttribute,
SirenEntityFeature,
SirenTurnOnServiceParameters,
process_turn_on_params,
)
from homeassistant.config_entries import ConfigEntry
from homeassistant.const import (
CONF_NAME,
CONF_OPTIMISTIC,
CONF_PAYLOAD_OFF,
CONF_PAYLOAD_ON,
)
from homeassistant.core import HomeAssistant, callback
from homeassistant.helpers import config_validation as cv
from homeassistant.helpers.entity_platform import AddConfigEntryEntitiesCallback
from homeassistant.helpers.json import json_dumps
from homeassistant.helpers.service_info.mqtt import ReceivePayloadType
from homeassistant.helpers.template import Template
from homeassistant.helpers.typing import ConfigType, TemplateVarsType, VolSchemaType
from homeassistant.util.json import JSON_DECODE_EXCEPTIONS, json_loads_object
from . import subscription
from .config import MQTT_RW_SCHEMA
from .const import (
CONF_AVAILABLE_TONES,
CONF_COMMAND_OFF_TEMPLATE,
CONF_COMMAND_TEMPLATE,
CONF_COMMAND_TOPIC,
CONF_STATE_OFF,
CONF_STATE_ON,
CONF_STATE_TOPIC,
CONF_STATE_VALUE_TEMPLATE,
CONF_SUPPORT_DURATION,
CONF_SUPPORT_VOLUME_SET,
DEFAULT_PAYLOAD_OFF,
DEFAULT_PAYLOAD_ON,
PAYLOAD_EMPTY_JSON,
PAYLOAD_NONE,
)
from .entity import MqttEntity, async_setup_entity_entry_helper
from .models import (
MqttCommandTemplate,
MqttValueTemplate,
PublishPayloadType,
ReceiveMessage,
)
from .schemas import MQTT_ENTITY_COMMON_SCHEMA
PARALLEL_UPDATES = 0
DEFAULT_NAME = "MQTT Siren"
ENTITY_ID_FORMAT = siren.DOMAIN + ".{}"
STATE = "state"
PLATFORM_SCHEMA_MODERN = MQTT_RW_SCHEMA.extend(
{
probatio.Optional(CONF_AVAILABLE_TONES): probatio.EnsureList(),
probatio.Optional(CONF_COMMAND_TEMPLATE): cv.template,
probatio.Optional(CONF_COMMAND_OFF_TEMPLATE): cv.template,
probatio.Optional(CONF_NAME): probatio.Any(cv.string, None),
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_STATE_OFF): cv.string,
probatio.Optional(CONF_STATE_ON): cv.string,
probatio.Optional(CONF_STATE_VALUE_TEMPLATE): cv.template,
probatio.Optional(CONF_SUPPORT_DURATION, default=True): cv.boolean,
probatio.Optional(CONF_SUPPORT_VOLUME_SET, default=True): cv.boolean,
},
).extend(MQTT_ENTITY_COMMON_SCHEMA.schema)
DISCOVERY_SCHEMA = probatio.All(
PLATFORM_SCHEMA_MODERN.extend({}, extra=probatio.REMOVE_EXTRA)
)
MQTT_SIREN_ATTRIBUTES_BLOCKED = frozenset(
{
ATTR_DURATION,
ATTR_TONE,
ATTR_VOLUME_LEVEL,
SirenEntityCapabilityAttribute.AVAILABLE_TONES,
}
)
SUPPORTED_BASE = SirenEntityFeature.TURN_OFF | SirenEntityFeature.TURN_ON
SUPPORTED_ATTRIBUTES = {
ATTR_DURATION: SirenEntityFeature.DURATION,
ATTR_TONE: SirenEntityFeature.TONES,
ATTR_VOLUME_LEVEL: SirenEntityFeature.VOLUME_SET,
}
_LOGGER = logging.getLogger(__name__)
async def async_setup_entry(
hass: HomeAssistant,
config_entry: ConfigEntry,
async_add_entities: AddConfigEntryEntitiesCallback,
) -> None:
"""Set up MQTT siren through YAML and through MQTT discovery."""
async_setup_entity_entry_helper(
hass,
config_entry,
MqttSiren,
siren.DOMAIN,
async_add_entities,
DISCOVERY_SCHEMA,
PLATFORM_SCHEMA_MODERN,
)
class MqttSiren(MqttEntity, SirenEntity):
"""Representation of a siren that can be controlled using MQTT."""
_default_name = DEFAULT_NAME
_entity_id_format = ENTITY_ID_FORMAT
_attributes_extra_blocked = MQTT_SIREN_ATTRIBUTES_BLOCKED
_extra_attributes: dict[str, Any]
_command_templates: dict[
str, Callable[[PublishPayloadType, TemplateVarsType], PublishPayloadType] | None
]
_value_template: Callable[[ReceivePayloadType], ReceivePayloadType]
_state_on: str
_state_off: str
_optimistic: bool
@staticmethod
@override
def config_schema() -> VolSchemaType:
"""Return the config schema."""
return DISCOVERY_SCHEMA
@override
def _setup_from_config(self, config: ConfigType) -> None:
"""(Re)Setup the entity."""
state_on: str | None = config.get(CONF_STATE_ON)
self._state_on = state_on or config[CONF_PAYLOAD_ON]
state_off: str | None = config.get(CONF_STATE_OFF)
self._state_off = state_off or config[CONF_PAYLOAD_OFF]
self._extra_attributes = {}
_supported_features = SUPPORTED_BASE
if config[CONF_SUPPORT_DURATION]:
_supported_features |= SirenEntityFeature.DURATION
self._extra_attributes[ATTR_DURATION] = None
if config.get(CONF_AVAILABLE_TONES):
_supported_features |= SirenEntityFeature.TONES
self._attr_available_tones = config[CONF_AVAILABLE_TONES]
self._extra_attributes[ATTR_TONE] = None
if config[CONF_SUPPORT_VOLUME_SET]:
_supported_features |= SirenEntityFeature.VOLUME_SET
self._extra_attributes[ATTR_VOLUME_LEVEL] = None
self._attr_supported_features = _supported_features
self._optimistic = config[CONF_OPTIMISTIC] or CONF_STATE_TOPIC not in config
self._attr_assumed_state = bool(self._optimistic)
self._attr_is_on = False if self._optimistic else None
command_template: Template | None = config.get(CONF_COMMAND_TEMPLATE)
command_off_template: Template | None = (
config.get(CONF_COMMAND_OFF_TEMPLATE) or command_template
)
self._command_templates = {
CONF_COMMAND_TEMPLATE: MqttCommandTemplate(
command_template, entity=self
).async_render
if command_template
else None,
CONF_COMMAND_OFF_TEMPLATE: MqttCommandTemplate(
command_off_template, entity=self
).async_render
if command_off_template
else None,
}
self._value_template = MqttValueTemplate(
config.get(CONF_STATE_VALUE_TEMPLATE),
entity=self,
).async_render_with_possible_json_value
@callback
def _state_message_received(self, msg: ReceiveMessage) -> None:
"""Handle new MQTT state messages."""
payload = self._value_template(msg.payload)
if not payload or payload == PAYLOAD_EMPTY_JSON:
_LOGGER.debug(
"Ignoring empty payload '%s' after rendering for topic %s",
payload,
msg.topic,
)
return
json_payload: dict[str, Any] = {}
if payload in [self._state_on, self._state_off, PAYLOAD_NONE]:
json_payload = {STATE: payload}
else:
try:
json_payload = json_loads_object(payload)
_LOGGER.debug(
"JSON payload detected after processing payload '%s' on topic %s",
json_payload,
msg.topic,
)
except JSON_DECODE_EXCEPTIONS:
_LOGGER.warning(
(
"No valid (JSON) payload detected after processing payload"
" '%s' on topic %s"
),
json_payload,
msg.topic,
)
return
if STATE in json_payload:
if json_payload[STATE] == self._state_on:
self._attr_is_on = True
if json_payload[STATE] == self._state_off:
self._attr_is_on = False
if json_payload[STATE] == PAYLOAD_NONE:
self._attr_is_on = None
del json_payload[STATE]
if json_payload:
# process attributes
try:
params: SirenTurnOnServiceParameters
params = probatio.All(TURN_ON_SCHEMA)(json_payload)
except probatio.MultipleInvalid as invalid_siren_parameters:
_LOGGER.warning(
"Unable to update siren state attributes from payload '%s': %s",
json_payload,
invalid_siren_parameters,
)
return
# To be able to track changes to self._extra_attributes we assign
# a fresh copy to make the original tracked reference immutable.
self._extra_attributes = dict(self._extra_attributes)
self._update(process_turn_on_params(self, params))
@callback
@override
def _prepare_subscribe_topics(self) -> None:
"""(Re)Subscribe to topics."""
if not self.add_subscription(
CONF_STATE_TOPIC,
self._state_message_received,
{"_attr_is_on", "_extra_attributes"},
):
# Force into optimistic mode.
self._optimistic = True
return
@override
async def _subscribe_topics(self) -> None:
"""(Re)Subscribe to topics."""
subscription.async_subscribe_topics_internal(self.hass, self._sub_state)
@property
@override
def extra_state_attributes(self) -> dict[str, Any] | None:
"""Return the state attributes."""
extra_attributes = (
self._attr_extra_state_attributes
if hasattr(self, "_attr_extra_state_attributes")
else {}
)
if extra_attributes:
return dict({*self._extra_attributes.items(), *extra_attributes.items()})
return self._extra_attributes or None
async def _async_publish(
self,
topic: str,
template: str,
value: Any,
variables: dict[str, Any] | None = None,
) -> None:
"""Publish MQTT payload with optional command template."""
template_variables: dict[str, Any] = {STATE: value}
if variables is not None:
template_variables.update(variables)
if command_template := self._command_templates[template]:
payload = command_template(value, template_variables)
else:
payload = json_dumps(template_variables)
if payload and str(payload) != PAYLOAD_NONE:
await self.async_publish_with_config(self._config[topic], payload)
@override
async def async_turn_on(self, **kwargs: Any) -> None:
"""Turn the siren on.
This method is a coroutine.
"""
await self._async_publish(
CONF_COMMAND_TOPIC,
CONF_COMMAND_TEMPLATE,
self._config[CONF_PAYLOAD_ON],
kwargs,
)
if self._optimistic:
# Optimistically assume that siren has changed state.
_LOGGER.debug("Writing state attributes %s", kwargs)
self._attr_is_on = True
self._update(cast(SirenTurnOnServiceParameters, kwargs))
self.async_write_ha_state()
@override
async def async_turn_off(self, **kwargs: Any) -> None:
"""Turn the siren off.
This method is a coroutine.
"""
await self._async_publish(
CONF_COMMAND_TOPIC,
CONF_COMMAND_OFF_TEMPLATE,
self._config[CONF_PAYLOAD_OFF],
)
if self._optimistic:
# Optimistically assume that siren has changed state.
self._attr_is_on = False
self.async_write_ha_state()
def _update(self, data: SirenTurnOnServiceParameters) -> None:
"""Update the extra siren state attributes."""
self._extra_attributes.update(
{
attribute: data_attr
for attribute, support in SUPPORTED_ATTRIBUTES.items()
if self._attr_supported_features & support
and attribute in data
and (data_attr := data[attribute]) # type: ignore[literal-required]
!= self._extra_attributes.get(attribute)
}
)
File diff suppressed because it is too large Load Diff
+167
View File
@@ -0,0 +1,167 @@
"""Helper to handle a set of topics to subscribe to."""
from collections.abc import Callable
from dataclasses import dataclass
from functools import partial
from typing import TYPE_CHECKING, Any
from homeassistant.core import HassJobType, HomeAssistant, callback
from . import debug_info
from .client import async_subscribe_internal
from .const import DEFAULT_QOS
from .models import MessageCallbackType
@dataclass(slots=True, kw_only=True)
class EntitySubscription:
"""Class to hold data about an active entity topic subscription."""
hass: HomeAssistant
topic: str | None
message_callback: MessageCallbackType
should_subscribe: bool | None
unsubscribe_callback: Callable[[], None] | None
qos: int = 0
encoding: str = "utf-8"
entity_id: str | None
job_type: HassJobType | None
def resubscribe_if_necessary(
self, hass: HomeAssistant, other: EntitySubscription | None
) -> None:
"""Re-subscribe to the new topic if necessary."""
if not self._should_resubscribe(other):
if TYPE_CHECKING:
assert other
self.unsubscribe_callback = other.unsubscribe_callback
return
if other is not None and other.unsubscribe_callback is not None:
other.unsubscribe_callback()
# Clear debug data if it exists
debug_info.remove_subscription(self.hass, str(other.topic), other.entity_id)
if self.topic is None:
# We were asked to remove the subscription or not to create it
return
# Prepare debug data
debug_info.add_subscription(self.hass, self.topic, self.entity_id)
self.should_subscribe = True
@callback
def subscribe(self) -> None:
"""Subscribe to a topic."""
if not self.should_subscribe or not self.topic:
return
self.unsubscribe_callback = async_subscribe_internal(
self.hass,
self.topic,
self.message_callback,
self.qos,
self.encoding,
self.job_type,
)
def _should_resubscribe(self, other: EntitySubscription | None) -> bool:
"""Check if we should re-subscribe to the topic using the old state."""
if other is None:
return True
return (
self.topic,
self.qos,
self.encoding,
) != (
other.topic,
other.qos,
other.encoding,
)
@callback
def async_prepare_subscribe_topics(
hass: HomeAssistant,
sub_state: dict[str, EntitySubscription] | None,
topics: dict[str, dict[str, Any]],
) -> dict[str, EntitySubscription]:
"""Prepare (re)subscribe to a set of MQTT topics.
State is kept in sub_state and a dictionary mapping from the subscription
key to the subscription state.
After this function has been called, async_subscribe_topics must be called to
finalize any new subscriptions.
Please note that the sub state must not be shared between multiple
sets of topics. Every call to async_subscribe_topics must always
contain _all_ the topics the subscription state should manage.
"""
current_subscriptions: dict[str, EntitySubscription]
current_subscriptions = sub_state if sub_state is not None else {}
sub_state = {}
for key, value in topics.items():
# Extract the new requested subscription
requested = EntitySubscription(
topic=value.get("topic"),
message_callback=value["msg_callback"],
unsubscribe_callback=None,
qos=value.get("qos", DEFAULT_QOS),
encoding=value.get("encoding", "utf-8"),
hass=hass,
should_subscribe=None,
entity_id=value.get("entity_id"),
job_type=value.get("job_type"),
)
# Get the current subscription state
current = current_subscriptions.pop(key, None)
requested.resubscribe_if_necessary(hass, current)
sub_state[key] = requested
# Go through all remaining subscriptions and unsubscribe them
for remaining in current_subscriptions.values():
if remaining.unsubscribe_callback is not None:
remaining.unsubscribe_callback()
# Clear debug data if it exists
debug_info.remove_subscription(
hass,
str(remaining.topic),
remaining.entity_id,
)
return sub_state
async def async_subscribe_topics(
hass: HomeAssistant,
sub_state: dict[str, EntitySubscription],
) -> None:
"""(Re)Subscribe to a set of MQTT topics."""
async_subscribe_topics_internal(hass, sub_state)
@callback
def async_subscribe_topics_internal(
hass: HomeAssistant,
sub_state: dict[str, EntitySubscription],
) -> None:
"""(Re)Subscribe to a set of MQTT topics.
This function is internal to the MQTT integration and should not be called
from outside the integration.
"""
for sub in sub_state.values():
sub.subscribe()
if TYPE_CHECKING:
def async_unsubscribe_topics(
hass: HomeAssistant, sub_state: dict[str, EntitySubscription] | None
) -> dict[str, EntitySubscription]:
"""Unsubscribe from all MQTT topics managed by async_subscribe_topics."""
async_unsubscribe_topics = partial(async_prepare_subscribe_topics, topics={})
+173
View File
@@ -0,0 +1,173 @@
"""Support for MQTT switches."""
from collections.abc import Callable
from typing import Any, override
import probatio
from homeassistant.components import switch
from homeassistant.components.switch import DEVICE_CLASSES_SCHEMA, SwitchEntity
from homeassistant.config_entries import ConfigEntry
from homeassistant.const import (
CONF_DEVICE_CLASS,
CONF_NAME,
CONF_OPTIMISTIC,
CONF_PAYLOAD_OFF,
CONF_PAYLOAD_ON,
CONF_VALUE_TEMPLATE,
STATE_ON,
)
from homeassistant.core import HomeAssistant, callback
from homeassistant.helpers import config_validation as cv
from homeassistant.helpers.entity_platform import AddConfigEntryEntitiesCallback
from homeassistant.helpers.restore_state import RestoreEntity
from homeassistant.helpers.service_info.mqtt import ReceivePayloadType
from homeassistant.helpers.typing import ConfigType
from . import subscription
from .config import MQTT_RW_SCHEMA
from .const import (
CONF_COMMAND_TEMPLATE,
CONF_COMMAND_TOPIC,
CONF_STATE_OFF,
CONF_STATE_ON,
CONF_STATE_TOPIC,
DEFAULT_PAYLOAD_OFF,
DEFAULT_PAYLOAD_ON,
PAYLOAD_NONE,
)
from .entity import MqttEntity, async_setup_entity_entry_helper
from .models import (
MqttCommandTemplate,
MqttValueTemplate,
PublishPayloadType,
ReceiveMessage,
)
from .schemas import MQTT_ENTITY_COMMON_SCHEMA
PARALLEL_UPDATES = 0
DEFAULT_NAME = "MQTT Switch"
PLATFORM_SCHEMA_MODERN = MQTT_RW_SCHEMA.extend(
{
probatio.Optional(CONF_COMMAND_TEMPLATE): cv.template,
probatio.Optional(CONF_NAME): probatio.Any(cv.string, None),
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_STATE_OFF): cv.string,
probatio.Optional(CONF_STATE_ON): cv.string,
probatio.Optional(CONF_VALUE_TEMPLATE): cv.template,
probatio.Optional(CONF_DEVICE_CLASS): probatio.Any(DEVICE_CLASSES_SCHEMA, None),
}
).extend(MQTT_ENTITY_COMMON_SCHEMA.schema)
DISCOVERY_SCHEMA = PLATFORM_SCHEMA_MODERN.extend({}, extra=probatio.REMOVE_EXTRA)
async def async_setup_entry(
hass: HomeAssistant,
config_entry: ConfigEntry,
async_add_entities: AddConfigEntryEntitiesCallback,
) -> None:
"""Set up MQTT switch through YAML and through MQTT discovery."""
async_setup_entity_entry_helper(
hass,
config_entry,
MqttSwitch,
switch.DOMAIN,
async_add_entities,
DISCOVERY_SCHEMA,
PLATFORM_SCHEMA_MODERN,
)
class MqttSwitch(MqttEntity, SwitchEntity, RestoreEntity):
"""Representation of a switch that can be toggled using MQTT."""
_default_name = DEFAULT_NAME
_entity_id_format = switch.ENTITY_ID_FORMAT
_optimistic: bool
_is_on_map: dict[str | bytes | bytearray, bool | None]
_command_template: Callable[[PublishPayloadType], PublishPayloadType]
_value_template: Callable[[ReceivePayloadType], ReceivePayloadType]
@staticmethod
@override
def config_schema() -> probatio.Schema:
"""Return the config schema."""
return DISCOVERY_SCHEMA
@override
def _setup_from_config(self, config: ConfigType) -> None:
"""(Re)Setup the entity."""
self._attr_device_class = config.get(CONF_DEVICE_CLASS)
state_on: str | None = config.get(CONF_STATE_ON)
state_off: str | None = config.get(CONF_STATE_OFF)
self._is_on_map = {
state_on or config[CONF_PAYLOAD_ON]: True,
state_off or config[CONF_PAYLOAD_OFF]: False,
PAYLOAD_NONE: None,
}
self._optimistic = (
config[CONF_OPTIMISTIC] or config.get(CONF_STATE_TOPIC) is None
)
self._attr_assumed_state = bool(self._optimistic)
self._command_template = MqttCommandTemplate(
config.get(CONF_COMMAND_TEMPLATE), entity=self
).async_render
self._value_template = MqttValueTemplate(
config.get(CONF_VALUE_TEMPLATE), entity=self
).async_render_with_possible_json_value
@callback
def _state_message_received(self, msg: ReceiveMessage) -> None:
"""Handle new MQTT state messages."""
if (payload := self._value_template(msg.payload)) in self._is_on_map:
self._attr_is_on = self._is_on_map[payload]
@callback
@override
def _prepare_subscribe_topics(self) -> None:
"""(Re)Subscribe to topics."""
if not self.add_subscription(
CONF_STATE_TOPIC, self._state_message_received, {"_attr_is_on"}
):
# Force into optimistic mode.
self._optimistic = True
return
@override
async def _subscribe_topics(self) -> None:
"""(Re)Subscribe to topics."""
subscription.async_subscribe_topics_internal(self.hass, self._sub_state)
if self._optimistic and (last_state := await self.async_get_last_state()):
self._attr_is_on = last_state.state == STATE_ON
@override
async def async_turn_on(self, **kwargs: Any) -> None:
"""Turn the device on.
This method is a coroutine.
"""
payload = self._command_template(self._config[CONF_PAYLOAD_ON])
await self.async_publish_with_config(self._config[CONF_COMMAND_TOPIC], payload)
if self._optimistic:
# Optimistically assume that switch has changed state.
self._attr_is_on = True
self.async_write_ha_state()
@override
async def async_turn_off(self, **kwargs: Any) -> None:
"""Turn the device off.
This method is a coroutine.
"""
payload = self._command_template(self._config[CONF_PAYLOAD_OFF])
await self.async_publish_with_config(self._config[CONF_COMMAND_TOPIC], payload)
if self._optimistic:
# Optimistically assume that switch has changed state.
self._attr_is_on = False
self.async_write_ha_state()
+186
View File
@@ -0,0 +1,186 @@
"""Provides tag scanning for MQTT."""
from collections.abc import Callable
import functools
import logging
from typing import override
import probatio
from homeassistant.components import tag
from homeassistant.config_entries import ConfigEntry
from homeassistant.const import CONF_DEVICE, CONF_VALUE_TEMPLATE
from homeassistant.core import HassJobType, HomeAssistant, callback
from homeassistant.helpers import config_validation as cv
from homeassistant.helpers.service_info.mqtt import ReceivePayloadType
from homeassistant.helpers.typing import ConfigType, DiscoveryInfoType
from . import subscription
from .config import MQTT_BASE_SCHEMA
from .const import ATTR_DISCOVERY_HASH, CONF_QOS, CONF_TOPIC
from .discovery import MQTTDiscoveryPayload
from .entity import (
MqttDiscoveryDeviceUpdateMixin,
async_handle_schema_error,
async_setup_non_entity_entry_helper,
send_discovery_done,
update_device,
)
from .models import (
DATA_MQTT,
MqttValueTemplate,
MqttValueTemplateException,
ReceiveMessage,
)
from .schemas import MQTT_ENTITY_DEVICE_INFO_SCHEMA
from .subscription import EntitySubscription
from .util import valid_subscribe_topic
_LOGGER = logging.getLogger(__name__)
LOG_NAME = "Tag"
TAG = "tag"
DISCOVERY_SCHEMA = MQTT_BASE_SCHEMA.extend(
{
probatio.Optional(CONF_DEVICE): MQTT_ENTITY_DEVICE_INFO_SCHEMA,
probatio.Required(CONF_TOPIC): valid_subscribe_topic,
probatio.Optional(CONF_VALUE_TEMPLATE): cv.template,
},
extra=probatio.REMOVE_EXTRA,
)
async def async_setup_mqtt_tag_entry(
hass: HomeAssistant, config_entry: ConfigEntry
) -> None:
"""Set up MQTT tag scanner dynamically through MQTT discovery."""
setup = functools.partial(_async_setup_tag, hass, config_entry=config_entry)
async_setup_non_entity_entry_helper(hass, TAG, setup, DISCOVERY_SCHEMA)
async def _async_setup_tag(
hass: HomeAssistant,
config: ConfigType,
config_entry: ConfigEntry,
discovery_data: DiscoveryInfoType,
) -> None:
"""Set up the MQTT tag scanner."""
discovery_hash = discovery_data[ATTR_DISCOVERY_HASH]
discovery_id = discovery_hash[1]
device_id = update_device(hass, config_entry, config)
if device_id is not None and device_id not in (tags := hass.data[DATA_MQTT].tags):
tags[device_id] = {}
tag_scanner = MQTTTagScanner(
hass,
config,
device_id,
discovery_data,
config_entry,
)
await tag_scanner.subscribe_topics()
if device_id:
tags[device_id][discovery_id] = tag_scanner
send_discovery_done(hass, discovery_data)
def async_has_tags(hass: HomeAssistant, device_id: str) -> bool:
"""Device has tag scanners."""
if device_id not in (tags := hass.data[DATA_MQTT].tags):
return False
return tags[device_id] != {}
class MQTTTagScanner(MqttDiscoveryDeviceUpdateMixin):
"""MQTT Tag scanner."""
_value_template: Callable[[ReceivePayloadType, str], ReceivePayloadType]
def __init__(
self,
hass: HomeAssistant,
config: ConfigType,
device_id: str | None,
discovery_data: DiscoveryInfoType,
config_entry: ConfigEntry,
) -> None:
"""Initialize."""
self._config = config
self._config_entry = config_entry
self.device_id = device_id
self.discovery_data = discovery_data
self.hass = hass
self._sub_state: dict[str, EntitySubscription] | None = None
self._value_template = MqttValueTemplate(
config.get(CONF_VALUE_TEMPLATE)
).async_render_with_possible_json_value
MqttDiscoveryDeviceUpdateMixin.__init__(
self, hass, discovery_data, device_id, config_entry, LOG_NAME
)
@override
async def async_update(self, discovery_data: MQTTDiscoveryPayload) -> None:
"""Handle MQTT tag discovery updates."""
# Update tag scanner
try:
config: DiscoveryInfoType = DISCOVERY_SCHEMA(discovery_data)
except probatio.Invalid as err:
async_handle_schema_error(discovery_data, err)
return
self._config = config
self._value_template = MqttValueTemplate(
config.get(CONF_VALUE_TEMPLATE)
).async_render_with_possible_json_value
update_device(self.hass, self._config_entry, config)
await self.subscribe_topics()
@callback
def _async_tag_scanned(self, msg: ReceiveMessage) -> None:
"""Handle new tag scanned."""
try:
tag_id = str(self._value_template(msg.payload, "")).strip()
except MqttValueTemplateException as exc:
_LOGGER.warning(exc)
return
if not tag_id: # No output from template, ignore
return
self.hass.async_create_task(
tag.async_scan_tag(self.hass, tag_id, self.device_id)
)
async def subscribe_topics(self) -> None:
"""Subscribe to MQTT topics."""
self._sub_state = subscription.async_prepare_subscribe_topics(
self.hass,
self._sub_state,
{
"state_topic": {
"topic": self._config[CONF_TOPIC],
"msg_callback": self._async_tag_scanned,
"qos": self._config[CONF_QOS],
"job_type": HassJobType.Callback,
}
},
)
subscription.async_subscribe_topics_internal(self.hass, self._sub_state)
@override
async def async_tear_down(self) -> None:
"""Cleanup tag scanner."""
discovery_hash = self.discovery_data[ATTR_DISCOVERY_HASH]
discovery_id = discovery_hash[1]
self._sub_state = subscription.async_unsubscribe_topics(
self.hass, self._sub_state
)
tags = self.hass.data[DATA_MQTT].tags
if self.device_id in tags and discovery_id in tags[self.device_id]:
del tags[self.device_id][discovery_id]
+186
View File
@@ -0,0 +1,186 @@
"""Support for MQTT text platform."""
from collections.abc import Callable
import logging
import re
from typing import Any, override
import probatio
from homeassistant.components import text
from homeassistant.components.text import TextEntity, TextEntityCapabilityAttribute
from homeassistant.config_entries import ConfigEntry
from homeassistant.const import (
CONF_MODE,
CONF_NAME,
CONF_OPTIMISTIC,
CONF_VALUE_TEMPLATE,
MAX_LENGTH_STATE_STATE,
)
from homeassistant.core import HomeAssistant, callback
from homeassistant.helpers import config_validation as cv
from homeassistant.helpers.entity_platform import AddConfigEntryEntitiesCallback
from homeassistant.helpers.service_info.mqtt import ReceivePayloadType
from homeassistant.helpers.typing import ConfigType, VolSchemaType
from . import subscription
from .config import MQTT_RW_SCHEMA
from .const import (
CONF_COMMAND_TEMPLATE,
CONF_COMMAND_TOPIC,
CONF_MAX,
CONF_MIN,
CONF_PATTERN,
CONF_STATE_TOPIC,
)
from .entity import MqttEntity, async_setup_entity_entry_helper
from .models import (
MqttCommandTemplate,
MqttValueTemplate,
PublishPayloadType,
ReceiveMessage,
)
from .schemas import MQTT_ENTITY_COMMON_SCHEMA
from .util import check_state_too_long
_LOGGER = logging.getLogger(__name__)
PARALLEL_UPDATES = 0
DEFAULT_NAME = "MQTT Text"
MQTT_TEXT_ATTRIBUTES_BLOCKED = frozenset(
{
TextEntityCapabilityAttribute.MAX,
TextEntityCapabilityAttribute.MIN,
TextEntityCapabilityAttribute.MODE,
TextEntityCapabilityAttribute.PATTERN,
}
)
def valid_text_size_configuration(config: ConfigType) -> ConfigType:
"""Validate that the text length configuration is valid, throws if it isn't."""
if config[CONF_MIN] > config[CONF_MAX]:
raise probatio.Invalid("text length min must be <= max")
if config[CONF_MAX] > MAX_LENGTH_STATE_STATE:
raise probatio.Invalid(f"max text length must be <= {MAX_LENGTH_STATE_STATE}")
return config
_PLATFORM_SCHEMA_BASE = MQTT_RW_SCHEMA.extend(
{
probatio.Optional(CONF_COMMAND_TEMPLATE): cv.template,
probatio.Optional(CONF_NAME): probatio.Any(cv.string, None),
probatio.Optional(CONF_MAX, default=MAX_LENGTH_STATE_STATE): cv.positive_int,
probatio.Optional(CONF_MIN, default=0): cv.positive_int,
probatio.Optional(CONF_MODE, default=text.TextMode.TEXT): probatio.In(
[text.TextMode.TEXT, text.TextMode.PASSWORD]
),
probatio.Optional(CONF_PATTERN): cv.is_regex,
probatio.Optional(CONF_VALUE_TEMPLATE): cv.template,
},
).extend(MQTT_ENTITY_COMMON_SCHEMA.schema)
DISCOVERY_SCHEMA = probatio.All(
_PLATFORM_SCHEMA_BASE.extend({}, extra=probatio.REMOVE_EXTRA),
valid_text_size_configuration,
)
PLATFORM_SCHEMA_MODERN = probatio.All(
_PLATFORM_SCHEMA_BASE, valid_text_size_configuration
)
async def async_setup_entry(
hass: HomeAssistant,
config_entry: ConfigEntry,
async_add_entities: AddConfigEntryEntitiesCallback,
) -> None:
"""Set up MQTT text through YAML and through MQTT discovery."""
async_setup_entity_entry_helper(
hass,
config_entry,
MqttTextEntity,
text.DOMAIN,
async_add_entities,
DISCOVERY_SCHEMA,
PLATFORM_SCHEMA_MODERN,
)
class MqttTextEntity(MqttEntity, TextEntity):
"""Representation of the MQTT text entity."""
_attr_native_value: str | None = None
_attributes_extra_blocked = MQTT_TEXT_ATTRIBUTES_BLOCKED
_default_name = DEFAULT_NAME
_entity_id_format = text.ENTITY_ID_FORMAT
_compiled_pattern: re.Pattern[Any] | None
_optimistic: bool
_command_template: Callable[[PublishPayloadType], PublishPayloadType]
_value_template: Callable[[ReceivePayloadType], ReceivePayloadType]
@staticmethod
@override
def config_schema() -> VolSchemaType:
"""Return the config schema."""
return DISCOVERY_SCHEMA
@override
def _setup_from_config(self, config: ConfigType) -> None:
"""(Re)Setup the entity."""
self._attr_native_max = config[CONF_MAX]
self._attr_native_min = config[CONF_MIN]
self._attr_mode = config[CONF_MODE]
self._compiled_pattern = config.get(CONF_PATTERN)
self._attr_pattern = (
self._compiled_pattern.pattern if self._compiled_pattern else None
)
self._command_template = MqttCommandTemplate(
config.get(CONF_COMMAND_TEMPLATE),
entity=self,
).async_render
self._value_template = MqttValueTemplate(
config.get(CONF_VALUE_TEMPLATE),
entity=self,
).async_render_with_possible_json_value
optimistic: bool = config[CONF_OPTIMISTIC]
self._optimistic = optimistic or config.get(CONF_STATE_TOPIC) is None
self._attr_assumed_state = bool(self._optimistic)
@callback
def _handle_state_message_received(self, msg: ReceiveMessage) -> None:
"""Handle receiving state message via MQTT."""
payload = str(self._value_template(msg.payload))
if check_state_too_long(_LOGGER, payload, self.entity_id, msg):
return
self._attr_native_value = payload
@callback
@override
def _prepare_subscribe_topics(self) -> None:
"""(Re)Subscribe to topics."""
self.add_subscription(
CONF_STATE_TOPIC,
self._handle_state_message_received,
{"_attr_native_value"},
)
@override
async def _subscribe_topics(self) -> None:
"""(Re)Subscribe to topics."""
subscription.async_subscribe_topics_internal(self.hass, self._sub_state)
@override
async def async_set_value(self, value: str) -> None:
"""Change the text."""
payload = self._command_template(value)
await self.async_publish_with_config(self._config[CONF_COMMAND_TOPIC], payload)
if self._optimistic:
self._attr_native_value = value
self.async_write_ha_state()
+159
View File
@@ -0,0 +1,159 @@
"""Support for MQTT time platform."""
from collections.abc import Callable
import datetime
import logging
from typing import Any, override
from dateutil.parser import ParserError, parse
import probatio
from homeassistant.components import time
from homeassistant.components.time import TimeEntity
from homeassistant.config_entries import ConfigEntry
from homeassistant.const import CONF_NAME, CONF_OPTIMISTIC, CONF_VALUE_TEMPLATE
from homeassistant.core import HomeAssistant, callback
from homeassistant.helpers import config_validation as cv
from homeassistant.helpers.entity_platform import AddConfigEntryEntitiesCallback
from homeassistant.helpers.service_info.mqtt import ReceivePayloadType
from homeassistant.helpers.typing import ConfigType, VolSchemaType
from . import subscription
from .config import MQTT_RW_SCHEMA
from .const import (
CONF_COMMAND_TEMPLATE,
CONF_COMMAND_TOPIC,
CONF_STATE_TOPIC,
PAYLOAD_NONE,
)
from .entity import MqttEntity, async_setup_entity_entry_helper
from .models import (
MqttCommandTemplate,
MqttValueTemplate,
PublishPayloadType,
ReceiveMessage,
)
from .schemas import MQTT_ENTITY_COMMON_SCHEMA
_LOGGER = logging.getLogger(__name__)
PARALLEL_UPDATES = 0
DEFAULT_NAME = "MQTT Time"
MQTT_TIME_ATTRIBUTES_BLOCKED: frozenset[str] = frozenset()
PLATFORM_SCHEMA_MODERN = MQTT_RW_SCHEMA.extend(
{
probatio.Optional(CONF_COMMAND_TEMPLATE): cv.template,
probatio.Optional(CONF_NAME): probatio.Any(cv.string, None),
probatio.Optional(CONF_VALUE_TEMPLATE): cv.template,
},
).extend(MQTT_ENTITY_COMMON_SCHEMA.schema)
DISCOVERY_SCHEMA = PLATFORM_SCHEMA_MODERN.extend({}, extra=probatio.REMOVE_EXTRA)
async def async_setup_entry(
hass: HomeAssistant,
config_entry: ConfigEntry,
async_add_entities: AddConfigEntryEntitiesCallback,
) -> None:
"""Set up MQTT time through YAML and through MQTT discovery."""
async_setup_entity_entry_helper(
hass,
config_entry,
MqttTimeEntity,
time.DOMAIN,
async_add_entities,
DISCOVERY_SCHEMA,
PLATFORM_SCHEMA_MODERN,
)
class MqttTimeEntity(MqttEntity, TimeEntity):
"""Representation of the MQTT time entity."""
_attr_native_value: datetime.time | None = None
_attributes_extra_blocked = MQTT_TIME_ATTRIBUTES_BLOCKED
_default_name = DEFAULT_NAME
_entity_id_format = time.ENTITY_ID_FORMAT
_optimistic: bool
_command_template: Callable[
[PublishPayloadType, dict[str, Any]], PublishPayloadType
]
_value_template: Callable[[ReceivePayloadType], ReceivePayloadType]
@staticmethod
@override
def config_schema() -> VolSchemaType:
"""Return the config schema."""
return DISCOVERY_SCHEMA
@override
def _setup_from_config(self, config: ConfigType) -> None:
"""(Re)Setup the entity."""
self._command_template = MqttCommandTemplate(
config.get(CONF_COMMAND_TEMPLATE),
entity=self,
).async_render
self._value_template = MqttValueTemplate(
config.get(CONF_VALUE_TEMPLATE),
entity=self,
).async_render_with_possible_json_value
optimistic: bool = config[CONF_OPTIMISTIC]
self._optimistic = optimistic or config.get(CONF_STATE_TOPIC) is None
self._attr_assumed_state = bool(self._optimistic)
@callback
def _handle_state_message_received(self, msg: ReceiveMessage) -> None:
"""Handle receiving state message via MQTT."""
payload = str(self._value_template(msg.payload))
if payload == PAYLOAD_NONE:
self._attr_native_value = None
return
if payload == "":
_LOGGER.debug(
"Ignoring empty state payload on topic %s for entity %s",
msg.topic,
self.entity_id,
)
return
try:
value = parse(payload)
except ParserError:
_LOGGER.warning(
"Invalid received time expression on topic %s for entity %s, got %s",
msg.topic,
self.entity_id,
msg.payload,
)
else:
self._attr_native_value = value.time()
@callback
@override
def _prepare_subscribe_topics(self) -> None:
"""(Re)Subscribe to topics."""
self.add_subscription(
CONF_STATE_TOPIC,
self._handle_state_message_received,
{"_attr_native_value"},
)
@override
async def _subscribe_topics(self) -> None:
"""(Re)Subscribe to topics."""
subscription.async_subscribe_topics_internal(self.hass, self._sub_state)
@override
async def async_set_value(self, value: datetime.time) -> None:
"""Change the time."""
payload = self._command_template(value.isoformat(), {"value": value})
await self.async_publish_with_config(self._config[CONF_COMMAND_TOPIC], payload)
if self._optimistic:
self._attr_native_value = value
self.async_write_ha_state()
File diff suppressed because it is too large Load Diff
+120
View File
@@ -0,0 +1,120 @@
"""Offer MQTT listening automation rules."""
from collections.abc import Callable
from contextlib import suppress
import logging
from typing import Any
import probatio
from homeassistant.const import CONF_PAYLOAD, CONF_PLATFORM, CONF_VALUE_TEMPLATE
from homeassistant.core import (
CALLBACK_TYPE,
HassJob,
HassJobType,
HomeAssistant,
callback,
)
from homeassistant.helpers import config_validation as cv
from homeassistant.helpers.service_info.mqtt import ReceivePayloadType
from homeassistant.helpers.template import Template
from homeassistant.helpers.trigger import TriggerActionType, TriggerData, TriggerInfo
from homeassistant.helpers.typing import ConfigType, TemplateVarsType
from homeassistant.util.json import json_loads
from .client import async_subscribe_internal
from .const import (
CONF_ENCODING,
CONF_QOS,
CONF_TOPIC,
DEFAULT_ENCODING,
DEFAULT_QOS,
DOMAIN,
)
from .models import (
MqttCommandTemplate,
MqttValueTemplate,
PayloadSentinel,
PublishPayloadType,
ReceiveMessage,
)
from .util import valid_subscribe_topic, valid_subscribe_topic_template
TRIGGER_SCHEMA = cv.TRIGGER_BASE_SCHEMA.extend(
{
probatio.Required(CONF_PLATFORM): DOMAIN,
probatio.Required(CONF_TOPIC): valid_subscribe_topic_template,
probatio.Optional(CONF_PAYLOAD): cv.template,
probatio.Optional(CONF_VALUE_TEMPLATE): cv.template,
probatio.Optional(CONF_ENCODING, default=DEFAULT_ENCODING): cv.string,
probatio.Optional(CONF_QOS, default=DEFAULT_QOS): probatio.All(
probatio.Coerce(int), probatio.In([0, 1, 2])
),
}
)
_LOGGER = logging.getLogger(__name__)
async def async_attach_trigger(
hass: HomeAssistant,
config: ConfigType,
action: TriggerActionType,
trigger_info: TriggerInfo,
) -> CALLBACK_TYPE:
"""Listen for state changes based on configuration."""
trigger_data: TriggerData = trigger_info["trigger_data"]
command_template: Callable[
[PublishPayloadType, TemplateVarsType], PublishPayloadType
] = MqttCommandTemplate(config.get(CONF_PAYLOAD)).async_render
value_template: Callable[[ReceivePayloadType, str], ReceivePayloadType]
value_template = MqttValueTemplate(
config.get(CONF_VALUE_TEMPLATE)
).async_render_with_possible_json_value
encoding: str | None = config[CONF_ENCODING] or None
qos: int = config[CONF_QOS]
job = HassJob(action)
variables: TemplateVarsType | None = None
if trigger_info:
variables = trigger_info.get("variables")
wanted_payload = command_template(None, variables)
topic_template: Template = config[CONF_TOPIC]
topic = topic_template.async_render(variables, limited=True, parse_result=False)
valid_subscribe_topic(topic)
@callback
def mqtt_automation_listener(mqttmsg: ReceiveMessage) -> None:
"""Listen for MQTT messages."""
if wanted_payload is None or (
(payload := value_template(mqttmsg.payload, PayloadSentinel.DEFAULT))
and payload is not PayloadSentinel.DEFAULT
and wanted_payload == payload
):
data: dict[str, Any] = {
**trigger_data,
"platform": DOMAIN,
"topic": mqttmsg.topic,
"payload": mqttmsg.payload,
"qos": mqttmsg.qos,
"description": f"mqtt topic {mqttmsg.topic}",
}
with suppress(ValueError):
data["payload_json"] = json_loads(mqttmsg.payload)
hass.async_run_hass_job(job, {"trigger": data})
_LOGGER.debug(
"Attaching MQTT trigger for topic: '%s', payload: '%s'", topic, wanted_payload
)
return async_subscribe_internal(
hass,
topic,
mqtt_automation_listener,
encoding=encoding,
qos=qos,
job_type=HassJobType.Callback,
)
+14
View File
@@ -0,0 +1,14 @@
# Describes the format for MQTT triggers
_:
fields:
payload:
example: "on"
required: false
selector:
text:
topic:
example: "living_room/switch/ac"
required: true
selector:
text:
+285
View File
@@ -0,0 +1,285 @@
"""Configure update platform in a device through MQTT topic."""
import logging
from typing import Any, override
import probatio
from homeassistant.components import update
from homeassistant.components.update import (
DEVICE_CLASSES_SCHEMA,
UpdateEntity,
UpdateEntityFeature,
)
from homeassistant.config_entries import ConfigEntry
from homeassistant.const import CONF_DEVICE_CLASS, CONF_NAME, CONF_VALUE_TEMPLATE
from homeassistant.core import HomeAssistant, callback
from homeassistant.helpers import config_validation as cv
from homeassistant.helpers.entity_platform import AddConfigEntryEntitiesCallback
from homeassistant.helpers.restore_state import RestoreEntity
from homeassistant.helpers.typing import ConfigType, VolSchemaType
from homeassistant.util.json import JSON_DECODE_EXCEPTIONS, json_loads
from . import subscription
from .config import DEFAULT_RETAIN, MQTT_RO_SCHEMA
from .const import CONF_COMMAND_TOPIC, CONF_RETAIN, CONF_STATE_TOPIC, PAYLOAD_EMPTY_JSON
from .entity import MqttEntity, async_setup_entity_entry_helper
from .models import MqttValueTemplate, PayloadSentinel, ReceiveMessage
from .schemas import MQTT_ENTITY_COMMON_SCHEMA
from .util import valid_publish_topic, valid_subscribe_topic
_LOGGER = logging.getLogger(__name__)
PARALLEL_UPDATES = 0
DEFAULT_NAME = "MQTT Update"
CONF_DISPLAY_PRECISION = "display_precision"
CONF_LATEST_VERSION_TEMPLATE = "latest_version_template"
CONF_LATEST_VERSION_TOPIC = "latest_version_topic"
CONF_PAYLOAD_INSTALL = "payload_install"
CONF_RELEASE_SUMMARY = "release_summary"
CONF_RELEASE_URL = "release_url"
CONF_TITLE = "title"
PLATFORM_SCHEMA_MODERN = MQTT_RO_SCHEMA.extend(
{
probatio.Optional(CONF_COMMAND_TOPIC): valid_publish_topic,
probatio.Optional(CONF_DEVICE_CLASS): probatio.Any(DEVICE_CLASSES_SCHEMA, None),
probatio.Optional(CONF_DISPLAY_PRECISION, default=0): cv.positive_int,
probatio.Optional(CONF_LATEST_VERSION_TEMPLATE): cv.template,
probatio.Optional(CONF_LATEST_VERSION_TOPIC): valid_subscribe_topic,
probatio.Optional(CONF_NAME): probatio.Any(cv.string, None),
probatio.Optional(CONF_PAYLOAD_INSTALL): cv.string,
probatio.Optional(CONF_RELEASE_SUMMARY): cv.string,
probatio.Optional(CONF_RELEASE_URL): cv.string,
probatio.Optional(CONF_RETAIN, default=DEFAULT_RETAIN): cv.boolean,
probatio.Optional(CONF_TITLE): cv.string,
},
).extend(MQTT_ENTITY_COMMON_SCHEMA.schema)
DISCOVERY_SCHEMA = probatio.All(
PLATFORM_SCHEMA_MODERN.extend({}, extra=probatio.REMOVE_EXTRA)
)
MQTT_JSON_UPDATE_SCHEMA = probatio.Schema(
{
probatio.Optional("installed_version"): cv.string,
probatio.Optional("latest_version"): cv.string,
probatio.Optional("title"): cv.string,
probatio.Optional("release_summary"): cv.string,
probatio.Optional("release_url"): cv.url,
probatio.Optional("entity_picture"): cv.url,
probatio.Optional("in_progress"): cv.boolean,
probatio.Optional("update_percentage"): probatio.Any(
probatio.Range(min=0, max=100), None
),
}
)
async def async_setup_entry(
hass: HomeAssistant,
config_entry: ConfigEntry,
async_add_entities: AddConfigEntryEntitiesCallback,
) -> None:
"""Set up MQTT update entity through YAML and through MQTT discovery."""
async_setup_entity_entry_helper(
hass,
config_entry,
MqttUpdate,
update.DOMAIN,
async_add_entities,
DISCOVERY_SCHEMA,
PLATFORM_SCHEMA_MODERN,
)
class MqttUpdate(MqttEntity, UpdateEntity, RestoreEntity):
"""Representation of the MQTT update entity."""
_default_name = DEFAULT_NAME
_entity_id_format = update.ENTITY_ID_FORMAT
@property
@override
def entity_picture(self) -> str | None:
"""Return the entity picture to use in the frontend."""
return self._attr_entity_picture
@staticmethod
@override
def config_schema() -> VolSchemaType:
"""Return the config schema."""
return DISCOVERY_SCHEMA
@override
def _setup_from_config(self, config: ConfigType) -> None:
"""(Re)Setup the entity."""
self._attr_device_class = self._config.get(CONF_DEVICE_CLASS)
self._attr_display_precision = self._config[CONF_DISPLAY_PRECISION]
self._attr_release_summary = self._config.get(CONF_RELEASE_SUMMARY)
self._attr_release_url = self._config.get(CONF_RELEASE_URL)
self._attr_title = self._config.get(CONF_TITLE)
self._templates = {
CONF_VALUE_TEMPLATE: MqttValueTemplate(
config.get(CONF_VALUE_TEMPLATE),
entity=self,
).async_render_with_possible_json_value,
CONF_LATEST_VERSION_TEMPLATE: MqttValueTemplate(
config.get(CONF_LATEST_VERSION_TEMPLATE),
entity=self,
).async_render_with_possible_json_value,
}
@callback
def _handle_state_message_received(self, msg: ReceiveMessage) -> None:
"""Handle receiving state message via MQTT."""
payload = self._templates[CONF_VALUE_TEMPLATE](
msg.payload, PayloadSentinel.DEFAULT
)
if payload is PayloadSentinel.DEFAULT:
_LOGGER.warning(
"Unable to process payload '%s' for topic %s, with value template '%s'",
msg.payload,
msg.topic,
self._config.get(CONF_VALUE_TEMPLATE),
)
return
if not payload or payload == PAYLOAD_EMPTY_JSON:
_LOGGER.debug(
"Ignoring empty payload '%s' after rendering for topic %s",
payload,
msg.topic,
)
return
json_payload: dict[str, Any] = {}
try:
rendered_json_payload = json_loads(payload)
if isinstance(rendered_json_payload, dict):
_LOGGER.debug(
"JSON payload detected after processing payload '%s' on topic %s",
rendered_json_payload,
msg.topic,
)
json_payload = MQTT_JSON_UPDATE_SCHEMA(rendered_json_payload)
else:
_LOGGER.debug(
(
"Non-dictionary JSON payload detected after processing"
" payload '%s' on topic %s"
),
payload,
msg.topic,
)
json_payload = {"installed_version": str(payload)}
except probatio.MultipleInvalid as exc:
_LOGGER.warning(
(
"Schema violation after processing payload '%s'"
" on topic '%s' for entity '%s': %s"
),
payload,
msg.topic,
self.entity_id,
exc,
)
return
except JSON_DECODE_EXCEPTIONS:
_LOGGER.debug(
(
"No valid (JSON) payload detected after processing payload '%s'"
" on topic '%s' for entity '%s'"
),
payload,
msg.topic,
self.entity_id,
)
json_payload["installed_version"] = str(payload)
if "installed_version" in json_payload:
self._attr_installed_version = json_payload["installed_version"]
if "latest_version" in json_payload:
self._attr_latest_version = json_payload["latest_version"]
if "title" in json_payload:
self._attr_title = json_payload["title"]
if "release_summary" in json_payload:
self._attr_release_summary = json_payload["release_summary"]
if "release_url" in json_payload:
self._attr_release_url = json_payload["release_url"]
if "entity_picture" in json_payload:
self._attr_entity_picture = json_payload["entity_picture"]
if "update_percentage" in json_payload:
self._attr_update_percentage = json_payload["update_percentage"]
self._attr_in_progress = self._attr_update_percentage is not None
if "in_progress" in json_payload:
self._attr_in_progress = json_payload["in_progress"]
@callback
def _handle_latest_version_received(self, msg: ReceiveMessage) -> None:
"""Handle receiving latest version via MQTT."""
latest_version = self._templates[CONF_LATEST_VERSION_TEMPLATE](msg.payload)
if isinstance(latest_version, str) and latest_version != "":
self._attr_latest_version = latest_version
@callback
@override
def _prepare_subscribe_topics(self) -> None:
"""(Re)Subscribe to topics."""
self.add_subscription(
CONF_STATE_TOPIC,
self._handle_state_message_received,
{
"_attr_entity_picture",
"_attr_in_progress",
"_attr_installed_version",
"_attr_latest_version",
"_attr_title",
"_attr_release_summary",
"_attr_release_url",
"_attr_update_percentage",
},
)
self.add_subscription(
CONF_LATEST_VERSION_TOPIC,
self._handle_latest_version_received,
{"_attr_latest_version"},
)
@override
async def _subscribe_topics(self) -> None:
"""(Re)Subscribe to topics."""
subscription.async_subscribe_topics_internal(self.hass, self._sub_state)
@override
async def async_install(
self, version: str | None, backup: bool, **kwargs: Any
) -> None:
"""Update the current value."""
payload = self._config[CONF_PAYLOAD_INSTALL]
await self.async_publish_with_config(self._config[CONF_COMMAND_TOPIC], payload)
@property
@override
def supported_features(self) -> UpdateEntityFeature:
"""Return the list of supported features."""
support = UpdateEntityFeature(UpdateEntityFeature.PROGRESS)
if self._config.get(CONF_COMMAND_TOPIC) is not None:
support |= UpdateEntityFeature.INSTALL
return support
+460
View File
@@ -0,0 +1,460 @@
"""Utility functions for the MQTT integration."""
import asyncio
from collections.abc import Callable, Coroutine
from functools import lru_cache
import logging
import os
from pathlib import Path
import tempfile
from typing import Any
import probatio
from homeassistant.config_entries import ConfigEntry, ConfigEntryState
from homeassistant.const import MAX_LENGTH_STATE_STATE, STATE_UNKNOWN, Platform
from homeassistant.core import HomeAssistant, callback
from homeassistant.exceptions import HomeAssistantError
from homeassistant.helpers import (
config_validation as cv,
device_registry as dr,
entity_registry as er,
template,
)
from homeassistant.helpers.typing import ConfigType
from homeassistant.util.async_ import create_eager_task
from .const import (
ATTR_PAYLOAD,
ATTR_QOS,
ATTR_RETAIN,
ATTR_TOPIC,
CONF_CERTIFICATE,
CONF_CLIENT_CERT,
CONF_CLIENT_KEY,
DEFAULT_ENCODING,
DEFAULT_QOS,
DEFAULT_RETAIN,
DOMAIN,
)
from .models import DATA_MQTT, DATA_MQTT_AVAILABLE, ReceiveMessage
AVAILABILITY_TIMEOUT = 50.0
TEMP_DIR_NAME = f"home-assistant-{DOMAIN}"
_VALID_QOS_SCHEMA = probatio.All(probatio.Coerce(int), probatio.In([0, 1, 2]))
_LOGGER = logging.getLogger(__name__)
class EnsureJobAfterCooldown:
"""Ensure a cool down period before executing a job.
When a new execute request arrives we cancel the current request
and start a new one.
We allow patching this util, as we generally have exceptions
for sleeps/waits/debouncers/timers causing long run times in tests.
"""
def __init__(
self, timeout: float, callback_job: Callable[[], Coroutine[Any, None, None]]
) -> None:
"""Initialize the timer."""
self._loop = asyncio.get_running_loop()
self._timeout = timeout
self._callback = callback_job
self._task: asyncio.Task | None = None
self._timer: asyncio.TimerHandle | None = None
self._next_execute_time = 0.0
def set_timeout(self, timeout: float) -> None:
"""Set a new timeout period."""
self._timeout = timeout
async def _async_job(self) -> None:
"""Execute after a cooldown period."""
try:
await self._callback()
except HomeAssistantError as ha_error:
_LOGGER.error("%s", ha_error)
@callback
def _async_task_done(self, task: asyncio.Task) -> None:
"""Handle task done."""
self._task = None
@callback
def async_execute(self) -> asyncio.Task:
"""Execute the job."""
if self._task:
# Task already running,
# so we schedule another run
self.async_schedule()
return self._task
self._async_cancel_timer()
self._task = create_eager_task(self._async_job())
self._task.add_done_callback(self._async_task_done)
return self._task
@callback
def _async_cancel_timer(self) -> None:
"""Cancel any pending task."""
if self._timer:
self._timer.cancel()
self._timer = None
@callback
def async_schedule(self) -> None:
"""Ensure we execute after a cooldown period."""
# We want to reschedule the timer in the future
# every time this is called.
next_when = self._loop.time() + self._timeout
if not self._timer:
self._timer = self._loop.call_at(next_when, self._async_timer_reached)
return
if self._timer.when() < next_when:
# Timer already running, set the next execute time
# if it fires too early, it will get rescheduled
self._next_execute_time = next_when
@callback
def _async_timer_reached(self) -> None:
"""Handle timer fire."""
self._timer = None
if self._loop.time() >= self._next_execute_time:
self.async_execute()
return
# Timer fired too early because there were multiple
# calls async_schedule. Reschedule the timer.
self._timer = self._loop.call_at(
self._next_execute_time, self._async_timer_reached
)
async def async_cleanup(self) -> None:
"""Cleanup any pending task."""
self._async_cancel_timer()
if not self._task:
return
self._task.cancel()
try:
await self._task
except asyncio.CancelledError:
pass
except Exception:
_LOGGER.exception("Error cleaning up task")
def platforms_from_config(config: list[ConfigType]) -> set[Platform | str]:
"""Return the platforms to be set up."""
return {key for platform in config for key in platform}
async def async_forward_entry_setup_and_setup_discovery(
hass: HomeAssistant,
config_entry: ConfigEntry,
platforms: set[Platform | str],
late: bool = False,
) -> None:
"""Forward the config entry setup to the platforms and set up discovery."""
mqtt_data = hass.data[DATA_MQTT]
platforms_loaded = mqtt_data.platforms_loaded
new_platforms: set[Platform | str] = platforms - platforms_loaded
tasks: list[asyncio.Task] = []
if "device_automation" in new_platforms:
# Local import to avoid circular dependencies
from . import device_automation # noqa: PLC0415
tasks.append(
create_eager_task(
device_automation.async_setup_mqtt_device_automation_entry(
hass, config_entry
)
)
)
if "tag" in new_platforms:
# Local import to avoid circular dependencies
from . import tag # noqa: PLC0415
tasks.append(
create_eager_task(tag.async_setup_mqtt_tag_entry(hass, config_entry))
)
if new_entity_platforms := (new_platforms - {"tag", "device_automation"}):
tasks.append(
create_eager_task(
hass.config_entries.async_forward_entry_setups(
config_entry, new_entity_platforms
)
)
)
if not tasks:
return
await asyncio.gather(*tasks)
platforms_loaded.update(new_platforms)
def mqtt_config_entry_enabled(hass: HomeAssistant) -> bool | None:
"""Return true when the MQTT config entry is enabled."""
# If the mqtt client is connected, skip the expensive config
# entry check as its roughly two orders of magnitude faster.
return (
DATA_MQTT in hass.data and hass.data[DATA_MQTT].client.connected
) or hass.config_entries.async_has_entries(
DOMAIN, include_disabled=False, include_ignore=False
)
async def async_wait_for_mqtt_client(hass: HomeAssistant) -> bool:
"""Wait for the MQTT client to become available.
Waits when mqtt set up is in progress,
It is not needed that the client is connected.
Returns True if the mqtt client is available.
Returns False when the client is not available.
"""
if not mqtt_config_entry_enabled(hass):
return False
entry = hass.config_entries.async_entries(DOMAIN)[0]
if entry.state is ConfigEntryState.LOADED:
return True
state_reached_future: asyncio.Future[bool]
if DATA_MQTT_AVAILABLE not in hass.data:
state_reached_future = hass.loop.create_future()
hass.data[DATA_MQTT_AVAILABLE] = state_reached_future
else:
state_reached_future = hass.data[DATA_MQTT_AVAILABLE]
try:
async with asyncio.timeout(AVAILABILITY_TIMEOUT):
# Await the client setup or an error state was received
return await state_reached_future
except TimeoutError:
return False
def valid_topic(topic: Any) -> str:
"""Validate that this is a valid topic name/filter.
This function is not cached and is not expected to be called
directly outside of this module. It is not marked as protected
only because its tested directly in test_util.py.
If it gets used outside of valid_subscribe_topic and
valid_publish_topic, it may need an lru_cache decorator or
an lru_cache decorator on the function where its used.
"""
validated_topic = cv.string(topic)
try:
raw_validated_topic = validated_topic.encode("utf-8")
except UnicodeError as err:
raise probatio.Invalid(
"MQTT topic name/filter must be valid UTF-8 string."
) from err
if not raw_validated_topic:
raise probatio.Invalid("MQTT topic name/filter must not be empty.")
if len(raw_validated_topic) > 65535:
raise probatio.Invalid(
"MQTT topic name/filter must not be longer than 65535 encoded bytes."
)
for char in validated_topic:
if char == "\0":
raise probatio.Invalid(
"MQTT topic name/filter must not contain null character."
)
if char <= "\u001f" or "\u007f" <= char <= "\u009f":
raise probatio.Invalid(
"MQTT topic name/filter must not contain control characters."
)
if "\ufdd0" <= char <= "\ufdef" or (ord(char) & 0xFFFF) in (0xFFFE, 0xFFFF):
raise probatio.Invalid(
"MQTT topic name/filter must not contain non-characters."
)
return validated_topic
@lru_cache
def valid_subscribe_topic(topic: Any) -> str:
"""Validate that we can subscribe using this MQTT topic."""
validated_topic = valid_topic(topic)
if "+" in validated_topic:
for i in (i for i, c in enumerate(validated_topic) if c == "+"):
if (i > 0 and validated_topic[i - 1] != "/") or (
i < len(validated_topic) - 1 and validated_topic[i + 1] != "/"
):
raise probatio.Invalid(
"Single-level wildcard must occupy an entire level of the filter"
)
index = validated_topic.find("#")
if index != -1:
if index != len(validated_topic) - 1:
# If there are multiple wildcards, this will also trigger
raise probatio.Invalid(
"Multi-level wildcard must be the last character in the topic filter."
)
if len(validated_topic) > 1 and validated_topic[index - 1] != "/":
raise probatio.Invalid(
"Multi-level wildcard must be after a topic level separator."
)
return validated_topic
def valid_subscribe_topic_template(value: Any) -> template.Template:
"""Validate either a jinja2 template or a valid MQTT subscription topic."""
tpl = cv.template(value)
if tpl.is_static:
valid_subscribe_topic(value)
return tpl
@lru_cache
def valid_publish_topic(topic: Any) -> str:
"""Validate that we can publish using this MQTT topic."""
validated_topic = valid_topic(topic)
if "+" in validated_topic or "#" in validated_topic:
raise probatio.Invalid("Wildcards cannot be used in topic names")
return validated_topic
def valid_qos_schema(qos: Any) -> int:
"""Validate that QOS value is valid."""
validated_qos: int = _VALID_QOS_SCHEMA(qos)
return validated_qos
_MQTT_WILL_BIRTH_SCHEMA = probatio.Schema(
{
probatio.Required(ATTR_TOPIC): valid_publish_topic,
probatio.Required(ATTR_PAYLOAD): cv.string,
probatio.Optional(ATTR_QOS, default=DEFAULT_QOS): valid_qos_schema,
probatio.Optional(ATTR_RETAIN, default=DEFAULT_RETAIN): cv.boolean,
},
required=True,
)
def valid_birth_will(config: ConfigType) -> ConfigType:
"""Validate a birth or will configuration and required topic/payload."""
if config:
config = _MQTT_WILL_BIRTH_SCHEMA(config)
return config
async def async_create_certificate_temp_files(
hass: HomeAssistant, config: ConfigType
) -> None:
"""Create certificate temporary files for the MQTT client."""
def _create_temp_file(temp_file: Path, data: str | None) -> None:
if data is None or data == "auto":
if temp_file.exists():
os.remove(Path(temp_file))
return
temp_file.write_text(data)
def _create_temp_dir_and_files() -> None:
"""Create temporary directory."""
temp_dir = Path(tempfile.gettempdir()) / TEMP_DIR_NAME
if (
config.get(CONF_CERTIFICATE)
or config.get(CONF_CLIENT_CERT)
or config.get(CONF_CLIENT_KEY)
) and not temp_dir.exists():
temp_dir.mkdir(0o700)
_create_temp_file(temp_dir / CONF_CERTIFICATE, config.get(CONF_CERTIFICATE))
_create_temp_file(temp_dir / CONF_CLIENT_CERT, config.get(CONF_CLIENT_CERT))
_create_temp_file(temp_dir / CONF_CLIENT_KEY, config.get(CONF_CLIENT_KEY))
await hass.async_add_executor_job(_create_temp_dir_and_files)
def check_state_too_long(
logger: logging.Logger, proposed_state: str, entity_id: str, msg: ReceiveMessage
) -> bool:
"""Check if the processed state is too long and log warning."""
if (state_length := len(proposed_state)) > MAX_LENGTH_STATE_STATE:
logger.warning(
"Cannot update state for entity %s after processing "
"payload on topic %s. The requested state (%s) exceeds "
"the maximum allowed length (%s). Fall back to "
"%s, failed state: %s",
entity_id,
msg.topic,
state_length,
MAX_LENGTH_STATE_STATE,
STATE_UNKNOWN,
proposed_state[:8192],
)
return True
return False
def get_file_path(option: str, default: str | None = None) -> str | None:
"""Get file path of a certificate file."""
temp_dir = Path(tempfile.gettempdir()) / TEMP_DIR_NAME
if not temp_dir.exists():
return default
file_path: Path = temp_dir / option
if not file_path.exists():
return default
return str(temp_dir / option)
def migrate_certificate_file_to_content(file_name_or_auto: str) -> str | None:
"""Convert certificate file or setting to config entry setting."""
if file_name_or_auto == "auto":
return "auto"
try:
with open(file_name_or_auto, encoding=DEFAULT_ENCODING) as certificate_file:
return certificate_file.read()
except OSError:
return None
@callback
def learn_more_url(platform: str) -> str:
"""Return the URL for the platform specific MQTT documentation."""
return f"https://www.home-assistant.io/integrations/{platform}.mqtt/"
async def async_cleanup_device_registry(
hass: HomeAssistant, device_id: str | None, config_entry_id: str | None
) -> None:
"""Clean up the device registry after MQTT removal.
Remove MQTT from the device registry entry if there are no remaining
entities, triggers or tags.
"""
# Local import to avoid circular dependencies
from . import device_trigger, tag # noqa: PLC0415
device_registry = dr.async_get(hass)
entity_registry = er.async_get(hass)
if (
device_id
and config_entry_id
and (device := device_registry.async_get(device_id)) is not None
# Only remove the device if it is owned by the MQTT config entry
and device.config_entry_id == config_entry_id
and not er.async_entries_for_device(
entity_registry, device_id, include_disabled_entities=False
)
and not await device_trigger.async_get_triggers(hass, device_id)
and not tag.async_has_tags(hass, device_id)
):
device_registry.async_remove_device(device_id)
+428
View File
@@ -0,0 +1,428 @@
"""Support for MQTT vacuums."""
import logging
from typing import Any, cast, override
import probatio
from homeassistant.components import vacuum
from homeassistant.components.vacuum import (
ENTITY_ID_FORMAT,
Segment,
StateVacuumEntity,
VacuumActivity,
VacuumEntityFeature,
VacuumEntityStateAttribute,
)
from homeassistant.config_entries import ConfigEntry
from homeassistant.const import (
ATTR_SUPPORTED_FEATURES,
CONF_NAME,
CONF_UNIQUE_ID,
STATE_IDLE,
STATE_PAUSED,
)
from homeassistant.core import HomeAssistant, callback
from homeassistant.helpers import config_validation as cv
from homeassistant.helpers.entity_platform import AddConfigEntryEntitiesCallback
from homeassistant.helpers.json import json_dumps
from homeassistant.helpers.typing import ConfigType, DiscoveryInfoType, VolSchemaType
from homeassistant.util.json import json_loads_object
from . import subscription
from .config import MQTT_BASE_SCHEMA
from .const import CONF_COMMAND_TOPIC, CONF_RETAIN, CONF_STATE_TOPIC
from .entity import MqttEntity, async_setup_entity_entry_helper
from .models import MqttCommandTemplate, ReceiveMessage
from .schemas import MQTT_ENTITY_COMMON_SCHEMA
from .util import valid_publish_topic
PARALLEL_UPDATES = 0
FAN_SPEED = "fan_speed"
SEGMENTS = "segments"
STATE = "state"
STATE_DOCKED = "docked"
STATE_ERROR = "error"
STATE_RETURNING = "returning"
STATE_CLEANING = "cleaning"
POSSIBLE_STATES: dict[str, VacuumActivity] = {
STATE_IDLE: VacuumActivity.IDLE,
STATE_DOCKED: VacuumActivity.DOCKED,
STATE_ERROR: VacuumActivity.ERROR,
STATE_PAUSED: VacuumActivity.PAUSED,
STATE_RETURNING: VacuumActivity.RETURNING,
STATE_CLEANING: VacuumActivity.CLEANING,
}
CONF_CLEAN_SEGMENTS_COMMAND_TOPIC = "clean_segments_command_topic"
CONF_CLEAN_SEGMENTS_COMMAND_TEMPLATE = "clean_segments_command_template"
CONF_SUPPORTED_FEATURES = ATTR_SUPPORTED_FEATURES
CONF_PAYLOAD_TURN_ON = "payload_turn_on"
CONF_PAYLOAD_TURN_OFF = "payload_turn_off"
CONF_PAYLOAD_RETURN_TO_BASE = "payload_return_to_base"
CONF_PAYLOAD_STOP = "payload_stop"
CONF_PAYLOAD_CLEAN_SPOT = "payload_clean_spot"
CONF_PAYLOAD_LOCATE = "payload_locate"
CONF_PAYLOAD_START = "payload_start"
CONF_PAYLOAD_PAUSE = "payload_pause"
CONF_SET_FAN_SPEED_TOPIC = "set_fan_speed_topic"
CONF_FAN_SPEED_LIST = "fan_speed_list"
CONF_SEND_COMMAND_TOPIC = "send_command_topic"
DEFAULT_NAME = "MQTT State Vacuum"
DEFAULT_RETAIN = False
DEFAULT_PAYLOAD_RETURN_TO_BASE = "return_to_base"
DEFAULT_PAYLOAD_STOP = "stop"
DEFAULT_PAYLOAD_CLEAN_SPOT = "clean_spot"
DEFAULT_PAYLOAD_LOCATE = "locate"
DEFAULT_PAYLOAD_START = "start"
DEFAULT_PAYLOAD_PAUSE = "pause"
_LOGGER = logging.getLogger(__name__)
SERVICE_TO_STRING: dict[VacuumEntityFeature, str] = {
VacuumEntityFeature.START: "start",
VacuumEntityFeature.PAUSE: "pause",
VacuumEntityFeature.STOP: "stop",
VacuumEntityFeature.RETURN_HOME: "return_home",
VacuumEntityFeature.FAN_SPEED: "fan_speed",
VacuumEntityFeature.STATUS: "status",
VacuumEntityFeature.SEND_COMMAND: "send_command",
VacuumEntityFeature.LOCATE: "locate",
VacuumEntityFeature.CLEAN_SPOT: "clean_spot",
}
STRING_TO_SERVICE = {v: k for k, v in SERVICE_TO_STRING.items()}
DEFAULT_SERVICES = (
VacuumEntityFeature.START
| VacuumEntityFeature.STOP
| VacuumEntityFeature.RETURN_HOME
| VacuumEntityFeature.CLEAN_SPOT
)
ALL_SERVICES = (
DEFAULT_SERVICES
| VacuumEntityFeature.PAUSE
| VacuumEntityFeature.LOCATE
| VacuumEntityFeature.FAN_SPEED
| VacuumEntityFeature.SEND_COMMAND
)
def services_to_strings(
services: VacuumEntityFeature,
service_to_string: dict[VacuumEntityFeature, str],
) -> list[str]:
"""Convert SUPPORT_* service bitmask to list of service strings."""
return [
service_to_string[service]
for service in service_to_string
if service & services
]
DEFAULT_SERVICE_STRINGS = services_to_strings(DEFAULT_SERVICES, SERVICE_TO_STRING)
_FEATURE_PAYLOADS = {
VacuumEntityFeature.START: CONF_PAYLOAD_START,
VacuumEntityFeature.STOP: CONF_PAYLOAD_STOP,
VacuumEntityFeature.PAUSE: CONF_PAYLOAD_PAUSE,
VacuumEntityFeature.CLEAN_SPOT: CONF_PAYLOAD_CLEAN_SPOT,
VacuumEntityFeature.LOCATE: CONF_PAYLOAD_LOCATE,
VacuumEntityFeature.RETURN_HOME: CONF_PAYLOAD_RETURN_TO_BASE,
}
MQTT_VACUUM_ATTRIBUTES_BLOCKED = frozenset(
{
VacuumEntityStateAttribute.FAN_SPEED,
}
)
MQTT_VACUUM_DOCS_URL = "https://www.home-assistant.io/integrations/vacuum.mqtt/"
def validate_clean_area_config(config: ConfigType) -> ConfigType:
"""Validate clean area configuration."""
if CONF_CLEAN_SEGMENTS_COMMAND_TOPIC not in config:
return config
if not config.get(CONF_UNIQUE_ID):
raise probatio.Invalid(
f"Option `{CONF_CLEAN_SEGMENTS_COMMAND_TOPIC}`"
f" requires `{CONF_UNIQUE_ID}` to be configured"
)
return config
_BASE_SCHEMA = MQTT_BASE_SCHEMA.extend(
{
probatio.Optional(CONF_CLEAN_SEGMENTS_COMMAND_TOPIC): valid_publish_topic,
probatio.Optional(CONF_CLEAN_SEGMENTS_COMMAND_TEMPLATE): cv.template,
probatio.Optional(CONF_FAN_SPEED_LIST, default=[]): probatio.All(
probatio.EnsureList(), [cv.string]
),
probatio.Optional(CONF_NAME): probatio.Any(cv.string, None),
probatio.Optional(
CONF_PAYLOAD_CLEAN_SPOT, default=DEFAULT_PAYLOAD_CLEAN_SPOT
): cv.string,
probatio.Optional(
CONF_PAYLOAD_LOCATE, default=DEFAULT_PAYLOAD_LOCATE
): cv.string,
probatio.Optional(
CONF_PAYLOAD_RETURN_TO_BASE, default=DEFAULT_PAYLOAD_RETURN_TO_BASE
): cv.string,
probatio.Optional(CONF_PAYLOAD_START, default=DEFAULT_PAYLOAD_START): cv.string,
probatio.Optional(CONF_PAYLOAD_PAUSE, default=DEFAULT_PAYLOAD_PAUSE): cv.string,
probatio.Optional(CONF_PAYLOAD_STOP, default=DEFAULT_PAYLOAD_STOP): cv.string,
probatio.Optional(CONF_SEND_COMMAND_TOPIC): valid_publish_topic,
probatio.Optional(CONF_SET_FAN_SPEED_TOPIC): valid_publish_topic,
probatio.Optional(CONF_STATE_TOPIC): valid_publish_topic,
probatio.Optional(
CONF_SUPPORTED_FEATURES, default=DEFAULT_SERVICE_STRINGS
): probatio.All(probatio.EnsureList(), [probatio.In(STRING_TO_SERVICE.keys())]),
probatio.Optional(CONF_COMMAND_TOPIC): valid_publish_topic,
probatio.Optional(CONF_RETAIN, default=DEFAULT_RETAIN): cv.boolean,
}
).extend(MQTT_ENTITY_COMMON_SCHEMA.schema)
PLATFORM_SCHEMA_MODERN = probatio.All(_BASE_SCHEMA, validate_clean_area_config)
DISCOVERY_SCHEMA = probatio.All(
_BASE_SCHEMA.extend({}, extra=probatio.ALLOW_EXTRA), validate_clean_area_config
)
async def async_setup_entry(
hass: HomeAssistant,
config_entry: ConfigEntry,
async_add_entities: AddConfigEntryEntitiesCallback,
) -> None:
"""Set up MQTT vacuum through YAML and through MQTT discovery."""
async_setup_entity_entry_helper(
hass,
config_entry,
MqttStateVacuum,
vacuum.DOMAIN,
async_add_entities,
DISCOVERY_SCHEMA,
PLATFORM_SCHEMA_MODERN,
)
class MqttStateVacuum(MqttEntity, StateVacuumEntity):
"""Representation of a MQTT-controlled state vacuum."""
_default_name = DEFAULT_NAME
_entity_id_format = ENTITY_ID_FORMAT
_attributes_extra_blocked = MQTT_VACUUM_ATTRIBUTES_BLOCKED
_segments: list[Segment]
_command_topic: str | None
_set_fan_speed_topic: str | None
_send_command_topic: str | None
_clean_segments_command_topic: str | None = None
_payloads: dict[str, str | None]
def __init__(
self,
hass: HomeAssistant,
config: ConfigType,
config_entry: ConfigEntry,
discovery_data: DiscoveryInfoType | None,
) -> None:
"""Initialize the vacuum."""
self._state_attrs: dict[str, Any] = {}
MqttEntity.__init__(self, hass, config, config_entry, discovery_data)
@staticmethod
@override
def config_schema() -> VolSchemaType:
"""Return the config schema."""
return DISCOVERY_SCHEMA
@override
def _setup_from_config(self, config: ConfigType) -> None:
"""(Re)Setup the entity."""
def _strings_to_services(
strings: list[str], string_to_service: dict[str, VacuumEntityFeature]
) -> VacuumEntityFeature:
"""Convert service strings to SUPPORT_* service bitmask."""
services = VacuumEntityFeature.STATE
for string in strings:
services |= string_to_service[string]
return services
supported_feature_strings: list[str] = config[CONF_SUPPORTED_FEATURES]
self._attr_supported_features = _strings_to_services(
supported_feature_strings, STRING_TO_SERVICE
) | (
self.supported_features & VacuumEntityFeature.CLEAN_AREA
if CONF_CLEAN_SEGMENTS_COMMAND_TOPIC in config
else 0
)
self._clean_segments_command_topic = config.get(
CONF_CLEAN_SEGMENTS_COMMAND_TOPIC
)
self._clean_segments_command_template = MqttCommandTemplate(
config.get(CONF_CLEAN_SEGMENTS_COMMAND_TEMPLATE),
entity=self,
).async_render
self._attr_fan_speed_list = config[CONF_FAN_SPEED_LIST]
self._command_topic = config.get(CONF_COMMAND_TOPIC)
self._set_fan_speed_topic = config.get(CONF_SET_FAN_SPEED_TOPIC)
self._send_command_topic = config.get(CONF_SEND_COMMAND_TOPIC)
self._payloads = {
key: config.get(key)
for key in (
CONF_PAYLOAD_START,
CONF_PAYLOAD_PAUSE,
CONF_PAYLOAD_STOP,
CONF_PAYLOAD_RETURN_TO_BASE,
CONF_PAYLOAD_CLEAN_SPOT,
CONF_PAYLOAD_LOCATE,
)
}
def _update_state_attributes(self, payload: dict[str, Any]) -> None:
"""Update the entity state attributes."""
self._state_attrs.update(payload)
self._attr_fan_speed = self._state_attrs.get(FAN_SPEED, 0)
@callback
def _state_message_received(self, msg: ReceiveMessage) -> None:
"""Handle state MQTT message."""
payload = json_loads_object(msg.payload)
if STATE in payload and (
(state := payload[STATE]) in POSSIBLE_STATES or state is None
):
self._attr_activity = (
POSSIBLE_STATES[cast(str, state)] if payload[STATE] else None
)
del payload[STATE]
if (
(segments_payload := payload.pop(SEGMENTS, None))
and self._clean_segments_command_topic is not None
and isinstance(segments_payload, dict)
and (
segments := [
Segment(id=segment_id, name=str(segment_name))
for segment_id, segment_name in segments_payload.items()
]
)
):
self._segments = segments
self._attr_supported_features |= VacuumEntityFeature.CLEAN_AREA
if (last_seen := self.last_seen_segments) is not None and {
s.id: s for s in last_seen
} != {s.id: s for s in self._segments}:
self.async_create_segments_issue()
self._update_state_attributes(payload)
@callback
@override
def _prepare_subscribe_topics(self) -> None:
"""(Re)Subscribe to topics."""
self.add_subscription(
CONF_STATE_TOPIC,
self._state_message_received,
{"_attr_fan_speed", "_attr_activity"},
)
@override
async def _subscribe_topics(self) -> None:
"""(Re)Subscribe to topics."""
subscription.async_subscribe_topics_internal(self.hass, self._sub_state)
@override
async def async_clean_segments(self, segment_ids: list[str], **kwargs: Any) -> None:
"""Perform an area clean."""
assert self._clean_segments_command_topic is not None
await self.async_publish_with_config(
self._clean_segments_command_topic,
self._clean_segments_command_template(
json_dumps(segment_ids), {"value": segment_ids}
),
)
@override
async def async_get_segments(self) -> list[Segment]:
"""Return the available segments."""
return self._segments
async def _async_publish_command(self, feature: VacuumEntityFeature) -> None:
"""Publish a command."""
if self._command_topic is None:
return
await self.async_publish_with_config(
self._command_topic, self._payloads[_FEATURE_PAYLOADS[feature]]
)
self.async_write_ha_state()
@override
async def async_start(self) -> None:
"""Start the vacuum."""
await self._async_publish_command(VacuumEntityFeature.START)
@override
async def async_pause(self) -> None:
"""Pause the vacuum."""
await self._async_publish_command(VacuumEntityFeature.PAUSE)
@override
async def async_stop(self, **kwargs: Any) -> None:
"""Stop the vacuum."""
await self._async_publish_command(VacuumEntityFeature.STOP)
@override
async def async_return_to_base(self, **kwargs: Any) -> None:
"""Tell the vacuum to return to its dock."""
await self._async_publish_command(VacuumEntityFeature.RETURN_HOME)
@override
async def async_clean_spot(self, **kwargs: Any) -> None:
"""Perform a spot clean-up."""
await self._async_publish_command(VacuumEntityFeature.CLEAN_SPOT)
@override
async def async_locate(self, **kwargs: Any) -> None:
"""Locate the vacuum (usually by playing a song)."""
await self._async_publish_command(VacuumEntityFeature.LOCATE)
@override
async def async_set_fan_speed(self, fan_speed: str, **kwargs: Any) -> None:
"""Set fan speed."""
if (
self._set_fan_speed_topic is None
or (self.supported_features & VacuumEntityFeature.FAN_SPEED == 0)
or (fan_speed not in self.fan_speed_list)
):
return
await self.async_publish_with_config(self._set_fan_speed_topic, fan_speed)
@override
async def async_send_command(
self,
command: str,
params: dict[str, Any] | list[Any] | None = None,
**kwargs: Any,
) -> None:
"""Send a command to a vacuum cleaner."""
if (
self._send_command_topic is None
or self.supported_features & VacuumEntityFeature.SEND_COMMAND == 0
):
return
if isinstance(params, dict):
message: dict[str, Any] = {"command": command}
message.update(params)
payload = json_dumps(message)
else:
payload = command
await self.async_publish_with_config(self._send_command_topic, payload)
+420
View File
@@ -0,0 +1,420 @@
"""Support for MQTT valve devices."""
from contextlib import suppress
import logging
from typing import Any, override
import probatio
from homeassistant.components import valve
from homeassistant.components.valve import (
DEVICE_CLASSES_SCHEMA,
ValveEntity,
ValveEntityFeature,
ValveEntityStateAttribute,
ValveState,
)
from homeassistant.config_entries import ConfigEntry
from homeassistant.const import (
CONF_DEVICE_CLASS,
CONF_NAME,
CONF_OPTIMISTIC,
CONF_VALUE_TEMPLATE,
)
from homeassistant.core import HomeAssistant, callback
from homeassistant.helpers import config_validation as cv
from homeassistant.helpers.entity_platform import AddConfigEntryEntitiesCallback
from homeassistant.helpers.typing import ConfigType, VolSchemaType
from homeassistant.util.json import JSON_DECODE_EXCEPTIONS, json_loads
from homeassistant.util.percentage import (
percentage_to_ranged_value,
ranged_value_to_percentage,
)
from . import subscription
from .config import MQTT_BASE_SCHEMA
from .const import (
CONF_COMMAND_TEMPLATE,
CONF_COMMAND_TOPIC,
CONF_PAYLOAD_CLOSE,
CONF_PAYLOAD_OPEN,
CONF_PAYLOAD_STOP,
CONF_POSITION_CLOSED,
CONF_POSITION_OPEN,
CONF_REPORTS_POSITION,
CONF_RETAIN,
CONF_STATE_CLOSED,
CONF_STATE_CLOSING,
CONF_STATE_OPEN,
CONF_STATE_OPENING,
CONF_STATE_TOPIC,
DEFAULT_OPTIMISTIC,
DEFAULT_PAYLOAD_CLOSE,
DEFAULT_PAYLOAD_OPEN,
DEFAULT_POSITION_CLOSED,
DEFAULT_POSITION_OPEN,
DEFAULT_RETAIN,
PAYLOAD_NONE,
)
from .entity import MqttEntity, async_setup_entity_entry_helper
from .models import MqttCommandTemplate, MqttValueTemplate, ReceiveMessage
from .schemas import MQTT_ENTITY_COMMON_SCHEMA
from .util import valid_publish_topic, valid_subscribe_topic
_LOGGER = logging.getLogger(__name__)
PARALLEL_UPDATES = 0
DEFAULT_NAME = "MQTT Valve"
MQTT_VALVE_ATTRIBUTES_BLOCKED = frozenset(
{
ValveEntityStateAttribute.CURRENT_POSITION,
}
)
NO_POSITION_KEYS = (
CONF_PAYLOAD_CLOSE,
CONF_PAYLOAD_OPEN,
CONF_STATE_CLOSED,
CONF_STATE_OPEN,
)
DEFAULTS = {
CONF_PAYLOAD_CLOSE: DEFAULT_PAYLOAD_CLOSE,
CONF_PAYLOAD_OPEN: DEFAULT_PAYLOAD_OPEN,
CONF_STATE_OPEN: ValveState.OPEN,
CONF_STATE_CLOSED: ValveState.CLOSED,
}
RESET_CLOSING_OPENING = "reset_opening_closing"
def _validate_and_add_defaults(config: ConfigType) -> ConfigType:
"""Validate config options and set defaults."""
if config[CONF_REPORTS_POSITION] and any(key in config for key in NO_POSITION_KEYS):
raise probatio.Invalid(
"Options `payload_open`, `payload_close`, `state_open` and "
"`state_closed` are not allowed if the valve reports a position."
)
return {**DEFAULTS, **config}
_PLATFORM_SCHEMA_BASE = MQTT_BASE_SCHEMA.extend(
{
probatio.Optional(CONF_COMMAND_TOPIC): valid_publish_topic,
probatio.Optional(CONF_COMMAND_TEMPLATE): cv.template,
probatio.Optional(CONF_DEVICE_CLASS): probatio.Any(DEVICE_CLASSES_SCHEMA, None),
probatio.Optional(CONF_NAME): probatio.Any(cv.string, None),
probatio.Optional(CONF_OPTIMISTIC, default=DEFAULT_OPTIMISTIC): cv.boolean,
probatio.Optional(CONF_PAYLOAD_CLOSE): probatio.Any(cv.string, None),
probatio.Optional(CONF_PAYLOAD_OPEN): probatio.Any(cv.string, None),
probatio.Optional(CONF_PAYLOAD_STOP): probatio.Any(cv.string, None),
probatio.Optional(
CONF_POSITION_CLOSED, default=DEFAULT_POSITION_CLOSED
): probatio.Coerce(int),
probatio.Optional(
CONF_POSITION_OPEN, default=DEFAULT_POSITION_OPEN
): probatio.Coerce(int),
probatio.Optional(CONF_REPORTS_POSITION, default=False): cv.boolean,
probatio.Optional(CONF_RETAIN, default=DEFAULT_RETAIN): cv.boolean,
probatio.Optional(CONF_STATE_CLOSED): cv.string,
probatio.Optional(CONF_STATE_CLOSING, default=ValveState.CLOSING): cv.string,
probatio.Optional(CONF_STATE_OPEN): cv.string,
probatio.Optional(CONF_STATE_OPENING, default=ValveState.OPENING): cv.string,
probatio.Optional(CONF_STATE_TOPIC): valid_subscribe_topic,
probatio.Optional(CONF_VALUE_TEMPLATE): cv.template,
}
).extend(MQTT_ENTITY_COMMON_SCHEMA.schema)
PLATFORM_SCHEMA_MODERN = probatio.All(_PLATFORM_SCHEMA_BASE, _validate_and_add_defaults)
DISCOVERY_SCHEMA = probatio.All(
_PLATFORM_SCHEMA_BASE.extend({}, extra=probatio.REMOVE_EXTRA),
_validate_and_add_defaults,
)
async def async_setup_entry(
hass: HomeAssistant,
config_entry: ConfigEntry,
async_add_entities: AddConfigEntryEntitiesCallback,
) -> None:
"""Set up MQTT valve through YAML and through MQTT discovery."""
async_setup_entity_entry_helper(
hass,
config_entry,
MqttValve,
valve.DOMAIN,
async_add_entities,
DISCOVERY_SCHEMA,
PLATFORM_SCHEMA_MODERN,
)
class MqttValve(MqttEntity, ValveEntity):
"""Representation of a valve that can be controlled using MQTT."""
_attr_is_closed: bool | None = None
_attributes_extra_blocked: frozenset[str] = MQTT_VALVE_ATTRIBUTES_BLOCKED
_default_name = DEFAULT_NAME
_entity_id_format: str = valve.ENTITY_ID_FORMAT
_optimistic: bool
_range: tuple[int, int]
_tilt_optimistic: bool
@staticmethod
@override
def config_schema() -> VolSchemaType:
"""Return the config schema."""
return DISCOVERY_SCHEMA
@override
def _setup_from_config(self, config: ConfigType) -> None:
"""Set up valve from config."""
self._attr_reports_position = config[CONF_REPORTS_POSITION]
self._range = (
self._config[CONF_POSITION_CLOSED] + 1,
self._config[CONF_POSITION_OPEN],
)
no_state_topic = config.get(CONF_STATE_TOPIC) is None
self._optimistic = config[CONF_OPTIMISTIC] or no_state_topic
self._attr_assumed_state = self._optimistic
template_config_attributes = {
"position_open": config[CONF_POSITION_OPEN],
"position_closed": config[CONF_POSITION_CLOSED],
}
self._value_template = MqttValueTemplate(
config.get(CONF_VALUE_TEMPLATE), entity=self
).async_render_with_possible_json_value
self._command_template = MqttCommandTemplate(
config.get(CONF_COMMAND_TEMPLATE), entity=self
).async_render
self._value_template = MqttValueTemplate(
config.get(CONF_VALUE_TEMPLATE),
entity=self,
config_attributes=template_config_attributes,
).async_render_with_possible_json_value
self._attr_device_class = config.get(CONF_DEVICE_CLASS)
supported_features = ValveEntityFeature(0)
if CONF_COMMAND_TOPIC in config:
if config[CONF_PAYLOAD_OPEN] is not None:
supported_features |= ValveEntityFeature.OPEN
if config[CONF_PAYLOAD_CLOSE] is not None:
supported_features |= ValveEntityFeature.CLOSE
if config[CONF_REPORTS_POSITION]:
supported_features |= ValveEntityFeature.SET_POSITION
if config.get(CONF_PAYLOAD_STOP) is not None:
supported_features |= ValveEntityFeature.STOP
self._attr_supported_features = supported_features
@callback
def _update_state(self, state: str | None) -> None:
"""Update the valve state properties."""
self._attr_is_opening = state == ValveState.OPENING
self._attr_is_closing = state == ValveState.CLOSING
if self.reports_position:
return
if state is None:
self._attr_is_closed = None
else:
self._attr_is_closed = state == ValveState.CLOSED
@callback
def _process_binary_valve_update(
self, msg: ReceiveMessage, state_payload: str
) -> None:
"""Process an update for a valve that does not report the position."""
state: str | None = None
if state_payload == self._config[CONF_STATE_OPENING]:
state = ValveState.OPENING
elif state_payload == self._config[CONF_STATE_CLOSING]:
state = ValveState.CLOSING
elif state_payload == self._config[CONF_STATE_OPEN]:
state = ValveState.OPEN
elif state_payload == self._config[CONF_STATE_CLOSED]:
state = ValveState.CLOSED
elif state_payload == PAYLOAD_NONE:
state = None
else:
_LOGGER.warning(
"Payload received on topic '%s' is not one of "
"[open, closed, opening, closing], got: %s",
msg.topic,
state_payload,
)
return
self._update_state(state)
@callback
def _process_position_valve_update(
self, msg: ReceiveMessage, position_payload: str, state_payload: str
) -> None:
"""Process an update for a valve that reports the position."""
state: str | None = None
position_set: bool = False
if state_payload == self._config[CONF_STATE_OPENING]:
state = ValveState.OPENING
elif state_payload == self._config[CONF_STATE_CLOSING]:
state = ValveState.CLOSING
elif state_payload == PAYLOAD_NONE:
self._attr_current_valve_position = None
return
if state is None or position_payload != state_payload:
try:
percentage_payload = ranged_value_to_percentage(
self._range, float(position_payload)
)
except ValueError:
_LOGGER.debug(
"Ignoring non numeric payload '%s' received on topic '%s'",
position_payload,
msg.topic,
)
else:
percentage_payload = min(max(percentage_payload, 0), 100)
self._attr_current_valve_position = percentage_payload
# Reset opening/closing when a position update is received
# without an explicit opening/closing transitional state.
state = state or RESET_CLOSING_OPENING
position_set = True
if state_payload and state is None and not position_set:
_LOGGER.warning(
"Payload received on topic '%s' is not one of "
"[opening, closing], got: %s",
msg.topic,
state_payload,
)
return
self._update_state(state)
@callback
def _state_message_received(self, msg: ReceiveMessage) -> None:
"""Handle new MQTT state messages."""
payload = self._value_template(msg.payload)
payload_dict: Any = None
position_payload: Any = payload
state_payload: Any = payload
if not payload:
_LOGGER.debug("Ignoring empty state message from '%s'", msg.topic)
return
with suppress(*JSON_DECODE_EXCEPTIONS):
payload_dict = json_loads(payload)
if isinstance(payload_dict, dict):
if self.reports_position and "position" not in payload_dict:
_LOGGER.warning(
"Missing required `position` attribute in json payload "
"on topic '%s', got: %s",
msg.topic,
payload,
)
return
if not self.reports_position and "state" not in payload_dict:
_LOGGER.warning(
"Missing required `state` attribute in json payload "
" on topic '%s', got: %s",
msg.topic,
payload,
)
return
position_payload = payload_dict.get("position")
state_payload = payload_dict.get("state")
if self._config[CONF_REPORTS_POSITION]:
self._process_position_valve_update(msg, position_payload, state_payload)
else:
self._process_binary_valve_update(msg, state_payload)
@callback
@override
def _prepare_subscribe_topics(self) -> None:
"""(Re)Subscribe to topics."""
self.add_subscription(
CONF_STATE_TOPIC,
self._state_message_received,
{
"_attr_current_valve_position",
"_attr_is_closed",
"_attr_is_closing",
"_attr_is_opening",
},
)
@override
async def _subscribe_topics(self) -> None:
"""(Re)Subscribe to topics."""
subscription.async_subscribe_topics_internal(self.hass, self._sub_state)
@override
async def async_open_valve(self) -> None:
"""Move the valve up.
This method is a coroutine.
"""
payload = self._command_template(
self._config.get(CONF_PAYLOAD_OPEN, DEFAULT_PAYLOAD_OPEN)
)
await self.async_publish_with_config(self._config[CONF_COMMAND_TOPIC], payload)
if self._optimistic:
# Optimistically assume that valve has changed state.
self._update_state(ValveState.OPEN)
self.async_write_ha_state()
@override
async def async_close_valve(self) -> None:
"""Move the valve down.
This method is a coroutine.
"""
payload = self._command_template(
self._config.get(CONF_PAYLOAD_CLOSE, DEFAULT_PAYLOAD_CLOSE)
)
await self.async_publish_with_config(self._config[CONF_COMMAND_TOPIC], payload)
if self._optimistic:
# Optimistically assume that valve has changed state.
self._update_state(ValveState.CLOSED)
self.async_write_ha_state()
@override
async def async_stop_valve(self) -> None:
"""Stop valve positioning.
This method is a coroutine.
"""
payload = self._command_template(self._config[CONF_PAYLOAD_STOP])
await self.async_publish_with_config(self._config[CONF_COMMAND_TOPIC], payload)
@override
async def async_set_valve_position(self, position: int) -> None:
"""Move the valve to a specific position."""
percentage_position = position
scaled_position = round(
percentage_to_ranged_value(self._range, percentage_position)
)
variables = {
"position": percentage_position,
"position_open": self._config[CONF_POSITION_OPEN],
"position_closed": self._config[CONF_POSITION_CLOSED],
}
rendered_position = self._command_template(scaled_position, variables=variables)
await self.async_publish_with_config(
self._config[CONF_COMMAND_TOPIC], rendered_position
)
if self._optimistic:
self._update_state(
ValveState.CLOSED
if percentage_position == self._config[CONF_POSITION_CLOSED]
else ValveState.OPEN
)
self._attr_current_valve_position = percentage_position
self.async_write_ha_state()
+361
View File
@@ -0,0 +1,361 @@
"""Support for MQTT water heater devices."""
import logging
from typing import TYPE_CHECKING, Any, override
import probatio
from homeassistant.components import water_heater
from homeassistant.components.water_heater import (
ATTR_OPERATION_MODE,
DEFAULT_MIN_TEMP,
STATE_ECO,
STATE_ELECTRIC,
STATE_GAS,
STATE_HEAT_PUMP,
STATE_HIGH_DEMAND,
STATE_PERFORMANCE,
WaterHeaterCapabilityAttribute,
WaterHeaterEntity,
WaterHeaterEntityFeature,
WaterHeaterStateAttribute,
)
from homeassistant.config_entries import ConfigEntry
from homeassistant.const import (
ATTR_TEMPERATURE,
CONF_NAME,
CONF_OPTIMISTIC,
CONF_PAYLOAD_OFF,
CONF_PAYLOAD_ON,
CONF_TEMPERATURE_UNIT,
CONF_VALUE_TEMPLATE,
PRECISION_HALVES,
PRECISION_TENTHS,
PRECISION_WHOLE,
STATE_OFF,
UnitOfTemperature,
)
from homeassistant.core import HomeAssistant, callback
from homeassistant.helpers import config_validation as cv
from homeassistant.helpers.entity_platform import AddConfigEntryEntitiesCallback
from homeassistant.helpers.template import Template
from homeassistant.helpers.typing import UNDEFINED, ConfigType, VolSchemaType
from homeassistant.util.unit_conversion import TemperatureConverter
from .climate import MqttTemperatureControlEntity
from .config import DEFAULT_RETAIN, MQTT_BASE_SCHEMA
from .const import (
CONF_CURRENT_TEMP_TEMPLATE,
CONF_CURRENT_TEMP_TOPIC,
CONF_MODE_COMMAND_TEMPLATE,
CONF_MODE_COMMAND_TOPIC,
CONF_MODE_LIST,
CONF_MODE_STATE_TEMPLATE,
CONF_MODE_STATE_TOPIC,
CONF_POWER_COMMAND_TEMPLATE,
CONF_POWER_COMMAND_TOPIC,
CONF_PRECISION,
CONF_RETAIN,
CONF_TEMP_COMMAND_TEMPLATE,
CONF_TEMP_COMMAND_TOPIC,
CONF_TEMP_INITIAL,
CONF_TEMP_MAX,
CONF_TEMP_MIN,
CONF_TEMP_STATE_TEMPLATE,
CONF_TEMP_STATE_TOPIC,
DEFAULT_OPTIMISTIC,
PAYLOAD_NONE,
)
from .entity import async_setup_entity_entry_helper
from .models import MqttCommandTemplate, MqttValueTemplate, ReceiveMessage
from .schemas import MQTT_ENTITY_COMMON_SCHEMA
from .util import valid_publish_topic, valid_subscribe_topic
_LOGGER = logging.getLogger(__name__)
PARALLEL_UPDATES = 0
DEFAULT_NAME = "MQTT Water Heater"
MQTT_WATER_HEATER_ATTRIBUTES_BLOCKED = frozenset(
{
WaterHeaterStateAttribute.CURRENT_TEMPERATURE,
WaterHeaterCapabilityAttribute.MAX_TEMP,
WaterHeaterCapabilityAttribute.MIN_TEMP,
WaterHeaterStateAttribute.TARGET_TEMPERATURE,
WaterHeaterCapabilityAttribute.OPERATION_LIST,
WaterHeaterStateAttribute.OPERATION_MODE,
}
)
VALUE_TEMPLATE_KEYS = (
CONF_CURRENT_TEMP_TEMPLATE,
CONF_MODE_STATE_TEMPLATE,
CONF_TEMP_STATE_TEMPLATE,
)
COMMAND_TEMPLATE_KEYS = {
CONF_MODE_COMMAND_TEMPLATE,
CONF_TEMP_COMMAND_TEMPLATE,
CONF_POWER_COMMAND_TEMPLATE,
}
TOPIC_KEYS = (
CONF_CURRENT_TEMP_TOPIC,
CONF_MODE_COMMAND_TOPIC,
CONF_MODE_STATE_TOPIC,
CONF_POWER_COMMAND_TOPIC,
CONF_TEMP_COMMAND_TOPIC,
CONF_TEMP_STATE_TOPIC,
)
_PLATFORM_SCHEMA_BASE = MQTT_BASE_SCHEMA.extend(
{
probatio.Optional(CONF_CURRENT_TEMP_TEMPLATE): cv.template,
probatio.Optional(CONF_CURRENT_TEMP_TOPIC): valid_subscribe_topic,
probatio.Optional(CONF_MODE_COMMAND_TEMPLATE): cv.template,
probatio.Optional(CONF_MODE_COMMAND_TOPIC): valid_publish_topic,
probatio.Optional(
CONF_MODE_LIST,
default=[
STATE_ECO,
STATE_ELECTRIC,
STATE_GAS,
STATE_HEAT_PUMP,
STATE_HIGH_DEMAND,
STATE_PERFORMANCE,
STATE_OFF,
],
): probatio.EnsureList(),
probatio.Optional(CONF_MODE_STATE_TEMPLATE): cv.template,
probatio.Optional(CONF_MODE_STATE_TOPIC): valid_subscribe_topic,
probatio.Optional(CONF_NAME): probatio.Any(cv.string, None),
probatio.Optional(CONF_OPTIMISTIC, default=DEFAULT_OPTIMISTIC): cv.boolean,
probatio.Optional(CONF_PAYLOAD_ON, default="ON"): cv.string,
probatio.Optional(CONF_PAYLOAD_OFF, default="OFF"): cv.string,
probatio.Optional(CONF_POWER_COMMAND_TOPIC): valid_publish_topic,
probatio.Optional(CONF_POWER_COMMAND_TEMPLATE): cv.template,
probatio.Optional(CONF_PRECISION): probatio.All(
probatio.Coerce(float),
probatio.In([PRECISION_TENTHS, PRECISION_HALVES, PRECISION_WHOLE]),
),
probatio.Optional(CONF_RETAIN, default=DEFAULT_RETAIN): cv.boolean,
probatio.Optional(CONF_TEMP_INITIAL): probatio.Coerce(float),
probatio.Optional(CONF_TEMP_MIN): probatio.Coerce(float),
probatio.Optional(CONF_TEMP_MAX): probatio.Coerce(float),
probatio.Optional(CONF_TEMP_COMMAND_TEMPLATE): cv.template,
probatio.Optional(CONF_TEMP_COMMAND_TOPIC): valid_publish_topic,
probatio.Optional(CONF_TEMP_STATE_TEMPLATE): cv.template,
probatio.Optional(CONF_TEMP_STATE_TOPIC): valid_subscribe_topic,
probatio.Optional(CONF_TEMPERATURE_UNIT): cv.temperature_unit,
probatio.Optional(CONF_VALUE_TEMPLATE): cv.template,
}
).extend(MQTT_ENTITY_COMMON_SCHEMA.schema)
PLATFORM_SCHEMA_MODERN = probatio.All(
_PLATFORM_SCHEMA_BASE,
)
_DISCOVERY_SCHEMA_BASE = _PLATFORM_SCHEMA_BASE.extend({}, extra=probatio.REMOVE_EXTRA)
DISCOVERY_SCHEMA = probatio.All(
_DISCOVERY_SCHEMA_BASE,
)
async def async_setup_entry(
hass: HomeAssistant,
config_entry: ConfigEntry,
async_add_entities: AddConfigEntryEntitiesCallback,
) -> None:
"""Set up MQTT water heater device through YAML and through MQTT discovery."""
async_setup_entity_entry_helper(
hass,
config_entry,
MqttWaterHeater,
water_heater.DOMAIN,
async_add_entities,
DISCOVERY_SCHEMA,
PLATFORM_SCHEMA_MODERN,
)
class MqttWaterHeater(MqttTemperatureControlEntity, WaterHeaterEntity):
"""Representation of an MQTT water heater device."""
_default_name = DEFAULT_NAME
_entity_id_format = water_heater.ENTITY_ID_FORMAT
_attributes_extra_blocked = MQTT_WATER_HEATER_ATTRIBUTES_BLOCKED
_attr_target_temperature_low: float | None = None
_attr_target_temperature_high: float | None = None
@staticmethod
@override
def config_schema() -> VolSchemaType:
"""Return the config schema."""
return DISCOVERY_SCHEMA
@override
def _setup_from_config(self, config: ConfigType) -> None:
"""(Re)Setup the entity."""
self._attr_operation_list = config[CONF_MODE_LIST]
self._attr_temperature_unit = config.get(
CONF_TEMPERATURE_UNIT, self.hass.config.units.temperature_unit
)
if (min_temp := config.get(CONF_TEMP_MIN)) is not None:
self._attr_min_temp = min_temp
if (max_temp := config.get(CONF_TEMP_MAX)) is not None:
self._attr_max_temp = max_temp
if (precision := config.get(CONF_PRECISION)) is not None:
self._attr_precision = precision
self._topic = {key: config.get(key) for key in TOPIC_KEYS}
self._optimistic = config[CONF_OPTIMISTIC]
# Set init temp, if it is missing convert the default to the temperature units
init_temp: float = config.get(
CONF_TEMP_INITIAL,
TemperatureConverter.convert(
DEFAULT_MIN_TEMP,
UnitOfTemperature.FAHRENHEIT,
self.temperature_unit,
),
)
if self._topic[CONF_TEMP_STATE_TOPIC] is None or self._optimistic:
self._attr_target_temperature = init_temp
if self._topic[CONF_MODE_STATE_TOPIC] is None or self._optimistic:
self._attr_current_operation = STATE_OFF
value_templates: dict[str, Template | None] = {
key: config.get(CONF_VALUE_TEMPLATE) for key in VALUE_TEMPLATE_KEYS
}
value_templates.update(
{key: config[key] for key in VALUE_TEMPLATE_KEYS & config.keys()}
)
self._value_templates = {
key: MqttValueTemplate(
template, entity=self
).async_render_with_possible_json_value
for key, template in value_templates.items()
}
self._command_templates = {
key: MqttCommandTemplate(config.get(key), entity=self).async_render
for key in COMMAND_TEMPLATE_KEYS
}
support = WaterHeaterEntityFeature(0)
if (self._topic[CONF_TEMP_STATE_TOPIC] is not None) or (
self._topic[CONF_TEMP_COMMAND_TOPIC] is not None
):
support |= WaterHeaterEntityFeature.TARGET_TEMPERATURE
if (self._topic[CONF_MODE_STATE_TOPIC] is not None) or (
self._topic[CONF_MODE_COMMAND_TOPIC] is not None
):
support |= WaterHeaterEntityFeature.OPERATION_MODE
if self._topic[CONF_POWER_COMMAND_TOPIC] is not None:
support |= WaterHeaterEntityFeature.ON_OFF
self._attr_supported_features = support
@callback
def _handle_current_mode_received(self, msg: ReceiveMessage) -> None:
"""Handle receiving operation mode via MQTT."""
payload = self.render_template(msg, CONF_MODE_STATE_TEMPLATE)
if not payload.strip(): # No output from template, ignore
_LOGGER.debug(
"Ignoring empty payload '%s' for current operation "
"after rendering for topic %s",
payload,
msg.topic,
)
return
if payload == PAYLOAD_NONE:
self._attr_current_operation = None
elif payload not in self._config[CONF_MODE_LIST]:
_LOGGER.warning("Invalid %s mode: %s", CONF_MODE_LIST, payload)
else:
if TYPE_CHECKING:
assert isinstance(payload, str)
self._attr_current_operation = payload
@callback
def _handle_target_temperature_received(self, msg: ReceiveMessage) -> None:
"""Handle receiving the target temperature via MQTT."""
if (
value := self._parse_float_payload(
msg, CONF_TEMP_STATE_TEMPLATE, "target temperature"
)
) is not UNDEFINED:
self._attr_target_temperature = value
@callback
@override
def _prepare_subscribe_topics(self) -> None:
"""(Re)Subscribe to topics."""
self.add_subscription(
CONF_MODE_STATE_TOPIC,
self._handle_current_mode_received,
{"_attr_current_operation"},
)
self.add_subscription(
CONF_CURRENT_TEMP_TOPIC,
self._handle_current_temperature_received,
{"_attr_current_temperature"},
)
self.add_subscription(
CONF_TEMP_STATE_TOPIC,
self._handle_target_temperature_received,
{"_attr_target_temperature"},
)
@override
async def async_set_temperature(self, **kwargs: Any) -> None:
"""Set new target temperature."""
operation_mode: str | None
if (operation_mode := kwargs.get(ATTR_OPERATION_MODE)) is not None:
await self.async_set_operation_mode(operation_mode)
temperature: float = kwargs[ATTR_TEMPERATURE]
mqtt_payload = self._command_templates[CONF_TEMP_COMMAND_TEMPLATE](temperature)
await self._publish(CONF_TEMP_COMMAND_TOPIC, mqtt_payload)
if self._optimistic or self._topic[CONF_TEMP_STATE_TOPIC] is None:
self._attr_target_temperature = temperature
self.async_write_ha_state()
@override
async def async_set_operation_mode(self, operation_mode: str) -> None:
"""Set new operation mode."""
payload = self._command_templates[CONF_MODE_COMMAND_TEMPLATE](operation_mode)
await self._publish(CONF_MODE_COMMAND_TOPIC, payload)
if self._optimistic or self._topic[CONF_MODE_STATE_TOPIC] is None:
self._attr_current_operation = operation_mode
self.async_write_ha_state()
@override
async def async_turn_on(self, **kwargs: Any) -> None:
"""Turn the entity on."""
if CONF_POWER_COMMAND_TOPIC in self._config:
mqtt_payload = self._command_templates[CONF_POWER_COMMAND_TEMPLATE](
self._config[CONF_PAYLOAD_ON]
)
await self._publish(CONF_POWER_COMMAND_TOPIC, mqtt_payload)
@override
async def async_turn_off(self, **kwargs: Any) -> None:
"""Turn the entity off."""
if CONF_POWER_COMMAND_TOPIC in self._config:
mqtt_payload = self._command_templates[CONF_POWER_COMMAND_TEMPLATE](
self._config[CONF_PAYLOAD_OFF]
)
await self._publish(CONF_POWER_COMMAND_TOPIC, mqtt_payload)
+3
View File
@@ -0,0 +1,3 @@
{
"name": "Visquitto MQTT"
}