11"""Trait for per-room (segment) cleaning mode overrides on Roborock devices.
22
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.
3+ Rooms without an override are absent from `modes` (the robot falls back to
4+ global settings for those; an empty list means no room has an override).
65
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.
6+ Per-room overrides are persisted on the device across cleaning runs and take
7+ effect when cleaning with the global mode set to custom (`CleaningMode.CUSTOM`
8+ where supported). When cleaning in an explicit global mode (`VACUUM`,
9+ `VAC_AND_MOP`, `MOP`, or `SMART_MODE`), global settings take precedence.
1010"""
1111
1212import asyncio
13+ from typing import Any
1314
1415from roborock .data import CustomizeCleanModes , SegmentCleanMode
16+ from roborock .data .containers import _decamelize
1517from roborock .data .v1 .v1_clean_modes import CleanRoutes , VacuumModes , WaterModes
1618from roborock .data .v1 .v1_containers import SEQ_TYPE_CLEAN_THEN_MOP
1719from roborock .devices .traits .v1 import common
2123
2224from .common import V1ResponseData
2325
24- _WRITE_KEYS = ("segment" , "fan_power" , "water_box_mode" , "mop_mode" , "repeat" , "seq_type" )
26+ # StatusTrait reports these sentinel codes while in custom or smart plan modes;
27+ # they are not valid concrete per-room settings.
28+ _INVALID_FAN_POWER_CODES = frozenset ({VacuumModes .CUSTOMIZED .code , VacuumModes .SMART_MODE .code })
29+ _INVALID_WATER_MODE_CODES = frozenset ({WaterModes .CUSTOMIZED .code , WaterModes .SMART_MODE .code })
30+ _INVALID_MOP_MODE_CODES = frozenset ({CleanRoutes .CUSTOMIZED .code , CleanRoutes .SMART_MODE .code })
31+
32+
33+ def _resolve_mode_codes (
34+ fan_power : VacuumModes | int | None ,
35+ water_box_mode : WaterModes | int | None ,
36+ mop_mode : CleanRoutes | int | None ,
37+ ) -> tuple [int | None , int | None , int | None ]:
38+ """Unwrap mode enums to wire codes and reject global sentinel codes."""
39+ fan_code = fan_power .code if isinstance (fan_power , VacuumModes ) else fan_power
40+ water_code = water_box_mode .code if isinstance (water_box_mode , WaterModes ) else water_box_mode
41+ mop_code = mop_mode .code if isinstance (mop_mode , CleanRoutes ) else mop_mode
42+
43+ if fan_code in _INVALID_FAN_POWER_CODES :
44+ raise ValueError (f"Invalid per-segment fan_power sentinel code: { fan_code } " )
45+ if water_code in _INVALID_WATER_MODE_CODES :
46+ raise ValueError (f"Invalid per-segment water_box_mode sentinel code: { water_code } " )
47+ if mop_code in _INVALID_MOP_MODE_CODES :
48+ raise ValueError (f"Invalid per-segment mop_mode sentinel code: { mop_code } " )
49+
50+ return fan_code , water_code , mop_code
2551
2652
2753class CustomizeCleanModeConverter (common .V1TraitDataConverter ):
@@ -37,15 +63,9 @@ def convert(self, response: V1ResponseData) -> CustomizeCleanModes:
3763class CustomizeCleanModeTrait (CustomizeCleanModes , common .V1TraitMixin ):
3864 """Trait for reading and writing per-room clean mode overrides.
3965
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.
66+ Gated on `is_customized_clean_supported` (which covers
67+ `get/set_customize_clean_mode` in general), while `clean_then_mop` writes
68+ are additionally gated on `is_clean_then_mop_mode_supported`.
4969 """
5070
5171 command = RoborockCommand .GET_CUSTOMIZE_CLEAN_MODE
@@ -56,18 +76,14 @@ def __init__(self, device_features: DeviceFeaturesTrait) -> None:
5676 super ().__init__ ()
5777 common .V1TraitMixin .__init__ (self )
5878 self ._device_features = device_features
59- self ._raw_by_segment : dict [int , dict ] = {}
79+ self ._raw_by_segment : dict [int , dict [ str , Any ] ] = {}
6080 self ._write_lock = asyncio .Lock ()
6181
6282 async def refresh (self ) -> None :
6383 """Refresh the contents of this trait.
6484
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.
85+ Retains each room's raw wire dict keyed by canonical typed segment id
86+ so writes round-trip untouched rooms and unmodeled per-model fields.
7187 """
7288 response = await self .rpc_channel .send_command (self .command )
7389 try :
@@ -79,18 +95,10 @@ async def refresh(self) -> None:
7995 payload = response ,
8096 inner_error = err ,
8197 ) 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 ] = {}
98+ assert isinstance (response , list ) and new_data .modes is not None
99+ # Key by canonical typed `mode.segment` (decamelized/coerced to int) so
100+ # `_raw_by_segment` stays aligned with `by_segment` across casing/type quirks.
101+ raw_by_segment : dict [int , dict [str , Any ]] = {}
94102 for raw_entry , mode in zip (response , new_data .modes , strict = True ):
95103 if mode .segment in raw_by_segment :
96104 raise RoborockParsingException (
@@ -108,94 +116,87 @@ async def set_clean_then_mop(
108116 segment : int ,
109117 enabled : bool ,
110118 * ,
111- fan_power : VacuumModes | int ,
112- water_box_mode : WaterModes | int ,
113- mop_mode : CleanRoutes | int ,
114- repeat : int = 1 ,
119+ fan_power : VacuumModes | int | None = None ,
120+ water_box_mode : WaterModes | int | None = None ,
121+ mop_mode : CleanRoutes | int | None = None ,
122+ repeat : int | None = None ,
115123 ) -> None :
116124 """Set whether a single room is vacuumed fully before it is mopped.
117125
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.
126+ Delegates to `set_segment_clean_mode(..., clean_then_mop=enabled)`;
127+ omitted mode/repeat arguments preserve an existing room's settings.
128+ """
129+ await self .set_segment_clean_mode (
130+ segment ,
131+ fan_power = fan_power ,
132+ water_box_mode = water_box_mode ,
133+ mop_mode = mop_mode ,
134+ repeat = repeat ,
135+ clean_then_mop = enabled ,
136+ )
137+
138+ async def set_segment_clean_mode (
139+ self ,
140+ segment : int ,
141+ * ,
142+ fan_power : VacuumModes | int | None = None ,
143+ water_box_mode : WaterModes | int | None = None ,
144+ mop_mode : CleanRoutes | int | None = None ,
145+ repeat : int | None = None ,
146+ clean_then_mop : bool | None = None ,
147+ ) -> None :
148+ """Set or update a single room's custom cleaning mode override.
149+
150+ Omitted fields preserve the room's existing override when present. For
151+ a room without an existing override, `fan_power`, `water_box_mode`, and
152+ `mop_mode` are required (firmware rejects requests missing `mop_mode`)
153+ and `repeat` defaults to `1` (omitting `repeat` on wire resets it to `1`
154+ on firmware).
155+
156+ Do not pass `StatusTrait` mode values as a fallback: while in custom or
157+ smart plan mode, `StatusTrait` reports sentinel codes (`106/204/302` or
158+ `110/209/306`), which are rejected with `ValueError`.
156159 """
157- if not self ._device_features .is_clean_then_mop_mode_supported :
160+ if all (v is None for v in (fan_power , water_box_mode , mop_mode , repeat , clean_then_mop )):
161+ raise ValueError ("At least one clean mode setting must be provided" )
162+ if clean_then_mop is not None and not self ._device_features .is_clean_then_mop_mode_supported :
158163 raise RoborockUnsupportedFeature ("Device does not support clean-then-mop" )
164+ if repeat is not None and repeat < 1 :
165+ raise ValueError (f"repeat must be >= 1, got { repeat } " )
166+
167+ fan_code , water_code , mop_code = _resolve_mode_codes (fan_power , water_box_mode , mop_mode )
159168
169+ # Serialize read-merge-write since SET_CUSTOMIZE_CLEAN_MODE replaces the
170+ # entire per-room table on V1 firmware rather than patching a single entry.
160171 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 ()
172+ # Lazily load the existing table if the caller hasn't refreshed yet
173+ # so a full-table SET doesn't wipe other rooms.
174+ if self .modes is None :
175+ await self .refresh ()
176+
177+ existing_mode = self .by_segment .get (segment )
178+ if existing_mode is None and (fan_code is None or water_code is None or mop_code is None ):
179+ raise ValueError (
180+ "fan_power, water_box_mode, and mop_mode must be provided when not already set "
181+ f"on segment { segment } "
182+ )
168183
169- seq_type = SEQ_TYPE_CLEAN_THEN_MOP if enabled else 0
170- new_entry = {
184+ updates : dict [str , int | None ] = {
171185 "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 ,
186+ "fan_power" : fan_code ,
187+ "water_box_mode" : water_code ,
188+ "mop_mode" : mop_code ,
189+ "repeat" : repeat or ( existing_mode . repeat if existing_mode else None ) or 1 ,
190+ "seq_type" : ( SEQ_TYPE_CLEAN_THEN_MOP if clean_then_mop else 0 ) if clean_then_mop is not None else None ,
177191 }
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.
192+ new_entry = {k : v for k , v in updates .items () if v is not None }
193+
194+ # Overlay updated keys onto this room's raw dict (preserving any
195+ # unmodeled per-model fields) and send the full segment table.
196+ existing = self ._raw_by_segment .get (segment , {})
197+ preserved = {k : v for k , v in existing .items () if _decamelize (k ) not in new_entry }
198+ raw_entries = {** self ._raw_by_segment , segment : {** preserved , ** new_entry }}
199+
199200 await self .rpc_channel .send_command (
200201 RoborockCommand .SET_CUSTOMIZE_CLEAN_MODE , params = list (raw_entries .values ())
201202 )
0 commit comments