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,11 @@ 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 `repeat` and
67+ `clean_then_mop` writes are additionally gated on
68+ `is_custom_clean_mode_count_supported` and
69+ `is_clean_then_mop_mode_supported`.
4970 """
5071
5172 command = RoborockCommand .GET_CUSTOMIZE_CLEAN_MODE
@@ -56,18 +77,14 @@ def __init__(self, device_features: DeviceFeaturesTrait) -> None:
5677 super ().__init__ ()
5778 common .V1TraitMixin .__init__ (self )
5879 self ._device_features = device_features
59- self ._raw_by_segment : dict [int , dict ] = {}
80+ self ._raw_by_segment : dict [int , dict [ str , Any ] ] = {}
6081 self ._write_lock = asyncio .Lock ()
6182
6283 async def refresh (self ) -> None :
6384 """Refresh the contents of this trait.
6485
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.
86+ Retains each room's raw wire dict keyed by canonical typed segment id
87+ so writes round-trip untouched rooms and unmodeled per-model fields.
7188 """
7289 response = await self .rpc_channel .send_command (self .command )
7390 try :
@@ -79,18 +96,10 @@ async def refresh(self) -> None:
7996 payload = response ,
8097 inner_error = err ,
8198 ) 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 ] = {}
99+ assert isinstance (response , list ) and new_data .modes is not None
100+ # Key by canonical typed `mode.segment` (decamelized/coerced to int) so
101+ # `_raw_by_segment` stays aligned with `by_segment` across casing/type quirks.
102+ raw_by_segment : dict [int , dict [str , Any ]] = {}
94103 for raw_entry , mode in zip (response , new_data .modes , strict = True ):
95104 if mode .segment in raw_by_segment :
96105 raise RoborockParsingException (
@@ -108,94 +117,96 @@ async def set_clean_then_mop(
108117 segment : int ,
109118 enabled : bool ,
110119 * ,
111- fan_power : VacuumModes | int ,
112- water_box_mode : WaterModes | int ,
113- mop_mode : CleanRoutes | int ,
114- repeat : int = 1 ,
120+ fan_power : VacuumModes | int | None = None ,
121+ water_box_mode : WaterModes | int | None = None ,
122+ mop_mode : CleanRoutes | int | None = None ,
123+ repeat : int | None = None ,
115124 ) -> None :
116125 """Set whether a single room is vacuumed fully before it is mopped.
117126
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.
127+ Delegates to `set_segment_clean_mode(..., clean_then_mop=enabled)`;
128+ omitted mode/repeat arguments preserve an existing room's settings.
156129 """
157- if not self ._device_features .is_clean_then_mop_mode_supported :
130+ await self .set_segment_clean_mode (
131+ segment ,
132+ fan_power = fan_power ,
133+ water_box_mode = water_box_mode ,
134+ mop_mode = mop_mode ,
135+ repeat = repeat ,
136+ clean_then_mop = enabled ,
137+ )
138+
139+ async def set_segment_clean_mode (
140+ self ,
141+ segment : int ,
142+ * ,
143+ fan_power : VacuumModes | int | None = None ,
144+ water_box_mode : WaterModes | int | None = None ,
145+ mop_mode : CleanRoutes | int | None = None ,
146+ repeat : int | None = None ,
147+ clean_then_mop : bool | None = None ,
148+ ) -> None :
149+ """Set or update a single room's custom cleaning mode override.
150+
151+ Omitted fields preserve the room's existing override when present. For
152+ a room without an existing override, `fan_power`, `water_box_mode`, and
153+ `mop_mode` are required (firmware rejects requests missing `mop_mode`)
154+ and `repeat` defaults to `1` (omitting `repeat` on wire resets it to `1`
155+ on firmware).
156+
157+ Do not pass `StatusTrait` mode values as a fallback: while in custom or
158+ smart plan mode, `StatusTrait` reports sentinel codes (`106/204/302` or
159+ `110/209/306`), which are rejected with `ValueError`.
160+ """
161+ if all (v is None for v in (fan_power , water_box_mode , mop_mode , repeat , clean_then_mop )):
162+ raise ValueError ("At least one clean mode setting must be provided" )
163+ if clean_then_mop is not None and not self ._device_features .is_clean_then_mop_mode_supported :
158164 raise RoborockUnsupportedFeature ("Device does not support clean-then-mop" )
165+ if repeat is not None :
166+ if not self ._device_features .is_custom_clean_mode_count_supported :
167+ raise RoborockUnsupportedFeature ("Device does not support per-segment repeat count" )
168+ if repeat < 1 :
169+ raise ValueError (f"repeat must be >= 1, got { repeat } " )
170+
171+ fan_code , water_code , mop_code = _resolve_mode_codes (fan_power , water_box_mode , mop_mode )
159172
173+ # Serialize read-merge-write since SET_CUSTOMIZE_CLEAN_MODE replaces the
174+ # entire per-room table on V1 firmware rather than patching a single entry.
160175 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.
176+ # Always refresh immediately before merging so a full-table SET
177+ # never clobbers external edits (e.g. from the vendor app or a map switch).
167178 await self .refresh ()
168179
169- seq_type = SEQ_TYPE_CLEAN_THEN_MOP if enabled else 0
170- new_entry = {
180+ existing_mode = self .by_segment .get (segment ) or SegmentCleanMode (segment = segment )
181+ if (
182+ (fan_code if fan_code is not None else existing_mode .fan_power ) is None
183+ or (water_code if water_code is not None else existing_mode .water_box_mode ) is None
184+ or (mop_code if mop_code is not None else existing_mode .mop_mode ) is None
185+ ):
186+ raise ValueError (
187+ "fan_power, water_box_mode, and mop_mode must be provided when not already set "
188+ f"on segment { segment } "
189+ )
190+
191+ updates : dict [str , int | None ] = {
171192 "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 ,
193+ "fan_power" : fan_code ,
194+ "water_box_mode" : water_code ,
195+ "mop_mode" : mop_code ,
196+ "repeat" : (
197+ (repeat or existing_mode .repeat or 1 )
198+ if self ._device_features .is_custom_clean_mode_count_supported
199+ else None
200+ ),
201+ "seq_type" : (SEQ_TYPE_CLEAN_THEN_MOP if clean_then_mop else 0 ) if clean_then_mop is not None else None ,
177202 }
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.
203+ new_entry = {k : v for k , v in updates .items () if v is not None }
204+
205+ # Overlay updated keys onto this room's raw dict (preserving any
206+ # unmodeled per-model fields) and send the full segment table.
185207 raw_entries = dict (self ._raw_by_segment )
186208 raw_entries [segment ] = {** raw_entries .get (segment , {}), ** new_entry }
187209
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.
199210 await self .rpc_channel .send_command (
200211 RoborockCommand .SET_CUSTOMIZE_CLEAN_MODE , params = list (raw_entries .values ())
201212 )
0 commit comments