Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
38 changes: 38 additions & 0 deletions roborock/devices/traits/v1/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,7 @@
HomeDataProduct Schema that is required for the field to be supported.
"""

import asyncio
import logging
from collections.abc import Callable
from dataclasses import dataclass, field, fields
Expand Down Expand Up @@ -123,6 +124,10 @@

_LOGGER = logging.getLogger(__name__)

# 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

__all__ = [
"PropertiesApi",
"camera",
Expand Down Expand Up @@ -213,6 +218,10 @@ def __init__(
self._device_cache = device_cache
self._region = region
self._unsub: Callable[[], None] | None = None
# True while a read-back is waiting for its delay (debounce). Live read-back
# tasks are kept referenced until done so they are not garbage collected.
self._status_refresh_pending = False
self._status_refresh_tasks: set[asyncio.Task[None]] = set()
self._add_dps_listener = add_dps_listener

self.device_features = DeviceFeaturesTrait(product, self._device_cache)
Expand Down Expand Up @@ -265,17 +274,46 @@ def close(self) -> None:
if self._unsub:
self._unsub()
self._unsub = None
self._status_refresh_pending = False
for task in self._status_refresh_tasks:
task.cancel()
self._status_refresh_tasks.clear()

def _on_dps_update(self, dps: dict[RoborockDataProtocol, Any]) -> None:
"""Handle incoming messages from the device.

This will notify all traits of the new values. This can be improved in
the future to be dynamic when we have more traits that support dynamic
updates but for now we just invoke them manually.

A push of the fan power or water mode also schedules a debounced status
read-back, since the device never pushes the mop mode.
"""
_LOGGER.debug("Received message from device: %s", dps)
self.status.update_from_dps(dps)
self.consumables.update_from_dps(dps)
if RoborockDataProtocol.FAN_POWER in dps or RoborockDataProtocol.WATER_BOX_MODE in dps:
self._schedule_status_refresh()

def _schedule_status_refresh(self) -> None:
"""Schedule a single debounced status read-back unless one is pending."""
# At most one read-back per delay window.
if self._status_refresh_pending:
return
self._status_refresh_pending = True
task = asyncio.create_task(self._refresh_status_after_push())
self._status_refresh_tasks.add(task)
task.add_done_callback(self._status_refresh_tasks.discard)

async def _refresh_status_after_push(self) -> None:
"""Read status back after a short delay to pick up values that are not pushed."""
await asyncio.sleep(_STATUS_REFRESH_DELAY)
# Clear first so a push arriving during the refresh schedules another one.
self._status_refresh_pending = False
try:
await self.status.refresh_and_notify()
except RoborockException as err:
_LOGGER.warning("Failed to refresh status after a push: %s", err)

async def discover_features(self) -> None:
"""Populate any supported traits that were not initialized in __init__."""
Expand Down
27 changes: 27 additions & 0 deletions roborock/devices/traits/v1/status.py
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,22 @@
_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.
"""
code = decoded_dps.get(RoborockDataProtocol.WATER_BOX_MODE)
if code is None or 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.

Expand Down Expand Up @@ -176,5 +192,16 @@ 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()

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()
221 changes: 221 additions & 0 deletions tests/devices/traits/v1/test_init.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,221 @@
"""Tests for the V1 trait properties API push handling."""

import asyncio
from collections.abc import AsyncIterator, 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.exceptions import RoborockException
from roborock.roborock_message import RoborockDataProtocol

DpsListener = Callable[[dict[RoborockDataProtocol, Any]], None]

DELAY = 0.01
# Long enough for a read-back that should not happen to have run.
SETTLE = DELAY * 8
TIMEOUT = 1


@pytest.fixture(name="refresh_delay", autouse=True)
def refresh_delay_fixture(monkeypatch: pytest.MonkeyPatch) -> float:
"""Shorten the read-back delay so tests run quickly."""
monkeypatch.setattr(v1, "_STATUS_REFRESH_DELAY", DELAY)
return DELAY


@pytest.fixture(name="props")
async def props_fixture(
device_info: HomeDataDevice,
products: list[HomeDataProduct],
trait_home_data: HomeData,
device_cache: DeviceCache,
) -> AsyncIterator[tuple[v1.PropertiesApi, DpsListener]]:
"""Create a started properties API and the DPS listener it registered."""
product = next(p for p in products if p.id == device_info.product_id)
listeners: list[DpsListener] = []

def add_dps_listener(listener: DpsListener) -> 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]
await api.start()
yield api, listeners[0]
api.close()


@pytest.fixture(name="read_back")
def read_back_fixture(props: tuple[v1.PropertiesApi, DpsListener]) -> asyncio.Event:
"""Mock the status read-back and return an event set each time it runs."""
api, _ = props
ran = asyncio.Event()

async def refresh() -> None:
ran.set()

api.status.refresh_and_notify = AsyncMock(side_effect=refresh) # type: ignore[method-assign]
return ran


