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

[ROS2] How to get all topic names

asked 2021-01-26 04:58:01 -0500

SteveYK gravatar image

In ROS, I can use this syntactic to get all topic names.

ros::master::V_TopicInfo topics;
ros::master::getTopics(topics);

Now, I using ROS2 Foxy.
I wonder know how to get all topic names.
Thanks for help.

edit retag flag offensive close merge delete

2 Answers

Sort by ยป oldest newest most voted
1

answered 2021-11-15 22:46:08 -0500

charlie92 gravatar image

updated 2021-11-17 00:26:36 -0500

The function is called get_topic_names_and_types`. For a more in depth answer go to this almost duplicated question

EDIT:

You'll need also to spin briefly to let the discovery happen and see the topics. For example the code could look like

rclcpp::Rate r(100);
int i = 0;
while (rclcpp::ok() && i < 100) {
  rclcpp::spin_some(this->get_node_base_interface());
  r.sleep();
  i++;
}
// Now you can call the function to get topics
std::map<std::string, std::vector<std::string>> topic_infos = this->get_topic_names_and_types();
for (const auto& topic_it : topic_infos) {
  std::string topic_name = topic_it.first;
  std::vector<std::string> topic_types = topic_it.second;
  // iterate over all topic types
  for (const auto& topic_type : topic_types) 
    RCLCPP_INFO(this->get_logger(), "Topic: %s, type: %s", topic_name.c_str(), topic_type.c_str());
}
edit flag offensive delete link more

Comments

You will see the method by clicking on the link above:

  /// Return a map of existing topic names to list of topic types.
  /**
   * \return a map of existing topic names to list of topic types.
   * \throws std::runtime_error anything that rcl_error can throw
   */
  RCLCPP_PUBLIC
  std::map<std::string, std::vector<std::string>>
  get_topic_names_and_types() const;
osilva gravatar image osilva  ( 2021-11-16 14:40:38 -0500 )edit
0

answered 2021-01-26 09:01:02 -0500

shlokgoel gravatar image

ros2 topic list gives the list of all active topics. Does that not work for you?

edit flag offensive delete link more

Comments

Thanks for reply. I'm sorry to have failed to make myself clear. I need to get topic names in my C++ program, but this command only display in Terminal.

SteveYK gravatar image SteveYK  ( 2021-01-26 19:38:34 -0500 )edit

Question Tools

2 followers

Stats

Asked: 2021-01-26 04:58:01 -0500

Seen: 1,329 times

Last updated: Nov 17 '21