Avoid redundant calls to async_ha_write_state in MQTT (binary) sensor (#100438)

* Only call `async_ha_write_state` on changes.

* Make helper class

* Use UndefinedType

* Remove del

* Integrate monitor into MqttEntity

* Track extra state attributes and availability

* Add `__slots__`

* Add monitor to MqttAttributes and MqttAvailability

* Write out loop

* Add test

* Make common test and parameterize

* Add test for last_reset attribute

* MqttMonitorEntity base class

* Rename attr and update docstr `track` method.

* correction doct

* Implement as a decorator

* Move tracking functions into decorator

* Rename decorator

* Follow up comment
This commit is contained in:
Jan Bouwhuis 2023-09-21 13:33:26 +02:00 committed by GitHub
parent 11c4c37cf9
commit aed3ba3acd
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
6 changed files with 147 additions and 11 deletions

View file

@ -43,9 +43,9 @@ from .mixins import (
MqttAvailability,
MqttEntity,
async_setup_entry_helper,
write_state_on_attr_change,
)
from .models import MqttValueTemplate, ReceiveMessage
from .util import get_mqtt_data
_LOGGER = logging.getLogger(__name__)
@ -191,6 +191,7 @@ class MqttBinarySensor(MqttEntity, BinarySensorEntity, RestoreEntity):
@callback
@log_messages(self.hass, self.entity_id)
@write_state_on_attr_change(self, {"_attr_is_on"})
def state_message_received(msg: ReceiveMessage) -> None:
"""Handle a new received MQTT state message."""
# auto-expire enabled?
@ -257,8 +258,6 @@ class MqttBinarySensor(MqttEntity, BinarySensorEntity, RestoreEntity):
self.hass, off_delay, off_delay_listener
)
get_mqtt_data(self.hass).state_write_requests.write_state_request(self)
self._sub_state = subscription.async_prepare_subscribe_topics(
self.hass,
self._sub_state,