Note: This tutorial assumes that you have completed the previous tutorials: examining the simple publisher and subscriber.
(!) Please ask about problems and questions regarding this tutorial on answers.ros.org. Don't forget to include in your question the link to this page, the versions of your OS & ROS, and also add appropriate tags.

Writing a Simple Service and Client (Python)

Description: This tutorial covers how to write a service and client node in python.

Tutorial Level: BEGINNER

Next Tutorial: Examining the simple service and client

Writing a Service Node

Here we'll create the service ("add_two_ints_server") node which will receive two ints and return the sum.

Change directory into the beginner_tutorials package, you created in the earlier tutorial, creating a package:

Change directory into the beginner_tutorials package, you created in the earlier tutorial, creating a package:

$ roscd beginner_tutorials

Please make sure you have followed the directions in the previous tutorial for creating the service needed in this tutorial, creating the AddTwoInts.srv (be sure to choose the right version of build tool you're using at the top of wiki page in the link).

The Code

Create the scripts/add_two_ints_server.py file within the beginner_tutorials package and paste the following inside it:

   1 #!/usr/bin/env python
   2 import roslib; roslib.load_manifest('beginner_tutorials')
   3 from beginner_tutorials.srv import *
   4 import rospy
   5 
   6 def handle_add_two_ints(req):
   7     print "Returning [%s + %s = %s]"%(req.a, req.b, (req.a + req.b))
   8     return AddTwoIntsResponse(req.a + req.b)
   9 
  10 def add_two_ints_server():
  11     rospy.init_node('add_two_ints_server')
  12     s = rospy.Service('add_two_ints', AddTwoInts, handle_add_two_ints)
  13     print "Ready to add two ints."
  14     rospy.spin()
  15 
  16 if __name__ == "__main__":
  17     add_two_ints_server()

   1 #!/usr/bin/env python
   2 
   3 from beginner_tutorials.srv import *
   4 import rospy
   5 
   6 def handle_add_two_ints(req):
   7     print "Returning [%s + %s = %s]"%(req.a, req.b, (req.a + req.b))
   8     return AddTwoIntsResponse(req.a + req.b)
   9 
  10 def add_two_ints_server():
  11     rospy.init_node('add_two_ints_server')
  12     s = rospy.Service('add_two_ints', AddTwoInts, handle_add_two_ints)
  13     print "Ready to add two ints."
  14     rospy.spin()
  15 
  16 if __name__ == "__main__":
  17     add_two_ints_server()

Don't forget to make the node executable:

  • chmod +x scripts/add_two_ints_server.py

The Code Explained

Now, let's break the code down.

There's very little to writing a service using rospy. We declare our node using init_node() and then declare our service:

  12     s = rospy.Service('add_two_ints', AddTwoInts, handle_add_two_ints)

This declares a new service named add_two_ints with the AddTwoInts service type. All requests are passed to handle_add_two_ints function. handle_add_two_ints is called with instances of AddTwoIntsRequest and returns instances of AddTwoIntsResponse.

Just like with the subscriber example, rospy.spin() keeps your code from exiting until the service is shutdown.

Writing the Client Node

The Code

Create the scripts/add_two_ints_client.py file within the beginner_tutorials package and paste the following inside it:

   1 #!/usr/bin/env python
   2 
   3 import sys
   4 import rospy
   5 from beginner_tutorials.srv import *
   6 
   7 def add_two_ints_client(x, y):
   8     rospy.wait_for_service('add_two_ints')
   9     try:
  10         add_two_ints = rospy.ServiceProxy('add_two_ints', AddTwoInts)
  11         resp1 = add_two_ints(x, y)
  12         return resp1.sum
  13     except rospy.ServiceException, e:
  14         print "Service call failed: %s"%e
  15 
  16 def usage():
  17     return "%s [x y]"%sys.argv[0]
  18 
  19 if __name__ == "__main__":
  20     if len(sys.argv) == 3:
  21         x = int(sys.argv[1])
  22         y = int(sys.argv[2])
  23     else:
  24         print usage()
  25         sys.exit(1)
  26     print "Requesting %s+%s"%(x, y)
  27     print "%s + %s = %s"%(x, y, add_two_ints_client(x, y))

Don't forget to make the node executable:

$ chmod +x scripts/add_two_ints_client.py

The Code Explained

Now, let's break the code down.

The client code for calling services is also simple. For clients you don't have to call init_node(). We first call:

   8     rospy.wait_for_service('add_two_ints')

This is a convenience method that blocks until the service named add_two_ints is available. Next we create a handle for calling the service:

  10         add_two_ints = rospy.ServiceProxy('add_two_ints', AddTwoInts)

We can use this handle just like a normal function and call it:

  11         resp1 = add_two_ints(x, y)
  12         return resp1.sum

Because we've declared the type of the service to be AddTwoInts, it does the work of generating the AddTwoIntsRequest object for you (you're free to pass in your own instead). The return value is an AddTwoIntsResponse object. If the call fails, a rospy.ServiceException may be thrown, so you should setup the appropriate try/except block.

Building your nodes

We use CMake as our build system and, yes, you have to use it even for Python nodes. This is to make sure that the autogenerated Python code for messages and services is created.

We also use a Makefile for a bit of convenience. roscreate-pkg automatically created a Makefile, so you don't have to edit it.

Now run make:

$ make

Go to your catkin workspace and run catkin_make.

# In your catkin workspace
$ cd ~/catkin_ws
$ catkin_make

Now that you have written a simple service and client, let's examine the simple service and client.

Wiki: ROS/Tutorials/WritingServiceClient(python) (last edited 2017-05-22 20:22:51 by ShaneLoretz)