async def test_fan_and_water_push_reads_status_back(
props: tuple[v1.PropertiesApi, DpsListener], read_back: asyncio.Event
) -> None:
"""A fan power and water mode push triggers one status read-back."""
api, push = props
push({RoborockDataProtocol.FAN_POWER: 101, RoborockDataProtocol.WATER_BOX_MODE: 202})
api.status.refresh_and_notify.assert_not_awaited() # type: ignore[attr-defined]

await asyncio.wait_for(read_back.wait(), timeout=TIMEOUT)
await asyncio.sleep(SETTLE)
api.status.refresh_and_notify.assert_awaited_once() # type: ignore[attr-defined]


async def test_repeated_pushes_are_debounced(
props: tuple[v1.PropertiesApi, DpsListener], read_back: asyncio.Event
) -> None:
"""Several pushes before the delay elapses cause a single read-back."""
api, push = props
push({RoborockDataProtocol.FAN_POWER: 101})
push({RoborockDataProtocol.WATER_BOX_MODE: 202})
push({RoborockDataProtocol.FAN_POWER: 102})

await asyncio.wait_for(read_back.wait(), timeout=TIMEOUT)
await asyncio.sleep(SETTLE)
api.status.refresh_and_notify.assert_awaited_once() # type: ignore[attr-defined]


async def test_unrelated_push_does_not_read_back(
props: tuple[v1.PropertiesApi, DpsListener], read_back: asyncio.Event
) -> None:
"""Pushes without fan power or water mode do not refresh status."""
api, push = props
push({RoborockDataProtocol.BATTERY: 80})

await asyncio.sleep(SETTLE)
api.status.refresh_and_notify.assert_not_awaited() # type: ignore[attr-defined]


async def test_refresh_failure_is_contained(
props: tuple[v1.PropertiesApi, DpsListener], read_back: asyncio.Event
) -> None:
"""A failing read-back does not raise and later pushes still read back."""
api, push = props
refresh = api.status.refresh_and_notify
ran = asyncio.Event()

async def failing_refresh() -> None:
ran.set()
raise RoborockException("boom")

refresh.side_effect = failing_refresh # type: ignore[attr-defined]
push({RoborockDataProtocol.FAN_POWER: 101})
await asyncio.wait_for(ran.wait(), timeout=TIMEOUT)

ran.clear()
push({RoborockDataProtocol.FAN_POWER: 102})
await asyncio.wait_for(ran.wait(), timeout=TIMEOUT)
assert refresh.await_count == 2 # type: ignore[attr-defined]


async def test_close_cancels_pending_read_back(
props: tuple[v1.PropertiesApi, DpsListener], read_back: asyncio.Event
) -> None:
"""Closing while a read-back is pending prevents it from running."""
api, push = props
push({RoborockDataProtocol.FAN_POWER: 101})
api.close()

await asyncio.sleep(SETTLE)
api.status.refresh_and_notify.assert_not_awaited() # type: ignore[attr-defined]


async def test_close_cancels_in_flight_read_back(
props: tuple[v1.PropertiesApi, DpsListener], read_back: asyncio.Event
) -> None:
"""Closing while a read-back is running cancels it."""
api, push = props
started = asyncio.Event()
cancelled = asyncio.Event()

async def hanging_refresh() -> None:
started.set()
try:
await asyncio.Event().wait()
except asyncio.CancelledError:
cancelled.set()
raise

api.status.refresh_and_notify.side_effect = hanging_refresh # type: ignore[attr-defined]
push({RoborockDataProtocol.FAN_POWER: 101})
await asyncio.wait_for(started.wait(), timeout=TIMEOUT)

api.close()
await asyncio.wait_for(cancelled.wait(), timeout=TIMEOUT)
api.status.refresh_and_notify.assert_awaited_once() # type: ignore[attr-defined]


async def test_push_during_refresh_schedules_another(
props: tuple[v1.PropertiesApi, DpsListener], read_back: asyncio.Event
) -> None:
"""A push arriving while a read-back is running is followed by another one."""
api, push = props
started = asyncio.Event()
release = asyncio.Event()
second_ran = asyncio.Event()
calls = 0

async def slow_refresh() -> None:
nonlocal calls
calls += 1
if calls == 2:
second_ran.set()
return
started.set()
await release.wait()

api.status.refresh_and_notify.side_effect = slow_refresh # type: ignore[attr-defined]
push({RoborockDataProtocol.FAN_POWER: 101})
await asyncio.wait_for(started.wait(), timeout=TIMEOUT)

push({RoborockDataProtocol.WATER_BOX_MODE: 202})
release.set()

await asyncio.wait_for(second_ran.wait(), timeout=TIMEOUT)
assert calls == 2


async def test_read_back_notifies_status_listeners(props: tuple[v1.PropertiesApi, DpsListener]) -> None:
"""Status listeners hear about values changed by the read-back."""
api, push = props
changed = asyncio.Event()
listener = Mock(side_effect=lambda: changed.set())
api.status.add_update_listener(listener)

async def refresh() -> None:
api.status.mop_mode = 301

api.status.refresh = AsyncMock(side_effect=refresh) # type: ignore[method-assign]
push({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=TIMEOUT)
assert api.status.mop_mode == 301
assert listener.call_count == 2
Loading
Loading