01-ROS入门-09 Python运行server与client

1 编写srv文件

cd ~/workspace/src/package_name
mkdir srv
roscp rospy_tutorials AddTwoInts.srv srv/Sum_Two.srv

2 更改package.xml文件与CMakeList.txt

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

message_generation
message_runtime

vim ~/workspace/src/package_name/CMakelist

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

3 新建server

vim ~/workspace/src/ex1/src/sum_two_server.py

#!/usr/bin/env python

from ex1.srv import *
import rospy

def handle_sum_two(req):
    print "Returning [%s + %s = %s]"%(req.a, req.b, (req.a + req.b))
    # 貌似是默认的 srvice回调函数的参数中,req.a req.b 是client中传递的数据。不清楚
    return Sum_TwoResponse(req.a + req.b)

def sum_two_server():
    rospy.init_node('sum_two_server')
    #初始化 节点 用节点 发布服务数据
    s = rospy.Service('sum_two', Sum_Two, handle_sum_two)
    # 声明了一个 'sum_two'的服务, 数据类型为Sum_Two, 调用handles_sum_two回调函数
    print "Ready to add two ints."
    rospy.spin()

if __name__ == "__main__":
    sum_two_server()

4 新建client

vim ~/workspace/src/ex1/sum_two_client.py

#!/usr/bin/env python

import sys
import rospy
from ex1.srv import *

def sum_two_client(x, y):
    rospy.wait_for_service('sum_two')
    #等待'sum_two'服务开启 
    try:
        sum_two = rospy.ServiceProxy('sum_two', Sum_Two)
        #服务开启后,从'sum_two'服务 Sum_Two数据类型关联数据
        resp1 = sum_two(x, y)
        #将函数定义成模块,用resp1 调用
        return resp1.sum
        #返回resp1.sum 的值,及sum_two(x,y)函数中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:
    # 当命令行输入的程序 及参数总数为3 里 rosrun exam sum_two_server.py 是一个 后面的数字是两个
        x = int(sys.argv[1])
        #第一个参数给x
        y = int(sys.argv[2])
        第二个参数给y
    else:
        print usage()
        sys.exit(1)
        #如果参数数目不对则退出
    print "Requesting %s+%s"%(x, y)
    print "%s + %s = %s"%(x, y, sum_two_client(x, y))

5 python文件改为执行文件

chmod +x ~/workspace/src/ex1/src/sum_two_server.py
chmod +x ~/workspace/src/ex1/src/sum_two_client.py

6 运行程序

cd ~/workspace/src/ex1/src
catkin_make
rosrun ex1 sum_two_server.py
rosrun ex1 sum_two_client.py

你可能感兴趣的:(01-ROS入门-09 Python运行server与client)