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
1516from roborock .data .v1 .v1_clean_modes import CleanRoutes , VacuumModes , WaterModes
2122
2223from .common import V1ResponseData
2324
24- _WRITE_KEYS = ("segment" , "fan_power" , "water_box_mode" , "mop_mode" , "repeat" , "seq_type" )
25+ # StatusTrait reports these sentinel codes while in custom or smart plan modes;
26+ # they are not valid concrete per-room settings.
27+ _INVALID_FAN_POWER_CODES = frozenset ({VacuumModes .CUSTOMIZED .code , VacuumModes .SMART_MODE .code })
28+ _INVALID_WATER_MODE_CODES = frozenset ({WaterModes .CUSTOMIZED .code , WaterModes .SMART_MODE .code })
29+ _INVALID_MOP_MODE_CODES = frozenset ({CleanRoutes .CUSTOMIZED .code , CleanRoutes .SMART_MODE .code })
30+
31+
32+ def _resolve_mode_codes (
33+ fan_power : VacuumModes | int | None ,
34+ water_box_mode : WaterModes | int | None ,
35+ mop_mode : CleanRoutes | int | None ,
36+ ) -> tuple [int | None , int | None , int | None ]:
37+ """Unwrap mode enums to wire codes and reject global sentinel codes."""
38+ fan_code = fan_power .code if isinstance (fan_power , VacuumModes ) else fan_power
39+ water_code = water_box_mode .code if isinstance (water_box_mode , WaterModes ) else water_box_mode
40+ mop_code = mop_mode .code if isinstance (mop_mode , CleanRoutes ) else mop_mode
41+
42+ if fan_code in _INVALID_FAN_POWER_CODES :
43+ raise ValueError (f"Invalid per-segment fan_power sentinel code: { fan_code } " )
44+ if water_code in _INVALID_WATER_MODE_CODES :
45+ raise ValueError (f"Invalid per-segment water_box_mode sentinel code: { water_code } " )
46+ if mop_code in _INVALID_MOP_MODE_CODES :
47+ raise ValueError (f"Invalid per-segment mop_mode sentinel code: { mop_code } " )
48+
49+ return fan_code , water_code , mop_code
2550
2651
2752class CustomizeCleanModeConverter (common .V1TraitDataConverter ):
@@ -37,15 +62,9 @@ def convert(self, response: V1ResponseData) -> CustomizeCleanModes:
3762class CustomizeCleanModeTrait (CustomizeCleanModes , common .V1TraitMixin ):
3863 """Trait for reading and writing per-room clean mode overrides.
3964
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.
65+ Gated on `is_customized_clean_supported` (which covers
66+ `get/set_customize_clean_mode` in general), while `clean_then_mop` writes
67+ are additionally gated on `is_clean_then_mop_mode_supported`.
4968 """
5069
5170 command = RoborockCommand .GET_CUSTOMIZE_CLEAN_MODE
@@ -56,18 +75,14 @@ def __init__(self, device_features: DeviceFeaturesTrait) -> None:
5675 super ().__init__ ()
5776 common .V1TraitMixin .__init__ (self )
5877 self ._device_features = device_features
59- self ._raw_by_segment : dict [int , dict ] = {}
78+ self ._raw_by_segment : dict [int , dict [ str , Any ] ] = {}
6079 self ._write_lock = asyncio .Lock ()
6180
6281 async def refresh (self ) -> None :
6382 """Refresh the contents of this trait.
6483
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.
84+ Retains each room's raw wire dict keyed by canonical typed segment id
85+ so writes round-trip untouched rooms and unmodeled per-model fields.
7186 """
7287 response = await self .rpc_channel .send_command (self .command )
7388 try :
@@ -79,18 +94,10 @@ async def refresh(self) -> None:
7994 payload = response ,
8095 inner_error = err ,
8196 ) 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 ] = {}
97+ assert isinstance (response , list ) and new_data .modes is not None
98+ # Key by canonical typed `mode.segment` (decamelized/coerced to int) so
99+ # `_raw_by_segment` stays aligned with `by_segment` across casing/type quirks.
100+ raw_by_segment : dict [int , dict [str , Any ]] = {}
94101 for raw_entry , mode in zip (response , new_data .modes , strict = True ):
95102 if mode .segment in raw_by_segment :
96103 raise RoborockParsingException (
@@ -108,94 +115,86 @@ async def set_clean_then_mop(
108115 segment : int ,
109116 enabled : bool ,
110117 * ,
111- fan_power : VacuumModes | int ,
112- water_box_mode : WaterModes | int ,
113- mop_mode : CleanRoutes | int ,
114- repeat : int = 1 ,
118+ fan_power : VacuumModes | int | None = None ,
119+ water_box_mode : WaterModes | int | None = None ,
120+ mop_mode : CleanRoutes | int | None = None ,
121+ repeat : int | None = None ,
115122 ) -> None :
116123 """Set whether a single room is vacuumed fully before it is mopped.
117124
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.
125+ Delegates to `set_segment_clean_mode(..., clean_then_mop=enabled)`;
126+ omitted mode/repeat arguments preserve an existing room's settings.
156127 """
157- if not self ._device_features .is_clean_then_mop_mode_supported :
128+ await self .set_segment_clean_mode (
129+ segment ,
130+ fan_power = fan_power ,
131+ water_box_mode = water_box_mode ,
132+ mop_mode = mop_mode ,
133+ repeat = repeat ,
134+ clean_then_mop = enabled ,
135+ )
136+
137+ async def set_segment_clean_mode (
138+ self ,
139+ segment : int ,
140+ * ,
141+ fan_power : VacuumModes | int | None = None ,
142+ water_box_mode : WaterModes | int | None = None ,
143+ mop_mode : CleanRoutes | int | None = None ,
144+ repeat : int | None = None ,
145+ clean_then_mop : bool | None = None ,
146+ ) -> None :
147+ """Set or update a single room's custom cleaning mode override.
148+
149+ Omitted fields preserve the room's existing override when present. For
150+ a room without an existing override, `fan_power`, `water_box_mode`, and
151+ `mop_mode` are required (firmware rejects requests missing `mop_mode`)
152+ and `repeat` defaults to `1` (omitting `repeat` on wire resets it to `1`
153+ on firmware).
154+
155+ Do not pass `StatusTrait` mode values as a fallback: while in custom or
156+ smart plan mode, `StatusTrait` reports sentinel codes (`106/204/302` or
157+ `110/209/306`), which are rejected with `ValueError`.
158+ """
159+ if all (v is None for v in (fan_power , water_box_mode , mop_mode , repeat , clean_then_mop )):
160+ raise ValueError ("At least one clean mode setting must be provided" )
161+ if clean_then_mop is not None and not self ._device_features .is_clean_then_mop_mode_supported :
158162 raise RoborockUnsupportedFeature ("Device does not support clean-then-mop" )
163+ if repeat is not None and repeat < 1 :
164+ raise ValueError (f"repeat must be >= 1, got { repeat } " )
165+
166+ fan_code , water_code , mop_code = _resolve_mode_codes (fan_power , water_box_mode , mop_mode )
159167
168+ # Serialize read-merge-write since SET_CUSTOMIZE_CLEAN_MODE replaces the
169+ # entire per-room table on V1 firmware rather than patching a single entry.
160170 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 ()
171+ # Lazily load the existing table if the caller hasn't refreshed yet
172+ # so a full-table SET doesn't wipe other rooms.
173+ if self .modes is None :
174+ await self .refresh ()
175+
176+ existing_mode = self .by_segment .get (segment )
177+ if existing_mode is None and (fan_code is None or water_code is None or mop_code is None ):
178+ raise ValueError (
179+ "fan_power, water_box_mode, and mop_mode must be provided when not already set "
180+ f"on segment { segment } "
181+ )
168182
169- seq_type = SEQ_TYPE_CLEAN_THEN_MOP if enabled else 0
170- new_entry = {
183+ updates : dict [str , int | None ] = {
171184 "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 ,
185+ "fan_power" : fan_code ,
186+ "water_box_mode" : water_code ,
187+ "mop_mode" : mop_code ,
188+ "repeat" : repeat or ( existing_mode . repeat if existing_mode else None ) or 1 ,
189+ "seq_type" : ( SEQ_TYPE_CLEAN_THEN_MOP if clean_then_mop else 0 ) if clean_then_mop is not None else None ,
177190 }
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.
191+ new_entry = {k : v for k , v in updates .items () if v is not None }
192+
193+ # Overlay updated keys onto this room's raw dict (preserving any
194+ # unmodeled per-model fields) and send the full segment table.
185195 raw_entries = dict (self ._raw_by_segment )
186196 raw_entries [segment ] = {** raw_entries .get (segment , {}), ** new_entry }
187197
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.
199198 await self .rpc_channel .send_command (
200199 RoborockCommand .SET_CUSTOMIZE_CLEAN_MODE , params = list (raw_entries .values ())
201200 )
0 commit comments