From 8b376957d22e532d3711f5500009eb9afc54928c Mon Sep 17 00:00:00 2001 From: mysiki Date: Tue, 1 Dec 2026 13:23:03 +0100 Subject: [PATCH 1/2] feat: add configurable room outlines Derive room polygons from the raw Roborock pixel matrix so the map card can represent concave and multi-rectangle rooms instead of always highlighting their bounding boxes. Add per-map room outline modes: precise uses the cleaned architectural contour, while square uses one bounding rectangle. Expose the choice through the options flow and a dedicated select entity, cache geometry by map payload and mode, synchronize updates, and localize the UI. Refresh only affected maps when the setting changes. --- .../roborock_custom_map/__init__.py | 19 ++ .../roborock_custom_map/config_flow.py | 59 +++- .../roborock_custom_map/const.py | 17 + .../roborock_custom_map/image.py | 31 +- .../roborock_custom_map/room_geometry.py | 315 ++++++++++++++++++ .../roborock_custom_map/select.py | 97 +++++- .../roborock_custom_map/translations/de.json | 29 +- .../roborock_custom_map/translations/en.json | 29 +- 8 files changed, 573 insertions(+), 23 deletions(-) create mode 100644 custom_components/roborock_custom_map/room_geometry.py diff --git a/custom_components/roborock_custom_map/__init__.py b/custom_components/roborock_custom_map/__init__.py index a65eacf..45c8740 100644 --- a/custom_components/roborock_custom_map/__init__.py +++ b/custom_components/roborock_custom_map/__init__.py @@ -13,7 +13,9 @@ from .const import ( CONF_BG_OVERRIDES, CONF_MAP_ROTATION, + CONF_ROOM_OUTLINE_MODES, DATA_LAST_BG_OVERRIDES, + DATA_LAST_ROOM_OUTLINE_MODES, DATA_PREVIEW_SESSIONS, DOMAIN, signal_map_refresh, @@ -53,6 +55,9 @@ def unload_this_entry() -> None: data.setdefault(CONF_MAP_ROTATION, {}) data.setdefault(DATA_PREVIEW_SESSIONS, {}) data[DATA_LAST_BG_OVERRIDES] = _overrides_snapshot(entry) + data[DATA_LAST_ROOM_OUTLINE_MODES] = dict( + entry.options.get(CONF_ROOM_OUTLINE_MODES, {}) + ) entry.async_on_unload(entry.add_update_listener(_async_update_listener)) @@ -75,6 +80,20 @@ async def _async_update_listener(hass: HomeAssistant, entry: ConfigEntry) -> Non changed = { key for key in old.keys() | new.keys() if old.get(key) != new.get(key) } + + old_modes = data.get(DATA_LAST_ROOM_OUTLINE_MODES) if data is not None else None + new_modes = entry.options.get(CONF_ROOM_OUTLINE_MODES, {}) + if data is not None: + data[DATA_LAST_ROOM_OUTLINE_MODES] = dict(new_modes) + if old_modes is None: + changed.update(new_modes) + else: + changed.update( + key + for key in old_modes.keys() | new_modes.keys() + if old_modes.get(key) != new_modes.get(key) + ) + for key in changed: async_dispatcher_send(hass, signal_map_refresh(entry.entry_id, key)) diff --git a/custom_components/roborock_custom_map/config_flow.py b/custom_components/roborock_custom_map/config_flow.py index 1e20804..ddc1c1d 100644 --- a/custom_components/roborock_custom_map/config_flow.py +++ b/custom_components/roborock_custom_map/config_flow.py @@ -38,18 +38,23 @@ CONF_MAP_ROTATION, CONF_OFFSET_X, CONF_OFFSET_Y, + CONF_ROOM_OUTLINE_MODE, + CONF_ROOM_OUTLINE_MODES, CONF_SCALE_X, CONF_SCALE_Y, + DEFAULT_ROOM_OUTLINE_MODE, DOMAIN, MAP_ROTATION_OPTIONS, MAX_SCALE, MIN_SCALE, + ROOM_OUTLINE_MODE_OPTIONS, get_map_rotation, map_key, map_unique_id, override_scales, set_map_rotation, signal_map_refresh, + signal_set_room_outline_mode, signal_set_rotation, ) from .preview import ( @@ -102,6 +107,13 @@ ], ) ) +ROOM_OUTLINE_MODE_SELECTOR = SelectSelector( + SelectSelectorConfig( + mode=SelectSelectorMode.DROPDOWN, + translation_key=CONF_ROOM_OUTLINE_MODE, + options=list(ROOM_OUTLINE_MODE_OPTIONS), + ) +) @dataclass @@ -229,18 +241,49 @@ async def async_step_init( async def async_step_map( self, user_input: dict[str, Any] | None = None ) -> ConfigFlowResult: - """Route to upload or the manage menu depending on stored state.""" - if self._current_override() is not None: - return await self.async_step_map_menu() - return await self.async_step_upload() + """Show the settings available for the selected map.""" + return await self.async_step_map_menu() async def async_step_map_menu( self, user_input: dict[str, Any] | None = None ) -> ConfigFlowResult: - """Manage an existing override.""" - return self.async_show_menu( - step_id="map_menu", - menu_options=["tune", "upload", "remove_confirm"], + """Show room outline and custom floor-plan actions.""" + menu_options = ["outline", "upload"] + if self._current_override() is not None: + menu_options = ["outline", "tune", "upload", "remove_confirm"] + return self.async_show_menu(step_id="map_menu", menu_options=menu_options) + + async def async_step_outline( + self, user_input: dict[str, Any] | None = None + ) -> ConfigFlowResult: + """Choose and save the room outline detail for this map.""" + if user_input is not None: + options = dict(self.config_entry.options) + modes = dict(options.get(CONF_ROOM_OUTLINE_MODES, {})) + mode = user_input[CONF_ROOM_OUTLINE_MODE] + modes[self._choice.rotation_key] = mode + options[CONF_ROOM_OUTLINE_MODES] = modes + async_dispatcher_send( + self.hass, + signal_set_room_outline_mode( + self.config_entry.entry_id, self._choice.rotation_key + ), + mode, + ) + return self.async_create_entry(data=options) + + mode = self.config_entry.options.get(CONF_ROOM_OUTLINE_MODES, {}).get( + self._choice.rotation_key, DEFAULT_ROOM_OUTLINE_MODE + ) + return self.async_show_form( + step_id="outline", + data_schema=vol.Schema( + { + vol.Required( + CONF_ROOM_OUTLINE_MODE, default=mode + ): ROOM_OUTLINE_MODE_SELECTOR + } + ), ) async def async_step_upload( diff --git a/custom_components/roborock_custom_map/const.py b/custom_components/roborock_custom_map/const.py index 7376891..ae90737 100644 --- a/custom_components/roborock_custom_map/const.py +++ b/custom_components/roborock_custom_map/const.py @@ -13,7 +13,18 @@ DEFAULT_MAP_ROTATION = 0 MAP_ROTATION_OPTIONS = (0, 90, 180, 270) +CONF_ROOM_OUTLINE_MODE = "room_outline_mode" +CONF_ROOM_OUTLINE_MODES = "room_outline_modes" +ROOM_OUTLINE_MODE_PRECISE = "precise" +ROOM_OUTLINE_MODE_SQUARE = "square" +DEFAULT_ROOM_OUTLINE_MODE = ROOM_OUTLINE_MODE_PRECISE +ROOM_OUTLINE_MODE_OPTIONS = ( + ROOM_OUTLINE_MODE_PRECISE, + ROOM_OUTLINE_MODE_SQUARE, +) + SIGNAL_MAP_REFRESH = "roborock_custom_map_refresh" +SIGNAL_SET_ROOM_OUTLINE_MODE = "roborock_custom_map_set_room_outline_mode" CONF_BG_OVERRIDES = "bg_overrides" CONF_FILE = "file" @@ -29,6 +40,7 @@ DATA_PREVIEW_SESSIONS = "preview_sessions" DATA_LAST_BG_OVERRIDES = "last_bg_overrides" +DATA_LAST_ROOM_OUTLINE_MODES = "last_room_outline_modes" PREVIEW_WS_TYPE = f"{DOMAIN}/start_preview" @@ -68,6 +80,11 @@ def signal_map_refresh(entry_id: str, key: str) -> str: return f"{SIGNAL_MAP_REFRESH}_{entry_id}_{key}" +def signal_set_room_outline_mode(entry_id: str, key: str) -> str: + """Dispatcher signal updating a map's outline select entity.""" + return f"{SIGNAL_SET_ROOM_OUTLINE_MODE}_{entry_id}_{key}" + + def get_map_rotation(hass: HomeAssistant, entry_id: str, key: str) -> int: """Return the currently applied rotation of one map.""" return ( diff --git a/custom_components/roborock_custom_map/image.py b/custom_components/roborock_custom_map/image.py index 255b6b6..941dc1b 100644 --- a/custom_components/roborock_custom_map/image.py +++ b/custom_components/roborock_custom_map/image.py @@ -34,7 +34,9 @@ CONF_BG_OVERRIDES, CONF_FILE, CONF_FILE_HASH, + CONF_ROOM_OUTLINE_MODES, DEFAULT_MAP_ROTATION, + DEFAULT_ROOM_OUTLINE_MODE, MAP_ROTATION_OPTIONS, get_map_rotation, map_key, @@ -43,6 +45,7 @@ signal_map_refresh, ) from .preview import PreviewSession, async_get_session +from .room_geometry import room_geometry _LOGGER = logging.getLogger(__name__) @@ -144,6 +147,7 @@ def __init__( self._raw_image_size: tuple[int, int] | None = None self._overlay_cache: tuple[bytes, Image.Image] | None = None self._mask_cache: tuple[bytes, Image.Image] | None = None + self._room_geometry_cache: tuple[bytes, str, dict[int, dict]] | None = None self._layers_generation = 0 self._bg_cache: tuple[tuple[str, str], bytes] | None = None self._composite_cache: tuple[tuple, bytes] | None = None @@ -428,10 +432,31 @@ def extra_state_attributes(self): if map_data is None: return {} - if map_data.rooms is not None: - for room in map_data.rooms.values(): + rooms = map_data.rooms + if rooms is not None: + raw = map_content.raw_api_response + geometry = {} + mode = self.config_entry.options.get(CONF_ROOM_OUTLINE_MODES, {}).get( + self.rotation_key, DEFAULT_ROOM_OUTLINE_MODE + ) + if raw is not None: + if ( + self._room_geometry_cache is None + or self._room_geometry_cache[0] != raw + or self._room_geometry_cache[1] != mode + ): + self._room_geometry_cache = (raw, mode, room_geometry(raw, mode)) + geometry = self._room_geometry_cache[2] + + room_attributes = {} + for room_number, room in rooms.items(): name = self._home_trait._rooms_trait.room_map.get(room.number) room.name = name.name if name else "Unknown" + room_attributes[room_number] = { + **room.as_dict(), + **geometry.get(room_number, {}), + } + rooms = room_attributes calibration = map_data.calibration() @@ -477,6 +502,6 @@ def extra_state_attributes(self): return { "calibration_points": calibration, - "rooms": map_data.rooms, + "rooms": rooms, "zones": map_data.zones, } diff --git a/custom_components/roborock_custom_map/room_geometry.py b/custom_components/roborock_custom_map/room_geometry.py new file mode 100644 index 0000000..01095fb --- /dev/null +++ b/custom_components/roborock_custom_map/room_geometry.py @@ -0,0 +1,315 @@ +"""Extract room outlines from Roborock map pixel data.""" + +from __future__ import annotations + +from collections import defaultdict +from collections.abc import Sequence +from typing import Any + +_IMAGE_BLOCK_TYPE = 2 +_MAP_INSIDE = 0xFF +_MAP_SCAN = 0x07 +_CLOSING_RADIUS = 2 +_SIMPLIFY_TOLERANCE = 4.0 +_OUTLINE_MODE_PRECISE = "precise" +_OUTLINE_MODE_SQUARE = "square" + +Point = tuple[int, int] +Edge = tuple[Point, Point] + + +def _uint16(data: bytes, offset: int) -> int: + return int.from_bytes(data[offset : offset + 2], "little") + + +def _uint32(data: bytes, offset: int) -> int: + return int.from_bytes(data[offset : offset + 4], "little") + + +def _room_number(pixel: int) -> int | None: + if pixel in (_MAP_INSIDE, _MAP_SCAN) or pixel & 0x07 != 0x07: + return None + return pixel >> 3 + + +def _image_block(raw: bytes) -> tuple[bytes, int, int, int, int] | None: + if len(raw) < 4: + return None + + block_start = _uint16(raw, 2) + while block_start + 8 <= len(raw): + block_header_length = _uint16(raw, block_start + 2) + if block_header_length < 8 or block_start + block_header_length > len(raw): + return None + + block_type = _uint16(raw, block_start) + block_data_length = _uint32(raw, block_start + 4) + block_data_start = block_start + block_header_length + block_end = block_data_start + block_data_length + if block_end > len(raw): + return None + + if block_type == _IMAGE_BLOCK_TYPE: + if block_header_length < 24: + return None + header = raw[block_start:block_data_start] + top = _uint32(header, block_header_length - 16) + left = _uint32(header, block_header_length - 12) + height = _uint32(header, block_header_length - 8) + width = _uint32(header, block_header_length - 4) + if width == 0 or height == 0 or block_data_length < width * height: + return None + return ( + raw[block_data_start : block_data_start + width * height], + width, + height, + top, + left, + ) + + block_start = block_end + + return None + + +def _trace_loops(edges: Sequence[Edge]) -> list[list[Point]]: + remaining = set(edges) + outgoing: dict[Point, list[Point]] = defaultdict(list) + for start, end in remaining: + outgoing[start].append(end) + + loops: list[list[Point]] = [] + direction_order = {(1, 0): 0, (0, 1): 1, (-1, 0): 2, (0, -1): 3} + + while remaining: + start, first_end = next(iter(remaining)) + loop = [start] + previous_direction = (first_end[0] - start[0], first_end[1] - start[1]) + current = start + + while True: + candidates = [end for end in outgoing[current] if (current, end) in remaining] + if not candidates: + break + + incoming = direction_order[previous_direction] + + def turn_rank(end: Point) -> int: + direction = (end[0] - current[0], end[1] - current[1]) + turn = (direction_order[direction] - incoming) % 4 + return {1: 0, 0: 1, 3: 2, 2: 3}[turn] + + end = min(candidates, key=turn_rank) + remaining.remove((current, end)) + previous_direction = (end[0] - current[0], end[1] - current[1]) + current = end + loop.append(current) + if current == start: + loops.append(loop[:-1]) + break + + return loops + + +def _simplify_loop(loop: list[Point]) -> list[Point]: + if len(loop) < 3: + return loop + + simplified: list[Point] = [] + for index, point in enumerate(loop): + previous = loop[index - 1] + following = loop[(index + 1) % len(loop)] + cross_product = ( + (point[0] - previous[0]) * (following[1] - point[1]) + - (point[1] - previous[1]) * (following[0] - point[0]) + ) + if cross_product != 0: + simplified.append(point) + return simplified + + +def _loop_area(loop: Sequence[Point]) -> int: + return abs( + sum( + point[0] * loop[(index + 1) % len(loop)][1] + - loop[(index + 1) % len(loop)][0] * point[1] + for index, point in enumerate(loop) + ) + ) + + +def _close_mask( + points: set[Point], width: int, height: int, radius: int +) -> set[Point]: + """Close narrow exterior notches and holes in a binary room mask.""" + dilated: set[Point] = set() + for x, y in points: + for offset_y in range(-radius, radius + 1): + next_y = y + offset_y + if not 0 <= next_y < height: + continue + for offset_x in range(-radius, radius + 1): + next_x = x + offset_x + if 0 <= next_x < width: + dilated.add((next_x, next_y)) + + closed: set[Point] = set() + for x, y in dilated: + if all( + not (0 <= x + offset_x < width and 0 <= y + offset_y < height) + or (x + offset_x, y + offset_y) in dilated + for offset_y in range(-radius, radius + 1) + for offset_x in range(-radius, radius + 1) + ): + closed.add((x, y)) + return closed + + +def _point_segment_distance(point: Point, start: Point, end: Point) -> float: + dx = end[0] - start[0] + dy = end[1] - start[1] + if dx == 0 and dy == 0: + return float((point[0] - start[0]) ** 2 + (point[1] - start[1]) ** 2) ** 0.5 + + position = ( + (point[0] - start[0]) * dx + (point[1] - start[1]) * dy + ) / (dx * dx + dy * dy) + position = max(0.0, min(1.0, position)) + projected_x = start[0] + position * dx + projected_y = start[1] + position * dy + return float( + (point[0] - projected_x) ** 2 + (point[1] - projected_y) ** 2 + ) ** 0.5 + + +def _simplify_path( + points: Sequence[Point], tolerance: float +) -> list[Point]: + if len(points) <= 2: + return list(points) + + distances = [ + _point_segment_distance(point, points[0], points[-1]) + for point in points[1:-1] + ] + maximum = max(distances, default=0.0) + if maximum <= tolerance: + return [points[0], points[-1]] + + split = distances.index(maximum) + 1 + left = _simplify_path(points[: split + 1], tolerance) + right = _simplify_path(points[split:], tolerance) + return left[:-1] + right + + +def _simplify_closed_loop(loop: list[Point], tolerance: float) -> list[Point]: + if len(loop) <= 4: + return loop + + start = min(range(len(loop)), key=lambda index: (loop[index][1], loop[index][0])) + first = loop[start] + opposite = max( + range(len(loop)), + key=lambda index: ( + (loop[index][0] - first[0]) ** 2 + + (loop[index][1] - first[1]) ** 2 + ), + ) + forward = loop[start:] + loop[:start] + opposite_offset = (opposite - start) % len(loop) + first_half = forward[: opposite_offset + 1] + second_half = forward[opposite_offset:] + [forward[0]] + simplified = _simplify_path(first_half, tolerance)[:-1] + simplified += _simplify_path(second_half, tolerance)[:-1] + return simplified + + +def room_geometry( + raw: bytes, mode: str = _OUTLINE_MODE_PRECISE +) -> dict[int, dict[str, Any]]: + """Return the architectural outline or bounding box for each room.""" + if mode not in (_OUTLINE_MODE_PRECISE, _OUTLINE_MODE_SQUARE): + mode = _OUTLINE_MODE_PRECISE + image = _image_block(raw) + if image is None: + return {} + + data, width, height, top, left = image + room_pixels: dict[int, set[Point]] = defaultdict(set) + sums: dict[int, list[int]] = defaultdict(lambda: [0, 0, 0]) + + for index, pixel in enumerate(data): + room = _room_number(pixel) + if room is None: + continue + + x = index % width + y = index // width + room_pixels[room].add((x, y)) + sums[room][0] += x + sums[room][1] += y + sums[room][2] += 1 + + if mode == _OUTLINE_MODE_SQUARE: + geometry: dict[int, dict[str, Any]] = {} + for room, pixels in room_pixels.items(): + min_x = min(x for x, _ in pixels) + max_x = max(x for x, _ in pixels) + 1 + min_y = min(y for _, y in pixels) + max_y = max(y for _, y in pixels) + 1 + geometry[room] = { + "outline": [ + [(min_x + left) * 50, (min_y + top) * 50], + [(max_x + left) * 50, (min_y + top) * 50], + [(max_x + left) * 50, (max_y + top) * 50], + [(min_x + left) * 50, (max_y + top) * 50], + ] + } + return geometry + + edges_by_room: dict[int, list[Edge]] = defaultdict(list) + for room, pixels in room_pixels.items(): + outline_pixels = _close_mask(pixels, width, height, _CLOSING_RADIUS) + for x, y in outline_pixels: + if (x, y - 1) not in outline_pixels: + edges_by_room[room].append(((x, y), (x + 1, y))) + if (x + 1, y) not in outline_pixels: + edges_by_room[room].append(((x + 1, y), (x + 1, y + 1))) + if (x, y + 1) not in outline_pixels: + edges_by_room[room].append(((x + 1, y + 1), (x, y + 1))) + if (x - 1, y) not in outline_pixels: + edges_by_room[room].append(((x, y + 1), (x, y))) + + label_points: dict[int, tuple[float, float, float]] = {} + for index, pixel in enumerate(data): + room = _room_number(pixel) + if room is None: + continue + x = index % width + 0.5 + y = index // width + 0.5 + mean_x = sums[room][0] / sums[room][2] + 0.5 + mean_y = sums[room][1] / sums[room][2] + 0.5 + distance = (x - mean_x) ** 2 + (y - mean_y) ** 2 + if room not in label_points or distance < label_points[room][2]: + label_points[room] = (x, y, distance) + + geometry: dict[int, dict[str, Any]] = {} + for room, edges in edges_by_room.items(): + loops = [_simplify_loop(loop) for loop in _trace_loops(edges)] + loops = [loop for loop in loops if len(loop) >= 3] + if not loops: + continue + + outline = _simplify_closed_loop( + max(loops, key=_loop_area), _SIMPLIFY_TOLERANCE + ) + label_x, label_y, _ = label_points[room] + geometry[room] = { + "outline": [ + [(x + left) * 50, (y + top) * 50] for x, y in outline + ], + "x": round((label_x + left) * 50), + "y": round((label_y + top) * 50), + } + + return geometry diff --git a/custom_components/roborock_custom_map/select.py b/custom_components/roborock_custom_map/select.py index 4516085..acc378c 100644 --- a/custom_components/roborock_custom_map/select.py +++ b/custom_components/roborock_custom_map/select.py @@ -16,11 +16,15 @@ from homeassistant.helpers.restore_state import RestoreEntity from .const import ( + CONF_ROOM_OUTLINE_MODES, DEFAULT_MAP_ROTATION, + DEFAULT_ROOM_OUTLINE_MODE, MAP_ROTATION_OPTIONS, + ROOM_OUTLINE_MODE_OPTIONS, map_key, set_map_rotation, signal_map_refresh, + signal_set_room_outline_mode, signal_set_rotation, ) @@ -52,14 +56,26 @@ def _async_add_new_maps() -> None: if key in added: continue added.add(key) - entities.append( - RoborockMapRotationSelect( - config_entry=config_entry, - unique_id=f"{coord.duid_slug}_map_rotation_{map_info.map_flag}", - coordinator=coord, - map_flag=map_info.map_flag, - map_name=map_info.name, - ) + entities.extend( + [ + RoborockMapRotationSelect( + config_entry=config_entry, + unique_id=f"{coord.duid_slug}_map_rotation_{map_info.map_flag}", + coordinator=coord, + map_flag=map_info.map_flag, + map_name=map_info.name, + ), + RoborockMapOutlineSelect( + config_entry=config_entry, + unique_id=( + f"{coord.duid_slug}_room_outline_mode_" + f"{map_info.map_flag}" + ), + coordinator=coord, + map_flag=map_info.map_flag, + map_name=map_info.name, + ), + ] ) if entities: async_add_entities(entities) @@ -151,3 +167,68 @@ def _apply_rotation(self, option: str) -> None: ) self.async_write_ha_state() + + +class RoborockMapOutlineSelect( + RoborockCoordinatedEntityV1, SelectEntity +): + """Select entity to control generated room outline detail.""" + + _attr_has_entity_name = True + _attr_entity_category = EntityCategory.CONFIG + _attr_translation_key = "room_outline_mode" + + def __init__( + self, + config_entry: ConfigEntry, + unique_id: str, + coordinator: RoborockDataUpdateCoordinator, + map_flag: int, + map_name: str, + ) -> None: + """Initialize the room outline select.""" + RoborockCoordinatedEntityV1.__init__(self, unique_id, coordinator) + + self.config_entry = config_entry + self.map_flag = map_flag + self.rotation_key = map_key(coordinator.duid_slug, map_flag) + self._attr_name = f"{map_name or f'Map {map_flag}'} room outline" + self._attr_options = list(ROOM_OUTLINE_MODE_OPTIONS) + self._attr_current_option = self.config_entry.options.get( + CONF_ROOM_OUTLINE_MODES, {} + ).get(self.rotation_key, DEFAULT_ROOM_OUTLINE_MODE) + + async def async_added_to_hass(self) -> None: + """Connect the select to options-flow updates.""" + await super().async_added_to_hass() + self.async_on_remove( + async_dispatcher_connect( + self.hass, + signal_set_room_outline_mode( + self.config_entry.entry_id, self.rotation_key + ), + self._apply_mode, + ) + ) + + async def async_select_option(self, option: str) -> None: + """Persist the selected room outline mode.""" + if option not in self._attr_options: + return + + self._attr_current_option = option + options = dict(self.config_entry.options) + modes = dict(options.get(CONF_ROOM_OUTLINE_MODES, {})) + modes[self.rotation_key] = option + options[CONF_ROOM_OUTLINE_MODES] = modes + self.hass.config_entries.async_update_entry( + self.config_entry, options=options + ) + self.async_write_ha_state() + + @callback + def _apply_mode(self, option: str) -> None: + """Reflect a change made from the options flow.""" + if option in self._attr_options: + self._attr_current_option = option + self.async_write_ha_state() diff --git a/custom_components/roborock_custom_map/translations/de.json b/custom_components/roborock_custom_map/translations/de.json index 5e215d0..1f86427 100644 --- a/custom_components/roborock_custom_map/translations/de.json +++ b/custom_components/roborock_custom_map/translations/de.json @@ -17,9 +17,19 @@ "map": "Karte" } }, + "outline": { + "title": "Raumkontur", + "data": { + "room_outline_mode": "Detailgrad der Kontur" + }, + "data_description": { + "room_outline_mode": "Präzise verwendet die vereinfachte architektonische Kontur. Rechteck verwendet je Raum ein einziges umschließendes Rechteck." + } + }, "map_menu": { - "title": "Eigener Grundriss", + "title": "Karteneinstellungen", "menu_options": { + "outline": "Raumkontur", "tune": "Eigenen Grundriss anpassen", "upload": "Eigenen Grundriss ersetzen", "remove_confirm": "Eigenen Grundriss entfernen" @@ -72,8 +82,23 @@ "write_failed": "Der Grundriss konnte nicht gespeichert werden. Prüfe die Home-Assistant-Logs." } }, + "selector": { + "room_outline_mode": { + "options": { + "precise": "Präzise", + "square": "Rechteck (Begrenzungsrahmen)" + } + } + }, "entity": { "select": { + "room_outline_mode": { + "name": "Raumkontur", + "state": { + "precise": "Präzise", + "square": "Rechteck" + } + }, "rotation": { "name": "Kartenrotation", "state": { @@ -85,4 +110,4 @@ } } } -} +} \ No newline at end of file diff --git a/custom_components/roborock_custom_map/translations/en.json b/custom_components/roborock_custom_map/translations/en.json index 02f2cc6..f44d9ed 100644 --- a/custom_components/roborock_custom_map/translations/en.json +++ b/custom_components/roborock_custom_map/translations/en.json @@ -17,9 +17,19 @@ "map": "Map" } }, + "outline": { + "title": "Room outline mode", + "data": { + "room_outline_mode": "Outline detail" + }, + "data_description": { + "room_outline_mode": "Precise uses a simplified architectural contour. Square uses one bounding rectangle per room." + } + }, "map_menu": { - "title": "Custom Floor Plan", + "title": "Map settings", "menu_options": { + "outline": "Room outline mode", "tune": "Adjust Custom Floor Plan", "upload": "Replace Custom Floor Plan", "remove_confirm": "Remove Custom Floor Plan" @@ -72,8 +82,23 @@ "write_failed": "The floor plan could not be saved. Check the Home Assistant logs." } }, + "selector": { + "room_outline_mode": { + "options": { + "precise": "Precise", + "square": "Square (bounding box)" + } + } + }, "entity": { "select": { + "room_outline_mode": { + "name": "Room outline", + "state": { + "precise": "Precise", + "square": "Square" + } + }, "rotation": { "name": "Map rotation", "state": { @@ -85,4 +110,4 @@ } } } -} +} \ No newline at end of file From 52340271a333ff16a05ffff91b83222c71034d37 Mon Sep 17 00:00:00 2001 From: mysiki Date: Tue, 1 Dec 2026 13:30:50 +0100 Subject: [PATCH 2/2] add tests --- tests/__init__.py | 1 + tests/test_room_geometry.py | 105 ++++++++++++++++++++++++++++++++++++ 2 files changed, 106 insertions(+) create mode 100644 tests/__init__.py create mode 100644 tests/test_room_geometry.py diff --git a/tests/__init__.py b/tests/__init__.py new file mode 100644 index 0000000..c762008 --- /dev/null +++ b/tests/__init__.py @@ -0,0 +1 @@ +"""Tests for the custom component.""" diff --git a/tests/test_room_geometry.py b/tests/test_room_geometry.py new file mode 100644 index 0000000..95590cb --- /dev/null +++ b/tests/test_room_geometry.py @@ -0,0 +1,105 @@ +"""Tests for Roborock room outline extraction.""" + +from __future__ import annotations + +import importlib.util +from pathlib import Path +import unittest + +_MODULE_PATH = ( + Path(__file__).parents[1] + / "custom_components" + / "roborock_custom_map" + / "room_geometry.py" +) +_SPEC = importlib.util.spec_from_file_location("room_geometry", _MODULE_PATH) +assert _SPEC is not None and _SPEC.loader is not None +_MODULE = importlib.util.module_from_spec(_SPEC) +_SPEC.loader.exec_module(_MODULE) +room_geometry = _MODULE.room_geometry + + +def _raw_map( + rows: list[list[int]], *, left: int = 10, top: int = 20 +) -> bytes: + width = len(rows[0]) + height = len(rows) + map_header = bytearray(20) + map_header[2:4] = (20).to_bytes(2, "little") + + image_header = bytearray(24) + image_header[0:2] = (2).to_bytes(2, "little") + image_header[2:4] = (24).to_bytes(2, "little") + image_header[4:8] = (width * height).to_bytes(4, "little") + image_header[8:12] = top.to_bytes(4, "little") + image_header[12:16] = left.to_bytes(4, "little") + image_header[16:20] = height.to_bytes(4, "little") + image_header[20:24] = width.to_bytes(4, "little") + + return bytes(map_header + image_header + bytes(sum(rows, []))) + + +class RoomGeometryTests(unittest.TestCase): + """Verify room pixel boundaries become card-compatible outlines.""" + + def test_extracts_rectangle_outline(self) -> None: + geometry = room_geometry(_raw_map([[15, 15], [15, 15]]))[1] + + self.assertEqual( + sorted(geometry["outline"]), + [[500, 1000], [500, 1100], [600, 1000], [600, 1100]], + ) + self.assertEqual(geometry["x"], 525) + self.assertEqual(geometry["y"], 1025) + + def test_extracts_concave_outline_without_collinear_points(self) -> None: + rows = [[15] * 20 for _ in range(5)] + rows.extend([[0] * 15 + [15] * 5 for _ in range(15)]) + precise_geometry = room_geometry(_raw_map(rows), "precise")[1] + square_geometry = room_geometry(_raw_map(rows), "square")[1] + + self.assertLessEqual(len(precise_geometry["outline"]), 8) + self.assertIn([500, 1000], precise_geometry["outline"]) + self.assertIn([1500, 2000], precise_geometry["outline"]) + self.assertIn([1250, 1250], precise_geometry["outline"]) + self.assertEqual(len(square_geometry["outline"]), 4) + self.assertGreater( + len(precise_geometry["outline"]), len(square_geometry["outline"]) + ) + + def test_keeps_diagonally_touching_components_separate(self) -> None: + rows = [[15] * 12 + [0] * 18] + rows += [[15] * 12 + [0] * 18 for _ in range(11)] + rows += [[0] * 30 for _ in range(10)] + rows += [[0] * 22 + [15] * 8 for _ in range(8)] + geometry = room_geometry(_raw_map(rows))[1] + + self.assertLessEqual(len(geometry["outline"]), 4) + self.assertEqual(max(point[0] for point in geometry["outline"]), 1100) + self.assertEqual(max(point[1] for point in geometry["outline"]), 1600) + + def test_simplifies_furniture_sized_edge_noise(self) -> None: + rows = [[0] * 30 for _ in range(30)] + for y in range(5, 25): + for x in range(5, 25): + rows[y][x] = 15 + rows[5][10] = 0 + rows[5][11] = 0 + rows[6][10] = 0 + rows[12][5] = 0 + rows[13][5] = 0 + rows[13][6] = 0 + + precise_geometry = room_geometry(_raw_map(rows), "precise")[1] + square_geometry = room_geometry(_raw_map(rows), "square")[1] + + self.assertLessEqual(len(precise_geometry["outline"]), 8) + self.assertEqual(len(square_geometry["outline"]), 4) + + def test_ignores_non_room_pixels_and_malformed_input(self) -> None: + self.assertEqual(room_geometry(_raw_map([[255, 7, 0, 1]])), {}) + self.assertEqual(room_geometry(b"not a roborock map"), {}) + + +if __name__ == "__main__": + unittest.main()