< >
Home » ROS2与Python入门教程 » ros2与Python入门教程-创建action客户端

ros2与Python入门教程-创建action客户端

ros2与Python入门教程-创建action客户端

说明:

  • 介绍如何创建action客户端

步骤:

  • 进入目录,新建文件fibonacci_action_client.py
cd ~/dev_ws/src/action_tutorials/action_tutorials
vim fibonacci_action_client.py
  • 内容如下:
import rclpy
from rclpy.node import Node
from rclpy.action import ActionClient
from action_tutorials.action import Fibonacci


class FibonacciActionClient(Node):

    def __init__(self):
        super().__init__('fibonacci_action_client')
        self._action_client = ActionClient(self, Fibonacci, 'fibonacci')

    def send_goal(self, order):
        goal_msg = Fibonacci.Goal()
        goal_msg.order = order
        self._action_client.wait_for_server()
        self._send_goal_future = self._action_client.send_goal_async(
            goal_msg,
            feedback_callback=self.feedback_callback)

        self._send_goal_future.add_done_callback(self.goal_response_callback)

    def goal_response_callback(self, future):
        goal_handle = future.result()
        if not goal_handle.accepted:
            self.get_logger().info('Goal rejected :(')
            return

        self.get_logger().info('Goal accepted :)')
        self._get_result_future = goal_handle.get_result_async()
        self._get_result_future.add_done_callback(self.get_result_callback)

    def get_result_callback(self, future):
        result = future.result().result
        self.get_logger().info('Result: {0}'.format(result.sequence))
        rclpy.shutdown()

    def feedback_callback(self, feedback_msg):
        feedback = feedback_msg.feedback
        self.get_logger().info('Received feedback: {0}'.format(feedback.partial_sequence))


def main(args=None):
    rclpy.init(args=args)

    action_client = FibonacciActionClient()
    action_client.send_goal(10)
    rclpy.spin(action_client)

if __name__ == '__main__':
    main()
  • 编译
cd ~/dev_ws/
colcon build --packages-select action_tutorials
  • 新开终端,运行
. install/setup.bash
cd ~/dev_ws/src/action_tutorials/action_tutorials/
python3 fibonacci_action_client.py

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

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


标签: ros2与python入门教程