How to get publisher and callback to talk to one another (python)
Hello,
I am trying to get my code (python)to publish a simple sequence in form of a Twist message, and then get the timestamp of when those messages are executed with the callback function. This is somehow not working, can someone please help? Thank you in advance.
The code:
#!/usr/bin/env python
import rospy
from geometry_msgs.msg import Twist, TransformStamped
Times = []
x_pos = []
class CommandEvaluatorNode(object):
def __init__(self):
self.cmd_vel_pub = rospy.Publisher('cmd_vel', Twist, queue_size = 10)
def run_command_tests(self):
r = rospy.Rate(0.8)
twist_sequence = [[1, 1, 1], [2, 2 , 3],[3, 3, 4]]
rospy.loginfo("Publishing first sequence")
for cmd in twist_sequence:
r.sleep()
msg = Twist()
msg.linear.x = cmd[0]
msg.linear.y =cmd[1]
msg.angular.z = cmd[2]
x_pos.append(cmd[0])
self.cmd_vel_pub.publish(msg)
def callback(self, msg):
l = rospy.Rate(0.8)
l.sleep()
time = msg.header.stamp.secs + msg.header.stamp.nsecs * 1e-9
Times.append(time)
def ros_init(self):
rospy.init_node('cmd_evaluator', anonymous=True)
rospy.Subscriber("tf", TransformStamped, self.callback)
if __name__ == '__main__':
rosnode = CommandEvaluatorNode()
rosnode.ros_init()
rosnode.run_command_tests()
Have you tried going through the python publisher/subscriber tutorials yet? Like these
I don't see any reference to rospy.spin() or while rospy.is_not_shutdown() referenced there, so you're only publishing a message once, and only subscribing once.
Also, you don't manually call callbacks. They're executed when a message is received on the topic that they subscribe to.
What are you trying to accomplish with the line
? How are you even getting this to run? You're not initializing the node before instantiating a publisher. Is this the actual code that you're using or is this a "simplified" version? Either way, can you please update your question with the errors that you get?
Hi @rukie , @jayess thank you very much for your answers. I edited the code to showcase the full thing.
The reason why I created this code is to test out short commands on a simulator. This is the reason why there is no reference to rospy.spin() or rospy.is_not_shutdown(). I want to publish a command to the simulator in a Twist() message. Furthermore, I want to subscribe to the tf topic and on the callback part I want to get the timestamp of when that command was sent/received. With the code as of now, my proble is that the callback function doesn't get called. So that I don't get any value for the time. I am very grateful for any ideas on how I could make this work.
There is no guarantee the message from
tf
topic will come in the mean time of executing the rest of the code. What do you think this should work like? You can wait for the message usingrospy.wait_for_message()
function instead of callback.@kump , @rukie thank you for the input. I will have a look at this.