ROS2 通信三大件之动作 -- Action

ops/2024/10/20 1:25:01/

通信最后一个,也是不太容易理解的方式action,复杂且重要

1、创建action数据结构

创建工作空间和模块就不多说了

在模块  src/action_moudle/action/Counter.action  下创建文件 Counter.action

int32 target  # Goal: 目标 
---
int32 current_value  # Result: 结果
---
int32[] sequence  # Feedback: 中间状态反馈

需要注意的是 这几个值不要搞混,结果和中间状态容易搞错

添加依赖:src/action_moudle/package.xml

  <depend>rclcpp_action</depend> <depend>rosidl_default_generators</depend><depend>rosidl_default_runtime</depend><member_of_group>rosidl_interface_packages</member_of_group>

src/action_moudle/CMakeLists.txt

find_package(rosidl_default_generators REQUIRED)
find_package(rclcpp_action REQUIRED)# 设置消息和服务文件路径
set(action_FILES"action/Counter.action"
)# 添加消息和服务生成目标
rosidl_generate_interfaces(${PROJECT_NAME}${action_FILES}DEPENDENCIES std_msgs
)# 安装 Action 文件
install(DIRECTORY action/DESTINATION share/${PROJECT_NAME}/action
)

编译后生成install/action_moudle/include/action_moudle/action_moudle/action/counter.hpp

c6a140fc2d6a41b99d5792586c679cf9.png

至此action文件生成

2、编写Count计时的Action服务端和客户端代码

AI生成的代码靠不住,改了很多才编译过

src/action_moudle/src/action_server.cpp

#include "rclcpp/rclcpp.hpp"
#include "action_moudle/action/counter.hpp"
#include "rclcpp_action/rclcpp_action.hpp"
#include <memory>
#include <vector>using Counter = action_moudle::action::Counter;
using namespace std::placeholders;class CounterActionServer : public rclcpp::Node
{
public:CounterActionServer() : Node("counter_action_server"){action_server_ =rclcpp_action::create_server<Counter>(this, "counter", std::bind(&CounterActionServer::handle_goal, this, _1, _2),std::bind(&CounterActionServer::handle_cancel, this, _1), std::bind(&CounterActionServer::handle_accepted, this, _1));}private:rclcpp_action::Server<Counter>::SharedPtr action_server_;rclcpp_action::GoalResponse handle_goal(const rclcpp_action::GoalUUID& uuid, std::shared_ptr<const Counter::Goal> goal){(void)uuid;RCLCPP_INFO(this->get_logger(), "Received goal request with target: %ld", goal->target);return rclcpp_action::GoalResponse::ACCEPT_AND_EXECUTE;}rclcpp_action::CancelResponse handle_cancel(const std::shared_ptr<rclcpp_action::ServerGoalHandle<Counter>> goal_handle){RCLCPP_INFO(this->get_logger(), "Received request to cancel goal");return rclcpp_action::CancelResponse::ACCEPT;}void handle_accepted(const std::shared_ptr<rclcpp_action::ServerGoalHandle<Counter>> goal_handle){using namespace std::placeholders;std::thread{std::bind(&CounterActionServer::execute, this, _1), goal_handle}.detach();}void execute(const std::shared_ptr<rclcpp_action::ServerGoalHandle<Counter>> goal_handle){RCLCPP_INFO(this->get_logger(), "Executing goal");rclcpp::Rate loop_rate(1);const auto   goal     = goal_handle->get_goal();auto         feedback = std::make_shared<Counter::Feedback>();auto         result   = std::make_shared<Counter::Result>();result->current_value = 0;feedback->sequence.push_back(0);if (goal_handle->is_canceling()){goal_handle->canceled(result);RCLCPP_INFO(this->get_logger(), "Goal canceled");return;}goal_handle->publish_feedback(feedback);for (int i = 1; i <= goal->target; ++i){result->current_value = i;feedback->sequence.push_back(i);if (goal_handle->is_canceling()){goal_handle->canceled(result);RCLCPP_INFO(this->get_logger(), "Goal canceled");return;}goal_handle->publish_feedback(feedback);loop_rate.sleep();}goal_handle->succeed(result);RCLCPP_INFO(this->get_logger(), "Returning result");}
};int main(int argc, char* argv[])
{rclcpp::init(argc, argv);rclcpp::spin(std::make_shared<CounterActionServer>());rclcpp::shutdown();return 0;
}

