当前位置: 首页 > article >正文

ros2 跟着官方教学从零开始 CS

ros2 从零开始10 服务者和消费者C/S前言上节课介绍写了简单的Topic订阅模型。本章我们将要学习C/S模型即服务者和消费者模型背景前面服务概念时提到过服务是ROS2 节点的另一种通信方式。服务基于调用与响应模型而非发布者-订阅者主题模型。服务就是我们常用的C/S模型Client 客户端请求而Service 服务端提供相应的响应。相较于发布者-订阅者主题模型调用与响应模型是点对点的通信。服务的通信数据结构用.srv文件来描述如下图srv文件用---来分隔上面是请求数据结构下面是响应数据结构如果数据结构为空则相应位置也为空。后面会有章节来介绍srv先按下不表。int64 a int64 b --- int64 sum实践创建一个包进入工作区的src目录用如下指令创建我们的包ros2 pkg create --build-type ament_cmake --license Apache-2.0 cpp_srvcli --dependencies rclcpp example_interfaces。--dependencies后面代表相关的依赖项rclcpp、example_interfaces命令会自动把依赖信息添加到package.xml和CMakeLists.txt里面。rootbc2bf85b2e4a:~/ros2_ws/src# ros2 pkg create --build-type ament_cmake --license Apache-2.0 cpp_srvcli --dependencies rclcpp example_interfaces going to create a new package package name: cpp_srvcli destination directory: /root/ros2_ws/src package format: 3 version: 0.0.0 description: TODO: Package description maintainer: [root xianlutinnove.com.cn] licenses: [Apache-2.0] build type: ament_cmake dependencies: [rclcpp, example_interfaces] creating folder ./cpp_srvcli creating ./cpp_srvcli/package.xml creating source and include folder creating folder ./cpp_srvcli/src creating folder ./cpp_srvcli/include/cpp_srvcli creating ./cpp_srvcli/CMakeLists.txt rootbc2bf85b2e4a:~/ros2_ws/src# ls cpp_srvcli example_interfaces examples mypackage以上命令ros2帮我们自动生成了cpp_srvcli。还记得example_interfaces吗example_interfaces是 ROS 2 中的一个消息接口包它包含了一系列示例消息类型主要用于测试、演示和学习目的。package.xml里面可以维护描述、作者信息、License等descriptionC client server tutorial/description maintainer emailyouemail.comYour Name/maintainer licenseApache License 2.0/license创建我们将设计2个节点执行程序server负责提供服务接口client负责调用client提供的服务接口开始吧2.1 在src里面创建一个cpp文件add_two_ints_server.cpp其内容如下#include rclcpp/rclcpp.hpp #include example_interfaces/srv/add_two_ints.hpp #include memory void add(const std::shared_ptrexample_interfaces::srv::AddTwoInts::Request request, std::shared_ptrexample_interfaces::srv::AddTwoInts::Response response) { response-sum request-a request-b; RCLCPP_INFO(rclcpp::get_logger(rclcpp), Incoming request\na: %ld b: %ld, request-a, request-b); RCLCPP_INFO(rclcpp::get_logger(rclcpp), sending back response: [%ld], (long int)response-sum); } int main(int argc, char **argv) { rclcpp::init(argc, argv); std::shared_ptrrclcpp::Node node rclcpp::Node::make_shared(add_two_ints_server); rclcpp::Serviceexample_interfaces::srv::AddTwoInts::SharedPtr service node-create_serviceexample_interfaces::srv::AddTwoInts(add_two_ints, add); RCLCPP_INFO(rclcpp::get_logger(rclcpp), Ready to add two ints.); rclcpp::spin(node); rclcpp::shutdown(); }解析 下面代码创建节点add_two_ints_server 并接下来创建 rclcpp::Service对象, 而 rclcpp::Service对象创建时把实现函数add当成参数初始化了。在创建完成对象会自动通过在网络上进行广播些服务。rclcpp::spin(node)会阻塞直到节点退出后才返回。std::shared_ptrrclcpp::Node node rclcpp::Node::make_shared(add_two_ints_server); rclcpp::Serviceexample_interfaces::srv::AddTwoInts::SharedPtr service node-create_serviceexample_interfaces::srv::AddTwoInts(add_two_ints, add); RCLCPP_INFO(rclcpp::get_logger(rclcpp), Ready to add two ints.); rclcpp::spin(node);关于add函数入参分别是std::shared_ptrexample_interfaces::srv::AddTwoInts::Request和std::shared_ptrexample_interfaces::srv::AddTwoInts::Response这2个定义的实现由前面提到的srv文件编译自动生成得到的。void add(const std::shared_ptrexample_interfaces::srv::AddTwoInts::Request request, std::shared_ptrexample_interfaces::srv::AddTwoInts::Response response) { response-sum request-a request-b; RCLCPP_INFO(rclcpp::get_logger(rclcpp), Incoming request\na: %ld b: %ld, request-a, request-b); RCLCPP_INFO(rclcpp::get_logger(rclcpp), sending back response: [%ld], (long int)response-sum); }2.2 在src里面一个cpp文件add_two_ints_client.cpp其内容如下#include rclcpp/rclcpp.hpp #include example_interfaces/srv/add_two_ints.hpp #include chrono #include cstdlib #include memory using namespace std::chrono_literals; int main(int argc, char **argv) { rclcpp::init(argc, argv); if (argc ! 3) { RCLCPP_INFO(rclcpp::get_logger(rclcpp), usage: add_two_ints_client X Y); return 1; } std::shared_ptrrclcpp::Node node rclcpp::Node::make_shared(add_two_ints_client); rclcpp::Clientexample_interfaces::srv::AddTwoInts::SharedPtr client node-create_clientexample_interfaces::srv::AddTwoInts(add_two_ints); auto request std::make_sharedexample_interfaces::srv::AddTwoInts::Request(); request-a atoll(argv[1]); request-b atoll(argv[2]); while (!client-wait_for_service(1s)) { if (!rclcpp::ok()) { RCLCPP_ERROR(rclcpp::get_logger(rclcpp), Interrupted while waiting for the service. Exiting.); return 0; } RCLCPP_INFO(rclcpp::get_logger(rclcpp), service not available, waiting again...); } auto result client-async_send_request(request); // Wait for the result. if (rclcpp::spin_until_future_complete(node, result) rclcpp::FutureReturnCode::SUCCESS) { RCLCPP_INFO(rclcpp::get_logger(rclcpp), Sum: %ld, result.get()-sum); } else { RCLCPP_ERROR(rclcpp::get_logger(rclcpp), Failed to call service add_two_ints); } rclcpp::shutdown(); return 0; }解析 像server一样, 下面代码创建节点node, 并且创建rclcpp::Client对象(对应rclcpp::Service对象)。std::shared_ptrrclcpp::Node node rclcpp::Node::make_shared(add_two_ints_client); rclcpp::Clientexample_interfaces::srv::AddTwoInts::SharedPtr client node-create_clientexample_interfaces::srv::AddTwoInts(add_two_ints);接下来创建请求入参request。并且给具体的值具体值a和b 是我们node节点启动时的参数1、参数2。auto request std::make_sharedexample_interfaces::srv::AddTwoInts::Request(); request-a atoll(argv[1]); request-b atoll(argv[2]);接下来查找服务client-wait_for_service(1s)如果找到就返回true否则1s超时返回。auto result client-async_send_request(request);就是调用服务。2.3 修改CMakeLists.txt在ament_package()的前一行新增如下信息add_executable(server src/add_two_ints_server.cpp) ament_target_dependencies(server rclcpp example_interfaces) add_executable(client src/add_two_ints_client.cpp) ament_target_dependencies(client rclcpp example_interfaces) install(TARGETS server client DESTINATION lib/${PROJECT_NAME})完整的CMakeLists.txt如下cmake_minimum_required(VERSION 3.8) project(cpp_srvcli) 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(rclcpp REQUIRED) find_package(example_interfaces REQUIRED) if(BUILD_TESTING) find_package(ament_lint_auto REQUIRED) # the following line skips the linter which checks for copyrights # comment the line when a copyright and license is added to all source files set(ament_cmake_copyright_FOUND TRUE) # the following line skips cpplint (only works in a git repo) # comment the line when this package is in a git repo and when # a copyright and license is added to all source files set(ament_cmake_cpplint_FOUND TRUE) ament_lint_auto_find_test_dependencies() endif() add_executable(server src/add_two_ints_server.cpp) ament_target_dependencies(server rclcpp example_interfaces) add_executable(client src/add_two_ints_client.cpp) ament_target_dependencies(client rclcpp example_interfaces) install(TARGETS server client DESTINATION lib/${PROJECT_NAME}) ament_package()开始编译进入工作区用colcon build等待编译完成。rootbc2bf85b2e4a:/# cd ~/ros2_ws rootbc2bf85b2e4a:~/ros2_ws# colcon build --packages-select cpp_srvcli Starting cpp_srvcli Finished cpp_srvcli [5.22s] Summary: 1 package finished [5.57s] rootbc2bf85b2e4a:~/ros2_ws#运行编译完成后我们需要安装后才能运行使用source install/setup.sh打开一个终端输入如下命令启动serverrootbc2bf85b2e4a:~/ros2_ws# source install/setup.sh rootbc2bf85b2e4a:~/ros2_ws# ros2 run cpp_srvcli server [INFO] [1774875183.179833701] [rclcpp]: Ready to add two ints.另开一个终端输入如下命令启动clientrootbc2bf85b2e4a:~/ros2_ws# cd ~/ros2_ws/ rootbc2bf85b2e4a:~/ros2_ws# source install/setup.sh rootbc2bf85b2e4a:~/ros2_ws# ros2 run cpp_srvcli client 300 300 [INFO] [1774875293.803476695] [rclcpp]: Sum: 600 rootbc2bf85b2e4a:~/ros2_ws#可以看到server计算2个数相加并把结果返回给client。总结在最近几个教程中你一直在使用主题和服务传递数据。 接下来我们学习如何自定义消息数据接口srv。

