Writing a Simpler Service and Client (Python)

From Lofaro Lab Wiki
Jump to: navigation, search

Close all previous terminals.

1) In a terminal, navigate to the beginner_tutorials folder:

  cd ~/catkin_ws/src/beginner_tutorials

2) Check to see if the srv or msg folders exist:

  ls

srv will be listed on the terminal if it exists.

3) If the srv or msg folders exist, use Home Folder and delete either or both folders.

4) Re-create the folder srv:

  mkdir srv

5) Re-create the folder msg:

  mkdir msg

5) Make the following file:

  roscp rospy_tutorials AddTwoInts.srv srv/AddTwoInts.srv

This should create the file AddTwoInts.srv in the srv folder.

6) Create the following file:

  echo "int64 num" > msg/Num.msg

This creates a copy of int64 in the msg folder and names it Num.msg

Writing a Service Node

1) Navigate to the beginner_tutorials folder:

  cd ~/catkin_ws/src/beginner_tutorials

2) Create the file add_two_ints_server.py:

  gedit scripts/add_two_ints_server.py

Inside the editor, copy and paste the following:

  #!/usr/bin/env python
   
   from beginner_tutorials.srv import *
   import rospy
   
   def handle_add_two_ints(req):
       print "Returning [%s + %s = %s]"%(req.a, req.b, (req.a + req.b))
       return AddTwoIntsResponse(req.a + req.b)
   
   def add_two_ints_server():
       rospy.init_node('add_two_ints_server')
       s = rospy.Service('add_two_ints', AddTwoInts, handle_add_two_ints)
       print "Ready to add two ints."
       rospy.spin()
   
   if __name__ == "__main__":
       add_two_ints_server()

Save the file and close the editor. For information on the code, see this link

3) Make the file executable:

chmod +x scripts/add_two_ints_server.py

Writing a Client Node

1) Navigate to the beginner_tutorials folder:

  cd ~/catkin_ws/src/beginner_tutorials

2) Create the file add_two_ints_client.py:

  gedit scripts/add_two_ints_client.py

Inside the editor, copy and paste the following:

  #!/usr/bin/env python
   
   import sys
   import rospy
   from beginner_tutorials.srv import *
   
   def add_two_ints_client(x, y):
       rospy.wait_for_service('add_two_ints')
       try:
           add_two_ints = rospy.ServiceProxy('add_two_ints', AddTwoInts)
           resp1 = add_two_ints(x, y)
           return resp1.sum
       except rospy.ServiceException, e:
           print "Service call failed: %s"%e
   
   def usage():
       return "%s [x y]"%sys.argv[0]
   
   if __name__ == "__main__":
       if len(sys.argv) == 3:
           x = int(sys.argv[1])
           y = int(sys.argv[2])
       else:
           print usage()
           sys.exit(1)
       print "Requesting %s+%s"%(x, y)
       print "%s + %s = %s"%(x, y, add_two_ints_client(x, y))

Save the file and close the editor. For information on the code, see this link

3) Make the file executable:

chmod +x scripts/add_two_ints_client.py

Building your Nodes

1) Navigate to the catkin workspace and make the package:

cd ~/catkin_ws
catkin_make