Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions roborock/data/b01_q7/b01_q7_containers.py
Original file line number Diff line number Diff line change
Expand Up @@ -117,6 +117,8 @@ class Q7MapListEntry(RoborockBase):

id: int | None = None
cur: bool | None = None
name: str | None = None
"""User-visible map name as shown in the app (e.g. ``"Temporary map"`` for an unsaved map)."""


@dataclass
Expand Down Expand Up @@ -204,6 +206,10 @@ class B01Props(RoborockBase):
serial_number: str | None = None
recommend: Recommend | None = None
add_sweep_status: int | None = None
carpet_turbo: int | None = None
"""Only set when ``carpet_turbo`` is queried directly; a ``privacy`` query fills ``privacy.carpet_turbo``."""
carpet_avoid: int | None = None
"""Only set when ``carpet_avoid`` is queried directly; a ``privacy`` query fills ``privacy.carpet_avoid``."""

@property
def battery(self) -> int | None:
Expand Down
1 change: 1 addition & 0 deletions roborock/devices/device_manager.py
Original file line number Diff line number Diff line change
Expand Up @@ -272,6 +272,7 @@ def device_creator(home_data: HomeData, device: HomeDataDevice, product: HomeDat
device,
rpc_channel=b01_q7_channel,
map_rpc_channel=b01_q7_channel,
push_channel=b01_q7_channel,
)
else:
raise UnsupportedDeviceError(f"Device {device.name} has unsupported B01 model: {product.model}")
Expand Down
21 changes: 20 additions & 1 deletion roborock/devices/rpc/b01_q7_channel.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,9 +15,11 @@
CommandType,
MapKey,
ParamsType,
Q7DevicePush,
Q7RequestMessage,
create_map_key,
create_map_response_assembler,
decode_device_push,
decode_map_payload,
decode_rpc_response,
encode_mqtt_payload,
Expand Down Expand Up @@ -58,6 +60,14 @@ async def subscribe_map_pushes(self, callback: Callable[[bytes], None]) -> Calla
...


class Q7PushChannel(Protocol):
"""Protocol for channels delivering unsolicited Q7 device pushes."""

async def subscribe_device_pushes(self, callback: Callable[[Q7DevicePush], None]) -> Callable[[], None]:
"""Subscribe to ``*.post`` messages the device publishes on its own."""
...


