您的位置:  首页 > 技术杂谈 > 正文

用C++编写一个简单的发布者和订阅者

2023-04-28 10:00 https://my.oschina.net/u/4526289/blog/8695685 华为云开发者联盟 次阅读 条评论
摘要:节点(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来停止运行节点。

 

点击关注,第一时间了解华为云新鲜技术~

展开阅读全文
  • 0
    感动
  • 0
    路过
  • 0
    高兴
  • 0
    难过
  • 0
    搞笑
  • 0
    无聊
  • 0
    愤怒
  • 0
    同情
热度排行
友情链接