Avoid redundant calls to async_write_ha_state in mqtt device_tracker (#100767)

Avoid redundant calls to async_ha_write_state
This commit is contained in:
Jan Bouwhuis 2023-09-24 12:52:13 +02:00 committed by GitHub
parent f0375eb97e
commit edb28be964
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 40 additions and 3 deletions

View File

@ -36,9 +36,10 @@ from .mixins import (
MQTT_ENTITY_COMMON_SCHEMA,
MqttEntity,
async_setup_entry_helper,
write_state_on_attr_change,
)
from .models import MqttValueTemplate, ReceiveMessage, ReceivePayloadType
from .util import get_mqtt_data, valid_subscribe_topic
from .util import valid_subscribe_topic
CONF_PAYLOAD_HOME = "payload_home"
CONF_PAYLOAD_NOT_HOME = "payload_not_home"
@ -135,6 +136,7 @@ class MqttDeviceTracker(MqttEntity, TrackerEntity):
@callback
@log_messages(self.hass, self.entity_id)
@write_state_on_attr_change(self, {"_location_name"})
def message_received(msg: ReceiveMessage) -> None:
"""Handle new MQTT messages."""
payload: ReceivePayloadType = self._value_template(msg.payload)
@ -148,8 +150,6 @@ class MqttDeviceTracker(MqttEntity, TrackerEntity):
assert isinstance(msg.payload, str)
self._location_name = msg.payload
get_mqtt_data(self.hass).state_write_requests.write_state_request(self)
state_topic: str | None = self._config.get(CONF_STATE_TOPIC)
if state_topic is None:
return

View File

@ -13,8 +13,10 @@ from homeassistant.helpers import device_registry as dr, entity_registry as er
from homeassistant.setup import async_setup_component
from .test_common import (
help_custom_config,
help_test_reloadable,
help_test_setting_blocked_attribute_via_mqtt_json_message,
help_test_skipped_async_ha_write_state,
)
from tests.common import async_fire_mqtt_message
@ -636,3 +638,38 @@ async def test_reloadable(
domain = device_tracker.DOMAIN
config = DEFAULT_CONFIG
await help_test_reloadable(hass, mqtt_client_mock, domain, config)
@pytest.mark.parametrize(
"hass_config",
[
help_custom_config(
device_tracker.DOMAIN,
DEFAULT_CONFIG,
(
{
"availability_topic": "availability-topic",
"json_attributes_topic": "json-attributes-topic",
},
),
)
],
)
@pytest.mark.parametrize(
("topic", "payload1", "payload2"),
[
("test-topic", "home", "work"),
("availability-topic", "online", "offline"),
("json-attributes-topic", '{"attr1": "val1"}', '{"attr1": "val2"}'),
],
)
async def test_skipped_async_ha_write_state(
hass: HomeAssistant,
mqtt_mock_entry: MqttMockHAClientGenerator,
topic: str,
payload1: str,
payload2: str,
) -> None:
"""Test a write state command is only called when there is change."""
await mqtt_mock_entry()
await help_test_skipped_async_ha_write_state(hass, topic, payload1, payload2)