src/action_moudle/src/action_client.cpp

#include "rclcpp/rclcpp.hpp"
#include "action_moudle/action/counter.hpp"
#include "rclcpp_action/rclcpp_action.hpp"
#include <memory>using Counter = action_moudle::action::Counter;
using namespace std::placeholders;class CounterActionClient : public rclcpp::Node
{
public:CounterActionClient() : Node("counter_action_client"){action_client_ = rclcpp_action::create_client<Counter>(this, "counter");while (!action_client_->wait_for_action_server()){if (!rclcpp::ok()){RCLCPP_ERROR(this->get_logger(), "Interrupted while waiting for the action server. Exiting.");return;}RCLCPP_INFO(this->get_logger(), "Action server not available, waiting again...");}auto goal   = Counter::Goal();goal.target = 10;auto send_goal_options                   = rclcpp_action::Client<Counter>::SendGoalOptions();send_goal_options.goal_response_callback = std::bind(&CounterActionClient::goal_response_callback, this, std::placeholders::_1);send_goal_options.feedback_callback      = std::bind(&CounterActionClient::feedback_callback, this, std::placeholders::_1, std::placeholders::_2);send_goal_options.result_callback        = std::bind(&CounterActionClient::result_callback, this, std::placeholders::_1);action_client_->async_send_goal(goal, send_goal_options);}private:rclcpp_action::Client<Counter>::SharedPtr action_client_;void goal_response_callback(rclcpp_action::ClientGoalHandle<Counter>::SharedPtr goal_handle){if (!goal_handle){RCLCPP_INFO(this->get_logger(), "Goal rejected");}else{RCLCPP_INFO(this->get_logger(), "Goal accepted");}}// void goal_response_callback(std::shared_future<std::shared_ptr<rclcpp_action::ClientGoalHandle<Counter>>> future)// {//     auto goal_handle = future.get();//     if (!goal_handle)//     {//         RCLCPP_INFO(this->get_logger(), "Goal rejected");//     }//     else//     {//         RCLCPP_INFO(this->get_logger(), "Goal accepted");//     }// }void feedback_callback(std::shared_ptr<rclcpp_action::ClientGoalHandle<Counter>>, const std::shared_ptr<const Counter::Feedback> feedback){// RCLCPP_INFO(this->get_logger(), "Current value: %ld", feedback->current_value);RCLCPP_INFO(this->get_logger(), "Sequence value: %s", print_sequence(feedback->sequence).c_str());}void result_callback(const rclcpp_action::ClientGoalHandle<Counter>::WrappedResult& result){switch (result.code){case rclcpp_action::ResultCode::SUCCEEDED:RCLCPP_INFO(this->get_logger(), "Result: %d", result.result->current_value);break;case rclcpp_action::ResultCode::ABORTED:RCLCPP_ERROR(this->get_logger(), "Goal was aborted");break;case rclcpp_action::ResultCode::CANCELED:RCLCPP_ERROR(this->get_logger(), "Goal was canceled");break;default:RCLCPP_ERROR(this->get_logger(), "Unknown result code");break;}rclcpp::shutdown();}std::string print_sequence(const std::vector<int32_t>& sequence){std::stringstream ss;ss << "[";for (size_t i = 0; i < sequence.size(); ++i){if (i > 0){ss << ", ";}ss << sequence[i];}ss << "]";return ss.str();}
};int main(int argc, char* argv[])
{rclcpp::init(argc, argv);rclcpp::spin(std::make_shared<CounterActionClient>());rclcpp::shutdown();return 0;
}

