/* * Publisher.h * * Created on: Nov 16, 2015 * Author: sune */ #ifndef PUBLISHER_HPP_ #define PUBLISHER_HPP_ #include #include #include "ndds/ndds_cpp.h" #include "ParticipantWrapper.h" #include "Exception.hpp" namespace cobraid { template class Publisher { public: Publisher(ParticipantWrapper& participant, std::string topicName); virtual ~Publisher(); void publish(T& message); private: void createPublisher(); void createTopic(const char* topicName); void createDataWriter(); void publisher_shutdown(); DDSDomainParticipant* participant; DDSPublisher* publisher; DDSTopic* topic; typename T::DataWriter* dataWriter; T* instance; }; } /* namespace cobraid */ //Implementation template inline cobraid::Publisher::Publisher(ParticipantWrapper& participant, std::string topicName) { this->participant = participant.getDomainParticipant(); createPublisher(); createTopic(topicName.c_str()); createDataWriter(); instance = T::TypeSupport::create_data(); if (instance == NULL) { publisher_shutdown(); throw cobraid::exceptions::NullReferenceError("Failed to create data"); } } template inline cobraid::Publisher::~Publisher() { publisher_shutdown(); T::TypeSupport::delete_data(instance); } template inline void cobraid::Publisher::publish(T& message) { T::TypeSupport::copy_data(instance, &message); dataWriter->write(*instance, DDS_HANDLE_NIL); } template inline void cobraid::Publisher::createPublisher() { publisher = participant->create_publisher(DDS_PUBLISHER_QOS_DEFAULT, NULL, DDS_STATUS_MASK_NONE); if (publisher == NULL) { publisher_shutdown(); throw cobraid::exceptions::NullReferenceError("Failed to create publisher"); } } template inline void cobraid::Publisher::createTopic(const char* topicName) { const char* TTypeName = T::TypeSupport::get_type_name(); T::TypeSupport::register_type(participant, TTypeName); topic = participant->create_topic(topicName, TTypeName, DDS_TOPIC_QOS_DEFAULT, NULL, DDS_STATUS_MASK_ALL); if (topic == NULL) { publisher_shutdown(); throw cobraid::exceptions::NullReferenceError("Failed to create topic"); } } template inline void cobraid::Publisher::createDataWriter() { DDS_DataWriterQos qos = DDS_DATAWRITER_QOS_DEFAULT; qos.publish_mode.kind = DDS_ASYNCHRONOUS_PUBLISH_MODE_QOS; qos.publish_mode.flow_controller_name = DDS_String_dup("MyFlowController"); qos.reliability.kind = DDS_RELIABLE_RELIABILITY_QOS; DDSDataWriter* writer = participant->create_datawriter(topic, qos, NULL, DDS_STATUS_MASK_NONE); if (writer == NULL) { publisher_shutdown(); throw cobraid::exceptions::NullReferenceError("Failed to create DataWriter"); } dataWriter = T::DataWriter::narrow(writer); if (dataWriter == NULL) { publisher_shutdown(); throw std::bad_cast(); } } template inline void cobraid::Publisher::publisher_shutdown() { participant->delete_datawriter(dataWriter); if (publisher != NULL) { participant->delete_publisher(publisher); } } #endif /* PUBLISHER_HPP_ */