Skip to content

Commit 99e47d2

Browse files
hCoureauHarry Coureauallenporter
authored
feat: add Q10 map management controls (#934)
Co-authored-by: Harry Coureau <hcoureau@amazon.com> Co-authored-by: Allen Porter <allen.porter@gmail.com>
1 parent 970b041 commit 99e47d2

7 files changed

Lines changed: 606 additions & 12 deletions

File tree

‎roborock/data/b01_q10/b01_q10_code_mappings.py‎

Lines changed: 10 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
from enum import IntEnum
22

3-
from ..code_mappings import RoborockModeEnum
3+
from ..code_mappings import RoborockEnum, RoborockModeEnum
44

55

66
class B01_Q10_DP(RoborockModeEnum):
@@ -354,3 +354,12 @@ class RemoteCommand(IntEnum):
354354
RIGHT = 3
355355
STOP = 4
356356
EXIT = 5
357+
358+
359+
class Q10RestrictionType(RoborockEnum):
360+
"""Restriction types supported by the Q10 map editor."""
361+
362+
unknown = -1
363+
NO_GO = 0
364+
NO_MOP = 2
365+
THRESHOLD = 3

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

Lines changed: 66 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -14,11 +14,12 @@
1414
"""
1515

1616
import logging
17+
from collections.abc import Sequence
1718
from dataclasses import dataclass, field
1819
from typing import Any
1920

2021
from roborock.data import RoborockBase
21-
from roborock.data.b01_q10.b01_q10_code_mappings import B01_Q10_DP, YXDeviceState
22+
from roborock.data.b01_q10.b01_q10_code_mappings import B01_Q10_DP, Q10RestrictionType, YXDeviceState
2223
from roborock.data.b01_q10.b01_q10_containers import Q10RoborockPoint
2324
from roborock.devices.traits.common import DpsDataConverter, TraitUpdateListener
2425
from roborock.exceptions import RoborockException
@@ -29,8 +30,9 @@
2930
Q10Room,
3031
Q10TracePacket,
3132
)
32-
from roborock.map.b01_q10_overlays import parse_virtual_wall_blob, parse_zone_blob
33+
from roborock.map.b01_q10_overlays import Q10RestrictedZone, Q10VirtualWall, parse_virtual_wall_blob, parse_zone_blob
3334
from roborock.map.b01_q10_render import Q10MapOverlays, render_q10_map
35+
from roborock.protocols.b01_q10_protocol import encode_restricted_zones, encode_room_name, encode_virtual_walls
3436

3537
from .command import CommandTrait
3638
from .common import UpdatableTrait
@@ -40,6 +42,10 @@
4042
_DOCKED_STATES = {YXDeviceState.CHARGING, YXDeviceState.EMPTYING_THE_BIN}
4143

4244

45+
def _to_roborock_point(point: tuple[int, int]) -> Q10RoborockPoint:
46+
return Q10RoborockPoint.from_vector(*point)
47+
48+
4349
@dataclass
4450
class MapDps(RoborockBase):
4551
"""Low-level map values delivered in the Q10 DPS stream."""
@@ -131,6 +137,64 @@ def path(self) -> list[Q10Point]:
131137
"""Full path in the Q10 trace coordinate space used by the map renderer."""
132138
return self._trace_packet.points if self._trace_packet else []
133139

140+
@property
141+
def restricted_zones(self) -> tuple[Q10RestrictedZone, ...]:
142+
"""Restrictions reported by the device in common Roborock coordinates."""
143+
restrictions: list[Q10RestrictedZone] = []
144+
for zone in self._map_dps.overlays.zones:
145+
if len(zone.vertices) != 4:
146+
continue
147+
vertices = (
148+
_to_roborock_point(zone.vertices[0]),
149+
_to_roborock_point(zone.vertices[1]),
150+
_to_roborock_point(zone.vertices[2]),
151+
_to_roborock_point(zone.vertices[3]),
152+
)
153+
restriction_type = Q10RestrictionType(zone.type)
154+
restrictions.append(Q10RestrictedZone(restriction_type, vertices))
155+
return tuple(restrictions)
156+
157+
@property
158+
def virtual_walls(self) -> tuple[Q10VirtualWall, ...]:
159+
"""Virtual walls reported by the device in common Roborock coordinates."""
160+
walls: list[Q10VirtualWall] = []
161+
for wall in self._map_dps.overlays.virtual_walls:
162+
if len(wall.vertices) != 2:
163+
continue
164+
walls.append(
165+
Q10VirtualWall(
166+
start=_to_roborock_point(wall.vertices[0]),
167+
end=_to_roborock_point(wall.vertices[1]),
168+
)
169+
)
170+
return tuple(walls)
171+
172+
async def set_restricted_zones(self, zones: Sequence[Q10RestrictedZone]) -> None:
173+
"""Replace the complete restricted-zone collection."""
174+
payload = encode_restricted_zones(zones)
175+
await self._command.send(
176+
B01_Q10_DP.COMMON,
177+
{str(B01_Q10_DP.RESTRICTED_ZONE.code): payload},
178+
)
179+
180+
async def set_virtual_walls(self, walls: Sequence[Q10VirtualWall]) -> None:
181+
"""Replace the complete virtual-wall collection."""
182+
payload = encode_virtual_walls(walls)
183+
await self._command.send(
184+
B01_Q10_DP.COMMON,
185+
{str(B01_Q10_DP.VIRTUAL_WALL.code): payload},
186+
)
187+
188+
async def set_room_name(self, room_id: int, name: str) -> None:
189+
"""Set the name of a room in the current map."""
190+
if room_id not in {room.id for room in self.rooms}:
191+
raise RoborockException(f"Unknown Q10 room ID: {room_id}")
192+
payload = encode_room_name(room_id, name)
193+
await self._command.send(
194+
B01_Q10_DP.COMMON,
195+
{str(B01_Q10_DP.RESET_ROOM_NAME.code): payload},
196+
)
197+
134198
@property
135199
def robot_position(self) -> Q10RoborockPoint | None:
136200
"""Current position in the common Roborock millimetre coordinate space."""

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

Lines changed: 23 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -6,8 +6,9 @@
66

77
from roborock.data import RoborockBase
88
from roborock.data.b01_q10.b01_q10_code_mappings import B01_Q10_DP
9-
from roborock.data.b01_q10.b01_q10_containers import dpMultiMap
9+
from roborock.data.b01_q10.b01_q10_containers import Q10MapInfo, dpMultiMap
1010
from roborock.devices.traits.common import DpsDataConverter
11+
from roborock.exceptions import RoborockException
1112

1213
from .command import CommandTrait
1314
from .common import UpdatableTrait
@@ -28,6 +29,13 @@ def current_map_id(self) -> str | None:
2829
return None
2930
return self.multi_map.current_map_id
3031

32+
@property
33+
def map_list(self) -> list[Q10MapInfo]:
34+
"""Return a copy of the successfully reported saved-map list."""
35+
if self.multi_map is None or self.multi_map.op != "list" or self.multi_map.result != 1:
36+
return []
37+
return list(self.multi_map.data)
38+
3139

3240
class MapsTrait(Maps, UpdatableTrait):
3341
"""Request and store the Q10 saved-map list."""
@@ -48,6 +56,20 @@ async def refresh(self) -> None:
4856
{str(B01_Q10_DP.MULTI_MAP.code): {"op": "list"}},
4957
)
5058

59+
async def set_current_map(self, map_id: str) -> None:
60+
"""Request a saved map without optimistically changing cached state."""
61+
if map_id not in {map_info.id for map_info in self.map_list}:
62+
raise RoborockException(f"Unknown Q10 saved-map ID: {map_id}")
63+
await self._command.send(
64+
B01_Q10_DP.COMMON,
65+
{
66+
str(B01_Q10_DP.MULTI_MAP.code): {
67+
"op": "apply",
68+
"id": map_id,
69+
}
70+
},
71+
)
72+
5173
def update_from_dps(self, decoded_dps: dict[B01_Q10_DP, Any]) -> None:
5274
"""Store a successful saved-map list response."""
5375
response = decoded_dps.get(B01_Q10_DP.MULTI_MAP)

‎roborock/map/b01_q10_overlays.py‎

Lines changed: 25 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -31,6 +31,10 @@
3131
import binascii
3232
from dataclasses import dataclass, field
3333

34+
from roborock.data import RoborockBase
35+
from roborock.data.b01_q10.b01_q10_code_mappings import Q10RestrictionType
36+
from roborock.data.b01_q10.b01_q10_containers import Q10RoborockPoint
37+
3438
_DEFAULT_RECORD_SIZE = 38 # 2-byte record header + up to 9 (x, y) int16 pairs
3539

3640

@@ -42,6 +46,22 @@ class Q10Zone:
4246
vertices: list[tuple[int, int]] = field(default_factory=list)
4347

4448

49+
@dataclass
50+
class Q10RestrictedZone(RoborockBase):
51+
"""A four-point restriction in common Roborock coordinates."""
52+
53+
type: Q10RestrictionType
54+
vertices: tuple[Q10RoborockPoint, Q10RoborockPoint, Q10RoborockPoint, Q10RoborockPoint]
55+
56+
57+
@dataclass
58+
class Q10VirtualWall(RoborockBase):
59+
"""A virtual wall in common Roborock coordinates."""
60+
61+
start: Q10RoborockPoint
62+
end: Q10RoborockPoint
63+
64+
4565
def _decode_blob(data: str | None) -> bytes:
4666
if data is None:
4767
return b""
@@ -55,8 +75,8 @@ def parse_zone_blob(data: str | None) -> list[Q10Zone]:
5575
"""Decode a Q10 zone/wall overlay blob into a list of :class:`Q10Zone`.
5676
5777
Accepts the base64 string straight from the data point. Returns ``[]`` for
58-
empty/absent/unparsable blobs (the device sends a single ``0x00`` byte when
59-
there are none).
78+
empty/absent/unparsable blobs. Empty DP 55 reports contain version ``1``
79+
and count ``0``; some firmware appends one padding byte.
6080
"""
6181
raw = _decode_blob(data)
6282
if len(raw) < 2:
@@ -156,7 +176,7 @@ def parse_virtual_wall_blob(data: str | None) -> list[Q10Zone]:
156176
# Corrected from an earlier reading that treated type 3 as no-mop -- 3 is the
157177
# door-threshold rectangle; the no-mop area reads back as type 2. Reported and
158178
# verified by @andrewlyeats (ss07 read-backs + the ioBroker Q10 parser).
159-
ZONE_TYPE_NO_GO = 0
179+
ZONE_TYPE_NO_GO = Q10RestrictionType.NO_GO.value
160180
ZONE_TYPE_VIRTUAL_WALL = 1
161-
ZONE_TYPE_NO_MOP = 2
162-
ZONE_TYPE_THRESHOLD = 3
181+
ZONE_TYPE_NO_MOP = Q10RestrictionType.NO_MOP.value
182+
ZONE_TYPE_THRESHOLD = Q10RestrictionType.THRESHOLD.value

‎roborock/protocols/b01_q10_protocol.py‎

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

3+
import base64
34
import json
45
import logging
6+
import struct
57
from base64 import b64encode
8+
from collections.abc import Sequence
69
from dataclasses import dataclass
710
from struct import pack
811
from typing import Any
912

10-
from roborock.data.b01_q10.b01_q10_code_mappings import B01_Q10_DP
13+
from roborock.data.b01_q10.b01_q10_code_mappings import B01_Q10_DP, Q10RestrictionType
1114
from roborock.data.b01_q10.b01_q10_containers import Q10RoborockPoint
1215
from roborock.exceptions import RoborockException
1316
from roborock.map.b01_q10_map_parser import (
@@ -19,6 +22,7 @@
1922
parse_map_packet,
2023
parse_trace_packet,
2124
)
25+
from roborock.map.b01_q10_overlays import Q10RestrictedZone, Q10VirtualWall
2226
from roborock.roborock_message import (
2327
RoborockMessage,
2428
RoborockMessageProtocol,
@@ -75,6 +79,118 @@ def encode_clean_params(params: CleanParams) -> str:
7579
return b64encode(payload).decode()
7680

7781

82+
_Q10_ZONE_RECORD_SIZE = 38
83+
_Q10_ROOM_NAME_FIELD_SIZE = 19
84+
85+
86+
def _orientation(a: tuple[int, int], b: tuple[int, int], c: tuple[int, int]) -> int:
87+
return (b[0] - a[0]) * (c[1] - a[1]) - (b[1] - a[1]) * (c[0] - a[0])
88+
89+
90+
def _on_segment(a: tuple[int, int], b: tuple[int, int], point: tuple[int, int]) -> bool:
91+
return min(a[0], b[0]) <= point[0] <= max(a[0], b[0]) and min(a[1], b[1]) <= point[1] <= max(a[1], b[1])
92+
93+
94+
def _segments_cross(a: tuple[int, int], b: tuple[int, int], c: tuple[int, int], d: tuple[int, int]) -> bool:
95+
orientations = (
96+
_orientation(a, b, c),
97+
_orientation(a, b, d),
98+
_orientation(c, d, a),
99+
_orientation(c, d, b),
100+
)
101+
if orientations[0] * orientations[1] < 0 and orientations[2] * orientations[3] < 0:
102+
return True
103+
return any(
104+
orientation == 0 and _on_segment(start, end, point)
105+
for orientation, start, end, point in (
106+
(orientations[0], a, b, c),
107+
(orientations[1], a, b, d),
108+
(orientations[2], c, d, a),
109+
(orientations[3], c, d, b),
110+
)
111+
)
112+
113+
114+
def _validate_quadrilateral(vertices: list[tuple[int, int]]) -> None:
115+
area_twice = sum(
116+
x1 * y2 - x2 * y1 for (x1, y1), (x2, y2) in zip(vertices, (*vertices[1:], vertices[0]), strict=True)
117+
)
118+
if area_twice == 0:
119+
raise ValueError("restricted-zone vertices must enclose an area")
120+
if _segments_cross(vertices[0], vertices[1], vertices[2], vertices[3]) or _segments_cross(
121+
vertices[1], vertices[2], vertices[3], vertices[0]
122+
):
123+
raise ValueError("restricted-zone edges must not cross")
124+
125+
126+
def encode_restricted_zones(zones: Sequence[Q10RestrictedZone]) -> str:
127+
"""Encode the complete Q10 restricted-zone collection."""
128+
if len(zones) > 255:
129+
raise ValueError("zones must be a sequence of at most 255 restrictions")
130+
if not zones:
131+
return base64.b64encode(b"\x01\x00").decode()
132+
133+
payload = bytearray((1, len(zones)))
134+
for zone in zones:
135+
if zone.type is Q10RestrictionType.unknown:
136+
raise ValueError("unknown restricted-zone types cannot be written")
137+
if len(zone.vertices) != 4:
138+
raise ValueError("restricted zones must contain exactly four vertices")
139+
if len(set(zone.vertices)) != 4:
140+
raise ValueError("restricted-zone vertices must be distinct")
141+
record = bytearray((zone.type, len(zone.vertices)))
142+
vector_vertices = [point.to_vector() for point in zone.vertices]
143+
_validate_quadrilateral(vector_vertices)
144+
for x, y in vector_vertices:
145+
record.extend(
146+
struct.pack(
147+
">hh",
148+
x,
149+
y,
150+
)
151+
)
152+
record.extend(bytes(_Q10_ZONE_RECORD_SIZE - len(record)))
153+
payload.extend(record)
154+
return base64.b64encode(payload).decode()
155+
156+
157+
def encode_virtual_walls(walls: Sequence[Q10VirtualWall]) -> str:
158+
"""Encode the complete Q10 virtual-wall collection."""
159+
if len(walls) > 255:
160+
raise ValueError("walls must be a sequence of at most 255 virtual walls")
161+
162+
payload = bytearray((len(walls),))
163+
for wall in walls:
164+
if wall.start == wall.end:
165+
raise ValueError("virtual-wall endpoints must be distinct")
166+
for point in (wall.start, wall.end):
167+
x, y = point.to_vector()
168+
payload.extend(
169+
struct.pack(
170+
">hh",
171+
x,
172+
y,
173+
)
174+
)
175+
return base64.b64encode(payload).decode()
176+
177+
178+
def encode_room_name(room_id: int, name: str) -> str:
179+
"""Encode a Q10 room-name update."""
180+
if not 0 <= room_id <= 255:
181+
raise ValueError("room_id must be an integer between 0 and 255")
182+
if not name or "\x00" in name:
183+
raise ValueError("name must be a non-empty string without null bytes")
184+
encoded_name = name.encode("utf-8")
185+
if len(encoded_name) > _Q10_ROOM_NAME_FIELD_SIZE:
186+
raise ValueError("name must be at most 19 UTF-8 bytes")
187+
188+
payload = bytearray((1, room_id, 0, len(encoded_name)))
189+
payload.extend(encoded_name)
190+
payload.extend(bytes(_Q10_ROOM_NAME_FIELD_SIZE - len(encoded_name)))
191+
return base64.b64encode(payload).decode()
192+
193+
78194
def encode_mqtt_payload(command: B01_Q10_DP, params: ParamsType) -> RoborockMessage:
79195
"""Encode payload for B01 Q10 commands over MQTT.
80196

0 commit comments

Comments
 (0)