15.2 编写Client节点
15.2.1 The Code
在beginner_tutorials包中创建scripts / 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))
不要忘记增加其可执行权限
$ chmod +x scripts/add_two_ints_client.py
15.2.2 The Code Explained
现在,让我们分解代码。调用服务的客户端代码也很简单。对于客户端,您不必调用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块。
Last updated