0
$\begingroup$

Rosanswers logo

Hi, I use callback (python) like:

def callback(self,data):
    print data
    topic = data._connection_header['topic']

this call back is called for more than one subscriber alternatively. I am interested to know which topic is currently calling the callback. I use data._connection_header['topic'] to get the name of the topic. I don't know for some topics I get their name but for some not. Like when callback is invoked for topic /scan I get error like:

[ERROR] [WallTime: 1362483495.362445] bad callback: <bound method Generator.callback of <__main__.Generator object at 0x31435d0>>
Traceback (most recent call last):
  File "/opt/ros/fuerte/lib/python2.7/dist-packages/rospy/topics.py", line 678, in _invoke_callback
    cb(msg)
  File "/home/my_workspace/my_pkg/src/callback.py", line 21, in callback
    topic = data._connection_header['topic']
KeyError: 'topic'

Any Idea? Or is there any other solution for knowing which topic is calling the callback? thanks


Originally posted by safzam on ROS Answers with karma: 111 on 2013-03-05

Post score: 4


Original comments

Comment by lucasw on 2014-07-10:
I just tried this out and the only keys I get are ['message_definition', 'latching', 'md5sum', 'type', 'callerid']. I'm going to have to put the topic information into a text field because topic doesn't work unfortunately.

$\endgroup$

1 Answer 1

0
$\begingroup$

Rosanswers logo

There is no guarantee that the connection header you're trying to use will have a topic, however, you can work around this by passing the topic name to the callback function as an argument when you set up the subscriber.

For example:

def callback(self, data, topic):
    # do something with the topic
    print data

and then when you hook up your subscriber, do it like this:

rospy.Subscriber(my_topic, My_data_type, callback=callback_odom, callback_args=my_topic)

For some reason, passing it as a lambda function, i.e.:

rospy.Subscriber(my_topic, My_data_type, lambda top: callback_odom(top, my_topic))

doesn't work.


Originally posted by CatherineH with karma: 248 on 2015-05-07

This answer was ACCEPTED on the original site

Post score: 3


Original comments

Comment by lucasw on 2015-06-15:
The answer here has the C++ equivalent (more complicated using boost::bind) http://answers.ros.org/question/63991/how-to-make-callback-function-called-by-several-subscriber/

Comment by afar on 2020-10-13:
This is very handy in ROS1 and I always use it. It seems this "callback_argsis" is not available in ROS2 in "create_publisher" method. Do you have any opinion on this?

$\endgroup$

Your Answer

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