From f32003ddde1f706bbcde89edf5fb4405d2eae386 Mon Sep 17 00:00:00 2001 From: Krisjanis Lejejs Date: Mon, 12 Oct 2026 23:50:47 +0300 Subject: [PATCH] Fix MQTT device triggers and tags firing twice after reload (#185998) --- homeassistant/components/mqtt/entity.py | 3 +- tests/components/mqtt/test_device_trigger.py | 136 ++++++++++++++++++- tests/components/mqtt/test_tag.py | 47 ++++++- 3 files changed, 181 insertions(+), 5 deletions(-) diff --git a/homeassistant/components/mqtt/entity.py b/homeassistant/components/mqtt/entity.py index a367ff028a60..383b1500c81e 100644 --- a/homeassistant/components/mqtt/entity.py +++ b/homeassistant/components/mqtt/entity.py @@ -830,7 +830,8 @@ class MqttDiscoveryDeviceUpdateMixin(ABC): MQTT_DISCOVERY_UPDATED.format(*discovery_hash), self.async_discovery_update, ) - config_entry.async_on_unload(self._entry_unload) + # 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 diff --git a/tests/components/mqtt/test_device_trigger.py b/tests/components/mqtt/test_device_trigger.py index 3c34ae1f5ca8..1aac6b849c73 100644 --- a/tests/components/mqtt/test_device_trigger.py +++ b/tests/components/mqtt/test_device_trigger.py @@ -1,5 +1,7 @@ """The tests for MQTT device triggers.""" +from collections.abc import Awaitable, Callable +from datetime import timedelta import json from typing import Any from unittest.mock import patch @@ -7,18 +9,31 @@ from unittest.mock import patch import pytest from pytest_unordered import unordered -from homeassistant.components import automation +from homeassistant.components import automation, mqtt from homeassistant.components.device_automation import DeviceAutomationType from homeassistant.components.mqtt import _LOGGER, DOMAIN, debug_info +from homeassistant.components.mqtt.models import DATA_MQTT +from homeassistant.config_entries import ( + RELOAD_AFTER_UPDATE_DELAY, + ConfigEntry, + ConfigEntryState, +) +from homeassistant.const import Platform from homeassistant.core import HomeAssistant, ServiceCall from homeassistant.exceptions import HomeAssistantError -from homeassistant.helpers import device_registry as dr +from homeassistant.helpers import device_registry as dr, entity_registry as er from homeassistant.helpers.trigger import async_initialize_triggers from homeassistant.setup import async_setup_component +from homeassistant.util import dt as dt_util from .common import help_test_unload_config_entry -from tests.common import async_fire_mqtt_message, async_get_device_automations +from tests.common import ( + MockConfigEntry, + async_fire_mqtt_message, + async_fire_time_changed, + async_get_device_automations, +) from tests.typing import MqttMockHAClientGenerator, WebSocketGenerator @@ -1865,3 +1880,118 @@ async def test_unload_entry( await hass.async_block_till_done() assert len(service_calls) == 2 await hass.async_block_till_done(wait_background_tasks=True) + + +async def _async_reload_entry(hass: HomeAssistant, entry: ConfigEntry) -> None: + """Reload the MQTT config entry.""" + assert await hass.config_entries.async_reload(entry.entry_id) + + +async def _async_enable_disabled_entity( + hass: HomeAssistant, entry: ConfigEntry +) -> None: + """Enable a disabled entity, which makes the entity registry reload the entry.""" + entity_registry = er.async_get(hass) + entity_id = entity_registry.async_get_entity_id( + Platform.SENSOR, DOMAIN, "0AFFD2_battery" + ) + assert entity_id is not None + entity_registry.async_update_entity(entity_id, disabled_by=None) + await hass.async_block_till_done() + async_fire_time_changed( + hass, dt_util.utcnow() + timedelta(seconds=RELOAD_AFTER_UPDATE_DELAY + 1) + ) + await hass.async_block_till_done() + + +@pytest.mark.parametrize( + "reload_entry", + [ + pytest.param(_async_reload_entry, id="reload"), + pytest.param(_async_enable_disabled_entity, id="enable_entity"), + ], +) +@pytest.mark.usefixtures("mqtt_client_mock") +@patch("homeassistant.components.mqtt.client.DISCOVERY_COOLDOWN", 0.0) +@patch("homeassistant.components.mqtt.client.INITIAL_SUBSCRIBE_COOLDOWN", 0.0) +@patch("homeassistant.components.mqtt.client.SUBSCRIBE_COOLDOWN", 0.0) +@patch("homeassistant.components.mqtt.client.UNSUBSCRIBE_COOLDOWN", 0.0) +async def test_fires_once_after_entry_reload( + hass: HomeAssistant, + device_registry: dr.DeviceRegistry, + service_calls: list[ServiceCall], + reload_entry: Callable[[HomeAssistant, ConfigEntry], Awaitable[None]], +) -> None: + """Test a device trigger fires once per message after the MQTT entry reloads.""" + # Uses a real MQTT client, so subscriptions are restored on reload + entry = MockConfigEntry( + domain=DOMAIN, + data={mqtt.CONF_BROKER: "mock-broker"}, + version=mqtt.CONFIG_ENTRY_VERSION, + minor_version=mqtt.CONFIG_ENTRY_MINOR_VERSION, + ) + entry.add_to_hass(hass) + assert await hass.config_entries.async_setup(entry.entry_id) + await hass.async_block_till_done() + + trigger_discovery_topic = "homeassistant/device_automation/0AFFD2/scene_1/config" + trigger_config = ( + '{ "automation_type":"trigger",' + ' "device":{"identifiers":["0AFFD2"]},' + ' "payload": "scene_1",' + ' "topic": "zigbee2mqtt/0AFFD2/action",' + ' "type": "action",' + ' "subtype": "scene_1" }' + ) + async_fire_mqtt_message(hass, trigger_discovery_topic, trigger_config, retain=True) + async_fire_mqtt_message( + hass, + "homeassistant/sensor/0AFFD2/battery/config", + '{ "name": "Battery",' + ' "unique_id": "0AFFD2_battery",' + ' "state_topic": "zigbee2mqtt/0AFFD2",' + ' "enabled_by_default": false,' + ' "device":{"identifiers":["0AFFD2"]} }', + retain=True, + ) + await hass.async_block_till_done() + device_entry = device_registry.async_get_device_by_identifier( + ("mqtt", "0AFFD2"), entry.entry_id + ) + + assert await async_setup_component( + hass, + automation.DOMAIN, + { + automation.DOMAIN: [ + { + "trigger": { + "platform": "device", + "domain": DOMAIN, + "device_id": device_entry.id, + "type": "action", + "subtype": "scene_1", + }, + "action": {"service": "test.automation"}, + }, + ] + }, + ) + await hass.async_block_till_done() + + async_fire_mqtt_message(hass, "zigbee2mqtt/0AFFD2/action", "scene_1") + await hass.async_block_till_done() + assert len(service_calls) == 1 + + client_before_reload = hass.data[DATA_MQTT].client + await reload_entry(hass, entry) + assert entry.state is ConfigEntryState.LOADED + assert hass.data[DATA_MQTT].client is not client_before_reload + + # The broker replays the retained discovery payload after the reload + async_fire_mqtt_message(hass, trigger_discovery_topic, trigger_config, retain=True) + await hass.async_block_till_done() + + async_fire_mqtt_message(hass, "zigbee2mqtt/0AFFD2/action", "scene_1") + await hass.async_block_till_done() + assert len(service_calls) == 2 diff --git a/tests/components/mqtt/test_tag.py b/tests/components/mqtt/test_tag.py index 866dde7b73d2..46165ea0c8b2 100644 --- a/tests/components/mqtt/test_tag.py +++ b/tests/components/mqtt/test_tag.py @@ -3,12 +3,15 @@ import copy import json from typing import Any -from unittest.mock import ANY, AsyncMock +from unittest.mock import ANY, AsyncMock, patch import pytest +from homeassistant.components import mqtt from homeassistant.components.device_automation import DeviceAutomationType from homeassistant.components.mqtt.const import DOMAIN +from homeassistant.components.mqtt.models import DATA_MQTT +from homeassistant.config_entries import ConfigEntryState from homeassistant.core import HomeAssistant from homeassistant.helpers import device_registry as dr from homeassistant.setup import async_setup_component @@ -1028,6 +1031,48 @@ async def test_unload_entry( tag_mock.assert_not_called() +@pytest.mark.usefixtures("mqtt_client_mock") +@patch("homeassistant.components.mqtt.client.DISCOVERY_COOLDOWN", 0.0) +@patch("homeassistant.components.mqtt.client.INITIAL_SUBSCRIBE_COOLDOWN", 0.0) +@patch("homeassistant.components.mqtt.client.SUBSCRIBE_COOLDOWN", 0.0) +@patch("homeassistant.components.mqtt.client.UNSUBSCRIBE_COOLDOWN", 0.0) +async def test_fires_once_after_entry_reload( + hass: HomeAssistant, device_registry: dr.DeviceRegistry, tag_mock: AsyncMock +) -> None: + """Test a tag scanner fires once per message after the MQTT entry reloads.""" + # Uses a real MQTT client, so subscriptions are restored on reload + entry = MockConfigEntry( + domain=DOMAIN, + data={mqtt.CONF_BROKER: "mock-broker"}, + version=mqtt.CONFIG_ENTRY_VERSION, + minor_version=mqtt.CONFIG_ENTRY_MINOR_VERSION, + ) + entry.add_to_hass(hass) + assert await hass.config_entries.async_setup(entry.entry_id) + await hass.async_block_till_done() + + config = json.dumps(DEFAULT_CONFIG_DEVICE) + async_fire_mqtt_message(hass, "homeassistant/tag/bla1/config", config, retain=True) + await hass.async_block_till_done() + device_entry = device_registry.async_get_device_by_identifier( + ("mqtt", "0AFFD2"), entry.entry_id + ) + + client_before_reload = hass.data[DATA_MQTT].client + assert await hass.config_entries.async_reload(entry.entry_id) + await hass.async_block_till_done() + assert entry.state is ConfigEntryState.LOADED + assert hass.data[DATA_MQTT].client is not client_before_reload + + # The broker replays the retained discovery payload after the reload + async_fire_mqtt_message(hass, "homeassistant/tag/bla1/config", config, retain=True) + await hass.async_block_till_done() + + async_fire_mqtt_message(hass, "foobar/tag_scanned", DEFAULT_TAG_SCAN) + await hass.async_block_till_done() + tag_mock.assert_called_once_with(ANY, DEFAULT_TAG_ID, device_entry.id) + + @pytest.mark.usefixtures("mqtt_mock", "tag_mock") async def test_value_template_fails( hass: HomeAssistant, caplog: pytest.LogCaptureFixture