From 5a8279462c5ba42e43344b1ae96bae01d37abaa2 Mon Sep 17 00:00:00 2001 From: infy1995 Date: Sun, 22 Nov 2026 10:33:58 +0100 Subject: [PATCH 1/3] fix(v1): ignore water codes pushed to water-slide devices that the slider cannot name Water-slide devices push legacy water codes (201-203 and 208) while get_status returns slider codes. Applying the pushed legacy code left water_mode_name as None until the next poll. On water-slide devices a pushed water code is now kept only when the slider can name it, or when it is the off, smart water, smart mode or custom code. Non-integer payloads are dropped without raising, so the rest of the push is still applied. --- roborock/devices/traits/v1/status.py | 30 +++++++++++ tests/devices/traits/v1/test_status.py | 72 +++++++++++++++++++++++++- 2 files changed, 101 insertions(+), 1 deletion(-) diff --git a/roborock/devices/traits/v1/status.py b/roborock/devices/traits/v1/status.py index 1bf0f09cf..4fb2395b9 100644 --- a/roborock/devices/traits/v1/status.py +++ b/roborock/devices/traits/v1/status.py @@ -33,6 +33,32 @@ _DPS_CONVERTER = DpsDataConverter.from_dataclass(StatusV2) +# Non-slider codes that water-slide devices report as valid (custom and smart mode). +_WATER_MODE_CODES_KEPT = frozenset({WaterModes.CUSTOMIZED.code, WaterModes.SMART_MODE.code}) + + +def _drop_unresolvable_water_level(decoded_dps: dict[RoborockDataProtocol, Any]) -> dict[RoborockDataProtocol, Any]: + """Return the pushed data without a water code a water-slide device cannot name. + + Water-slide devices push legacy codes (201-203, 208) that get_status never + returns. Only slider codes, off, smart water, smart mode and custom are kept. + """ + if RoborockDataProtocol.WATER_BOX_MODE not in decoded_dps: + return decoded_dps + # The pushed value is raw JSON, so narrow it to an integer before resolving it. + raw = decoded_dps[RoborockDataProtocol.WATER_BOX_MODE] + code: int | None = None + if isinstance(raw, int) and not isinstance(raw, bool): + code = raw + elif isinstance(raw, str): + try: + code = int(raw) + except ValueError: + code = None + if code is not None and (code in _WATER_MODE_CODES_KEPT or get_water_slide_mode_name(code) is not None): + return decoded_dps + return {key: value for key, value in decoded_dps.items() if key != RoborockDataProtocol.WATER_BOX_MODE} + class StatusTrait(StatusV2, common.V1TraitMixin, TraitUpdateListener): """Trait for managing the status of Roborock devices. @@ -179,5 +205,9 @@ def update_from_dps(self, decoded_dps: dict[RoborockDataProtocol, Any]) -> None: This handles unsolicited status updates pushed by the device via RoborockDataProtocol codes (e.g. STATE=121, BATTERY=122). """ + # Water-slide devices push legacy codes (e.g. 201-203, 208) while get_status + # returns slider codes, so a pushed legacy code would overwrite the real value. + if self._device_features_trait.is_water_slide_mode_supported: + decoded_dps = _drop_unresolvable_water_level(decoded_dps) if _DPS_CONVERTER.update_from_dps(self, decoded_dps): self._notify_update() diff --git a/tests/devices/traits/v1/test_status.py b/tests/devices/traits/v1/test_status.py index a890e8d92..81296ebc0 100644 --- a/tests/devices/traits/v1/test_status.py +++ b/tests/devices/traits/v1/test_status.py @@ -3,7 +3,7 @@ import asyncio import warnings from typing import cast -from unittest.mock import AsyncMock, call +from unittest.mock import AsyncMock, Mock, call import pytest @@ -14,6 +14,7 @@ WaterModes, get_cleaning_mode_parameters, get_current_cleaning_mode, + get_water_slide_mode_name, resolve_cleaning_mode, ) from roborock.data import SHORT_MODEL_TO_ENUM, HomeDataDevice, RoborockProductNickname @@ -952,6 +953,75 @@ def test_update_from_dps_partial(status_trait: StatusTrait) -> None: assert status_trait.state == RoborockStateCode.charging # Unchanged +@pytest.mark.parametrize("pushed", [201, 202, 203, 208, 251, 999]) +def test_update_from_dps_water_slide_ignores_unresolvable_water_codes(pushed: int) -> None: + """Water codes the slider cannot name do not overwrite the slider value.""" + status_trait = _create_cleaning_mode_status_trait(is_water_slide_mode_supported=True) + status_trait.water_box_mode = 235 + listener = Mock() + status_trait.add_update_listener(listener) + + status_trait.update_from_dps({RoborockDataProtocol.WATER_BOX_MODE: pushed}) + + assert status_trait.water_box_mode == 235 + assert status_trait.water_mode_name == get_water_slide_mode_name(235) + listener.assert_not_called() + + +@pytest.mark.parametrize("pushed", [200, WaterModes.CUSTOMIZED.code, 209, 221, 225, 245, 250]) +def test_update_from_dps_water_slide_keeps_other_water_codes(pushed: int) -> None: + """Slider codes pushed to a water-slide device are applied.""" + status_trait = _create_cleaning_mode_status_trait(is_water_slide_mode_supported=True) + status_trait.water_box_mode = 235 + + status_trait.update_from_dps({RoborockDataProtocol.WATER_BOX_MODE: pushed}) + + assert status_trait.water_box_mode == pushed + + +def test_update_from_dps_water_slide_applies_numeric_string_code() -> None: + """A stringified slider code is resolved like the integer.""" + status_trait = _create_cleaning_mode_status_trait(is_water_slide_mode_supported=True) + status_trait.water_box_mode = 225 + + status_trait.update_from_dps({RoborockDataProtocol.WATER_BOX_MODE: "235"}) + + assert status_trait.water_box_mode == 235 + + +@pytest.mark.parametrize("pushed", ["abc", "", True, 1.5, None, [235], {"code": 235}]) +def test_update_from_dps_water_slide_ignores_non_integer_codes(pushed: object) -> None: + """Malformed water codes are dropped without raising and other fields still apply.""" + status_trait = _create_cleaning_mode_status_trait(is_water_slide_mode_supported=True) + status_trait.water_box_mode = 235 + + status_trait.update_from_dps({RoborockDataProtocol.WATER_BOX_MODE: pushed, RoborockDataProtocol.FAN_POWER: 101}) + + assert status_trait.water_box_mode == 235 + assert status_trait.fan_power == 101 + + +def test_update_from_dps_water_slide_still_applies_other_fields() -> None: + """Ignoring a legacy water level does not drop other fields in the same push.""" + status_trait = _create_cleaning_mode_status_trait(is_water_slide_mode_supported=True) + status_trait.water_box_mode = 235 + + status_trait.update_from_dps({RoborockDataProtocol.FAN_POWER: 101, RoborockDataProtocol.WATER_BOX_MODE: 202}) + + assert status_trait.fan_power == 101 + assert status_trait.water_box_mode == 235 + + +@pytest.mark.parametrize("pushed", [201, 202, 203, 208]) +def test_update_from_dps_without_water_slide_keeps_legacy_levels(pushed: int) -> None: + """Devices without the water slider use the legacy level codes.""" + status_trait = _create_cleaning_mode_status_trait(is_water_slide_mode_supported=False) + + status_trait.update_from_dps({RoborockDataProtocol.WATER_BOX_MODE: pushed}) + + assert status_trait.water_box_mode == pushed + + def test_update_listener(status_trait: StatusTrait) -> None: """Test that update listeners receive notifications.""" event = asyncio.Event() From a1c312242fe5b3b278ba83e6cbc51cdbfa2643c6 Mon Sep 17 00:00:00 2001 From: infy1995 Date: Sun, 22 Nov 2026 10:35:03 +0100 Subject: [PATCH 2/3] fix(v1): read back status after fan or water pushes The robot pushes fan power and water mode changes but never pushes the mop mode, so the cleaning mode stayed stale after such a push until the next poll. After a fan power or water mode push the status trait now reads get_status back once, debounced. At most one get_status is in flight at a time, a burst of pushes causes one read-back per window, and a push during a running read-back is followed by another one after it finishes. Listeners are notified only if the read-back changed the status. PropertiesApi.close() cancels a pending or running read-back. --- roborock/devices/traits/v1/__init__.py | 1 + roborock/devices/traits/v1/status.py | 56 ++++++ tests/devices/traits/v1/test_init.py | 55 ++++++ tests/devices/traits/v1/test_status.py | 263 ++++++++++++++++++++++++- 4 files changed, 368 insertions(+), 7 deletions(-) create mode 100644 tests/devices/traits/v1/test_init.py diff --git a/roborock/devices/traits/v1/__init__.py b/roborock/devices/traits/v1/__init__.py index 28c404d65..1c33dcbb8 100644 --- a/roborock/devices/traits/v1/__init__.py +++ b/roborock/devices/traits/v1/__init__.py @@ -265,6 +265,7 @@ def close(self) -> None: if self._unsub: self._unsub() self._unsub = None + self.status.close() def _on_dps_update(self, dps: dict[RoborockDataProtocol, Any]) -> None: """Handle incoming messages from the device. diff --git a/roborock/devices/traits/v1/status.py b/roborock/devices/traits/v1/status.py index 4fb2395b9..e2853ef7c 100644 --- a/roborock/devices/traits/v1/status.py +++ b/roborock/devices/traits/v1/status.py @@ -1,3 +1,4 @@ +import asyncio import logging from functools import cached_property from typing import Any @@ -23,6 +24,7 @@ resolve_cleaning_mode, ) from roborock.devices.traits.common import DpsDataConverter, TraitUpdateListener +from roborock.exceptions import RoborockException from roborock.roborock_message import RoborockDataProtocol from roborock.roborock_typing import RoborockCommand @@ -33,6 +35,10 @@ _DPS_CONVERTER = DpsDataConverter.from_dataclass(StatusV2) +# Delay before reading status back after a fan power or water mode push. The +# robot never pushes the mop mode, so a read-back is needed to get it right. +_STATUS_REFRESH_DELAY = 1.0 + # Non-slider codes that water-slide devices report as valid (custom and smart mode). _WATER_MODE_CODES_KEPT = frozenset({WaterModes.CUSTOMIZED.code, WaterModes.SMART_MODE.code}) @@ -95,6 +101,18 @@ def __init__(self, device_feature_trait: DeviceFeaturesTrait, region: str | None TraitUpdateListener.__init__(self, logger=_LOGGER) self._device_features_trait = device_feature_trait self._region = region + # A single task serializes the status read-backs after pushes; the flag + # records that a push still needs one. The task reference is kept so it + # is not garbage collected and can be cancelled in close(). + self._status_refresh_needed = False + self._status_refresh_task: asyncio.Task[None] | None = None + + def close(self) -> None: + """Cancel any pending or running status read-back.""" + self._status_refresh_needed = False + if self._status_refresh_task: + self._status_refresh_task.cancel() + self._status_refresh_task = None @property def dock_state(self) -> RoborockDockState: @@ -204,10 +222,48 @@ def update_from_dps(self, decoded_dps: dict[RoborockDataProtocol, Any]) -> None: This handles unsolicited status updates pushed by the device via RoborockDataProtocol codes (e.g. STATE=121, BATTERY=122). + + A push of the fan power or water mode also schedules a debounced status + read-back, since the device never pushes the mop mode. This needs a + running event loop. """ + # Decide on the raw push, before the water code filter below rebinds it. + needs_read_back = ( + RoborockDataProtocol.FAN_POWER in decoded_dps or RoborockDataProtocol.WATER_BOX_MODE in decoded_dps + ) # Water-slide devices push legacy codes (e.g. 201-203, 208) while get_status # returns slider codes, so a pushed legacy code would overwrite the real value. if self._device_features_trait.is_water_slide_mode_supported: decoded_dps = _drop_unresolvable_water_level(decoded_dps) if _DPS_CONVERTER.update_from_dps(self, decoded_dps): self._notify_update() + if needs_read_back: + self._schedule_status_refresh() + + def _schedule_status_refresh(self) -> None: + """Request a debounced status read-back, starting the worker if it is idle.""" + self._status_refresh_needed = True + # At most one read-back per delay window, and never two at once. + if self._status_refresh_task and not self._status_refresh_task.done(): + return + # Look up the loop first so a missing loop raises before a coroutine is created. + loop = asyncio.get_running_loop() + self._status_refresh_task = loop.create_task(self._refresh_status_after_push()) + + async def _refresh_status_after_push(self) -> None: + """Read status back after a short delay to pick up values that are not pushed.""" + while self._status_refresh_needed: + await asyncio.sleep(_STATUS_REFRESH_DELAY) + # Clear before reading so a push during the read-back requests another one. + self._status_refresh_needed = False + try: + await self.refresh_and_notify() + except RoborockException as err: + _LOGGER.warning("Failed to refresh status after a push: %s", err) + + async def refresh_and_notify(self) -> None: + """Refresh the status and notify update listeners if any value changed.""" + before = self.as_dict() + await self.refresh() + if self.as_dict() != before: + self._notify_update() diff --git a/tests/devices/traits/v1/test_init.py b/tests/devices/traits/v1/test_init.py new file mode 100644 index 000000000..23299efe6 --- /dev/null +++ b/tests/devices/traits/v1/test_init.py @@ -0,0 +1,55 @@ +"""Tests for the V1 trait properties API.""" + +import asyncio +from collections.abc import Callable +from typing import Any +from unittest.mock import AsyncMock, Mock + +import pytest + +from roborock.data import HomeData, HomeDataDevice, HomeDataProduct +from roborock.devices.cache import DeviceCache +from roborock.devices.traits import v1 +from roborock.devices.traits.v1 import status as status_module +from roborock.roborock_message import RoborockDataProtocol + +DELAY = 0.01 + + +async def test_close_cancels_status_read_back( + device_info: HomeDataDevice, + products: list[HomeDataProduct], + trait_home_data: HomeData, + device_cache: DeviceCache, + monkeypatch: pytest.MonkeyPatch, +) -> None: + """Closing the properties API stops a status read-back that a push scheduled.""" + monkeypatch.setattr(status_module, "_STATUS_REFRESH_DELAY", DELAY) + product = next(p for p in products if p.id == device_info.product_id) + listeners: list[Callable[[dict[RoborockDataProtocol, Any]], None]] = [] + + def add_dps_listener(listener: Callable[[dict[RoborockDataProtocol, Any]], None]) -> Callable[[], None]: + listeners.append(listener) + return Mock() + + api = v1.create( + device_info.duid, + product, + trait_home_data, + AsyncMock(), + AsyncMock(), + AsyncMock(), + AsyncMock(), + add_dps_listener, + AsyncMock(), + device_cache=device_cache, + ) + api.discover_features = AsyncMock() # type: ignore[method-assign] + api.status.refresh_and_notify = AsyncMock() # type: ignore[method-assign] + await api.start() + + listeners[0]({RoborockDataProtocol.FAN_POWER: 101}) + api.close() + + await asyncio.sleep(DELAY * 8) + api.status.refresh_and_notify.assert_not_awaited() # type: ignore[attr-defined] diff --git a/tests/devices/traits/v1/test_status.py b/tests/devices/traits/v1/test_status.py index 81296ebc0..bfd0a08c5 100644 --- a/tests/devices/traits/v1/test_status.py +++ b/tests/devices/traits/v1/test_status.py @@ -2,6 +2,7 @@ import asyncio import warnings +from collections.abc import Iterator from typing import cast from unittest.mock import AsyncMock, Mock, call @@ -28,6 +29,7 @@ ) from roborock.device_features import DeviceFeatures from roborock.devices.device import RoborockDevice +from roborock.devices.traits.v1 import status as status_module from roborock.devices.traits.v1.device_features import DeviceFeaturesTrait from roborock.devices.traits.v1.status import StatusTrait from roborock.exceptions import RoborockException, RoborockParsingException, RoborockUnsupportedFeature @@ -920,7 +922,7 @@ def test_water_slide_mode_name_covers_slider_positions(water_box_mode: int, expe assert status_trait.water_mode_name == expected_name -def test_update_from_dps(status_trait: StatusTrait) -> None: +async def test_update_from_dps(status_trait: StatusTrait) -> None: """Test updating status from data protocol push message.""" assert status_trait.battery is None assert status_trait.state is None @@ -938,6 +940,14 @@ def test_update_from_dps(status_trait: StatusTrait) -> None: assert status_trait.fan_power == 102 +def test_update_from_dps_applies_values_even_if_read_back_cannot_be_scheduled(status_trait: StatusTrait) -> None: + """Without a running event loop the read-back cannot be scheduled, but the push is still applied.""" + with pytest.raises(RuntimeError): + status_trait.update_from_dps({RoborockDataProtocol.FAN_POWER: 102}) + + assert status_trait.fan_power == 102 + + def test_update_from_dps_partial(status_trait: StatusTrait) -> None: """Test that partial updates only modify the specified fields.""" status_trait.battery = 100 @@ -954,7 +964,7 @@ def test_update_from_dps_partial(status_trait: StatusTrait) -> None: @pytest.mark.parametrize("pushed", [201, 202, 203, 208, 251, 999]) -def test_update_from_dps_water_slide_ignores_unresolvable_water_codes(pushed: int) -> None: +async def test_update_from_dps_water_slide_ignores_unresolvable_water_codes(pushed: int) -> None: """Water codes the slider cannot name do not overwrite the slider value.""" status_trait = _create_cleaning_mode_status_trait(is_water_slide_mode_supported=True) status_trait.water_box_mode = 235 @@ -969,7 +979,7 @@ def test_update_from_dps_water_slide_ignores_unresolvable_water_codes(pushed: in @pytest.mark.parametrize("pushed", [200, WaterModes.CUSTOMIZED.code, 209, 221, 225, 245, 250]) -def test_update_from_dps_water_slide_keeps_other_water_codes(pushed: int) -> None: +async def test_update_from_dps_water_slide_keeps_other_water_codes(pushed: int) -> None: """Slider codes pushed to a water-slide device are applied.""" status_trait = _create_cleaning_mode_status_trait(is_water_slide_mode_supported=True) status_trait.water_box_mode = 235 @@ -979,7 +989,7 @@ def test_update_from_dps_water_slide_keeps_other_water_codes(pushed: int) -> Non assert status_trait.water_box_mode == pushed -def test_update_from_dps_water_slide_applies_numeric_string_code() -> None: +async def test_update_from_dps_water_slide_applies_numeric_string_code() -> None: """A stringified slider code is resolved like the integer.""" status_trait = _create_cleaning_mode_status_trait(is_water_slide_mode_supported=True) status_trait.water_box_mode = 225 @@ -990,7 +1000,7 @@ def test_update_from_dps_water_slide_applies_numeric_string_code() -> None: @pytest.mark.parametrize("pushed", ["abc", "", True, 1.5, None, [235], {"code": 235}]) -def test_update_from_dps_water_slide_ignores_non_integer_codes(pushed: object) -> None: +async def test_update_from_dps_water_slide_ignores_non_integer_codes(pushed: object) -> None: """Malformed water codes are dropped without raising and other fields still apply.""" status_trait = _create_cleaning_mode_status_trait(is_water_slide_mode_supported=True) status_trait.water_box_mode = 235 @@ -1001,7 +1011,7 @@ def test_update_from_dps_water_slide_ignores_non_integer_codes(pushed: object) - assert status_trait.fan_power == 101 -def test_update_from_dps_water_slide_still_applies_other_fields() -> None: +async def test_update_from_dps_water_slide_still_applies_other_fields() -> None: """Ignoring a legacy water level does not drop other fields in the same push.""" status_trait = _create_cleaning_mode_status_trait(is_water_slide_mode_supported=True) status_trait.water_box_mode = 235 @@ -1013,7 +1023,7 @@ def test_update_from_dps_water_slide_still_applies_other_fields() -> None: @pytest.mark.parametrize("pushed", [201, 202, 203, 208]) -def test_update_from_dps_without_water_slide_keeps_legacy_levels(pushed: int) -> None: +async def test_update_from_dps_without_water_slide_keeps_legacy_levels(pushed: int) -> None: """Devices without the water slider use the legacy level codes.""" status_trait = _create_cleaning_mode_status_trait(is_water_slide_mode_supported=False) @@ -1061,3 +1071,242 @@ def test_update_listener_ignores_unrelated(status_trait: StatusTrait) -> None: assert not event.is_set() unsubscribe() + + +async def test_refresh_and_notify_notifies_when_values_changed( + status_trait: StatusTrait, mock_rpc_channel: AsyncMock +) -> None: + """Listeners hear about water and mop route values that changed in the read-back.""" + status_trait.water_box_mode = 202 + status_trait.mop_mode = 300 + listener = Mock() + status_trait.add_update_listener(listener) + mock_rpc_channel.send_command.return_value = [{**STATUS, "water_box_mode": 203, "mop_mode": 301}] + + await status_trait.refresh_and_notify() + + assert status_trait.water_box_mode == 203 + assert status_trait.mop_mode == 301 + listener.assert_called_once_with() + + +async def test_refresh_and_notify_silent_when_nothing_changed( + status_trait: StatusTrait, mock_rpc_channel: AsyncMock +) -> None: + """Listeners are not called when the read-back matches the current state.""" + mock_rpc_channel.send_command.return_value = [STATUS] + await status_trait.refresh() + listener = Mock() + status_trait.add_update_listener(listener) + + await status_trait.refresh_and_notify() + + listener.assert_not_called() + + +async def test_refresh_and_notify_propagates_exception(status_trait: StatusTrait, mock_rpc_channel: AsyncMock) -> None: + """Errors from the read-back reach the caller and do not notify.""" + listener = Mock() + status_trait.add_update_listener(listener) + mock_rpc_channel.send_command.side_effect = RoborockException("boom") + + with pytest.raises(RoborockException): + await status_trait.refresh_and_notify() + + listener.assert_not_called() + + +READ_BACK_DELAY = 0.01 +# Long enough for a read-back that should not happen to have run. +READ_BACK_SETTLE = READ_BACK_DELAY * 8 +READ_BACK_TIMEOUT = 1 + + +@pytest.fixture(autouse=True) +def close_scheduled_read_backs(monkeypatch: pytest.MonkeyPatch) -> Iterator[None]: + """Close every trait that scheduled a read-back so no task is left pending after a test.""" + scheduled: list[StatusTrait] = [] + schedule = StatusTrait._schedule_status_refresh + + def recording_schedule(self: StatusTrait) -> None: + scheduled.append(self) + schedule(self) + + monkeypatch.setattr(StatusTrait, "_schedule_status_refresh", recording_schedule) + yield + for trait in scheduled: + trait.close() + + +@pytest.fixture(name="read_back") +def read_back_fixture(status_trait: StatusTrait, monkeypatch: pytest.MonkeyPatch) -> asyncio.Event: + """Shorten the read-back delay, mock the read-back and return an event set each time it runs.""" + monkeypatch.setattr(status_module, "_STATUS_REFRESH_DELAY", READ_BACK_DELAY) + ran = asyncio.Event() + + async def refresh() -> None: + ran.set() + + status_trait.refresh_and_notify = AsyncMock(side_effect=refresh) # type: ignore[method-assign] + return ran + + +async def test_fan_and_water_push_reads_status_back(status_trait: StatusTrait, read_back: asyncio.Event) -> None: + """A fan power and water mode push triggers one status read-back.""" + status_trait.update_from_dps({RoborockDataProtocol.FAN_POWER: 101, RoborockDataProtocol.WATER_BOX_MODE: 202}) + status_trait.refresh_and_notify.assert_not_awaited() # type: ignore[attr-defined] + + await asyncio.wait_for(read_back.wait(), timeout=READ_BACK_TIMEOUT) + await asyncio.sleep(READ_BACK_SETTLE) + status_trait.refresh_and_notify.assert_awaited_once() # type: ignore[attr-defined] + + +async def test_repeated_pushes_are_debounced(status_trait: StatusTrait, read_back: asyncio.Event) -> None: + """Several pushes before the delay elapses cause a single read-back.""" + status_trait.update_from_dps({RoborockDataProtocol.FAN_POWER: 101}) + status_trait.update_from_dps({RoborockDataProtocol.WATER_BOX_MODE: 202}) + status_trait.update_from_dps({RoborockDataProtocol.FAN_POWER: 102}) + + await asyncio.wait_for(read_back.wait(), timeout=READ_BACK_TIMEOUT) + await asyncio.sleep(READ_BACK_SETTLE) + status_trait.refresh_and_notify.assert_awaited_once() # type: ignore[attr-defined] + + +async def test_unrelated_push_does_not_read_back(status_trait: StatusTrait, read_back: asyncio.Event) -> None: + """Pushes without fan power or water mode do not refresh status.""" + status_trait.update_from_dps({RoborockDataProtocol.BATTERY: 80}) + + await asyncio.sleep(READ_BACK_SETTLE) + status_trait.refresh_and_notify.assert_not_awaited() # type: ignore[attr-defined] + + +async def test_read_back_failure_is_contained(status_trait: StatusTrait, read_back: asyncio.Event) -> None: + """A failing read-back does not raise and later pushes still read back.""" + ran = asyncio.Event() + + async def failing_refresh() -> None: + ran.set() + raise RoborockException("boom") + + status_trait.refresh_and_notify.side_effect = failing_refresh # type: ignore[attr-defined] + status_trait.update_from_dps({RoborockDataProtocol.FAN_POWER: 101}) + await asyncio.wait_for(ran.wait(), timeout=READ_BACK_TIMEOUT) + + ran.clear() + status_trait.update_from_dps({RoborockDataProtocol.FAN_POWER: 102}) + await asyncio.wait_for(ran.wait(), timeout=READ_BACK_TIMEOUT) + assert status_trait.refresh_and_notify.await_count == 2 # type: ignore[attr-defined] + + +async def test_close_cancels_pending_read_back(status_trait: StatusTrait, read_back: asyncio.Event) -> None: + """Closing while a read-back is pending prevents it from running.""" + status_trait.update_from_dps({RoborockDataProtocol.FAN_POWER: 101}) + status_trait.close() + + await asyncio.sleep(READ_BACK_SETTLE) + status_trait.refresh_and_notify.assert_not_awaited() # type: ignore[attr-defined] + + +async def test_close_cancels_in_flight_read_back(status_trait: StatusTrait, read_back: asyncio.Event) -> None: + """Closing while a read-back is running cancels it.""" + started = asyncio.Event() + cancelled = asyncio.Event() + + async def hanging_refresh() -> None: + started.set() + try: + await asyncio.Event().wait() + except asyncio.CancelledError: + cancelled.set() + raise + + status_trait.refresh_and_notify.side_effect = hanging_refresh # type: ignore[attr-defined] + status_trait.update_from_dps({RoborockDataProtocol.FAN_POWER: 101}) + await asyncio.wait_for(started.wait(), timeout=READ_BACK_TIMEOUT) + + status_trait.close() + await asyncio.wait_for(cancelled.wait(), timeout=READ_BACK_TIMEOUT) + status_trait.refresh_and_notify.assert_awaited_once() # type: ignore[attr-defined] + + +async def test_push_during_read_back_schedules_another_after_it( + status_trait: StatusTrait, read_back: asyncio.Event +) -> None: + """A push arriving while a read-back runs is followed by another one, never concurrently.""" + started = asyncio.Event() + release = asyncio.Event() + second_ran = asyncio.Event() + calls = 0 + running = 0 + max_running = 0 + + async def slow_refresh() -> None: + nonlocal calls, running, max_running + calls += 1 + call = calls + running += 1 + max_running = max(max_running, running) + try: + if call == 1: + started.set() + await release.wait() + # Each response is applied when its call finishes. + status_trait.mop_mode = call + finally: + running -= 1 + if call == 2: + second_ran.set() + + status_trait.refresh_and_notify.side_effect = slow_refresh # type: ignore[attr-defined] + status_trait.update_from_dps({RoborockDataProtocol.FAN_POWER: 101}) + await asyncio.wait_for(started.wait(), timeout=READ_BACK_TIMEOUT) + + status_trait.update_from_dps({RoborockDataProtocol.WATER_BOX_MODE: 202}) + # Give a (wrongly) concurrent second read-back the chance to start. + await asyncio.sleep(READ_BACK_SETTLE) + assert calls == 1 + release.set() + + await asyncio.wait_for(second_ran.wait(), timeout=READ_BACK_TIMEOUT) + assert calls == 2 + assert max_running == 1 + assert status_trait.mop_mode == 2 + + +async def test_malformed_water_code_still_applies_other_fields_and_reads_back( + monkeypatch: pytest.MonkeyPatch, +) -> None: + """A malformed water code on a slide device does not stop the other fields or the read-back.""" + monkeypatch.setattr(status_module, "_STATUS_REFRESH_DELAY", READ_BACK_DELAY) + status_trait = _create_cleaning_mode_status_trait(is_water_slide_mode_supported=True) + ran = asyncio.Event() + + async def refresh() -> None: + ran.set() + + status_trait.refresh_and_notify = AsyncMock(side_effect=refresh) # type: ignore[method-assign] + status_trait.update_from_dps({RoborockDataProtocol.WATER_BOX_MODE: "abc", RoborockDataProtocol.FAN_POWER: 101}) + + assert status_trait.fan_power == 101 + await asyncio.wait_for(ran.wait(), timeout=READ_BACK_TIMEOUT) + status_trait.close() + + +async def test_read_back_notifies_status_listeners(status_trait: StatusTrait, monkeypatch: pytest.MonkeyPatch) -> None: + """Status listeners hear about values changed by the read-back.""" + monkeypatch.setattr(status_module, "_STATUS_REFRESH_DELAY", READ_BACK_DELAY) + changed = asyncio.Event() + listener = Mock(side_effect=lambda: changed.set()) + status_trait.add_update_listener(listener) + + async def refresh() -> None: + status_trait.mop_mode = 301 + + status_trait.refresh = AsyncMock(side_effect=refresh) # type: ignore[method-assign] + status_trait.update_from_dps({RoborockDataProtocol.WATER_BOX_MODE: 202}) + # The push itself notifies once; the read-back's change is the second call. + changed.clear() + + await asyncio.wait_for(changed.wait(), timeout=READ_BACK_TIMEOUT) + assert status_trait.mop_mode == 301 + assert listener.call_count == 2 From 82fee57c1e9bf3ce22f6e7f76643b386240063f1 Mon Sep 17 00:00:00 2001 From: infy1995 Date: Sun, 22 Nov 2026 10:35:07 +0100 Subject: [PATCH 3/3] docs(v1): describe pushed status updates and the status read-back --- docs/DEVICES.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/docs/DEVICES.md b/docs/DEVICES.md index cc7591e6b..6218538aa 100644 --- a/docs/DEVICES.md +++ b/docs/DEVICES.md @@ -11,6 +11,8 @@ Cloud and Network. * **Control**: * **Vacuums (V1)**: Use `device.v1_properties` to access traits like `status` or `consumables`. * Call `await trait.refresh()` to update state. + * The `status` trait also updates from values the robot pushes on its own (fan power, water, state, battery). Register `device.v1_properties.status.add_update_listener(cb)` to be notified. After a pushed fan power or water change the library reads the full status back once, because water on water-slider models is pushed as a legacy level code and the mop route is never pushed. + * A change of only the mop route made in the Roborock app is not pushed, so it shows up with the next `await device.v1_properties.status.refresh()`. * Use `device.v1_properties.command.send()` for raw commands (start/stop). * **Washers (A01)**: Use `device.dyad` or `device.zeo` for Dyad/Zeo devices. * Read `api.values` for the latest known state, merged from query responses and unsolicited pushes.