相关文章:

ros2 跟着官方教学从零开始 CS

ros2 从零开始10 服务者和消费者C/S 前言 上节课介绍写了简单的Topic订阅模型。本章我们将要学习C/S模型,即服务者和消费者模型 背景 前面服务概念时提到过,服务是ROS2 节点的另一种通信方式。服务基于调用与响应模型,而非发布者-订阅者主题模…...

OpenClaw故障排查手册:GLM-4.7-Flash接口连接常见问题解决

OpenClaw故障排查手册:GLM-4.7-Flash接口连接常见问题解决 1. 问题背景与排查准备 上周在本地部署OpenClaw对接GLM-4.7-Flash时,我遇到了三次连接中断和两次响应解析失败。这个开源框架虽然强大,但调试过程确实需要些技巧。本文将分享实战中…...

颠覆式突破限制:五大核心技术实现网盘下载加速革命

颠覆式突破限制:五大核心技术实现网盘下载加速革命 【免费下载链接】Online-disk-direct-link-download-assistant 可以获取网盘文件真实下载地址。基于【网盘直链下载助手】修改(改自6.1.4版本) ,自用,去推广&#xf…...

终极BewlyBewly插件指南:5分钟打造个性化Bilibili界面

终极BewlyBewly插件指南:5分钟打造个性化Bilibili界面 【免费下载链接】BewlyBewly Improve your Bilibili homepage by redesigning it, adding more features, and personalizing it to match your preferences. 项目地址: https://gitcode.com/gh_mirrors/be/B…...

