How does subscriber works?
In the code below, turtlebot is moved using /turtle1/cmd_vel topic and we get current pose using /turtle1/Pose topic. My question is if we see the code in if __name__ == '__main__': block, we initialise node, declare subscriber and call for publisher function i.e. motion(speed,distance). This code works perfectly fine. I would like to know how does it get current pose values all the time, how is this program executed? Is it like prem-emptive scheduler, something like RTOS systems, just a thought. I would like to know the background logic and working here.
#!/usr/bin/env python
#libaries
import rospy
from turtlesim.msg import Pose
from geometry_msgs.msg import Twist
import math
import time
from std_srvs.srv import Empty
#initialize variables
x = 0
y = 0
z = 0
yaw = 0
#call back function for subscriber
def pose_callback(posedata):
global x,y,z,yaw
x = posedata.x
y = posedata.y
yaw = posedata.theta
#print("Pose CallBack\nx={}\ny={}\nyaw={}".format(posedata.x,posedata.y,posedata.theta))
# publisher function
def motion(speed,distance):
vel_msg = Twist()
# get current location
x0 = x
y0 = y
# set velocities to speed
vel_msg.linear.x = speed
distance_moved = 0
loop_rate = rospy.Rate(10)
# define publisher
vel_publisher = rospy.Publisher("/turtle1/cmd_vel",Twist,queue_size = 10)
while not rospy.is_shutdown():
rospy.loginfo("Turtlesim Moves Forward")
#publish topic = writing to variable
vel_publisher.publish(vel_msg)
loop_rate.sleep()
distance_moved = distance_moved + math.sqrt((x-x0)**2 + (y-y0)**2)
rospy.loginfo(distance_moved)
print(distance_moved)
if not(distance_moved<distance):
print("Reahed")
break
vel_msg.linear.x = 0
vel_msg.linear.y = 0
vel_publisher.publish(vel_msg)
if __name__ == '__main__':
try:
# intialise node, node name
rospy.init_node("my_turtlesim_pose",anonymous=True)
#call subscriber - read values
rospy.Subscriber("/turtle1/pose",Pose,pose_callback)
time.sleep(2)
print ('move: ')
#write values
motion (5.0, 5.0)
time.sleep(2)
print ('start reset: ')
rospy.wait_for_service('reset')
reset_turtle = rospy.ServiceProxy('reset', Empty)
reset_turtle()
print ('end reset: ')
rospy.spin()
except rospy.ROSInterruptException:
rospy.loginfo("Node Terminated")
Please edit your question to provide enough context to reproduce your problem. It's not clear what you mean "we don't call it in publish" and what other things are running on your system? Please take a look at the question guidelines at: https://wiki.ros.org/Support