[ROS2] SubscriberListener for Publisher (peer_subscribe)

asked 2020-09-18 06:58:34 -0500

mehmetkillioglu gravatar image


I am doing an implementation for rosbridge(websockets) and ROS2.

In ROS1, when creating a publisher, subscriber_listener callbacks can be defined, callback functions peer_subscribe and peer_unsubscribe. This way, a publisher can do a setup for data transmission.

Example simplified code in ROS1:

class PublisherWrapper(rospy.SubscribeListener):
    def __init__(self, topic_config, robot):
        self.topic_config = topic_config
        self.robot = robot
        self.pub = rospy.Publisher(name=topic_config.topic,

    def peer_subscribe(self, topic_name, topic_publish, peer_publish):
        # Called if there is a new subscriber for topic.
        # Creates a websocket subscriber, with the callback
        self.robot.subscribe(topic=('/' + self.topic_config.topic), callback=self.callback)

    def peer_unsubscribe(self, topic_name, num_peers):

    def callback(self, msg):
        # When there is a message coming from websocket, publishes them through the topic

So this way, the subscription to the websocket is only done if some node is already listening to this topic.

But as I checked, I couldn't find a way to do this in ROS2. There is PublisherEventCallbacks, but it only contains liveliness and deadline, and I couldn't connect them to this implementation somehow.

By using Node.count_subscribers(topic), I can see if there are subscribers for that specific topic. But it is not feasible to check this for each topic that the node has as publisher. Around 100 publish topics can be in this node, and checking those in a loop seems like unnecessary workload.

So, in a few words, publisher should only start publishing when there is a subscriber.

Is there a better way to implement this? Any suggestions?

Best, Mehmet

edit retag flag offensive close merge delete