服務:
一個srv文件描述一項服務。它包含兩個部分:請求和響應
服務(services)是節點之間通訊的另一種方式。服務允許節點發送請求(request) 並獲得一個響應(response)
上一篇博客講過了,如何新建工作空間和功能包,不在贅述了,在learning_communication功能包中
1、創建服務(server)節點
在功能包下的src文件下,即learning_communication/src創建服務(server)節點文件:server.cpp 內容如下:
//Add Two_Ints Server
#include "ros/ros.h" #include "learning_communication/AddTwoInts.h" // service回調函數,輸入參數req,輸出參數res 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節點初始化 ros::init(argc, argv, "add_two_ints_server"); // 創建節點句柄 ros::NodeHandle n; // 創建一個名為add_two_ints的server,注冊回調函數add() ros::ServiceServer service = n.advertiseService("add_two_ints", add); // 循環等待回調函數 ROS_INFO("Ready to add two ints."); ros::spin(); return 0; }
2、創建客戶端(client)節點
在功能包下的src文件下,即learning_communication/src創建客戶端(client)節點文件:client.cpp 內容如下:
// Add TwoInts Client #include <cstdlib> #include "ros/ros.h" #include "learning_communication/AddTwoInts.h" int main(int argc, char **argv) { // ROS節點初始化 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; // 創建一個client,請求add_two_int service // service消息類型是learning_communication::AddTwoInts ros::ServiceClient client = n.serviceClient<learning_communication::AddTwoInts>("add_two_ints"); // 創建learning_communication::AddTwoInts類型的service消息 learning_communication::AddTwoInts srv; srv.request.a = atoll(argv[1]); srv.request.b = atoll(argv[2]); // 發布service請求,等待加法運算的應答結果 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; }
創建一個srv頭文件:
int64 a int64 b --- int64 sum
3、編譯
返回工作空間根目錄進行編譯:
cd ~/ROS_Learning catkin_make
編譯完成后運行
roscore rosrun learning_communication server #需開啟新終端 rosrun learning_communication client #需開啟新終端
運行結果如圖所示: