ROS下写服务

ROS下写服务_第1张图片

话题和服务的对比:

1.话题
话题是单向的,而且不需要等待服务端上线,直接发就行,数据的实时性比较高。

频率高,实时性强的传感器数据的传递一般使用话题实现。

ROS下写服务_第2张图片

话题通信是ROS中使用频率最高的一种通信模式,话题通信是基于发布订阅模式的,也即:一个节点发布消息,另一个节点订阅该消息。话题通信的应用场景也极其广泛。

用于不断更新的、少逻辑处理的数据传输场景。

2.服务
服务是双向的,客户端发送请求后,服务端有响应,可以得知服务端的处理结果。

频率较低,强调服务特性和反馈的场景一般使用服务实现。

ROS下写服务_第3张图片

服务通信也是ROS中一种极其常用的通信模式,服务通信是基于请求响应模式的,是一种应答机制。也即: 一个节点A向另一个节点B发送请求,B接收处理请求并产生响应结果返回给A。比如如下场景:

机器人巡逻过程中,控制系统分析传感器数据发现可疑物体或人... 此时需要拍摄照片并留存。

在上述场景中,就使用到了服务通信。

一个节点需要向相机节点发送拍照请求,相机节点处理请求,并返回处理结果
与上述应用类似的,服务通信更适用于对时时性有要求、具有一定逻辑处理的应用场景。
 

ROS下写服务_第4张图片

 2,编写简单的服务

 参考链接: [ROS学习]ROS服务浅析及简单实现(C++)_c++ ros 服务_Haley__xu的博客-CSDN博客

如果没有工作空间,可以先创建一个工作空间,创建工作空间的步骤为:

mkdir -p haley_ws/src
cd haley_ws/src/
catkin_init_workspace 

在该工作空间下创建功能包,包名命名为: haley_service

catkin_create_pkg haley_service roscpp std_msgs

 2.1 创建服务的消息

创建所需的自定义服务消息(srv),这里我们定义一个求和的srv,在sum.srv中写入消息的格式。

mkdir srv
cd srv
touch sum.srv

 sum.srv的内容如下,这里的上半部分是请求数据格式,下半部分是应答的数据格式。中间必须用三个短线隔开。

int32 A
int32 B

---

int32 SUM

 现在来查看一下我们的srv消息吧
(a)编译工作空间
(b)查看srv格式

catkin_make
source ./devel/setup.bash 
rossrv show haley_service/sum 

消息格式的显示的结果如下图所示: 

ROS下写服务_第5张图片

 2.2 编写服务

在haley_service功能包下的src中建立service.cpp,并写入如下内容:

#include "ros/ros.h"
#include "haley_service/sum.h"

/**
*   服务器的回调函数
*   输入参数:服务所需的请求消息,这里是定义好的sum.srv中的Request数据形式
*   对服务请求数据进行求和操作,返回Response数据
**/
bool add(haley_service::sum::Request& req, haley_service::sum::Response& res)
{
    res.SUM = req.A + req.B;
    ROS_INFO("Response the request: %d + %d = %d", req.A ,req.B, res.SUM);
    return true;
}

/**
*   主函数
**/
int main(int argc, char** argv)
{
    //初始化节点,节点名为sum_service_node
    ros::init(argc, argv, "sum_service_node");
    //初始化句柄
    ros::NodeHandle n;
    //建立一个服务实例,服务端的名称为:sum_server。使用服务函数为add
    ros::ServiceServer service = n.advertiseService("sum_server", add);
    //判断服务是否建立成功
    if (service)
    {
        ROS_INFO("Server has been ready...");
        ros::spin();
    }
    else
    {   
        ROS_ERROR("Server not ready !");
        return 1;
    }
    return 0;
}

2.3 对Cmake和package.xml做处理

我们发现在haley_service的软件包下的CMakeLists.txt有这样一段话(大概在24-46行)

################################################
## 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 ...)

说的还是比较明白的,这里说说自己的理解:
要声明和建立像messages、services和actions按照下面的步骤操作就行:
(1) 在package.xml里做如下的操作
添加message_generation的依赖标记
添加message_runtime的标记
(2)在CMakeLists.txt的处理
在 find_package(…)添加message_generation和每个使用的消息包集
在 catkin_package(CATKIN_DEPENDS…)添加message_runtime和每个使用的消息包集
取消需要的add_*_files的注释
在generate_messages(…)中添加使用的消息包集

