Skip to content

Commit 575f824

Browse files
author
Harry Coureau
committed
fix: simplify Q10 room cleaning state and commands
1 parent 8173937 commit 575f824

10 files changed

Lines changed: 198 additions & 107 deletions

File tree

‎roborock/data/b01_q10/b01_q10_containers.py‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -292,7 +292,9 @@ def fault_name(self) -> str | None:
292292
@property
293293
def clean_count_mode(self) -> Q10CleanCount | None:
294294
"""Return the typed cleaning pass count from the reported status."""
295-
return Q10CleanCount.from_code_optional(self.clean_count) if self.clean_count is not None else None
295+
if self.clean_count is None:
296+
return None
297+
return Q10CleanCount.from_code_optional(self.clean_count) or Q10CleanCount.UNKNOWN
296298

297299

298300
@dataclass

‎roborock/devices/traits/b01/q10/__init__.py‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -114,7 +114,7 @@ def __init__(self, channel: B01Q10Channel, *, map_parser_config: B01Q10MapParser
114114
self.maps = MapsTrait(self.command)
115115
self.map = MapContentTrait(self._map_dps, self.maps, self.command, map_parser_config=map_parser_config)
116116
self.room_cleaning = RoomCleaningTrait(self.command)
117-
self.vacuum = VacuumTrait(self.command, self.status, self.map, self.room_cleaning)
117+
self.vacuum = VacuumTrait(self.command, self.status, self.map)
118118
self.clean_history = CleanHistoryTrait(self.command)
119119
# Read-model traits updated from the device's DPS push stream.
120120
self._updatable_traits = [

‎roborock/devices/traits/b01/q10/room_cleaning.py‎

Lines changed: 9 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@
55
from dataclasses import dataclass
66
from typing import Any
77

8-
from roborock.data.b01_q10.b01_q10_code_mappings import B01_Q10_DP, YXCleanType, YXDeviceCleanTask
8+
from roborock.data.b01_q10.b01_q10_code_mappings import B01_Q10_DP
99
from roborock.data.b01_q10.b01_q10_containers import Q10RoomCleanSettings
1010
from roborock.data.containers import RoborockBase
1111
from roborock.exceptions import RoborockException
@@ -21,8 +21,7 @@
2121
class RoomCleaning(RoborockBase):
2222
"""Current customized room-cleaning state."""
2323

24-
settings: tuple[Q10RoomCleanSettings, ...] = ()
25-
settings_available: bool = False
24+
settings: list[Q10RoomCleanSettings] | None = None
2625

2726

2827
class RoomCleaningTrait(RoomCleaning, UpdatableTrait):
@@ -35,6 +34,8 @@ def __init__(self, command: CommandTrait) -> None:
3534

3635
def settings_for_room(self, room_id: int) -> Q10RoomCleanSettings | None:
3736
"""Return the latest reported settings for one room."""
37+
if self.settings is None:
38+
return None
3839
return next((room for room in self.settings if room.room_id == room_id), None)
3940

4041
async def refresh(self) -> None:
@@ -47,17 +48,6 @@ async def set_settings(self, settings: Sequence[Q10RoomCleanSettings]) -> None:
4748
await self._command.send(B01_Q10_DP.COMMON, {str(B01_Q10_DP.CUSTOMER_CLEAN.code): payload})
4849
await self.refresh()
4950

50-
async def clean(self, settings: Sequence[Q10RoomCleanSettings]) -> None:
51-
"""Publish settings, select customized mode, and start the selected rooms."""
52-
selected = tuple(settings)
53-
payload = encode_room_clean_settings(selected)
54-
await self._command.send(B01_Q10_DP.COMMON, {str(B01_Q10_DP.CUSTOMER_CLEAN.code): payload})
55-
await self._command.send(B01_Q10_DP.CLEAN_MODE, YXCleanType.CUSTOMIZED.code)
56-
await self._command.send(
57-
B01_Q10_DP.START_CLEAN,
58-
{"cmd": YXDeviceCleanTask.ELECTORAL.code, "clean_paramters": [room.room_id for room in selected]},
59-
)
60-
6151
def update_from_dps(self, decoded_dps: dict[B01_Q10_DP, Any]) -> None:
6252
"""Replace full settings or upsert the rooms in a compact push."""
6353
payload = decoded_dps.get(B01_Q10_DP.CUSTOMER_CLEAN)
@@ -69,13 +59,11 @@ def update_from_dps(self, decoded_dps: dict[B01_Q10_DP, Any]) -> None:
6959
_LOGGER.debug("Ignoring malformed Q10 customized-room settings", exc_info=True)
7060
return
7161
if update.complete:
72-
settings = update.settings
62+
settings = list(update.settings)
7363
else:
74-
by_room = {room.room_id: room for room in self.settings}
64+
by_room = {room.room_id: room for room in (self.settings or [])}
7565
by_room.update((room.room_id, room) for room in update.settings)
76-
settings = tuple(by_room.values())
77-
changed = settings != self.settings or not self.settings_available
78-
self.settings = settings
79-
self.settings_available = True
80-
if changed:
66+
settings = list(by_room.values())
67+
if settings != self.settings:
68+
self.settings = settings
8169
self._notify_update()

‎roborock/devices/traits/b01/q10/vacuum.py‎

Lines changed: 9 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -16,12 +16,11 @@
1616
)
1717
from roborock.data.b01_q10.b01_q10_containers import Q10RoborockPoint, Q10RoomCleanSettings
1818
from roborock.exceptions import RoborockException
19-
from roborock.protocols.b01_q10_protocol import CleanParams, encode_clean_params
19+
from roborock.protocols.b01_q10_protocol import CleanParams, encode_clean_params, encode_room_clean_settings
2020

2121
from .command import CommandTrait
2222
from .goto import GotoAction, GotoActionCommand, GotoSnapshot
2323
from .map import MapContentTrait
24-
from .room_cleaning import RoomCleaningTrait
2524
from .status import StatusTrait
2625

2726
_GOTO_HALF_ZONE_SIZE = 200
@@ -44,13 +43,11 @@ def __init__(
4443
command: CommandTrait,
4544
status: StatusTrait,
4645
map_content: MapContentTrait,
47-
room_cleaning: RoomCleaningTrait,
4846
) -> None:
4947
"""Initialize the VacuumTrait."""
5048
self._command = command
5149
self._status = status
5250
self._map = map_content
53-
self._room_cleaning = room_cleaning
5451
self._goto_action: GotoAction | None = None
5552
self._goto_action_remove_listener: Callable[[], None] | None = None
5653
self._goto_timeout_task: asyncio.Task[None] | None = None
@@ -175,7 +172,14 @@ async def clean_segments(self, segment_ids: list[int]) -> None:
175172

176173
async def clean_rooms(self, settings: Sequence[Q10RoomCleanSettings]) -> None:
177174
"""Start a customized clean for the supplied rooms."""
178-
await self._room_cleaning.clean(settings)
175+
selected = tuple(settings)
176+
payload = encode_room_clean_settings(selected)
177+
await self._command.send(B01_Q10_DP.COMMON, {str(B01_Q10_DP.CUSTOMER_CLEAN.code): payload})
178+
await self._command.send(B01_Q10_DP.CLEAN_MODE, YXCleanType.CUSTOMIZED.code)
179+
await self._command.send(
180+
B01_Q10_DP.START_CLEAN,
181+
{"cmd": YXDeviceCleanTask.ELECTORAL.code, "clean_paramters": [room.room_id for room in selected]},
182+
)
179183
self.cancel_goto()
180184

181185
async def clean_zone(

‎roborock/protocols/b01_q10_protocol.py‎

Lines changed: 7 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,10 @@
11
"""Roborock B01 Protocol encoding and decoding."""
22

3-
import base64
43
import binascii
5-
6-
74
import json
85
import logging
96
import struct
10-
from base64 import b64encode
7+
from base64 import b64decode, b64encode
118
from collections.abc import Sequence
129
from dataclasses import dataclass
1310
from struct import pack
@@ -131,7 +128,7 @@ def encode_room_clean_settings(settings: Sequence[Q10RoomCleanSettings]) -> str:
131128
raise ValueError(f"{field_name} must be a supported {mode_type.__name__}")
132129
values.append(value.code)
133130
payload.extend(values)
134-
return base64.b64encode(payload).decode()
131+
return b64encode(payload).decode()
135132

136133

137134
def decode_room_clean_settings(payload: str) -> Q10RoomCleanUpdate:
@@ -142,7 +139,7 @@ def decode_room_clean_settings(payload: str) -> Q10RoomCleanUpdate:
142139
are room id 0, count 5, type 7, fan 8, water 9, and route 11.
143140
"""
144141
try:
145-
raw = base64.b64decode(payload, validate=True)
142+
raw = b64decode(payload, validate=True)
146143
except (ValueError, binascii.Error) as ex:
147144
raise RoborockException("Invalid Q10 customized-room payload: malformed base64") from ex
148145
if not raw:
@@ -253,7 +250,7 @@ def encode_restricted_zones(zones: Sequence[Q10RestrictedZone]) -> str:
253250
if len(zones) > 255:
254251
raise ValueError("zones must be a sequence of at most 255 restrictions")
255252
if not zones:
256-
return base64.b64encode(b"\x01\x00").decode()
253+
return b64encode(b"\x01\x00").decode()
257254

258255
payload = bytearray((1, len(zones)))
259256
for zone in zones:
@@ -276,7 +273,7 @@ def encode_restricted_zones(zones: Sequence[Q10RestrictedZone]) -> str:
276273
)
277274
record.extend(bytes(_Q10_ZONE_RECORD_SIZE - len(record)))
278275
payload.extend(record)
279-
return base64.b64encode(payload).decode()
276+
return b64encode(payload).decode()
280277

281278

282279
def encode_virtual_walls(walls: Sequence[Q10VirtualWall]) -> str:
@@ -297,7 +294,7 @@ def encode_virtual_walls(walls: Sequence[Q10VirtualWall]) -> str:
297294
y,
298295
)
299296
)
300-
return base64.b64encode(payload).decode()
297+
return b64encode(payload).decode()
301298

302299

303300
def encode_room_name(room_id: int, name: str) -> str:
@@ -313,7 +310,7 @@ def encode_room_name(room_id: int, name: str) -> str:
313310
payload = bytearray((1, room_id, 0, len(encoded_name)))
314311
payload.extend(encoded_name)
315312
payload.extend(bytes(_Q10_ROOM_NAME_FIELD_SIZE - len(encoded_name)))
316-
return base64.b64encode(payload).decode()
313+
return b64encode(payload).decode()
317314

318315

319316
def encode_mqtt_payload(command: B01_Q10_DP, params: ParamsType) -> RoborockMessage:

‎tests/devices/traits/b01/q10/__snapshots__/test_status.ambr‎

Lines changed: 0 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -42,9 +42,6 @@
4242
}),
4343
}),
4444
'room_cleaning': dict({
45-
'settings': tuple(
46-
),
47-
'settingsAvailable': False,
4845
}),
4946
'status': dict({
5047
'addCleanState': False,
@@ -427,9 +424,6 @@
427424
}),
428425
}),
429426
'room_cleaning': dict({
430-
'settings': tuple(
431-
),
432-
'settingsAvailable': False,
433427
}),
434428
'status': dict({
435429
'addCleanState': False,
@@ -502,9 +496,6 @@
502496
'network_info': dict({
503497
}),
504498
'room_cleaning': dict({
505-
'settings': tuple(
506-
),
507-
'settingsAvailable': False,
508499
}),
509500
'status': dict({
510501
}),

‎tests/devices/traits/b01/q10/test_room_cleaning.py‎

Lines changed: 51 additions & 50 deletions
Original file line numberDiff line numberDiff line change
@@ -55,40 +55,7 @@ async def test_set_settings_publishes_then_requests_full_settings(
5555
(B01_Q10_DP.COMMON, {"62": encode_room_clean_settings(settings)}),
5656
(B01_Q10_DP.COMMON, {"63": 0}),
5757
]
58-
assert q10_api.room_cleaning.settings == ()
59-
60-
61-
async def test_clean_rooms_sends_settings_mode_and_start_in_order(
62-
q10_api: Q10PropertiesApi, fake_channel: FakeB01Q10Channel
63-
) -> None:
64-
settings = (_settings(3), _settings(9))
65-
await q10_api.vacuum.clean_rooms(settings)
66-
assert fake_channel.published_commands == [
67-
(B01_Q10_DP.COMMON, {"62": encode_room_clean_settings(settings)}),
68-
(B01_Q10_DP.CLEAN_MODE, 4),
69-
(B01_Q10_DP.START_CLEAN, {"cmd": 2, "clean_paramters": [3, 9]}),
70-
]
71-
72-
73-
@pytest.mark.parametrize("fail_on", [1, 2, 3])
74-
async def test_publish_failure_stops_remaining_clean_commands(
75-
q10_api: Q10PropertiesApi, fake_channel: FakeB01Q10Channel, fail_on: int, monkeypatch: pytest.MonkeyPatch
76-
) -> None:
77-
original = fake_channel.send_command
78-
calls = 0
79-
80-
async def send(command, params=None):
81-
nonlocal calls
82-
calls += 1
83-
if calls == fail_on:
84-
raise RoborockException("publish failed")
85-
await original(command, params)
86-
87-
monkeypatch.setattr(fake_channel, "send_command", send)
88-
with pytest.raises(RoborockException, match="publish failed"):
89-
await q10_api.room_cleaning.clean((_settings(),))
90-
assert calls == fail_on
91-
assert len(fake_channel.published_commands) == fail_on - 1
58+
assert q10_api.room_cleaning.settings is None
9259

9360

9461
async def test_set_settings_failure_does_not_request_refresh(
@@ -109,30 +76,64 @@ def test_full_push_replaces_and_compact_push_upserts(q10_api: Q10PropertiesApi)
10976
trait.add_update_listener(lambda: notified.append(True))
11077
trait.update_from_dps({B01_Q10_DP.CUSTOMER_CLEAN: _complete_payload(_settings(3))})
11178
trait.update_from_dps({B01_Q10_DP.CUSTOMER_CLEAN: encode_room_clean_settings((_settings(9),))})
112-
assert trait.settings == (_settings(3), _settings(9))
79+
assert trait.settings == [_settings(3), _settings(9)]
11380
changed = _settings(3, fan=Q10RoomFanLevel.MAX)
11481
trait.update_from_dps({B01_Q10_DP.CUSTOMER_CLEAN: encode_room_clean_settings((changed,))})
115-
assert trait.settings == (changed, _settings(9))
82+
assert trait.settings == [changed, _settings(9)]
11683
assert trait.settings_for_room(3) == changed
11784
trait.update_from_dps({B01_Q10_DP.CUSTOMER_CLEAN: _complete_payload(_settings(1))})
118-
assert trait.settings == (_settings(1),)
85+
assert trait.settings == [_settings(1)]
11986
trait.update_from_dps({B01_Q10_DP.CUSTOMER_CLEAN: "invalid"})
120-
assert trait.settings == (_settings(1),)
87+
assert trait.settings == [_settings(1)]
12188
trait.update_from_dps({B01_Q10_DP.CUSTOMER_CLEAN: "AA=="})
122-
assert trait.settings == ()
123-
assert trait.settings_available
89+
assert trait.settings == []
12490
assert len(notified) == 5
12591

12692

127-
@pytest.mark.parametrize("field", ["fan_level", "water_level", "clean_type", "clean_count", "clean_line"])
128-
def test_unknown_setting_cannot_be_written(field: str) -> None:
129-
settings = _settings()
130-
setattr(settings, field, type(getattr(settings, field)).UNKNOWN)
131-
with pytest.raises(ValueError, match=field):
132-
encode_room_clean_settings((settings,))
93+
async def test_refresh_requests_complete_settings(q10_api: Q10PropertiesApi, fake_channel: FakeB01Q10Channel) -> None:
94+
await q10_api.room_cleaning.refresh()
95+
assert fake_channel.published_commands == [(B01_Q10_DP.COMMON, {"63": 0})]
96+
assert q10_api.room_cleaning.settings is None
13397

13498

135-
@pytest.mark.parametrize("rooms", [(), (_settings(-1),), (_settings(256),), (_settings(), _settings())])
136-
def test_semantic_room_guards(rooms: tuple[Q10RoomCleanSettings, ...]) -> None:
137-
with pytest.raises(ValueError):
138-
encode_room_clean_settings(rooms)
99+
def test_settings_for_room_unpopulated(q10_api: Q10PropertiesApi) -> None:
100+
assert q10_api.room_cleaning.settings_for_room(3) is None
101+
assert q10_api.room_cleaning.as_dict() == {}
102+
assert q10_api.as_dict()["room_cleaning"] == {}
103+
104+
105+
def test_settings_for_room_missing(q10_api: Q10PropertiesApi) -> None:
106+
q10_api.room_cleaning.update_from_dps({B01_Q10_DP.CUSTOMER_CLEAN: _complete_payload(_settings(3))})
107+
assert q10_api.room_cleaning.settings_for_room(9) is None
108+
109+
110+
def test_repeated_pushes_do_not_notify(q10_api: Q10PropertiesApi) -> None:
111+
trait = q10_api.room_cleaning
112+
notified: list[bool] = []
113+
trait.add_update_listener(lambda: notified.append(True))
114+
trait.update_from_dps({B01_Q10_DP.CUSTOMER_CLEAN: "invalid"})
115+
assert trait.settings is None
116+
assert not notified
117+
compact = encode_room_clean_settings((_settings(3),))
118+
trait.update_from_dps({B01_Q10_DP.CUSTOMER_CLEAN: compact})
119+
trait.update_from_dps({B01_Q10_DP.CUSTOMER_CLEAN: compact})
120+
trait.update_from_dps({B01_Q10_DP.CUSTOMER_CLEAN: _complete_payload(_settings(3))})
121+
assert trait.settings == [_settings(3)]
122+
assert len(notified) == 1
123+
assert isinstance(trait.as_dict()["settings"], list)
124+
trait.update_from_dps({B01_Q10_DP.CUSTOMER_CLEAN: "AA=="})
125+
trait.update_from_dps({B01_Q10_DP.CUSTOMER_CLEAN: "AA=="})
126+
assert trait.settings == []
127+
assert trait.as_dict() == {"settings": []}
128+
assert trait.settings_for_room(3) is None
129+
assert len(notified) == 2
130+
131+
132+
def test_first_empty_push_is_reported(q10_api: Q10PropertiesApi) -> None:
133+
trait = q10_api.room_cleaning
134+
notified: list[bool] = []
135+
trait.add_update_listener(lambda: notified.append(True))
136+
trait.update_from_dps({B01_Q10_DP.CUSTOMER_CLEAN: "AA=="})
137+
assert trait.settings == []
138+
assert trait.as_dict() == {"settings": []}
139+
assert notified == [True]

‎tests/devices/traits/b01/q10/test_status.py‎

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@
1111
from roborock.data import HomeDataDevice, HomeDataProduct
1212
from roborock.data.b01_q10.b01_q10_code_mappings import (
1313
B01_Q10_DP,
14+
Q10CleanCount,
1415
YXAreaUnit,
1516
YXCarpetCleanType,
1617
YXCleanLine,
@@ -282,3 +283,19 @@ async def test_q10_properties_as_dict_and_diagnostic_data(
282283
# Verify diagnostic_data extracts the properties correctly
283284
diagnostics = device.diagnostic_data()
284285
assert diagnostics == snapshot
286+
287+
288+
@pytest.mark.parametrize(
289+
("code", "expected"),
290+
[
291+
(None, None),
292+
(1, Q10CleanCount.ONCE),
293+
(2, Q10CleanCount.TWICE),
294+
(3, Q10CleanCount.THREE_TIMES),
295+
(99, Q10CleanCount.UNKNOWN),
296+
],
297+
)
298+
def test_clean_count_mode(q10_api: Q10PropertiesApi, code: int | None, expected: Q10CleanCount | None) -> None:
299+
if code is not None:
300+
q10_api.status.update_from_dps({B01_Q10_DP.CLEAN_COUNT: code})
301+
assert q10_api.status.clean_count_mode is expected

0 commit comments

Comments
 (0)