DDS_Bridge
一个基于Fast DDS的DDS桥接库
载入中...
搜索中...
未找到
subscriber.hpp
浏览该文件的文档.
1
10#pragma once
11#include <functional>
12#include <fastdds/dds/subscriber/Subscriber.hpp>
13#include <fastdds/dds/subscriber/DataReader.hpp>
14#include <fastdds/dds/subscriber/qos/DataReaderQos.hpp>
15#include <fastdds/dds/subscriber/SampleInfo.hpp>
16
17namespace zclcpp
18{
19 class Node;
20
26 template <typename MsgPubSubType>
27 class Subscription : public eprosima::fastdds::dds::DataReaderListener
28 {
29 public:
31 using MsgT = typename MsgPubSubType::type;
32
34 using SharedPtr = std::shared_ptr<Subscription<MsgPubSubType>>;
35
37 using Callback = std::function<void(const typename MsgPubSubType::type&)>;
38
47 Subscription(std::shared_ptr<Node> node,
48 const std::string& topic_name,
49 int qos_depth,
50 Callback cb)
51 : node_(node), cb_(cb)
52 {
53 type_.reset(new MsgPubSubType());
54 type_.register_type(node_->participant());
55
56 topic_ = node_->participant()->find_topic(topic_name, eprosima::fastdds::dds::Duration_t(1));
57 if (topic_ == nullptr)
58 {
59 topic_ = node_->participant()->create_topic(
60 topic_name, type_.get_type_name(),
61 eprosima::fastdds::dds::TOPIC_QOS_DEFAULT);
62 }
63
64 sub_ = node_->participant()->create_subscriber(
65 eprosima::fastdds::dds::SUBSCRIBER_QOS_DEFAULT, nullptr);
66
67 eprosima::fastdds::dds::DataReaderQos rqos;
68 rqos.history().kind = eprosima::fastdds::dds::KEEP_LAST_HISTORY_QOS;
69 rqos.history().depth = qos_depth;
70 reader_ = sub_->create_datareader(topic_, rqos, this);
71 }
72
75 void on_data_available(eprosima::fastdds::dds::DataReader* reader) override
76 {
77 MsgT msg;
78 eprosima::fastdds::dds::SampleInfo info;
79 while (reader->take_next_sample(&msg, &info) == eprosima::fastdds::dds::RETCODE_OK)
80 {
81 if (info.valid_data && cb_)
82 cb_(msg);
83 }
84 }
85
86 private:
87 std::shared_ptr<Node> node_;
88 Callback cb_;
89 eprosima::fastdds::dds::TypeSupport type_;
90 eprosima::fastdds::dds::Topic* topic_{ nullptr };
91 eprosima::fastdds::dds::Subscriber* sub_{ nullptr };
92 eprosima::fastdds::dds::DataReader* reader_{ nullptr };
93 };
94};
95
Represents a DDS node.
定义 node.hpp:31
std::function< void(const typename MsgPubSubType::type &)> Callback
Callback type for message reception.
定义 subscriber.hpp:37
std::shared_ptr< Subscription< MsgPubSubType > > SharedPtr
Shared pointer type for Subscription.
定义 subscriber.hpp:34
Subscription(std::shared_ptr< Node > node, const std::string &topic_name, int qos_depth, Callback cb)
Construct a new Subscription object, it is recommended to use the create_subscription() method of the...
定义 subscriber.hpp:47
typename MsgPubSubType::type MsgT
Message type for Subscription.
定义 subscriber.hpp:31
void on_data_available(eprosima::fastdds::dds::DataReader *reader) override
internal method to handle data availability, user should NOT call this directly.
定义 subscriber.hpp:75
Namespace for zzs communication library.
定义 node.hpp:18