Skip to content
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

refactor: internal ros communication #335

Open
wants to merge 26 commits into
base: development
Choose a base branch
from

Conversation

boczekbartek
Copy link
Member

@boczekbartek boczekbartek commented Dec 6, 2024

Purpose

  • Refactors internal ros communication and they way ros2-based tools communicate with the agent.

Proposed Changes

  • replace nodes spinning by the executor/rclpy by callbacks - from my testing this is the only reliable method for waiting on rclpy.Future for nodes that are being span by executor.spin()
  • this allows to remove the dedicated node for tools that needed to spin on futures
  • refactor RaiNode and extract methods to separate classes to improve code clarity
  • improve feedback from ros2 actions by parsing nav2 error codes

Issues

Testing

  • on rosbot-xl demo

Summary by CodeRabbit

  • New Features

    • Added support for transform checking in robot interactions
    • Introduced new tools for robot interfaces and transform retrieval
  • Improvements

    • Enhanced logging for tool execution
    • Improved ROS 2 action and topic handling
    • Updated node discovery and asynchronous future result management
  • Technical Updates

    • Refactored node and tool classes for better organization
    • Updated callback group handling
    • Modified error handling and logging mechanisms

@boczekbartek boczekbartek force-pushed the refactor/ros_communication branch 2 times, most recently from 3a28ad0 to da1e490 Compare December 20, 2024 13:50
@boczekbartek boczekbartek marked this pull request as ready for review December 23, 2024 12:23
@boczekbartek boczekbartek force-pushed the refactor/ros_communication branch from fc74566 to c7974de Compare December 30, 2024 06:50
Copy link
Member

@maciejmajek maciejmajek left a comment

Choose a reason for hiding this comment

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

Tested on rosbot xl demo. Works as intended. Please respond to comments

@boczekbartek boczekbartek force-pushed the refactor/ros_communication branch from 60208a5 to f9da367 Compare January 7, 2025 12:56
@boczekbartek
Copy link
Member Author

@maciejmajek I responded to your comments. Could you check again?

@maciejmajek maciejmajek self-requested a review January 7, 2025 12:58
@boczekbartek
Copy link
Member Author

@coderabbitai full review

Copy link
Contributor

coderabbitai bot commented Jan 7, 2025

Walkthrough

The pull request introduces significant architectural changes to the ROS 2 interaction framework, focusing on improving node management, action handling, and tool integration. The modifications span multiple files, with key updates in node structure, action handling, and discovery mechanisms. The changes enhance the flexibility and robustness of ROS 2 interactions, introducing new helper classes like Ros2ActionsHelper and Ros2TopicsHandler to manage complex ROS 2 operations more effectively.

Changes

File Change Summary
examples/rosbot-xl-demo.py - Removed GetCameraImage tool
- Added Ros2GetRobotInterfaces and GetTransformTool
- Modified allowlist handling
- Added conversion_ratio parameter
src/rai/rai/node.py - Introduced Ros2ActionsHelper and Ros2TopicsHandler classes
- Refactored RaiBaseNode and RaiStateBasedLlmNode
- Enhanced action and topic management
src/rai/rai/tools/ros/native_actions.py - Updated method calls to use public methods
- Added GetTransformInput model
- Modified GetTransformTool default parameters
src/rai/rai/utils/ros.py - Transformed NodeDiscovery from dataclass to standard class
- Added constructor and add_setter method
src/rai/rai/utils/ros_async.py - Added get_future_result function for handling futures
Other files Minor updates to imports, type hints, and method signatures

Sequence Diagram

sequenceDiagram
    participant Node as RaiStateBasedLlmNode
    participant ActionsHelper as Ros2ActionsHelper
    participant TopicsHandler as Ros2TopicsHandler
    participant ROS2 as ROS2 System

    Node->>ActionsHelper: run_action()
    ActionsHelper->>ROS2: Send action goal
    ActionsHelper->>ActionsHelper: Wait for future result
    ActionsHelper-->>Node: Return action result

    Node->>TopicsHandler: get_raw_message_from_topic()
    TopicsHandler->>ROS2: Subscribe to topic
    ROS2-->>TopicsHandler: Receive message
    TopicsHandler-->>Node: Return message
Loading

