C++入门 ros服务通信

一、 开发环境

ubuntu20.04
ros版本noetic
参考视频
https://www.bilibili.com/video/BV1Ci4y1L7ZZ/?p=52&spm_id_from=333.1007.top_right_bar_window_history.content.click&vd_source=4cd1b6f268e2a29a11bea5d2568836ee

二、 编写srv文件

在功能包下面创建srv文件夹(srv文件夹和src文件夹并列),在srv文件夹中创建AddInt.srv文件
AddInt.srv

int32 num1
int32 num2
---
int32 sum

三、 编写服务端

smain.cpp

#include "ros/ros.h"
#include "/home/leon/project/ros/helloworld/ws/devel/include/addserver/AddInt.h"
#include <sstream>bool doNums(addserver::AddInt::Request &request,addserver::AddInt::Response &response)
{int num1 = request.num1;int num2 = request.num2;ROS_INFO("收到:%d,%d",num1,num2);int sum = num1 + num2;response.sum = sum;ROS_INFO("反馈:%d",sum);return true;
}//服务端
int main(int argc,char *argv[])
{//中文支持setlocale(LC_ALL,"");//初始化ros节点//指定节点名称ros::init(argc,argv,"server");//创建ros节点句柄ros::NodeHandle n;//创建服务对象ros::ServiceServer server = n.advertiseService("add",doNums);ros::spin();return 0;
}
//
//通过ros工具打印话题消息
//rostopic echo fang//通过命令方式调用服务
//rosservice call add "num1: 5 num2: 2"

四、 编写客户端

cmain.cpp

#include "ros/ros.h"
#include "/home/leon/project/ros/helloworld/ws/devel/include/addserver/AddInt.h"
#include <sstream>bool doNums(addserver::AddInt::Request &request,addserver::AddInt::Response &response)
{int num1 = request.num1;int num2 = request.num2;ROS_INFO("收到:%d,%d",num1,num2);int sum = num1 + num2;response.sum = sum;ROS_INFO("反馈:%d",sum);return true;
}//服务调用端
int main(int argc,char *argv[])
{//中文支持setlocale(LC_ALL,"");if(argc != 3){ROS_INFO("参数个数不对");return 1;}//初始化ros节点//指定节点名称ros::init(argc,argv,"client");//创建ros节点句柄ros::NodeHandle n;//创建服务对象ros::ServiceClient client = n.serviceClient<addserver::AddInt>("add");addserver::AddInt to;to.request.num1 = atoi(argv[1]);to.request.num2 = atoi(argv[2]);//客户端先启动时等待服务器启动client.waitForExistence();//ros::service::waitForService("add");//功能同上一行bool flag = client.call(to);if(flag){ROS_INFO("响应结果:%d",to.response.sum);}else{ROS_INFO("响应失败");}return 0;
}
//
//通过ros工具打印话题消息
//rostopic echo fang//通过命令方式调用服务
//rosservice call add "num1: 5 num2: 2"

五、 修改配置

package.xml

