草庐IT

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

华为云开发者社区 2024-01-13 原文
摘要:节点(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++编写一个简单的发布者和订阅者的更多相关文章

  1. ruby - 使用 Vim Rails,您可以创建一个新的迁移文件并一次性打开它吗? - 2

    使用带有Rails插件的vim,您可以创建一个迁移文件,然后一次性打开该文件吗?textmate也可以这样吗? 最佳答案 你可以使用rails.vim然后做类似的事情::Rgeneratemigratonadd_foo_to_bar插件将打开迁移生成的文件,这正是您想要的。我不能代表textmate。 关于ruby-使用VimRails,您可以创建一个新的迁移文件并一次性打开它吗?,我们在StackOverflow上找到一个类似的问题: https://sta

  2. ruby-on-rails - Rails - 一个 View 中的多个模型 - 2

    我需要从一个View访问多个模型。以前,我的links_controller仅用于提供以不同方式排序的链接资源。现在我想包括一个部分(我假设)显示按分数排序的顶级用户(@users=User.all.sort_by(&:score))我知道我可以将此代码插入每个链接操作并从View访问它,但这似乎不是“ruby方式”,我将需要在不久的将来访问更多模型。这可能会变得很脏,是否有针对这种情况的任何技术?注意事项:我认为我的应用程序正朝着单一格式和动态页面内容的方向发展,本质上是一个典型的网络应用程序。我知道before_filter但考虑到我希望应用程序进入的方向,这似乎很麻烦。最终从任何

  3. ruby-on-rails - 渲染另一个 Controller 的 View - 2

    我想要做的是有2个不同的Controller,client和test_client。客户端Controller已经构建,我想创建一个test_clientController,我可以使用它来玩弄客户端的UI并根据需要进行调整。我主要是想绕过我在客户端中内置的验证及其对加载数据的管理Controller的依赖。所以我希望test_clientController加载示例数据集,然后呈现客户端Controller的索引View,以便我可以调整客户端UI。就是这样。我在test_clients索引方法中试过这个:classTestClientdefindexrender:template=>

  4. ruby - 在 Ruby 中编写命令行实用程序 - 2

    我想用ruby​​编写一个小的命令行实用程序并将其作为gem分发。我知道安装后,Guard、Sass和Thor等某些gem可以从命令行自行运行。为了让gem像二进制文件一样可用,我需要在我的gemspec中指定什么。 最佳答案 Gem::Specification.newdo|s|...s.executable='name_of_executable'...endhttp://docs.rubygems.org/read/chapter/20 关于ruby-在Ruby中编写命令行实用程序

  5. ruby-on-rails - 如果 Object::try 被发送到一个 nil 对象,为什么它会起作用? - 2

    如果您尝试在Ruby中的nil对象上调用方法,则会出现NoMethodError异常并显示消息:"undefinedmethod‘...’fornil:NilClass"然而,有一个tryRails中的方法,如果它被发送到一个nil对象,它只返回nil:require'rubygems'require'active_support/all'nil.try(:nonexisting_method)#noNoMethodErrorexceptionanymore那么try如何在内部工作以防止该异常? 最佳答案 像Ruby中的所有其他对象

  6. ruby - 为什么 SecureRandom.uuid 创建一个唯一的字符串? - 2

    关闭。这个问题需要detailsorclarity.它目前不接受答案。想改进这个问题吗?通过editingthispost添加细节并澄清问题.关闭8年前。Improvethisquestion为什么SecureRandom.uuid创建一个唯一的字符串?SecureRandom.uuid#=>"35cb4e30-54e1-49f9-b5ce-4134799eb2c0"SecureRandom.uuid方法创建的字符串从不重复?

  7. ruby - 简单获取法拉第超时 - 2

    有没有办法在这个简单的get方法中添加超时选项?我正在使用法拉第3.3。Faraday.get(url)四处寻找,我只能先发起连接后应用超时选项,然后应用超时选项。或者有什么简单的方法?这就是我现在正在做的:conn=Faraday.newresponse=conn.getdo|req|req.urlurlreq.options.timeout=2#2secondsend 最佳答案 试试这个:conn=Faraday.newdo|conn|conn.options.timeout=20endresponse=conn.get(url

  8. ruby-on-rails - Rails - 从另一个模型中创建一个模型的实例 - 2

    我有一个正在构建的应用程序,我需要一个模型来创建另一个模型的实例。我希望每辆车都有4个轮胎。汽车模型classCar轮胎模型classTire但是,在make_tires内部有一个错误,如果我为Tire尝试它,则没有用于创建或新建的activerecord方法。当我检查轮胎时,它没有这些方法。我该如何补救?错误是这样的:未定义的方法'create'forActiveRecord::AttributeMethods::Serialization::Tire::Module我测试了两个环境:测试和开发,它们都因相同的错误而失败。 最佳答案

  9. ruby - 用 Ruby 编写一个简单的网络服务器 - 2

    我想在Ruby中创建一个用于开发目的的极其简单的Web服务器(不,不想使用现成的解决方案)。代码如下:#!/usr/bin/rubyrequire'socket'server=TCPServer.new('127.0.0.1',8080)whileconnection=server.acceptheaders=[]length=0whileline=connection.getsheaders想法是从命令行运行这个脚本,提供另一个脚本,它将在其标准输入上获取请求,并在其标准输出上返回完整的响应。到目前为止一切顺利,但事实证明这真的很脆弱,因为它在第二个请求上中断并出现错误:/usr/b

  10. ruby - 一个 YAML 对象可以引用另一个吗? - 2

    我想让一个yaml对象引用另一个,如下所示:intro:"Hello,dearuser."registration:$introThanksforregistering!new_message:$introYouhaveanewmessage!上面的语法只是它如何工作的一个例子(这也是它在thiscpanmodule中的工作方式。)我正在使用标准的ruby​​yaml解析器。这可能吗? 最佳答案 一些yaml对象确实引用了其他对象:irb>require'yaml'#=>trueirb>str="hello"#=>"hello"ir

随机推荐