ROS2-教你如何自定义动作接口类型,并使用Action完成指定任务


手把手教你如何自定义动作接口类型,并演示Action的用法。假如:客户端发送数数到100,服务端接收后,每隔一秒数一个数,并打印日志;并在数数的过程中告诉客户端数到那里了,说完以后告诉客户端数完了。

1.定义Action文件

1.1 首先创建Action定义文件 CountNumbers.action:

# Goal
float32 target_num  # 目标数字
---
# Result
string result       # 结果:success, failed, cancel
float32 current_num # 当前数字
---
# Feedback
float32 current_num # 当前进度数字

1.2 配置 CMakeLists.txt

修改 CMakeLists.txt 文件:

cmake_minimum_required(VERSION 3.8)
project(ros_two_interface)
if(CMAKE_COMPILER_IS_GNUCXX OR CMAKE_CXX_COMPILER_ID MATCHES "Clang")
  add_compile_options(-Wall -Wextra -Wpedantic)
endif()

# find dependencies
find_package(ament_cmake REQUIRED)
# 查找依赖
find_package(rosidl_default_generators REQUIRED)
find_package(std_msgs REQUIRED)
# 设置服务文件
rosidl_generate_interfaces(${
   
   PROJECT_NAME}
  "srv/AddTwoInts.srv"
  "action/CountNumbers.action"
  DEPENDENCIES std_msgs
)
# 安装接口文件
install(
  DIRECTORY include/
  DESTINATION include
)
# 安装服务定义
install(
  DIRECTORY srv/
  DESTINATION share/${
   
   PROJECT_NAME}/srv
)
# 安装动作定义
install(
  DIRECTORY action/
  DESTINATION share/${
   
   PROJECT_NAME}/action
)
ament_export_dependencies(rosidl_default_runtime)
ament_export_include_directories(include)
ament_package()

1.3 编译

colcon build --packages-select ros_two_interface

编译后的结果:
在这里插入图片描述

2 实现服务端和客户端

2.1 创建ros_two_action功能包

ros2 pkg create ros_two_action --build-type ament_cmake --dependencies rclcpp  rclcpp_action ros_two_interface

2.2 创建count_action_server.cpp文件,其代码为:

#include <rclcpp/rclcpp.hpp>
#include <rclcpp_action/rclcpp_action.hpp>
#include <thread>
#include <chrono>
#include "ros_two_interface/action/count_numbers.hpp"  // 替换为你的包名

using namespace std::chrono_literals;
using CountNumbers = ros_two_interface::action::CountNumbers;  // 替换为你的包名
using GoalHandleCountNumbers = rclcpp_action::ServerGoalHandle<CountNumbers>;

class CountActionServer : public rclcpp::Node
{
   
   
public:
    CountActionServer() : Node("count_action_server")
    {
   
   
        // 创建Action Server
        action_server_ = rclcpp_action::create_server<CountNumbers>(
            this,
            "count_numbers",
            std::bind(&CountActionServer::handle_goal, this, std::placeholders::_1, std::placeholders::_2),
            std::bind(&CountActionServer::handle_cancel, this, std::placeholders::_1),
            std::bind(&CountActionServer::handle_accepted, this, std::placeholders
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值