0
$\begingroup$

Rosanswers logo

I am looking to replicate ROS1 behaviour where I could use ShapeShifter to subscribe to any topic, and not have to specify the message type. This code would run in C++.

I have found this Pull Request but it seems nothing has yet come of this.

Does anyone know if this is possible in ROS2 using C++? If not C++, then Python?

Many thanks


Originally posted by nyxaria on ROS Answers with karma: 13 on 2020-08-17

Post score: 1

$\endgroup$

2 Answers 2

0
$\begingroup$

Rosanswers logo

Not completely what are looking for, but here is one way to do in Python. In Python, you can use get_msg_class from ros2topic.api to get the message type and then subscribe to the topic. Here is an example:

import rclpy
from rclpy.node import Node
from ros2topic.api import get_msg_class


class TestSubscriber(Node):
    def __init__(self):
        super().__init__('test_subscriber')
        message_type = get_msg_class(self, '/topic_name', include_hidden_topics=True)
        print('Message type:', message_type)
        self.create_subscription(message_type, '/topic_name', self.on_message_received, 1)

    def on_message_received(self, message):
        print(message)


def main(args=None):
    rclpy.init(args=args)
    test_subscriber = TestSubscriber()
    rclpy.spin(test_subscriber)
    test_subscriber.destroy_node()
    rclpy.shutdown()


if __name__ == '__main__':
    main()

Test it by running e.g.:

ros2 topic pub /topic_name std_msgs/String '{ data: test_value }'

Originally posted by lukicdarkoo with karma: 486 on 2020-08-17

This answer was ACCEPTED on the original site

Post score: 2


Original comments

Comment by nyxaria on 2020-08-17:
This is awesome, thanks! Such as a shame the C++ api is not there yet.

$\endgroup$
0
$\begingroup$

Rosanswers logo

Take a look at rosbag2, it subscribes to serialized topics regardless of message type.

https://github.com/ros2/rosbag2/blob/master/rosbag2_transport/src/rosbag2_transport/recorder.cpp#L163


Originally posted by dawonn_haval with karma: 103 on 2020-08-17

This answer was NOT ACCEPTED on the original site

Post score: 1


Original comments

Comment by nyxaria on 2020-08-17:
Thank you!

$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.