01-ROS入门-12 自定义srv格式的server与client通信

1. 创建ex4工作区,test_srv 工作包

见Python运行server与client

2. 创建srv文件

cd test_srv | mkdir srv
vim srv/Sum_Mutip.srv

int64[] number
---
int64 sum

3. 修改CMake文件及package文件

vim ~/workspace/src/package_name/package.xml

message_generation
message_runtime

vim ~/workspace/src/package_name/CMakelist

find_package(catkin REQUIRED COMPONENTS  roscpp  rospy  message_generation)
generate_messages(  DEPENDENCIES  std_msgs)
add_service_files(  FILES  Sum_Mutip.srv)

4. 编写server程序

vim ~/workspace/src/package_name/src/add_many_server.py

#!/usr/bin/python

import rospy
from test_srv.srv import *

def f_add(x,y):
    return x+'+'+y

def add_many(req):
    reqnumstr=list(map(str,req.number))
    print('%s = %s'%(reduce(f_add,reqnumstr),sum(req.number)))
    return Sum_MutipResponse(sum(req.number))   

def rossrv_creat():
    rospy.init_node('sum_many_server',anonymous=0)
    ser=rospy.Service('sum_many',Sum_Mutip,add_many)
    print('ready to add many num')
    rospy.spin()


if __name__=='__main__':
    rossrv_creat()

chmod +x ~/workspace/src/package_name/src/add_many_server.py

5. 编写client程序

vim ~/workspace/src/package_name/src/add_many_client.py

#!/usr/bin/python

import rospy
import sys
from test_srv.srv import *

def sum_all(*num):
    rospy.init_node('sum_many_client',anonymous=0)
    rospy.wait_for_service('sum_many')
    try:
        add_many_nums=rospy.ServiceProxy('sum_many',Sum_Mutip)
        resp1=add_many_nums(*num)
        return resp1.sum
    except rospy.ServiceException,e:
        print('error is %s'%e)

def f_add(x,y):
    return x+'+'+y

if __name__== '__main__':
    if len(sys.argv)< 3:
        print('please input 2 more number')
        sys.exit(1)
    else:
        num=sys.argv[1:]
        numstr=reduce(f_add,num)
        numint=list(map(int,num))
    print('request: %s'% numstr)
    print('%s = %s '% (numstr,sum_all(numint)))

chmod +x ~/workspace/src/package_name/src/add_many_client.py

6. 运行程序

rosrun test_srv add_many_server.py
rosrun test_srv add_many_server.py 1,2,4,6,7,8,9,786,23

你可能感兴趣的:(01-ROS入门-12 自定义srv格式的server与client通信)