Skip to content

Commit 00401de

Browse files
committed
feat: add Q7 goto position
Add `Q7PropertiesApi.goto_position`. The Q7 firmware has no goto command, so (like the Q10) it is emulated with a small zone-clean task around the target that is stopped once the live position is within 30 cm, leaving the robot there. A `GotoAction` state machine decides when to stop, based on the robot position and the `work_mode` reported in device pushes: - near the target while the zone task runs: stop the task; - the zone finished and the robot heads home (`PLAN_AREA_GO_HOME`) before a close position arrived: stop, since it already reached the target; - the zone task ended or was replaced any other way: complete silently. While a goto is active the live map is requested every 3 s, because `cur_path` pushes are not always streamed. A 300 s safety timeout stops a zone task that is still running. Any other cleaning command cancels the goto.
1 parent 0c1d76c commit 00401de

3 files changed

Lines changed: 480 additions & 0 deletions

File tree

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

Lines changed: 136 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,8 @@
33
Potentially other devices may fall into this category in the future.
44
"""
55

6+
import asyncio
7+
import logging
68
from collections.abc import Callable
79
from typing import Any
810

@@ -16,6 +18,7 @@
1618
SCDeviceCleanParam,
1719
SCWindMapping,
1820
WaterLevelMapping,
21+
WorkModeMapping,
1922
)
2023
from roborock.devices.rpc.b01_q7_channel import Q7MapRpcChannel, Q7PushChannel, Q7RpcChannel
2124
from roborock.devices.traits import Trait
@@ -25,6 +28,7 @@
2528
from roborock.roborock_typing import RoborockB01Q7Methods
2629

2730
from .clean_summary import CleanSummaryTrait
31+
from .goto import GotoAction, GotoActionCommand, GotoSnapshot
2832
from .map import MapTrait
2933
from .map_content import MapContentTrait
3034
from .remote import RemoteTrait
@@ -40,6 +44,18 @@
4044
"Q7RoborockPoint",
4145
]
4246

47+
_LOGGER = logging.getLogger(__name__)
48+
49+
# Emulated goto: a small zone around the target, stopped once the robot is close.
50+
_GOTO_HALF_ZONE_MM = 250
51+
_GOTO_TOLERANCE_MM = 300
52+
# Leaving the dock alone takes ~30 s before the robot moves.
53+
_GOTO_TIMEOUT = 300
54+
_GOTO_RETRY_INTERVAL = 1
55+
# While a goto is active the live map is requested periodically: it carries the
56+
# current pose and keeps the device streaming ``cur_path`` positions.
57+
_GOTO_LIVE_MAP_INTERVAL = 3
58+
4359

4460
class Q7PropertiesApi(Trait):
4561
"""API for interacting with B01 Q7 devices."""
@@ -83,26 +99,140 @@ def __init__(
8399
)
84100
self._unsub_map_pushes: Callable[[], None] | None = None
85101
self._unsub_device_pushes: Callable[[], None] | None = None
102+
self._remove_map_listener: Callable[[], None] | None = None
103+
self._work_mode: WorkModeMapping | None = None
104+
self._goto_action: GotoAction | None = None
105+
self._goto_action_remove_listener: Callable[[], None] | None = None
106+
self._goto_track_task: asyncio.Task[None] | None = None
107+
self._goto_command_task: asyncio.Task[None] | None = None
86108

87109
async def start(self) -> None:
88110
"""Start listening for unsolicited map frames and device pushes."""
89111
if self._unsub_map_pushes is None:
90112
self._unsub_map_pushes = await self._map_rpc_channel.subscribe_map_pushes(self.map_content.update_from_push)
91113
if self._unsub_device_pushes is None:
92114
self._unsub_device_pushes = await self._push_channel.subscribe_device_pushes(self._handle_device_push)
115+
if self._remove_map_listener is None:
116+
self._remove_map_listener = self.map_content.add_update_listener(self._goto_source_updated)
93117

94118
async def close(self) -> None:
95119
"""Stop listening for unsolicited map frames and device pushes."""
120+
self.cancel_goto()
96121
if self._unsub_map_pushes is not None:
97122
self._unsub_map_pushes()
98123
self._unsub_map_pushes = None
99124
if self._unsub_device_pushes is not None:
100125
self._unsub_device_pushes()
101126
self._unsub_device_pushes = None
127+
if self._remove_map_listener is not None:
128+
self._remove_map_listener()
129+
self._remove_map_listener = None
102130

103131
def _handle_device_push(self, push: Q7DevicePush) -> None:
104132
"""Route an unsolicited device push to the state that depends on it."""
105133
self.map_content.update_from_device_push(push)
134+
if push.method == "prop.post" and isinstance(work_mode := push.params.get("work_mode"), int):
135+
self._work_mode = WorkModeMapping.from_code_optional(work_mode)
136+
self._goto_source_updated()
137+
138+
def cancel_goto(self) -> None:
139+
"""Cancel an emulated goto, e.g. because another command replaced it."""
140+
if self._goto_action is not None:
141+
self._goto_action.complete()
142+
self._goto_action = None
143+
if self._goto_action_remove_listener is not None:
144+
self._goto_action_remove_listener()
145+
self._goto_action_remove_listener = None
146+
current_task = asyncio.current_task()
147+
for task_name in ("_goto_track_task", "_goto_command_task"):
148+
if (task := getattr(self, task_name)) is not None:
149+
if task is not current_task:
150+
task.cancel()
151+
setattr(self, task_name, None)
152+
153+
def _goto_snapshot(self) -> GotoSnapshot:
154+
"""Return the latest push-derived state used by an active goto action."""
155+
return GotoSnapshot(position=self.map_content.robot_position, work_mode=self._work_mode)
156+
157+
def _goto_source_updated(self) -> None:
158+
"""Feed the latest position / work mode to the active goto action."""
159+
if self._goto_action is not None:
160+
self._goto_action.update(self._goto_snapshot())
161+
162+
def _goto_action_updated(self, action: GotoAction, command: GotoActionCommand) -> None:
163+
"""Schedule a device command requested by the active goto action."""
164+
if action is not self._goto_action:
165+
return
166+
if command is GotoActionCommand.COMPLETE:
167+
self.cancel_goto()
168+
return
169+
if self._goto_command_task is None:
170+
self._goto_command_task = asyncio.create_task(
171+
self._async_stop_goto_zone(action),
172+
name="roborock_q7_goto_stop",
173+
)
174+
175+
async def _async_stop_goto_zone(self, action: GotoAction) -> None:
176+
"""Stop the goto zone task, leaving the robot where it is."""
177+
current_task = asyncio.current_task()
178+
try:
179+
await self.send(RoborockB01Q7Methods.SET_ZONE_CLEAN, {"ctrl_value": SCDeviceCleanParam.STOP.code})
180+
except RoborockException as err:
181+
_LOGGER.warning("Failed to stop Q7 goto zone task; retrying: %s", err)
182+
await asyncio.sleep(_GOTO_RETRY_INTERVAL)
183+
if action is self._goto_action:
184+
self._goto_command_task = None
185+
action.retry()
186+
return
187+
if action is self._goto_action:
188+
action.complete()
189+
self.cancel_goto()
190+
if self._goto_command_task is current_task:
191+
self._goto_command_task = None
192+
193+
async def _async_track_goto(self, action: GotoAction) -> None:
194+
"""Keep live positions flowing while the goto is active, then apply the safety timeout."""
195+
loop = asyncio.get_running_loop()
196+
deadline = loop.time() + _GOTO_TIMEOUT
197+
try:
198+
while action is self._goto_action and loop.time() < deadline:
199+
try:
200+
await self.map_content.refresh_live()
201+
except RoborockException as err:
202+
_LOGGER.debug("Failed to refresh the Q7 live map during goto: %s", err)
203+
await asyncio.sleep(_GOTO_LIVE_MAP_INTERVAL)
204+
except asyncio.CancelledError:
205+
return
206+
if action is self._goto_action:
207+
action.timeout(self._goto_snapshot())
208+
209+
async def goto_position(self, target: Q7RoborockPoint) -> None:
210+
"""Move to a coordinate (common Roborock coordinates), then stay there.
211+
212+
The firmware has no goto command, so (like the Q10) this starts a small
213+
zone-clean task around ``target`` and stops it once the live position is
214+
within ``_GOTO_TOLERANCE_MM``. Requires :meth:`start` so that live
215+
positions are received. Any other cleaning command cancels the goto.
216+
"""
217+
probe = GotoAction(target, tolerance=_GOTO_TOLERANCE_MM)
218+
if probe.is_near_target(self.map_content.robot_position):
219+
if self._goto_action is not None:
220+
# A previous goto is still driving its zone elsewhere: stop it here.
221+
self.cancel_goto()
222+
await self.send(RoborockB01Q7Methods.SET_ZONE_CLEAN, {"ctrl_value": SCDeviceCleanParam.STOP.code})
223+
return
224+
225+
await self.clean_zone(
226+
Q7RoborockPoint(x=target.x - _GOTO_HALF_ZONE_MM, y=target.y - _GOTO_HALF_ZONE_MM),
227+
Q7RoborockPoint(x=target.x + _GOTO_HALF_ZONE_MM, y=target.y + _GOTO_HALF_ZONE_MM),
228+
)
229+
action = probe
230+
self._goto_action = action
231+
self._goto_action_remove_listener = action.add_update_listener(
232+
lambda command: self._goto_action_updated(action, command)
233+
)
234+
self._goto_track_task = asyncio.create_task(self._async_track_goto(action), name="roborock_q7_goto_track")
235+
action.update(self._goto_snapshot())
106236

107237
async def query_values(self, props: list[RoborockB01Props]) -> B01Props | None:
108238
"""Query the device for the values of the given Q7 properties."""
@@ -196,6 +326,7 @@ async def start_clean(self) -> None:
196326
"room_ids": [],
197327
},
198328
)
329+
self.cancel_goto()
199330

200331
async def clean_segments(self, segment_ids: list[int]) -> None:
201332
"""Start segment cleaning for the given ids (Q7 uses room ids)."""
@@ -207,6 +338,7 @@ async def clean_segments(self, segment_ids: list[int]) -> None:
207338
"room_ids": segment_ids,
208339
},
209340
)
341+
self.cancel_goto()
210342

211343
async def clean_zone(self, first_corner: Q7RoborockPoint, second_corner: Q7RoborockPoint) -> None:
212344
"""Clean one rectangular zone given two opposite corners in common Roborock coordinates."""
@@ -234,6 +366,7 @@ async def clean_zones(self, zones: list[tuple[Q7RoborockPoint, Q7RoborockPoint]]
234366
await self.send(RoborockB01Q7Methods.SET_PREFERENCE_TYPE, {"prefer_type": CleanTaskTypeMapping.AREA.code})
235367
await self.send(RoborockB01Q7Methods.SET_ZONE_POINTS, {"zone_points": zone_points})
236368
await self.send(RoborockB01Q7Methods.SET_ZONE_CLEAN, {"ctrl_value": SCDeviceCleanParam.START.code})
369+
self.cancel_goto()
237370

238371
async def set_carpet_turbo(self, enabled: bool) -> None:
239372
"""Enable or disable increased suction on carpets."""
@@ -253,6 +386,7 @@ async def pause_clean(self) -> None:
253386
"room_ids": [],
254387
},
255388
)
389+
self.cancel_goto()
256390

257391
async def stop_clean(self) -> None:
258392
"""Stop cleaning."""
@@ -264,13 +398,15 @@ async def stop_clean(self) -> None:
264398
"room_ids": [],
265399
},
266400
)
401+
self.cancel_goto()
267402

268403
async def return_to_dock(self) -> None:
269404
"""Return to dock."""
270405
await self.send(
271406
command=RoborockB01Q7Methods.START_RECHARGE,
272407
params={},
273408
)
409+
self.cancel_goto()
274410

275411
async def find_me(self) -> None:
276412
"""Locate the robot."""
Lines changed: 135 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,135 @@
1+
"""State management for an emulated Q7 goto action.
2+
3+
The Q7 firmware has no "go to point" command, so a goto is emulated (like on the
4+
Q10) with a small zone-clean task around the target that is stopped once the
5+
robot gets close enough.
6+
"""
7+
8+
import logging
9+
from collections.abc import Callable
10+
from dataclasses import dataclass
11+
from enum import StrEnum
12+
from math import hypot
13+
14+
from roborock.callbacks import CallbackList
15+
from roborock.data.b01_q7.b01_q7_code_mappings import WorkModeMapping
16+
from roborock.data.b01_q7.b01_q7_containers import Q7RoborockPoint
17+
18+
_LOGGER = logging.getLogger(__name__)
19+
20+
# ``work_mode`` reported while a zone-clean task is running (verified on a Q7 sc05).
21+
_ZONE_WORK_MODE = WorkModeMapping.PLAN_AREA
22+
# Reported once the zone is done and the robot heads home: it already reached the target.
23+
_ZONE_DONE_WORK_MODE = WorkModeMapping.PLAN_AREA_GO_HOME
24+
25+
26+
class GotoActionCommand(StrEnum):
27+
"""A command requested by a Q7 goto action."""
28+
29+
STOP = "stop"
30+
COMPLETE = "complete"
31+
32+
33+
@dataclass(frozen=True)
34+
class GotoSnapshot:
35+
"""Device state needed to advance a goto action."""
36+
37+
position: Q7RoborockPoint | None
38+
work_mode: WorkModeMapping | None
39+
40+
41+
class GotoAction:
42+
"""Decide how one emulated goto should react to device updates.
43+
44+
The action owns no tasks and sends no device commands. ``Q7PropertiesApi``
45+
feeds it push-derived snapshots and performs the commands it requests.
46+
"""
47+
48+
def __init__(self, target: Q7RoborockPoint, *, tolerance: int) -> None:
49+
"""Initialize a goto action waiting for its zone task to start."""
50+
self._target = target
51+
self._tolerance = tolerance
52+
self._task_seen = False
53+
self._command_pending = False
54+
self._finished = False
55+
self._timeout_requested = False
56+
self._latest_snapshot: GotoSnapshot | None = None
57+
self._callbacks: CallbackList[GotoActionCommand] = CallbackList(logger=_LOGGER)
58+
59+
def add_update_listener(self, callback: Callable[[GotoActionCommand], None]) -> Callable[[], None]:
60+
"""Register a callback for the commands requested by the action."""
61+
return self._callbacks.add_callback(callback)
62+
63+
def update(self, snapshot: GotoSnapshot) -> None:
64+
"""Process the latest push-derived device state."""
65+
self._latest_snapshot = snapshot
66+
self._evaluate(snapshot)
67+
68+
def retry(self) -> None:
69+
"""Re-evaluate the latest state after a requested command failed."""
70+
if self._finished or self._latest_snapshot is None:
71+
return
72+
self._command_pending = False
73+
if self._timeout_requested:
74+
self._evaluate_timeout(self._latest_snapshot)
75+
else:
76+
self._evaluate(self._latest_snapshot)
77+
78+
def timeout(self, snapshot: GotoSnapshot) -> None:
79+
"""Stop the zone task if it is still running when the safety timeout expires."""
80+
if self._finished:
81+
return
82+
self._latest_snapshot = snapshot
83+
# Remembered so that a retry after a failed in-flight command still applies the timeout.
84+
self._timeout_requested = True
85+
if self._command_pending:
86+
return
87+
self._evaluate_timeout(snapshot)
88+
89+
def complete(self) -> None:
90+
"""Mark the action complete after its requested command succeeds."""
91+
self._finished = True
92+
self._command_pending = False
93+
94+
def is_near_target(self, position: Q7RoborockPoint | None) -> bool:
95+
"""Return whether ``position`` is within the arrival tolerance of the target."""
96+
return (
97+
position is not None and hypot(position.x - self._target.x, position.y - self._target.y) <= self._tolerance
98+
)
99+
100+
def _evaluate(self, snapshot: GotoSnapshot) -> None:
101+
"""Derive the next command from the latest device state."""
102+
if self._finished or self._command_pending:
103+
return
104+
105+
if snapshot.work_mode is _ZONE_WORK_MODE:
106+
self._task_seen = True
107+
elif self._task_seen and snapshot.work_mode is _ZONE_DONE_WORK_MODE:
108+
# The small zone around the target was finished before a close-enough
109+
# position arrived: stop the trip home so the robot stays at the target.
110+
self._emit(GotoActionCommand.STOP)
111+
return
112+
elif self._task_seen:
113+
# The zone task ended (finished, paused, docking) or was replaced.
114+
_LOGGER.debug("Q7 goto zone task ended or was replaced (work_mode=%s)", snapshot.work_mode)
115+
self._emit(GotoActionCommand.COMPLETE)
116+
return
117+
118+
if self._task_seen and self.is_near_target(snapshot.position):
119+
self._emit(GotoActionCommand.STOP)
120+
121+
def _evaluate_timeout(self, snapshot: GotoSnapshot) -> None:
122+
"""Derive the safe command once the safety timeout expired."""
123+
# Still stop the trip home: a STOP requested for it may be the one being retried.
124+
if self._task_seen and snapshot.work_mode in (_ZONE_WORK_MODE, _ZONE_DONE_WORK_MODE):
125+
self._emit(GotoActionCommand.STOP)
126+
else:
127+
self._emit(GotoActionCommand.COMPLETE)
128+
129+
def _emit(self, command: GotoActionCommand) -> None:
130+
"""Publish a requested command once until it is handled."""
131+
if command is GotoActionCommand.COMPLETE:
132+
self._finished = True
133+
else:
134+
self._command_pending = True
135+
self._callbacks(command)

0 commit comments

Comments
 (0)