ROS Resources: Documentation | Support | Discussion Forum | Index | Service Status | Q&A
Ask Your Question

Generic Subscriber in ROS2

asked 2020-08-17 05:38:26 -0600

nyxaria gravatar image

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

edit retag flag offensive close merge delete

2 Answers

Sort by ยป oldest newest most voted

answered 2020-08-17 08:16:31 -0600

lukicdarkoo gravatar image

updated 2020-08-17 08:24:15 -0600

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):
        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):

def main(args=None):
    test_subscriber = TestSubscriber()

if __name__ == '__main__':

Test it by running e.g.:

ros2 topic pub /topic_name std_msgs/String '{ data: test_value }'
edit flag offensive delete link more


This is awesome, thanks! Such as a shame the C++ api is not there yet.

nyxaria gravatar image nyxaria  ( 2020-08-17 08:22:39 -0600 )edit

answered 2020-08-17 07:25:57 -0600

dawonn_haval gravatar image

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

edit flag offensive delete link more


Thank you!

nyxaria gravatar image nyxaria  ( 2020-08-17 08:22:47 -0600 )edit

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account.

Add Answer

Question Tools

1 follower


Asked: 2020-08-17 05:38:26 -0600

Seen: 1,167 times

Last updated: Aug 17 '20