先进入包里面: roscd beginner_tutorials
在script文件夹下面添加一个文件add_two_ints_server.py:
#!/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()
然后再编译一下:
chmod +x scripts/add_two_ints_server.py
添加一个 Client Node, 文件也放在script下面,命名为add_two_ints_client.py
#!/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))
然后再building一下
# In your catkin workspace
cd ~/catkin_ws
catkin_make
分别再新的terminal里面运行
cd ~/catkin_ws
. devel/setup.bash
rosrun beginner_tutorials add_two_ints_server.py
cd ~/catkin_ws
. devel/setup.bash
rosrun beginner_tutorials add_two_ints_client.py
再在第二个terminal里面运行:
rosrun beginner_tutorials add_two_ints_client.py 4 5