Skip to content

Commit

Permalink
Restore speed when turning a Tasmota fan back on (home-assistant#84337)
Browse files Browse the repository at this point in the history
  • Loading branch information
emontnemery authored Dec 22, 2022
1 parent 2bd1a68 commit 41341c7
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 1 deletion.
6 changes: 5 additions & 1 deletion homeassistant/components/tasmota/fan.py
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand All @@ -84,6 +85,9 @@ async def async_added_to_hass(self) -> None:
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
Expand Down Expand Up @@ -121,7 +125,7 @@ async def async_turn_on(
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
)
)

Expand Down
27 changes: 27 additions & 0 deletions tests/components/tasmota/test_fan.py
Original file line number Diff line number Diff line change
Expand Up @@ -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."""
Expand Down

0 comments on commit 41341c7

Please sign in to comment.