Learning ROS: Service and Client (C++)
生活随笔
收集整理的這篇文章主要介紹了
Learning ROS: Service and Client (C++)
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
本文主要部分來源于ROS官網(wǎng)的Tutorials.
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)
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 servicerosrun 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?
轉(zhuǎn)載于:https://www.cnblogs.com/xbit/p/8477380.html
總結(jié)
以上是生活随笔為你收集整理的Learning ROS: Service and Client (C++)的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 【luogu P3378 堆】 模板
- 下一篇: C/C++ strict-aliasin