0
$\begingroup$

Rosanswers logo

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.


Originally posted by Pablo Iñigo Blasco on ROS Answers with karma: 2982 on 2021-05-04

Post score: 0

$\endgroup$

1 Answer 1

0
$\begingroup$

Rosanswers logo

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/1057#issuecomment-728012323

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.


Originally posted by sgvandijk with karma: 649 on 2021-05-04

This answer was ACCEPTED on the original site

Post score: 4


Original comments

Comment by Pablo Iñigo Blasco on 2021-05-04:
Thank you, sounds good, I am going to check that and I will return with the result!

Comment by Pablo Iñigo Blasco on 2021-05-06:
Marked as correct! Also guys do not forget to spin the node!

$\endgroup$

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.