摘要:節(jié)點(diǎn)(Node)是通過 ROS 圖進(jìn)行通信的可執(zhí)行進(jìn)程。
本文分享自華為云社區(qū)《編寫一個(gè)簡單的發(fā)布者和訂閱者》,作者: MAVER1CK 。
@[toc]
參考官方文檔:Writing a simple publisher and subscriber (C++)
背景
節(jié)點(diǎn)(Node)是通過 ROS 圖進(jìn)行通信的可執(zhí)行進(jìn)程。 在本教程中,節(jié)點(diǎn)將通過話題(Topic)以字符串消息的形式相互傳遞信息。 這里使用的例子是一個(gè)簡單的“talker”和“l(fā)istener”系統(tǒng); 一個(gè)節(jié)點(diǎn)發(fā)布數(shù)據(jù),另一個(gè)節(jié)點(diǎn)訂閱該話題,以便它可以接收該數(shù)據(jù)。?可以在此處找到這些示例中使用的代碼。
1.創(chuàng)建一個(gè)包
打開一個(gè)新的終端然后source你的ROS 2安裝,以便ros2命令可以正常使用:
source /opt/ros/humble/setup.bash
回顧一下,包應(yīng)該在src目錄下創(chuàng)建,而不是在工作區(qū)的根目錄下。因此,接下來,cd到ros2_ws/src,并運(yùn)行包創(chuàng)建命令。
ros2 pkg create --build-type ament_cmake cpp_pubsub
你的終端將返回一條信息,驗(yàn)證你的cpp_pubsub包及其所有必要的文件和文件夾的創(chuàng)建。
cd到ros2_ws/src/cpp_pubsub/src?;仡櫼幌?,這是任何CMake包中包含可執(zhí)行文件的源文件所在的目錄。
2.編寫發(fā)布者節(jié)點(diǎn)
下載示例代碼:
wget -O publisher_member_function.cpp https://raw.githubusercontent.com/ros2/examples/humble/rclcpp/topics/minimal_publisher/member_function.cpp
打開之后內(nèi)容如下
#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 查看代碼
代碼的頂部包括你將要使用的標(biāo)準(zhǔn)C++頭文件。在標(biāo)準(zhǔn)C++頭文件之后是rclcpp/rclcpp.hpp,它允許你使用ROS 2系統(tǒng)中最常見的部分。最后是std_msgs/msg/string.hpp,它包括你將用于發(fā)布數(shù)據(jù)的內(nèi)置消息類型。
這些行代表節(jié)點(diǎn)的依賴關(guān)系。 回想一下,必須將依賴項(xiàng)添加到 package.xml 和 CMakeLists.txt,您將在下一節(jié)中執(zhí)行此操作。
#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創(chuàng)建節(jié)點(diǎn)類MinimalPublisher。代碼中的每個(gè)this都是指的節(jié)點(diǎn)。
class MinimalPublisher : public rclcpp::Node
公共構(gòu)造函數(shù)將節(jié)點(diǎn)命名為 minimal_publisher 并將 count_ 初始化為 0。在構(gòu)造函數(shù)內(nèi)部,發(fā)布者使用 String 消息類型、話題名稱為 topic 以及所需的隊(duì)列大小,以便在發(fā)生備份時(shí)限制消息,進(jìn)行初始化。 接下來,timer_ 被初始化,這導(dǎo)致 timer_callback 函數(shù)每秒執(zhí)行兩次。
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函數(shù)是設(shè)置消息數(shù)據(jù)和實(shí)際發(fā)布消息的地方。RCLCPP_INFO宏確保每個(gè)發(fā)布的消息都被打印到控制臺(tái)。
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); }
最后是定時(shí)器、發(fā)布者和計(jì)數(shù)器字段的聲明。
rclcpp::TimerBase::SharedPtr timer_; rclcpp::Publisher<std_msgs::msg::String>::SharedPtr publisher_; size_t count_;
在 MinimalPublisher 類之后是 main,節(jié)點(diǎn)實(shí)際執(zhí)行的地方。 rclcpp::init 初始化 ROS 2,rclcpp::spin 開始處理來自節(jié)點(diǎn)的數(shù)據(jù),包括來自定時(shí)器的回調(diào)。
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目錄,那里已經(jīng)為你創(chuàng)建了CMakeLists.txt和package.xml文件。
打開 package.xml文件。正如上一個(gè)教程中提到的,確保填寫<description>、<maintainer>和<license>標(biāo)簽。
<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構(gòu)建工具的依賴關(guān)系后增加一行,并粘貼以下與你的節(jié)點(diǎn)的include語句相對應(yīng)的依賴關(guān)系。
<depend>rclcpp</depend> <depend>std_msgs</depend>
這聲明包在執(zhí)行其代碼時(shí)需要 rclcpp 和 std_msgs。
修改好后記得保存文件。
2.3 CMakeLists
現(xiàn)在打開CMakeLists.txt文件。在現(xiàn)有的依賴關(guān)系find_package(ament_cmake REQUIRED)下面,添加幾行:
find_package(rclcpp REQUIRED)
find_package(std_msgs REQUIRED)
之后,添加可執(zhí)行文件并將其命名為talker,這樣你就可以用ros2 run來運(yùn)行你的節(jié)點(diǎn):
add_executable(talker src/publisher_member_function.cpp)
ament_target_dependencies(talker rclcpp std_msgs)
最后,添加install(TARGETS...)部分,以便ros2 run能夠找到你的可執(zhí)行文件:
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()
你現(xiàn)在可以 build 你的包,source local_setup.bash,然后運(yùn)行它,但讓我們先創(chuàng)建訂閱者節(jié)點(diǎn),這樣你就可以看到一個(gè)完整工作的系統(tǒng)。
3.編寫訂閱者節(jié)點(diǎn)
返回到ros2_ws/src/cpp_pubsub/src來創(chuàng)建下一個(gè)節(jié)點(diǎn)。在你的終端輸入以下代碼:
wget -O subscriber_member_function.cpp https://raw.githubusercontent.com/ros2/examples/humble/rclcpp/topics/minimal_subscriber/member_function.cpp
在終端中輸入ls,現(xiàn)在將返回:
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 查看代碼
訂閱者節(jié)點(diǎn)的代碼幾乎與發(fā)布者的相同?,F(xiàn)在節(jié)點(diǎn)被命名為minimal_subscriber,構(gòu)造函數(shù)使用節(jié)點(diǎn)的create_subscription類來執(zhí)行回調(diào)。
沒有計(jì)時(shí)器,因?yàn)闊o論任何時(shí)候只要數(shù)據(jù)發(fā)送到topic話題,訂閱者都會(huì)作出響應(yīng):
public: MinimalSubscriber() : Node("minimal_subscriber") { subscription_ = this->create_subscription<std_msgs::msg::String>( "topic", 10, std::bind(&MinimalSubscriber::topic_callback, this, _1)); }
在話題教程中已經(jīng)知道,發(fā)布者和訂閱者使用的話題名稱和消息類型必須匹配,這樣他們才能進(jìn)行通信。
topic_callback函數(shù)接收通過話題發(fā)布的字符串消息數(shù)據(jù),然后使用RCLCPP_INFO宏將內(nèi)容輸出到終端。
這個(gè)類中唯一的字段聲明是訂閱:
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函數(shù)是完全一樣的,只是現(xiàn)在它spin了MinimalSubscriber節(jié)點(diǎn)。對于發(fā)布者節(jié)點(diǎn)來說,spin意味著啟動(dòng)定時(shí)器,但對于訂閱者來說,它只是意味著準(zhǔn)備在消息到來時(shí)接收它們。
由于這個(gè)節(jié)點(diǎn)與發(fā)布者節(jié)點(diǎn)有相同的依賴關(guān)系,所以沒有什么新的東西需要添加到package.xml中。
4.構(gòu)建并運(yùn)行
你可能已經(jīng)安裝了rclcpp和std_msgs軟件包作為你的ROS 2系統(tǒng)的一部分。在你的工作空間(ros2_ws)的根目錄下運(yùn)行rosdep是一個(gè)很好的做法,可以在構(gòu)建之前檢查是否有遺漏的依賴:
rosdep install -i --from-path src --rosdistro humble -y
然后構(gòu)建軟件包:
colcon build --packages-select cpp_pubsub
打開一個(gè)新的終端,cd到ros2_ws,然后source設(shè)置文件:
. install/setup.bash
現(xiàn)在運(yùn)行 talker 節(jié)點(diǎn):
ros2 run cpp_pubsub talker
終端應(yīng)該開始每0.5秒發(fā)布一次信息,像這樣:
[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"
再打開一個(gè)新的終端,cd到ros2_ws,然后source設(shè)置文件:
. install/setup.bash
現(xiàn)在運(yùn)行 listener 節(jié)點(diǎn):
ros2 run cpp_pubsub listener
listener 將開始在終端打印消息,從發(fā)布者當(dāng)時(shí)的消息計(jì)數(shù)開始,如下所示:
[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"
在每個(gè)終端中按Ctrl+C來停止運(yùn)行節(jié)點(diǎn)。
?文章來源:http://www.zghlxwxcb.cn/news/detail-426843.html
點(diǎn)擊關(guān)注,第一時(shí)間了解華為云新鮮技術(shù)~文章來源地址http://www.zghlxwxcb.cn/news/detail-426843.html
到了這里,關(guān)于用C++編寫一個(gè)簡單的發(fā)布者和訂閱者的文章就介紹完了。如果您還想了解更多內(nèi)容,請?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!