Skip to content

Commit fd88b3e

Browse files
coma0815claude
andauthored
fix: reassemble V1 map responses split into multiple messages (#1004)
* fix: reassemble V1 map responses split into multiple messages Large maps are delivered over MQTT as several messages sharing the same random/timestamp: all but the last part use protocol 300, the last part uses MAP_RESPONSE (301), and only the first part carries the map header. Parts can arrive out of order. Previously each part was decoded on its own, so decryption of the truncated first part failed, the request timed out and Home Assistant marked the device unavailable. Buffer parts per (random, timestamp), decode once complete, and compare the endpoint as bytes so header-less parts no longer raise UnicodeDecodeError in the response callback. Fixes home-assistant/core#188374 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * style: use a comment instead of a docstring for the pending map limit Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
1 parent 97db9ce commit fd88b3e

3 files changed

Lines changed: 116 additions & 6 deletions

File tree

‎roborock/protocols/v1_protocol.py‎

Lines changed: 52 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -306,16 +306,29 @@ def _decode_blob_response(message: RoborockMessage) -> BlobResponse | None:
306306
return _decode_blob_response
307307

308308

309+
# Number of incomplete multi-part map responses kept while waiting for missing parts.
310+
_MAX_PENDING_MAP_RESPONSES = 4
311+
312+
309313
def create_map_response_decoder(security_data: SecurityData) -> Callable[[RoborockMessage], MapResponse | None]:
310-
"""Create a decoder for V1 map response messages."""
314+
"""Create a decoder for V1 map response messages.
311315
312-
def _decode_map_response(message: RoborockMessage) -> MapResponse | None:
313-
"""Decode a V1 map response message."""
314-
if not message.payload or len(message.payload) < 24:
316+
Large maps are split into multiple messages that share the same ``random``
317+
and ``timestamp`` and are numbered by ``seq``. All parts except the last
318+
one use protocol ``MAP_RESPONSE_PART`` (300), the last one uses
319+
``MAP_RESPONSE`` (301). Only the first part starts with the map header.
320+
Parts may arrive out of order, so they are buffered until complete.
321+
"""
322+
endpoint_bytes = security_data.endpoint.encode()
323+
# (random, timestamp) -> seq -> (is last part, payload)
324+
pending: dict[tuple[int, int], dict[int, tuple[bool, bytes]]] = {}
325+
326+
def _decode_payload(payload: bytes) -> MapResponse | None:
327+
if len(payload) < 24:
315328
raise RoborockException("Invalid V1 map response format: missing payload")
316-
header, body = message.payload[:24], message.payload[24:]
329+
header, body = payload[:24], payload[24:]
317330
[endpoint, _, request_id, _] = struct.unpack("<8s8sH6s", header)
318-
if not endpoint.decode().startswith(security_data.endpoint):
331+
if not endpoint.startswith(endpoint_bytes):
319332
_LOGGER.debug("Received map response not requested by this device, ignoring.")
320333
return None
321334
try:
@@ -325,6 +338,39 @@ def _decode_map_response(message: RoborockMessage) -> MapResponse | None:
325338
decompressed = Utils.decompress(decrypted)
326339
return MapResponse(request_id=request_id, data=decompressed)
327340

341+
def _remember(key: tuple[int, int], parts: dict[int, tuple[bool, bytes]]) -> None:
342+
pending[key] = parts
343+
while len(pending) > _MAX_PENDING_MAP_RESPONSES:
344+
del pending[next(iter(pending))]
345+
346+
def _add_part(key: tuple[int, int], seq: int, is_last: bool, payload: bytes) -> MapResponse | None:
347+
parts = pending.pop(key, {})
348+
parts[seq] = (is_last, payload)
349+
seqs = sorted(parts)
350+
complete = (
351+
parts[seqs[-1]][0]
352+
and seqs == list(range(seqs[0], seqs[-1] + 1))
353+
and parts[seqs[0]][1].startswith(endpoint_bytes)
354+
)
355+
if not complete:
356+
_remember(key, parts)
357+
return None
358+
return _decode_payload(b"".join(parts[s][1] for s in seqs))
359+
360+
def _decode_map_response(message: RoborockMessage) -> MapResponse | None:
361+
"""Decode a V1 map response message."""
362+
if not message.payload:
363+
raise RoborockException("Invalid V1 map response format: missing payload")
364+
payload = message.payload
365+
key = (message.random, message.timestamp)
366+
is_last = message.protocol == RoborockMessageProtocol.MAP_RESPONSE
367+
if message.protocol == RoborockMessageProtocol.MAP_RESPONSE_PART or (is_last and key in pending):
368+
return _add_part(key, message.seq, is_last, payload)
369+
if is_last and not payload.startswith(endpoint_bytes):
370+
# Possibly the last part of a multi-part response that arrived first.
371+
_remember(key, {message.seq: (True, payload)})
372+
return _decode_payload(payload)
373+
328374
return _decode_map_response
329375

330376

‎roborock/roborock_message.py‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,7 @@ class RoborockMessageProtocol(RoborockEnum):
1515
GENERAL_RESPONSE = 5
1616
RPC_REQUEST = 101
1717
RPC_RESPONSE = 102
18+
MAP_RESPONSE_PART = 300 # Non-final part of a map response split into multiple messages
1819
MAP_RESPONSE = 301
1920

2021

‎tests/protocols/test_v1_protocol.py‎

Lines changed: 63 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,10 @@
11
"""Tests for the v1 protocol message encoding and decoding."""
22

3+
import gzip
34
import json
45
import logging
56
import pathlib
7+
import random
68
from collections.abc import Generator
79
from unittest.mock import patch
810

@@ -229,6 +231,67 @@ def test_create_map_response_decoder_invalid_payload():
229231
decoder(message)
230232

231233

234+
def _multipart_map_messages(test_data: bytes, split_at: int) -> tuple[RoborockMessage, RoborockMessage]:
235+
"""Build a map response split into two messages like large maps sent over MQTT."""
236+
header = TEST_ENDPOINT_BYTES + b"\x00" * 8 + b"\xdc\xad" + b"\x00" * 6
237+
payload = header + Utils.encrypt_cbc(gzip.compress(test_data), SECURITY_DATA.nonce)
238+
first = RoborockMessage(
239+
protocol=RoborockMessageProtocol.MAP_RESPONSE_PART,
240+
payload=payload[:split_at],
241+
seq=1,
242+
version=b"1.0",
243+
random=1248,
244+
timestamp=1792857010,
245+
)
246+
last = RoborockMessage(
247+
protocol=RoborockMessageProtocol.MAP_RESPONSE,
248+
payload=payload[split_at:],
249+
seq=2,
250+
version=b"1.0",
251+
random=1248,
252+
timestamp=1792857010,
253+
)
254+
return first, last
255+
256+
257+
@pytest.mark.parametrize("last_first", [False, True], ids=["in_order", "out_of_order"])
258+
def test_create_map_response_decoder_multipart(last_first: bool):
259+
"""Test that a map response split into multiple messages is reassembled."""
260+
test_data = random.Random(0).randbytes(4000) # incompressible, so both parts carry data
261+
first, last = _multipart_map_messages(test_data, split_at=1000)
262+
messages = [last, first] if last_first else [first, last]
263+
264+
decoder = create_map_response_decoder(SECURITY_DATA)
265+
assert decoder(messages[0]) is None
266+
result = decoder(messages[1])
267+
assert result is not None
268+
assert result.request_id == 44508
269+
assert result.data == test_data
270+
271+
272+
def test_create_map_response_decoder_multipart_incomplete():
273+
"""Test that a lone first part of a multi-part map response is buffered, not decoded."""
274+
first, _ = _multipart_map_messages(b"some map\n" * 100, split_at=100)
275+
276+
decoder = create_map_response_decoder(SECURITY_DATA)
277+
assert decoder(first) is None
278+
279+
280+
def test_create_map_response_decoder_non_utf8_header():
281+
"""Test that a map response part without header does not raise on non UTF-8 bytes."""
282+
message = RoborockMessage(
283+
protocol=RoborockMessageProtocol.MAP_RESPONSE,
284+
payload=b'\x9bv9\x15\x8e;"R' + b"\xff" * 40,
285+
seq=2,
286+
version=b"1.0",
287+
random=1248,
288+
timestamp=1792857010,
289+
)
290+
291+
decoder = create_map_response_decoder(SECURITY_DATA)
292+
assert decoder(message) is None
293+
294+
232295
@pytest.mark.parametrize(
233296
("payload", "expected_data", "expected_error"),
234297
[

0 commit comments

Comments
 (0)