Skip to content

Commit 252ec92

Browse files
hCoureauHarry Coureauallenporter
authored
feat: expose Q10 map archives (#937)
* feat: expose Q10 map archives * fix: keep Q10 archive traits lightweight --------- Co-authored-by: Harry Coureau <hcoureau@amazon.com> Co-authored-by: Allen Porter <allen.porter@gmail.com>
1 parent ab1736b commit 252ec92

8 files changed

Lines changed: 479 additions & 65 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
@@ -144,7 +144,9 @@ class Q10MapInfo(RoborockBase):
144144
"""A saved map reported by ``dpMultiMap``.
145145
146146
Q10 firmware represents the map identifier as a string on the wire. The
147-
value is sent back unchanged in a subsequent ``{"op": "get"}`` request.
147+
value is sent back unchanged in a subsequent ``{"op": "select"}`` detail
148+
request. On Q10 firmware, ``select`` previews a saved map without applying
149+
it as the active map.
148150
"""
149151

150152
id: str

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

Lines changed: 34 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,13 @@
88
from roborock.data.containers import RoborockBase
99
from roborock.devices.rpc.b01_q10_channel import B01Q10Channel
1010
from roborock.devices.traits import Trait
11-
from roborock.map.b01_q10_map_parser import B01Q10MapParserConfig, Q10MapPacket, Q10TracePacket
11+
from roborock.map.b01_q10_map_parser import (
12+
B01Q10MapParserConfig,
13+
Q10CleanRecordDetail,
14+
Q10MapPacket,
15+
Q10MapPacketKind,
16+
Q10TracePacket,
17+
)
1218
from roborock.protocols.b01_q10_protocol import Q10DpsUpdate, Q10Message
1319

1420
from .button_light import ButtonLightTrait
@@ -92,7 +98,12 @@ class Q10PropertiesApi(Trait):
9298
clean_history: CleanHistoryTrait
9399
"""Trait for fetching the device clean-record history (``dpCleanRecord``)."""
94100

95-
def __init__(self, channel: B01Q10Channel, *, map_parser_config: B01Q10MapParserConfig | None = None) -> None:
101+
def __init__(
102+
self,
103+
channel: B01Q10Channel,
104+
*,
105+
map_parser_config: B01Q10MapParserConfig | None = None,
106+
) -> None:
96107
"""Initialize the B01Props API."""
97108
self._channel = channel
98109
self.command = CommandTrait(channel)
@@ -107,9 +118,13 @@ def __init__(self, channel: B01Q10Channel, *, map_parser_config: B01Q10MapParser
107118
self.consumable = ConsumableTrait()
108119
self._map_dps = MapDpsTrait()
109120
self.maps = MapsTrait(self.command)
110-
self.map = MapContentTrait(self._map_dps, self.maps, self.command, map_parser_config=map_parser_config)
111-
self.vacuum = VacuumTrait(self.command, self.status, self.map)
121+
self.map = MapContentTrait(
122+
self._map_dps,
123+
self.command,
124+
map_parser_config=map_parser_config,
125+
)
112126
self.clean_history = CleanHistoryTrait(self.command)
127+
self.vacuum = VacuumTrait(self.command, self.status, self.map)
113128
# Read-model traits updated from the device's DPS push stream.
114129
self._updatable_traits = [
115130
self.status,
@@ -158,7 +173,12 @@ def _handle_message(self, message: Q10Message) -> None:
158173
Map-list DPS responses and other DPS updates feed the read-model traits.
159174
"""
160175
if isinstance(message, Q10MapPacket):
161-
self.map.update_from_map_packet(message)
176+
if message.kind is Q10MapPacketKind.CURRENT:
177+
self.map.update_from_map_packet(message)
178+
elif message.kind is Q10MapPacketKind.SAVED_MAP_DETAIL:
179+
self.maps.update_from_map_packet(message)
180+
elif isinstance(message, Q10CleanRecordDetail):
181+
self.clean_history.update_from_detail(message)
162182
elif isinstance(message, Q10TracePacket):
163183
self.map.update_from_trace_packet(message)
164184
elif isinstance(message, Q10DpsUpdate):
@@ -179,6 +199,13 @@ def as_dict(self) -> dict[str, Any]:
179199
return result
180200

181201

182-
def create(channel: B01Q10Channel, *, map_parser_config: B01Q10MapParserConfig | None = None) -> Q10PropertiesApi:
202+
def create(
203+
channel: B01Q10Channel,
204+
*,
205+
map_parser_config: B01Q10MapParserConfig | None = None,
206+
) -> Q10PropertiesApi:
183207
"""Create traits for B01 devices."""
184-
return Q10PropertiesApi(channel, map_parser_config=map_parser_config)
208+
return Q10PropertiesApi(
209+
channel,
210+
map_parser_config=map_parser_config,
211+
)

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

Lines changed: 71 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,7 @@
1414
from dataclasses import dataclass, field
1515
from typing import Any
1616

17+
from roborock.data import RoborockBase
1718
from roborock.data.b01_q10.b01_q10_code_mappings import (
1819
B01_Q10_DP,
1920
YXCleaningResult,
@@ -22,11 +23,20 @@
2223
YXStartMethod,
2324
)
2425
from roborock.data.b01_q10.b01_q10_containers import Q10CleanRecord
26+
from roborock.exceptions import RoborockException
27+
from roborock.map.b01_q10_map_parser import (
28+
Q10CleanRecordDetail,
29+
Q10HistoricalTracePacket,
30+
Q10MapPacket,
31+
Q10MapPacketKind,
32+
Q10Point,
33+
)
2534

2635
from .command import CommandTrait
2736
from .common import UpdatableTrait
2837

2938
__all__ = [
39+
"CleanHistory",
3040
"CleanHistoryTrait",
3141
"CleanRecordConverter",
3242
"CleanRecordPush",
@@ -107,40 +117,78 @@ def parse_record(raw: Any | None) -> Q10CleanRecord | None:
107117
return None
108118

109119

110-
class CleanHistoryTrait(UpdatableTrait):
111-
"""Access to the Q10 clean-record history (``dpCleanRecord``, DP 52).
112-
113-
A read-model trait updated from the DPS stream like the others, but it overrides
114-
:meth:`update_from_dps` because the payload is a structured push (a record list,
115-
or a single ``op:"notify"`` record) rather than a flat data-point-to-field map.
116-
"""
120+
@dataclass
121+
class CleanHistory(RoborockBase):
122+
"""Received clean-history data, independent of request and transport state."""
117123

118-
def __init__(self, command: CommandTrait) -> None:
119-
"""Initialize the clean history trait."""
120-
UpdatableTrait.__init__(self, command, _LOGGER)
121-
self._converter = CleanRecordConverter()
122-
self.records: list[Q10CleanRecord] = []
123-
"""Decoded clean records, most recent first."""
124+
records: list[Q10CleanRecord] = field(default_factory=list)
125+
"""Decoded clean records, most recent first."""
126+
detail: Q10CleanRecordDetail | None = None
127+
"""Latest received archive. Its wire payload contains no record identifier."""
128+
detail_path: list[Q10Point] = field(default_factory=list)
129+
"""Historical path points from the latest received archive, included in diagnostics."""
124130

125131
@property
126132
def last_record(self) -> Q10CleanRecord | None:
127133
"""The most recent clean record, or ``None`` if there are none."""
128134
return self.records[0] if self.records else None
129135

136+
@property
137+
def detail_packet(self) -> Q10MapPacket | None:
138+
"""The map from the most recently received clean-record detail."""
139+
return self.detail.map if self.detail else None
140+
141+
@property
142+
def detail_trace(self) -> Q10HistoricalTracePacket | None:
143+
"""Historical path embedded in the latest received clean-record detail."""
144+
return self.detail.trace if self.detail else None
145+
146+
def as_dict(self, exclude: set[str] | None = None) -> dict[str, Any]:
147+
"""Serialize history metadata and path without binary map packets and grids."""
148+
return super().as_dict(exclude=(exclude or set()) | {"detail"})
149+
150+
151+
class CleanHistoryTrait(CleanHistory, UpdatableTrait):
152+
"""Browse past cleaning runs and retrieve their parsed maps and historical paths.
153+
154+
Subscribe with ``add_update_listener`` to receive requested or unsolicited
155+
archives. Archive pushes contain no record ID, so the latest detail cannot
156+
be attributed to a particular selection.
157+
"""
158+
159+
_command: CommandTrait
160+
161+
def __init__(self, command: CommandTrait) -> None:
162+
CleanHistory.__init__(self)
163+
UpdatableTrait.__init__(self, command, _LOGGER)
164+
self._command = command
165+
self._converter = CleanRecordConverter()
166+
130167
async def refresh(self) -> None:
131168
"""Request the clean-record list from the device.
132169
133170
This sends the query and returns immediately; the records arrive
134171
asynchronously on the device stream and populate :attr:`records` once
135172
:meth:`update_from_dps` processes the ``dpCleanRecord`` push.
136173
"""
137-
if self._command is None:
138-
raise ValueError("Trait is read-only; no command channel was provided")
139174
await self._command.send(
140175
B01_Q10_DP.COMMON,
141176
params={str(B01_Q10_DP.CLEAN_RECORD.code): {"op": "list"}},
142177
)
143178

179+
async def refresh_detail(self, record: Q10CleanRecord) -> None:
180+
"""Request the saved map and path for a past cleaning run.
181+
182+
Returns after sending; listeners receive the archive separately. The
183+
push contains no record ID to correlate it with this selection.
184+
"""
185+
if not record.raw or not record.map_len:
186+
raise RoborockException("The Q10 clean record has no saved map detail")
187+
await self._command.send(
188+
B01_Q10_DP.COMMON,
189+
{str(B01_Q10_DP.CLEAN_RECORD.code): {"op": "select", "id": record.raw}},
190+
)
191+
144192
def update_from_dps(self, decoded_dps: dict[B01_Q10_DP, Any]) -> None:
145193
"""Apply a ``dpCleanRecord`` push (a full list reply or a single notify)."""
146194
envelope = decoded_dps.get(B01_Q10_DP.CLEAN_RECORD)
@@ -151,6 +199,14 @@ def update_from_dps(self, decoded_dps: dict[B01_Q10_DP, Any]) -> None:
151199
return
152200
self._apply(push)
153201

202+
def update_from_detail(self, detail: Q10CleanRecordDetail) -> None:
203+
"""Store a pushed clean-record map and path and notify listeners."""
204+
if detail.map.kind is not Q10MapPacketKind.CLEAN_RECORD_DETAIL:
205+
raise ValueError(f"Expected a Q10 clean-record detail packet, got {detail.map.kind.value}")
206+
self.detail = detail
207+
self.detail_path = list(detail.trace.points) if detail.trace else []
208+
self._notify_update()
209+
154210
def _apply(self, push: CleanRecordPush) -> None:
155211
"""Merge or replace the records from ``push``, then sort newest-first and notify."""
156212
if push.replace:

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

Lines changed: 5 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -26,6 +26,7 @@
2626
from roborock.map.b01_q10_map_parser import (
2727
B01Q10MapParserConfig,
2828
Q10MapPacket,
29+
Q10MapPacketKind,
2930
Q10Point,
3031
Q10Room,
3132
Q10TracePacket,
@@ -36,7 +37,6 @@
3637

3738
from .command import CommandTrait
3839
from .common import UpdatableTrait
39-
from .maps import MapsTrait
4040

4141
_LOGGER = logging.getLogger(__name__)
4242
_DOCKED_STATES = {YXDeviceState.CHARGING, YXDeviceState.EMPTYING_THE_BIN}
@@ -90,23 +90,20 @@ class MapContentTrait(TraitUpdateListener):
9090
"""High-level composed Q10 map view.
9191
9292
The latest map and trace packets are combined with the injected
93-
:class:`MapDpsTrait` whenever a source changes. The
94-
:class:`MapsTrait` supplies a stored ID only when this trait requests
95-
content.
93+
:class:`MapDpsTrait` whenever a source changes. Current-map acquisition is
94+
independent of the saved-map list.
9695
"""
9796

9897
def __init__(
9998
self,
10099
map_dps: MapDpsTrait,
101-
maps: MapsTrait,
102100
command: CommandTrait,
103101
*,
104102
map_parser_config: B01Q10MapParserConfig | None = None,
105103
) -> None:
106104
TraitUpdateListener.__init__(self, logger=_LOGGER)
107105
self._config = map_parser_config or B01Q10MapParserConfig()
108106
self._map_dps = map_dps
109-
self._maps = maps
110107
self._command = command
111108
self._map_packet: Q10MapPacket | None = None
112109
self._trace_packet: Q10TracePacket | None = None
@@ -214,6 +211,8 @@ def robot_heading(self) -> int | None:
214211

215212
def update_from_map_packet(self, packet: Q10MapPacket) -> None:
216213
"""Store a map-protocol update and render the latest sources."""
214+
if packet.kind is not Q10MapPacketKind.CURRENT:
215+
raise ValueError(f"Expected a current Q10 map packet, got {packet.kind.value}")
217216
self._map_packet = packet
218217
self._render()
219218
self._notify_update()

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

Lines changed: 41 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@
99
from roborock.data.b01_q10.b01_q10_containers import Q10MapInfo, dpMultiMap
1010
from roborock.devices.traits.common import DpsDataConverter
1111
from roborock.exceptions import RoborockException
12+
from roborock.map.b01_q10_map_parser import Q10MapPacket, Q10MapPacketKind
1213

1314
from .command import CommandTrait
1415
from .common import UpdatableTrait
@@ -22,6 +23,15 @@ class Maps(RoborockBase):
2223

2324
multi_map: dpMultiMap | None = field(default=None, metadata={"dps": B01_Q10_DP.MULTI_MAP})
2425

26+
detail_packet: Q10MapPacket | None = None
27+
"""Most recently received saved-map preview."""
28+
detail_map_id: str | None = None
29+
"""Map ID supplied by the preview packet itself."""
30+
31+
def as_dict(self, exclude: set[str] | None = None) -> dict[str, Any]:
32+
"""Serialize metadata without binary map packets and grids."""
33+
return super().as_dict(exclude=(exclude or set()) | {"detail_packet"})
34+
2535
@property
2636
def current_map_id(self) -> str | None:
2737
"""Return the first saved-map ID for a content request, if available."""
@@ -38,7 +48,11 @@ def map_list(self) -> list[Q10MapInfo]:
3848

3949

4050
class MapsTrait(Maps, UpdatableTrait):
41-
"""Request and store the Q10 saved-map list."""
51+
"""Browse saved maps and retrieve their parsed previews independently of the live map.
52+
53+
Preview pushes identify their map, but carry no request correlation ID.
54+
Consumers receive them through ``add_update_listener``.
55+
"""
4256

4357
_CONVERTER = DpsDataConverter.from_dataclass(Maps)
4458
_command: CommandTrait
@@ -70,6 +84,24 @@ async def set_current_map(self, map_id: str) -> None:
7084
},
7185
)
7286

87+
async def refresh_detail(self, map_id: str | None = None) -> None:
88+
"""Request a read-only preview for one saved map.
89+
90+
Returns after publishing. Subscribe with ``add_update_listener`` to
91+
receive previews separately from the live map. ``detail_map_id`` is
92+
read from each pushed packet; it is not a request correlation ID.
93+
"""
94+
if map_id is None:
95+
map_id = self.current_map_id
96+
if map_id is None:
97+
raise RoborockException("Cannot request Q10 saved-map detail before the map list is available")
98+
if map_id not in {map_info.id for map_info in self.map_list}:
99+
raise RoborockException(f"Unknown Q10 saved-map ID: {map_id}")
100+
await self._command.send(
101+
B01_Q10_DP.COMMON,
102+
{str(B01_Q10_DP.MULTI_MAP.code): {"op": "select", "id": map_id}},
103+
)
104+
73105
def update_from_dps(self, decoded_dps: dict[B01_Q10_DP, Any]) -> None:
74106
"""Store a successful saved-map list response."""
75107
response = decoded_dps.get(B01_Q10_DP.MULTI_MAP)
@@ -78,3 +110,11 @@ def update_from_dps(self, decoded_dps: dict[B01_Q10_DP, Any]) -> None:
78110
if not isinstance(response, dict) or response.get("op") != "list" or response.get("result") != 1:
79111
return
80112
super().update_from_dps(decoded_dps)
113+
114+
def update_from_map_packet(self, packet: Q10MapPacket) -> None:
115+
"""Store a pushed saved-map detail packet and notify listeners."""
116+
if packet.kind is not Q10MapPacketKind.SAVED_MAP_DETAIL:
117+
raise ValueError(f"Expected a Q10 saved-map detail packet, got {packet.kind.value}")
118+
self.detail_map_id = str(packet.map_id)
119+
self.detail_packet = packet
120+
self._notify_update()

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

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,12 @@
44
'child_lock': dict({
55
'childLock': False,
66
}),
7+
'clean_history': dict({
8+
'detailPath': list([
9+
]),
10+
'records': list([
11+
]),
12+
}),
713
'consumable': dict({
814
'filterLife': 0,
915
'mainBrushLife': 0,
@@ -384,6 +390,12 @@
384390
'child_lock': dict({
385391
'childLock': False,
386392
}),
393+
'clean_history': dict({
394+
'detailPath': list([
395+
]),
396+
'records': list([
397+
]),
398+
}),
387399
'consumable': dict({
388400
'filterLife': 0,
389401
'mainBrushLife': 0,
@@ -473,6 +485,12 @@
473485
dict({
474486
'child_lock': dict({
475487
}),
488+
'clean_history': dict({
489+
'detailPath': list([
490+
]),
491+
'records': list([
492+
]),
493+
}),
476494
'consumable': dict({
477495
}),
478496
'do_not_disturb': dict({

0 commit comments

Comments
 (0)