依照上面的说法,修改对应的文件

 2.3.1 在package.xml中打开注释

message_generation
message_runtime

在第40和46行: 

ROS下写服务_第6张图片

 2.3.2 在CMakeLists.txt下做处理

在find_package添加message_generation

find_package(catkin REQUIRED COMPONENTS
  roscpp
  std_msgs
  message_generation
)

 在 catkin_package(CATKIN_DEPENDS…)添加message_runtime

catkin_package(
#  INCLUDE_DIRS include
#  LIBRARIES haley_service
#  CATKIN_DEPENDS roscpp std_msgs
#  DEPENDS system_lib
   CATKIN_DEPENDS message_runtime
)

ROS下写服务_第7张图片

 取消需要的add_*_files的注释,将服务的消息添加进去:

add_service_files(
  FILES
  sum.srv
)

ROS下写服务_第8张图片

在generate_messages(…)中添加使用的消息包集,(这一步很重要,不然无法生成相应的头文件)

generate_messages(
  DEPENDENCIES
  std_msgs
)

搞定了消息的处理,现在将service.cpp也加入编译。 在CMakeLists.txt添加如下的内容

add_executable(${PROJECT_NAME}_node src/service.cpp)

target_link_libraries(${PROJECT_NAME}_node
  ${catkin_LIBRARIES}
)

 最终CMakeLists.txt的内容如下:

cmake_minimum_required(VERSION 3.0.2)
project(haley_service)

## 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
  sum.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 haley_service
#  CATKIN_DEPENDS roscpp std_msgs
#  DEPENDS system_lib
CATKIN_DEPENDS message_runtime
)

###########
## Build ##
###########

## Specify additional locations of header files
## Your package locations should be listed before other locations
include_directories(
# include
  ${catkin_INCLUDE_DIRS}
)

add_executable(haley_service_node src/service.cpp)

target_link_libraries(haley_service_node
  ${catkin_LIBRARIES}
)


## Declare a C++ library
# add_library(${PROJECT_NAME}
#   src/${PROJECT_NAME}/haley_service.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(${PROJECT_NAME}_node src/haley_service_node.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(${PROJECT_NAME}_node ${${PROJECT_NAME}_EXPORTED_TARGETS} ${catkin_EXPORTED_TARGETS})

## Specify libraries to link a library or executable target against
# target_link_libraries(${PROJECT_NAME}_node
#   ${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_haley_service.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)

然后进行编译,编译没有错误后,进入下面的测试环境。

3,测试

运行服务

roscore

rosrun   haley_service   haley_service_node

ROS下写服务_第9张图片 调用服务:

打开一个终端,source后,执行以下语句:

rosservice call /sum_server 4 5

ROS下写服务_第10张图片

 查看活跃的服务:

rosservice list            //查看活跃的Server,然后Call他

 ROS下写服务_第11张图片

 使用rqt调用服务:

rosrun haley_service haley_service_node 

rosrun rqt_service_caller rqt_service_caller 

 双击Expression进行数值的输入,然后点击call就可以执行ROS下写服务_第12张图片

4. 使用c++写一个客户端测试服务

创建一个 client.cpp,内容如下:

#include 
#include "ros/ros.h"
#include "haley_service/sum.h"

#include "iostream"
using namespace std;
 
int main(int argc, char **argv)
{
  // ROS节点初始化
  ros::init(argc, argv, "add_two_ints_client");
  
  // 从终端命令行获取两个加数
  if (argc != 3)
  {
    ROS_INFO("usage: add_two_ints_client X Y");
    return 1;
  }
 
  // 创建节点句柄
  ros::NodeHandle n;
  
  // 创建一个client,请求add_two_int service,service消息类型是learning_communication::AddTwoInts
  ros::ServiceClient client = n.serviceClient("sum_server");
  
  // 创建learning_communication::AddTwoInts类型的service消息
  haley_service::sum srv;
  srv.request.A= atoll(argv[1]);
  srv.request.B = atoll(argv[2]);
  
  std::cout<<"!!!!!!!!!!!!!!!!!"<

在CMakeLists.txt的内容中添加如下的内容:

add_executable(haley_client_node  src/client.cpp)

target_link_libraries(haley_client_node ${catkin_LIBRARIES})

运行打开三个终端

roscore

 rosrun haley_service haley_service_node 

rosrun haley_service haley_client_node 1314 521

 

你可能感兴趣的:(ROS,linux)