用C++编写一个简单的发布者和订阅者
Posted 华为云开发者社区
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了用C++编写一个简单的发布者和订阅者相关的知识,希望对你有一定的参考价值。
摘要:节点(Node)是通过 ROS 图进行通信的可执行进程。
本文分享自华为云社区《编写一个简单的发布者和订阅者》,作者: MAVER1CK 。
@[toc]
参考官方文档:Writing a simple publisher and subscriber (C++)
背景
节点(Node)是通过 ROS 图进行通信的可执行进程。 在本教程中,节点将通过话题(Topic)以字符串消息的形式相互传递信息。 这里使用的例子是一个简单的“talker”和“listener”系统; 一个节点发布数据,另一个节点订阅该话题,以便它可以接收该数据。 可以在此处找到这些示例中使用的代码。
1.创建一个包
打开一个新的终端然后source你的ROS 2安装,以便ros2命令可以正常使用:
source /opt/ros/humble/setup.bash
回顾一下,包应该在src目录下创建,而不是在工作区的根目录下。因此,接下来,cd到ros2_ws/src,并运行包创建命令。
ros2 pkg create --build-type ament_cmake cpp_pubsub
你的终端将返回一条信息,验证你的cpp_pubsub包及其所有必要的文件和文件夹的创建。
cd到ros2_ws/src/cpp_pubsub/src。回顾一下,这是任何CMake包中包含可执行文件的源文件所在的目录。
2.编写发布者节点
下载示例代码:
wget -O publisher_member_function.cpp https://raw.githubusercontent.com/ros2/examples/humble/rclcpp/topics/minimal_publisher/member_function.cpp
打开之后内容如下
#include <chrono> #include <functional> #include <memory> #include <string> #include "rclcpp/rclcpp.hpp" #include "std_msgs/msg/string.hpp" using namespace std::chrono_literals; /* This example creates a subclass of Node and uses std::bind() to register a * member function as a callback from the timer. */ class MinimalPublisher : public rclcpp::Node public: MinimalPublisher() : Node("minimal_publisher"), count_(0) publisher_ = this->create_publisher<std_msgs::msg::String>("topic", 10); timer_ = this->create_wall_timer( 500ms, std::bind(&MinimalPublisher::timer_callback, this)); private: void timer_callback() auto message = std_msgs::msg::String(); message.data = "Hello, world! " + std::to_string(count_++); RCLCPP_INFO(this->get_logger(), "Publishing: \'%s\'", message.data.c_str()); publisher_->publish(message); rclcpp::TimerBase::SharedPtr timer_; rclcpp::Publisher<std_msgs::msg::String>::SharedPtr publisher_; size_t count_; ; int main(int argc, char * argv[]) rclcpp::init(argc, argv); rclcpp::spin(std::make_shared<MinimalPublisher>()); rclcpp::shutdown(); return 0;
2.1 查看代码
代码的顶部包括你将要使用的标准C++头文件。在标准C++头文件之后是rclcpp/rclcpp.hpp,它允许你使用ROS 2系统中最常见的部分。最后是std_msgs/msg/string.hpp,它包括你将用于发布数据的内置消息类型。
这些行代表节点的依赖关系。 回想一下,必须将依赖项添加到 package.xml 和 CMakeLists.txt,您将在下一节中执行此操作。
#include <chrono> #include <functional> #include <memory> #include <string> #include "rclcpp/rclcpp.hpp" #include "std_msgs/msg/string.hpp" using namespace std::chrono_literals;
下一行通过继承rclcpp::Node创建节点类MinimalPublisher。代码中的每个this都是指的节点。
class MinimalPublisher : public rclcpp::Node
公共构造函数将节点命名为 minimal_publisher 并将 count_ 初始化为 0。在构造函数内部,发布者使用 String 消息类型、话题名称为 topic 以及所需的队列大小,以便在发生备份时限制消息,进行初始化。 接下来,timer_ 被初始化,这导致 timer_callback 函数每秒执行两次。
public: MinimalPublisher() : Node("minimal_publisher"), count_(0) publisher_ = this->create_publisher<std_msgs::msg::String>("topic", 10); timer_ = this->create_wall_timer( 500ms, std::bind(&MinimalPublisher::timer_callback, this));
timer_callback函数是设置消息数据和实际发布消息的地方。RCLCPP_INFO宏确保每个发布的消息都被打印到控制台。
private: void timer_callback() auto message = std_msgs::msg::String(); message.data = "Hello, world! " + std::to_string(count_++); RCLCPP_INFO(this->get_logger(), "Publishing: \'%s\'", message.data.c_str()); publisher_->publish(message);
最后是定时器、发布者和计数器字段的声明。
rclcpp::TimerBase::SharedPtr timer_; rclcpp::Publisher<std_msgs::msg::String>::SharedPtr publisher_; size_t count_;
在 MinimalPublisher 类之后是 main,节点实际执行的地方。 rclcpp::init 初始化 ROS 2,rclcpp::spin 开始处理来自节点的数据,包括来自定时器的回调。
int main(int argc, char * argv[]) rclcpp::init(argc, argv); rclcpp::spin(std::make_shared<MinimalPublisher>()); rclcpp::shutdown(); return 0;
2.2 添加依赖
回到ros2_ws/src/cpp_pubsub目录,那里已经为你创建了CMakeLists.txt和package.xml文件。
打开 package.xml文件。正如上一个教程中提到的,确保填写<description>、<maintainer>和<license>标签。
<description>Examples of minimal publisher/subscriber using rclcpp</description> <maintainer email="you@email.com">Your Name</maintainer> <license>Apache License 2.0</license>
在ament_cmake构建工具的依赖关系后增加一行,并粘贴以下与你的节点的include语句相对应的依赖关系。
<depend>rclcpp</depend> <depend>std_msgs</depend>
这声明包在执行其代码时需要 rclcpp 和 std_msgs。
修改好后记得保存文件。
2.3 CMakeLists
现在打开CMakeLists.txt文件。在现有的依赖关系find_package(ament_cmake REQUIRED)下面,添加几行:
find_package(rclcpp REQUIRED)
find_package(std_msgs REQUIRED)
之后,添加可执行文件并将其命名为talker,这样你就可以用ros2 run来运行你的节点:
add_executable(talker src/publisher_member_function.cpp)
ament_target_dependencies(talker rclcpp std_msgs)
最后,添加install(TARGETS...)部分,以便ros2 run能够找到你的可执行文件:
install(TARGETS
talker
DESTINATION lib/$PROJECT_NAME)
你可以通过删除一些不必要的部分和注释来清理你的CMakeLists.txt,所以它看起来像这样:
cmake_minimum_required(VERSION 3.5) project(cpp_pubsub) Default to C++14 if(NOT CMAKE_CXX_STANDARD) set(CMAKE_CXX_STANDARD 14) endif() if(CMAKE_COMPILER_IS_GNUCXX OR CMAKE_CXX_COMPILER_ID MATCHES "Clang") add_compile_options(-Wall -Wextra -Wpedantic) endif() find_package(ament_cmake REQUIRED) find_package(rclcpp REQUIRED) find_package(std_msgs REQUIRED) add_executable(talker src/publisher_member_function.cpp) ament_target_dependencies(talker rclcpp std_msgs) install(TARGETS talker DESTINATION lib/$PROJECT_NAME) ament_package()
你现在可以 build 你的包,source local_setup.bash,然后运行它,但让我们先创建订阅者节点,这样你就可以看到一个完整工作的系统。
3.编写订阅者节点
返回到ros2_ws/src/cpp_pubsub/src来创建下一个节点。在你的终端输入以下代码:
wget -O subscriber_member_function.cpp https://raw.githubusercontent.com/ros2/examples/humble/rclcpp/topics/minimal_subscriber/member_function.cpp
在终端中输入ls,现在将返回:
publisher_member_function.cpp subscriber_member_function.cpp
打开subscriber_member_function.cpp文件:
#include <memory> #include "rclcpp/rclcpp.hpp" #include "std_msgs/msg/string.hpp" using std::placeholders::_1; class MinimalSubscriber : public rclcpp::Node public: MinimalSubscriber() : Node("minimal_subscriber") subscription_ = this->create_subscription<std_msgs::msg::String>( "topic", 10, std::bind(&MinimalSubscriber::topic_callback, this, _1)); private: void topic_callback(const std_msgs::msg::String & msg) const RCLCPP_INFO(this->get_logger(), "I heard: \'%s\'", msg.data.c_str()); rclcpp::Subscription<std_msgs::msg::String>::SharedPtr subscription_; ; int main(int argc, char * argv[]) rclcpp::init(argc, argv); rclcpp::spin(std::make_shared<MinimalSubscriber>()); rclcpp::shutdown(); return 0;
3.1 查看代码
订阅者节点的代码几乎与发布者的相同。现在节点被命名为minimal_subscriber,构造函数使用节点的create_subscription类来执行回调。
没有计时器,因为无论任何时候只要数据发送到topic话题,订阅者都会作出响应:
public: MinimalSubscriber() : Node("minimal_subscriber") subscription_ = this->create_subscription<std_msgs::msg::String>( "topic", 10, std::bind(&MinimalSubscriber::topic_callback, this, _1));
在话题教程中已经知道,发布者和订阅者使用的话题名称和消息类型必须匹配,这样他们才能进行通信。
topic_callback函数接收通过话题发布的字符串消息数据,然后使用RCLCPP_INFO宏将内容输出到终端。
这个类中唯一的字段声明是订阅:
private: void topic_callback(const std_msgs::msg::String & msg) const RCLCPP_INFO(this->get_logger(), "I heard: \'%s\'", msg.data.c_str()); rclcpp::Subscription<std_msgs::msg::String>::SharedPtr subscription_;
main函数是完全一样的,只是现在它spin了MinimalSubscriber节点。对于发布者节点来说,spin意味着启动定时器,但对于订阅者来说,它只是意味着准备在消息到来时接收它们。
由于这个节点与发布者节点有相同的依赖关系,所以没有什么新的东西需要添加到package.xml中。
4.构建并运行
你可能已经安装了rclcpp和std_msgs软件包作为你的ROS 2系统的一部分。在你的工作空间(ros2_ws)的根目录下运行rosdep是一个很好的做法,可以在构建之前检查是否有遗漏的依赖:
rosdep install -i --from-path src --rosdistro humble -y
然后构建软件包:
colcon build --packages-select cpp_pubsub
打开一个新的终端,cd到ros2_ws,然后source设置文件:
. install/setup.bash
现在运行 talker 节点:
ros2 run cpp_pubsub talker
终端应该开始每0.5秒发布一次信息,像这样:
[INFO] [minimal_publisher]: Publishing: "Hello World: 0" [INFO] [minimal_publisher]: Publishing: "Hello World: 1" [INFO] [minimal_publisher]: Publishing: "Hello World: 2" [INFO] [minimal_publisher]: Publishing: "Hello World: 3" [INFO] [minimal_publisher]: Publishing: "Hello World: 4"
再打开一个新的终端,cd到ros2_ws,然后source设置文件:
. install/setup.bash
现在运行 listener 节点:
ros2 run cpp_pubsub listener
listener 将开始在终端打印消息,从发布者当时的消息计数开始,如下所示:
[INFO] [minimal_subscriber]: I heard: "Hello World: 10" [INFO] [minimal_subscriber]: I heard: "Hello World: 11" [INFO] [minimal_subscriber]: I heard: "Hello World: 12" [INFO] [minimal_subscriber]: I heard: "Hello World: 13" [INFO] [minimal_subscriber]: I heard: "Hello World: 14"
在每个终端中按Ctrl+C来停止运行节点。
编写简单的发布者和订阅者(C++)---ROS学习第9篇
文章目录
1.编写发布者节点
在之前创建的study/src目录下创建talker.cpp文件并粘贴以下内容进去
#include "ros/ros.h"
#include "std_msgs/String.h"
#include <sstream>
/**
* This tutorial demonstrates simple sending of messages over the ROS system.
*/
int main(int argc, char **argv)
/**
* The ros::init() function needs to see argc and argv so that it can perform
* any ROS arguments and name remapping that were provided at the command line.
* For programmatic remappings you can use a different version of init() which takes
* remappings directly, but for most command-line programs, passing argc and argv is
* the easiest way to do it. The third argument to init() is the name of the node.
*
* You must call one of the versions of ros::init() before using any other
* part of the ROS system.
*/
ros::init(argc, argv, "talker");
/**
* NodeHandle is the main access point to communications with the ROS system.
* The first NodeHandle constructed will fully initialize this node, and the last
* NodeHandle destructed will close down the node.
*/
ros::NodeHandle n;
/**
* The advertise() function is how you tell ROS that you want to
* publish on a given topic name. This invokes a call to the ROS
* master node, which keeps a registry of who is publishing and who
* is subscribing. After this advertise() call is made, the master
* node will notify anyone who is trying to subscribe to this topic name,
* and they will in turn negotiate a peer-to-peer connection with this
* node. advertise() returns a Publisher object which allows you to
* publish messages on that topic through a call to publish(). Once
* all copies of the returned Publisher object are destroyed, the topic
* will be automatically unadvertised.
*
* The second parameter to advertise() is the size of the message queue
* used for publishing messages. If messages are published more quickly
* than we can send them, the number here specifies how many messages to
* buffer up before throwing some away.
*/
ros::Publisher chatter_pub = n.advertise<std_msgs::String>("chatter", 1000);
ros::Rate loop_rate(10);
/**
* A count of how many messages we have sent. This is used to create
* a unique string for each message.
*/
int count = 0;
while (ros::ok())
/**
* This is a message object. You stuff it with data, and then publish it.
*/
std_msgs::String msg;
std::stringstream ss;
ss << "hello world " << count;
msg.data = ss.str();
ROS_INFO("%s", msg.data.c_str());
/**
* The publish() function is how you send messages. The parameter
* is the message object. The type of this object must agree with the type
* given as a template parameter to the advertise<>() call, as was done
* in the constructor above.
*/
chatter_pub.publish(msg);
ros::spinOnce();
loop_rate.sleep();
++count;
return 0;
这部分代码的解读,可参考:添加链接描述
2. 编写订阅者节点
在src目录下创建listener.cpp文件并粘贴以下内容进去:
#include "ros/ros.h"
#include "std_msgs/String.h"
/**
* This tutorial demonstrates simple receipt of messages over the ROS system.
*/
void chatterCallback(const std_msgs::String::ConstPtr& msg)
ROS_INFO("I heard: [%s]", msg->data.c_str());
int main(int argc, char **argv)
/**
* The ros::init() function needs to see argc and argv so that it can perform
* any ROS arguments and name remapping that were provided at the command line.
* For programmatic remappings you can use a different version of init() which takes
* remappings directly, but for most command-line programs, passing argc and argv is
* the easiest way to do it. The third argument to init() is the name of the node.
*
* You must call one of the versions of ros::init() before using any other
* part of the ROS system.
*/
ros::init(argc, argv, "listener");
/**
* NodeHandle is the main access point to communications with the ROS system.
* The first NodeHandle constructed will fully initialize this node, and the last
* NodeHandle destructed will close down the node.
*/
ros::NodeHandle n;
/**
* The subscribe() call is how you tell ROS that you want to receive messages
* on a given topic. This invokes a call to the ROS
* master node, which keeps a registry of who is publishing and who
* is subscribing. Messages are passed to a callback function, here
* called chatterCallback. subscribe() returns a Subscriber object that you
* must hold on to until you want to unsubscribe. When all copies of the Subscriber
* object go out of scope, this callback will automatically be unsubscribed from
* this topic.
*
* The second parameter to the subscribe() function is the size of the message
* queue. If messages are arriving faster than they are being processed, this
* is the number of messages that will be buffered up before beginning to throw
* away the oldest ones.
*/
ros::Subscriber sub = n.subscribe("chatter", 1000, chatterCallback);
/**
* ros::spin() will enter a loop, pumping callbacks. With this version, all
* callbacks will be called from within this thread (the main one). ros::spin()
* will exit when Ctrl-C is pressed, or the node is shutdown by the master.
*/
ros::spin();
return 0;
3.构建节点
前面的介绍使用了catkin_create_pkg,它创建了一个和一个package.xml和CMakeLists.txt文件。只需将这几行添加到CMakeLists.txt文件的底部:
add_executable(talker src/talker.cpp)
target_link_libraries(talker $catkin_LIBRARIES)
add_dependencies(talker study_generate_messages_cpp)
add_executable(listener src/listener.cpp)
target_link_libraries(listener $catkin_LIBRARIES)
add_dependencies(listener study_generate_messages_cpp)
这将创建两个可执行文件talker和listener,默认情况下,它们将被放到软件包目录下的devel空间中,即~/catkin_ws/devel/lib/。
现在可以运行catkin_make:
# 在你的catkin工作空间下
$ cd ~/catkin_ws
$ catkin_make
4.运行节点
打开一个终端,运行roscore;
再打开一个新的终端,运行接收节点:rosrun study listener
再打开一个新的终端,运行发布节点:rosrun study talker
再打开一个新的终端,运行rqt_graph,可以看到:
以上是关于用C++编写一个简单的发布者和订阅者的主要内容,如果未能解决你的问题,请参考以下文章