本文转载自机器人知识社区:古月居
原作者:古月
原文链接:https://www.guyuehome.com/2543
之前我们讲到如何在ROS2中自定义话题和服务,在编译之后产生了相应的头文件。
本篇以自定义的话题接口为例,看下如何调用之前定义好的接口内容。
接口定义参考:ROS 2中的话题与服务接口定义
一、完整代码示例
在test_pkg功能包的src下创建publish_contact.cpp文件,完整代码内容如下:
#include <iostream>#include <memory>#include "rclcpp/rclcpp.hpp"#include "test_pkg/msg/contact.hpp"using namespace std::chrono_literals;class ContactPublisher : public rclcpp::Node{public: ContactPublisher() : Node("address_book_publisher") { contact_publisher_ = this->create_publisher<test_pkg::msg::Contact>("contact"); auto publish_msg = [this]() -> void { auto msg = std::make_shared<test_pkg::msg::Contact>(); msg->first_name = "John"; msg->last_name = "Doe"; msg->age = 30; msg->gender = msg->MALE; msg->address = "unknown"; std::cout << "Publishing Contact\nFirst:" << msg->first_name << " Last:" << msg->last_name << std::endl; contact_publisher_->publish(msg); }; timer_ = this->create_wall_timer(1s, publish_msg); }private: rclcpp::Publisher<test_pkg::msg::Contact>::SharedPtr contact_publisher_; rclcpp::TimerBase::SharedPtr timer_;};int main(int argc, char * argv[]){ rclcpp::init(argc, argv); auto publisher_node = std::make_shared<ContactPublisher>(); rclcpp::spin(publisher_node); return 0;}
二、示例代码剖析
接下来具体分析以上代码:
#include "test_pkg/msg/contact.hpp"
头文件包含很重要,contact.hpp是根据msg文件编译时动态生成的头问题,头文件名就是msg文件的名字,所以此时虽然还未生成头文件,但是我们也可以确定将来生成的路径和名字;
ContactPublisher(): Node("address_book_publisher"){
创建一个名为address_book_publisher的节点;
auto publish_msg = [this]() -> void {
创建一个周期发布话题消息的功能函数;
auto msg = std::make_shared<test_pkg::msg::Contact>();msg->first_name = "John";msg->last_name = "Doe";msg->age = 30;msg->gender = msg->MALE;msg->address = "unknown";
在发布函数中创建 Contact消息并填充数据域,注意这里的话题接口test_pkg::msg::Contact就是我们自定义的内容;
std::cout << "Publishing Contact\nFirst:" << msg->first_name << " Last:" << msg->last_name << std::endl;contact_publisher_->publish(msg);
发布话题消息并输出日志信息;
timer_ = this->create_wall_timer(1s, publish_msg);
创建周期为1秒的定时器,用来调用以上发布话题消息的函数。
为了编译以上代码,除了像之前文章一样修改package.xml,还需要修改CMakeLists.txt:
find_package(test_pkg REQUIRED)add_executable(publish_contact src/publish_contact.cpp)ament_target_dependencies(publish_contact "rclcpp" "test_pkg")
三、示例运行效果
编译之后配置环境变量并运行节点,效果如下:
可以通过终端订阅并打印话题,查看消息内容:
ROS2接口定义与调用的相关源码,请关注微信公众号“古月居”,后台回复“ros2接口定义”获取完整代码的下载地址。