C++入门 ros服务通信

news2024/11/14 12:07:47

一、 开发环境

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 COMPONENTS
  roscpp
  std_msgs
  message_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(
  FILES
  AddInt.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(
  DEPENDENCIES
  std_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 addserver
 CATKIN_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.coloradmin.cn/o/1794942.html

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

相关文章

数据结构(3)栈、队列、数组

1 栈 1.1 栈的定义 后进先出【LIFO】 1.2 基本操作 元素进栈出栈 只能在栈顶进行&#xff01;&#xff01;&#xff01; 经常考的题&#xff1a; 穿插的进行进栈和出栈 可能有多个选项 1.3 顺序栈 1.3.1 初始化 下标是从0开始的 1.3.2 进栈 更简单的写法&#xff1a; 1.3…

记录某书请求返回406及响应{“code“:-1,“success“:false}

今天测试某个平台的爬虫时使用requests post请求正常写了个测试脚本把各种参数带上出来以后出现了406情况&#xff0c;和网站数据是完全一样的 以为是 X-S、X-T参接不对&#xff0c;但在postman里测试又是可以的成功&#xff0c;以为是检验了参数顺序&#xff0c;测试发现也没…

【机器学习系列】“购物篮分析入门:使用Apyori库进行关联规则挖掘”

目录 一、关联分析介绍 关键概念&#xff1a; 1. 支持度&#xff08;Support&#xff09; 2. 置信度&#xff08;Confidence&#xff09; 3. 提升度&#xff08;Lift&#xff09; 4. 频繁项集 5. 关联规则 应用场景&#xff1a; 实现方法 二、导入数据集 额外介绍一…

动态IP与静态IP的优缺点

在网络连接中&#xff0c;使用动态和静态 IP 地址取决于连接的性质和要求。静态 IP 地址通常更适合企业相关服务&#xff0c;而动态 IP 地址更适合家庭网络。让我们来看看动态 IP 与静态 IP 的优缺点。 1.静态IP的优点&#xff1a; 更好的 DNS 支持&#xff1a;静态 IP 地址在…

⾃动化批量管理-Ansible

目录 一、ansible 简介 自动化工具选择 &#xff08;了解&#xff09;​编辑 1、ansible 是什么&#xff1f; 2、ansible 特点 3、ansible 架构图 二、ansible 任务执行 1、ansible 任务执行模式 2、ansible 执行流程 3、ansible 命令执行过程 三、ansible 配置详解 …

6、架构-服务端缓存

为系统引入缓存之前&#xff0c;第一件事情是确认系统是否真的需要缓 存。从开发角度来说&#xff0c;引入缓存会提 高系统复杂度&#xff0c;因为你要考虑缓存的失效、更新、一致性等问题&#xff1b;从运维角度来说&#xff0c;缓存会掩盖一些缺 陷&#xff0c;让问题在更久的…

Nginx企业级负载均衡:技术详解系列(18)—— 作为上传服务器

你好&#xff0c;我是赵兴晨&#xff0c;97年文科程序员。 在上一期的技术分享中&#xff0c;我们探讨了如何高效搭建Nginx下载服务器&#xff0c;并讨论了长连接优化策略。那么今天&#xff0c;咱们进一步了解Nginx的另一面——作为上传服务器的配置技巧。 作为上传服务器&a…

RPC 框架

RPC 全称 Remote Procedure Call——远程过程调用。 RPC技术简单说就是为了解决远程调用服务的一种技术&#xff0c;使得调用者像调用本地服务一样方便透明。RPC是一种通过网络从远程计算机程序上请求服务&#xff0c;不需要了解底层网络技术的协议。 集群和分布式 集群&…

【matlab】绘图插入并放大/缩小子图

参考链接 代码分为两个&#xff1a;绘图代码与magnify.m 绘图代码就是普通的绘图代码&#xff0c;以下为例 %https://zhuanlan.zhihu.com/p/655767542 clc clear close all x 0:pi/100:2*pi; y1 sin(x); plot(x,y1,r-o); hold on y2sin(x)-0.05; y3sin(x)0.05; xlim([0 2*…

企业在现代市场中的战略:通过数据可视化提升财务决策

新时代&#xff0c;财务规划团队不仅仅是企业内部的一个部门&#xff0c;更是帮助企业做出明智决策和设定战略目标的中坚力量。在当今瞬息万变的商业环境中&#xff0c;财务专业人士需要具备应对挑战并引导企业走向成功的角色职能。企业领导者时常面临着数据压力&#xff0c;需…

混剪素材哪里找?分享几个热门混剪素材下载网站

在短视频和新媒体的世界里&#xff0c;高质量的混剪素材是吸引观众的关键。今天&#xff0c;我将为大家详细介绍几个优秀的素材网站&#xff0c;它们不仅资源丰富&#xff0c;而且完全满足新媒体创作者的需求。这篇文章将帮助你理解如何有效利用这些平台提升你的视频创作。 蛙…

小型企业网络组网与配置仿真实验

实验要求如下: 我这里以学号46为例 一、IP 地址规划表 &#xff08;一&#xff09;主类网络 &#xff08;二&#xff09;子网划分 需要自己计算有效ip范围 在C类主网络192.168.46.0/24中&#xff0c;我们需要先了解这个网络的子网掩码为255.255.255.0&#xff0c;其二进制…

DDMA信号处理以及数据处理的流程---DDMA原理介绍

Hello&#xff0c;大家好&#xff0c;我是Xiaojie&#xff0c;好久不见&#xff0c;欢迎大家能够和Xiaojie一起学习毫米波雷达知识&#xff0c;Xiaojie准备连载一个系列的文章—DDMA信号处理以及数据处理的流程&#xff0c;本系列文章将从目标生成、信号仿真、测距、测速、cfar…

Vitis HLS 学习笔记--接口聚合与解聚-AXI主接口

目录 1. 简介 2. 用法及语法 3. 详细解读 4. 总结 1. 简介 在使用 Vitis HLS 工具进行硬件设计时&#xff0c;如果你在接口上使用了结构体&#xff0c;工具会自动把结构体里的所有元素组合成一个整体。就像把一堆零件组装成一个玩具一样。这样做的好处是&#xff0c;数据可…

【System Verilog and UVM基础入门4】程序和接口

目录 方法task和函数function 接口 [System Verilog特性] 方法task和函数function 首先要明白一个事情!Task任务,是消耗时间的,函数function是不消耗时间的! 这样写看着是不是很高大上呢?此外,如果我们想修改时钟周期怎么办呢?这时我们可以在task clk_gen(int period…

从报名到领证:软考高级【系统分析师】报名考试全攻略

本文共计13156字&#xff0c;预计阅读39分钟。包括七个篇章&#xff1a;报名、准考证打印、备考、考试、成绩查询、证书领取及常见问题。 不想看全文的可以点击目录&#xff0c;找到自己想看的篇章进行阅读。 一、报名篇 报名条件要求&#xff1a; 1.凡遵守中华人民共和国宪…

盛夏之约,即将启程,2024中国北京消防展将于6月26举行

盛夏之约&#xff0c;即将启程&#xff0c;2024中国北京消防展将于6月26举行 盛夏之约&#xff0c;即将启程&#xff01;备受瞩目的2024中国&#xff08;北京&#xff09;消防技术与设备展览会将于6月26-28 日在北京.首钢会展中心盛大召开。作为消防安全和应急救援的年度盛会&…

Camtasia Studio2024永久免费版及最新版本功能讲解

在当前数字化时代&#xff0c;视频内容的制作与编辑变得愈发重要。无论是企业宣传、在线教育还是个人Vlog制作&#xff0c;一款功能强大且易于上手的视频编辑软件成为了刚需。Camtasia Studio作为市场上备受欢迎的视频编辑与屏幕录像工具&#xff0c;凭借其强大的功能与用户友好…

Golang——gRPC与ProtoBuf介绍

一. 安装 1.1 gRPC简介 gRPC由google开发&#xff0c;是一款语言中立&#xff0c;平台中立&#xff0c;开源的远程过程调用系统。gRPC客户端和服务器可以在多种环境中运行和交互&#xff0c;例如用java写一个服务器端&#xff0c;可以用go语言写客户端调用。 1.2 gRPC与Protob…

android睡眠分期图

一、效果图 做医疗类项目&#xff0c;经常会遇到做各种图表&#xff0c;本文做的睡眠分期图。 二、代码 引入用到的库 api joda-time:joda-time:2.10.1 调用代码 /*** 睡眠* 分期*/private SleepChartAdapter mAdapter;private SleepChartAttrs mAttrs;private List<SleepI…