SIT/templates/cpp/dds_receiver.template

116 lines
2.4 KiB
Plaintext

{# DDS接收器模板 #}
{% if part == 'header' %}
#pragma once
#include <vector>
#include <cstdint>
#include <string>
#include <dds/dds.hpp>
/**
* DDS数据接收器
* 用于接收{{ source_message.full_name }}消息
*/
class DataReceiver {
public:
DataReceiver();
~DataReceiver();
// 初始化DDS连接
bool initialize(const std::string& topic_name, int domain_id = 0);
// 接收数据
std::vector<uint8_t> receive();
// 关闭连接
void close();
private:
dds::domain::DomainParticipant* participant_;
dds::sub::Subscriber* subscriber_;
dds::sub::DataReader<dds::core::BytesTopicType>* reader_;
bool initialized_;
};
{% else %}
#include "receiver.h"
#include <stdexcept>
DataReceiver::DataReceiver()
: participant_(nullptr),
subscriber_(nullptr),
reader_(nullptr),
initialized_(false) {
}
DataReceiver::~DataReceiver() {
close();
}
bool DataReceiver::initialize(const std::string& topic_name, int domain_id) {
try {
// 创建Domain Participant
participant_ = new dds::domain::DomainParticipant(domain_id);
// 创建Subscriber
subscriber_ = new dds::sub::Subscriber(*participant_);
// 创建Topic
dds::topic::Topic<dds::core::BytesTopicType> topic(
*participant_, topic_name
);
// 创建DataReader
reader_ = new dds::sub::DataReader<dds::core::BytesTopicType>(
*subscriber_, topic
);
initialized_ = true;
return true;
} catch (const std::exception& e) {
close();
return false;
}
}
std::vector<uint8_t> DataReceiver::receive() {
if (!initialized_) {
throw std::runtime_error("DDS not initialized");
}
// 等待数据
dds::sub::LoanedSamples<dds::core::BytesTopicType> samples =
reader_->take();
if (samples.length() > 0) {
const dds::core::BytesTopicType& data = samples[0].data();
// 转换为vector
std::vector<uint8_t> buffer(data.begin(), data.end());
return buffer;
}
return std::vector<uint8_t>();
}
void DataReceiver::close() {
if (reader_) {
delete reader_;
reader_ = nullptr;
}
if (subscriber_) {
delete subscriber_;
subscriber_ = nullptr;
}
if (participant_) {
delete participant_;
participant_ = nullptr;
}
initialized_ = false;
}
{% endif %}