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
171 changes: 164 additions & 7 deletions roborock/devices/traits/b01/q7/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@
Potentially other devices may fall into this category in the future.
"""

import asyncio
import logging
from collections.abc import Callable
from typing import Any

Expand All @@ -16,15 +18,17 @@
SCDeviceCleanParam,
SCWindMapping,
WaterLevelMapping,
WorkModeMapping,
)
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

from .clean_summary import CleanSummaryTrait
from .goto import GotoAction, GotoActionCommand, GotoSnapshot
from .map import MapTrait
from .map_content import MapContentTrait
from .remote import RemoteTrait
Expand All @@ -40,6 +44,18 @@
"Q7RoborockPoint",
]

_LOGGER = logging.getLogger(__name__)

# Emulated goto: a small zone around the target, stopped once the robot is close.
_GOTO_HALF_ZONE_MM = 250
_GOTO_TOLERANCE_MM = 300
# Leaving the dock alone takes ~30 s before the robot moves.
_GOTO_TIMEOUT = 300
_GOTO_RETRY_INTERVAL = 1
# While a goto is active the live map is requested periodically: it carries the
# current pose and keeps the device streaming ``cur_path`` positions.
_GOTO_LIVE_MAP_INTERVAL = 3


class Q7PropertiesApi(Trait):
"""API for interacting with B01 Q7 devices."""
Expand All @@ -60,12 +76,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 +98,141 @@ def __init__(
self.map,
)
self._unsub_map_pushes: Callable[[], None] | None = None
self._unsub_device_pushes: Callable[[], None] | None = None
self._remove_map_listener: Callable[[], None] | None = None
self._work_mode: WorkModeMapping | None = None
self._goto_action: GotoAction | None = None
self._goto_action_remove_listener: Callable[[], None] | None = None
self._goto_track_task: asyncio.Task[None] | None = None
self._goto_command_task: asyncio.Task[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)
if self._remove_map_listener is None:
self._remove_map_listener = self.map_content.add_update_listener(self._goto_source_updated)

async def close(self) -> None:
"""Stop listening for unsolicited map pushes."""
"""Stop listening for unsolicited map frames and device pushes."""
self.cancel_goto()
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
if self._remove_map_listener is not None:
self._remove_map_listener()
self._remove_map_listener = 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)
if push.method == "prop.post" and isinstance(work_mode := push.params.get("work_mode"), int):
self._work_mode = WorkModeMapping.from_code_optional(work_mode)
self._goto_source_updated()

def cancel_goto(self) -> None:
"""Cancel an emulated goto, e.g. because another command replaced it."""
if self._goto_action is not None:
self._goto_action.complete()
self._goto_action = None
if self._goto_action_remove_listener is not None:
self._goto_action_remove_listener()
self._goto_action_remove_listener = None
current_task = asyncio.current_task()
for task_name in ("_goto_track_task", "_goto_command_task"):
if (task := getattr(self, task_name)) is not None:
if task is not current_task:
task.cancel()
setattr(self, task_name, None)

def _goto_snapshot(self) -> GotoSnapshot:
"""Return the latest push-derived state used by an active goto action."""
return GotoSnapshot(position=self.map_content.robot_position, work_mode=self._work_mode)

def _goto_source_updated(self) -> None:
"""Feed the latest position / work mode to the active goto action."""
if self._goto_action is not None:
self._goto_action.update(self._goto_snapshot())

def _goto_action_updated(self, action: GotoAction, command: GotoActionCommand) -> None:
"""Schedule a device command requested by the active goto action."""
if action is not self._goto_action:
return
if command is GotoActionCommand.COMPLETE:
self.cancel_goto()
return
if self._goto_command_task is None:
self._goto_command_task = asyncio.create_task(
self._async_stop_goto_zone(action),
name="roborock_q7_goto_stop",
)

async def _async_stop_goto_zone(self, action: GotoAction) -> None:
"""Stop the goto zone task, leaving the robot where it is."""
current_task = asyncio.current_task()
try:
await self.send(RoborockB01Q7Methods.SET_ZONE_CLEAN, {"ctrl_value": SCDeviceCleanParam.STOP.code})
except RoborockException as err:
_LOGGER.warning("Failed to stop Q7 goto zone task; retrying: %s", err)
await asyncio.sleep(_GOTO_RETRY_INTERVAL)
if action is self._goto_action:
self._goto_command_task = None
action.retry()
return
if action is self._goto_action:
action.complete()
self.cancel_goto()
if self._goto_command_task is current_task:
self._goto_command_task = None

async def _async_track_goto(self, action: GotoAction) -> None:
"""Keep live positions flowing while the goto is active, then apply the safety timeout."""
loop = asyncio.get_running_loop()
deadline = loop.time() + _GOTO_TIMEOUT
try:
while action is self._goto_action and loop.time() < deadline:
try:
await self.map_content.refresh_live()
except RoborockException as err:
_LOGGER.debug("Failed to refresh the Q7 live map during goto: %s", err)
await asyncio.sleep(_GOTO_LIVE_MAP_INTERVAL)
except asyncio.CancelledError:
return
if action is self._goto_action:
action.timeout(self._goto_snapshot())

async def goto_position(self, target: Q7RoborockPoint) -> None:
"""Move to a coordinate (common Roborock coordinates), then stay there.

