Rospy的官方教程代码讲解(四)服务

Rospy的官方教程代码讲解(四)服务与参数

  • Rospy的官方教程代码讲解(四)服务与参数
    • 服务
      • 服务端
      • 客户端
    • 参数
  • 日记性质的东西

服务

服务(services)是节点之间通讯的另一种方式。服务允许节点发送请求(request) 并获得一个响应(response)
具体的概念和命令行应用请参见wiki
直接看代码:

服务端

# 首先在AddTwoInts.srv中定义服务,两个输入一个输出
    int64 a
    int64 b
    ---
    int64 sum

然后是服务的代码:

#!/usr/bin/env python
# Software License Agreement (BSD License)
#
# Copyright (c) 2008, Willow Garage, Inc.
# All rights reserved.

## 通过rospy service返回两个整数的和

NAME = 'add_two_ints_server'

# 获取刚刚定义的服务
from rospy_tutorials.srv import *
import rospy 

def 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(NAME)
    s = rospy.Service('add_two_ints', AddTwoInts, add_two_ints)

    # spin() keeps Python from exiting until node is shutdown
    rospy.spin()

if __name__ == "__main__":
    add_two_ints_server()

客户端

#!/usr/bin/env python
# Software License Agreement (BSD License)
#
# Copyright (c) 2008, Willow Garage, Inc.
# All rights reserved.

## 通过rospy service 客户端求两个整数的和

import sys
import os
import rospy

# 获取求和的服务 
from rospy_tutorials.srv import *

## @param x int: 加数
## @param y int: 被加数(这好像是小学时代学的叫法( ̄▽ ̄))
def add_two_ints_client(x, y):

    # 注意:rospy.init_node()在调用服务时不时必须的,因为客户端可以不是一个节点
    # 等待服务上线
    rospy.wait_for_service('add_two_ints')

    try:
        # 制作服务的handle
        add_two_ints = rospy.ServiceProxy('add_two_ints', AddTwoInts)
        print "Requesting %s+%s"%(x, y)
        #调用服务
        resp1 = add_two_ints(x, y)
        resp2 = add_two_ints.call(AddTwoIntsRequest(x, y))

        if not resp1.sum == (x + y):
            raise Exception("test failure, returned sum was %s"%resp1.sum)
        if not resp2.sum == (x + y):
            raise Exception("test failure, returned sum was %s"%resp2.sum)
        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__":

    argv = rospy.myargv()
    if len(argv) == 1:
        import random
        x = random.randint(-50000, 50000)
        y = random.randint(-50000, 50000)
    elif len(argv) == 3:
        try:
            x = int(argv[1])
            y = int(argv[2])
        except:
            print usage()
            sys.exit(1)
    else:
        print usage()
        sys.exit(1)
    print "%s + %s = %s"%(x, y, add_two_ints_client(x, y))

参数

一个参数服务器是一个多变量的、共享的、能够通过网络API进入的词典。节点使用这个服务器在运行时来存储或者检索参数。因为它不是为了高性能的应用而设计的,所以最好用它来存储一些静态的、非二进制的数据,例如初始化时的配置参数。它被设计为全局可见的,因此你的机器能够轻而易举地检索系统的配置状态,并且在必要时进行更改。

参数服务器是基于XMLRPC来实施,然后再ROS Master中运行,这意味着它的API可以在普通的XMLRPC库中访问。

更加详细的解释请参见wiki
参数在rospy中的用法请参见rospy/Overview/Parameter Server

代码:
param_talker.launch

<launch>
  
  <param name="global_example" value="global value" />
  <group ns="foo">
    
    <param name="utterance" value="Hello World" />
    <param name="to_delete" value="Delete Me" />
    
    <group ns="gains">
      <param name="P" value="1.0" />
      <param name="I" value="2.0" />
      <param name="D" value="3.0" />      
    group>
    <node pkg="rospy_tutorials" name="param_talker" type="param_talker.py" output="screen">
      
      <param name="topic_name" value="chatter" />
    node>
  group>
launch>

param_talker.py

#!/usr/bin/env python
# Software License Agreement (BSD License)
#
# Copyright (c) 2008, Willow Garage, Inc.
# All rights reserved.

## 用于展示参数服务发布的消息

import rospy
from std_msgs.msg import String

def param_talker():
    rospy.init_node('param_talker')

    # 从参数服务器获取参数信息:
    # 1) global (/global_example)
    # 2) parent (/foo/utterance)
    # 3) private (/foo/param_talker/topic_name)

    # fetch a /global parameter
    global_example = rospy.get_param("/global_example")
    rospy.loginfo("%s is %s", rospy.resolve_name('/global_example'), global_example)

    # fetch the utterance parameter from our parent namespace
    utterance = rospy.get_param('utterance')
    rospy.loginfo("%s is %s", rospy.resolve_name('utterance'), utterance)

    # fetch topic_name from the ~private namespace
    topic_name = rospy.get_param('~topic_name')
    rospy.loginfo("%s is %s", rospy.resolve_name('~topic_name'), topic_name)

    # fetch a parameter, using 'default_value' if it doesn't exist
    default_param = rospy.get_param('default_param', 'default_value')
    rospy.loginfo('%s is %s', rospy.resolve_name('default_param'), default_param)

    # fetch a group (dictionary) of parameters
    gains = rospy.get_param('gains')
    p, i, d = gains['P'], gains['I'], gains['D']
    rospy.loginfo("gains are %s, %s, %s", p, i, d)    

    # set some parameters
    rospy.loginfo('setting parameters...')
    rospy.set_param('list_of_floats', [1., 2., 3., 4.])
    rospy.set_param('bool_True', True)
    rospy.set_param('~private_bar', 1+2)
    rospy.set_param('to_delete', 'baz')
    rospy.loginfo('...parameters have been set')

    # delete a parameter
    if rospy.has_param('to_delete'):
        rospy.delete_param('to_delete')
        rospy.loginfo("deleted %s parameter"%rospy.resolve_name('to_delete'))
    else:
        rospy.loginfo('parameter %s was already deleted'%rospy.resolve_name('to_delete'))

    # search for a parameter
    param_name = rospy.search_param('global_example')
    rospy.loginfo('found global_example parameter under key: %s'%param_name)

    # publish the value of utterance repeatedly
    pub = rospy.Publisher(topic_name, String, queue_size=10)
    while not rospy.is_shutdown():
        pub.publish(utterance)
        rospy.loginfo(utterance)
        rospy.sleep(1)

if __name__ == '__main__':
    try:
        param_talker()
    except rospy.ROSInterruptException: pass

日记性质的东西

这段时间因为工作又累又烦,假期也没歇过来的感觉。
这篇几乎没怎么写,几乎只是把wiki的东西照搬了过来,介于翻译和转载之间,质量太差了真的很对不起(>_<)
这一段时间不知怎么回事,对生活工作学习都没有实感,仿佛人生如梦幻泡影,我只是走马观花蜻蜓点水的飘过一片片云烟。
最近明显感觉注意力无法集中,体力和记忆力都下降的很厉害,每天都很疲倦很难拿出干劲来做些什么
我到底是真心的想去学习,还是单纯的想要逃避,这个问题我必须找到我能接受的答案。
过去在谎言和自我放逐中变得模糊,未来在彷徨中散发恐慌和恶意。

不知道怎么办呢。。。

I’ve wrote some hidden messages between lines, then I deleted them. This world already has enough shit without me shitting in people’s face. Hopefully more people would get that, and stop shitting around, so the world could be less chaos and shity.

你可能感兴趣的:(ROS,Python,ROS,Python)