本文主要部分来源于ROS官网的Tutorials.
Writing a Service Node
roscd beginner_tutorials gedit src/add_two_ints_server.cpp
粘贴如下代码:
#include "ros/ros.h" #include "beginner_tutorials/AddTwoInts.h" bool add(beginner_tutorials::AddTwoInts::Request &req, beginner_tutorials::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; }
Writing the Client Node
gedit src/add_two_ints_client.cpp
粘贴如下代码:
#include "ros/ros.h" #include "beginner_tutorials/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<beginner_tutorials::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; }
Building your nodes
Edit the beginner_tutorials CMakeLists.txt located at ~/catkin_ws/src/beginner_tutorials/CMakeLists.txt and add the following at the end:
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)
Now run catkin_make:
make sure you have followed the directions in the previous tutorial: Creating a ROS msg and srv
cd ~/catkin_ws
catkin_make
Examining the Simple Service and Client
# Running the service
rosrun beginner_tutorials add_two_ints_server (C++) rosrun beginner_tutorials add_two_ints_server.py (Python)
# run the client with the arguments
rosrun beginner_tutorials add_two_ints_client 1 3 (C++) rosrun beginner_tutorials add_two_ints_client.py 1 3 (Python)
You will get the result:
[ INFO] [1519702993.581949133]: Sum: 4