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…

MySQL 8.0中查询缓存的废弃与原因分析

MySQL 8.0中查询缓存&#xff08;Query Cache&#xff09;的废弃与原因分析 引言 尽管MySQL的查询缓存&#xff08;Query Cache&#xff09;最初设计目的是为了提升性能&#xff0c;但因其存在严重的可扩展性问题和易成为系统瓶颈&#xff0c;MySQL在8.0版本中正式移除了这一…

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

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

解决跨域的几种方法

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

python-数据分析-缺失值-函数-数据类型

1 常用排序和统计函数 1 排序 sort_values() # by 指定排序的字段 可以传入列表&#xff0c;做多字段排序&#xff0c; 比如下面的例子&#xff0c; 当价格相同的时候&#xff0c; 价格相同的数据再按面积排序 # ascending 也可以传入列表&#xff0c;长度更by 的列表相同&…

[笔试训练](三十四)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…

大数据技术Hbase列数据库——topic2

目录 启动Hadoop启动HbaseHbase常用Shell命令基本命令关于表的操作增删改查询 启动Hadoop 1.到Hadoop安装目录下输入命令 sbin/start-all.sh[rootlocalhost hadoop-2.7.1]# sbin/start-all.sh This script is Deprecated. Instead use start-dfs.sh and start-yarn.sh Starti…

Maven导入jar包到本地仓库

导入本地jar包 <dependency><groupId>com.xxl</groupId>-----------------(参数二)<artifactId>xxl-sso-client</artifactId>-----------(参数三)<version>1.1.2</version>-----------------------(参数四) </dependency>用m…

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…

MySQL查询数据库响应时长的方法

要查询MySQL数据库的响应时长&#xff0c;通常我们需要测量查询执行的时间。MySQL本身并不直接提供一个查询来显示每个查询的响应时长历史记录&#xff0c;但我们可以使用MySQL的内置函数和工具来测量和记录查询的执行时间。 以下是一些方法&#xff0c;我们可以用来测量MySQL…

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

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

Laravel PHP 给富文本内容的图片设置最大宽度(自适应)

Laravel & PHP $data->富文本字段 preg_replace(/<img\s([^>])>/i, <img $1 style"max-width: 100%;">, $data->富文本字段); Js解决 小程序富文本图片宽度自适应-CSDN博客

数据分析第一天(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…

Kotlin 内联值类(@JvmInline value class)

文章目录 定义相等判定 我并不知道它的名字是不是这样翻译&#xff0c;以前是叫内联类&#xff08;inline class&#xff09;&#xff0c;我感觉现在这样叫有点拗口&#xff0c;或者是“值内联类”&#xff1f;如果有错误&#xff0c;麻烦您花点时间告诉我一声&#xff0c;十分…

Hutool工具网络文件下载与文件压缩

1.下载文件 HttpUtil.downloadFile(url,dest) url 为网络文件路径 dest 为下载后文件 2.文件压缩 ZipUtil.zip(srcPath,zip path)

PCA算法

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

聚焦热点-浙江省“十五五”规划重大前期研究选聘课题(学习借鉴)

聚焦热点-浙江省“十五五”规划重大前期研究选聘课题&#xff08;学习借鉴&#xff09; 浙江省在经济发展、规划编制等各个方面走在全国前列&#xff0c;全国各地应学习借鉴。下面就浙江省发展和改革委员会关于“十五五”规划重大前期研究课题选聘内容梳理如下&#xff1a; 四…

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;享受无忧的老年生活。用户可以通过此应用获取关于基本养老保险、养老保险的缴费与领取…