Unit_4 Exercise_4_3 launch file doubt

Respected Prof,
I ran the following code before making .launch file

#! /usr/bin/env python

import rospy
from my_custom_srv_msg_pkg.srv import MyCustomServiceMessage, MyCustomServiceMessageResponse # you import the service message python classes generated from my_custom_srv_msg_pkg.srv.
from geometry_msgs.msg import Twist

def my_callback(request):
    rospy.loginfo("The Service move_bb8_in_circle_custom has been called")
    move_circle.linear.x = 0.2
    move_circle.angular.z = 0.2
    
    i = 0
    while i <= request.duration:
        my_pub.publish(move_circle)
        rate.sleep()
        i=i+1
    
    move_circle.linear.x = 0
    move_circle.angular.z = 0
    my_pub.publish(move_circle)

    my_response = MyCustomServiceMessageResponse()
    my_response.success = True
    rospy.loginfo("Finished service move_bb8_in_circle_custom")
    return my_response # the service Response class, in this case MyCustomServiceMessageResponse

rospy.init_node('service_move_bb8_in_circle_custom_server') 
my_service = rospy.Service('/move_bb8_in_circle_custom', MyCustomServiceMessage , my_callback) # create the Service called move_bb8_in_circle_custom with the defined callback
my_pub = rospy.Publisher('/cmd_vel', Twist, queue_size=1)
move_circle = Twist()
rate = rospy.Rate(1)
rospy.loginfo("Service /move_bb8_in_circle_custom Ready")
rospy.spin() # mantain the service open.

Result: The robot moved for the given time, but it didn’t stop after that.
But…When I created .launch file and ran the code again, the robot stopped after the specified amount of time. Would you please tell me why so ?

When you ran it as a script, the publisher latches on to the my_pub = rospy.Publisher(’/cmd_vel’, Twist, queue_size=1), so you would need to update the cmd_vel message so it stops. Once you ran it as a launch file, the service can look at the request.duration to make sure that the movement stays within the specified parameter.

The request.duration is taken from .srv file. So does that mean that, the pythonfile.py without having launchfile.launch will not take the service_message.srv file into consideration ?

It should. I’ll check with your code to see what the issue is

1 Like