diff --git a/roborock/data/v1/v1_containers.py b/roborock/data/v1/v1_containers.py index 65bcba64a..512c3dd9b 100644 --- a/roborock/data/v1/v1_containers.py +++ b/roborock/data/v1/v1_containers.py @@ -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.""" diff --git a/roborock/device_features.py b/roborock/device_features.py index 160d14cc5..441c33403 100644 --- a/roborock/device_features.py +++ b/roborock/device_features.py @@ -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, @@ -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 @@ -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 diff --git a/roborock/devices/traits/v1/__init__.py b/roborock/devices/traits/v1/__init__.py index 28c404d65..1b6034db5 100644 --- a/roborock/devices/traits/v1/__init__.py +++ b/roborock/devices/traits/v1/__init__.py @@ -71,6 +71,7 @@ from . import ( camera, child_lock, + clean_sequence, clean_summary, command, common, @@ -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 @@ -127,6 +129,7 @@ "PropertiesApi", "camera", "child_lock", + "clean_sequence", "clean_summary", "command", "common", @@ -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, diff --git a/roborock/devices/traits/v1/clean_sequence.py b/roborock/devices/traits/v1/clean_sequence.py new file mode 100644 index 000000000..defaa96fe --- /dev/null +++ b/roborock/devices/traits/v1/clean_sequence.py @@ -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([]) diff --git a/roborock/devices/traits/v1/device_features.py b/roborock/devices/traits/v1/device_features.py index 1f785e65a..97c1c1185 100644 --- a/roborock/devices/traits/v1/device_features.py +++ b/roborock/devices/traits/v1/device_features.py @@ -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, ) diff --git a/tests/devices/__snapshots__/test_device_manager.ambr b/tests/devices/__snapshots__/test_device_manager.ambr index dadae5983..dc53b0c6d 100644 --- a/tests/devices/__snapshots__/test_device_manager.ambr +++ b/tests/devices/__snapshots__/test_device_manager.ambr @@ -278,7 +278,7 @@ 'isObjectDetectCheckSupported': False, 'isOfflineMapSupported': False, 'isOptimizeBatterySupported': False, - 'isOrderCleanSupported': True, + 'isOrderCleanSupported': False, 'isOverSeaCtmSupported': False, 'isPetSnapshotSupported': False, 'isPetSuppliesDeepCleanSupported': False, diff --git a/tests/devices/__snapshots__/test_v1_device.ambr b/tests/devices/__snapshots__/test_v1_device.ambr index bc0d8fdb3..2f8122b95 100644 --- a/tests/devices/__snapshots__/test_v1_device.ambr +++ b/tests/devices/__snapshots__/test_v1_device.ambr @@ -306,7 +306,7 @@ 'isObjectDetectCheckSupported': False, 'isOfflineMapSupported': False, 'isOptimizeBatterySupported': False, - 'isOrderCleanSupported': True, + 'isOrderCleanSupported': False, 'isOverSeaCtmSupported': False, 'isPetSnapshotSupported': False, 'isPetSuppliesDeepCleanSupported': False, @@ -727,7 +727,7 @@ 'isObjectDetectCheckSupported': False, 'isOfflineMapSupported': False, 'isOptimizeBatterySupported': False, - 'isOrderCleanSupported': True, + 'isOrderCleanSupported': False, 'isOverSeaCtmSupported': False, 'isPetSnapshotSupported': False, 'isPetSuppliesDeepCleanSupported': False, @@ -1155,7 +1155,7 @@ 'isObjectDetectCheckSupported': False, 'isOfflineMapSupported': False, 'isOptimizeBatterySupported': False, - 'isOrderCleanSupported': True, + 'isOrderCleanSupported': False, 'isOverSeaCtmSupported': False, 'isPetSnapshotSupported': False, 'isPetSuppliesDeepCleanSupported': False, @@ -1553,7 +1553,7 @@ 'isObjectDetectCheckSupported': False, 'isOfflineMapSupported': False, 'isOptimizeBatterySupported': False, - 'isOrderCleanSupported': True, + 'isOrderCleanSupported': False, 'isOverSeaCtmSupported': False, 'isPetSnapshotSupported': False, 'isPetSuppliesDeepCleanSupported': False, diff --git a/tests/devices/traits/v1/test_clean_sequence.py b/tests/devices/traits/v1/test_clean_sequence.py new file mode 100644 index 000000000..3810cf79d --- /dev/null +++ b/tests/devices/traits/v1/test_clean_sequence.py @@ -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" + + +@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 diff --git a/tests/test_supported_features.py b/tests/test_supported_features.py index b427ccc5d..09b1948da 100644 --- a/tests/test_supported_features.py +++ b/tests/test_supported_features.py @@ -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