From 41341c76cf88eee92ef11c56ead650479cb9539e Mon Sep 17 00:00:00 2001 From: Erik Montnemery Date: Thu, 22 Dec 2022 09:31:14 +0100 Subject: [PATCH] Restore speed when turning a Tasmota fan back on (#84337) --- homeassistant/components/tasmota/fan.py | 6 +++++- tests/components/tasmota/test_fan.py | 27 +++++++++++++++++++++++++ 2 files changed, 32 insertions(+), 1 deletion(-) diff --git a/homeassistant/components/tasmota/fan.py b/homeassistant/components/tasmota/fan.py index 8a1deee7d60..38ba5fcc476 100644 --- a/homeassistant/components/tasmota/fan.py +++ b/homeassistant/components/tasmota/fan.py @@ -65,6 +65,7 @@ class TasmotaFan( """Representation of a Tasmota fan.""" _attr_supported_features = FanEntityFeature.SET_SPEED + _fan_speed = tasmota_const.FAN_SPEED_MEDIUM _tasmota_entity: tasmota_fan.TasmotaFan def __init__(self, **kwds: Any) -> None: @@ -84,6 +85,9 @@ class TasmotaFan( def fan_state_updated(self, state: int, **kwargs: Any) -> None: """Handle state updates.""" self._state = state + if self._state is not None and self._state != 0: + # Store the last known fan speed + self._fan_speed = state self.async_write_ha_state() @property @@ -121,7 +125,7 @@ class TasmotaFan( await self.async_set_percentage( percentage or ordered_list_item_to_percentage( - ORDERED_NAMED_FAN_SPEEDS, tasmota_const.FAN_SPEED_MEDIUM + ORDERED_NAMED_FAN_SPEEDS, self._fan_speed ) ) diff --git a/tests/components/tasmota/test_fan.py b/tests/components/tasmota/test_fan.py index 8c54e913f7c..2d2cb93406b 100644 --- a/tests/components/tasmota/test_fan.py +++ b/tests/components/tasmota/test_fan.py @@ -154,6 +154,33 @@ async def test_sending_mqtt_commands(hass, mqtt_mock, setup_tasmota): "tasmota_49A3BC/cmnd/FanSpeed", "3", 0, False ) + # Test the last known fan speed is restored + # First, get a fan speed update + async_fire_mqtt_message(hass, "tasmota_49A3BC/tele/STATE", '{"FanSpeed":3}') + state = hass.states.get("fan.tasmota") + assert state.state == STATE_ON + assert state.attributes["percentage"] == 100 + mqtt_mock.async_publish.reset_mock() + + # Then turn the fan off and get a fan state update + await common.async_turn_off(hass, "fan.tasmota") + mqtt_mock.async_publish.assert_called_once_with( + "tasmota_49A3BC/cmnd/FanSpeed", "0", 0, False + ) + mqtt_mock.async_publish.reset_mock() + async_fire_mqtt_message(hass, "tasmota_49A3BC/stat/RESULT", '{"FanSpeed":0}') + state = hass.states.get("fan.tasmota") + assert state.state == STATE_OFF + assert state.attributes["percentage"] == 0 + mqtt_mock.async_publish.reset_mock() + + # Finally, turn the fan on again and verify MQTT message is sent with last known speed + await common.async_turn_on(hass, "fan.tasmota") + mqtt_mock.async_publish.assert_called_once_with( + "tasmota_49A3BC/cmnd/FanSpeed", "3", 0, False + ) + mqtt_mock.async_publish.reset_mock() + async def test_invalid_fan_speed_percentage(hass, mqtt_mock, setup_tasmota): """Test the sending MQTT commands."""