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.
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.
3+ Per-room overrides are persisted on the device and applied when cleaning with
4+ the global mode set to custom (`CleaningMode.CUSTOM` where supported). Rooms
5+ without an override are absent from `modes`.
106"""
117
128import asyncio
9+ from typing import Any
1310
1411from roborock .data import CustomizeCleanModes , SegmentCleanMode
12+ from roborock .data .containers import _decamelize
1513from roborock .data .v1 .v1_clean_modes import CleanRoutes , VacuumModes , WaterModes
1614from roborock .data .v1 .v1_containers import SEQ_TYPE_CLEAN_THEN_MOP
1715from roborock .devices .traits .v1 import common
2119
2220from .common import V1ResponseData
2321
24- _WRITE_KEYS = ("segment" , "fan_power" , "water_box_mode" , "mop_mode" , "repeat" , "seq_type" )
22+ _INVALID_FAN_POWER_CODES = frozenset ({VacuumModes .CUSTOMIZED .code , VacuumModes .SMART_MODE .code })
23+ _INVALID_WATER_MODE_CODES = frozenset ({WaterModes .CUSTOMIZED .code , WaterModes .SMART_MODE .code })
24+ _INVALID_MOP_MODE_CODES = frozenset ({CleanRoutes .CUSTOMIZED .code , CleanRoutes .SMART_MODE .code })
25+
26+
27+ def _resolve_mode_codes (
28+ fan_power : VacuumModes | int | None ,
29+ water_box_mode : WaterModes | int | None ,
30+ mop_mode : CleanRoutes | int | None ,
31+ ) -> tuple [int | None , int | None , int | None ]:
32+ """Unwrap mode enums to wire codes and reject global sentinel codes."""
33+ fan_code = fan_power .code if isinstance (fan_power , VacuumModes ) else fan_power
34+ water_code = water_box_mode .code if isinstance (water_box_mode , WaterModes ) else water_box_mode
35+ mop_code = mop_mode .code if isinstance (mop_mode , CleanRoutes ) else mop_mode
36+
37+ if fan_code in _INVALID_FAN_POWER_CODES :
38+ raise ValueError (f"Invalid per-segment fan_power sentinel code: { fan_code } " )
39+ if water_code in _INVALID_WATER_MODE_CODES :
40+ raise ValueError (f"Invalid per-segment water_box_mode sentinel code: { water_code } " )
41+ if mop_code in _INVALID_MOP_MODE_CODES :
42+ raise ValueError (f"Invalid per-segment mop_mode sentinel code: { mop_code } " )
43+
44+ return fan_code , water_code , mop_code
2545
2646
2747class CustomizeCleanModeConverter (common .V1TraitDataConverter ):
@@ -35,18 +55,7 @@ def convert(self, response: V1ResponseData) -> CustomizeCleanModes:
3555
3656
3757class 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- """
58+ """Trait for reading and writing per-room clean mode overrides."""
5059
5160 command = RoborockCommand .GET_CUSTOMIZE_CLEAN_MODE
5261 converter = CustomizeCleanModeConverter ()
@@ -56,19 +65,11 @@ def __init__(self, device_features: DeviceFeaturesTrait) -> None:
5665 super ().__init__ ()
5766 common .V1TraitMixin .__init__ (self )
5867 self ._device_features = device_features
59- self ._raw_by_segment : dict [int , dict ] = {}
68+ self ._raw_by_segment : dict [int , dict [ str , Any ] ] = {}
6069 self ._write_lock = asyncio .Lock ()
6170
6271 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+ """Refresh the contents of this trait and retain raw per-segment wire dicts."""
7273 response = await self .rpc_channel .send_command (self .command )
7374 try :
7475 new_data = self .converter .convert (response )
@@ -79,18 +80,8 @@ async def refresh(self) -> None:
7980 payload = response ,
8081 inner_error = err ,
8182 ) 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 ] = {}
83+ assert isinstance (response , list ) and new_data .modes is not None
84+ raw_by_segment : dict [int , dict [str , Any ]] = {}
9485 for raw_entry , mode in zip (response , new_data .modes , strict = True ):
9586 if mode .segment in raw_by_segment :
9687 raise RoborockParsingException (
@@ -108,94 +99,77 @@ async def set_clean_then_mop(
10899 segment : int ,
109100 enabled : bool ,
110101 * ,
111- fan_power : VacuumModes | int ,
112- water_box_mode : WaterModes | int ,
113- mop_mode : CleanRoutes | int ,
114- repeat : int = 1 ,
102+ fan_power : VacuumModes | int | None = None ,
103+ water_box_mode : WaterModes | int | None = None ,
104+ mop_mode : CleanRoutes | int | None = None ,
105+ repeat : int | None = None ,
106+ ) -> None :
107+ """Set whether a single room is vacuumed fully before it is mopped."""
108+ await self .set_segment_clean_mode (
109+ segment ,
110+ fan_power = fan_power ,
111+ water_box_mode = water_box_mode ,
112+ mop_mode = mop_mode ,
113+ repeat = repeat ,
114+ clean_then_mop = enabled ,
115+ )
116+
117+ async def set_segment_clean_mode (
118+ self ,
119+ segment : int ,
120+ * ,
121+ fan_power : VacuumModes | int | None = None ,
122+ water_box_mode : WaterModes | int | None = None ,
123+ mop_mode : CleanRoutes | int | None = None ,
124+ repeat : int | None = None ,
125+ clean_then_mop : bool | None = None ,
115126 ) -> 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.
127+ """Set or update a single room's custom cleaning mode override.
128+
129+ Omitted fields preserve the room's existing override when present; for
130+ a room without an existing override, `fan_power`, `water_box_mode`, and
131+ `mop_mode` are required and `repeat` defaults to `1`.
156132 """
157- if not self ._device_features .is_clean_then_mop_mode_supported :
133+ if all (v is None for v in (fan_power , water_box_mode , mop_mode , repeat , clean_then_mop )):
134+ raise ValueError ("At least one clean mode setting must be provided" )
135+ if clean_then_mop is not None and not self ._device_features .is_clean_then_mop_mode_supported :
158136 raise RoborockUnsupportedFeature ("Device does not support clean-then-mop" )
137+ if repeat is not None and repeat < 1 :
138+ raise ValueError (f"repeat must be >= 1, got { repeat } " )
139+
140+ fan_code , water_code , mop_code = _resolve_mode_codes (fan_power , water_box_mode , mop_mode )
159141
160142 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 ()
143+ # Lazily load the existing table if the caller hasn't refreshed yet
144+ # so a full-table SET doesn't wipe other rooms.
145+ if self .modes is None :
146+ await self .refresh ()
147+
148+ base = self .by_segment .get (segment ) or SegmentCleanMode (segment = segment )
149+ resolved_fan = fan_code if fan_code is not None else base .fan_power
150+ resolved_water = water_code if water_code is not None else base .water_box_mode
151+ resolved_mop = mop_code if mop_code is not None else base .mop_mode
152+ if resolved_fan is None or resolved_water is None or resolved_mop is None :
153+ raise ValueError (
154+ "fan_power, water_box_mode, and mop_mode must be provided when not already set "
155+ f"on segment { segment } "
156+ )
168157
169- seq_type = SEQ_TYPE_CLEAN_THEN_MOP if enabled else 0
170- new_entry = {
158+ new_entry : dict [str , Any ] = {
171159 "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 ,
160+ "fan_power" : resolved_fan ,
161+ "water_box_mode" : resolved_water ,
162+ "mop_mode" : resolved_mop ,
163+ "repeat" : repeat if repeat is not None else (base .repeat if base .repeat is not None else 1 ),
177164 }
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.
165+ if clean_then_mop is not None :
166+ new_entry ["seq_type" ] = SEQ_TYPE_CLEAN_THEN_MOP if clean_then_mop else 0
167+
168+ # SET_CUSTOMIZE_CLEAN_MODE replaces the entire segment table on V1 firmware.
169+ existing = self ._raw_by_segment .get (segment , {})
170+ preserved = {k : v for k , v in existing .items () if _decamelize (k ) not in new_entry }
171+ raw_entries = {** self ._raw_by_segment , segment : {** preserved , ** new_entry }}
172+
199173 await self .rpc_channel .send_command (
200174 RoborockCommand .SET_CUSTOMIZE_CLEAN_MODE , params = list (raw_entries .values ())
201175 )
0 commit comments