From 74e61ab7f75f228e87de16bf0b8b6ca03e4accdb Mon Sep 17 00:00:00 2001 From: Erik Montnemery Date: Tue, 29 Jun 2021 11:22:25 +0200 Subject: [PATCH] Filter MQTT switch JSON attributes (#52290) --- homeassistant/components/mqtt/switch.py | 9 +++++++++ tests/components/mqtt/test_switch.py | 9 +++++++++ 2 files changed, 18 insertions(+) diff --git a/homeassistant/components/mqtt/switch.py b/homeassistant/components/mqtt/switch.py index 5dfc26ce613..f383a2ae310 100644 --- a/homeassistant/components/mqtt/switch.py +++ b/homeassistant/components/mqtt/switch.py @@ -32,6 +32,13 @@ from .. import mqtt from .debug_info import log_messages from .mixins import MQTT_ENTITY_COMMON_SCHEMA, MqttEntity, async_setup_entry_helper +MQTT_SWITCH_ATTRIBUTES_BLOCKED = frozenset( + { + switch.ATTR_CURRENT_POWER_W, + switch.ATTR_TODAY_ENERGY_KWH, + } +) + DEFAULT_NAME = "MQTT Switch" DEFAULT_PAYLOAD_ON = "ON" DEFAULT_PAYLOAD_OFF = "OFF" @@ -78,6 +85,8 @@ async def _async_setup_entity( class MqttSwitch(MqttEntity, SwitchEntity, RestoreEntity): """Representation of a switch that can be toggled using MQTT.""" + _attributes_extra_blocked = MQTT_SWITCH_ATTRIBUTES_BLOCKED + def __init__(self, hass, config, config_entry, discovery_data): """Initialize the MQTT switch.""" self._state = False diff --git a/tests/components/mqtt/test_switch.py b/tests/components/mqtt/test_switch.py index 607e4468a5f..d5dcfbd4fa7 100644 --- a/tests/components/mqtt/test_switch.py +++ b/tests/components/mqtt/test_switch.py @@ -6,6 +6,7 @@ from unittest.mock import patch import pytest from homeassistant.components import switch +from homeassistant.components.mqtt.switch import MQTT_SWITCH_ATTRIBUTES_BLOCKED from homeassistant.const import ATTR_ASSUMED_STATE, STATE_OFF, STATE_ON import homeassistant.core as ha from homeassistant.setup import async_setup_component @@ -29,6 +30,7 @@ from .test_common import ( help_test_entity_id_update_subscriptions, help_test_setting_attribute_via_mqtt_json_message, help_test_setting_attribute_with_template, + help_test_setting_blocked_attribute_via_mqtt_json_message, help_test_unique_id, help_test_update_with_json_attrs_bad_JSON, help_test_update_with_json_attrs_not_dict, @@ -246,6 +248,13 @@ async def test_setting_attribute_via_mqtt_json_message(hass, mqtt_mock): ) +async def test_setting_blocked_attribute_via_mqtt_json_message(hass, mqtt_mock): + """Test the setting of attribute via MQTT with JSON payload.""" + await help_test_setting_blocked_attribute_via_mqtt_json_message( + hass, mqtt_mock, switch.DOMAIN, DEFAULT_CONFIG, MQTT_SWITCH_ATTRIBUTES_BLOCKED + ) + + async def test_setting_attribute_with_template(hass, mqtt_mock): """Test the setting of attribute via MQTT with JSON payload.""" await help_test_setting_attribute_with_template(