Skip to content

Commit cab602e

Browse files
committed
fix(testing): generate valid V1 maps and honor custom handlers
1 parent cab1296 commit cab602e

2 files changed

Lines changed: 104 additions & 18 deletions

File tree

‎roborock/testing/v1_simulator.py‎

Lines changed: 27 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@
55
"""
66

77
import gzip
8+
import hashlib
89
import json
910
import logging
1011
import struct
@@ -171,10 +172,12 @@ def _serialize_dataclass(obj: Any) -> dict[str, Any]:
171172
# Eight character endpoint, matching the width of the map response header field.
172173
MAP_ENDPOINT = "fakeendp"
173174

174-
# Side length in cells of the simulated map image.
175+
# Minimum side length in cells of the simulated map image.
175176
MAP_IMAGE_SIZE = 32
176177

177178
_MAP_FILE_HEADER_LEN = 20
179+
_MAP_CELL_SIZE_MM = 50
180+
_MAP_IMAGE_PADDING = 2
178181
_IMAGE_BLOCK_TYPE = 2
179182
_PATH_BLOCK_TYPE = 3
180183
_POSE_BLOCK_TYPE = 8
@@ -247,6 +250,7 @@ def __init__(
247250
"reset_consumable": self._handle_reset_consumable,
248251
"app_get_init_status": self._handle_app_get_init_status,
249252
"get_network_info": self._handle_get_network_info,
253+
"get_map_v1": lambda params: self.build_map_bytes(),
250254
}
251255

252256
# The simulated robot's own view of its map. Tests extend the path
@@ -393,23 +397,28 @@ def _path_blocks(self, start: int, count: int) -> bytes:
393397

394398
def build_map_bytes(self) -> bytes:
395399
"""Build a decompressed map file reflecting the current robot state."""
400+
# Full-map image offsets are cells; path and robot coordinates are millimetres.
401+
points = [self.robot_position[:2], *struct.iter_unpack("<HH", self.path_payload(0, self.path_length))]
402+
xs = [x // _MAP_CELL_SIZE_MM for x, _ in points]
403+
ys = [y // _MAP_CELL_SIZE_MM for _, y in points]
404+
left = max(0, min(xs) - _MAP_IMAGE_PADDING)
405+
top = max(0, min(ys) - _MAP_IMAGE_PADDING)
406+
width = max(MAP_IMAGE_SIZE, max(xs) - left + _MAP_IMAGE_PADDING + 1)
407+
height = max(MAP_IMAGE_SIZE, max(ys) - top + _MAP_IMAGE_PADDING + 1)
396408
image = _block(
397409
_IMAGE_BLOCK_TYPE,
398-
bytes([_MAP_INSIDE]) * (MAP_IMAGE_SIZE * MAP_IMAGE_SIZE),
399-
struct.pack("<IIII", 0, 0, MAP_IMAGE_SIZE, MAP_IMAGE_SIZE),
400-
)
401-
header = b"rr" + struct.pack("<H", _MAP_FILE_HEADER_LEN) + bytes(_MAP_FILE_HEADER_LEN - 4)
402-
return (
403-
header
404-
+ image
405-
+ self._path_blocks(0, self.path_length)
406-
+ self._pose_block()
407-
+ _block(_DIGEST_BLOCK_TYPE, bytes(20))
410+
bytes([_MAP_INSIDE]) * (width * height),
411+
struct.pack("<Iiiii", 0, top, left, height, width),
408412
)
413+
body = image + self._path_blocks(0, self.path_length) + self._pose_block()
414+
digest_header = struct.pack("<HHI", _DIGEST_BLOCK_TYPE, 8, 20)
415+
header = struct.pack("<2sHIHHII", b"rr", _MAP_FILE_HEADER_LEN, len(body) + len(digest_header) + 20, 1, 0, 0, 0)
416+
data = header + body + digest_header
417+
return data + hashlib.sha1(data, usedforsecurity=False).digest()
409418

410-
def _map_response_message(self, request_id: int) -> RoborockMessage:
419+
def _map_response_message(self, request_id: int, map_bytes: bytes) -> RoborockMessage:
411420
"""Frame the map as the encrypted binary response the device sends."""
412-
body = Utils.encrypt_cbc(gzip.compress(self.build_map_bytes()), self.security_data.nonce)
421+
body = Utils.encrypt_cbc(gzip.compress(map_bytes), self.security_data.nonce)
413422
header = struct.pack("<8s8sH6s", self.security_data.endpoint.encode(), bytes(8), request_id & 0xFFFF, bytes(6))
414423
return RoborockMessage(protocol=RoborockMessageProtocol.MAP_RESPONSE, payload=header + body)
415424

@@ -430,11 +439,6 @@ async def _handle_publish(self, message: RoborockMessage, channel: FakeChannel)
430439
_LOGGER.debug("Failed to parse plaintext JSON RPC payload: %s", e, exc_info=True)
431440
return
432441

433-
if method == "get_map_v1":
434-
# The map arrives as an encrypted binary frame rather than a JSON result.
435-
channel.notify_subscribers(self._map_response_message(msg_id))
436-
return
437-
438442
result = None
439443
error = None
440444

@@ -449,6 +453,11 @@ async def _handle_publish(self, message: RoborockMessage, channel: FakeChannel)
449453
else:
450454
result = "ok"
451455

456+
if method == "get_map_v1" and error is None and isinstance(result, bytes):
457+
# Custom handlers return decompressed map bytes, just like the default.
458+
channel.notify_subscribers(self._map_response_message(msg_id, result))
459+
return
460+
452461
response_data = {
453462
"dps": {"102": json.dumps({"id": msg_id, "result": result, "error": error})},
454463
"t": int(time.time()),

‎tests/testing/test_v1_simulator.py‎

Lines changed: 77 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,9 @@
1+
import hashlib
2+
import struct
13
from dataclasses import replace
24

35
import pytest
6+
from vacuum_map_parser_base.config.drawable import Drawable
47

58
from roborock.data import UserData
69
from roborock.data.v1 import RoborockStateCode
@@ -9,6 +12,7 @@
912
from roborock.devices.device_manager import UserParams, create_device_manager
1013
from roborock.devices.traits.v1.consumeable import ConsumableAttribute
1114
from roborock.exceptions import RoborockException
15+
from roborock.map.map_parser import MapParser, MapParserConfig
1216
from roborock.testing import (
1317
DEFAULT_NETWORK_INFO,
1418
DEFAULT_STATUS,
@@ -302,3 +306,76 @@ async def test_full_map_refresh_from_simulator():
302306
assert len(_path_points(device)) == 40
303307
assert map_content.map_data is not None and map_content.map_data.vacuum_position is not None
304308
assert (map_content.map_data.vacuum_position.x, map_content.map_data.vacuum_position.y) == (31000, 32000)
309+
310+
311+
@pytest.mark.parametrize("count", [0, 40, 400])
312+
def test_simulated_map_length_and_digest(count: int) -> None:
313+
"""Synthetic maps satisfy the app's full-file length and SHA-1 checks."""
314+
simulator = V1VacuumSimulator()
315+
simulator.advance_path(count)
316+
raw = simulator.build_map_bytes()
317+
magic, header_length, payload_length, major, minor = struct.unpack_from("<2sHIHH", raw)
318+
assert magic == b"rr"
319+
assert (major, minor) == (1, 0)
320+
assert header_length + payload_length == len(raw)
321+
assert struct.unpack_from("<HHI", raw, len(raw) - 28) == (1024, 8, 20)
322+
assert raw[-20:] == hashlib.sha1(raw[:-20], usedforsecurity=False).digest()
323+
324+
325+
@pytest.mark.parametrize("position", [(25000, 24000, 90), (31000, 32000, 180), (0, 0, 0)])
326+
@pytest.mark.parametrize("count", [0, 40, 400])
327+
def test_simulated_map_contains_robot_and_path(position: tuple[int, int, int], count: int) -> None:
328+
"""Map geometry keeps all simulated overlays inside the rendered image."""
329+
simulator = V1VacuumSimulator()
330+
simulator.robot_position = position
331+
simulator.advance_path(count)
332+
parsed = MapParser(MapParserConfig()).parse(simulator.build_map_bytes())
333+
assert parsed is not None and parsed.map_data is not None
334+
data = parsed.map_data
335+
assert data.image is not None and data.vacuum_position is not None and data.path is not None
336+
width, height = data.image.data.size
337+
for point in [data.vacuum_position, *data.path.path[0]]:
338+
pixel = point.to_img(data.image.dimensions)
339+
assert 0 <= pixel.x < width
340+
assert 0 <= pixel.y < height
341+
342+
343+
@pytest.mark.parametrize("drawable", [Drawable.PATH, Drawable.VACUUM_POSITION])
344+
def test_simulated_map_renders_overlays(drawable: Drawable) -> None:
345+
"""Each overlay changes the image rather than silently being clipped away."""
346+
simulator = V1VacuumSimulator()
347+
simulator.advance_path(40)
348+
raw = simulator.build_map_bytes()
349+
background = MapParser(MapParserConfig(drawables=[])).parse(raw)
350+
rendered = MapParser(MapParserConfig(drawables=[drawable])).parse(raw)
351+
assert background is not None and rendered is not None
352+
assert rendered.image_content != background.image_content
353+
354+
355+
async def test_map_custom_handler_override() -> None:
356+
"""A custom map travels through the same binary response path as the default."""
357+
custom_simulator = V1VacuumSimulator()
358+
custom_simulator.advance_path(7)
359+
custom_simulator.robot_position = (31000, 32000, 180)
360+
custom_map = custom_simulator.build_map_bytes()
361+
362+
def get_map(params):
363+
assert params == []
364+
return custom_map
365+
366+
simulator = V1VacuumSimulator(custom_handlers={"get_map_v1": get_map})
367+
device = await _create_connected_device(FakeRoborockCloud(), simulator)
368+
await device.v1_properties.map_content.refresh()
369+
assert device.v1_properties.map_content.raw_api_response == custom_map
370+
assert len(_path_points(device)) == 7
371+
372+
373+
async def test_map_custom_handler_error() -> None:
374+
"""A failing override emits an RPC error instead of a successful default map."""
375+
376+
def get_map(params):
377+
raise RoborockException("map unavailable")
378+
379+
simulator = V1VacuumSimulator(custom_handlers={"get_map_v1": get_map})
380+
with pytest.raises(RoborockException, match="map unavailable"):
381+
await simulator.v1_channel.mqtt_rpc_channel.send_command("get_map_v1")

0 commit comments

Comments
 (0)