Skip to content

Commit 916e5e8

Browse files
authored
refactor(map): consolidate Q10 render config and grid constants (#1011)
1 parent c245569 commit 916e5e8

8 files changed

Lines changed: 157 additions & 132 deletions

File tree

‎roborock/devices/device_manager.py‎

Lines changed: 1 addition & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -19,7 +19,6 @@
1919
from roborock.devices.device import DeviceReadyCallback, RoborockDevice
2020
from roborock.diagnostics import Diagnostics, redact_device_data
2121
from roborock.exceptions import RoborockException
22-
from roborock.map.b01_q10_map_parser import B01Q10MapParserConfig
2322
from roborock.map.map_parser import MapParserConfig
2423
from roborock.mqtt.roborock_session import create_lazy_mqtt_session
2524
from roborock.mqtt.session import MqttSession, SessionUnauthorizedHook
@@ -263,16 +262,7 @@ def device_creator(home_data: HomeData, device: HomeDataDevice, product: HomeDat
263262
if "ss" in model_part:
264263
b01_q10_channel = create_b01_q10_channel(mqtt_channel)
265264
channel = b01_q10_channel
266-
trait = b01.q10.create(
267-
channel,
268-
map_parser_config=(
269-
B01Q10MapParserConfig(
270-
map_scale=map_parser_config.map_scale, drawables=map_parser_config.drawables
271-
)
272-
if map_parser_config
273-
else None
274-
),
275-
)
265+
trait = b01.q10.create(channel, map_parser_config=map_parser_config)
276266
elif "sc" in model_part:
277267
# Q7 devices start with 'sc' in their model naming.
278268
b01_q7_channel = create_b01_q7_channel(device, product, mqtt_channel)

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

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -9,12 +9,12 @@
99
from roborock.devices.rpc.b01_q10_channel import B01Q10Channel
1010
from roborock.devices.traits import Trait
1111
from roborock.map.b01_q10_map_parser import (
12-
B01Q10MapParserConfig,
1312
Q10CleanRecordDetail,
1413
Q10MapPacket,
1514
Q10MapPacketKind,
1615
Q10TracePacket,
1716
)
17+
from roborock.map.map_parser import MapParserConfig
1818
from roborock.protocols.b01_q10_protocol import Q10DpsUpdate, Q10Message
1919

2020
from .button_light import ButtonLightTrait
@@ -102,7 +102,7 @@ def __init__(
102102
self,
103103
channel: B01Q10Channel,
104104
*,
105-
map_parser_config: B01Q10MapParserConfig | None = None,
105+
map_parser_config: MapParserConfig | None = None,
106106
) -> None:
107107
"""Initialize the B01Props API."""
108108
self._channel = channel
@@ -202,7 +202,7 @@ def as_dict(self) -> dict[str, Any]:
202202
def create(
203203
channel: B01Q10Channel,
204204
*,
205-
map_parser_config: B01Q10MapParserConfig | None = None,
205+
map_parser_config: MapParserConfig | None = None,
206206
) -> Q10PropertiesApi:
207207
"""Create traits for B01 devices."""
208208
return Q10PropertiesApi(

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

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -24,7 +24,6 @@
2424
from roborock.devices.traits.common import DpsDataConverter, TraitUpdateListener
2525
from roborock.exceptions import RoborockException
2626
from roborock.map.b01_q10_map_parser import (
27-
B01Q10MapParserConfig,
2827
Q10MapPacket,
2928
Q10MapPacketKind,
3029
Q10Point,
@@ -33,6 +32,7 @@
3332
)
3433
from roborock.map.b01_q10_overlays import Q10RestrictedZone, Q10VirtualWall, parse_virtual_wall_blob, parse_zone_blob
3534
from roborock.map.b01_q10_render import Q10MapOverlays, render_q10_map, resolve_q10_current_room
35+
from roborock.map.map_parser import MapParserConfig
3636
from roborock.protocols.b01_q10_protocol import encode_restricted_zones, encode_room_name, encode_virtual_walls
3737

3838
from .command import CommandTrait
@@ -99,10 +99,10 @@ def __init__(
9999
map_dps: MapDpsTrait,
100100
command: CommandTrait,
101101
*,
102-
map_parser_config: B01Q10MapParserConfig | None = None,
102+
map_parser_config: MapParserConfig | None = None,
103103
) -> None:
104104
TraitUpdateListener.__init__(self, logger=_LOGGER)
105-
self._config = map_parser_config or B01Q10MapParserConfig()
105+
self._config = map_parser_config or MapParserConfig()
106106
self._map_dps = map_dps
107107
self._command = command
108108
self._map_packet: Q10MapPacket | None = None

‎roborock/map/b01_q10_map_parser.py‎

Lines changed: 9 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -25,8 +25,6 @@
2525
import struct
2626
from dataclasses import dataclass, field, replace
2727

28-
from vacuum_map_parser_base.config.drawable import Drawable
29-
3028
from roborock.data.b01_q10.b01_q10_containers import Q10RoborockPoint
3129
from roborock.data.code_mappings import RoborockEnum
3230
from roborock.data.containers import RoborockBase
@@ -45,19 +43,21 @@
4543
# eyeballed): 243 is the background outside the home (~half the grid), 240 is
4644
# scanned floor not yet assigned to a room, other values >= 240 are walls, and
4745
# 0 < value < 240 are per-room floor cells (value == room_id * 4).
48-
_BACKGROUND_VALUE = 243
49-
_UNSEGMENTED_FLOOR_VALUE = 240
46+
Q10_BACKGROUND_VALUE = 243
47+
Q10_UNSEGMENTED_FLOOR_VALUE = 240
48+
# Grid cell values >= this are walls / borders rather than room segments.
49+
Q10_WALL_THRESHOLD = 240
5050

5151

5252
def classify_q10_cell(value: int) -> str:
5353
"""Map a Q10 grid cell value to a canonical layer class."""
5454
if value == 0:
5555
return LAYER_UNKNOWN
56-
if value == _BACKGROUND_VALUE:
56+
if value == Q10_BACKGROUND_VALUE:
5757
return LAYER_BACKGROUND
58-
if value == _UNSEGMENTED_FLOOR_VALUE:
58+
if value == Q10_UNSEGMENTED_FLOOR_VALUE:
5959
return LAYER_FLOOR
60-
if value >= _WALL_THRESHOLD:
60+
if value >= Q10_WALL_THRESHOLD:
6161
return LAYER_WALL
6262
return LAYER_FLOOR
6363

@@ -103,9 +103,6 @@ def classify_q10_cell(value: int) -> str:
103103
# although they use different coordinate frames as documented above.
104104
_HEADER_UNITS_PER_PIXEL = 10
105105

106-
# Grid cell values >= this are walls / borders rather than room segments.
107-
_WALL_THRESHOLD = 240
108-
109106

110107
@dataclass
111108
class Q10Room(RoborockBase):
@@ -785,7 +782,7 @@ def _parse_clean_record_trace(
785782
)
786783

787784

788-
def erased_packet(packet: "Q10MapPacket", cells: set[int]) -> "Q10MapPacket":
785+
def erased_packet(packet: Q10MapPacket, cells: set[int]) -> Q10MapPacket:
789786
"""Return a copy of ``packet`` with ``cells`` (grid indices) set to background.
790787
791788
Used to apply the app's erase zones: cells inside an erase rectangle are blanked
@@ -796,15 +793,5 @@ def erased_packet(packet: "Q10MapPacket", cells: set[int]) -> "Q10MapPacket":
796793
grid = bytearray(packet.grid)
797794
for cell in cells:
798795
if 0 <= cell < len(grid):
799-
grid[cell] = _BACKGROUND_VALUE
796+
grid[cell] = Q10_BACKGROUND_VALUE
800797
return replace(packet, grid=bytes(grid))
801-
802-
803-
@dataclass
804-
class B01Q10MapParserConfig:
805-
"""Configuration for the Q10 map parser."""
806-
807-
map_scale: int = 4
808-
"""Scale factor for the rendered map image."""
809-
drawables: list[Drawable] | None = None
810-
"""Enabled overlays, or ``None`` for the Q10 defaults."""

‎roborock/map/b01_q10_render.py‎

Lines changed: 60 additions & 58 deletions
Original file line numberDiff line numberDiff line change
@@ -34,10 +34,9 @@
3434
solve_calibration,
3535
)
3636
from .b01_q10_map_parser import (
37-
_BACKGROUND_VALUE,
38-
_UNSEGMENTED_FLOOR_VALUE,
39-
_WALL_THRESHOLD,
40-
B01Q10MapParserConfig,
37+
Q10_BACKGROUND_VALUE,
38+
Q10_UNSEGMENTED_FLOOR_VALUE,
39+
Q10_WALL_THRESHOLD,
4140
Q10EraseZone,
4241
Q10HistoricalTracePacket,
4342
Q10MapPacket,
@@ -48,7 +47,7 @@
4847
erased_packet,
4948
)
5049
from .b01_q10_overlays import ZONE_TYPE_NO_GO, ZONE_TYPE_NO_MOP, Q10Zone
51-
from .map_parser import DEFAULT_DRAWABLES, MapParserConfig, _create_image_generator
50+
from .map_parser import MapParserConfig, _create_image_generator
5251
from .room_colors import adjacency_aware_room_colors
5352

5453
# Path-units-per-pixel candidates for calibration. A dense ss07 path lands a
@@ -79,7 +78,6 @@
7978
Drawable.VACUUM_POSITION,
8079
Drawable.VIRTUAL_WALLS,
8180
}
82-
_Q10_DRAWABLES = [drawable for drawable in DEFAULT_DRAWABLES if drawable in _Q10_DRAWABLE_TYPES]
8381

8482

8583
@dataclass(frozen=True)
@@ -95,7 +93,7 @@ def render_q10_map(
9593
trace: Q10TracePacket | Q10HistoricalTracePacket | None,
9694
overlays: Q10MapOverlays,
9795
*,
98-
config: B01Q10MapParserConfig,
96+
config: MapParserConfig,
9997
robot_at_dock: bool = False,
10098
) -> bytes:
10199
"""Compose the latest map, trace and DPS inputs into one PNG image.
@@ -120,19 +118,21 @@ def render_q10_map(
120118
if map_data.image is None:
121119
raise RoborockException("Failed to render Q10 map image")
122120

123-
has_drawables = _place_obstacles(map_data, packet)
124-
if trace_calibration is not None and trace is not None:
125-
charger_heading = packet.header_calibration.charger_phi if packet.header_calibration is not None else None
126-
_place_trace(map_data, trace_calibration, trace, charger_heading=charger_heading)
127-
has_drawables = True
128-
has_drawables = _place_charger_from_header(map_data, packet) or has_drawables
129-
if robot_at_dock:
130-
has_drawables = _place_docked_robot(map_data) or has_drawables
131-
if vector_calibration is not None:
132-
_place_overlays(map_data, vector_calibration, overlays)
133-
has_drawables = has_drawables or bool(map_data.no_go_areas or map_data.no_mopping_areas or map_data.walls)
134-
if has_drawables:
135-
return _draw_map_content(map_data, config=config)
121+
drawables = [drawable for drawable in config.drawables if drawable in _Q10_DRAWABLE_TYPES]
122+
if drawables:
123+
has_drawables = _place_obstacles(map_data, packet)
124+
if trace_calibration is not None and trace is not None:
125+
charger_heading = packet.header_calibration.charger_phi if packet.header_calibration is not None else None
126+
_place_trace(map_data, trace_calibration, trace, charger_heading=charger_heading)
127+
has_drawables = True
128+
has_drawables = _place_charger_from_header(map_data, packet) or has_drawables
129+
if robot_at_dock:
130+
has_drawables = _place_docked_robot(map_data) or has_drawables
131+
if vector_calibration is not None:
132+
_place_overlays(map_data, vector_calibration, overlays)
133+
has_drawables = has_drawables or bool(map_data.no_go_areas or map_data.no_mopping_areas or map_data.walls)
134+
if has_drawables:
135+
return _draw_map_content(map_data, config=config, drawables=drawables)
136136

137137
buffer = io.BytesIO()
138138
map_data.image.data.save(buffer, format="PNG")
@@ -432,17 +432,13 @@ def to_area(zone: Q10Zone) -> Area | None:
432432
def _draw_map_content(
433433
map_data: MapData,
434434
*,
435-
config: B01Q10MapParserConfig,
435+
config: MapParserConfig,
436+
drawables: list[Drawable],
436437
) -> bytes:
437438
"""Draw Q10 content with the shared V1 image generator."""
438439
if map_data.image is None:
439440
raise RoborockException("Failed to render Q10 map image")
440-
drawables = (
441-
_Q10_DRAWABLES
442-
if config.drawables is None
443-
else [drawable for drawable in config.drawables if drawable in _Q10_DRAWABLE_TYPES]
444-
)
445-
generator = _create_image_generator(MapParserConfig(map_scale=config.map_scale), drawables=drawables)
441+
generator = _create_image_generator(config, drawables=drawables)
446442
generator.draw_map(map_data)
447443
buffer = io.BytesIO()
448444
map_data.image.data.save(buffer, format="PNG")
@@ -452,10 +448,10 @@ def _draw_map_content(
452448
def _map_data_from_packet(
453449
packet: Q10MapPacket,
454450
*,
455-
config: B01Q10MapParserConfig,
451+
config: MapParserConfig,
456452
) -> MapData:
457453
"""Build MapData with a rendered base image, without PNG serialization."""
458-
image = _render_base_grid(packet, scale=config.map_scale)
454+
image = _render_base_grid(packet, config=config)
459455

460456
map_data = MapData()
461457
map_data.image = ImageData(
@@ -473,29 +469,28 @@ def _map_data_from_packet(
473469
# overlays vertically.
474470
img_transformation=lambda p: Point(p.x, packet.height - p.y - 1, p.a),
475471
)
476-
room_names = {room.id: room.name for room in packet.rooms}
477-
if room_names:
478-
map_data.additional_parameters["room_names"] = room_names
479-
480-
# Carpet cells are flat grid indices (y*width + x) in the same top-down
481-
# pixel space as the rendered raster, so they line up with the image.
482-
if packet.carpet_mask is not None:
483-
map_data.carpet_map = {i for i, value in enumerate(packet.carpet_mask) if value}
484-
485472
return map_data
486473

487474

488-
def _render_base_grid(packet: Q10MapPacket, *, scale: int) -> Image.Image:
475+
def _render_base_grid(packet: Q10MapPacket, *, config: MapParserConfig) -> Image.Image:
489476
"""Render the Q10 grid with the V1 map palette."""
490-
palette = _build_palette(packet.grid, packet.width)
477+
palette = _build_palette(
478+
packet.grid,
479+
packet.width,
480+
show_walls=config.show_walls,
481+
show_rooms=config.show_rooms,
482+
)
491483
flat_palette = [channel for color in palette for channel in color]
492484
p_img = Image.frombytes("P", (packet.width, packet.height), packet.grid)
493485
p_img.putpalette(flat_palette, rawmode="RGBA")
494486
img = p_img.convert("RGBA")
495487
# The ss07 grid is stored top-down (row 0 = top of the home), so it is
496488
# rendered as-is -- unlike the V1/Q7 convention, no vertical flip.
497-
if scale > 1:
498-
img = img.resize((packet.width * scale, packet.height * scale), resample=Image.Resampling.NEAREST)
489+
if config.map_scale > 1:
490+
img = img.resize(
491+
(packet.width * config.map_scale, packet.height * config.map_scale),
492+
resample=Image.Resampling.NEAREST,
493+
)
499494
return img
500495

501496

@@ -504,27 +499,34 @@ def _opaque(color: tuple[int, ...]) -> tuple[int, int, int, int]:
504499
return (color[0], color[1], color[2], color[3] if len(color) == 4 else 255)
505500

506501

507-
def _build_palette(grid: bytes, width: int) -> list[tuple[int, int, int, int]]:
502+
def _build_palette(
503+
grid: bytes,
504+
width: int,
505+
*,
506+
show_walls: bool = True,
507+
show_rooms: bool = True,
508+
) -> list[tuple[int, int, int, int]]:
508509
"""Map Q10 cells onto the same colors used by the V1 map renderer."""
509510

510511
def room_id(value: int) -> int | None:
511-
return max(1, value // 4) if 0 < value < _WALL_THRESHOLD else None
512+
return max(1, value // 4) if 0 < value < Q10_WALL_THRESHOLD else None
512513

513514
colors = ColorsPalette()
514-
room_colors = adjacency_aware_room_colors(
515-
grid,
516-
width,
517-
colors,
518-
room_id,
519-
)
520515
outside = (0, 0, 0, 0)
521516
palette = [outside] * 256
522-
for value in {value for value in grid if 0 < value < _WALL_THRESHOLD}:
523-
palette[value] = _opaque(room_colors[max(1, value // 4)])
524-
wall = _opaque(colors.get_color(SupportedColor.GREY_WALL))
525-
for value in range(_WALL_THRESHOLD, 256):
526-
palette[value] = wall
527-
palette[_UNSEGMENTED_FLOOR_VALUE] = _opaque(colors.get_color(SupportedColor.MAP_INSIDE))
528-
palette[_BACKGROUND_VALUE] = outside
529-
palette[0] = outside
517+
if show_rooms:
518+
room_colors = adjacency_aware_room_colors(
519+
grid,
520+
width,
521+
colors,
522+
room_id,
523+
)
524+
for value in {value for value in grid if 0 < value < Q10_WALL_THRESHOLD}:
525+
palette[value] = _opaque(room_colors[max(1, value // 4)])
526+
palette[Q10_UNSEGMENTED_FLOOR_VALUE] = _opaque(colors.get_color(SupportedColor.MAP_INSIDE))
527+
if show_walls:
528+
wall = _opaque(colors.get_color(SupportedColor.GREY_WALL))
529+
for value in range(Q10_WALL_THRESHOLD, 256):
530+
if value not in (Q10_UNSEGMENTED_FLOOR_VALUE, Q10_BACKGROUND_VALUE):
531+
palette[value] = wall
530532
return palette

0 commit comments

Comments
 (0)