参考:Writing a Simple Service and Client (Python)
首先是用到的add_two_ints/srv路径下的AddTwoInts.srv文件:
int64 a
int64 b
---
int64 sum # 前面是field type,后面是field name
server
#!/usr/bin/env python
import rospy
# 导入srv文件,此处是AddTwoInts.srv
from add_two_ints.srv import *
def add_two_ints():
rospy.init_node('add_two_ints_node') # initialize the node, define the node name
s = rospy.Service('add_two_ints', AddTwoInts, handle_add_two_ints) # define the service name, srv type and handle function
print('ready add two ints:')
# 维持python解释器的运行?
rospy.spin()
def handle_add_two_ints(req):
print('return: %s + %s = %s' % (req.a, req.b, (req.a + req.b)))
return AddTwoIntsResponse(req.a + req.b)
if __name__ == '__main__':
add_two_ints()
client
#!/usr/bin/env python
import sys
import rospy
from add_two_ints.srv import *
def add_two_ints_client(a, b):
rospy.init_node('add_two_ints_client_node', anonymous=True)
# 阻塞,一直到service可用
rospy.wait_for_service('add_two_ints')
try:
# create a handle for calling the service,just like a function
add_two_ints = rospy.ServiceProxy('add_two_ints', AddTwoInts)
# 调用这个'function',返回一个响应体(也就是一个数据结构,由srv文件定义)
resp = add_two_ints(a,b)
# sum是srv文件定义的数据的name
return resp.sum
except rospy.ServiceException,e:
print 'error: %s' % e
if __name__ == '__main__':
if len(sys.argv) == 3:
# 注意:这里需要转类型
a = int(sys.argv[1])
b = int(sys.argv[2])
else:
print sys.argv
sys.exit(1)
print 'request %s + %s' % (a, b)
# 调用函数,此时会与server通信
print '%s + %s = %s' % (a, b, add_two_ints_client(a,b))