From be0ef5ad6c437ece3443cf4dfda1f719b299d0f0 Mon Sep 17 00:00:00 2001 From: Erik Montnemery Date: Wed, 16 Feb 2022 23:07:21 +0100 Subject: [PATCH] Correct MQTT binary_sensor and sensor state restoring (#66690) --- homeassistant/components/mqtt/binary_sensor.py | 7 +++---- homeassistant/components/mqtt/sensor.py | 7 +++---- 2 files changed, 6 insertions(+), 8 deletions(-) diff --git a/homeassistant/components/mqtt/binary_sensor.py b/homeassistant/components/mqtt/binary_sensor.py index e3c3f10b98f..40d5c876c11 100644 --- a/homeassistant/components/mqtt/binary_sensor.py +++ b/homeassistant/components/mqtt/binary_sensor.py @@ -126,6 +126,9 @@ class MqttBinarySensor(MqttEntity, BinarySensorEntity, RestoreEntity): and expire_after > 0 and (last_state := await self.async_get_last_state()) is not None and last_state.state not in [STATE_UNKNOWN, STATE_UNAVAILABLE] + # We might have set up a trigger already after subscribing from + # super().async_added_to_hass(), then we should not restore state + and not self._expiration_trigger ): expiration_at = last_state.last_changed + timedelta(seconds=expire_after) if expiration_at < (time_now := dt_util.utcnow()): @@ -135,10 +138,6 @@ class MqttBinarySensor(MqttEntity, BinarySensorEntity, RestoreEntity): self._expired = False self._state = last_state.state == STATE_ON - if self._expiration_trigger: - # We might have set up a trigger already after subscribing from - # super().async_added_to_hass() - self._expiration_trigger() self._expiration_trigger = async_track_point_in_utc_time( self.hass, self._value_is_expired, expiration_at ) diff --git a/homeassistant/components/mqtt/sensor.py b/homeassistant/components/mqtt/sensor.py index 8dd53901755..31a784a259e 100644 --- a/homeassistant/components/mqtt/sensor.py +++ b/homeassistant/components/mqtt/sensor.py @@ -172,6 +172,9 @@ class MqttSensor(MqttEntity, SensorEntity, RestoreEntity): and expire_after > 0 and (last_state := await self.async_get_last_state()) is not None and last_state.state not in [STATE_UNKNOWN, STATE_UNAVAILABLE] + # We might have set up a trigger already after subscribing from + # super().async_added_to_hass(), then we should not restore state + and not self._expiration_trigger ): expiration_at = last_state.last_changed + timedelta(seconds=expire_after) if expiration_at < (time_now := dt_util.utcnow()): @@ -181,10 +184,6 @@ class MqttSensor(MqttEntity, SensorEntity, RestoreEntity): self._expired = False self._state = last_state.state - if self._expiration_trigger: - # We might have set up a trigger already after subscribing from - # super().async_added_to_hass() - self._expiration_trigger() self._expiration_trigger = async_track_point_in_utc_time( self.hass, self._value_is_expired, expiration_at )