ROS入门教程(四)

本文为原创博客, 转载请注明出处:https://blog.csdn.net/q_z_r_s

机器感知
一个专注于SLAM、三维重建、机器视觉等相关技术文章分享的公众号

ROS入门教程(四)_第1张图片

GitHub链接

参考自:http://wiki.ros.org/ROS/Tutorials
【Beginner Level】ROS入门教程(一)
【Beginner Level】ROS入门教程(二)
【Beginner Level】ROS入门教程(三)
【Beginner Level】ROS入门教程(四)
【Beginner Level】ROS入门教程(五)

【Beginner Level】ROS入门教程(四)

14. 写一个简单的ServiceClient

本节涉及到用C++写一个serviceclient节点

14.1 写一个Service Node
//add_two_ints_server.cpp
#include "ros/ros.h"
//从之前创建的`srv`文件生成而来
#include "beginner_tutorials/AddTwoInts.h"
bool add(beginner_tutorials::AddTwoInts::Request  &req,
         beginner_tutorials::AddTwoInts::Response &res)
{
  //此处的.*要与srv/*.srv中的命名相对应
  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;
}
14.2 写一个Client Node
//add_two_ints_client.cpp
#include "ros/ros.h"
#include "beginner_tutorials/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;
}
14.3 编写CMakeLists.txt
#向CMakeLists.txt中添加
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)

可执行程序会生成在~/catkin_ws/devel/lib/路径下.

15. 测试ServiceClient
  • 运行Service: $ rosrun beginner_tutorials add_two_ints_server
  • 运行Client: $ rosrun beginner_tutorials add_two_ints_client 1 3

你可能感兴趣的:(ROS,ROS入门教程)