05.ROS入門學習-Server 和 client

本文主要參考以下文章:

CSDN ROS入門教程(四)

ROS官方wiki教程

本文繼續(xù)上一篇學習并記錄下重要的操作過程。


十四、寫一個簡單的 Service 和 client

本節(jié)涉及到用 C++ 寫一個 serviceclient 節(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.cppAddTwoIntsServer.cpp 程序有依賴于頭文件 beginner_tutorials/AddTwoInts.h 該頭文件存在于目錄 ~/catkin_ws/devel/include/ 中,通過執(zhí)行 catkin_make 命令后生成的相關(guān)可執(zhí)行文件存在于 /catkin_ws/devel/lib/beginner_tutorials/ 中。

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容