ROS的学习日记(2)话题通信与服务通信与action通信
今天简单了解ROS的话题(自定义话题)编程以及ROS的server和client的通信和action的通信编程。基于(c++)
(1)自定义话题编程
在功能包learning_communication下创建一个msg的文件夹,在里面创建一个Person.msg的文件
内容为:
string name uint8 sex uint8 age uint8 unknown = 0 uint8 male = 1 uint8 female = 2
在Package.xml中添加功能包依赖:
<build_depend>message_generation</build_depend>
<exec_depend>message_runtime</exec_depend>
在CMakeLists.txt中添加编译选项:
find_package( …… message_generation)
catkin_package(CATKIN_DEPENDS geometry_msgs roscpp
rospy std_msgs message_runtime)
add_message_files(FILES Person.msg)
generate_messages(DEPENDENCIES std_msgs)
在工作空间catkin_ws中使用rosmsg show Person.msg能够看到你在该msg文件下的内容,如果能够看到同时也说明它已经生效。
回到工作空间编译catkin_make
(2)Server and Client
* AddTwoInts Server
*/
#include "ros/ros.h"
#include "learning_communication/AddTwoInts.h"
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;
}
{
// ROS节点初始化
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();
}
/** * AddTwoInts 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; }
写完后在cmakelists.txtl文件下加入:
然后返回工作空间,对于我来说就是在catkin_ws路径下使用catkin_make编译。
编译成功后
打开一个终端运行roscore
打开一个终端运行rosrun learning_communication server
打开一个终端运行rosrun learning_communication client 3 4
就可以观察到server 与 client 之间进行信息交互。
看到结果为7,你能够清晰的看到客户通过终端发送变量内容,服务端接收并处理变量内容再将最后的结果返回。
action通信是问答通信机制,首先要定义一个文件名为action的文件夹,在里面创建DoDIshes.action文件
然后与上面类似去定义自己想要的action信息。
然后就是更改Package.xml文件
更改CMakeLists.txt文件
最后编译
然后运行
具体步骤内容官方应该都有,这是官方的例程。
浙公网安备 33010602011771号