1、参考网址:ROS/Tutorials/WritingServiceClient(python) - ROS Wiki
2、首先,写一个srv文件,这个文件用于定义变量数据类型。在roboware定义非常方便
2.1、首先讲工作哦空间导入进来,即文件-打开工作空间文件,选择功能包(dxy_carless)右击选中新建srv文件,如果没有说明已经新建好了。选中srv右键选择新建文件即可创建:
2.2、点击ROS构建,然后在界面的终端输入catkin_make编译即可
2.3 操作如下,rossrv验证是否可以:如下则成功。
3、编写server文件add_two_ints_server.py
#!/usr/bin/env python
from dxy_carless.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()
4、编写client文件add_two_ints_client.py
#!/usr/bin/env python
import sys
import rospy
from dxy_carless.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))
5、运行