导师推荐!盘点2026年当红之选的AI论文平台

一天写完毕业论文在2026年已不再是天方夜谭。2026年最炸裂、实测能大幅提速的AI论文平台,覆盖选题构思、文献综述、数据整理、降重润色、格式排版等全流程,高效搞定论文,让你轻松应对学术挑战。 一、全流程王者:一站式搞定论文全链…...

ASP.NET Core 认证鉴权实战:JWT、Policy 与权限边界怎么落地

实现场:一个后台退款接口原本只允许财务角色调用,但线上排查发现,普通运营账号只要拿到有效 token,也能调用成功。根因并不复杂:接口加了 [Authorize]系统只校验“是否登录”没有继续校验角色、权限和资源归属结果就是…...

AI率太高被退稿?这5款工具帮你稳过查重+降AI双关!

&#x1f525; 2026实测推荐&#xff1a;5款真正管用的工具1️⃣ 毕业之家 AI&#xff08;毕业季救星&#xff09;AI率效果&#xff1a;<8%亮点&#xff1a;专为国内高校定制&#xff0c;自动适配学校格式要求&#xff0c;连页眉页脚都不用手调价格&#xff1a;本科套餐199元…...

如何安全高效地烧录系统镜像?Balena Etcher带来无忧体验

如何安全高效地烧录系统镜像&#xff1f;Balena Etcher带来无忧体验 【免费下载链接】etcher Flash OS images to SD cards & USB drives, safely and easily. 项目地址: https://gitcode.com/GitHub_Trending/et/etcher 你是否曾因误操作将系统镜像写入电脑硬盘而丢…...

5个Adobe-GenP实用技巧:从安装到完美运行Photoshop

5个Adobe-GenP实用技巧&#xff1a;从安装到完美运行Photoshop 【免费下载链接】Adobe-GenP Adobe CC 2019/2020/2021/2022/2023 GenP Universal Patch 3.0 项目地址: https://gitcode.com/gh_mirrors/ad/Adobe-GenP Adobe-GenP是一款强大的Adobe Creative Cloud通用补丁…...

【DexGraspNet与多指手抓取算法详解】第三章 DexGraspNet数据集构建机理

