1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364
|
// Copyright 2024 Proyectos y Sistemas de Mantenimiento SL (eProsima).
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/**
* @file SubscriberApp.cpp
*
*/
#include "SubscriberApp.hpp"
#include <condition_variable>
#include <mutex>
#include <stdexcept>
#include <fastcdr/exceptions/BadParamException.h>
#include <fastdds/dds/core/status/SubscriptionMatchedStatus.hpp>
#include <fastdds/dds/domain/DomainParticipantFactory.hpp>
#include <fastdds/dds/subscriber/DataReader.hpp>
#include <fastdds/dds/xtypes/dynamic_types/DynamicType.hpp>
#include <fastdds/dds/xtypes/dynamic_types/DynamicDataFactory.hpp>
#include <fastdds/dds/xtypes/dynamic_types/DynamicTypeBuilder.hpp>
#include <fastdds/dds/xtypes/dynamic_types/DynamicTypeBuilderFactory.hpp>
#include <fastdds/dds/subscriber/qos/SubscriberQos.hpp>
#include <fastdds/dds/topic/TypeSupport.hpp>
#include <fastdds/dds/subscriber/SampleInfo.hpp>
#include <fastdds/dds/subscriber/Subscriber.hpp>
#include <fastdds/dds/xtypes/type_representation/TypeObject.hpp>
#include "CLIParser.hpp"
#include "Application.hpp"
using namespace eprosima::fastdds::dds;
namespace eprosima {
namespace fastdds {
namespace examples {
namespace xtypes {
SubscriberApp::SubscriberApp(
const CLIParser::config& config,
const std::string& topic_name)
: participant_(nullptr)
, subscriber_(nullptr)
, topic_name_(topic_name)
, topic_(nullptr)
, reader_(nullptr)
, samples_(config.samples)
, received_samples_(0)
, type_discovered_("")
, stop_(false)
{
// Create the participant
auto factory = DomainParticipantFactory::get_instance();
StatusMask participant_mask = StatusMask::data_available();
participant_mask << eprosima::fastdds::dds::StatusMask::subscription_matched();
participant_ = factory->create_participant_with_default_profile(this, participant_mask);
if (participant_ == nullptr)
{
throw std::runtime_error("Participant initialization failed");
}
}
SubscriberApp::~SubscriberApp()
{
if (nullptr != participant_)
{
// Delete DDS entities contained within the DomainParticipant
if (RETCODE_OK != participant_->delete_contained_entities())
{
// C++11 dtors default to noexcept
std::cerr << "Error deleting contained entities" << std::endl;
}
// Delete DomainParticipant
if (RETCODE_OK != DomainParticipantFactory::get_instance()->delete_participant(participant_))
{
// C++11 dtors default to noexcept
std::cerr << "Error deleting participant" << std::endl;
}
}
}
void SubscriberApp::on_subscription_matched(
DataReader* /*reader*/,
const SubscriptionMatchedStatus& info)
{
if (info.current_count_change == 1)
{
std::cout << "Subscriber matched." << std::endl;
}
else if (info.current_count_change == -1)
{
std::cout << "Subscriber unmatched." << std::endl;
}
else
{
std::cout << info.current_count_change
<< " is not a valid value for SubscriptionMatchedStatus current count change" << std::endl;
}
}
void SubscriberApp::on_data_available(
DataReader* reader)
{
using eprosima::fastcdr::exception::BadParamException;
SampleInfo info;
while ((!is_stopped()) && (RETCODE_OK == reader->take_next_sample(&hello_, &info)))
{
// Mininal type objects are registered with autogenerated member names that may containg non-utf-8 chars.
bool is_member_name_known = false;
// Extract type kind from remote type object
TypeKind type_kind = TK_NONE;
try
{
type_kind = remote_type_object_.complete()._d();
is_member_name_known = true;
}
catch (const BadParamException&)
{
try
{
type_kind = remote_type_object_.minimal()._d();
}
catch (const BadParamException&)
{
throw std::runtime_error("Cannot get type kind from remote type object");
}
}
if (ALIVE_INSTANCE_STATE == info.instance_state && info.valid_data &&
TK_STRUCTURE == type_kind)
{
// Increase received samples
received_samples_++;
std::cout << "Message received:" << std::endl;
// Get all the members by name
DynamicTypeMembersByName members;
if (RETCODE_OK != hello_->type()->get_all_members_by_name(members))
{
throw std::runtime_error("Error getting members by name");
}
// Print all the members
for (auto elem : members)
{
std::string member_name = is_member_name_known ? elem.first.c_str() : "Unkown member name";
std::cout << " - " << member_name << ": ";
MemberDescriptor::_ref_type member_descriptor = {traits<MemberDescriptor>::make_shared()};
if (RETCODE_OK != elem.second->get_descriptor(member_descriptor))
{
throw std::runtime_error("Error getting member descriptor for member");
}
switch (member_descriptor->type()->get_kind())
{
case TK_UINT32:
{
uint32_t uint_data {0};
if (RETCODE_OK != hello_->get_uint32_value(uint_data, elem.second->get_id()))
{
throw std::runtime_error("Error getting uint32 value");
}
std::cout << uint_data << std::endl;
break;
}
case TK_STRING8:
{
std::string str_data {0};
if (RETCODE_OK != hello_->get_string_value(str_data, elem.second->get_id()))
{
throw std::runtime_error("Error getting string value");
}
std::cout << "'" << str_data << "'" << std::endl;
break;
}
default:
{
std::cout << "Unhandled type " << member_descriptor->type()->get_kind() << std::endl;
break;
}
}
}
}
// Stop if the sample limit has been reached
if (samples_ > 0 && (received_samples_ >= samples_))
{
stop();
}
}
}
void SubscriberApp::on_data_writer_discovery(
DomainParticipant* /*participant*/,
eprosima::fastdds::rtps::WriterDiscoveryStatus /*reason*/,
const eprosima::fastdds::dds::PublicationBuiltinTopicData& info,
bool& should_be_ignored)
{
// We don't want to ignore the writer
should_be_ignored = false;
std::lock_guard<std::mutex> lck(mtx_);
// Check if the discovered topic is the one we are interested in
if ((type_discovered_ == "") && (topic_name_ == info.topic_name.to_string()))
{
// Get remote type information and use it to retrieve the type object
remote_type_information_ = info.type_information.type_information;
auto type_id_complete = remote_type_information_.complete().typeid_with_size().type_id();
auto type_id_minimal = remote_type_information_.minimal().typeid_with_size().type_id();
if ((RETCODE_OK != DomainParticipantFactory::get_instance()->type_object_registry().get_type_object(
type_id_complete,
remote_type_object_)) &&
(RETCODE_OK != DomainParticipantFactory::get_instance()->type_object_registry().get_type_object(
type_id_minimal,
remote_type_object_)))
{
std::cout << "Cannot get discovered type from registry:" << std::endl;
std::cout << " - Topic name: " << info.topic_name << std::endl;
std::cout << " - Type name: " << info.type_name << std::endl;
throw std::runtime_error("Error getting type object from registry");
}
// Notify run thread that type has been discovered
type_discovered_ = info.type_name.to_string();
cv_.notify_one();
}
}
void SubscriberApp::run()
{
// Wait for type discovery
{
std::unique_lock<std::mutex> lck(mtx_);
cv_.wait(lck, [&]
{
return is_stopped() || (type_discovered_ != "");
});
}
// Create entities unless we need to exit
if (type_discovered_ != "")
{
initialize_entities();
}
// Wait for shutdown command
{
std::unique_lock<std::mutex> lck(mtx_);
cv_.wait(lck, [&]
{
return is_stopped();
});
}
}
bool SubscriberApp::is_stopped()
{
return stop_.load();
}
void SubscriberApp::stop()
{
stop_.store(true);
cv_.notify_all();
}
void SubscriberApp::initialize_entities()
{
// Register remotely discovered type
DynamicTypeBuilder::_ref_type type_builder = DynamicTypeBuilderFactory::get_instance()->create_type_w_type_object(
remote_type_object_);
if (!type_builder)
{
throw std::runtime_error("Error creating type builder");
}
// Build the type
remote_type_ = type_builder->build();
if (!remote_type_)
{
throw std::runtime_error("Error building type");
}
TypeSupport dyn_type_support(new DynamicPubSubType(remote_type_, remote_type_information_));
if (RETCODE_OK != dyn_type_support.register_type(participant_, type_discovered_))
{
throw std::runtime_error("Error registering type");
}
// Initialize the DynamicData
hello_ = DynamicDataFactory::get_instance()->create_data(remote_type_);
if (!hello_)
{
throw std::runtime_error("Error creating DynamicData");
}
// Create the subscriber
SubscriberQos sub_qos = SUBSCRIBER_QOS_DEFAULT;
participant_->get_default_subscriber_qos(sub_qos);
subscriber_ = participant_->create_subscriber(sub_qos);
if (nullptr == subscriber_)
{
throw std::runtime_error("Subscriber initialization failed");
}
// Create the topic
TopicQos topic_qos = TOPIC_QOS_DEFAULT;
participant_->get_default_topic_qos(topic_qos);
topic_ = participant_->create_topic(topic_name_, type_discovered_, topic_qos);
if (nullptr == topic_)
{
throw std::runtime_error("Topic initialization failed");
}
// Create the reader
DataReaderQos reader_qos = DATAREADER_QOS_DEFAULT;
subscriber_->get_default_datareader_qos(reader_qos);
reader_ = subscriber_->create_datareader(topic_, reader_qos);
if (nullptr == reader_)
{
throw std::runtime_error("DataReader initialization failed");
}
}
} // namespace xtypes
} // namespace examples
} // namespace fastdds
} // namespace eprosima
|