33Potentially other devices may fall into this category in the future.
44"""
55
6+ import asyncio
7+ import logging
68from collections .abc import Callable
79from typing import Any
810
1618 SCDeviceCleanParam ,
1719 SCWindMapping ,
1820 WaterLevelMapping ,
21+ WorkModeMapping ,
1922)
2023from roborock .devices .rpc .b01_q7_channel import Q7MapRpcChannel , Q7PushChannel , Q7RpcChannel
2124from roborock .devices .traits import Trait
2528from roborock .roborock_typing import RoborockB01Q7Methods
2629
2730from .clean_summary import CleanSummaryTrait
31+ from .goto import GotoAction , GotoActionCommand , GotoSnapshot
2832from .map import MapTrait
2933from .map_content import MapContentTrait
3034from .remote import RemoteTrait
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
4460class 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."""
0 commit comments