目录 第三章 DexGraspNet数据集构建机理 第一部分 原理详解 3.1 数据生成流程总览 3.1.1 Asset准备与处理 3.1.1.1 ShapeNetSem物体库筛选 3.1.1.1.1 几何网格清理与流形检测 3.1.1.1.2 物理属性赋值(质量、质心) 3.1.1.2 视觉资产渲染管线 3.1.1.2.1 材质与纹理映射…...

Tendis与Redis Cluster对比分析:性能、成本与适用场景深度评测

Tendis与Redis Cluster对比分析&#xff1a;性能、成本与适用场景深度评测 【免费下载链接】Tendis Tendis is a high-performance distributed storage system fully compatible with the Redis protocol. 项目地址: https://gitcode.com/gh_mirrors/te/Tendis 在当今…...

Atmosphere-stable开源项目实战指南:从基础到进阶的完整路径

Atmosphere-stable开源项目实战指南&#xff1a;从基础到进阶的完整路径 【免费下载链接】Atmosphere-stable 大气层整合包系统稳定版 项目地址: https://gitcode.com/gh_mirrors/at/Atmosphere-stable 一、认知基础&#xff1a;如何理解Atmosphere自定义固件&#xff1…...

保姆级教程:用YOLOv11+PyQt5打造你的专属天气识别桌面应用(附完整源码)

从零构建基于YOLOv11的智能天气识别桌面应用 窗外阴云密布&#xff0c;你是否曾好奇此刻的天气状况究竟如何&#xff1f;现代计算机视觉技术让机器也能像人类一样"看懂"天气。本文将带你完整实现一个能识别11种天气类型的桌面应用&#xff0c;从模型加载到界面交互&a…...

破局足球数据分析困境:Understat工具的技术赋能与实战应用

破局足球数据分析困境&#xff1a;Understat工具的技术赋能与实战应用 【免费下载链接】understat An asynchronous Python package for https://understat.com/. 项目地址: https://gitcode.com/gh_mirrors/un/understat 问题发现&#xff1a;足球数据分析的三重技术壁…...

在Windows 11上用Bochs调试Linux 0.00:从BIOS加载到保护模式切换的完整实战

在Windows 11上用Bochs调试Linux 0.00&#xff1a;从BIOS加载到保护模式切换的完整实战 如果你对操作系统的底层实现充满好奇&#xff0c;想亲手探索计算机从加电到运行第一个用户程序的完整过程&#xff0c;那么这次实验将是一次绝佳的实践机会。我们将使用Bochs模拟器&#x…...

Python接口与抽象基类:构建可扩展系统的终极指南

Python接口与抽象基类&#xff1a;构建可扩展系统的终极指南 【免费下载链接】example-code Example code for the book Fluent Python, 1st Edition (OReilly, 2015) 项目地址: https://gitcode.com/gh_mirrors/ex/example-code Python接口与抽象基类是构建可扩展、可维…...

OpenClaw备份与迁移:Qwen3.5-4B-Claude项目环境快速转移

OpenClaw备份与迁移&#xff1a;Qwen3.5-4B-Claude项目环境快速转移 1. 为什么需要备份与迁移方案 上周我的主力开发机突然硬盘故障&#xff0c;导致所有OpenClaw配置和技能丢失。在经历了8小时的手动重建后&#xff0c;我意识到必须建立一套可靠的备份迁移流程。特别是当我们…...

提升51%运行速度:Win11Debloat系统优化工具全方位应用指南

提升51%运行速度&#xff1a;Win11Debloat系统优化工具全方位应用指南 【免费下载链接】Win11Debloat 一个简单的PowerShell脚本&#xff0c;用于从Windows中移除预装的无用软件&#xff0c;禁用遥测&#xff0c;从Windows搜索中移除Bing&#xff0c;以及执行各种其他更改以简化…...

终极WebGL 3D图形开发指南:gl-matrix快速集成实战

终极WebGL 3D图形开发指南&#xff1a;gl-matrix快速集成实战 【免费下载链接】gl-matrix Javascript Matrix and Vector library for High Performance WebGL apps 项目地址: https://gitcode.com/gh_mirrors/gl/gl-matrix gl-matrix是一款专为高性能WebGL应用打造的Ja…...

Excel报表自动化:用JXLS实现动态数据填充的5个高级技巧

Excel报表自动化&#xff1a;用JXLS实现动态数据填充的5个高级技巧 每次看到同事手动复制粘贴数据到Excel模板时&#xff0c;我都忍不住想分享JXLS这个神器。作为Java开发者&#xff0c;我们完全可以用代码实现专业级报表自动化&#xff0c;告别重复劳动。本文将带你深入JXLS的…...

