本文主要参考以下文章:
本文继续上一篇学习并记录下重要的操作过程。
十四、写一个简单的 Service 和 client
本节涉及到用 C++ 写一个 service 和 client 节点
14.1 写一个 Service Node
// AddTwoIntsServer.cpp
#include "ros/ros.h"
// 从之前创建的 ‘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 文件
# 在上一节的基础上添加如下内容
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/ 中,通过执行 catkin_make 命令后生成的相关可执行文件存在于 /catkin_ws/devel/lib/beginner_tutorials/ 中。
网友评论