< >
Home » ROS与Python入门教程 » ROS与Python入门教程-actionlib-开发简单的action客户端

ROS与Python入门教程-actionlib-开发简单的action客户端

ROS与Python入门教程-actionlib-开发简单的action客户端

说明

  • 使用SimpleActionClient库创建Python的Fibonacci(斐波那契数列)action客户端
  • 发送目标并获取反馈结果

介绍

代码

#! /usr/bin/env python

import roslib; roslib.load_manifest('actionlib_tutorials')
import rospy

# Brings in the SimpleActionClient
import actionlib

# Brings in the messages used by the fibonacci action, including the
# goal message and the result message.
import actionlib_tutorials.msg

def fibonacci_client():
    # Creates the SimpleActionClient, passing the type of the action
    # (FibonacciAction) to the constructor.
    client = actionlib.SimpleActionClient('fibonacci', actionlib_tutorials.msg.FibonacciAction)

    # Waits until the action server has started up and started
    # listening for goals.
    client.wait_for_server()

    # Creates a goal to send to the action server.
    goal = actionlib_tutorials.msg.FibonacciGoal(order=20)

    # Sends the goal to the action server.
    client.send_goal(goal)

    # Waits for the server to finish performing the action.
    client.wait_for_result()

    # Prints out the result of executing the action
    return client.get_result()  # A FibonacciResult

if __name__ == '__main__':
    try:
        # Initializes a rospy node so that the SimpleActionClient can
        # publish and subscribe over ROS.
        rospy.init_node('fibonacci_client_py')
        result = fibonacci_client()
        print "Result:", ', '.join([str(n) for n in result.sequence])
    except rospy.ROSInterruptException:
        print "program interrupted before completion"

代码分析:

  • 代码:import actionlib_tutorials.msg

  • 分析:导入生成的消息,action会生成用于发送目标,接受反馈的消息。

  • 代码:client = actionlib.SimpleActionClient('fibonacci', actionlib_tutorials.msg.FibonacciAction)

  • 分析:创建action客户端,action客户端和action服务器端利用一系列主题(在actionlib协议描述)交流。action名称描述了包含这些主题的命名空间,并且action规范消息描述了这些主题应该传递什么信息。

  • 代码:client.wait_for_server()

  • 分析:在action服务器端运行之前发送目标是无效的,这行就等待直到action服务器端连接上。

  • 代码:

# Creates a goal to send to the action server.
goal = actionlib_tutorials.msg.FibonacciGoal(order=20)

# Sends the goal to the action server.
client.send_goal(goal)
  • 分析:创建目标并发送到action服务器端

  • 代码:

# Waits for the server to finish performing the action.
client.wait_for_result()

# Prints out the result of executing the action
return client.get_result()  # A FibonacciResult
  • 分析:等待action服务器端完成运算,并取得反馈的结果。

运行客户端

  • 运行roscore
$ roscore
  • 运行服务器端
$ rosrun actionlib_tutorials fibonacci_server
  • 运行客户端
$ rosrun actionlib_tutorials fibonacci_client.py

纠错,疑问,交流: 请进入讨论区点击加入Q群

获取最新文章: 扫一扫右上角的二维码加入“创客智造”公众号


标签: ros与python入门教程-actionlib