src/action_moudle/CMakeLists.txt  添加

find_package(action_moudle REQUIRED)
find_package(rclcpp_action REQUIRED)# 创建可执行文件
add_executable(action_server src/action_server.cpp)
ament_target_dependencies(action_server rclcpp std_msgs action_moudle rclcpp_action)add_executable(action_client src/action_client.cpp)
ament_target_dependencies(action_client rclcpp std_msgs action_moudle rclcpp_action)# 安装目标
install(TARGETSaction_server action_clientDESTINATION lib/${PROJECT_NAME}
)

3、编译后测试

edaa2982375c40b588702640e4975cf9.png

 


http://www.ppmy.cn/ops/126851.html

相关文章

用自己的数据集复现YOLOv5

yolov5已经出了很多版本了&#xff0c;这里我以目前最新的版本为例&#xff0c;先在官网下载源码&#xff1a;GitHub - ultralytics/yolov5: YOLOv5 &#x1f680; in PyTorch > ONNX > CoreML > TFLite 然后下载预训练模型&#xff0c;需要哪个就点击哪个模型就行&am…

安装TDengine数据库3.3版本和TDengine数据库可视化管理工具

安装TDengine数据库3.3版本和TDengine数据库可视化管理工具 一、下载安装包二、解压安装包三、部署四、启动服务五、进入数据库六、创建数据库、表和往表中插入数据七、测试 TDengine 性能八、使用数据库九、查询数据十、TDengine数据库可视化界面 一、下载安装包 TDengine-cl…

AnaTraf | 提升网络稳定性与效率:深入解析网络流量采集分析与故障定位

目录 网络流量采集分析的核心价值 什么是网络流量采集分析&#xff1f; 网络流量分析的应用场景 利用流量分析优化企业网络 网络故障定位的关键步骤 故障定位的基本流程 常用故障定位方法 实用技巧 网络流量采集分析与故障定位的协同作用 整合流量分析提升故障响应速…

【运维基础知识】《Linux 系统架构与文件系统及权限管理全解析》

标题&#xff1a;《Linux 系统架构与文件系统及权限管理全解析》 摘要&#xff1a; 本文将深入介绍 Linux 系统架构、文件系统和权限管理。涵盖内核、用户空间、守护进程等系统架构组成部分&#xff0c;详细阐述文件系统层次结构、设备文件、符号链接等内容&#xff0c;同时深…

基于springboot+微信小程序校园自助打印管理系统(打印1)

&#x1f449;文末查看项目功能视频演示获取源码sql脚本视频导入教程视频 1、项目介绍 基于springboot微信小程序校园自助打印管理系统实现了管理员、店长和用户。管理员实现了用户管理、店长管理、打印店管理、打印服务管理、服务类型管理、预约打印管理和系统管理。店长实现…

SpringBoot驱动的智能购物推荐平台开发指南

1系统概述 1.1 研究背景 如今互联网高速发展&#xff0c;网络遍布全球&#xff0c;通过互联网发布的消息能快而方便的传播到世界每个角落&#xff0c;并且互联网上能传播的信息也很广&#xff0c;比如文字、图片、声音、视频等。从而&#xff0c;这种种好处使得互联网成了信息传…

Vue 字符串常用方法

文章目录 前言在模板中使用在计算属性中使用在方法中使用 前言 Vue.js中的字符串处理主要是依赖于JavaScript的字符串方法&#xff0c;Vue.js本身并没有提供额外的字符串处理方法&#xff0c;但它允许你在模板、计算属性和方法中方便地使用这些JavaScript方法。想要了解JavaSc…

高可用之限流-07-token bucket 令牌桶算法

限流系列 开源组件 rate-limit: 限流 高可用之限流-01-入门介绍 高可用之限流-02-如何设计限流框架 高可用之限流-03-Semaphore 信号量做限流 高可用之限流-04-fixed window 固定窗口 高可用之限流-05-slide window 滑动窗口 高可用之限流-06-slide window 滑动窗口 sen…