<?xml version="1.0"?>
<package format="2"><name>addserver</name><version>0.0.0</version><description>The addserver package</description><!-- One maintainer tag required, multiple allowed, one person per tag --><!-- Example:  --><!-- <maintainer email="jane.doe@example.com">Jane Doe</maintainer> --><maintainer email="leon@todo.todo">leon</maintainer><!-- One license tag required, multiple allowed, one license per tag --><!-- Commonly used license strings: --><!--   BSD, MIT, Boost Software License, GPLv2, GPLv3, LGPLv2.1, LGPLv3 --><license>TODO</license><!-- Url tags are optional, but multiple are allowed, one per tag --><!-- Optional attribute type can be: website, bugtracker, or repository --><!-- Example: --><!-- <url type="website">http://wiki.ros.org/addserver</url> --><!-- Author tags are optional, multiple are allowed, one per tag --><!-- Authors do not have to be maintainers, but could be --><!-- Example: --><!-- <author email="jane.doe@example.com">Jane Doe</author> --><!-- The *depend tags are used to specify dependencies --><!-- Dependencies can be catkin packages or system dependencies --><!-- Examples: --><!-- Use depend as a shortcut for packages that are both build and exec dependencies --><!--   <depend>roscpp</depend> --><!--   Note that this is equivalent to the following: --><!--   <build_depend>roscpp</build_depend> --><!--   <exec_depend>roscpp</exec_depend> --><!-- Use build_depend for packages you need at compile time: --><!--   <build_depend>message_generation</build_depend> --><!-- Use build_export_depend for packages you need in order to build against this package: --><!--   <build_export_depend>message_generation</build_export_depend> --><!-- Use buildtool_depend for build tool packages: --><!--   <buildtool_depend>catkin</buildtool_depend> --><!-- Use exec_depend for packages you need at runtime: --><!--   <exec_depend>message_runtime</exec_depend> --><!-- Use test_depend for packages you need only for testing: --><!--   <test_depend>gtest</test_depend> --><!-- Use doc_depend for packages you need only for building documentation: --><!--   <doc_depend>doxygen</doc_depend> --><buildtool_depend>catkin</buildtool_depend><build_depend>roscpp</build_depend><build_depend>std_msgs</build_depend><build_depend>message_generation</build_depend><build_export_depend>roscpp</build_export_depend><build_export_depend>std_msgs</build_export_depend><exec_depend>roscpp</exec_depend><exec_depend>std_msgs</exec_depend><exec_depend>message_runtime</exec_depend><!-- The export tag contains other, unspecified, tags --><export><!-- Other tools can request additional information be placed here --></export>
</package>

修改配置
CMakeLists.txt

