Skip to content

Commit b213233

Browse files
committed
fix: offload map parsing to worker thread to prevent event loop blocking
Offload CPU-intensive map parsing and rendering to worker threads via `asyncio.to_thread` to prevent blocking the asyncio event loop. - In `MapContentTrait.refresh()`, offload `self.converter.convert` to `asyncio.to_thread`. - In `HomeTrait.discover_home()`, move cached map parsing to a helper function `_parse_cached_home_map_content` and run it via `asyncio.to_thread`. - Avoid reparsing cached maps in `HomeTrait` when raw bytes are unchanged. Addresses home-assistant/core#182656
1 parent 16606c9 commit b213233

2 files changed

Lines changed: 41 additions & 5 deletions

File tree

‎roborock/devices/traits/v1/home.py‎

Lines changed: 25 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -28,7 +28,7 @@
2828
from roborock.exceptions import RoborockDeviceBusy, RoborockException, RoborockInvalidStatus
2929
from roborock.roborock_typing import RoborockCommand
3030

31-
from .map_content import MapContent, MapContentTrait
31+
from .map_content import MapContent, MapContentConverter, MapContentTrait
3232
from .maps import MapsTrait
3333
from .rooms import RoomsTrait
3434
from .status import StatusTrait
@@ -38,6 +38,24 @@
3838
MAP_SLEEP = 3
3939

4040

41+
def _parse_cached_home_map_content(
42+
map_content_converter: MapContentConverter,
43+
raw_map_content_base64: dict[int, str] | None,
44+
existing_content: dict[int, MapContent] | None = None,
45+
) -> dict[int, MapContent]:
46+
"""Parse base64-encoded cached map contents, reusing already parsed maps when unchanged."""
47+
if not raw_map_content_base64:
48+
return {}
49+
cached_content: dict[int, MapContent] = {}
50+
for k, v in raw_map_content_base64.items():
51+
raw_bytes = base64.b64decode(v)
52+
if existing_content and k in existing_content and existing_content[k].raw_api_response == raw_bytes:
53+
cached_content[k] = existing_content[k]
54+
else:
55+
cached_content[k] = map_content_converter.parse_map_content(raw_bytes)
56+
return cached_content
57+
58+
4159
class HomeTrait(RoborockBase, common.V1TraitMixin, TraitUpdateListener):
4260
"""Trait that represents a full view of the home layout."""
4361

@@ -95,10 +113,12 @@ async def discover_home(self) -> None:
95113
self._home_map_info = device_cache_data.home_map_info
96114
self._discovery_completed = True
97115
try:
98-
self._home_map_content = {
99-
k: self._map_content.converter.parse_map_content(base64.b64decode(v))
100-
for k, v in (device_cache_data.home_map_content_base64 or {}).items()
101-
}
116+
self._home_map_content = await asyncio.to_thread(
117+
_parse_cached_home_map_content,
118+
self._map_content.converter,
119+
device_cache_data.home_map_content_base64,
120+
self._home_map_content,
121+
)
102122
except (ValueError, RoborockException) as ex:
103123
_LOGGER.warning("Failed to parse cached home map content, will re-discover: %s", ex)
104124
self._home_map_content = {}

‎roborock/devices/traits/v1/map_content.py‎

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,14 @@
11
"""Trait for fetching the map content from Roborock devices."""
22

3+
import asyncio
34
import logging
45
from dataclasses import dataclass
56

67
from vacuum_map_parser_base.map_data import MapData
78

89
from roborock.data import RoborockBase
910
from roborock.devices.traits.v1 import common
11+
from roborock.exceptions import RoborockParsingException
1012
from roborock.map.map_parser import MapParser, MapParserConfig
1113
from roborock.roborock_typing import RoborockCommand
1214

@@ -90,3 +92,17 @@ def __init__(self, map_parser_config: MapParserConfig | None = None) -> None:
9092
"""Initialize MapContentTrait."""
9193
super().__init__()
9294
self.converter = MapContentConverter(MapParser(map_parser_config or MapParserConfig()))
95+
96+
async def refresh(self) -> None:
97+
"""Refresh the contents of this trait without blocking the event loop."""
98+
response = await self.rpc_channel.send_command(self.command)
99+
try:
100+
new_data = await asyncio.to_thread(self.converter.convert, response)
101+
except (TypeError, ValueError) as err:
102+
raise RoborockParsingException(
103+
trait_name=type(self).__name__,
104+
command=self.command,
105+
payload=response,
106+
inner_error=err,
107+
) from err
108+
common.merge_trait_values(self, new_data)

0 commit comments

Comments
 (0)