This sequence diagram illustrates the high-level interaction between the new RaiStateBasedLlmNode, Ros2ActionsHelper, and Ros2TopicsHandler when executing actions and retrieving messages from ROS 2 topics.


Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR. (Beta)
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 5

🧹 Nitpick comments (6)
src/rai/rai/node.py (2)

391-394: Simplify has_subscription method using any

You can simplify the has_subscription method by using a generator expression with any(), making the code more concise and Pythonic.

Apply this diff to update the method:

-def has_subscription(self, topic: str) -> bool:
-    for sub in self.node._subscriptions:
-        if sub.topic == topic:
-            return True
-    return False
+def has_subscription(self, topic: str) -> bool:
+    return any(sub.topic == topic for sub in self.node._subscriptions)
🧰 Tools
🪛 Ruff (0.8.2)

391-394: Use return any(sub.topic == topic for sub in self.node._subscriptions) instead of for loop

Replace with return any(sub.topic == topic for sub in self.node._subscriptions)

(SIM110)


675-677: Remove unnecessary None check on last_subscription_msgs_buffer

The attribute self.topics_handler.last_subscription_msgs_buffer is initialized as an empty dictionary and should not be None. The check if self.topics_handler.last_subscription_msgs_buffer is None is unnecessary and can be removed to simplify the code.

Apply this diff to remove the unnecessary condition:

-        if self.topics_handler.last_subscription_msgs_buffer is None:
-            self.state_dict = state_dict
-            return
src/rai/rai/utils/ros_async.py (1)

21-37: Consider optimizing the future handling implementation.

The implementation could be improved in several ways:

  1. Add early return when future is done to avoid unnecessary sleep.
  2. Make the sleep duration configurable.
  3. Clean up the callback on timeout.

Consider this implementation:

 def get_future_result(
     future: rclpy.task.Future, timeout_sec: float = 5.0
 ) -> Optional[Any]:
     """Replaces rclpy.spin_until_future_complete"""
     result = None
+    sleep_duration = 0.1  # Make this a parameter
 
     def callback(future: rclpy.task.Future) -> None:
         nonlocal result
         result = future.result()
 
     future.add_done_callback(callback)
 
     ts = time.perf_counter()
     while result is None and time.perf_counter() - ts < timeout_sec:
+        if future.done():  # Early return if future is done
+            break
-        time.sleep(0.1)
+        time.sleep(sleep_duration)
+
+    if result is None:  # Clean up callback on timeout
+        future.remove_done_callback(callback)
 
     return result
src/rai/rai/utils/ros_logs.py (1)

77-81: Consider adding timeout parameter for service calls.

The service call is using the default timeout from get_future_result. For better control, consider exposing the timeout parameter.

-        response: Optional[rai_interfaces.srv.StringList.Response] = get_future_result(
-            future
-        )
+        response: Optional[rai_interfaces.srv.StringList.Response] = get_future_result(
+            future,
+            timeout_sec=self.node.get_parameter('service_timeout').value
+        )
examples/rosbot-xl-demo.py (2)

93-93: Consider enhancing collision detection handling.

The collision detection rule is good, but consider adding specific guidance on what actions to take when a collision is detected.

Add more specific rules:

-    - if you detect collision, please stop operation
+    - if you detect collision:
+        1. Immediately stop all motion by canceling running actions
+        2. Publish zero velocity on /cmd_vel topic
+        3. Report collision details and location
+        4. Wait for operator instructions

138-138: Document the purpose of conversion_ratio parameter.

The parameter is declared but its purpose and usage are not documented.

Add a comment explaining the parameter's purpose:

+    # Conversion ratio for transforming between different unit systems (e.g., meters to millimeters)
     node.declare_parameter("conversion_ratio", 1.0)
📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 0d2cbc4 and f9da367.

📒 Files selected for processing (10)
  • examples/rosbot-xl-demo.py (4 hunks)
  • src/rai/rai/agents/tool_runner.py (1 hunks)
  • src/rai/rai/node.py (17 hunks)
  • src/rai/rai/tools/ros/native.py (1 hunks)
  • src/rai/rai/tools/ros/native_actions.py (5 hunks)
  • src/rai/rai/tools/ros/utils.py (3 hunks)
  • src/rai/rai/utils/ros.py (1 hunks)
  • src/rai/rai/utils/ros_async.py (1 hunks)
  • src/rai/rai/utils/ros_logs.py (4 hunks)
  • src/rai_extensions/rai_open_set_vision/rai_open_set_vision/tools/gdino_tools.py (2 hunks)
