1、编写 Service 节点
1.1 源代码
查看 add_two_ints_server.py 文件:
$ roscd dashgo_tutorials/src
$ cat add_two_ints_server.py
显示:
#!/usr/bin/env python
from dashgo_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()
1.2 代码解释
使用 rospy 编写服务几乎没有什么。 我们使用 init_node()声明节点,然后声明我们的服 务:
s = rospy.Service('add_two_ints', AddTwoInts, handle_add_two_ints)
这用 AddTwoInts 服务类型声明了一个名为 add_two_ints 的新服务。 所有请求都传递给 handle_add_two_ints 函数。 handle_add_two_ints 用 AddTwoIntsRequest 的实例调用并返回 AddTwoIntsResponse 的实例。
就像用户例子一样,rospy.spin()让你的代码退出,直到服务关闭。
2、编写 Client 节点
2.1 源代码
查看 add_two_ints_client.py 文件:
$ roscd dashgo_tutorials/src
$ cat add_two_ints_client.py
显示:
#!/usr/bin/env python
import sys
import rospy
from dashgo_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))
2.2 代码解释
调用服务的客户端代码也很简单。 对于客户端,不必调用 init_node()。 首先调用:
rospy.wait_for_service('add_two_ints')
这是一种方便的方法,可以阻止直到名为 add_two_ints 的服务可用。 接下来我们创建一个 调用服务的句柄:
add_two_ints = rospy.ServiceProxy('add_two_ints', AddTwoInts)
我们可以像使用普通函数一样使用这个句柄,并调用它:
resp1 = add_two_ints(x, y)
return resp1.sum
因为我们已经将服务的类型声明为 AddTwoInts,所以它为您生成 AddTwoIntsRequest 对象 (您可以自由传入)。 返回值是一个 AddTwoIntsResponse 对象。 如果调用失败,可能会 抛出 rospy.ServiceException,因此应该设置适当的 try / except 块。
3、测试 Service 和 Client
3.1 确保 roscore 可用,并运行:
$ roscore
3.2 运行 Service
$ rosrun dashgo_tutorials add_two_ints_server.py
3.3 运行 Client
$ rosrun dashgo_tutorials add_two_ints_client.py 4 5
显示:
Requesting 4+5
4 + 5 = 9