cmake_minimum_required(VERSION 3.0.2)
project(addserver)## Compile as C++11, supported in ROS Kinetic and newer
# add_compile_options(-std=c++11)## Find catkin macros and libraries
## if COMPONENTS list like find_package(catkin REQUIRED COMPONENTS xyz)
## is used, also find other catkin packages
find_package(catkin REQUIRED COMPONENTSroscppstd_msgsmessage_generation
)## System dependencies are found with CMake's conventions
# find_package(Boost REQUIRED COMPONENTS system)## Uncomment this if the package has a setup.py. This macro ensures
## modules and global scripts declared therein get installed
## See http://ros.org/doc/api/catkin/html/user_guide/setup_dot_py.html
# catkin_python_setup()################################################
## Declare ROS messages, services and actions ##
################################################## To declare and build messages, services or actions from within this
## package, follow these steps:
## * Let MSG_DEP_SET be the set of packages whose message types you use in
##   your messages/services/actions (e.g. std_msgs, actionlib_msgs, ...).
## * In the file package.xml:
##   * add a build_depend tag for "message_generation"
##   * add a build_depend and a exec_depend tag for each package in MSG_DEP_SET
##   * If MSG_DEP_SET isn't empty the following dependency has been pulled in
##     but can be declared for certainty nonetheless:
##     * add a exec_depend tag for "message_runtime"
## * In this file (CMakeLists.txt):
##   * add "message_generation" and every package in MSG_DEP_SET to
##     find_package(catkin REQUIRED COMPONENTS ...)
##   * add "message_runtime" and every package in MSG_DEP_SET to
##     catkin_package(CATKIN_DEPENDS ...)
##   * uncomment the add_*_files sections below as needed
##     and list every .msg/.srv/.action file to be processed
##   * uncomment the generate_messages entry below
##   * add every package in MSG_DEP_SET to generate_messages(DEPENDENCIES ...)## Generate messages in the 'msg' folder
# add_message_files(
#   FILES
#   Message1.msg
#   Message2.msg
# )## Generate services in the 'srv' folder
add_service_files(FILESAddInt.srv
)## Generate actions in the 'action' folder
# add_action_files(
#   FILES
#   Action1.action
#   Action2.action
# )## Generate added messages and services with any dependencies listed here
generate_messages(DEPENDENCIESstd_msgs
)################################################
## Declare ROS dynamic reconfigure parameters ##
################################################## To declare and build dynamic reconfigure parameters within this
## package, follow these steps:
## * In the file package.xml:
##   * add a build_depend and a exec_depend tag for "dynamic_reconfigure"
## * In this file (CMakeLists.txt):
##   * add "dynamic_reconfigure" to
##     find_package(catkin REQUIRED COMPONENTS ...)
##   * uncomment the "generate_dynamic_reconfigure_options" section below
##     and list every .cfg file to be processed## Generate dynamic reconfigure parameters in the 'cfg' folder
# generate_dynamic_reconfigure_options(
#   cfg/DynReconf1.cfg
#   cfg/DynReconf2.cfg
# )###################################
## catkin specific configuration ##
###################################
## The catkin_package macro generates cmake config files for your package
## Declare things to be passed to dependent projects
## INCLUDE_DIRS: uncomment this if your package contains header files
## LIBRARIES: libraries you create in this project that dependent projects also need
## CATKIN_DEPENDS: catkin_packages dependent projects also need
## DEPENDS: system dependencies of this project that dependent projects also need
catkin_package(
#  INCLUDE_DIRS include
#  LIBRARIES addserverCATKIN_DEPENDS roscpp std_msgs message_runtime
#  DEPENDS system_lib
)###########
## Build ##
############# Specify additional locations of header files
## Your package locations should be listed before other locations
include_directories(
# include${catkin_INCLUDE_DIRS}
)## Declare a C++ library
# add_library(${PROJECT_NAME}
#   src/${PROJECT_NAME}/addserver.cpp
# )## Add cmake target dependencies of the library
## as an example, code may need to be generated before libraries
## either from message generation or dynamic reconfigure
# add_dependencies(${PROJECT_NAME} ${${PROJECT_NAME}_EXPORTED_TARGETS} ${catkin_EXPORTED_TARGETS})## Declare a C++ executable
## With catkin_make all packages are built within a single CMake context
## The recommended prefix ensures that target names across packages don't collide
add_executable(addserver src/smain.cpp)
add_executable(addclient src/cmain.cpp)## Rename C++ executable without prefix
## The above recommended prefix causes long target names, the following renames the
## target back to the shorter version for ease of user use
## e.g. "rosrun someones_pkg node" instead of "rosrun someones_pkg someones_pkg_node"
# set_target_properties(${PROJECT_NAME}_node PROPERTIES OUTPUT_NAME node PREFIX "")## Add cmake target dependencies of the executable
## same as for the library above
add_dependencies(addserver ${PROJECT_NAME}_gencpp)
add_dependencies(addclient ${PROJECT_NAME}_gencpp)## Specify libraries to link a library or executable target against
target_link_libraries(addserver${catkin_LIBRARIES}
)
target_link_libraries(addclient${catkin_LIBRARIES}
)#############
## Install ##
############## all install targets should use catkin DESTINATION variables
# See http://ros.org/doc/api/catkin/html/adv_user_guide/variables.html## Mark executable scripts (Python etc.) for installation
## in contrast to setup.py, you can choose the destination
# catkin_install_python(PROGRAMS
#   scripts/my_python_script
#   DESTINATION ${CATKIN_PACKAGE_BIN_DESTINATION}
# )## Mark executables for installation
## See http://docs.ros.org/melodic/api/catkin/html/howto/format1/building_executables.html
# install(TARGETS ${PROJECT_NAME}_node
#   RUNTIME DESTINATION ${CATKIN_PACKAGE_BIN_DESTINATION}
# )## Mark libraries for installation
## See http://docs.ros.org/melodic/api/catkin/html/howto/format1/building_libraries.html
# install(TARGETS ${PROJECT_NAME}
#   ARCHIVE DESTINATION ${CATKIN_PACKAGE_LIB_DESTINATION}
#   LIBRARY DESTINATION ${CATKIN_PACKAGE_LIB_DESTINATION}
#   RUNTIME DESTINATION ${CATKIN_GLOBAL_BIN_DESTINATION}
# )## Mark cpp header files for installation
# install(DIRECTORY include/${PROJECT_NAME}/
#   DESTINATION ${CATKIN_PACKAGE_INCLUDE_DESTINATION}
#   FILES_MATCHING PATTERN "*.h"
#   PATTERN ".svn" EXCLUDE
# )## Mark other files for installation (e.g. launch and bag files, etc.)
# install(FILES
#   # myfile1
#   # myfile2
#   DESTINATION ${CATKIN_PACKAGE_SHARE_DESTINATION}
# )#############
## Testing ##
############### Add gtest based cpp test target and link libraries
# catkin_add_gtest(${PROJECT_NAME}-test test/test_addserver.cpp)
# if(TARGET ${PROJECT_NAME}-test)
#   target_link_libraries(${PROJECT_NAME}-test ${PROJECT_NAME})
# endif()## Add folders to be run by python nosetests
# catkin_add_nosetests(test)