The firmware has no goto command, so (like the Q10) this starts a small
zone-clean task around ``target`` and stops it once the live position is
within ``_GOTO_TOLERANCE_MM``. Requires :meth:`start` so that live
positions are received. Any other cleaning command cancels the goto.
"""
probe = GotoAction(target, tolerance=_GOTO_TOLERANCE_MM)
if probe.is_near_target(self.map_content.robot_position):
if self._goto_action is not None:
# A previous goto is still driving its zone elsewhere: stop it here.
self.cancel_goto()
await self.send(RoborockB01Q7Methods.SET_ZONE_CLEAN, {"ctrl_value": SCDeviceCleanParam.STOP.code})
return

await self.clean_zone(
Q7RoborockPoint(x=target.x - _GOTO_HALF_ZONE_MM, y=target.y - _GOTO_HALF_ZONE_MM),

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Priority 2 (Lifecycle & State Management): Stop an active goto zone task when a new goto_position target is already within tolerance

If a caller invokes goto_position(target_b) while an earlier goto_position(target_a) is still running and the robot happens to be within _GOTO_TOLERANCE_MM of target_b, returning early here leaves the previous goto action and its 50×50 cm zone-clean task around target_a running (driving the robot away from target_b).

On Q10 (VacuumTrait.goto_position), this case cancels the active goto and stops/pauses the owned task before returning. Doing the same here ensures the robot stays at target_b:

Suggested change
Q7RoborockPoint(x=target.x - _GOTO_HALF_ZONE_MM, y=target.y - _GOTO_HALF_ZONE_MM),
if probe.is_near_target(self.map_content.robot_position):
if self._goto_action is not None:
self.cancel_goto()
await self.send(RoborockB01Q7Methods.SET_ZONE_CLEAN, {"ctrl_value": SCDeviceCleanParam.STOP.code})
return

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done in 54f38a2: if a goto is still active and the new target is already within tolerance, the previous goto is cancelled and its zone task stopped. Covered by test_q7_goto_new_target_already_reached_stops_previous_goto.

Q7RoborockPoint(x=target.x + _GOTO_HALF_ZONE_MM, y=target.y + _GOTO_HALF_ZONE_MM),
)
action = probe
self._goto_action = action
self._goto_action_remove_listener = action.add_update_listener(
lambda command: self._goto_action_updated(action, command)
)
self._goto_track_task = asyncio.create_task(self._async_track_goto(action), name="roborock_q7_goto_track")
action.update(self._goto_snapshot())

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 @@ -185,6 +326,7 @@ async def start_clean(self) -> None:
"room_ids": [],
},
)
self.cancel_goto()

async def clean_segments(self, segment_ids: list[int]) -> None:
"""Start segment cleaning for the given ids (Q7 uses room ids)."""
Expand All @@ -196,6 +338,7 @@ async def clean_segments(self, segment_ids: list[int]) -> None:
"room_ids": segment_ids,
},
)
self.cancel_goto()

async def clean_zone(self, first_corner: Q7RoborockPoint, second_corner: Q7RoborockPoint) -> None:
"""Clean one rectangular zone given two opposite corners in common Roborock coordinates."""
Expand Down Expand Up @@ -223,6 +366,15 @@ async def clean_zones(self, zones: list[tuple[Q7RoborockPoint, Q7RoborockPoint]]
await self.send(RoborockB01Q7Methods.SET_PREFERENCE_TYPE, {"prefer_type": CleanTaskTypeMapping.AREA.code})
await self.send(RoborockB01Q7Methods.SET_ZONE_POINTS, {"zone_points": zone_points})
await self.send(RoborockB01Q7Methods.SET_ZONE_CLEAN, {"ctrl_value": SCDeviceCleanParam.START.code})
self.cancel_goto()

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."""
Expand All @@ -234,6 +386,7 @@ async def pause_clean(self) -> None:
"room_ids": [],
},
)
self.cancel_goto()

async def stop_clean(self) -> None:
"""Stop cleaning."""
Expand All @@ -245,13 +398,15 @@ async def stop_clean(self) -> None:
"room_ids": [],
},
)
self.cancel_goto()

async def return_to_dock(self) -> None:
"""Return to dock."""
await self.send(
command=RoborockB01Q7Methods.START_RECHARGE,
params={},
)
self.cancel_goto()

async def find_me(self) -> None:
"""Locate the robot."""
Expand All @@ -270,6 +425,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 +435,7 @@ def create(
return Q7PropertiesApi(
rpc_channel=rpc_channel,
map_rpc_channel=map_rpc_channel,
push_channel=push_channel,
device=device,
product=product,
)
Loading
Loading