高效音频录制实战:如何为你的Web应用选择最佳编码方案

高效音频录制实战&#xff1a;如何为你的Web应用选择最佳编码方案 【免费下载链接】Recorder html5 js 录音 mp3 wav ogg webm amr g711a g711u 格式&#xff0c;支持pc和Android、iOS部分浏览器、Hybrid App&#xff08;提供Android iOS App源码&#xff09;、微信&#xff0c…...

Atmosphere系统功能扩展指南:从基础配置到高级应用的完整学习路径

Atmosphere系统功能扩展指南&#xff1a;从基础配置到高级应用的完整学习路径 【免费下载链接】Atmosphere-stable 大气层整合包系统稳定版 项目地址: https://gitcode.com/gh_mirrors/at/Atmosphere-stable 问题导入&#xff1a;为什么需要自定义系统 想象一下&#x…...

微信读书助手wereader:革新数字阅读体验的全方位解决方案

微信读书助手wereader&#xff1a;革新数字阅读体验的全方位解决方案 【免费下载链接】wereader 一个功能全面的微信读书笔记助手 wereader 项目地址: https://gitcode.com/gh_mirrors/we/wereader 在信息爆炸的时代&#xff0c;如何高效管理数字阅读内容、系统化整理读…...

从一次存储故障复盘说起:深入理解FC SAN中WWN、WWPN、WWNN的区别与实战应用

从一次存储故障复盘说起&#xff1a;深入理解FC SAN中WWN、WWPN、WWNN的区别与实战应用 那天凌晨三点&#xff0c;我被一阵急促的电话铃声惊醒。客户的核心数据库集群突然失去存储连接&#xff0c;业务完全停滞。当我赶到现场时&#xff0c;运维团队已经尝试了重启服务器、更换…...

Microstation v8与Terrasolid插件安装全攻略:从零到精通

1. MicroStation v8安装前的准备工作 在开始安装MicroStation v8之前&#xff0c;我们需要做好充分的准备工作。首先确保你的电脑满足最低系统要求&#xff1a;Windows 7/8/10操作系统&#xff08;32位或64位均可&#xff09;、至少4GB内存、2GB可用磁盘空间。我建议使用独立显…...

megaAVR_PWM硬件PWM库:工业级实时PWM控制详解

1. megaAVR_PWM 库深度技术解析&#xff1a;面向工业级实时控制的硬件PWM实现1.1 工程背景与核心价值定位在嵌入式系统开发中&#xff0c;PWM&#xff08;脉宽调制&#xff09;是电机驱动、LED调光、电源管理及伺服控制等场景的基础技术。然而&#xff0c;大量开发者仍依赖anal…...

革命性主题建模工具Top2Vec:自动发现隐藏主题的完整指南

革命性主题建模工具Top2Vec&#xff1a;自动发现隐藏主题的完整指南 【免费下载链接】Top2Vec Top2Vec learns jointly embedded topic, document and word vectors. 项目地址: https://gitcode.com/gh_mirrors/to/Top2Vec Top2Vec是一款革命性的主题建模工具&#xff0…...

突破常规认知的编辑器革命:TinyEditor轻量级代码编辑器深度解析

突破常规认知的编辑器革命&#xff1a;TinyEditor轻量级代码编辑器深度解析 【免费下载链接】TinyEditor A functional HTML/CSS/JS editor in less than 400 bytes 项目地址: https://gitcode.com/gh_mirrors/ti/TinyEditor 当开发者在移动设备上调试代码&#xff0c;或…...

从仿真到真机:基于ROS2 Control和MoveIt2的Panda机械臂运动控制实战(Humble环境)

从仿真到真机&#xff1a;基于ROS2 Control和MoveIt2的Panda机械臂运动控制实战&#xff08;Humble环境&#xff09; 在工业自动化和科研领域&#xff0c;机械臂的运动控制正经历着从传统专用控制器向开源软件栈的转型。ROS2生态系统中的两大支柱——ROS2 Control和MoveIt2&…...

从NASA到你家菜园:聊聊那些藏在智慧农业背后的‘黑科技’传感器(光学/微波遥感全解析)

从NASA到你家菜园&#xff1a;智慧农业背后的传感器技术革命 当清晨的阳光洒在堪萨斯州的麦田上&#xff0c;NASA的Landsat卫星正以每秒7.5公里的速度掠过北美大陆上空。它的多光谱传感器捕捉到的数据&#xff0c;将在6小时后转化为中国山东某葡萄种植园主的手机推送——"…...