Ask Your Question
4

topic name inside the callback

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

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 imagelucasw ( 2014-07-10 22:44:36 -0600 )edit

1 Answer

Sort by ยป oldest newest most voted
3

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

CatherineH 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 imagelucasw ( 2015-06-15 08:03:58 -0600 )edit

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account.

Add Answer

Question Tools

Stats

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

Seen: 2,678 times

Last updated: Mar 05 '13