🧰 Additional context used
🪛 Ruff (0.8.2)
src/rai/rai/node.py

391-394: Use return any(sub.topic == topic for sub in self.node._subscriptions) instead of for loop

Replace with return any(sub.topic == topic for sub in self.node._subscriptions)

(SIM110)

🔇 Additional comments (8)
src/rai/rai/tools/ros/utils.py (1)

161-180: LGTM: Updated get_transform function implementation

The updated implementation of get_transform enhances robustness by adding a timeout and handling asynchronous transform lookup correctly. Resource cleanup with tf_listener.unregister() is appropriately handled.

src/rai/rai/utils/ros_logs.py (1)

59-61: LGTM! Good improvement in constructor signature.

The addition of the callback_group parameter enhances the flexibility of ROS2 service client creation.

examples/rosbot-xl-demo.py (1)

71-71: Good addition of transform verification rule.

The rule to check transforms as a first step improves safety and reliability.

src/rai/rai/agents/tool_runner.py (1)

65-65: LGTM! Enhanced logging improves debugging.

Adding tool arguments to the log message provides better context for debugging tool execution.

src/rai/rai/tools/ros/native_actions.py (2)

144-144: LGTM! Method calls updated to use public interface.

The changes from private methods (_run_action, _is_task_complete, _get_task_result, _cancel_task) to their public counterparts improve the API's clarity and accessibility.

Also applies to: 154-154, 164-164, 174-174


189-191: LGTM! Well-structured input model for transform operations.

The new GetTransformInput model with clear field descriptions and sensible defaults enhances the API's usability.

src/rai/rai/tools/ros/native.py (1)

187-187: LGTM! Consistent callback group usage.

The addition of callback_group parameter to both publisher and timer creation ensures proper callback handling within the same executor group. This is a good practice for ROS2 applications as it provides better control over execution scheduling.

Also applies to: 195-197

src/rai_extensions/rai_open_set_vision/rai_open_set_vision/tools/gdino_tools.py (1)

29-29: Verify compatibility with RaiBaseNode.

The change from RaiAsyncToolsNode to RaiBaseNode suggests a significant architectural shift. While this aligns with the refactoring goals, we should verify that all required async functionality is still available in the base node.

Also applies to: 84-84

✅ Verification successful

Compatibility with RaiBaseNode is verified and safe

The change from RaiAsyncToolsNode to RaiBaseNode is compatible as the tool accesses node functionality through delegation (self.node), and RaiBaseNode provides all necessary Node capabilities through inheritance from rclpy.node.Node. No async-specific functionality from RaiAsyncToolsNode is being used.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Check if RaiBaseNode provides all necessary methods used in GroundingDinoBaseTool
rg -A 5 "class RaiBaseNode" 
rg -A 5 "def (create_client|create_publisher|get_logger|get_parameter)" 

Length of output: 979


Script:

#!/bin/bash
# Check GroundingDinoBaseTool implementation and inheritance
ast-grep --pattern 'class GroundingDinoBaseTool extends RaiBaseNode { $$$ }'

# Search for async patterns and method usage
rg -l "async def" src/rai_extensions/rai_open_set_vision/rai_open_set_vision/tools/gdino_tools.py
rg "(create_client|create_publisher|get_parameter)" src/rai_extensions/rai_open_set_vision/rai_open_set_vision/tools/gdino_tools.py

# Check Node base class
rg "from rclpy.node import Node" src/rai/rai/node.py -A 2

Length of output: 684

src/rai/rai/utils/ros.py Outdated Show resolved Hide resolved
src/rai/rai/utils/ros.py Show resolved Hide resolved
src/rai/rai/node.py Outdated Show resolved Hide resolved
src/rai/rai/node.py Outdated Show resolved Hide resolved
src/rai/rai/tools/ros/native_actions.py Outdated Show resolved Hide resolved
@boczekbartek
Copy link
Member Author

@maciejmajek I have noticed that open-set detection and GetTransform tools were not refactored properly and caused executor problems. Could you test again on your side?

@boczekbartek boczekbartek force-pushed the refactor/ros_communication branch from fff5085 to d91204b Compare January 9, 2025 12:28
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants