Parse list of TopicEndpointInfo to get topic names

asked 2021-11-07 08:04:45 -0500

goxul gravatar image

I am new to ROS2 and am using rclpy to play around. I am running Galactic, on Ubuntu 20.04.

I am trying to get info about the list of Publishers and Subscribers that are publishing to a certain topic. I know that I can directly use the command line package ros2cli but for a research project that I am working on, I am trying to do it this way, via rclpy

I ran the demo talker and listener program in the background, and after that I executed this code:

import time
import rclpy

def main(args=None):

    rclpy.init(args=args)

    node = rclpy.create_node('foo')
    time.sleep(5)

    names = node.get_node_names_and_namespaces()
    print('Node names: {}'.format(names))

    info1 = node.get_publisher_names_and_types_by_node("talker", "")
    print('info: {}'.format(info1))

    info2 = node.get_subscriber_names_and_types_by_node("listener", "")
    print('info2: {}'.format(info2))  

    publishers = node.get_publishers_info_by_topic("/chatter")
    print('Publishers List: {}'.format(publishers))

    subscribers = node.get_subscriptions_info_by_topic("/chatter")
    print('Subscribers List: {}'.format(subscribers))

    count = node.count_publishers("chatter")
    print("Count Publishers: {}".format(count))

    count_sub = node.count_subscribers("chatter")
    print("Count Subscribers: {}".format(count_sub))

    node.destroy_node()
    rclpy.shutdown()

if __name__ == '__main__':
    main()

I got the output as:

1636292789.199286 [0]    python3: using network interface enp5s0 (udp/10.192.46.18) selected arbitrarily from: enp5s0, docker0, enxbaf50f79d9fa
Node names: [('listener', '/'), ('talker', '/'), ('_ros2cli_daemon_0', '/'), ('foo', '/')]
info: [('/chatter', ['std_msgs/msg/String']), ('/parameter_events', ['rcl_interfaces/msg/ParameterEvent']), ('/rosout', ['rcl_interfaces/msg/Log'])]
info2: [('/chatter', ['std_msgs/msg/String'])]
Publishers List: [<rclpy.topic_endpoint_info.TopicEndpointInfo object at 0x7fb2fa5c1450>]
Subscribers List: [<rclpy.topic_endpoint_info.TopicEndpointInfo object at 0x7fb2fa5c1b30>]
Count: 1
Count subscribers: 1

My question is - how do I parse the list of TopicEndpointInfo I've received to get the actual Publishers and Subscribers? Is there a way? Or does a random node not have the permission to perform this operation?

If not this way, is there any way I can use rclpy to obtain the list of Publishers and Subscribers that are associated with a topic, given the topic name?

edit retag flag offensive close merge delete