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

@ -45,6 +45,7 @@ from .mixins import (
MqttAvailability,
MqttEntity,
async_setup_entry_helper,
write_state_on_attr_change,
)
from .models import (
MqttValueTemplate,
@ -52,7 +53,6 @@ from .models import (
ReceiveMessage,
ReceivePayloadType,
)
from .util import get_mqtt_data
_LOGGER = logging.getLogger(__name__)
@ -287,13 +287,13 @@ class MqttSensor(MqttEntity, RestoreSensor):
)
@callback
@write_state_on_attr_change(self, {"_attr_native_value", "_attr_last_reset"})
@log_messages(self.hass, self.entity_id)
def message_received(msg: ReceiveMessage) -> None:
"""Handle new MQTT messages."""
_update_state(msg)
if CONF_LAST_RESET_VALUE_TEMPLATE in self._config:
_update_last_reset(msg)
get_mqtt_data(self.hass).state_write_requests.write_state_request(self)
topics["state_topic"] = {
"topic": self._config[CONF_STATE_TOPIC],