Subscriber callback function with multiple parameters
Hi folks, This is a follow-up to a question about callbacks found at http://answers.ros.org/question/39123/can-someone-explain-callbacks/?comment=39701#comment-39701
I'm using Python to implement a navigation interface between the ROS nav stack and my own motor controllers. I have created a Driver object that subscribes to the 'cmd_vel' topic and receives Twist messages from this topic. My callback function from the subscriber determines motor commands based on the info in each Twist message it receives.
A confusing problem I've found is that I need to hand both the Twist message and the 'self' object to my callback function , so that the callback has access to some global parameters associated with the Driver object. I cannot find a way to pass both pieces of information to the callback function when it's called within the Subscriber command.
Code:
class Driver:
def __init__(self):
# node initialized and constants described here
def subscribe_cmd_vel(self):
rospy.Subscriber("cmd_vel", Twist, self.callback(self))
rospy.spin()
def callback(self, msg):
print "Linear x of Twist message: " + str(msg.linear.x)
# do some calculations with contents of msg
if __name__ == "__main__"
dr = Driver()
dr.subscribe_cmd_vel()
I am consistently only passing the self object to my callback, not the Twist message. When this code hits the print line in the callback function, I get an error saying something like "The Driver object has no 'linear' field.". This means that my msg pointer is being pointed to the self object and my actual Twist message is being lost. Please tell me if you know what mistakes I've made here.
EDIT - SOLUTION =================
By removing the self
parameter and parentheses from the callback invoked in the subscriber, both the message and the self
object were correctly passed to the callback. I was overthinking the process of passing parameters and the significance of parentheses. Thanks to those who answered me below.
=================================
Many thanks,
Khiya