ROS編程(二)——基於service通信的代碼編寫

1.查看service列表的代碼:

rosservice list

可以用代碼或者終端對列表中的服務進行調用:

rosservice call /服務名稱

2.service介紹

client負責發佈請求數據等待server處理 ---------------數據
server負責處理相應功能並返回應答數據--------------操作

3.自定義服務數據

在srv文件夾下的.srv文件,其中包括請求和應答的數據,用“- - -”進行分割。
(1)在Package.xml中添加功能包依賴

<build_depend>message_generation</build_depend>
<run_depend>message_runtime</run_depend>

(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 <cstdlib>

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<learning_communication::AddTwoInts>("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.分別運行兩個節點即可

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章