async def _send_command(
mqtt_channel: MqttChannel,
request_message: Q7RequestMessage,
Expand Down Expand Up @@ -155,7 +165,7 @@ def find_response(response_message: RoborockMessage) -> DecodedB01Response | Non
raise


class B01Q7Channel(Channel, Q7RpcChannel, Q7MapRpcChannel):
class B01Q7Channel(Channel, Q7RpcChannel, Q7MapRpcChannel, Q7PushChannel):
"""Unified B01 Q7 channel wrapping MQTT transport."""

def __init__(self, mqtt_channel: MqttChannel, map_key: MapKey) -> None:
Expand Down Expand Up @@ -222,6 +232,15 @@ def on_message(message: RoborockMessage) -> None:

return await self._mqtt_channel.subscribe(on_message)

async def subscribe_device_pushes(self, callback: Callable[[Q7DevicePush], None]) -> Callable[[], None]:
"""Subscribe to unsolicited ``*.post`` messages (property changes, live path, events)."""

def on_message(message: RoborockMessage) -> None:
if (push := decode_device_push(message)) is not None:
callback(push)

return await self._mqtt_channel.subscribe(on_message)


def create_b01_q7_channel(
device: HomeDataDevice,
Expand Down
35 changes: 28 additions & 7 deletions roborock/devices/traits/b01/q7/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,10 +17,10 @@
SCWindMapping,
WaterLevelMapping,
)
from roborock.devices.rpc.b01_q7_channel import Q7MapRpcChannel, Q7RpcChannel
from roborock.devices.rpc.b01_q7_channel import Q7MapRpcChannel, Q7PushChannel, Q7RpcChannel
from roborock.devices.traits import Trait
from roborock.exceptions import RoborockException
from roborock.protocols.b01_q7_protocol import CommandType, ParamsType
from roborock.protocols.b01_q7_protocol import CommandType, ParamsType, Q7DevicePush
from roborock.roborock_message import RoborockB01Props
from roborock.roborock_typing import RoborockB01Q7Methods

Expand Down Expand Up @@ -60,12 +60,14 @@ def __init__(
self,
rpc_channel: Q7RpcChannel,
map_rpc_channel: Q7MapRpcChannel,
push_channel: Q7PushChannel,
device: HomeDataDevice,
product: HomeDataProduct,
) -> None:
"""Initialize the Q7 API."""
self._rpc_channel = rpc_channel
self._map_rpc_channel = map_rpc_channel
self._push_channel = push_channel
self._device = device
self._product = product

Expand All @@ -80,18 +82,27 @@ def __init__(
self.map,
)
self._unsub_map_pushes: Callable[[], None] | None = None
self._unsub_device_pushes: Callable[[], None] | None = None

async def start(self) -> None:
"""Start listening for unsolicited map pushes from the device."""
if self._unsub_map_pushes is not None:
return
self._unsub_map_pushes = await self._map_rpc_channel.subscribe_map_pushes(self.map_content.update_from_push)
"""Start listening for unsolicited map frames and device pushes."""
if self._unsub_map_pushes is None:
self._unsub_map_pushes = await self._map_rpc_channel.subscribe_map_pushes(self.map_content.update_from_push)
if self._unsub_device_pushes is None:
self._unsub_device_pushes = await self._push_channel.subscribe_device_pushes(self._handle_device_push)

async def close(self) -> None:
"""Stop listening for unsolicited map pushes."""
"""Stop listening for unsolicited map frames and device pushes."""
if self._unsub_map_pushes is not None:
self._unsub_map_pushes()
self._unsub_map_pushes = None
if self._unsub_device_pushes is not None:
self._unsub_device_pushes()
self._unsub_device_pushes = None

def _handle_device_push(self, push: Q7DevicePush) -> None:
"""Route an unsolicited device push to the state that depends on it."""
self.map_content.update_from_device_push(push)

async def query_values(self, props: list[RoborockB01Props]) -> B01Props | None:
"""Query the device for the values of the given Q7 properties."""
Expand Down Expand Up @@ -224,6 +235,14 @@ async def clean_zones(self, zones: list[tuple[Q7RoborockPoint, Q7RoborockPoint]]
await self.send(RoborockB01Q7Methods.SET_ZONE_POINTS, {"zone_points": zone_points})
await self.send(RoborockB01Q7Methods.SET_ZONE_CLEAN, {"ctrl_value": SCDeviceCleanParam.START.code})

async def set_carpet_turbo(self, enabled: bool) -> None:
"""Enable or disable increased suction on carpets."""
await self.set_prop(RoborockB01Props.CARPET_TURBO, int(enabled))

async def set_carpet_avoid(self, enabled: bool) -> None:
"""Enable or disable carpet avoidance."""
await self.set_prop(RoborockB01Props.CARPET_AVOID, int(enabled))

async def pause_clean(self) -> None:
"""Pause cleaning."""
await self.send(
Expand Down Expand Up @@ -270,6 +289,7 @@ def create(
device: HomeDataDevice,
rpc_channel: Q7RpcChannel,
map_rpc_channel: Q7MapRpcChannel,
push_channel: Q7PushChannel,
) -> Q7PropertiesApi:
"""Create traits for B01 Q7 devices."""
if device.sn is None or product.model is None:
Expand All @@ -279,6 +299,7 @@ def create(
return Q7PropertiesApi(
rpc_channel=rpc_channel,
map_rpc_channel=map_rpc_channel,
push_channel=push_channel,
device=device,
product=product,
)
66 changes: 63 additions & 3 deletions roborock/devices/traits/b01/q7/map_content.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,15 +15,17 @@
import asyncio
import logging
from dataclasses import dataclass
from typing import Any

from vacuum_map_parser_base.map_data import MapData

from roborock.data import RoborockBase
from roborock.data import Q7RoborockPoint, RoborockBase
from roborock.devices.rpc.b01_q7_channel import Q7MapRpcChannel
from roborock.devices.traits import Trait
from roborock.devices.traits.common import TraitUpdateListener
from roborock.exceptions import RoborockException
from roborock.map.b01_map_parser import B01MapParser, B01MapParserConfig, parse_map_type
from roborock.map.b01_map_parser import ROBOT_WORLD_POSITION, B01MapParser, B01MapParserConfig, parse_map_type
from roborock.protocols.b01_q7_protocol import Q7DevicePush
from roborock.roborock_typing import RoborockB01Q7Methods

from .map import MapTrait
Expand All @@ -50,11 +52,34 @@ class MapContent(RoborockBase):
library to re-parse the map data when needed.
"""

robot_position: Q7RoborockPoint | None = None
"""Latest known robot position in common Roborock coordinates.

Updated from map frames and, while the robot moves, from the live
``cur_path`` pushes the device publishes roughly once per second.
"""

def __repr__(self) -> str:
img = self.image_content
if img and len(img) > _TRUNCATE_LENGTH:
img = img[: _TRUNCATE_LENGTH - 3] + b"..."
return f"MapContent(image_content={img!r}, map_data={self.map_data!r})"
return f"MapContent(image_content={img!r}, map_data={self.map_data!r}, robot_position={self.robot_position!r})"


def latest_position_from_cur_path(cur_path: list[Any]) -> Q7RoborockPoint | None:
"""Return the newest pose of a ``cur_path`` push, or ``None`` if malformed.

The device sends ``[start_index, x, y, phi, kind, (x, y, phi, kind)..., timestamp]``
with world coordinates in meters; ``kind`` is 0 while travelling and 5 while
cleaning.
"""
samples = cur_path[1:-1]
if not samples or len(samples) % 4:
return None
x, y = samples[-4], samples[-3]
if not all(isinstance(value, int | float) and not isinstance(value, bool) for value in (x, y)):
return None
return Q7RoborockPoint.from_world(x, y)


class MapContentTrait(MapContent, Trait, TraitUpdateListener):
Expand Down Expand Up @@ -93,6 +118,24 @@ async def refresh(self) -> None:

self._parse_and_store(raw_payload)

async def refresh_live(self) -> None:
"""Fetch and parse the live map of the current task, including the robot pose.

Unlike :meth:`refresh` (the saved map, which carries no live pose), this
requests the live map (``service.upload_by_maptype`` with map type 0), as the
official app does. Requesting it also makes the device stream ``cur_path``
pushes while it moves (verified on a Q7 sc05: without a live-map request no
``cur_path`` is published), keeping :attr:`robot_position` current about
once per second.
"""
async with self._map_command_lock:
raw_payload = await self._map_rpc_channel.send_map_command(
RoborockB01Q7Methods.UPLOAD_BY_MAPTYPE,
{"map_type": _LIVE_MAP_TYPE},
)

self._parse_and_store(raw_payload)

def update_from_push(self, raw_payload: bytes) -> None:
"""Store an unsolicited SCMap frame pushed by the device during cleaning.

Expand Down Expand Up @@ -132,3 +175,20 @@ def _parse_and_store(self, raw_payload: bytes) -> None:
self.image_content = parsed_data.image_content
self.map_data = parsed_data.map_data
self.raw_api_response = raw_payload
# Saved maps and frames without a fix carry no usable pose: keep the last known one.
if parsed_data.map_data is None:
return
if (pose := parsed_data.map_data.additional_parameters.get(ROBOT_WORLD_POSITION)) is not None:
self.robot_position = Q7RoborockPoint.from_world(*pose)

def update_from_device_push(self, push: Q7DevicePush) -> None:
"""Update the robot position from a live ``cur_path`` push and notify listeners."""
if push.method != "prop.post" or not isinstance(cur_path := push.params.get("cur_path"), list):
return
if (position := latest_position_from_cur_path(cur_path)) is None:
_LOGGER.debug("Ignoring malformed Q7 cur_path push: %s", cur_path)
return
if position == self.robot_position:
return
self.robot_position = position
self._notify_update()
26 changes: 23 additions & 3 deletions roborock/map/b01_map_parser.py
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,9 @@
_FLOOR = 127
_WALL = 128

# ``MapData.additional_parameters`` key holding the valid live robot pose ``(x, y)`` in world meters.
ROBOT_WORLD_POSITION = "robot_world_position"

_B01_DRAWABLES = [
Drawable.CHARGER,
Drawable.NO_GO_AREAS,
Expand Down Expand Up @@ -163,6 +166,21 @@ def to_pixel(self, x: float, y: float) -> tuple[float, float]:
return px, py


def _valid_current_pose(parsed: RobotMap, projector: _WorldToPixel) -> tuple[float, float, float] | None:
"""Return the live robot pose ``(x, y, phi)`` in world meters, if the frame has a valid one.

Frames without a live pose yield ``None``, as do the placeholders the firmware
reports while it has no fix: ``(1100.0, 1100.0)`` (outside the map bounds) and
an exact ``(0.0, 0.0)`` while a task is starting.
"""
if not parsed.HasField("currentPose"):
return None
pose = parsed.currentPose
if (pose.x == 0.0 and pose.y == 0.0) or not projector.in_bounds(pose.x, pose.y):
return None
return pose.x, pose.y, pose.phi


def _place_poses(map_data: MapData, parsed: RobotMap, projector: _WorldToPixel) -> bool:
"""Populate charger, robot position and path from the decoded SCMap."""
has_drawables = False
Expand All @@ -172,9 +190,11 @@ def _place_poses(map_data: MapData, parsed: RobotMap, projector: _WorldToPixel)
map_data.charger = Point(px, py, math.degrees(parsed.chargeStation.phi))
has_drawables = True

if parsed.HasField("currentPose") and projector.in_bounds(parsed.currentPose.x, parsed.currentPose.y):
px, py = projector.to_pixel(parsed.currentPose.x, parsed.currentPose.y)
map_data.vacuum_position = Point(px, py, math.degrees(parsed.currentPose.phi))
if (pose := _valid_current_pose(parsed, projector)) is not None:
x, y, phi = pose
px, py = projector.to_pixel(x, y)
map_data.vacuum_position = Point(px, py, math.degrees(phi))
map_data.additional_parameters[ROBOT_WORLD_POSITION] = (x, y)
has_drawables = True
elif map_data.charger is not None:
# A saved map carries no live pose; show the robot at its dock.
Expand Down
41 changes: 41 additions & 0 deletions roborock/protocols/b01_q7_protocol.py
Original file line number Diff line number Diff line change
Expand Up @@ -90,6 +90,47 @@ def decode_rpc_response(message: RoborockMessage) -> dict[int, Any]:
) from err


@dataclass
class Q7DevicePush:
"""An unsolicited message the device publishes on its own.

Examples observed on a Q7 (sc05): ``prop.post`` with changed properties
(``{"status": 5, "fault": 2110}``, ``{"cur_path": [...]}``) and events such
as ``event.startClean.post``.
"""

method: str
params: dict[str, Any]


def decode_device_push(message: RoborockMessage) -> Q7DevicePush | None:
"""Return the device push carried by ``message``, or ``None`` if it is not one.

Pushes are distinguished from command responses by their ``*.post`` method
and their ``params`` payload (responses carry ``data`` and a ``code``).
"""
if message.protocol != RoborockMessageProtocol.RPC_RESPONSE or message.version != B01_VERSION:
return None
try:
datapoints = decode_rpc_response(message)
except RoborockException:
return None
for value in datapoints.values():
if not isinstance(value, str):
continue
try:
inner = json.loads(value)
except json.JSONDecodeError:
continue
if not isinstance(inner, dict):
continue
method = inner.get("method")
params = inner.get("params")
if isinstance(method, str) and method.endswith(".post") and isinstance(params, dict):
return Q7DevicePush(method=method, params=params)
return None


@dataclass
class MapKey:
"""Data class for holding a B01 map decryption key."""
Expand Down
4 changes: 4 additions & 0 deletions roborock/roborock_message.py
Original file line number Diff line number Diff line change
Expand Up @@ -336,6 +336,10 @@ class RoborockB01Props(StrEnum):
SERIAL_NUMBER = "serial_number"
RECOMMEND = "recommend"
ADD_SWEEP_STATUS = "add_sweep_status"
# Settable individually via prop.set. A direct prop.get returns them top-level;
# they are also reported nested under ``privacy``.
CARPET_TURBO = "carpet_turbo"
CARPET_AVOID = "carpet_avoid"


ROBOROCK_DATA_STATUS_PROTOCOL = [
Expand Down
Loading
Loading