ROS Resources: Documentation | Support | Discussion Forum | Index | Service Status | ros @ Robotics Stack Exchange
Ask Your Question
0

How to list the ros2 topics from a c++ node?

asked 2021-05-04 14:50:52 -0500

updated 2021-05-04 14:51:05 -0500

How to list the ros2 topics from a c++ node? I am interested in all the topics in the ros2 network. Something equivalent to the commnand line ros2 topic list

I tried the methodrclcpp::Node::get_node_names() but it looks like only shows the topics associated to the current node.

edit retag flag offensive close merge delete

1 Answer

Sort by » oldest newest most voted
4

answered 2021-05-04 16:44:44 -0500

sgvandijk gravatar image

The method to use is get_topic_names_and_types.

That is what ros2 topic list uses, as well as for instance what the RQT topic plugin uses to list the available topics. These are both in Python, but the method is the same in C++.

However, do take into account this comment: https://github.com/ros2/ros2/issues/1...

In general, it can take some time for discovery to happen. That's because we are currently doing "P2P" discovery on the backend, and if you create a Node and call get_topic_names_and_types on it right away, discovery may not have happened yet. It may make sense to add a timeout to get_topic_names_and_types; I'm not sure.

The command-line tools get around this a different way. When you launch any ros2 command-line tool the first time, a daemon is spun up in the background. The daemon then does discovery, and hangs around. The command-line tool then queries the daemon for information. You may want to think about architecting something more like that; currently rapidly creating Nodes doesn't always do the discovery you want (as you discovered)

So if you use the method right at startup you may not get the full results. That may also be what happened for you with get_node_names.

edit flag offensive delete link more

Comments

Thank you, sounds good, I am going to check that and I will return with the result!

Pablo Iñigo Blasco gravatar image Pablo Iñigo Blasco  ( 2021-05-04 16:59:52 -0500 )edit

Marked as correct! Also guys do not forget to spin the node!

Pablo Iñigo Blasco gravatar image Pablo Iñigo Blasco  ( 2021-05-06 10:42:44 -0500 )edit

Question Tools

3 followers

Stats

Asked: 2021-05-04 14:50:52 -0500

Seen: 2,329 times

Last updated: May 04 '21