-
Notifications
You must be signed in to change notification settings - Fork 279
Feature: async node #1620
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
christophebedard
merged 8 commits into
ros2:rolling
from
nadavelkabets:feature/async-node
Apr 21, 2026
Merged
Feature: async node #1620
Changes from all commits
Commits
Show all changes
8 commits
Select commit
Hold shift + click to select a range
5be1fa4
Feature: add native asyncio support via AsyncNode
nadavelkabets 54a8b71
Fix: pipe autostart arg for timers, check if node is already destroye…
nadavelkabets 8eabb3c
Extend test suite
nadavelkabets 06b1f11
Improve test timing and wait for dds discovery to prevent flaky behav…
nadavelkabets 073d96e
Improve documentation
nadavelkabets 3724bab
Fix review comments for AsyncNode PR
nadavelkabets 0c146b2
Import AsyncNode only on 3.12+
nadavelkabets 27c27c1
Exclude async modules from line if python version is under 3.12
nadavelkabets File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,111 @@ | ||
| # Copyright 2026 Open Source Robotics Foundation, Inc. | ||
| # | ||
| # Licensed under the Apache License, Version 2.0 (the "License"); | ||
| # you may not use this file except in compliance with the License. | ||
| # You may obtain a copy of the License at | ||
| # | ||
| # http://www.apache.org/licenses/LICENSE-2.0 | ||
| # | ||
| # Unless required by applicable law or agreed to in writing, software | ||
| # distributed under the License is distributed on an "AS IS" BASIS, | ||
| # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
| # See the License for the specific language governing permissions and | ||
| # limitations under the License. | ||
|
|
||
| import asyncio | ||
| from typing import Callable, Dict, Optional, Type | ||
|
|
||
| from rclpy.client import BaseClient | ||
| from rclpy.context import Context | ||
| from rclpy.qos import QoSProfile | ||
| from rclpy.type_support import Srv, SrvRequestT, SrvResponseT | ||
|
|
||
|
|
||
| class AsyncClient(BaseClient[SrvRequestT, SrvResponseT]): | ||
| """ | ||
| A client of a ROS service. | ||
|
|
||
| .. admonition:: Experimental | ||
|
|
||
| This API is experimental. | ||
| """ | ||
|
|
||
| def __init__( | ||
| self, | ||
| context: Context, | ||
| client_impl: object, | ||
| srv_type: Type[Srv[SrvRequestT, SrvResponseT]], | ||
| srv_name: str, | ||
| qos_profile: QoSProfile, | ||
| on_destroy: Callable[['AsyncClient'], None], | ||
| tg: Optional[asyncio.TaskGroup] = None, | ||
| ) -> None: | ||
| super().__init__(context, client_impl, srv_type, srv_name, qos_profile, | ||
| on_destroy=on_destroy) | ||
| self._pending_requests: Dict[int, asyncio.Future] = {} | ||
| self._task: Optional[asyncio.Task] = None | ||
| self._loop: Optional[asyncio.AbstractEventLoop] = None | ||
| self._read_event = asyncio.Event() | ||
| if tg is not None: | ||
| self._task = tg.create_task(self._run()) | ||
|
|
||
| def _on_new_response(self, _num_waiting: int) -> None: | ||
| assert self._loop is not None | ||
| self._loop.call_soon_threadsafe(self._read_event.set) | ||
|
|
||
| async def wait_for_service(self, *, check_interval: float = 0.1) -> None: | ||
| """ | ||
| Wait for a service server to become ready. | ||
|
|
||
| To apply a timeout, wrap the call with ``async with asyncio.timeout()``. | ||
|
|
||
| :param check_interval: Seconds between checks. Defaults to 0.1. | ||
| """ | ||
| while not self.service_is_ready(): | ||
| await asyncio.sleep(check_interval) | ||
|
|
||
| def _destroy(self) -> None: | ||
| if self._task is not None: | ||
| self._task.cancel() | ||
| self.handle.clear_on_new_response_callback() | ||
| for future in self._pending_requests.values(): | ||
| future.cancel() | ||
| super()._destroy() | ||
|
|
||
| async def call(self, request: SrvRequestT) -> SrvResponseT: | ||
| """Send a service request and await the response.""" | ||
| if self._destroyed: | ||
| raise RuntimeError('Calling a destroyed client is forbidden') | ||
| loop = asyncio.get_running_loop() | ||
| future: asyncio.Future[SrvResponseT] = loop.create_future() | ||
| sequence_number = self.handle.send_request(request) | ||
| self._pending_requests[sequence_number] = future | ||
| try: | ||
| return await future | ||
| finally: | ||
| self._pending_requests.pop(sequence_number) | ||
|
|
||
| async def _responses(self): | ||
| """Async generator yielding (header, response) from DDS.""" | ||
| self.handle.set_on_new_response_callback(self._on_new_response) | ||
| while not self._destroyed: | ||
| header_and_response = self.handle.take_response( | ||
| self.srv_type.Response) | ||
| if header_and_response != (None, None): | ||
| yield header_and_response | ||
| else: | ||
| self._read_event.clear() | ||
| await self._read_event.wait() | ||
|
|
||
| async def _run(self) -> None: | ||
| """DDS bridge response loop for clients.""" | ||
| self._loop = asyncio.get_running_loop() | ||
| try: | ||
| async for header, response in self._responses(): | ||
| future = self._pending_requests.get( | ||
| header.request_id.sequence_number) | ||
| if future is not None: | ||
| future.set_result(response) | ||
| finally: | ||
| self._task = None | ||
| self.destroy() |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,107 @@ | ||
| # Copyright 2026 Open Source Robotics Foundation, Inc. | ||
| # | ||
| # Licensed under the Apache License, Version 2.0 (the "License"); | ||
| # you may not use this file except in compliance with the License. | ||
| # You may obtain a copy of the License at | ||
| # | ||
| # http://www.apache.org/licenses/LICENSE-2.0 | ||
| # | ||
| # Unless required by applicable law or agreed to in writing, software | ||
| # distributed under the License is distributed on an "AS IS" BASIS, | ||
| # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
| # See the License for the specific language governing permissions and | ||
| # limitations under the License. | ||
|
|
||
| import asyncio | ||
| from typing import Dict, Optional | ||
|
|
||
| from rclpy.clock import BaseClock, ClockChange, JumpHandle, JumpThreshold, TimeJump | ||
| from rclpy.clock_type import ClockType | ||
| from rclpy.duration import Duration | ||
| from rclpy.exceptions import TimeSourceChangedError | ||
| from rclpy.time import Time | ||
|
|
||
|
|
||
| class AsyncClock(BaseClock): | ||
| """ | ||
| A ROS clock with async ``sleep``. | ||
|
|
||
| .. admonition:: Experimental | ||
|
|
||
| This API is experimental. | ||
| """ | ||
|
|
||
| def __init__(self, *, clock_type: ClockType = ClockType.SYSTEM_TIME) -> None: | ||
| super().__init__(clock_type=clock_type) | ||
| self._pending_sleeps: Dict[asyncio.Future, Optional[Time]] = {} | ||
| self._destroyed = False | ||
|
|
||
| threshold = JumpThreshold( | ||
| min_forward=Duration(nanoseconds=1), | ||
| min_backward=None, | ||
| on_clock_change=True, | ||
| ) | ||
| self._jump_handle: JumpHandle = self.create_jump_callback( | ||
| threshold, post_callback=self._on_jump) | ||
|
|
||
| @staticmethod | ||
| def _resolve_future(future: asyncio.Future) -> None: | ||
| if not future.done(): | ||
| future.set_result(None) | ||
|
|
||
| def _on_jump(self, time_jump: TimeJump) -> None: | ||
| if time_jump.clock_change in ( | ||
| ClockChange.ROS_TIME_ACTIVATED, | ||
| ClockChange.ROS_TIME_DEACTIVATED, | ||
| ): | ||
| for future in self._pending_sleeps: | ||
| if not future.done(): | ||
| future.set_exception(TimeSourceChangedError()) | ||
| elif time_jump.clock_change == ClockChange.ROS_TIME_NO_CHANGE: | ||
| now = self.now() | ||
| for future, target in self._pending_sleeps.items(): | ||
| if target is not None and now >= target: | ||
| self._resolve_future(future) | ||
|
|
||
| def _destroy(self) -> None: | ||
| """Cancel all pending sleeps. Called by AsyncNode.destroy_node().""" | ||
| if self._destroyed: | ||
| return | ||
| self._destroyed = True | ||
| self._jump_handle.unregister() | ||
| for future in self._pending_sleeps: | ||
| future.cancel() | ||
| self.handle.destroy_when_not_in_use() | ||
|
|
||
| async def sleep(self, duration_sec: float) -> None: | ||
| """ | ||
| Sleep for a duration respecting sim time. | ||
|
|
||
| Cancelled on clock destruction. Raises TimeSourceChangedError if ROS | ||
| time is activated or deactivated during the sleep. | ||
| """ | ||
| if self._destroyed: | ||
| raise RuntimeError('Cannot sleep on a destroyed clock') | ||
| duration = Duration(seconds=duration_sec) | ||
| if duration <= Duration(nanoseconds=0): | ||
| await asyncio.sleep(0) | ||
| return | ||
|
|
||
| loop = asyncio.get_running_loop() | ||
| future: asyncio.Future[None] = loop.create_future() | ||
| timer_handle: Optional[asyncio.TimerHandle] = None | ||
| target: Optional[Time] = None | ||
|
|
||
| if self.ros_time_is_active: | ||
| target = self.now() + duration | ||
| else: | ||
| timer_handle = loop.call_later( | ||
| duration_sec, AsyncClock._resolve_future, future) | ||
|
|
||
| self._pending_sleeps[future] = target | ||
| try: | ||
| await future | ||
| finally: | ||
| self._pending_sleeps.pop(future) | ||
| if timer_handle is not None: | ||
| timer_handle.cancel() | ||
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.