Consider a ROS service server that adds two integers sent by a client. What will be the response if the client sends 3 and 5?
import rospy from beginner_tutorials.srv import AddTwoInts, AddTwoIntsResponse def handle_add_two_ints(req): return AddTwoIntsResponse(req.a + req.b) rospy.init_node('add_two_ints_server') service = rospy.Service('add_two_ints', AddTwoInts, handle_add_two_ints) rospy.spin()
Look at the return statement inside the handler function.
The handler function returns the sum of the two integers, so the server responds with 8 when given 3 and 5.
Which option correctly initializes a ROS service server named 'multiply' that uses the 'MultiplyTwoInts' service type and calls 'handle_multiply' as the handler?
import rospy from beginner_tutorials.srv import MultiplyTwoInts def handle_multiply(req): pass rospy.init_node('multiply_server')
The order is: service name, service type, handler function.
The rospy.Service constructor requires the service name as a string, the service type class, and the handler function in that order.
What error will occur when running this service server code?
import rospy from beginner_tutorials.srv import AddTwoInts, AddTwoIntsResponse def handle_add(req): return req.a + req.b rospy.init_node('add_server') service = rospy.Service('add_two_ints', AddTwoInts, handle_add) rospy.spin()
The handler must return a response object, not a raw value.
The handler returns an int, but ROS expects an AddTwoIntsResponse object. This causes a TypeError at runtime.
A service server keeps a count of how many times it was called. What will be the value of count after three client requests?
import rospy from beginner_tutorials.srv import Empty, EmptyResponse count = 0 def handle_count(req): global count count += 1 return EmptyResponse() rospy.init_node('count_server') service = rospy.Service('count_service', Empty, handle_count) rospy.spin()
Global variables keep their value between calls.
The global variable count increments by 1 each time the handler runs, so after three calls it is 3.
What happens to a ROS service server when rospy.signal_shutdown() is called?
Think about what signal_shutdown does to the node.
Calling rospy.signal_shutdown() triggers a clean shutdown of the node, stopping the service server from accepting new requests.
