1 Premise
Create AddTwoInts.srv in the /catkin_ws/src/beginner_tutorials/srv directory
1 int64 a 2 int64 b 3 --- 4 int64 sum
2 Write the server node
[~/catkin_ws/src/beginner_tutorials]$ vim src/add_two_ints_server.cpp
The contents of add_two_ints_server.cpp are as follows:
1 #include "ros/ros.h" 2 /* is the corresponding header file automatically generated by the compiler system according to the srv file created by the user*/ 3 #include "beginner_tutorials/AddTwoInts.h" 4 5 bool add(beginner_tutorials::AddTwoInts::Request &req, 6 beginner_tutorials::AddTwoInts::Response &res) 7 { 8 res.sum = req.a + req.b; 9 ROS_INFO("request: x=%ld, y=%ld", (long int)req.a, (long int)req.b); 10 ROS_INFO("sending back response: [%ld]", (long int)res.sum); 11 return true; 12 } 13 14 15 int main(int argc, char **argv) 16 { 17 ros::init(argc, argv, "add_two_ints_server"); 18 ros::NodeHandle n; 19 /* Create a server and publish it in ros*/ 20 ros::ServiceServer service = n.advertiseService("add_two_ints", add); 21 ROS_INFO("Ready to add two ints."); 22 ros::spin(); 23 24 return 0; 25 } 26
3 Write the client node
[~/catkin_ws/src/beginner_tutorials]$ vim src/add_two_ints_client.cpp
The contents of add_two_ints_client.cpp are as follows:
1 #include "ros/ros.h" 2 #include "beginner_tutorials/AddTwoInts.h" 3 #include <cstdlib> 4 5 6 int main(int argc,char **argv) 7 { 8 ros::init(argc, argv, "add_two_ints_client"); 9 if(argc != 3) 10 { 11 ROS_INFO("usage: add_two_ints_client"); 12 return 1; 13 } 14 15 ros::NodeHandle n; 16 ros::ServiceClient client = n.serviceClient<beginner_tutorials::AddTwoIn ts>("add_two_ints"); 17 beginner_tutorials::AddTwoInts srv; 18 srv.request.a = atoll(argv[1]); 19 srv.request.b = atoll(argv[2]); 20 if(client.call(srv)) 21 { 22 ROS_INFO("Sum: %ld", (long int)srv.response.sum); 23 } 24 else 25 { 26 ROS_INFO("Failed to call service add_two_ints"); 27 return 1; 28 } 29 30 return 0; 31 32 33 } 34 35
4 Compile
Modify the CMakeLists.txt file and add at the end of the file
211 212 add_executable(add_two_ints_server src/add_two_ints_server.cpp) 213 target_link_libraries(add_two_ints_server ${catkin_LIBRARIES}) 214 add_dependencies(add_two_ints_server beginner_tutorials_gencpp) 215 216 add_executable(add_two_ints_client src/add_two_ints_client.cpp) 217 target_link_libraries(add_two_ints_client ${catkin_LIBRARIES}) 218 add_dependencies(add_two_ints_client beginner_tutorials_gencpp)compile
[~/catkin_ws]$ catkin_make
5 Verify
runService
rosrun beginner_tutorials add_two_ints_server
Start another terminal and run the Client
rosrun beginner_tutorials add_two_ints_client 1 3
The service side shows:
Client
display