ROS编程(二)——基于service通信的代码编写

1.查看service列表的代码:

rosservice list

可以用代码或者终端对列表中的服务进行调用:

rosservice call /服务名称

2.service介绍

client负责发布请求数据等待server处理 ---------------数据
server负责处理相应功能并返回应答数据--------------操作

3.自定义服务数据

在srv文件夹下的.srv文件,其中包括请求和应答的数据,用“- - -”进行分割。
(1)在Package.xml中添加功能包依赖

message_generation
message_runtime

(2)在CMakeLists.txt中添加功能包依赖

find_package(catkin REQUIRED COMPONENTS
roscpp
std_msgs
message_generation
)
add_service_files(
FILES
AddTwoInts.msg
)

4.编写server和client代码

server:

#include "ros/ros.h"
#include "learning_communication/AddTwoInts.h"

bool add(learning_communication::AddTwoInts::Request  &req,
         learning_communication::AddTwoInts::Response &res)
{
  res.sum = req.a + req.b;
  ROS_INFO("request: x=%ld, y=%ld", (long int)req.a, (long int)req.b);
  ROS_INFO("sending back response: [%ld]", (long int)res.sum);
  return true;
}

int main(int argc, char **argv)
{
  ros::init(argc, argv, "add_two_ints_server");
  ros::NodeHandle n; 
  ros::ServiceServer service = n.advertiseService("add_two_ints", add);
  ROS_INFO("Ready to add two ints.");
  ros::spin();

  return 0;

client:

#include "ros/ros.h"
#include "learning_communication/AddTwoInts.h"
#include 

int main(int argc, char **argv)
{
  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;
  ros::ServiceClient client = n.serviceClient("add_two_ints");
  beginner_tutorials::AddTwoInts srv;
  srv.request.a = atoll(argv[1]);
  srv.request.b = atoll(argv[2]);
  if (client.call(srv))
  {
    ROS_INFO("Sum: %ld", (long int)srv.response.sum);
  }
  else
  {
    ROS_ERROR("Failed to call service add_two_ints");
    return 1;
  }

  return 0;
}

5.编译功能包

add_executable(add_two_ints_server src/add_two_ints_server.cpp)
target_link_libraries(add_two_ints_server ${catkin_LIBRARIES})
add_dependencies(add_two_ints_server beginner_tutorials_gencpp)

add_executable(add_two_ints_client src/add_two_ints_client.cpp)
target_link_libraries(add_two_ints_client ${catkin_LIBRARIES})
add_dependencies(add_two_ints_client beginner_tutorials_gencpp)

注意:add_executable中的第一个参数为期望生成的可执行文件的而名称,第二个参数为源码文件;target_link_libraries第一个参数与add_executable相同;

6.分别运行两个节点即可

你可能感兴趣的:(ros编程,Linux)