Skip to content

Commit d8bcbb9

Browse files
committed
feat(v1): generalize segment clean mode updates and preserve existing settings
1 parent ed5f859 commit d8bcbb9

2 files changed

Lines changed: 323 additions & 60 deletions

File tree

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

Lines changed: 127 additions & 60 deletions
Original file line numberDiff line numberDiff line change
@@ -4,14 +4,19 @@
44
back to the global settings (fan power, water box mode, mop mode and
55
clean-then-mop) for those. An empty list means no room currently has one.
66
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.
7+
A per-room override set via `set_segment_clean_mode` or `set_clean_then_mop`
8+
is persisted on the device across cleaning runs, and is applied whenever the
9+
robot cleans with its global cleaning mode set to custom (`fan_power=106`,
10+
`water_box_mode=204`, `mop_mode=302`, e.g. `CleaningMode.CUSTOM` where
11+
supported). When the robot runs in an explicit global mode (`VACUUM`,
12+
`VAC_AND_MOP`, `MOP`, or `SMART_MODE`), the global settings take precedence.
1013
"""
1114

1215
import asyncio
16+
from typing import Any
1317

1418
from roborock.data import CustomizeCleanModes, SegmentCleanMode
19+
from roborock.data.containers import _decamelize
1520
from roborock.data.v1.v1_clean_modes import CleanRoutes, VacuumModes, WaterModes
1621
from roborock.data.v1.v1_containers import SEQ_TYPE_CLEAN_THEN_MOP
1722
from roborock.devices.traits.v1 import common
@@ -21,7 +26,29 @@
2126

2227
from .common import V1ResponseData
2328

24-
_WRITE_KEYS = ("segment", "fan_power", "water_box_mode", "mop_mode", "repeat", "seq_type")
29+
_INVALID_FAN_POWER_CODES = frozenset({VacuumModes.CUSTOMIZED.code, VacuumModes.SMART_MODE.code})
30+
_INVALID_WATER_MODE_CODES = frozenset({WaterModes.CUSTOMIZED.code, WaterModes.SMART_MODE.code})
31+
_INVALID_MOP_MODE_CODES = frozenset({CleanRoutes.CUSTOMIZED.code, CleanRoutes.SMART_MODE.code})
32+
33+
34+
def _resolve_mode_codes(
35+
fan_power: VacuumModes | int | None,
36+
water_box_mode: WaterModes | int | None,
37+
mop_mode: CleanRoutes | int | None,
38+
) -> tuple[int | None, int | None, int | None]:
39+
"""Unwrap mode enums to wire codes and reject global sentinel codes."""
40+
fan_code = fan_power.code if isinstance(fan_power, VacuumModes) else fan_power
41+
water_code = water_box_mode.code if isinstance(water_box_mode, WaterModes) else water_box_mode
42+
mop_code = mop_mode.code if isinstance(mop_mode, CleanRoutes) else mop_mode
43+
44+
if fan_code in _INVALID_FAN_POWER_CODES:
45+
raise ValueError(f"Invalid per-segment fan_power sentinel code: {fan_code}")
46+
if water_code in _INVALID_WATER_MODE_CODES:
47+
raise ValueError(f"Invalid per-segment water_box_mode sentinel code: {water_code}")
48+
if mop_code in _INVALID_MOP_MODE_CODES:
49+
raise ValueError(f"Invalid per-segment mop_mode sentinel code: {mop_code}")
50+
51+
return fan_code, water_code, mop_code
2552

2653

2754
class CustomizeCleanModeConverter(common.V1TraitDataConverter):
@@ -41,9 +68,8 @@ class CustomizeCleanModeTrait(CustomizeCleanModes, common.V1TraitMixin):
4168
`get/set_customize_clean_mode` in general, not `is_clean_then_mop_mode_supported`
4269
(which only gates the narrower `seq_type` axis within it). A device can
4370
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
71+
specifically; writing `clean_then_mop` via `set_clean_then_mop` or
72+
`set_segment_clean_mode` additionally checks
4773
`is_clean_then_mop_mode_supported` itself before writing, since writing
4874
`seq_type` to firmware that doesn't support it is not just a no-op read.
4975
"""
@@ -56,7 +82,7 @@ def __init__(self, device_features: DeviceFeaturesTrait) -> None:
5682
super().__init__()
5783
common.V1TraitMixin.__init__(self)
5884
self._device_features = device_features
59-
self._raw_by_segment: dict[int, dict] = {}
85+
self._raw_by_segment: dict[int, dict[str, Any]] = {}
6086
self._write_lock = asyncio.Lock()
6187

