-
Notifications
You must be signed in to change notification settings - Fork 47
feat: unified ROS2 hri message #416
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
Merged
Changes from 3 commits
Commits
Show all changes
8 commits
Select commit
Hold shift + click to select a range
b138916
feat: add unified ros2 hri message
maciejmajek 361fafc
fix: sample_rate type definition in AudioMessage
maciejmajek 297832d
chore: use uint16 instead of int16 for sample_rate definition
maciejmajek 61b7899
chore: set channels field to uint16
maciejmajek ecba394
fix: update tests
maciejmajek f83138e
fix: circular import
maciejmajek 8e26366
style: update HRIMessage (rai_interfaces) import
maciejmajek 5b6371f
chore: add typing info to to_ros2_dict method of ROS2HRIMessage
maciejmajek 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
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -15,16 +15,21 @@ | |
import threading | ||
import time | ||
import uuid | ||
from typing import Any, Callable, Dict, List, Literal, Optional, Tuple | ||
from typing import Any, Callable, Dict, List, Literal, Optional, Tuple, Union, cast | ||
|
||
import numpy as np | ||
import rclpy | ||
import rclpy.executors | ||
import rclpy.node | ||
import rclpy.time | ||
from cv_bridge import CvBridge | ||
from PIL import Image | ||
from pydub import AudioSegment | ||
from rclpy.duration import Duration | ||
from rclpy.executors import MultiThreadedExecutor | ||
from rclpy.node import Node | ||
from rclpy.qos import QoSProfile | ||
from sensor_msgs.msg import Image as ROS2Image | ||
from tf2_ros import Buffer, LookupException, TransformListener, TransformStamped | ||
|
||
from rai.communication import ( | ||
|
@@ -41,6 +46,10 @@ | |
ROS2TopicAPI, | ||
TopicConfig, | ||
) | ||
from rai_interfaces.msg import HRIMessage as ROS2HRIMessage_ | ||
from rai_interfaces.msg._audio_message import ( | ||
AudioMessage as ROS2HRIMessage__Audio, | ||
) | ||
|
||
|
||
class ROS2ARIMessage(ARIMessage): | ||
|
@@ -200,26 +209,100 @@ class ROS2HRIMessage(HRIMessage): | |
def __init__(self, payload: HRIPayload, message_author: Literal["ai", "human"]): | ||
super().__init__(payload, message_author) | ||
|
||
@classmethod | ||
def from_ros2(cls, msg: Any, message_author: Literal["ai", "human"]): | ||
from rai_interfaces.msg import HRIMessage as ROS2HRIMessage_ | ||
|
||
if not isinstance(msg, ROS2HRIMessage_): | ||
raise ValueError( | ||
"ROS2HRIMessage can only be created from rai_interfaces/msg/HRIMessage" | ||
) | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Why is this not a top level import? If it can be it should be, and the type annotations should utilise it. There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. 8e26366 |
||
|
||
cv_bridge = CvBridge() | ||
images = [ | ||
cv_bridge.imgmsg_to_cv2(img_msg, "rgb8") | ||
for img_msg in cast(List[ROS2Image], msg.images) | ||
] | ||
pil_images = [Image.fromarray(img) for img in images] | ||
audio_segments = [ | ||
AudioSegment( | ||
data=audio_msg.audio, | ||
frame_rate=audio_msg.sample_rate, | ||
sample_width=2, # bytes, int16 | ||
channels=audio_msg.channels, | ||
) | ||
for audio_msg in msg.audios | ||
] | ||
return ROS2HRIMessage( | ||
payload=HRIPayload(text=msg.text, images=pil_images, audios=audio_segments), | ||
message_author=message_author, | ||
) | ||
|
||
def to_ros2_dict(self): | ||
# TODO: This import causes circular import. Fix it. | ||
from rai.tools.ros2.utils import ros2_message_to_dict | ||
|
||
cv_bridge = CvBridge() | ||
assert isinstance(self.payload, HRIPayload) | ||
img_msgs = [ | ||
cv_bridge.cv2_to_imgmsg(np.array(img), "rgb8") | ||
for img in self.payload.images | ||
] | ||
audio_msgs = [ | ||
ROS2HRIMessage__Audio( | ||
audio=audio.raw_data, | ||
sample_rate=audio.frame_rate, | ||
channels=audio.channels, | ||
) | ||
for audio in self.payload.audios | ||
] | ||
|
||
return ros2_message_to_dict( | ||
ROS2HRIMessage_( | ||
text=self.payload.text, | ||
images=img_msgs, | ||
audios=audio_msgs, | ||
) | ||
) | ||
|
||
maciejmajek marked this conversation as resolved.
Show resolved
Hide resolved
|
||
|
||
class ROS2HRIConnector(HRIConnector[ROS2HRIMessage]): | ||
def __init__( | ||
self, | ||
node_name: str = f"rai_ros2_hri_connector_{str(uuid.uuid4())[-12:]}", | ||
targets: List[Tuple[str, TopicConfig]] = [], | ||
sources: List[Tuple[str, TopicConfig]] = [], | ||
targets: List[Union[str, Tuple[str, TopicConfig]]] = [], | ||
sources: List[Union[str, Tuple[str, TopicConfig]]] = [], | ||
): | ||
configured_targets = [target[0] for target in targets] | ||
configured_sources = [source[0] for source in sources] | ||
configured_targets = [ | ||
target[0] if isinstance(target, tuple) else target for target in targets | ||
] | ||
configured_sources = [ | ||
source[0] if isinstance(source, tuple) else source for source in sources | ||
] | ||
|
||
self._configure_publishers(targets) | ||
self._configure_subscribers(sources) | ||
_targets = [ | ||
target | ||
if isinstance(target, tuple) | ||
else (target, TopicConfig(is_subscriber=False)) | ||
for target in targets | ||
] | ||
_sources = [ | ||
source | ||
if isinstance(source, tuple) | ||
else (source, TopicConfig(is_subscriber=True)) | ||
for source in sources | ||
] | ||
maciejmajek marked this conversation as resolved.
Show resolved
Hide resolved
|
||
|
||
super().__init__(configured_targets, configured_sources) | ||
self._node = Node(node_name) | ||
self._topic_api = ConfigurableROS2TopicAPI(self._node) | ||
self._service_api = ROS2ServiceAPI(self._node) | ||
self._actions_api = ROS2ActionAPI(self._node) | ||
|
||
self._configure_publishers(_targets) | ||
self._configure_subscribers(_sources) | ||
|
||
super().__init__(configured_targets, configured_sources) | ||
|
||
self._executor = MultiThreadedExecutor() | ||
self._executor.add_node(self._node) | ||
self._thread = threading.Thread(target=self._executor.spin) | ||
|
@@ -236,7 +319,7 @@ def _configure_subscribers(self, sources: List[Tuple[str, TopicConfig]]): | |
def send_message(self, message: ROS2HRIMessage, target: str, **kwargs): | ||
self._topic_api.publish_configured( | ||
topic=target, | ||
msg_content=message.payload, | ||
msg_content=message.to_ros2_dict(), | ||
) | ||
|
||
def receive_message( | ||
|
@@ -249,16 +332,12 @@ def receive_message( | |
auto_topic_type: bool = True, | ||
**kwargs: Any, | ||
) -> ROS2HRIMessage: | ||
if msg_type != "std_msgs/msg/String": | ||
raise ValueError("ROS2HRIConnector only supports receiving sting messages") | ||
msg = self._topic_api.receive( | ||
topic=source, | ||
timeout_sec=timeout_sec, | ||
msg_type=msg_type, | ||
auto_topic_type=auto_topic_type, | ||
) | ||
payload = HRIPayload(msg.data) | ||
return ROS2HRIMessage(payload=payload, message_author=message_author) | ||
return ROS2HRIMessage.from_ros2(msg, message_author) | ||
|
||
def service_call( | ||
self, message: ROS2HRIMessage, target: str, timeout_sec: float, **kwargs: Any | ||
|
@@ -284,3 +363,10 @@ def terminate_action(self, action_handle: str, **kwargs: Any): | |
raise NotImplementedError( | ||
f"{self.__class__.__name__} doesn't support action calls" | ||
) | ||
|
||
def shutdown(self): | ||
self._executor.shutdown() | ||
self._thread.join() | ||
self._actions_api.shutdown() | ||
self._topic_api.shutdown() | ||
self._node.destroy_node() |
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,19 @@ | ||
# | ||
# Copyright (C) 2024 Robotec.AI | ||
# | ||
# 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. | ||
# | ||
|
||
int16[] audio | ||
uint16 sample_rate | ||
int16 channels |
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,20 @@ | ||
# | ||
# Copyright (C) 2024 Robotec.AI | ||
# | ||
# 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. | ||
# | ||
|
||
std_msgs/Header header | ||
string text | ||
sensor_msgs/Image[] images | ||
rai_interfaces/AudioMessage[] audios |
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
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.