I'm new at ROS and I'm trying to figure out how does the node works with a pyton/C++ code. I have two codes for the same situation:
Use a Xbox Controller to move the turtle in turtlesim
FIRST - Using class python and a while as a main:
#!/usr/bin/env python
import rospy
from geometry_msgs.msg import Twist
from sensor_msgs.msg import Joy
# DEFINING CLASS
class pubSub:
def __init__(self):
# DEFINE VARIABLE TO KEEP LAST VALUE
rospy.init_node('c2t')
self.twt = Twist()
self.hold = Twist()
def callback_function(self,joyData):
self.twt.linear.x = 4*joyData.axes[1]
self.twt.angular.z = 4*joyData.axes[0]
self.hold = self.twt
def assuming_cont(self):
pub = rospy.Publisher('turtle1/cmd_vel', Twist, queue_size=10)
rospy.Subscriber("joy", Joy, self.callback_function, queue_size=10)
pub.publish(self.twt)
ps = pubSub()
while not rospy.is_shutdown():
ps.assuming_cont()
SECOND - Using global variables and a if __name__ == '__main__'
with rospy.spin()
#!/usr/bin/env python
import rospy
from geometry_msgs.msg import Twist
from sensor_msgs.msg import Joy
# FUNCTION - GET JOY VALUES TRANSFORM TO TURTLE MOVE
def joy_to_twist_transform(jData):
twt = Twist()
twt.linear.x = 5*jData.axes[1]
twt.angular.z = 4*jData.axes[0]
pub.publish(twt)
# FUNCTION - START PROCESS
def process():
global pub
pub = rospy.Publisher('turtle1/cmd_vel', Twist, queue_size=10)
sub = rospy.Subscriber("joy", Joy, joy_to_twist_transform, queue_size=1)
rospy.init_node('control_2turtle')
rospy.spin()
# MAIN
if __name__ == '__main__':
try:
process()
except rospy.ROSInterruptException:
pass
My questions are more theoretical:
1 - What I understand about how a node works is: he run the code in a loop until is shutdown. But this does not answer Why can I still save the last value published in a topic (in my head, if I run my code in a loop I start from the beginning everytime)
2 - Why is necessary to keep creating a rospy.Publisher
and rospy.Subscriber
in every loop? it is possible to create those guy one time only?(for example using them into init function in the seconde example)
3 - What is the difference betweenwhile not rospy.is_shutdown():
and if __name__ == '__main__'
with rospy.spin()
?
4 - What is rospy.spin()
? in any documentation says that keeps your node running, but the way I see he stuck the code in that line and keep there only.
If any could give any recommendation to read about those problems I would thanks a lot.