六、 运行截图

在这里插入图片描述

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/pingmian/23651.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

【SpringBoot + Vue 尚庭公寓实战】项目初始化准备(二)

尚庭公寓SpringBoot Vue 项目实战】项目初始化准备&#xff08;二&#xff09; 文章目录 尚庭公寓SpringBoot Vue 项目实战】项目初始化准备&#xff08;二&#xff09;1、导入数据库2、创建工程3、项目初始配置3.1、SpringBoot依赖配置3.2、创建application.yml文件3.3、创建…

【Linux取经路】网络套接字编程——TCP篇

文章目录 前言十、Tcp Server 端代码10.1 socket、bind10.1 listen——监听一个套接字10.2 accept——获取一个新连接10.3 read——从套接字中读取数据10.4 write——向套接字中进行写入10.5 Tcp Service 端完整代码&#xff08;单进程版&#xff09;10.6 Tcp Server 端代码&am…

这个世界,对于心态好的人,就是个大游乐场,越刺激越好玩。对于胆小鬼,那就是地狱,随时随地都会受伤

心态决定你的世界&#xff1a;游乐场还是地狱 在这个充满变数的世界里&#xff0c;我们的心态决定了我们看待世界的方式。对于心态积极的人来说&#xff0c;世界就像一个巨大的游乐场&#xff0c;每一个挑战都是一个新的游戏&#xff0c;每一个刺激都是乐趣的一部分。而对于那…

解决跨域的几种方法

解决跨域的方法主要有以下几种&#xff1a; 1.CORS&#xff08;跨域资源共享&#xff09; CORS是一种W3C规范&#xff0c;它定义了一种浏览器和服务器交互的方式来确定是否允许跨源请求。 服务器通过设置响应头Access-Control-Allow-Origin来允许或拒绝跨域请求。例如&#xf…

[笔试训练](三十四)100:[NOIP2008]ISBN号码101:kotori和迷宫102:矩阵最长递增路径

目录 100:[NOIP2008]ISBN号码 101:kotori和迷宫 102:矩阵最长递增路径 100:[NOIP2008]ISBN号码 题目链接:[NOIP2008]ISBN号码_牛客题霸_牛客网 (nowcoder.com) 题目&#xff1a; 题解: 简单模拟 #include <iostream> #include<string> using namespace std; str…

5-Django项目--分页与搜索(资产页面)

目录 views/asset_data.py asset_data/asset_data.html 搜索与分页笔记: 搜索 整数搜索 字符串搜索 分页 views/asset_data.py # -*- coding:utf-8 -*- from django.shortcuts import render, redirect, HttpResponse from django.utils.safestring import mark_safe f…

电子元器件采购商城的售后服务保障

电子元器件采购商城的售后服务保障是用户在采购电子元器件时的重要考量因素之一。以下是常见的售后服务保障内容&#xff1a; 退换货政策&#xff1a; 质量问题退换货&#xff1a;如果用户收到的元器件存在质量问题&#xff0c;通常可以在一定时间内申请退换货。无理由退换货&a…

数据分析第一天(pandas简单的对快餐店数据进行操作获得想要的信息,使用apply,groupby)

前言 数据保存在 https://github.com/harkbox/DataAnalyseStudy 数据名称&#xff1a;快餐数据.tsv &#xff08;tsv是用\t作为字符分隔符的文件格式&#xff1b;csv是逗号&#xff09; 因此可以用pandas的read_csv函数读取数据 1.读取数据 import pandas as pd import matp…

PCA算法

PCA算法 原创 小王搬运工 时序课堂 2024-06-06 19:16 四川 1. PCA算法 PCA算法称为主成分分析&#xff0c;是一种无监督学习算法&#xff0c;主要用于数据降维和特征提取。 PCA是一种数据降维模型&#xff0c;它的基本模型是通过线性变换将数据转换到新的空间&#xff0c;这…

windows架设NTP时间服务器进行时间同步

