Skip to content
Merged
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
2 changes: 2 additions & 0 deletions docs/DEVICES.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
1 change: 1 addition & 0 deletions roborock/devices/traits/v1/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
86 changes: 86 additions & 0 deletions roborock/devices/traits/v1/status.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import asyncio
import logging
from functools import cached_property
from typing import Any
Expand All @@ -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

Expand All @@ -33,6 +35,36 @@

_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})


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

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I don't think we need this given we have sufficient coverage in test_status.py? I'm going to merge to get the change and we can clean up in a followup.


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]
Loading
Loading