6288
async def refresh(self) -> None:
@@ -90,7 +116,7 @@ async def refresh(self) -> None:
90116
# in the same order, by construction (one SegmentCleanMode per raw
91117
# entry, no filtering) - zip(strict=True) turns any future change to
92118
# that invariant into a loud error instead of silent misalignment.
93-
raw_by_segment: dict[int, dict] = {}
119+
raw_by_segment: dict[int, dict[str, Any]] = {}
94120
for raw_entry, mode in zip(response, new_data.modes, strict=True):
95121
if mode.segment in raw_by_segment:
96122
raise RoborockParsingException(
@@ -108,44 +134,57 @@ async def set_clean_then_mop(
108134
segment: int,
109135
enabled: bool,
110136
*,
111-
fan_power: VacuumModes | int,
112-
water_box_mode: WaterModes | int,
113-
mop_mode: CleanRoutes | int,
114-
repeat: int = 1,
137+
fan_power: VacuumModes | int | None = None,
138+
water_box_mode: WaterModes | int | None = None,
139+
mop_mode: CleanRoutes | int | None = None,
140+
repeat: int | None = None,
115141
) -> None:
116142
"""Set whether a single room is vacuumed fully before it is mopped.
117143
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.
144+
Convenience wrapper around `set_segment_clean_mode(..., clean_then_mop=enabled)`.
145+
If `segment` already has an override on the device, `fan_power`,
146+
`water_box_mode`, `mop_mode`, and `repeat` may be omitted to preserve
147+
that room's existing settings; if `segment` has no prior override,
148+
`fan_power`, `water_box_mode`, and `mop_mode` are required (`repeat`
149+
defaults to `1`).
150+
"""
151+
await self.set_segment_clean_mode(
152+
segment,
153+
fan_power=fan_power,
154+
water_box_mode=water_box_mode,
155+
mop_mode=mop_mode,
156+
repeat=repeat,
157+
clean_then_mop=enabled,
158+
)
159+
160+
async def set_segment_clean_mode(
161+
self,
162+
segment: int,
163+
*,
164+
fan_power: VacuumModes | int | None = None,
165+
water_box_mode: WaterModes | int | None = None,
166+
mop_mode: CleanRoutes | int | None = None,
167+
repeat: int | None = None,
168+
clean_then_mop: bool | None = None,
169+
) -> None:
170+
"""Set or update a single room's custom cleaning mode override.
171+
172+
When `segment` already has an override on the device, any omitted
173+
`fan_power`, `water_box_mode`, `mop_mode`, `repeat`, or `clean_then_mop`
174+
fields preserve that room's existing values (along with any unmodeled
175+
model-specific fields). When `segment` has no existing override yet,
176+
`fan_power`, `water_box_mode`, and `mop_mode` are required (`mop_mode`
177+
is rejected by firmware if omitted) and `repeat` defaults to `1`
178+
(omitting `repeat` on wire resets it to `1` on firmware).
179+
180+
Do NOT source mode values from `StatusTrait` as a fallback when a room
181+
has no override yet: while the device is in custom or smart plan
182+
cleaning mode, `StatusTrait` reports the global sentinel codes
183+
(`CUSTOMIZED` `106/204/302` or `SMART_MODE` `110/209/306`), which are
184+
rejected here with `ValueError`.
185+
186+
Raises `RoborockUnsupportedFeature` if `clean_then_mop` is specified on
187+
a device where `is_clean_then_mop_mode_supported` is `False`.
149188
150189
This whole read-merge-write sequence is serialized per trait
151190
instance (concurrent calls queue rather than racing): the device's
@@ -154,36 +193,64 @@ async def set_clean_then_mop(
154193
building their own full table from the same stale read would
155194
otherwise silently revert each other's room.
156195
"""
157-
if not self._device_features.is_clean_then_mop_mode_supported:
196+
if (
197+
fan_power is None
198+
and water_box_mode is None
199+
and mop_mode is None
200+
and repeat is None
201+
and clean_then_mop is None
202+
):
203+
raise ValueError("At least one clean mode setting must be provided")
204+
if clean_then_mop is not None and not self._device_features.is_clean_then_mop_mode_supported:
158205
raise RoborockUnsupportedFeature("Device does not support clean-then-mop")
206+
if repeat is not None and repeat < 1:
207+
raise ValueError(f"repeat must be >= 1, got {repeat}")
208+
209+
fan_code, water_code, mop_code = _resolve_mode_codes(fan_power, water_box_mode, mop_mode)
159210

160211
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()
212+
# Lazily load the existing table if the caller hasn't refreshed yet
213+
# so a full-table SET doesn't wipe other rooms; once loaded,
214+
# subsequent writes rely on the post-write refresh below.
215+
if self.modes is None:
216+
await self.refresh()
168217

169-
seq_type = SEQ_TYPE_CLEAN_THEN_MOP if enabled else 0
170-
new_entry = {
218+
existing = self._raw_by_segment.get(segment, {})
219+
existing_mode = self.by_segment.get(segment)
220+
resolved_fan = fan_code if fan_code is not None else (existing_mode.fan_power if existing_mode else None)
221+
resolved_water = (
222+
water_code if water_code is not None else (existing_mode.water_box_mode if existing_mode else None)
223+
)
224+
resolved_mop = mop_code if mop_code is not None else (existing_mode.mop_mode if existing_mode else None)
225+
if resolved_fan is None or resolved_water is None or resolved_mop is None:
226+
raise ValueError(
227+
"fan_power, water_box_mode, and mop_mode must be provided when not already set "
228+
f"on segment {segment}"
229+
)
230+
231+
existing_repeat = existing_mode.repeat if existing_mode else None
232+
resolved_repeat = repeat if repeat is not None else (existing_repeat if existing_repeat is not None else 1)
233+
234+
new_entry: dict[str, Any] = {
171235
"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,
236+
"fan_power": resolved_fan,
237+
"water_box_mode": resolved_water,
238+
"mop_mode": resolved_mop,
239+
"repeat": resolved_repeat,
177240
}
241+
if clean_then_mop is not None:
242+
new_entry["seq_type"] = SEQ_TYPE_CLEAN_THEN_MOP if clean_then_mop else 0
243+
178244
# Start from this room's raw wire dict (if it already had an
179245
# override) so any field this library doesn't model - or
180246
# couldn't parse - survives the write, and only overlay the keys
181247
# this call actually changes. A room with no prior override
182248
# gets only the known fields; the device fills in its own
183249
# per-model defaults for the rest, same as the original
184250
# single-entry write did.
251+
preserved = {k: v for k, v in existing.items() if _decamelize(k) not in new_entry}
185252
raw_entries = dict(self._raw_by_segment)
186-
raw_entries[segment] = {**raw_entries.get(segment, {}), **new_entry}
253+
raw_entries[segment] = {**preserved, **new_entry}
187254

188255
# Send the full known table, not just the changed room: on at
189256
# least some V1 firmware (confirmed first-hand for a Saros 20

0 commit comments

Comments
 (0)