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

topic name inside the callback

asked 2013-03-04 23:50:57 -0500

this post is marked as community wiki

This post is a wiki. Anyone with karma >75 is welcome to improve it.

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

edit retag flag offensive close merge delete

Comments

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.

lucasw gravatar image lucasw  ( 2014-07-10 22:44:36 -0500 )edit

1 Answer

Sort by ยป oldest newest most voted
3

answered 2015-05-07 12:53:02 -0500

CatherineH gravatar image

updated 2020-10-12 16:30:28 -0500

lucasw gravatar image

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.

edit flag offensive delete link more

Comments

2

The answer here has the C++ equivalent (more complicated using boost::bind) http://answers.ros.org/question/63991...

lucasw gravatar image lucasw  ( 2015-06-15 08:03:58 -0500 )edit

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?

afar gravatar image afar  ( 2020-10-13 07:18:42 -0500 )edit

Question Tools

Stats

Asked: 2013-03-04 23:50:57 -0500

Seen: 5,780 times

Last updated: Oct 12 '20