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
10 changes: 10 additions & 0 deletions roborock/data/v1/v1_containers.py
Original file line number Diff line number Diff line change
Expand Up @@ -553,6 +553,16 @@ def clean_then_mop(self) -> bool | None:
return self.seq_type == SEQ_TYPE_CLEAN_THEN_MOP


@dataclass
class CleanSequence(RoborockBase):
"""The order in which the device cleans rooms, as segment ids.

Rooms that are not listed are cleaned after the listed ones.
"""

rooms: list[int] | None = None


@dataclass
class CustomizeCleanModes(RoborockBase):
"""Collection of per-room clean mode overrides."""
Expand Down
38 changes: 37 additions & 1 deletion roborock/device_features.py
Original file line number Diff line number Diff line change
Expand Up @@ -169,6 +169,36 @@ class ProductFeatures(StrEnum):
RoborockProductNickname.RUBYSC,
RoborockProductNickname.RUBYSE,
}
# The app shows room order on these products in every region (isModelOrderSupported).
PRODUCTS_WITH_ORDER_CLEAN_IN_ALL_REGIONS: set[RoborockProductNickname] = {
RoborockProductNickname.RUBYPLUS,
RoborockProductNickname.RUBYSC,
RoborockProductNickname.RUBYSLITE,
RoborockProductNickname.TANOS,
RoborockProductNickname.TANOSE,
RoborockProductNickname.TANOSV,
}


def _is_model_order_supported(product_nickname: RoborockProductNickname | None, location: str | None) -> bool:
"""Mirror the app's isModelOrderSupported() for room cleaning order.

The app requires robot feature 123 and this check: no device location means
no support; the products above are supported everywhere; any other product
is supported only outside the US (FCC) region. ``location`` is
``local_info.location`` from ``app_get_init_status``. ``None`` means the
caller has no init status (for example offline tooling), so the rule is not
applied.
"""
if location is None:
return True
if not location:
return False
if product_nickname in PRODUCTS_WITH_ORDER_CLEAN_IN_ALL_REGIONS:
return True
return location.lower() != "us"