一、windows架设NTP时间服务器 1.win11更改注册表 winR输入regedit 2.HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\W32Time\Config&#xff0c;找到Config目录&#xff0c;双击Config目录下的AnnounceFlags&#xff0c;设为5。 3.HKEY_LOCAL_MACHINE\SYSTEM\Current…

【养老政策问答】银发经济你怎么看?

概述 养老政策问答是一个专门为老年人设计的一站式问答服务平台。该应用旨在为用户提供关于养老政策的全面信息和专业解答&#xff0c;帮助老年人理解和获取相关政策的详细内容&#xff0c;享受无忧的老年生活。用户可以通过此应用获取关于基本养老保险、养老保险的缴费与领取…

第二十六章CSS3续~

3.CSS3渐变属性 CSS3渐变(gradients)可以在两个或多个指定的颜色之间显示平稳的过渡。 以前&#xff0c;我们必须使用图像来实现这些效果。但是&#xff0c;通过使用CSS3渐变(gradients)&#xff0c;可以减少下载的事件和宽带的使用。由于渐变(gradient)是由浏览器生成的&…

YOLOv3深入解析与实战:实时目标检测的高效多尺度架构网络

参考&#xff1a; https://arxiv.org/pdf/1804.02767.pdf https://blog.csdn.net/weixin_43334693/article/details/129143961 网上有很多关于yolo的文章&#xff0c;有些东西没讲清楚&#xff0c;基于自己对论文的理解&#xff0c;也做一个按照自己的想法做的理解。 1. 预测…

神经网络 torch.nn---损失函数与反向传播

torch.nn - PyTorch中文文档 (pytorch-cn.readthedocs.io) torch.nn — PyTorch 2.3 documentation Loss Function的作用 每次训练神经网络的时候都会有一个目标&#xff0c;也会有一个输出。目标和输出之间的误差&#xff0c;就是用Loss Function来衡量的。所以&#xff0c;…

Qt图像处理技术十一:得到QImage图像的马赛克图像

效果图 指数5 指数15 指数40 原理 马赛克的原理很简单&#xff0c;就是取一个值&#xff0c;让这个值作为一个方格子的长宽&#xff0c;如40*40px的格子&#xff0c;取这个区域的平均R G B值&#xff0c;然后这个区域的所有像素点都是这个RGB值即可 源码 QImage applyM…

力扣2968.执行操作使频率分数最大

力扣2968.执行操作使频率分数最大 方法一&#xff1a;滑窗 前缀和 求前缀和数组s 求一个数组补齐到中位数的差值 枚举右端点 class Solution {public:int maxFrequencyScore(vector<int>& nums, long long k) {int res0,n nums.size();sort(nums.begin(),nums…

27-unittest之断言(assert)

在测试方法中需要判断结果是pass还是fail&#xff0c;自动化测试脚本里面一般把这种生成测试结果的方法称为断言&#xff08;assert&#xff09;。 使用unittest测试框架时&#xff0c;有很多的断言方法&#xff0c;下面介绍几种常用的断言方法&#xff1a;assertEqual、assert…

Vue可视化表单设计 FcDesigner v3.1.0 发布,新增 12 个组件,支持事件配置等

FcDesigner 是一款可视化表单设计器组件。可以通过拖拽的方式快速创建表单&#xff0c;提高开发者对表单的开发效率&#xff0c;节省开发者的时间。 本项目采用 Vue 和 ElementPlus 进行页面构建&#xff0c;内置多语言解决方案&#xff0c;支持二次扩展开发&#xff0c;支持自…

【cmake】cmake cache

cmake cache是什么 cmake cache是cmake在配置好后生成的一个CMakeCache.txt的文件&#xff0c;里面存储了一堆变量&#xff0c;这些变量一般都是关于项目的配置和环境的。 比如你用的什么编译器&#xff0c;编译器选项&#xff0c;还有项目目录。 例如&#xff08;在cmakelist…

前端工程化工具系列(九)—— mddir(v1.1.1):自动生成文件目录结构工具

mddir 是一个基于项目目录结构动态生成 Markdown 格式目录结构的工具&#xff0c;方便开发者在文档中展示文件和文件夹的组织结构。 1. 安装 全局安装改工具&#xff0c;方便用于各个项目。 pnpm i -g mddir2. 使用 在想要生成目录接口的项目内打开命令行工具&#xff0c;输…