本文主要參考以下文章:
本文繼續(xù)上一篇學習并記錄下重要的操作過程。
十四、寫一個簡單的 Service 和 client
本節(jié)涉及到用 C++ 寫一個 service 和 client 節(jié)點
14.1 寫一個 Service Node
// AddTwoIntsServer.cpp
#include "ros/ros.h"
// 從之前創(chuàng)建的 ‘srv’ 文件生成而來
#include "beginner_tutorials/AddTwoInts.h"
bool add(beginner_tutorials::AddTwoInts::Request &req,
beginner_tutorials::AddTwoInts::Response &resp)
{
// 此處的 .*要與 srv/*.srv中的命名相對應
resp.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)resp.sum);
return true;
}
int main(int argc, char **argv)
{
ros::init(argc, argv, "AddTwoIntsServer");
ros::NodeHandle n;
ros::ServiceServer service = n.advertiseService("AddTwoInts", add);
ROS_INFO("Ready to add two ints.");
ros::spin();
return 0;
}
14.2 寫一個client node
// AddTwoIntsClient.cpp
#include "ros/ros.h"
#include "beginner_tutorials/AddTwoInts.h"
#include <cstdlib>
int main(int argc, char **argv)
{
ros::init(argc, argv, "AddTwoIntsClient");
if (argc != 3){
ROS_INFO("usage: AddTwoIntsClient X Y");
return 1;
}
ros::NodeHandle n;
ros::ServiceClient client = n.serviceClient<beginner_tutorials::AddTwoInts>("AddTwoInts");
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("Sum:%ld", (long int)srv.response.sum);
return 1;
}
return 0;
}
14.3 完善一下 CMakeLists.txt 文件
# 在上一節(jié)的基礎(chǔ)上添加如下內(nèi)容
add_executable(AddTwoIntsServer src/AddTwoIntsServer.cpp)
target_link_libraries(AddTwoIntsServer ${catkin_LIBRARIES})
add_dependencies(AddTwoIntsServer beginner_tutorials_gencpp)
add_executable(AddTwoIntsClient src/AddTwoIntsClient.cpp)
target_link_libraries(AddTwoIntsClient ${catkin_LIBRARIES})
add_dependencies(AddTwoIntsClient beginner_tutorials_gencpp)
特別說明:AddTwoIntsClient.cpp 和 AddTwoIntsServer.cpp 程序有依賴于頭文件 beginner_tutorials/AddTwoInts.h 該頭文件存在于目錄 ~/catkin_ws/devel/include/ 中,通過執(zhí)行 catkin_make 命令后生成的相關(guān)可執(zhí)行文件存在于 /catkin_ws/devel/lib/beginner_tutorials/ 中。