Skip to content

Commit e6d5196

Browse files
feat(v1): expose per-room clean-then-mop via customize clean mode (#984)
* feat(v1): expose per-room clean-then-mop via customize clean mode Follow-up to #959, which models the global get_status seq_type flag but explicitly leaves the per-room get/set_customize_clean_mode layer alone. Adds a CustomizeCleanModeTrait exposing each room's SegmentCleanMode (fan_power/water_box_mode/mop_mode/repeat/seq_type) and a set_clean_then_mop(segment, enabled, ...) setter, mirroring StatusTrait.clean_then_mop at room granularity. * fix(v1): require mop_mode in set_clean_then_mop, document repeat reset Tested against a real device: omitting mop_mode makes the device reject the request outright ("Param error, no mop_mode"), it is not silently defaulted. Omitting repeat does not preserve the room's existing value either - the device resets it to 1. Address review feedback on #984. * fix(v1): correct feature gate, require repeat, reject malformed entries - Gate CustomizeCleanModeTrait on is_customized_clean_supported (the feature that actually covers get/set_customize_clean_mode) instead of is_clean_then_mop_mode_supported (which only gates the seq_type axis within it) - a device can support per-room custom modes without clean-then-mop specifically. - repeat now defaults to 1 instead of being left out of the wire request when unset: omitting it resets the room's repeat to 1 on the device rather than preserving the previous value, confirmed against a real device, so leaving it Optional was a footgun. - CustomizeCleanModeConverter now rejects a response list containing a non-dict entry instead of silently dropping it. - Corrected the module docstring's claim that the global clean_then_mop flag is per-job and clears after every clean - it's persisted, per StatusTrait.clean_then_mop's own docstring from #959. - Documented that StatusTrait reports sentinel "customized" codes (fan_power=106/water_box_mode=204/mop_mode=302) while a per-room custom mode is active, so it must not be used as a fallback source for those values when calling set_clean_then_mop on a room with no prior override. Addresses review feedback on #984. * fix(v1): serialize writes and round-trip unmodeled fields losslessly Addresses a second review round on #984 (allenporter, 2026-11-01) plus two rounds of independent review by a second AI reviewer, both of which reproduced real bugs rather than just raising theoretical concerns: - Move SegmentCleanMode/CustomizeCleanModes to data/v1/v1_containers.py (re-exported via roborock.data), matching how other trait container models (WashTowelMode, MopDryerSetting, etc.) are organized. Decouple the module docstring from unmerged #959 (StatusTrait.clean_then_mop doesn't exist on main). - CustomizeCleanModeTrait now takes a DeviceFeaturesTrait in __init__ (mirroring WashTowelModeTrait) instead of relying on the dataclass MRO to run V1TraitMixin.__init__, which it silently didn't. set_clean_then_mop now raises RoborockUnsupportedFeature up front if is_clean_then_mop_mode_supported is False, instead of writing seq_type to firmware that doesn't support it - many per-room-custom-mode devices (S7 MaxV, S8, Qrevo) don't support clean-then-mop specifically. - set_clean_then_mop's fan_power/water_box_mode/mop_mode now accept the typed VacuumModes/WaterModes/CleanRoutes enums (or a raw int, for codes this library doesn't model) instead of only raw ints. - The read-merge-write sequence (refresh, build payload, SET, refresh) is now serialized per trait instance via an asyncio.Lock. Reproduced the race without it: two concurrent calls enabling different rooms each read the same stale table, and the second call's write silently reverted the first call's room. - set_clean_then_mop sends the full known table on every write, not a single-entry list: SET_CUSTOMIZE_CLEAN_MODE replaces the whole customized-segment table on at least some firmware (first-hand Saros 20 Sonic report: https://github.com/orgs/home-assistant/discussions/3998), so a single-entry write silently wiped other rooms' overrides. - Untouched rooms are round-tripped from their raw wire dict (now cached by refresh(), keyed by the canonical typed segment id - not the raw dict's own possibly-differently-cased/typed "segment" key, which reproducibly desynced the cache from by_segment) rather than reconstructed from typed SegmentCleanMode fields, so fields this library doesn't model at all (not just the two now added to the dataclass) survive a write instead of being silently dropped. A response with two entries resolving to the same segment id now raises RoborockParsingException instead of one silently overwriting the other in the cache. - Tests: switched the fixture to real device discovery (device + discover_features_fixture, Saros 10R for the clean-then-mop-supported path, S7 MaxV default for the unsupported path, S5E for is_customized_clean_supported=False) instead of constructing the trait directly and poking private attributes. Fixed the enabled=False case never actually being exercised (the mocked post-write refresh was a static always-enabled fixture regardless of what was written). Added regression tests for multi-room preservation, unmodeled-field preservation (including on an untouched room), concurrent-call serialization (verified to actually fail without the lock), and the three segment-identity cases above (also verified to fail against the prior raw-indexing approach). Addresses review feedback on #984. * chore: fix codespell typo in customize clean mode tests --------- Co-authored-by: Allen Porter <allen.porter@gmail.com>
1 parent 9d73026 commit e6d5196

4 files changed

Lines changed: 737 additions & 0 deletions

File tree

‎roborock/data/v1/v1_containers.py‎

Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -515,6 +515,56 @@ class WashTowelMode(RoborockBase):
515515
wash_mode: WashTowelModes | None = None
516516

517517

518+
SEQ_TYPE_CLEAN_THEN_MOP = 1
519+
520+
521+
@dataclass
522+
class SegmentCleanMode(RoborockBase):
523+
"""A single room's clean mode override, as reported by the device.
524+
525+
`fan_power` / `water_box_mode` / `mop_mode` / `seq_type` are kept as raw
526+
`int | None` wire codes rather than typed enums, matching `StatusV2`, so
527+
model-specific values (e.g. water-slide codes like 222) round-trip
528+
losslessly even for codes this library doesn't otherwise model.
529+
530+
`mop_power` and `custom_water_box_distance` are only reported by some
531+
models (roller-mop / custom-water-flow devices); they are `None` on
532+
models that don't report them.
533+
"""
534+
535+
segment: int
536+
fan_power: int | None = None
537+
water_box_mode: int | None = None
538+
mop_mode: int | None = None
539+
repeat: int | None = None
540+
seq_type: int | None = None
541+
mop_power: int | None = None
542+
custom_water_box_distance: int | None = None
543+
544+
@property
545+
def clean_then_mop(self) -> bool | None:
546+
"""Whether this room is vacuumed fully before it is mopped.
547+
548+
`None` means the device did not report a sequence type for this
549+
room's override.
550+
"""
551+
if self.seq_type is None:
552+
return None
553+
return self.seq_type == SEQ_TYPE_CLEAN_THEN_MOP
554+
555+
556+
@dataclass
557+
class CustomizeCleanModes(RoborockBase):
558+
"""Collection of per-room clean mode overrides."""
559+
560+
modes: list[SegmentCleanMode] | None = None
561+
562+
@property
563+
def by_segment(self) -> dict[int, SegmentCleanMode]:
564+
"""Index the overrides by segment id."""
565+
return {mode.segment: mode for mode in self.modes or []}
566+
567+
518568
@dataclass
519569
class NetworkInfo(RoborockBase):
520570
ip: str

‎roborock/devices/traits/v1/__init__.py‎

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -74,6 +74,7 @@
7474
command,
7575
common,
7676
consumeable,
77+
customize_clean_mode,
7778
device_features,
7879
do_not_disturb,
7980
dust_collection_mode,
@@ -98,6 +99,7 @@
9899
from .command import CommandTrait
99100
from .common import V1TraitMixin
100101
from .consumeable import ConsumableTrait
102+
from .customize_clean_mode import CustomizeCleanModeTrait
101103
from .device_features import DeviceFeaturesTrait
102104
from .do_not_disturb import DoNotDisturbTrait
103105
from .dust_collection_mode import DustCollectionModeTrait
@@ -126,6 +128,7 @@
126128
"command",
127129
"common",
128130
"consumeable",
131+
"customize_clean_mode",
129132
"device_features",
130133
"do_not_disturb",
131134
"dust_collection_mode",
@@ -179,6 +182,7 @@ class PropertiesApi(Trait):
179182
smart_wash_params: SmartWashParamsTrait | None = None
180183
obstacle_photos: ObstaclePhotoTrait | None = None
181184
mop_dryer: MopDryerTrait | None = None
185+
customize_clean_mode: CustomizeCleanModeTrait | None = None
182186

183187
def __init__(
184188
self,
@@ -284,6 +288,13 @@ async def discover_features(self) -> None:
284288
wash_towel_mode._rpc_channel = self._get_rpc_channel(wash_towel_mode) # type: ignore[assignment]
285289
self.wash_towel_mode = wash_towel_mode
286290

291+
if self.customize_clean_mode is None and self._is_supported(
292+
CustomizeCleanModeTrait, "customize_clean_mode", dock_features
293+
):
294+
customize_clean_mode = CustomizeCleanModeTrait(self.device_features)
295+
customize_clean_mode._rpc_channel = self._get_rpc_channel(customize_clean_mode) # type: ignore[assignment]
296+
self.customize_clean_mode = customize_clean_mode
297+
287298
if self.obstacle_photos is None and self._is_supported(ObstaclePhotoTrait, "obstacle_photos", dock_features):
288299
obstacle_photos = ObstaclePhotoTrait(self._rpc_channel)
289300
obstacle_photos._rpc_channel = self._get_rpc_channel(obstacle_photos)
Lines changed: 202 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,202 @@
1+
"""Trait for per-room (segment) cleaning mode overrides on Roborock devices.
2+
3+
Rooms without an override are simply absent from `modes` - the robot falls
4+
back to the global settings (fan power, water box mode, mop mode and
5+
clean-then-mop) for those. An empty list means no room currently has one.
6+
7+
A per-room override set via `set_clean_then_mop` is persisted on the device:
8+
it is a preference attached to that room and is re-applied whenever the room
9+
is cleaned, until overwritten or cleared from the vendor app.
10+
"""
11+
12+
import asyncio
13+
14+
from roborock.data import CustomizeCleanModes, SegmentCleanMode
15+
from roborock.data.v1.v1_clean_modes import CleanRoutes, VacuumModes, WaterModes
16+
from roborock.data.v1.v1_containers import SEQ_TYPE_CLEAN_THEN_MOP
17+
from roborock.devices.traits.v1 import common
18+
from roborock.devices.traits.v1.device_features import DeviceFeaturesTrait
19+
from roborock.exceptions import RoborockParsingException, RoborockUnsupportedFeature
20+
from roborock.roborock_typing import RoborockCommand
21+
22+
from .common import V1ResponseData
23+
24+
_WRITE_KEYS = ("segment", "fan_power", "water_box_mode", "mop_mode", "repeat", "seq_type")
25+
26+
27+
class CustomizeCleanModeConverter(common.V1TraitDataConverter):
28+
"""Converts get_customize_clean_mode responses to CustomizeCleanModes."""
29+
30+
def convert(self, response: V1ResponseData) -> CustomizeCleanModes:
31+
"""Parse the response from the device into a CustomizeCleanModes."""
32+
if not isinstance(response, list) or not all(isinstance(entry, dict) for entry in response):
33+
raise ValueError(f"Unexpected CustomizeCleanModes response format: {response!r}")
34+
return CustomizeCleanModes(modes=[SegmentCleanMode.from_dict(entry) for entry in response])
35+
36+
37+
class CustomizeCleanModeTrait(CustomizeCleanModes, common.V1TraitMixin):
38+
"""Trait for reading and writing per-room clean mode overrides.
39+
40+
Gated on `is_customized_clean_supported` - the feature that covers
41+
`get/set_customize_clean_mode` in general, not `is_clean_then_mop_mode_supported`
42+
(which only gates the narrower `seq_type` axis within it). A device can
43+
support per-room custom modes without supporting clean-then-mop
44+
specifically; on such a device `SegmentCleanMode.seq_type` (and therefore
45+
`.clean_then_mop`) is simply `None` for every room, same as when the
46+
device never reports it. `set_clean_then_mop` additionally checks
47+
`is_clean_then_mop_mode_supported` itself before writing, since writing
48+
`seq_type` to firmware that doesn't support it is not just a no-op read.
49+
"""
50+
51+
command = RoborockCommand.GET_CUSTOMIZE_CLEAN_MODE
52+
converter = CustomizeCleanModeConverter()
53+
requires_feature = "is_customized_clean_supported"
54+
55+
def __init__(self, device_features: DeviceFeaturesTrait) -> None:
56+
super().__init__()
57+
common.V1TraitMixin.__init__(self)
58+
self._device_features = device_features
59+
self._raw_by_segment: dict[int, dict] = {}
60+
self._write_lock = asyncio.Lock()
61+
62+
async def refresh(self) -> None:
63+
"""Refresh the contents of this trait.
64+
65+
Overrides `V1TraitMixin.refresh()` to additionally retain each
66+
room's raw wire dict, by segment - `set_clean_then_mop` round-trips
67+
untouched rooms from this raw data rather than the typed
68+
`SegmentCleanMode` fields, so per-model keys this library doesn't
69+
model (or a value it failed to parse) are preserved on write instead
70+
of being silently dropped.
71+
"""
72+
response = await self.rpc_channel.send_command(self.command)
73+
try:
74+
new_data = self.converter.convert(response)
75+
except (TypeError, ValueError) as err:
76+
raise RoborockParsingException(
77+
trait_name=type(self).__name__,
78+
command=self.command,
79+
payload=response,
80+
inner_error=err,
81+
) from err
82+
assert isinstance(response, list) and new_data.modes is not None # converter.convert already validated this
83+
# Key the raw cache off the canonical TYPED segment id (int, already
84+
# decamelized/coerced by SegmentCleanMode.from_dict), not the raw
85+
# dict's own "segment" key - a device that ever sent a differently
86+
# cased key (e.g. "Segment") or a stringified id ("7" instead of 7)
87+
# would otherwise desync the raw cache from `by_segment`, so this
88+
# same room would be silently missing from (or duplicated in) a
89+
# later write. `response` and `new_data.modes` are the same length,
90+
# in the same order, by construction (one SegmentCleanMode per raw
91+
# entry, no filtering) - zip(strict=True) turns any future change to
92+
# that invariant into a loud error instead of silent misalignment.
93+
raw_by_segment: dict[int, dict] = {}
94+
for raw_entry, mode in zip(response, new_data.modes, strict=True):
95+
if mode.segment in raw_by_segment:
96+
raise RoborockParsingException(
97+
trait_name=type(self).__name__,
98+
command=self.command,
99+
payload=response,
100+
inner_error=ValueError(f"Duplicate segment {mode.segment} in response, cannot safely write"),
101+
)
102+
raw_by_segment[mode.segment] = raw_entry
103+
common.merge_trait_values(self, new_data)
104+
self._raw_by_segment = raw_by_segment
105+
106+
async def set_clean_then_mop(
107+
self,
108+
segment: int,
109+
enabled: bool,
110+
*,
111+
fan_power: VacuumModes | int,
112+
water_box_mode: WaterModes | int,
113+
mop_mode: CleanRoutes | int,
114+
repeat: int = 1,
115+
) -> None:
116+
"""Set whether a single room is vacuumed fully before it is mopped.
117+
118+
The firmware requires the room's full clean mode alongside the
119+
sequence type, not the flag on its own, so callers pass through the
120+
fan power / water box mode / mop mode that room already cleans with
121+
- typically read from the room's existing `SegmentCleanMode` (via
122+
`by_segment`) - so this call only changes the order, not the
123+
settings. `fan_power`, `water_box_mode` and `mop_mode` accept either
124+
the typed mode enum or a raw wire int (for codes this library
125+
doesn't model, e.g. water-slide values).
126+
127+
Do NOT source these from `StatusTrait` as a fallback when a room has
128+
no override yet: while the device is in a per-room custom cleaning
129+
mode, `StatusTrait` itself reports the sentinel "customized" codes
130+
(`fan_power=106`, `water_box_mode=204`, `mop_mode=302`) rather than
131+
real settings, and those sentinels are not valid values to echo back
132+
here.
133+
134+
`fan_power`, `water_box_mode` and `mop_mode` are all required: the
135+
device rejects the request outright (`Param error, no mop_mode`) if
136+
`mop_mode` is left out, confirmed against a real device - this isn't
137+
a case where a missing field is silently defaulted.
138+
139+
`repeat` defaults to `1` rather than being left out when the caller
140+
doesn't have an opinion: omitting it from the wire request is NOT a
141+
no-op on the device, which resets it to `1` instead of preserving
142+
whatever the room's `repeat` was set to before this call - confirmed
143+
against a real device. Pass the room's current `repeat` explicitly if
144+
you want a different value preserved.
145+
146+
Raises `RoborockUnsupportedFeature` if the device doesn't support
147+
clean-then-mop at all (`is_clean_then_mop_mode_supported`), even if
148+
it does support per-room custom modes in general.
149+
150+
This whole read-merge-write sequence is serialized per trait
151+
instance (concurrent calls queue rather than racing): the device's
152+
SET_CUSTOMIZE_CLEAN_MODE replaces the whole per-room table rather
153+
than patching one entry (see below), so two overlapping calls each
154+
building their own full table from the same stale read would
155+
otherwise silently revert each other's room.
156+
"""
157+
if not self._device_features.is_clean_then_mop_mode_supported:
158+
raise RoborockUnsupportedFeature("Device does not support clean-then-mop")
159+
160+
async with self._write_lock:
161+
# Always refresh immediately before building the write, even if
162+
# `self.modes` is already populated: this merges-and-replaces
163+
# the whole table (see below), so writing from a stale cache
164+
# could silently revert another room's override changed since
165+
# the last refresh (e.g. from the vendor app) back to its old
166+
# value.
167+
await self.refresh()
168+
169+
seq_type = SEQ_TYPE_CLEAN_THEN_MOP if enabled else 0
170+
new_entry = {
171+
"segment": segment,
172+
"fan_power": fan_power.code if isinstance(fan_power, VacuumModes) else fan_power,
173+
"water_box_mode": water_box_mode.code if isinstance(water_box_mode, WaterModes) else water_box_mode,
174+
"mop_mode": mop_mode.code if isinstance(mop_mode, CleanRoutes) else mop_mode,
175+
"repeat": repeat,
176+
"seq_type": seq_type,
177+
}
178+
# Start from this room's raw wire dict (if it already had an
179+
# override) so any field this library doesn't model - or
180+
# couldn't parse - survives the write, and only overlay the keys
181+
# this call actually changes. A room with no prior override
182+
# gets only the known fields; the device fills in its own
183+
# per-model defaults for the rest, same as the original
184+
# single-entry write did.
185+
raw_entries = dict(self._raw_by_segment)
186+
raw_entries[segment] = {**raw_entries.get(segment, {}), **new_entry}
187+
188+
# Send the full known table, not just the changed room: on at
189+
# least some V1 firmware (confirmed first-hand for a Saros 20
190+
# Sonic, see https://github.com/orgs/home-assistant/discussions/3998),
191+
# SET_CUSTOMIZE_CLEAN_MODE replaces the customized segment table
192+
# rather than patching a single entry, so sending only
193+
# `[new_entry]` would silently wipe every other room's
194+
# override. This has not been re-verified against real hardware
195+
# for THIS device since this fix was written (no second
196+
# customized room available to test with); please confirm on a
197+
# device with two or more customized rooms before relying on
198+
# it.
199+
await self.rpc_channel.send_command(
200+
RoborockCommand.SET_CUSTOMIZE_CLEAN_MODE, params=list(raw_entries.values())
201+
)
202+
await self.refresh()

0 commit comments

Comments
 (0)