在线时间:8:00-16:00
迪恩网络APP
随时随地掌握行业动态
扫描二维码
关注迪恩网络微信公众号
一、编写Service节点 1、节点功能: 我们将创建一个简单的service节点("add_two_ints_server"),该节点将接收到两个整形数字,并返回它们的和。
2、beginner_tutorials包中创建src/add_two_ints_server.cpp文件 且编写代码 cd ~/catkin_ws/src/beginner_tutorials
#include "ros/ros.h" #include "beginner_tutorials/AddTwoInts.h" // beginner_tutorials/AddTwoInts.h是由编译系统自动根据我们先前创建的srv文件生成的对应该srv文件的头文件。 /* 这个函数提供两个int值求和的服务,int值从request里面获取,而返回数据装入response内,这些数据类型都定义在srv文件内部,函数返回一个boolean值。 */ 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; }
二、编写Client节点 1、在beginner_tutorials包中创建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; }
三、编译节点 1、编辑beginner_tutorials 中的CMakeLists.txt文件,末尾加入 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_two_ints_server"和"add_two_ints_client",这两个可执行程序默认被放在你的devel space下的包目录下,默认为~/catkin_ws/devel/lib/share/<package name>。你可以直接调用可执行程序,或者使用rosrun命令去调用它们
2、编译 # In your catkin workspace cd ~/catkin_ws catkin_make
四、测试 1、运行Sevice $ rosrun beginner_tutorials add_two_ints_server (C++)
# 你将会看到如下类似的信息:
Ready to add two ints.
2、运行Client $ rosrun beginner_tutorials add_two_ints_client 1 3 (C++) 你将会看到如下类似的信息: request: x=1, y=3 sending back response: [4] 现在,你已经成功地运行了你的第一个Service和Client程序
|
2023-10-27
2022-08-15
2022-08-17
2022-09-23
2022-08-13
请发表评论