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

ros2与Python入门教程-创建action服务端

ros2与Python入门教程-创建action服务端

说明:

  • 介绍如何创建action服务端

步骤:

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


class FibonacciActionServer(Node):

    def __init__(self):
        super().__init__('fibonacci_action_server')
        self._action_server = ActionServer(
            self,
            Fibonacci,
            'fibonacci',
            self.execute_callback)

    def execute_callback(self, goal_handle):
        self.get_logger().info('Executing goal...')
        feedback_msg = Fibonacci.Feedback()
        feedback_msg.partial_sequence = [0, 1]

        for i in range(1, goal_handle.request.order):
            feedback_msg.partial_sequence.append(
                feedback_msg.partial_sequence[i] + feedback_msg.partial_sequence[i-1])
            self.get_logger().info('Feedback: {0}'.format(feedback_msg.partial_sequence))
            goal_handle.publish_feedback(feedback_msg)
            time.sleep(1)

        goal_handle.succeed()
        result = Fibonacci.Result()
        result.sequence = feedback_msg.partial_sequence
        return result

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

    fibonacci_action_server = FibonacciActionServer()

    rclpy.spin(fibonacci_action_server)


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_server.py
  • 新开终端,执行
ros2 action send_goal --feedback fibonacci action_tutorials/action/Fibonacci "{order: 5}"

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

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


标签: ros2与python入门教程