From 7bbb3e5dfd58d81183dfd364520453df56a4f251 Mon Sep 17 00:00:00 2001 From: Saman Sajedi Date: Tue, 3 Nov 2026 15:18:38 +0330 Subject: [PATCH] Initial Visquitto MQTT release --- README.md | 34 + custom_components/vmqtt/README.md | 13 + custom_components/vmqtt/__init__.py | 739 +++ custom_components/vmqtt/abbreviations.py | 299 + custom_components/vmqtt/addon.py | 20 + .../vmqtt/alarm_control_panel.py | 313 + custom_components/vmqtt/async_client.py | 71 + custom_components/vmqtt/binary_sensor.py | 262 + custom_components/vmqtt/button.py | 100 + custom_components/vmqtt/camera.py | 129 + custom_components/vmqtt/client.py | 1540 +++++ custom_components/vmqtt/climate.py | 1012 +++ custom_components/vmqtt/config.py | 46 + custom_components/vmqtt/config_flow.py | 5460 +++++++++++++++++ custom_components/vmqtt/config_integration.py | 40 + custom_components/vmqtt/const.py | 456 ++ custom_components/vmqtt/cover.py | 673 ++ custom_components/vmqtt/date.py | 159 + custom_components/vmqtt/datetime.py | 205 + custom_components/vmqtt/debug_info.py | 260 + custom_components/vmqtt/device_automation.py | 52 + custom_components/vmqtt/device_tracker.py | 225 + custom_components/vmqtt/device_trigger.py | 415 ++ custom_components/vmqtt/diagnostics.py | 128 + custom_components/vmqtt/discovery.py | 733 +++ custom_components/vmqtt/entity.py | 1803 ++++++ custom_components/vmqtt/event.py | 198 + custom_components/vmqtt/fan.py | 572 ++ custom_components/vmqtt/humidifier.py | 487 ++ custom_components/vmqtt/icons.json | 18 + custom_components/vmqtt/image.py | 209 + custom_components/vmqtt/infrared.py | 263 + custom_components/vmqtt/lawn_mower.py | 232 + custom_components/vmqtt/light/__init__.py | 82 + custom_components/vmqtt/light/schema.py | 13 + custom_components/vmqtt/light/schema_basic.py | 889 +++ custom_components/vmqtt/light/schema_json.py | 531 ++ .../vmqtt/light/schema_template.py | 478 ++ custom_components/vmqtt/lock.py | 281 + custom_components/vmqtt/manifest.json | 20 + custom_components/vmqtt/models.py | 560 ++ custom_components/vmqtt/notify.py | 88 + custom_components/vmqtt/number.py | 238 + custom_components/vmqtt/quality_scale.yaml | 133 + custom_components/vmqtt/repairs.py | 71 + custom_components/vmqtt/scene.py | 94 + custom_components/vmqtt/schemas.py | 227 + custom_components/vmqtt/select.py | 168 + custom_components/vmqtt/sensor.py | 408 ++ custom_components/vmqtt/services.yaml | 51 + custom_components/vmqtt/siren.py | 357 ++ custom_components/vmqtt/strings.json | 1428 +++++ custom_components/vmqtt/subscription.py | 167 + custom_components/vmqtt/switch.py | 173 + custom_components/vmqtt/tag.py | 186 + custom_components/vmqtt/text.py | 186 + custom_components/vmqtt/time.py | 159 + custom_components/vmqtt/translations/en.json | 1428 +++++ custom_components/vmqtt/trigger.py | 120 + custom_components/vmqtt/triggers.yaml | 14 + custom_components/vmqtt/update.py | 285 + custom_components/vmqtt/util.py | 460 ++ custom_components/vmqtt/vacuum.py | 428 ++ custom_components/vmqtt/valve.py | 420 ++ custom_components/vmqtt/water_heater.py | 361 ++ hacs.json | 3 + 66 files changed, 27673 insertions(+) create mode 100644 README.md create mode 100644 custom_components/vmqtt/README.md create mode 100644 custom_components/vmqtt/__init__.py create mode 100644 custom_components/vmqtt/abbreviations.py create mode 100644 custom_components/vmqtt/addon.py create mode 100644 custom_components/vmqtt/alarm_control_panel.py create mode 100644 custom_components/vmqtt/async_client.py create mode 100644 custom_components/vmqtt/binary_sensor.py create mode 100644 custom_components/vmqtt/button.py create mode 100644 custom_components/vmqtt/camera.py create mode 100644 custom_components/vmqtt/client.py create mode 100644 custom_components/vmqtt/climate.py create mode 100644 custom_components/vmqtt/config.py create mode 100644 custom_components/vmqtt/config_flow.py create mode 100644 custom_components/vmqtt/config_integration.py create mode 100644 custom_components/vmqtt/const.py create mode 100644 custom_components/vmqtt/cover.py create mode 100644 custom_components/vmqtt/date.py create mode 100644 custom_components/vmqtt/datetime.py create mode 100644 custom_components/vmqtt/debug_info.py create mode 100644 custom_components/vmqtt/device_automation.py create mode 100644 custom_components/vmqtt/device_tracker.py create mode 100644 custom_components/vmqtt/device_trigger.py create mode 100644 custom_components/vmqtt/diagnostics.py create mode 100644 custom_components/vmqtt/discovery.py create mode 100644 custom_components/vmqtt/entity.py create mode 100644 custom_components/vmqtt/event.py create mode 100644 custom_components/vmqtt/fan.py create mode 100644 custom_components/vmqtt/humidifier.py create mode 100644 custom_components/vmqtt/icons.json create mode 100644 custom_components/vmqtt/image.py create mode 100644 custom_components/vmqtt/infrared.py create mode 100644 custom_components/vmqtt/lawn_mower.py create mode 100644 custom_components/vmqtt/light/__init__.py create mode 100644 custom_components/vmqtt/light/schema.py create mode 100644 custom_components/vmqtt/light/schema_basic.py create mode 100644 custom_components/vmqtt/light/schema_json.py create mode 100644 custom_components/vmqtt/light/schema_template.py create mode 100644 custom_components/vmqtt/lock.py create mode 100644 custom_components/vmqtt/manifest.json create mode 100644 custom_components/vmqtt/models.py create mode 100644 custom_components/vmqtt/notify.py create mode 100644 custom_components/vmqtt/number.py create mode 100644 custom_components/vmqtt/quality_scale.yaml create mode 100644 custom_components/vmqtt/repairs.py create mode 100644 custom_components/vmqtt/scene.py create mode 100644 custom_components/vmqtt/schemas.py create mode 100644 custom_components/vmqtt/select.py create mode 100644 custom_components/vmqtt/sensor.py create mode 100644 custom_components/vmqtt/services.yaml create mode 100644 custom_components/vmqtt/siren.py create mode 100644 custom_components/vmqtt/strings.json create mode 100644 custom_components/vmqtt/subscription.py create mode 100644 custom_components/vmqtt/switch.py create mode 100644 custom_components/vmqtt/tag.py create mode 100644 custom_components/vmqtt/text.py create mode 100644 custom_components/vmqtt/time.py create mode 100644 custom_components/vmqtt/translations/en.json create mode 100644 custom_components/vmqtt/trigger.py create mode 100644 custom_components/vmqtt/triggers.yaml create mode 100644 custom_components/vmqtt/update.py create mode 100644 custom_components/vmqtt/util.py create mode 100644 custom_components/vmqtt/vacuum.py create mode 100644 custom_components/vmqtt/valve.py create mode 100644 custom_components/vmqtt/water_heater.py create mode 100644 hacs.json diff --git a/README.md b/README.md new file mode 100644 index 0000000..af9f5f2 --- /dev/null +++ b/README.md @@ -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. + diff --git a/custom_components/vmqtt/README.md b/custom_components/vmqtt/README.md new file mode 100644 index 0000000..675a347 --- /dev/null +++ b/custom_components/vmqtt/README.md @@ -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. diff --git a/custom_components/vmqtt/__init__.py b/custom_components/vmqtt/__init__.py new file mode 100644 index 0000000..c2708b6 --- /dev/null +++ b/custom_components/vmqtt/__init__.py @@ -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 diff --git a/custom_components/vmqtt/abbreviations.py b/custom_components/vmqtt/abbreviations.py new file mode 100644 index 0000000..a2249a6 --- /dev/null +++ b/custom_components/vmqtt/abbreviations.py @@ -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", +} diff --git a/custom_components/vmqtt/addon.py b/custom_components/vmqtt/addon.py new file mode 100644 index 0000000..1485000 --- /dev/null +++ b/custom_components/vmqtt/addon.py @@ -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) diff --git a/custom_components/vmqtt/alarm_control_panel.py b/custom_components/vmqtt/alarm_control_panel.py new file mode 100644 index 0000000..4d3dbb1 --- /dev/null +++ b/custom_components/vmqtt/alarm_control_panel.py @@ -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 diff --git a/custom_components/vmqtt/async_client.py b/custom_components/vmqtt/async_client.py new file mode 100644 index 0000000..38f0dcc --- /dev/null +++ b/custom_components/vmqtt/async_client.py @@ -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] diff --git a/custom_components/vmqtt/binary_sensor.py b/custom_components/vmqtt/binary_sensor.py new file mode 100644 index 0000000..9de17c2 --- /dev/null +++ b/custom_components/vmqtt/binary_sensor.py @@ -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 + ) diff --git a/custom_components/vmqtt/button.py b/custom_components/vmqtt/button.py new file mode 100644 index 0000000..6bb5727 --- /dev/null +++ b/custom_components/vmqtt/button.py @@ -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) diff --git a/custom_components/vmqtt/camera.py b/custom_components/vmqtt/camera.py new file mode 100644 index 0000000..3e36188 --- /dev/null +++ b/custom_components/vmqtt/camera.py @@ -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 diff --git a/custom_components/vmqtt/client.py b/custom_components/vmqtt/client.py new file mode 100644 index 0000000..1841de4 --- /dev/null +++ b/custom_components/vmqtt/client.py @@ -0,0 +1,1540 @@ +"""Support for MQTT message handling.""" + +import asyncio +from collections import defaultdict +from collections.abc import AsyncGenerator, Callable, Coroutine, Iterable +import contextlib +from dataclasses import dataclass +from functools import lru_cache, partial +from itertools import chain, groupby +import logging +from operator import attrgetter +import queue +import socket +import ssl +import time +from typing import TYPE_CHECKING, Any +from uuid import uuid4 + +import certifi +import paho.mqtt.client as mqtt +from paho.mqtt.matcher import MQTTMatcher + +from homeassistant.config_entries import ConfigEntry +from homeassistant.const import ( + CONF_CLIENT_ID, + CONF_PASSWORD, + CONF_PORT, + CONF_PROTOCOL, + CONF_USERNAME, + EVENT_HOMEASSISTANT_STOP, +) +from homeassistant.core import ( + CALLBACK_TYPE, + Event, + HassJob, + HassJobType, + HomeAssistant, + callback, + get_hassjob_callable_job_type, +) +from homeassistant.exceptions import HomeAssistantError, ServiceValidationError +from homeassistant.helpers.dispatcher import ( + async_dispatcher_connect, + async_dispatcher_send, +) +from homeassistant.helpers.frame import ReportBehavior, report_usage +from homeassistant.helpers.importlib import async_import_module +from homeassistant.helpers.start import async_at_started +from homeassistant.helpers.typing import ConfigType +from homeassistant.setup import SetupPhases, async_pause_setup +from homeassistant.util.collection import chunked_or_all +from homeassistant.util.logging import catch_log_exception, log_exception + +from .async_client import AsyncMQTTClient +from .const import ( + CONF_BIRTH_MESSAGE, + CONF_BROKER, + CONF_CERTIFICATE, + CONF_CLIENT_CERT, + CONF_CLIENT_KEY, + CONF_KEEPALIVE, + CONF_TLS_INSECURE, + CONF_TRANSPORT, + CONF_WILL_MESSAGE, + CONF_WS_HEADERS, + CONF_WS_PATH, + DEFAULT_BIRTH, + DEFAULT_ENCODING, + DEFAULT_KEEPALIVE, + DEFAULT_PORT, + DEFAULT_QOS, + DEFAULT_TRANSPORT, + DEFAULT_WILL, + DEFAULT_WS_PATH, + DOMAIN, + MQTT_CONNECTION_STATE, + MQTT_PROCESSED_SUBSCRIPTIONS, + PROTOCOL_5, + PROTOCOL_31, + PROTOCOL_311, + TRANSPORT_WEBSOCKETS, +) +from .models import ( + DATA_MQTT, + MessageCallbackType, + MqttData, + PublishMessage, + PublishPayloadType, + ReceiveMessage, +) +from .util import EnsureJobAfterCooldown, get_file_path, mqtt_config_entry_enabled + +_LOGGER = logging.getLogger(__name__) + +MQTT_TIMEOUT = 5 + +MIN_BUFFER_SIZE = 131072 # Minimum buffer size to use if preferred size fails +PREFERRED_BUFFER_SIZE = 8 * 1024 * 1024 # Set receive buffer size to 8MiB + +DISCOVERY_COOLDOWN = 5 +# The initial subscribe cooldown controls how long to wait to group +# subscriptions together. This is to avoid making too many subscribe +# requests in a short period of time. If the number is too low, the +# system will be flooded with subscribe requests. If the number is too +# high, we risk being flooded with responses to the subscribe requests +# which can exceed the receive buffer size of the socket. To mitigate +# this, we increase the receive buffer size of the socket as well. +INITIAL_SUBSCRIBE_COOLDOWN = 0.5 +SUBSCRIBE_COOLDOWN = 0.1 +UNSUBSCRIBE_COOLDOWN = 0.1 +TIMEOUT_ACK = 10 +SUBSCRIBE_TIMEOUT = 10 +RECONNECT_INTERVAL_SECONDS = 10 + +MAX_SUBSCRIBES_PER_CALL = 500 +MAX_UNSUBSCRIBES_PER_CALL = 500 + +MAX_PACKETS_TO_READ = 500 + +type SocketType = socket.socket | ssl.SSLSocket | mqtt._WebsocketWrapper | Any # noqa: SLF001 + +type SubscribePayloadType = str | bytes | bytearray # Only bytes if encoding is None + + +def publish( + hass: HomeAssistant, + topic: str, + payload: PublishPayloadType, + qos: int = 0, + retain: bool = False, + encoding: str | None = DEFAULT_ENCODING, + *, + message_expiry_interval: int | None = None, +) -> None: + """Publish message to a MQTT topic.""" + hass.create_task( + async_publish( + hass, + topic, + payload, + qos, + retain, + encoding, + message_expiry_interval=message_expiry_interval, + ) + ) + + +async def async_publish( + hass: HomeAssistant, + topic: str, + payload: PublishPayloadType, + qos: int = 0, + retain: bool = False, + encoding: str | None = DEFAULT_ENCODING, + *, + message_expiry_interval: int | None = None, +) -> None: + """Publish message to a MQTT topic.""" + if not mqtt_config_entry_enabled(hass): + raise HomeAssistantError( + translation_key="mqtt_not_setup_cannot_publish", + translation_domain=DOMAIN, + translation_placeholders={"topic": topic}, + ) + mqtt_data = hass.data[DATA_MQTT] + outgoing_payload = payload + if not isinstance(payload, bytes) and payload is not None: + if not encoding: + _LOGGER.error( + ( + "Can't pass-through payload for publishing %s on %s with no" + " encoding set, need 'bytes' got %s" + ), + payload, + topic, + type(payload), + ) + return + outgoing_payload = str(payload) + if encoding != DEFAULT_ENCODING: + # A string is encoded as utf-8 by default, other encoding + # requires bytes as payload + try: + outgoing_payload = outgoing_payload.encode(encoding) + except AttributeError, LookupError, UnicodeEncodeError: + _LOGGER.error( + "Can't encode payload for publishing %s on %s with encoding %s", + payload, + topic, + encoding, + ) + return + + # Passing None for qos or retain args was deprecated. + # Custom integrations should update there code. + # Check for fallback to `None` values can be removed with HA Core 2027.6 + if qos is None or retain is None: + report_usage( # type: ignore[unreachable] + "that calls the MQTT publish API with `None` for qos or retain. " + "The `qos` argument must be an `int`, " + "and the `retain` argument must be a `bool`", + breaks_in_ha_version="2027.6.0", + core_behavior=ReportBehavior.LOG, + exclude_integrations={DOMAIN}, + ) + qos = qos or 0 + retain = retain or False + + await mqtt_data.client.async_publish( + topic, + outgoing_payload, + qos, + retain, + message_expiry_interval=message_expiry_interval, + ) + + +@callback +def async_on_subscribe_done( + hass: HomeAssistant, + topic: str, + qos: int, + on_subscribe_status: CALLBACK_TYPE, +) -> CALLBACK_TYPE: + """Call on_subscribe_done when the matched subscription was completed. + + If a subscription is already present the callback will call + on_subscribe_status directly. + Call the returned callback to stop and cleanup status monitoring. + """ + + async def _sync_mqtt_subscribe(subscriptions: list[tuple[str, int]]) -> None: + if (topic, qos) not in subscriptions: + return + hass.loop.call_soon(on_subscribe_status) + + mqtt_data = hass.data[DATA_MQTT] + if ( + mqtt_data.client.connected + and mqtt_data.client.is_active_subscription(topic) + and not mqtt_data.client.is_pending_subscription(topic) + ): + hass.loop.call_soon(on_subscribe_status) + + return async_dispatcher_connect( + hass, MQTT_PROCESSED_SUBSCRIPTIONS, _sync_mqtt_subscribe + ) + + +async def async_subscribe( + hass: HomeAssistant, + topic: str, + msg_callback: Callable[[ReceiveMessage], Coroutine[Any, Any, None] | None], + qos: int = DEFAULT_QOS, + encoding: str | None = DEFAULT_ENCODING, +) -> CALLBACK_TYPE: + """Subscribe to an MQTT topic. + + Call the return value to unsubscribe. + """ + return async_subscribe_internal(hass, topic, msg_callback, qos, encoding) + + +@callback +def async_subscribe_internal( + hass: HomeAssistant, + topic: str, + msg_callback: Callable[[ReceiveMessage], Coroutine[Any, Any, None] | None], + qos: int = DEFAULT_QOS, + encoding: str | None = DEFAULT_ENCODING, + job_type: HassJobType | None = None, +) -> CALLBACK_TYPE: + """Subscribe to an MQTT topic. + + This function is internal to the MQTT integration + and may change at any time. It should not be considered + a stable API. + + Call the return value to unsubscribe. + """ + try: + mqtt_data = hass.data[DATA_MQTT] + except KeyError as exc: + raise HomeAssistantError( + translation_key="mqtt_not_setup_cannot_subscribe", + translation_domain=DOMAIN, + translation_placeholders={"topic": topic}, + ) from exc + client = mqtt_data.client + if not mqtt_config_entry_enabled(hass): + raise HomeAssistantError( + translation_key="mqtt_not_enabled_cannot_subscribe", + translation_domain=DOMAIN, + translation_placeholders={"topic": topic}, + ) + return client.async_subscribe(topic, msg_callback, qos, encoding, job_type) + + +def subscribe( + hass: HomeAssistant, + topic: str, + msg_callback: MessageCallbackType, + qos: int = DEFAULT_QOS, + encoding: str = "utf-8", +) -> Callable[[], None]: + """Subscribe to an MQTT topic.""" + async_remove = asyncio.run_coroutine_threadsafe( + async_subscribe(hass, topic, msg_callback, qos, encoding), hass.loop + ).result() + + def remove() -> None: + """Remove listener convert.""" + # MQTT messages tend to be high volume, and since they + # come in via a thread and need to be processed in the + # event loop, we want to avoid hass.add_job since most + # of the time is spent calling inspect to figure out + # how to run the callback. + hass.loop.call_soon_threadsafe(async_remove) + + return remove + + +@dataclass(slots=True, frozen=True) +class Subscription: + """Class to hold data about an active subscription.""" + + topic: str + is_simple_match: bool + complex_matcher: Callable[[str], bool] | None + job: HassJob[[ReceiveMessage], Coroutine[Any, Any, None] | None] + qos: int + encoding: str | None + subscription_id: int + + +class MqttClientSetup: + """Helper class to setup the paho mqtt client from config.""" + + _client: AsyncMQTTClient + + def __init__(self, config: ConfigType) -> None: + """Initialize the MQTT client setup helper. + + self.setup must be run in an executor job. + """ + + self._config = config + + def setup(self) -> None: + """Set up the MQTT client. + + The setup of the MQTT client should be run in an executor job, + because it accesses files, so it does IO. + """ + config = self._config + clean_session: bool | None = None + # If no protocol setting is set in the config entry data + # we assume the config was migrated from YAML, and the + # protocol version is defaulting to legacy version 3.1.1. + if (protocol := config.get(CONF_PROTOCOL, PROTOCOL_311)) == PROTOCOL_31: + proto = mqtt.MQTTv31 + clean_session = True + elif protocol == PROTOCOL_5: + proto = mqtt.MQTTv5 + else: + proto = mqtt.MQTTv311 + clean_session = True + + if (client_id := config.get(CONF_CLIENT_ID)) is None: + # PAHO MQTT relies on the MQTT server to generate random client ID + # for protocol version 3.1, however, that feature is not mandatory + # so we generate our own. + client_id = mqtt._base62(uuid4().int, padding=22) # noqa: SLF001 + transport: str = config.get(CONF_TRANSPORT, DEFAULT_TRANSPORT) + self._client = AsyncMQTTClient( + callback_api_version=mqtt.CallbackAPIVersion.VERSION2, + client_id=client_id, + # See: https://eclipse.dev/paho/files/paho.mqtt.python/html/client.html + # clean_session (bool defaults to None) + # a boolean that determines the client type. + # If True, the broker will remove all information about this client when it + # disconnects. If False, the client is a persistent client and subscription + # information and queued messages will be retained when the client + # disconnects. Note that a client will never discard its own outgoing + # messages on disconnect. Calling connect() or reconnect() will cause the + # messages to be resent. Use reinitialise() to reset a client to its + # original state. The clean_session argument only applies to MQTT versions + # v3.1.1 and v3.1. It is not accepted if the MQTT version is v5.0 - use the + # clean_start argument on connect() instead. + clean_session=clean_session, + protocol=proto, + transport=transport, # type: ignore[arg-type] + reconnect_on_failure=False, + ) + self._client.setup() + + # Enable logging + self._client.enable_logger() + + username: str | None = config.get(CONF_USERNAME) + password: str | None = config.get(CONF_PASSWORD) + if username is not None: + self._client.username_pw_set(username, password) + + if ( + certificate := get_file_path(CONF_CERTIFICATE, config.get(CONF_CERTIFICATE)) + ) == "auto": + certificate = certifi.where() + + client_key = get_file_path(CONF_CLIENT_KEY, config.get(CONF_CLIENT_KEY)) + client_cert = get_file_path(CONF_CLIENT_CERT, config.get(CONF_CLIENT_CERT)) + tls_insecure = config.get(CONF_TLS_INSECURE) + if transport == TRANSPORT_WEBSOCKETS: + ws_path: str = config.get(CONF_WS_PATH, DEFAULT_WS_PATH) + ws_headers: dict[str, str] = config.get(CONF_WS_HEADERS, {}) + self._client.ws_set_options(ws_path, ws_headers) + if certificate is not None: + self._client.tls_set( + certificate, + certfile=client_cert, + keyfile=client_key, + tls_version=ssl.PROTOCOL_TLS_CLIENT, + ) + + if tls_insecure is not None: + self._client.tls_insecure_set(tls_insecure) + + @property + def client(self) -> AsyncMQTTClient: + """Return the paho MQTT client.""" + return self._client + + +def try_connection( + user_input: dict[str, Any], +) -> bool: + """Test if we can connect to an MQTT broker.""" + mqtt_client_setup = MqttClientSetup(user_input) + mqtt_client_setup.setup() + client = mqtt_client_setup.client + + result: queue.Queue[bool] = queue.Queue(maxsize=1) + + def on_connect( + _mqttc: mqtt.Client, + _userdata: None, + _connect_flags: mqtt.ConnectFlags, + reason_code: mqtt.ReasonCode, + _properties: mqtt.Properties | None = None, + ) -> None: + """Handle connection result.""" + result.put(not reason_code.is_failure) + + client.on_connect = on_connect + + client.connect_async(user_input[CONF_BROKER], user_input[CONF_PORT]) + client.loop_start() + + try: + return result.get(timeout=MQTT_TIMEOUT) + except queue.Empty: + return False + finally: + client.disconnect() + client.loop_stop() + + +class MQTT: + """Home Assistant MQTT client.""" + + _mqttc: AsyncMQTTClient + _last_subscribe: float + _mqtt_data: MqttData + _supports_subscription_identifiers: bool = False + + def __init__( + self, hass: HomeAssistant, config_entry: ConfigEntry, conf: ConfigType + ) -> None: + """Initialize Home Assistant MQTT client.""" + self.hass = hass + self.loop = hass.loop + self.config_entry = config_entry + self.conf = conf + # If no protocol setting is set in the config entry data + # we assume the config was migrated from YAML, and the + # protocol version is defaulting to legacy version 3.1.1. + self.is_mqttv5 = conf.get(CONF_PROTOCOL, PROTOCOL_311) == PROTOCOL_5 + + self._simple_subscriptions: defaultdict[str, set[Subscription]] = defaultdict( + set + ) + # To ensure the wildcard subscriptions order is preserved, we use a dict + # with `None` values instead of a set. + self._wildcard_subscriptions: dict[Subscription, None] = {} + # _retained_topics prevents a Subscription from receiving a + # retained message more than once per topic. This prevents flooding + # already active subscribers when new subscribers subscribe to a topic + # which has subscribed messages. + self._retained_topics: defaultdict[Subscription, set[str]] = defaultdict(set) + self.connected = False + self._ha_started = asyncio.Event() + self._cleanup_on_unload: list[Callable[[], None]] = [] + + self._connection_lock = asyncio.Lock() + self._pending_operations: dict[int, asyncio.Future[None]] = {} + self._subscribe_debouncer = EnsureJobAfterCooldown( + INITIAL_SUBSCRIBE_COOLDOWN, self._async_perform_subscriptions + ) + self._misc_timer: asyncio.TimerHandle | None = None + self._reconnect_task: asyncio.Task | None = None + self._should_reconnect: bool = True + self._available_future: asyncio.Future[bool] | None = None + + self._max_qos: defaultdict[str, int] = defaultdict(int) # topic, max qos + self._pending_subscriptions: dict[str, int] = {} # topic, qos + self._unsubscribe_debouncer = EnsureJobAfterCooldown( + UNSUBSCRIBE_COOLDOWN, self._async_perform_unsubscribes + ) + self._pending_unsubscribes: set[str] = set() # topic + self._cleanup_on_unload.extend( + ( + async_at_started(hass, self._async_ha_started), + hass.bus.async_listen(EVENT_HOMEASSISTANT_STOP, self._async_ha_stop), + ) + ) + self._socket_buffersize: int | None = None + + @callback + def _async_ha_started(self, _hass: HomeAssistant) -> None: + """Handle HA started.""" + self._ha_started.set() + + async def _async_ha_stop(self, _event: Event) -> None: + """Handle HA stop.""" + await self.async_disconnect() + + async def async_start( + self, + mqtt_data: MqttData, + ) -> None: + """Start Home Assistant MQTT client.""" + self._mqtt_data = mqtt_data + await self.async_init_client() + + @property + def subscriptions(self) -> set[Subscription]: + """Return the tracked subscriptions.""" + return { + *chain.from_iterable(self._simple_subscriptions.values()), + *self._wildcard_subscriptions, + } + + def cleanup(self) -> None: + """Clean up listeners.""" + while self._cleanup_on_unload: + self._cleanup_on_unload.pop()() + + @contextlib.asynccontextmanager + async def _async_connect_in_executor(self) -> AsyncGenerator[None]: + # While we are connecting in the executor we need to + # handle on_socket_open and on_socket_register_write + # in the executor as well. + mqttc = self._mqttc + try: + mqttc.on_socket_open = self._on_socket_open + mqttc.on_socket_register_write = self._on_socket_register_write + yield + finally: + # Once the executor job is done, we can switch back to + # handling these in the event loop. + mqttc.on_socket_open = self._async_on_socket_open + mqttc.on_socket_register_write = self._async_on_socket_register_write + + async def async_init_client(self) -> None: + """Initialize paho client.""" + with async_pause_setup(self.hass, SetupPhases.WAIT_IMPORT_PACKAGES): + await async_import_module( + self.hass, "custom_components.vmqtt.async_client" + ) + + mqttc_setup = MqttClientSetup(self.conf) + await self.hass.async_add_executor_job(mqttc_setup.setup) + mqttc = mqttc_setup.client + # on_socket_unregister_write and _async_on_socket_close + # are only ever called in the event loop + mqttc.on_socket_close = self._async_on_socket_close + mqttc.on_socket_unregister_write = self._async_on_socket_unregister_write + + # These will be called in the event loop + mqttc.on_connect = self._async_mqtt_on_connect + mqttc.on_disconnect = self._async_mqtt_on_disconnect + mqttc.on_message = self._async_mqtt_on_message + mqttc.on_publish = self._async_mqtt_on_publish + mqttc.on_subscribe = self._async_mqtt_on_subscribe_unsubscribe + mqttc.on_unsubscribe = self._async_mqtt_on_subscribe_unsubscribe + + # suppress exceptions at callback + mqttc.suppress_exceptions = True + + if will := self.conf.get(CONF_WILL_MESSAGE, DEFAULT_WILL): + will_message = PublishMessage(**will) + mqttc.will_set( + topic=will_message.topic, + payload=will_message.payload, + qos=will_message.qos, + retain=will_message.retain, + ) + + self._mqttc = mqttc + + @callback + def _async_reader_callback(self, client: mqtt.Client) -> None: + """Handle reading data from the socket.""" + if (status := client.loop_read(MAX_PACKETS_TO_READ)) != 0: + self._async_handle_callback_exception(status) + + @callback + def _async_start_misc_periodic(self) -> None: + """Start the misc periodic.""" + assert self._misc_timer is None, "Misc periodic already started" + _LOGGER.debug("%s: Starting client misc loop", self.config_entry.title) + + # Inner function to avoid having to check late import + # each time the function is called. + @callback + def _async_misc() -> None: + """Start the MQTT client misc loop.""" + if self._mqttc.loop_misc() == mqtt.MQTT_ERR_SUCCESS: + self._misc_timer = self.loop.call_at(self.loop.time() + 1, _async_misc) + + self._misc_timer = self.loop.call_at(self.loop.time() + 1, _async_misc) + + def _increase_socket_buffer_size(self, sock: SocketType) -> None: + """Increase the socket buffer size.""" + if not hasattr(sock, "setsockopt") and hasattr(sock, "_socket"): + # The WebsocketWrapper does not wrap setsockopt + # so we need to get the underlying socket + # Remove this once + # https://github.com/eclipse/paho.mqtt.python/pull/843 + # is available. + sock = sock._socket # noqa: SLF001 + + new_buffer_size = PREFERRED_BUFFER_SIZE + while True: + try: + # Some operating systems do not allow us to set the preferred + # buffer size. In that case we try some other size options. + sock.setsockopt(socket.SOL_SOCKET, socket.SO_RCVBUF, new_buffer_size) # type: ignore[union-attr] + except OSError as err: + if new_buffer_size <= MIN_BUFFER_SIZE: + _LOGGER.warning( + "Unable to increase the socket buffer size to %s; " + "The connection may be unstable if the MQTT broker " + "sends data at volume or a large amount of subscriptions " + "need to be processed: %s", + new_buffer_size, + err, + ) + return + new_buffer_size //= 2 + else: + return + + def _on_socket_open( + self, client: mqtt.Client, userdata: Any, sock: SocketType + ) -> None: + """Handle socket open.""" + self.loop.call_soon_threadsafe( + self._async_on_socket_open, client, userdata, sock + ) + + @callback + def _async_on_socket_open( + self, client: mqtt.Client, userdata: Any, sock: SocketType + ) -> None: + """Handle socket open.""" + fileno = sock.fileno() + _LOGGER.debug("%s: connection opened %s", self.config_entry.title, fileno) + if fileno > -1: + self._increase_socket_buffer_size(sock) + self.loop.add_reader(sock, partial(self._async_reader_callback, client)) + if not self._misc_timer: + self._async_start_misc_periodic() + # Try to consume the buffer right away so it doesn't fill up + # since add_reader will wait for the next loop iteration + self._async_reader_callback(client) + + @callback + def _async_on_socket_close( + self, client: mqtt.Client, userdata: Any, sock: SocketType + ) -> None: + """Handle socket close.""" + fileno = sock.fileno() + _LOGGER.debug("%s: connection closed %s", self.config_entry.title, fileno) + # If socket close is called before the connect + # result is set make sure the first connection result is set + self._async_connection_result(False) + if fileno > -1: + self.loop.remove_reader(sock) + if self._misc_timer: + self._misc_timer.cancel() + self._misc_timer = None + + @callback + def _async_writer_callback(self, client: mqtt.Client) -> None: + """Handle writing data to the socket.""" + if (status := client.loop_write()) != 0: + self._async_handle_callback_exception(status) + + def _on_socket_register_write( + self, client: mqtt.Client, userdata: Any, sock: SocketType + ) -> None: + """Register the socket for writing.""" + self.loop.call_soon_threadsafe( + self._async_on_socket_register_write, client, None, sock + ) + + @callback + def _async_on_socket_register_write( + self, client: mqtt.Client, userdata: Any, sock: SocketType + ) -> None: + """Register the socket for writing.""" + fileno = sock.fileno() + _LOGGER.debug("%s: register write %s", self.config_entry.title, fileno) + if fileno > -1: + self.loop.add_writer(sock, partial(self._async_writer_callback, client)) + + @callback + def _async_on_socket_unregister_write( + self, client: mqtt.Client, userdata: Any, sock: SocketType + ) -> None: + """Unregister the socket for writing.""" + fileno = sock.fileno() + _LOGGER.debug("%s: unregister write %s", self.config_entry.title, fileno) + if fileno > -1: + self.loop.remove_writer(sock) + + def is_active_subscription(self, topic: str) -> bool: + """Check if a topic has an active subscription.""" + return topic in self._simple_subscriptions or any( + other.topic == topic for other in self._wildcard_subscriptions + ) + + def is_pending_subscription(self, topic: str) -> bool: + """Check if a topic has a pending subscription.""" + return topic in self._pending_subscriptions + + async def async_publish( + self, + topic: str, + payload: PublishPayloadType, + qos: int, + retain: bool, + *, + message_expiry_interval: int | None = None, + ) -> None: + """Publish a MQTT message.""" + properties = mqtt.Properties(mqtt.PacketTypes.PUBLISH) # type: ignore[no-untyped-call] + if message_expiry_interval is not None: + if not self.is_mqttv5: + raise ServiceValidationError( + translation_domain=DOMAIN, + translation_key="mqtt_message_expiry_interval_not_supported", + translation_placeholders={ + "topic": topic, + "protocol": self.conf.get(CONF_PROTOCOL, PROTOCOL_311), + }, + ) + properties.MessageExpiryInterval = message_expiry_interval + msg_info = self._mqttc.publish(topic, payload, qos, retain, properties) + _LOGGER.debug( + "Transmitting%s message on %s: '%s', mid: %s, qos: %s," + " message_expiry_interval: %s", + " retained" if retain else "", + topic, + payload, + msg_info.mid, + qos, + message_expiry_interval, + ) + await self._async_wait_for_mid_or_raise(msg_info.mid, msg_info.rc) + + async def async_connect(self, client_available: asyncio.Future[bool]) -> None: + """Connect to the host. Does not process messages yet.""" + + result: int | None = None + self._available_future = client_available + self._should_reconnect = True + connect_partial = partial( + self._mqttc.connect, + host=self.conf[CONF_BROKER], + port=self.conf.get(CONF_PORT, DEFAULT_PORT), + keepalive=self.conf.get(CONF_KEEPALIVE, DEFAULT_KEEPALIVE), + # See: + # https://eclipse.dev/paho/files/paho.mqtt.python/html/client.html + # `clean_start` (bool) - (MQTT v5.0 only) `True`, `False` or + # `MQTT_CLEAN_START_FIRST_ONLY`. Sets the MQTT v5.0 clean_start flag + # always, never or on the first successful connect only, + # respectively. MQTT session data (such as outstanding messages and + # subscriptions) is cleared on successful connect when the + # clean_start flag is set. For MQTT v3.1.1, the clean_session + # argument of Client should be used for similar result. + clean_start=True if self.is_mqttv5 else mqtt.MQTT_CLEAN_START_FIRST_ONLY, + ) + try: + async with self._connection_lock, self._async_connect_in_executor(): + result = await self.hass.async_add_executor_job(connect_partial) + except (OSError, mqtt.WebsocketConnectionError) as err: + _LOGGER.error("Failed to connect to MQTT server due to exception: %s", err) + self._async_connection_result(False) + finally: + if result is not None and result != 0: + if result is not None: + _LOGGER.error( + "Failed to connect to MQTT server: %s", + mqtt.error_string(result), + ) + self._async_connection_result(False) + + @callback + def _async_connection_result(self, connected: bool) -> None: + """Handle a connection result.""" + if self._available_future and not self._available_future.done(): + self._available_future.set_result(connected) + + if connected: + self._async_cancel_reconnect() + elif self._should_reconnect and not self._reconnect_task: + self._reconnect_task = self.config_entry.async_create_background_task( + self.hass, self._reconnect_loop(), "mqtt reconnect loop" + ) + + @callback + def _async_cancel_reconnect(self) -> None: + """Cancel the reconnect task.""" + if self._reconnect_task: + self._reconnect_task.cancel() + self._reconnect_task = None + + async def _reconnect_loop(self) -> None: + """Reconnect to the MQTT server.""" + + while True: + if not self.connected: + try: + async with self._connection_lock, self._async_connect_in_executor(): + await self.hass.async_add_executor_job(self._mqttc.reconnect) + except (OSError, mqtt.WebsocketConnectionError) as err: + _LOGGER.debug( + "Error re-connecting to MQTT server due to exception: %s", err + ) + + await asyncio.sleep(RECONNECT_INTERVAL_SECONDS) + + async def async_disconnect(self, disconnect_paho_client: bool = False) -> None: + """Stop the MQTT client. + + We only disconnect grafully if disconnect_paho_client is set, but not + when Home Assistant is shut down. + """ + + # stop waiting for any pending subscriptions + await self._subscribe_debouncer.async_cleanup() + # reset timeout to initial subscribe cooldown + self._subscribe_debouncer.set_timeout(INITIAL_SUBSCRIBE_COOLDOWN) + # stop the unsubscribe debouncer + await self._unsubscribe_debouncer.async_cleanup() + # make sure the unsubscribes are processed + await self._async_perform_unsubscribes() + + # wait for ACKs to be processed + if pending := self._pending_operations.values(): + await asyncio.wait(pending) + + # stop the MQTT loop + async with self._connection_lock: + self._should_reconnect = False + self._async_cancel_reconnect() + # We do not gracefully disconnect to ensure + # the broker publishes the will message unless the entry is reloaded + if disconnect_paho_client: + self._mqttc.disconnect() + + @callback + def async_restore_tracked_subscriptions( + self, subscriptions: set[Subscription] + ) -> None: + """Restore tracked subscriptions after reload.""" + for subscription in subscriptions: + subscription_id = ( + 1 + if subscription.is_simple_match + else self._mqtt_data.subscription_id_generator.get_subscription_id( + subscription.topic + ) + ) + self._async_track_subscription( + Subscription( + subscription.topic, + subscription.is_simple_match, + subscription.complex_matcher, + subscription.job, + subscription.qos, + subscription.encoding, + subscription_id, + ) + ) + self._matching_subscriptions.cache_clear() + + @callback + def _async_track_subscription(self, subscription: Subscription) -> None: + """Track a subscription. + + This method does not send a SUBSCRIBE message to the broker. + + The caller is responsible clearing the cache of _matching_subscriptions. + """ + if subscription.is_simple_match: + self._simple_subscriptions[subscription.topic].add(subscription) + else: + self._wildcard_subscriptions[subscription] = None + + @callback + def _async_untrack_subscription(self, subscription: Subscription) -> None: + """Untrack a subscription. + + This method does not send an UNSUBSCRIBE message to the broker. + + The caller is responsible clearing the cache of _matching_subscriptions. + """ + topic = subscription.topic + try: + if subscription.is_simple_match: + simple_subscriptions = self._simple_subscriptions + simple_subscriptions[topic].remove(subscription) + if not simple_subscriptions[topic]: + del simple_subscriptions[topic] + else: + del self._wildcard_subscriptions[subscription] + except (KeyError, ValueError) as exc: + raise HomeAssistantError( + translation_domain=DOMAIN, + translation_key="mqtt_not_setup_cannot_unsubscribe_twice", + translation_placeholders={"topic": topic}, + ) from exc + + @callback + def _async_queue_subscriptions( + self, subscriptions: Iterable[tuple[str, int]], queue_only: bool = False + ) -> None: + """Queue requested subscriptions.""" + for subscription in subscriptions: + topic, qos = subscription + if (max_qos := self._max_qos[topic]) < qos: + self._max_qos[topic] = (max_qos := qos) + self._pending_subscriptions[topic] = max_qos + # Cancel any pending unsubscribe since we are subscribing now + if topic in self._pending_unsubscribes: + self._pending_unsubscribes.remove(topic) + if queue_only: + return + self._subscribe_debouncer.async_schedule() + + def _exception_message( + self, + msg_callback: Callable[[ReceiveMessage], Coroutine[Any, Any, None] | None], + msg: ReceiveMessage, + ) -> str: + """Return a string with the exception message.""" + # if msg_callback is a partial we return the name of the first argument + if isinstance(msg_callback, partial): + call_back_name = msg_callback.args[0].__name__ + else: + call_back_name = msg_callback.__name__ + return ( + f"Exception in {call_back_name} when handling msg on " + f"'{msg.topic}': '{msg.payload}'" # type: ignore[str-bytes-safe] + ) + + @callback + def async_subscribe( + self, + topic: str, + msg_callback: Callable[[ReceiveMessage], Coroutine[Any, Any, None] | None], + qos: int, + encoding: str | None = None, + job_type: HassJobType | None = None, + ) -> Callable[[], None]: + """Set up a subscription to a topic with the provided qos.""" + if not isinstance(topic, str): + raise HomeAssistantError( + translation_domain=DOMAIN, + translation_key="mqtt_topic_not_a_string", + translation_placeholders={"topic": topic}, + ) + + if job_type is None: + job_type = get_hassjob_callable_job_type(msg_callback) + if job_type is not HassJobType.Callback: + # Only wrap the callback with catch_log_exception + # if it is not a simple callback since we catch + # exceptions for simple callbacks inline for + # performance reasons. + msg_callback = catch_log_exception( + msg_callback, partial(self._exception_message, msg_callback) + ) + + job = HassJob(msg_callback, job_type=job_type) + is_simple_match = not ("+" in topic or "#" in topic) + matcher = None if is_simple_match else _matcher_for_topic(topic) + + if is_simple_match: + subscription_id = 1 + else: + subscription_id = self._mqtt_data.subscription_id_generator.get_or_generate( + topic + ) + + subscription = Subscription( + topic, is_simple_match, matcher, job, qos, encoding, subscription_id + ) + + self._async_track_subscription(subscription) + self._matching_subscriptions.cache_clear() + + # Only subscribe if currently connected. + if self.connected: + self._async_queue_subscriptions(((topic, qos),)) + + return partial(self._async_remove, subscription) + + @callback + def _async_remove(self, subscription: Subscription) -> None: + """Remove subscription.""" + self._async_untrack_subscription(subscription) + self._matching_subscriptions.cache_clear() + if subscription in self._retained_topics: + del self._retained_topics[subscription] + # Only unsubscribe if currently connected + if self.connected: + self._async_unsubscribe(subscription.topic, subscription.subscription_id) + + @callback + def _async_unsubscribe(self, topic: str, subscription_id: int) -> None: + """Unsubscribe from a topic.""" + if self.is_active_subscription(topic): + if self._max_qos[topic] == 0: + return + subs = self._matching_subscriptions(topic, (subscription_id,)) + self._max_qos[topic] = max(sub.qos for sub in subs) + # Other subscriptions on topic remaining - don't unsubscribe. + return + if topic in self._max_qos: + del self._max_qos[topic] + if topic in self._pending_subscriptions: + # Avoid any pending subscription to be executed + del self._pending_subscriptions[topic] + + self._pending_unsubscribes.add(topic) + self._unsubscribe_debouncer.async_schedule() + + async def _async_perform_subscriptions(self) -> None: + """Perform MQTT client subscriptions.""" + # Section 3.3.1.3 in the specification: + # http://docs.oasis-open.org/mqtt/mqtt/v3.1.1/os/mqtt-v3.1.1-os.html + # When sending a PUBLISH Packet to a Client the Server MUST + # set the RETAIN flag to 1 if a message is sent as a result of a + # new subscription being made by a Client [MQTT-3.3.1-8]. + # It MUST set the RETAIN flag to 0 when a PUBLISH Packet is sent to + # a Client because it matches an established subscription regardless + # of how the flag was set in the message it received [MQTT-3.3.1-9]. + # + # Since we do not know if a published value is retained we need to + # (re)subscribe, to ensure retained messages are replayed + if not self._pending_subscriptions: + return + + # Split out the wildcard subscriptions, we subscribe to them one by one + debug_enabled = _LOGGER.isEnabledFor(logging.DEBUG) + pending_subscriptions: dict[str, int] = self._pending_subscriptions + pending_wildcard_subscriptions = { + subscription.topic: pending_subscriptions.pop(subscription.topic) + for subscription in self._wildcard_subscriptions + if subscription.topic in pending_subscriptions + } + subscribe_chain = chunked_or_all( + pending_subscriptions.items(), MAX_SUBSCRIBES_PER_CALL + ) + if self._supports_subscription_identifiers and pending_subscriptions: + bulk_properties = mqtt.Properties(packetType=mqtt.PacketTypes.SUBSCRIBE) # type: ignore[no-untyped-call] + bulk_properties.SubscriptionIdentifier = 1 + else: + bulk_properties = None + + self._pending_subscriptions = {} + + for topic, qos in pending_wildcard_subscriptions.items(): + if self._supports_subscription_identifiers: + properties = mqtt.Properties(packetType=mqtt.PacketTypes.SUBSCRIBE) # type: ignore[no-untyped-call] + properties.SubscriptionIdentifier = ( + self._mqtt_data.subscription_id_generator.get_subscription_id(topic) + ) + else: + properties = None + + result, mid = self._mqttc.subscribe(topic, qos, properties=properties) + if debug_enabled: + _LOGGER.debug( + "Subscribing with mid: %s to topic %s " + "with qos: %s and properties: %s", + mid, + topic, + qos, + properties, + ) + self._last_subscribe = time.monotonic() + + await self._async_wait_for_mid_or_raise(mid, result) + async_dispatcher_send( + self.hass, MQTT_PROCESSED_SUBSCRIPTIONS, [(topic, qos)] + ) + + for chunk in subscribe_chain: + chunk_list = list(chunk) + if not chunk_list: + continue + + result, mid = self._mqttc.subscribe(chunk_list, properties=bulk_properties) + + if debug_enabled: + _LOGGER.debug( + "Subscribing with mid: %s to topics with qos: %s", mid, chunk_list + ) + self._last_subscribe = time.monotonic() + + await self._async_wait_for_mid_or_raise(mid, result) + async_dispatcher_send(self.hass, MQTT_PROCESSED_SUBSCRIPTIONS, chunk_list) + + async def _async_perform_unsubscribes(self) -> None: + """Perform pending MQTT client unsubscribes.""" + if not self._pending_unsubscribes: + return + + topics = list(self._pending_unsubscribes) + self._pending_unsubscribes = set() + debug_enabled = _LOGGER.isEnabledFor(logging.DEBUG) + + for chunk in chunked_or_all(topics, MAX_UNSUBSCRIBES_PER_CALL): + chunk_list = list(chunk) + + result, mid = self._mqttc.unsubscribe(chunk_list) + if debug_enabled: + _LOGGER.debug( + "Unsubscribing with mid: %s to topics: %s", mid, chunk_list + ) + + await self._async_wait_for_mid_or_raise(mid, result) + + # Remove stored subscription identifiers for topics that were just unsubscribed + # Keep the ID if the topic was subscribed again while waiting for the UNSUBACK + for topic in topics: + if not self.is_active_subscription(topic): + self._mqtt_data.subscription_id_generator.release(topic) + + async def _async_resubscribe_and_publish_birth_message( + self, birth_message: PublishMessage + ) -> None: + """Resubscribe to all topics and publish birth message.""" + self._async_queue_resubscribe() + self._subscribe_debouncer.async_schedule() + await self._ha_started.wait() # Wait for Home Assistant to start + await self._discovery_cooldown() # Wait for MQTT discovery to cool down + # Update subscribe cooldown period to a shorter time + # and make sure we flush the debouncer + await self._subscribe_debouncer.async_execute() + self._subscribe_debouncer.set_timeout(SUBSCRIBE_COOLDOWN) + await self.async_publish( + topic=birth_message.topic, + payload=birth_message.payload, + qos=birth_message.qos, + retain=birth_message.retain, + ) + _LOGGER.info("MQTT client initialized, birth message sent") + + @callback + def _async_mqtt_on_connect( + self, + _mqttc: mqtt.Client, + _userdata: None, + _connect_flags: mqtt.ConnectFlags, + reason_code: mqtt.ReasonCode, + properties: mqtt.Properties | None = None, + ) -> None: + """On connect callback. + + Resubscribe to all topics we were subscribed to and publish birth + message. + """ + if self.is_mqttv5: + # Check if the server explicitly disabled Subscription Identifiers + if ( + properties is not None + and hasattr(properties, "SubscriptionIdentifierAvailable") + and properties.SubscriptionIdentifierAvailable == 0 + ): + _LOGGER.warning( + "Your MQTT broker reports it does not support " + "Subscription Identifiers, see " + "https://docs.oasis-open.org/" + "mqtt/mqtt/v5.0/os/mqtt-v5.0-os.html#_Toc3901092. " + "Please use a supported MQTT broker; got broker properties: %s", + properties, + ) + self._supports_subscription_identifiers = False + else: + self._supports_subscription_identifiers = True + else: + self._supports_subscription_identifiers = False + + if reason_code.is_failure: + # 24: Continue authentication + # 25: Re-authenticate + # 134: Bad user name or password + # 135: Not authorized + # 140: Bad authentication method + if reason_code.value in (24, 25, 134, 135, 140): + self._should_reconnect = False + self.hass.async_create_task(self.async_disconnect()) + self.config_entry.async_start_reauth(self.hass) + _LOGGER.error( + "Unable to connect to the MQTT broker: %s", + reason_code.getName(), # type: ignore[no-untyped-call] + ) + self._async_connection_result(False) + return + + self.connected = True + async_dispatcher_send(self.hass, MQTT_CONNECTION_STATE, True) + _LOGGER.debug( + "Connected to MQTT server %s:%s (%s)", + self.conf[CONF_BROKER], + self.conf.get(CONF_PORT, DEFAULT_PORT), + reason_code, + ) + + birth: dict[str, Any] + if birth := self.conf.get(CONF_BIRTH_MESSAGE, DEFAULT_BIRTH): + birth_message = PublishMessage(**birth) + self.config_entry.async_create_background_task( + self.hass, + self._async_resubscribe_and_publish_birth_message(birth_message), + name="mqtt re-subscribe and birth", + ) + else: + # Update subscribe cooldown period to a shorter time + self._async_queue_resubscribe() + self._subscribe_debouncer.async_schedule() + + self._async_connection_result(True) + + @callback + def _async_queue_resubscribe(self) -> None: + """Queue subscriptions on reconnect. + + self._async_perform_subscriptions must be called + after this method to actually subscribe. + """ + self._max_qos.clear() + self._retained_topics.clear() + # Group subscriptions to only re-subscribe once for each topic. + keyfunc = attrgetter("topic") + self._async_queue_subscriptions( + [ + # Re-subscribe with the highest requested qos + (topic, max(subscription.qos for subscription in subs)) + for topic, subs in groupby( + sorted(self.subscriptions, key=keyfunc), keyfunc + ) + ], + queue_only=True, + ) + + @lru_cache(None) # pylint: disable=method-cache-max-size-none + def _matching_subscriptions( + self, topic: str, identifiers: tuple[int, ...] | None + ) -> list[Subscription]: + subscriptions: list[Subscription] = [] + if topic in self._simple_subscriptions and ( + identifiers is None or 1 in identifiers + ): + # The subscription identifier is always 1 for simple subscriptions, + # so only include them when no identifiers are provided or 1 matches. + subscriptions.extend(self._simple_subscriptions[topic]) + subscriptions.extend( + subscription + for subscription in self._wildcard_subscriptions + # mypy doesn't know that complex_matcher is always set when + # is_simple_match is False + if subscription.complex_matcher(topic) # type: ignore[misc] + and (identifiers is None or subscription.subscription_id in identifiers) + ) + return subscriptions + + @callback + def _async_mqtt_on_message( + self, _mqttc: mqtt.Client, _userdata: None, msg: mqtt.MQTTMessage + ) -> None: + identifiers: tuple[int, ...] | None = None + if self._supports_subscription_identifiers: + # It is possible we have multiple messages if there + # are overlapping wildcard subscriptions. + # So we assigned all wildcard subscriptions with a + # unique SubscriptionIdentifier. Simple subscriptions are assigned + # with SubscriptionIdentifier 1. + if TYPE_CHECKING: + assert msg.properties is not None + assert hasattr(msg.properties, "SubscriptionIdentifier") + with contextlib.suppress(AttributeError): + identifiers = tuple(msg.properties.SubscriptionIdentifier) + try: + # msg.topic is a property that decodes the topic to a string + # every time it is accessed. Save the result to avoid + # decoding the same topic multiple times. + topic = msg.topic + except UnicodeDecodeError: + bare_topic: bytes = msg._topic # noqa: SLF001 + _LOGGER.warning( + "Skipping received%s message on invalid topic %s (qos=%s): %s", + " retained" if msg.retain else "", + bare_topic, + msg.qos, + msg.payload[0:8192], + ) + return + if _LOGGER.isEnabledFor(logging.DEBUG): + # Guard the debug log so the payload is not sliced (copied) on + # every received message when debug logging is disabled. + _LOGGER.debug( + "Received%s message on %s (qos=%s) IDs=%s: %s", + " retained" if msg.retain else "", + topic, + msg.qos, + identifiers, + msg.payload[0:8192], + ) + msg_cache_by_subscription_topic: dict[str, ReceiveMessage] = {} + + for subscription in self._matching_subscriptions(topic, identifiers): + if msg.retain: + retained_topics = self._retained_topics[subscription] + # Skip if the subscription already received a retained message + if topic in retained_topics: + continue + # Remember the subscription had an initial retained message + self._retained_topics[subscription].add(topic) + + payload: SubscribePayloadType = msg.payload + if subscription.encoding is not None: + try: + payload = msg.payload.decode(subscription.encoding) + except AttributeError, UnicodeDecodeError: + _LOGGER.warning( + "Can't decode payload %s on %s with encoding %s (for %s)", + msg.payload[0:8192], + topic, + subscription.encoding, + subscription.job, + ) + continue + subscription_topic = subscription.topic + if subscription_topic not in msg_cache_by_subscription_topic: + # Only make one copy of the message + # per topic so we avoid storing a separate + # dataclass in memory for each subscriber + # to the same topic for retained messages + receive_msg = ReceiveMessage( + topic, + payload, + msg.qos, + msg.retain, + subscription_topic, + msg.timestamp, + ) + msg_cache_by_subscription_topic[subscription_topic] = receive_msg + else: + receive_msg = msg_cache_by_subscription_topic[subscription_topic] + job = subscription.job + if job.job_type is HassJobType.Callback: + # We do not wrap Callback jobs in catch_log_exception since + # its expensive and we have to do it 2x for every entity + try: + job.target(receive_msg) + except Exception: # noqa: BLE001 + log_exception( + partial(self._exception_message, job.target, receive_msg) + ) + else: + self.hass.async_run_hass_job(job, receive_msg) + self._mqtt_data.state_write_requests.process_write_state_requests(msg) + + @callback + def _async_mqtt_on_publish( + self, + _mqttc: mqtt.Client, + _userdata: None, + mid: int, + _reason_code: mqtt.ReasonCode, + _properties: mqtt.Properties | None, + ) -> None: + """Publish callback.""" + self._async_mqtt_on_callback(mid) + + @callback + def _async_mqtt_on_subscribe_unsubscribe( + self, + _mqttc: mqtt.Client, + _userdata: None, + mid: int, + _reason_code: list[mqtt.ReasonCode], + _properties: mqtt.Properties | None, + ) -> None: + """Subscribe / Unsubscribe callback.""" + self._async_mqtt_on_callback(mid) + + @callback + def _async_mqtt_on_callback(self, mid: int) -> None: + """Publish / Subscribe / Unsubscribe callback.""" + future = self._async_get_mid_future(mid) + if future.done() and (future.cancelled() or future.exception()): + # Timed out or cancelled + return + future.set_result(None) + + @callback + def _async_get_mid_future(self, mid: int) -> asyncio.Future[None]: + """Get the future for a mid.""" + if future := self._pending_operations.get(mid): + return future + future = self.hass.loop.create_future() + self._pending_operations[mid] = future + return future + + @callback + def _async_handle_callback_exception(self, status: mqtt.MQTTErrorCode) -> None: + """Handle a callback exception.""" + + _LOGGER.warning( + "Error returned from MQTT server: %s", + mqtt.error_string(status), + ) + + @callback + def _async_mqtt_on_disconnect( + self, + _mqttc: mqtt.Client, + _userdata: None, + _disconnect_flags: mqtt.DisconnectFlags, + reason_code: mqtt.ReasonCode, + properties: mqtt.Properties | None = None, + ) -> None: + """Disconnected callback.""" + if not self.connected: + # This function is re-entrant and may be called multiple times + # when there is a broken pipe error. + return + # If disconnect is called before the connect + # result is set make sure the first connection result is set + self._async_connection_result(False) + self.connected = False + async_dispatcher_send(self.hass, MQTT_CONNECTION_STATE, False) + _LOGGER.log( + logging.INFO if reason_code == 0 else logging.DEBUG, + "Disconnected from MQTT server %s:%s (%s)", + self.conf[CONF_BROKER], + self.conf.get(CONF_PORT, DEFAULT_PORT), + reason_code, + ) + + @callback + def _async_timeout_mid(self, future: asyncio.Future[None]) -> None: + """Timeout waiting for a mid.""" + if not future.done(): + future.set_exception(asyncio.TimeoutError) + + async def _async_wait_for_mid_or_raise( + self, mid: int | None, result_code: int + ) -> None: + """Wait for ACK from broker or raise on error.""" + if result_code != 0: + raise HomeAssistantError( + translation_domain=DOMAIN, + translation_key="mqtt_broker_error", + translation_placeholders={ + "error_message": mqtt.error_string(result_code) + }, + ) + + # Create the mid event if not created, either _mqtt_handle_mid or + # _async_wait_for_mid_or_raise may be executed first. + if TYPE_CHECKING: + assert mid is not None + future = self._async_get_mid_future(mid) + loop = self.hass.loop + timer_handle = loop.call_later(TIMEOUT_ACK, self._async_timeout_mid, future) + try: + await future + except TimeoutError: + _LOGGER.warning( + "No ACK from MQTT server in %s seconds (mid: %s)", TIMEOUT_ACK, mid + ) + finally: + timer_handle.cancel() + del self._pending_operations[mid] + + async def _discovery_cooldown(self) -> None: + """Wait until all discovery and subscriptions are processed.""" + now = time.monotonic() + # Reset discovery and subscribe cooldowns + self._mqtt_data.last_discovery = now + self._last_subscribe = now + + last_discovery = self._mqtt_data.last_discovery + last_subscribe = now if self._pending_subscriptions else self._last_subscribe + wait_until = max(last_discovery, last_subscribe) + DISCOVERY_COOLDOWN + while now < wait_until: + await asyncio.sleep(wait_until - now) + now = time.monotonic() + last_discovery = self._mqtt_data.last_discovery + last_subscribe = ( + now if self._pending_subscriptions else self._last_subscribe + ) + wait_until = max(last_discovery, last_subscribe) + DISCOVERY_COOLDOWN + + +def _matcher_for_topic(subscription: str) -> Callable[[str], bool]: + matcher = MQTTMatcher() # type: ignore[no-untyped-call] + matcher[subscription] = True + + return lambda topic: next(matcher.iter_match(topic), False) # type: ignore[no-untyped-call] diff --git a/custom_components/vmqtt/climate.py b/custom_components/vmqtt/climate.py new file mode 100644 index 0000000..f469bb6 --- /dev/null +++ b/custom_components/vmqtt/climate.py @@ -0,0 +1,1012 @@ +"""Support for MQTT climate devices.""" + +from abc import ABC, abstractmethod +from collections.abc import Callable +from functools import partial +import logging +from typing import Any, override + +import probatio + +from homeassistant.components import climate +from homeassistant.components.climate import ( + ATTR_HVAC_MODE, + ATTR_TARGET_TEMP_HIGH, + ATTR_TARGET_TEMP_LOW, + DEFAULT_MAX_HUMIDITY, + DEFAULT_MIN_HUMIDITY, + FAN_AUTO, + FAN_HIGH, + FAN_LOW, + FAN_MEDIUM, + PRESET_NONE, + SWING_OFF, + SWING_ON, + ClimateEntity, + ClimateEntityCapabilityAttribute, + ClimateEntityFeature, + ClimateEntityStateAttribute, + HVACAction, + HVACMode, +) +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, + 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.service_info.mqtt import ReceivePayloadType +from homeassistant.helpers.template import Template +from homeassistant.helpers.typing import ( + UNDEFINED, + ConfigType, + UndefinedType, + VolSchemaType, +) +from homeassistant.util.unit_conversion import TemperatureConverter + +from . import subscription +from .config import DEFAULT_RETAIN, MQTT_BASE_SCHEMA +from .const import ( + CONF_ACTION_TEMPLATE, + CONF_ACTION_TOPIC, + CONF_CURRENT_HUMIDITY_TEMPLATE, + CONF_CURRENT_HUMIDITY_TOPIC, + CONF_CURRENT_TEMP_TEMPLATE, + CONF_CURRENT_TEMP_TOPIC, + CONF_FAN_MODE_COMMAND_TEMPLATE, + CONF_FAN_MODE_COMMAND_TOPIC, + CONF_FAN_MODE_LIST, + CONF_FAN_MODE_STATE_TEMPLATE, + CONF_FAN_MODE_STATE_TOPIC, + CONF_HUMIDITY_COMMAND_TEMPLATE, + CONF_HUMIDITY_COMMAND_TOPIC, + CONF_HUMIDITY_MAX, + CONF_HUMIDITY_MIN, + CONF_HUMIDITY_STATE_TEMPLATE, + CONF_HUMIDITY_STATE_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_PRESET_MODE_COMMAND_TEMPLATE, + CONF_PRESET_MODE_COMMAND_TOPIC, + CONF_PRESET_MODE_STATE_TOPIC, + CONF_PRESET_MODE_VALUE_TEMPLATE, + CONF_PRESET_MODES_LIST, + CONF_RETAIN, + CONF_SWING_HORIZONTAL_MODE_COMMAND_TEMPLATE, + CONF_SWING_HORIZONTAL_MODE_COMMAND_TOPIC, + CONF_SWING_HORIZONTAL_MODE_LIST, + CONF_SWING_HORIZONTAL_MODE_STATE_TEMPLATE, + CONF_SWING_HORIZONTAL_MODE_STATE_TOPIC, + CONF_SWING_MODE_COMMAND_TEMPLATE, + CONF_SWING_MODE_COMMAND_TOPIC, + CONF_SWING_MODE_LIST, + CONF_SWING_MODE_STATE_TEMPLATE, + CONF_SWING_MODE_STATE_TOPIC, + CONF_TEMP_COMMAND_TEMPLATE, + CONF_TEMP_COMMAND_TOPIC, + CONF_TEMP_HIGH_COMMAND_TEMPLATE, + CONF_TEMP_HIGH_COMMAND_TOPIC, + CONF_TEMP_HIGH_STATE_TEMPLATE, + CONF_TEMP_HIGH_STATE_TOPIC, + CONF_TEMP_INITIAL, + CONF_TEMP_LOW_COMMAND_TEMPLATE, + CONF_TEMP_LOW_COMMAND_TOPIC, + CONF_TEMP_LOW_STATE_TEMPLATE, + CONF_TEMP_LOW_STATE_TOPIC, + CONF_TEMP_MAX, + CONF_TEMP_MIN, + CONF_TEMP_STATE_TEMPLATE, + CONF_TEMP_STATE_TOPIC, + CONF_TEMP_STEP, + DEFAULT_CLIMATE_INITIAL_TEMPERATURE, + DEFAULT_OPTIMISTIC, + 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_NAME = "MQTT HVAC" + +MQTT_CLIMATE_ATTRIBUTES_BLOCKED = frozenset( + { + ClimateEntityCapabilityAttribute.FAN_MODES, + ClimateEntityCapabilityAttribute.HVAC_MODES, + ClimateEntityCapabilityAttribute.MAX_HUMIDITY, + ClimateEntityCapabilityAttribute.MAX_TEMP, + ClimateEntityCapabilityAttribute.MIN_HUMIDITY, + ClimateEntityCapabilityAttribute.MIN_TEMP, + ClimateEntityCapabilityAttribute.PRESET_MODES, + ClimateEntityCapabilityAttribute.SWING_HORIZONTAL_MODES, + ClimateEntityCapabilityAttribute.SWING_MODES, + ClimateEntityCapabilityAttribute.TARGET_TEMP_STEP, + ClimateEntityStateAttribute.CURRENT_HUMIDITY, + ClimateEntityStateAttribute.CURRENT_TEMPERATURE, + ClimateEntityStateAttribute.FAN_MODE, + ClimateEntityStateAttribute.HVAC_ACTION, + ClimateEntityStateAttribute.PRESET_MODE, + ClimateEntityStateAttribute.SWING_HORIZONTAL_MODE, + ClimateEntityStateAttribute.SWING_MODE, + ClimateEntityStateAttribute.TARGET_HUMIDITY, + ClimateEntityStateAttribute.TARGET_TEMPERATURE, + ClimateEntityStateAttribute.TARGET_TEMP_HIGH, + ClimateEntityStateAttribute.TARGET_TEMP_LOW, + } +) + +VALUE_TEMPLATE_KEYS = ( + CONF_CURRENT_HUMIDITY_TEMPLATE, + CONF_CURRENT_TEMP_TEMPLATE, + CONF_FAN_MODE_STATE_TEMPLATE, + CONF_HUMIDITY_STATE_TEMPLATE, + CONF_MODE_STATE_TEMPLATE, + CONF_ACTION_TEMPLATE, + CONF_PRESET_MODE_VALUE_TEMPLATE, + CONF_SWING_HORIZONTAL_MODE_STATE_TEMPLATE, + CONF_SWING_MODE_STATE_TEMPLATE, + CONF_TEMP_HIGH_STATE_TEMPLATE, + CONF_TEMP_LOW_STATE_TEMPLATE, + CONF_TEMP_STATE_TEMPLATE, +) + +COMMAND_TEMPLATE_KEYS = { + CONF_FAN_MODE_COMMAND_TEMPLATE, + CONF_HUMIDITY_COMMAND_TEMPLATE, + CONF_MODE_COMMAND_TEMPLATE, + CONF_POWER_COMMAND_TEMPLATE, + CONF_PRESET_MODE_COMMAND_TEMPLATE, + CONF_SWING_HORIZONTAL_MODE_COMMAND_TEMPLATE, + CONF_SWING_MODE_COMMAND_TEMPLATE, + CONF_TEMP_COMMAND_TEMPLATE, + CONF_TEMP_HIGH_COMMAND_TEMPLATE, + CONF_TEMP_LOW_COMMAND_TEMPLATE, +} + + +TOPIC_KEYS = ( + CONF_ACTION_TOPIC, + CONF_CURRENT_HUMIDITY_TOPIC, + CONF_CURRENT_TEMP_TOPIC, + CONF_FAN_MODE_COMMAND_TOPIC, + CONF_FAN_MODE_STATE_TOPIC, + CONF_HUMIDITY_COMMAND_TOPIC, + CONF_HUMIDITY_STATE_TOPIC, + CONF_MODE_COMMAND_TOPIC, + CONF_MODE_STATE_TOPIC, + CONF_POWER_COMMAND_TOPIC, + CONF_PRESET_MODE_COMMAND_TOPIC, + CONF_PRESET_MODE_STATE_TOPIC, + CONF_SWING_HORIZONTAL_MODE_COMMAND_TOPIC, + CONF_SWING_HORIZONTAL_MODE_STATE_TOPIC, + CONF_SWING_MODE_COMMAND_TOPIC, + CONF_SWING_MODE_STATE_TOPIC, + CONF_TEMP_COMMAND_TOPIC, + CONF_TEMP_HIGH_COMMAND_TOPIC, + CONF_TEMP_HIGH_STATE_TOPIC, + CONF_TEMP_LOW_COMMAND_TOPIC, + CONF_TEMP_LOW_STATE_TOPIC, + CONF_TEMP_STATE_TOPIC, +) + + +def valid_preset_mode_configuration(config: ConfigType) -> ConfigType: + """Validate that the preset mode reset payload is not one of the preset modes.""" + if PRESET_NONE in config[CONF_PRESET_MODES_LIST]: + raise probatio.Invalid("preset_modes must not include preset mode 'none'") + return config + + +def valid_humidity_range_configuration(config: ConfigType) -> ConfigType: + """Validate a target_humidity range configuration, throws otherwise.""" + if config[CONF_HUMIDITY_MIN] >= config[CONF_HUMIDITY_MAX]: + raise probatio.Invalid("target_humidity_max must be > target_humidity_min") + if config[CONF_HUMIDITY_MAX] > 100: + raise probatio.Invalid("max_humidity must be <= 100") + + return config + + +def valid_humidity_state_configuration(config: ConfigType) -> ConfigType: + """Validate humidity state. + + Ensure that if CONF_HUMIDITY_STATE_TOPIC is set then + CONF_HUMIDITY_COMMAND_TOPIC is also set. + """ + if ( + CONF_HUMIDITY_STATE_TOPIC in config + and CONF_HUMIDITY_COMMAND_TOPIC not in config + ): + raise probatio.Invalid( + f"{CONF_HUMIDITY_STATE_TOPIC} cannot be used without" + f" {CONF_HUMIDITY_COMMAND_TOPIC}" + ) + + return config + + +_PLATFORM_SCHEMA_BASE = MQTT_BASE_SCHEMA.extend( + { + probatio.Optional(CONF_CURRENT_HUMIDITY_TEMPLATE): cv.template, + probatio.Optional(CONF_CURRENT_HUMIDITY_TOPIC): valid_subscribe_topic, + probatio.Optional(CONF_CURRENT_TEMP_TEMPLATE): cv.template, + probatio.Optional(CONF_CURRENT_TEMP_TOPIC): valid_subscribe_topic, + probatio.Optional(CONF_FAN_MODE_COMMAND_TEMPLATE): cv.template, + probatio.Optional(CONF_FAN_MODE_COMMAND_TOPIC): valid_publish_topic, + probatio.Optional( + CONF_FAN_MODE_LIST, + default=[FAN_AUTO, FAN_LOW, FAN_MEDIUM, FAN_HIGH], + ): probatio.EnsureList(), + probatio.Optional(CONF_FAN_MODE_STATE_TEMPLATE): cv.template, + probatio.Optional(CONF_FAN_MODE_STATE_TOPIC): valid_subscribe_topic, + probatio.Optional(CONF_HUMIDITY_COMMAND_TEMPLATE): cv.template, + probatio.Optional(CONF_HUMIDITY_COMMAND_TOPIC): valid_publish_topic, + probatio.Optional( + CONF_HUMIDITY_MIN, default=DEFAULT_MIN_HUMIDITY + ): cv.positive_float, + probatio.Optional( + CONF_HUMIDITY_MAX, default=DEFAULT_MAX_HUMIDITY + ): cv.positive_float, + probatio.Optional(CONF_HUMIDITY_STATE_TEMPLATE): cv.template, + probatio.Optional(CONF_HUMIDITY_STATE_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=[ + HVACMode.AUTO, + HVACMode.OFF, + HVACMode.COOL, + HVACMode.HEAT, + HVACMode.DRY, + HVACMode.FAN_ONLY, + ], + ): 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_ACTION_TEMPLATE): cv.template, + probatio.Optional(CONF_ACTION_TOPIC): valid_subscribe_topic, + # 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_SWING_HORIZONTAL_MODE_COMMAND_TEMPLATE): cv.template, + probatio.Optional( + CONF_SWING_HORIZONTAL_MODE_COMMAND_TOPIC + ): valid_publish_topic, + probatio.Optional( + CONF_SWING_HORIZONTAL_MODE_LIST, default=[SWING_ON, SWING_OFF] + ): probatio.EnsureList(), + probatio.Optional(CONF_SWING_HORIZONTAL_MODE_STATE_TEMPLATE): cv.template, + probatio.Optional( + CONF_SWING_HORIZONTAL_MODE_STATE_TOPIC + ): valid_subscribe_topic, + probatio.Optional(CONF_SWING_MODE_COMMAND_TEMPLATE): cv.template, + probatio.Optional(CONF_SWING_MODE_COMMAND_TOPIC): valid_publish_topic, + probatio.Optional( + CONF_SWING_MODE_LIST, default=[SWING_ON, SWING_OFF] + ): probatio.EnsureList(), + probatio.Optional(CONF_SWING_MODE_STATE_TEMPLATE): cv.template, + probatio.Optional(CONF_SWING_MODE_STATE_TOPIC): valid_subscribe_topic, + probatio.Optional(CONF_TEMP_INITIAL): probatio.All(probatio.Coerce(float)), + probatio.Optional(CONF_TEMP_MIN): probatio.Coerce(float), + probatio.Optional(CONF_TEMP_MAX): probatio.Coerce(float), + probatio.Optional(CONF_TEMP_STEP, default=1.0): probatio.Coerce(float), + probatio.Optional(CONF_TEMP_COMMAND_TEMPLATE): cv.template, + probatio.Optional(CONF_TEMP_COMMAND_TOPIC): valid_publish_topic, + probatio.Optional(CONF_TEMP_HIGH_COMMAND_TEMPLATE): cv.template, + probatio.Optional(CONF_TEMP_HIGH_COMMAND_TOPIC): valid_publish_topic, + probatio.Optional(CONF_TEMP_HIGH_STATE_TOPIC): valid_subscribe_topic, + probatio.Optional(CONF_TEMP_HIGH_STATE_TEMPLATE): cv.template, + probatio.Optional(CONF_TEMP_LOW_COMMAND_TEMPLATE): cv.template, + probatio.Optional(CONF_TEMP_LOW_COMMAND_TOPIC): valid_publish_topic, + probatio.Optional(CONF_TEMP_LOW_STATE_TEMPLATE): cv.template, + probatio.Optional(CONF_TEMP_LOW_STATE_TOPIC): valid_subscribe_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, + valid_preset_mode_configuration, + valid_humidity_range_configuration, + valid_humidity_state_configuration, +) + +_DISCOVERY_SCHEMA_BASE = _PLATFORM_SCHEMA_BASE.extend({}, extra=probatio.REMOVE_EXTRA) + +DISCOVERY_SCHEMA = probatio.All( + _DISCOVERY_SCHEMA_BASE, + valid_preset_mode_configuration, + valid_humidity_range_configuration, + valid_humidity_state_configuration, +) + + +async def async_setup_entry( + hass: HomeAssistant, + config_entry: ConfigEntry, + async_add_entities: AddConfigEntryEntitiesCallback, +) -> None: + """Set up MQTT climate through YAML and through MQTT discovery.""" + async_setup_entity_entry_helper( + hass, + config_entry, + MqttClimate, + climate.DOMAIN, + async_add_entities, + DISCOVERY_SCHEMA, + PLATFORM_SCHEMA_MODERN, + ) + + +class MqttTemperatureControlEntity(MqttEntity, ABC): + """Helper entity class to control temperature. + + MqttTemperatureControlEntity supports shared methods for + climate and water_heater platforms. + """ + + _attr_current_temperature: float | None + _attr_target_temperature: float | None + _attr_target_temperature_low: float | None + _attr_target_temperature_high: float | None + + _feature_preset_mode: bool = False + _optimistic: bool + _topic: dict[str, Any] + + _command_templates: dict[str, Callable[[PublishPayloadType], PublishPayloadType]] + _value_templates: dict[str, Callable[[ReceivePayloadType], ReceivePayloadType]] + + def render_template( + self, msg: ReceiveMessage, template_name: str + ) -> ReceivePayloadType: + """Render a template by name.""" + template = self._value_templates[template_name] + return template(msg.payload) + + @callback + def _parse_float_payload( + self, msg: ReceiveMessage, template_name: str, name: str + ) -> float | UndefinedType | None: + """Render and parse a numeric payload, UNDEFINED means ignore the update.""" + payload = self.render_template(msg, template_name) + if not payload: + _LOGGER.debug( + "Invalid empty payload for %s, ignoring update", + name, + ) + return UNDEFINED + if payload == PAYLOAD_NONE: + return None + try: + return float(payload) + except ValueError: + _LOGGER.error("Could not parse %s from %s", template_name, payload) + return UNDEFINED + + @callback + def _handle_current_temperature_received(self, msg: ReceiveMessage) -> None: + """Handle receiving the current temperature via MQTT.""" + if ( + value := self._parse_float_payload( + msg, CONF_CURRENT_TEMP_TEMPLATE, "current temperature" + ) + ) is not UNDEFINED: + self._attr_current_temperature = value + + @override + async def _subscribe_topics(self) -> None: + """(Re)Subscribe to topics.""" + subscription.async_subscribe_topics_internal(self.hass, self._sub_state) + + async def _publish(self, topic: str, payload: PublishPayloadType) -> None: + if self._topic[topic] is not None: + await self.async_publish_with_config(self._topic[topic], payload) + + @abstractmethod + async def async_set_temperature(self, **kwargs: Any) -> None: + """Set new target temperatures.""" + + +class MqttClimate(MqttTemperatureControlEntity, ClimateEntity): + """Representation of an MQTT climate device.""" + + _attr_fan_mode: str | None = None + _attr_hvac_mode: HVACMode | None = None + _attr_swing_horizontal_mode: str | None = None + _attr_swing_mode: str | None = None + _default_name = DEFAULT_NAME + _entity_id_format = climate.ENTITY_ID_FORMAT + _attributes_extra_blocked = MQTT_CLIMATE_ATTRIBUTES_BLOCKED + _attr_target_temperature_low: float | None = None + _attr_target_temperature_high: float | None = None + _single_and_range_setpoints: bool + _parked_target_temperature: float | None = None + _parked_target_temperature_range: tuple[float | None, float | None] = (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_hvac_modes = config[CONF_MODE_LIST] + self._single_and_range_setpoints = ( + HVACMode.HEAT_COOL in self._attr_hvac_modes + and ( + HVACMode.HEAT in self._attr_hvac_modes + or HVACMode.COOL in self._attr_hvac_modes + ) + ) + # Make sure the min an max temp is converted to the correct when not set + 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 + self._attr_min_humidity = config[CONF_HUMIDITY_MIN] + self._attr_max_humidity = config[CONF_HUMIDITY_MAX] + if (precision := config.get(CONF_PRECISION)) is not None: + self._attr_precision = precision + self._attr_fan_modes = config[CONF_FAN_MODE_LIST] + self._attr_swing_horizontal_modes = config[CONF_SWING_HORIZONTAL_MODE_LIST] + self._attr_swing_modes = config[CONF_SWING_MODE_LIST] + self._attr_target_temperature_step = config[CONF_TEMP_STEP] + + 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_CLIMATE_INITIAL_TEMPERATURE, + UnitOfTemperature.CELSIUS, + 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_TEMP_LOW_STATE_TOPIC] is None or self._optimistic: + self._attr_target_temperature_low = init_temp + if self._topic[CONF_TEMP_HIGH_STATE_TOPIC] is None or self._optimistic: + self._attr_target_temperature_high = init_temp + + if self._topic[CONF_FAN_MODE_STATE_TOPIC] is None or self._optimistic: + self._attr_fan_mode = FAN_LOW + if ( + self._topic[CONF_SWING_HORIZONTAL_MODE_STATE_TOPIC] is None + or self._optimistic + ): + self._attr_swing_horizontal_mode = SWING_OFF + if self._topic[CONF_SWING_MODE_STATE_TOPIC] is None or self._optimistic: + self._attr_swing_mode = SWING_OFF + if self._topic[CONF_MODE_STATE_TOPIC] is None or self._optimistic: + self._attr_hvac_mode = HVACMode.OFF + self._feature_preset_mode = CONF_PRESET_MODE_COMMAND_TOPIC in config + if self._feature_preset_mode: + presets = [] + presets.extend(config[CONF_PRESET_MODES_LIST]) + if presets: + presets.insert(0, PRESET_NONE) + self._attr_preset_modes = presets + self._attr_preset_mode = PRESET_NONE + else: + self._attr_preset_modes = [] + self._optimistic_preset_mode = ( + self._optimistic or CONF_PRESET_MODE_STATE_TOPIC not in config + ) + + 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 = ClimateEntityFeature.TURN_ON | ClimateEntityFeature.TURN_OFF + if (self._topic[CONF_TEMP_STATE_TOPIC] is not None) or ( + self._topic[CONF_TEMP_COMMAND_TOPIC] is not None + ): + support |= ClimateEntityFeature.TARGET_TEMPERATURE + + if (self._topic[CONF_TEMP_LOW_STATE_TOPIC] is not None) or ( + self._topic[CONF_TEMP_LOW_COMMAND_TOPIC] is not None + ): + support |= ClimateEntityFeature.TARGET_TEMPERATURE_RANGE + + if (self._topic[CONF_TEMP_HIGH_STATE_TOPIC] is not None) or ( + self._topic[CONF_TEMP_HIGH_COMMAND_TOPIC] is not None + ): + support |= ClimateEntityFeature.TARGET_TEMPERATURE_RANGE + + if self._topic[CONF_HUMIDITY_COMMAND_TOPIC] is not None: + support |= ClimateEntityFeature.TARGET_HUMIDITY + + if (self._topic[CONF_FAN_MODE_STATE_TOPIC] is not None) or ( + self._topic[CONF_FAN_MODE_COMMAND_TOPIC] is not None + ): + support |= ClimateEntityFeature.FAN_MODE + + if (self._topic[CONF_SWING_HORIZONTAL_MODE_STATE_TOPIC] is not None) or ( + self._topic[CONF_SWING_HORIZONTAL_MODE_COMMAND_TOPIC] is not None + ): + support |= ClimateEntityFeature.SWING_HORIZONTAL_MODE + + if (self._topic[CONF_SWING_MODE_STATE_TOPIC] is not None) or ( + self._topic[CONF_SWING_MODE_COMMAND_TOPIC] is not None + ): + support |= ClimateEntityFeature.SWING_MODE + + if self._feature_preset_mode: + support |= ClimateEntityFeature.PRESET_MODE + + self._attr_supported_features = support + + @callback + def _handle_action_received(self, msg: ReceiveMessage) -> None: + """Handle receiving action via MQTT.""" + payload = self.render_template(msg, CONF_ACTION_TEMPLATE) + if not payload: + _LOGGER.debug( + "Invalid %s action: %s, ignoring", + [e.value for e in HVACAction], + payload, + ) + return + if payload == PAYLOAD_NONE: + self._attr_hvac_action = None + return + try: + self._attr_hvac_action = HVACAction(str(payload)) + except ValueError: + _LOGGER.warning( + "Invalid %s action: %s", + [e.value for e in HVACAction], + payload, + ) + return + + @callback + def _handle_mode_received( + self, template_name: str, attr: str, mode_list: str, msg: ReceiveMessage + ) -> None: + """Handle receiving listed mode via MQTT.""" + payload = self.render_template(msg, template_name) + + if payload == PAYLOAD_NONE: + setattr(self, attr, None) + elif payload not in self._config[mode_list]: + _LOGGER.warning("Invalid %s mode: %s", mode_list, payload) + else: + setattr(self, attr, payload) + + @callback + def _handle_preset_mode_received(self, msg: ReceiveMessage) -> None: + """Handle receiving preset mode via MQTT.""" + preset_mode = self.render_template(msg, CONF_PRESET_MODE_VALUE_TEMPLATE) + if preset_mode in [PRESET_NONE, PAYLOAD_NONE]: + self._attr_preset_mode = PRESET_NONE + return + if not preset_mode: + _LOGGER.debug("Ignoring empty preset_mode from '%s'", msg.topic) + return + if not self._attr_preset_modes or preset_mode not in self._attr_preset_modes: + _LOGGER.warning( + "'%s' received on topic %s. '%s' is not a valid preset mode", + msg.payload, + msg.topic, + preset_mode, + ) + else: + self._attr_preset_mode = str(preset_mode) + + @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 UNDEFINED: + return + self._attr_target_temperature = value + if value is not None: + self._park_range_setpoints() + + @callback + def _handle_target_temperature_low_received(self, msg: ReceiveMessage) -> None: + """Handle receiving the target temperature low via MQTT.""" + if ( + value := self._parse_float_payload( + msg, CONF_TEMP_LOW_STATE_TEMPLATE, "target temperature low" + ) + ) is UNDEFINED: + return + self._attr_target_temperature_low = value + if value is not None: + self._park_single_setpoint() + + @callback + def _handle_target_temperature_high_received(self, msg: ReceiveMessage) -> None: + """Handle receiving the target temperature high via MQTT.""" + if ( + value := self._parse_float_payload( + msg, CONF_TEMP_HIGH_STATE_TEMPLATE, "target temperature high" + ) + ) is UNDEFINED: + return + self._attr_target_temperature_high = value + if value is not None: + self._park_single_setpoint() + + @callback + def _handle_current_humidity_received(self, msg: ReceiveMessage) -> None: + """Handle receiving the current humidity via MQTT.""" + if ( + value := self._parse_float_payload( + msg, CONF_CURRENT_HUMIDITY_TEMPLATE, "current humidity" + ) + ) is not UNDEFINED: + self._attr_current_humidity = value + + @callback + def _handle_target_humidity_received(self, msg: ReceiveMessage) -> None: + """Handle receiving the target humidity via MQTT.""" + if ( + value := self._parse_float_payload( + msg, CONF_HUMIDITY_STATE_TEMPLATE, "target humidity" + ) + ) is not UNDEFINED: + self._attr_target_humidity = value + + @callback + @override + def _prepare_subscribe_topics(self) -> None: + """(Re)Subscribe to topics.""" + self.add_subscription( + CONF_ACTION_TOPIC, + self._handle_action_received, + {"_attr_hvac_action"}, + ) + self.add_subscription( + CONF_CURRENT_HUMIDITY_TOPIC, + self._handle_current_humidity_received, + {"_attr_current_humidity"}, + ) + self.add_subscription( + CONF_HUMIDITY_STATE_TOPIC, + self._handle_target_humidity_received, + {"_attr_target_humidity"}, + ) + self.add_subscription( + CONF_MODE_STATE_TOPIC, + partial( + self._handle_mode_received, + CONF_MODE_STATE_TEMPLATE, + "_attr_hvac_mode", + CONF_MODE_LIST, + ), + {"_attr_hvac_mode"}, + ) + self.add_subscription( + CONF_FAN_MODE_STATE_TOPIC, + partial( + self._handle_mode_received, + CONF_FAN_MODE_STATE_TEMPLATE, + "_attr_fan_mode", + CONF_FAN_MODE_LIST, + ), + {"_attr_fan_mode"}, + ) + self.add_subscription( + CONF_SWING_HORIZONTAL_MODE_STATE_TOPIC, + partial( + self._handle_mode_received, + CONF_SWING_HORIZONTAL_MODE_STATE_TEMPLATE, + "_attr_swing_horizontal_mode", + CONF_SWING_HORIZONTAL_MODE_LIST, + ), + {"_attr_swing_horizontal_mode"}, + ) + self.add_subscription( + CONF_SWING_MODE_STATE_TOPIC, + partial( + self._handle_mode_received, + CONF_SWING_MODE_STATE_TEMPLATE, + "_attr_swing_mode", + CONF_SWING_MODE_LIST, + ), + {"_attr_swing_mode"}, + ) + self.add_subscription( + CONF_PRESET_MODE_STATE_TOPIC, + self._handle_preset_mode_received, + {"_attr_preset_mode"}, + ) + self.add_subscription( + CONF_CURRENT_TEMP_TOPIC, + self._handle_current_temperature_received, + {"_attr_current_temperature"}, + ) + setpoints = { + "_attr_target_temperature", + "_attr_target_temperature_low", + "_attr_target_temperature_high", + } + self.add_subscription( + CONF_TEMP_STATE_TOPIC, + self._handle_target_temperature_received, + setpoints, + ) + self.add_subscription( + CONF_TEMP_LOW_STATE_TOPIC, + self._handle_target_temperature_low_received, + setpoints, + ) + self.add_subscription( + CONF_TEMP_HIGH_STATE_TOPIC, + self._handle_target_temperature_high_received, + setpoints, + ) + + @override + async def async_set_temperature(self, **kwargs: Any) -> None: + """Set new target temperatures.""" + operation_mode: HVACMode | None + if (operation_mode := kwargs.get(ATTR_HVAC_MODE)) is not None: + await self.async_set_hvac_mode(operation_mode) + + optimistic_update = False + temperature: float | None + if (temperature := kwargs.get(ATTR_TEMPERATURE)) is not None: + if self._optimistic or self._topic[CONF_TEMP_STATE_TOPIC] is None: + optimistic_update = True + self._attr_target_temperature = temperature + # We reset low and high setpoints when a single setpoint is set + self._park_range_setpoints() + mqtt_payload = self._command_templates[CONF_TEMP_COMMAND_TEMPLATE]( + temperature + ) + await self._publish(CONF_TEMP_COMMAND_TOPIC, mqtt_payload) + + target_temp_low: float | None + if (target_temp_low := kwargs.get(ATTR_TARGET_TEMP_LOW)) is not None: + if self._optimistic or self._topic[CONF_TEMP_LOW_STATE_TOPIC] is None: + optimistic_update = True + self._attr_target_temperature_low = target_temp_low + # We reset the single setpoint when a setpoint range is set + self._park_single_setpoint() + mqtt_payload = self._command_templates[CONF_TEMP_LOW_COMMAND_TEMPLATE]( + target_temp_low + ) + await self._publish(CONF_TEMP_LOW_COMMAND_TOPIC, mqtt_payload) + + target_temp_high: float | None + if (target_temp_high := kwargs.get(ATTR_TARGET_TEMP_HIGH)) is not None: + if self._optimistic or self._topic[CONF_TEMP_HIGH_STATE_TOPIC] is None: + optimistic_update = True + self._attr_target_temperature_high = target_temp_high + self._park_single_setpoint() + mqtt_payload = self._command_templates[CONF_TEMP_HIGH_COMMAND_TEMPLATE]( + target_temp_high + ) + await self._publish(CONF_TEMP_HIGH_COMMAND_TOPIC, mqtt_payload) + + if optimistic_update: + self.async_write_ha_state() + + @override + async def async_set_humidity(self, humidity: float) -> None: + """Set new target humidity.""" + mqtt_payload = self._command_templates[CONF_HUMIDITY_COMMAND_TEMPLATE](humidity) + await self._publish(CONF_HUMIDITY_COMMAND_TOPIC, mqtt_payload) + + if self._optimistic or self._topic[CONF_HUMIDITY_STATE_TOPIC] is None: + self._attr_target_humidity = humidity + self.async_write_ha_state() + + @override + async def async_set_swing_horizontal_mode(self, swing_horizontal_mode: str) -> None: + """Set new swing horizontal mode.""" + payload = self._command_templates[CONF_SWING_HORIZONTAL_MODE_COMMAND_TEMPLATE]( + swing_horizontal_mode + ) + await self._publish(CONF_SWING_HORIZONTAL_MODE_COMMAND_TOPIC, payload) + + if ( + self._optimistic + or self._topic[CONF_SWING_HORIZONTAL_MODE_STATE_TOPIC] is None + ): + self._attr_swing_horizontal_mode = swing_horizontal_mode + self.async_write_ha_state() + + @override + async def async_set_swing_mode(self, swing_mode: str) -> None: + """Set new swing mode.""" + payload = self._command_templates[CONF_SWING_MODE_COMMAND_TEMPLATE](swing_mode) + await self._publish(CONF_SWING_MODE_COMMAND_TOPIC, payload) + + if self._optimistic or self._topic[CONF_SWING_MODE_STATE_TOPIC] is None: + self._attr_swing_mode = swing_mode + self.async_write_ha_state() + + @override + async def async_set_fan_mode(self, fan_mode: str) -> None: + """Set new target temperature.""" + payload = self._command_templates[CONF_FAN_MODE_COMMAND_TEMPLATE](fan_mode) + await self._publish(CONF_FAN_MODE_COMMAND_TOPIC, payload) + + if self._optimistic or self._topic[CONF_FAN_MODE_STATE_TOPIC] is None: + self._attr_fan_mode = fan_mode + self.async_write_ha_state() + + @override + async def async_set_hvac_mode(self, hvac_mode: HVACMode) -> None: + """Set new operation mode.""" + payload = self._command_templates[CONF_MODE_COMMAND_TEMPLATE](hvac_mode) + await self._publish(CONF_MODE_COMMAND_TOPIC, payload) + + if self._optimistic or self._topic[CONF_MODE_STATE_TOPIC] is None: + self._attr_hvac_mode = hvac_mode + self._swap_setpoints(hvac_mode) + self.async_write_ha_state() + + def _park_single_setpoint(self) -> None: + """Park and reset the single setpoint when a setpoint range is active.""" + if not self._single_and_range_setpoints or self.target_temperature is None: + return + self._parked_target_temperature = self.target_temperature + self._attr_target_temperature = None + + def _park_range_setpoints(self) -> None: + """Park and reset the setpoint range when a single setpoint is active.""" + temp_range = (self.target_temperature_low, self.target_temperature_high) + if not self._single_and_range_setpoints or temp_range == (None, None): + return + self._parked_target_temperature_range = temp_range + self._attr_target_temperature_low = None + self._attr_target_temperature_high = None + + def _swap_setpoints(self, hvac_mode: HVACMode) -> None: + """Swap optimistic single and range setpoints on an HVAC mode change. + + The inactive setpoints are parked, so they can be restored + when switching back, as the device is expected to remember them. + """ + if not self._single_and_range_setpoints or hvac_mode not in ( + HVACMode.COOL, + HVACMode.HEAT, + HVACMode.HEAT_COOL, + ): + return + uses_range = hvac_mode is HVACMode.HEAT_COOL + if self._optimistic or self._topic[CONF_TEMP_STATE_TOPIC] is None: + if uses_range: + self._park_single_setpoint() + elif self.target_temperature is None: + self._attr_target_temperature = self._parked_target_temperature + if self._optimistic or ( + self._topic[CONF_TEMP_LOW_STATE_TOPIC] is None + and self._topic[CONF_TEMP_HIGH_STATE_TOPIC] is None + ): + if not uses_range: + self._park_range_setpoints() + elif ( + self.target_temperature_low is None + and self.target_temperature_high is None + ): + ( + self._attr_target_temperature_low, + self._attr_target_temperature_high, + ) = self._parked_target_temperature_range + + @override + async def async_set_preset_mode(self, preset_mode: str) -> None: + """Set a preset mode.""" + mqtt_payload = self._command_templates[CONF_PRESET_MODE_COMMAND_TEMPLATE]( + preset_mode + ) + await self._publish( + 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_turn_on(self) -> 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) + return + # Fall back to default behavior without power command topic + await super().async_turn_on() + + @override + async def async_turn_off(self) -> 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) + if self._optimistic: + self._attr_hvac_mode = HVACMode.OFF + self.async_write_ha_state() + return + # Fall back to default behavior without power command topic + await super().async_turn_off() diff --git a/custom_components/vmqtt/config.py b/custom_components/vmqtt/config.py new file mode 100644 index 0000000..4560d44 --- /dev/null +++ b/custom_components/vmqtt/config.py @@ -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, + } +) diff --git a/custom_components/vmqtt/config_flow.py b/custom_components/vmqtt/config_flow.py new file mode 100644 index 0000000..9120490 --- /dev/null +++ b/custom_components/vmqtt/config_flow.py @@ -0,0 +1,5460 @@ +"""Config flow for MQTT.""" + +import asyncio +from collections import OrderedDict +from collections.abc import Callable, Mapping +from copy import deepcopy +from dataclasses import dataclass +from enum import IntEnum +import json +import logging +from ssl import PROTOCOL_TLS_CLIENT, SSLContext, SSLError +from types import MappingProxyType +from typing import TYPE_CHECKING, Any, cast, override +from uuid import uuid4 + +from cryptography.hazmat.primitives.serialization import ( + Encoding, + NoEncryption, + PrivateFormat, + load_der_private_key, + load_pem_private_key, +) +from cryptography.x509 import load_der_x509_certificate, load_pem_x509_certificate +import probatio +import yaml + +from homeassistant.components.climate import ( + DEFAULT_MAX_HUMIDITY, + DEFAULT_MAX_TEMP, + DEFAULT_MIN_HUMIDITY, + DEFAULT_MIN_TEMP, + PRESET_NONE, +) +from homeassistant.components.file_upload import process_uploaded_file +from homeassistant.components.hassio import AddonError, AddonManager, AddonState +from homeassistant.components.image import DEFAULT_CONTENT_TYPE +from homeassistant.components.light import ( + DEFAULT_MAX_KELVIN, + DEFAULT_MIN_KELVIN, + VALID_COLOR_MODES, + valid_supported_color_modes, +) +from homeassistant.components.number import ( + DEFAULT_MAX_VALUE, + DEFAULT_MIN_VALUE, + DEFAULT_STEP, + DEVICE_CLASS_UNITS as NUMBER_DEVICE_CLASS_UNITS, + NumberMode, +) +from homeassistant.components.sensor import ( + CONF_STATE_CLASS, + DEVICE_CLASS_UNITS, + STATE_CLASS_UNITS, + SensorDeviceClass, +) +from homeassistant.components.valve import ValveState +from homeassistant.config_entries import ( + SOURCE_RECONFIGURE, + ConfigEntry, + ConfigFlow, + ConfigFlowResult, + ConfigSubentryFlow, + OptionsFlow, + SubentryFlowResult, +) +from homeassistant.const import ( + CONF_BRIGHTNESS, + CONF_CLIENT_ID, + CONF_CODE, + CONF_DEVICE, + CONF_DEVICE_CLASS, + CONF_DISCOVERY, + CONF_EFFECT, + CONF_ENTITY_CATEGORY, + CONF_HOST, + CONF_MODE, + CONF_MODEL, + CONF_MODEL_ID, + CONF_NAME, + CONF_OPTIMISTIC, + CONF_OPTIONS, + CONF_PASSWORD, + CONF_PAYLOAD, + CONF_PAYLOAD_OFF, + CONF_PAYLOAD_ON, + CONF_PLATFORM, + CONF_PORT, + CONF_PROTOCOL, + CONF_STATE_TEMPLATE, + CONF_TEMPERATURE_UNIT, + CONF_UNIQUE_ID, + CONF_UNIT_OF_MEASUREMENT, + CONF_USERNAME, + CONF_VALUE_TEMPLATE, + STATE_CLOSED, + STATE_CLOSING, + STATE_OPEN, + STATE_OPENING, + EntityCategory, + Platform, + UnitOfTemperature, +) +from homeassistant.core import HomeAssistant, async_get_hass, callback +from homeassistant.data_entry_flow import AbortFlow, SectionConfig, section +from homeassistant.helpers import config_validation as cv, entity_registry as er +from homeassistant.helpers.hassio import is_hassio +from homeassistant.helpers.json import json_dumps +from homeassistant.helpers.selector import ( + BooleanSelector, + DeviceClassSelector, + DeviceClassSelectorConfig, + DurationSelector, + DurationSelectorConfig, + FileSelector, + FileSelectorConfig, + NumberSelector, + NumberSelectorConfig, + NumberSelectorMode, + SelectOptionDict, + Selector, + SelectSelector, + SelectSelectorConfig, + SelectSelectorMode, + StateClassSelector, + TemplateSelector, + TemplateSelectorConfig, + TextSelector, + TextSelectorConfig, + TextSelectorType, +) +from homeassistant.helpers.service_info.hassio import HassioServiceInfo +from homeassistant.util.json import JSON_DECODE_EXCEPTIONS, json_loads +from homeassistant.util.unit_conversion import TemperatureConverter + +from .addon import get_addon_manager +from .client import try_connection +from .const import ( + ALARM_CONTROL_PANEL_SUPPORTED_FEATURES, + ATTR_PAYLOAD, + ATTR_QOS, + ATTR_RETAIN, + ATTR_TOPIC, + CONF_ACTION_TEMPLATE, + CONF_ACTION_TOPIC, + CONF_AVAILABILITY_TEMPLATE, + CONF_AVAILABILITY_TOPIC, + CONF_AVAILABLE_TONES, + CONF_BIRTH_MESSAGE, + CONF_BLUE_TEMPLATE, + CONF_BRIGHTNESS_COMMAND_TEMPLATE, + CONF_BRIGHTNESS_COMMAND_TOPIC, + CONF_BRIGHTNESS_SCALE, + CONF_BRIGHTNESS_STATE_TOPIC, + CONF_BRIGHTNESS_TEMPLATE, + CONF_BRIGHTNESS_VALUE_TEMPLATE, + CONF_BROKER, + CONF_CERTIFICATE, + CONF_CLIENT_CERT, + CONF_CLIENT_KEY, + CONF_CODE_ARM_REQUIRED, + CONF_CODE_DISARM_REQUIRED, + CONF_CODE_FORMAT, + CONF_CODE_TRIGGER_REQUIRED, + 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_TEMPLATE, + CONF_COLOR_TEMP_VALUE_TEMPLATE, + CONF_COMMAND_OFF_TEMPLATE, + CONF_COMMAND_ON_TEMPLATE, + CONF_COMMAND_TEMPLATE, + CONF_COMMAND_TOPIC, + CONF_CONFIGURATION_URL, + CONF_CONTENT_TYPE, + CONF_CURRENT_HUMIDITY_TEMPLATE, + CONF_CURRENT_HUMIDITY_TOPIC, + CONF_CURRENT_TEMP_TEMPLATE, + CONF_CURRENT_TEMP_TOPIC, + CONF_DIRECTION_COMMAND_TEMPLATE, + CONF_DIRECTION_COMMAND_TOPIC, + CONF_DIRECTION_STATE_TOPIC, + CONF_DIRECTION_VALUE_TEMPLATE, + CONF_DISCOVERY_PREFIX, + CONF_DISCOVERY_QOS, + CONF_EFFECT_COMMAND_TEMPLATE, + CONF_EFFECT_COMMAND_TOPIC, + CONF_EFFECT_LIST, + CONF_EFFECT_STATE_TOPIC, + CONF_EFFECT_TEMPLATE, + CONF_EFFECT_VALUE_TEMPLATE, + CONF_ENTITY_PICTURE, + CONF_EXPIRE_AFTER, + CONF_FAN_MODE_COMMAND_TEMPLATE, + CONF_FAN_MODE_COMMAND_TOPIC, + CONF_FAN_MODE_LIST, + CONF_FAN_MODE_STATE_TEMPLATE, + CONF_FAN_MODE_STATE_TOPIC, + CONF_FLASH, + CONF_FLASH_TIME_LONG, + CONF_FLASH_TIME_SHORT, + CONF_GET_POSITION_TEMPLATE, + CONF_GET_POSITION_TOPIC, + CONF_GREEN_TEMPLATE, + CONF_HS_COMMAND_TEMPLATE, + CONF_HS_COMMAND_TOPIC, + CONF_HS_STATE_TOPIC, + CONF_HS_VALUE_TEMPLATE, + CONF_HUMIDITY_COMMAND_TEMPLATE, + CONF_HUMIDITY_COMMAND_TOPIC, + CONF_HUMIDITY_MAX, + CONF_HUMIDITY_MIN, + CONF_HUMIDITY_STATE_TEMPLATE, + CONF_HUMIDITY_STATE_TOPIC, + CONF_HW_VERSION, + CONF_IMAGE_ENCODING, + CONF_IMAGE_TOPIC, + CONF_KEEPALIVE, + CONF_LAST_RESET_VALUE_TEMPLATE, + CONF_MANUFACTURER, + CONF_MAX, + CONF_MAX_KELVIN, + CONF_MESSAGE_EXPIRY_INTERVAL, + CONF_MIN, + CONF_MIN_KELVIN, + CONF_MODE_COMMAND_TEMPLATE, + CONF_MODE_COMMAND_TOPIC, + CONF_MODE_LIST, + CONF_MODE_STATE_TEMPLATE, + CONF_MODE_STATE_TOPIC, + CONF_OFF_DELAY, + CONF_ON_COMMAND_TYPE, + CONF_OSCILLATION_COMMAND_TEMPLATE, + CONF_OSCILLATION_COMMAND_TOPIC, + CONF_OSCILLATION_STATE_TOPIC, + CONF_OSCILLATION_VALUE_TEMPLATE, + CONF_PATTERN, + CONF_PAYLOAD_ARM_AWAY, + CONF_PAYLOAD_ARM_CUSTOM_BYPASS, + CONF_PAYLOAD_ARM_HOME, + CONF_PAYLOAD_ARM_NIGHT, + CONF_PAYLOAD_ARM_VACATION, + CONF_PAYLOAD_AVAILABLE, + CONF_PAYLOAD_CLOSE, + CONF_PAYLOAD_LOCK, + CONF_PAYLOAD_NOT_AVAILABLE, + CONF_PAYLOAD_OPEN, + CONF_PAYLOAD_OSCILLATION_OFF, + CONF_PAYLOAD_OSCILLATION_ON, + CONF_PAYLOAD_PRESS, + CONF_PAYLOAD_RESET, + CONF_PAYLOAD_RESET_PERCENTAGE, + CONF_PAYLOAD_RESET_PRESET_MODE, + CONF_PAYLOAD_STOP, + CONF_PAYLOAD_STOP_TILT, + CONF_PAYLOAD_TRIGGER, + CONF_PAYLOAD_UNLOCK, + CONF_PERCENTAGE_COMMAND_TEMPLATE, + CONF_PERCENTAGE_COMMAND_TOPIC, + CONF_PERCENTAGE_STATE_TOPIC, + CONF_PERCENTAGE_VALUE_TEMPLATE, + CONF_POSITION_CLOSED, + CONF_POSITION_OPEN, + CONF_POWER_COMMAND_TEMPLATE, + CONF_POWER_COMMAND_TOPIC, + CONF_PRECISION, + 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_QOS, + CONF_RED_TEMPLATE, + CONF_REPORTS_POSITION, + CONF_RETAIN, + 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_SCHEMA, + CONF_SET_POSITION_TEMPLATE, + CONF_SET_POSITION_TOPIC, + CONF_SPEED_RANGE_MAX, + CONF_SPEED_RANGE_MIN, + CONF_STATE_CLOSED, + CONF_STATE_CLOSING, + CONF_STATE_JAMMED, + CONF_STATE_LOCKED, + CONF_STATE_LOCKING, + CONF_STATE_OFF, + CONF_STATE_ON, + CONF_STATE_OPEN, + CONF_STATE_OPENING, + CONF_STATE_STOPPED, + CONF_STATE_TOPIC, + CONF_STATE_UNLOCKED, + CONF_STATE_UNLOCKING, + CONF_STATE_VALUE_TEMPLATE, + CONF_STEP, + CONF_SUGGESTED_DISPLAY_PRECISION, + CONF_SUPPORT_DURATION, + CONF_SUPPORT_VOLUME_SET, + CONF_SUPPORTED_COLOR_MODES, + CONF_SUPPORTED_FEATURES, + CONF_SW_VERSION, + CONF_SWING_HORIZONTAL_MODE_COMMAND_TEMPLATE, + CONF_SWING_HORIZONTAL_MODE_COMMAND_TOPIC, + CONF_SWING_HORIZONTAL_MODE_LIST, + CONF_SWING_HORIZONTAL_MODE_STATE_TEMPLATE, + CONF_SWING_HORIZONTAL_MODE_STATE_TOPIC, + CONF_SWING_MODE_COMMAND_TEMPLATE, + CONF_SWING_MODE_COMMAND_TOPIC, + CONF_SWING_MODE_LIST, + CONF_SWING_MODE_STATE_TEMPLATE, + CONF_SWING_MODE_STATE_TOPIC, + CONF_TEMP_COMMAND_TEMPLATE, + CONF_TEMP_COMMAND_TOPIC, + CONF_TEMP_HIGH_COMMAND_TEMPLATE, + CONF_TEMP_HIGH_COMMAND_TOPIC, + CONF_TEMP_HIGH_STATE_TEMPLATE, + CONF_TEMP_HIGH_STATE_TOPIC, + CONF_TEMP_INITIAL, + CONF_TEMP_LOW_COMMAND_TEMPLATE, + CONF_TEMP_LOW_COMMAND_TOPIC, + CONF_TEMP_LOW_STATE_TEMPLATE, + CONF_TEMP_LOW_STATE_TOPIC, + CONF_TEMP_MAX, + CONF_TEMP_MIN, + CONF_TEMP_STATE_TEMPLATE, + CONF_TEMP_STATE_TOPIC, + CONF_TEMP_STEP, + 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, + CONF_TIMEZONE, + CONF_TLS_INSECURE, + CONF_TRANSITION, + CONF_TRANSPORT, + CONF_URL_TEMPLATE, + CONF_URL_TOPIC, + CONF_WHITE_COMMAND_TOPIC, + CONF_WHITE_SCALE, + CONF_WILL_MESSAGE, + CONF_WS_HEADERS, + CONF_WS_PATH, + CONF_XY_COMMAND_TEMPLATE, + CONF_XY_COMMAND_TOPIC, + CONF_XY_STATE_TOPIC, + CONF_XY_VALUE_TEMPLATE, + CONFIG_ENTRY_MINOR_VERSION, + CONFIG_ENTRY_VERSION, + DEFAULT_ALARM_CONTROL_PANEL_COMMAND_TEMPLATE, + DEFAULT_BIRTH, + DEFAULT_CLIMATE_INITIAL_TEMPERATURE, + DEFAULT_DISCOVERY, + DEFAULT_ENCODING, + DEFAULT_ON_COMMAND_TYPE, + DEFAULT_PAYLOAD_ARM_AWAY, + DEFAULT_PAYLOAD_ARM_CUSTOM_BYPASS, + DEFAULT_PAYLOAD_ARM_HOME, + DEFAULT_PAYLOAD_ARM_NIGHT, + DEFAULT_PAYLOAD_ARM_VACATION, + DEFAULT_PAYLOAD_AVAILABLE, + DEFAULT_PAYLOAD_CLOSE, + DEFAULT_PAYLOAD_LOCK, + DEFAULT_PAYLOAD_NOT_AVAILABLE, + DEFAULT_PAYLOAD_OFF, + DEFAULT_PAYLOAD_ON, + DEFAULT_PAYLOAD_OPEN, + DEFAULT_PAYLOAD_OSCILLATE_OFF, + DEFAULT_PAYLOAD_OSCILLATE_ON, + DEFAULT_PAYLOAD_PRESS, + DEFAULT_PAYLOAD_RESET, + DEFAULT_PAYLOAD_STOP, + DEFAULT_PAYLOAD_TRIGGER, + DEFAULT_PAYLOAD_UNLOCK, + DEFAULT_PORT, + DEFAULT_POSITION_CLOSED, + DEFAULT_POSITION_OPEN, + DEFAULT_PREFIX, + DEFAULT_PROTOCOL, + DEFAULT_QOS, + DEFAULT_SPEED_RANGE_MAX, + DEFAULT_SPEED_RANGE_MIN, + DEFAULT_STATE_JAMMED, + DEFAULT_STATE_LOCKED, + DEFAULT_STATE_LOCKING, + DEFAULT_STATE_STOPPED, + DEFAULT_STATE_UNLOCKED, + DEFAULT_STATE_UNLOCKING, + DEFAULT_TILT_CLOSED_POSITION, + DEFAULT_TILT_MAX, + DEFAULT_TILT_MIN, + DEFAULT_TILT_OPEN_POSITION, + DEFAULT_TRANSPORT, + DEFAULT_WILL, + DOMAIN, + REMOTE_CODE, + REMOTE_CODE_TEXT, + SUPPORTED_PROTOCOLS, + TRANSPORT_TCP, + TRANSPORT_WEBSOCKETS, + VALUES_ON_COMMAND_TYPE, +) +from .models import MqttAvailabilityData, MqttDeviceData, MqttSubentryData +from .util import ( + async_create_certificate_temp_files, + get_file_path, + learn_more_url, + valid_birth_will, + valid_publish_topic, + valid_subscribe_topic, + valid_subscribe_topic_template, +) + +_LOGGER = logging.getLogger(__name__) + +ADDON_SETUP_TIMEOUT = 5 +ADDON_SETUP_TIMEOUT_ROUNDS = 5 + +CONF_CLIENT_KEY_PASSWORD = "client_key_password" + +OTHER_SETTINGS = "other_settings" +SET_CA_CERT = "set_ca_cert" +SET_CLIENT_CERT = "set_client_cert" + +CA_VERIFICATION_MODES = [ + "off", + "auto", + "custom", +] + +SUBENTRY_PLATFORMS = [ + Platform.ALARM_CONTROL_PANEL, + Platform.BINARY_SENSOR, + Platform.BUTTON, + Platform.CLIMATE, + Platform.COVER, + Platform.DATE, + Platform.DATETIME, + Platform.FAN, + Platform.IMAGE, + Platform.LIGHT, + Platform.LOCK, + Platform.NOTIFY, + Platform.NUMBER, + Platform.SELECT, + Platform.SENSOR, + Platform.SIREN, + Platform.SWITCH, + Platform.TEXT, + Platform.TIME, + Platform.VALVE, + Platform.WATER_HEATER, +] + +_CODE_VALIDATION_MODE = { + "remote_code": REMOTE_CODE, + "remote_code_text": REMOTE_CODE_TEXT, +} +EXCLUDE_FROM_CONFIG_IF_NONE = {CONF_ENTITY_CATEGORY, CONF_UNIT_OF_MEASUREMENT} +PWD_NOT_CHANGED = "__**password_not_changed**__" + +DEVELOPER_DOCUMENTATION_URL = "https://developers.home-assistant.io/" +USER_DOCUMENTATION_URL = "https://www.home-assistant.io/" +TZ_ZONE_ABBR_URL = ( + "https://en.wikipedia.org/wiki/List_of_tz_database_time_zones" + "#Time_zone_abbreviations" +) + +INTEGRATION_URL = f"{USER_DOCUMENTATION_URL}integrations/mqtt/" +TEMPLATING_URL = f"{USER_DOCUMENTATION_URL}docs/configuration/templating/" +COMMAND_TEMPLATING_URL = f"{TEMPLATING_URL}#using-command-templates-with-mqtt" +VALUE_TEMPLATING_URL = f"{TEMPLATING_URL}#using-value-templates-with-mqtt" +AVAILABLE_STATE_CLASSES_URL = ( + f"{DEVELOPER_DOCUMENTATION_URL}docs/core/entity/sensor/#available-state-classes" +) +NAMING_ENTITIES_URL = f"{INTEGRATION_URL}#naming-of-mqtt-entities" +REGISTRY_PROPERTIES_URL = ( + f"{DEVELOPER_DOCUMENTATION_URL}docs/core/entity/#registry-properties" +) + +TRANSLATION_DESCRIPTION_PLACEHOLDERS = { + "command_templating_url": COMMAND_TEMPLATING_URL, + "value_templating_url": VALUE_TEMPLATING_URL, + "available_state_classes_url": AVAILABLE_STATE_CLASSES_URL, + "naming_entities_url": NAMING_ENTITIES_URL, + "registry_properties_url": REGISTRY_PROPERTIES_URL, + "tz_abbr_url": TZ_ZONE_ABBR_URL, +} + +# Common selectors +BOOLEAN_SELECTOR = BooleanSelector() +TEMPLATE_SELECTOR = TemplateSelector(TemplateSelectorConfig()) +TEMPLATE_SELECTOR_READ_ONLY = TemplateSelector(TemplateSelectorConfig(read_only=True)) +TEXT_SELECTOR = TextSelector(TextSelectorConfig(type=TextSelectorType.TEXT)) +TEXT_SELECTOR_READ_ONLY = TextSelector( + TextSelectorConfig(type=TextSelectorType.TEXT, read_only=True) +) +OPTIONS_SELECTOR = SelectSelector( + SelectSelectorConfig( + options=[], + custom_value=True, + multiple=True, + ) +) +PASSWORD_SELECTOR = TextSelector(TextSelectorConfig(type=TextSelectorType.PASSWORD)) +QOS_SELECTOR = NumberSelector( + NumberSelectorConfig(mode=NumberSelectorMode.BOX, min=0, max=2) +) +URL_SELECTOR = TextSelector(TextSelectorConfig(type=TextSelectorType.URL)) + +# Config flow specific selectors +BROKER_VERIFICATION_SELECTOR = SelectSelector( + SelectSelectorConfig( + options=CA_VERIFICATION_MODES, + mode=SelectSelectorMode.DROPDOWN, + translation_key=SET_CA_CERT, + ) +) +# mime configuration from https://pki-tutorial.readthedocs.io/en/latest/mime.html +CA_CERT_UPLOAD_SELECTOR = FileSelector( + FileSelectorConfig(accept=".pem,.crt,.cer,.der,application/x-x509-ca-cert") +) +CERT_KEY_UPLOAD_SELECTOR = FileSelector( + FileSelectorConfig(accept=".pem,.key,.der,.pk8,application/pkcs8") +) +CERT_UPLOAD_SELECTOR = FileSelector( + FileSelectorConfig(accept=".pem,.crt,.cer,.der,application/x-x509-user-cert") +) +KEEPALIVE_SELECTOR = probatio.All( + NumberSelector( + NumberSelectorConfig( + mode=NumberSelectorMode.BOX, min=15, step="any", unit_of_measurement="sec" + ) + ), + probatio.Coerce(int), +) +PORT_SELECTOR = probatio.All( + NumberSelector(NumberSelectorConfig(mode=NumberSelectorMode.BOX, min=1, max=65535)), + probatio.Coerce(int), +) +PROTOCOL_SELECTOR = SelectSelector( + SelectSelectorConfig( + options=SUPPORTED_PROTOCOLS, + mode=SelectSelectorMode.DROPDOWN, + ) +) +PUBLISH_TOPIC_SELECTOR = TextSelector(TextSelectorConfig(type=TextSelectorType.TEXT)) +SUPPORTED_TRANSPORTS = [ + SelectOptionDict(value=TRANSPORT_TCP, label="TCP"), + SelectOptionDict(value=TRANSPORT_WEBSOCKETS, label="WebSocket"), +] +TRANSPORT_SELECTOR = SelectSelector( + SelectSelectorConfig( + options=SUPPORTED_TRANSPORTS, + mode=SelectSelectorMode.DROPDOWN, + ) +) +WS_HEADERS_SELECTOR = TextSelector( + TextSelectorConfig(type=TextSelectorType.TEXT, multiline=True) +) + +# MQTT device subentry selectors +ENTITY_CATEGORY_SELECTOR = SelectSelector( + SelectSelectorConfig( + options=[category.value for category in EntityCategory], + mode=SelectSelectorMode.DROPDOWN, + translation_key=CONF_ENTITY_CATEGORY, + sort=True, + ) +) +SUBENTRY_AVAILABILITY_SCHEMA = probatio.Schema( + { + probatio.Optional(CONF_AVAILABILITY_TOPIC): TEXT_SELECTOR, + probatio.Optional(CONF_AVAILABILITY_TEMPLATE): TEMPLATE_SELECTOR, + probatio.Optional( + CONF_PAYLOAD_AVAILABLE, default=DEFAULT_PAYLOAD_AVAILABLE + ): TEXT_SELECTOR, + probatio.Optional( + CONF_PAYLOAD_NOT_AVAILABLE, default=DEFAULT_PAYLOAD_NOT_AVAILABLE + ): TEXT_SELECTOR, + } +) +SUBENTRY_PLATFORM_SELECTOR = SelectSelector( + SelectSelectorConfig( + options=[platform.value for platform in SUBENTRY_PLATFORMS], + mode=SelectSelectorMode.DROPDOWN, + translation_key=CONF_PLATFORM, + ) +) +SUGGESTED_DISPLAY_PRECISION_SELECTOR = NumberSelector( + NumberSelectorConfig(mode=NumberSelectorMode.BOX, min=0, max=9) +) +TIMEOUT_SELECTOR = NumberSelector( + NumberSelectorConfig(mode=NumberSelectorMode.BOX, min=0) +) + +# Entity platform specific selectors +ALARM_CONTROL_PANEL_FEATURES_SELECTOR = SelectSelector( + SelectSelectorConfig( + options=list(ALARM_CONTROL_PANEL_SUPPORTED_FEATURES), + multiple=True, + translation_key="alarm_control_panel_features", + ) +) +ALARM_CONTROL_PANEL_CODE_MODE = SelectSelector( + SelectSelectorConfig( + options=["local_code", "remote_code", "remote_code_text"], + translation_key="alarm_control_panel_code_mode", + ) +) +BINARY_SENSOR_DEVICE_CLASS_SELECTOR = DeviceClassSelector( + DeviceClassSelectorConfig(domain=Platform.BINARY_SENSOR) +) +BUTTON_DEVICE_CLASS_SELECTOR = DeviceClassSelector( + DeviceClassSelectorConfig(domain=Platform.BUTTON) +) +CLIMATE_MODE_SELECTOR = SelectSelector( + SelectSelectorConfig( + options=["auto", "off", "cool", "heat", "dry", "fan_only"], + multiple=True, + translation_key="climate_modes", + ) +) +COVER_DEVICE_CLASS_SELECTOR = DeviceClassSelector( + DeviceClassSelectorConfig(domain=Platform.COVER) +) +FAN_SPEED_RANGE_MIN_SELECTOR = probatio.All( + NumberSelector(NumberSelectorConfig(mode=NumberSelectorMode.BOX, min=1)), + probatio.Coerce(int), +) +FAN_SPEED_RANGE_MAX_SELECTOR = probatio.All( + NumberSelector(NumberSelectorConfig(mode=NumberSelectorMode.BOX, min=2)), + probatio.Coerce(int), +) +FLASH_TIME_SELECTOR = NumberSelector( + NumberSelectorConfig( + mode=NumberSelectorMode.BOX, + min=1, + ) +) +HUMIDITY_SELECTOR = probatio.All( + NumberSelector( + NumberSelectorConfig(mode=NumberSelectorMode.BOX, min=0, max=100, step=1) + ), + probatio.Coerce(int), +) +IMAGE_CONTENT_TYPE_SELECTOR = SelectSelector( + SelectSelectorConfig( + options=[ + SelectOptionDict( + value="image/jpeg", label="Joint Photographic Expert Group image (JPEG)" + ), + SelectOptionDict( + value="image/png", label="Portable Network Graphics (PNG)" + ), + SelectOptionDict( + value="image/apng", label="Animated Portable Network Graphics (APNG)" + ), + SelectOptionDict(value="image/avif", label="AV1 Image File Format (AVIF)"), + SelectOptionDict( + value="image/gif", label="Graphics Interchange Format (GIF)" + ), + SelectOptionDict( + value="image/svg+xml", label="Scalable Vector Graphics (SVG)" + ), + SelectOptionDict(value="image/webp", label="Web Picture format (WEBP)"), + ], + mode=SelectSelectorMode.DROPDOWN, + ) +) +IMAGE_ENCODING_SELECTOR = SelectSelector( + SelectSelectorConfig( + options=["raw", "b64"], + translation_key="image_encoding", + mode=SelectSelectorMode.DROPDOWN, + ) +) +IMAGE_PROCESSING_MODE_SELECTOR = SelectSelector( + SelectSelectorConfig( + options=["image_url", "image_data"], + translation_key="image_processing_mode", + ) +) +KELVIN_SELECTOR = NumberSelector( + NumberSelectorConfig( + mode=NumberSelectorMode.BOX, + min=1000, + max=10000, + step="any", + unit_of_measurement="K", + ) +) +LIGHT_SCHEMA_SELECTOR = SelectSelector( + SelectSelectorConfig( + options=["basic", "json", "template"], + translation_key="light_schema", + ) +) +MIN_MAX_SELECTOR = NumberSelector(NumberSelectorConfig(step=1e-3)) +NUMBER_DEVICE_CLASS_SELECTOR = DeviceClassSelector( + DeviceClassSelectorConfig(domain=Platform.NUMBER) +) +NUMBER_MODE_SELECTOR = SelectSelector( + SelectSelectorConfig( + options=[mode.value for mode in NumberMode], + mode=SelectSelectorMode.DROPDOWN, + translation_key="number_mode", + sort=True, + ) +) +ON_COMMAND_TYPE_SELECTOR = SelectSelector( + SelectSelectorConfig( + options=VALUES_ON_COMMAND_TYPE, + mode=SelectSelectorMode.DROPDOWN, + translation_key=CONF_ON_COMMAND_TYPE, + sort=True, + ) +) +POSITION_SELECTOR = NumberSelector(NumberSelectorConfig(mode=NumberSelectorMode.BOX)) +PRECISION_SELECTOR = SelectSelector( + SelectSelectorConfig( + options=["1.0", "0.5", "0.1"], + mode=SelectSelectorMode.DROPDOWN, + ) +) +PRESET_MODES_SELECTOR = OPTIONS_SELECTOR +SCALE_SELECTOR = NumberSelector( + NumberSelectorConfig( + mode=NumberSelectorMode.BOX, + min=1, + max=255, + step=1, + ) +) +SENSOR_DEVICE_CLASS_SELECTOR = DeviceClassSelector( + DeviceClassSelectorConfig(domain=Platform.SENSOR) +) +SENSOR_ENTITY_CATEGORY_SELECTOR = SelectSelector( + SelectSelectorConfig( + options=[EntityCategory.DIAGNOSTIC.value], + mode=SelectSelectorMode.DROPDOWN, + translation_key=CONF_ENTITY_CATEGORY, + sort=True, + ) +) +SENSOR_STATE_CLASS_SELECTOR = StateClassSelector() +STEP_SELECTOR = NumberSelector(NumberSelectorConfig(min=1e-3, step=1e-3)) +SUPPORTED_COLOR_MODES_SELECTOR = SelectSelector( + SelectSelectorConfig( + options=[platform.value for platform in VALID_COLOR_MODES], + mode=SelectSelectorMode.DROPDOWN, + translation_key=CONF_SUPPORTED_COLOR_MODES, + multiple=True, + sort=True, + ) +) +SWITCH_DEVICE_CLASS_SELECTOR = DeviceClassSelector( + DeviceClassSelectorConfig(domain=Platform.SWITCH) +) +TARGET_TEMPERATURE_FEATURE_SELECTOR = SelectSelector( + SelectSelectorConfig( + options=["single", "high_low", "none"], + mode=SelectSelectorMode.DROPDOWN, + translation_key="target_temperature_feature", + ) +) +TEMPERATURE_UNIT_SELECTOR = SelectSelector( + SelectSelectorConfig( + options=[ + SelectOptionDict(value="C", label="°C"), + SelectOptionDict(value="F", label="°F"), + ], + mode=SelectSelectorMode.DROPDOWN, + ) +) +TEXT_MODE_SELECTOR = SelectSelector( + SelectSelectorConfig( + options=[TextSelectorType.TEXT.value, TextSelectorType.PASSWORD.value], + mode=SelectSelectorMode.DROPDOWN, + translation_key="text_mode", + ) +) +TEXT_SIZE_SELECTOR = NumberSelector( + NumberSelectorConfig(min=0, max=255, step=1, mode=NumberSelectorMode.BOX) +) +VALVE_DEVICE_CLASS_SELECTOR = DeviceClassSelector( + DeviceClassSelectorConfig(domain=Platform.VALVE) +) +VALVE_POSITION_SELECTOR = NumberSelector( + NumberSelectorConfig(mode=NumberSelectorMode.BOX, step=1) +) +WATER_HEATER_MODE_SELECTOR = SelectSelector( + SelectSelectorConfig( + options=[ + "off", + "eco", + "electric", + "gas", + "heat_pump", + "high_demand", + "performance", + ], + multiple=True, + translation_key="water_heater_modes", + ) +) + + +@callback +def configured_target_temperature_feature(config: dict[str, Any]) -> str: + """Calculate current target temperature feature from config.""" + if config == {CONF_PLATFORM: Platform.CLIMATE} or CONF_TEMP_COMMAND_TOPIC in config: + # default to single on initial set + return "single" + if CONF_TEMP_HIGH_COMMAND_TOPIC in config: + return "high_low" + return "none" + + +@callback +def default_alarm_control_panel_code(config: dict[str, Any]) -> str: + """Return alarm control panel code based on the stored code and code mode.""" + code: str + if config["alarm_control_panel_code_mode"] in _CODE_VALIDATION_MODE: + # Return magic value for remote code validation + return _CODE_VALIDATION_MODE[config["alarm_control_panel_code_mode"]] + if (code := config.get(CONF_CODE, "")) in _CODE_VALIDATION_MODE.values(): + # Remove magic value for remote code validation + return "" + + return code + + +@callback +def default_precision(config: dict[str, Any]) -> str: + """Return the thermostat precision for system default unit.""" + + return str( + config.get( + CONF_PRECISION, + 0.1 + if cv.temperature_unit(config[CONF_TEMPERATURE_UNIT]) + is UnitOfTemperature.CELSIUS + else 1.0, + ) + ) + + +@callback +def no_empty_list(value: list[Any]) -> list[Any]: + """Validate a selector returns at least one item.""" + if not value: + raise probatio.Invalid("empty_list_not_allowed") + return value + + +@callback +def temperature_default_from_celsius_to_system_default( + value: float, +) -> Callable[[dict[str, Any]], int]: + """Return temperature in Celsius in system default unit.""" + + def _default(config: dict[str, Any]) -> int: + return round( + TemperatureConverter.convert( + value, + UnitOfTemperature.CELSIUS, + cv.temperature_unit(config[CONF_TEMPERATURE_UNIT]), + ) + ) + + return _default + + +@callback +def temperature_selector(config: dict[str, Any]) -> Selector: + """Return a temperature selector with configured or system unit.""" + + return NumberSelector( + NumberSelectorConfig( + mode=NumberSelectorMode.BOX, + unit_of_measurement=cv.temperature_unit(config[CONF_TEMPERATURE_UNIT]), + ) + ) + + +@callback +def temperature_step_selector(config: dict[str, Any]) -> Selector: + """Return a temperature step selector.""" + + return NumberSelector( + NumberSelectorConfig( + mode=NumberSelectorMode.BOX, + min=0.1, + max=10.0, + step=0.1, + unit_of_measurement=cv.temperature_unit(config[CONF_TEMPERATURE_UNIT]), + ) + ) + + +@callback +def unit_of_measurement_selector(user_data: dict[str, Any | None]) -> Selector: + """Return a context based unit of measurement selector.""" + + if (state_class := user_data.get(CONF_STATE_CLASS)) in STATE_CLASS_UNITS: + return SelectSelector( + SelectSelectorConfig( + options=[str(uom) for uom in STATE_CLASS_UNITS[state_class]], + sort=True, + custom_value=True, + ) + ) + + if ( + device_class := user_data.get(CONF_DEVICE_CLASS) + ) is None or device_class not in DEVICE_CLASS_UNITS: + return TEXT_SELECTOR + return SelectSelector( + SelectSelectorConfig( + options=[str(uom) for uom in DEVICE_CLASS_UNITS[device_class]], + sort=True, + custom_value=True, + ) + ) + + +@callback +def number_unit_of_measurement_selector(user_data: dict[str, Any | None]) -> Selector: + """Return a context based unit of measurement selector for number entities.""" + + if ( + device_class := user_data.get(CONF_DEVICE_CLASS) + ) is None or device_class not in NUMBER_DEVICE_CLASS_UNITS: + return TEXT_SELECTOR + return SelectSelector( + SelectSelectorConfig( + options=[str(uom) for uom in NUMBER_DEVICE_CLASS_UNITS[device_class]], + sort=True, + custom_value=True, + ) + ) + + +@callback +def validate(validator: Callable[[Any], Any]) -> Callable[[Any], Any]: + """Run validator, then return the unmodified input.""" + + def _validate(value: Any) -> Any: + validator(value) + return value + + return _validate + + +@callback +def validate_field( + field: str, + validator: Callable[..., Any], + user_input: dict[str, Any] | None, + errors: dict[str, str], + error: str, +) -> None: + """Validate a single field.""" + if user_input is None or field not in user_input or validator is None: + return + try: + user_input[field] = validator(user_input[field]) + except ValueError, probatio.Error, probatio.Invalid: + errors[field] = error + + +# Entity platform config validation +@callback +def validate_climate_platform_config(config: dict[str, Any]) -> dict[str, str]: + """Validate the climate platform options.""" + errors: dict[str, str] = {} + if ( + CONF_PRESET_MODES_LIST in config + and PRESET_NONE in config[CONF_PRESET_MODES_LIST] + ): + errors["climate_preset_mode_settings"] = "preset_mode_none_not_allowed" + if ( + CONF_HUMIDITY_MIN in config + and config[CONF_HUMIDITY_MIN] >= config[CONF_HUMIDITY_MAX] + ): + errors["target_humidity_settings"] = "max_below_min_humidity" + if CONF_TEMP_MIN in config and config[CONF_TEMP_MIN] >= config[CONF_TEMP_MAX]: + errors["target_temperature_settings"] = "max_below_min_temperature" + + return errors + + +@callback +def validate_cover_platform_config(config: dict[str, Any]) -> dict[str, str]: + """Validate the cover platform options.""" + errors: dict[str, str] = {} + + # 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: + errors["cover_position_settings"] = ( + "cover_get_and_set_position_must_be_set_together" + ) + + # 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: + errors[CONF_VALUE_TEMPLATE] = ( + "cover_value_template_must_be_used_with_state_topic" + ) + + if CONF_GET_POSITION_TEMPLATE in config and CONF_GET_POSITION_TOPIC not in config: + errors["cover_position_settings"] = ( + "cover_get_position_template_must_be_used_with_get_position_topic" + ) + + if CONF_SET_POSITION_TEMPLATE in config and CONF_SET_POSITION_TOPIC not in config: + errors["cover_position_settings"] = ( + "cover_set_position_template_must_be_used_with_set_position_topic" + ) + + if CONF_TILT_COMMAND_TEMPLATE in config and CONF_TILT_COMMAND_TOPIC not in config: + errors["cover_tilt_settings"] = ( + "cover_tilt_command_template_must_be_used_with_tilt_command_topic" + ) + + if CONF_TILT_STATUS_TEMPLATE in config and CONF_TILT_STATUS_TOPIC not in config: + errors["cover_tilt_settings"] = ( + "cover_tilt_status_template_must_be_used_with_tilt_status_topic" + ) + + return errors + + +@callback +def validate_fan_platform_config(config: dict[str, Any]) -> dict[str, str]: + """Validate the fan config options.""" + errors: dict[str, str] = {} + if ( + CONF_SPEED_RANGE_MIN in config + and CONF_SPEED_RANGE_MAX in config + and config[CONF_SPEED_RANGE_MIN] >= config[CONF_SPEED_RANGE_MAX] + ): + errors["fan_speed_settings"] = ( + "fan_speed_range_max_must_be_greater_than_speed_range_min" + ) + if ( + CONF_PRESET_MODES_LIST in config + and config.get(CONF_PAYLOAD_RESET_PRESET_MODE) in config[CONF_PRESET_MODES_LIST] + ): + errors["fan_preset_mode_settings"] = ( + "fan_preset_mode_reset_in_preset_modes_list" + ) + + return errors + + +@callback +def validate_light_platform_config(user_data: dict[str, Any]) -> dict[str, str]: + """Validate MQTT light configuration.""" + errors: dict[str, Any] = {} + if user_data.get(CONF_MIN_KELVIN, DEFAULT_MIN_KELVIN) >= user_data.get( + CONF_MAX_KELVIN, DEFAULT_MAX_KELVIN + ): + errors[OTHER_SETTINGS] = "max_below_min_kelvin" + return errors + + +@callback +def validate_number_platform_config(config: dict[str, Any]) -> dict[str, str]: + """Validate MQTT number configuration.""" + errors: dict[str, Any] = {} + if ( + CONF_MIN in config + and CONF_MAX in config + and config[CONF_MIN] > config[CONF_MAX] + ): + errors[CONF_MIN] = "max_below_min" + errors[CONF_MAX] = "max_below_min" + + if (unit_of_measurement := config.get(CONF_UNIT_OF_MEASUREMENT)) == "None": + unit_of_measurement = None + + if ( + (device_class := config.get(CONF_DEVICE_CLASS)) is not None + and device_class in NUMBER_DEVICE_CLASS_UNITS + and unit_of_measurement not in NUMBER_DEVICE_CLASS_UNITS[device_class] + ): + errors[CONF_UNIT_OF_MEASUREMENT] = "invalid_uom" + + return errors + + +@callback +def validate_sensor_platform_config( + config: dict[str, Any], +) -> dict[str, str]: + """Validate the sensor options, state and device class config.""" + errors: dict[str, str] = {} + # Only allow `options` to be set for `enum` sensors + # to limit the possible sensor values + if config.get(CONF_OPTIONS) is not None: + if config.get(CONF_STATE_CLASS) or config.get(CONF_UNIT_OF_MEASUREMENT): + errors[CONF_OPTIONS] = "options_not_allowed_with_state_class_or_uom" + + if (device_class := config.get(CONF_DEVICE_CLASS)) != SensorDeviceClass.ENUM: + errors[CONF_DEVICE_CLASS] = "options_device_class_enum" + + if ( + (device_class := config.get(CONF_DEVICE_CLASS)) == SensorDeviceClass.ENUM + and errors is not None + and CONF_OPTIONS not in config + ): + errors[CONF_OPTIONS] = "options_with_enum_device_class" + + unit_of_measurement: str | None = None + if ( + device_class in DEVICE_CLASS_UNITS + and (unit_of_measurement := config.get(CONF_UNIT_OF_MEASUREMENT)) is None + and errors is not None + ): + # Do not allow an empty unit of measurement in a subentry data flow + errors[CONF_UNIT_OF_MEASUREMENT] = "uom_required_for_device_class" + return errors + + if unit_of_measurement == "None": + unit_of_measurement = None + config.pop(CONF_UNIT_OF_MEASUREMENT) + + if ( + device_class is not None + and device_class in DEVICE_CLASS_UNITS + and unit_of_measurement not in DEVICE_CLASS_UNITS[device_class] + ): + errors[CONF_UNIT_OF_MEASUREMENT] = "invalid_uom" + + if ( + (state_class := config.get(CONF_STATE_CLASS)) is not None + and state_class in STATE_CLASS_UNITS + and config.get(CONF_UNIT_OF_MEASUREMENT) not in STATE_CLASS_UNITS[state_class] + ): + errors[CONF_UNIT_OF_MEASUREMENT] = "invalid_uom_for_state_class" + + return errors + + +@callback +def validate_text_platform_config( + config: dict[str, Any], +) -> dict[str, str]: + """Validate the text entity options.""" + errors: dict[str, str] = {} + if ( + CONF_MIN in config + and CONF_MAX in config + and config[CONF_MIN] > config[CONF_MAX] + ): + errors["text_other_settings"] = "max_below_min" + + return errors + + +@callback +def validate_water_heater_platform_config(config: dict[str, Any]) -> dict[str, str]: + """Validate the water heater platform options.""" + errors: dict[str, str] = {} + if CONF_TEMP_MIN in config and config[CONF_TEMP_MIN] >= config[CONF_TEMP_MAX]: + errors["target_temperature_settings"] = "max_below_min_temperature" + + return errors + + +ENTITY_CONFIG_VALIDATOR: dict[ + str, + Callable[[dict[str, Any]], dict[str, str]] | None, +] = { + Platform.ALARM_CONTROL_PANEL: None, + Platform.BINARY_SENSOR: None, + Platform.BUTTON: None, + Platform.CLIMATE: validate_climate_platform_config, + Platform.COVER: validate_cover_platform_config, + Platform.DATE: None, + Platform.DATETIME: None, + Platform.FAN: validate_fan_platform_config, + Platform.IMAGE: None, + Platform.LIGHT: validate_light_platform_config, + Platform.LOCK: None, + Platform.NOTIFY: None, + Platform.NUMBER: validate_number_platform_config, + Platform.SELECT: None, + Platform.SENSOR: validate_sensor_platform_config, + Platform.SIREN: None, + Platform.SWITCH: None, + Platform.TEXT: validate_text_platform_config, + Platform.TIME: None, + Platform.VALVE: None, + Platform.WATER_HEATER: validate_water_heater_platform_config, +} + + +@dataclass(frozen=True, kw_only=True) +class PlatformField: + """Stores a platform config field schema, required flag and validator.""" + + selector: ( + Selector[Any] | probatio.All[Any] | Callable[[dict[str, Any]], Selector[Any]] + ) + required: bool + validator: Callable[[Any], Any] | None = None + error: str | None = None + default: Any | Callable[[dict[str, Any]], Any] | probatio.Undefined | None = ( + probatio.UNDEFINED + ) + is_schema_default: bool = False + include_in_config: bool = False + exclude_from_reconfig: bool = False + exclude_from_config: bool = False + conditions: tuple[dict[str, Any], ...] | None = None + custom_filtering: bool = False + section: str | None = None + + +COMMON_ENTITY_FIELDS: dict[str, PlatformField] = { + CONF_PLATFORM: PlatformField( + selector=SUBENTRY_PLATFORM_SELECTOR, + required=True, + exclude_from_reconfig=True, + ), + CONF_NAME: PlatformField( + selector=TEXT_SELECTOR, + required=False, + exclude_from_reconfig=True, + default=None, + ), + CONF_ENTITY_PICTURE: PlatformField( + selector=TEXT_SELECTOR, required=False, validator=cv.url, error="invalid_url" + ), +} +SHARED_PLATFORM_ENTITY_FIELDS: dict[str, PlatformField] = { + CONF_ENTITY_CATEGORY: PlatformField( + selector=ENTITY_CATEGORY_SELECTOR, + required=False, + default=None, + ), +} +PLATFORM_ENTITY_FIELDS: dict[Platform, dict[str, PlatformField]] = { + Platform.ALARM_CONTROL_PANEL: { + CONF_SUPPORTED_FEATURES: PlatformField( + selector=ALARM_CONTROL_PANEL_FEATURES_SELECTOR, + required=True, + default=lambda config: config.get( + CONF_SUPPORTED_FEATURES, list(ALARM_CONTROL_PANEL_SUPPORTED_FEATURES) + ), + ), + "alarm_control_panel_code_mode": PlatformField( + selector=ALARM_CONTROL_PANEL_CODE_MODE, + required=True, + exclude_from_config=True, + default=lambda config: ( + config[CONF_CODE].lower() + if config.get(CONF_CODE) in (REMOTE_CODE, REMOTE_CODE_TEXT) + else "local_code" + ), + ), + }, + Platform.BINARY_SENSOR: { + CONF_DEVICE_CLASS: PlatformField( + selector=BINARY_SENSOR_DEVICE_CLASS_SELECTOR, + required=False, + ), + CONF_ENTITY_CATEGORY: PlatformField( + selector=SENSOR_ENTITY_CATEGORY_SELECTOR, + required=False, + default=None, + ), + }, + Platform.BUTTON: { + CONF_DEVICE_CLASS: PlatformField( + selector=BUTTON_DEVICE_CLASS_SELECTOR, + required=False, + ), + }, + Platform.CLIMATE: { + CONF_TEMPERATURE_UNIT: PlatformField( + selector=TEMPERATURE_UNIT_SELECTOR, + validator=validate(cv.temperature_unit), + required=True, + exclude_from_reconfig=True, + default=lambda _: ( + "C" + if async_get_hass().config.units.temperature_unit + is UnitOfTemperature.CELSIUS + else "F" + ), + ), + "climate_feature_action": PlatformField( + selector=BOOLEAN_SELECTOR, + required=False, + exclude_from_config=True, + default=lambda config: bool(config.get(CONF_ACTION_TOPIC)), + ), + "climate_feature_target_temperature": PlatformField( + selector=TARGET_TEMPERATURE_FEATURE_SELECTOR, + required=False, + exclude_from_config=True, + default=configured_target_temperature_feature, + ), + "climate_feature_current_temperature": PlatformField( + selector=BOOLEAN_SELECTOR, + required=False, + exclude_from_config=True, + default=lambda config: bool(config.get(CONF_CURRENT_TEMP_TOPIC)), + ), + "climate_feature_target_humidity": PlatformField( + selector=BOOLEAN_SELECTOR, + required=False, + exclude_from_config=True, + default=lambda config: bool(config.get(CONF_HUMIDITY_COMMAND_TOPIC)), + ), + "climate_feature_current_humidity": PlatformField( + selector=BOOLEAN_SELECTOR, + required=False, + exclude_from_config=True, + default=lambda config: bool(config.get(CONF_HUMIDITY_STATE_TOPIC)), + ), + "climate_feature_preset_modes": PlatformField( + selector=BOOLEAN_SELECTOR, + required=False, + exclude_from_config=True, + default=lambda config: bool(config.get(CONF_PRESET_MODES_LIST)), + ), + "climate_feature_fan_modes": PlatformField( + selector=BOOLEAN_SELECTOR, + required=False, + exclude_from_config=True, + default=lambda config: bool(config.get(CONF_FAN_MODE_LIST)), + ), + "climate_feature_swing_modes": PlatformField( + selector=BOOLEAN_SELECTOR, + required=False, + exclude_from_config=True, + default=lambda config: bool(config.get(CONF_SWING_MODE_LIST)), + ), + "climate_feature_swing_horizontal_modes": PlatformField( + selector=BOOLEAN_SELECTOR, + required=False, + exclude_from_config=True, + default=lambda config: bool(config.get(CONF_SWING_HORIZONTAL_MODE_LIST)), + ), + "climate_feature_power": PlatformField( + selector=BOOLEAN_SELECTOR, + required=False, + exclude_from_config=True, + default=lambda config: bool(config.get(CONF_POWER_COMMAND_TOPIC)), + ), + }, + Platform.COVER: { + CONF_DEVICE_CLASS: PlatformField( + selector=COVER_DEVICE_CLASS_SELECTOR, + required=False, + ), + }, + Platform.DATE: {}, + Platform.DATETIME: {}, + Platform.FAN: { + "fan_feature_speed": PlatformField( + selector=BOOLEAN_SELECTOR, + required=False, + exclude_from_config=True, + default=lambda config: bool(config.get(CONF_PERCENTAGE_COMMAND_TOPIC)), + ), + "fan_feature_preset_modes": PlatformField( + selector=BOOLEAN_SELECTOR, + required=False, + exclude_from_config=True, + default=lambda config: bool(config.get(CONF_PRESET_MODE_COMMAND_TOPIC)), + ), + "fan_feature_oscillation": PlatformField( + selector=BOOLEAN_SELECTOR, + required=False, + exclude_from_config=True, + default=lambda config: bool(config.get(CONF_OSCILLATION_COMMAND_TOPIC)), + ), + "fan_feature_direction": PlatformField( + selector=BOOLEAN_SELECTOR, + required=False, + exclude_from_config=True, + default=lambda config: bool(config.get(CONF_DIRECTION_COMMAND_TOPIC)), + ), + }, + Platform.IMAGE: { + "image_processing_mode": PlatformField( + selector=IMAGE_PROCESSING_MODE_SELECTOR, + required=True, + exclude_from_config=True, + default=( + lambda config: ( + "image_url" + if config.get(CONF_IMAGE_TOPIC) is None + else "image_data" + ) + ), + ) + }, + Platform.LIGHT: { + CONF_SCHEMA: PlatformField( + selector=LIGHT_SCHEMA_SELECTOR, + required=True, + default="basic", + exclude_from_reconfig=True, + ), + CONF_COLOR_TEMP_KELVIN: PlatformField( + selector=BOOLEAN_SELECTOR, + required=True, + default=True, + is_schema_default=True, + ), + }, + Platform.LOCK: {}, + Platform.NOTIFY: {}, + Platform.NUMBER: { + CONF_DEVICE_CLASS: PlatformField( + selector=NUMBER_DEVICE_CLASS_SELECTOR, + required=False, + ), + CONF_UNIT_OF_MEASUREMENT: PlatformField( + selector=number_unit_of_measurement_selector, + required=False, + custom_filtering=True, + ), + }, + Platform.SELECT: {}, + Platform.SENSOR: { + CONF_DEVICE_CLASS: PlatformField( + selector=SENSOR_DEVICE_CLASS_SELECTOR, required=False + ), + CONF_STATE_CLASS: PlatformField( + selector=SENSOR_STATE_CLASS_SELECTOR, required=False + ), + CONF_UNIT_OF_MEASUREMENT: PlatformField( + selector=unit_of_measurement_selector, + required=False, + custom_filtering=True, + ), + CONF_SUGGESTED_DISPLAY_PRECISION: PlatformField( + selector=SUGGESTED_DISPLAY_PRECISION_SELECTOR, + required=False, + validator=cv.positive_int, + section=OTHER_SETTINGS, + ), + CONF_OPTIONS: PlatformField( + selector=OPTIONS_SELECTOR, + required=False, + conditions=({"device_class": "enum"},), + ), + CONF_ENTITY_CATEGORY: PlatformField( + selector=SENSOR_ENTITY_CATEGORY_SELECTOR, + required=False, + default=None, + ), + }, + Platform.SIREN: {}, + Platform.SWITCH: { + CONF_DEVICE_CLASS: PlatformField( + selector=SWITCH_DEVICE_CLASS_SELECTOR, required=False + ), + }, + Platform.TEXT: {}, + Platform.TIME: {}, + Platform.VALVE: { + CONF_DEVICE_CLASS: PlatformField( + selector=VALVE_DEVICE_CLASS_SELECTOR, required=False, default=None + ), + CONF_REPORTS_POSITION: PlatformField( + selector=BOOLEAN_SELECTOR, + required=True, + default=False, + ), + }, + Platform.WATER_HEATER: { + CONF_TEMPERATURE_UNIT: PlatformField( + selector=TEMPERATURE_UNIT_SELECTOR, + validator=validate(cv.temperature_unit), + required=True, + exclude_from_reconfig=True, + default=lambda _: ( + "C" + if async_get_hass().config.units.temperature_unit + is UnitOfTemperature.CELSIUS + else "F" + ), + ), + "water_heater_feature_current_temperature": PlatformField( + selector=BOOLEAN_SELECTOR, + required=False, + exclude_from_config=True, + default=lambda config: bool(config.get(CONF_CURRENT_TEMP_TOPIC)), + ), + "water_heater_feature_power": PlatformField( + selector=BOOLEAN_SELECTOR, + required=False, + exclude_from_config=True, + default=lambda config: bool(config.get(CONF_POWER_COMMAND_TOPIC)), + ), + }, +} +PLATFORM_MQTT_FIELDS: dict[Platform, dict[str, PlatformField]] = { + Platform.ALARM_CONTROL_PANEL: { + CONF_COMMAND_TOPIC: PlatformField( + selector=TEXT_SELECTOR, + required=True, + validator=valid_publish_topic, + error="invalid_publish_topic", + ), + CONF_COMMAND_TEMPLATE: PlatformField( + selector=TEMPLATE_SELECTOR, + required=False, + default=DEFAULT_ALARM_CONTROL_PANEL_COMMAND_TEMPLATE, + validator=validate(cv.template), + error="invalid_template", + ), + CONF_STATE_TOPIC: PlatformField( + selector=TEXT_SELECTOR, + required=True, + validator=valid_subscribe_topic, + error="invalid_subscribe_topic", + ), + CONF_VALUE_TEMPLATE: PlatformField( + selector=TEMPLATE_SELECTOR, + required=False, + validator=validate(cv.template), + error="invalid_template", + ), + CONF_CODE: PlatformField( + selector=PASSWORD_SELECTOR, + required=True, + include_in_config=True, + default=default_alarm_control_panel_code, + conditions=({"alarm_control_panel_code_mode": "local_code"},), + ), + CONF_CODE_ARM_REQUIRED: PlatformField( + selector=BOOLEAN_SELECTOR, + required=True, + default=True, + ), + CONF_CODE_DISARM_REQUIRED: PlatformField( + selector=BOOLEAN_SELECTOR, + required=True, + default=True, + ), + CONF_CODE_TRIGGER_REQUIRED: PlatformField( + selector=BOOLEAN_SELECTOR, + required=True, + default=True, + ), + CONF_RETAIN: PlatformField(selector=BOOLEAN_SELECTOR, required=False), + CONF_PAYLOAD_ARM_HOME: PlatformField( + selector=TEXT_SELECTOR, + required=False, + default=DEFAULT_PAYLOAD_ARM_HOME, + section="alarm_control_panel_payload_settings", + ), + CONF_PAYLOAD_ARM_AWAY: PlatformField( + selector=TEXT_SELECTOR, + required=False, + default=DEFAULT_PAYLOAD_ARM_AWAY, + section="alarm_control_panel_payload_settings", + ), + CONF_PAYLOAD_ARM_NIGHT: PlatformField( + selector=TEXT_SELECTOR, + required=False, + default=DEFAULT_PAYLOAD_ARM_NIGHT, + section="alarm_control_panel_payload_settings", + ), + CONF_PAYLOAD_ARM_VACATION: PlatformField( + selector=TEXT_SELECTOR, + required=False, + default=DEFAULT_PAYLOAD_ARM_VACATION, + section="alarm_control_panel_payload_settings", + ), + CONF_PAYLOAD_ARM_CUSTOM_BYPASS: PlatformField( + selector=TEXT_SELECTOR, + required=False, + default=DEFAULT_PAYLOAD_ARM_CUSTOM_BYPASS, + section="alarm_control_panel_payload_settings", + ), + CONF_PAYLOAD_TRIGGER: PlatformField( + selector=TEXT_SELECTOR, + required=False, + default=DEFAULT_PAYLOAD_TRIGGER, + section="alarm_control_panel_payload_settings", + ), + }, + Platform.BINARY_SENSOR: { + CONF_STATE_TOPIC: PlatformField( + selector=TEXT_SELECTOR, + required=True, + validator=valid_subscribe_topic, + error="invalid_subscribe_topic", + ), + CONF_VALUE_TEMPLATE: PlatformField( + selector=TEMPLATE_SELECTOR, + required=False, + validator=validate(cv.template), + error="invalid_template", + ), + CONF_PAYLOAD_OFF: PlatformField( + selector=TEXT_SELECTOR, + required=False, + default=DEFAULT_PAYLOAD_OFF, + ), + CONF_PAYLOAD_ON: PlatformField( + selector=TEXT_SELECTOR, + required=False, + default=DEFAULT_PAYLOAD_ON, + ), + CONF_EXPIRE_AFTER: PlatformField( + selector=TIMEOUT_SELECTOR, + required=False, + validator=cv.positive_int, + section=OTHER_SETTINGS, + ), + CONF_OFF_DELAY: PlatformField( + selector=TIMEOUT_SELECTOR, + required=False, + validator=cv.positive_int, + section=OTHER_SETTINGS, + ), + }, + Platform.BUTTON: { + CONF_COMMAND_TOPIC: PlatformField( + selector=TEXT_SELECTOR, + required=True, + validator=valid_publish_topic, + error="invalid_publish_topic", + ), + CONF_COMMAND_TEMPLATE: PlatformField( + selector=TEMPLATE_SELECTOR, + required=False, + validator=validate(cv.template), + error="invalid_template", + ), + CONF_PAYLOAD_PRESS: PlatformField( + selector=TEXT_SELECTOR, + required=False, + default=DEFAULT_PAYLOAD_PRESS, + ), + CONF_RETAIN: PlatformField(selector=BOOLEAN_SELECTOR, required=False), + }, + Platform.CLIMATE: { + # operation mode settings + CONF_MODE_COMMAND_TOPIC: PlatformField( + selector=TEXT_SELECTOR, + required=False, + validator=valid_publish_topic, + error="invalid_publish_topic", + ), + CONF_MODE_COMMAND_TEMPLATE: PlatformField( + selector=TEMPLATE_SELECTOR, + required=False, + validator=validate(cv.template), + error="invalid_template", + ), + CONF_MODE_STATE_TOPIC: PlatformField( + selector=TEXT_SELECTOR, + required=False, + validator=valid_subscribe_topic, + error="invalid_subscribe_topic", + ), + CONF_MODE_STATE_TEMPLATE: PlatformField( + selector=TEMPLATE_SELECTOR, + required=False, + validator=validate(cv.template), + error="invalid_template", + ), + CONF_MODE_LIST: PlatformField( + selector=CLIMATE_MODE_SELECTOR, + required=True, + default=[], + validator=validate(no_empty_list), + error="empty_list_not_allowed", + ), + CONF_RETAIN: PlatformField( + selector=BOOLEAN_SELECTOR, required=False, validator=validate(bool) + ), + CONF_OPTIMISTIC: PlatformField( + selector=BOOLEAN_SELECTOR, required=False, validator=validate(bool) + ), + # current action settings + CONF_ACTION_TOPIC: PlatformField( + selector=TEXT_SELECTOR, + required=True, + validator=valid_subscribe_topic, + error="invalid_subscribe_topic", + section="climate_action_settings", + conditions=({"climate_feature_action": True},), + ), + CONF_ACTION_TEMPLATE: PlatformField( + selector=TEMPLATE_SELECTOR, + required=False, + validator=validate(cv.template), + error="invalid_template", + section="climate_action_settings", + conditions=({"climate_feature_action": True},), + ), + # target temperature settings + CONF_TEMP_COMMAND_TOPIC: PlatformField( + selector=TEXT_SELECTOR, + required=True, + validator=valid_publish_topic, + error="invalid_publish_topic", + section="target_temperature_settings", + conditions=({"climate_feature_target_temperature": "single"},), + ), + CONF_TEMP_COMMAND_TEMPLATE: PlatformField( + selector=TEMPLATE_SELECTOR, + required=False, + validator=validate(cv.template), + error="invalid_template", + section="target_temperature_settings", + conditions=({"climate_feature_target_temperature": "single"},), + ), + CONF_TEMP_STATE_TOPIC: PlatformField( + selector=TEXT_SELECTOR, + required=False, + validator=valid_subscribe_topic, + error="invalid_subscribe_topic", + section="target_temperature_settings", + conditions=({"climate_feature_target_temperature": "single"},), + ), + CONF_TEMP_STATE_TEMPLATE: PlatformField( + selector=TEMPLATE_SELECTOR, + required=False, + validator=validate(cv.template), + error="invalid_template", + section="target_temperature_settings", + conditions=({"climate_feature_target_temperature": "single"},), + ), + CONF_TEMP_LOW_COMMAND_TOPIC: PlatformField( + selector=TEXT_SELECTOR, + required=True, + validator=valid_publish_topic, + error="invalid_publish_topic", + section="target_temperature_settings", + conditions=({"climate_feature_target_temperature": "high_low"},), + ), + CONF_TEMP_LOW_COMMAND_TEMPLATE: PlatformField( + selector=TEMPLATE_SELECTOR, + required=False, + validator=validate(cv.template), + error="invalid_template", + section="target_temperature_settings", + conditions=({"climate_feature_target_temperature": "high_low"},), + ), + CONF_TEMP_LOW_STATE_TOPIC: PlatformField( + selector=TEXT_SELECTOR, + required=False, + validator=valid_subscribe_topic, + error="invalid_subscribe_topic", + section="target_temperature_settings", + conditions=({"climate_feature_target_temperature": "high_low"},), + ), + CONF_TEMP_LOW_STATE_TEMPLATE: PlatformField( + selector=TEMPLATE_SELECTOR, + required=False, + validator=validate(cv.template), + error="invalid_template", + section="target_temperature_settings", + conditions=({"climate_feature_target_temperature": "high_low"},), + ), + CONF_TEMP_HIGH_COMMAND_TOPIC: PlatformField( + selector=TEXT_SELECTOR, + required=True, + validator=valid_publish_topic, + error="invalid_publish_topic", + section="target_temperature_settings", + conditions=({"climate_feature_target_temperature": "high_low"},), + ), + CONF_TEMP_HIGH_COMMAND_TEMPLATE: PlatformField( + selector=TEMPLATE_SELECTOR, + required=False, + validator=validate(cv.template), + error="invalid_template", + section="target_temperature_settings", + conditions=({"climate_feature_target_temperature": "high_low"},), + ), + CONF_TEMP_HIGH_STATE_TOPIC: PlatformField( + selector=TEXT_SELECTOR, + required=False, + validator=valid_subscribe_topic, + error="invalid_subscribe_topic", + section="target_temperature_settings", + conditions=({"climate_feature_target_temperature": "high_low"},), + ), + CONF_TEMP_HIGH_STATE_TEMPLATE: PlatformField( + selector=TEMPLATE_SELECTOR, + required=False, + validator=validate(cv.template), + error="invalid_template", + section="target_temperature_settings", + conditions=({"climate_feature_target_temperature": "high_low"},), + ), + CONF_TEMP_MIN: PlatformField( + selector=temperature_selector, + custom_filtering=True, + required=True, + default=temperature_default_from_celsius_to_system_default( + DEFAULT_MIN_TEMP + ), + section="target_temperature_settings", + conditions=( + {"climate_feature_target_temperature": "high_low"}, + {"climate_feature_target_temperature": "single"}, + ), + ), + CONF_TEMP_MAX: PlatformField( + selector=temperature_selector, + custom_filtering=True, + required=True, + default=temperature_default_from_celsius_to_system_default( + DEFAULT_MAX_TEMP + ), + section="target_temperature_settings", + conditions=( + {"climate_feature_target_temperature": "high_low"}, + {"climate_feature_target_temperature": "single"}, + ), + ), + CONF_PRECISION: PlatformField( + selector=PRECISION_SELECTOR, + required=False, + default=default_precision, + section="target_temperature_settings", + conditions=( + {"climate_feature_target_temperature": "high_low"}, + {"climate_feature_target_temperature": "single"}, + ), + ), + CONF_TEMP_STEP: PlatformField( + selector=temperature_step_selector, + custom_filtering=True, + required=False, + default=1.0, + section="target_temperature_settings", + conditions=( + {"climate_feature_target_temperature": "high_low"}, + {"climate_feature_target_temperature": "single"}, + ), + ), + CONF_TEMP_INITIAL: PlatformField( + selector=temperature_selector, + custom_filtering=True, + required=False, + default=temperature_default_from_celsius_to_system_default( + DEFAULT_CLIMATE_INITIAL_TEMPERATURE + ), + section="target_temperature_settings", + conditions=( + {"climate_feature_target_temperature": "high_low"}, + {"climate_feature_target_temperature": "single"}, + ), + ), + # current temperature settings + CONF_CURRENT_TEMP_TOPIC: PlatformField( + selector=TEXT_SELECTOR, + required=False, + validator=valid_subscribe_topic, + error="invalid_subscribe_topic", + section="current_temperature_settings", + conditions=({"climate_feature_current_temperature": True},), + ), + CONF_CURRENT_TEMP_TEMPLATE: PlatformField( + selector=TEMPLATE_SELECTOR, + required=False, + validator=validate(cv.template), + error="invalid_template", + section="current_temperature_settings", + conditions=({"climate_feature_current_temperature": True},), + ), + # target humidity settings + CONF_HUMIDITY_COMMAND_TOPIC: PlatformField( + selector=TEXT_SELECTOR, + required=True, + validator=valid_publish_topic, + error="invalid_publish_topic", + section="target_humidity_settings", + conditions=({"climate_feature_target_humidity": True},), + ), + CONF_HUMIDITY_COMMAND_TEMPLATE: PlatformField( + selector=TEMPLATE_SELECTOR, + required=False, + validator=validate(cv.template), + error="invalid_template", + section="target_humidity_settings", + conditions=({"climate_feature_target_humidity": True},), + ), + CONF_HUMIDITY_STATE_TOPIC: PlatformField( + selector=TEXT_SELECTOR, + required=False, + validator=valid_subscribe_topic, + error="invalid_subscribe_topic", + section="target_humidity_settings", + conditions=({"climate_feature_target_humidity": True},), + ), + CONF_HUMIDITY_STATE_TEMPLATE: PlatformField( + selector=TEMPLATE_SELECTOR, + required=False, + validator=validate(cv.template), + error="invalid_template", + section="target_humidity_settings", + conditions=({"climate_feature_target_humidity": True},), + ), + CONF_HUMIDITY_MIN: PlatformField( + selector=HUMIDITY_SELECTOR, + required=True, + default=DEFAULT_MIN_HUMIDITY, + section="target_humidity_settings", + conditions=({"climate_feature_target_humidity": True},), + ), + CONF_HUMIDITY_MAX: PlatformField( + selector=HUMIDITY_SELECTOR, + required=True, + default=DEFAULT_MAX_HUMIDITY, + section="target_humidity_settings", + conditions=({"climate_feature_target_humidity": True},), + ), + # current humidity settings + CONF_CURRENT_HUMIDITY_TOPIC: PlatformField( + selector=TEXT_SELECTOR, + required=True, + validator=valid_subscribe_topic, + error="invalid_subscribe_topic", + section="current_humidity_settings", + conditions=({"climate_feature_current_humidity": True},), + ), + CONF_CURRENT_HUMIDITY_TEMPLATE: PlatformField( + selector=TEMPLATE_SELECTOR, + required=False, + validator=validate(cv.template), + error="invalid_template", + section="current_humidity_settings", + conditions=({"climate_feature_current_humidity": True},), + ), + # power on/off support + CONF_POWER_COMMAND_TOPIC: PlatformField( + selector=TEXT_SELECTOR, + required=False, + validator=valid_publish_topic, + error="invalid_publish_topic", + section="climate_power_settings", + conditions=({"climate_feature_power": True},), + ), + CONF_POWER_COMMAND_TEMPLATE: PlatformField( + selector=TEMPLATE_SELECTOR, + required=False, + validator=validate(cv.template), + error="invalid_template", + section="climate_power_settings", + conditions=({"climate_feature_power": True},), + ), + CONF_PAYLOAD_OFF: PlatformField( + selector=TEXT_SELECTOR, + required=False, + default=DEFAULT_PAYLOAD_OFF, + section="climate_power_settings", + conditions=({"climate_feature_power": True},), + ), + CONF_PAYLOAD_ON: PlatformField( + selector=TEXT_SELECTOR, + required=False, + default=DEFAULT_PAYLOAD_ON, + section="climate_power_settings", + conditions=({"climate_feature_power": True},), + ), + # preset mode settings + CONF_PRESET_MODE_COMMAND_TOPIC: PlatformField( + selector=TEXT_SELECTOR, + required=True, + validator=valid_publish_topic, + error="invalid_publish_topic", + section="climate_preset_mode_settings", + conditions=({"climate_feature_preset_modes": True},), + ), + CONF_PRESET_MODE_COMMAND_TEMPLATE: PlatformField( + selector=TEMPLATE_SELECTOR, + required=False, + validator=validate(cv.template), + error="invalid_template", + section="climate_preset_mode_settings", + conditions=({"climate_feature_preset_modes": True},), + ), + CONF_PRESET_MODE_STATE_TOPIC: PlatformField( + selector=TEXT_SELECTOR, + required=False, + validator=valid_subscribe_topic, + error="invalid_subscribe_topic", + section="climate_preset_mode_settings", + conditions=({"climate_feature_preset_modes": True},), + ), + CONF_PRESET_MODE_VALUE_TEMPLATE: PlatformField( + selector=TEMPLATE_SELECTOR, + required=False, + validator=validate(cv.template), + error="invalid_template", + section="climate_preset_mode_settings", + conditions=({"climate_feature_preset_modes": True},), + ), + CONF_PRESET_MODES_LIST: PlatformField( + selector=PRESET_MODES_SELECTOR, + required=True, + validator=validate(no_empty_list), + error="empty_list_not_allowed", + section="climate_preset_mode_settings", + conditions=({"climate_feature_preset_modes": True},), + ), + # fan mode settings + CONF_FAN_MODE_COMMAND_TOPIC: PlatformField( + selector=TEXT_SELECTOR, + required=True, + validator=valid_publish_topic, + error="invalid_publish_topic", + section="climate_fan_mode_settings", + conditions=({"climate_feature_fan_modes": True},), + ), + CONF_FAN_MODE_COMMAND_TEMPLATE: PlatformField( + selector=TEMPLATE_SELECTOR, + required=False, + validator=validate(cv.template), + error="invalid_template", + section="climate_fan_mode_settings", + conditions=({"climate_feature_fan_modes": True},), + ), + CONF_FAN_MODE_STATE_TOPIC: PlatformField( + selector=TEXT_SELECTOR, + required=False, + validator=valid_subscribe_topic, + error="invalid_subscribe_topic", + section="climate_fan_mode_settings", + conditions=({"climate_feature_fan_modes": True},), + ), + CONF_FAN_MODE_STATE_TEMPLATE: PlatformField( + selector=TEMPLATE_SELECTOR, + required=False, + validator=validate(cv.template), + error="invalid_template", + section="climate_fan_mode_settings", + conditions=({"climate_feature_fan_modes": True},), + ), + CONF_FAN_MODE_LIST: PlatformField( + selector=PRESET_MODES_SELECTOR, + required=True, + validator=validate(no_empty_list), + error="empty_list_not_allowed", + section="climate_fan_mode_settings", + conditions=({"climate_feature_fan_modes": True},), + ), + # swing mode settings + CONF_SWING_MODE_COMMAND_TOPIC: PlatformField( + selector=TEXT_SELECTOR, + required=True, + validator=valid_publish_topic, + error="invalid_publish_topic", + section="climate_swing_mode_settings", + conditions=({"climate_feature_swing_modes": True},), + ), + CONF_SWING_MODE_COMMAND_TEMPLATE: PlatformField( + selector=TEMPLATE_SELECTOR, + required=False, + validator=validate(cv.template), + error="invalid_template", + section="climate_swing_mode_settings", + conditions=({"climate_feature_swing_modes": True},), + ), + CONF_SWING_MODE_STATE_TOPIC: PlatformField( + selector=TEXT_SELECTOR, + required=False, + validator=valid_subscribe_topic, + error="invalid_subscribe_topic", + section="climate_swing_mode_settings", + conditions=({"climate_feature_swing_modes": True},), + ), + CONF_SWING_MODE_STATE_TEMPLATE: PlatformField( + selector=TEMPLATE_SELECTOR, + required=False, + validator=validate(cv.template), + error="invalid_template", + section="climate_swing_mode_settings", + conditions=({"climate_feature_swing_modes": True},), + ), + CONF_SWING_MODE_LIST: PlatformField( + selector=PRESET_MODES_SELECTOR, + required=True, + validator=validate(no_empty_list), + error="empty_list_not_allowed", + section="climate_swing_mode_settings", + conditions=({"climate_feature_swing_modes": True},), + ), + # swing horizontal mode settings + CONF_SWING_HORIZONTAL_MODE_COMMAND_TOPIC: PlatformField( + selector=TEXT_SELECTOR, + required=True, + validator=valid_publish_topic, + error="invalid_publish_topic", + section="climate_swing_horizontal_mode_settings", + conditions=({"climate_feature_swing_horizontal_modes": True},), + ), + CONF_SWING_HORIZONTAL_MODE_COMMAND_TEMPLATE: PlatformField( + selector=TEMPLATE_SELECTOR, + required=False, + validator=validate(cv.template), + error="invalid_template", + section="climate_swing_horizontal_mode_settings", + conditions=({"climate_feature_swing_horizontal_modes": True},), + ), + CONF_SWING_HORIZONTAL_MODE_STATE_TOPIC: PlatformField( + selector=TEXT_SELECTOR, + required=False, + validator=valid_subscribe_topic, + error="invalid_subscribe_topic", + section="climate_swing_horizontal_mode_settings", + conditions=({"climate_feature_swing_horizontal_modes": True},), + ), + CONF_SWING_HORIZONTAL_MODE_STATE_TEMPLATE: PlatformField( + selector=TEMPLATE_SELECTOR, + required=False, + validator=validate(cv.template), + error="invalid_template", + section="climate_swing_horizontal_mode_settings", + conditions=({"climate_feature_swing_horizontal_modes": True},), + ), + CONF_SWING_HORIZONTAL_MODE_LIST: PlatformField( + selector=PRESET_MODES_SELECTOR, + required=True, + validator=validate(no_empty_list), + error="empty_list_not_allowed", + section="climate_swing_horizontal_mode_settings", + conditions=({"climate_feature_swing_horizontal_modes": True},), + ), + }, + Platform.COVER: { + CONF_COMMAND_TOPIC: PlatformField( + selector=TEXT_SELECTOR, + required=False, + validator=valid_publish_topic, + error="invalid_publish_topic", + ), + CONF_STATE_TOPIC: PlatformField( + selector=TEXT_SELECTOR, + required=False, + validator=valid_subscribe_topic, + error="invalid_subscribe_topic", + ), + CONF_VALUE_TEMPLATE: PlatformField( + selector=TEMPLATE_SELECTOR, + required=False, + validator=validate(cv.template), + error="invalid_template", + ), + CONF_RETAIN: PlatformField(selector=BOOLEAN_SELECTOR, required=False), + CONF_OPTIMISTIC: PlatformField(selector=BOOLEAN_SELECTOR, required=False), + CONF_PAYLOAD_CLOSE: PlatformField( + selector=TEXT_SELECTOR, + required=False, + default=DEFAULT_PAYLOAD_CLOSE, + section="cover_payload_settings", + ), + CONF_PAYLOAD_OPEN: PlatformField( + selector=TEXT_SELECTOR, + required=False, + default=DEFAULT_PAYLOAD_OPEN, + section="cover_payload_settings", + ), + CONF_PAYLOAD_STOP: PlatformField( + selector=TEXT_SELECTOR, + required=False, + default=None, + section="cover_payload_settings", + ), + CONF_PAYLOAD_STOP_TILT: PlatformField( + selector=TEXT_SELECTOR, + required=False, + default=DEFAULT_PAYLOAD_STOP, + section="cover_payload_settings", + ), + CONF_STATE_CLOSED: PlatformField( + selector=TEXT_SELECTOR, + required=False, + default=STATE_CLOSED, + section="cover_payload_settings", + ), + CONF_STATE_CLOSING: PlatformField( + selector=TEXT_SELECTOR, + required=False, + default=STATE_CLOSING, + section="cover_payload_settings", + ), + CONF_STATE_OPEN: PlatformField( + selector=TEXT_SELECTOR, + required=False, + default=STATE_OPEN, + section="cover_payload_settings", + ), + CONF_STATE_OPENING: PlatformField( + selector=TEXT_SELECTOR, + required=False, + default=STATE_OPENING, + section="cover_payload_settings", + ), + CONF_STATE_STOPPED: PlatformField( + selector=TEXT_SELECTOR, + required=False, + default=DEFAULT_STATE_STOPPED, + section="cover_payload_settings", + ), + CONF_SET_POSITION_TOPIC: PlatformField( + selector=TEXT_SELECTOR, + required=False, + validator=valid_publish_topic, + error="invalid_publish_topic", + section="cover_position_settings", + ), + CONF_SET_POSITION_TEMPLATE: PlatformField( + selector=TEMPLATE_SELECTOR, + required=False, + validator=validate(cv.template), + error="invalid_template", + section="cover_position_settings", + ), + CONF_GET_POSITION_TOPIC: PlatformField( + selector=TEXT_SELECTOR, + required=False, + validator=valid_subscribe_topic, + error="invalid_subscribe_topic", + section="cover_position_settings", + ), + CONF_GET_POSITION_TEMPLATE: PlatformField( + selector=TEMPLATE_SELECTOR, + required=False, + validator=validate(cv.template), + error="invalid_template", + section="cover_position_settings", + ), + CONF_POSITION_CLOSED: PlatformField( + selector=POSITION_SELECTOR, + required=False, + validator=int, + default=DEFAULT_POSITION_CLOSED, + section="cover_position_settings", + ), + CONF_POSITION_OPEN: PlatformField( + selector=POSITION_SELECTOR, + required=False, + validator=int, + default=DEFAULT_POSITION_OPEN, + section="cover_position_settings", + ), + CONF_TILT_COMMAND_TOPIC: PlatformField( + selector=TEXT_SELECTOR, + required=False, + validator=valid_publish_topic, + error="invalid_publish_topic", + section="cover_tilt_settings", + ), + CONF_TILT_COMMAND_TEMPLATE: PlatformField( + selector=TEMPLATE_SELECTOR, + required=False, + validator=validate(cv.template), + error="invalid_template", + section="cover_tilt_settings", + ), + CONF_TILT_CLOSED_POSITION: PlatformField( + selector=POSITION_SELECTOR, + required=False, + validator=int, + default=DEFAULT_TILT_CLOSED_POSITION, + section="cover_tilt_settings", + ), + CONF_TILT_OPEN_POSITION: PlatformField( + selector=POSITION_SELECTOR, + required=False, + validator=int, + default=DEFAULT_TILT_OPEN_POSITION, + section="cover_tilt_settings", + ), + CONF_TILT_STATUS_TOPIC: PlatformField( + selector=TEXT_SELECTOR, + required=False, + validator=valid_subscribe_topic, + error="invalid_subscribe_topic", + section="cover_tilt_settings", + ), + CONF_TILT_STATUS_TEMPLATE: PlatformField( + selector=TEMPLATE_SELECTOR, + required=False, + validator=validate(cv.template), + error="invalid_template", + section="cover_tilt_settings", + ), + CONF_TILT_MIN: PlatformField( + selector=POSITION_SELECTOR, + required=False, + validator=int, + default=DEFAULT_TILT_MIN, + section="cover_tilt_settings", + ), + CONF_TILT_MAX: PlatformField( + selector=POSITION_SELECTOR, + required=False, + validator=int, + default=DEFAULT_TILT_MAX, + section="cover_tilt_settings", + ), + CONF_TILT_STATE_OPTIMISTIC: PlatformField( + selector=BOOLEAN_SELECTOR, + required=False, + section="cover_tilt_settings", + ), + }, + Platform.DATE: { + CONF_COMMAND_TOPIC: PlatformField( + selector=TEXT_SELECTOR, + required=True, + validator=valid_publish_topic, + error="invalid_publish_topic", + ), + CONF_COMMAND_TEMPLATE: PlatformField( + selector=TEMPLATE_SELECTOR, + required=False, + validator=validate(cv.template), + error="invalid_template", + ), + CONF_STATE_TOPIC: PlatformField( + selector=TEXT_SELECTOR, + required=False, + validator=valid_subscribe_topic, + error="invalid_subscribe_topic", + ), + CONF_VALUE_TEMPLATE: PlatformField( + selector=TEMPLATE_SELECTOR, + required=False, + validator=validate(cv.template), + error="invalid_template", + ), + CONF_RETAIN: PlatformField(selector=BOOLEAN_SELECTOR, required=False), + }, + Platform.DATETIME: { + CONF_COMMAND_TOPIC: PlatformField( + selector=TEXT_SELECTOR, + required=True, + validator=valid_publish_topic, + error="invalid_publish_topic", + ), + CONF_COMMAND_TEMPLATE: PlatformField( + selector=TEMPLATE_SELECTOR, + required=False, + validator=validate(cv.template), + error="invalid_template", + ), + CONF_STATE_TOPIC: PlatformField( + selector=TEXT_SELECTOR, + required=False, + validator=valid_subscribe_topic, + error="invalid_subscribe_topic", + ), + CONF_VALUE_TEMPLATE: PlatformField( + selector=TEMPLATE_SELECTOR, + required=False, + validator=validate(cv.template), + error="invalid_template", + ), + CONF_TIMEZONE: PlatformField(selector=TEXT_SELECTOR, required=False), + CONF_RETAIN: PlatformField(selector=BOOLEAN_SELECTOR, required=False), + }, + Platform.FAN: { + CONF_COMMAND_TOPIC: PlatformField( + selector=TEXT_SELECTOR, + required=True, + validator=valid_publish_topic, + error="invalid_publish_topic", + ), + CONF_COMMAND_TEMPLATE: PlatformField( + selector=TEMPLATE_SELECTOR, + required=False, + validator=validate(cv.template), + error="invalid_template", + ), + CONF_STATE_TOPIC: PlatformField( + selector=TEXT_SELECTOR, + required=False, + validator=valid_subscribe_topic, + error="invalid_subscribe_topic", + ), + CONF_STATE_VALUE_TEMPLATE: PlatformField( + selector=TEMPLATE_SELECTOR, + required=False, + validator=validate(cv.template), + error="invalid_template", + ), + CONF_PAYLOAD_OFF: PlatformField( + selector=TEXT_SELECTOR, + required=False, + default=DEFAULT_PAYLOAD_OFF, + ), + CONF_PAYLOAD_ON: PlatformField( + selector=TEXT_SELECTOR, + required=False, + default=DEFAULT_PAYLOAD_ON, + ), + CONF_RETAIN: PlatformField( + selector=BOOLEAN_SELECTOR, required=False, validator=bool + ), + CONF_OPTIMISTIC: PlatformField( + selector=BOOLEAN_SELECTOR, required=False, validator=bool + ), + CONF_PERCENTAGE_COMMAND_TOPIC: PlatformField( + selector=TEXT_SELECTOR, + required=True, + validator=valid_publish_topic, + error="invalid_publish_topic", + section="fan_speed_settings", + conditions=({"fan_feature_speed": True},), + ), + CONF_PERCENTAGE_COMMAND_TEMPLATE: PlatformField( + selector=TEMPLATE_SELECTOR, + required=False, + validator=validate(cv.template), + error="invalid_template", + section="fan_speed_settings", + conditions=({"fan_feature_speed": True},), + ), + CONF_PERCENTAGE_STATE_TOPIC: PlatformField( + selector=TEXT_SELECTOR, + required=False, + validator=valid_subscribe_topic, + error="invalid_subscribe_topic", + section="fan_speed_settings", + conditions=({"fan_feature_speed": True},), + ), + CONF_PERCENTAGE_VALUE_TEMPLATE: PlatformField( + selector=TEMPLATE_SELECTOR, + required=False, + validator=validate(cv.template), + error="invalid_template", + section="fan_speed_settings", + conditions=({"fan_feature_speed": True},), + ), + CONF_SPEED_RANGE_MIN: PlatformField( + selector=FAN_SPEED_RANGE_MIN_SELECTOR, + required=False, + validator=int, + default=DEFAULT_SPEED_RANGE_MIN, + section="fan_speed_settings", + conditions=({"fan_feature_speed": True},), + ), + CONF_SPEED_RANGE_MAX: PlatformField( + selector=FAN_SPEED_RANGE_MAX_SELECTOR, + required=False, + validator=int, + default=DEFAULT_SPEED_RANGE_MAX, + section="fan_speed_settings", + conditions=({"fan_feature_speed": True},), + ), + CONF_PAYLOAD_RESET_PERCENTAGE: PlatformField( + selector=TEXT_SELECTOR, + required=False, + default=DEFAULT_PAYLOAD_RESET, + section="fan_speed_settings", + conditions=({"fan_feature_speed": True},), + ), + CONF_PRESET_MODES_LIST: PlatformField( + selector=PRESET_MODES_SELECTOR, + required=True, + section="fan_preset_mode_settings", + conditions=({"fan_feature_preset_modes": True},), + ), + CONF_PRESET_MODE_COMMAND_TOPIC: PlatformField( + selector=TEXT_SELECTOR, + required=True, + validator=valid_publish_topic, + error="invalid_publish_topic", + section="fan_preset_mode_settings", + conditions=({"fan_feature_preset_modes": True},), + ), + CONF_PRESET_MODE_COMMAND_TEMPLATE: PlatformField( + selector=TEMPLATE_SELECTOR, + required=False, + validator=validate(cv.template), + error="invalid_template", + section="fan_preset_mode_settings", + conditions=({"fan_feature_preset_modes": True},), + ), + CONF_PRESET_MODE_STATE_TOPIC: PlatformField( + selector=TEXT_SELECTOR, + required=False, + validator=valid_subscribe_topic, + error="invalid_subscribe_topic", + section="fan_preset_mode_settings", + conditions=({"fan_feature_preset_modes": True},), + ), + CONF_PRESET_MODE_VALUE_TEMPLATE: PlatformField( + selector=TEMPLATE_SELECTOR, + required=False, + validator=validate(cv.template), + error="invalid_template", + section="fan_preset_mode_settings", + conditions=({"fan_feature_preset_modes": True},), + ), + CONF_PAYLOAD_RESET_PRESET_MODE: PlatformField( + selector=TEXT_SELECTOR, + required=False, + default=DEFAULT_PAYLOAD_RESET, + section="fan_preset_mode_settings", + conditions=({"fan_feature_preset_modes": True},), + ), + CONF_OSCILLATION_COMMAND_TOPIC: PlatformField( + selector=TEXT_SELECTOR, + required=True, + validator=valid_publish_topic, + error="invalid_publish_topic", + section="fan_oscillation_settings", + conditions=({"fan_feature_oscillation": True},), + ), + CONF_OSCILLATION_COMMAND_TEMPLATE: PlatformField( + selector=TEMPLATE_SELECTOR, + required=False, + validator=validate(cv.template), + error="invalid_template", + section="fan_oscillation_settings", + conditions=({"fan_feature_oscillation": True},), + ), + CONF_OSCILLATION_STATE_TOPIC: PlatformField( + selector=TEXT_SELECTOR, + required=False, + validator=valid_subscribe_topic, + error="invalid_subscribe_topic", + section="fan_oscillation_settings", + conditions=({"fan_feature_oscillation": True},), + ), + CONF_OSCILLATION_VALUE_TEMPLATE: PlatformField( + selector=TEMPLATE_SELECTOR, + required=False, + validator=validate(cv.template), + error="invalid_template", + section="fan_oscillation_settings", + conditions=({"fan_feature_oscillation": True},), + ), + CONF_PAYLOAD_OSCILLATION_OFF: PlatformField( + selector=TEXT_SELECTOR, + required=False, + default=DEFAULT_PAYLOAD_OSCILLATE_OFF, + section="fan_oscillation_settings", + conditions=({"fan_feature_oscillation": True},), + ), + CONF_PAYLOAD_OSCILLATION_ON: PlatformField( + selector=TEXT_SELECTOR, + required=False, + default=DEFAULT_PAYLOAD_OSCILLATE_ON, + section="fan_oscillation_settings", + conditions=({"fan_feature_oscillation": True},), + ), + CONF_DIRECTION_COMMAND_TOPIC: PlatformField( + selector=TEXT_SELECTOR, + required=True, + validator=valid_publish_topic, + error="invalid_publish_topic", + section="fan_direction_settings", + conditions=({"fan_feature_direction": True},), + ), + CONF_DIRECTION_COMMAND_TEMPLATE: PlatformField( + selector=TEMPLATE_SELECTOR, + required=False, + validator=validate(cv.template), + error="invalid_template", + section="fan_direction_settings", + conditions=({"fan_feature_direction": True},), + ), + CONF_DIRECTION_STATE_TOPIC: PlatformField( + selector=TEXT_SELECTOR, + required=False, + validator=valid_subscribe_topic, + error="invalid_subscribe_topic", + section="fan_direction_settings", + conditions=({"fan_feature_direction": True},), + ), + CONF_DIRECTION_VALUE_TEMPLATE: PlatformField( + selector=TEMPLATE_SELECTOR, + required=False, + validator=validate(cv.template), + error="invalid_template", + section="fan_direction_settings", + conditions=({"fan_feature_direction": True},), + ), + }, + Platform.IMAGE: { + CONF_IMAGE_TOPIC: PlatformField( + selector=TEXT_SELECTOR, + required=True, + validator=valid_subscribe_topic, + error="invalid_subscribe_topic", + conditions=({"image_processing_mode": "image_data"},), + ), + CONF_CONTENT_TYPE: PlatformField( + selector=IMAGE_CONTENT_TYPE_SELECTOR, + required=True, + default=DEFAULT_CONTENT_TYPE, + conditions=({"image_processing_mode": "image_data"},), + ), + CONF_IMAGE_ENCODING: PlatformField( + selector=IMAGE_ENCODING_SELECTOR, + required=False, + conditions=({"image_processing_mode": "image_data"},), + default="raw", + ), + CONF_URL_TOPIC: PlatformField( + selector=TEXT_SELECTOR, + required=True, + validator=valid_subscribe_topic, + error="invalid_subscribe_topic", + conditions=({"image_processing_mode": "image_url"},), + ), + CONF_URL_TEMPLATE: PlatformField( + selector=TEMPLATE_SELECTOR, + required=False, + validator=validate(cv.template), + error="invalid_template", + ), + }, + Platform.LIGHT: { + CONF_COMMAND_TOPIC: PlatformField( + selector=TEXT_SELECTOR, + required=True, + validator=valid_publish_topic, + error="invalid_publish_topic", + ), + CONF_COMMAND_ON_TEMPLATE: PlatformField( + selector=TEMPLATE_SELECTOR, + required=True, + validator=validate(cv.template), + error="invalid_template", + conditions=({CONF_SCHEMA: "template"},), + ), + CONF_COMMAND_OFF_TEMPLATE: PlatformField( + selector=TEMPLATE_SELECTOR, + required=True, + validator=validate(cv.template), + error="invalid_template", + conditions=({CONF_SCHEMA: "template"},), + ), + CONF_ON_COMMAND_TYPE: PlatformField( + selector=ON_COMMAND_TYPE_SELECTOR, + required=False, + default=DEFAULT_ON_COMMAND_TYPE, + conditions=({CONF_SCHEMA: "basic"},), + ), + CONF_STATE_TOPIC: PlatformField( + selector=TEXT_SELECTOR, + required=False, + validator=valid_subscribe_topic, + error="invalid_subscribe_topic", + ), + CONF_STATE_VALUE_TEMPLATE: PlatformField( + selector=TEMPLATE_SELECTOR, + required=False, + validator=validate(cv.template), + error="invalid_template", + conditions=({CONF_SCHEMA: "basic"},), + ), + CONF_STATE_TEMPLATE: PlatformField( + selector=TEMPLATE_SELECTOR, + required=False, + validator=validate(cv.template), + error="invalid_template", + conditions=({CONF_SCHEMA: "template"},), + ), + CONF_SUPPORTED_COLOR_MODES: PlatformField( + selector=SUPPORTED_COLOR_MODES_SELECTOR, + required=False, + validator=valid_supported_color_modes, + error="invalid_supported_color_modes", + conditions=({CONF_SCHEMA: "json"},), + ), + CONF_OPTIMISTIC: PlatformField(selector=BOOLEAN_SELECTOR, required=False), + CONF_RETAIN: PlatformField( + selector=BOOLEAN_SELECTOR, + required=False, + conditions=({CONF_SCHEMA: "basic"},), + ), + CONF_BRIGHTNESS: PlatformField( + selector=BOOLEAN_SELECTOR, + required=False, + conditions=({CONF_SCHEMA: "json"},), + section="light_brightness_settings", + ), + CONF_BRIGHTNESS_COMMAND_TOPIC: PlatformField( + selector=TEXT_SELECTOR, + required=False, + validator=valid_publish_topic, + error="invalid_publish_topic", + conditions=({CONF_SCHEMA: "basic"},), + section="light_brightness_settings", + ), + CONF_BRIGHTNESS_COMMAND_TEMPLATE: PlatformField( + selector=TEMPLATE_SELECTOR, + required=False, + validator=validate(cv.template), + error="invalid_template", + conditions=({CONF_SCHEMA: "basic"},), + section="light_brightness_settings", + ), + CONF_BRIGHTNESS_STATE_TOPIC: PlatformField( + selector=TEXT_SELECTOR, + required=False, + validator=valid_subscribe_topic, + error="invalid_subscribe_topic", + conditions=({CONF_SCHEMA: "basic"},), + section="light_brightness_settings", + ), + CONF_PAYLOAD_OFF: PlatformField( + selector=TEXT_SELECTOR, + required=False, + default=DEFAULT_PAYLOAD_OFF, + conditions=({CONF_SCHEMA: "basic"},), + ), + CONF_PAYLOAD_ON: PlatformField( + selector=TEXT_SELECTOR, + required=False, + default=DEFAULT_PAYLOAD_ON, + conditions=({CONF_SCHEMA: "basic"},), + ), + CONF_BRIGHTNESS_VALUE_TEMPLATE: PlatformField( + selector=TEMPLATE_SELECTOR, + required=False, + validator=validate(cv.template), + error="invalid_template", + conditions=({CONF_SCHEMA: "basic"},), + section="light_brightness_settings", + ), + CONF_BRIGHTNESS_SCALE: PlatformField( + selector=SCALE_SELECTOR, + required=False, + validator=cv.positive_int, + default=255, + conditions=( + {CONF_SCHEMA: "basic"}, + {CONF_SCHEMA: "json"}, + ), + section="light_brightness_settings", + ), + CONF_COLOR_MODE_STATE_TOPIC: PlatformField( + selector=TEXT_SELECTOR, + required=False, + validator=valid_subscribe_topic, + error="invalid_subscribe_topic", + conditions=({CONF_SCHEMA: "basic"},), + section="light_color_mode_settings", + ), + CONF_COLOR_MODE_VALUE_TEMPLATE: PlatformField( + selector=TEMPLATE_SELECTOR, + required=False, + validator=validate(cv.template), + error="invalid_template", + conditions=({CONF_SCHEMA: "basic"},), + section="light_color_mode_settings", + ), + CONF_COLOR_TEMP_COMMAND_TOPIC: PlatformField( + selector=TEXT_SELECTOR, + required=False, + validator=valid_publish_topic, + error="invalid_publish_topic", + conditions=({CONF_SCHEMA: "basic"},), + section="light_color_temp_settings", + ), + CONF_COLOR_TEMP_COMMAND_TEMPLATE: PlatformField( + selector=TEMPLATE_SELECTOR, + required=False, + validator=validate(cv.template), + error="invalid_template", + conditions=({CONF_SCHEMA: "basic"},), + section="light_color_temp_settings", + ), + CONF_COLOR_TEMP_STATE_TOPIC: PlatformField( + selector=TEXT_SELECTOR, + required=False, + validator=valid_subscribe_topic, + error="invalid_subscribe_topic", + conditions=({CONF_SCHEMA: "basic"},), + section="light_color_temp_settings", + ), + CONF_COLOR_TEMP_VALUE_TEMPLATE: PlatformField( + selector=TEMPLATE_SELECTOR, + required=False, + validator=validate(cv.template), + error="invalid_template", + conditions=({CONF_SCHEMA: "basic"},), + section="light_color_temp_settings", + ), + CONF_BRIGHTNESS_TEMPLATE: PlatformField( + selector=TEMPLATE_SELECTOR, + required=False, + validator=validate(cv.template), + error="invalid_template", + conditions=({CONF_SCHEMA: "template"},), + ), + CONF_RED_TEMPLATE: PlatformField( + selector=TEMPLATE_SELECTOR, + required=False, + validator=validate(cv.template), + error="invalid_template", + conditions=({CONF_SCHEMA: "template"},), + ), + CONF_GREEN_TEMPLATE: PlatformField( + selector=TEMPLATE_SELECTOR, + required=False, + validator=validate(cv.template), + error="invalid_template", + conditions=({CONF_SCHEMA: "template"},), + ), + CONF_BLUE_TEMPLATE: PlatformField( + selector=TEMPLATE_SELECTOR, + required=False, + validator=validate(cv.template), + error="invalid_template", + conditions=({CONF_SCHEMA: "template"},), + ), + CONF_COLOR_TEMP_TEMPLATE: PlatformField( + selector=TEMPLATE_SELECTOR, + required=False, + validator=validate(cv.template), + error="invalid_template", + conditions=({CONF_SCHEMA: "template"},), + ), + CONF_HS_COMMAND_TOPIC: PlatformField( + selector=TEXT_SELECTOR, + required=False, + validator=valid_publish_topic, + error="invalid_publish_topic", + conditions=({CONF_SCHEMA: "basic"},), + section="light_hs_settings", + ), + CONF_HS_COMMAND_TEMPLATE: PlatformField( + selector=TEMPLATE_SELECTOR, + required=False, + validator=validate(cv.template), + error="invalid_template", + conditions=({CONF_SCHEMA: "basic"},), + section="light_hs_settings", + ), + CONF_HS_STATE_TOPIC: PlatformField( + selector=TEXT_SELECTOR, + required=False, + validator=valid_subscribe_topic, + error="invalid_subscribe_topic", + conditions=({CONF_SCHEMA: "basic"},), + section="light_hs_settings", + ), + CONF_HS_VALUE_TEMPLATE: PlatformField( + selector=TEMPLATE_SELECTOR, + required=False, + validator=validate(cv.template), + error="invalid_template", + conditions=({CONF_SCHEMA: "basic"},), + section="light_hs_settings", + ), + CONF_RGB_COMMAND_TOPIC: PlatformField( + selector=TEXT_SELECTOR, + required=False, + validator=valid_publish_topic, + error="invalid_publish_topic", + conditions=({CONF_SCHEMA: "basic"},), + section="light_rgb_settings", + ), + CONF_RGB_COMMAND_TEMPLATE: PlatformField( + selector=TEMPLATE_SELECTOR, + required=False, + validator=validate(cv.template), + error="invalid_template", + conditions=({CONF_SCHEMA: "basic"},), + section="light_rgb_settings", + ), + CONF_RGB_STATE_TOPIC: PlatformField( + selector=TEXT_SELECTOR, + required=False, + validator=valid_subscribe_topic, + error="invalid_subscribe_topic", + conditions=({CONF_SCHEMA: "basic"},), + section="light_rgb_settings", + ), + CONF_RGB_VALUE_TEMPLATE: PlatformField( + selector=TEMPLATE_SELECTOR, + required=False, + validator=validate(cv.template), + error="invalid_template", + conditions=({CONF_SCHEMA: "basic"},), + section="light_rgb_settings", + ), + CONF_RGBW_COMMAND_TOPIC: PlatformField( + selector=TEXT_SELECTOR, + required=False, + validator=valid_publish_topic, + error="invalid_publish_topic", + conditions=({CONF_SCHEMA: "basic"},), + section="light_rgbw_settings", + ), + CONF_RGBW_COMMAND_TEMPLATE: PlatformField( + selector=TEMPLATE_SELECTOR, + required=False, + validator=validate(cv.template), + error="invalid_template", + conditions=({CONF_SCHEMA: "basic"},), + section="light_rgbw_settings", + ), + CONF_RGBW_STATE_TOPIC: PlatformField( + selector=TEXT_SELECTOR, + required=False, + validator=valid_subscribe_topic, + error="invalid_subscribe_topic", + conditions=({CONF_SCHEMA: "basic"},), + section="light_rgbw_settings", + ), + CONF_RGBW_VALUE_TEMPLATE: PlatformField( + selector=TEMPLATE_SELECTOR, + required=False, + validator=validate(cv.template), + error="invalid_template", + conditions=({CONF_SCHEMA: "basic"},), + section="light_rgbw_settings", + ), + CONF_RGBWW_COMMAND_TOPIC: PlatformField( + selector=TEXT_SELECTOR, + required=False, + validator=valid_publish_topic, + error="invalid_publish_topic", + conditions=({CONF_SCHEMA: "basic"},), + section="light_rgbww_settings", + ), + CONF_RGBWW_COMMAND_TEMPLATE: PlatformField( + selector=TEMPLATE_SELECTOR, + required=False, + validator=validate(cv.template), + error="invalid_template", + conditions=({CONF_SCHEMA: "basic"},), + section="light_rgbww_settings", + ), + CONF_RGBWW_STATE_TOPIC: PlatformField( + selector=TEXT_SELECTOR, + required=False, + validator=valid_subscribe_topic, + error="invalid_subscribe_topic", + conditions=({CONF_SCHEMA: "basic"},), + section="light_rgbww_settings", + ), + CONF_RGBWW_VALUE_TEMPLATE: PlatformField( + selector=TEMPLATE_SELECTOR, + required=False, + validator=validate(cv.template), + error="invalid_template", + conditions=({CONF_SCHEMA: "basic"},), + section="light_rgbww_settings", + ), + CONF_XY_COMMAND_TOPIC: PlatformField( + selector=TEXT_SELECTOR, + required=False, + validator=valid_publish_topic, + error="invalid_publish_topic", + conditions=({CONF_SCHEMA: "basic"},), + section="light_xy_settings", + ), + CONF_XY_COMMAND_TEMPLATE: PlatformField( + selector=TEMPLATE_SELECTOR, + required=False, + validator=validate(cv.template), + error="invalid_template", + conditions=({CONF_SCHEMA: "basic"},), + section="light_xy_settings", + ), + CONF_XY_STATE_TOPIC: PlatformField( + selector=TEXT_SELECTOR, + required=False, + validator=valid_subscribe_topic, + error="invalid_subscribe_topic", + conditions=({CONF_SCHEMA: "basic"},), + section="light_xy_settings", + ), + CONF_XY_VALUE_TEMPLATE: PlatformField( + selector=TEMPLATE_SELECTOR, + required=False, + validator=validate(cv.template), + error="invalid_template", + conditions=({CONF_SCHEMA: "basic"},), + section="light_xy_settings", + ), + CONF_WHITE_COMMAND_TOPIC: PlatformField( + selector=TEXT_SELECTOR, + required=False, + validator=valid_publish_topic, + error="invalid_publish_topic", + conditions=({CONF_SCHEMA: "basic"},), + section="light_white_settings", + ), + CONF_WHITE_SCALE: PlatformField( + selector=SCALE_SELECTOR, + required=False, + validator=cv.positive_int, + default=255, + conditions=( + {CONF_SCHEMA: "basic"}, + {CONF_SCHEMA: "json"}, + ), + section="light_white_settings", + ), + CONF_EFFECT: PlatformField( + selector=BOOLEAN_SELECTOR, + required=False, + conditions=({CONF_SCHEMA: "json"},), + section="light_effect_settings", + ), + CONF_EFFECT_COMMAND_TOPIC: PlatformField( + selector=TEXT_SELECTOR, + required=False, + validator=valid_publish_topic, + error="invalid_publish_topic", + conditions=({CONF_SCHEMA: "basic"},), + section="light_effect_settings", + ), + CONF_EFFECT_COMMAND_TEMPLATE: PlatformField( + selector=TEMPLATE_SELECTOR, + required=False, + validator=validate(cv.template), + error="invalid_template", + conditions=({CONF_SCHEMA: "basic"},), + section="light_effect_settings", + ), + CONF_EFFECT_STATE_TOPIC: PlatformField( + selector=TEXT_SELECTOR, + required=False, + validator=valid_subscribe_topic, + error="invalid_subscribe_topic", + conditions=({CONF_SCHEMA: "basic"},), + section="light_effect_settings", + ), + CONF_EFFECT_TEMPLATE: PlatformField( + selector=TEMPLATE_SELECTOR, + required=False, + validator=validate(cv.template), + error="invalid_template", + conditions=({CONF_SCHEMA: "template"},), + section="light_effect_settings", + ), + CONF_EFFECT_VALUE_TEMPLATE: PlatformField( + selector=TEMPLATE_SELECTOR, + required=False, + validator=validate(cv.template), + error="invalid_template", + conditions=({CONF_SCHEMA: "basic"},), + section="light_effect_settings", + ), + CONF_EFFECT_LIST: PlatformField( + selector=OPTIONS_SELECTOR, + required=False, + section="light_effect_settings", + ), + CONF_FLASH: PlatformField( + selector=BOOLEAN_SELECTOR, + required=False, + default=False, + validator=cv.boolean, + conditions=({CONF_SCHEMA: "json"},), + section=OTHER_SETTINGS, + ), + CONF_FLASH_TIME_SHORT: PlatformField( + selector=FLASH_TIME_SELECTOR, + required=False, + validator=cv.positive_int, + default=2, + conditions=({CONF_SCHEMA: "json"},), + section=OTHER_SETTINGS, + ), + CONF_FLASH_TIME_LONG: PlatformField( + selector=FLASH_TIME_SELECTOR, + required=False, + validator=cv.positive_int, + default=10, + conditions=({CONF_SCHEMA: "json"},), + section=OTHER_SETTINGS, + ), + CONF_TRANSITION: PlatformField( + selector=BOOLEAN_SELECTOR, + required=False, + default=False, + validator=cv.boolean, + conditions=({CONF_SCHEMA: "json"},), + section=OTHER_SETTINGS, + ), + CONF_MAX_KELVIN: PlatformField( + selector=KELVIN_SELECTOR, + required=False, + validator=cv.positive_int, + default=DEFAULT_MAX_KELVIN, + section=OTHER_SETTINGS, + ), + CONF_MIN_KELVIN: PlatformField( + selector=KELVIN_SELECTOR, + required=False, + validator=cv.positive_int, + default=DEFAULT_MIN_KELVIN, + section=OTHER_SETTINGS, + ), + }, + Platform.LOCK: { + CONF_COMMAND_TOPIC: PlatformField( + selector=TEXT_SELECTOR, + required=True, + validator=valid_publish_topic, + error="invalid_publish_topic", + ), + CONF_COMMAND_TEMPLATE: PlatformField( + selector=TEMPLATE_SELECTOR, + required=False, + validator=validate(cv.template), + error="invalid_template", + ), + CONF_STATE_TOPIC: PlatformField( + selector=TEXT_SELECTOR, + required=False, + validator=valid_subscribe_topic, + error="invalid_subscribe_topic", + ), + CONF_VALUE_TEMPLATE: PlatformField( + selector=TEMPLATE_SELECTOR, + required=False, + validator=validate(cv.template), + error="invalid_template", + ), + CONF_CODE_FORMAT: PlatformField( + selector=TEXT_SELECTOR, + required=False, + validator=validate(cv.is_regex), + error="invalid_regular_expression", + ), + CONF_PAYLOAD_LOCK: PlatformField( + selector=TEXT_SELECTOR, + required=False, + default=DEFAULT_PAYLOAD_LOCK, + section="lock_payload_settings", + ), + CONF_PAYLOAD_UNLOCK: PlatformField( + selector=TEXT_SELECTOR, + required=False, + default=DEFAULT_PAYLOAD_UNLOCK, + section="lock_payload_settings", + ), + CONF_PAYLOAD_OPEN: PlatformField( + selector=TEXT_SELECTOR, + required=False, + section="lock_payload_settings", + ), + CONF_PAYLOAD_RESET: PlatformField( + selector=TEXT_SELECTOR, + required=False, + default=DEFAULT_PAYLOAD_RESET, + section="lock_payload_settings", + ), + CONF_STATE_LOCKED: PlatformField( + selector=TEXT_SELECTOR, + required=False, + default=DEFAULT_STATE_LOCKED, + section="lock_payload_settings", + ), + CONF_STATE_UNLOCKED: PlatformField( + selector=TEXT_SELECTOR, + required=False, + default=DEFAULT_STATE_UNLOCKED, + section="lock_payload_settings", + ), + CONF_STATE_LOCKING: PlatformField( + selector=TEXT_SELECTOR, + required=False, + default=DEFAULT_STATE_LOCKING, + section="lock_payload_settings", + ), + CONF_STATE_UNLOCKING: PlatformField( + selector=TEXT_SELECTOR, + required=False, + default=DEFAULT_STATE_UNLOCKING, + section="lock_payload_settings", + ), + CONF_STATE_JAMMED: PlatformField( + selector=TEXT_SELECTOR, + required=False, + default=DEFAULT_STATE_JAMMED, + section="lock_payload_settings", + ), + CONF_RETAIN: PlatformField(selector=BOOLEAN_SELECTOR, required=False), + CONF_OPTIMISTIC: PlatformField(selector=BOOLEAN_SELECTOR, required=False), + }, + Platform.NOTIFY: { + CONF_COMMAND_TOPIC: PlatformField( + selector=TEXT_SELECTOR, + required=True, + validator=valid_publish_topic, + error="invalid_publish_topic", + ), + CONF_COMMAND_TEMPLATE: PlatformField( + selector=TEMPLATE_SELECTOR, + required=False, + validator=validate(cv.template), + error="invalid_template", + ), + CONF_RETAIN: PlatformField(selector=BOOLEAN_SELECTOR, required=False), + }, + Platform.NUMBER: { + CONF_COMMAND_TOPIC: PlatformField( + selector=TEXT_SELECTOR, + required=True, + validator=valid_publish_topic, + error="invalid_publish_topic", + ), + CONF_COMMAND_TEMPLATE: PlatformField( + selector=TEMPLATE_SELECTOR, + required=False, + validator=validate(cv.template), + error="invalid_template", + ), + CONF_STATE_TOPIC: PlatformField( + selector=TEXT_SELECTOR, + required=False, + validator=valid_subscribe_topic, + error="invalid_subscribe_topic", + ), + CONF_VALUE_TEMPLATE: PlatformField( + selector=TEMPLATE_SELECTOR, + required=False, + validator=validate(cv.template), + error="invalid_template", + ), + CONF_MIN: PlatformField( + selector=MIN_MAX_SELECTOR, + required=True, + default=DEFAULT_MIN_VALUE, + ), + CONF_MAX: PlatformField( + selector=MIN_MAX_SELECTOR, + required=True, + default=DEFAULT_MAX_VALUE, + ), + CONF_STEP: PlatformField( + selector=STEP_SELECTOR, + required=True, + default=DEFAULT_STEP, + ), + CONF_MODE: PlatformField( + selector=NUMBER_MODE_SELECTOR, + required=True, + default=NumberMode.AUTO.value, + ), + CONF_PAYLOAD_RESET: PlatformField( + selector=TEXT_SELECTOR, + required=False, + default=DEFAULT_PAYLOAD_RESET, + ), + CONF_RETAIN: PlatformField(selector=BOOLEAN_SELECTOR, required=False), + }, + Platform.SELECT: { + CONF_COMMAND_TOPIC: PlatformField( + selector=TEXT_SELECTOR, + required=True, + validator=valid_publish_topic, + error="invalid_publish_topic", + ), + CONF_COMMAND_TEMPLATE: PlatformField( + selector=TEMPLATE_SELECTOR, + required=False, + validator=validate(cv.template), + error="invalid_template", + ), + CONF_STATE_TOPIC: PlatformField( + selector=TEXT_SELECTOR, + required=False, + validator=valid_subscribe_topic, + error="invalid_subscribe_topic", + ), + CONF_VALUE_TEMPLATE: PlatformField( + selector=TEMPLATE_SELECTOR, + required=False, + validator=validate(cv.template), + error="invalid_template", + ), + CONF_OPTIONS: PlatformField(selector=OPTIONS_SELECTOR, required=True), + CONF_RETAIN: PlatformField(selector=BOOLEAN_SELECTOR, required=False), + }, + Platform.SENSOR: { + CONF_STATE_TOPIC: PlatformField( + selector=TEXT_SELECTOR, + required=True, + validator=valid_subscribe_topic, + error="invalid_subscribe_topic", + ), + CONF_VALUE_TEMPLATE: PlatformField( + selector=TEMPLATE_SELECTOR, + required=False, + validator=validate(cv.template), + error="invalid_template", + ), + CONF_LAST_RESET_VALUE_TEMPLATE: PlatformField( + selector=TEMPLATE_SELECTOR, + required=False, + validator=validate(cv.template), + error="invalid_template", + conditions=({CONF_STATE_CLASS: "total"},), + ), + CONF_EXPIRE_AFTER: PlatformField( + selector=TIMEOUT_SELECTOR, + required=False, + validator=cv.positive_int, + section=OTHER_SETTINGS, + ), + }, + Platform.SIREN: { + CONF_COMMAND_TOPIC: PlatformField( + selector=TEXT_SELECTOR, + required=True, + validator=valid_publish_topic, + error="invalid_publish_topic", + ), + CONF_COMMAND_TEMPLATE: PlatformField( + selector=TEMPLATE_SELECTOR, + required=False, + validator=validate(cv.template), + error="invalid_template", + ), + CONF_STATE_TOPIC: PlatformField( + selector=TEXT_SELECTOR, + required=False, + validator=valid_subscribe_topic, + error="invalid_subscribe_topic", + ), + CONF_STATE_VALUE_TEMPLATE: PlatformField( + selector=TEMPLATE_SELECTOR, + required=False, + validator=validate(cv.template), + error="invalid_template", + ), + CONF_PAYLOAD_OFF: PlatformField( + selector=TEXT_SELECTOR, + required=False, + default=DEFAULT_PAYLOAD_OFF, + ), + CONF_PAYLOAD_ON: PlatformField( + selector=TEXT_SELECTOR, + required=False, + default=DEFAULT_PAYLOAD_ON, + ), + CONF_STATE_OFF: PlatformField( + selector=TEXT_SELECTOR, + required=False, + ), + CONF_STATE_ON: PlatformField( + selector=TEXT_SELECTOR, + required=False, + ), + CONF_AVAILABLE_TONES: PlatformField( + selector=OPTIONS_SELECTOR, + required=False, + ), + CONF_SUPPORT_DURATION: PlatformField( + selector=BOOLEAN_SELECTOR, + required=False, + ), + CONF_SUPPORT_VOLUME_SET: PlatformField( + selector=BOOLEAN_SELECTOR, + required=False, + ), + CONF_RETAIN: PlatformField(selector=BOOLEAN_SELECTOR, required=False), + CONF_OPTIMISTIC: PlatformField(selector=BOOLEAN_SELECTOR, required=False), + CONF_COMMAND_OFF_TEMPLATE: PlatformField( + selector=TEMPLATE_SELECTOR, + required=False, + validator=validate(cv.template), + error="invalid_template", + section="siren_other_settings", + ), + }, + Platform.SWITCH: { + CONF_COMMAND_TOPIC: PlatformField( + selector=TEXT_SELECTOR, + required=True, + validator=valid_publish_topic, + error="invalid_publish_topic", + ), + CONF_COMMAND_TEMPLATE: PlatformField( + selector=TEMPLATE_SELECTOR, + required=False, + validator=validate(cv.template), + error="invalid_template", + ), + CONF_STATE_TOPIC: PlatformField( + selector=TEXT_SELECTOR, + required=False, + validator=valid_subscribe_topic, + error="invalid_subscribe_topic", + ), + CONF_VALUE_TEMPLATE: PlatformField( + selector=TEMPLATE_SELECTOR, + required=False, + validator=validate(cv.template), + error="invalid_template", + ), + CONF_PAYLOAD_OFF: PlatformField( + selector=TEXT_SELECTOR, + required=False, + default=DEFAULT_PAYLOAD_OFF, + ), + CONF_PAYLOAD_ON: PlatformField( + selector=TEXT_SELECTOR, + required=False, + default=DEFAULT_PAYLOAD_ON, + ), + CONF_STATE_OFF: PlatformField( + selector=TEXT_SELECTOR, + required=False, + ), + CONF_STATE_ON: PlatformField( + selector=TEXT_SELECTOR, + required=False, + ), + CONF_RETAIN: PlatformField(selector=BOOLEAN_SELECTOR, required=False), + CONF_OPTIMISTIC: PlatformField(selector=BOOLEAN_SELECTOR, required=False), + }, + Platform.TEXT: { + CONF_COMMAND_TOPIC: PlatformField( + selector=TEXT_SELECTOR, + required=True, + validator=valid_publish_topic, + error="invalid_publish_topic", + ), + CONF_COMMAND_TEMPLATE: PlatformField( + selector=TEMPLATE_SELECTOR, + required=False, + validator=validate(cv.template), + error="invalid_template", + ), + CONF_STATE_TOPIC: PlatformField( + selector=TEXT_SELECTOR, + required=False, + validator=valid_subscribe_topic, + error="invalid_subscribe_topic", + ), + CONF_VALUE_TEMPLATE: PlatformField( + selector=TEMPLATE_SELECTOR, + required=False, + validator=validate(cv.template), + error="invalid_template", + ), + CONF_RETAIN: PlatformField(selector=BOOLEAN_SELECTOR, required=False), + CONF_MIN: PlatformField( + selector=TEXT_SIZE_SELECTOR, + required=True, + default=0, + section="text_other_settings", + ), + CONF_MAX: PlatformField( + selector=TEXT_SIZE_SELECTOR, + required=True, + default=255, + section="text_other_settings", + ), + CONF_MODE: PlatformField( + selector=TEXT_MODE_SELECTOR, + required=True, + default=TextSelectorType.TEXT.value, + section="text_other_settings", + ), + CONF_PATTERN: PlatformField( + selector=TEXT_SELECTOR, + required=False, + validator=validate(cv.is_regex), + error="invalid_regular_expression", + section="text_other_settings", + ), + }, + Platform.TIME: { + CONF_COMMAND_TOPIC: PlatformField( + selector=TEXT_SELECTOR, + required=True, + validator=valid_publish_topic, + error="invalid_publish_topic", + ), + CONF_COMMAND_TEMPLATE: PlatformField( + selector=TEMPLATE_SELECTOR, + required=False, + validator=validate(cv.template), + error="invalid_template", + ), + CONF_STATE_TOPIC: PlatformField( + selector=TEXT_SELECTOR, + required=False, + validator=valid_subscribe_topic, + error="invalid_subscribe_topic", + ), + CONF_VALUE_TEMPLATE: PlatformField( + selector=TEMPLATE_SELECTOR, + required=False, + validator=validate(cv.template), + error="invalid_template", + ), + CONF_RETAIN: PlatformField(selector=BOOLEAN_SELECTOR, required=False), + }, + Platform.VALVE: { + CONF_COMMAND_TOPIC: PlatformField( + selector=TEXT_SELECTOR, + required=True, + validator=valid_publish_topic, + error="invalid_publish_topic", + ), + CONF_COMMAND_TEMPLATE: PlatformField( + selector=TEMPLATE_SELECTOR, + required=False, + validator=validate(cv.template), + error="invalid_template", + ), + CONF_STATE_TOPIC: PlatformField( + selector=TEXT_SELECTOR, + required=False, + validator=valid_subscribe_topic, + error="invalid_subscribe_topic", + ), + CONF_VALUE_TEMPLATE: PlatformField( + selector=TEMPLATE_SELECTOR, + required=False, + validator=validate(cv.template), + error="invalid_template", + ), + CONF_POSITION_CLOSED: PlatformField( + selector=VALVE_POSITION_SELECTOR, + required=True, + default=DEFAULT_POSITION_CLOSED, + conditions=({CONF_REPORTS_POSITION: True},), + ), + CONF_POSITION_OPEN: PlatformField( + selector=VALVE_POSITION_SELECTOR, + required=True, + default=DEFAULT_POSITION_OPEN, + conditions=({CONF_REPORTS_POSITION: True},), + ), + CONF_PAYLOAD_OPEN: PlatformField( + selector=TEXT_SELECTOR, + required=True, + default=DEFAULT_PAYLOAD_OPEN, + conditions=({CONF_REPORTS_POSITION: False},), + section="valve_payload_settings", + ), + CONF_PAYLOAD_CLOSE: PlatformField( + selector=TEXT_SELECTOR, + required=True, + default=DEFAULT_PAYLOAD_CLOSE, + conditions=({CONF_REPORTS_POSITION: False},), + section="valve_payload_settings", + ), + CONF_PAYLOAD_STOP: PlatformField( + selector=TEXT_SELECTOR, + required=False, + section="valve_payload_settings", + ), + CONF_STATE_OPEN: PlatformField( + selector=TEXT_SELECTOR, + required=True, + default=ValveState.OPEN.value, + conditions=({CONF_REPORTS_POSITION: False},), + section="valve_payload_settings", + ), + CONF_STATE_CLOSED: PlatformField( + selector=TEXT_SELECTOR, + required=True, + default=ValveState.CLOSED.value, + conditions=({CONF_REPORTS_POSITION: False},), + section="valve_payload_settings", + ), + CONF_STATE_OPENING: PlatformField( + selector=TEXT_SELECTOR, + required=True, + default=ValveState.OPENING.value, + section="valve_payload_settings", + ), + CONF_STATE_CLOSING: PlatformField( + selector=TEXT_SELECTOR, + required=True, + default=ValveState.CLOSING.value, + section="valve_payload_settings", + ), + CONF_RETAIN: PlatformField(selector=BOOLEAN_SELECTOR, required=False), + CONF_OPTIMISTIC: PlatformField(selector=BOOLEAN_SELECTOR, required=False), + }, + Platform.WATER_HEATER: { + # operation mode settings + CONF_MODE_COMMAND_TOPIC: PlatformField( + selector=TEXT_SELECTOR, + required=False, + validator=valid_publish_topic, + error="invalid_publish_topic", + ), + CONF_MODE_COMMAND_TEMPLATE: PlatformField( + selector=TEMPLATE_SELECTOR, + required=False, + validator=validate(cv.template), + error="invalid_template", + ), + CONF_MODE_STATE_TOPIC: PlatformField( + selector=TEXT_SELECTOR, + required=False, + validator=valid_subscribe_topic, + error="invalid_subscribe_topic", + ), + CONF_MODE_STATE_TEMPLATE: PlatformField( + selector=TEMPLATE_SELECTOR, + required=False, + validator=validate(cv.template), + error="invalid_template", + ), + CONF_MODE_LIST: PlatformField( + selector=WATER_HEATER_MODE_SELECTOR, + required=True, + default=[], + validator=validate(no_empty_list), + error="empty_list_not_allowed", + ), + CONF_RETAIN: PlatformField( + selector=BOOLEAN_SELECTOR, required=False, validator=validate(bool) + ), + CONF_OPTIMISTIC: PlatformField( + selector=BOOLEAN_SELECTOR, required=False, validator=validate(bool) + ), + # target temperature settings + CONF_TEMP_COMMAND_TOPIC: PlatformField( + selector=TEXT_SELECTOR, + required=True, + validator=valid_publish_topic, + error="invalid_publish_topic", + section="target_temperature_settings", + ), + CONF_TEMP_COMMAND_TEMPLATE: PlatformField( + selector=TEMPLATE_SELECTOR, + required=False, + validator=validate(cv.template), + error="invalid_template", + section="target_temperature_settings", + ), + CONF_TEMP_STATE_TOPIC: PlatformField( + selector=TEXT_SELECTOR, + required=False, + validator=valid_subscribe_topic, + error="invalid_subscribe_topic", + section="target_temperature_settings", + ), + CONF_TEMP_STATE_TEMPLATE: PlatformField( + selector=TEMPLATE_SELECTOR, + required=False, + validator=validate(cv.template), + error="invalid_template", + section="target_temperature_settings", + ), + CONF_TEMP_MIN: PlatformField( + selector=temperature_selector, + custom_filtering=True, + required=True, + default=temperature_default_from_celsius_to_system_default(43.3), + section="target_temperature_settings", + ), + CONF_TEMP_MAX: PlatformField( + selector=temperature_selector, + custom_filtering=True, + required=True, + default=temperature_default_from_celsius_to_system_default(60), + section="target_temperature_settings", + ), + CONF_PRECISION: PlatformField( + selector=PRECISION_SELECTOR, + required=False, + default=default_precision, + section="target_temperature_settings", + ), + CONF_TEMP_INITIAL: PlatformField( + selector=temperature_selector, + custom_filtering=True, + required=False, + default=temperature_default_from_celsius_to_system_default(43.3), + section="target_temperature_settings", + ), + # current temperature settings + CONF_CURRENT_TEMP_TOPIC: PlatformField( + selector=TEXT_SELECTOR, + required=False, + validator=valid_subscribe_topic, + error="invalid_subscribe_topic", + section="current_temperature_settings", + conditions=({"water_heater_feature_current_temperature": True},), + ), + CONF_CURRENT_TEMP_TEMPLATE: PlatformField( + selector=TEMPLATE_SELECTOR, + required=False, + validator=validate(cv.template), + error="invalid_template", + section="current_temperature_settings", + conditions=({"water_heater_feature_current_temperature": True},), + ), + # power on/off support + CONF_POWER_COMMAND_TOPIC: PlatformField( + selector=TEXT_SELECTOR, + required=False, + validator=valid_publish_topic, + error="invalid_publish_topic", + section="water_heater_power_settings", + conditions=({"water_heater_feature_power": True},), + ), + CONF_POWER_COMMAND_TEMPLATE: PlatformField( + selector=TEMPLATE_SELECTOR, + required=False, + validator=validate(cv.template), + error="invalid_template", + section="water_heater_power_settings", + conditions=({"water_heater_feature_power": True},), + ), + CONF_PAYLOAD_OFF: PlatformField( + selector=TEXT_SELECTOR, + required=False, + default=DEFAULT_PAYLOAD_OFF, + section="water_heater_power_settings", + conditions=({"water_heater_feature_power": True},), + ), + CONF_PAYLOAD_ON: PlatformField( + selector=TEXT_SELECTOR, + required=False, + default=DEFAULT_PAYLOAD_ON, + section="water_heater_power_settings", + conditions=({"water_heater_feature_power": True},), + ), + }, +} +MQTT_DEVICE_PLATFORM_FIELDS = { + CONF_NAME: PlatformField(selector=TEXT_SELECTOR, required=True), + CONF_SW_VERSION: PlatformField( + selector=TEXT_SELECTOR, required=False, section=OTHER_SETTINGS + ), + CONF_HW_VERSION: PlatformField( + selector=TEXT_SELECTOR, required=False, section=OTHER_SETTINGS + ), + CONF_MODEL: PlatformField(selector=TEXT_SELECTOR, required=False), + CONF_MODEL_ID: PlatformField(selector=TEXT_SELECTOR, required=False), + CONF_MANUFACTURER: PlatformField(selector=TEXT_SELECTOR, required=False), + CONF_CONFIGURATION_URL: PlatformField( + selector=TEXT_SELECTOR, required=False, validator=cv.url, error="invalid_url" + ), + CONF_QOS: PlatformField( + selector=QOS_SELECTOR, + required=False, + validator=int, + default=DEFAULT_QOS, + section="mqtt_settings", + ), + CONF_MESSAGE_EXPIRY_INTERVAL: PlatformField( + selector=DurationSelector(DurationSelectorConfig(enable_day=True)), + required=False, + section="mqtt_settings", + ), +} + + +@callback +def _check_conditions( + platform_field: PlatformField, component_data: dict[str, Any] | None = None +) -> bool: + """Only include field if one of conditions match, or no conditions are set.""" + if platform_field.conditions is None or component_data is None: + return True + return any( + all(component_data.get(key) == value for key, value in condition.items()) + for condition in platform_field.conditions + ) + + +@callback +def calculate_merged_config( + merged_user_input: dict[str, Any], + data_schema_fields: dict[str, PlatformField], + component_data: dict[str, Any], +) -> dict[str, Any]: + """Calculate merged config.""" + base_schema_fields = { + key + for key, platform_field in data_schema_fields.items() + if _check_conditions(platform_field, component_data) + } - set(merged_user_input) + return { + key: value + for key, value in component_data.items() + if key not in base_schema_fields + } | merged_user_input + + +@callback +def data_schema_from_fields( + data_schema_fields: dict[str, PlatformField], + reconfig: bool, + component_data: dict[str, Any] | None = None, + user_input: dict[str, Any] | None = None, + device_data: MqttDeviceData | None = None, +) -> probatio.Schema: + """Generate custom data schema from platform fields or device data.""" + + def get_default(field_details: PlatformField) -> Any: + if callable(field_details.default): + if TYPE_CHECKING: + assert component_data is not None + return field_details.default(component_data) + return field_details.default + + if device_data is not None: + component_data_with_user_input: dict[str, Any] | None = dict(device_data) + if TYPE_CHECKING: + assert component_data_with_user_input is not None + component_data_with_user_input.update( + component_data_with_user_input.pop("mqtt_settings", {}) + ) + else: + component_data_with_user_input = deepcopy(component_data) + if component_data_with_user_input is not None and user_input is not None: + component_data_with_user_input |= user_input + + sections: dict[str | None, None] = { + field_details.section: None + for field_details in data_schema_fields.values() + if not field_details.is_schema_default + } + data_schema: dict[Any, Any] = {} + all_data_element_options: set[Any] = set() + no_reconfig_options: set[Any] = set() + + defaults: dict[str, Any] = {} + for field_name, field_details in data_schema_fields.items(): + default = defaults[field_name] = get_default(field_details) + if not field_details.include_in_config or component_data is None: + continue + component_data[field_name] = default + + for schema_section in sections: + # Always calculate the default values + # Getting the default value may update the subentry data, + # even when and option is filtered out + data_schema_element = { + probatio.Required(field_name, default=defaults[field_name]) + if field_details.required + else probatio.Optional( + field_name, + default=defaults[field_name] + if field_details.default is not None + else probatio.UNDEFINED, + ): field_details.selector(component_data_with_user_input or {}) + if callable(field_details.selector) and field_details.custom_filtering + else field_details.selector + for field_name, field_details in data_schema_fields.items() + if not field_details.is_schema_default + and field_details.section == schema_section + and (not field_details.exclude_from_reconfig or not reconfig) + and _check_conditions(field_details, component_data_with_user_input) + } + data_element_options = set(data_schema_element) + all_data_element_options |= data_element_options + no_reconfig_options |= { + field_name + for field_name, field_details in data_schema_fields.items() + if field_details.section == schema_section + and field_details.exclude_from_reconfig + } + if schema_section is None: + data_schema.update(data_schema_element) + continue + if not data_schema_element: + # Do not show empty sections + continue + # Collapse if no values are changed and no required fields need to be set + collapsed = ( + not any( + (default := data_schema_fields[str(option)].default) + is probatio.UNDEFINED + or ( + str(option) in component_data_with_user_input + and component_data_with_user_input[str(option)] != default + ) + for option in data_element_options + if option in component_data_with_user_input + or ( + str(option) in data_schema_fields + and data_schema_fields[str(option)].required + ) + ) + if component_data_with_user_input is not None + else True + ) + data_schema[probatio.Optional(schema_section)] = section( + probatio.Schema(data_schema_element), + SectionConfig({"collapsed": collapsed}), + ) + + # Reset all fields from the component_data not in the schema + # except for options that should stay included + if component_data: + filtered_fields = ( + set(data_schema_fields) - all_data_element_options - no_reconfig_options + ) + for field in filtered_fields: + if ( + field in component_data + and not data_schema_fields[field].include_in_config + ): + del component_data[field] + return probatio.Schema(data_schema) + + +@callback +def validate_user_input( + user_input: dict[str, Any], + data_schema_fields: dict[str, PlatformField], + *, + component_data: dict[str, Any] | None = None, + config_validator: Callable[[dict[str, Any]], dict[str, str]] | None = None, +) -> tuple[dict[str, Any], dict[str, str]]: + """Validate user input.""" + errors: dict[str, str] = {} + # Merge sections + merged_user_input: dict[str, Any] = {} + for key, value in user_input.items(): + if isinstance(value, dict): + merged_user_input.update(value) + else: + merged_user_input[key] = value + + for field, value in merged_user_input.items(): + validator = data_schema_fields[field].validator + try: + merged_user_input[field] = ( + validator(value) if validator is not None else value + ) + except ValueError, probatio.Error, probatio.Invalid: + data_schema_field = data_schema_fields[field] + errors[data_schema_field.section or field] = ( + data_schema_field.error or "invalid_input" + ) + + if config_validator is not None: + if TYPE_CHECKING: + assert component_data is not None + + errors |= config_validator( + calculate_merged_config( + merged_user_input, data_schema_fields, component_data + ), + ) + + return merged_user_input, errors + + +@callback +def subentry_schema_default_data_from_fields( + data_schema_fields: dict[str, PlatformField], + component_data: dict[str, Any], +) -> dict[str, Any]: + """Generate custom data schema from platform fields or device data.""" + return { + key: field.default + for key, field in data_schema_fields.items() + if _check_conditions(field, component_data) + and ( + field.is_schema_default + or (field.default is not probatio.UNDEFINED and key not in component_data) + ) + } + + +@callback +def update_password_from_user_input( + entry_password: str | None, user_input: dict[str, Any] +) -> None: + """Update the password if the entry has been updated. + + As we want to avoid reflecting the stored password in the UI, + we replace the suggested value in the UI with a sentitel, + and we change it back here if it was changed. + """ + # Take out the password submitted + user_password: str | None = user_input.pop(CONF_PASSWORD, None) + # Only add the password if it has changed. + # If the sentinel password is submitted, we replace that with our current + # password from the config entry data. + password_changed = user_password is not None and user_password != PWD_NOT_CHANGED + password = user_password if password_changed else entry_password + if password is not None: + user_input[CONF_PASSWORD] = password + + +REAUTH_SCHEMA = probatio.Schema( + { + probatio.Required(CONF_USERNAME): TEXT_SELECTOR, + probatio.Required(CONF_PASSWORD): PASSWORD_SELECTOR, + } +) + +OTHER_SETTINGS_SCHEMA = probatio.Schema( + { + probatio.Optional(CONF_CLIENT_ID): TEXT_SELECTOR, + probatio.Optional(CONF_KEEPALIVE): KEEPALIVE_SELECTOR, + probatio.Required(SET_CLIENT_CERT): BOOLEAN_SELECTOR, + probatio.Optional(CONF_CLIENT_CERT): CERT_UPLOAD_SELECTOR, + probatio.Optional(CONF_CLIENT_KEY): CERT_KEY_UPLOAD_SELECTOR, + probatio.Optional(CONF_CLIENT_KEY_PASSWORD): PASSWORD_SELECTOR, + probatio.Required(SET_CA_CERT): BROKER_VERIFICATION_SELECTOR, + probatio.Optional(CONF_CERTIFICATE): CA_CERT_UPLOAD_SELECTOR, + probatio.Optional(CONF_TLS_INSECURE): BOOLEAN_SELECTOR, + probatio.Required( + CONF_TRANSPORT, default=DEFAULT_TRANSPORT + ): TRANSPORT_SELECTOR, + probatio.Optional(CONF_WS_PATH): TEXT_SELECTOR, + probatio.Optional(CONF_WS_HEADERS): WS_HEADERS_SELECTOR, + } +) +CONFIG_DATAFLOW_SCHEMA = probatio.Schema( + { + probatio.Required(CONF_BROKER): TEXT_SELECTOR, + probatio.Required(CONF_PORT, default=DEFAULT_PORT): PORT_SELECTOR, + probatio.Required(CONF_PROTOCOL, default=DEFAULT_PROTOCOL): PROTOCOL_SELECTOR, + probatio.Optional(CONF_USERNAME): TEXT_SELECTOR, + probatio.Optional(CONF_PASSWORD): PASSWORD_SELECTOR, + probatio.Required(OTHER_SETTINGS): section( + OTHER_SETTINGS_SCHEMA, SectionConfig({"collapsed": True}) + ), + } +) + + +class FlowHandler(ConfigFlow, domain=DOMAIN): + """Handle a config flow.""" + + VERSION = CONFIG_ENTRY_VERSION # 2 + MINOR_VERSION = CONFIG_ENTRY_MINOR_VERSION # 1 + + _hassio_discovery: dict[str, Any] | None = None + _addon_manager: AddonManager + last_uploaded: dict[str, Any] + + def __init__(self) -> None: + """Set up flow instance.""" + self.install_task: asyncio.Task | None = None + self.start_task: asyncio.Task | None = None + self.last_uploaded = {} + + @override + @classmethod + @callback + def async_get_supported_subentry_types( + cls, config_entry: ConfigEntry + ) -> dict[str, type[ConfigSubentryFlow]]: + """Return subentries supported by this handler.""" + return {CONF_DEVICE: MQTTSubentryFlowHandler} + + @override + @staticmethod + @callback + def async_get_options_flow( + config_entry: ConfigEntry, + ) -> MQTTOptionsFlowHandler: + """Get the options flow for this handler.""" + return MQTTOptionsFlowHandler() + + async def _async_install_addon(self) -> None: + """Install the Mosquitto Mqtt broker add-on.""" + addon_manager: AddonManager = get_addon_manager(self.hass) + await addon_manager.async_schedule_install_addon() + + async def async_step_install_failed( + self, user_input: dict[str, Any] | None = None + ) -> ConfigFlowResult: + """Add-on installation failed.""" + return self.async_abort( + reason="addon_install_failed", + description_placeholders={"addon": self._addon_manager.addon_name}, + ) + + async def async_step_install_addon( + self, user_input: dict[str, Any] | None = None + ) -> ConfigFlowResult: + """Install Mosquitto Broker add-on.""" + if self.install_task is None: + self.install_task = self.hass.async_create_task(self._async_install_addon()) + + if not self.install_task.done(): + return self.async_show_progress( + step_id="install_addon", + progress_action="install_addon", + progress_task=self.install_task, + ) + + try: + await self.install_task + except AddonError as err: + _LOGGER.error(err) + return self.async_show_progress_done(next_step_id="install_failed") + finally: + self.install_task = None + + return self.async_show_progress_done(next_step_id="start_addon") + + async def async_step_start_failed( + self, user_input: dict[str, Any] | None = None + ) -> ConfigFlowResult: + """Add-on start failed.""" + return self.async_abort( + reason="addon_start_failed", + description_placeholders={"addon": self._addon_manager.addon_name}, + ) + + async def async_step_start_addon( + self, user_input: dict[str, Any] | None = None + ) -> ConfigFlowResult: + """Start Mosquitto Broker add-on.""" + if not self.start_task: + self.start_task = self.hass.async_create_task(self._async_start_addon()) + if not self.start_task.done(): + return self.async_show_progress( + step_id="start_addon", + progress_action="start_addon", + progress_task=self.start_task, + ) + try: + await self.start_task + except AddonError as err: + _LOGGER.error(err) + return self.async_show_progress_done(next_step_id="start_failed") + finally: + self.start_task = None + + return self.async_show_progress_done(next_step_id="setup_entry_from_discovery") + + async def _async_get_config_and_try(self) -> dict[str, Any] | None: + """Get the MQTT add-on discovery info and try the connection.""" + if self._hassio_discovery is not None: + return self._hassio_discovery + addon_manager: AddonManager = get_addon_manager(self.hass) + try: + addon_discovery_config = ( + await addon_manager.async_get_addon_discovery_info() + ) + config: dict[str, Any] = { + CONF_BROKER: addon_discovery_config[CONF_HOST], + CONF_PORT: addon_discovery_config[CONF_PORT], + CONF_PROTOCOL: DEFAULT_PROTOCOL, + CONF_USERNAME: addon_discovery_config.get(CONF_USERNAME), + CONF_PASSWORD: addon_discovery_config.get(CONF_PASSWORD), + } + except AddonError: + # We do not have discovery information yet + return None + if await self.hass.async_add_executor_job( + try_connection, + config, + ): + self._hassio_discovery = config + return config + return None + + async def _async_start_addon(self) -> None: + """Start the Mosquitto Broker add-on.""" + addon_manager: AddonManager = get_addon_manager(self.hass) + await addon_manager.async_schedule_start_addon() + + # Sleep some seconds to let the add-on start properly before connecting. + for _ in range(ADDON_SETUP_TIMEOUT_ROUNDS): + await asyncio.sleep(ADDON_SETUP_TIMEOUT) + # Finish setup using discovery info to test the connection + if await self._async_get_config_and_try(): + break + else: + raise AddonError( + translation_domain=DOMAIN, + translation_key="addon_start_failed", + translation_placeholders={"addon": addon_manager.addon_name}, + ) + + @override + async def async_step_user( + self, user_input: dict[str, Any] | None = None + ) -> ConfigFlowResult: + """Handle a flow initialized by the user.""" + if is_hassio(self.hass): + # Offer to set up broker add-on if supervisor is available + self._addon_manager = get_addon_manager(self.hass) + return self.async_show_menu( + step_id="user", + menu_options=["addon", "broker"], + description_placeholders={"addon": self._addon_manager.addon_name}, + ) + + # Start up a flow for manual setup + return await self.async_step_broker() + + async def async_step_setup_entry_from_discovery( + self, user_input: dict[str, Any] | None = None + ) -> ConfigFlowResult: + """Set up mqtt entry from discovery info.""" + if (config := await self._async_get_config_and_try()) is not None: + return self.async_create_entry( + title=self._addon_manager.addon_name, + data=config, + ) + + raise AbortFlow( + "addon_connection_failed", + description_placeholders={"addon": self._addon_manager.addon_name}, + ) + + async def async_step_addon( + self, user_input: dict[str, Any] | None = None + ) -> ConfigFlowResult: + """Install and start MQTT broker add-on.""" + addon_manager = self._addon_manager + + try: + addon_info = await addon_manager.async_get_addon_info() + except AddonError as err: + raise AbortFlow( + "addon_info_failed", + description_placeholders={"addon": self._addon_manager.addon_name}, + ) from err + + if addon_info.state is AddonState.RUNNING: + # Finish setup using discovery info + return await self.async_step_setup_entry_from_discovery() + + if addon_info.state is AddonState.NOT_RUNNING: + return await self.async_step_start_addon() + + # Install the add-on and start it + return await self.async_step_install_addon() + + async def async_step_reauth( + self, entry_data: Mapping[str, Any] + ) -> ConfigFlowResult: + """Handle re-authentication with MQTT broker.""" + if is_hassio(self.hass): + # Check if entry setup matches the add-on discovery config + addon_manager = get_addon_manager(self.hass) + try: + addon_discovery_config = ( + await addon_manager.async_get_addon_discovery_info() + ) + except AddonError: + # Follow manual flow if we have an error + pass + else: + # Check if the addon secrets need to be renewed. + # This will repair the config entry, + # in case the official Mosquitto Broker addon was re-installed. + if ( + entry_data[CONF_BROKER] == addon_discovery_config[CONF_HOST] + and entry_data[CONF_PORT] == addon_discovery_config[CONF_PORT] + and entry_data.get(CONF_USERNAME) + == (username := addon_discovery_config.get(CONF_USERNAME)) + and entry_data.get(CONF_PASSWORD) + != (password := addon_discovery_config.get(CONF_PASSWORD)) + ): + _LOGGER.info( + "Executing autorecovery %s add-on secrets", + addon_manager.addon_name, + ) + return await self.async_step_reauth_confirm( + user_input={CONF_USERNAME: username, CONF_PASSWORD: password} + ) + + return await self.async_step_reauth_confirm() + + async def async_step_reauth_confirm( + self, user_input: dict[str, Any] | None = None + ) -> ConfigFlowResult: + """Confirm re-authentication with MQTT broker.""" + errors: dict[str, str] = {} + + reauth_entry = self._get_reauth_entry() + if user_input: + substituted_used_data = deepcopy(user_input) + update_password_from_user_input( + reauth_entry.data.get(CONF_PASSWORD), substituted_used_data + ) + new_entry_data = {**reauth_entry.data, **substituted_used_data} + if await self.hass.async_add_executor_job( + try_connection, + new_entry_data, + ): + return self.async_update_and_abort(reauth_entry, data=new_entry_data) + + errors["base"] = "invalid_auth" + + schema = self.add_suggested_values_to_schema( + REAUTH_SCHEMA, + { + CONF_USERNAME: reauth_entry.data.get(CONF_USERNAME), + CONF_PASSWORD: PWD_NOT_CHANGED, + }, + ) + return self.async_show_form( + step_id="reauth_confirm", + data_schema=schema, + errors=errors, + ) + + @callback + def async_get_entry_defaults(self) -> dict[str, Any]: + """Load the default settings from the entry.""" + data = self._get_reconfigure_entry().data + other_settings: dict[str, Any] = { + key.schema: data[key.schema] + for key in OTHER_SETTINGS_SCHEMA.schema + if key in data + } + other_settings[SET_CLIENT_CERT] = (CONF_CLIENT_CERT in other_settings) and ( + CONF_CLIENT_KEY in other_settings + ) + other_settings.pop(CONF_CLIENT_CERT, None) + other_settings.pop(CONF_CLIENT_KEY, None) + conf_cert = other_settings.pop(CONF_CERTIFICATE, None) + other_settings[SET_CA_CERT] = ( + "auto" + if conf_cert == "auto" + else "custom" + if conf_cert is not None + else "off" + ) + if CONF_WS_HEADERS in other_settings: + other_settings[CONF_WS_HEADERS] = json_dumps( + other_settings.pop(CONF_WS_HEADERS) + ) + + settings: dict[str, Any] = { + key.schema: data[key.schema] + for key in CONFIG_DATAFLOW_SCHEMA.schema + if key in data + } + settings[OTHER_SETTINGS] = other_settings + if CONF_PASSWORD in settings: + # Hide entry password + settings[CONF_PASSWORD] = PWD_NOT_CHANGED + return settings + + async def async_step_broker( + self, user_input: dict[str, Any] | None = None + ) -> ConfigFlowResult: + """Confirm the setup.""" + errors: dict[str, str] = {} + schema = CONFIG_DATAFLOW_SCHEMA + entry_config_update: dict[str, Any] = {} + entry_defaults: dict[str, Any] | None = None + if is_reconfigure := (self.source == SOURCE_RECONFIGURE): + reconfigure_entry = self._get_reconfigure_entry() + entry_defaults = self.async_get_entry_defaults() + if await async_validate_broker_settings( + self, + reconfigure_entry.data if is_reconfigure else None, + user_input, + entry_config_update, + errors, + ): + if is_reconfigure: + return self.async_update_and_abort( + reconfigure_entry, + data=entry_config_update, + ) + return self.async_create_entry( + title=entry_config_update[CONF_BROKER], + data=entry_config_update, + ) + + schema = self.add_suggested_values_to_schema( + schema, (entry_defaults or {}) | (user_input or {}) + ) + return self.async_show_form(step_id="broker", data_schema=schema, errors=errors) + + async def async_step_reconfigure( + self, user_input: dict[str, Any] | None = None + ) -> ConfigFlowResult: + """Handle a reconfiguration flow initialized by the user.""" + return await self.async_step_broker() + + @override + async def async_step_hassio( + self, discovery_info: HassioServiceInfo + ) -> ConfigFlowResult: + """Receive a Hass.io discovery or process setup after addon install.""" + await self._async_handle_discovery_without_unique_id() + + self._hassio_discovery = discovery_info.config + + return await self.async_step_hassio_confirm() + + async def async_step_hassio_confirm( + self, user_input: dict[str, Any] | None = None + ) -> ConfigFlowResult: + """Confirm a Hass.io discovery.""" + errors: dict[str, str] = {} + if TYPE_CHECKING: + assert self._hassio_discovery + + if user_input is not None: + data: dict[str, Any] = self._hassio_discovery.copy() + data[CONF_BROKER] = data.pop(CONF_HOST) + data[CONF_PROTOCOL] = DEFAULT_PROTOCOL + can_connect = await self.hass.async_add_executor_job( + try_connection, + data, + ) + + if can_connect: + return self.async_create_entry( + title=data["addon"], + data={ + CONF_BROKER: data[CONF_BROKER], + CONF_PORT: data[CONF_PORT], + CONF_PROTOCOL: DEFAULT_PROTOCOL, + CONF_USERNAME: data.get(CONF_USERNAME), + CONF_PASSWORD: data.get(CONF_PASSWORD), + }, + ) + + errors["base"] = "cannot_connect" + + return self.async_show_form( + step_id="hassio_confirm", + description_placeholders={"addon": self._hassio_discovery["addon"]}, + errors=errors, + ) + + +class MQTTOptionsFlowHandler(OptionsFlow): + """Handle MQTT options.""" + + async def async_step_init(self, user_input: None = None) -> ConfigFlowResult: + """Manage the MQTT options.""" + return await self.async_step_options() + + async def async_step_options( + self, user_input: dict[str, Any] | None = None + ) -> ConfigFlowResult: + """Manage the MQTT options.""" + errors = {} + + options_config: dict[str, Any] = dict(self.config_entry.options) + bad_input: bool = False + + def _birth_will(birt_or_will: str) -> dict[str, Any]: + """Return the user input for birth or will.""" + if TYPE_CHECKING: + assert user_input + return { + ATTR_TOPIC: user_input[f"{birt_or_will}_topic"], + ATTR_PAYLOAD: user_input.get(f"{birt_or_will}_payload", ""), + ATTR_QOS: user_input[f"{birt_or_will}_qos"], + ATTR_RETAIN: user_input[f"{birt_or_will}_retain"], + } + + def _validate( + field: str, + values: dict[str, Any], + error_code: str, + schema: Callable[[Any], Any], + ) -> None: + """Validate the user input.""" + nonlocal bad_input + try: + option_values = schema(values) + options_config[field] = option_values + except probatio.Invalid: + errors["base"] = error_code + bad_input = True + + if user_input is not None: + # validate input + options_config[CONF_DISCOVERY] = user_input[CONF_DISCOVERY] + _validate( + CONF_DISCOVERY_PREFIX, + user_input[CONF_DISCOVERY_PREFIX], + "bad_discovery_prefix", + valid_publish_topic, + ) + options_config[CONF_DISCOVERY_QOS] = int(user_input[CONF_DISCOVERY_QOS]) + if "birth_topic" in user_input: + _validate( + CONF_BIRTH_MESSAGE, + _birth_will("birth"), + "bad_birth", + valid_birth_will, + ) + if not user_input["birth_enable"]: + options_config[CONF_BIRTH_MESSAGE] = {} + + if "will_topic" in user_input: + _validate( + CONF_WILL_MESSAGE, + _birth_will("will"), + "bad_will", + valid_birth_will, + ) + if not user_input["will_enable"]: + options_config[CONF_WILL_MESSAGE] = {} + + if not bad_input: + return self.async_create_entry(data=options_config) + + birth = { + **DEFAULT_BIRTH, + **options_config.get(CONF_BIRTH_MESSAGE, {}), + } + will = { + **DEFAULT_WILL, + **options_config.get(CONF_WILL_MESSAGE, {}), + } + discovery = options_config.get(CONF_DISCOVERY, DEFAULT_DISCOVERY) + discovery_prefix = options_config.get(CONF_DISCOVERY_PREFIX, DEFAULT_PREFIX) + discovery_qos = options_config.get(CONF_DISCOVERY_QOS, DEFAULT_QOS) + + # build form + fields: OrderedDict[probatio.Marker, Any] = OrderedDict() + fields[probatio.Optional(CONF_DISCOVERY, default=discovery)] = BOOLEAN_SELECTOR + fields[probatio.Optional(CONF_DISCOVERY_PREFIX, default=discovery_prefix)] = ( + PUBLISH_TOPIC_SELECTOR + ) + fields[probatio.Optional("discovery_qos", default=discovery_qos)] = QOS_SELECTOR + + # Birth message is disabled if CONF_BIRTH_MESSAGE = {} + fields[ + probatio.Optional( + "birth_enable", + default=CONF_BIRTH_MESSAGE not in options_config + or options_config[CONF_BIRTH_MESSAGE] != {}, + ) + ] = BOOLEAN_SELECTOR + fields[ + probatio.Optional( + "birth_topic", description={"suggested_value": birth[ATTR_TOPIC]} + ) + ] = PUBLISH_TOPIC_SELECTOR + fields[ + probatio.Optional( + "birth_payload", description={"suggested_value": birth[CONF_PAYLOAD]} + ) + ] = TEXT_SELECTOR + fields[probatio.Optional("birth_qos", default=birth[ATTR_QOS])] = QOS_SELECTOR + fields[probatio.Optional("birth_retain", default=birth[ATTR_RETAIN])] = ( + BOOLEAN_SELECTOR + ) + + # Will message is disabled if CONF_WILL_MESSAGE = {} + fields[ + probatio.Optional( + "will_enable", + default=CONF_WILL_MESSAGE not in options_config + or options_config[CONF_WILL_MESSAGE] != {}, + ) + ] = BOOLEAN_SELECTOR + fields[ + probatio.Optional( + "will_topic", description={"suggested_value": will[ATTR_TOPIC]} + ) + ] = PUBLISH_TOPIC_SELECTOR + fields[ + probatio.Optional( + "will_payload", description={"suggested_value": will[CONF_PAYLOAD]} + ) + ] = TEXT_SELECTOR + fields[probatio.Optional("will_qos", default=will[ATTR_QOS])] = QOS_SELECTOR + fields[probatio.Optional("will_retain", default=will[ATTR_RETAIN])] = ( + BOOLEAN_SELECTOR + ) + + return self.async_show_form( + step_id="options", + data_schema=probatio.Schema(fields), + errors=errors, + last_step=True, + ) + + +class MQTTSubentryFlowHandler(ConfigSubentryFlow): + """Handle MQTT subentry flow.""" + + _subentry_data: MqttSubentryData + _component_id: str | None = None + + @callback + def update_component_fields( + self, + data_schema_fields: dict[str, PlatformField], + merged_user_input: dict[str, Any], + ) -> None: + """Update the componment fields.""" + if TYPE_CHECKING: + assert self._component_id is not None + component_data = self._subentry_data["components"][self._component_id] + # Remove the fields from the component data + # if they are not in the schema and not in the user input + config = calculate_merged_config( + merged_user_input, data_schema_fields, component_data + ) + for field in ( + field + for field, platform_field in data_schema_fields.items() + if field in (set(component_data) - set(config)) + and not platform_field.exclude_from_reconfig + and not platform_field.include_in_config + ): + component_data.pop(field) + component_data.update(merged_user_input) + + @callback + def generate_names(self) -> tuple[str, str]: + """Generate the device and full entity name.""" + if TYPE_CHECKING: + assert self._component_id is not None + device_name = self._subentry_data[CONF_DEVICE][CONF_NAME] + if entity_name := self._subentry_data["components"][self._component_id].get( + CONF_NAME + ): + full_entity_name: str = f"{device_name} {entity_name}" + else: + full_entity_name = device_name + return device_name, full_entity_name + + @callback + def get_suggested_values_from_component( + self, data_schema: probatio.Schema + ) -> dict[str, Any]: + """Get suggestions from component data based on the data schema.""" + if TYPE_CHECKING: + assert self._component_id is not None + component_data = self._subentry_data["components"][self._component_id] + return { + field_key: self.get_suggested_values_from_component(value.schema) + if isinstance(value, section) + else component_data.get(field_key) + for field_key, value in data_schema.schema.items() + } + + @callback + def get_suggested_values_from_device_data( + self, data_schema: probatio.Schema + ) -> dict[str, Any]: + """Get suggestions from device data based on the data schema.""" + device_data = deepcopy(self._subentry_data["device"]) + device_data.update(device_data.get("mqtt_settings", {})) + return { + field_key: self.get_suggested_values_from_device_data(value.schema) + if isinstance(value, section) + else device_data.get(field_key) + for field_key, value in data_schema.schema.items() + } + + async def async_step_user( + self, user_input: dict[str, Any] | None = None + ) -> SubentryFlowResult: + """Add a subentry.""" + self._subentry_data = MqttSubentryData(device=MqttDeviceData(), components={}) + return await self.async_step_device() + + async def async_step_reconfigure( + self, user_input: dict[str, Any] | None = None + ) -> SubentryFlowResult: + """Reconfigure a subentry.""" + reconfigure_subentry = self._get_reconfigure_subentry() + self._subentry_data = cast( + MqttSubentryData, deepcopy(dict(reconfigure_subentry.data)) + ) + return await self.async_step_summary_menu() + + async def async_step_device( + self, user_input: dict[str, Any] | None = None + ) -> SubentryFlowResult: + """Add a new MQTT device.""" + errors: dict[str, Any] = {} + device_data = self._subentry_data[CONF_DEVICE] + data_schema = data_schema_from_fields( + MQTT_DEVICE_PLATFORM_FIELDS, + device_data=device_data, + reconfig=True, + ) + if user_input is not None: + new_device_data: dict[str, Any] = user_input.copy() + _, errors = validate_user_input(user_input, MQTT_DEVICE_PLATFORM_FIELDS) + if OTHER_SETTINGS in new_device_data: + new_device_data |= new_device_data.pop(OTHER_SETTINGS) + if not errors: + self._subentry_data[CONF_DEVICE] = cast(MqttDeviceData, new_device_data) + if self.source == SOURCE_RECONFIGURE: + return await self.async_step_summary_menu() + return await self.async_step_entity() + data_schema = self.add_suggested_values_to_schema( + data_schema, device_data if user_input is None else user_input + ) + elif self.source == SOURCE_RECONFIGURE: + data_schema = self.add_suggested_values_to_schema( + data_schema, + self.get_suggested_values_from_device_data(data_schema), + ) + + return self.async_show_form( + step_id=CONF_DEVICE, + data_schema=data_schema, + errors=errors, + last_step=False, + ) + + async def async_step_entity( + self, user_input: dict[str, Any] | None = None + ) -> SubentryFlowResult: + """Add or edit an mqtt entity.""" + errors: dict[str, str] = {} + data_schema_fields = COMMON_ENTITY_FIELDS + entity_name_label: str = "" + platform_label: str = "" + component_data: dict[str, Any] | None = None + if reconfig := (self._component_id is not None): + component_data = self._subentry_data["components"][self._component_id] + name: str | None = component_data.get(CONF_NAME) + platform_label = f"{component_data[CONF_PLATFORM]} " + entity_name_label = f" ({name})" if name is not None else "" + data_schema = data_schema_from_fields(data_schema_fields, reconfig=reconfig) + if user_input is not None: + merged_user_input, errors = validate_user_input( + user_input, data_schema_fields, component_data=component_data + ) + if not errors: + if self._component_id is None: + self._component_id = uuid4().hex + self._subentry_data["components"].setdefault(self._component_id, {}) + self.update_component_fields(data_schema_fields, merged_user_input) + return await self.async_step_entity_platform_config() + data_schema = self.add_suggested_values_to_schema(data_schema, user_input) + elif self.source == SOURCE_RECONFIGURE and self._component_id is not None: + data_schema = self.add_suggested_values_to_schema( + data_schema, + self.get_suggested_values_from_component(data_schema), + ) + device_name = self._subentry_data[CONF_DEVICE][CONF_NAME] + return self.async_show_form( + step_id="entity", + data_schema=data_schema, + description_placeholders=TRANSLATION_DESCRIPTION_PLACEHOLDERS + | { + "mqtt_device": device_name, + "entity_name_label": entity_name_label, + "platform_label": platform_label, + }, + errors=errors, + last_step=False, + ) + + def _show_update_or_delete_form(self, step_id: str) -> SubentryFlowResult: + """Help selecting an entity to update or delete.""" + device_name = self._subentry_data[CONF_DEVICE][CONF_NAME] + entities = [ + SelectOptionDict( + value=key, + label=f"{device_name} {component_data.get(CONF_NAME, '-') or '-'}" + f" ({component_data[CONF_PLATFORM]})", + ) + for key, component_data in self._subentry_data["components"].items() + ] + data_schema = probatio.Schema( + { + probatio.Required("component"): SelectSelector( + SelectSelectorConfig( + options=entities, + mode=SelectSelectorMode.LIST, + ) + ) + } + ) + return self.async_show_form( + step_id=step_id, data_schema=data_schema, last_step=False + ) + + async def async_step_update_entity( + self, user_input: dict[str, Any] | None = None + ) -> SubentryFlowResult: + """Select the entity to update.""" + if user_input: + self._component_id = user_input["component"] + return await self.async_step_entity() + if len(self._subentry_data["components"]) == 1: + # Return first key + self._component_id = next(iter(self._subentry_data["components"])) + return await self.async_step_entity() + return self._show_update_or_delete_form("update_entity") + + async def async_step_delete_entity( + self, user_input: dict[str, Any] | None = None + ) -> SubentryFlowResult: + """Select the entity to delete.""" + if user_input: + del self._subentry_data["components"][user_input["component"]] + return await self.async_step_summary_menu() + return self._show_update_or_delete_form("delete_entity") + + async def async_step_entity_platform_config( + self, user_input: dict[str, Any] | None = None + ) -> SubentryFlowResult: + """Configure platform entity details.""" + if TYPE_CHECKING: + assert self._component_id is not None + component_data = self._subentry_data["components"][self._component_id] + platform = component_data[CONF_PLATFORM] + data_schema_fields = ( + SHARED_PLATFORM_ENTITY_FIELDS | PLATFORM_ENTITY_FIELDS[platform] + ) + errors: dict[str, str] = {} + + data_schema = data_schema_from_fields( + data_schema_fields, + reconfig=bool( + {field for field in data_schema_fields if field in component_data} + ), + component_data=component_data, + user_input=user_input, + ) + if user_input is not None: + # Test entity fields against the validator + merged_user_input, errors = validate_user_input( + user_input, + data_schema_fields, + component_data=component_data, + config_validator=ENTITY_CONFIG_VALIDATOR[platform], + ) + if not errors: + self.update_component_fields(data_schema_fields, merged_user_input) + return await self.async_step_mqtt_platform_config() + + data_schema = self.add_suggested_values_to_schema(data_schema, user_input) + else: + data_schema = self.add_suggested_values_to_schema( + data_schema, + self.get_suggested_values_from_component(data_schema), + ) + + device_name, full_entity_name = self.generate_names() + return self.async_show_form( + step_id="entity_platform_config", + data_schema=data_schema, + description_placeholders=TRANSLATION_DESCRIPTION_PLACEHOLDERS + | { + "mqtt_device": device_name, + CONF_PLATFORM: platform, + "entity": full_entity_name, + "url": learn_more_url(platform), + } + | (user_input or {}), + errors=errors, + last_step=False, + ) + + async def async_step_mqtt_platform_config( + self, user_input: dict[str, Any] | None = None + ) -> SubentryFlowResult: + """Configure entity platform MQTT details.""" + errors: dict[str, str] = {} + if TYPE_CHECKING: + assert self._component_id is not None + component_data = self._subentry_data["components"][self._component_id] + platform = component_data[CONF_PLATFORM] + data_schema_fields = PLATFORM_MQTT_FIELDS[platform] + data_schema = data_schema_from_fields( + data_schema_fields, + reconfig=bool( + {field for field in data_schema_fields if field in component_data} + ), + component_data=component_data, + ) + if user_input is not None: + # Test entity fields against the validator + merged_user_input, errors = validate_user_input( + user_input, + data_schema_fields, + component_data=component_data, + config_validator=ENTITY_CONFIG_VALIDATOR[platform], + ) + if not errors: + self.update_component_fields(data_schema_fields, merged_user_input) + self._component_id = None + if self.source == SOURCE_RECONFIGURE: + return await self.async_step_summary_menu() + return self._async_create_subentry() + + data_schema = self.add_suggested_values_to_schema(data_schema, user_input) + else: + data_schema = self.add_suggested_values_to_schema( + data_schema, + self.get_suggested_values_from_component(data_schema), + ) + device_name, full_entity_name = self.generate_names() + return self.async_show_form( + step_id="mqtt_platform_config", + data_schema=data_schema, + description_placeholders=TRANSLATION_DESCRIPTION_PLACEHOLDERS + | { + "mqtt_device": device_name, + CONF_PLATFORM: platform, + "entity": full_entity_name, + "url": learn_more_url(platform), + }, + errors=errors, + last_step=False, + ) + + @callback + def _async_update_component_data_defaults(self) -> None: + """Update component data defaults.""" + for component_data in self._subentry_data["components"].values(): + platform = component_data[CONF_PLATFORM] + platform_fields: dict[str, PlatformField] = ( + COMMON_ENTITY_FIELDS + | SHARED_PLATFORM_ENTITY_FIELDS + | PLATFORM_ENTITY_FIELDS[platform] + | PLATFORM_MQTT_FIELDS[platform] + ) + subentry_default_data = subentry_schema_default_data_from_fields( + platform_fields, + component_data, + ) + component_data.update(subentry_default_data) + for key, platform_field in platform_fields.items(): + if ( + not platform_field.exclude_from_config + or platform_field.include_in_config + ): + continue + if key in component_data: + component_data.pop(key) + + @callback + def _async_create_subentry( + self, user_input: dict[str, Any] | None = None + ) -> SubentryFlowResult: + """Create a subentry for a new MQTT device.""" + device_name = self._subentry_data[CONF_DEVICE][CONF_NAME] + component_data: dict[str, Any] = next( + iter(self._subentry_data["components"].values()) + ) + platform = component_data[CONF_PLATFORM] + entity_name: str | None + if entity_name := component_data.get(CONF_NAME): + full_entity_name: str = f"{device_name} {entity_name}" + else: + full_entity_name = device_name + + self._async_update_component_data_defaults() + return self.async_create_entry( + data=self._subentry_data, + title=self._subentry_data[CONF_DEVICE][CONF_NAME], + description_placeholders={ + "entity": full_entity_name, + CONF_PLATFORM: platform, + }, + ) + + async def async_step_availability( + self, user_input: dict[str, Any] | None = None + ) -> SubentryFlowResult: + """Configure availability options.""" + errors: dict[str, str] = {} + validate_field( + "availability_topic", + valid_subscribe_topic, + user_input, + errors, + "invalid_subscribe_topic", + ) + validate_field( + "availability_template", + valid_subscribe_topic_template, + user_input, + errors, + "invalid_template", + ) + if not errors and user_input is not None: + self._subentry_data.setdefault("availability", MqttAvailabilityData()) + self._subentry_data["availability"] = cast(MqttAvailabilityData, user_input) + return await self.async_step_summary_menu() + + data_schema = SUBENTRY_AVAILABILITY_SCHEMA + data_schema = self.add_suggested_values_to_schema( + data_schema, + dict(self._subentry_data.setdefault("availability", {})) + if self.source == SOURCE_RECONFIGURE + else user_input, + ) + return self.async_show_form( + step_id="availability", + data_schema=data_schema, + errors=errors, + last_step=False, + ) + + async def async_step_summary_menu( + self, user_input: dict[str, Any] | None = None + ) -> SubentryFlowResult: + """Show summary menu and decide to add more entities or to finish the flow.""" + self._component_id = None + mqtt_device = self._subentry_data[CONF_DEVICE][CONF_NAME] + mqtt_items = ", ".join( + f"{mqtt_device} {component_data.get(CONF_NAME, '-') or '-'} " + f"({component_data[CONF_PLATFORM]})" + for component_data in self._subentry_data["components"].values() + ) + menu_options = [ + "entity", + "update_entity", + ] + if len(self._subentry_data["components"]) > 1: + menu_options.append("delete_entity") + menu_options.extend(["device", "availability"]) + self._async_update_component_data_defaults() + menu_options.append( + "save_changes" + if self._subentry_data != self._get_reconfigure_subentry().data + else "export" + ) + return self.async_show_menu( + step_id="summary_menu", + menu_options=menu_options, + description_placeholders={ + "mqtt_device": mqtt_device, + "mqtt_items": mqtt_items, + }, + ) + + async def async_step_save_changes( + self, user_input: dict[str, Any] | None = None + ) -> SubentryFlowResult: + """Save the changes made to the subentry.""" + entry = self._get_entry() + subentry = self._get_reconfigure_subentry() + entity_registry = er.async_get(self.hass) + + # When a component is removed from the MQTT device, + # And we save the changes to the subentry, + # we need to clean up stale entity registry entries. + # The component id is used as a part of the unique id of the entity. + for unique_id, platform in [ + ( + f"{subentry.subentry_id}_{component_id}", + subentry.data["components"][component_id][CONF_PLATFORM], + ) + for component_id in subentry.data["components"] + if component_id not in self._subentry_data["components"] + ]: + if entity_id := entity_registry.async_get_entity_id( + platform, DOMAIN, unique_id + ): + entity_registry.async_remove(entity_id) + + return self.async_update_and_abort( + entry, + subentry, + data=self._subentry_data, + title=self._subentry_data[CONF_DEVICE][CONF_NAME], + ) + + async def async_step_export( + self, user_input: dict[str, Any] | None = None + ) -> SubentryFlowResult: + """Export the MQTT device config as YAML or discovery payload.""" + return self.async_show_menu( + step_id="export", + menu_options=["export_yaml", "export_discovery"], + ) + + async def async_step_export_yaml( + self, user_input: dict[str, Any] | None = None + ) -> SubentryFlowResult: + """Export the MQTT device config as YAML.""" + if user_input is not None: + return await self.async_step_summary_menu() + + subentry = self._get_reconfigure_subentry() + mqtt_yaml_config_base: dict[str, list[dict[str, dict[str, Any]]]] = {DOMAIN: []} + mqtt_yaml_config = mqtt_yaml_config_base[DOMAIN] + + for component_id, component_data in self._subentry_data["components"].items(): + component_config: dict[str, Any] = component_data.copy() + component_config[CONF_UNIQUE_ID] = f"{subentry.subentry_id}_{component_id}" + component_config[CONF_DEVICE] = { + key: value + for key, value in self._subentry_data["device"].items() + if key != "mqtt_settings" + } | {"identifiers": [subentry.subentry_id]} + platform = component_config.pop(CONF_PLATFORM) + component_config.update(self._subentry_data.get("availability", {})) + component_config.update( + self._subentry_data["device"].get("mqtt_settings", {}).copy() + ) + for field in EXCLUDE_FROM_CONFIG_IF_NONE: + if field in component_config and ( + component_config[field] is None or component_config[field] == "None" + ): + component_config.pop(field) + mqtt_yaml_config.append({platform: component_config}) + + yaml_config = yaml.dump(mqtt_yaml_config_base) + data_schema = probatio.Schema( + { + probatio.Optional("yaml"): TEMPLATE_SELECTOR_READ_ONLY, + } + ) + data_schema = self.add_suggested_values_to_schema( + data_schema=data_schema, + suggested_values={"yaml": yaml_config}, + ) + return self.async_show_form( + step_id="export_yaml", + last_step=False, + data_schema=data_schema, + description_placeholders={"url": INTEGRATION_URL}, + ) + + async def async_step_export_discovery( + self, user_input: dict[str, Any] | None = None + ) -> SubentryFlowResult: + """Export the MQTT device config dor MQTT discovery.""" + + if user_input is not None: + return await self.async_step_summary_menu() + + subentry = self._get_reconfigure_subentry() + discovery_topic = f"homeassistant/device/{subentry.subentry_id}/config" + discovery_payload: dict[str, Any] = {} + discovery_payload.update(self._subentry_data.get("availability", {})) + discovery_payload["dev"] = { + key: value + for key, value in self._subentry_data["device"].items() + if key != "mqtt_settings" + } | {"identifiers": [subentry.subentry_id]} + discovery_payload["o"] = {"name": "MQTT subentry export"} + discovery_payload["cmps"] = {} + + for component_id, component_data in self._subentry_data["components"].items(): + component_config: dict[str, Any] = component_data.copy() + component_config[CONF_UNIQUE_ID] = f"{subentry.subentry_id}_{component_id}" + component_config.update(self._subentry_data.get("availability", {})) + component_config.update( + self._subentry_data["device"].get("mqtt_settings", {}).copy() + ) + for field in EXCLUDE_FROM_CONFIG_IF_NONE: + if field in component_config and ( + component_config[field] is None or component_config[field] == "None" + ): + component_config.pop(field) + discovery_payload["cmps"][component_id] = component_config + + data_schema = probatio.Schema( + { + probatio.Optional("discovery_topic"): TEXT_SELECTOR_READ_ONLY, + probatio.Optional("discovery_payload"): TEMPLATE_SELECTOR_READ_ONLY, + } + ) + data_schema = self.add_suggested_values_to_schema( + data_schema=data_schema, + suggested_values={ + "discovery_topic": discovery_topic, + "discovery_payload": json.dumps(discovery_payload, indent=2), + }, + ) + return self.async_show_form( + step_id="export_discovery", + last_step=False, + data_schema=data_schema, + description_placeholders={"url": INTEGRATION_URL}, + ) + + +@callback +def async_is_pem_data(data: bytes) -> bool: + """Return True if data is in PEM format.""" + return ( + b"-----BEGIN CERTIFICATE-----" in data + or b"-----BEGIN PRIVATE KEY-----" in data + or b"-----BEGIN EC PRIVATE KEY-----" in data + or b"-----BEGIN RSA PRIVATE KEY-----" in data + or b"-----BEGIN ENCRYPTED PRIVATE KEY-----" in data + ) + + +class PEMType(IntEnum): + """Type of PEM data.""" + + CERTIFICATE = 1 + PRIVATE_KEY = 2 + + +@callback +def async_convert_to_pem( + data: bytes, pem_type: PEMType, password: str | None = None +) -> str | None: + """Convert data to PEM format.""" + try: + if async_is_pem_data(data): + if not password: + # Assume unencrypted PEM encoded private key + return data.decode(DEFAULT_ENCODING) + # Return decrypted PEM encoded private key + return ( + load_pem_private_key(data, password=password.encode(DEFAULT_ENCODING)) + .private_bytes( + encoding=Encoding.PEM, + format=PrivateFormat.TraditionalOpenSSL, + encryption_algorithm=NoEncryption(), + ) + .decode(DEFAULT_ENCODING) + ) + # Convert from DER encoding to PEM + if pem_type == PEMType.CERTIFICATE: + return ( + load_der_x509_certificate(data) + .public_bytes( + encoding=Encoding.PEM, + ) + .decode(DEFAULT_ENCODING) + ) + # Assume DER encoded private key + pem_key_data: bytes = load_der_private_key( + data, password.encode(DEFAULT_ENCODING) if password else None + ).private_bytes( + encoding=Encoding.PEM, + format=PrivateFormat.TraditionalOpenSSL, + encryption_algorithm=NoEncryption(), + ) + return pem_key_data.decode("utf-8") + except TypeError, ValueError, SSLError: + _LOGGER.exception("Error converting %s file data to PEM format", pem_type.name) + return None + + +async def _get_uploaded_file(hass: HomeAssistant, id: str) -> bytes: + """Get file content from uploaded certificate or key file.""" + + def _proces_uploaded_file() -> bytes: + with process_uploaded_file(hass, id) as file_path: + return file_path.read_bytes() + + return await hass.async_add_executor_job(_proces_uploaded_file) + + +async def async_validate_broker_settings( + flow: FlowHandler, + entry_config: MappingProxyType[str, Any] | None, + user_input: dict[str, Any] | None, + entry_config_update: dict[str, Any], + errors: dict[str, str], +) -> bool: + """Validate the broker settings, and return the updated entry dataset.""" + + async def _async_process_file_upload( + upload_id: str, + field: str, + pem_type: PEMType, + error_code: str, + password: str | None = None, + ) -> bool: + """Get uploaded file, or a preserved copy, and convert to a PEM file.""" + try: + data_raw = await _get_uploaded_file(hass, upload_id) + except ValueError: + # Use preserved file if available. + # When an uploaded file was read, but an error occurs, + # the form will reload but the temporary file from the upload + # will not be available any more. If it was processed correctly, + # we can use the preserved copy. + if upload_id in flow.last_uploaded: + data_raw = flow.last_uploaded[upload_id] + else: + raise + else: + # Preserve a copy in case the validation fails, + # and we need it later + flow.last_uploaded[upload_id] = data_raw + pem_data = async_convert_to_pem(data_raw, pem_type, password) + if upload_id and not pem_data: + errors["base"] = error_code + return False + entry_config_update[field] = pem_data + return True + + if user_input is None: + return False + + hass = flow.hass + + # Copy basic and other entry fields + entry_config_update |= user_input + entry_config_update.update(entry_config_update.pop(OTHER_SETTINGS)) + # Pop incompatible fields for update + for key in ( + SET_CA_CERT, + SET_CLIENT_CERT, + CONF_CERTIFICATE, + CONF_CLIENT_CERT, + CONF_CLIENT_KEY, + CONF_CLIENT_KEY_PASSWORD, + ): + entry_config_update.pop(key, None) + + # Get current CA certificate settings from config entry + if (set_ca_cert := user_input[OTHER_SETTINGS][SET_CA_CERT]) == "auto": + entry_config_update[CONF_CERTIFICATE] = "auto" + elif ( + entry_config is not None + and set_ca_cert == "custom" + and (current_cert := entry_config.get(CONF_CERTIFICATE)) + ): + entry_config_update[CONF_CERTIFICATE] = current_cert + + # Prepare entry update with uploaded certificate files + # converted to PEM format + new_client_certificate: str | None = user_input[OTHER_SETTINGS].get( + CONF_CLIENT_CERT + ) + new_client_key: str | None = user_input[OTHER_SETTINGS].get(CONF_CLIENT_KEY) + set_client_cert = user_input[OTHER_SETTINGS][SET_CLIENT_CERT] + + if (new_client_certificate and not new_client_key) or ( + not new_client_certificate and new_client_key + ): + errors["base"] = "invalid_inclusion" + return False + + if new_certificate := user_input[OTHER_SETTINGS].get(CONF_CERTIFICATE): + if not await _async_process_file_upload( + new_certificate, CONF_CERTIFICATE, PEMType.CERTIFICATE, "bad_certificate" + ): + return False + + if new_client_certificate: + if not await _async_process_file_upload( + new_client_certificate, + CONF_CLIENT_CERT, + PEMType.CERTIFICATE, + "bad_client_cert", + ): + return False + elif ( + entry_config is not None + and set_client_cert + and (client_cert := entry_config.get(CONF_CLIENT_CERT)) + ): + entry_config_update[CONF_CLIENT_CERT] = client_cert + + if new_client_key: + if not await _async_process_file_upload( + new_client_key, + CONF_CLIENT_KEY, + PEMType.PRIVATE_KEY, + "client_key_error", + password=user_input[OTHER_SETTINGS].get(CONF_CLIENT_KEY_PASSWORD), + ): + return False + elif ( + entry_config is not None + and set_client_cert + and (client_key := entry_config.get(CONF_CLIENT_KEY)) + ): + entry_config_update[CONF_CLIENT_KEY] = client_key + + # We temporarily create the current and new uploaded certificate files + # and we check the certificate chain. + await async_create_certificate_temp_files(hass, entry_config_update) + if error := await hass.async_add_executor_job( + check_certicate_chain, + ): + errors["base"] = error + return False + + if user_input[OTHER_SETTINGS].get(CONF_TRANSPORT, TRANSPORT_TCP) == TRANSPORT_TCP: + entry_config_update.pop(CONF_WS_PATH, None) + entry_config_update.pop(CONF_WS_HEADERS, None) + else: + # Web socket transport + try: + entry_config_update[CONF_WS_HEADERS] = json_loads( + user_input[OTHER_SETTINGS].get(CONF_WS_HEADERS, "{}") + ) + schema = probatio.Schema({str: str}) + schema(entry_config_update[CONF_WS_HEADERS]) + except (*JSON_DECODE_EXCEPTIONS, probatio.MultipleInvalid): + errors["base"] = "bad_ws_headers" + return False + + # Test the configuration + if entry_config is not None: + update_password_from_user_input( + entry_config.get(CONF_PASSWORD), entry_config_update + ) + if await hass.async_add_executor_job( + try_connection, + entry_config_update, + ): + return True + + errors["base"] = "cannot_connect" + return False + + +def check_certicate_chain() -> str | None: + """Check the MQTT certificates.""" + if client_certificate := get_file_path(CONF_CLIENT_CERT): + try: + with open(client_certificate, "rb") as client_certificate_file: + load_pem_x509_certificate(client_certificate_file.read()) + except ValueError: + return "bad_client_cert" + # Check we can serialize the private key file + if private_key := get_file_path(CONF_CLIENT_KEY): + try: + with open(private_key, "rb") as client_key_file: + load_pem_private_key(client_key_file.read(), password=None) + except TypeError, ValueError: + return "client_key_error" + # Check the certificate chain + context = SSLContext(PROTOCOL_TLS_CLIENT) + if client_certificate and private_key: + try: + context.load_cert_chain(client_certificate, private_key) + except SSLError: + return "bad_client_cert_key" + # try to load the custom CA file + if (ca_cert := get_file_path(CONF_CERTIFICATE)) is None: + return None + + try: + context.load_verify_locations(ca_cert) + except SSLError: + return "bad_certificate" + return None diff --git a/custom_components/vmqtt/config_integration.py b/custom_components/vmqtt/config_integration.py new file mode 100644 index 0000000..5771cb6 --- /dev/null +++ b/custom_components/vmqtt/config_integration.py @@ -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]), + } +) diff --git a/custom_components/vmqtt/const.py b/custom_components/vmqtt/const.py new file mode 100644 index 0000000..c57d0af --- /dev/null +++ b/custom_components/vmqtt/const.py @@ -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", +) diff --git a/custom_components/vmqtt/cover.py b/custom_components/vmqtt/cover.py new file mode 100644 index 0000000..7e8849a --- /dev/null +++ b/custom_components/vmqtt/cover.py @@ -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], + ) diff --git a/custom_components/vmqtt/date.py b/custom_components/vmqtt/date.py new file mode 100644 index 0000000..76d2212 --- /dev/null +++ b/custom_components/vmqtt/date.py @@ -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() diff --git a/custom_components/vmqtt/datetime.py b/custom_components/vmqtt/datetime.py new file mode 100644 index 0000000..9ca67b8 --- /dev/null +++ b/custom_components/vmqtt/datetime.py @@ -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() diff --git a/custom_components/vmqtt/debug_info.py b/custom_components/vmqtt/debug_info.py new file mode 100644 index 0000000..5c6deda --- /dev/null +++ b/custom_components/vmqtt/debug_info.py @@ -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 diff --git a/custom_components/vmqtt/device_automation.py b/custom_components/vmqtt/device_automation.py new file mode 100644 index 0000000..c0a1487 --- /dev/null +++ b/custom_components/vmqtt/device_automation.py @@ -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) diff --git a/custom_components/vmqtt/device_tracker.py b/custom_components/vmqtt/device_tracker.py new file mode 100644 index 0000000..33411b6 --- /dev/null +++ b/custom_components/vmqtt/device_tracker.py @@ -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, + } + } diff --git a/custom_components/vmqtt/device_trigger.py b/custom_components/vmqtt/device_trigger.py new file mode 100644 index 0000000..4ed272f --- /dev/null +++ b/custom_components/vmqtt/device_trigger.py @@ -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) diff --git a/custom_components/vmqtt/diagnostics.py b/custom_components/vmqtt/diagnostics.py new file mode 100644 index 0000000..8b1a643 --- /dev/null +++ b/custom_components/vmqtt/diagnostics.py @@ -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 diff --git a/custom_components/vmqtt/discovery.py b/custom_components/vmqtt/discovery.py new file mode 100644 index 0000000..a3ccc54 --- /dev/null +++ b/custom_components/vmqtt/discovery.py @@ -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\w+)/(?:(?P[a-zA-Z0-9_-]+)/)" + r"?(?P[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) diff --git a/custom_components/vmqtt/entity.py b/custom_components/vmqtt/entity.py new file mode 100644 index 0000000..3d9704d --- /dev/null +++ b/custom_components/vmqtt/entity.py @@ -0,0 +1,1803 @@ +"""MQTT (entity) component mixins and helpers.""" + +from abc import ABC, abstractmethod +from collections.abc import Callable, Coroutine +from functools import partial +import logging +from typing import TYPE_CHECKING, Any, Protocol, cast, final, override + +import probatio + +from homeassistant.config_entries import ConfigEntry +from homeassistant.const import ( + ATTR_CONFIGURATION_URL, + ATTR_HW_VERSION, + ATTR_MANUFACTURER, + ATTR_MODEL, + ATTR_MODEL_ID, + ATTR_NAME, + ATTR_SERIAL_NUMBER, + ATTR_SUGGESTED_AREA, + ATTR_SW_VERSION, + CONF_DEVICE, + CONF_ENTITY_CATEGORY, + CONF_ICON, + CONF_MODEL, + CONF_MODEL_ID, + CONF_NAME, + CONF_UNIQUE_ID, + CONF_UNIT_OF_MEASUREMENT, + CONF_VALUE_TEMPLATE, + EntityCapabilityAttribute, + EntityStateAttribute, +) +from homeassistant.core import Event, HassJobType, HomeAssistant, callback +from homeassistant.helpers import device_registry as dr, entity_registry as er +from homeassistant.helpers.device_registry import ( + DeviceEntry, + DeviceInfo, + EventDeviceRegistryUpdatedData, +) +from homeassistant.helpers.dispatcher import ( + async_dispatcher_connect, + async_dispatcher_send, +) +from homeassistant.helpers.entity import Entity, async_generate_entity_id +from homeassistant.helpers.entity_platform import AddConfigEntryEntitiesCallback +from homeassistant.helpers.event import ( + async_track_device_registry_updated_event, + async_track_entity_registry_updated_event, +) +from homeassistant.helpers.group import IntegrationSpecificGroup +from homeassistant.helpers.issue_registry import IssueSeverity, async_create_issue +from homeassistant.helpers.service_info.mqtt import ReceivePayloadType +from homeassistant.helpers.typing import ( + UNDEFINED, + ConfigType, + DiscoveryInfoType, + UndefinedType, + VolSchemaType, +) +from homeassistant.util.json import json_loads +from homeassistant.util.yaml import dump as yaml_dump + +from . import debug_info, subscription +from .client import async_publish +from .const import ( + ATTR_DISCOVERY_HASH, + ATTR_DISCOVERY_PAYLOAD, + ATTR_DISCOVERY_TOPIC, + AVAILABILITY_ALL, + AVAILABILITY_ANY, + CONF_AVAILABILITY, + CONF_AVAILABILITY_MODE, + CONF_AVAILABILITY_TEMPLATE, + CONF_AVAILABILITY_TOPIC, + CONF_CONFIGURATION_URL, + CONF_CONNECTIONS, + CONF_DEFAULT_ENTITY_ID, + CONF_ENABLED_BY_DEFAULT, + CONF_ENCODING, + CONF_ENTITY_PICTURE, + CONF_GROUP, + CONF_HW_VERSION, + CONF_IDENTIFIERS, + CONF_JSON_ATTRS_TEMPLATE, + CONF_JSON_ATTRS_TOPIC, + CONF_MANUFACTURER, + CONF_MESSAGE_EXPIRY_INTERVAL, + CONF_PAYLOAD_AVAILABLE, + CONF_PAYLOAD_NOT_AVAILABLE, + CONF_QOS, + CONF_RETAIN, + CONF_SCHEMA, + CONF_SERIAL_NUMBER, + CONF_SUGGESTED_AREA, + CONF_SW_VERSION, + CONF_TOPIC, + CONF_VIA_DEVICE, + CONF_VISIBLE_BY_DEFAULT, + DOMAIN, + MQTT_CONNECTION_STATE, +) +from .debug_info import log_message +from .discovery import ( + MQTT_DISCOVERY_DONE, + MQTT_DISCOVERY_NEW, + MQTT_DISCOVERY_UPDATED, + MQTTDiscoveryPayload, + clear_discovery_hash, + get_origin_log_string, + get_origin_support_url, + set_discovery_hash, +) +from .models import ( + DATA_MQTT, + MessageCallbackType, + MqttSubentryData, + MqttValueTemplate, + MqttValueTemplateException, + PublishPayloadType, + ReceiveMessage, +) +from .subscription import ( + EntitySubscription, + async_prepare_subscribe_topics, + async_subscribe_topics_internal, + async_unsubscribe_topics, +) +from .util import ( + async_cleanup_device_registry, + learn_more_url, + mqtt_config_entry_enabled, +) + +_LOGGER = logging.getLogger(__name__) + +MQTT_ATTRIBUTES_BLOCKED = { + "available", + "device_info", + "entity_category", + "entity_id", + "entity_registry_enabled_default", + "extra_state_attributes", + "force_update", + "should_poll", + "state", + "unique_id", + EntityCapabilityAttribute.GROUP_ENTITIES, + EntityStateAttribute.ASSUMED_STATE, + EntityStateAttribute.DEVICE_CLASS, + EntityStateAttribute.ENTITY_PICTURE, + EntityStateAttribute.FRIENDLY_NAME, + EntityStateAttribute.ICON, + EntityStateAttribute.SUPPORTED_FEATURES, + EntityStateAttribute.UNIT_OF_MEASUREMENT, +} + +PUBLISH_KWARGS = (CONF_MESSAGE_EXPIRY_INTERVAL,) + + +@callback +def async_handle_schema_error( + discovery_payload: MQTTDiscoveryPayload, err: probatio.Invalid +) -> None: + """Help handling schema errors on MQTT discovery messages.""" + discovery_topic: str = discovery_payload.discovery_data[ATTR_DISCOVERY_TOPIC] + _LOGGER.error( + "Error '%s' when processing MQTT discovery message topic: '%s', message: '%s'", + err, + discovery_topic, + discovery_payload, + ) + + +def _handle_discovery_failure( + hass: HomeAssistant, + discovery_payload: MQTTDiscoveryPayload, +) -> None: + """Handle discovery failure.""" + discovery_hash = discovery_payload.discovery_data[ATTR_DISCOVERY_HASH] + clear_discovery_hash(hass, discovery_hash) + async_dispatcher_send(hass, MQTT_DISCOVERY_DONE.format(*discovery_hash), None) + + +def _verify_mqtt_config_entry_enabled_for_discovery( + hass: HomeAssistant, domain: str, discovery_payload: MQTTDiscoveryPayload +) -> bool: + """Verify MQTT config entry is enabled or log warning.""" + if not mqtt_config_entry_enabled(hass): + _LOGGER.warning( + ( + "MQTT integration is disabled, skipping setup of discovered item " + "MQTT %s, payload %s" + ), + domain, + discovery_payload, + ) + return False + return True + + +class _SetupNonEntityHelperCallbackProtocol(Protocol): # pragma: no cover + """Callback protocol for async_setup in async_setup_non_entity_entry_helper.""" + + async def __call__( + self, config: ConfigType, discovery_data: DiscoveryInfoType + ) -> None: ... + + +@callback +def async_setup_non_entity_entry_helper( + hass: HomeAssistant, + domain: str, + async_setup: _SetupNonEntityHelperCallbackProtocol, + discovery_schema: probatio.Schema, +) -> None: + """Set up automation or tag creation dynamically through MQTT discovery.""" + mqtt_data = hass.data[DATA_MQTT] + + async def _async_setup_non_entity_entry_from_discovery( + discovery_payload: MQTTDiscoveryPayload, + ) -> None: + """Set up an MQTT entity, automation or tag from discovery.""" + if not _verify_mqtt_config_entry_enabled_for_discovery( + hass, domain, discovery_payload + ): + return + try: + config: ConfigType = discovery_schema(discovery_payload) + await async_setup(config, discovery_data=discovery_payload.discovery_data) + except probatio.Invalid as err: + _handle_discovery_failure(hass, discovery_payload) + async_handle_schema_error(discovery_payload, err) + except Exception: + _handle_discovery_failure(hass, discovery_payload) + raise + + mqtt_data.reload_dispatchers.append( + async_dispatcher_connect( + hass, + MQTT_DISCOVERY_NEW.format(domain, "mqtt"), + _async_setup_non_entity_entry_from_discovery, + ) + ) + + +@callback +def async_setup_entity_entry_helper( # noqa: C901 + hass: HomeAssistant, + entry: ConfigEntry, + entity_class: type[MqttEntity] | None, + domain: str, + async_add_entities: AddConfigEntryEntitiesCallback, + discovery_schema: VolSchemaType, + platform_schema_modern: VolSchemaType, + schema_class_mapping: dict[str, type[MqttEntity]] | None = None, +) -> None: + """Set up entity creation dynamically through MQTT discovery.""" + mqtt_data = hass.data[DATA_MQTT] + + @callback + def _async_migrate_subentry( + config: dict[str, Any], raw_config: dict[str, Any], migration_type: str + ) -> bool: + """Start a repair flow to allow migration of MQTT device subentries. + + If a YAML config or discovery is detected using the ID + of an existing mqtt subentry, and exported configuration is detected, + and a repair flow is offered to migrate the subentry. + """ + if ( + CONF_DEVICE in config + and CONF_IDENTIFIERS in config[CONF_DEVICE] + and config[CONF_DEVICE][CONF_IDENTIFIERS] + and (subentry_id := config[CONF_DEVICE][CONF_IDENTIFIERS][0]) + in entry.subentries + ): + name: str = config[CONF_DEVICE].get(CONF_NAME, "-") + if migration_type == "subentry_migration_yaml": + _LOGGER.info( + "Starting migration repair flow for MQTT subentry %s " + "for migration to YAML config: %s", + subentry_id, + raw_config, + ) + elif migration_type == "subentry_migration_discovery": + _LOGGER.info( + "Starting migration repair flow for MQTT subentry %s " + "for migration to configuration via MQTT discovery: %s", + subentry_id, + raw_config, + ) + async_create_issue( + hass, + DOMAIN, + subentry_id, + issue_domain=DOMAIN, + is_fixable=True, + severity=IssueSeverity.WARNING, + learn_more_url=learn_more_url(domain), + data={ + "entry_id": entry.entry_id, + "subentry_id": subentry_id, + "name": name, + }, + translation_placeholders={"name": name}, + translation_key=migration_type, + ) + return True + + return False + + @callback + def _async_setup_entity_entry_from_discovery( + discovery_payload: MQTTDiscoveryPayload, + ) -> None: + """Set up an MQTT entity from discovery.""" + nonlocal entity_class + if not _verify_mqtt_config_entry_enabled_for_discovery( + hass, domain, discovery_payload + ): + return + try: + config: DiscoveryInfoType = discovery_schema(discovery_payload) + if schema_class_mapping is not None: + entity_class = schema_class_mapping[config[CONF_SCHEMA]] + if TYPE_CHECKING: + assert entity_class is not None + if _async_migrate_subentry( + config, discovery_payload, "subentry_migration_discovery" + ): + _handle_discovery_failure(hass, discovery_payload) + _LOGGER.debug( + "MQTT discovery skipped, as device exists in subentry, " + "and repair flow must be completed first" + ) + else: + async_add_entities( + [ + entity_class( + hass, config, entry, discovery_payload.discovery_data + ) + ] + ) + except probatio.Invalid as err: + _handle_discovery_failure(hass, discovery_payload) + async_handle_schema_error(discovery_payload, err) + except Exception: + _handle_discovery_failure(hass, discovery_payload) + raise + + mqtt_data.reload_dispatchers.append( + async_dispatcher_connect( + hass, + MQTT_DISCOVERY_NEW.format(domain, "mqtt"), + _async_setup_entity_entry_from_discovery, + ) + ) + + @callback + def _async_setup_entities() -> None: + """Set up MQTT items from subentries and configuration.yaml.""" + nonlocal entity_class + mqtt_data = hass.data[DATA_MQTT] + config_yaml = mqtt_data.config + yaml_configs: list[ConfigType] = [ + config + for config_item in config_yaml + for config_domain, configs in config_item.items() + for config in configs + if config_domain == domain + ] + # process subentry entity setup + for config_subentry_id, subentry in entry.subentries.items(): + subentry_data = cast(MqttSubentryData, subentry.data) + availability_config = subentry_data.get("availability", {}) + subentry_entities: list[Entity] = [] + device_config = subentry_data["device"].copy() + device_mqtt_options = device_config.pop("mqtt_settings", {}) + device_config["identifiers"] = config_subentry_id + for component_id, component_data in subentry_data["components"].items(): + if component_data["platform"] != domain: + continue + component_config: dict[str, Any] = component_data.copy() + component_config[CONF_UNIQUE_ID] = ( + f"{config_subentry_id}_{component_id}" + ) + component_config[CONF_DEVICE] = device_config + component_config.pop("platform") + component_config.update(availability_config) + component_config.update(device_mqtt_options) + if ( + CONF_ENTITY_CATEGORY in component_config + and component_config[CONF_ENTITY_CATEGORY] is None + ): + component_config.pop(CONF_ENTITY_CATEGORY) + if component_config.get(CONF_UNIT_OF_MEASUREMENT) == "None": + component_config.pop(CONF_UNIT_OF_MEASUREMENT) + + try: + config = platform_schema_modern(component_config) + if schema_class_mapping is not None: + entity_class = schema_class_mapping[config[CONF_SCHEMA]] + if TYPE_CHECKING: + assert entity_class is not None + subentry_entities.append(entity_class(hass, config, entry, None)) + except probatio.Invalid as exc: + _LOGGER.error( + "Schema violation occurred when trying to set up " + "entity from subentry %s %s %s: %s", + config_subentry_id, + subentry.title, + subentry.data, + exc, + ) + + async_add_entities(subentry_entities, config_subentry_id=config_subentry_id) + + entities: list[Entity] = [] + for yaml_config in yaml_configs: + try: + config = platform_schema_modern(yaml_config) + if schema_class_mapping is not None: + entity_class = schema_class_mapping[config[CONF_SCHEMA]] + if TYPE_CHECKING: + assert entity_class is not None + if _async_migrate_subentry( + config, yaml_config, "subentry_migration_yaml" + ): + continue + + entities.append(entity_class(hass, config, entry, None)) + except probatio.Invalid as exc: + error = str(exc) + config_file = getattr(yaml_config, "__config_file__", "?") + line = getattr(yaml_config, "__line__", "?") + issue_id = hex(hash(frozenset(yaml_config))) + yaml_config_str = yaml_dump(yaml_config) + async_create_issue( + hass, + DOMAIN, + issue_id, + issue_domain=domain, + is_fixable=False, + severity=IssueSeverity.ERROR, + learn_more_url=learn_more_url(domain), + translation_placeholders={ + "domain": domain, + "config_file": config_file, + "line": line, + "config": yaml_config_str, + "error": error, + }, + translation_key="invalid_platform_config", + ) + _LOGGER.error( + "%s for manually configured MQTT %s item, in %s, line %s Got %s", + error, + domain, + config_file, + line, + yaml_config, + ) + + async_add_entities(entities) + + # When reloading we check manual configured items against the schema + # before reloading + mqtt_data.reload_schema[domain] = platform_schema_modern + # discover manual configured MQTT items + mqtt_data.reload_handlers[domain] = _async_setup_entities + _async_setup_entities() + + +class MqttAttributesMixin(Entity): + """Mixin used for platforms that support JSON attributes and group entities.""" + + _attributes_extra_blocked: frozenset[str] = frozenset() + _attr_tpl: Callable[[ReceivePayloadType], ReceivePayloadType] | None = None + _message_callback: Callable[ + [MessageCallbackType, set[str] | None, ReceiveMessage], None + ] + _process_update_extra_state_attributes: Callable[[dict[str, Any]], None] + group: IntegrationSpecificGroup | None + + def __init__(self, config: ConfigType) -> None: + """Initialize the JSON attributes and handle group entities.""" + self._attributes_sub_state: dict[str, EntitySubscription] = {} + if CONF_GROUP in config: + self.group = IntegrationSpecificGroup(self, config[CONF_GROUP]) + self._attributes_config = config + + @override + async def async_added_to_hass(self) -> None: + """Subscribe MQTT events.""" + await super().async_added_to_hass() + self._attributes_prepare_subscribe_topics() + self._attributes_subscribe_topics() + + def attributes_prepare_discovery_update(self, config: DiscoveryInfoType) -> None: + """Handle updated discovery message.""" + if CONF_GROUP in config: + if self.group is not None: + self.group.member_unique_ids = config[CONF_GROUP] + else: + _LOGGER.info( + "Group member update received for entity %s, " + "but this entity was not initialized with the `group` option. " + "Reload the MQTT integration or restart Home Assistant to activate", + self.entity_id, + ) + + self._attributes_config = config + self._attributes_prepare_subscribe_topics() + + async def attributes_discovery_update(self, config: DiscoveryInfoType) -> None: + """Handle updated discovery message.""" + self._attributes_subscribe_topics() + + def _attributes_prepare_subscribe_topics(self) -> None: + """(Re)Subscribe to topics.""" + if template := self._attributes_config.get(CONF_JSON_ATTRS_TEMPLATE): + self._attr_tpl = MqttValueTemplate( + template, entity=self + ).async_render_with_possible_json_value + self._attributes_sub_state = async_prepare_subscribe_topics( + self.hass, + self._attributes_sub_state, + { + CONF_JSON_ATTRS_TOPIC: { + "topic": self._attributes_config.get(CONF_JSON_ATTRS_TOPIC), + "msg_callback": partial( + self._message_callback, + self._attributes_message_received, + { + "_attr_extra_state_attributes", + "_attr_location_accuracy", + "_attr_latitude", + "_attr_location_name", + "_attr_longitude", + }, + ), + "entity_id": self.entity_id, + "qos": self._attributes_config.get(CONF_QOS), + "encoding": self._attributes_config[CONF_ENCODING] or None, + "job_type": HassJobType.Callback, + } + }, + ) + + @callback + def _attributes_subscribe_topics(self) -> None: + """(Re)Subscribe to topics.""" + async_subscribe_topics_internal(self.hass, self._attributes_sub_state) + + @override + async def async_will_remove_from_hass(self) -> None: + """Unsubscribe when removed.""" + self._attributes_sub_state = async_unsubscribe_topics( + self.hass, self._attributes_sub_state + ) + await super().async_will_remove_from_hass() + + @callback + def _attributes_message_received(self, msg: ReceiveMessage) -> None: + """Update extra state attributes.""" + payload = ( + self._attr_tpl(msg.payload) if self._attr_tpl is not None else msg.payload + ) + try: + json_dict = json_loads(payload) if isinstance(payload, str) else None + except ValueError: + _LOGGER.warning("Erroneous JSON: %s", payload) + else: + if isinstance(json_dict, dict): + filtered_dict: dict[str, Any] = { + k: v + for k, v in json_dict.items() + if k not in MQTT_ATTRIBUTES_BLOCKED + and k not in self._attributes_extra_blocked + } + if hasattr(self, "_process_update_extra_state_attributes"): + self._process_update_extra_state_attributes(filtered_dict) + else: + self._attr_extra_state_attributes = filtered_dict + + else: + _LOGGER.warning("JSON result was not a dictionary") + + +class MqttAvailabilityMixin(Entity): + """Mixin used for platforms that report availability.""" + + _message_callback: Callable[ + [MessageCallbackType, set[str] | None, ReceiveMessage], None + ] + + def __init__(self, config: ConfigType) -> None: + """Initialize the availability mixin.""" + self._availability_sub_state: dict[str, EntitySubscription] = {} + self._available: dict[str, str | bool] = {} + self._available_latest: bool = False + self._availability_setup_from_config(config) + + @override + async def async_added_to_hass(self) -> None: + """Subscribe MQTT events.""" + await super().async_added_to_hass() + self._availability_prepare_subscribe_topics() + self._availability_subscribe_topics() + self.async_on_remove( + async_dispatcher_connect( + self.hass, + MQTT_CONNECTION_STATE, + self.async_mqtt_connection_state_changed, + ) + ) + + def availability_prepare_discovery_update(self, config: DiscoveryInfoType) -> None: + """Handle updated discovery message.""" + self._availability_setup_from_config(config) + self._availability_prepare_subscribe_topics() + + async def availability_discovery_update(self, config: DiscoveryInfoType) -> None: + """Handle updated discovery message.""" + self._availability_subscribe_topics() + + def _availability_setup_from_config(self, config: ConfigType) -> None: + """(Re)Setup.""" + self._avail_topics: dict[str, dict[str, Any]] = {} + if CONF_AVAILABILITY_TOPIC in config: + self._avail_topics[config[CONF_AVAILABILITY_TOPIC]] = { + CONF_PAYLOAD_AVAILABLE: config[CONF_PAYLOAD_AVAILABLE], + CONF_PAYLOAD_NOT_AVAILABLE: config[CONF_PAYLOAD_NOT_AVAILABLE], + CONF_AVAILABILITY_TEMPLATE: config.get(CONF_AVAILABILITY_TEMPLATE), + } + + if CONF_AVAILABILITY in config: + avail: dict[str, Any] + for avail in config[CONF_AVAILABILITY]: + self._avail_topics[avail[CONF_TOPIC]] = { + CONF_PAYLOAD_AVAILABLE: avail[CONF_PAYLOAD_AVAILABLE], + CONF_PAYLOAD_NOT_AVAILABLE: avail[CONF_PAYLOAD_NOT_AVAILABLE], + CONF_AVAILABILITY_TEMPLATE: avail.get(CONF_VALUE_TEMPLATE), + } + + for avail_topic_conf in self._avail_topics.values(): + if template := avail_topic_conf[CONF_AVAILABILITY_TEMPLATE]: + avail_topic_conf[CONF_AVAILABILITY_TEMPLATE] = MqttValueTemplate( + template, entity=self + ).async_render_with_possible_json_value + + self._avail_config = config + + def _availability_prepare_subscribe_topics(self) -> None: + """(Re)Subscribe to topics.""" + self._available = { + topic: (self._available.get(topic, False)) for topic in self._avail_topics + } + topics: dict[str, dict[str, Any]] = { + f"availability_{topic}": { + "topic": topic, + "msg_callback": partial( + self._message_callback, + self._availability_message_received, + {"available"}, + ), + "entity_id": self.entity_id, + "qos": self._avail_config[CONF_QOS], + "encoding": self._avail_config[CONF_ENCODING] or None, + "job_type": HassJobType.Callback, + } + for topic in self._avail_topics + } + + self._availability_sub_state = async_prepare_subscribe_topics( + self.hass, + self._availability_sub_state, + topics, + ) + + @callback + def _availability_message_received(self, msg: ReceiveMessage) -> None: + """Handle a new received MQTT availability message.""" + topic = msg.topic + avail_topic = self._avail_topics[topic] + template = avail_topic[CONF_AVAILABILITY_TEMPLATE] + payload = template(msg.payload) if template else msg.payload + + if payload == avail_topic[CONF_PAYLOAD_AVAILABLE]: + self._available[topic] = True + self._available_latest = True + elif payload == avail_topic[CONF_PAYLOAD_NOT_AVAILABLE]: + self._available[topic] = False + self._available_latest = False + + @callback + def _availability_subscribe_topics(self) -> None: + """(Re)Subscribe to topics.""" + async_subscribe_topics_internal(self.hass, self._availability_sub_state) + + @callback + def async_mqtt_connection_state_changed(self, state: bool) -> None: + """Update state on connection/disconnection to MQTT broker.""" + if not self.hass.is_stopping: + self.async_write_ha_state() + + @override + async def async_will_remove_from_hass(self) -> None: + """Unsubscribe when removed.""" + self._availability_sub_state = async_unsubscribe_topics( + self.hass, self._availability_sub_state + ) + await super().async_will_remove_from_hass() + + @property + @override + def available(self) -> bool: + """Return if the device is available.""" + mqtt_data = self.hass.data[DATA_MQTT] + client = mqtt_data.client + if not client.connected and not self.hass.is_stopping: + return False + if not self._avail_topics: + return True + if self._avail_config[CONF_AVAILABILITY_MODE] == AVAILABILITY_ALL: + return all(self._available.values()) + if self._avail_config[CONF_AVAILABILITY_MODE] == AVAILABILITY_ANY: + return any(self._available.values()) + return self._available_latest + + +def get_discovery_hash(discovery_data: DiscoveryInfoType) -> tuple[str, str]: + """Get the discovery hash from the discovery data.""" + discovery_hash: tuple[str, str] = discovery_data[ATTR_DISCOVERY_HASH] + return discovery_hash + + +def send_discovery_done(hass: HomeAssistant, discovery_data: DiscoveryInfoType) -> None: + """Acknowledge a discovery message has been handled.""" + discovery_hash = get_discovery_hash(discovery_data) + async_dispatcher_send(hass, MQTT_DISCOVERY_DONE.format(*discovery_hash), None) + + +def stop_discovery_updates( + hass: HomeAssistant, + discovery_data: DiscoveryInfoType, + remove_discovery_updated: Callable[[], None] | None = None, +) -> None: + """Stop discovery updates of being sent.""" + if remove_discovery_updated: + remove_discovery_updated() + remove_discovery_updated = None + discovery_hash = get_discovery_hash(discovery_data) + clear_discovery_hash(hass, discovery_hash) + + +async def async_remove_discovery_payload( + hass: HomeAssistant, discovery_data: DiscoveryInfoType +) -> None: + """Clear retained discovery payload. + + Remove discovery topic in broker to avoid rediscovery + after a restart of Home Assistant. + """ + discovery_topic = discovery_data[ATTR_DISCOVERY_TOPIC] + await async_publish(hass, discovery_topic, None, retain=True) + + +async def async_clear_discovery_topic_if_entity_removed( + hass: HomeAssistant, + discovery_data: DiscoveryInfoType, + event: Event[er.EventEntityRegistryUpdatedData], +) -> None: + """Clear the discovery topic if the entity is removed.""" + if event.data["action"] == "remove": + # publish empty payload to config topic to avoid re-adding + await async_remove_discovery_payload(hass, discovery_data) + + +class MqttDiscoveryDeviceUpdateMixin(ABC): + """Add support for auto discovery for platforms without an entity.""" + + def __init__( + self, + hass: HomeAssistant, + discovery_data: DiscoveryInfoType, + device_id: str | None, + config_entry: ConfigEntry, + log_name: str, + ) -> None: + """Initialize the update service.""" + + self.hass = hass + self.log_name = log_name + + self._discovery_data = discovery_data + self._device_id = device_id + self._config_entry = config_entry + self._config_entry_id = config_entry.entry_id + self._skip_device_removal: bool = False + self._migrate_discovery: str | None = None + + discovery_hash = get_discovery_hash(discovery_data) + self._remove_discovery_updated = async_dispatcher_connect( + hass, + MQTT_DISCOVERY_UPDATED.format(*discovery_hash), + self.async_discovery_update, + ) + # Tear down before the client disconnects, so subscriptions are not restored + hass.data[DATA_MQTT].reload_dispatchers.append(self._entry_unload) + if device_id is not None: + self._remove_device_updated = async_track_device_registry_updated_event( + hass, device_id, self._async_device_removed + ) + _LOGGER.debug( + "%s %s has been initialized", + self.log_name, + discovery_hash, + ) + + @callback + def _entry_unload(self, *_: Any) -> None: + """Handle cleanup when the config entry is unloaded.""" + stop_discovery_updates( + self.hass, self._discovery_data, self._remove_discovery_updated + ) + self._config_entry.async_create_task(self.hass, self.async_tear_down()) + + async def async_discovery_update( + self, + discovery_payload: MQTTDiscoveryPayload, + ) -> None: + """Handle discovery update.""" + discovery_hash = get_discovery_hash(self._discovery_data) + # Start discovery migration or rollback if migrate_discovery flag is set + # and the discovery topic is valid and not yet migrating + if ( + discovery_payload.migrate_discovery + and self._migrate_discovery is None + and self._discovery_data[ATTR_DISCOVERY_TOPIC] + == discovery_payload.discovery_data[ATTR_DISCOVERY_TOPIC] + ): + self._migrate_discovery = self._discovery_data[ATTR_DISCOVERY_TOPIC] + discovery_hash = self._discovery_data[ATTR_DISCOVERY_HASH] + origin_info = get_origin_log_string( + self._discovery_data[ATTR_DISCOVERY_PAYLOAD], include_url=False + ) + action = "Rollback" if discovery_payload.device_discovery else "Migration" + schema_type = "platform" if discovery_payload.device_discovery else "device" + _LOGGER.info( + "%s to MQTT %s discovery schema started for %s '%s'" + "%s on topic %s. To complete %s, publish a %s discovery " + "message with %s '%s'. After completed %s, " + "publish an empty (retained) payload to %s", + action, + schema_type, + discovery_hash[0], + discovery_hash[1], + origin_info, + self._migrate_discovery, + action.lower(), + schema_type, + discovery_hash[0], + discovery_hash[1], + action.lower(), + self._migrate_discovery, + ) + + # Cleanup platform resources + await self.async_tear_down() + # Unregister and clean discovery + stop_discovery_updates( + self.hass, self._discovery_data, self._remove_discovery_updated + ) + send_discovery_done(self.hass, self._discovery_data) + return + + _LOGGER.debug( + "Got update for %s with hash: %s '%s'", + self.log_name, + discovery_hash, + discovery_payload, + ) + new_discovery_topic = discovery_payload.discovery_data[ATTR_DISCOVERY_TOPIC] + + # Abort early if an update is not received via the registered discovery topic. + # This can happen if a device and single component discovery payload + # share the same discovery ID. + if self._discovery_data[ATTR_DISCOVERY_TOPIC] != new_discovery_topic: + # Prevent illegal updates + old_origin_info = get_origin_log_string( + self._discovery_data[ATTR_DISCOVERY_PAYLOAD], include_url=False + ) + new_origin_info = get_origin_log_string( + discovery_payload.discovery_data[ATTR_DISCOVERY_PAYLOAD], + include_url=False, + ) + new_origin_support_url = get_origin_support_url( + discovery_payload.discovery_data[ATTR_DISCOVERY_PAYLOAD] + ) + if new_origin_support_url: + get_support = f"for support visit {new_origin_support_url}" + else: + get_support = ( + "for documentation on migration to device schema or rollback to " + "discovery schema, visit https://www.home-assistant.io/integrations/" + "mqtt/#migration-from-single-component-to-device-based-discovery" + ) + _LOGGER.warning( + "Received a conflicting MQTT discovery message for %s '%s' which was " + "previously discovered on topic %s%s; the conflicting discovery " + "message was received on topic %s%s; %s", + discovery_hash[0], + discovery_hash[1], + self._discovery_data[ATTR_DISCOVERY_TOPIC], + old_origin_info, + new_discovery_topic, + new_origin_info, + get_support, + ) + send_discovery_done(self.hass, self._discovery_data) + return + + if ( + discovery_payload + and discovery_payload != self._discovery_data[ATTR_DISCOVERY_PAYLOAD] + ): + _LOGGER.debug( + "Updating %s with hash %s", + self.log_name, + discovery_hash, + ) + try: + await self.async_update(discovery_payload) + finally: + send_discovery_done(self.hass, self._discovery_data) + self._discovery_data[ATTR_DISCOVERY_PAYLOAD] = discovery_payload + elif not discovery_payload: + # Unregister and clean up the current discovery instance + stop_discovery_updates( + self.hass, self._discovery_data, self._remove_discovery_updated + ) + await self._async_tear_down() + send_discovery_done(self.hass, self._discovery_data) + _LOGGER.debug( + "%s %s has been removed", + self.log_name, + discovery_hash, + ) + else: + # Normal update without change + send_discovery_done(self.hass, self._discovery_data) + _LOGGER.debug( + "%s %s no changes", + self.log_name, + discovery_hash, + ) + return + + async def _async_device_removed( + self, event: Event[EventDeviceRegistryUpdatedData] + ) -> None: + """Handle the manual removal of a device.""" + if self._skip_device_removal or not async_removed_from_device(event): + return + # Prevent a second cleanup round after the device is removed + self._remove_device_updated() + self._skip_device_removal = True + # Unregister and clean up and publish an empty payload + # so the service is not rediscovered after a restart + stop_discovery_updates( + self.hass, self._discovery_data, self._remove_discovery_updated + ) + await self._async_tear_down() + await async_remove_discovery_payload(self.hass, self._discovery_data) + + async def _async_tear_down(self) -> None: + """Handle the cleanup of the discovery service.""" + # Cleanup platform resources + await self.async_tear_down() + # remove the service for auto discovery updates and clean up the device registry + if not self._skip_device_removal: + # Prevent a second cleanup round after the device is removed + self._skip_device_removal = True + await async_cleanup_device_registry( + self.hass, self._device_id, self._config_entry_id + ) + + @abstractmethod + async def async_update(self, discovery_data: MQTTDiscoveryPayload) -> None: + """Handle the update of platform specific parts, extend to the platform.""" + + @abstractmethod + async def async_tear_down(self) -> None: + """Handle the cleanup of platform specific parts, extend to the platform.""" + + +class MqttDiscoveryUpdateMixin(Entity): + """Mixin used to handle updated discovery message for entity based platforms.""" + + def __init__( + self, + hass: HomeAssistant, + discovery_data: DiscoveryInfoType | None, + discovery_update: Callable[[MQTTDiscoveryPayload], Coroutine[Any, Any, None]] + | None = None, + ) -> None: + """Initialize the discovery update mixin.""" + self._discovery_data = discovery_data + self._discovery_update = discovery_update + self._remove_discovery_updated: Callable[[], None] | None = None + self._removed_from_hass = False + if discovery_data is None: + return + mqtt_data = hass.data[DATA_MQTT] + self._registry_hooks = mqtt_data.discovery_registry_hooks + discovery_hash: tuple[str, str] = discovery_data[ATTR_DISCOVERY_HASH] + self._migrate_discovery: str | None = None + if discovery_hash in self._registry_hooks: + self._registry_hooks.pop(discovery_hash)() + + @override + async def async_added_to_hass(self) -> None: + """Subscribe to discovery updates.""" + await super().async_added_to_hass() + self._removed_from_hass = False + if not self._discovery_data: + return + discovery_hash: tuple[str, str] = self._discovery_data[ATTR_DISCOVERY_HASH] + debug_info.add_entity_discovery_data( + self.hass, self._discovery_data, self.entity_id + ) + # Set in case the entity has been removed and is re-added, + # for example when changing entity_id + set_discovery_hash(self.hass, discovery_hash) + self._remove_discovery_updated = async_dispatcher_connect( + self.hass, + MQTT_DISCOVERY_UPDATED.format(*discovery_hash), + self._async_discovery_callback, + ) + + async def _async_remove_state_and_registry_entry( + self: MqttDiscoveryUpdateMixin, + ) -> None: + """Remove entity's state and entity registry entry. + + Remove entity from entity registry if it is registered, + this also removes the state. If the entity is not in the entity + registry, just remove the state. + """ + entity_registry = er.async_get(self.hass) + if entity_entry := entity_registry.async_get(self.entity_id): + entity_registry.async_remove(self.entity_id) + await async_cleanup_device_registry( + self.hass, entity_entry.device_id, entity_entry.config_entry_id + ) + else: + await self.async_remove(force_remove=True) + + async def _async_process_discovery_update( + self, + payload: MQTTDiscoveryPayload, + discovery_update: Callable[[MQTTDiscoveryPayload], Coroutine[Any, Any, None]], + discovery_data: DiscoveryInfoType, + ) -> None: + """Process discovery update.""" + try: + await discovery_update(payload) + finally: + send_discovery_done(self.hass, discovery_data) + + async def _async_process_discovery_update_and_remove(self) -> None: + """Process discovery update and remove entity.""" + if TYPE_CHECKING: + assert self._discovery_data + self._cleanup_discovery_on_remove() + if self._migrate_discovery is None: + # Unload and cleanup registry + await self._async_remove_state_and_registry_entry() + else: + # Only unload the entity + await self.async_remove(force_remove=True) + send_discovery_done(self.hass, self._discovery_data) + + @callback + def _async_discovery_callback(self, payload: MQTTDiscoveryPayload) -> None: + """Handle discovery update. + + If the payload has changed we will create a task to + do the discovery update. + + As this callback can fire when nothing has changed, this + is a normal function to avoid task creation until it is needed. + """ + if TYPE_CHECKING: + assert self._discovery_data + discovery_hash = get_discovery_hash(self._discovery_data) + # Start discovery migration or rollback if migrate_discovery flag is set + # and the discovery topic is valid and not yet migrating + if ( + payload.migrate_discovery + and self._migrate_discovery is None + and self._discovery_data[ATTR_DISCOVERY_TOPIC] + == payload.discovery_data[ATTR_DISCOVERY_TOPIC] + ): + if self.unique_id is None or self.device_info is None: + _LOGGER.error( + "Discovery migration is not possible for " + "for entity %s on topic %s. A unique_id " + "and device context is required, got unique_id: %s, device: %s", + self.entity_id, + self._discovery_data[ATTR_DISCOVERY_TOPIC], + self.unique_id, + self.device_info, + ) + send_discovery_done(self.hass, self._discovery_data) + return + + self._migrate_discovery = self._discovery_data[ATTR_DISCOVERY_TOPIC] + discovery_hash = self._discovery_data[ATTR_DISCOVERY_HASH] + origin_info = get_origin_log_string( + self._discovery_data[ATTR_DISCOVERY_PAYLOAD], include_url=False + ) + action = "Rollback" if payload.device_discovery else "Migration" + schema_type = "platform" if payload.device_discovery else "device" + _LOGGER.info( + "%s to MQTT %s discovery schema started for entity %s" + "%s on topic %s. To complete %s, publish a %s discovery " + "message with %s entity '%s'. After completed %s, " + "publish an empty (retained) payload to %s", + action, + schema_type, + self.entity_id, + origin_info, + self._migrate_discovery, + action.lower(), + schema_type, + discovery_hash[0], + discovery_hash[1], + action.lower(), + self._migrate_discovery, + ) + old_payload = self._discovery_data[ATTR_DISCOVERY_PAYLOAD] + _LOGGER.debug( + "Got update for entity with hash: %s '%s'", + discovery_hash, + payload, + ) + new_discovery_topic = payload.discovery_data[ATTR_DISCOVERY_TOPIC] + # Abort early if an update is not received via the registered discovery topic. + # This can happen if a device and single component discovery payload + # share the same discovery ID. + if self._discovery_data[ATTR_DISCOVERY_TOPIC] != new_discovery_topic: + # Prevent illegal updates + old_origin_info = get_origin_log_string( + self._discovery_data[ATTR_DISCOVERY_PAYLOAD], include_url=False + ) + new_origin_info = get_origin_log_string( + payload.discovery_data[ATTR_DISCOVERY_PAYLOAD], include_url=False + ) + new_origin_support_url = get_origin_support_url( + payload.discovery_data[ATTR_DISCOVERY_PAYLOAD] + ) + if new_origin_support_url: + get_support = f"for support visit {new_origin_support_url}" + else: + get_support = ( + "for documentation on migration to device schema or rollback to " + "discovery schema, visit https://www.home-assistant.io/integrations/" + "mqtt/#migration-from-single-component-to-device-based-discovery" + ) + _LOGGER.warning( + "Received a conflicting MQTT discovery message for entity %s; the " + "entity was previously discovered on topic %s%s; the conflicting " + "discovery message was received on topic %s%s; %s", + self.entity_id, + self._discovery_data[ATTR_DISCOVERY_TOPIC], + old_origin_info, + new_discovery_topic, + new_origin_info, + get_support, + ) + send_discovery_done(self.hass, self._discovery_data) + return + + debug_info.update_entity_discovery_data(self.hass, payload, self.entity_id) + if not payload: + # Empty payload: Remove component + if self._migrate_discovery is None: + _LOGGER.info("Removing component: %s", self.entity_id) + else: + _LOGGER.info("Unloading component: %s", self.entity_id) + self.hass.async_create_task( + self._async_process_discovery_update_and_remove() + ) + elif self._discovery_update: + if old_payload != payload: + # Non-empty, changed payload: Notify component + _LOGGER.info("Updating component: %s", self.entity_id) + self.hass.async_create_task( + self._async_process_discovery_update( + payload, self._discovery_update, self._discovery_data + ) + ) + else: + # Non-empty, unchanged payload: Ignore to avoid changing states + _LOGGER.debug("Ignoring unchanged update for: %s", self.entity_id) + send_discovery_done(self.hass, self._discovery_data) + + @override + async def async_removed_from_registry(self) -> None: + """Clear retained discovery topic in broker.""" + if not self._removed_from_hass and self._discovery_data is not None: + # Stop subscribing to discovery updates to not trigger when we + # clear the discovery topic + self._cleanup_discovery_on_remove() + + # Clear the discovery topic so the entity is not + # rediscovered after a restart + await async_remove_discovery_payload(self.hass, self._discovery_data) + + @final + @override + async def add_to_platform_finish(self) -> None: + """Finish adding entity to platform.""" + await super().add_to_platform_finish() + # Only send the discovery done after the entity is fully added + # and the state is written to the state machine. + if self._discovery_data is not None: + send_discovery_done(self.hass, self._discovery_data) + + @callback + @override + def add_to_platform_abort(self) -> None: + """Abort adding an entity to a platform.""" + if self._discovery_data is not None: + discovery_hash: tuple[str, str] = self._discovery_data[ATTR_DISCOVERY_HASH] + if self.registry_entry is not None: + self._registry_hooks[discovery_hash] = ( + async_track_entity_registry_updated_event( + self.hass, + self.entity_id, + partial( + async_clear_discovery_topic_if_entity_removed, + self.hass, + self._discovery_data, + ), + ) + ) + stop_discovery_updates(self.hass, self._discovery_data) + send_discovery_done(self.hass, self._discovery_data) + super().add_to_platform_abort() + + @override + async def async_will_remove_from_hass(self) -> None: + """Stop listening to signal and cleanup discovery data.""" + self._cleanup_discovery_on_remove() + await super().async_will_remove_from_hass() + + def _cleanup_discovery_on_remove(self) -> None: + """Stop listening to signal and cleanup discovery data.""" + if self._discovery_data and not self._removed_from_hass: + stop_discovery_updates( + self.hass, self._discovery_data, self._remove_discovery_updated + ) + self._removed_from_hass = True + + +def device_info_from_specifications( + specifications: dict[str, Any] | None, +) -> DeviceInfo | None: + """Return a device description for device registry.""" + if not specifications: + return None + + info = DeviceInfo( + identifiers={(DOMAIN, id_) for id_ in specifications[CONF_IDENTIFIERS]}, + connections={ + (conn_[0], conn_[1]) for conn_ in specifications[CONF_CONNECTIONS] + }, + ) + + if CONF_MANUFACTURER in specifications: + info[ATTR_MANUFACTURER] = specifications[CONF_MANUFACTURER] + + if CONF_MODEL in specifications: + info[ATTR_MODEL] = specifications[CONF_MODEL] + + if CONF_MODEL_ID in specifications: + info[ATTR_MODEL_ID] = specifications[CONF_MODEL_ID] + + if CONF_NAME in specifications: + info[ATTR_NAME] = specifications[CONF_NAME] + + if CONF_HW_VERSION in specifications: + info[ATTR_HW_VERSION] = specifications[CONF_HW_VERSION] + + if CONF_SERIAL_NUMBER in specifications: + info[ATTR_SERIAL_NUMBER] = specifications[CONF_SERIAL_NUMBER] + + if CONF_SW_VERSION in specifications: + info[ATTR_SW_VERSION] = specifications[CONF_SW_VERSION] + + if CONF_SUGGESTED_AREA in specifications: + info[ATTR_SUGGESTED_AREA] = specifications[CONF_SUGGESTED_AREA] + + if CONF_CONFIGURATION_URL in specifications: + info[ATTR_CONFIGURATION_URL] = specifications[CONF_CONFIGURATION_URL] + + return info + + +def _via_device_identifier( + specifications: dict[str, Any] | None, +) -> tuple[str, str] | None: + """Return the device registry identifier of the referenced via device.""" + if not specifications or CONF_VIA_DEVICE not in specifications: + return None + return (DOMAIN, specifications[CONF_VIA_DEVICE]) + + +@callback +def ensure_via_device_exists( + hass: HomeAssistant, + specifications: dict[str, Any] | None, + config_entry: ConfigEntry, +) -> None: + """Ensure the via device is in the device registry. + + MQTT discovery can announce a child device before its via device, so the + referenced parent is stub-created here when it does not yet exist. + """ + if (identifier := _via_device_identifier(specifications)) is None: + return + + device_registry = dr.async_get(hass) + if device_registry.async_get_device_by_identifier( + identifier, config_entry.entry_id + ): + return + + _LOGGER.debug( + "Device identifier %s referenced as via_device not found in the " + "Device Registry, creating new entry", + identifier, + ) + device_registry.async_get_or_create( + config_entry_id=config_entry.entry_id, + identifiers={identifier}, + ) + + +@callback +def _resolve_via_device_id( + hass: HomeAssistant, + specifications: dict[str, Any] | None, + config_entry: ConfigEntry, +) -> str | None: + """Resolve the referenced via device to its device registry id. + + Best-effort read-only lookup: returns None when no via device is referenced + or the referenced device is not (yet) registered. It never raises, so a + missing parent cannot abort entity setup given MQTT's non-deterministic + discovery order. + """ + if (identifier := _via_device_identifier(specifications)) is None: + return None + via_device = dr.async_get(hass).async_get_device_by_identifier( + identifier, config_entry.entry_id + ) + return via_device.id if via_device else None + + +class MqttEntityDeviceInfo(Entity): + """Mixin used for mqtt platforms that support the device registry.""" + + def __init__( + self, specifications: dict[str, Any] | None, config_entry: ConfigEntry + ) -> None: + """Initialize the device mixin.""" + self._device_specifications = specifications + self._config_entry = config_entry + + def device_info_discovery_update(self, config: DiscoveryInfoType) -> None: + """Handle updated discovery message.""" + self._device_specifications = config.get(CONF_DEVICE) + device_registry = dr.async_get(self.hass) + config_entry_id = self._config_entry.entry_id + ensure_via_device_exists( + self.hass, self._device_specifications, self._config_entry + ) + device_info = self.device_info + + if device_info is not None: + device_registry.async_get_or_create( + config_entry_id=config_entry_id, **device_info + ) + + @property + @override + def device_info(self) -> DeviceInfo | None: + """Return a device description for device registry.""" + info = device_info_from_specifications(self._device_specifications) + if info is not None and ( + via_device_id := _resolve_via_device_id( + self.hass, self._device_specifications, self._config_entry + ) + ): + info["via_device_id"] = via_device_id + return info + + +class MqttEntity( + MqttAttributesMixin, + MqttAvailabilityMixin, + MqttDiscoveryUpdateMixin, + MqttEntityDeviceInfo, +): + """Representation of an MQTT entity.""" + + _attr_force_update = False + _attr_has_entity_name = True + _attr_should_poll = False + _default_name: str | None + _entity_id_format: str + _update_registry_entity_id: str | None = None + + def __init__( + self, + hass: HomeAssistant, + config: ConfigType, + config_entry: ConfigEntry, + discovery_data: DiscoveryInfoType | None, + ) -> None: + """Init the MQTT Entity.""" + self.hass = hass + self._config: ConfigType = config + self._attr_unique_id = config.get(CONF_UNIQUE_ID) + self._sub_state: dict[str, EntitySubscription] = {} + self._discovery = discovery_data is not None + self._subscriptions: dict[str, dict[str, Any]] + + # Load config + self._setup_from_config(self._config) + self._setup_common_attributes_from_config(self._config) + + # Initialize entity_id from config + self._init_entity_registry(discovery_data) + + # Initialize mixin classes + MqttAttributesMixin.__init__(self, config) + MqttAvailabilityMixin.__init__(self, config) + MqttDiscoveryUpdateMixin.__init__( + self, hass, discovery_data, self.discovery_update + ) + MqttEntityDeviceInfo.__init__(self, config.get(CONF_DEVICE), config_entry) + ensure_via_device_exists( + self.hass, self._device_specifications, self._config_entry + ) + + def _init_entity_registry(self, discovery_data: DiscoveryInfoType | None) -> None: + """Set entity_id from default_entity_id if defined in config. + + Check if the previous registry state was disabled + or is set to be disabled initially for discovered entities. + """ + object_id: str + default_entity_id: str | None + if default_entity_id := self._config.get(CONF_DEFAULT_ENTITY_ID): + _, _, object_id = default_entity_id.partition(".") + self.entity_id = async_generate_entity_id( + self._entity_id_format, object_id, None, self.hass + ) + + if self.unique_id is None: + return + # Check for previous deleted entities + entity_registry = er.async_get(self.hass) + entity_platform = self._entity_id_format.split(".")[0] + if ( + deleted_entry := entity_registry.deleted_entities.get( + (entity_platform, DOMAIN, self.unique_id) + ) + ) and deleted_entry.entity_id != self.entity_id: + # Plan to update the entity_id based on `default_entity_id` + # if a deleted entity was found + self._update_registry_entity_id = self.entity_id + if ( + reenable_condition := ( + deleted_entry + and self._config[CONF_ENABLED_BY_DEFAULT] + and deleted_entry.disabled_by is er.RegistryEntryDisabler.INTEGRATION + ) + ) or ( + deleted_entry + and self._config[CONF_VISIBLE_BY_DEFAULT] + and deleted_entry.hidden_by is not None + ): + # Enable previous deleted entity, + # if it was not disabled by the user. + # Only reset hidden by flag if it was not hidden by the user. + if ( + deleted_entry.hidden_by is er.RegistryEntryHider.USER + and self._config[CONF_VISIBLE_BY_DEFAULT] + ): + _LOGGER.info( + "Restored entity %s was configured as visible by default, " + "but was hidden by the user before, and will remain hidden", + self.entity_id, + ) + if deleted_entry.hidden_by is er.RegistryEntryHider.USER: + hidden_by: er.RegistryEntryHider | None = er.RegistryEntryHider.USER + else: + hidden_by = ( + None + if self._config[CONF_VISIBLE_BY_DEFAULT] + else er.RegistryEntryHider.INTEGRATION + ) + recreated_entry = entity_registry.async_get_or_create( + entity_platform, DOMAIN, self.unique_id + ) + entity_registry.async_update_entity( + recreated_entry.entity_id, + disabled_by=None if reenable_condition else UNDEFINED, + hidden_by=hidden_by, + ) + + if discovery_data is None: + return + + # Allow a disabled entity and device registry + # to be cleaned up via MQTT discovery + if existing_entity_id := entity_registry.async_get_entity_id( + entity_platform, DOMAIN, self.unique_id + ): + existing_entry = entity_registry.async_get(existing_entity_id) + + # Store discovery hash for new entities that are initial disabled + # or for entries that are disabled in the registry, + # so they can be removed with an empty discovery payload + if ( + existing_entity_id is None + or (existing_entry and existing_entry.disabled_by is not None) + ) and not self._config[CONF_ENABLED_BY_DEFAULT]: + mqtt_data = self.hass.data[DATA_MQTT] + mqtt_data.discovery_discovered_and_disabled[ + discovery_data[ATTR_DISCOVERY_HASH] + ] = (entity_platform, DOMAIN, self.unique_id) + + @final + @override + async def async_added_to_hass(self) -> None: + """Subscribe to MQTT events.""" + if self._update_registry_entity_id is not None: + entity_registry = er.async_get(self.hass) + entity_registry.async_update_entity( + self.entity_id, new_entity_id=self._update_registry_entity_id + ) + self._update_registry_entity_id = None + + await super().async_added_to_hass() + await self._async_finish_update_config() + self._subscriptions = {} + self._prepare_subscribe_topics() + if self._subscriptions: + self._sub_state = subscription.async_prepare_subscribe_topics( + self.hass, + self._sub_state, + self._subscriptions, + ) + await self._subscribe_topics() + await self.mqtt_async_added_to_hass() + + async def mqtt_async_added_to_hass(self) -> None: + """Call before the discovery message is acknowledged. + + To be extended by subclasses. + """ + + async def _async_finish_update_config(self) -> None: + """Called after added to hass and after discovery update. + + To be extended by subclasses. + """ + + async def discovery_update(self, discovery_payload: MQTTDiscoveryPayload) -> None: + """Handle updated discovery message.""" + try: + config: DiscoveryInfoType = self.config_schema()(discovery_payload) + except probatio.Invalid as err: + async_handle_schema_error(discovery_payload, err) + return + self._config = config + self._setup_from_config(self._config) + self._setup_common_attributes_from_config(self._config) + await self._async_finish_update_config() + + # Prepare MQTT subscriptions + self.attributes_prepare_discovery_update(config) + self.availability_prepare_discovery_update(config) + self.device_info_discovery_update(config) + self._subscriptions = {} + self._prepare_subscribe_topics() + if self._subscriptions: + self._sub_state = subscription.async_prepare_subscribe_topics( + self.hass, + self._sub_state, + self._subscriptions, + ) + + # Finalize MQTT subscriptions + await self.attributes_discovery_update(config) + await self.availability_discovery_update(config) + await self._subscribe_topics() + self.async_write_ha_state() + + @override + async def async_will_remove_from_hass(self) -> None: + """Unsubscribe when removed.""" + self._sub_state = subscription.async_unsubscribe_topics( + self.hass, self._sub_state + ) + await super().async_will_remove_from_hass() + debug_info.remove_entity_data(self.hass, self.entity_id) + + async def async_publish_with_config( + self, topic: str, payload: PublishPayloadType + ) -> None: + """Publish payload to a topic using config.""" + kwargs: dict[str, Any] = { + key: value for key, value in self._config.items() if key in PUBLISH_KWARGS + } + qos: int = self._config[CONF_QOS] + retain: bool = self._config[CONF_RETAIN] + encoding: str = self._config[CONF_ENCODING] + log_message( + self.hass, self.entity_id, topic, payload, qos, retain, encoding, **kwargs + ) + await async_publish(self.hass, topic, payload, qos, retain, encoding, **kwargs) + + @staticmethod + @abstractmethod + def config_schema() -> VolSchemaType: + """Return the config schema.""" + + def _set_entity_name(self, config: ConfigType) -> None: + """Help setting the entity name if needed.""" + entity_name: str | UndefinedType | None = config.get(CONF_NAME, UNDEFINED) + # Only set _attr_name if it is needed + if entity_name is not UNDEFINED: + self._attr_name = entity_name + elif not self._default_to_device_class_name(): + # Assign the default name + self._attr_name = self._default_name + elif hasattr(self, "_attr_name"): + # An entity name was not set in the config + # don't set the name attribute and derive + # the name from the device_class + delattr(self, "_attr_name") + if CONF_DEVICE in config and CONF_NAME not in config[CONF_DEVICE]: + _LOGGER.info( + "MQTT device information always needs to include a name, got %s, " + "if device information is shared between multiple entities, the device " + "name must be included in each entity's device configuration", + config, + ) + + def _setup_common_attributes_from_config(self, config: ConfigType) -> None: + """(Re)Setup the common attributes for the entity.""" + self._attr_entity_category = config.get(CONF_ENTITY_CATEGORY) + self._attr_entity_registry_enabled_default = bool( + config.get(CONF_ENABLED_BY_DEFAULT, True) + ) + self._attr_entity_registry_visible_default = bool( + config.get(CONF_VISIBLE_BY_DEFAULT, True) + ) + self._attr_icon = config.get(CONF_ICON) + self._attr_entity_picture = config.get(CONF_ENTITY_PICTURE) + # Set the entity name if needed + self._set_entity_name(config) + + def _setup_from_config(self, config: ConfigType) -> None: + """(Re)Setup the entity.""" + + @abstractmethod + @callback + def _prepare_subscribe_topics(self) -> None: + """(Re)Subscribe to topics.""" + + @abstractmethod + async def _subscribe_topics(self) -> None: + """(Re)Subscribe to topics.""" + + @callback + def _attrs_have_changed( + self, attrs_snapshot: tuple[tuple[str, Any | UndefinedType], ...] + ) -> bool: + """Return True if attributes on entity changed or if update is forced.""" + if self._attr_force_update: + return True + for attribute, last_value in attrs_snapshot: + if getattr(self, attribute, UNDEFINED) != last_value: + return True + return False + + @callback + @override + def _message_callback( + self, + msg_callback: MessageCallbackType, + attributes: set[str] | None, + msg: ReceiveMessage, + ) -> None: + """Process the message callback.""" + if attributes is not None: + attrs_snapshot: tuple[tuple[str, Any | UndefinedType], ...] = tuple( + (attribute, getattr(self, attribute, UNDEFINED)) + for attribute in attributes + ) + mqtt_data = self.hass.data[DATA_MQTT] + messages = mqtt_data.debug_info_entities[self.entity_id]["subscriptions"][ + msg.subscribed_topic + ]["messages"] + if msg not in messages: + messages.append(msg) + + try: + msg_callback(msg) + except MqttValueTemplateException as exc: + _LOGGER.warning(exc) + return + + if attributes is not None and self._attrs_have_changed(attrs_snapshot): + mqtt_data.state_write_requests.write_state_request(self) + + def add_subscription( + self, + state_topic_config_key: str, + msg_callback: Callable[[ReceiveMessage], None], + tracked_attributes: set[str] | None, + disable_encoding: bool = False, + ) -> bool: + """Add a subscription.""" + qos: int = self._config[CONF_QOS] + encoding: str | None = None + if not disable_encoding: + encoding = self._config[CONF_ENCODING] or None + if ( + state_topic_config_key in self._config + and self._config[state_topic_config_key] is not None + ): + self._subscriptions[state_topic_config_key] = { + "topic": self._config[state_topic_config_key], + "msg_callback": partial( + self._message_callback, msg_callback, tracked_attributes + ), + "entity_id": self.entity_id, + "qos": qos, + "encoding": encoding, + "job_type": HassJobType.Callback, + } + return True + return False + + +def update_device( + hass: HomeAssistant, + config_entry: ConfigEntry, + config: ConfigType, +) -> str | None: + """Update device registry.""" + if CONF_DEVICE not in config: + return None + + device: DeviceEntry | None = None + device_registry = dr.async_get(hass) + config_entry_id = config_entry.entry_id + specifications = config[CONF_DEVICE] + + ensure_via_device_exists(hass, specifications, config_entry) + device_info = device_info_from_specifications(specifications) + + if config_entry_id is not None and device_info is not None: + if via_device_id := _resolve_via_device_id(hass, specifications, config_entry): + device_info["via_device_id"] = via_device_id + device = device_registry.async_get_or_create( + config_entry_id=config_entry_id, **device_info + ) + + return device.id if device else None + + +@callback +def async_removed_from_device( + event: Event[EventDeviceRegistryUpdatedData], +) -> bool: + """Check if the passed event indicates MQTT was removed from a device. + + A device is associated with a single config entry, so MQTT is removed from a + device only when the device itself is removed. + """ + return event.data["action"] == "remove" diff --git a/custom_components/vmqtt/event.py b/custom_components/vmqtt/event.py new file mode 100644 index 0000000..d0649f1 --- /dev/null +++ b/custom_components/vmqtt/event.py @@ -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) diff --git a/custom_components/vmqtt/fan.py b/custom_components/vmqtt/fan.py new file mode 100644 index 0000000..ee44aa4 --- /dev/null +++ b/custom_components/vmqtt/fan.py @@ -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() diff --git a/custom_components/vmqtt/humidifier.py b/custom_components/vmqtt/humidifier.py new file mode 100644 index 0000000..f7ccddb --- /dev/null +++ b/custom_components/vmqtt/humidifier.py @@ -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() diff --git a/custom_components/vmqtt/icons.json b/custom_components/vmqtt/icons.json new file mode 100644 index 0000000..513c491 --- /dev/null +++ b/custom_components/vmqtt/icons.json @@ -0,0 +1,18 @@ +{ + "services": { + "dump": { + "service": "mdi:database-export" + }, + "publish": { + "service": "mdi:publish" + }, + "reload": { + "service": "mdi:reload" + } + }, + "triggers": { + "_": { + "trigger": "mdi:swap-horizontal" + } + } +} diff --git a/custom_components/vmqtt/image.py b/custom_components/vmqtt/image.py new file mode 100644 index 0000000..f3e5315 --- /dev/null +++ b/custom_components/vmqtt/image.py @@ -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() diff --git a/custom_components/vmqtt/infrared.py b/custom_components/vmqtt/infrared.py new file mode 100644 index 0000000..b912bfa --- /dev/null +++ b/custom_components/vmqtt/infrared.py @@ -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) diff --git a/custom_components/vmqtt/lawn_mower.py b/custom_components/vmqtt/lawn_mower.py new file mode 100644 index 0000000..141028c --- /dev/null +++ b/custom_components/vmqtt/lawn_mower.py @@ -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) diff --git a/custom_components/vmqtt/light/__init__.py b/custom_components/vmqtt/light/__init__.py new file mode 100644 index 0000000..39b3e08 --- /dev/null +++ b/custom_components/vmqtt/light/__init__.py @@ -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}, + ) diff --git a/custom_components/vmqtt/light/schema.py b/custom_components/vmqtt/light/schema.py new file mode 100644 index 0000000..7432742 --- /dev/null +++ b/custom_components/vmqtt/light/schema.py @@ -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") + ) + } +) diff --git a/custom_components/vmqtt/light/schema_basic.py b/custom_components/vmqtt/light/schema_basic.py new file mode 100644 index 0000000..6a138f9 --- /dev/null +++ b/custom_components/vmqtt/light/schema_basic.py @@ -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() diff --git a/custom_components/vmqtt/light/schema_json.py b/custom_components/vmqtt/light/schema_json.py new file mode 100644 index 0000000..7ff458f --- /dev/null +++ b/custom_components/vmqtt/light/schema_json.py @@ -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() diff --git a/custom_components/vmqtt/light/schema_template.py b/custom_components/vmqtt/light/schema_template.py new file mode 100644 index 0000000..acd6d7d --- /dev/null +++ b/custom_components/vmqtt/light/schema_template.py @@ -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() diff --git a/custom_components/vmqtt/lock.py b/custom_components/vmqtt/lock.py new file mode 100644 index 0000000..5814b4f --- /dev/null +++ b/custom_components/vmqtt/lock.py @@ -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() diff --git a/custom_components/vmqtt/manifest.json b/custom_components/vmqtt/manifest.json new file mode 100644 index 0000000..d09f29f --- /dev/null +++ b/custom_components/vmqtt/manifest.json @@ -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 +} diff --git a/custom_components/vmqtt/models.py b/custom_components/vmqtt/models.py new file mode 100644 index 0000000..b7266c8 --- /dev/null +++ b/custom_components/vmqtt/models.py @@ -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") diff --git a/custom_components/vmqtt/notify.py b/custom_components/vmqtt/notify.py new file mode 100644 index 0000000..1a51c26 --- /dev/null +++ b/custom_components/vmqtt/notify.py @@ -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) diff --git a/custom_components/vmqtt/number.py b/custom_components/vmqtt/number.py new file mode 100644 index 0000000..9edcb99 --- /dev/null +++ b/custom_components/vmqtt/number.py @@ -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) diff --git a/custom_components/vmqtt/quality_scale.yaml b/custom_components/vmqtt/quality_scale.yaml new file mode 100644 index 0000000..cb62d49 --- /dev/null +++ b/custom_components/vmqtt/quality_scale.yaml @@ -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). diff --git a/custom_components/vmqtt/repairs.py b/custom_components/vmqtt/repairs.py new file mode 100644 index 0000000..357b4cb --- /dev/null +++ b/custom_components/vmqtt/repairs.py @@ -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, + ) diff --git a/custom_components/vmqtt/scene.py b/custom_components/vmqtt/scene.py new file mode 100644 index 0000000..b7b53ca --- /dev/null +++ b/custom_components/vmqtt/scene.py @@ -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] + ) diff --git a/custom_components/vmqtt/schemas.py b/custom_components/vmqtt/schemas.py new file mode 100644 index 0000000..3d3743f --- /dev/null +++ b/custom_components/vmqtt/schemas.py @@ -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, + } +) diff --git a/custom_components/vmqtt/select.py b/custom_components/vmqtt/select.py new file mode 100644 index 0000000..36bc10d --- /dev/null +++ b/custom_components/vmqtt/select.py @@ -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) diff --git a/custom_components/vmqtt/sensor.py b/custom_components/vmqtt/sensor.py new file mode 100644 index 0000000..9346fb9 --- /dev/null +++ b/custom_components/vmqtt/sensor.py @@ -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 + ) diff --git a/custom_components/vmqtt/services.yaml b/custom_components/vmqtt/services.yaml new file mode 100644 index 0000000..a24c084 --- /dev/null +++ b/custom_components/vmqtt/services.yaml @@ -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: diff --git a/custom_components/vmqtt/siren.py b/custom_components/vmqtt/siren.py new file mode 100644 index 0000000..7a2d807 --- /dev/null +++ b/custom_components/vmqtt/siren.py @@ -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) + } + ) diff --git a/custom_components/vmqtt/strings.json b/custom_components/vmqtt/strings.json new file mode 100644 index 0000000..90d8982 --- /dev/null +++ b/custom_components/vmqtt/strings.json @@ -0,0 +1,1428 @@ +{ + "config": { + "abort": { + "addon_connection_failed": "Failed to connect to the {addon} app. Check the app status and try again later.", + "addon_info_failed": "Failed get info for the {addon} app.", + "addon_install_failed": "Failed to install the {addon} app.", + "addon_start_failed": "Failed to start the {addon} app.", + "already_configured": "[%key:common::config_flow::abort::already_configured_service%]" + }, + "error": { + "bad_birth": "Invalid birth topic", + "bad_certificate": "The CA certificate is invalid", + "bad_client_cert": "Invalid client certificate, ensure a valid file is supplied", + "bad_client_cert_key": "Client certificate and private key are not a valid pair", + "bad_discovery_prefix": "Invalid discovery prefix", + "bad_will": "Invalid will topic", + "bad_ws_headers": "Supply valid HTTP headers as a JSON object", + "cannot_connect": "[%key:common::config_flow::error::cannot_connect%]", + "client_key_error": "Invalid private key file or invalid password supplied", + "invalid_auth": "[%key:common::config_flow::error::invalid_auth%]", + "invalid_inclusion": "The client certificate and private key must be configured together" + }, + "step": { + "broker": { + "data": { + "broker": "Broker", + "password": "[%key:common::config_flow::data::password%]", + "port": "[%key:common::config_flow::data::port%]", + "protocol": "MQTT protocol", + "username": "[%key:common::config_flow::data::username%]" + }, + "data_description": { + "broker": "The hostname or IP address of your MQTT broker.", + "password": "The password to log in to your MQTT broker.", + "port": "The port your MQTT broker listens to. For example 1883.", + "protocol": "The MQTT protocol version that is used. Note that Home Assistant will silently change to version 5 if your broker supports it.", + "username": "The username to log in to your MQTT broker." + }, + "description": "Please enter the connection information of your MQTT broker.", + "sections": { + "other_settings": { + "data": { + "certificate": "Upload custom CA certificate file", + "client_cert": "Upload client certificate file", + "client_id": "Client ID (leave empty for a randomly generated one)", + "client_key": "Upload private key file", + "client_key_password": "[%key:common::config_flow::data::password%]", + "keepalive": "The time between sending keep alive messages", + "set_ca_cert": "Broker certificate validation", + "set_client_cert": "Use a client certificate", + "tls_insecure": "Ignore broker certificate validation", + "transport": "MQTT transport", + "ws_headers": "WebSocket headers in JSON format", + "ws_path": "WebSocket path" + }, + "data_description": { + "certificate": "The custom CA certificate file to validate your MQTT broker's certificate.", + "client_cert": "The client certificate to authenticate against your MQTT broker.", + "client_id": "The unique ID to identify the Home Assistant MQTT API as MQTT client. It is recommended to leave this option blank.", + "client_key": "The private key file that belongs to your client certificate.", + "client_key_password": "The password for the private key file (if set).", + "keepalive": "A value less than 90 seconds is advised. Defaults to 60 seconds.", + "set_ca_cert": "When already set to **Custom**, a custom CA validation certificate is configured. Select **Auto** for automatic CA validation, or upload a custom CA certificate, to allow validating your MQTT broker's certificate.", + "set_client_cert": "When already selected, client certificate authentication is enabled. Upload a client certificate and key to enable.", + "tls_insecure": "Option to ignore validation of your MQTT broker's certificate.", + "transport": "The transport to be used for the connection to your MQTT broker.", + "ws_headers": "The WebSocket headers to pass through the WebSocket-based connection to your MQTT broker.", + "ws_path": "The WebSocket path to be used for the connection to your MQTT broker." + }, + "name": "Other settings" + } + } + }, + "hassio_confirm": { + "description": "Do you want to configure Home Assistant to connect to the MQTT broker provided by the {addon} app?", + "title": "MQTT broker via Home Assistant app" + }, + "install_addon": { + "title": "Installing app" + }, + "reauth_confirm": { + "data": { + "password": "[%key:common::config_flow::data::password%]", + "username": "[%key:common::config_flow::data::username%]" + }, + "data_description": { + "password": "[%key:component::mqtt::config::step::broker::data_description::password%]", + "username": "[%key:component::mqtt::config::step::broker::data_description::username%]" + }, + "description": "The MQTT broker reported an authentication error. Please confirm the broker's correct username and password.", + "title": "Re-authentication required with the MQTT broker" + }, + "start_addon": { + "title": "Starting app" + }, + "user": { + "description": "Please choose how you want to connect to the MQTT broker:", + "menu_options": { + "addon": "Use the official {addon} app.", + "broker": "Manually enter the MQTT broker connection details" + } + } + } + }, + "config_subentries": { + "device": { + "create_entry": { + "default": "MQTT device with {platform} entity \"{entity}\" was set up successfully.\n\nNote that you can reconfigure the MQTT device at any time, e.g. to add more entities." + }, + "entry_type": "MQTT device", + "error": { + "cover_get_and_set_position_must_be_set_together": "The get position and set position topic options must be set together", + "cover_get_position_template_must_be_used_with_get_position_topic": "The position value template must be used together with the position state topic", + "cover_set_position_template_must_be_used_with_set_position_topic": "The set position template must be used with the set position topic", + "cover_tilt_command_template_must_be_used_with_tilt_command_topic": "The tilt command template must be used with the tilt command topic", + "cover_tilt_status_template_must_be_used_with_tilt_status_topic": "The tilt value template must be used with the tilt status topic", + "cover_value_template_must_be_used_with_state_topic": "The value template must be used with the state topic option", + "empty_list_not_allowed": "Empty list is not allowed. Add at least one item", + "fan_preset_mode_reset_in_preset_modes_list": "Payload \"reset preset mode\" is not a valid as a preset mode", + "fan_speed_range_max_must_be_greater_than_speed_range_min": "Speed range max must be greater than speed range min", + "invalid_input": "Invalid value", + "invalid_regular_expression": "Must be a valid regular expression", + "invalid_subscribe_topic": "Invalid subscribe topic", + "invalid_supported_color_modes": "Invalid supported color modes selection", + "invalid_template": "Invalid template", + "invalid_uom": "The unit of measurement \"{unit_of_measurement}\" is not supported by the selected device class, please either remove the device class, select a device class which supports \"{unit_of_measurement}\", or pick a supported unit of measurement from the list", + "invalid_uom_for_state_class": "The unit of measurement \"{unit_of_measurement}\" is not supported by the selected state class, please either remove the state class, select a state class which supports \"{unit_of_measurement}\", or pick a supported unit of measurement from the list", + "invalid_url": "Invalid URL", + "last_reset_not_with_state_class_total": "The last reset value template option should be used with state class 'Total' only", + "max_below_min": "Max value should be greater or equal to min value", + "max_below_min_humidity": "Max humidity value should be greater than min humidity value", + "max_below_min_kelvin": "Max Kelvin value should be greater than min Kelvin value", + "max_below_min_temperature": "Max temperature value should be greater than min temperature value", + "options_device_class_enum": "The 'Options' setting must be used with the Enumeration device class. If you continue, the existing options will be reset", + "options_not_allowed_with_state_class_or_uom": "The 'Options' setting is not allowed when state class or unit of measurement are used", + "options_with_enum_device_class": "Configure options for the enumeration sensor", + "preset_mode_none_not_allowed": "Preset \"none\" is not a valid preset mode", + "uom_required_for_device_class": "The selected device class requires a unit" + }, + "initiate_flow": { + "reconfigure": "Reconfigure MQTT device", + "user": "Add MQTT device" + }, + "step": { + "availability": { + "data": { + "availability_template": "Availability template", + "availability_topic": "Availability topic", + "payload_available": "Payload available", + "payload_not_available": "Payload not available" + }, + "data_description": { + "availability_template": "A [template]({value_templating_url}) to render the availability payload received on the availability topic", + "availability_topic": "Topic to receive the availability payload on", + "payload_available": "The payload that indicates the device is available (defaults to 'online')", + "payload_not_available": "The payload that indicates the device is not available (defaults to 'offline')" + }, + "description": "The availability feature allows a device to report its availability.", + "title": "Availability options" + }, + "delete_entity": { + "data": { + "component": "Entity" + }, + "data_description": { + "component": "Select the entity you want to delete. At least one entity is required." + }, + "description": "Delete an entity. The entity will be removed from the device. Removing an entity will break any automations or scripts that depend on it.", + "title": "Delete entity" + }, + "device": { + "data": { + "configuration_url": "Configuration URL", + "manufacturer": "Manufacturer", + "model": "Model", + "model_id": "Model ID", + "name": "[%key:common::config_flow::data::name%]" + }, + "data_description": { + "configuration_url": "A link to the webpage that can manage the configuration of this device. Can be either a 'http://', 'https://' or an internal 'homeassistant://' URL.", + "manufacturer": "E.g. Cleanmaster Ltd.", + "model": "E.g. 'Cleanmaster Pro'.", + "model_id": "E.g. '123NK2PRO'.", + "name": "The name of the manually added MQTT device." + }, + "description": "Enter the MQTT device details:", + "sections": { + "mqtt_settings": { + "data": { + "message_expiry_interval": "Message Expiry Interval", + "qos": "QoS" + }, + "data_description": { + "message_expiry_interval": "Retention time interval for published message.", + "qos": "The Quality of Service value the device's entities should use." + }, + "name": "MQTT settings" + }, + "other_settings": { + "data": { + "hw_version": "Hardware version", + "sw_version": "Software version" + }, + "data_description": { + "hw_version": "The hardware version of the device. E.g. 'v1.0 rev a'.", + "sw_version": "The software version of the device. E.g. '2025.1.0'." + }, + "name": "Other device settings" + } + }, + "title": "Configure MQTT device details" + }, + "entity": { + "data": { + "entity_picture": "Entity picture", + "name": "Entity name", + "platform": "Type of entity" + }, + "data_description": { + "entity_picture": "An URL to a picture to be assigned.", + "name": "The name of the entity. Leave empty to set it to `None` to [mark it as main feature of the MQTT device]({naming_entities_url}).", + "platform": "The type of the entity to configure." + }, + "description": "Configure the basic {platform_label}entity settings{entity_name_label}", + "title": "Configure MQTT device \"{mqtt_device}\"" + }, + "entity_platform_config": { + "data": { + "alarm_control_panel_code_mode": "Alarm code validation mode", + "climate_feature_action": "Current action support", + "climate_feature_current_humidity": "Current humidity support", + "climate_feature_current_temperature": "Current temperature support", + "climate_feature_fan_modes": "Fan mode support", + "climate_feature_power": "Power on/off support", + "climate_feature_preset_modes": "[%key:component::mqtt::config_subentries::device::step::entity_platform_config::data::fan_feature_preset_modes%]", + "climate_feature_swing_horizontal_modes": "Horizontal swing mode support", + "climate_feature_swing_modes": "Swing mode support", + "climate_feature_target_humidity": "Target humidity support", + "climate_feature_target_temperature": "Target temperature support", + "device_class": "Device class", + "entity_category": "Entity category", + "fan_feature_direction": "Direction support", + "fan_feature_oscillation": "Oscillation support", + "fan_feature_preset_modes": "Preset modes support", + "fan_feature_speed": "Speed support", + "image_processing_mode": "Image processing mode", + "options": "Add option", + "reports_position": "Reports position", + "schema": "Schema", + "state_class": "State class", + "suggested_display_precision": "Suggested display precision", + "supported_features": "Supported features", + "temperature_unit": "Temperature unit", + "unit_of_measurement": "Unit of measurement", + "water_heater_feature_current_temperature": "[%key:component::mqtt::config_subentries::device::step::entity_platform_config::data::climate_feature_current_temperature%]", + "water_heater_feature_power": "[%key:component::mqtt::config_subentries::device::step::entity_platform_config::data::climate_feature_power%]" + }, + "data_description": { + "alarm_control_panel_code_mode": "Configures how the alarm control panel validates the code. A local code is configured with the entity and is validated by Home Assistant. A remote code is sent to the device and validated remotely. [Learn more.]({url}#code)", + "climate_feature_action": "The climate supports reporting the current action.", + "climate_feature_current_humidity": "The climate supports reporting the current humidity.", + "climate_feature_current_temperature": "The climate supports reporting the current temperature.", + "climate_feature_fan_modes": "The climate supports fan modes.", + "climate_feature_power": "The climate supports the power \"on\" and \"off\" commands.", + "climate_feature_preset_modes": "The climate supports preset modes.", + "climate_feature_swing_horizontal_modes": "The climate supports horizontal swing modes.", + "climate_feature_swing_modes": "The climate supports swing modes.", + "climate_feature_target_humidity": "The climate supports setting the target humidity.", + "climate_feature_target_temperature": "The climate supports setting the target temperature.", + "device_class": "The device class of the {platform} entity. [Learn more.]({url}#device_class)", + "entity_category": "Allows marking an entity as device configuration or diagnostics. An entity with a category will not be exposed to cloud, Alexa, or Google Assistant components, nor included in indirect action calls to devices or areas. Sensor entities cannot be assigned a device configuration class. [Learn more.]({registry_properties_url})", + "fan_feature_direction": "The fan supports direction.", + "fan_feature_oscillation": "The fan supports oscillation.", + "fan_feature_preset_modes": "The fan supports preset modes.", + "fan_feature_speed": "The fan supports multiple speeds.", + "image_processing_mode": "Select how the image data is received.", + "options": "Options for allowed sensor state values. The sensor’s Device class must be set to Enumeration. The 'Options' setting cannot be used together with State class or Unit of measurement.", + "reports_position": "Set this option if the valve reports the position or supports setting the position. Enabling this option will cause the position to be published instead of a payload defined by payload \"open\", payload \"close\" or payload \"stop\". When receiving messages, state topic will accept numeric payloads or one of the configured state messages.", + "schema": "The schema to use. [Learn more.]({url}#comparison-of-light-mqtt-schemas)", + "state_class": "The [state class]({available_state_classes_url}) of the sensor. [Learn more.]({url}#state_class)", + "suggested_display_precision": "The number of decimals which should be used in the {platform} entity state after rounding. [Learn more.]({url}#suggested_display_precision)", + "supported_features": "The features that the entity supports.", + "temperature_unit": "This determines the native unit of measurement the MQTT device works with.", + "unit_of_measurement": "Defines the unit of measurement, if any.", + "water_heater_feature_current_temperature": "The water heater supports reporting the current temperature.", + "water_heater_feature_power": "The water heater supports the power \"on\" and \"off\" commands." + }, + "description": "Please configure specific details for {platform} entity \"{entity}\":", + "sections": { + "other_settings": { + "data": { + "suggested_display_precision": "Suggested display precision" + }, + "data_description": { + "suggested_display_precision": "The number of decimals which should be used in the {platform} entity state after rounding. [Learn more.]({url}#suggested_display_precision)" + }, + "name": "Other settings" + } + }, + "title": "Configure MQTT device \"{mqtt_device}\"" + }, + "export": { + "description": "An export allows you to migrate the MQTT device configuration to YAML-based configuration or MQTT discovery. The configuration export can also be helpful for troubleshooting.", + "menu_options": { + "export_discovery": "Export MQTT discovery information", + "export_yaml": "Export to YAML configuration" + }, + "title": "Export MQTT device config" + }, + "export_discovery": { + "data": { + "discovery_payload": "Discovery payload:", + "discovery_topic": "Discovery topic" + }, + "data_description": { + "discovery_payload": "The JSON [discovery payload]({url}#device-discovery-payload) that contains information about the MQTT device.", + "discovery_topic": "The [discovery topic]({url}#discovery-topic) to publish the discovery payload, used to trigger MQTT discovery. An empty payload published to this topic will remove the device and discovered entities." + }, + "description": "To allow setup via MQTT [discovery]({url}#device-discovery-payload), the discovery payload needs to be published to the discovery topic. Copy the information from the fields below. Home Assistant will detect if the setup of the MQTT device was tried via MQTT discovery instead, and will offer a repair flow to clean up the redundant subentry. You can also choose to change the identifiers if you do not want to remove the subentry.", + "title": "[%key:component::mqtt::config_subentries::device::step::export::title%]" + }, + "export_yaml": { + "data": { + "yaml": "Copy the YAML configuration below:" + }, + "data_description": { + "yaml": "Place YAML configuration in your [configuration.yaml]({url}#yaml-configuration-listed-per-item)." + }, + "description": "You can copy the configuration below and place it your configuration.yaml file. Home Assistant will detect if the setup of the MQTT device was tried via YAML instead, and will offer a repair flow to clean up the redundant subentry. You can also choose to change the identifiers if you do not want to remove the subentry.", + "title": "[%key:component::mqtt::config_subentries::device::step::export::title%]" + }, + "mqtt_platform_config": { + "data": { + "available_tones": "Available Tones", + "blue_template": "Blue template", + "brightness_template": "Brightness template", + "code": "Alarm code", + "code_arm_required": "Code arm required", + "code_disarm_required": "Code disarm required", + "code_format": "Code format", + "code_trigger_required": "Code trigger required", + "color_temp_template": "Color temperature template", + "command_off_template": "Command \"off\" template", + "command_on_template": "Command \"on\" template", + "command_template": "Command template", + "command_topic": "Command topic", + "content_type": "Content type", + "force_update": "Force update", + "green_template": "Green template", + "image_encoding": "Image encoding", + "image_topic": "Image topic", + "last_reset_value_template": "Last reset value template", + "max": "Maximum", + "min": "Minimum", + "mode": "Mode", + "mode_command_template": "Operation mode command template", + "mode_command_topic": "Operation mode command topic", + "mode_state_template": "Operation mode value template", + "mode_state_topic": "Operation mode state topic", + "modes": "Supported operation modes", + "on_command_type": "ON command type", + "optimistic": "Optimistic", + "options": "Set options", + "payload_off": "Payload \"off\"", + "payload_on": "Payload \"on\"", + "payload_press": "Payload \"press\"", + "payload_reset": "Payload \"reset\"", + "position_closed": "Position \"closed\"", + "position_open": "Position \"open\"", + "qos": "QoS", + "red_template": "Red template", + "retain": "Retain", + "state_off": "State \"off\"", + "state_on": "State \"on\"", + "state_template": "State template", + "state_topic": "State topic", + "state_value_template": "State value template", + "step": "Step", + "support_duration": "Duration support", + "support_volume_set": "Set volume support", + "supported_color_modes": "Supported color modes", + "timezone": "Time zone", + "url_template": "URL template", + "url_topic": "URL topic", + "value_template": "Value template" + }, + "data_description": { + "available_tones": "The siren supports tones. The `tone` variable will become available for use in the \"Command template\" setting. [Learn more.]({url}#available_tones)", + "blue_template": "[Template]({value_templating_url}) to extract blue color from the state payload value. Expected result of the template is an integer from 0-255 range.", + "brightness_template": "[Template]({value_templating_url}) to extract brightness from the state payload value. Expected result of the template is an integer from 0-255 range.", + "code": "Specifies a code to enable or disable the alarm in the frontend. Note that this blocks sending MQTT message commands to the remote device if the code validation fails. [Learn more.]({url}#code)", + "code_arm_required": "If set, the code is required to arm the alarm. If not set, the code is not validated.", + "code_disarm_required": "If set, the code is required to disarm the alarm. If not set, the code is not validated.", + "code_format": "A regular expression to validate a supplied code when it is set during the action to open, lock or unlock the MQTT lock. [Learn more.]({url}#code_format)", + "code_trigger_required": "If set, the code is required to manually trigger the alarm. If not set, the code is not validated.", + "color_temp_template": "[Template]({value_templating_url}) to extract color temperature in Kelvin from the state payload value. Expected result of the template is an integer.", + "command_off_template": "The [template]({command_templating_url}) for \"off\" state changes. Available variables are: `state` and `transition`.", + "command_on_template": "The [template]({command_templating_url}) for \"on\" state changes. Available variables: `state`, `brightness`, `color_temp`, `red`, `green`, `blue`, `hue`, `sat`, `flash`, `transition` and `effect`. Values `red`, `green`, `blue` and `brightness` are provided as integers from range 0-255. Value of `hue` is provided as float from range 0-360. Value of `sat` is provided as float from range 0-100. Value of `color_temp` is provided as integer representing Kelvin units.", + "command_template": "A [template]({command_templating_url}) to render the payload to be published at the command topic. [Learn more.]({url}#command_template)", + "command_topic": "The publishing topic that will be used to control the {platform} entity. [Learn more.]({url}#command_topic)", + "content_type": "The content type or the image data that is received at the image topic.", + "force_update": "Sends update events even if the value hasn’t changed. Useful if you want to have meaningful value graphs in history. [Learn more.]({url}#force_update)", + "green_template": "[Template]({value_templating_url}) to extract green color from the state payload value. Expected result of the template is an integer from 0-255 range.", + "image_encoding": "Select the encoding of the received image data", + "image_topic": "The MQTT topic subscribed to receive messages containing the image data. [Learn more.]({url}#image_topic)", + "last_reset_value_template": "Defines a [template]({value_templating_url}) to extract the last reset. When Last reset template is set, the State class option must be Total. [Learn more.]({url}#last_reset_value_template)", + "max": "Maximum value. [Learn more.]({url}#max)", + "min": "Minimum value. [Learn more.]({url}#min)", + "mode": "Control how the number should be displayed in the UI. [Learn more.]({url}#mode)", + "mode_command_template": "[Template]({command_templating_url}) to define the operation mode to be sent to the operation mode command topic. [Learn more.]({url}#mode_command_template)", + "mode_command_topic": "The MQTT topic to publish commands to change the operation mode. [Learn more.]({url}#mode_command_topic)", + "mode_state_template": "Defines a [template]({value_templating_url}) to extract the operation mode state. [Learn more.]({url}#mode_state_template)", + "mode_state_topic": "The MQTT topic subscribed to receive operation mode state messages. [Learn more.]({url}#mode_state_topic)", + "modes": "A list of supported operation modes. [Learn more.]({url}#modes)", + "on_command_type": "Defines when the payload \"on\" is sent. Using \"Last\" (the default) will send any style (brightness, color, etc) topics first and then a payload \"on\" to the command topic. Using \"First\" will send the payload \"on\" and then any style topics. Using \"Brightness\" will only send brightness commands instead of the payload \"on\" to turn the light on.", + "optimistic": "Flag that defines if the {platform} entity works in optimistic mode. [Learn more.]({url}#optimistic)", + "options": "List of options that can be selected.", + "payload_off": "The payload that represents the \"off\" state.", + "payload_on": "The payload that represents the \"on\" state.", + "payload_press": "The payload to send when the button is triggered.", + "payload_reset": "The payload received at the state topic that resets the entity to an unknown state.", + "position_closed": "Number which represents closed position. The valve’s position will be scaled to the (position \"closed\"…position \"open\") range when an action is performed and scaled back when a value is received.", + "position_open": "Number which represents open position. The valve’s position will be scaled to the (position \"closed\"…position \"open\") range when an action is performed and scaled back when a value is received.", + "qos": "The QoS value a {platform} entity should use.", + "red_template": "[Template]({value_templating_url}) to extract red color from the state payload value. Expected result of the template is an integer from 0-255 range.", + "retain": "Select if values published by the {platform} entity should be retained at the MQTT broker.", + "state_off": "The incoming payload that represents the \"off\" state. Use only when the value that represents \"off\" state in the state topic is different from value that should be sent to the command topic to turn the device off.", + "state_on": "The incoming payload that represents the \"on\" state. Use only when the value that represents \"on\" state in the state topic is different from value that should be sent to the command topic to turn the device on.", + "state_template": "[Template]({value_templating_url}) to extract state from the state payload value.", + "state_topic": "The MQTT topic subscribed to receive {platform} state values. [Learn more.]({url}#state_topic)", + "step": "Step value. Smallest value 0.001.", + "support_duration": "The siren supports setting a duration in second. The `duration` variable will become available for use in the \"Command template\" setting. [Learn more.]({url}#support_duration)", + "support_volume_set": "The siren supports setting a volume. The `volume_level` variable will become available for use in the \"Command template\" setting. [Learn more.]({url}#support_volume_set)", + "supported_color_modes": "A list of color modes supported by the light. Possible color modes are On/Off, Brightness, Color temperature, HS, XY, RGB, RGBW, RGBWW, White. Note that if On/Off or Brightness are used, that must be the only value in the list. [Learn more.]({url}#supported_color_modes)", + "timezone": "Set to a valid [IANA time zone identifier]({tz_abbr_url}). Do not set this option if the date/time structure is providing time zone information via the status update.", + "url_template": "[Template]({value_templating_url}) to extract an URL from the received URL topic payload value. [Learn more.]({url}#url_template)", + "url_topic": "The MQTT topic subscribed to receive messages containing the image URL. [Learn more.]({url}#url_topic)", + "value_template": "Defines a [template]({value_templating_url}) to extract the {platform} entity value. [Learn more.]({url}#value_template)" + }, + "description": "Please configure MQTT specific details for {platform} entity \"{entity}\":", + "sections": { + "alarm_control_panel_payload_settings": { + "data": { + "payload_arm_away": "Payload \"arm away\"", + "payload_arm_custom_bypass": "Payload \"arm custom bypass\"", + "payload_arm_disarm": "Payload \"disarm\"", + "payload_arm_home": "Payload \"arm home\"", + "payload_arm_night": "Payload \"arm night\"", + "payload_arm_vacation": "Payload \"arm vacation\"", + "payload_trigger": "Payload \"trigger alarm\"" + }, + "data_description": { + "payload_arm_away": "The payload sent when an \"arm away\" command is issued.", + "payload_arm_custom_bypass": "The payload sent when an \"arm custom bypass\" command is issued.", + "payload_arm_disarm": "The payload sent when a \"disarm\" command is issued.", + "payload_arm_home": "The payload sent when an \"arm home\" command is issued.", + "payload_arm_night": "The payload sent when an \"arm night\" command is issued.", + "payload_arm_vacation": "The payload sent when an \"arm vacation\" command is issued.", + "payload_trigger": "The payload sent when a \"trigger alarm\" command is issued." + }, + "name": "Alarm control panel payload settings" + }, + "climate_action_settings": { + "data": { + "action_template": "Action template", + "action_topic": "Action topic" + }, + "data_description": { + "action_template": "A [template]({value_templating_url}) to render the value received on the action topic with.", + "action_topic": "The MQTT topic to subscribe for changes of the current action. If this is set, the climate graph uses the value received as data source. A \"None\" payload resets the current action state. An empty payload is ignored. Valid action values are: \"off\", \"heating\", \"cooling\", \"drying\", \"idle\" and \"fan\". [Learn more.]({url}#action_topic)" + }, + "name": "Current action settings" + }, + "climate_fan_mode_settings": { + "data": { + "fan_mode_command_template": "Fan mode command template", + "fan_mode_command_topic": "Fan mode command topic", + "fan_mode_state_template": "Fan mode state template", + "fan_mode_state_topic": "Fan mode state topic", + "fan_modes": "Fan modes" + }, + "data_description": { + "fan_mode_command_template": "A [template]({command_templating_url}) to compose the payload to be published at the fan mode command topic.", + "fan_mode_command_topic": "The MQTT topic to publish commands to change the climate fan mode. [Learn more.]({url}#fan_mode_command_topic)", + "fan_mode_state_template": "Defines a [template]({value_templating_url}) to extract the climate fan mode value.", + "fan_mode_state_topic": "The MQTT topic subscribed to receive the climate fan mode. [Learn more.]({url}#fan_mode_state_topic)", + "fan_modes": "List of fan modes this climate is capable of running at. Common fan modes that offer translations are `off`, `on`, `auto`, `low`, `medium`, `high`, `middle`, `focus` and `diffuse`." + }, + "name": "Fan mode settings" + }, + "climate_power_settings": { + "data": { + "payload_off": "[%key:component::mqtt::config_subentries::device::step::mqtt_platform_config::data::payload_off%]", + "payload_on": "[%key:component::mqtt::config_subentries::device::step::mqtt_platform_config::data::payload_on%]", + "power_command_template": "Power command template", + "power_command_topic": "Power command topic" + }, + "data_description": { + "payload_off": "[%key:component::mqtt::config_subentries::device::step::mqtt_platform_config::data_description::payload_off%]", + "payload_on": "[%key:component::mqtt::config_subentries::device::step::mqtt_platform_config::data_description::payload_on%]", + "power_command_template": "A [template]({command_templating_url}) to compose the payload to be published at the power command topic. The `value` parameter is the payload set for payload \"on\" or payload \"off\".", + "power_command_topic": "The MQTT topic to publish commands to change the climate power state. Sends the payload configured with payload \"on\" or payload \"off\". [Learn more.]({url}#power_command_topic)" + }, + "name": "Power settings" + }, + "climate_preset_mode_settings": { + "data": { + "preset_mode_command_template": "[%key:component::mqtt::config_subentries::device::step::mqtt_platform_config::sections::fan_preset_mode_settings::data::preset_mode_command_template%]", + "preset_mode_command_topic": "[%key:component::mqtt::config_subentries::device::step::mqtt_platform_config::sections::fan_preset_mode_settings::data::preset_mode_command_topic%]", + "preset_mode_state_topic": "[%key:component::mqtt::config_subentries::device::step::mqtt_platform_config::sections::fan_preset_mode_settings::data::preset_mode_state_topic%]", + "preset_mode_value_template": "[%key:component::mqtt::config_subentries::device::step::mqtt_platform_config::sections::fan_preset_mode_settings::data::preset_mode_value_template%]", + "preset_modes": "[%key:component::mqtt::config_subentries::device::step::mqtt_platform_config::sections::fan_preset_mode_settings::data::preset_modes%]" + }, + "data_description": { + "preset_mode_command_template": "[%key:component::mqtt::config_subentries::device::step::mqtt_platform_config::sections::fan_preset_mode_settings::data_description::preset_mode_command_template%]", + "preset_mode_command_topic": "The MQTT topic to publish commands to change the climate preset mode. [Learn more.]({url}#preset_mode_command_topic)", + "preset_mode_state_topic": "[%key:component::mqtt::config_subentries::device::step::mqtt_platform_config::sections::fan_preset_mode_settings::data_description::preset_mode_state_topic%]", + "preset_mode_value_template": "[%key:component::mqtt::config_subentries::device::step::mqtt_platform_config::sections::fan_preset_mode_settings::data_description::preset_mode_value_template%]", + "preset_modes": "List of preset modes this climate is capable of running at. Common preset modes that offer translations are `none`, `away`, `eco`, `boost`, `comfort`, `home`, `sleep` and `activity`." + }, + "name": "[%key:component::mqtt::config_subentries::device::step::mqtt_platform_config::sections::fan_preset_mode_settings::name%]" + }, + "climate_swing_horizontal_mode_settings": { + "data": { + "swing_horizontal_mode_command_template": "Horizontal swing mode command template", + "swing_horizontal_mode_command_topic": "Horizontal swing mode command topic", + "swing_horizontal_mode_state_template": "Horizontal swing mode state template", + "swing_horizontal_mode_state_topic": "Horizontal swing mode state topic", + "swing_horizontal_modes": "Horizontal swing modes" + }, + "data_description": { + "swing_horizontal_mode_command_template": "A [template]({command_templating_url}) to compose the payload to be published at the horizontal swing mode command topic.", + "swing_horizontal_mode_command_topic": "The MQTT topic to publish commands to change the climate horizontal swing mode. [Learn more.]({url}#swing_horizontal_mode_command_topic)", + "swing_horizontal_mode_state_template": "Defines a [template]({value_templating_url}) to extract the climate horizontal swing mode value.", + "swing_horizontal_mode_state_topic": "The MQTT topic subscribed to receive the climate horizontal swing mode. [Learn more.]({url}#swing_horizontal_mode_state_topic)", + "swing_horizontal_modes": "List of horizontal swing modes this climate is capable of running at. Common horizontal swing modes that offer translations are `off` and `on`." + }, + "name": "Horizontal swing mode settings" + }, + "climate_swing_mode_settings": { + "data": { + "swing_mode_command_template": "Swing mode command template", + "swing_mode_command_topic": "Swing mode command topic", + "swing_mode_state_template": "Swing mode state template", + "swing_mode_state_topic": "Swing mode state topic", + "swing_modes": "Swing modes" + }, + "data_description": { + "swing_mode_command_template": "A [template]({command_templating_url}) to compose the payload to be published at the swing mode command topic.", + "swing_mode_command_topic": "The MQTT topic to publish commands to change the climate swing mode. [Learn more.]({url}#swing_mode_command_topic)", + "swing_mode_state_template": "Defines a [template]({value_templating_url}) to extract the climate swing mode value.", + "swing_mode_state_topic": "The MQTT topic subscribed to receive the climate swing mode. [Learn more.]({url}#swing_mode_state_topic)", + "swing_modes": "List of swing modes this climate is capable of running at. Common swing modes that offer translations are `off`, `on`, `vertical`, `horizontal` and `both`." + }, + "name": "Swing mode settings" + }, + "cover_payload_settings": { + "data": { + "payload_close": "Payload \"close\"", + "payload_open": "Payload \"open\"", + "payload_stop": "Payload \"stop\"", + "payload_stop_tilt": "Payload \"stop tilt\"", + "state_closed": "State \"closed\"", + "state_closing": "State \"closing\"", + "state_open": "State \"open\"", + "state_opening": "State \"opening\"", + "state_stopped": "State \"stopped\"" + }, + "data_description": { + "payload_close": "The payload sent when a \"close\" command is issued.", + "payload_open": "The payload sent when an \"open\" command is issued.", + "payload_stop": "The payload sent when a \"stop\" command is issued. Leave empty to disable the \"stop\" feature.", + "payload_stop_tilt": "The payload sent when a \"stop tilt\" command is issued.", + "state_closed": "The payload received at the state topic that represents the \"closed\" state.", + "state_closing": "The payload received at the state topic that represents the \"closing\" state.", + "state_open": "The payload received at the state topic that represents the \"open\" state.", + "state_opening": "The payload received at the state topic that represents the \"opening\" state.", + "state_stopped": "The payload received at the state topic that represents the \"stopped\" state (for covers that do not report \"open\"/\"closed\" state)." + }, + "name": "Payload settings" + }, + "cover_position_settings": { + "data": { + "position_closed": "Position \"closed\" value", + "position_open": "Position \"open\" value", + "position_template": "Position value template", + "position_topic": "Position state topic", + "set_position_template": "Set position template", + "set_position_topic": "Set position topic" + }, + "data_description": { + "position_closed": "Number which represents \"closed\" position.", + "position_open": "Number which represents \"open\" position.", + "position_template": "Defines a [template]({value_templating_url}) to extract the payload for the position topic. Within the template the following variables are also available: `entity_id`, `position_open`, `position_closed`, `tilt_min` and `tilt_max`. [Learn more.]({url}#position_template)", + "position_topic": "The MQTT topic subscribed to receive cover position state messages. [Learn more.]({url}#position_topic)", + "set_position_template": "[Template]({command_templating_url}) to define the position to be sent to the set position topic. Within the template the following variables are available: `value` (the scaled target position), `entity_id`, `position` (the target position percentage), `position_open`, `position_closed`, `tilt_min` and `tilt_max`. [Learn more.]({url}#set_position_template)", + "set_position_topic": "The MQTT topic to publish position commands to. You need to use the set position topic as well if you want to use the position topic. Use template if position topic wants different values than within range \"position closed\" - \"position_open\". If template is not defined and position \"closed\" != 100 and position \"open\" != 0 then proper position value is calculated from percentage position. [Learn more.]({url}#set_position_topic)" + }, + "name": "Position settings" + }, + "cover_tilt_settings": { + "data": { + "tilt_closed_value": "Tilt \"closed\" value", + "tilt_command_template": "Tilt command template", + "tilt_command_topic": "Tilt command topic", + "tilt_max": "Tilt max", + "tilt_min": "Tilt min", + "tilt_opened_value": "Tilt \"opened\" value", + "tilt_optimistic": "Tilt optimistic", + "tilt_status_template": "Tilt value template", + "tilt_status_topic": "Tilt status topic" + }, + "data_description": { + "tilt_closed_value": "The value that will be sent to the \"tilt command topic\" when the cover tilt is closed.", + "tilt_command_template": "[Template]({command_templating_url}) to define the position to be sent to the tilt command topic. Within the template the following variables are available: `entity_id`, `tilt_position` (the target tilt position percentage), `position_open`, `position_closed`, `tilt_min` and `tilt_max`. [Learn more.]({url}#tilt_command_template)", + "tilt_command_topic": "The MQTT topic to publish commands to control the cover tilt. [Learn more.]({url}#tilt_command_topic)", + "tilt_max": "The maximum tilt value.", + "tilt_min": "The minimum tilt value.", + "tilt_opened_value": "The value that will be sent to the \"tilt command topic\" when the cover tilt is opened.", + "tilt_optimistic": "Flag that defines if tilt works in optimistic mode. If tilt status topic is not defined, tilt works in optimistic mode by default. [Learn more.]({url}#tilt_optimistic)", + "tilt_status_template": "Defines a [template]({value_templating_url}) to extract the payload for the tilt status topic. Within the template the following variables are available: `entity_id`, `position_open`, `position_closed`, `tilt_min` and `tilt_max`. [Learn more.]({url}#tilt_status_template)", + "tilt_status_topic": "The MQTT topic subscribed to receive tilt status update values. [Learn more.]({url}#tilt_status_topic)" + }, + "name": "Tilt settings" + }, + "current_humidity_settings": { + "data": { + "current_humidity_template": "Current humidity template", + "current_humidity_topic": "Current humidity topic" + }, + "data_description": { + "current_humidity_template": "Defines a [template]({value_templating_url}) to extract the current humidity value. [Learn more.]({url}#current_humidity_template)", + "current_humidity_topic": "The MQTT topic subscribed to receive current humidity update values. [Learn more.]({url}#current_humidity_topic)" + }, + "name": "Current humidity settings" + }, + "current_temperature_settings": { + "data": { + "current_temperature_template": "Current temperature template", + "current_temperature_topic": "Current temperature topic" + }, + "data_description": { + "current_temperature_template": "Defines a [template]({value_templating_url}) to extract the current temperature value. [Learn more.]({url}#current_temperature_template)", + "current_temperature_topic": "The MQTT topic subscribed to receive current temperature update values. [Learn more.]({url}#current_temperature_topic)" + }, + "name": "Current temperature settings" + }, + "fan_direction_settings": { + "data": { + "direction_command_template": "Direction command template", + "direction_command_topic": "Direction command topic", + "direction_state_topic": "Direction state topic", + "direction_value_template": "Direction value template" + }, + "data_description": { + "direction_command_template": "A [template]({command_templating_url}) to compose the payload to be published at the direction command topic. The template variable `value` will be either `forward` or `reverse`.", + "direction_command_topic": "The MQTT topic to publish commands to change the fan direction. The payload will be either `forward` or `reverse` and can be customized using the direction command template. [Learn more.]({url}#direction_command_topic)", + "direction_state_topic": "The MQTT topic subscribed to receive fan direction state. Accepted state payloads are `forward` or `reverse`. [Learn more.]({url}#direction_state_topic)", + "direction_value_template": "Defines a [template]({value_templating_url}) to extract fan direction state value. The template should return either `forward` or `reverse`. When the template returns an empty string, the direction will be ignored." + }, + "name": "Direction settings" + }, + "fan_oscillation_settings": { + "data": { + "oscillation_command_template": "Oscillation command template", + "oscillation_command_topic": "Oscillation command topic", + "oscillation_state_topic": "Oscillation state topic", + "oscillation_value_template": "Oscillation value template", + "payload_oscillation_off": "Payload \"oscillation off\"", + "payload_oscillation_on": "Payload \"oscillation on\"" + }, + "data_description": { + "oscillation_command_template": "A [template]({command_templating_url}) to compose the payload to be published at the oscillation command topic.", + "oscillation_command_topic": "The MQTT topic to publish commands to change the fan oscillation state. [Learn more.]({url}#oscillation_command_topic)", + "oscillation_state_topic": "The MQTT topic subscribed to receive fan oscillation state. [Learn more.]({url}#oscillation_state_topic)", + "oscillation_value_template": "Defines a [template]({value_templating_url}) to extract fan oscillation state value.", + "payload_oscillation_off": "The payload that represents the oscillation \"off\" state.", + "payload_oscillation_on": "The payload that represents the oscillation \"on\" state." + }, + "name": "Oscillation settings" + }, + "fan_preset_mode_settings": { + "data": { + "payload_reset_preset_mode": "Payload \"reset preset mode\"", + "preset_mode_command_template": "Preset mode command template", + "preset_mode_command_topic": "Preset mode command topic", + "preset_mode_state_topic": "Preset mode state topic", + "preset_mode_value_template": "Preset mode value template", + "preset_modes": "Preset modes" + }, + "data_description": { + "payload_reset_preset_mode": "A special payload that resets the fan preset mode state attribute to unknown when received at the preset mode state topic.", + "preset_mode_command_template": "A [template]({command_templating_url}) to compose the payload to be published at the preset mode command topic.", + "preset_mode_command_topic": "The MQTT topic to publish commands to change the fan preset mode. [Learn more.]({url}#preset_mode_command_topic)", + "preset_mode_state_topic": "The MQTT topic subscribed to receive fan preset mode. [Learn more.]({url}#preset_mode_state_topic)", + "preset_mode_value_template": "Defines a [template]({value_templating_url}) to extract fan preset mode value.", + "preset_modes": "List of preset modes this fan is capable of running at. Common examples include auto, smart, whoosh, eco and breeze." + }, + "name": "Preset mode settings" + }, + "fan_speed_settings": { + "data": { + "payload_reset_percentage": "Payload \"reset percentage\"", + "percentage_command_template": "Percentage command template", + "percentage_command_topic": "Percentage command topic", + "percentage_state_topic": "Percentage state topic", + "percentage_value_template": "Percentage value template", + "speed_range_max": "Speed range max", + "speed_range_min": "Speed range min" + }, + "data_description": { + "payload_reset_percentage": "A special payload that resets the fan speed percentage state attribute to unknown when received at the percentage state topic.", + "percentage_command_template": "A [template]({command_templating_url}) to compose the payload to be published at the percentage command topic.", + "percentage_command_topic": "The MQTT topic to publish commands to change the fan speed state based on a percentage setting. The value shall be in the range from \"speed range min\" to \"speed range max\". [Learn more.]({url}#percentage_command_topic)", + "percentage_state_topic": "The MQTT topic subscribed to receive fan speed state. This is a value in the range from \"speed range min\" to \"speed range max\". [Learn more.]({url}#percentage_state_topic)", + "percentage_value_template": "Defines a [template]({value_templating_url}) to extract the speed percentage value.", + "speed_range_max": "The maximum of numeric output range (representing 100 %). The percentage step is 100 / number of speeds within the \"speed range\".", + "speed_range_min": "The minimum of numeric output range (off not included, so speed_range_min - 1 represents 0 %). The percentage step is 100 / the number of speeds within the \"speed range\"." + }, + "name": "Speed settings" + }, + "light_brightness_settings": { + "data": { + "brightness": "Separate brightness", + "brightness_command_template": "Brightness command template", + "brightness_command_topic": "Brightness command topic", + "brightness_scale": "Brightness scale", + "brightness_state_topic": "Brightness state topic", + "brightness_value_template": "Brightness value template" + }, + "data_description": { + "brightness": "Flag that defines if light supports brightness when the RGB, RGBW, or RGBWW color mode is supported.", + "brightness_command_template": "A [template]({command_templating_url}) to compose the payload to be published at the brightness command topic.", + "brightness_command_topic": "The publishing topic that will be used to control the brightness. [Learn more.]({url}#brightness_command_topic)", + "brightness_scale": "Defines the maximum brightness value (i.e., 100%) of the maximum brightness.", + "brightness_state_topic": "The MQTT topic subscribed to receive brightness state values. [Learn more.]({url}#brightness_state_topic)", + "brightness_value_template": "Defines a [template]({value_templating_url}) to extract the brightness value." + }, + "name": "Brightness settings" + }, + "light_color_mode_settings": { + "data": { + "color_mode_state_topic": "Color mode state topic", + "color_mode_value_template": "Color mode value template" + }, + "data_description": { + "color_mode_state_topic": "The MQTT topic subscribed to receive color mode updates. If this is not configured, the color mode will be automatically set according to the last received valid color or color temperature.", + "color_mode_value_template": "Defines a [template]({value_templating_url}) to extract the color mode value." + }, + "name": "Color mode settings" + }, + "light_color_temp_settings": { + "data": { + "color_temp_command_template": "Color temperature command template", + "color_temp_command_topic": "Color temperature command topic", + "color_temp_state_topic": "Color temperature state topic", + "color_temp_value_template": "Color temperature value template" + }, + "data_description": { + "color_temp_command_template": "A [template]({command_templating_url}) to compose the payload to be published at the color temperature command topic.", + "color_temp_command_topic": "The publishing topic that will be used to control the color temperature. [Learn more.]({url}#color_temp_command_topic)", + "color_temp_state_topic": "The MQTT topic subscribed to receive color temperature state updates. [Learn more.]({url}#color_temp_state_topic)", + "color_temp_value_template": "Defines a [template]({value_templating_url}) to extract the color temperature value." + }, + "name": "Color temperature settings" + }, + "light_effect_settings": { + "data": { + "effect": "Effect", + "effect_command_template": "Effect command template", + "effect_command_topic": "Effect command topic", + "effect_list": "Effect list", + "effect_state_topic": "Effect state topic", + "effect_template": "Effect template", + "effect_value_template": "Effect value template" + }, + "data_description": { + "effect": "Flag that defines if the light supports effects.", + "effect_command_template": "A [template]({command_templating_url}) to compose the payload to be published at the effect command topic.", + "effect_command_topic": "The publishing topic that will be used to control the light's effect state. [Learn more.]({url}#effect_command_topic)", + "effect_list": "The list of effects the light supports.", + "effect_state_topic": "The MQTT topic subscribed to receive effect state updates. [Learn more.]({url}#effect_state_topic)" + }, + "name": "Effect settings" + }, + "light_hs_settings": { + "data": { + "hs_command_template": "HS command template", + "hs_command_topic": "HS command topic", + "hs_state_topic": "HS state topic", + "hs_value_template": "HS value template" + }, + "data_description": { + "hs_command_template": "Defines a [template]({command_templating_url}) to compose message which will be sent to HS command topic. Available variables: `hue` and `sat`.", + "hs_command_topic": "The MQTT topic to publish commands to change the light’s color state in HS format (Hue Saturation). Range for Hue: 0° .. 360°, Range of Saturation: 0..100. Note: Brightness is sent separately in the brightness command topic. [Learn more.]({url}#hs_command_topic)", + "hs_state_topic": "The MQTT topic subscribed to receive color state updates in HS format. The expected payload is the hue and saturation values separated by commas, for example, `359.5,100.0`. Note: Brightness is received separately in the brightness state topic. [Learn more.]({url}#hs_state_topic)", + "hs_value_template": "Defines a [template]({value_templating_url}) to extract the HS value." + }, + "name": "HS color mode settings" + }, + "light_rgb_settings": { + "data": { + "rgb_command_template": "RGB command template", + "rgb_command_topic": "RGB command topic", + "rgb_state_topic": "RGB state topic", + "rgb_value_template": "RGB value template" + }, + "data_description": { + "rgb_command_template": "Defines a [template]({command_templating_url}) to compose message which will be sent to RGB command topic. Available variables: `red`, `green` and `blue`.", + "rgb_command_topic": "The MQTT topic to publish commands to change the light’s RGB state. [Learn more.]({url}#rgb_command_topic)", + "rgb_state_topic": "The MQTT topic subscribed to receive RGB state updates. The expected payload is the RGB values separated by commas, for example, `255,0,127`. [Learn more.]({url}#rgb_state_topic)", + "rgb_value_template": "Defines a [template]({value_templating_url}) to extract the RGB value." + }, + "name": "RGB color mode settings" + }, + "light_rgbw_settings": { + "data": { + "rgbw_command_template": "RGBW command template", + "rgbw_command_topic": "RGBW command topic", + "rgbw_state_topic": "RGBW state topic", + "rgbw_value_template": "RGBW value template" + }, + "data_description": { + "rgbw_command_template": "Defines a [template]({command_templating_url}) to compose message which will be sent to RGBW command topic. Available variables: `red`, `green`, `blue` and `white`.", + "rgbw_command_topic": "The MQTT topic to publish commands to change the light’s RGBW state. [Learn more.]({url}#rgbw_command_topic)", + "rgbw_state_topic": "The MQTT topic subscribed to receive RGBW state updates. The expected payload is the RGBW values separated by commas, for example, `255,0,127,64`. [Learn more.]({url}#rgbw_state_topic)", + "rgbw_value_template": "Defines a [template]({value_templating_url}) to extract the RGBW value." + }, + "name": "RGBW color mode settings" + }, + "light_rgbww_settings": { + "data": { + "rgbww_command_template": "RGBWW command template", + "rgbww_command_topic": "RGBWW command topic", + "rgbww_state_topic": "RGBWW state topic", + "rgbww_value_template": "RGBWW value template" + }, + "data_description": { + "rgbww_command_template": "Defines a [template]({command_templating_url}) to compose message which will be sent to RGBWW command topic. Available variables: `red`, `green`, `blue`, `cold_white` and `warm_white`.", + "rgbww_command_topic": "The MQTT topic to publish commands to change the light’s RGBWW state. [Learn more.]({url}#rgbww_command_topic)", + "rgbww_state_topic": "The MQTT topic subscribed to receive RGBWW state updates. The expected payload is the RGBWW values separated by commas, for example, `255,0,127,64,32`. [Learn more.]({url}#rgbww_state_topic)", + "rgbww_value_template": "Defines a [template]({value_templating_url}) to extract the RGBWW value." + }, + "name": "RGBWW color mode settings" + }, + "light_white_settings": { + "data": { + "white_command_topic": "White command topic", + "white_scale": "White scale" + }, + "data_description": { + "white_command_topic": "The MQTT topic to publish commands to change the light to white mode with a given brightness. [Learn more.]({url}#white_command_topic)", + "white_scale": "Defines the maximum white level (i.e., 100%) of the maximum." + }, + "name": "White color mode settings" + }, + "light_xy_settings": { + "data": { + "xy_command_template": "XY command template", + "xy_command_topic": "XY command topic", + "xy_state_topic": "XY state topic", + "xy_value_template": "XY value template" + }, + "data_description": { + "xy_command_template": "Defines a [template]({command_templating_url}) to compose message which will be sent to XY command topic. Available variables: `x` and `y`.", + "xy_command_topic": "The MQTT topic to publish commands to change the light’s XY state. [Learn more.]({url}#xy_command_topic)", + "xy_state_topic": "The MQTT topic subscribed to receive XY state updates. The expected payload is the X and Y color values separated by commas, for example, `0.675,0.322`. [Learn more.]({url}#xy_state_topic)", + "xy_value_template": "Defines a [template]({value_templating_url}) to extract the XY value." + }, + "name": "XY color mode settings" + }, + "lock_payload_settings": { + "data": { + "payload_lock": "Payload \"lock\"", + "payload_open": "Payload \"open\"", + "payload_reset": "Payload \"reset\"", + "payload_unlock": "Payload \"unlock\"", + "state_jammed": "State \"jammed\"", + "state_locked": "State \"locked\"", + "state_locking": "State \"locking\"", + "state_unlocked": "State \"unlocked\"", + "state_unlocking": "State \"unlocking\"" + }, + "data_description": { + "payload_lock": "The payload sent when a \"lock\" command is issued.", + "payload_open": "The payload sent when an \"open\" command is issued. Set this payload if your lock supports the \"open\" action.", + "payload_reset": "The payload received at the state topic that resets the lock to an unknown state.", + "payload_unlock": "The payload sent when an \"unlock\" command is issued.", + "state_jammed": "The payload received at the state topic that represents the \"jammed\" state.", + "state_locked": "The payload received at the state topic that represents the \"locked\" state.", + "state_locking": "The payload received at the state topic that represents the \"locking\" state.", + "state_unlocked": "The payload received at the state topic that represents the \"unlocked\" state.", + "state_unlocking": "The payload received at the state topic that represents the \"unlocking\" state." + }, + "name": "Lock payload settings" + }, + "other_settings": { + "data": { + "expire_after": "Expire after", + "flash": "Flash support", + "flash_time_long": "Flash time long", + "flash_time_short": "Flash time short", + "max_kelvin": "Max Kelvin", + "min_kelvin": "Min Kelvin", + "off_delay": "OFF delay", + "transition": "Transition support" + }, + "data_description": { + "expire_after": "If set, it defines the number of seconds after the sensor’s state expires, if it’s not updated. After expiry, the sensor’s state becomes unavailable. If not set, the sensor's state never expires. [Learn more.]({url}#expire_after)", + "flash": "Enable the flash feature for this light", + "flash_time_long": "The duration, in seconds, of a \"long\" flash.", + "flash_time_short": "The duration, in seconds, of a \"short\" flash.", + "max_kelvin": "The maximum color temperature in Kelvin.", + "min_kelvin": "The minimum color temperature in Kelvin.", + "off_delay": "For sensors that only send \"on\" state updates (like PIRs), this variable sets a delay in seconds after which the sensor’s state will be updated back to \"off\".", + "transition": "Enable the transition feature for this light" + }, + "name": "Other settings" + }, + "siren_other_settings": { + "data": { + "command_off_template": "Command \"off\" template" + }, + "data_description": { + "command_off_template": "The [template]({command_templating_url}) for \"off\" state changes. By default the \"[Command template]({url}#command_template)\" will be used. [Learn more.]({url}#command_off_template)" + }, + "name": "Other siren settings" + }, + "target_humidity_settings": { + "data": { + "max_humidity": "Maximum humidity", + "min_humidity": "Minimum humidity", + "target_humidity_command_template": "Target humidity command template", + "target_humidity_command_topic": "Target humidity command topic", + "target_humidity_state_template": "Target humidity state template", + "target_humidity_state_topic": "Target humidity state topic" + }, + "data_description": { + "max_humidity": "The maximum target humidity that can be set.", + "min_humidity": "The minimum target humidity that can be set.", + "target_humidity_command_template": "A [template]({command_templating_url}) to compose the payload to be published at the target humidity command topic.", + "target_humidity_command_topic": "The MQTT topic to publish commands to change the climate target humidity. [Learn more.]({url}#humidity_command_topic)", + "target_humidity_state_template": "A [template]({value_templating_url}) to render the value received on the target humidity state topic with.", + "target_humidity_state_topic": "The MQTT topic to subscribe for changes of the target humidity. [Learn more.]({url}#humidity_state_topic)" + }, + "name": "Target humidity settings" + }, + "target_temperature_settings": { + "data": { + "initial": "Initial temperature", + "max_temp": "Maximum temperature", + "min_temp": "Minimum temperature", + "precision": "Precision", + "temp_step": "Temperature step", + "temperature_command_template": "Temperature command template", + "temperature_command_topic": "Temperature command topic", + "temperature_high_command_template": "Upper temperature command template", + "temperature_high_command_topic": "Upper temperature command topic", + "temperature_high_state_template": "Upper temperature state template", + "temperature_high_state_topic": "Upper temperature state topic", + "temperature_low_command_template": "Lower temperature command template", + "temperature_low_command_topic": "Lower temperature command topic", + "temperature_low_state_template": "Lower temperature state template", + "temperature_low_state_topic": "Lower temperature state topic", + "temperature_state_template": "Temperature state template", + "temperature_state_topic": "Temperature state topic" + }, + "data_description": { + "initial": "The device initializes with this target temperature.", + "max_temp": "The maximum target temperature that can be set.", + "min_temp": "The minimum target temperature that can be set.", + "precision": "The precision in degrees the thermostat is working at.", + "temp_step": "The target temperature step in degrees Celsius or Fahrenheit.", + "temperature_command_template": "A [template]({command_templating_url}) to compose the payload to be published at the temperature command topic.", + "temperature_command_topic": "The MQTT topic to publish commands to change the target temperature. [Learn more.]({url}#temperature_command_topic)", + "temperature_high_command_template": "A [template]({command_templating_url}) to compose the payload to be published at the upper temperature command topic.", + "temperature_high_command_topic": "The MQTT topic to publish commands to change the climate upper target temperature. [Learn more.]({url}#temperature_high_command_topic)", + "temperature_high_state_template": "A [template]({value_templating_url}) to render the value received on the upper temperature state topic with.", + "temperature_high_state_topic": "The MQTT topic to subscribe for changes of the upper target temperature. [Learn more.]({url}#temperature_high_state_topic)", + "temperature_low_command_template": "A [template]({command_templating_url}) to compose the payload to be published at the lower temperature command topic.", + "temperature_low_command_topic": "The MQTT topic to publish commands to change the climate lower target temperature. [Learn more.]({url}#temperature_low_command_topic)", + "temperature_low_state_template": "A [template]({value_templating_url}) to render the value received on the lower temperature state topic with.", + "temperature_low_state_topic": "The MQTT topic to subscribe for changes of the lower target temperature. [Learn more.]({url}#temperature_low_state_topic)", + "temperature_state_template": "A [template]({value_templating_url}) to render the value received on the temperature state topic with.", + "temperature_state_topic": "The MQTT topic to subscribe for changes of the target temperature. [Learn more.]({url}#temperature_state_topic)" + }, + "name": "Target temperature settings" + }, + "text_other_settings": { + "data": { + "max": "Maximum length", + "min": "Minimum length", + "mode": "Mode", + "pattern": "Pattern" + }, + "data_description": { + "max": "Maximum length of the text input", + "min": "Minimum length of the text input", + "mode": "Mode of the text input", + "pattern": "A valid regex pattern" + }, + "name": "Other text entity settings" + }, + "valve_payload_settings": { + "data": { + "payload_close": "Payload \"close\"", + "payload_open": "Payload \"open\"", + "payload_stop": "Payload \"stop\"", + "state_closed": "State \"closed\"", + "state_closing": "State \"closing\"", + "state_open": "State \"open\"", + "state_opening": "State \"opening\"" + }, + "data_description": { + "payload_close": "The payload sent when a \"close\" command is issued.", + "payload_open": "The payload sent when an \"open\" command is issued.", + "payload_stop": "The payload sent when a \"stop\" command is issued. Set this payload only if your valve supports the \"stop\" action.", + "state_closed": "The payload received at the state topic that represents the \"closed\" state.", + "state_closing": "The payload received at the state topic that represents the \"closing\" state.", + "state_open": "The payload received at the state topic that represents the \"open\" state.", + "state_opening": "The payload received at the state topic that represents the \"opening\" state." + }, + "name": "Valve payload settings" + }, + "water_heater_power_settings": { + "data": { + "payload_off": "[%key:component::mqtt::config_subentries::device::step::mqtt_platform_config::data::payload_off%]", + "payload_on": "[%key:component::mqtt::config_subentries::device::step::mqtt_platform_config::data::payload_on%]", + "power_command_template": "[%key:component::mqtt::config_subentries::device::step::mqtt_platform_config::sections::climate_power_settings::data::power_command_template%]", + "power_command_topic": "[%key:component::mqtt::config_subentries::device::step::mqtt_platform_config::sections::climate_power_settings::data::power_command_topic%]" + }, + "data_description": { + "payload_off": "[%key:component::mqtt::config_subentries::device::step::mqtt_platform_config::data_description::payload_off%]", + "payload_on": "[%key:component::mqtt::config_subentries::device::step::mqtt_platform_config::data_description::payload_on%]", + "power_command_template": "[%key:component::mqtt::config_subentries::device::step::mqtt_platform_config::sections::climate_power_settings::data_description::power_command_template%]", + "power_command_topic": "The MQTT topic to publish commands to change the water heater power state. Sends the payload configured with payload \"on\" or payload \"off\". [Learn more.]({url}#power_command_topic)" + }, + "name": "Power settings" + } + }, + "title": "Configure MQTT device \"{mqtt_device}\"" + }, + "summary_menu": { + "description": "Entities set up:\n{mqtt_items}\n\nDecide what to do next:", + "menu_options": { + "availability": "Configure availability", + "delete_entity": "Delete an entity", + "device": "Update device properties", + "entity": "Add another entity to \"{mqtt_device}\"", + "export": "Export MQTT device configuration", + "save_changes": "Save changes", + "update_entity": "Update entity properties" + }, + "title": "Reconfigure \"{mqtt_device}\"" + }, + "update_entity": { + "data": { + "component": "Entity" + }, + "data_description": { + "component": "Select the entity you want to update." + }, + "description": "Select the entity you want to update", + "title": "Select entity" + } + } + } + }, + "device_automation": { + "trigger_subtype": { + "button_1": "First button", + "button_2": "Second button", + "button_3": "Third button", + "button_4": "Fourth button", + "button_5": "Fifth button", + "button_6": "Sixth button", + "turn_off": "[%key:common::action::turn_off%]", + "turn_on": "[%key:common::action::turn_on%]" + }, + "trigger_type": { + "button_double_press": "\"{subtype}\" double clicked", + "button_long_press": "\"{subtype}\" continuously pressed", + "button_long_release": "\"{subtype}\" released after long press", + "button_quadruple_press": "\"{subtype}\" quadruple clicked", + "button_quintuple_press": "\"{subtype}\" quintuple clicked", + "button_short_press": "\"{subtype}\" pressed", + "button_short_release": "\"{subtype}\" released", + "button_triple_press": "\"{subtype}\" triple clicked" + } + }, + "exceptions": { + "addon_start_failed": { + "message": "Failed to correctly start {addon} app." + }, + "command_template_error": { + "message": "Parsing template `{command_template}` for entity `{entity_id}` failed with error: {error}." + }, + "invalid_platform_config_message": { + "message": "Reloading YAML config for manually configured MQTT `{domain}` item failed. Message: {message}" + }, + "invalid_publish_topic": { + "message": "Unable to publish: topic template `{topic_template}` produced an invalid topic `{topic}` after rendering ({error})" + }, + "mqtt_broker_error": { + "message": "Error talking to MQTT: {error_message}." + }, + "mqtt_max_subscription_id_reached": { + "message": "MQTT Subscription ID limit reached. Cannot generate more IDs to subscribe." + }, + "mqtt_message_expiry_interval_not_supported": { + "message": "Publishing to topic {topic} with a Message Expiry Interval is not supported for protocol version {protocol}." + }, + "mqtt_not_enabled_cannot_subscribe": { + "message": "Cannot subscribe to topic \"{topic}\" because MQTT is not enabled, make sure MQTT is set up correctly." + }, + "mqtt_not_setup_cannot_publish": { + "message": "Cannot publish to topic \"{topic}\", make sure MQTT is set up correctly." + }, + "mqtt_not_setup_cannot_subscribe": { + "message": "Cannot subscribe to topic \"{topic}\", make sure MQTT is set up correctly." + }, + "mqtt_not_setup_cannot_unsubscribe_twice": { + "message": "Cannot unsubscribe topic \"{topic}\" twice." + }, + "mqtt_topic_not_a_string": { + "message": "Topic needs to be a string! Got: {topic}." + }, + "mqtt_trigger_cannot_remove_twice": { + "message": "Can't remove trigger twice." + } + }, + "issues": { + "invalid_platform_config": { + "description": "Home Assistant detected an invalid config for a manually configured item.\n\nPlatform domain: **{domain}**\nConfiguration file: **{config_file}**\nNear line: **{line}**\nConfiguration found:\n```yaml\n{config}\n```\nError: **{error}**.\n\nMake sure the configuration is valid and [reload](/config/tools/yaml) the manually configured MQTT items or restart Home Assistant to fix this issue.", + "title": "Invalid config found for MQTT {domain} item" + }, + "protocol_5_migration": { + "description": "The automatic migration to MQTT protocol version 5 failed. The currently configured protocol version for MQTT broker {broker} is {protocol}, but this protocol version is deprecated, and support for it will be removed.\n\nMake sure your broker supports protocol version 5. Update your MQTT broker's connection settings, and restart Home Assistant to fix this issue.", + "title": "MQTT protocol migration failed" + }, + "subentry_migration_discovery": { + "fix_flow": { + "step": { + "confirm": { + "description": "Exported MQTT device \"{name}\" identified via MQTT discovery. Select **Submit** to confirm that the MQTT device is to be migrated to the main MQTT configuration, and to remove the existing MQTT device subentry. Make sure that the discovery is retained at the MQTT broker, or is resent after the subentry is removed, so that the MQTT device will be set up correctly. As an alternative you can change the device identifiers and entity unique ID-s in your MQTT discovery configuration payload, and cancel this repair if you want to keep the MQTT device subentry.", + "title": "[%key:component::mqtt::issues::subentry_migration_discovery::title%]" + } + } + }, + "title": "MQTT device \"{name}\" subentry migration to MQTT discovery" + }, + "subentry_migration_yaml": { + "fix_flow": { + "step": { + "confirm": { + "description": "Exported MQTT device \"{name}\" identified in YAML configuration. Select **Submit** to confirm that the MQTT device is to be migrated to main MQTT config entry, and to remove the existing MQTT device subentry. As an alternative you can change the device identifiers and entity unique ID-s in your configuration.yaml file, and cancel this repair if you want to keep the MQTT device subentry.", + "title": "[%key:component::mqtt::issues::subentry_migration_yaml::title%]" + } + } + }, + "title": "MQTT device \"{name}\" subentry migration to YAML" + }, + "yaml_setup_without_active_setup": { + "description": "Home Assistant detected manually configured MQTT items, but these items cannot be loaded because MQTT is not set up correctly. Make sure the MQTT broker is set up correctly, or remove the MQTT configuration from your `configuration.yaml` file and restart Home Assistant to fix this issue.", + "title": "MQTT is not set up correctly" + } + }, + "options": { + "error": { + "bad_birth": "[%key:component::mqtt::config::error::bad_birth%]", + "bad_certificate": "[%key:component::mqtt::config::error::bad_certificate%]", + "bad_client_cert": "[%key:component::mqtt::config::error::bad_client_cert%]", + "bad_client_cert_key": "[%key:component::mqtt::config::error::bad_client_cert_key%]", + "bad_discovery_prefix": "[%key:component::mqtt::config::error::bad_discovery_prefix%]", + "bad_will": "[%key:component::mqtt::config::error::bad_will%]", + "bad_ws_headers": "[%key:component::mqtt::config::error::bad_ws_headers%]", + "cannot_connect": "[%key:common::config_flow::error::cannot_connect%]", + "client_key_error": "[%key:component::mqtt::config::error::client_key_error%]", + "invalid_inclusion": "[%key:component::mqtt::config::error::invalid_inclusion%]" + }, + "step": { + "options": { + "data": { + "birth_enable": "Enable birth message", + "birth_payload": "Birth message payload", + "birth_qos": "Birth message QoS", + "birth_retain": "Birth message retain", + "birth_topic": "Birth message topic", + "discovery": "Enable discovery", + "discovery_prefix": "Discovery prefix", + "discovery_qos": "Discovery QoS", + "will_enable": "Enable will message", + "will_payload": "Will message payload", + "will_qos": "Will message QoS", + "will_retain": "Will message retain", + "will_topic": "Will message topic" + }, + "data_description": { + "birth_enable": "When set, Home Assistant will publish an online message to your MQTT broker when MQTT is ready.", + "birth_payload": "The \"birth\" message that is published when MQTT is ready and connected.", + "birth_qos": "The quality of service of the \"birth\" message that is published when MQTT is ready and connected", + "birth_retain": "When set, Home Assistant will retain the \"birth\" message published to your MQTT broker.", + "birth_topic": "The MQTT topic where Home Assistant will publish a \"birth\" message.", + "discovery": "Option to enable MQTT automatic discovery.", + "discovery_prefix": "The prefix of configuration topics the MQTT integration will subscribe to.", + "discovery_qos": "The quality of service for discovery subscriptions to your MQTT broker.", + "will_enable": "When set, Home Assistant will ask your broker to publish a \"will\" message when MQTT is stopped or when it loses the connection to your broker.", + "will_payload": "The message your MQTT broker \"will\" publish when the MQTT integration is stopped or when the connection is lost.", + "will_qos": "The quality of service of the \"will\" message that is published by your MQTT broker.", + "will_retain": "When set, your MQTT broker will retain the \"will\" message.", + "will_topic": "The MQTT topic your MQTT broker will publish a \"will\" message to." + }, + "description": "Discovery - If discovery is enabled (recommended), Home Assistant will automatically discover devices and entities which publish their configuration on the MQTT broker. If discovery is disabled, all configuration must be done manually.\nDiscovery prefix - The prefix a configuration topic for automatic discovery must start with.\nBirth message - The birth message will be sent each time Home Assistant (re)connects to the MQTT broker.\nWill message - The will message will be sent each time Home Assistant loses its connection to the broker, both in case of a clean (e.g. Home Assistant shutting down) and in case of an unclean (e.g. Home Assistant crashing or losing its network connection) disconnect.", + "title": "MQTT options" + } + } + }, + "selector": { + "alarm_control_panel_code_mode": { + "options": { + "local_code": "Local code validation", + "remote_code": "Numeric remote code validation", + "remote_code_text": "Text remote code validation" + } + }, + "alarm_control_panel_features": { + "options": { + "arm_away": "[%key:component::alarm_control_panel::services::alarm_arm_away::name%]", + "arm_custom_bypass": "[%key:component::alarm_control_panel::services::alarm_arm_custom_bypass::name%]", + "arm_home": "[%key:component::alarm_control_panel::services::alarm_arm_home::name%]", + "arm_night": "[%key:component::alarm_control_panel::services::alarm_arm_night::name%]", + "arm_vacation": "[%key:component::alarm_control_panel::services::alarm_arm_vacation::name%]", + "trigger": "[%key:component::alarm_control_panel::services::alarm_trigger::name%]" + } + }, + "climate_modes": { + "options": { + "auto": "[%key:common::state::auto%]", + "cool": "[%key:component::climate::entity_component::_::state::cool%]", + "dry": "[%key:component::climate::entity_component::_::state::dry%]", + "fan_only": "[%key:component::climate::entity_component::_::state::fan_only%]", + "heat": "[%key:component::climate::entity_component::_::state::heat%]", + "heat_cool": "[%key:component::climate::entity_component::_::state::heat_cool%]", + "off": "[%key:common::state::off%]" + } + }, + "entity_category": { + "options": { + "config": "Config", + "diagnostic": "Diagnostic" + } + }, + "image_encoding": { + "options": { + "b64": "Base64 encoding", + "raw": "Raw data" + } + }, + "image_processing_mode": { + "options": { + "image_data": "Image data is received", + "image_url": "Image URL is received" + } + }, + "light_schema": { + "options": { + "basic": "Default schema", + "json": "JSON", + "template": "Template" + } + }, + "number_mode": { + "options": { + "auto": "[%key:component::number::entity_component::_::state_attributes::mode::state::auto%]", + "box": "[%key:component::number::entity_component::_::state_attributes::mode::state::box%]", + "slider": "[%key:component::number::entity_component::_::state_attributes::mode::state::slider%]" + } + }, + "on_command_type": { + "options": { + "brightness": "Brightness", + "first": "First", + "last": "Last" + } + }, + "platform": { + "options": { + "alarm_control_panel": "[%key:component::alarm_control_panel::title%]", + "binary_sensor": "[%key:component::binary_sensor::title%]", + "button": "[%key:component::button::title%]", + "climate": "[%key:component::climate::title%]", + "cover": "[%key:component::cover::title%]", + "date": "[%key:component::date::title%]", + "datetime": "[%key:component::datetime::title%]", + "fan": "[%key:component::fan::title%]", + "image": "[%key:component::image::title%]", + "light": "[%key:component::light::title%]", + "lock": "[%key:component::lock::title%]", + "notify": "[%key:component::notify::title%]", + "number": "[%key:component::number::title%]", + "select": "[%key:component::select::title%]", + "sensor": "[%key:component::sensor::title%]", + "siren": "[%key:component::siren::title%]", + "switch": "[%key:component::switch::title%]", + "text": "[%key:component::text::title%]", + "time": "[%key:component::time::title%]", + "valve": "[%key:component::valve::title%]", + "water_heater": "[%key:component::water_heater::title%]" + } + }, + "set_ca_cert": { + "options": { + "auto": "[%key:common::state::auto%]", + "custom": "Custom", + "off": "[%key:common::state::off%]" + } + }, + "supported_color_modes": { + "options": { + "brightness": "[%key:component::light::entity_component::_::state_attributes::color_mode::state::brightness%]", + "color_temp": "[%key:component::light::entity_component::_::state_attributes::color_mode::state::color_temp%]", + "hs": "[%key:component::light::entity_component::_::state_attributes::color_mode::state::hs%]", + "onoff": "[%key:component::light::entity_component::_::state_attributes::color_mode::state::onoff%]", + "rgb": "[%key:component::light::entity_component::_::state_attributes::color_mode::state::rgb%]", + "rgbw": "[%key:component::light::entity_component::_::state_attributes::color_mode::state::rgbw%]", + "rgbww": "[%key:component::light::entity_component::_::state_attributes::color_mode::state::rgbww%]", + "white": "[%key:component::light::entity_component::_::state_attributes::color_mode::state::white%]", + "xy": "[%key:component::light::entity_component::_::state_attributes::color_mode::state::xy%]" + } + }, + "target_temperature_feature": { + "options": { + "high_low": "Upper/lower target temperature", + "none": "No target temperature", + "single": "Single target temperature" + } + }, + "text_mode": { + "options": { + "password": "[%key:common::config_flow::data::password%]", + "text": "[%key:component::text::entity_component::_::state_attributes::mode::state::text%]" + } + }, + "water_heater_modes": { + "options": { + "auto": "[%key:common::state::auto%]", + "eco": "[%key:component::water_heater::entity_component::_::state::eco%]", + "electric": "[%key:component::water_heater::entity_component::_::state::electric%]", + "gas": "[%key:component::water_heater::entity_component::_::state::gas%]", + "heat_pump": "[%key:component::water_heater::entity_component::_::state::heat_pump%]", + "high_demand": "[%key:component::water_heater::entity_component::_::state::high_demand%]", + "off": "[%key:common::state::off%]", + "performance": "[%key:component::water_heater::entity_component::_::state::performance%]" + } + } + }, + "services": { + "dump": { + "description": "Writes all messages on a specific topic into the `vmqtt_dump.txt` file in your configuration folder.", + "fields": { + "duration": { + "description": "How long we should listen for messages in seconds.", + "name": "Duration" + }, + "topic": { + "description": "Topic to listen to.", + "name": "[%key:component::mqtt::services::publish::fields::topic::name%]" + } + }, + "name": "Export" + }, + "publish": { + "description": "Publishes a message to an MQTT topic.", + "fields": { + "evaluate_payload": { + "description": "If 'Payload' is a Python bytes literal, evaluate the bytes literal and publish the raw data.", + "name": "Evaluate payload" + }, + "message_expiry_interval": { + "description": "Expires a publish message after the interval in case the device subscriber was temporarily offline, or the message was set as a retained message. Only supported with MQTT protocol version 5.0.", + "name": "Message Expiry Interval" + }, + "payload": { + "description": "The payload to publish. Publishes an empty message if not provided.", + "name": "Payload" + }, + "qos": { + "description": "Quality of Service to use. 0: At most once. 1: At least once. 2: Exactly once.", + "name": "QoS" + }, + "retain": { + "description": "If the message should have the retain flag set. If set, the broker stores the most recent message on a topic.", + "name": "Retain" + }, + "topic": { + "description": "Topic to publish to.", + "name": "Topic" + } + }, + "name": "Publish", + "sections": { + "publish_options": { + "name": "Publish options" + } + } + }, + "reload": { + "description": "Reloads MQTT entities from the YAML-configuration.", + "name": "[%key:common::action::reload%]" + } + }, + "triggers": { + "_": { + "description": "Triggers after a specific message is received on a given MQTT topic.", + "fields": { + "payload": { + "description": "The payload to trigger on.", + "name": "Payload" + }, + "topic": { + "description": "MQTT topic to listen to.", + "name": "Topic" + } + }, + "name": "MQTT message received" + } + } +} diff --git a/custom_components/vmqtt/subscription.py b/custom_components/vmqtt/subscription.py new file mode 100644 index 0000000..c888dd2 --- /dev/null +++ b/custom_components/vmqtt/subscription.py @@ -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={}) diff --git a/custom_components/vmqtt/switch.py b/custom_components/vmqtt/switch.py new file mode 100644 index 0000000..b4ac6cc --- /dev/null +++ b/custom_components/vmqtt/switch.py @@ -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() diff --git a/custom_components/vmqtt/tag.py b/custom_components/vmqtt/tag.py new file mode 100644 index 0000000..aabef57 --- /dev/null +++ b/custom_components/vmqtt/tag.py @@ -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] diff --git a/custom_components/vmqtt/text.py b/custom_components/vmqtt/text.py new file mode 100644 index 0000000..9cd40fd --- /dev/null +++ b/custom_components/vmqtt/text.py @@ -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() diff --git a/custom_components/vmqtt/time.py b/custom_components/vmqtt/time.py new file mode 100644 index 0000000..00bceac --- /dev/null +++ b/custom_components/vmqtt/time.py @@ -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() diff --git a/custom_components/vmqtt/translations/en.json b/custom_components/vmqtt/translations/en.json new file mode 100644 index 0000000..90d8982 --- /dev/null +++ b/custom_components/vmqtt/translations/en.json @@ -0,0 +1,1428 @@ +{ + "config": { + "abort": { + "addon_connection_failed": "Failed to connect to the {addon} app. Check the app status and try again later.", + "addon_info_failed": "Failed get info for the {addon} app.", + "addon_install_failed": "Failed to install the {addon} app.", + "addon_start_failed": "Failed to start the {addon} app.", + "already_configured": "[%key:common::config_flow::abort::already_configured_service%]" + }, + "error": { + "bad_birth": "Invalid birth topic", + "bad_certificate": "The CA certificate is invalid", + "bad_client_cert": "Invalid client certificate, ensure a valid file is supplied", + "bad_client_cert_key": "Client certificate and private key are not a valid pair", + "bad_discovery_prefix": "Invalid discovery prefix", + "bad_will": "Invalid will topic", + "bad_ws_headers": "Supply valid HTTP headers as a JSON object", + "cannot_connect": "[%key:common::config_flow::error::cannot_connect%]", + "client_key_error": "Invalid private key file or invalid password supplied", + "invalid_auth": "[%key:common::config_flow::error::invalid_auth%]", + "invalid_inclusion": "The client certificate and private key must be configured together" + }, + "step": { + "broker": { + "data": { + "broker": "Broker", + "password": "[%key:common::config_flow::data::password%]", + "port": "[%key:common::config_flow::data::port%]", + "protocol": "MQTT protocol", + "username": "[%key:common::config_flow::data::username%]" + }, + "data_description": { + "broker": "The hostname or IP address of your MQTT broker.", + "password": "The password to log in to your MQTT broker.", + "port": "The port your MQTT broker listens to. For example 1883.", + "protocol": "The MQTT protocol version that is used. Note that Home Assistant will silently change to version 5 if your broker supports it.", + "username": "The username to log in to your MQTT broker." + }, + "description": "Please enter the connection information of your MQTT broker.", + "sections": { + "other_settings": { + "data": { + "certificate": "Upload custom CA certificate file", + "client_cert": "Upload client certificate file", + "client_id": "Client ID (leave empty for a randomly generated one)", + "client_key": "Upload private key file", + "client_key_password": "[%key:common::config_flow::data::password%]", + "keepalive": "The time between sending keep alive messages", + "set_ca_cert": "Broker certificate validation", + "set_client_cert": "Use a client certificate", + "tls_insecure": "Ignore broker certificate validation", + "transport": "MQTT transport", + "ws_headers": "WebSocket headers in JSON format", + "ws_path": "WebSocket path" + }, + "data_description": { + "certificate": "The custom CA certificate file to validate your MQTT broker's certificate.", + "client_cert": "The client certificate to authenticate against your MQTT broker.", + "client_id": "The unique ID to identify the Home Assistant MQTT API as MQTT client. It is recommended to leave this option blank.", + "client_key": "The private key file that belongs to your client certificate.", + "client_key_password": "The password for the private key file (if set).", + "keepalive": "A value less than 90 seconds is advised. Defaults to 60 seconds.", + "set_ca_cert": "When already set to **Custom**, a custom CA validation certificate is configured. Select **Auto** for automatic CA validation, or upload a custom CA certificate, to allow validating your MQTT broker's certificate.", + "set_client_cert": "When already selected, client certificate authentication is enabled. Upload a client certificate and key to enable.", + "tls_insecure": "Option to ignore validation of your MQTT broker's certificate.", + "transport": "The transport to be used for the connection to your MQTT broker.", + "ws_headers": "The WebSocket headers to pass through the WebSocket-based connection to your MQTT broker.", + "ws_path": "The WebSocket path to be used for the connection to your MQTT broker." + }, + "name": "Other settings" + } + } + }, + "hassio_confirm": { + "description": "Do you want to configure Home Assistant to connect to the MQTT broker provided by the {addon} app?", + "title": "MQTT broker via Home Assistant app" + }, + "install_addon": { + "title": "Installing app" + }, + "reauth_confirm": { + "data": { + "password": "[%key:common::config_flow::data::password%]", + "username": "[%key:common::config_flow::data::username%]" + }, + "data_description": { + "password": "[%key:component::mqtt::config::step::broker::data_description::password%]", + "username": "[%key:component::mqtt::config::step::broker::data_description::username%]" + }, + "description": "The MQTT broker reported an authentication error. Please confirm the broker's correct username and password.", + "title": "Re-authentication required with the MQTT broker" + }, + "start_addon": { + "title": "Starting app" + }, + "user": { + "description": "Please choose how you want to connect to the MQTT broker:", + "menu_options": { + "addon": "Use the official {addon} app.", + "broker": "Manually enter the MQTT broker connection details" + } + } + } + }, + "config_subentries": { + "device": { + "create_entry": { + "default": "MQTT device with {platform} entity \"{entity}\" was set up successfully.\n\nNote that you can reconfigure the MQTT device at any time, e.g. to add more entities." + }, + "entry_type": "MQTT device", + "error": { + "cover_get_and_set_position_must_be_set_together": "The get position and set position topic options must be set together", + "cover_get_position_template_must_be_used_with_get_position_topic": "The position value template must be used together with the position state topic", + "cover_set_position_template_must_be_used_with_set_position_topic": "The set position template must be used with the set position topic", + "cover_tilt_command_template_must_be_used_with_tilt_command_topic": "The tilt command template must be used with the tilt command topic", + "cover_tilt_status_template_must_be_used_with_tilt_status_topic": "The tilt value template must be used with the tilt status topic", + "cover_value_template_must_be_used_with_state_topic": "The value template must be used with the state topic option", + "empty_list_not_allowed": "Empty list is not allowed. Add at least one item", + "fan_preset_mode_reset_in_preset_modes_list": "Payload \"reset preset mode\" is not a valid as a preset mode", + "fan_speed_range_max_must_be_greater_than_speed_range_min": "Speed range max must be greater than speed range min", + "invalid_input": "Invalid value", + "invalid_regular_expression": "Must be a valid regular expression", + "invalid_subscribe_topic": "Invalid subscribe topic", + "invalid_supported_color_modes": "Invalid supported color modes selection", + "invalid_template": "Invalid template", + "invalid_uom": "The unit of measurement \"{unit_of_measurement}\" is not supported by the selected device class, please either remove the device class, select a device class which supports \"{unit_of_measurement}\", or pick a supported unit of measurement from the list", + "invalid_uom_for_state_class": "The unit of measurement \"{unit_of_measurement}\" is not supported by the selected state class, please either remove the state class, select a state class which supports \"{unit_of_measurement}\", or pick a supported unit of measurement from the list", + "invalid_url": "Invalid URL", + "last_reset_not_with_state_class_total": "The last reset value template option should be used with state class 'Total' only", + "max_below_min": "Max value should be greater or equal to min value", + "max_below_min_humidity": "Max humidity value should be greater than min humidity value", + "max_below_min_kelvin": "Max Kelvin value should be greater than min Kelvin value", + "max_below_min_temperature": "Max temperature value should be greater than min temperature value", + "options_device_class_enum": "The 'Options' setting must be used with the Enumeration device class. If you continue, the existing options will be reset", + "options_not_allowed_with_state_class_or_uom": "The 'Options' setting is not allowed when state class or unit of measurement are used", + "options_with_enum_device_class": "Configure options for the enumeration sensor", + "preset_mode_none_not_allowed": "Preset \"none\" is not a valid preset mode", + "uom_required_for_device_class": "The selected device class requires a unit" + }, + "initiate_flow": { + "reconfigure": "Reconfigure MQTT device", + "user": "Add MQTT device" + }, + "step": { + "availability": { + "data": { + "availability_template": "Availability template", + "availability_topic": "Availability topic", + "payload_available": "Payload available", + "payload_not_available": "Payload not available" + }, + "data_description": { + "availability_template": "A [template]({value_templating_url}) to render the availability payload received on the availability topic", + "availability_topic": "Topic to receive the availability payload on", + "payload_available": "The payload that indicates the device is available (defaults to 'online')", + "payload_not_available": "The payload that indicates the device is not available (defaults to 'offline')" + }, + "description": "The availability feature allows a device to report its availability.", + "title": "Availability options" + }, + "delete_entity": { + "data": { + "component": "Entity" + }, + "data_description": { + "component": "Select the entity you want to delete. At least one entity is required." + }, + "description": "Delete an entity. The entity will be removed from the device. Removing an entity will break any automations or scripts that depend on it.", + "title": "Delete entity" + }, + "device": { + "data": { + "configuration_url": "Configuration URL", + "manufacturer": "Manufacturer", + "model": "Model", + "model_id": "Model ID", + "name": "[%key:common::config_flow::data::name%]" + }, + "data_description": { + "configuration_url": "A link to the webpage that can manage the configuration of this device. Can be either a 'http://', 'https://' or an internal 'homeassistant://' URL.", + "manufacturer": "E.g. Cleanmaster Ltd.", + "model": "E.g. 'Cleanmaster Pro'.", + "model_id": "E.g. '123NK2PRO'.", + "name": "The name of the manually added MQTT device." + }, + "description": "Enter the MQTT device details:", + "sections": { + "mqtt_settings": { + "data": { + "message_expiry_interval": "Message Expiry Interval", + "qos": "QoS" + }, + "data_description": { + "message_expiry_interval": "Retention time interval for published message.", + "qos": "The Quality of Service value the device's entities should use." + }, + "name": "MQTT settings" + }, + "other_settings": { + "data": { + "hw_version": "Hardware version", + "sw_version": "Software version" + }, + "data_description": { + "hw_version": "The hardware version of the device. E.g. 'v1.0 rev a'.", + "sw_version": "The software version of the device. E.g. '2025.1.0'." + }, + "name": "Other device settings" + } + }, + "title": "Configure MQTT device details" + }, + "entity": { + "data": { + "entity_picture": "Entity picture", + "name": "Entity name", + "platform": "Type of entity" + }, + "data_description": { + "entity_picture": "An URL to a picture to be assigned.", + "name": "The name of the entity. Leave empty to set it to `None` to [mark it as main feature of the MQTT device]({naming_entities_url}).", + "platform": "The type of the entity to configure." + }, + "description": "Configure the basic {platform_label}entity settings{entity_name_label}", + "title": "Configure MQTT device \"{mqtt_device}\"" + }, + "entity_platform_config": { + "data": { + "alarm_control_panel_code_mode": "Alarm code validation mode", + "climate_feature_action": "Current action support", + "climate_feature_current_humidity": "Current humidity support", + "climate_feature_current_temperature": "Current temperature support", + "climate_feature_fan_modes": "Fan mode support", + "climate_feature_power": "Power on/off support", + "climate_feature_preset_modes": "[%key:component::mqtt::config_subentries::device::step::entity_platform_config::data::fan_feature_preset_modes%]", + "climate_feature_swing_horizontal_modes": "Horizontal swing mode support", + "climate_feature_swing_modes": "Swing mode support", + "climate_feature_target_humidity": "Target humidity support", + "climate_feature_target_temperature": "Target temperature support", + "device_class": "Device class", + "entity_category": "Entity category", + "fan_feature_direction": "Direction support", + "fan_feature_oscillation": "Oscillation support", + "fan_feature_preset_modes": "Preset modes support", + "fan_feature_speed": "Speed support", + "image_processing_mode": "Image processing mode", + "options": "Add option", + "reports_position": "Reports position", + "schema": "Schema", + "state_class": "State class", + "suggested_display_precision": "Suggested display precision", + "supported_features": "Supported features", + "temperature_unit": "Temperature unit", + "unit_of_measurement": "Unit of measurement", + "water_heater_feature_current_temperature": "[%key:component::mqtt::config_subentries::device::step::entity_platform_config::data::climate_feature_current_temperature%]", + "water_heater_feature_power": "[%key:component::mqtt::config_subentries::device::step::entity_platform_config::data::climate_feature_power%]" + }, + "data_description": { + "alarm_control_panel_code_mode": "Configures how the alarm control panel validates the code. A local code is configured with the entity and is validated by Home Assistant. A remote code is sent to the device and validated remotely. [Learn more.]({url}#code)", + "climate_feature_action": "The climate supports reporting the current action.", + "climate_feature_current_humidity": "The climate supports reporting the current humidity.", + "climate_feature_current_temperature": "The climate supports reporting the current temperature.", + "climate_feature_fan_modes": "The climate supports fan modes.", + "climate_feature_power": "The climate supports the power \"on\" and \"off\" commands.", + "climate_feature_preset_modes": "The climate supports preset modes.", + "climate_feature_swing_horizontal_modes": "The climate supports horizontal swing modes.", + "climate_feature_swing_modes": "The climate supports swing modes.", + "climate_feature_target_humidity": "The climate supports setting the target humidity.", + "climate_feature_target_temperature": "The climate supports setting the target temperature.", + "device_class": "The device class of the {platform} entity. [Learn more.]({url}#device_class)", + "entity_category": "Allows marking an entity as device configuration or diagnostics. An entity with a category will not be exposed to cloud, Alexa, or Google Assistant components, nor included in indirect action calls to devices or areas. Sensor entities cannot be assigned a device configuration class. [Learn more.]({registry_properties_url})", + "fan_feature_direction": "The fan supports direction.", + "fan_feature_oscillation": "The fan supports oscillation.", + "fan_feature_preset_modes": "The fan supports preset modes.", + "fan_feature_speed": "The fan supports multiple speeds.", + "image_processing_mode": "Select how the image data is received.", + "options": "Options for allowed sensor state values. The sensor’s Device class must be set to Enumeration. The 'Options' setting cannot be used together with State class or Unit of measurement.", + "reports_position": "Set this option if the valve reports the position or supports setting the position. Enabling this option will cause the position to be published instead of a payload defined by payload \"open\", payload \"close\" or payload \"stop\". When receiving messages, state topic will accept numeric payloads or one of the configured state messages.", + "schema": "The schema to use. [Learn more.]({url}#comparison-of-light-mqtt-schemas)", + "state_class": "The [state class]({available_state_classes_url}) of the sensor. [Learn more.]({url}#state_class)", + "suggested_display_precision": "The number of decimals which should be used in the {platform} entity state after rounding. [Learn more.]({url}#suggested_display_precision)", + "supported_features": "The features that the entity supports.", + "temperature_unit": "This determines the native unit of measurement the MQTT device works with.", + "unit_of_measurement": "Defines the unit of measurement, if any.", + "water_heater_feature_current_temperature": "The water heater supports reporting the current temperature.", + "water_heater_feature_power": "The water heater supports the power \"on\" and \"off\" commands." + }, + "description": "Please configure specific details for {platform} entity \"{entity}\":", + "sections": { + "other_settings": { + "data": { + "suggested_display_precision": "Suggested display precision" + }, + "data_description": { + "suggested_display_precision": "The number of decimals which should be used in the {platform} entity state after rounding. [Learn more.]({url}#suggested_display_precision)" + }, + "name": "Other settings" + } + }, + "title": "Configure MQTT device \"{mqtt_device}\"" + }, + "export": { + "description": "An export allows you to migrate the MQTT device configuration to YAML-based configuration or MQTT discovery. The configuration export can also be helpful for troubleshooting.", + "menu_options": { + "export_discovery": "Export MQTT discovery information", + "export_yaml": "Export to YAML configuration" + }, + "title": "Export MQTT device config" + }, + "export_discovery": { + "data": { + "discovery_payload": "Discovery payload:", + "discovery_topic": "Discovery topic" + }, + "data_description": { + "discovery_payload": "The JSON [discovery payload]({url}#device-discovery-payload) that contains information about the MQTT device.", + "discovery_topic": "The [discovery topic]({url}#discovery-topic) to publish the discovery payload, used to trigger MQTT discovery. An empty payload published to this topic will remove the device and discovered entities." + }, + "description": "To allow setup via MQTT [discovery]({url}#device-discovery-payload), the discovery payload needs to be published to the discovery topic. Copy the information from the fields below. Home Assistant will detect if the setup of the MQTT device was tried via MQTT discovery instead, and will offer a repair flow to clean up the redundant subentry. You can also choose to change the identifiers if you do not want to remove the subentry.", + "title": "[%key:component::mqtt::config_subentries::device::step::export::title%]" + }, + "export_yaml": { + "data": { + "yaml": "Copy the YAML configuration below:" + }, + "data_description": { + "yaml": "Place YAML configuration in your [configuration.yaml]({url}#yaml-configuration-listed-per-item)." + }, + "description": "You can copy the configuration below and place it your configuration.yaml file. Home Assistant will detect if the setup of the MQTT device was tried via YAML instead, and will offer a repair flow to clean up the redundant subentry. You can also choose to change the identifiers if you do not want to remove the subentry.", + "title": "[%key:component::mqtt::config_subentries::device::step::export::title%]" + }, + "mqtt_platform_config": { + "data": { + "available_tones": "Available Tones", + "blue_template": "Blue template", + "brightness_template": "Brightness template", + "code": "Alarm code", + "code_arm_required": "Code arm required", + "code_disarm_required": "Code disarm required", + "code_format": "Code format", + "code_trigger_required": "Code trigger required", + "color_temp_template": "Color temperature template", + "command_off_template": "Command \"off\" template", + "command_on_template": "Command \"on\" template", + "command_template": "Command template", + "command_topic": "Command topic", + "content_type": "Content type", + "force_update": "Force update", + "green_template": "Green template", + "image_encoding": "Image encoding", + "image_topic": "Image topic", + "last_reset_value_template": "Last reset value template", + "max": "Maximum", + "min": "Minimum", + "mode": "Mode", + "mode_command_template": "Operation mode command template", + "mode_command_topic": "Operation mode command topic", + "mode_state_template": "Operation mode value template", + "mode_state_topic": "Operation mode state topic", + "modes": "Supported operation modes", + "on_command_type": "ON command type", + "optimistic": "Optimistic", + "options": "Set options", + "payload_off": "Payload \"off\"", + "payload_on": "Payload \"on\"", + "payload_press": "Payload \"press\"", + "payload_reset": "Payload \"reset\"", + "position_closed": "Position \"closed\"", + "position_open": "Position \"open\"", + "qos": "QoS", + "red_template": "Red template", + "retain": "Retain", + "state_off": "State \"off\"", + "state_on": "State \"on\"", + "state_template": "State template", + "state_topic": "State topic", + "state_value_template": "State value template", + "step": "Step", + "support_duration": "Duration support", + "support_volume_set": "Set volume support", + "supported_color_modes": "Supported color modes", + "timezone": "Time zone", + "url_template": "URL template", + "url_topic": "URL topic", + "value_template": "Value template" + }, + "data_description": { + "available_tones": "The siren supports tones. The `tone` variable will become available for use in the \"Command template\" setting. [Learn more.]({url}#available_tones)", + "blue_template": "[Template]({value_templating_url}) to extract blue color from the state payload value. Expected result of the template is an integer from 0-255 range.", + "brightness_template": "[Template]({value_templating_url}) to extract brightness from the state payload value. Expected result of the template is an integer from 0-255 range.", + "code": "Specifies a code to enable or disable the alarm in the frontend. Note that this blocks sending MQTT message commands to the remote device if the code validation fails. [Learn more.]({url}#code)", + "code_arm_required": "If set, the code is required to arm the alarm. If not set, the code is not validated.", + "code_disarm_required": "If set, the code is required to disarm the alarm. If not set, the code is not validated.", + "code_format": "A regular expression to validate a supplied code when it is set during the action to open, lock or unlock the MQTT lock. [Learn more.]({url}#code_format)", + "code_trigger_required": "If set, the code is required to manually trigger the alarm. If not set, the code is not validated.", + "color_temp_template": "[Template]({value_templating_url}) to extract color temperature in Kelvin from the state payload value. Expected result of the template is an integer.", + "command_off_template": "The [template]({command_templating_url}) for \"off\" state changes. Available variables are: `state` and `transition`.", + "command_on_template": "The [template]({command_templating_url}) for \"on\" state changes. Available variables: `state`, `brightness`, `color_temp`, `red`, `green`, `blue`, `hue`, `sat`, `flash`, `transition` and `effect`. Values `red`, `green`, `blue` and `brightness` are provided as integers from range 0-255. Value of `hue` is provided as float from range 0-360. Value of `sat` is provided as float from range 0-100. Value of `color_temp` is provided as integer representing Kelvin units.", + "command_template": "A [template]({command_templating_url}) to render the payload to be published at the command topic. [Learn more.]({url}#command_template)", + "command_topic": "The publishing topic that will be used to control the {platform} entity. [Learn more.]({url}#command_topic)", + "content_type": "The content type or the image data that is received at the image topic.", + "force_update": "Sends update events even if the value hasn’t changed. Useful if you want to have meaningful value graphs in history. [Learn more.]({url}#force_update)", + "green_template": "[Template]({value_templating_url}) to extract green color from the state payload value. Expected result of the template is an integer from 0-255 range.", + "image_encoding": "Select the encoding of the received image data", + "image_topic": "The MQTT topic subscribed to receive messages containing the image data. [Learn more.]({url}#image_topic)", + "last_reset_value_template": "Defines a [template]({value_templating_url}) to extract the last reset. When Last reset template is set, the State class option must be Total. [Learn more.]({url}#last_reset_value_template)", + "max": "Maximum value. [Learn more.]({url}#max)", + "min": "Minimum value. [Learn more.]({url}#min)", + "mode": "Control how the number should be displayed in the UI. [Learn more.]({url}#mode)", + "mode_command_template": "[Template]({command_templating_url}) to define the operation mode to be sent to the operation mode command topic. [Learn more.]({url}#mode_command_template)", + "mode_command_topic": "The MQTT topic to publish commands to change the operation mode. [Learn more.]({url}#mode_command_topic)", + "mode_state_template": "Defines a [template]({value_templating_url}) to extract the operation mode state. [Learn more.]({url}#mode_state_template)", + "mode_state_topic": "The MQTT topic subscribed to receive operation mode state messages. [Learn more.]({url}#mode_state_topic)", + "modes": "A list of supported operation modes. [Learn more.]({url}#modes)", + "on_command_type": "Defines when the payload \"on\" is sent. Using \"Last\" (the default) will send any style (brightness, color, etc) topics first and then a payload \"on\" to the command topic. Using \"First\" will send the payload \"on\" and then any style topics. Using \"Brightness\" will only send brightness commands instead of the payload \"on\" to turn the light on.", + "optimistic": "Flag that defines if the {platform} entity works in optimistic mode. [Learn more.]({url}#optimistic)", + "options": "List of options that can be selected.", + "payload_off": "The payload that represents the \"off\" state.", + "payload_on": "The payload that represents the \"on\" state.", + "payload_press": "The payload to send when the button is triggered.", + "payload_reset": "The payload received at the state topic that resets the entity to an unknown state.", + "position_closed": "Number which represents closed position. The valve’s position will be scaled to the (position \"closed\"…position \"open\") range when an action is performed and scaled back when a value is received.", + "position_open": "Number which represents open position. The valve’s position will be scaled to the (position \"closed\"…position \"open\") range when an action is performed and scaled back when a value is received.", + "qos": "The QoS value a {platform} entity should use.", + "red_template": "[Template]({value_templating_url}) to extract red color from the state payload value. Expected result of the template is an integer from 0-255 range.", + "retain": "Select if values published by the {platform} entity should be retained at the MQTT broker.", + "state_off": "The incoming payload that represents the \"off\" state. Use only when the value that represents \"off\" state in the state topic is different from value that should be sent to the command topic to turn the device off.", + "state_on": "The incoming payload that represents the \"on\" state. Use only when the value that represents \"on\" state in the state topic is different from value that should be sent to the command topic to turn the device on.", + "state_template": "[Template]({value_templating_url}) to extract state from the state payload value.", + "state_topic": "The MQTT topic subscribed to receive {platform} state values. [Learn more.]({url}#state_topic)", + "step": "Step value. Smallest value 0.001.", + "support_duration": "The siren supports setting a duration in second. The `duration` variable will become available for use in the \"Command template\" setting. [Learn more.]({url}#support_duration)", + "support_volume_set": "The siren supports setting a volume. The `volume_level` variable will become available for use in the \"Command template\" setting. [Learn more.]({url}#support_volume_set)", + "supported_color_modes": "A list of color modes supported by the light. Possible color modes are On/Off, Brightness, Color temperature, HS, XY, RGB, RGBW, RGBWW, White. Note that if On/Off or Brightness are used, that must be the only value in the list. [Learn more.]({url}#supported_color_modes)", + "timezone": "Set to a valid [IANA time zone identifier]({tz_abbr_url}). Do not set this option if the date/time structure is providing time zone information via the status update.", + "url_template": "[Template]({value_templating_url}) to extract an URL from the received URL topic payload value. [Learn more.]({url}#url_template)", + "url_topic": "The MQTT topic subscribed to receive messages containing the image URL. [Learn more.]({url}#url_topic)", + "value_template": "Defines a [template]({value_templating_url}) to extract the {platform} entity value. [Learn more.]({url}#value_template)" + }, + "description": "Please configure MQTT specific details for {platform} entity \"{entity}\":", + "sections": { + "alarm_control_panel_payload_settings": { + "data": { + "payload_arm_away": "Payload \"arm away\"", + "payload_arm_custom_bypass": "Payload \"arm custom bypass\"", + "payload_arm_disarm": "Payload \"disarm\"", + "payload_arm_home": "Payload \"arm home\"", + "payload_arm_night": "Payload \"arm night\"", + "payload_arm_vacation": "Payload \"arm vacation\"", + "payload_trigger": "Payload \"trigger alarm\"" + }, + "data_description": { + "payload_arm_away": "The payload sent when an \"arm away\" command is issued.", + "payload_arm_custom_bypass": "The payload sent when an \"arm custom bypass\" command is issued.", + "payload_arm_disarm": "The payload sent when a \"disarm\" command is issued.", + "payload_arm_home": "The payload sent when an \"arm home\" command is issued.", + "payload_arm_night": "The payload sent when an \"arm night\" command is issued.", + "payload_arm_vacation": "The payload sent when an \"arm vacation\" command is issued.", + "payload_trigger": "The payload sent when a \"trigger alarm\" command is issued." + }, + "name": "Alarm control panel payload settings" + }, + "climate_action_settings": { + "data": { + "action_template": "Action template", + "action_topic": "Action topic" + }, + "data_description": { + "action_template": "A [template]({value_templating_url}) to render the value received on the action topic with.", + "action_topic": "The MQTT topic to subscribe for changes of the current action. If this is set, the climate graph uses the value received as data source. A \"None\" payload resets the current action state. An empty payload is ignored. Valid action values are: \"off\", \"heating\", \"cooling\", \"drying\", \"idle\" and \"fan\". [Learn more.]({url}#action_topic)" + }, + "name": "Current action settings" + }, + "climate_fan_mode_settings": { + "data": { + "fan_mode_command_template": "Fan mode command template", + "fan_mode_command_topic": "Fan mode command topic", + "fan_mode_state_template": "Fan mode state template", + "fan_mode_state_topic": "Fan mode state topic", + "fan_modes": "Fan modes" + }, + "data_description": { + "fan_mode_command_template": "A [template]({command_templating_url}) to compose the payload to be published at the fan mode command topic.", + "fan_mode_command_topic": "The MQTT topic to publish commands to change the climate fan mode. [Learn more.]({url}#fan_mode_command_topic)", + "fan_mode_state_template": "Defines a [template]({value_templating_url}) to extract the climate fan mode value.", + "fan_mode_state_topic": "The MQTT topic subscribed to receive the climate fan mode. [Learn more.]({url}#fan_mode_state_topic)", + "fan_modes": "List of fan modes this climate is capable of running at. Common fan modes that offer translations are `off`, `on`, `auto`, `low`, `medium`, `high`, `middle`, `focus` and `diffuse`." + }, + "name": "Fan mode settings" + }, + "climate_power_settings": { + "data": { + "payload_off": "[%key:component::mqtt::config_subentries::device::step::mqtt_platform_config::data::payload_off%]", + "payload_on": "[%key:component::mqtt::config_subentries::device::step::mqtt_platform_config::data::payload_on%]", + "power_command_template": "Power command template", + "power_command_topic": "Power command topic" + }, + "data_description": { + "payload_off": "[%key:component::mqtt::config_subentries::device::step::mqtt_platform_config::data_description::payload_off%]", + "payload_on": "[%key:component::mqtt::config_subentries::device::step::mqtt_platform_config::data_description::payload_on%]", + "power_command_template": "A [template]({command_templating_url}) to compose the payload to be published at the power command topic. The `value` parameter is the payload set for payload \"on\" or payload \"off\".", + "power_command_topic": "The MQTT topic to publish commands to change the climate power state. Sends the payload configured with payload \"on\" or payload \"off\". [Learn more.]({url}#power_command_topic)" + }, + "name": "Power settings" + }, + "climate_preset_mode_settings": { + "data": { + "preset_mode_command_template": "[%key:component::mqtt::config_subentries::device::step::mqtt_platform_config::sections::fan_preset_mode_settings::data::preset_mode_command_template%]", + "preset_mode_command_topic": "[%key:component::mqtt::config_subentries::device::step::mqtt_platform_config::sections::fan_preset_mode_settings::data::preset_mode_command_topic%]", + "preset_mode_state_topic": "[%key:component::mqtt::config_subentries::device::step::mqtt_platform_config::sections::fan_preset_mode_settings::data::preset_mode_state_topic%]", + "preset_mode_value_template": "[%key:component::mqtt::config_subentries::device::step::mqtt_platform_config::sections::fan_preset_mode_settings::data::preset_mode_value_template%]", + "preset_modes": "[%key:component::mqtt::config_subentries::device::step::mqtt_platform_config::sections::fan_preset_mode_settings::data::preset_modes%]" + }, + "data_description": { + "preset_mode_command_template": "[%key:component::mqtt::config_subentries::device::step::mqtt_platform_config::sections::fan_preset_mode_settings::data_description::preset_mode_command_template%]", + "preset_mode_command_topic": "The MQTT topic to publish commands to change the climate preset mode. [Learn more.]({url}#preset_mode_command_topic)", + "preset_mode_state_topic": "[%key:component::mqtt::config_subentries::device::step::mqtt_platform_config::sections::fan_preset_mode_settings::data_description::preset_mode_state_topic%]", + "preset_mode_value_template": "[%key:component::mqtt::config_subentries::device::step::mqtt_platform_config::sections::fan_preset_mode_settings::data_description::preset_mode_value_template%]", + "preset_modes": "List of preset modes this climate is capable of running at. Common preset modes that offer translations are `none`, `away`, `eco`, `boost`, `comfort`, `home`, `sleep` and `activity`." + }, + "name": "[%key:component::mqtt::config_subentries::device::step::mqtt_platform_config::sections::fan_preset_mode_settings::name%]" + }, + "climate_swing_horizontal_mode_settings": { + "data": { + "swing_horizontal_mode_command_template": "Horizontal swing mode command template", + "swing_horizontal_mode_command_topic": "Horizontal swing mode command topic", + "swing_horizontal_mode_state_template": "Horizontal swing mode state template", + "swing_horizontal_mode_state_topic": "Horizontal swing mode state topic", + "swing_horizontal_modes": "Horizontal swing modes" + }, + "data_description": { + "swing_horizontal_mode_command_template": "A [template]({command_templating_url}) to compose the payload to be published at the horizontal swing mode command topic.", + "swing_horizontal_mode_command_topic": "The MQTT topic to publish commands to change the climate horizontal swing mode. [Learn more.]({url}#swing_horizontal_mode_command_topic)", + "swing_horizontal_mode_state_template": "Defines a [template]({value_templating_url}) to extract the climate horizontal swing mode value.", + "swing_horizontal_mode_state_topic": "The MQTT topic subscribed to receive the climate horizontal swing mode. [Learn more.]({url}#swing_horizontal_mode_state_topic)", + "swing_horizontal_modes": "List of horizontal swing modes this climate is capable of running at. Common horizontal swing modes that offer translations are `off` and `on`." + }, + "name": "Horizontal swing mode settings" + }, + "climate_swing_mode_settings": { + "data": { + "swing_mode_command_template": "Swing mode command template", + "swing_mode_command_topic": "Swing mode command topic", + "swing_mode_state_template": "Swing mode state template", + "swing_mode_state_topic": "Swing mode state topic", + "swing_modes": "Swing modes" + }, + "data_description": { + "swing_mode_command_template": "A [template]({command_templating_url}) to compose the payload to be published at the swing mode command topic.", + "swing_mode_command_topic": "The MQTT topic to publish commands to change the climate swing mode. [Learn more.]({url}#swing_mode_command_topic)", + "swing_mode_state_template": "Defines a [template]({value_templating_url}) to extract the climate swing mode value.", + "swing_mode_state_topic": "The MQTT topic subscribed to receive the climate swing mode. [Learn more.]({url}#swing_mode_state_topic)", + "swing_modes": "List of swing modes this climate is capable of running at. Common swing modes that offer translations are `off`, `on`, `vertical`, `horizontal` and `both`." + }, + "name": "Swing mode settings" + }, + "cover_payload_settings": { + "data": { + "payload_close": "Payload \"close\"", + "payload_open": "Payload \"open\"", + "payload_stop": "Payload \"stop\"", + "payload_stop_tilt": "Payload \"stop tilt\"", + "state_closed": "State \"closed\"", + "state_closing": "State \"closing\"", + "state_open": "State \"open\"", + "state_opening": "State \"opening\"", + "state_stopped": "State \"stopped\"" + }, + "data_description": { + "payload_close": "The payload sent when a \"close\" command is issued.", + "payload_open": "The payload sent when an \"open\" command is issued.", + "payload_stop": "The payload sent when a \"stop\" command is issued. Leave empty to disable the \"stop\" feature.", + "payload_stop_tilt": "The payload sent when a \"stop tilt\" command is issued.", + "state_closed": "The payload received at the state topic that represents the \"closed\" state.", + "state_closing": "The payload received at the state topic that represents the \"closing\" state.", + "state_open": "The payload received at the state topic that represents the \"open\" state.", + "state_opening": "The payload received at the state topic that represents the \"opening\" state.", + "state_stopped": "The payload received at the state topic that represents the \"stopped\" state (for covers that do not report \"open\"/\"closed\" state)." + }, + "name": "Payload settings" + }, + "cover_position_settings": { + "data": { + "position_closed": "Position \"closed\" value", + "position_open": "Position \"open\" value", + "position_template": "Position value template", + "position_topic": "Position state topic", + "set_position_template": "Set position template", + "set_position_topic": "Set position topic" + }, + "data_description": { + "position_closed": "Number which represents \"closed\" position.", + "position_open": "Number which represents \"open\" position.", + "position_template": "Defines a [template]({value_templating_url}) to extract the payload for the position topic. Within the template the following variables are also available: `entity_id`, `position_open`, `position_closed`, `tilt_min` and `tilt_max`. [Learn more.]({url}#position_template)", + "position_topic": "The MQTT topic subscribed to receive cover position state messages. [Learn more.]({url}#position_topic)", + "set_position_template": "[Template]({command_templating_url}) to define the position to be sent to the set position topic. Within the template the following variables are available: `value` (the scaled target position), `entity_id`, `position` (the target position percentage), `position_open`, `position_closed`, `tilt_min` and `tilt_max`. [Learn more.]({url}#set_position_template)", + "set_position_topic": "The MQTT topic to publish position commands to. You need to use the set position topic as well if you want to use the position topic. Use template if position topic wants different values than within range \"position closed\" - \"position_open\". If template is not defined and position \"closed\" != 100 and position \"open\" != 0 then proper position value is calculated from percentage position. [Learn more.]({url}#set_position_topic)" + }, + "name": "Position settings" + }, + "cover_tilt_settings": { + "data": { + "tilt_closed_value": "Tilt \"closed\" value", + "tilt_command_template": "Tilt command template", + "tilt_command_topic": "Tilt command topic", + "tilt_max": "Tilt max", + "tilt_min": "Tilt min", + "tilt_opened_value": "Tilt \"opened\" value", + "tilt_optimistic": "Tilt optimistic", + "tilt_status_template": "Tilt value template", + "tilt_status_topic": "Tilt status topic" + }, + "data_description": { + "tilt_closed_value": "The value that will be sent to the \"tilt command topic\" when the cover tilt is closed.", + "tilt_command_template": "[Template]({command_templating_url}) to define the position to be sent to the tilt command topic. Within the template the following variables are available: `entity_id`, `tilt_position` (the target tilt position percentage), `position_open`, `position_closed`, `tilt_min` and `tilt_max`. [Learn more.]({url}#tilt_command_template)", + "tilt_command_topic": "The MQTT topic to publish commands to control the cover tilt. [Learn more.]({url}#tilt_command_topic)", + "tilt_max": "The maximum tilt value.", + "tilt_min": "The minimum tilt value.", + "tilt_opened_value": "The value that will be sent to the \"tilt command topic\" when the cover tilt is opened.", + "tilt_optimistic": "Flag that defines if tilt works in optimistic mode. If tilt status topic is not defined, tilt works in optimistic mode by default. [Learn more.]({url}#tilt_optimistic)", + "tilt_status_template": "Defines a [template]({value_templating_url}) to extract the payload for the tilt status topic. Within the template the following variables are available: `entity_id`, `position_open`, `position_closed`, `tilt_min` and `tilt_max`. [Learn more.]({url}#tilt_status_template)", + "tilt_status_topic": "The MQTT topic subscribed to receive tilt status update values. [Learn more.]({url}#tilt_status_topic)" + }, + "name": "Tilt settings" + }, + "current_humidity_settings": { + "data": { + "current_humidity_template": "Current humidity template", + "current_humidity_topic": "Current humidity topic" + }, + "data_description": { + "current_humidity_template": "Defines a [template]({value_templating_url}) to extract the current humidity value. [Learn more.]({url}#current_humidity_template)", + "current_humidity_topic": "The MQTT topic subscribed to receive current humidity update values. [Learn more.]({url}#current_humidity_topic)" + }, + "name": "Current humidity settings" + }, + "current_temperature_settings": { + "data": { + "current_temperature_template": "Current temperature template", + "current_temperature_topic": "Current temperature topic" + }, + "data_description": { + "current_temperature_template": "Defines a [template]({value_templating_url}) to extract the current temperature value. [Learn more.]({url}#current_temperature_template)", + "current_temperature_topic": "The MQTT topic subscribed to receive current temperature update values. [Learn more.]({url}#current_temperature_topic)" + }, + "name": "Current temperature settings" + }, + "fan_direction_settings": { + "data": { + "direction_command_template": "Direction command template", + "direction_command_topic": "Direction command topic", + "direction_state_topic": "Direction state topic", + "direction_value_template": "Direction value template" + }, + "data_description": { + "direction_command_template": "A [template]({command_templating_url}) to compose the payload to be published at the direction command topic. The template variable `value` will be either `forward` or `reverse`.", + "direction_command_topic": "The MQTT topic to publish commands to change the fan direction. The payload will be either `forward` or `reverse` and can be customized using the direction command template. [Learn more.]({url}#direction_command_topic)", + "direction_state_topic": "The MQTT topic subscribed to receive fan direction state. Accepted state payloads are `forward` or `reverse`. [Learn more.]({url}#direction_state_topic)", + "direction_value_template": "Defines a [template]({value_templating_url}) to extract fan direction state value. The template should return either `forward` or `reverse`. When the template returns an empty string, the direction will be ignored." + }, + "name": "Direction settings" + }, + "fan_oscillation_settings": { + "data": { + "oscillation_command_template": "Oscillation command template", + "oscillation_command_topic": "Oscillation command topic", + "oscillation_state_topic": "Oscillation state topic", + "oscillation_value_template": "Oscillation value template", + "payload_oscillation_off": "Payload \"oscillation off\"", + "payload_oscillation_on": "Payload \"oscillation on\"" + }, + "data_description": { + "oscillation_command_template": "A [template]({command_templating_url}) to compose the payload to be published at the oscillation command topic.", + "oscillation_command_topic": "The MQTT topic to publish commands to change the fan oscillation state. [Learn more.]({url}#oscillation_command_topic)", + "oscillation_state_topic": "The MQTT topic subscribed to receive fan oscillation state. [Learn more.]({url}#oscillation_state_topic)", + "oscillation_value_template": "Defines a [template]({value_templating_url}) to extract fan oscillation state value.", + "payload_oscillation_off": "The payload that represents the oscillation \"off\" state.", + "payload_oscillation_on": "The payload that represents the oscillation \"on\" state." + }, + "name": "Oscillation settings" + }, + "fan_preset_mode_settings": { + "data": { + "payload_reset_preset_mode": "Payload \"reset preset mode\"", + "preset_mode_command_template": "Preset mode command template", + "preset_mode_command_topic": "Preset mode command topic", + "preset_mode_state_topic": "Preset mode state topic", + "preset_mode_value_template": "Preset mode value template", + "preset_modes": "Preset modes" + }, + "data_description": { + "payload_reset_preset_mode": "A special payload that resets the fan preset mode state attribute to unknown when received at the preset mode state topic.", + "preset_mode_command_template": "A [template]({command_templating_url}) to compose the payload to be published at the preset mode command topic.", + "preset_mode_command_topic": "The MQTT topic to publish commands to change the fan preset mode. [Learn more.]({url}#preset_mode_command_topic)", + "preset_mode_state_topic": "The MQTT topic subscribed to receive fan preset mode. [Learn more.]({url}#preset_mode_state_topic)", + "preset_mode_value_template": "Defines a [template]({value_templating_url}) to extract fan preset mode value.", + "preset_modes": "List of preset modes this fan is capable of running at. Common examples include auto, smart, whoosh, eco and breeze." + }, + "name": "Preset mode settings" + }, + "fan_speed_settings": { + "data": { + "payload_reset_percentage": "Payload \"reset percentage\"", + "percentage_command_template": "Percentage command template", + "percentage_command_topic": "Percentage command topic", + "percentage_state_topic": "Percentage state topic", + "percentage_value_template": "Percentage value template", + "speed_range_max": "Speed range max", + "speed_range_min": "Speed range min" + }, + "data_description": { + "payload_reset_percentage": "A special payload that resets the fan speed percentage state attribute to unknown when received at the percentage state topic.", + "percentage_command_template": "A [template]({command_templating_url}) to compose the payload to be published at the percentage command topic.", + "percentage_command_topic": "The MQTT topic to publish commands to change the fan speed state based on a percentage setting. The value shall be in the range from \"speed range min\" to \"speed range max\". [Learn more.]({url}#percentage_command_topic)", + "percentage_state_topic": "The MQTT topic subscribed to receive fan speed state. This is a value in the range from \"speed range min\" to \"speed range max\". [Learn more.]({url}#percentage_state_topic)", + "percentage_value_template": "Defines a [template]({value_templating_url}) to extract the speed percentage value.", + "speed_range_max": "The maximum of numeric output range (representing 100 %). The percentage step is 100 / number of speeds within the \"speed range\".", + "speed_range_min": "The minimum of numeric output range (off not included, so speed_range_min - 1 represents 0 %). The percentage step is 100 / the number of speeds within the \"speed range\"." + }, + "name": "Speed settings" + }, + "light_brightness_settings": { + "data": { + "brightness": "Separate brightness", + "brightness_command_template": "Brightness command template", + "brightness_command_topic": "Brightness command topic", + "brightness_scale": "Brightness scale", + "brightness_state_topic": "Brightness state topic", + "brightness_value_template": "Brightness value template" + }, + "data_description": { + "brightness": "Flag that defines if light supports brightness when the RGB, RGBW, or RGBWW color mode is supported.", + "brightness_command_template": "A [template]({command_templating_url}) to compose the payload to be published at the brightness command topic.", + "brightness_command_topic": "The publishing topic that will be used to control the brightness. [Learn more.]({url}#brightness_command_topic)", + "brightness_scale": "Defines the maximum brightness value (i.e., 100%) of the maximum brightness.", + "brightness_state_topic": "The MQTT topic subscribed to receive brightness state values. [Learn more.]({url}#brightness_state_topic)", + "brightness_value_template": "Defines a [template]({value_templating_url}) to extract the brightness value." + }, + "name": "Brightness settings" + }, + "light_color_mode_settings": { + "data": { + "color_mode_state_topic": "Color mode state topic", + "color_mode_value_template": "Color mode value template" + }, + "data_description": { + "color_mode_state_topic": "The MQTT topic subscribed to receive color mode updates. If this is not configured, the color mode will be automatically set according to the last received valid color or color temperature.", + "color_mode_value_template": "Defines a [template]({value_templating_url}) to extract the color mode value." + }, + "name": "Color mode settings" + }, + "light_color_temp_settings": { + "data": { + "color_temp_command_template": "Color temperature command template", + "color_temp_command_topic": "Color temperature command topic", + "color_temp_state_topic": "Color temperature state topic", + "color_temp_value_template": "Color temperature value template" + }, + "data_description": { + "color_temp_command_template": "A [template]({command_templating_url}) to compose the payload to be published at the color temperature command topic.", + "color_temp_command_topic": "The publishing topic that will be used to control the color temperature. [Learn more.]({url}#color_temp_command_topic)", + "color_temp_state_topic": "The MQTT topic subscribed to receive color temperature state updates. [Learn more.]({url}#color_temp_state_topic)", + "color_temp_value_template": "Defines a [template]({value_templating_url}) to extract the color temperature value." + }, + "name": "Color temperature settings" + }, + "light_effect_settings": { + "data": { + "effect": "Effect", + "effect_command_template": "Effect command template", + "effect_command_topic": "Effect command topic", + "effect_list": "Effect list", + "effect_state_topic": "Effect state topic", + "effect_template": "Effect template", + "effect_value_template": "Effect value template" + }, + "data_description": { + "effect": "Flag that defines if the light supports effects.", + "effect_command_template": "A [template]({command_templating_url}) to compose the payload to be published at the effect command topic.", + "effect_command_topic": "The publishing topic that will be used to control the light's effect state. [Learn more.]({url}#effect_command_topic)", + "effect_list": "The list of effects the light supports.", + "effect_state_topic": "The MQTT topic subscribed to receive effect state updates. [Learn more.]({url}#effect_state_topic)" + }, + "name": "Effect settings" + }, + "light_hs_settings": { + "data": { + "hs_command_template": "HS command template", + "hs_command_topic": "HS command topic", + "hs_state_topic": "HS state topic", + "hs_value_template": "HS value template" + }, + "data_description": { + "hs_command_template": "Defines a [template]({command_templating_url}) to compose message which will be sent to HS command topic. Available variables: `hue` and `sat`.", + "hs_command_topic": "The MQTT topic to publish commands to change the light’s color state in HS format (Hue Saturation). Range for Hue: 0° .. 360°, Range of Saturation: 0..100. Note: Brightness is sent separately in the brightness command topic. [Learn more.]({url}#hs_command_topic)", + "hs_state_topic": "The MQTT topic subscribed to receive color state updates in HS format. The expected payload is the hue and saturation values separated by commas, for example, `359.5,100.0`. Note: Brightness is received separately in the brightness state topic. [Learn more.]({url}#hs_state_topic)", + "hs_value_template": "Defines a [template]({value_templating_url}) to extract the HS value." + }, + "name": "HS color mode settings" + }, + "light_rgb_settings": { + "data": { + "rgb_command_template": "RGB command template", + "rgb_command_topic": "RGB command topic", + "rgb_state_topic": "RGB state topic", + "rgb_value_template": "RGB value template" + }, + "data_description": { + "rgb_command_template": "Defines a [template]({command_templating_url}) to compose message which will be sent to RGB command topic. Available variables: `red`, `green` and `blue`.", + "rgb_command_topic": "The MQTT topic to publish commands to change the light’s RGB state. [Learn more.]({url}#rgb_command_topic)", + "rgb_state_topic": "The MQTT topic subscribed to receive RGB state updates. The expected payload is the RGB values separated by commas, for example, `255,0,127`. [Learn more.]({url}#rgb_state_topic)", + "rgb_value_template": "Defines a [template]({value_templating_url}) to extract the RGB value." + }, + "name": "RGB color mode settings" + }, + "light_rgbw_settings": { + "data": { + "rgbw_command_template": "RGBW command template", + "rgbw_command_topic": "RGBW command topic", + "rgbw_state_topic": "RGBW state topic", + "rgbw_value_template": "RGBW value template" + }, + "data_description": { + "rgbw_command_template": "Defines a [template]({command_templating_url}) to compose message which will be sent to RGBW command topic. Available variables: `red`, `green`, `blue` and `white`.", + "rgbw_command_topic": "The MQTT topic to publish commands to change the light’s RGBW state. [Learn more.]({url}#rgbw_command_topic)", + "rgbw_state_topic": "The MQTT topic subscribed to receive RGBW state updates. The expected payload is the RGBW values separated by commas, for example, `255,0,127,64`. [Learn more.]({url}#rgbw_state_topic)", + "rgbw_value_template": "Defines a [template]({value_templating_url}) to extract the RGBW value." + }, + "name": "RGBW color mode settings" + }, + "light_rgbww_settings": { + "data": { + "rgbww_command_template": "RGBWW command template", + "rgbww_command_topic": "RGBWW command topic", + "rgbww_state_topic": "RGBWW state topic", + "rgbww_value_template": "RGBWW value template" + }, + "data_description": { + "rgbww_command_template": "Defines a [template]({command_templating_url}) to compose message which will be sent to RGBWW command topic. Available variables: `red`, `green`, `blue`, `cold_white` and `warm_white`.", + "rgbww_command_topic": "The MQTT topic to publish commands to change the light’s RGBWW state. [Learn more.]({url}#rgbww_command_topic)", + "rgbww_state_topic": "The MQTT topic subscribed to receive RGBWW state updates. The expected payload is the RGBWW values separated by commas, for example, `255,0,127,64,32`. [Learn more.]({url}#rgbww_state_topic)", + "rgbww_value_template": "Defines a [template]({value_templating_url}) to extract the RGBWW value." + }, + "name": "RGBWW color mode settings" + }, + "light_white_settings": { + "data": { + "white_command_topic": "White command topic", + "white_scale": "White scale" + }, + "data_description": { + "white_command_topic": "The MQTT topic to publish commands to change the light to white mode with a given brightness. [Learn more.]({url}#white_command_topic)", + "white_scale": "Defines the maximum white level (i.e., 100%) of the maximum." + }, + "name": "White color mode settings" + }, + "light_xy_settings": { + "data": { + "xy_command_template": "XY command template", + "xy_command_topic": "XY command topic", + "xy_state_topic": "XY state topic", + "xy_value_template": "XY value template" + }, + "data_description": { + "xy_command_template": "Defines a [template]({command_templating_url}) to compose message which will be sent to XY command topic. Available variables: `x` and `y`.", + "xy_command_topic": "The MQTT topic to publish commands to change the light’s XY state. [Learn more.]({url}#xy_command_topic)", + "xy_state_topic": "The MQTT topic subscribed to receive XY state updates. The expected payload is the X and Y color values separated by commas, for example, `0.675,0.322`. [Learn more.]({url}#xy_state_topic)", + "xy_value_template": "Defines a [template]({value_templating_url}) to extract the XY value." + }, + "name": "XY color mode settings" + }, + "lock_payload_settings": { + "data": { + "payload_lock": "Payload \"lock\"", + "payload_open": "Payload \"open\"", + "payload_reset": "Payload \"reset\"", + "payload_unlock": "Payload \"unlock\"", + "state_jammed": "State \"jammed\"", + "state_locked": "State \"locked\"", + "state_locking": "State \"locking\"", + "state_unlocked": "State \"unlocked\"", + "state_unlocking": "State \"unlocking\"" + }, + "data_description": { + "payload_lock": "The payload sent when a \"lock\" command is issued.", + "payload_open": "The payload sent when an \"open\" command is issued. Set this payload if your lock supports the \"open\" action.", + "payload_reset": "The payload received at the state topic that resets the lock to an unknown state.", + "payload_unlock": "The payload sent when an \"unlock\" command is issued.", + "state_jammed": "The payload received at the state topic that represents the \"jammed\" state.", + "state_locked": "The payload received at the state topic that represents the \"locked\" state.", + "state_locking": "The payload received at the state topic that represents the \"locking\" state.", + "state_unlocked": "The payload received at the state topic that represents the \"unlocked\" state.", + "state_unlocking": "The payload received at the state topic that represents the \"unlocking\" state." + }, + "name": "Lock payload settings" + }, + "other_settings": { + "data": { + "expire_after": "Expire after", + "flash": "Flash support", + "flash_time_long": "Flash time long", + "flash_time_short": "Flash time short", + "max_kelvin": "Max Kelvin", + "min_kelvin": "Min Kelvin", + "off_delay": "OFF delay", + "transition": "Transition support" + }, + "data_description": { + "expire_after": "If set, it defines the number of seconds after the sensor’s state expires, if it’s not updated. After expiry, the sensor’s state becomes unavailable. If not set, the sensor's state never expires. [Learn more.]({url}#expire_after)", + "flash": "Enable the flash feature for this light", + "flash_time_long": "The duration, in seconds, of a \"long\" flash.", + "flash_time_short": "The duration, in seconds, of a \"short\" flash.", + "max_kelvin": "The maximum color temperature in Kelvin.", + "min_kelvin": "The minimum color temperature in Kelvin.", + "off_delay": "For sensors that only send \"on\" state updates (like PIRs), this variable sets a delay in seconds after which the sensor’s state will be updated back to \"off\".", + "transition": "Enable the transition feature for this light" + }, + "name": "Other settings" + }, + "siren_other_settings": { + "data": { + "command_off_template": "Command \"off\" template" + }, + "data_description": { + "command_off_template": "The [template]({command_templating_url}) for \"off\" state changes. By default the \"[Command template]({url}#command_template)\" will be used. [Learn more.]({url}#command_off_template)" + }, + "name": "Other siren settings" + }, + "target_humidity_settings": { + "data": { + "max_humidity": "Maximum humidity", + "min_humidity": "Minimum humidity", + "target_humidity_command_template": "Target humidity command template", + "target_humidity_command_topic": "Target humidity command topic", + "target_humidity_state_template": "Target humidity state template", + "target_humidity_state_topic": "Target humidity state topic" + }, + "data_description": { + "max_humidity": "The maximum target humidity that can be set.", + "min_humidity": "The minimum target humidity that can be set.", + "target_humidity_command_template": "A [template]({command_templating_url}) to compose the payload to be published at the target humidity command topic.", + "target_humidity_command_topic": "The MQTT topic to publish commands to change the climate target humidity. [Learn more.]({url}#humidity_command_topic)", + "target_humidity_state_template": "A [template]({value_templating_url}) to render the value received on the target humidity state topic with.", + "target_humidity_state_topic": "The MQTT topic to subscribe for changes of the target humidity. [Learn more.]({url}#humidity_state_topic)" + }, + "name": "Target humidity settings" + }, + "target_temperature_settings": { + "data": { + "initial": "Initial temperature", + "max_temp": "Maximum temperature", + "min_temp": "Minimum temperature", + "precision": "Precision", + "temp_step": "Temperature step", + "temperature_command_template": "Temperature command template", + "temperature_command_topic": "Temperature command topic", + "temperature_high_command_template": "Upper temperature command template", + "temperature_high_command_topic": "Upper temperature command topic", + "temperature_high_state_template": "Upper temperature state template", + "temperature_high_state_topic": "Upper temperature state topic", + "temperature_low_command_template": "Lower temperature command template", + "temperature_low_command_topic": "Lower temperature command topic", + "temperature_low_state_template": "Lower temperature state template", + "temperature_low_state_topic": "Lower temperature state topic", + "temperature_state_template": "Temperature state template", + "temperature_state_topic": "Temperature state topic" + }, + "data_description": { + "initial": "The device initializes with this target temperature.", + "max_temp": "The maximum target temperature that can be set.", + "min_temp": "The minimum target temperature that can be set.", + "precision": "The precision in degrees the thermostat is working at.", + "temp_step": "The target temperature step in degrees Celsius or Fahrenheit.", + "temperature_command_template": "A [template]({command_templating_url}) to compose the payload to be published at the temperature command topic.", + "temperature_command_topic": "The MQTT topic to publish commands to change the target temperature. [Learn more.]({url}#temperature_command_topic)", + "temperature_high_command_template": "A [template]({command_templating_url}) to compose the payload to be published at the upper temperature command topic.", + "temperature_high_command_topic": "The MQTT topic to publish commands to change the climate upper target temperature. [Learn more.]({url}#temperature_high_command_topic)", + "temperature_high_state_template": "A [template]({value_templating_url}) to render the value received on the upper temperature state topic with.", + "temperature_high_state_topic": "The MQTT topic to subscribe for changes of the upper target temperature. [Learn more.]({url}#temperature_high_state_topic)", + "temperature_low_command_template": "A [template]({command_templating_url}) to compose the payload to be published at the lower temperature command topic.", + "temperature_low_command_topic": "The MQTT topic to publish commands to change the climate lower target temperature. [Learn more.]({url}#temperature_low_command_topic)", + "temperature_low_state_template": "A [template]({value_templating_url}) to render the value received on the lower temperature state topic with.", + "temperature_low_state_topic": "The MQTT topic to subscribe for changes of the lower target temperature. [Learn more.]({url}#temperature_low_state_topic)", + "temperature_state_template": "A [template]({value_templating_url}) to render the value received on the temperature state topic with.", + "temperature_state_topic": "The MQTT topic to subscribe for changes of the target temperature. [Learn more.]({url}#temperature_state_topic)" + }, + "name": "Target temperature settings" + }, + "text_other_settings": { + "data": { + "max": "Maximum length", + "min": "Minimum length", + "mode": "Mode", + "pattern": "Pattern" + }, + "data_description": { + "max": "Maximum length of the text input", + "min": "Minimum length of the text input", + "mode": "Mode of the text input", + "pattern": "A valid regex pattern" + }, + "name": "Other text entity settings" + }, + "valve_payload_settings": { + "data": { + "payload_close": "Payload \"close\"", + "payload_open": "Payload \"open\"", + "payload_stop": "Payload \"stop\"", + "state_closed": "State \"closed\"", + "state_closing": "State \"closing\"", + "state_open": "State \"open\"", + "state_opening": "State \"opening\"" + }, + "data_description": { + "payload_close": "The payload sent when a \"close\" command is issued.", + "payload_open": "The payload sent when an \"open\" command is issued.", + "payload_stop": "The payload sent when a \"stop\" command is issued. Set this payload only if your valve supports the \"stop\" action.", + "state_closed": "The payload received at the state topic that represents the \"closed\" state.", + "state_closing": "The payload received at the state topic that represents the \"closing\" state.", + "state_open": "The payload received at the state topic that represents the \"open\" state.", + "state_opening": "The payload received at the state topic that represents the \"opening\" state." + }, + "name": "Valve payload settings" + }, + "water_heater_power_settings": { + "data": { + "payload_off": "[%key:component::mqtt::config_subentries::device::step::mqtt_platform_config::data::payload_off%]", + "payload_on": "[%key:component::mqtt::config_subentries::device::step::mqtt_platform_config::data::payload_on%]", + "power_command_template": "[%key:component::mqtt::config_subentries::device::step::mqtt_platform_config::sections::climate_power_settings::data::power_command_template%]", + "power_command_topic": "[%key:component::mqtt::config_subentries::device::step::mqtt_platform_config::sections::climate_power_settings::data::power_command_topic%]" + }, + "data_description": { + "payload_off": "[%key:component::mqtt::config_subentries::device::step::mqtt_platform_config::data_description::payload_off%]", + "payload_on": "[%key:component::mqtt::config_subentries::device::step::mqtt_platform_config::data_description::payload_on%]", + "power_command_template": "[%key:component::mqtt::config_subentries::device::step::mqtt_platform_config::sections::climate_power_settings::data_description::power_command_template%]", + "power_command_topic": "The MQTT topic to publish commands to change the water heater power state. Sends the payload configured with payload \"on\" or payload \"off\". [Learn more.]({url}#power_command_topic)" + }, + "name": "Power settings" + } + }, + "title": "Configure MQTT device \"{mqtt_device}\"" + }, + "summary_menu": { + "description": "Entities set up:\n{mqtt_items}\n\nDecide what to do next:", + "menu_options": { + "availability": "Configure availability", + "delete_entity": "Delete an entity", + "device": "Update device properties", + "entity": "Add another entity to \"{mqtt_device}\"", + "export": "Export MQTT device configuration", + "save_changes": "Save changes", + "update_entity": "Update entity properties" + }, + "title": "Reconfigure \"{mqtt_device}\"" + }, + "update_entity": { + "data": { + "component": "Entity" + }, + "data_description": { + "component": "Select the entity you want to update." + }, + "description": "Select the entity you want to update", + "title": "Select entity" + } + } + } + }, + "device_automation": { + "trigger_subtype": { + "button_1": "First button", + "button_2": "Second button", + "button_3": "Third button", + "button_4": "Fourth button", + "button_5": "Fifth button", + "button_6": "Sixth button", + "turn_off": "[%key:common::action::turn_off%]", + "turn_on": "[%key:common::action::turn_on%]" + }, + "trigger_type": { + "button_double_press": "\"{subtype}\" double clicked", + "button_long_press": "\"{subtype}\" continuously pressed", + "button_long_release": "\"{subtype}\" released after long press", + "button_quadruple_press": "\"{subtype}\" quadruple clicked", + "button_quintuple_press": "\"{subtype}\" quintuple clicked", + "button_short_press": "\"{subtype}\" pressed", + "button_short_release": "\"{subtype}\" released", + "button_triple_press": "\"{subtype}\" triple clicked" + } + }, + "exceptions": { + "addon_start_failed": { + "message": "Failed to correctly start {addon} app." + }, + "command_template_error": { + "message": "Parsing template `{command_template}` for entity `{entity_id}` failed with error: {error}." + }, + "invalid_platform_config_message": { + "message": "Reloading YAML config for manually configured MQTT `{domain}` item failed. Message: {message}" + }, + "invalid_publish_topic": { + "message": "Unable to publish: topic template `{topic_template}` produced an invalid topic `{topic}` after rendering ({error})" + }, + "mqtt_broker_error": { + "message": "Error talking to MQTT: {error_message}." + }, + "mqtt_max_subscription_id_reached": { + "message": "MQTT Subscription ID limit reached. Cannot generate more IDs to subscribe." + }, + "mqtt_message_expiry_interval_not_supported": { + "message": "Publishing to topic {topic} with a Message Expiry Interval is not supported for protocol version {protocol}." + }, + "mqtt_not_enabled_cannot_subscribe": { + "message": "Cannot subscribe to topic \"{topic}\" because MQTT is not enabled, make sure MQTT is set up correctly." + }, + "mqtt_not_setup_cannot_publish": { + "message": "Cannot publish to topic \"{topic}\", make sure MQTT is set up correctly." + }, + "mqtt_not_setup_cannot_subscribe": { + "message": "Cannot subscribe to topic \"{topic}\", make sure MQTT is set up correctly." + }, + "mqtt_not_setup_cannot_unsubscribe_twice": { + "message": "Cannot unsubscribe topic \"{topic}\" twice." + }, + "mqtt_topic_not_a_string": { + "message": "Topic needs to be a string! Got: {topic}." + }, + "mqtt_trigger_cannot_remove_twice": { + "message": "Can't remove trigger twice." + } + }, + "issues": { + "invalid_platform_config": { + "description": "Home Assistant detected an invalid config for a manually configured item.\n\nPlatform domain: **{domain}**\nConfiguration file: **{config_file}**\nNear line: **{line}**\nConfiguration found:\n```yaml\n{config}\n```\nError: **{error}**.\n\nMake sure the configuration is valid and [reload](/config/tools/yaml) the manually configured MQTT items or restart Home Assistant to fix this issue.", + "title": "Invalid config found for MQTT {domain} item" + }, + "protocol_5_migration": { + "description": "The automatic migration to MQTT protocol version 5 failed. The currently configured protocol version for MQTT broker {broker} is {protocol}, but this protocol version is deprecated, and support for it will be removed.\n\nMake sure your broker supports protocol version 5. Update your MQTT broker's connection settings, and restart Home Assistant to fix this issue.", + "title": "MQTT protocol migration failed" + }, + "subentry_migration_discovery": { + "fix_flow": { + "step": { + "confirm": { + "description": "Exported MQTT device \"{name}\" identified via MQTT discovery. Select **Submit** to confirm that the MQTT device is to be migrated to the main MQTT configuration, and to remove the existing MQTT device subentry. Make sure that the discovery is retained at the MQTT broker, or is resent after the subentry is removed, so that the MQTT device will be set up correctly. As an alternative you can change the device identifiers and entity unique ID-s in your MQTT discovery configuration payload, and cancel this repair if you want to keep the MQTT device subentry.", + "title": "[%key:component::mqtt::issues::subentry_migration_discovery::title%]" + } + } + }, + "title": "MQTT device \"{name}\" subentry migration to MQTT discovery" + }, + "subentry_migration_yaml": { + "fix_flow": { + "step": { + "confirm": { + "description": "Exported MQTT device \"{name}\" identified in YAML configuration. Select **Submit** to confirm that the MQTT device is to be migrated to main MQTT config entry, and to remove the existing MQTT device subentry. As an alternative you can change the device identifiers and entity unique ID-s in your configuration.yaml file, and cancel this repair if you want to keep the MQTT device subentry.", + "title": "[%key:component::mqtt::issues::subentry_migration_yaml::title%]" + } + } + }, + "title": "MQTT device \"{name}\" subentry migration to YAML" + }, + "yaml_setup_without_active_setup": { + "description": "Home Assistant detected manually configured MQTT items, but these items cannot be loaded because MQTT is not set up correctly. Make sure the MQTT broker is set up correctly, or remove the MQTT configuration from your `configuration.yaml` file and restart Home Assistant to fix this issue.", + "title": "MQTT is not set up correctly" + } + }, + "options": { + "error": { + "bad_birth": "[%key:component::mqtt::config::error::bad_birth%]", + "bad_certificate": "[%key:component::mqtt::config::error::bad_certificate%]", + "bad_client_cert": "[%key:component::mqtt::config::error::bad_client_cert%]", + "bad_client_cert_key": "[%key:component::mqtt::config::error::bad_client_cert_key%]", + "bad_discovery_prefix": "[%key:component::mqtt::config::error::bad_discovery_prefix%]", + "bad_will": "[%key:component::mqtt::config::error::bad_will%]", + "bad_ws_headers": "[%key:component::mqtt::config::error::bad_ws_headers%]", + "cannot_connect": "[%key:common::config_flow::error::cannot_connect%]", + "client_key_error": "[%key:component::mqtt::config::error::client_key_error%]", + "invalid_inclusion": "[%key:component::mqtt::config::error::invalid_inclusion%]" + }, + "step": { + "options": { + "data": { + "birth_enable": "Enable birth message", + "birth_payload": "Birth message payload", + "birth_qos": "Birth message QoS", + "birth_retain": "Birth message retain", + "birth_topic": "Birth message topic", + "discovery": "Enable discovery", + "discovery_prefix": "Discovery prefix", + "discovery_qos": "Discovery QoS", + "will_enable": "Enable will message", + "will_payload": "Will message payload", + "will_qos": "Will message QoS", + "will_retain": "Will message retain", + "will_topic": "Will message topic" + }, + "data_description": { + "birth_enable": "When set, Home Assistant will publish an online message to your MQTT broker when MQTT is ready.", + "birth_payload": "The \"birth\" message that is published when MQTT is ready and connected.", + "birth_qos": "The quality of service of the \"birth\" message that is published when MQTT is ready and connected", + "birth_retain": "When set, Home Assistant will retain the \"birth\" message published to your MQTT broker.", + "birth_topic": "The MQTT topic where Home Assistant will publish a \"birth\" message.", + "discovery": "Option to enable MQTT automatic discovery.", + "discovery_prefix": "The prefix of configuration topics the MQTT integration will subscribe to.", + "discovery_qos": "The quality of service for discovery subscriptions to your MQTT broker.", + "will_enable": "When set, Home Assistant will ask your broker to publish a \"will\" message when MQTT is stopped or when it loses the connection to your broker.", + "will_payload": "The message your MQTT broker \"will\" publish when the MQTT integration is stopped or when the connection is lost.", + "will_qos": "The quality of service of the \"will\" message that is published by your MQTT broker.", + "will_retain": "When set, your MQTT broker will retain the \"will\" message.", + "will_topic": "The MQTT topic your MQTT broker will publish a \"will\" message to." + }, + "description": "Discovery - If discovery is enabled (recommended), Home Assistant will automatically discover devices and entities which publish their configuration on the MQTT broker. If discovery is disabled, all configuration must be done manually.\nDiscovery prefix - The prefix a configuration topic for automatic discovery must start with.\nBirth message - The birth message will be sent each time Home Assistant (re)connects to the MQTT broker.\nWill message - The will message will be sent each time Home Assistant loses its connection to the broker, both in case of a clean (e.g. Home Assistant shutting down) and in case of an unclean (e.g. Home Assistant crashing or losing its network connection) disconnect.", + "title": "MQTT options" + } + } + }, + "selector": { + "alarm_control_panel_code_mode": { + "options": { + "local_code": "Local code validation", + "remote_code": "Numeric remote code validation", + "remote_code_text": "Text remote code validation" + } + }, + "alarm_control_panel_features": { + "options": { + "arm_away": "[%key:component::alarm_control_panel::services::alarm_arm_away::name%]", + "arm_custom_bypass": "[%key:component::alarm_control_panel::services::alarm_arm_custom_bypass::name%]", + "arm_home": "[%key:component::alarm_control_panel::services::alarm_arm_home::name%]", + "arm_night": "[%key:component::alarm_control_panel::services::alarm_arm_night::name%]", + "arm_vacation": "[%key:component::alarm_control_panel::services::alarm_arm_vacation::name%]", + "trigger": "[%key:component::alarm_control_panel::services::alarm_trigger::name%]" + } + }, + "climate_modes": { + "options": { + "auto": "[%key:common::state::auto%]", + "cool": "[%key:component::climate::entity_component::_::state::cool%]", + "dry": "[%key:component::climate::entity_component::_::state::dry%]", + "fan_only": "[%key:component::climate::entity_component::_::state::fan_only%]", + "heat": "[%key:component::climate::entity_component::_::state::heat%]", + "heat_cool": "[%key:component::climate::entity_component::_::state::heat_cool%]", + "off": "[%key:common::state::off%]" + } + }, + "entity_category": { + "options": { + "config": "Config", + "diagnostic": "Diagnostic" + } + }, + "image_encoding": { + "options": { + "b64": "Base64 encoding", + "raw": "Raw data" + } + }, + "image_processing_mode": { + "options": { + "image_data": "Image data is received", + "image_url": "Image URL is received" + } + }, + "light_schema": { + "options": { + "basic": "Default schema", + "json": "JSON", + "template": "Template" + } + }, + "number_mode": { + "options": { + "auto": "[%key:component::number::entity_component::_::state_attributes::mode::state::auto%]", + "box": "[%key:component::number::entity_component::_::state_attributes::mode::state::box%]", + "slider": "[%key:component::number::entity_component::_::state_attributes::mode::state::slider%]" + } + }, + "on_command_type": { + "options": { + "brightness": "Brightness", + "first": "First", + "last": "Last" + } + }, + "platform": { + "options": { + "alarm_control_panel": "[%key:component::alarm_control_panel::title%]", + "binary_sensor": "[%key:component::binary_sensor::title%]", + "button": "[%key:component::button::title%]", + "climate": "[%key:component::climate::title%]", + "cover": "[%key:component::cover::title%]", + "date": "[%key:component::date::title%]", + "datetime": "[%key:component::datetime::title%]", + "fan": "[%key:component::fan::title%]", + "image": "[%key:component::image::title%]", + "light": "[%key:component::light::title%]", + "lock": "[%key:component::lock::title%]", + "notify": "[%key:component::notify::title%]", + "number": "[%key:component::number::title%]", + "select": "[%key:component::select::title%]", + "sensor": "[%key:component::sensor::title%]", + "siren": "[%key:component::siren::title%]", + "switch": "[%key:component::switch::title%]", + "text": "[%key:component::text::title%]", + "time": "[%key:component::time::title%]", + "valve": "[%key:component::valve::title%]", + "water_heater": "[%key:component::water_heater::title%]" + } + }, + "set_ca_cert": { + "options": { + "auto": "[%key:common::state::auto%]", + "custom": "Custom", + "off": "[%key:common::state::off%]" + } + }, + "supported_color_modes": { + "options": { + "brightness": "[%key:component::light::entity_component::_::state_attributes::color_mode::state::brightness%]", + "color_temp": "[%key:component::light::entity_component::_::state_attributes::color_mode::state::color_temp%]", + "hs": "[%key:component::light::entity_component::_::state_attributes::color_mode::state::hs%]", + "onoff": "[%key:component::light::entity_component::_::state_attributes::color_mode::state::onoff%]", + "rgb": "[%key:component::light::entity_component::_::state_attributes::color_mode::state::rgb%]", + "rgbw": "[%key:component::light::entity_component::_::state_attributes::color_mode::state::rgbw%]", + "rgbww": "[%key:component::light::entity_component::_::state_attributes::color_mode::state::rgbww%]", + "white": "[%key:component::light::entity_component::_::state_attributes::color_mode::state::white%]", + "xy": "[%key:component::light::entity_component::_::state_attributes::color_mode::state::xy%]" + } + }, + "target_temperature_feature": { + "options": { + "high_low": "Upper/lower target temperature", + "none": "No target temperature", + "single": "Single target temperature" + } + }, + "text_mode": { + "options": { + "password": "[%key:common::config_flow::data::password%]", + "text": "[%key:component::text::entity_component::_::state_attributes::mode::state::text%]" + } + }, + "water_heater_modes": { + "options": { + "auto": "[%key:common::state::auto%]", + "eco": "[%key:component::water_heater::entity_component::_::state::eco%]", + "electric": "[%key:component::water_heater::entity_component::_::state::electric%]", + "gas": "[%key:component::water_heater::entity_component::_::state::gas%]", + "heat_pump": "[%key:component::water_heater::entity_component::_::state::heat_pump%]", + "high_demand": "[%key:component::water_heater::entity_component::_::state::high_demand%]", + "off": "[%key:common::state::off%]", + "performance": "[%key:component::water_heater::entity_component::_::state::performance%]" + } + } + }, + "services": { + "dump": { + "description": "Writes all messages on a specific topic into the `vmqtt_dump.txt` file in your configuration folder.", + "fields": { + "duration": { + "description": "How long we should listen for messages in seconds.", + "name": "Duration" + }, + "topic": { + "description": "Topic to listen to.", + "name": "[%key:component::mqtt::services::publish::fields::topic::name%]" + } + }, + "name": "Export" + }, + "publish": { + "description": "Publishes a message to an MQTT topic.", + "fields": { + "evaluate_payload": { + "description": "If 'Payload' is a Python bytes literal, evaluate the bytes literal and publish the raw data.", + "name": "Evaluate payload" + }, + "message_expiry_interval": { + "description": "Expires a publish message after the interval in case the device subscriber was temporarily offline, or the message was set as a retained message. Only supported with MQTT protocol version 5.0.", + "name": "Message Expiry Interval" + }, + "payload": { + "description": "The payload to publish. Publishes an empty message if not provided.", + "name": "Payload" + }, + "qos": { + "description": "Quality of Service to use. 0: At most once. 1: At least once. 2: Exactly once.", + "name": "QoS" + }, + "retain": { + "description": "If the message should have the retain flag set. If set, the broker stores the most recent message on a topic.", + "name": "Retain" + }, + "topic": { + "description": "Topic to publish to.", + "name": "Topic" + } + }, + "name": "Publish", + "sections": { + "publish_options": { + "name": "Publish options" + } + } + }, + "reload": { + "description": "Reloads MQTT entities from the YAML-configuration.", + "name": "[%key:common::action::reload%]" + } + }, + "triggers": { + "_": { + "description": "Triggers after a specific message is received on a given MQTT topic.", + "fields": { + "payload": { + "description": "The payload to trigger on.", + "name": "Payload" + }, + "topic": { + "description": "MQTT topic to listen to.", + "name": "Topic" + } + }, + "name": "MQTT message received" + } + } +} diff --git a/custom_components/vmqtt/trigger.py b/custom_components/vmqtt/trigger.py new file mode 100644 index 0000000..42b34f5 --- /dev/null +++ b/custom_components/vmqtt/trigger.py @@ -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, + ) diff --git a/custom_components/vmqtt/triggers.yaml b/custom_components/vmqtt/triggers.yaml new file mode 100644 index 0000000..0de44f4 --- /dev/null +++ b/custom_components/vmqtt/triggers.yaml @@ -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: diff --git a/custom_components/vmqtt/update.py b/custom_components/vmqtt/update.py new file mode 100644 index 0000000..cbe4a1f --- /dev/null +++ b/custom_components/vmqtt/update.py @@ -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 diff --git a/custom_components/vmqtt/util.py b/custom_components/vmqtt/util.py new file mode 100644 index 0000000..d7fc1c7 --- /dev/null +++ b/custom_components/vmqtt/util.py @@ -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) diff --git a/custom_components/vmqtt/vacuum.py b/custom_components/vmqtt/vacuum.py new file mode 100644 index 0000000..cb10534 --- /dev/null +++ b/custom_components/vmqtt/vacuum.py @@ -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) diff --git a/custom_components/vmqtt/valve.py b/custom_components/vmqtt/valve.py new file mode 100644 index 0000000..d631561 --- /dev/null +++ b/custom_components/vmqtt/valve.py @@ -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() diff --git a/custom_components/vmqtt/water_heater.py b/custom_components/vmqtt/water_heater.py new file mode 100644 index 0000000..09e3258 --- /dev/null +++ b/custom_components/vmqtt/water_heater.py @@ -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) diff --git a/hacs.json b/hacs.json new file mode 100644 index 0000000..2ef039e --- /dev/null +++ b/hacs.json @@ -0,0 +1,3 @@ +{ + "name": "Visquitto MQTT" +}