PRODUCTS_WITHOUT_PURE_CLEAN_MOP: set[RoborockProductNickname] = {
RoborockProductNickname.TANOS,
RoborockProductNickname.TANOSE,
Expand Down Expand Up @@ -573,12 +603,14 @@ def from_feature_flags(
new_feature_info_str: str,
feature_info: list[int],
product_nickname: RoborockProductNickname | None,
location: str | None = None,
) -> Self:
"""Creates a DeviceFeatures instance from raw feature flags.
:param new_feature_info: A int from get_init_status (sometimes can be found in homedata, but it is not always)
:param new_feature_info_str: A hex string from get_init_status or home_data.
:param feature_info: A list of ints from get_init_status
:param product_nickname: The product nickname of the device."""
:param product_nickname: The product nickname of the device.
:param location: ``local_info.location`` from get_init_status; gates room order like the app."""
# For any future reverse engineerining:
# RobotNewFeatures = new_feature_info
# newFeatureInfoStr = new_feature_info_str
Expand Down Expand Up @@ -652,6 +684,10 @@ def from_feature_flags(
kwargs["is_shake_mop_set_supported"] or kwargs["is_roller_mop_supported"]
)

# The app shows room order only when feature 123 is set and the model and
# region allow it (isOrderCleanSupported = feature 123 && isModelOrderSupported).
kwargs["is_order_clean_supported"] &= _is_model_order_supported(product_nickname, location)

return cls(**kwargs)

@classmethod
Expand Down
4 changes: 4 additions & 0 deletions roborock/devices/traits/v1/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -71,6 +71,7 @@
from . import (
camera,
child_lock,
clean_sequence,
clean_summary,
command,
common,
Expand All @@ -97,6 +98,7 @@
)
from .camera import CameraTrait
from .child_lock import ChildLockTrait
from .clean_sequence import CleanSequenceTrait
from .clean_summary import CleanSummaryTrait
from .command import CommandTrait
from .common import V1TraitMixin
Expand Down Expand Up @@ -127,6 +129,7 @@
"PropertiesApi",
"camera",
"child_lock",
"clean_sequence",
"clean_summary",
"command",
"common",
Expand Down Expand Up @@ -187,6 +190,7 @@ class PropertiesApi(Trait):
obstacle_photos: ObstaclePhotoTrait | None = None
mop_dryer: MopDryerTrait | None = None
customize_clean_mode: CustomizeCleanModeTrait | None = None
clean_sequence: CleanSequenceTrait | None = None

def __init__(
self,
Expand Down
47 changes: 47 additions & 0 deletions roborock/devices/traits/v1/clean_sequence.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
"""Trait for the room cleaning order of Roborock devices."""

from roborock.data import CleanSequence
from roborock.devices.traits.v1 import common
from roborock.roborock_typing import RoborockCommand

from .common import V1ResponseData


class CleanSequenceConverter(common.V1TraitDataConverter):
"""Converts get_clean_sequence responses to CleanSequence."""

def convert(self, response: V1ResponseData) -> CleanSequence:
"""Parse the list of segment ids returned by the device."""
if not isinstance(response, list) or not all(isinstance(room, int) for room in response):
raise ValueError(f"Unexpected CleanSequence response format: {response!r}")
return CleanSequence(rooms=list(response))


class CleanSequenceTrait(CleanSequence, common.V1TraitMixin):
"""Trait for reading and setting the order in which rooms are cleaned.

The device keeps this order and uses it for room cleaning
(`app_segment_clean`), whatever order the segments are sent in.
"""

command = RoborockCommand.GET_CLEAN_SEQUENCE
converter = CleanSequenceConverter()
requires_feature = "is_order_clean_supported"

async def set_order(self, rooms: list[int]) -> None:
"""Set the room cleaning order.

An empty list clears the custom order, and the device then chooses the
order itself (the app's reset). A device rejects a new order with an
invalid status error while it is cleaning or moving; set it while the
device is idle or docked.
"""
if len(set(rooms)) != len(rooms):
raise ValueError(f"rooms must contain distinct segment ids: {rooms!r}")
await self.rpc_channel.send_command(RoborockCommand.SET_CLEAN_SEQUENCE, params=list(rooms))
# Optimistic update to avoid an extra refresh
self.rooms = list(rooms)

async def reset_order(self) -> None:
"""Clear the custom room order so the device uses its automatic order."""
await self.set_order([])
1 change: 1 addition & 0 deletions roborock/devices/traits/v1/device_features.py
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,7 @@ def convert(self, response: common.V1ResponseData) -> DeviceFeatures:
new_feature_info_str=app_status.new_feature_info_str,
feature_info=app_status.feature_info,
product_nickname=self._product.product_nickname,
location=app_status.local_info.location,
)


Expand Down
2 changes: 1 addition & 1 deletion tests/devices/__snapshots__/test_device_manager.ambr
Original file line number Diff line number Diff line change
Expand Up @@ -278,7 +278,7 @@
'isObjectDetectCheckSupported': False,
'isOfflineMapSupported': False,
'isOptimizeBatterySupported': False,
'isOrderCleanSupported': True,
'isOrderCleanSupported': False,
'isOverSeaCtmSupported': False,
'isPetSnapshotSupported': False,
'isPetSuppliesDeepCleanSupported': False,
Expand Down
8 changes: 4 additions & 4 deletions tests/devices/__snapshots__/test_v1_device.ambr
Original file line number Diff line number Diff line change
Expand Up @@ -306,7 +306,7 @@
'isObjectDetectCheckSupported': False,
'isOfflineMapSupported': False,
'isOptimizeBatterySupported': False,
'isOrderCleanSupported': True,
'isOrderCleanSupported': False,
'isOverSeaCtmSupported': False,
'isPetSnapshotSupported': False,
'isPetSuppliesDeepCleanSupported': False,
Expand Down Expand Up @@ -727,7 +727,7 @@
'isObjectDetectCheckSupported': False,
'isOfflineMapSupported': False,
'isOptimizeBatterySupported': False,
'isOrderCleanSupported': True,
'isOrderCleanSupported': False,
'isOverSeaCtmSupported': False,
'isPetSnapshotSupported': False,
'isPetSuppliesDeepCleanSupported': False,
Expand Down Expand Up @@ -1155,7 +1155,7 @@
'isObjectDetectCheckSupported': False,
'isOfflineMapSupported': False,
'isOptimizeBatterySupported': False,
'isOrderCleanSupported': True,
'isOrderCleanSupported': False,
'isOverSeaCtmSupported': False,
'isPetSnapshotSupported': False,
'isPetSuppliesDeepCleanSupported': False,
Expand Down Expand Up @@ -1553,7 +1553,7 @@
'isObjectDetectCheckSupported': False,
'isOfflineMapSupported': False,
'isOptimizeBatterySupported': False,
'isOrderCleanSupported': True,
'isOrderCleanSupported': False,
'isOverSeaCtmSupported': False,
'isPetSnapshotSupported': False,
'isPetSuppliesDeepCleanSupported': False,
Expand Down
135 changes: 135 additions & 0 deletions tests/devices/traits/v1/test_clean_sequence.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,135 @@
"""Tests for the CleanSequenceTrait class."""

from unittest.mock import AsyncMock

import pytest

from roborock.data import HomeDataDevice
from roborock.devices.device import RoborockDevice
from roborock.devices.traits.v1.clean_sequence import CleanSequenceTrait
from roborock.exceptions import RoborockParsingException
from roborock.roborock_typing import RoborockCommand
from tests import mock_data

S5E = mock_data.DEVICE_PRODUCT_PAIRS["home_data_device_s5e.json"][0]


@pytest.fixture(name="clean_sequence_trait")
def clean_sequence_trait_fixture(
device: RoborockDevice,
discover_features_fixture: None,
) -> CleanSequenceTrait | None:
"""Return the discovered CleanSequenceTrait from the device."""
assert device.v1_properties
return device.v1_properties.clean_sequence


def test_requires_feature() -> None:
"""The trait is only created on devices that report order cleaning (robot feature 123)."""
assert CleanSequenceTrait.requires_feature == "is_order_clean_supported"

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Tests — Behavior-driven feature-gating & empty-list coverage

Per AGENTS.md (Behavior-Driven Assertions) and sibling optional-trait suites (test_customize_clean_mode.py, test_mop_dryer.py, test_dust_collection_mode.py), consider testing end-to-end discovery on an unsupported device (the default S7 MaxV fixture has is_order_clean_supported=False):

async def test_unsupported_clean_sequence(
    clean_sequence_trait: CleanSequenceTrait | None,
) -> None:
    """Trait is not initialized when is_order_clean_supported is False."""
    assert clean_sequence_trait is None

It would also be helpful to cover refresh() when the device returns [] (no custom cleaning order set), and update test_set_order_rejects_bad_input if set_order([]) is allowed to clear the order.



@pytest.mark.parametrize("device_info", [S5E])
async def test_refresh(
clean_sequence_trait: CleanSequenceTrait | None,
mock_rpc_channel: AsyncMock,
device_info: HomeDataDevice,
) -> None:
"""The response is the list of segment ids in cleaning order."""
assert clean_sequence_trait is not None
mock_rpc_channel.send_command.side_effect = [[8, 3, 7, 10, 1, 9]]

await clean_sequence_trait.refresh()

mock_rpc_channel.send_command.assert_called_once_with(RoborockCommand.GET_CLEAN_SEQUENCE)
assert clean_sequence_trait.rooms == [8, 3, 7, 10, 1, 9]


@pytest.mark.parametrize("device_info", [S5E])
@pytest.mark.parametrize("response", [{"unexpected": "shape"}, ["7"], [7, None]])
async def test_refresh_bad_format(
clean_sequence_trait: CleanSequenceTrait | None,
mock_rpc_channel: AsyncMock,
device_info: HomeDataDevice,
response: object,
) -> None:
"""A response that is not a list of segment ids raises a parsing error."""
assert clean_sequence_trait is not None
mock_rpc_channel.send_command.side_effect = [response]

with pytest.raises(RoborockParsingException):
await clean_sequence_trait.refresh()


@pytest.mark.parametrize("device_info", [S5E])
async def test_set_order(
clean_sequence_trait: CleanSequenceTrait | None,
mock_rpc_channel: AsyncMock,
device_info: HomeDataDevice,
) -> None:
"""set_order sends the list as is and updates the trait."""
assert clean_sequence_trait is not None
mock_rpc_channel.send_command.side_effect = [["ok"]]

await clean_sequence_trait.set_order([7, 8, 3, 10, 1, 9])

mock_rpc_channel.send_command.assert_called_once_with(
RoborockCommand.SET_CLEAN_SEQUENCE, params=[7, 8, 3, 10, 1, 9]
)
assert clean_sequence_trait.rooms == [7, 8, 3, 10, 1, 9]


@pytest.mark.parametrize("device_info", [S5E])
async def test_set_order_rejects_repeated_room(
clean_sequence_trait: CleanSequenceTrait | None,
mock_rpc_channel: AsyncMock,
device_info: HomeDataDevice,
) -> None:
"""A repeated room is refused before anything is sent."""
assert clean_sequence_trait is not None

with pytest.raises(ValueError):
await clean_sequence_trait.set_order([7, 7])
mock_rpc_channel.send_command.assert_not_called()


@pytest.mark.parametrize("device_info", [S5E])
async def test_refresh_empty(
clean_sequence_trait: CleanSequenceTrait | None,
mock_rpc_channel: AsyncMock,
device_info: HomeDataDevice,
) -> None:
"""A device with no custom order answers an empty list."""
assert clean_sequence_trait is not None
mock_rpc_channel.send_command.side_effect = [[]]

await clean_sequence_trait.refresh()

assert clean_sequence_trait.rooms == []


@pytest.mark.parametrize("device_info", [S5E])
@pytest.mark.parametrize("use_reset", [True, False])
async def test_reset_order(
clean_sequence_trait: CleanSequenceTrait | None,
mock_rpc_channel: AsyncMock,
device_info: HomeDataDevice,
use_reset: bool,
) -> None:
"""reset_order() and set_order([]) send an empty list, which restores the automatic order."""
assert clean_sequence_trait is not None
clean_sequence_trait.rooms = [8, 3, 7]
mock_rpc_channel.send_command.side_effect = [["ok"]]

if use_reset:
await clean_sequence_trait.reset_order()
else:
await clean_sequence_trait.set_order([])

mock_rpc_channel.send_command.assert_called_once_with(RoborockCommand.SET_CLEAN_SEQUENCE, params=[])
assert clean_sequence_trait.rooms == []


async def test_unsupported_clean_sequence(clean_sequence_trait: CleanSequenceTrait | None) -> None:
"""The trait is not created on a device without order cleaning (the default S7 MaxV fixture)."""
assert clean_sequence_trait is None
27 changes: 27 additions & 0 deletions tests/test_supported_features.py
Original file line number Diff line number Diff line change
Expand Up @@ -416,3 +416,30 @@ def test_device_features_from_home_data(
)
feature_dict = {k: v for k, v in asdict(device_features).items() if isinstance(v, bool)}
assert feature_dict == snapshot


@pytest.mark.parametrize(
("feature_info", "product", "location", "expected"),
[
([123], RoborockProductNickname.RUBYSLITE, "us", True),
([123], RoborockProductNickname.TANOSV, "us", True),
([123], RoborockProductNickname.PEARL, "us", False),
([123], RoborockProductNickname.PEARL, "US", False),
([123], RoborockProductNickname.PEARL, "eu", True),
([123], RoborockProductNickname.PEARL, "", False),
([123], RoborockProductNickname.PEARL, None, True),
([], RoborockProductNickname.RUBYSLITE, "eu", False),
],
)
def test_order_clean_follows_app_model_and_region_rule(
feature_info: list[int], product: RoborockProductNickname, location: str | None, expected: bool
) -> None:
"""Room order needs feature 123 and the app's isModelOrderSupported(): US units only on Ruby/Tanos products."""
features = DeviceFeatures.from_feature_flags(
new_feature_info=0,
new_feature_info_str="",
feature_info=feature_info,
product_nickname=product,
location=location,
)
assert features.is_order_clean_supported is expected