Skip to content

Commit afbb1bb

Browse files
committed
feat: add v1 map block container helpers for dynamic map diffs
Add byte-level helpers for the block framing shared by V1 map files and the data values returned by get_dynamic_map_diff / get_dynamic_data: splitting and re-encoding block sequences, the bounded dynamic-value validator, block substitution that preserves parser-relevant ordering, and the block 34 nonce table decoder.
1 parent 5787a6f commit afbb1bb

2 files changed

Lines changed: 401 additions & 0 deletions

File tree

‎roborock/map/dynamic_blocks.py‎

Lines changed: 218 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,218 @@
1+
"""Byte-level container helpers for Roborock V1 map blocks.
2+
3+
A V1 map file and the ``data`` / ``robot_data`` values returned by the dynamic
4+
map diff commands share one block framing. Every block begins with an
5+
eight-byte common header::
6+
7+
offset 0, u16 block type
8+
offset 2, u16 header length H (including these eight bytes)
9+
offset 4, u32 payload length P
10+
offset 8 ..H type-specific header fields
11+
offset H ..H+P payload
12+
13+
The next block starts exactly ``H + P`` bytes after the current one. All
14+
multibyte fields are little-endian and unsigned.
15+
16+
This module only understands that framing. It can split a map file or a
17+
dynamic value into blocks, rebuild a map file from blocks, and decode the
18+
block 34 nonce table that identifies the base map and its dynamic elements.
19+
It deliberately knows nothing about the meaning of any block payload; that
20+
stays with the map parser (full maps) and the dynamic element merge logic.
21+
"""
22+
23+
import struct
24+
from collections.abc import Iterable, Iterator
25+
from dataclasses import dataclass
26+
27+
from roborock.exceptions import RoborockException
28+
29+
# Marker at the start of a full V1 map file.
30+
MAP_FILE_MAGIC = b"rr"
31+
32+
# Size of the block header fields shared by every block type.
33+
COMMON_HEADER_LEN = 8
34+
35+
# A dynamic ``data`` / ``robot_data`` value holds at most this many blocks.
36+
MAX_DYNAMIC_VALUE_BLOCKS = 4
37+
38+
# Block type of the nonce table carried inside a full map.
39+
NONCE_TABLE_BLOCK_TYPE = 34
40+
41+
# Entry identifier inside the nonce table that supplies the map nonce.
42+
MAP_NONCE_ENTRY_ID = 35
43+
44+
# Trailing digest block of a full map. New blocks are inserted before it.
45+
DIGEST_BLOCK_TYPE = 1024
46+
47+
_COMMON_HEADER = struct.Struct("<HHI")
48+
_NONCE_TABLE_NUM = struct.Struct("<I")
49+
_NONCE_ENTRY = struct.Struct("<BI")
50+
_NONCE_TABLE_MIN_HEADER_LEN = COMMON_HEADER_LEN + _NONCE_TABLE_NUM.size
51+
_MAP_FILE_HEADER_LEN = struct.Struct("<H")
52+
53+
54+
@dataclass(frozen=True)
55+
class MapBlock:
56+
"""One framed block: its type, type-specific header fields, and payload.
57+
58+
``extra_header`` holds the bytes between the common eight-byte header and
59+
the payload, so the common header is always regenerated from the lengths
60+
and can never disagree with the data it describes.
61+
"""
62+
63+
block_type: int
64+
payload: bytes
65+
extra_header: bytes = b""
66+
67+
@property
68+
def header_length(self) -> int:
69+
"""Total header length ``H`` written to the common header."""
70+
return COMMON_HEADER_LEN + len(self.extra_header)
71+
72+
def with_payload(self, payload: bytes) -> "MapBlock":
73+
"""Return a copy carrying ``payload`` and the same type and header fields."""
74+
return MapBlock(self.block_type, payload, self.extra_header)
75+
76+
def encode(self) -> bytes:
77+
"""Serialize the block with a regenerated common header."""
78+
common = _COMMON_HEADER.pack(self.block_type, self.header_length, len(self.payload))
79+
return common + self.extra_header + self.payload
80+
81+
82+
def iter_blocks(data: bytes, start: int = 0) -> Iterator[MapBlock]:
83+
"""Yield consecutive blocks from ``data`` beginning at byte ``start``.
84+
85+
The sequence must consume ``data`` exactly. A header shorter than eight
86+
bytes, a header or payload that runs past the end of ``data``, or a block
87+
that does not fit a complete common header is rejected.
88+
"""
89+
position = start
90+
end = len(data)
91+
while position < end:
92+
if end - position < COMMON_HEADER_LEN:
93+
raise RoborockException(f"Map block at offset {position} is shorter than its common header")
94+
block_type, header_length, payload_length = _COMMON_HEADER.unpack_from(data, position)
95+
if header_length < COMMON_HEADER_LEN:
96+
raise RoborockException(f"Map block at offset {position} declares header length {header_length} < 8")
97+
block_end = position + header_length + payload_length
98+
if block_end > end:
99+
raise RoborockException(f"Map block at offset {position} extends past the end of the data")
100+
header_end = position + header_length
101+
yield MapBlock(
102+
block_type=block_type,
103+
payload=data[header_end:block_end],
104+
extra_header=data[position + COMMON_HEADER_LEN : header_end],
105+
)
106+
position = block_end
107+
108+
109+
def parse_dynamic_value(data: bytes) -> list[MapBlock]:
110+
"""Split a decoded dynamic ``data`` / ``robot_data`` value into blocks.
111+
112+
A dynamic value is a bare block sequence: there is no ``rr`` file header
113+
and no digest. An empty value yields no blocks. A value that reaches a
114+
fifth block is rejected, so a non-empty value holds one to four blocks.
115+
"""
116+
blocks: list[MapBlock] = []
117+
for block in iter_blocks(data):
118+
if len(blocks) == MAX_DYNAMIC_VALUE_BLOCKS:
119+
raise RoborockException(f"Dynamic map value holds more than {MAX_DYNAMIC_VALUE_BLOCKS} blocks")
120+
blocks.append(block)
121+
return blocks
122+
123+
124+
def encode_blocks(blocks: Iterable[MapBlock]) -> bytes:
125+
"""Serialize a block sequence without any file header."""
126+
return b"".join(block.encode() for block in blocks)
127+
128+
129+
@dataclass(frozen=True)
130+
class MapFile:
131+
"""A full V1 map file split into its file header and framed blocks."""
132+
133+
header: bytes
134+
"""The ``rr`` file header, kept verbatim so it round-trips unchanged."""
135+
136+
blocks: list[MapBlock]
137+
138+
def encode(self) -> bytes:
139+
"""Serialize the file header followed by every block."""
140+
return self.header + encode_blocks(self.blocks)
141+
142+
143+
def split_map_file(map_bytes: bytes) -> MapFile:
144+
"""Split a decompressed full map into its file header and blocks."""
145+
if not map_bytes.startswith(MAP_FILE_MAGIC):
146+
raise RoborockException("Map file does not start with the 'rr' marker")
147+
if len(map_bytes) < _MAP_FILE_HEADER_LEN.size + 2:
148+
raise RoborockException("Map file is shorter than its header length field")
149+
(header_length,) = _MAP_FILE_HEADER_LEN.unpack_from(map_bytes, 2)
150+
if header_length < 4 or header_length > len(map_bytes):
151+
raise RoborockException(f"Map file declares an invalid header length {header_length}")
152+
return MapFile(header=map_bytes[:header_length], blocks=list(iter_blocks(map_bytes, header_length)))
153+
154+
155+
def find_block(blocks: Iterable[MapBlock], block_type: int) -> MapBlock | None:
156+
"""Return the first block of ``block_type``, or ``None`` when absent."""
157+
for block in blocks:
158+
if block.block_type == block_type:
159+
return block
160+
return None
161+
162+
163+
def replace_block(blocks: list[MapBlock], new_block: MapBlock) -> list[MapBlock]:
164+
"""Return a new block list with ``new_block`` substituted for its type.
165+
166+
The first existing block of the same type is replaced in place, so the
167+
relative order the map parser depends on (for example mop flags after
168+
the path they describe) is preserved. When the type is not present the
169+
block is inserted before the trailing digest, or appended when there is
170+
no digest.
171+
"""
172+
for index, block in enumerate(blocks):
173+
if block.block_type == new_block.block_type:
174+
return [*blocks[:index], new_block, *blocks[index + 1 :]]
175+
for index, block in enumerate(blocks):
176+
if block.block_type == DIGEST_BLOCK_TYPE:
177+
return [*blocks[:index], new_block, *blocks[index:]]
178+
return [*blocks, new_block]
179+
180+
181+
@dataclass(frozen=True)
182+
class NonceTable:
183+
"""Decoded block 34: identities of the base map and its dynamic elements.
184+
185+
Nonces are opaque 32-bit identities. Only equality is meaningful. They are
186+
decoded unsigned so they compare equal to the decimal values the device
187+
reports in JSON responses.
188+
"""
189+
190+
map_nonce: int | None
191+
"""Nonce of the base map (entry 35), or ``None`` when the table lacks it."""
192+
193+
element_nonces: dict[int, int]
194+
"""Element nonce keyed by element id, excluding the map nonce entry."""
195+
196+
197+
def decode_nonce_table(block: MapBlock) -> NonceTable:
198+
"""Decode a block 34 nonce table.
199+
200+
The header carries ``num`` as a u32 at offset 8. The payload holds ``num``
201+
five-byte entries, each a one-byte identifier followed by a u32 nonce.
202+
"""
203+
if block.block_type != NONCE_TABLE_BLOCK_TYPE:
204+
raise RoborockException(f"Block type {block.block_type} is not a nonce table")
205+
if block.header_length < _NONCE_TABLE_MIN_HEADER_LEN:
206+
raise RoborockException("Nonce table header is shorter than 12 bytes")
207+
(num,) = _NONCE_TABLE_NUM.unpack_from(block.extra_header, 0)
208+
if len(block.payload) < num * _NONCE_ENTRY.size:
209+
raise RoborockException(f"Nonce table declares {num} entries but the payload is too short")
210+
map_nonce: int | None = None
211+
element_nonces: dict[int, int] = {}
212+
for index in range(num):
213+
entry_id, nonce = _NONCE_ENTRY.unpack_from(block.payload, index * _NONCE_ENTRY.size)
214+
if entry_id == MAP_NONCE_ENTRY_ID:
215+
map_nonce = nonce
216+
else:
217+
element_nonces[entry_id] = nonce
218+
return NonceTable(map_nonce=map_nonce, element_nonces=element_nonces)

0 commit comments

Comments
 (0)