repo_name
stringclasses 10
values | file_path
stringlengths 29
222
| content
stringlengths 24
926k
| extention
stringclasses 5
values |
---|---|---|---|
rticonnextdds-examples | data/projects/rticonnextdds-examples/connext_dds/asynchronous_publication/c++11/async_subscriber.cxx | /*******************************************************************************
(c) 2005-2015 Copyright, Real-Time Innovations, Inc. All rights reserved.
RTI grants Licensee a license to use, modify, compile, and create derivative
works of the Software. Licensee has the right to distribute object form only
for use with RTI products. The Software is provided "as is", with no warranty
of any type, including any warranty for fitness for any purpose. RTI is under
no obligation to maintain or support the Software. RTI shall not be liable for
any incidental or consequential damages arising out of the use or inability to
use the software.
******************************************************************************/
#include <algorithm>
#include <iostream>
#include <dds/sub/ddssub.hpp>
#include <dds/core/ddscore.hpp>
#include <rti/config/Logger.hpp> // for logging
#include "async.hpp"
#include "application.hpp" // for command line parsing and ctrl-c
// For timekeeping
clock_t InitTime;
int process_data(dds::sub::DataReader<async> reader)
{
int count = 0;
dds::sub::LoanedSamples<async> samples = reader.take();
for (const auto &sample : samples) {
// Print the time we get each sample.
if (sample.info().valid()) {
count++;
double elapsed_ticks = clock() - InitTime;
double elapsed_secs = elapsed_ticks / CLOCKS_PER_SEC;
std::cout << "@ t=" << elapsed_secs << "s"
<< ", got x = " << sample.data().x() << std::endl;
} else {
std::cout << "Instance state changed to "
<< sample.info().state().instance_state() << std::endl;
}
}
return count;
} // The LoanedSamples destructor returns the loan
void run_subscriber_application(
unsigned int domain_id,
unsigned int sample_count)
{
// For timekeeping
InitTime = clock();
// To customize the paritcipant QoS, use the file USER_QOS_PROFILES.xml
dds::domain::DomainParticipant participant(domain_id);
// To customize the topic QoS, use the file USER_QOS_PROFILES.xml
dds::topic::Topic<async> topic(participant, "Example async");
// Retrieve the default DataReader QoS, from USER_QOS_PROFILES.xml
dds::sub::qos::DataReaderQos reader_qos =
dds::core::QosProvider::Default().datareader_qos();
// If you want to change the DataWriter's QoS programmatically rather than
// using the XML file, uncomment the following lines.
// reader_qos << Reliability::Reliable();
// reader_qos << History::KeepAll();
// Create a DataReader with a QoS
// Create a Subscriber and DataReader with default Qos
dds::sub::Subscriber subscriber(participant);
dds::sub::DataReader<async> reader(subscriber, topic, reader_qos);
// WaitSet will be woken when the attached condition is triggered
dds::core::cond::WaitSet waitset;
// Create a ReadCondition for any data on this reader, and add to WaitSet
unsigned int samples_read = 0;
dds::sub::cond::ReadCondition read_condition(
reader,
dds::sub::status::DataState::new_data(),
[reader, &samples_read]() {
samples_read += process_data(reader);
});
waitset += read_condition;
// Main loop
while (!application::shutdown_requested && samples_read < sample_count) {
std::cout << "async subscriber sleeping up to 4 sec..." << std::endl;
// Wait for data and report if it does not arrive in 1 second
waitset.dispatch(dds::core::Duration(4));
}
}
int main(int argc, char *argv[])
{
using namespace application;
// Parse arguments and handle control-C
auto arguments = parse_arguments(argc, argv);
if (arguments.parse_result == ParseReturn::exit) {
return EXIT_SUCCESS;
} else if (arguments.parse_result == ParseReturn::failure) {
return EXIT_FAILURE;
}
setup_signal_handlers();
// Sets Connext verbosity to help debugging
rti::config::Logger::instance().verbosity(arguments.verbosity);
try {
run_subscriber_application(arguments.domain_id, arguments.sample_count);
} catch (const std::exception &ex) {
// This will catch DDS exceptions
std::cerr << "Exception in run_subscriber_application(): " << ex.what()
<< std::endl;
return EXIT_FAILURE;
}
// Releases the memory used by the participant factory. Optional at
// application exit
dds::domain::DomainParticipant::finalize_participant_factory();
return EXIT_SUCCESS;
}
| cxx |
rticonnextdds-examples | data/projects/rticonnextdds-examples/connext_dds/group_coherent_presentation/c++11/application.hpp | /*
* (c) Copyright, Real-Time Innovations, 2020. All rights reserved.
* RTI grants Licensee a license to use, modify, compile, and create derivative
* works of the software solely for use with RTI Connext DDS. Licensee may
* redistribute copies of the software provided that all such copies are subject
* to this license. The software is provided "as is", with no warranty of any
* type, including any warranty for fitness for any purpose. RTI is under no
* obligation to maintain or support the software. RTI shall not be liable for
* any incidental or consequential damages arising out of the use or inability
* to use the software.
*/
#ifndef APPLICATION_HPP
#define APPLICATION_HPP
#include <iostream>
#include <csignal>
#include <dds/core/ddscore.hpp>
namespace application {
// Catch control-C and tell application to shut down
bool shutdown_requested = false;
inline void stop_handler(int)
{
shutdown_requested = true;
std::cout << "preparing to shut down..." << std::endl;
}
inline void setup_signal_handlers()
{
signal(SIGINT, stop_handler);
signal(SIGTERM, stop_handler);
}
enum class ParseReturn {
ok,
failure,
exit
};
struct ApplicationArguments {
ParseReturn parse_result;
unsigned int domain_id;
unsigned int set_count;
rti::config::Verbosity verbosity;
bool use_xml_qos;
ApplicationArguments(
ParseReturn parse_result_param,
unsigned int domain_id_param,
unsigned int set_count_param,
rti::config::Verbosity verbosity_param,
bool use_xml_qos_param)
: parse_result(parse_result_param),
domain_id(domain_id_param),
set_count(set_count_param),
verbosity(verbosity_param),
use_xml_qos(use_xml_qos_param) {}
};
inline void set_verbosity(
rti::config::Verbosity& verbosity,
int verbosity_value)
{
switch (verbosity_value) {
case 0:
verbosity = rti::config::Verbosity::SILENT;
break;
case 1:
verbosity = rti::config::Verbosity::EXCEPTION;
break;
case 2:
verbosity = rti::config::Verbosity::WARNING;
break;
case 3:
verbosity = rti::config::Verbosity::STATUS_ALL;
break;
default:
verbosity = rti::config::Verbosity::EXCEPTION;
break;
}
}
// Parses application arguments for example.
inline ApplicationArguments parse_arguments(int argc, char *argv[])
{
int arg_processing = 1;
bool show_usage = false;
ParseReturn parse_result = ParseReturn::ok;
unsigned int domain_id = 0;
unsigned int set_count = (std::numeric_limits<unsigned int>::max)();
rti::config::Verbosity verbosity(rti::config::Verbosity::EXCEPTION);
bool use_xml_qos = true;
while (arg_processing < argc) {
if ((argc > arg_processing + 1)
&& (strcmp(argv[arg_processing], "-d") == 0
|| strcmp(argv[arg_processing], "--domain") == 0)) {
domain_id = atoi(argv[arg_processing + 1]);
arg_processing += 2;
} else if ((argc > arg_processing + 1)
&& (strcmp(argv[arg_processing], "-s") == 0
|| strcmp(argv[arg_processing], "--set-count") == 0)) {
set_count = atoi(argv[arg_processing + 1]);
arg_processing += 2;
} else if ((argc > arg_processing + 1)
&& (strcmp(argv[arg_processing], "-v") == 0
|| strcmp(argv[arg_processing], "--verbosity") == 0)) {
set_verbosity(verbosity, atoi(argv[arg_processing + 1]));
arg_processing += 2;
} else if ((argc > arg_processing + 1)
&& (strcmp(argv[arg_processing], "-x") == 0
|| strcmp(argv[arg_processing], "--xml_qos") == 0)) {
use_xml_qos = atoi(argv[arg_processing + 1]) == 0 ? false : true;
arg_processing += 2;
} else if (strcmp(argv[arg_processing], "-h") == 0
|| strcmp(argv[arg_processing], "--help") == 0) {
std::cout << "Example application." << std::endl;
show_usage = true;
parse_result = ParseReturn::exit;
break;
} else {
std::cout << "Bad parameter." << std::endl;
show_usage = true;
parse_result = ParseReturn::failure;
break;
}
}
if (show_usage) {
std::cout << "Usage:\n"\
" -d, --domain <int> Domain ID this application will\n" \
" join. \n"
" Default: 0\n"\
" -s, --set_count <int> (publisher only) Number of coherent \n" \
" sets to send before cleanly shutting \n" \
" down. \n"
" Default: infinite\n"
" -v, --verbosity <int> Logging verbosity.\n"\
" Range: 0-3 \n"
" Default: 1\n"
" -x, --xml_qos <0|1> Whether to set the QoS using XML or programatically.\n"\
" Default: 1 (use XML) \n"
<< std::endl;
}
return ApplicationArguments(
parse_result, domain_id, set_count, verbosity, use_xml_qos);
}
} // namespace application
#endif // APPLICATION_HPP
| hpp |
rticonnextdds-examples | data/projects/rticonnextdds-examples/connext_dds/group_coherent_presentation/c++11/GroupCoherentExample_publisher.cxx | /*
* (c) Copyright, Real-Time Innovations, 2021. All rights reserved.
* RTI grants Licensee a license to use, modify, compile, and create derivative
* works of the software solely for use with RTI Connext DDS. Licensee may
* redistribute copies of the software provided that all such copies are subject
* to this license. The software is provided "as is", with no warranty of any
* type, including any warranty for fitness for any purpose. RTI is under no
* obligation to maintain or support the software. RTI shall not be liable for
* any incidental or consequential damages arising out of the use or inability
* to use the software.
*/
#include <iostream>
#include <random>
#include <dds/pub/ddspub.hpp>
#include <rti/util/util.hpp>
#include <rti/config/Logger.hpp>
#include "application.hpp"
#include "GroupCoherentExample.hpp"
using namespace dds::core;
using namespace dds::core::policy;
using namespace dds::pub::qos;
using namespace GroupCoherentExample;
// Generate patient data
std::default_random_engine generator;
std::uniform_int_distribution<int32_t> distrib(0, 3);
int32_t get_patient_heart_rate()
{
static int32_t heart_rates[4] = { 35, 56, 85, 110 };
int32_t index = distrib(generator);
return heart_rates[index];
}
float get_patient_temperature()
{
static float temperatures[4] = { 95.0, 98.1, 99.2, 101.7 };
int32_t index = distrib(generator);
return temperatures[index];
}
void run_publisher_application(
unsigned int domain_id,
unsigned int set_count,
bool use_xml_qos)
{
// Start communicating in a domain, usually one participant per application
dds::domain::DomainParticipant participant(domain_id);
// Create three Topics with names and a datatypes
dds::topic::Topic<Alarm> alarm_topic(participant, "Alarm");
dds::topic::Topic<HeartRate> heart_rate_topic(participant, "HeartRate");
dds::topic::Topic<Temperature> temperature_topic(
participant,
"Temperature");
PublisherQos publisher_qos;
if (use_xml_qos) {
// Retrieve the Publisher QoS, from USER_QOS_PROFILES.xml.
publisher_qos = QosProvider::Default().publisher_qos();
} else {
// Set the Publisher QoS programatically
publisher_qos << Presentation::GroupAccessScope(true, true);
}
dds::pub::Publisher publisher(participant, publisher_qos);
DataWriterQos writer_qos;
if (use_xml_qos) {
// Retrieve the DataWriter QoS, from USER_QOS_PROFILES.xml.
writer_qos = QosProvider::Default().datawriter_qos();
} else {
// Set the DataWriter QoS programatically
writer_qos << Reliability::Reliable() << History::KeepAll();
}
// Create a DataWriter for each topic
dds::pub::DataWriter<Alarm> alarm_writer(
publisher,
alarm_topic,
writer_qos);
dds::pub::DataWriter<HeartRate> heart_rate_writer(
publisher,
heart_rate_topic,
writer_qos);
dds::pub::DataWriter<Temperature> temperature_writer(
publisher,
temperature_topic,
writer_qos);
Alarm alarm_data;
alarm_data.patient_id(1);
alarm_data.alarm_code(AlarmCode::PATIENT_OK);
HeartRate heart_rate_data;
heart_rate_data.patient_id(1);
heart_rate_data.beats_per_minute(65);
Temperature temperature_data;
temperature_data.patient_id(1);
temperature_data.temperature(98.6);
// Below we will write a coherent set any time the patient's vitals are
// abnormal. Otherwise, we will publish the patient's vitals normally
for (unsigned int samples_written = 0;
!application::shutdown_requested && samples_written < set_count;
samples_written++) {
heart_rate_data.beats_per_minute(get_patient_heart_rate());
temperature_data.temperature(get_patient_temperature());
if (heart_rate_data.beats_per_minute() >= 100
|| heart_rate_data.beats_per_minute() <= 40
|| temperature_data.temperature() >= 100.0
|| temperature_data.temperature() <= 95.0) {
// Sound an alarm. In this case, we want all of the patients vitals
// along with the alarm to be delivered as a single coherent set of
// data so that we can correlate the alarm with the set of vitals
// that triggered it
{
dds::pub::CoherentSet coherent_set(publisher); // Start a
// coherent set
heart_rate_writer.write(heart_rate_data);
temperature_writer.write(temperature_data);
alarm_data.alarm_code(AlarmCode::ABNORMAL_READING);
alarm_writer.write(alarm_data);
} // end coherent set
} else {
// No alarm necessary, publish the patient's vitals as normal
heart_rate_writer.write(heart_rate_data);
temperature_writer.write(temperature_data);
}
rti::util::sleep(dds::core::Duration(2));
}
}
int main(int argc, char *argv[])
{
using namespace application;
// Parse arguments and handle control-C
auto arguments = parse_arguments(argc, argv);
if (arguments.parse_result == ParseReturn::exit) {
return EXIT_SUCCESS;
} else if (arguments.parse_result == ParseReturn::failure) {
return EXIT_FAILURE;
}
setup_signal_handlers();
// Sets Connext verbosity to help debugging
rti::config::Logger::instance().verbosity(arguments.verbosity);
try {
run_publisher_application(
arguments.domain_id,
arguments.set_count,
arguments.use_xml_qos);
} catch (const std::exception &ex) {
// This will catch DDS exceptions
std::cerr << "Exception in run_publisher_application(): " << ex.what()
<< std::endl;
return EXIT_FAILURE;
}
// Releases the memory used by the participant factory. Optional at
// application exit
dds::domain::DomainParticipant::finalize_participant_factory();
return EXIT_SUCCESS;
}
| cxx |
rticonnextdds-examples | data/projects/rticonnextdds-examples/connext_dds/group_coherent_presentation/c++11/GroupCoherentExample_subscriber.cxx | /*
* (c) Copyright, Real-Time Innovations, 2021. All rights reserved.
* RTI grants Licensee a license to use, modify, compile, and create derivative
* works of the software solely for use with RTI Connext DDS. Licensee may
* redistribute copies of the software provided that all such copies are subject
* to this license. The software is provided "as is", with no warranty of any
* type, including any warranty for fitness for any purpose. RTI is under no
* obligation to maintain or support the software. RTI shall not be liable for
* any incidental or consequential damages arising out of the use or inability
* to use the software.
*/
#include <algorithm>
#include <iostream>
#include <dds/sub/ddssub.hpp>
#include <dds/core/ddscore.hpp>
#include <rti/config/Logger.hpp>
#include "GroupCoherentExample.hpp"
#include "application.hpp"
using namespace dds::core;
using namespace dds::core::policy;
using namespace dds::sub;
using namespace dds::sub::qos;
using namespace GroupCoherentExample;
template<typename T>
class PatientDRListener : public dds::sub::NoOpDataReaderListener<T> {
public:
void on_sample_lost(
dds::sub::DataReader<T> &,
const dds::core::status::SampleLostStatus &status)
{
if (status.extensions().last_reason()
== rti::core::status::SampleLostState::
lost_by_incomplete_coherent_set()) {
std::cout << "Lost " << status.total_count_change()
<< " samples in an incomplete coherent set.\n";
}
}
};
void print_coherent_set_info(const dds::sub::SampleInfo &info)
{
// The coherent_set_info in the SampleInfo is only present if the sample is
// part of a coherent set. We therefore need to check if it is present
// before accessing any of the members
if (info.extensions().coherent_set_info().has_value()) {
const rti::core::CoherentSetInfo &set_info =
*info.extensions().coherent_set_info();
std::cout << "Sample is part of "
<< (set_info.incomplete_coherent_set() ? "an incomplete "
: "a complete ")
<< "group coherent set with SN ("
<< set_info.group_coherent_set_sequence_number() << ");\n"
<< std::endl;
} else {
std::cout << "Sample is not part of a coherent set.\n" << std::endl;
}
}
void process_data(dds::sub::Subscriber subscriber)
{
{
CoherentAccess coherent_access(subscriber); // Begin coherent access
std::vector<AnyDataReader> readers;
// Get the list of readers with samples that have not been read yet
find(subscriber,
dds::sub::status::SampleState::not_read(),
std::back_inserter(readers));
// Iterate through the returned readers list and take their samples
for (AnyDataReader reader : readers) {
if (reader.topic_name() == "Alarm") {
dds::sub::LoanedSamples<Alarm> samples =
reader.get<Alarm>().take();
for (const auto &sample : samples) {
std::cout << sample << std::endl;
print_coherent_set_info(sample.info());
}
} else if (reader.topic_name() == "HeartRate") {
dds::sub::LoanedSamples<HeartRate> samples =
reader.get<HeartRate>().take();
for (const auto &sample : samples) {
std::cout << sample << std::endl;
print_coherent_set_info(sample.info());
}
} else if (reader.topic_name() == "Temperature") {
dds::sub::LoanedSamples<Temperature> samples =
reader.get<Temperature>().take();
for (const auto &sample : samples) {
std::cout << sample << std::endl;
print_coherent_set_info(sample.info());
}
}
}
} // end coherent access
}
void run_subscriber_application(unsigned int domain_id, bool use_xml_qos)
{
// Start communicating in a domain, usually one participant per application
dds::domain::DomainParticipant participant(domain_id);
// Create three Topics with names and a datatypes
dds::topic::Topic<Alarm> alarm_topic(participant, "Alarm");
dds::topic::Topic<HeartRate> heart_rate_topic(participant, "HeartRate");
dds::topic::Topic<Temperature> temperature_topic(
participant,
"Temperature");
SubscriberQos subscriber_qos;
if (use_xml_qos) {
// Retrieve the Subscriber QoS, from USER_QOS_PROFILES.xml.
subscriber_qos = QosProvider::Default().subscriber_qos();
} else {
// Set the Subscriber QoS programatically
subscriber_qos << Presentation::GroupAccessScope(true, true);
// Uncomment this line to keep and deliver incomplete coherent sets to
// the application
// subscriber_qos.policy<Presentation>().extensions().drop_incomplete_coherent_set(false);
}
dds::sub::Subscriber subscriber(participant, subscriber_qos);
// Retrieve the default DataReader QoS, from USER_QOS_PROFILES.xml
DataReaderQos reader_qos;
if (use_xml_qos) {
// Retrieve the DataReader QoS, from USER_QOS_PROFILES.xml.
reader_qos = QosProvider::Default().datareader_qos();
} else {
// Set the DataReader QoS programatically
reader_qos << Reliability::Reliable() << History::KeepAll();
}
auto alarm_listener = std::make_shared<PatientDRListener<Alarm>>();
auto heart_rate_listener = std::make_shared<PatientDRListener<HeartRate>>();
auto temperature_listener =
std::make_shared<PatientDRListener<Temperature>>();
// We are installing a listener for the sample lost status in case an
// incomplete coherent set is received and dropped (assuming the
// PresentationQosPolicy::drop_incomplete_coherent_set is
// true (the default))
dds::sub::DataReader<Alarm> alarm_reader(
subscriber,
alarm_topic,
reader_qos,
alarm_listener,
dds::core::status::StatusMask::sample_lost());
dds::sub::DataReader<HeartRate> heart_rate_reader(
subscriber,
heart_rate_topic,
reader_qos,
heart_rate_listener,
dds::core::status::StatusMask::sample_lost());
dds::sub::DataReader<Temperature> temperature_reader(
subscriber,
temperature_topic,
reader_qos,
temperature_listener,
dds::core::status::StatusMask::sample_lost());
dds::core::cond::WaitSet waitset;
dds::core::cond::StatusCondition cond(subscriber);
dds::core::cond::Condition scond_from_handler = dds::core::null;
cond.enabled_statuses(dds::core::status::StatusMask::data_on_readers());
cond.extensions().handler([subscriber]() { process_data(subscriber); });
waitset += cond;
while (!application::shutdown_requested) {
waitset.dispatch(dds::core::Duration(1));
}
}
int main(int argc, char *argv[])
{
using namespace application;
// Parse arguments and handle control-C
auto arguments = parse_arguments(argc, argv);
if (arguments.parse_result == ParseReturn::exit) {
return EXIT_SUCCESS;
} else if (arguments.parse_result == ParseReturn::failure) {
return EXIT_FAILURE;
}
setup_signal_handlers();
// Sets Connext verbosity to help debugging
rti::config::Logger::instance().verbosity(arguments.verbosity);
if (arguments.set_count != (std::numeric_limits<unsigned int>::max)()) {
std::cerr << "The -s, --set_count argument is only applicable to the"
" publisher application. It will be ignored."
<< std::endl;
}
try {
run_subscriber_application(arguments.domain_id, arguments.use_xml_qos);
} catch (const std::exception &ex) {
// This will catch DDS exceptions
std::cerr << "Exception in run_subscriber_application(): " << ex.what()
<< std::endl;
return EXIT_FAILURE;
}
// Releases the memory used by the participant factory. Optional at
// application exit
dds::domain::DomainParticipant::finalize_participant_factory();
return EXIT_SUCCESS;
}
| cxx |
rticonnextdds-examples | data/projects/rticonnextdds-examples/connext_dds/zero_copy/c++/zero_copy_subscriber.cxx | /*******************************************************************************
(c) 2005-2017 Copyright, Real-Time Innovations, Inc. All rights reserved.
RTI grants Licensee a license to use, modify, compile, and create derivative
works of the Software. Licensee has the right to distribute object form only
for use with RTI products. The Software is provided "as is", with no warranty
of any type, including any warranty for fitness for any purpose. RTI is under
no obligation to maintain or support the Software. RTI shall not be liable for
any incidental or consequential damages arising out of the use or inability to
use the software.
******************************************************************************/
#include <cstdio>
#include <cstdlib>
#include <map>
#include <iostream>
#include <sstream>
#include "zero_copy.h"
#include "zero_copySupport.h"
#include "FrameSupport.h"
#include "ndds/ndds_cpp.h"
#include "ndds/ndds_namespace_cpp.h"
#include "ndds/clock/clock_highResolution.h"
#include "ndds/osapi/osapi_ntptime.h"
using namespace DDS;
struct CommandLineArguments {
public:
int domain_id;
int size;
int sample_count;
bool verbose;
CommandLineArguments() {
domain_id = 0;
sample_count = 1200;
size = 1048576;
verbose = false;
}
};
CommandLineArguments arg;
// Compute the latency with the given current_time and source_timestamp
static void compute_latency(
DDS_Duration_t &latency,
RTINtpTime current_time,
const DDS_Time_t &source_timestamp)
{
RTINtpTime source_time = RTI_NTP_TIME_ZERO;
// Convert DDS_Time_t format to RTINtpTime format
RTINtpTime_packFromNanosec(
source_time,
source_timestamp.sec,
source_timestamp.nanosec);
// Compute the difference and store in current_time
RTINtpTime_decrement(current_time, source_time);
// Convert RTINtpTime format to DDS_Duration_t format
RTINtpTime_unpackToNanosec(latency.sec, latency.nanosec, current_time);
}
// Get the shared memory key from the publication data property
static int lookup_shmem_key_property(DDS::PropertyQosPolicy& property)
{
const DDS::Property_t *p = DDS::PropertyQosPolicyHelper::lookup_property(
property,
"shmem_key");
if (p == NULL) {
return -1;
}
int key;
std::istringstream str_to_key(p->value);
str_to_key >> key;
return key;
}
bool operator<(const DDS::GUID_t& a, const DDS::GUID_t& b)
{
return DDS_GUID_compare(&a, &b) < 0;
}
bool operator==(const DDS::GUID_t& a, const DDS::GUID_t& b)
{
return DDS_GUID_equals(&a, &b) == DDS_BOOLEAN_TRUE;
}
class ShmemKeyTrackingReaderListener : public DDSDataReaderListener {
public:
~ShmemKeyTrackingReaderListener()
{
for (FrameSetViewMap::iterator iter = frame_set_views.begin();
iter != frame_set_views.end(); ++iter) {
delete iter->second;
}
}
FrameSetView* get_frame_set_view(const DDS::GUID_t& publication_guid) const
{
FrameSetViewMap::const_iterator key_it = frame_set_views.find(
publication_guid);
if (key_it == frame_set_views.end()) {
return NULL;
}
return key_it->second;
}
size_t get_frame_set_view_count() const
{
return frame_set_views.size();
}
private:
typedef std::map<DDS::GUID_t, FrameSetView*> FrameSetViewMap;
// Map to store the frame_set_views created for each matched frame_set
FrameSetViewMap frame_set_views;
void on_subscription_matched(
DDSDataReader* reader,
const DDS_SubscriptionMatchedStatus& status) /* override */
{
try {
DDS::PublicationBuiltinTopicData publication_data;
if (reader->get_matched_publication_data(
publication_data,
status.last_publication_handle) != DDS_RETCODE_OK) {
return;
}
int key = lookup_shmem_key_property(publication_data.property);
if (key == -1) {
return;
}
DDS::GUID_t publication_guid;
DDS_BuiltinTopicKey_to_guid(
&publication_data.key,
&publication_guid);
if (frame_set_views.find(publication_guid)
== frame_set_views.end()){
// Create the frame_set_view with the key and size. This frame
// set view attaches to the shared memory segment created by the
// frame set managed by the matched DataWriter
FrameSetView *frame_set_view = new FrameSetView(key, arg.size);
frame_set_views[publication_guid] = frame_set_view;
} else {
std::cout << "Unable to track the key " << key << std::endl;
}
} catch (...) {
std::cout << "Exception in on_subscription_matched. " << std::endl;
}
}
};
class ZeroCopyListener : public ShmemKeyTrackingReaderListener {
public:
virtual void on_requested_deadline_missed(
DataReader* /*reader*/,
const RequestedDeadlineMissedStatus& /*status*/) {}
virtual void on_requested_incompatible_qos(
DataReader* /*reader*/,
const RequestedIncompatibleQosStatus& /*status*/) {}
virtual void on_sample_rejected(
DataReader* /*reader*/,
const SampleRejectedStatus& /*status*/) {}
virtual void on_liveliness_changed(
DataReader* /*reader*/,
const LivelinessChangedStatus& /*status*/) {}
virtual void on_sample_lost(
DataReader* /*reader*/,
const SampleLostStatus& /*status*/) {}
virtual void on_data_available(DataReader* reader);
ZeroCopyListener() :
total_latency(DDS_DURATION_ZERO),
received_frames(0),
shutdown_application(false)
{
clock = RTIHighResolutionClock_new();
}
~ZeroCopyListener()
{
RTIHighResolutionClock_delete(clock);
}
bool start_shutdown()
{
return shutdown_application;
}
private:
// Sum of frame latency
DDS_Duration_t total_latency;
// Total number of received frames
int received_frames;
// Used for getting system time
RTIClock *clock;
RTINtpTime previous_print_time;
bool shutdown_application;
// Prints average latency in micro seconds
void print_average_latency()
{
std::cout << "Average latency: "
<< ((total_latency.sec * 1000000)
+ (total_latency.nanosec / 1000)) / received_frames
<< " microseconds" << std::endl;
}
};
void ZeroCopyListener::on_data_available(DataReader* reader)
{
ZeroCopyDataReader *ZeroCopy_reader = ZeroCopyDataReader::narrow(reader);
if (ZeroCopy_reader == NULL) {
std::cout << "DataReader narrow error" << std::endl;
return;
}
ZeroCopySeq data_seq;
SampleInfoSeq info_seq;
ReturnCode_t retcode;
retcode = ZeroCopy_reader->take(
data_seq, info_seq, LENGTH_UNLIMITED,
ANY_SAMPLE_STATE, ANY_VIEW_STATE, ANY_INSTANCE_STATE);
if (retcode == RETCODE_NO_DATA) {
return;
} else if (retcode != RETCODE_OK) {
std::cout << "take error "<< retcode << std::endl;
return;
}
unsigned int received_checksum = 0, computed_checksum = 0;
RTINtpTime current_time = RTI_NTP_TIME_ZERO;
DDS_Duration_t latency;
for (int i = 0; i < data_seq.length(); ++i) {
if (info_seq[i].valid_data) {
// Get the frame_set_view associated with the virtual guid
// This is done because there may be multiple Publishers
// publishing frames. Each publisher creates its own
// shared memory segement to store frames and is identified by
// info_seq[i].publication_virtual_guid
FrameSetView *frame_set_view = get_frame_set_view(
info_seq[i].publication_virtual_guid);
if (frame_set_view == NULL) {
std::cout << "Received data from an un recognized frame "
"writer" << std::endl;
continue;
}
// Get the frame checksum from the sample
received_checksum = data_seq[i].checksum;
// Get the frame from the shared memory segment
// at the provided index
const Frame *frame = (*frame_set_view)[data_seq[i].index];
// Compute the checksum of the frame
// We only compute the checksum of the first 4 bytes. These
// are the bytes that we change in each frame for this example
// We dont compute CRC for the whole frame because it would add
// a latency component not due to the middleware. Real
// application may compute CRC differently
computed_checksum = RTIOsapiUtility_crc32(
frame->get_buffer(),
sizeof(int),
0);
// Validate the computed checksum with the checksum sent by the
// DataWriter
if (computed_checksum != received_checksum) {
std::cout << "Checksum NOT OK" << std::endl;
}
// Compute the latency from the source time
clock->getTime(clock, ¤t_time);
compute_latency(latency, current_time, info_seq[i].source_timestamp);
// Keep track of total latency for computing averages
total_latency = total_latency + latency;
received_frames++;
if (arg.verbose) {
std::cout << "Received frame " << received_frames
<< " from DataWriter with key "
<< frame_set_view->get_key() << " with checksum: "
<< frame->checksum << std::endl;
}
if (received_frames == 1) {
previous_print_time = current_time;
}
if (((current_time.sec - previous_print_time.sec) >= 1)
|| (received_frames == arg.sample_count)) {
previous_print_time = current_time;
print_average_latency();
}
}
}
retcode = ZeroCopy_reader->return_loan(data_seq, info_seq);
if (retcode != RETCODE_OK) {
std::cout << "return loan error " << retcode << std::endl;
}
if ((received_frames == arg.sample_count) && (!shutdown_application)) {
std::cout << "Received " << received_frames << " frames " << std::endl;
shutdown_application = true;
}
}
// Delete all entities
static int subscriber_shutdown(
DomainParticipant *participant)
{
ReturnCode_t retcode;
int status = 0;
if (participant != NULL) {
retcode = participant->delete_contained_entities();
if (retcode != RETCODE_OK) {
std::cout << "delete_contained_entities error " << retcode
<< std::endl;
status = -1;
}
retcode = TheParticipantFactory->delete_participant(participant);
if (retcode != RETCODE_OK) {
std::cout << "delete_participant error " << retcode << std::endl;
status = -1;
}
}
// RTI Connext provides the finalize_instance() method on
// domain participant factory for people who want to release memory used
// by the participant factory. Uncomment the following block of code for
// clean destruction of the singleton.
// retcode = DomainParticipantFactory::finalize_instance();
// if (retcode != RETCODE_OK) {
// std::cout << "finalize_instance error " << retcode << std::endl;
// status = -1;
// }
return status;
}
extern "C" int subscriber_main()
{
// To customize the participant QoS, use
// the configuration file USER_QOS_PROFILES.xml
DomainParticipant *participant = TheParticipantFactory->create_participant(
arg.domain_id, PARTICIPANT_QOS_DEFAULT,
NULL /* listener */, STATUS_MASK_NONE);
if (participant == NULL) {
std::cout << "create_participant error" << std::endl;
subscriber_shutdown(participant);
return -1;
}
// To customize the subscriber QoS, use
// the configuration file USER_QOS_PROFILES.xml
Subscriber *subscriber = participant->create_subscriber(
SUBSCRIBER_QOS_DEFAULT, NULL /* listener */, STATUS_MASK_NONE);
if (subscriber == NULL) {
std::cout << "create_subscriber error" << std::endl;
subscriber_shutdown(participant);
return -1;
}
// Register the type before creating the topic
const char *type_name = ZeroCopyTypeSupport::get_type_name();
ReturnCode_t retcode = ZeroCopyTypeSupport::register_type(
participant, type_name);
if (retcode != RETCODE_OK) {
std::cout << "register_type error " << retcode << std::endl;
subscriber_shutdown(participant);
return -1;
}
// To customize the topic QoS, use
// the configuration file USER_QOS_PROFILES.xml
Topic *topic = participant->create_topic(
"Example ZeroCopy",
type_name, TOPIC_QOS_DEFAULT, NULL /* listener */,
STATUS_MASK_NONE);
if (topic == NULL) {
std::cout << "create_topic error" << std::endl;
subscriber_shutdown(participant);
return -1;
}
// Create a data reader listener
ZeroCopyListener *reader_listener = new ZeroCopyListener();
// To customize the data reader QoS, use
// the configuration file USER_QOS_PROFILES.xml
DataReader *reader = subscriber->create_datareader(
topic, DATAREADER_QOS_DEFAULT, reader_listener,
STATUS_MASK_ALL);
if (reader == NULL) {
std::cout << "create_datareader error" << std::endl;
subscriber_shutdown(participant);
delete reader_listener;
return -1;
}
// Main loop
std::cout << "ZeroCopy subscriber waiting to receive samples..."
<< std::endl;
Duration_t receive_period = {4,0};
while (!reader_listener->start_shutdown()) {
NDDSUtility::sleep(receive_period);
};
std::cout << "Subscriber application shutting down" << std::endl;
// Delete all entities
int status = subscriber_shutdown(participant);
delete reader_listener;
return status;
}
void ZeroCopy_print_usage()
{
std::cout << "Usage: ZeroCopy_subscriber [options]" << std::endl;
std::cout << "Where arguments are:" << std::endl;
std::cout << " -h Shows this page" << std::endl;
std::cout << " -d <domain_id> Sets the domain id [default = 0]" << std::endl;
std::cout << " -sc <sample count> Sets the number of frames to receive "
"[default = 1200]" << std::endl;
std::cout << " -s <buffer size> Sets the payload size of the frame in bytes "
"[default = 1048576 (1MB)]" << std::endl;
std::cout << " -v Displays checksum and computed latency of "
"each received frame " << std::endl;
}
int main(int argc, char *argv[])
{
// Parse the optional arguments
for (int i = 1; i < argc; ++i) {
if (!strncmp(argv[i], "-h", 2)) {
ZeroCopy_print_usage();
return 0;
} else if (!strncmp(argv[i], "-d", 2)) {
char *ptr;
arg.domain_id = strtol(argv[++i], &ptr, 10);
} else if (!strncmp(argv[i], "-sc", 3)) {
char *ptr;
arg.sample_count = strtol(argv[++i], &ptr, 10);
} else if (!strncmp(argv[i], "-s", 2)) {
char *ptr;
arg.size = strtol(argv[++i], &ptr, 10);
} else if (!strncmp(argv[i], "-v", 2)) {
arg.verbose = true;
} else {
std::cout << "Invalid command-line parameter: " << argv[i] << std::endl;
return -1;
}
}
std::cout << "Running using:" << std::endl;
std::cout << " Domain ID: " << arg.domain_id << std::endl;
std::cout << " Sample Count: " << arg.sample_count << std::endl;
std::cout << " Frame size: " << arg.size << " bytes" << std::endl;
// Uncomment this to turn on additional logging
// NDDSConfigLogger::get_instance()->
// set_verbosity_by_category(NDDS_CONFIG_LOG_CATEGORY_API,
// NDDS_CONFIG_LOG_VERBOSITY_STATUS_ALL);
return subscriber_main();
}
| cxx |
rticonnextdds-examples | data/projects/rticonnextdds-examples/connext_dds/zero_copy/c++/Frame.h | /*******************************************************************************
(c) 2005-2017 Copyright, Real-Time Innovations, Inc. All rights reserved.
RTI grants Licensee a license to use, modify, compile, and create derivative
works of the Software. Licensee has the right to distribute object form only
for use with RTI products. The Software is provided "as is", with no warranty
of any type, including any warranty for fitness for any purpose. RTI is under
no obligation to maintain or support the Software. RTI shall not be liable for
any incidental or consequential damages arising out of the use or inability to
use the software.
******************************************************************************/
struct Dimension {
int x;
int y;
};
class Frame {
public:
char* get_buffer();
const char* get_buffer() const;
int length;
unsigned int checksum;
Dimension dimension;
};
char* Frame::get_buffer()
{
return ((char *)this) + sizeof(Frame);
}
const char* Frame::get_buffer() const
{
return ((char *)this) + sizeof(Frame);
}
| h |
rticonnextdds-examples | data/projects/rticonnextdds-examples/connext_dds/zero_copy/c++/zero_copy_publisher.cxx | /*******************************************************************************
(c) 2005-2017 Copyright, Real-Time Innovations, Inc. All rights reserved.
RTI grants Licensee a license to use, modify, compile, and create derivative
works of the Software. Licensee has the right to distribute object form only
for use with RTI products. The Software is provided "as is", with no warranty
of any type, including any warranty for fitness for any purpose. RTI is under
no obligation to maintain or support the Software. RTI shall not be liable for
any incidental or consequential damages arising out of the use or inability to
use the software.
******************************************************************************/
#include <stdio.h>
#include <stdlib.h>
#include <iostream>
#include <sstream>
#include "zero_copy.h"
#include "zero_copySupport.h"
#include "FrameSupport.h"
#include "ndds/ndds_cpp.h"
#include "ndds/ndds_namespace_cpp.h"
#include "ndds/osapi/osapi_utility.h"
#include "ndds/clock/clock_highResolution.h"
#include "ndds/osapi/osapi_ntptime.h"
using namespace DDS;
struct CommandLineArguments {
int domain_id;
int frame_count;
int frame_rate;
int sample_count;
int key;
int size;
int dr_count;
bool verbose;
CommandLineArguments() {
domain_id = 0;
frame_count = 0;
frame_rate = 60;
sample_count = 1200;
key = -1;
size = 1048576;
dr_count = 1;
verbose = false;
}
};
static void set_current_timestamp(RTIClock *clock, DDS_Time_t ×tamp)
{
if (clock == NULL) {
std::cout << "Clock not available" << std::endl;
return;
}
RTINtpTime current_time = RTI_NTP_TIME_ZERO;
clock->getTime(clock, ¤t_time);
RTINtpTime_unpackToNanosec(
timestamp.sec,
timestamp.nanosec,
current_time);
}
static void add_shmem_key_property(DDS::PropertyQosPolicy& property, int key)
{
std::ostringstream key_to_str;
key_to_str << key;
DDS::PropertyQosPolicyHelper::assert_property(
property,
"shmem_key",
key_to_str.str().c_str(),
true);
}
static void fill_frame_data(Frame* frame)
{
char *buffer = frame->get_buffer();
int random_number = RTIOsapiUtility_rand();
memcpy(buffer, &random_number, sizeof(random_number));
// We dont compute CRC for the whole frame because it would add
// a latency component not due to the middleware. Real
// application may compute CRC differently
frame->checksum = RTIOsapiUtility_crc32(buffer, sizeof(random_number), 0);
}
// Delete all entities
static int publisher_shutdown(
DomainParticipant *participant)
{
ReturnCode_t retcode;
int status = 0;
if (participant != NULL) {
retcode = participant->delete_contained_entities();
if (retcode != RETCODE_OK) {
std::cout << "delete_contained_entities error " << retcode
<< std::endl;
status = -1;
}
retcode = TheParticipantFactory->delete_participant(participant);
if (retcode != RETCODE_OK) {
std::cout << "delete_participant error " << retcode << std::endl;
status = -1;
}
}
// RTI Connext provides finalize_instance() method on
// domain participant factory for people who want to release memory used
// by the participant factory. Uncomment the following block of code for
// clean destruction of the singleton.
//retcode = DomainParticipantFactory::finalize_instance();
//if (retcode != RETCODE_OK) {
// std::cout << "finalize_instance error " << retcode << std::endl;
// status = -1;
//}
return status;
}
extern "C" int publisher_main(CommandLineArguments arg)
{
// Creates a frame set in shared memory with the user provided settings
FrameSet frame_set(
arg.key, //shared memory key
arg.frame_count, //number of frames contained in the shared memory segment
arg.size //size of a frame
);
// To customize participant QoS, use
// the configuration file USER_QOS_PROFILES.xml
DomainParticipant *participant = TheParticipantFactory->create_participant(
arg.domain_id, PARTICIPANT_QOS_DEFAULT,
NULL /* listener */, STATUS_MASK_NONE);
if (participant == NULL) {
std::cout << "create_participant error" << std::endl;
publisher_shutdown(participant);
return -1;
}
// To customize publisher QoS, use
// the configuration file USER_QOS_PROFILES.xml
Publisher *publisher = participant->create_publisher(
PUBLISHER_QOS_DEFAULT, NULL /* listener */, STATUS_MASK_NONE);
if (publisher == NULL) {
std::cout << "create_publisher error" << std::endl;
publisher_shutdown(participant);
return -1;
}
// Register type before creating topic
const char *type_name = ZeroCopyTypeSupport::get_type_name();
ReturnCode_t retcode = ZeroCopyTypeSupport::register_type(
participant, type_name);
if (retcode != RETCODE_OK) {
std::cout << "register_type error " << retcode << std::endl;
publisher_shutdown(participant);
return -1;
}
// To customize topic QoS, use
// the configuration file USER_QOS_PROFILES.xml
Topic *topic = participant->create_topic(
"Example ZeroCopy",
type_name, TOPIC_QOS_DEFAULT, NULL /* listener */,
STATUS_MASK_NONE);
if (topic == NULL) {
std::cout << "create_topic error" << std::endl;
publisher_shutdown(participant);
return -1;
}
// To customize data writer QoS, use
// the configuration file USER_QOS_PROFILES.xml
DDS::DataWriterQos writer_qos;
publisher->get_default_datawriter_qos(writer_qos);
// The key identifying the shared memory segment containing the frames
// is sent to the Subscriber app so that it can attcah to it
add_shmem_key_property(writer_qos.property, arg.key);
DataWriter *writer = publisher->create_datawriter(
topic, writer_qos, NULL /* listener */,
STATUS_MASK_NONE);
if (writer == NULL) {
std::cout << "create_datawriter error" << std::endl;
publisher_shutdown(participant);
return -1;
}
ZeroCopyDataWriter *ZeroCopy_writer = ZeroCopyDataWriter::narrow(writer);
if (ZeroCopy_writer == NULL) {
std::cout << "DataWriter narrow error" << std::endl;
publisher_shutdown(participant);
return -1;
}
// Create data sample for writing
ZeroCopy *instance = ZeroCopyTypeSupport::create_data();
if (instance == NULL) {
std::cout << "ZeroCopyTypeSupport::create_data error" << std::endl;
publisher_shutdown(participant);
return -1;
}
// Waiting to discover the expected number of DataReaders
std::cout << "Waiting until " << arg.dr_count
<< " DataReaders are discovered" << std::endl;
DDS_PublicationMatchedStatus matchedStatus;
do {
writer->get_publication_matched_status(matchedStatus);
} while (matchedStatus.total_count < arg.dr_count);
// Configuring the send period with frame rate
Duration_t send_period = {0, 0};
send_period.sec = 0;
send_period.nanosec = 1000000000 / arg.frame_rate;
// Create a clock to get the write timestamp
RTIClock *clock = RTIHighResolutionClock_new();
if (clock == NULL) {
std::cout << "Failed to create the System clock" << std::endl;
ZeroCopyTypeSupport::delete_data(instance);
publisher_shutdown(participant);
return -1;
}
// Main loop
std::cout << "Going to send " << arg.sample_count << " frames at "
<< arg.frame_rate << " fps" << std::endl;
DDS_WriteParams_t write_params = DDS_WRITEPARAMS_DEFAULT;
int index = 0;
for (int count = 0; count < arg.sample_count; ++count) {
index = count % arg.frame_count;
// Setting the source_timestamp before the shared memory segment is
// updated
set_current_timestamp(clock, write_params.source_timestamp);
// Getting the frame at the desired index
Frame *frame = frame_set[index];
// Updating the frame with the desired data and setting the checksum
frame->length = arg.size;
frame->dimension.x = 800;
frame->dimension.y = 1600;
fill_frame_data(frame);
if (arg.verbose) {
std::cout << "Sending frame " << count + 1 << " with checksum: "
<< frame->checksum << std::endl;
}
// Sending the index and checksum
instance->index = index;
instance->checksum = frame->checksum;
retcode = ZeroCopy_writer->write_w_params(*instance, write_params);
if (retcode != RETCODE_OK) {
std::cout << "write error " << retcode << std::endl;
}
if ((count % arg.frame_rate) == (arg.frame_rate-1)) {
std::cout << "Writen " << count+1 <<" frames" << std::endl;
}
NDDSUtility::sleep(send_period);
}
std::cout << "Written " << arg.sample_count << " frames" << std::endl;
std::cout << "Publisher application shutting down" << std::endl;
RTIHighResolutionClock_delete(clock);
// Delete data sample
retcode = ZeroCopyTypeSupport::delete_data(instance);
if (retcode != RETCODE_OK) {
std::cout << "ZeroCopyTypeSupport::delete_data error " << retcode
<< std::endl;
}
// Delete all entities
return publisher_shutdown(participant);
}
void ZeroCopy_print_usage()
{
std::cout << "Usage: ZeroCopy_publisher [options]" << std::endl;
std::cout << "Where arguments are:" << std::endl;
std::cout << " -h Shows this page" << std::endl;
std::cout << " -d <domain_id> Sets the domain id [default = 0]" << std::endl;
std::cout << " -fc <frame count> Sets the total number of frames to be mapped "
"in the shared memory queue [default = frame rate]" << std::endl;
std::cout << " -fr <frame rate> Sets the rate at which frames are written "
"[default = 60fps]" << std::endl;
std::cout << " -sc <sample count> Sets the number of frames to send "
"[default = 1200]" << std::endl;
std::cout << " -k <key> Sets the key for shared memory segment "
"[default = 10] " << std::endl;
std::cout << " -s <buffer size> Sets payload size of the frame in bytes "
"[default = 1048576 (1MB)]" << std::endl;
std::cout << " -rc <dr count> Expected number of DataReaders that will receive frames "
"[default = 1]" << std::endl;
std::cout << " -v Displays the checksum for each frame " << std::endl;
}
int main(int argc, char *argv[])
{
CommandLineArguments arg;
// Parse the optional arguments
for (int i = 1; i < argc; ++i) {
if (!strncmp(argv[i], "-h", 2)) {
ZeroCopy_print_usage();
return 0;
} else if (!strncmp(argv[i], "-d", 2)) {
char *ptr;
arg.domain_id = strtol(argv[++i], &ptr, 10);
} else if (!strncmp(argv[i], "-fc", 3)) {
char *ptr;
arg.frame_count = strtol(argv[++i], &ptr, 10);
} else if (!strncmp(argv[i], "-fr", 3)) {
char *ptr;
arg.frame_rate = strtol(argv[++i], &ptr, 10);
} else if (!strncmp(argv[i], "-sc", 3)) {
char *ptr;
arg.sample_count = strtol(argv[++i], &ptr, 10);
} else if (!strncmp(argv[i], "-k", 2)) {
char *ptr;
arg.key = strtol(argv[++i], &ptr, 10);
} else if (!strncmp(argv[i], "-s", 2)) {
char *ptr;
arg.size = strtol(argv[++i], &ptr, 10);
if (arg.size < 4) {
std::cout << "-s must be greater or equal to 4" << std::endl;
return -1;
}
} else if (!strncmp(argv[i], "-rc", 3)) {
char *ptr;
arg.dr_count = strtol(argv[++i], &ptr, 10);
} else if (!strncmp(argv[i], "-v", 2)) {
arg.verbose = true;
} else {
std::cout << "Invalid command-line parameter: " << argv[i]
<< std::endl;
return -1;
}
}
if (arg.frame_count == 0) {
arg.frame_count = arg.frame_rate;
}
if (arg.key == -1) {
CommandLineArguments * argPtr = &arg;
memcpy(&arg.key,&argPtr, sizeof(int));
}
std::cout << "Running using:" << std::endl;
std::cout << " Domain ID: " << arg.domain_id << std::endl;
std::cout << " Frame Count in SHMEM segment: " << arg.frame_count << std::endl;
std::cout << " Frame Rate: " << arg.frame_rate << " fps" << std::endl;
std::cout << " Sample Count: " << arg.sample_count << std::endl;
std::cout << " SHMEM Key: " << arg.key << std::endl;
std::cout << " Frame size: " << arg.size << " bytes" << std::endl;
std::cout << " Expected DataReader Count: " << arg.dr_count << std::endl;
// Uncomment this to turn on additional logging
// NDDSConfigLogger::get_instance()->
// set_verbosity_by_category(NDDS_CONFIG_LOG_CATEGORY_API,
// NDDS_CONFIG_LOG_VERBOSITY_STATUS_ALL);
return publisher_main(arg);
}
| cxx |
rticonnextdds-examples | data/projects/rticonnextdds-examples/connext_dds/zero_copy/c++/FrameSupport.h | /*******************************************************************************
(c) 2005-2017 Copyright, Real-Time Innovations, Inc. All rights reserved.
RTI grants Licensee a license to use, modify, compile, and create derivative
works of the Software. Licensee has the right to distribute object form only
for use with RTI products. The Software is provided "as is", with no warranty
of any type, including any warranty for fitness for any purpose. RTI is under
no obligation to maintain or support the Software. RTI shall not be liable for
any incidental or consequential damages arising out of the use or inability to
use the software.
******************************************************************************/
#include <iostream>
#include <stdexcept>
#include "ndds/osapi/osapi_sharedMemorySegment.h"
#include "ndds/osapi/osapi_process.h"
#include "ndds/osapi/osapi_alignment.h"
#include "ndds/osapi/osapi_utility.h"
#include "string.h"
#include "Frame.h"
//
// Implementation details to access frames in shared memory
//
class FrameSupport {
public:
explicit FrameSupport(int payload_size);
// Gets the adress of the Frame Header located at given offset
Frame* get_frame(int index);
const Frame* get_const_frame(int index) const;
// Sets the base address of the frame
void set_frame_base_address(RTIOsapiSharedMemorySegmentHandle *handle);
// Gets the frame size
int get_frame_size();
private:
// Points to the begining of a Frame header
char *frame_base_address;
// Size of the payload
int buffer_size;
// Size of Frame including Frame header, payload and alignment
int frame_size;
};
//
// Provides write access to a set of frames in shared memory
//
class FrameSet {
public:
//
// Creates a shared memory segment to contain frames of fixed-sized payload
// identified by a key
//
FrameSet(int key, int frame_count, int payload_size);
~FrameSet();
// Obtains a frame in the specified position
Frame* operator[](int index)
{
if ((index >= 0) && (index < frame_count)) {
return frame_support.get_frame(index);
} else {
return NULL;
}
}
private:
FrameSupport frame_support;
// Shared memory handle
RTIOsapiSharedMemorySegmentHandle handle;
// Number of frames being mapped into shared memory
int frame_count;
};
//
// Provides read-only access to a set of frames in shared memory
//
class FrameSetView {
public:
// Attaches to a shared memory segment that contains frames of a fixed-size
// payload, identified by a key.
//
// The key and the payload_size must match those used to create a
// FrameSet.
FrameSetView(int key, int payload_size);
~FrameSetView();
// Obtains a read-only frame in the specified position
const Frame* operator[](int index) const
{
if ((index >= 0) && (index < frame_count)) {
return frame_support.get_const_frame(index);
} else {
return NULL;
}
}
// Returns the key used to attach to the shared memory segment
int get_key()
{
return key;
}
private:
FrameSupport frame_support;
// Shared memory handle
RTIOsapiSharedMemorySegmentHandle handle;
// Number of frames being mapped into shared memory
int frame_count;
// Key used for attaching to shared memory segments
int key;
};
// --- FrameSupport: ----------------------------------------------------------
FrameSupport::FrameSupport(int payload_size)
: frame_base_address(NULL),
buffer_size(payload_size)
{
struct FrameOffset { char c; class Frame member; };
int alignment = offsetof (FrameOffset, member);
frame_size = sizeof(Frame) + buffer_size + alignment;
}
Frame* FrameSupport::get_frame(int index)
{
Frame *frame =
(Frame *)((char *)frame_base_address + (index * frame_size));
frame->length = buffer_size;
return frame;
}
const Frame* FrameSupport::get_const_frame(int index) const
{
return (const Frame *)((char *)frame_base_address + (index * frame_size));
}
void FrameSupport::set_frame_base_address(
RTIOsapiSharedMemorySegmentHandle *handle) {
frame_base_address = (char *)RTIOsapiSharedMemorySegment_getAddress(handle);
}
int FrameSupport::get_frame_size() {
return frame_size;
}
// --- FrameSet: --------------------------------------------------------------
FrameSet::FrameSet(int key, int frame_count, int payload_size)
: frame_support(payload_size), frame_count(frame_count)
{
int frame_size = frame_support.get_frame_size();
int total_size = frame_size * frame_count;
RTI_UINT64 pid = RTIOsapiProcess_getId();
int status = 0;
RTIBool result = RTIOsapiSharedMemorySegment_createOrAttach(
&handle,
&status,
key,
total_size,
pid);
if (!result) {
std::ostringstream status_to_str;
status_to_str << "create shared memory segments error " << status;
throw std::runtime_error(status_to_str.str().c_str());
}
if (status == RTI_OSAPI_SHARED_MEMORY_ATTACHED) {
// The shared memory segement already exists. Because the settings
// maybe different we have to destroy it a recreate it
RTIOsapiSharedMemorySegment_delete(&handle);
result = RTIOsapiSharedMemorySegment_create(
&handle,
&status,
key,
total_size,
pid);
if (!result) {
std::ostringstream status_to_str;
status_to_str << "create shared memory segments error " << status;
throw std::runtime_error(status_to_str.str().c_str());
}
}
frame_support.set_frame_base_address(&handle);
}
FrameSet::~FrameSet()
{
if (!RTIOsapiSharedMemorySegment_delete(&handle)) {
std::cout << "delete shared memory segments error" << std::endl;
}
}
// --- FrameSetView: ----------------------------------------------------------
FrameSetView::FrameSetView(int key, int payload_size)
: frame_support(payload_size), key(key)
{
int status = 0;
RTIBool result = RTIOsapiSharedMemorySegment_attach(
&handle,
&status,
key);
if (!result) {
std::ostringstream status_to_str;
status_to_str << "attach to shared memory segments error " << status;
throw std::runtime_error(status_to_str.str().c_str());
}
frame_support.set_frame_base_address(&handle);
int total_size = RTIOsapiSharedMemorySegment_getSize(&handle);
int frame_size = frame_support.get_frame_size();
frame_count = total_size/frame_size;
}
FrameSetView::~FrameSetView()
{
if (!RTIOsapiSharedMemorySegment_detach(&handle)) {
std::cout << "detach shared memory segments error" << std::endl;
}
}
| h |
rticonnextdds-examples | data/projects/rticonnextdds-examples/connext_dds/waitset_status_cond/c++/waitset_statuscond_publisher.cxx | /*******************************************************************************
(c) 2005-2014 Copyright, Real-Time Innovations, Inc. All rights reserved.
RTI grants Licensee a license to use, modify, compile, and create derivative
works of the Software. Licensee has the right to distribute object form only
for use with RTI products. The Software is provided "as is", with no warranty
of any type, including any warranty for fitness for any purpose. RTI is under
no obligation to maintain or support the Software. RTI shall not be liable for
any incidental or consequential damages arising out of the use or inability to
use the software.
******************************************************************************/
/* waitset_statuscond_publisher.cxx
A publication of data of type waitset_statuscond
This file is derived from code automatically generated by the rtiddsgen
command:
rtiddsgen -language C++ -example <arch> waitset_statuscond.idl
Example publication of type waitset_statuscond automatically generated by
'rtiddsgen'. To test them follow these steps:
(1) Compile this file and the example subscription.
(2) Start the subscription with the command
objs/<arch>/waitset_statuscond_subscriber <domain_id> <sample_count>
(3) Start the publication with the command
objs/<arch>/waitset_statuscond_publisher <domain_id> <sample_count>
(4) [Optional] Specify the list of discovery initial peers and
multicast receive addresses via an environment variable or a file
(in the current working directory) called NDDS_DISCOVERY_PEERS.
You can run any number of publishers and subscribers programs, and can
add and remove them dynamically from the domain.
Example:
To run the example application on domain <domain_id>:
On Unix:
objs/<arch>/waitset_statuscond_publisher <domain_id> o
objs/<arch>/waitset_statuscond_subscriber <domain_id>
On Windows:
objs\<arch>\waitset_statuscond_publisher <domain_id>
objs\<arch>\waitset_statuscond_subscriber <domain_id>
modification history
------------ -------
*/
#include <stdio.h>
#include <stdlib.h>
#ifdef RTI_VX653
#include <vThreadsData.h>
#endif
#include "ndds/ndds_cpp.h"
#include "waitset_statuscond.h"
#include "waitset_statuscondSupport.h"
/* Delete all entities */
static int publisher_shutdown(DDSDomainParticipant *participant)
{
DDS_ReturnCode_t retcode;
int status = 0;
if (participant != NULL) {
retcode = participant->delete_contained_entities();
if (retcode != DDS_RETCODE_OK) {
printf("delete_contained_entities error %d\n", retcode);
status = -1;
}
retcode = DDSTheParticipantFactory->delete_participant(participant);
if (retcode != DDS_RETCODE_OK) {
printf("delete_participant error %d\n", retcode);
status = -1;
}
}
/* RTI Connext provides finalize_instance() method on
domain participant factory for people who want to release memory used
by the participant factory. Uncomment the following block of code for
clean destruction of the singleton. */
/*
retcode = DDSDomainParticipantFactory::finalize_instance();
if (retcode != DDS_RETCODE_OK) {
printf("finalize_instance error %d\n", retcode);
status = -1;
}
*/
return status;
}
extern "C" int publisher_main(int domainId, int sample_count)
{
DDSDomainParticipant *participant = NULL;
DDSPublisher *publisher = NULL;
DDSTopic *topic = NULL;
DDSDataWriter *writer = NULL;
waitset_statuscondDataWriter *waitset_statuscond_writer = NULL;
waitset_statuscond *instance = NULL;
DDS_ReturnCode_t retcode;
DDS_InstanceHandle_t instance_handle = DDS_HANDLE_NIL;
const char *type_name = NULL;
int count = 0;
/* Send a new sample every second */
DDS_Duration_t send_period = { 1, 0 };
/* To customize participant QoS, use
the configuration file USER_QOS_PROFILES.xml */
participant = DDSTheParticipantFactory->create_participant(
domainId,
DDS_PARTICIPANT_QOS_DEFAULT,
NULL /* listener */,
DDS_STATUS_MASK_NONE);
if (participant == NULL) {
printf("create_participant error\n");
publisher_shutdown(participant);
return -1;
}
/* To customize publisher QoS, use
the configuration file USER_QOS_PROFILES.xml */
publisher = participant->create_publisher(
DDS_PUBLISHER_QOS_DEFAULT,
NULL /* listener */,
DDS_STATUS_MASK_NONE);
if (publisher == NULL) {
printf("create_publisher error\n");
publisher_shutdown(participant);
return -1;
}
/* Register type before creating topic */
type_name = waitset_statuscondTypeSupport::get_type_name();
retcode = waitset_statuscondTypeSupport::register_type(
participant,
type_name);
if (retcode != DDS_RETCODE_OK) {
printf("register_type error %d\n", retcode);
publisher_shutdown(participant);
return -1;
}
/* To customize topic QoS, use
the configuration file USER_QOS_PROFILES.xml */
topic = participant->create_topic(
"Example waitset_statuscond",
type_name,
DDS_TOPIC_QOS_DEFAULT,
NULL /* listener */,
DDS_STATUS_MASK_NONE);
if (topic == NULL) {
printf("create_topic error\n");
publisher_shutdown(participant);
return -1;
}
/* To customize data writer QoS, use
the configuration file USER_QOS_PROFILES.xml */
writer = publisher->create_datawriter(
topic,
DDS_DATAWRITER_QOS_DEFAULT,
NULL,
DDS_STATUS_MASK_NONE);
if (writer == NULL) {
printf("create_datawriter error\n");
publisher_shutdown(participant);
return -1;
}
waitset_statuscond_writer = waitset_statuscondDataWriter::narrow(writer);
if (waitset_statuscond_writer == NULL) {
printf("DataWriter narrow error\n");
publisher_shutdown(participant);
return -1;
}
/* Create data sample for writing */
instance = waitset_statuscondTypeSupport::create_data();
if (instance == NULL) {
printf("waitset_statuscondTypeSupport::create_data error\n");
publisher_shutdown(participant);
return -1;
}
/* For a data type that has a key, if the same instance is going to be
written multiple times, initialize the key here
and register the keyed instance prior to writing */
/*
instance_handle =
waitset_statuscond_writer->register_instance(*instance);
*/
/* Main loop */
for (count = 0; (sample_count == 0) || (count < sample_count); ++count) {
printf("Writing waitset_statuscond, count %d\n", count);
/* Modify the data to be sent here */
instance->x = count;
retcode = waitset_statuscond_writer->write(*instance, instance_handle);
if (retcode != DDS_RETCODE_OK) {
printf("write error %d\n", retcode);
}
NDDSUtility::sleep(send_period);
}
/*
retcode = waitset_statuscond_writer->unregister_instance(
*instance, instance_handle);
if (retcode != DDS_RETCODE_OK) {
printf("unregister instance error %d\n", retcode);
}
*/
/* Delete data sample */
retcode = waitset_statuscondTypeSupport::delete_data(instance);
if (retcode != DDS_RETCODE_OK) {
printf("waitset_statuscondTypeSupport::delete_data error %d\n",
retcode);
}
/* Delete all entities */
return publisher_shutdown(participant);
}
#if defined(RTI_WINCE)
int wmain(int argc, wchar_t **argv)
{
int domainId = 0;
int sample_count = 0; /* infinite loop */
if (argc >= 2) {
domainId = _wtoi(argv[1]);
}
if (argc >= 3) {
sample_count = _wtoi(argv[2]);
}
/* Uncomment this to turn on additional logging
NDDSConfigLogger::get_instance()->
set_verbosity_by_category(NDDS_CONFIG_LOG_CATEGORY_API,
NDDS_CONFIG_LOG_VERBOSITY_STATUS_ALL);
*/
return publisher_main(domainId, sample_count);
}
#elif !(defined(RTI_VXWORKS) && !defined(__RTP__)) && !defined(RTI_PSOS)
int main(int argc, char *argv[])
{
int domainId = 0;
int sample_count = 0; /* infinite loop */
if (argc >= 2) {
domainId = atoi(argv[1]);
}
if (argc >= 3) {
sample_count = atoi(argv[2]);
}
/* Uncomment this to turn on additional logging
NDDSConfigLogger::get_instance()->
set_verbosity_by_category(NDDS_CONFIG_LOG_CATEGORY_API,
NDDS_CONFIG_LOG_VERBOSITY_STATUS_ALL);
*/
return publisher_main(domainId, sample_count);
}
#endif
#ifdef RTI_VX653
const unsigned char *__ctype = *(__ctypePtrGet());
extern "C" void usrAppInit()
{
#ifdef USER_APPL_INIT
USER_APPL_INIT; /* for backwards compatibility */
#endif
/* add application specific code here */
taskSpawn(
"pub",
RTI_OSAPI_THREAD_PRIORITY_NORMAL,
0x8,
0x150000,
(FUNCPTR) publisher_main,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0);
}
#endif
| cxx |
rticonnextdds-examples | data/projects/rticonnextdds-examples/connext_dds/waitset_status_cond/c++/waitset_statuscond_subscriber.cxx | /*******************************************************************************
(c) 2005-2014 Copyright, Real-Time Innovations, Inc. All rights reserved.
RTI grants Licensee a license to use, modify, compile, and create derivative
works of the Software. Licensee has the right to distribute object form only
for use with RTI products. The Software is provided "as is", with no warranty
of any type, including any warranty for fitness for any purpose. RTI is under
no obligation to maintain or support the Software. RTI shall not be liable for
any incidental or consequential damages arising out of the use or inability to
use the software.
******************************************************************************/
/* waitset_statuscond_subscriber.cxx
A subscription example
This file is derived from code automatically generated by the rtiddsgen
command:
rtiddsgen -language C++ -example <arch> waitset_statuscond.idl
Example subscription of type waitset_statuscond automatically generated by
'rtiddsgen'. To test them follow these steps:
(1) Compile this file and the example publication.
(2) Start the subscription with the command
objs/<arch>/waitset_statuscond_subscriber <domain_id> <sample_count>
(3) Start the publication with the command
objs/<arch>/waitset_statuscond_publisher <domain_id> <sample_count>
(4) [Optional] Specify the list of discovery initial peers and
multicast receive addresses via an environment variable or a file
(in the current working directory) called NDDS_DISCOVERY_PEERS.
You can run any number of publishers and subscribers programs, and can
add and remove them dynamically from the domain.
Example:
To run the example application on domain <domain_id>:
On Unix:
objs/<arch>/waitset_statuscond_publisher <domain_id>
objs/<arch>/waitset_statuscond_subscriber <domain_id>
On Windows:
objs\<arch>\waitset_statuscond_publisher <domain_id>
objs\<arch>\waitset_statuscond_subscriber <domain_id>
modification history
------------ -------
*/
#include <stdio.h>
#include <stdlib.h>
#ifdef RTI_VX653
#include <vThreadsData.h>
#endif
#include "ndds/ndds_cpp.h"
#include "waitset_statuscond.h"
#include "waitset_statuscondSupport.h"
/* We don't need to use listeners as we are going to use waitset_statuscond and
* Conditions so we have removed the auto generated code for listeners here
*/
/* Delete all entities */
static int subscriber_shutdown(DDSDomainParticipant *participant)
{
DDS_ReturnCode_t retcode;
int status = 0;
if (participant != NULL) {
retcode = participant->delete_contained_entities();
if (retcode != DDS_RETCODE_OK) {
printf("delete_contained_entities error %d\n", retcode);
status = -1;
}
retcode = DDSTheParticipantFactory->delete_participant(participant);
if (retcode != DDS_RETCODE_OK) {
printf("delete_participant error %d\n", retcode);
status = -1;
}
}
/* RTI Connext provides the finalize_instance() method on
domain participant factory for people who want to release memory used
by the participant factory. Uncomment the following block of code for
clean destruction of the singleton. */
/*
retcode = DDSDomainParticipantFactory::finalize_instance();
if (retcode != DDS_RETCODE_OK) {
printf("finalize_instance error %d\n", retcode);
status = -1;
}
*/
return status;
}
extern "C" int subscriber_main(int domainId, int sample_count)
{
DDSDomainParticipant *participant = NULL;
DDSSubscriber *subscriber = NULL;
DDSTopic *topic = NULL;
DDSDataReader *reader = NULL;
DDS_ReturnCode_t retcode;
const char *type_name = NULL;
int count = 0;
int status = 0;
struct DDS_Duration_t wait_timeout = { 1, 500000000 };
/* To customize the participant QoS, use
the configuration file USER_QOS_PROFILES.xml */
participant = DDSTheParticipantFactory->create_participant(
domainId,
DDS_PARTICIPANT_QOS_DEFAULT,
NULL /* listener */,
DDS_STATUS_MASK_NONE);
if (participant == NULL) {
printf("create_participant error\n");
subscriber_shutdown(participant);
return -1;
}
/* To customize the subscriber QoS, use
the configuration file USER_QOS_PROFILES.xml */
subscriber = participant->create_subscriber(
DDS_SUBSCRIBER_QOS_DEFAULT,
NULL /* listener */,
DDS_STATUS_MASK_NONE);
if (subscriber == NULL) {
printf("create_subscriber error\n");
subscriber_shutdown(participant);
return -1;
}
/* Register the type before creating the topic */
type_name = waitset_statuscondTypeSupport::get_type_name();
retcode = waitset_statuscondTypeSupport::register_type(
participant,
type_name);
if (retcode != DDS_RETCODE_OK) {
printf("register_type error %d\n", retcode);
subscriber_shutdown(participant);
return -1;
}
/* To customize the topic QoS, use
the configuration file USER_QOS_PROFILES.xml */
topic = participant->create_topic(
"Example waitset_statuscond",
type_name,
DDS_TOPIC_QOS_DEFAULT,
NULL /* listener */,
DDS_STATUS_MASK_NONE);
if (topic == NULL) {
printf("create_topic error\n");
subscriber_shutdown(participant);
return -1;
}
/* To customize the data reader QoS, use
the configuration file USER_QOS_PROFILES.xml */
reader = subscriber->create_datareader(
topic,
DDS_DATAREADER_QOS_DEFAULT,
NULL,
DDS_STATUS_MASK_NONE);
if (reader == NULL) {
printf("create_datareader error\n");
subscriber_shutdown(participant);
return -1;
}
/* Get status conditions
* ---------------------
* Each entity may have an attached Status Condition. To modify the
* statuses we need to get the reader's Status Conditions first.
*/
DDSStatusCondition *status_condition = reader->get_statuscondition();
if (status_condition == NULL) {
printf("get_statuscondition error\n");
subscriber_shutdown(participant);
return -1;
}
/* Set enabled statuses
* --------------------
* Now that we have the Status Condition, we are going to enable the
* status we are interested in: knowing that data is available
*/
retcode = status_condition->set_enabled_statuses(DDS_DATA_AVAILABLE_STATUS);
if (retcode != DDS_RETCODE_OK) {
printf("set_enabled_statuses error\n");
subscriber_shutdown(participant);
return -1;
}
/* Create and attach conditions to the WaitSet
* -------------------------------------------
* Finally, we create the WaitSet and attach both the Read Conditions
* and the Status Condition to it.
*/
DDSWaitSet *waitset = new DDSWaitSet();
/* Attach Status Conditions */
retcode = waitset->attach_condition(status_condition);
if (retcode != DDS_RETCODE_OK) {
printf("attach_condition error\n");
subscriber_shutdown(participant);
return -1;
}
/* Narrow the reader into your specific data type */
waitset_statuscondDataReader *waitset_statuscond_reader =
waitset_statuscondDataReader::narrow(reader);
if (waitset_statuscond_reader == NULL) {
printf("DataReader narrow error\n");
return -1;
}
/* Main loop */
for (count = 0; (sample_count == 0) || (count < sample_count); ++count) {
DDSConditionSeq active_conditions_seq;
/* wait() blocks execution of the thread until one or more attached
* Conditions become true, or until a user-specified timeout expires.
*/
retcode = waitset->wait(active_conditions_seq, wait_timeout);
/* We get to timeout if no conditions were triggered */
if (retcode == DDS_RETCODE_TIMEOUT) {
printf("Wait timed out!! No conditions were triggered.\n");
continue;
} else if (retcode != DDS_RETCODE_OK) {
printf("wait returned error: %d\n", retcode);
break;
}
/* Get the number of active conditions */
int active_conditions = active_conditions_seq.length();
printf("Got %d active conditions\n", active_conditions);
/* In this case, we have only a single condition, but
if we had multiple, we would need to iterate over
them and check which one is true. Leaving the logic
for the more complex case. */
for (int i = 0; i < active_conditions; ++i) {
/* Compare with Status Conditions */
if (active_conditions_seq[i] == status_condition) {
/* Get the status changes so we can check which status
* condition triggered. */
DDS_StatusMask triggeredmask =
waitset_statuscond_reader->get_status_changes();
/* Subscription matched */
if (triggeredmask & DDS_DATA_AVAILABLE_STATUS) {
/* Current conditions match our conditions to read data, so
* we can read data just like we would do in any other
* example. */
waitset_statuscondSeq data_seq;
DDS_SampleInfoSeq info_seq;
/* Access data using read(), take(), etc. If you fail to do
* this the condition will remain true, and the WaitSet will
* wake up immediately - causing high CPU usage when it does
* not sleep in the loop */
retcode = DDS_RETCODE_OK;
while (retcode != DDS_RETCODE_NO_DATA) {
retcode = waitset_statuscond_reader->take(
data_seq,
info_seq,
DDS_LENGTH_UNLIMITED,
DDS_ANY_SAMPLE_STATE,
DDS_ANY_VIEW_STATE,
DDS_ANY_INSTANCE_STATE);
for (int j = 0; j < data_seq.length(); ++j) {
if (!info_seq[j].valid_data) {
printf("Got metadata\n");
continue;
}
waitset_statuscondTypeSupport::print_data(
&data_seq[j]);
}
/* Return the loaned data */
waitset_statuscond_reader->return_loan(
data_seq,
info_seq);
}
}
}
}
}
/* Delete all entities */
delete waitset;
status = subscriber_shutdown(participant);
return status;
}
#if defined(RTI_WINCE)
int wmain(int argc, wchar_t **argv)
{
int domainId = 0;
int sample_count = 0; /* infinite loop */
if (argc >= 2) {
domainId = _wtoi(argv[1]);
}
if (argc >= 3) {
sample_count = _wtoi(argv[2]);
}
/* Uncomment this to turn on additional logging
NDDSConfigLogger::get_instance()->
set_verbosity_by_category(NDDS_CONFIG_LOG_CATEGORY_API,
NDDS_CONFIG_LOG_VERBOSITY_STATUS_ALL);
*/
return subscriber_main(domainId, sample_count);
}
#elif !(defined(RTI_VXWORKS) && !defined(__RTP__)) && !defined(RTI_PSOS)
int main(int argc, char *argv[])
{
int domainId = 0;
int sample_count = 0; /* infinite loop */
if (argc >= 2) {
domainId = atoi(argv[1]);
}
if (argc >= 3) {
sample_count = atoi(argv[2]);
}
/* Uncomment this to turn on additional logging
NDDSConfigLogger::get_instance()->
set_verbosity_by_category(NDDS_CONFIG_LOG_CATEGORY_API,
NDDS_CONFIG_LOG_VERBOSITY_STATUS_ALL);
*/
return subscriber_main(domainId, sample_count);
}
#endif
#ifdef RTI_VX653
const unsigned char *__ctype = *(__ctypePtrGet());
extern "C" void usrAppInit()
{
#ifdef USER_APPL_INIT
USER_APPL_INIT; /* for backwards compatibility */
#endif
/* add application specific code here */
taskSpawn(
"sub",
RTI_OSAPI_THREAD_PRIORITY_NORMAL,
0x8,
0x150000,
(FUNCPTR) subscriber_main,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0);
}
#endif
| cxx |
rticonnextdds-examples | data/projects/rticonnextdds-examples/connext_dds/waitset_status_cond/c++98/waitset_statuscond_publisher.cxx | /*******************************************************************************
(c) 2005-2014 Copyright, Real-Time Innovations, Inc. All rights reserved.
RTI grants Licensee a license to use, modify, compile, and create derivative
works of the Software. Licensee has the right to distribute object form only
for use with RTI products. The Software is provided "as is", with no warranty
of any type, including any warranty for fitness for any purpose. RTI is under
no obligation to maintain or support the Software. RTI shall not be liable for
any incidental or consequential damages arising out of the use or inability to
use the software.
******************************************************************************/
#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include "waitset_statuscond.h"
#include "waitset_statuscondSupport.h"
#include "ndds/ndds_cpp.h"
#include "application.h"
using namespace application;
static int shutdown_participant(
DDSDomainParticipant *participant,
const char *shutdown_message,
int status);
int run_publisher_application(unsigned int domain_id, unsigned int sample_count)
{
/* Send a new sample every second */
DDS_Duration_t send_period = { 1, 0 };
// Start communicating in a domain, usually one participant per application
DDSDomainParticipant *participant =
DDSTheParticipantFactory->create_participant(
domain_id,
DDS_PARTICIPANT_QOS_DEFAULT,
NULL /* listener */,
DDS_STATUS_MASK_NONE);
if (participant == NULL) {
return shutdown_participant(
participant,
"create_participant error",
EXIT_FAILURE);
}
// A Publisher allows an application to create one or more DataWriters
DDSPublisher *publisher = participant->create_publisher(
DDS_PUBLISHER_QOS_DEFAULT,
NULL /* listener */,
DDS_STATUS_MASK_NONE);
if (publisher == NULL) {
return shutdown_participant(
participant,
"create_publisher error",
EXIT_FAILURE);
}
// Register the datatype to use when creating the Topic
const char *type_name = waitset_statuscondTypeSupport::get_type_name();
DDS_ReturnCode_t retcode = waitset_statuscondTypeSupport::register_type(
participant,
type_name);
if (retcode != DDS_RETCODE_OK) {
return shutdown_participant(
participant,
"register_type error",
EXIT_FAILURE);
}
// Create a Topic with a name and a datatype
DDSTopic *topic = participant->create_topic(
"Example waitset_statuscond",
type_name,
DDS_TOPIC_QOS_DEFAULT,
NULL /* listener */,
DDS_STATUS_MASK_NONE);
if (topic == NULL) {
return shutdown_participant(
participant,
"create_topic error",
EXIT_FAILURE);
}
// This DataWriter writes data on "Example waitset_statuscond" Topic
DDSDataWriter *untyped_writer = publisher->create_datawriter(
topic,
DDS_DATAWRITER_QOS_DEFAULT,
NULL,
DDS_STATUS_MASK_NONE);
if (untyped_writer == NULL) {
return shutdown_participant(
participant,
"create_datawriter error",
EXIT_FAILURE);
}
waitset_statuscondDataWriter *typed_writer =
waitset_statuscondDataWriter::narrow(untyped_writer);
if (typed_writer == NULL) {
return shutdown_participant(
participant,
"DataWriter narrow error",
EXIT_FAILURE);
}
// Create data sample for writing
waitset_statuscond *data = waitset_statuscondTypeSupport::create_data();
if (data == NULL) {
return shutdown_participant(
participant,
"waitset_statuscondTypeSupport::create_data error",
EXIT_FAILURE);
}
DDS_InstanceHandle_t instance_handle = DDS_HANDLE_NIL;
/* For a data type that has a key, if the same instance is going to be
written multiple times, initialize the key here
and register the keyed instance prior to writing */
/*
instance_handle = typed_writer->register_instance(*data);
*/
// Main loop, write data
for (unsigned int samples_written = 0;
!shutdown_requested && samples_written < sample_count;
++samples_written) {
std::cout << "Writing waitset_statuscond, count " << samples_written
<< std::endl;
// Modify the data to be sent here
data->x = samples_written;
retcode = typed_writer->write(*data, instance_handle);
if (retcode != DDS_RETCODE_OK) {
std::cerr << "write error " << retcode << std::endl;
}
NDDSUtility::sleep(send_period);
}
/*
retcode = typed_writer->unregister_instance(
*data, instance_handle);
if (retcode != DDS_RETCODE_OK) {
std::cerr << "unregister instance error " << retcode << std::endl;
}
*/
// Delete previously allocated data, including all contained elements
retcode = waitset_statuscondTypeSupport::delete_data(data);
if (retcode != DDS_RETCODE_OK) {
std::cerr << "waitset_statuscondTypeSupport::delete_data error "
<< retcode << std::endl;
}
// Delete all entities (DataWriter, Topic, Publisher, DomainParticipant)
return shutdown_participant(participant, "Shutting down", EXIT_SUCCESS);
}
// Delete all entities
static int shutdown_participant(
DDSDomainParticipant *participant,
const char *shutdown_message,
int status)
{
DDS_ReturnCode_t retcode;
std::cout << shutdown_message << std::endl;
if (participant != NULL) {
// Cleanup everything created by this Participant
retcode = participant->delete_contained_entities();
if (retcode != DDS_RETCODE_OK) {
std::cerr << "delete_contained_entities error " << retcode
<< std::endl;
status = EXIT_FAILURE;
}
retcode = DDSTheParticipantFactory->delete_participant(participant);
if (retcode != DDS_RETCODE_OK) {
std::cerr << "delete_participant error " << retcode << std::endl;
status = EXIT_FAILURE;
}
}
return status;
}
int main(int argc, char *argv[])
{
// Parse arguments and handle control-C
ApplicationArguments arguments;
parse_arguments(arguments, argc, argv);
if (arguments.parse_result == PARSE_RETURN_EXIT) {
return EXIT_SUCCESS;
} else if (arguments.parse_result == PARSE_RETURN_FAILURE) {
return EXIT_FAILURE;
}
setup_signal_handlers();
// Sets Connext verbosity to help debugging
NDDSConfigLogger::get_instance()->set_verbosity(arguments.verbosity);
int status = run_publisher_application(
arguments.domain_id,
arguments.sample_count);
// Releases the memory used by the participant factory. Optional at
// application exit
DDS_ReturnCode_t retcode = DDSDomainParticipantFactory::finalize_instance();
if (retcode != DDS_RETCODE_OK) {
std::cerr << "finalize_instance error " << retcode << std::endl;
status = EXIT_FAILURE;
}
return status;
}
| cxx |
rticonnextdds-examples | data/projects/rticonnextdds-examples/connext_dds/waitset_status_cond/c++98/waitset_statuscond_subscriber.cxx | /*******************************************************************************
(c) 2005-2014 Copyright, Real-Time Innovations, Inc. All rights reserved.
RTI grants Licensee a license to use, modify, compile, and create derivative
works of the Software. Licensee has the right to distribute object form only
for use with RTI products. The Software is provided "as is", with no warranty
of any type, including any warranty for fitness for any purpose. RTI is under
no obligation to maintain or support the Software. RTI shall not be liable for
any incidental or consequential damages arising out of the use or inability to
use the software.
******************************************************************************/
#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include "waitset_statuscond.h"
#include "waitset_statuscondSupport.h"
#include "ndds/ndds_cpp.h"
#include "application.h"
using namespace application;
static int shutdown_participant(
DDSDomainParticipant *participant,
const char *shutdown_message,
int status);
/* We don't need to use listeners as we are going to use waitset_statuscond and
* Conditions so we have removed the auto generated code for listeners here
*/
int run_subscriber_application(
unsigned int domain_id,
unsigned int sample_count)
{
struct DDS_Duration_t wait_timeout = { 1, 500000000 };
// Start communicating in a domain, usually one participant per application
DDSDomainParticipant *participant =
DDSTheParticipantFactory->create_participant(
domain_id,
DDS_PARTICIPANT_QOS_DEFAULT,
NULL /* listener */,
DDS_STATUS_MASK_NONE);
if (participant == NULL) {
return shutdown_participant(
participant,
"create_participant error",
EXIT_FAILURE);
}
// A Subscriber allows an application to create one or more DataReaders
DDSSubscriber *subscriber = participant->create_subscriber(
DDS_SUBSCRIBER_QOS_DEFAULT,
NULL /* listener */,
DDS_STATUS_MASK_NONE);
if (subscriber == NULL) {
return shutdown_participant(
participant,
"create_subscriber error",
EXIT_FAILURE);
}
// Register the datatype to use when creating the Topic
const char *type_name = waitset_statuscondTypeSupport::get_type_name();
DDS_ReturnCode_t retcode = waitset_statuscondTypeSupport::register_type(
participant,
type_name);
if (retcode != DDS_RETCODE_OK) {
return shutdown_participant(
participant,
"register_type error",
EXIT_FAILURE);
}
// Create a Topic with a name and a datatype
DDSTopic *topic = participant->create_topic(
"Example waitset_statuscond",
type_name,
DDS_TOPIC_QOS_DEFAULT,
NULL /* listener */,
DDS_STATUS_MASK_NONE);
if (topic == NULL) {
return shutdown_participant(
participant,
"create_topic error",
EXIT_FAILURE);
}
// This DataReader reads data on "Example waitset_statuscond" Topic
DDSDataReader *untyped_reader = subscriber->create_datareader(
topic,
DDS_DATAREADER_QOS_DEFAULT,
NULL,
DDS_STATUS_MASK_NONE);
if (untyped_reader == NULL) {
return shutdown_participant(
participant,
"create_datareader error",
EXIT_FAILURE);
}
/* Get status conditions
* ---------------------
* Each entity may have an attached Status Condition. To modify the
* statuses we need to get the reader's Status Conditions first.
*/
DDSStatusCondition *status_condition =
untyped_reader->get_statuscondition();
if (status_condition == NULL) {
return shutdown_participant(
participant,
"get_statuscondition error",
EXIT_FAILURE);
}
/* Set enabled statuses
* --------------------
* Now that we have the Status Condition, we are going to enable the
* status we are interested in: knowing that data is available
*/
retcode = status_condition->set_enabled_statuses(DDS_DATA_AVAILABLE_STATUS);
if (retcode != DDS_RETCODE_OK) {
return shutdown_participant(
participant,
"set_enabled_statuses error",
EXIT_FAILURE);
}
/* Create and attach conditions to the WaitSet
* -------------------------------------------
* Finally, we create the WaitSet and attach both the Read Conditions
* and the Status Condition to it.
*/
DDSWaitSet *waitset = new DDSWaitSet();
// Attach Status Conditions
retcode = waitset->attach_condition(status_condition);
if (retcode != DDS_RETCODE_OK) {
return shutdown_participant(
participant,
"attach_condition error",
EXIT_FAILURE);
}
// Narrow the reader into your specific data type
waitset_statuscondDataReader *typed_reader =
waitset_statuscondDataReader::narrow(untyped_reader);
if (typed_reader == NULL) {
return shutdown_participant(
participant,
"DataReader narrow error",
EXIT_FAILURE);
}
// Main loop. Wait for data to arrive, and process when it arrives
unsigned int samples_read = 0;
while (!shutdown_requested && samples_read < sample_count) {
DDSConditionSeq active_conditions_seq;
/* wait() blocks execution of the thread until one or more attached
* Conditions become true, or until a user-specified timeout expires.
*/
retcode = waitset->wait(active_conditions_seq, wait_timeout);
// We get to timeout if no conditions were triggered
if (retcode == DDS_RETCODE_TIMEOUT) {
std::cout << "Wait timed out!! No conditions were triggered.\n";
continue;
} else if (retcode != DDS_RETCODE_OK) {
std::cerr << "wait returned error: " << retcode << std::endl;
break;
}
// Get the number of active conditions
int active_conditions = active_conditions_seq.length();
std::cout << "Got " << active_conditions << " active conditions\n";
/* In this case, we have only a single condition, but
if we had multiple, we would need to iterate over
them and check which one is true. Leaving the logic
for the more complex case. */
for (int i = 0; i < active_conditions; ++i) {
// Compare with Status Conditions
if (active_conditions_seq[i] == status_condition) {
/* Get the status changes so we can check which status
* condition triggered. */
DDS_StatusMask triggeredmask =
typed_reader->get_status_changes();
// Subscription matched
if (triggeredmask & DDS_DATA_AVAILABLE_STATUS) {
/* Current conditions match our conditions to read data, so
* we can read data just like we would do in any other
* example. */
waitset_statuscondSeq data_seq;
DDS_SampleInfoSeq info_seq;
/* Access data using read(), take(), etc. If you fail to do
* this the condition will remain true, and the WaitSet will
* wake up immediately - causing high CPU usage when it does
* not sleep in the loop */
retcode = DDS_RETCODE_OK;
while (retcode != DDS_RETCODE_NO_DATA) {
retcode = typed_reader->take(
data_seq,
info_seq,
DDS_LENGTH_UNLIMITED,
DDS_ANY_SAMPLE_STATE,
DDS_ANY_VIEW_STATE,
DDS_ANY_INSTANCE_STATE);
for (int j = 0; j < data_seq.length(); ++j) {
if (!info_seq[j].valid_data) {
std::cout << "Got metadata\n";
continue;
}
waitset_statuscondTypeSupport::print_data(
&data_seq[j]);
samples_read++;
}
/* Return the loaned data */
typed_reader->return_loan(data_seq, info_seq);
}
}
}
}
}
// Delete all entities
delete waitset;
// Cleanup
return shutdown_participant(participant, "Shutting down", 0);
}
// Delete all entities
static int shutdown_participant(
DDSDomainParticipant *participant,
const char *shutdown_message,
int status)
{
DDS_ReturnCode_t retcode;
std::cout << shutdown_message << std::endl;
if (participant != NULL) {
// Cleanup everything created by this Participant
retcode = participant->delete_contained_entities();
if (retcode != DDS_RETCODE_OK) {
std::cerr << "delete_contained_entities error" << retcode
<< std::endl;
status = EXIT_FAILURE;
}
retcode = DDSTheParticipantFactory->delete_participant(participant);
if (retcode != DDS_RETCODE_OK) {
std::cerr << "delete_participant error" << retcode << std::endl;
status = EXIT_FAILURE;
}
}
return status;
}
int main(int argc, char *argv[])
{
// Parse arguments and handle control-C
ApplicationArguments arguments;
parse_arguments(arguments, argc, argv);
if (arguments.parse_result == PARSE_RETURN_EXIT) {
return EXIT_SUCCESS;
} else if (arguments.parse_result == PARSE_RETURN_FAILURE) {
return EXIT_FAILURE;
}
setup_signal_handlers();
// Sets Connext verbosity to help debugging
NDDSConfigLogger::get_instance()->set_verbosity(arguments.verbosity);
int status = run_subscriber_application(
arguments.domain_id,
arguments.sample_count);
// Releases the memory used by the participant factory. Optional at
// application exit
DDS_ReturnCode_t retcode = DDSDomainParticipantFactory::finalize_instance();
if (retcode != DDS_RETCODE_OK) {
std::cerr << "finalize_instance error" << retcode << std::endl;
status = EXIT_FAILURE;
}
return status;
}
| cxx |
rticonnextdds-examples | data/projects/rticonnextdds-examples/connext_dds/waitset_status_cond/c++98/application.h | /*
* (c) Copyright, Real-Time Innovations, 2020. All rights reserved.
* RTI grants Licensee a license to use, modify, compile, and create derivative
* works of the software solely for use with RTI Connext DDS. Licensee may
* redistribute copies of the software provided that all such copies are subject
* to this license. The software is provided "as is", with no warranty of any
* type, including any warranty for fitness for any purpose. RTI is under no
* obligation to maintain or support the software. RTI shall not be liable for
* any incidental or consequential damages arising out of the use or inability
* to use the software.
*/
#ifndef APPLICATION_H
#define APPLICATION_H
#include <iostream>
#include <csignal>
#include <climits>
namespace application {
// Catch control-C and tell application to shut down
bool shutdown_requested = false;
inline void stop_handler(int)
{
shutdown_requested = true;
std::cout << "preparing to shut down..." << std::endl;
}
inline void setup_signal_handlers()
{
signal(SIGINT, stop_handler);
signal(SIGTERM, stop_handler);
}
enum ParseReturn { PARSE_RETURN_OK, PARSE_RETURN_FAILURE, PARSE_RETURN_EXIT };
struct ApplicationArguments {
ParseReturn parse_result;
unsigned int domain_id;
unsigned int sample_count;
NDDS_Config_LogVerbosity verbosity;
};
inline void set_verbosity(ApplicationArguments &arguments, int verbosity)
{
switch (verbosity) {
case 0:
arguments.verbosity = NDDS_CONFIG_LOG_VERBOSITY_SILENT;
break;
case 1:
arguments.verbosity = NDDS_CONFIG_LOG_VERBOSITY_ERROR;
break;
case 2:
arguments.verbosity = NDDS_CONFIG_LOG_VERBOSITY_WARNING;
break;
case 3:
arguments.verbosity = NDDS_CONFIG_LOG_VERBOSITY_STATUS_ALL;
break;
default:
arguments.verbosity = NDDS_CONFIG_LOG_VERBOSITY_ERROR;
break;
}
}
// Parses application arguments for example. Returns whether to exit.
inline void parse_arguments(
ApplicationArguments &arguments,
int argc,
char *argv[])
{
int arg_processing = 1;
bool show_usage = false;
arguments.domain_id = 0;
arguments.sample_count = INT_MAX;
arguments.verbosity = NDDS_CONFIG_LOG_VERBOSITY_ERROR;
arguments.parse_result = PARSE_RETURN_OK;
while (arg_processing < argc) {
if ((argc > arg_processing + 1)
&& (strcmp(argv[arg_processing], "-d") == 0
|| strcmp(argv[arg_processing], "--domain") == 0)) {
arguments.domain_id = atoi(argv[arg_processing + 1]);
arg_processing += 2;
} else if (
(argc > arg_processing + 1)
&& (strcmp(argv[arg_processing], "-s") == 0
|| strcmp(argv[arg_processing], "--sample-count") == 0)) {
arguments.sample_count = atoi(argv[arg_processing + 1]);
arg_processing += 2;
} else if (
(argc > arg_processing + 1)
&& (strcmp(argv[arg_processing], "-v") == 0
|| strcmp(argv[arg_processing], "--verbosity") == 0)) {
set_verbosity(arguments, atoi(argv[arg_processing + 1]));
arg_processing += 2;
} else if (
strcmp(argv[arg_processing], "-h") == 0
|| strcmp(argv[arg_processing], "--help") == 0) {
std::cout << "Example application." << std::endl;
show_usage = true;
arguments.parse_result = PARSE_RETURN_EXIT;
break;
} else {
std::cout << "Bad parameter." << std::endl;
show_usage = true;
arguments.parse_result = PARSE_RETURN_FAILURE;
break;
}
}
if (show_usage) {
std::cout << "Usage:\n"
" -d, --domain <int> Domain ID this "
"application will\n"
" subscribe in. \n"
" Default: 0\n"
" -s, --sample_count <int> Number of samples to "
"receive before\n"
" cleanly shutting down. \n"
" Default: infinite\n"
" -v, --verbosity <int> How much debugging output "
"to show.\n"
" Range: 0-3 \n"
" Default: 1"
<< std::endl;
}
}
} // namespace application
#endif // APPLICATION_H
| h |
rticonnextdds-examples | data/projects/rticonnextdds-examples/connext_dds/waitset_status_cond/c/waitset_statuscond_publisher.c | /*******************************************************************************
(c) 2005-2014 Copyright, Real-Time Innovations, Inc. All rights reserved.
RTI grants Licensee a license to use, modify, compile, and create derivative
works of the Software. Licensee has the right to distribute object form only
for use with RTI products. The Software is provided "as is", with no warranty
of any type, including any warranty for fitness for any purpose. RTI is under
no obligation to maintain or support the Software. RTI shall not be liable for
any incidental or consequential damages arising out of the use or inability to
use the software.
******************************************************************************/
/* waitset_statuscond_publisher.c
A publication of data of type waitset_statuscond
This file is derived from code automatically generated by the rtiddsgen
command:
rtiddsgen -language C -example <arch> waitset_statuscond.idl
Example publication of type waitset_statuscond automatically generated by
'rtiddsgen'. To test them follow these steps:
(1) Compile this file and the example subscription.
(2) Start the subscription with the command
objs/<arch>/waitset_statuscond_subscriber <domain_id> <sample_count>
(3) Start the publication with the command
objs/<arch>/waitset_statuscond_publisher <domain_id> <sample_count>
(4) [Optional] Specify the list of discovery initial peers and
multicast receive addresses via an environment variable or a file
(in the current working directory) called NDDS_DISCOVERY_PEERS.
You can run any number of publishers and subscribers programs, and can
add and remove them dynamically from the domain.
Example:
To run the example application on domain <domain_id>:
On Unix:
objs/<arch>/waitset_statuscond_publisher <domain_id>
objs/<arch>/waitset_statuscond_subscriber <domain_id>
On Windows:
objs\<arch>\waitset_statuscond_publisher <domain_id>
objs\<arch>\waitset_statuscond_subscriber <domain_id>
modification history
------------ -------
*/
#include "ndds/ndds_c.h"
#include "waitset_statuscond.h"
#include "waitset_statuscondSupport.h"
#include <stdio.h>
#include <stdlib.h>
/* Delete all entities */
static int publisher_shutdown(DDS_DomainParticipant *participant)
{
DDS_ReturnCode_t retcode;
int status = 0;
if (participant != NULL) {
retcode = DDS_DomainParticipant_delete_contained_entities(participant);
if (retcode != DDS_RETCODE_OK) {
printf("delete_contained_entities error %d\n", retcode);
status = -1;
}
retcode = DDS_DomainParticipantFactory_delete_participant(
DDS_TheParticipantFactory,
participant);
if (retcode != DDS_RETCODE_OK) {
printf("delete_participant error %d\n", retcode);
status = -1;
}
}
/* RTI Connext provides finalize_instance() method on
domain participant factory for people who want to release memory used
by the participant factory. Uncomment the following block of code for
clean destruction of the singleton. */
/*
retcode = DDS_DomainParticipantFactory_finalize_instance();
if (retcode != DDS_RETCODE_OK) {
printf("finalize_instance error %d\n", retcode);
status = -1;
}
*/
return status;
}
static int publisher_main(int domainId, int sample_count)
{
DDS_DomainParticipant *participant = NULL;
DDS_Publisher *publisher = NULL;
DDS_Topic *topic = NULL;
DDS_DataWriter *writer = NULL;
waitset_statuscondDataWriter *waitset_statuscond_writer = NULL;
waitset_statuscond *instance = NULL;
DDS_ReturnCode_t retcode;
DDS_InstanceHandle_t instance_handle = DDS_HANDLE_NIL;
const char *type_name = NULL;
int count = 0;
struct DDS_Duration_t send_period = { 1, 0 };
/* To customize participant QoS, use
the configuration file USER_QOS_PROFILES.xml */
participant = DDS_DomainParticipantFactory_create_participant(
DDS_TheParticipantFactory,
domainId,
&DDS_PARTICIPANT_QOS_DEFAULT,
NULL /* listener */,
DDS_STATUS_MASK_NONE);
if (participant == NULL) {
printf("create_participant error\n");
publisher_shutdown(participant);
return -1;
}
/* To customize publisher QoS, use
the configuration file USER_QOS_PROFILES.xml */
publisher = DDS_DomainParticipant_create_publisher(
participant,
&DDS_PUBLISHER_QOS_DEFAULT,
NULL /* listener */,
DDS_STATUS_MASK_NONE);
if (publisher == NULL) {
printf("create_publisher error\n");
publisher_shutdown(participant);
return -1;
}
/* Register type before creating topic */
type_name = waitset_statuscondTypeSupport_get_type_name();
retcode =
waitset_statuscondTypeSupport_register_type(participant, type_name);
if (retcode != DDS_RETCODE_OK) {
printf("register_type error %d\n", retcode);
publisher_shutdown(participant);
return -1;
}
/* To customize topic QoS, use
the configuration file USER_QOS_PROFILES.xml */
topic = DDS_DomainParticipant_create_topic(
participant,
"Example waitset_statuscond",
type_name,
&DDS_TOPIC_QOS_DEFAULT,
NULL /* listener */,
DDS_STATUS_MASK_NONE);
if (topic == NULL) {
printf("create_topic error\n");
publisher_shutdown(participant);
return -1;
}
/* To customize data writer QoS, use
the configuration file USER_QOS_PROFILES.xml */
writer = DDS_Publisher_create_datawriter(
publisher,
topic,
&DDS_DATAWRITER_QOS_DEFAULT,
NULL /* listener */,
DDS_STATUS_MASK_NONE);
if (writer == NULL) {
printf("create_datawriter error\n");
publisher_shutdown(participant);
return -1;
}
waitset_statuscond_writer = waitset_statuscondDataWriter_narrow(writer);
if (waitset_statuscond_writer == NULL) {
printf("DataWriter narrow error\n");
publisher_shutdown(participant);
return -1;
}
/* Create data sample for writing */
instance = waitset_statuscondTypeSupport_create_data_ex(DDS_BOOLEAN_TRUE);
if (instance == NULL) {
printf("waitset_statuscondTypeSupport_create_data error\n");
publisher_shutdown(participant);
return -1;
}
/* For a data type that has a key, if the same instance is going to be
written multiple times, initialize the key here
and register the keyed instance prior to writing */
/*
instance_handle = waitset_statuscondDataWriter_register_instance(
waitset_statuscond_writer, instance);
*/
/* Main loop */
for (count = 0; (sample_count == 0) || (count < sample_count); ++count) {
printf("Writing waitset_statuscond, count %d\n", count);
/* Modify the data to be written here */
instance->x = count;
/* Write data */
retcode = waitset_statuscondDataWriter_write(
waitset_statuscond_writer,
instance,
&instance_handle);
if (retcode != DDS_RETCODE_OK) {
printf("write error %d\n", retcode);
}
NDDS_Utility_sleep(&send_period);
}
/*
retcode = waitset_statuscondDataWriter_unregister_instance(
waitset_statuscond_writer, instance, &instance_handle);
if (retcode != DDS_RETCODE_OK) {
printf("unregister instance error %d\n", retcode);
}
*/
/* Delete data sample */
retcode = waitset_statuscondTypeSupport_delete_data_ex(
instance,
DDS_BOOLEAN_TRUE);
if (retcode != DDS_RETCODE_OK) {
printf("waitset_statuscondTypeSupport_delete_data error %d\n", retcode);
}
/* Cleanup and delete delete all entities */
return publisher_shutdown(participant);
}
#if defined(RTI_WINCE)
int wmain(int argc, wchar_t **argv)
{
int domainId = 0;
int sample_count = 0; /* infinite loop */
if (argc >= 2) {
domainId = _wtoi(argv[1]);
}
if (argc >= 3) {
sample_count = _wtoi(argv[2]);
}
/* Uncomment this to turn on additional logging
NDDS_Config_Logger_set_verbosity_by_category(
NDDS_Config_Logger_get_instance(),
NDDS_CONFIG_LOG_CATEGORY_API,
NDDS_CONFIG_LOG_VERBOSITY_STATUS_ALL);
*/
return publisher_main(domainId, sample_count);
}
#elif !(defined(RTI_VXWORKS) && !defined(__RTP__)) && !defined(RTI_PSOS)
int main(int argc, char *argv[])
{
int domainId = 0;
int sample_count = 0; /* infinite loop */
if (argc >= 2) {
domainId = atoi(argv[1]);
}
if (argc >= 3) {
sample_count = atoi(argv[2]);
}
/* Uncomment this to turn on additional logging
NDDS_Config_Logger_set_verbosity_by_category(
NDDS_Config_Logger_get_instance(),
NDDS_CONFIG_LOG_CATEGORY_API,
NDDS_CONFIG_LOG_VERBOSITY_STATUS_ALL);
*/
return publisher_main(domainId, sample_count);
}
#endif
#ifdef RTI_VX653
const unsigned char *__ctype = NULL;
void usrAppInit()
{
#ifdef USER_APPL_INIT
USER_APPL_INIT; /* for backwards compatibility */
#endif
/* add application specific code here */
taskSpawn(
"pub",
RTI_OSAPI_THREAD_PRIORITY_NORMAL,
0x8,
0x150000,
(FUNCPTR) publisher_main,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0);
}
#endif
| c |
rticonnextdds-examples | data/projects/rticonnextdds-examples/connext_dds/waitset_status_cond/c/waitset_statuscond_subscriber.c | /*******************************************************************************
(c) 2005-2014 Copyright, Real-Time Innovations, Inc. All rights reserved.
RTI grants Licensee a license to use, modify, compile, and create derivative
works of the Software. Licensee has the right to distribute object form only
for use with RTI products. The Software is provided "as is", with no warranty
of any type, including any warranty for fitness for any purpose. RTI is under
no obligation to maintain or support the Software. RTI shall not be liable for
any incidental or consequential damages arising out of the use or inability to
use the software.
******************************************************************************/
/* waitset_statuscond_subscriber.c
A subscription example
This file is derived from code automatically generated by the rtiddsgen
command:
rtiddsgen -language C -example <arch> waitset_statuscond.idl
Example subscription of type waitset_statuscond automatically generated by
'rtiddsgen'. To test them, follow these steps:
(1) Compile this file and the example publication.
(2) Start the subscription with the command
objs/<arch>/waitset_statuscond_subscriber <domain_id> <sample_count>
(3) Start the publication with the command
objs/<arch>/waitset_statuscond_publisher <domain_id> <sample_count>
(4) [Optional] Specify the list of discovery initial peers and
multicast receive addresses via an environment variable or a file
(in the current working directory) called NDDS_DISCOVERY_PEERS.
You can run any number of publishers and subscribers programs, and can
add and remove them dynamically from the domain.
Example:
To run the example application on domain <domain_id>:
On UNIX systems:
objs/<arch>/waitset_statuscond_publisher <domain_id>
objs/<arch>/waitset_statuscond_subscriber <domain_id>
On Windows systems:
objs\<arch>\waitset_statuscond_publisher <domain_id>
objs\<arch>\waitset_statuscond_subscriber <domain_id>
modification history
------------ -------
*/
#include "ndds/ndds_c.h"
#include "waitset_statuscond.h"
#include "waitset_statuscondSupport.h"
#include <stdio.h>
#include <stdlib.h>
/* Delete all entities */
static int subscriber_shutdown(DDS_DomainParticipant *participant)
{
DDS_ReturnCode_t retcode;
int status = 0;
if (participant != NULL) {
retcode = DDS_DomainParticipant_delete_contained_entities(participant);
if (retcode != DDS_RETCODE_OK) {
printf("delete_contained_entities error %d\n", retcode);
status = -1;
}
retcode = DDS_DomainParticipantFactory_delete_participant(
DDS_TheParticipantFactory,
participant);
if (retcode != DDS_RETCODE_OK) {
printf("delete_participant error %d\n", retcode);
status = -1;
}
}
/* RTI Connext provides the finalize_instance() method on
domain participant factory for users who want to release memory used
by the participant factory. Uncomment the following block of code for
clean destruction of the singleton. */
/*
retcode = DDS_DomainParticipantFactory_finalize_instance();
if (retcode != DDS_RETCODE_OK) {
printf("finalize_instance error %d\n", retcode);
status = -1;
}
*/
return status;
}
static int subscriber_main(int domainId, int sample_count)
{
DDS_DomainParticipant *participant = NULL;
DDS_Subscriber *subscriber = NULL;
DDS_Topic *topic = NULL;
/* struct DDS_DataReaderListener reader_listener =
DDS_DataReaderListener_INITIALIZER; */
DDS_DataReader *reader = NULL;
DDS_ReturnCode_t retcode;
const char *type_name = NULL;
int count = 0;
DDS_StatusCondition *status_condition;
DDS_WaitSet *waitset = NULL;
waitset_statuscondDataReader *waitsets_reader = NULL;
struct DDS_Duration_t timeout = { 4, 0 };
/* To customize participant QoS, use
the configuration file USER_QOS_PROFILES.xml */
participant = DDS_DomainParticipantFactory_create_participant(
DDS_TheParticipantFactory,
domainId,
&DDS_PARTICIPANT_QOS_DEFAULT,
NULL /* listener */,
DDS_STATUS_MASK_NONE);
if (participant == NULL) {
printf("create_participant error\n");
subscriber_shutdown(participant);
return -1;
}
/* To customize subscriber QoS, use
the configuration file USER_QOS_PROFILES.xml */
subscriber = DDS_DomainParticipant_create_subscriber(
participant,
&DDS_SUBSCRIBER_QOS_DEFAULT,
NULL /* listener */,
DDS_STATUS_MASK_NONE);
if (subscriber == NULL) {
printf("create_subscriber error\n");
subscriber_shutdown(participant);
return -1;
}
/* Register the type before creating the topic */
type_name = waitset_statuscondTypeSupport_get_type_name();
retcode =
waitset_statuscondTypeSupport_register_type(participant, type_name);
if (retcode != DDS_RETCODE_OK) {
printf("register_type error %d\n", retcode);
subscriber_shutdown(participant);
return -1;
}
/* To customize topic QoS, use
the configuration file USER_QOS_PROFILES.xml */
topic = DDS_DomainParticipant_create_topic(
participant,
"Example waitset_statuscond",
type_name,
&DDS_TOPIC_QOS_DEFAULT,
NULL /* listener */,
DDS_STATUS_MASK_NONE);
if (topic == NULL) {
printf("create_topic error\n");
subscriber_shutdown(participant);
return -1;
}
/* To customize data reader QoS, use
the configuration file USER_QOS_PROFILES.xml */
reader = DDS_Subscriber_create_datareader(
subscriber,
DDS_Topic_as_topicdescription(topic),
&DDS_DATAREADER_QOS_DEFAULT,
NULL,
DDS_STATUS_MASK_NONE);
if (reader == NULL) {
printf("create_datareader error\n");
subscriber_shutdown(participant);
return -1;
}
status_condition = DDS_Entity_get_statuscondition((DDS_Entity *) reader);
if (status_condition == NULL) {
printf("get_statuscondition error\n");
subscriber_shutdown(participant);
return -1;
}
// Since a single status condition can match many statuses,
// enable only those we're interested in.
retcode = DDS_StatusCondition_set_enabled_statuses(
status_condition,
DDS_DATA_AVAILABLE_STATUS);
if (retcode != DDS_RETCODE_OK) {
printf("set_enabled_statuses error\n");
subscriber_shutdown(participant);
return -1;
}
// Create WaitSet, and attach conditions
waitset = DDS_WaitSet_new();
if (waitset == NULL) {
printf("create waitset error\n");
subscriber_shutdown(participant);
return -1;
}
retcode = DDS_WaitSet_attach_condition(
waitset,
(DDS_Condition *) status_condition);
if (retcode != DDS_RETCODE_OK) {
printf("attach_condition error\n");
subscriber_shutdown(participant);
return -1;
}
// Get narrowed datareader
waitsets_reader = waitset_statuscondDataReader_narrow(reader);
if (waitsets_reader == NULL) {
printf("DataReader narrow error\n");
return -1;
}
/* Main loop */
for (count = 0; (sample_count == 0) || (count < sample_count); ++count) {
struct DDS_ConditionSeq active_conditions = DDS_SEQUENCE_INITIALIZER;
int i, j;
retcode = DDS_WaitSet_wait(waitset, &active_conditions, &timeout);
if (retcode == DDS_RETCODE_TIMEOUT) {
printf("wait timed out\n");
count += 2;
continue;
} else if (retcode != DDS_RETCODE_OK) {
printf("wait returned error: %d\n", retcode);
break;
}
printf("got %d active conditions\n",
DDS_ConditionSeq_get_length(&active_conditions));
for (i = 0; i < DDS_ConditionSeq_get_length(&active_conditions); ++i) {
/* Compare with Status Conditions */
if (DDS_ConditionSeq_get(&active_conditions, i)
== (DDS_Condition *) status_condition) {
/* A status condition triggered--see which ones */
DDS_StatusMask triggeredmask;
triggeredmask = DDS_Entity_get_status_changes(
(DDS_Entity *) waitsets_reader);
/* Subscription matched */
if (triggeredmask & DDS_DATA_AVAILABLE_STATUS) {
/* Current conditions match our conditions to read data, so
* we can read data just like we would do in any other
* example.
*/
struct waitset_statuscondSeq data_seq =
DDS_SEQUENCE_INITIALIZER;
struct DDS_SampleInfoSeq info_seq =
DDS_SEQUENCE_INITIALIZER;
/* Access data using read(), take(), etc. If you fail to do
* this the condition will remain true, and the WaitSet will
* wake up immediately - causing high CPU usage when it does
* not sleep in the loop */
retcode = DDS_RETCODE_OK;
while (retcode != DDS_RETCODE_NO_DATA) {
retcode = waitset_statuscondDataReader_take(
waitsets_reader,
&data_seq,
&info_seq,
DDS_LENGTH_UNLIMITED,
DDS_ANY_SAMPLE_STATE,
DDS_ANY_VIEW_STATE,
DDS_ANY_INSTANCE_STATE);
for (j = 0;
j < waitset_statuscondSeq_get_length(&data_seq);
++j) {
if (!DDS_SampleInfoSeq_get_reference(&info_seq, j)
->valid_data) {
printf(" Got metadata\n");
continue;
}
waitset_statuscondTypeSupport_print_data(
waitset_statuscondSeq_get_reference(
&data_seq,
j));
}
waitset_statuscondDataReader_return_loan(
waitsets_reader,
&data_seq,
&info_seq);
}
}
}
}
}
/* Delete all entities */
retcode = DDS_WaitSet_delete(waitset);
if (retcode != DDS_RETCODE_OK) {
printf("delete waitset error %d\n", retcode);
}
/* Cleanup and delete all entities */
return subscriber_shutdown(participant);
}
#if defined(RTI_WINCE)
int wmain(int argc, wchar_t **argv)
{
int domainId = 0;
int sample_count = 0; /* infinite loop */
if (argc >= 2) {
domainId = _wtoi(argv[1]);
}
if (argc >= 3) {
sample_count = _wtoi(argv[2]);
}
/* Uncomment this to turn on additional logging
NDDS_Config_Logger_set_verbosity_by_category(
NDDS_Config_Logger_get_instance(),
NDDS_CONFIG_LOG_CATEGORY_API,
NDDS_CONFIG_LOG_VERBOSITY_STATUS_ALL);
*/
return subscriber_main(domainId, sample_count);
}
#elif !(defined(RTI_VXWORKS) && !defined(__RTP__)) && !defined(RTI_PSOS)
int main(int argc, char *argv[])
{
int domainId = 0;
int sample_count = 0; /* infinite loop */
if (argc >= 2) {
domainId = atoi(argv[1]);
}
if (argc >= 3) {
sample_count = atoi(argv[2]);
}
/* Uncomment this to turn on additional logging
NDDS_Config_Logger_set_verbosity_by_category(
NDDS_Config_Logger_get_instance(),
NDDS_CONFIG_LOG_CATEGORY_API,
NDDS_CONFIG_LOG_VERBOSITY_STATUS_ALL);
*/
return subscriber_main(domainId, sample_count);
}
#endif
#ifdef RTI_VX653
const unsigned char *__ctype = NULL;
void usrAppInit()
{
#ifdef USER_APPL_INIT
USER_APPL_INIT; /* for backwards compatibility */
#endif
/* add application specific code here */
taskSpawn(
"sub",
RTI_OSAPI_THREAD_PRIORITY_NORMAL,
0x8,
0x150000,
(FUNCPTR) subscriber_main,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0);
}
#endif
| c |
rticonnextdds-examples | data/projects/rticonnextdds-examples/connext_dds/waitset_status_cond/c++03/waitset_statuscond_publisher.cxx | /*******************************************************************************
(c) 2005-2015 Copyright, Real-Time Innovations, Inc. All rights reserved.
RTI grants Licensee a license to use, modify, compile, and create derivative
works of the Software. Licensee has the right to distribute object form only
for use with RTI products. The Software is provided "as is", with no warranty
of any type, including any warranty for fitness for any purpose. RTI is under
no obligation to maintain or support the Software. RTI shall not be liable for
any incidental or consequential damages arising out of the use or inability to
use the software.
******************************************************************************/
#include <cstdlib>
#include <iostream>
#include "waitset_statuscond.hpp"
#include <dds/dds.hpp>
using namespace dds::core;
using namespace dds::core::policy;
using namespace dds::domain;
using namespace dds::topic;
using namespace dds::pub;
using namespace dds::pub::qos;
void publisher_main(int domain_id, int sample_count)
{
// Create a DomainParticipant.
DomainParticipant participant(domain_id);
// Create a Topic -- and automatically register the type.
Topic<Foo> topic(participant, "Example waitset_statuscond");
// Retrieve the DataWriter QoS, from USER_QOS_PROFILES.xml.
DataWriterQos writer_qos = QosProvider::Default().datawriter_qos();
// If you want to change the DataWriter's QoS programmatically rather
// than using the XML file, you will need to comment out the previous
// publisher_qos assignment and uncomment these files.
// writer_qos << Reliability::Reliable()
// << History::KeepAll();
// Create a DataWriter.
DataWriter<Foo> writer(Publisher(participant), topic, writer_qos);
// Create a sample for writing.
Foo instance;
for (int count = 0; (sample_count == 0) || (count < sample_count);
++count) {
std::cout << "Writing waitset_statuscond, count " << count << std::endl;
instance.x(count);
writer.write(instance);
rti::util::sleep(Duration(1));
}
}
int main(int argc, char *argv[])
{
int domain_id = 0;
int sample_count = 0; // Infinite loop
if (argc >= 2) {
domain_id = atoi(argv[1]);
}
if (argc >= 3) {
sample_count = atoi(argv[2]);
}
// To turn on additional logging, include <rti/config/Logger.hpp> and
// uncomment the following line:
// rti::config::Logger::instance().verbosity(rti::config::Verbosity::STATUS_ALL);
try {
publisher_main(domain_id, sample_count);
} catch (std::exception ex) {
std::cout << "Exception caught: " << ex.what() << std::endl;
return -1;
}
return 0;
}
| cxx |
rticonnextdds-examples | data/projects/rticonnextdds-examples/connext_dds/waitset_status_cond/c++03/waitset_statuscond_subscriber.cxx | /*******************************************************************************
(c) 2005-2015 Copyright, Real-Time Innovations, Inc. All rights reserved.
RTI grants Licensee a license to use, modify, compile, and create derivative
works of the Software. Licensee has the right to distribute object form only
for use with RTI products. The Software is provided "as is", with no warranty
of any type, including any warranty for fitness for any purpose. RTI is under
no obligation to maintain or support the Software. RTI shall not be liable for
any incidental or consequential damages arising out of the use or inability to
use the software.
******************************************************************************/
#include <cstdlib>
#include <iostream>
#include "waitset_statuscond.hpp"
#include <dds/dds.hpp>
using namespace dds::core;
using namespace dds::core::cond;
using namespace dds::core::policy;
using namespace dds::core::status;
using namespace dds::domain;
using namespace dds::topic;
using namespace dds::sub;
using namespace dds::sub::qos;
void subscriber_main(int domain_id, int sample_count)
{
// Create a DomainParticipant.
DomainParticipant participant(domain_id);
// Create a Topic -- and automatically register the type.
Topic<Foo> topic(participant, "Example waitset_statuscond");
// Retrieve the subscriber QoS from USER_QOS_PROFILES.xml
DataReaderQos reader_qos = QosProvider::Default().datareader_qos();
// If you want to change the DataReader's QoS programmatically rather
// than using the XML file, you will need to comment out the previous
// publisher_qos assignment and uncomment these files.
// reader_qos << Reliability::Reliable()
// << History::KeepAll();
// Create a DataReader.
DataReader<Foo> reader(Subscriber(participant), topic, reader_qos);
// Get status conditions.
// Each entity may have an attached Status Condition. To modify the
// statuses we need to get the reader's Status Conditions first.
// By instantiating a StatusCondition we are obtaining a reference to this
// reader's StatusCondition
StatusCondition status_condition(reader);
// Set enabled statuses.
// Now that we have the Status Condition, we are going to enable the
// statuses we are interested in:
status_condition.enabled_statuses(StatusMask::data_available());
// Create the waitset and attach the condition.
WaitSet waitset;
waitset += status_condition;
// Main loop
for (int count = 0; (sample_count == 0) || (count < sample_count);
count++) {
// 'wait()' blocks execution of the thread until one or more attached
// Conditions become true, or until a user-specified timeout expires.
// Another way would be to use 'dispatch()' to wait and dispatch the
// events as it's done in the "waitset_query_cond" example.
WaitSet::ConditionSeq active_conditions =
waitset.wait(Duration::from_millisecs(1500));
if (active_conditions.size() == 0) {
std::cout << "Wait timed out!! No conditions were triggered."
<< std::endl;
continue;
}
std::cout << "Got " << active_conditions.size() << " active conditions"
<< std::endl;
// In this case, we have only a single condition, but if we had
// multiple, we would need to iterate over them and check which one is
// true. Leaving the logic for the more complex case.
for (std::vector<int>::size_type i = 0; i < active_conditions.size();
i++) {
// Compare with Status Condition
if (active_conditions[i] == status_condition) {
// Get the status changes so we can check witch status condition
// triggered.
StatusMask triggeredmask = reader.status_changes();
// Subscription matched
if ((triggeredmask & StatusMask::data_available()).any()) {
// Current conditions match our conditions to read data, so
// we can read data just like we would do in any other
// example.
LoanedSamples<Foo> samples = reader.take();
for (LoanedSamples<Foo>::iterator sampleIt =
samples.begin();
sampleIt != samples.end();
++sampleIt) {
if (!sampleIt->info().valid()) {
std::cout << "Got metadata" << std::endl;
} else {
std::cout << sampleIt->data() << std::endl;
}
}
}
}
}
}
}
int main(int argc, char *argv[])
{
int domain_id = 0;
int sample_count = 0; // Infinite loop
if (argc >= 2) {
domain_id = atoi(argv[1]);
}
if (argc >= 3) {
sample_count = atoi(argv[2]);
}
// To turn on additional logging, include <rti/config/Logger.hpp> and
// uncomment the following line:
// rti::config::Logger::instance().verbosity(rti::config::Verbosity::STATUS_ALL);
try {
subscriber_main(domain_id, sample_count);
} catch (std::exception ex) {
std::cout << "Exception caught: " << ex.what() << std::endl;
return -1;
}
return 0;
}
| cxx |
rticonnextdds-examples | data/projects/rticonnextdds-examples/connext_dds/waitset_status_cond/c++11/application.hpp | /*
* (c) Copyright, Real-Time Innovations, 2020. All rights reserved.
* RTI grants Licensee a license to use, modify, compile, and create derivative
* works of the software solely for use with RTI Connext DDS. Licensee may
* redistribute copies of the software provided that all such copies are subject
* to this license. The software is provided "as is", with no warranty of any
* type, including any warranty for fitness for any purpose. RTI is under no
* obligation to maintain or support the software. RTI shall not be liable for
* any incidental or consequential damages arising out of the use or inability
* to use the software.
*/
#ifndef APPLICATION_HPP
#define APPLICATION_HPP
#include <iostream>
#include <csignal>
#include <dds/core/ddscore.hpp>
namespace application {
// Catch control-C and tell application to shut down
bool shutdown_requested = false;
inline void stop_handler(int)
{
shutdown_requested = true;
std::cout << "preparing to shut down..." << std::endl;
}
inline void setup_signal_handlers()
{
signal(SIGINT, stop_handler);
signal(SIGTERM, stop_handler);
}
enum class ParseReturn {
ok,
failure,
exit
};
struct ApplicationArguments {
ParseReturn parse_result;
unsigned int domain_id;
unsigned int sample_count;
rti::config::Verbosity verbosity;
ApplicationArguments(
ParseReturn parse_result_param,
unsigned int domain_id_param,
unsigned int sample_count_param,
rti::config::Verbosity verbosity_param)
: parse_result(parse_result_param),
domain_id(domain_id_param),
sample_count(sample_count_param),
verbosity(verbosity_param) {}
};
inline void set_verbosity(
rti::config::Verbosity& verbosity,
int verbosity_value)
{
switch (verbosity_value) {
case 0:
verbosity = rti::config::Verbosity::SILENT;
break;
case 1:
verbosity = rti::config::Verbosity::EXCEPTION;
break;
case 2:
verbosity = rti::config::Verbosity::WARNING;
break;
case 3:
verbosity = rti::config::Verbosity::STATUS_ALL;
break;
default:
verbosity = rti::config::Verbosity::EXCEPTION;
break;
}
}
// Parses application arguments for example.
inline ApplicationArguments parse_arguments(int argc, char *argv[])
{
int arg_processing = 1;
bool show_usage = false;
ParseReturn parse_result = ParseReturn::ok;
unsigned int domain_id = 0;
unsigned int sample_count = (std::numeric_limits<unsigned int>::max)();
rti::config::Verbosity verbosity(rti::config::Verbosity::EXCEPTION);
while (arg_processing < argc) {
if ((argc > arg_processing + 1)
&& (strcmp(argv[arg_processing], "-d") == 0
|| strcmp(argv[arg_processing], "--domain") == 0)) {
domain_id = atoi(argv[arg_processing + 1]);
arg_processing += 2;
} else if ((argc > arg_processing + 1)
&& (strcmp(argv[arg_processing], "-s") == 0
|| strcmp(argv[arg_processing], "--sample-count") == 0)) {
sample_count = atoi(argv[arg_processing + 1]);
arg_processing += 2;
} else if ((argc > arg_processing + 1)
&& (strcmp(argv[arg_processing], "-v") == 0
|| strcmp(argv[arg_processing], "--verbosity") == 0)) {
set_verbosity(verbosity, atoi(argv[arg_processing + 1]));
arg_processing += 2;
} else if (strcmp(argv[arg_processing], "-h") == 0
|| strcmp(argv[arg_processing], "--help") == 0) {
std::cout << "Example application." << std::endl;
show_usage = true;
parse_result = ParseReturn::exit;
break;
} else {
std::cout << "Bad parameter." << std::endl;
show_usage = true;
parse_result = ParseReturn::failure;
break;
}
}
if (show_usage) {
std::cout << "Usage:\n"\
" -d, --domain <int> Domain ID this application will\n" \
" subscribe in. \n"
" Default: 0\n"\
" -s, --sample_count <int> Number of samples to receive before\n"\
" cleanly shutting down. \n"
" Default: infinite\n"
" -v, --verbosity <int> How much debugging output to show.\n"\
" Range: 0-3 \n"
" Default: 1"
<< std::endl;
}
return ApplicationArguments(parse_result, domain_id, sample_count, verbosity);
}
} // namespace application
#endif // APPLICATION_HPP | hpp |
rticonnextdds-examples | data/projects/rticonnextdds-examples/connext_dds/waitset_status_cond/c++11/waitset_cond_modern_subscriber.cxx | /*******************************************************************************
(c) 2005-2017 Copyright, Real-Time Innovations, Inc. All rights reserved.
RTI grants Licensee a license to use, modify, compile, and create derivative
works of the Software. Licensee has the right to distribute object form only
for use with RTI products. The Software is provided "as is", with no warranty
of any type, including any warranty for fitness for any purpose. RTI is under
no obligation to maintain or support the Software. RTI shall not be liable for
any incidental or consequential damages arising out of the use or inability to
use the software.
******************************************************************************/
#include <algorithm>
#include <iostream>
#include <dds/core/ddscore.hpp>
#include <dds/sub/ddssub.hpp>
// Or simply include <dds/dds.hpp>
#include <rti/config/Logger.hpp> // for logging
#include "waitset_cond_modern.hpp"
#include "application.hpp" // for command line parsing and ctrl-c
int run_subscriber_application(
unsigned int domain_id,
unsigned int sample_count)
{
// Create a DomainParticipant with default Qos
dds::domain::DomainParticipant participant(domain_id);
// Create a Topic -- and automatically register the type
dds::topic::Topic<Foo> topic(participant, "Example Foo");
// Create a DataReader with default Qos (Subscriber created in-line)
dds::sub::DataReader<Foo> reader(dds::sub::Subscriber(participant), topic);
// Create a Status Condition for the reader
dds::core::cond::StatusCondition status_condition(reader);
// Enable statuses configuration for the status that it is desired
status_condition.enabled_statuses(
dds::core::status::StatusMask::liveliness_changed());
// Lambda function for the status_condition
// Handler register a custom handler with the condition
status_condition->handler([&reader]() {
// Get the status changes so we can check witch status condition
// triggered
dds::core::status::StatusMask status_mask = reader.status_changes();
// In Case of Liveliness changed
if ((status_mask & dds::core::status::StatusMask::liveliness_changed())
.any()) {
dds::core::status::LivelinessChangedStatus st =
reader.liveliness_changed_status();
std::cout << "Liveliness changed => Active writers = "
<< st.alive_count() << std::endl;
}
}); // Create a ReadCondition for any data on this reader and associate a
// handler
int samples_read = 0;
dds::sub::cond::ReadCondition read_condition(
reader,
dds::sub::status::DataState::any(),
[&reader, &samples_read]() {
// Take all samples
dds::sub::LoanedSamples<Foo> samples = reader.take();
for (auto sample : samples) {
if (sample.info().valid()) {
samples_read++;
std::cout << sample.data() << std::endl;
}
}
} // The LoanedSamples destructor returns the loan
);
// Create a WaitSet and attach both ReadCondition and StatusCondition
dds::core::cond::WaitSet waitset;
waitset += read_condition;
waitset += status_condition;
while (!application::shutdown_requested && samples_read < sample_count) {
// Dispatch will call the handlers associated to the WaitSet conditions
// when they activate
waitset.dispatch(dds::core::Duration(4)); // Wait up to 4s each time
}
return 1;
}
int main(int argc, char *argv[])
{
using namespace application;
// Parse arguments and handle control-C
auto arguments = parse_arguments(argc, argv);
if (arguments.parse_result == ParseReturn::exit) {
return EXIT_SUCCESS;
} else if (arguments.parse_result == ParseReturn::failure) {
return EXIT_FAILURE;
}
setup_signal_handlers();
// Sets Connext verbosity to help debugging
rti::config::Logger::instance().verbosity(arguments.verbosity);
try {
run_subscriber_application(arguments.domain_id, arguments.sample_count);
} catch (const std::exception &ex) {
// This will catch DDS exceptions
std::cerr << "Exception in run_subscriber_application(): " << ex.what()
<< std::endl;
return EXIT_FAILURE;
}
// Releases the memory used by the participant factory. Optional at
// application exit
dds::domain::DomainParticipant::finalize_participant_factory();
return EXIT_SUCCESS;
}
| cxx |
rticonnextdds-examples | data/projects/rticonnextdds-examples/connext_dds/waitset_status_cond/c++11/waitset_cond_modern_publisher.cxx | /*******************************************************************************
(c) 2005-2017 Copyright, Real-Time Innovations, Inc. All rights reserved.
RTI grants Licensee a license to use, modify, compile, and create derivative
works of the Software. Licensee has the right to distribute object form only
for use with RTI products. The Software is provided "as is", with no warranty
of any type, including any warranty for fitness for any purpose. RTI is under
no obligation to maintain or support the Software. RTI shall not be liable for
any incidental or consequential damages arising out of the use or inability to
use the software.
******************************************************************************/
#include <dds/pub/ddspub.hpp>
#include <rti/util/util.hpp> // for sleep()
#include <rti/config/Logger.hpp> // for logging
#include "waitset_cond_modern.hpp"
#include "application.hpp" // for command line parsing and ctrl-c
void run_publisher_application(
unsigned int domain_id,
unsigned int sample_count)
{
// Create a DomainParticipant with default Qos
dds::domain::DomainParticipant participant(domain_id);
// Create a Topic -- and automatically register the type
dds::topic::Topic<Foo> topic(participant, "Example Foo");
// Create a DataWriter with default Qos (Publisher created in-line)
dds::pub::DataWriter<Foo> writer(dds::pub::Publisher(participant), topic);
Foo sample;
for (unsigned int samples_written = 0;
!application::shutdown_requested && samples_written < sample_count;
samples_written++) {
std::cout << "Writing Foo, count " << samples_written << std::endl;
sample.x(samples_written);
writer.write(sample);
rti::util::sleep(dds::core::Duration(1));
}
}
int main(int argc, char *argv[])
{
using namespace application;
// Parse arguments and handle control-C
auto arguments = parse_arguments(argc, argv);
if (arguments.parse_result == ParseReturn::exit) {
return EXIT_SUCCESS;
} else if (arguments.parse_result == ParseReturn::failure) {
return EXIT_FAILURE;
}
setup_signal_handlers();
// Sets Connext verbosity to help debugging
rti::config::Logger::instance().verbosity(arguments.verbosity);
try {
run_publisher_application(arguments.domain_id, arguments.sample_count);
} catch (const std::exception &ex) {
// This will catch DDS exceptions
std::cerr << "Exception in run_publisher_application(): " << ex.what()
<< std::endl;
return EXIT_FAILURE;
}
// Releases the memory used by the participant factory. Optional at
// application exit
dds::domain::DomainParticipant::finalize_participant_factory();
return EXIT_SUCCESS;
}
| cxx |
rticonnextdds-examples | data/projects/rticonnextdds-examples/connext_dds/using_qos_profiles/c++/profiles_subscriber.cxx | /*******************************************************************************
(c) 2005-2014 Copyright, Real-Time Innovations, Inc. All rights reserved.
RTI grants Licensee a license to use, modify, compile, and create derivative
works of the Software. Licensee has the right to distribute object form only
for use with RTI products. The Software is provided "as is", with no warranty
of any type, including any warranty for fitness for any purpose. RTI is under
no obligation to maintain or support the Software. RTI shall not be liable for
any incidental or consequential damages arising out of the use or inability to
use the software.
******************************************************************************/
/* profiles_subscriber.cxx
A subscription example
This file is derived from code automatically generated by the rtiddsgen
command:
rtiddsgen -language C++ -example <arch> profiles.idl
Example subscription of type profiles automatically generated by
'rtiddsgen'. To test them follow these steps:
(1) Compile this file and the example publication.
(2) Start the subscription with the command
objs/<arch>/profiles_subscriber <domain_id> <sample_count>
(3) Start the publication with the command
objs/<arch>/profiles_publisher <domain_id> <sample_count>
(4) [Optional] Specify the list of discovery initial peers and
multicast receive addresses via an environment variable or a file
(in the current working directory) called NDDS_DISCOVERY_PEERS.
You can run any number of publishers and subscribers programs, and can
add and remove them dynamically from the domain.
Example:
To run the example application on domain <domain_id>:
On Unix:
objs/<arch>/profiles_publisher <domain_id>
objs/<arch>/profiles_subscriber <domain_id>
On Windows:
objs\<arch>\profiles_publisher <domain_id>
objs\<arch>\profiles_subscriber <domain_id>
modification history
------------ -------
*/
#include <stdio.h>
#include <stdlib.h>
#ifdef RTI_VX653
#include <vThreadsData.h>
#endif
#include "ndds/ndds_cpp.h"
#include "profiles.h"
#include "profilesSupport.h"
#define PROFILE_NAME_STRING_LEN 100
class profilesListener : public DDSDataReaderListener {
public:
profilesListener(char listener_name[PROFILE_NAME_STRING_LEN])
{
strcpy(_listener_name, listener_name);
}
virtual void on_requested_deadline_missed(
DDSDataReader * /*reader*/,
const DDS_RequestedDeadlineMissedStatus & /*status*/)
{
}
virtual void on_requested_incompatible_qos(
DDSDataReader * /*reader*/,
const DDS_RequestedIncompatibleQosStatus & /*status*/)
{
}
virtual void on_sample_rejected(
DDSDataReader * /*reader*/,
const DDS_SampleRejectedStatus & /*status*/)
{
}
virtual void on_liveliness_changed(
DDSDataReader * /*reader*/,
const DDS_LivelinessChangedStatus & /*status*/)
{
}
virtual void on_sample_lost(
DDSDataReader * /*reader*/,
const DDS_SampleLostStatus & /*status*/)
{
}
virtual void on_subscription_matched(
DDSDataReader * /*reader*/,
const DDS_SubscriptionMatchedStatus & /*status*/)
{
}
virtual void on_data_available(DDSDataReader *reader);
private:
char _listener_name[PROFILE_NAME_STRING_LEN];
};
void profilesListener::on_data_available(DDSDataReader *reader)
{
profilesDataReader *profiles_reader = NULL;
profilesSeq data_seq;
DDS_SampleInfoSeq info_seq;
DDS_ReturnCode_t retcode;
int i;
profiles_reader = profilesDataReader::narrow(reader);
if (profiles_reader == NULL) {
printf("DataReader narrow error\n");
return;
}
retcode = profiles_reader->take(
data_seq,
info_seq,
DDS_LENGTH_UNLIMITED,
DDS_ANY_SAMPLE_STATE,
DDS_ANY_VIEW_STATE,
DDS_ANY_INSTANCE_STATE);
if (retcode == DDS_RETCODE_NO_DATA) {
return;
} else if (retcode != DDS_RETCODE_OK) {
printf("take error %d\n", retcode);
return;
}
printf("=============================================\n");
printf("%s listener received\n", _listener_name);
printf("=============================================\n");
for (i = 0; i < data_seq.length(); ++i) {
if (info_seq[i].valid_data) {
profilesTypeSupport::print_data(&data_seq[i]);
}
}
retcode = profiles_reader->return_loan(data_seq, info_seq);
if (retcode != DDS_RETCODE_OK) {
printf("return loan error %d\n", retcode);
}
}
/* Delete all entities */
static int subscriber_shutdown(DDSDomainParticipant *participant)
{
DDS_ReturnCode_t retcode;
int status = 0;
if (participant != NULL) {
retcode = participant->delete_contained_entities();
if (retcode != DDS_RETCODE_OK) {
printf("delete_contained_entities error %d\n", retcode);
status = -1;
}
retcode = DDSTheParticipantFactory->delete_participant(participant);
if (retcode != DDS_RETCODE_OK) {
printf("delete_participant error %d\n", retcode);
status = -1;
}
}
/* RTI Connext provides the finalize_instance() method on
domain participant factory for people who want to release memory used
by the participant factory. Uncomment the following block of code for
clean destruction of the singleton. */
/*
retcode = DDSDomainParticipantFactory::finalize_instance();
if (retcode != DDS_RETCODE_OK) {
printf("finalize_instance error %d\n", retcode);
status = -1;
}
*/
return status;
}
extern "C" int subscriber_main(int domainId, int sample_count)
{
DDSDomainParticipant *participant = NULL;
DDSSubscriber *subscriber = NULL;
DDSTopic *topic = NULL;
/* Volatile and transient local readers and profilesListeners */
DDSDataReader *reader_volatile = NULL;
DDSDataReader *reader_transient_local = NULL;
profilesListener *reader_volatile_listener = NULL;
profilesListener *reader_transient_local_listener = NULL;
DDS_ReturnCode_t retcode;
const char *type_name = NULL;
int count = 0;
DDS_Duration_t receive_period = { 1, 0 };
int status = 0;
/* There are several different approaches for loading QoS profiles from XML
* files (see Configuring QoS with XML chapter in the RTI Connext Core
* Libraries and Utilities User's Manual). In this example we illustrate
* two of them:
*
* 1) Creating a file named USER_QOS_PROFILES.xml, which is loaded,
* automatically by the DomainParticipantFactory. In this case, the file
* defines a QoS profile named volatile_profile that configures reliable,
* volatile DataWriters and DataReaders.
*
* 2) Adding XML documents to the DomainParticipantFactory using its
* Profile QoSPolicy (DDS Extension). In this case, we add
* my_custom_qos_profiles.xml to the url_profile sequence, which stores
* the URLs of all the XML documents with QoS policies that are loaded by
* the DomainParticipantFactory aside from the ones that are automatically
* loaded.
* my_custom_qos_profiles.xml defines a QoS profile named
* transient_local_profile that configures reliable, transient local
* DataWriters and DataReaders.
*/
/* To load my_custom_qos_profiles.xml, as explained above, we need to modify
* the DDSTheParticipantFactory Profile QoSPolicy */
DDS_DomainParticipantFactoryQos factory_qos;
DDSTheParticipantFactory->get_qos(factory_qos);
/* We are only going to add one XML file to the url_profile sequence, so we
* ensure a length of 1,1. */
factory_qos.profile.url_profile.ensure_length(1, 1);
/* The XML file will be loaded from the working directory. That means, you
* need to run the example like this:
* ./objs/<architecture>/profiles_publisher
* (see README.txt for more information on how to run the example).
*
* Note that you can specify the absolute path of the XML QoS file to avoid
* this problem.
*/
factory_qos.profile.url_profile[0] =
DDS_String_dup("my_custom_qos_profiles.xml");
DDSTheParticipantFactory->set_qos(factory_qos);
/* Our default Qos profile, volatile_profile, sets the participant name.
* This is the only participant_qos policy that we change in our
* example. As this is done in the default QoS profile, we don't need
* to specify its name, so we can create the participant using the
* create_participant() method rather than using
* create_participant_with_profile(). */
participant = DDSTheParticipantFactory->create_participant(
domainId,
DDS_PARTICIPANT_QOS_DEFAULT,
NULL /* listener */,
DDS_STATUS_MASK_NONE);
if (participant == NULL) {
printf("create_participant error\n");
subscriber_shutdown(participant);
return -1;
}
/* We haven't changed the subscriber_qos in any of QoS profiles we use in
* this example, so we can just use the create_topic() method. If you want
* to load an specific profile in which you may have changed the
* publisher_qos, use the create_publisher_with_profile() method. */
subscriber = participant->create_subscriber(
DDS_SUBSCRIBER_QOS_DEFAULT,
NULL /* listener */,
DDS_STATUS_MASK_NONE);
if (subscriber == NULL) {
printf("create_subscriber error\n");
subscriber_shutdown(participant);
return -1;
}
/* Register the type before creating the topic */
type_name = profilesTypeSupport::get_type_name();
retcode = profilesTypeSupport::register_type(participant, type_name);
if (retcode != DDS_RETCODE_OK) {
printf("register_type error %d\n", retcode);
subscriber_shutdown(participant);
return -1;
}
/* We haven't changed the topic_qos in any of QoS profiles we use in this
* example, so we can just use the create_topic() method. If you want to
* load an specific profile in which you may have changed the topic_qos,
* use the create_topic_with_profile() method. */
topic = participant->create_topic(
"Example profiles",
type_name,
DDS_TOPIC_QOS_DEFAULT,
NULL /* listener */,
DDS_STATUS_MASK_NONE);
if (topic == NULL) {
printf("create_topic error\n");
subscriber_shutdown(participant);
return -1;
}
/* Create Data Readers listeners */
reader_volatile_listener =
new profilesListener((char *) "volatile_profile");
reader_transient_local_listener =
new profilesListener((char *) "transient_local_profile");
/* Volatile reader -- As volatile_profile is the default qos profile
* we don't need to specify the profile we are going to use, we can
* just call create_datareader passing DDS_DATAWRITER_QOS_DEFAULT. */
reader_volatile = subscriber->create_datareader(
topic,
DDS_DATAREADER_QOS_DEFAULT,
reader_volatile_listener,
DDS_STATUS_MASK_ALL);
if (reader_volatile == NULL) {
printf("create_datareader error\n");
subscriber_shutdown(participant);
delete reader_volatile_listener;
return -1;
}
/* Transient Local writer -- In this case we use
* create_datareader_with_profile, because we have to use a profile other
* than the default one. This profile has been defined in
* my_custom_qos_profiles.xml, but since we already loaded the XML file
* we don't need to specify anything else. */
reader_transient_local = subscriber->create_datareader_with_profile(
topic, /* DDS_Topic* */
"profiles_Library", /* library_name */
"transient_local_profile", /* profile_name */
reader_transient_local_listener /* listener */,
DDS_STATUS_MASK_ALL /* DDS_StatusMask */
);
if (reader_transient_local == NULL) {
printf("create_datareader error\n");
subscriber_shutdown(participant);
delete reader_transient_local_listener;
return -1;
}
printf("Created reader_transient_local");
/* Main loop */
for (count = 0; (sample_count == 0) || (count < sample_count); ++count) {
NDDSUtility::sleep(receive_period);
}
/* Delete all entities */
status = subscriber_shutdown(participant);
delete reader_volatile_listener;
delete reader_transient_local_listener;
return status;
}
#if defined(RTI_WINCE)
int wmain(int argc, wchar_t **argv)
{
int domainId = 0;
int sample_count = 0; /* infinite loop */
if (argc >= 2) {
domainId = _wtoi(argv[1]);
}
if (argc >= 3) {
sample_count = _wtoi(argv[2]);
}
/* Uncomment this to turn on additional logging
NDDSConfigLogger::get_instance()->
set_verbosity_by_category(NDDS_CONFIG_LOG_CATEGORY_API,
NDDS_CONFIG_LOG_VERBOSITY_STATUS_ALL);
*/
return subscriber_main(domainId, sample_count);
}
#elif !(defined(RTI_VXWORKS) && !defined(__RTP__)) && !defined(RTI_PSOS)
int main(int argc, char *argv[])
{
int domainId = 0;
int sample_count = 0; /* infinite loop */
if (argc >= 2) {
domainId = atoi(argv[1]);
}
if (argc >= 3) {
sample_count = atoi(argv[2]);
}
/* Uncomment this to turn on additional logging
NDDSConfigLogger::get_instance()->
set_verbosity_by_category(NDDS_CONFIG_LOG_CATEGORY_API,
NDDS_CONFIG_LOG_VERBOSITY_STATUS_ALL);
*/
return subscriber_main(domainId, sample_count);
}
#endif
#ifdef RTI_VX653
const unsigned char *__ctype = *(__ctypePtrGet());
extern "C" void usrAppInit()
{
#ifdef USER_APPL_INIT
USER_APPL_INIT; /* for backwards compatibility */
#endif
/* add application specific code here */
taskSpawn(
"sub",
RTI_OSAPI_THREAD_PRIORITY_NORMAL,
0x8,
0x150000,
(FUNCPTR) subscriber_main,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0);
}
#endif
| cxx |
rticonnextdds-examples | data/projects/rticonnextdds-examples/connext_dds/using_qos_profiles/c++/profiles_publisher.cxx | /*******************************************************************************
(c) 2005-2014 Copyright, Real-Time Innovations, Inc. All rights reserved.
RTI grants Licensee a license to use, modify, compile, and create derivative
works of the Software. Licensee has the right to distribute object form only
for use with RTI products. The Software is provided "as is", with no warranty
of any type, including any warranty for fitness for any purpose. RTI is under
no obligation to maintain or support the Software. RTI shall not be liable for
any incidental or consequential damages arising out of the use or inability to
use the software.
******************************************************************************/
/* profiles_publisher.cxx
A publication of data of type profiles
This file is derived from code automatically generated by the rtiddsgen
command:
rtiddsgen -language C++ -example <arch> profiles.idl
Example publication of type profiles automatically generated by
'rtiddsgen'. To test them follow these steps:
(1) Compile this file and the example subscription.
(2) Start the subscription with the command
objs/<arch>/profiles_subscriber <domain_id> <sample_count>
(3) Start the publication with the command
objs/<arch>/profiles_publisher <domain_id> <sample_count>
(4) [Optional] Specify the list of discovery initial peers and
multicast receive addresses via an environment variable or a file
(in the current working directory) called NDDS_DISCOVERY_PEERS.
You can run any number of publishers and subscribers programs, and can
add and remove them dynamically from the domain.
Example:
To run the example application on domain <domain_id>:
On Unix:
objs/<arch>/profiles_publisher <domain_id> o
objs/<arch>/profiles_subscriber <domain_id>
On Windows:
objs\<arch>\profiles_publisher <domain_id>
objs\<arch>\profiles_subscriber <domain_id>
modification history
------------ -------
*/
#include <stdio.h>
#include <stdlib.h>
#ifdef RTI_VX653
#include <vThreadsData.h>
#endif
#include "ndds/ndds_cpp.h"
#include "profiles.h"
#include "profilesSupport.h"
/* Delete all entities */
static int publisher_shutdown(DDSDomainParticipant *participant)
{
DDS_ReturnCode_t retcode;
int status = 0;
if (participant != NULL) {
retcode = participant->delete_contained_entities();
if (retcode != DDS_RETCODE_OK) {
printf("delete_contained_entities error %d\n", retcode);
status = -1;
}
retcode = DDSTheParticipantFactory->delete_participant(participant);
if (retcode != DDS_RETCODE_OK) {
printf("delete_participant error %d\n", retcode);
status = -1;
}
}
/* RTI Connext provides finalize_instance() method on
domain participant factory for people who want to release memory used
by the participant factory. Uncomment the following block of code for
clean destruction of the singleton. */
/*
retcode = DDSDomainParticipantFactory::finalize_instance();
if (retcode != DDS_RETCODE_OK) {
printf("finalize_instance error %d\n", retcode);
status = -1;
}
*/
return status;
}
extern "C" int publisher_main(int domainId, int sample_count)
{
DDSDomainParticipant *participant = NULL;
DDSPublisher *publisher = NULL;
DDSTopic *topic = NULL;
/* Volatile and transient local writers and profilesDataWriters */
DDSDataWriter *writer_volatile = NULL;
DDSDataWriter *writer_transient_local = NULL;
profilesDataWriter *profiles_writer_volatile = NULL;
profilesDataWriter *profiles_writer_transient_local = NULL;
profiles *instance = NULL;
DDS_ReturnCode_t retcode;
DDS_InstanceHandle_t instance_handle = DDS_HANDLE_NIL;
const char *type_name = NULL;
int count = 0;
/* Send a new sample every second */
DDS_Duration_t send_period = { 1, 0 };
/* There are several different approaches for loading QoS profiles from XML
* files (see Configuring QoS with XML chapter in the RTI Connext Core
* Libraries and Utilities User's Manual). In this example we illustrate
* two of them:
*
* 1) Creating a file named USER_QOS_PROFILES.xml, which is loaded,
* automatically by the DomainParticipantFactory. In this case, the file
* defines a QoS profile named volatile_profile that configures reliable,
* volatile DataWriters and DataReaders.
*
* 2) Adding XML documents to the DomainParticipantFactory using its
* Profile QoSPolicy (DDS Extension). In this case, we add
* my_custom_qos_profiles.xml to the url_profile sequence, which stores
* the URLs of all the XML documents with QoS policies that are loaded by
* the DomainParticipantFactory aside from the ones that are automatically
* loaded.
* my_custom_qos_profiles.xml defines a QoS profile named
* transient_local_profile that configures reliable, transient local
* DataWriters and DataReaders.
*/
/* To load my_custom_qos_profiles.xml, as explained above, we need to modify
* the DDSTheParticipantFactory Profile QoSPolicy */
DDS_DomainParticipantFactoryQos factory_qos;
DDSTheParticipantFactory->get_qos(factory_qos);
/* We are only going to add one XML file to the url_profile sequence, so we
* ensure a length of 1,1. */
factory_qos.profile.url_profile.ensure_length(1, 1);
/* The XML file will be loaded from the working directory. That means, you
* need to run the example like this:
* ./objs/<architecture>/profiles_publisher
* (see README.txt for more information on how to run the example).
*
* Note that you can specify the absolute path of the XML QoS file to avoid
* this problem.
*/
factory_qos.profile.url_profile[0] =
DDS_String_dup("my_custom_qos_profiles.xml");
DDSTheParticipantFactory->set_qos(factory_qos);
/* Our default Qos profile, volatile_profile, sets the participant name.
* This is the only participant_qos policy that we change in our
* example. As this is done in the default QoS profile, we don't need
* to specify its name, so we can create the participant using the
* create_participant() method rather than using
* create_participant_with_profile(). */
participant = DDSTheParticipantFactory->create_participant(
domainId,
DDS_PARTICIPANT_QOS_DEFAULT,
NULL /* listener */,
DDS_STATUS_MASK_NONE);
if (participant == NULL) {
printf("create_participant error\n");
publisher_shutdown(participant);
return -1;
}
/* We haven't changed the publisher_qos in any of QoS profiles we use in
* this example, so we can just use the create_publisher() method. If you
* want to load an specific profile in which you may have changed the
* publisher_qos, use the create_publisher_with_profile() method. */
publisher = participant->create_publisher(
DDS_PUBLISHER_QOS_DEFAULT,
NULL /* listener */,
DDS_STATUS_MASK_NONE);
if (publisher == NULL) {
printf("create_publisher error\n");
publisher_shutdown(participant);
return -1;
}
/* Register type before creating topic */
type_name = profilesTypeSupport::get_type_name();
retcode = profilesTypeSupport::register_type(participant, type_name);
if (retcode != DDS_RETCODE_OK) {
printf("register_type error %d\n", retcode);
publisher_shutdown(participant);
return -1;
}
/* We haven't changed the topic_qos in any of QoS profiles we use in this
* example, so we can just use the create_topic() method. If you want to
* load an specific profile in which you may have changed the topic_qos,
* use the create_topic_with_profile() method. */
topic = participant->create_topic(
"Example profiles",
type_name,
DDS_TOPIC_QOS_DEFAULT,
NULL /* listener */,
DDS_STATUS_MASK_NONE);
if (topic == NULL) {
printf("create_topic error\n");
publisher_shutdown(participant);
return -1;
}
/* Volatile writer -- As volatile_profile is the default qos profile
* we don't need to specify the profile we are going to use, we can
* just call create_datawriter passing DDS_DATAWRITER_QOS_DEFAULT. */
writer_volatile = publisher->create_datawriter(
topic,
DDS_DATAWRITER_QOS_DEFAULT, /* Default datawriter_qos */
NULL /* listener */,
DDS_STATUS_MASK_NONE);
if (writer_volatile == NULL) {
printf("create_datawriter error\n");
publisher_shutdown(participant);
return -1;
}
/* Transient Local writer -- In this case we use
* create_datawriter_with_profile, because we have to use a profile other
* than the default one. This profile has been defined in
* my_custom_qos_profiles.xml, but since we already loaded the XML file
* we don't need to specify anything else. */
writer_transient_local = publisher->create_datawriter_with_profile(
topic, /* DDS_Topic* */
"profiles_Library", /* library_name */
"transient_local_profile", /* profile_name */
NULL /* listener */,
DDS_STATUS_MASK_NONE /* DDS_StatusMask */
);
if (writer_transient_local == NULL) {
printf("create_datawriter error\n");
publisher_shutdown(participant);
return -1;
}
profiles_writer_volatile = profilesDataWriter::narrow(writer_volatile);
if (profiles_writer_volatile == NULL) {
printf("DataWriter narrow error\n");
publisher_shutdown(participant);
return -1;
}
profiles_writer_transient_local =
profilesDataWriter::narrow(writer_transient_local);
if (profiles_writer_volatile == NULL) {
printf("DataWriter narrow error\n");
publisher_shutdown(participant);
return -1;
}
/* Create data sample for writing */
instance = profilesTypeSupport::create_data();
if (instance == NULL) {
printf("profilesTypeSupport::create_data error\n");
publisher_shutdown(participant);
return -1;
}
/* For a data type that has a key, if the same instance is going to be
written multiple times, initialize the key here
and register the keyed instance prior to writing */
/*
instance_handle = profiles_writer->register_instance(*instance);
*/
/* Main loop */
for (count = 0; (sample_count == 0) || (count < sample_count); ++count) {
/* Modify the data to be sent here */
strcpy(instance->profile_name, "volatile_profile");
instance->x = count;
printf("Writing profile_name = %s,\t x = %d\n",
instance->profile_name,
instance->x);
retcode = profiles_writer_volatile->write(*instance, instance_handle);
if (retcode != DDS_RETCODE_OK) {
printf("write error %d\n", retcode);
}
strcpy(instance->profile_name, "transient_local_profile");
instance->x = count;
printf("Writing profile_name = %s,\t x = %d\n\n",
instance->profile_name,
instance->x);
retcode = profiles_writer_transient_local->write(
*instance,
instance_handle);
if (retcode != DDS_RETCODE_OK) {
printf("write error %d\n", retcode);
}
NDDSUtility::sleep(send_period);
}
/*
retcode = profiles_writer->unregister_instance(
*instance, instance_handle);
if (retcode != DDS_RETCODE_OK) {
printf("unregister instance error %d\n", retcode);
}
*/
/* Delete data sample */
retcode = profilesTypeSupport::delete_data(instance);
if (retcode != DDS_RETCODE_OK) {
printf("profilesTypeSupport::delete_data error %d\n", retcode);
}
/* Delete all entities */
return publisher_shutdown(participant);
}
#if defined(RTI_WINCE)
int wmain(int argc, wchar_t **argv)
{
int domainId = 0;
int sample_count = 0; /* infinite loop */
if (argc >= 2) {
domainId = _wtoi(argv[1]);
}
if (argc >= 3) {
sample_count = _wtoi(argv[2]);
}
/* Uncomment this to turn on additional logging
NDDSConfigLogger::get_instance()->
set_verbosity_by_category(NDDS_CONFIG_LOG_CATEGORY_API,
NDDS_CONFIG_LOG_VERBOSITY_STATUS_ALL);
*/
return publisher_main(domainId, sample_count);
}
#elif !(defined(RTI_VXWORKS) && !defined(__RTP__)) && !defined(RTI_PSOS)
int main(int argc, char *argv[])
{
int domainId = 0;
int sample_count = 0; /* infinite loop */
if (argc >= 2) {
domainId = atoi(argv[1]);
}
if (argc >= 3) {
sample_count = atoi(argv[2]);
}
/* Uncomment this to turn on additional logging
NDDSConfigLogger::get_instance()->
set_verbosity_by_category(NDDS_CONFIG_LOG_CATEGORY_API,
NDDS_CONFIG_LOG_VERBOSITY_STATUS_ALL);
*/
return publisher_main(domainId, sample_count);
}
#endif
#ifdef RTI_VX653
const unsigned char *__ctype = *(__ctypePtrGet());
extern "C" void usrAppInit()
{
#ifdef USER_APPL_INIT
USER_APPL_INIT; /* for backwards compatibility */
#endif
/* add application specific code here */
taskSpawn(
"pub",
RTI_OSAPI_THREAD_PRIORITY_NORMAL,
0x8,
0x150000,
(FUNCPTR) publisher_main,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0);
}
#endif
| cxx |
rticonnextdds-examples | data/projects/rticonnextdds-examples/connext_dds/using_qos_profiles/c++98/profiles_subscriber.cxx | /*******************************************************************************
(c) 2005-2014 Copyright, Real-Time Innovations, Inc. All rights reserved.
RTI grants Licensee a license to use, modify, compile, and create derivative
works of the Software. Licensee has the right to distribute object form only
for use with RTI products. The Software is provided "as is", with no warranty
of any type, including any warranty for fitness for any purpose. RTI is under
no obligation to maintain or support the Software. RTI shall not be liable for
any incidental or consequential damages arising out of the use or inability to
use the software.
******************************************************************************/
#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include "profiles.h"
#include "profilesSupport.h"
#include "ndds/ndds_cpp.h"
#include "application.h"
#define PROFILE_NAME_STRING_LEN 100
using namespace application;
static int shutdown_participant(
DDSDomainParticipant *participant,
const char *shutdown_message,
int status);
class profilesListener : public DDSDataReaderListener {
public:
profilesListener(char listener_name[PROFILE_NAME_STRING_LEN])
{
strcpy(_listener_name, listener_name);
}
virtual void on_requested_deadline_missed(
DDSDataReader * /*reader*/,
const DDS_RequestedDeadlineMissedStatus & /*status*/)
{
}
virtual void on_requested_incompatible_qos(
DDSDataReader * /*reader*/,
const DDS_RequestedIncompatibleQosStatus & /*status*/)
{
}
virtual void on_sample_rejected(
DDSDataReader * /*reader*/,
const DDS_SampleRejectedStatus & /*status*/)
{
}
virtual void on_liveliness_changed(
DDSDataReader * /*reader*/,
const DDS_LivelinessChangedStatus & /*status*/)
{
}
virtual void on_sample_lost(
DDSDataReader * /*reader*/,
const DDS_SampleLostStatus & /*status*/)
{
}
virtual void on_subscription_matched(
DDSDataReader * /*reader*/,
const DDS_SubscriptionMatchedStatus & /*status*/)
{
}
virtual void on_data_available(DDSDataReader *reader);
private:
char _listener_name[PROFILE_NAME_STRING_LEN];
};
void profilesListener::on_data_available(DDSDataReader *reader)
{
profilesDataReader *profiles_reader = NULL;
profilesSeq data_seq;
DDS_SampleInfoSeq info_seq;
DDS_ReturnCode_t retcode;
int i;
profiles_reader = profilesDataReader::narrow(reader);
if (profiles_reader == NULL) {
printf("DataReader narrow error\n");
return;
}
retcode = profiles_reader->take(
data_seq,
info_seq,
DDS_LENGTH_UNLIMITED,
DDS_ANY_SAMPLE_STATE,
DDS_ANY_VIEW_STATE,
DDS_ANY_INSTANCE_STATE);
if (retcode == DDS_RETCODE_NO_DATA) {
return;
} else if (retcode != DDS_RETCODE_OK) {
std::cerr << "take error " << retcode << std::endl;
return;
}
std::cout << "=============================================\n";
std::cout << _listener_name << " listener received\n";
std::cout << "=============================================\n";
for (i = 0; i < data_seq.length(); ++i) {
if (info_seq[i].valid_data) {
profilesTypeSupport::print_data(&data_seq[i]);
}
}
retcode = profiles_reader->return_loan(data_seq, info_seq);
if (retcode != DDS_RETCODE_OK) {
std::cerr << "return loan error " << retcode << std::endl;
}
}
int run_subscriber_application(
unsigned int domain_id,
unsigned int sample_count)
{
DDS_Duration_t receive_period = { 1, 0 };
/* There are several different approaches for loading QoS profiles from XML
* files (see Configuring QoS with XML chapter in the RTI Connext Core
* Libraries and Utilities User's Manual). In this example we illustrate
* two of them:
*
* 1) Creating a file named USER_QOS_PROFILES.xml, which is loaded,
* automatically by the DomainParticipantFactory. In this case, the file
* defines a QoS profile named volatile_profile that configures reliable,
* volatile DataWriters and DataReaders.
*
* 2) Adding XML documents to the DomainParticipantFactory using its
* Profile QoSPolicy (DDS Extension). In this case, we add
* my_custom_qos_profiles.xml to the url_profile sequence, which stores
* the URLs of all the XML documents with QoS policies that are loaded by
* the DomainParticipantFactory aside from the ones that are automatically
* loaded.
* my_custom_qos_profiles.xml defines a QoS profile named
* transient_local_profile that configures reliable, transient local
* DataWriters and DataReaders.
*/
/* To load my_custom_qos_profiles.xml, as explained above, we need to modify
* the DDSTheParticipantFactory Profile QoSPolicy */
DDS_DomainParticipantFactoryQos factory_qos;
DDSTheParticipantFactory->get_qos(factory_qos);
/* We are only going to add one XML file to the url_profile sequence, so we
* ensure a length of 1,1. */
factory_qos.profile.url_profile.ensure_length(1, 1);
/* The XML file will be loaded from the working directory. That means, you
* need to run the example like this:
* ./objs/<architecture>/profiles_publisher
* (see README.txt for more information on how to run the example).
*
* Note that you can specify the absolute path of the XML QoS file to avoid
* this problem.
*/
factory_qos.profile.url_profile[0] =
DDS_String_dup("my_custom_qos_profiles.xml");
DDSTheParticipantFactory->set_qos(factory_qos);
/* Our default Qos profile, volatile_profile, sets the participant name.
* This is the only participant_qos policy that we change in our
* example. As this is done in the default QoS profile, we don't need
* to specify its name, so we can create the participant using the
* create_participant() method rather than using
* create_participant_with_profile(). */
DDSDomainParticipant *participant =
DDSTheParticipantFactory->create_participant(
domain_id,
DDS_PARTICIPANT_QOS_DEFAULT,
NULL /* listener */,
DDS_STATUS_MASK_NONE);
if (participant == NULL) {
return shutdown_participant(
participant,
"create_participant error",
EXIT_FAILURE);
}
/* We haven't changed the subscriber_qos in any of QoS profiles we use in
* this example, so we can just use the create_topic() method. If you want
* to load an specific profile in which you may have changed the
* publisher_qos, use the create_publisher_with_profile() method. */
DDSSubscriber *subscriber = participant->create_subscriber(
DDS_SUBSCRIBER_QOS_DEFAULT,
NULL /* listener */,
DDS_STATUS_MASK_NONE);
if (subscriber == NULL) {
return shutdown_participant(
participant,
"create_subscriber error",
EXIT_FAILURE);
}
// Register the datatype to use when creating the Topic
const char *type_name = profilesTypeSupport::get_type_name();
DDS_ReturnCode_t retcode =
profilesTypeSupport::register_type(participant, type_name);
if (retcode != DDS_RETCODE_OK) {
return shutdown_participant(
participant,
"register_type error",
EXIT_FAILURE);
}
/* We haven't changed the topic_qos in any of QoS profiles we use in this
* example, so we can just use the create_topic() method. If you want to
* load an specific profile in which you may have changed the topic_qos,
* use the create_topic_with_profile() method. */
DDSTopic *topic = participant->create_topic(
"Example profiles",
type_name,
DDS_TOPIC_QOS_DEFAULT,
NULL /* listener */,
DDS_STATUS_MASK_NONE);
if (topic == NULL) {
return shutdown_participant(
participant,
"create_topic error",
EXIT_FAILURE);
}
/* Create Data Readers listeners */
profilesListener *reader_volatile_listener =
new profilesListener((char *) "volatile_profile");
profilesListener *reader_transient_local_listener =
new profilesListener((char *) "transient_local_profile");
/* Volatile reader -- As volatile_profile is the default qos profile
* we don't need to specify the profile we are going to use, we can
* just call create_datareader passing DDS_DATAWRITER_QOS_DEFAULT. */
DDSDataReader *reader_volatile = subscriber->create_datareader(
topic,
DDS_DATAREADER_QOS_DEFAULT,
reader_volatile_listener,
DDS_STATUS_MASK_ALL);
if (reader_volatile == NULL) {
return shutdown_participant(
participant,
"create_datareader error",
EXIT_FAILURE);
}
/* Transient Local writer -- In this case we use
* create_datareader_with_profile, because we have to use a profile other
* than the default one. This profile has been defined in
* my_custom_qos_profiles.xml, but since we already loaded the XML file
* we don't need to specify anything else. */
DDSDataReader *reader_transient_local =
subscriber->create_datareader_with_profile(
topic, /* DDS_Topic* */
"profiles_Library", /* library_name */
"transient_local_profile", /* profile_name */
reader_transient_local_listener /* listener */,
DDS_STATUS_MASK_ALL /* DDS_StatusMask */
);
if (reader_transient_local == NULL) {
return shutdown_participant(
participant,
"create_datareader error",
EXIT_FAILURE);
}
std::cout << "Created reader_transient_local\n";
// Main loop, write data
for (unsigned int samples_read = 0;
!shutdown_requested && samples_read < sample_count;
++samples_read) {
NDDSUtility::sleep(receive_period);
}
// Cleanup
return shutdown_participant(participant, "Shutting down", 0);
}
// Delete all entities
static int shutdown_participant(
DDSDomainParticipant *participant,
const char *shutdown_message,
int status)
{
DDS_ReturnCode_t retcode;
std::cout << shutdown_message << std::endl;
if (participant != NULL) {
// Cleanup everything created by this Participant
retcode = participant->delete_contained_entities();
if (retcode != DDS_RETCODE_OK) {
std::cerr << "delete_contained_entities error" << retcode
<< std::endl;
status = EXIT_FAILURE;
}
retcode = DDSTheParticipantFactory->delete_participant(participant);
if (retcode != DDS_RETCODE_OK) {
std::cerr << "delete_participant error" << retcode << std::endl;
status = EXIT_FAILURE;
}
}
return status;
}
int main(int argc, char *argv[])
{
// Parse arguments and handle control-C
ApplicationArguments arguments;
parse_arguments(arguments, argc, argv, subscriber);
if (arguments.parse_result == PARSE_RETURN_EXIT) {
return EXIT_SUCCESS;
} else if (arguments.parse_result == PARSE_RETURN_FAILURE) {
return EXIT_FAILURE;
}
setup_signal_handlers();
// Sets Connext verbosity to help debugging
NDDSConfigLogger::get_instance()->set_verbosity(arguments.verbosity);
int status = run_subscriber_application(
arguments.domain_id,
arguments.sample_count);
// Releases the memory used by the participant factory. Optional at
// application exit
DDS_ReturnCode_t retcode = DDSDomainParticipantFactory::finalize_instance();
if (retcode != DDS_RETCODE_OK) {
std::cerr << "finalize_instance error" << retcode << std::endl;
status = EXIT_FAILURE;
}
return status;
}
| cxx |
rticonnextdds-examples | data/projects/rticonnextdds-examples/connext_dds/using_qos_profiles/c++98/profiles_publisher.cxx | /*******************************************************************************
(c) 2005-2014 Copyright, Real-Time Innovations, Inc. All rights reserved.
RTI grants Licensee a license to use, modify, compile, and create derivative
works of the Software. Licensee has the right to distribute object form only
for use with RTI products. The Software is provided "as is", with no warranty
of any type, including any warranty for fitness for any purpose. RTI is under
no obligation to maintain or support the Software. RTI shall not be liable for
any incidental or consequential damages arising out of the use or inability to
use the software.
******************************************************************************/
#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include "profiles.h"
#include "profilesSupport.h"
#include "ndds/ndds_cpp.h"
#include "application.h"
using namespace application;
static int shutdown_participant(
DDSDomainParticipant *participant,
const char *shutdown_message,
int status);
int run_publisher_application(unsigned int domain_id, unsigned int sample_count)
{
/* Send a new sample every second */
DDS_Duration_t send_period = { 1, 0 };
/* There are several different approaches for loading QoS profiles from XML
* files (see Configuring QoS with XML chapter in the RTI Connext Core
* Libraries and Utilities User's Manual). In this example we illustrate
* two of them:
*
* 1) Creating a file named USER_QOS_PROFILES.xml, which is loaded,
* automatically by the DomainParticipantFactory. In this case, the file
* defines a QoS profile named volatile_profile that configures reliable,
* volatile DataWriters and DataReaders.
*
* 2) Adding XML documents to the DomainParticipantFactory using its
* Profile QoSPolicy (DDS Extension). In this case, we add
* my_custom_qos_profiles.xml to the url_profile sequence, which stores
* the URLs of all the XML documents with QoS policies that are loaded by
* the DomainParticipantFactory aside from the ones that are automatically
* loaded.
* my_custom_qos_profiles.xml defines a QoS profile named
* transient_local_profile that configures reliable, transient local
* DataWriters and DataReaders.
*/
/* To load my_custom_qos_profiles.xml, as explained above, we need to modify
* the DDSTheParticipantFactory Profile QoSPolicy */
DDS_DomainParticipantFactoryQos factory_qos;
DDSTheParticipantFactory->get_qos(factory_qos);
/* We are only going to add one XML file to the url_profile sequence, so we
* ensure a length of 1,1. */
factory_qos.profile.url_profile.ensure_length(1, 1);
/* The XML file will be loaded from the working directory. That means, you
* need to run the example like this:
* ./objs/<architecture>/profiles_publisher
* (see README.txt for more information on how to run the example).
*
* Note that you can specify the absolute path of the XML QoS file to avoid
* this problem.
*/
factory_qos.profile.url_profile[0] =
DDS_String_dup("my_custom_qos_profiles.xml");
DDSTheParticipantFactory->set_qos(factory_qos);
/* Our default Qos profile, volatile_profile, sets the participant name.
* This is the only participant_qos policy that we change in our
* example. As this is done in the default QoS profile, we don't need
* to specify its name, so we can create the participant using the
* create_participant() method rather than using
* create_participant_with_profile(). */
DDSDomainParticipant *participant =
DDSTheParticipantFactory->create_participant(
domain_id,
DDS_PARTICIPANT_QOS_DEFAULT,
NULL /* listener */,
DDS_STATUS_MASK_NONE);
if (participant == NULL) {
return shutdown_participant(
participant,
"create_participant error",
EXIT_FAILURE);
}
/* We haven't changed the publisher_qos in any of QoS profiles we use in
* this example, so we can just use the create_publisher() method. If you
* want to load an specific profile in which you may have changed the
* publisher_qos, use the create_publisher_with_profile() method. */
DDSPublisher *publisher = participant->create_publisher(
DDS_PUBLISHER_QOS_DEFAULT,
NULL /* listener */,
DDS_STATUS_MASK_NONE);
if (publisher == NULL) {
return shutdown_participant(
participant,
"create_publisher error",
EXIT_FAILURE);
}
// Register the datatype to use when creating the Topic
const char *type_name = profilesTypeSupport::get_type_name();
DDS_ReturnCode_t retcode =
profilesTypeSupport::register_type(participant, type_name);
if (retcode != DDS_RETCODE_OK) {
return shutdown_participant(
participant,
"register_type error",
EXIT_FAILURE);
}
/* We haven't changed the topic_qos in any of QoS profiles we use in this
* example, so we can just use the create_topic() method. If you want to
* load an specific profile in which you may have changed the topic_qos,
* use the create_topic_with_profile() method. */
DDSTopic *topic = participant->create_topic(
"Example profiles",
type_name,
DDS_TOPIC_QOS_DEFAULT,
NULL /* listener */,
DDS_STATUS_MASK_NONE);
if (topic == NULL) {
return shutdown_participant(
participant,
"create_topic error",
EXIT_FAILURE);
}
/* Volatile writer -- As volatile_profile is the default qos profile
* we don't need to specify the profile we are going to use, we can
* just call create_datawriter passing DDS_DATAWRITER_QOS_DEFAULT. */
DDSDataWriter *writer_volatile = publisher->create_datawriter(
topic,
DDS_DATAWRITER_QOS_DEFAULT, /* Default datawriter_qos */
NULL /* listener */,
DDS_STATUS_MASK_NONE);
if (writer_volatile == NULL) {
return shutdown_participant(
participant,
"create_datawriter error",
EXIT_FAILURE);
}
/* Transient Local writer -- In this case we use
* create_datawriter_with_profile, because we have to use a profile other
* than the default one. This profile has been defined in
* my_custom_qos_profiles.xml, but since we already loaded the XML file
* we don't need to specify anything else. */
DDSDataWriter *writer_transient_local =
publisher->create_datawriter_with_profile(
topic, /* DDS_Topic* */
"profiles_Library", /* library_name */
"transient_local_profile", /* profile_name */
NULL /* listener */,
DDS_STATUS_MASK_NONE /* DDS_StatusMask */
);
if (writer_transient_local == NULL) {
return shutdown_participant(
participant,
"create_datawriter error",
EXIT_FAILURE);
}
profilesDataWriter *typed_writer_volatile =
profilesDataWriter::narrow(writer_volatile);
if (typed_writer_volatile == NULL) {
return shutdown_participant(
participant,
"DataWriter narrow error",
EXIT_FAILURE);
}
profilesDataWriter *typed_writer_transient_local =
profilesDataWriter::narrow(writer_transient_local);
if (typed_writer_transient_local == NULL) {
return shutdown_participant(
participant,
"DataWriter narrow error",
EXIT_FAILURE);
}
// Create data for writing, allocating all members
profiles *data = profilesTypeSupport::create_data();
if (data == NULL) {
return shutdown_participant(
participant,
"profilesTypeSupport::create_data error",
EXIT_FAILURE);
}
// Main loop, write data
for (unsigned int samples_written = 0;
!shutdown_requested && samples_written < sample_count;
++samples_written) {
// Modify the data to be sent here
strcpy(data->profile_name, "volatile_profile");
data->x = samples_written;
std::cout << "Writing profile_name = " << data->profile_name
<< ",\t x = " << data->x << std::endl;
retcode = typed_writer_volatile->write(*data, DDS_HANDLE_NIL);
if (retcode != DDS_RETCODE_OK) {
std::cerr << "write error " << retcode << std::endl;
}
strcpy(data->profile_name, "transient_local_profile");
data->x = samples_written;
std::cout << "Writing profile_name = " << data->profile_name
<< ",\t x = " << data->x << std::endl;
retcode = typed_writer_transient_local->write(*data, DDS_HANDLE_NIL);
if (retcode != DDS_RETCODE_OK) {
std::cerr << "write error " << retcode << std::endl;
}
NDDSUtility::sleep(send_period);
}
/* Delete data sample */
retcode = profilesTypeSupport::delete_data(data);
if (retcode != DDS_RETCODE_OK) {
std::cerr << "profilesTypeSupport::delete_data error " << retcode
<< std::endl;
}
// Delete all entities (DataWriter, Topic, Publisher, DomainParticipant)
return shutdown_participant(participant, "Shutting down", EXIT_SUCCESS);
}
// Delete all entities
static int shutdown_participant(
DDSDomainParticipant *participant,
const char *shutdown_message,
int status)
{
DDS_ReturnCode_t retcode;
std::cout << shutdown_message << std::endl;
if (participant != NULL) {
// Cleanup everything created by this Participant
retcode = participant->delete_contained_entities();
if (retcode != DDS_RETCODE_OK) {
std::cerr << "delete_contained_entities error " << retcode
<< std::endl;
status = EXIT_FAILURE;
}
retcode = DDSTheParticipantFactory->delete_participant(participant);
if (retcode != DDS_RETCODE_OK) {
std::cerr << "delete_participant error " << retcode << std::endl;
status = EXIT_FAILURE;
}
}
return status;
}
int main(int argc, char *argv[])
{
// Parse arguments and handle control-C
ApplicationArguments arguments;
parse_arguments(arguments, argc, argv, publisher);
if (arguments.parse_result == PARSE_RETURN_EXIT) {
return EXIT_SUCCESS;
} else if (arguments.parse_result == PARSE_RETURN_FAILURE) {
return EXIT_FAILURE;
}
setup_signal_handlers();
// Sets Connext verbosity to help debugging
NDDSConfigLogger::get_instance()->set_verbosity(arguments.verbosity);
int status = run_publisher_application(
arguments.domain_id,
arguments.sample_count);
// Releases the memory used by the participant factory. Optional at
// application exit
DDS_ReturnCode_t retcode = DDSDomainParticipantFactory::finalize_instance();
if (retcode != DDS_RETCODE_OK) {
std::cerr << "finalize_instance error " << retcode << std::endl;
status = EXIT_FAILURE;
}
return status;
}
| cxx |
rticonnextdds-examples | data/projects/rticonnextdds-examples/connext_dds/using_qos_profiles/c++98/application.h | /*
* (c) Copyright, Real-Time Innovations, 2020. All rights reserved.
* RTI grants Licensee a license to use, modify, compile, and create derivative
* works of the software solely for use with RTI Connext DDS. Licensee may
* redistribute copies of the software provided that all such copies are subject
* to this license. The software is provided "as is", with no warranty of any
* type, including any warranty for fitness for any purpose. RTI is under no
* obligation to maintain or support the software. RTI shall not be liable for
* any incidental or consequential damages arising out of the use or inability
* to use the software.
*/
#ifndef APPLICATION_H
#define APPLICATION_H
#include <iostream>
#include <csignal>
#include <climits>
namespace application {
// Catch control-C and tell application to shut down
bool shutdown_requested = false;
inline void stop_handler(int)
{
shutdown_requested = true;
std::cout << "preparing to shut down..." << std::endl;
}
inline void setup_signal_handlers()
{
signal(SIGINT, stop_handler);
signal(SIGTERM, stop_handler);
}
enum ParseReturn { PARSE_RETURN_OK, PARSE_RETURN_FAILURE, PARSE_RETURN_EXIT };
enum ApplicationKind { publisher, subscriber };
struct ApplicationArguments {
ParseReturn parse_result;
unsigned int domain_id;
unsigned int sample_count;
NDDS_Config_LogVerbosity verbosity;
};
inline void set_verbosity(ApplicationArguments &arguments, int verbosity)
{
switch (verbosity) {
case 0:
arguments.verbosity = NDDS_CONFIG_LOG_VERBOSITY_SILENT;
break;
case 1:
arguments.verbosity = NDDS_CONFIG_LOG_VERBOSITY_ERROR;
break;
case 2:
arguments.verbosity = NDDS_CONFIG_LOG_VERBOSITY_WARNING;
break;
case 3:
arguments.verbosity = NDDS_CONFIG_LOG_VERBOSITY_STATUS_ALL;
break;
default:
arguments.verbosity = NDDS_CONFIG_LOG_VERBOSITY_ERROR;
break;
}
}
// Parses application arguments for example. Returns whether to exit.
inline void parse_arguments(
ApplicationArguments &arguments,
int argc,
char *argv[],
ApplicationKind current_application)
{
int arg_processing = 1;
bool show_usage = false;
arguments.domain_id = 0;
arguments.sample_count = INT_MAX;
arguments.verbosity = NDDS_CONFIG_LOG_VERBOSITY_ERROR;
arguments.parse_result = PARSE_RETURN_OK;
while (arg_processing < argc) {
if ((argc > arg_processing + 1)
&& (strcmp(argv[arg_processing], "-d") == 0
|| strcmp(argv[arg_processing], "--domain") == 0)) {
arguments.domain_id = atoi(argv[arg_processing + 1]);
arg_processing += 2;
} else if (
(argc > arg_processing + 1)
&& (strcmp(argv[arg_processing], "-s") == 0
|| strcmp(argv[arg_processing], "--sample-count") == 0
|| strcmp(argv[arg_processing], "--sleep-periods") == 0)) {
arguments.sample_count = atoi(argv[arg_processing + 1]);
arg_processing += 2;
} else if (
(argc > arg_processing + 1)
&& (strcmp(argv[arg_processing], "-v") == 0
|| strcmp(argv[arg_processing], "--verbosity") == 0)) {
set_verbosity(arguments, atoi(argv[arg_processing + 1]));
arg_processing += 2;
} else if (
strcmp(argv[arg_processing], "-h") == 0
|| strcmp(argv[arg_processing], "--help") == 0) {
std::cout << "Example application." << std::endl;
show_usage = true;
arguments.parse_result = PARSE_RETURN_EXIT;
break;
} else {
std::cout << "Bad parameter." << std::endl;
show_usage = true;
arguments.parse_result = PARSE_RETURN_FAILURE;
break;
}
}
if (show_usage) {
std::cout << "Usage:\n"
" -d, --domain <int> Domain ID this "
"application will\n"
" subscribe in. \n"
" Default: 0\n";
if (current_application == publisher) {
std::cout << " -s, --sample-count <int> Number of samples to "
"receive before\n"
" cleanly shutting "
"down. \n"
" Default: infinite\n";
} else if (current_application == subscriber) {
std::cout << " -s, --sleep-periods <int> Number of sleeps "
"before cleanly\n"
" shutting down. \n"
" Default: infinite\n";
}
std::cout << " -v, --verbosity <int> How much debugging output "
"to show.\n"
" Range: 0-3 \n"
" Default: 1"
<< std::endl;
}
}
} // namespace application
#endif // APPLICATION_H
| h |
rticonnextdds-examples | data/projects/rticonnextdds-examples/connext_dds/using_qos_profiles/c/profiles_publisher.c | /*******************************************************************************
(c) 2005-2014 Copyright, Real-Time Innovations, Inc. All rights reserved.
RTI grants Licensee a license to use, modify, compile, and create derivative
works of the Software. Licensee has the right to distribute object form only
for use with RTI products. The Software is provided "as is", with no warranty
of any type, including any warranty for fitness for any purpose. RTI is under
no obligation to maintain or support the Software. RTI shall not be liable for
any incidental or consequential damages arising out of the use or inability to
use the software.
******************************************************************************/
/* profiles_publisher.c
A publication of data of type profiles
This file is derived from code automatically generated by the rtiddsgen
command:
rtiddsgen -language C -example <arch> profiles.idl
Example publication of type profiles automatically generated by
'rtiddsgen'. To test them follow these steps:
(1) Compile this file and the example subscription.
(2) Start the subscription with the command
objs/<arch>/profiles_subscriber <domain_id> <sample_count>
(3) Start the publication with the command
objs/<arch>/profiles_publisher <domain_id> <sample_count>
(4) [Optional] Specify the list of discovery initial peers and
multicast receive addresses via an environment variable or a file
(in the current working directory) called NDDS_DISCOVERY_PEERS.
You can run any number of publishers and subscribers programs, and can
add and remove them dynamically from the domain.
Example:
To run the example application on domain <domain_id>:
On Unix:
objs/<arch>/profiles_publisher <domain_id>
objs/<arch>/profiles_subscriber <domain_id>
On Windows:
objs\<arch>\profiles_publisher <domain_id>
objs\<arch>\profiles_subscriber <domain_id>
modification history
------------ -------
*/
#include "ndds/ndds_c.h"
#include "profiles.h"
#include "profilesSupport.h"
#include <stdio.h>
#include <stdlib.h>
#define NUM_PROFILE_FILES 1
/* Delete all entities */
static int publisher_shutdown(
DDS_DomainParticipant *participant,
struct DDS_DomainParticipantFactoryQos *factory_qos)
{
DDS_ReturnCode_t retcode;
int status = 0;
retcode = DDS_DomainParticipantFactoryQos_finalize(factory_qos);
if (retcode != DDS_RETCODE_OK) {
printf("FactoryQos_finalize error %d\n", retcode);
status = -1;
}
if (participant != NULL) {
retcode = DDS_DomainParticipant_delete_contained_entities(participant);
if (retcode != DDS_RETCODE_OK) {
printf("delete_contained_entities error %d\n", retcode);
status = -1;
}
retcode = DDS_DomainParticipantFactory_delete_participant(
DDS_TheParticipantFactory,
participant);
if (retcode != DDS_RETCODE_OK) {
printf("delete_participant error %d\n", retcode);
status = -1;
}
}
/* RTI Connext provides finalize_instance() method on
domain participant factory for people who want to release memory used
by the participant factory. Uncomment the following block of code for
clean destruction of the singleton. */
/*
retcode = DDS_DomainParticipantFactory_finalize_instance();
if (retcode != DDS_RETCODE_OK) {
printf("finalize_instance error %d\n", retcode);
status = -1;
}
*/
return status;
}
static int publisher_main(int domainId, int sample_count)
{
DDS_DomainParticipant *participant = NULL;
DDS_Publisher *publisher = NULL;
DDS_Topic *topic = NULL;
/* Volatile and transient local writers and profilesDataWriters */
DDS_DataWriter *writer_volatile = NULL;
DDS_DataWriter *writer_transient_local = NULL;
profilesDataWriter *profiles_writer_volatile = NULL;
profilesDataWriter *profiles_writer_transient_local = NULL;
profiles *instance = NULL;
DDS_ReturnCode_t retcode;
DDS_InstanceHandle_t instance_handle = DDS_HANDLE_NIL;
const char *type_name = NULL;
int count = 0;
/* Send a new sample every second */
struct DDS_Duration_t send_period = { 1, 0 };
struct DDS_DomainParticipantFactoryQos factory_qos =
DDS_DomainParticipantFactoryQos_INITIALIZER;
static const char *myUrlProfile[NUM_PROFILE_FILES] = {
"file://./my_custom_qos_profiles.xml"
};
/* There are several different approaches for loading QoS profiles from XML
* files (see Configuring QoS with XML chapter in the RTI Connext Core
* Libraries and Utilities User's Manual). In this example we illustrate
* two of them:
*
* 1) Creating a file named USER_QOS_PROFILES.xml, which is loaded,
* automatically by the DomainParticipantFactory. In this case, the file
* defines a QoS profile named volatile_profile that configures reliable,
* volatile DataWriters and DataReaders.
*
* 2) Adding XML documents to the DomainParticipantFactory using its
* Profile QoSPolicy (DDS Extension). In this case, we add
* my_custom_qos_profiles.xml to the url_profile sequence, which stores
* the URLs of all the XML documents with QoS policies that are loaded by
* the DomainParticipantFactory aside from the ones that are automatically
* loaded.
* my_custom_qos_profiles.xml defines a QoS profile named
* transient_local_profile that configures reliable, transient local
* DataWriters and DataReaders.
*/
/* To load my_custom_qos_profiles.xml, as explained above, we need to modify
* the DDSTheParticipantFactory Profile QoSPolicy */
DDS_DomainParticipantFactory_get_qos(
DDS_TheParticipantFactory,
&factory_qos);
/* We are only going to add one XML file to the url_profile sequence, so our
* NUM_PROFILE_FILES is 1 (defined at start) */
DDS_StringSeq_from_array(
&(factory_qos.profile.url_profile),
(const char **) myUrlProfile,
NUM_PROFILE_FILES);
/* The XML file will be loaded from the working directory. That means, you
* need to run the example like this:
* ./objs/<architecture>/profiles_publisher
* (see README.txt for more information on how to run the example).
*
* Note that you can specify the absolute path of the XML QoS file to avoid
* this problem.
*/
retcode = DDS_DomainParticipantFactory_set_qos(
DDS_TheParticipantFactory,
&factory_qos);
if (retcode != DDS_RETCODE_OK) {
printf("set_qos error %d\n", retcode);
publisher_shutdown(participant, &factory_qos);
return -1;
}
/* Our default Qos profile, volatile_profile, sets the participant name.
* This is the only participant_qos policy that we change in our
* example. As this is done in the default QoS profile, we don't need
* to specify its name, so we can create the participant using the
* create_participant() method rather than using
* create_participant_with_profile(). */
participant = DDS_DomainParticipantFactory_create_participant(
DDS_TheParticipantFactory,
domainId,
&DDS_PARTICIPANT_QOS_DEFAULT,
NULL /* listener */,
DDS_STATUS_MASK_NONE);
if (participant == NULL) {
printf("create_participant error\n");
publisher_shutdown(participant, &factory_qos);
return -1;
}
/* We haven't changed the publisher_qos in any of QoS profiles we use in
* this example, so we can just use the create_publisher() method. If you
* want to load an specific profile in which you may have changed the
* publisher_qos, use the create_publisher_with_profile() method. */
publisher = DDS_DomainParticipant_create_publisher(
participant,
&DDS_PUBLISHER_QOS_DEFAULT,
NULL /* listener */,
DDS_STATUS_MASK_NONE);
if (publisher == NULL) {
printf("create_publisher error\n");
publisher_shutdown(participant, &factory_qos);
return -1;
}
/* Register type before creating topic */
type_name = profilesTypeSupport_get_type_name();
retcode = profilesTypeSupport_register_type(participant, type_name);
if (retcode != DDS_RETCODE_OK) {
printf("register_type error %d\n", retcode);
publisher_shutdown(participant, &factory_qos);
return -1;
}
/* We haven't changed the topic_qos in any of QoS profiles we use in this
* example, so we can just use the create_topic() method. If you want to
* load an specific profile in which you may have changed the topic_qos,
* use the create_topic_with_profile() method. */
topic = DDS_DomainParticipant_create_topic(
participant,
"Example profiles",
type_name,
&DDS_TOPIC_QOS_DEFAULT,
NULL /* listener */,
DDS_STATUS_MASK_NONE);
if (topic == NULL) {
printf("create_topic error\n");
publisher_shutdown(participant, &factory_qos);
return -1;
}
/* Volatile writer -- As volatile_profile is the default qos profile
* we don't need to specify the profile we are going to use, we can
* just call create_datawriter passing DDS_DATAWRITER_QOS_DEFAULT. */
writer_volatile = DDS_Publisher_create_datawriter(
publisher,
topic,
&DDS_DATAWRITER_QOS_DEFAULT, /* Default datawriter_qos */
NULL /* listener */,
DDS_STATUS_MASK_NONE);
if (writer_volatile == NULL) {
printf("create_datawriter error\n");
publisher_shutdown(participant, &factory_qos);
return -1;
}
/* Transient Local writer -- In this case we use
* create_datawriter_with_profile, because we have to use a profile other
* than the default one. This profile has been defined in
* my_custom_qos_profiles.xml, but since we already loaded the XML file
* we don't need to specify anything else. */
writer_transient_local = DDS_Publisher_create_datawriter_with_profile(
publisher, /* publisher which creates the writer */
topic, /* DDS_topic */
"profiles_Library", /* library_name */
"transient_local_profile", /*profile_name */
NULL /* listener */,
DDS_STATUS_MASK_NONE);
if (writer_transient_local == NULL) {
printf("create_datawriter_with_profile error\n");
publisher_shutdown(participant, &factory_qos);
return -1;
}
profiles_writer_volatile = profilesDataWriter_narrow(writer_volatile);
if (profiles_writer_volatile == NULL) {
printf("DataWriter narrow error\n");
publisher_shutdown(participant, &factory_qos);
return -1;
}
profiles_writer_transient_local =
profilesDataWriter_narrow(writer_transient_local);
if (profiles_writer_transient_local == NULL) {
printf("DataWriter narrow error\n");
publisher_shutdown(participant, &factory_qos);
return -1;
}
/* Create data sample for writing */
instance = profilesTypeSupport_create_data_ex(DDS_BOOLEAN_TRUE);
if (instance == NULL) {
printf("profilesTypeSupport_create_data error\n");
publisher_shutdown(participant, &factory_qos);
return -1;
}
/* For a data type that has a key, if the same instance is going to be
written multiple times, initialize the key here
and register the keyed instance prior to writing */
/*
instance_handle = profilesDataWriter_register_instance(
profiles_writer, instance);
*/
/* Main loop */
for (count = 0; (sample_count == 0) || (count < sample_count); ++count) {
printf("Writing profiles, count %d\n", count);
/* Modify the data to be written here */
strcpy(instance->profile_name, "volatile_profile");
instance->x = count;
printf("Writing profile_name = %s,\t x = %d\n",
instance->profile_name,
instance->x);
retcode = profilesDataWriter_write(
profiles_writer_volatile,
instance,
&instance_handle);
if (retcode != DDS_RETCODE_OK) {
printf("write error %d\n", retcode);
}
strcpy(instance->profile_name, "transient_local_profile");
instance->x = count;
printf("Writing profile_name = %s,\t x = %d\n\n",
instance->profile_name,
instance->x);
retcode = profilesDataWriter_write(
profiles_writer_transient_local,
instance,
&instance_handle);
if (retcode != DDS_RETCODE_OK) {
printf("write error %d\n", retcode);
}
NDDS_Utility_sleep(&send_period);
}
/*
retcode = profilesDataWriter_unregister_instance(
profiles_writer, instance, &instance_handle);
if (retcode != DDS_RETCODE_OK) {
printf("unregister instance error %d\n", retcode);
}
*/
/* Delete data sample */
retcode = profilesTypeSupport_delete_data_ex(instance, DDS_BOOLEAN_TRUE);
if (retcode != DDS_RETCODE_OK) {
printf("profilesTypeSupport_delete_data error %d\n", retcode);
}
/* Cleanup and delete delete all entities */
return publisher_shutdown(participant, &factory_qos);
}
#if defined(RTI_WINCE)
int wmain(int argc, wchar_t **argv)
{
int domainId = 0;
int sample_count = 0; /* infinite loop */
if (argc >= 2) {
domainId = _wtoi(argv[1]);
}
if (argc >= 3) {
sample_count = _wtoi(argv[2]);
}
/* Uncomment this to turn on additional logging
NDDS_Config_Logger_set_verbosity_by_category(
NDDS_Config_Logger_get_instance(),
NDDS_CONFIG_LOG_CATEGORY_API,
NDDS_CONFIG_LOG_VERBOSITY_STATUS_ALL);
*/
return publisher_main(domainId, sample_count);
}
#elif !(defined(RTI_VXWORKS) && !defined(__RTP__)) && !defined(RTI_PSOS)
int main(int argc, char *argv[])
{
int domainId = 0;
int sample_count = 0; /* infinite loop */
if (argc >= 2) {
domainId = atoi(argv[1]);
}
if (argc >= 3) {
sample_count = atoi(argv[2]);
}
/* Uncomment this to turn on additional logging
NDDS_Config_Logger_set_verbosity_by_category(
NDDS_Config_Logger_get_instance(),
NDDS_CONFIG_LOG_CATEGORY_API,
NDDS_CONFIG_LOG_VERBOSITY_STATUS_ALL);
*/
return publisher_main(domainId, sample_count);
}
#endif
#ifdef RTI_VX653
const unsigned char *__ctype = NULL;
void usrAppInit()
{
#ifdef USER_APPL_INIT
USER_APPL_INIT; /* for backwards compatibility */
#endif
/* add application specific code here */
taskSpawn(
"pub",
RTI_OSAPI_THREAD_PRIORITY_NORMAL,
0x8,
0x150000,
(FUNCPTR) publisher_main,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0);
}
#endif
| c |
rticonnextdds-examples | data/projects/rticonnextdds-examples/connext_dds/using_qos_profiles/c/profiles_subscriber.c | /*******************************************************************************
(c) 2005-2014 Copyright, Real-Time Innovations, Inc. All rights reserved.
RTI grants Licensee a license to use, modify, compile, and create derivative
works of the Software. Licensee has the right to distribute object form only
for use with RTI products. The Software is provided "as is", with no warranty
of any type, including any warranty for fitness for any purpose. RTI is under
no obligation to maintain or support the Software. RTI shall not be liable for
any incidental or consequential damages arising out of the use or inability to
use the software.
******************************************************************************/
/* profiles_subscriber.c
A subscription example
This file is derived from code automatically generated by the rtiddsgen
command:
rtiddsgen -language C -example <arch> profiles.idl
Example subscription of type profiles automatically generated by
'rtiddsgen'. To test them, follow these steps:
(1) Compile this file and the example publication.
(2) Start the subscription with the command
objs/<arch>/profiles_subscriber <domain_id> <sample_count>
(3) Start the publication with the command
objs/<arch>/profiles_publisher <domain_id> <sample_count>
(4) [Optional] Specify the list of discovery initial peers and
multicast receive addresses via an environment variable or a file
(in the current working directory) called NDDS_DISCOVERY_PEERS.
You can run any number of publishers and subscribers programs, and can
add and remove them dynamically from the domain.
Example:
To run the example application on domain <domain_id>:
On UNIX systems:
objs/<arch>/profiles_publisher <domain_id>
objs/<arch>/profiles_subscriber <domain_id>
On Windows systems:
objs\<arch>\profiles_publisher <domain_id>
objs\<arch>\profiles_subscriber <domain_id>
modification history
------------ -------
*/
#include "ndds/ndds_c.h"
#include "profiles.h"
#include "profilesSupport.h"
#include <stdio.h>
#include <stdlib.h>
#define NUM_PROFILE_FILES 1
void profilesListener_on_requested_deadline_missed(
void *listener_data,
DDS_DataReader *reader,
const struct DDS_RequestedDeadlineMissedStatus *status)
{
}
void profilesListener_on_requested_incompatible_qos(
void *listener_data,
DDS_DataReader *reader,
const struct DDS_RequestedIncompatibleQosStatus *status)
{
}
void profilesListener_on_sample_rejected(
void *listener_data,
DDS_DataReader *reader,
const struct DDS_SampleRejectedStatus *status)
{
}
void profilesListener_on_liveliness_changed(
void *listener_data,
DDS_DataReader *reader,
const struct DDS_LivelinessChangedStatus *status)
{
}
void profilesListener_on_sample_lost(
void *listener_data,
DDS_DataReader *reader,
const struct DDS_SampleLostStatus *status)
{
}
void profilesListener_on_subscription_matched(
void *listener_data,
DDS_DataReader *reader,
const struct DDS_SubscriptionMatchedStatus *status)
{
}
void profilesListener_on_data_available(
void *listener_data,
DDS_DataReader *reader)
{
profilesDataReader *profiles_reader = NULL;
struct profilesSeq data_seq = DDS_SEQUENCE_INITIALIZER;
struct DDS_SampleInfoSeq info_seq = DDS_SEQUENCE_INITIALIZER;
DDS_ReturnCode_t retcode;
int i;
profiles_reader = profilesDataReader_narrow(reader);
if (profiles_reader == NULL) {
printf("DataReader narrow error\n");
return;
}
retcode = profilesDataReader_take(
profiles_reader,
&data_seq,
&info_seq,
DDS_LENGTH_UNLIMITED,
DDS_ANY_SAMPLE_STATE,
DDS_ANY_VIEW_STATE,
DDS_ANY_INSTANCE_STATE);
if (retcode == DDS_RETCODE_NO_DATA) {
return;
} else if (retcode != DDS_RETCODE_OK) {
printf("take error %d\n", retcode);
return;
}
printf("=============================================\n");
printf("listener received\n");
printf("=============================================\n");
for (i = 0; i < profilesSeq_get_length(&data_seq); ++i) {
if (DDS_SampleInfoSeq_get_reference(&info_seq, i)->valid_data) {
profilesTypeSupport_print_data(
profilesSeq_get_reference(&data_seq, i));
}
}
retcode = profilesDataReader_return_loan(
profiles_reader,
&data_seq,
&info_seq);
if (retcode != DDS_RETCODE_OK) {
printf("return loan error %d\n", retcode);
}
}
/* Delete all entities */
static int subscriber_shutdown(
DDS_DomainParticipant *participant,
struct DDS_DomainParticipantFactoryQos *factory_qos)
{
DDS_ReturnCode_t retcode;
int status = 0;
retcode = DDS_DomainParticipantFactoryQos_finalize(factory_qos);
if (retcode != DDS_RETCODE_OK) {
printf("FactoryQos_finalize error %d\n", retcode);
status = -1;
}
if (participant != NULL) {
retcode = DDS_DomainParticipant_delete_contained_entities(participant);
if (retcode != DDS_RETCODE_OK) {
printf("delete_contained_entities error %d\n", retcode);
status = -1;
}
retcode = DDS_DomainParticipantFactory_delete_participant(
DDS_TheParticipantFactory,
participant);
if (retcode != DDS_RETCODE_OK) {
printf("delete_participant error %d\n", retcode);
status = -1;
}
}
/* RTI Connext provides the finalize_instance() method on
domain participant factory for users who want to release memory used
by the participant factory. Uncomment the following block of code for
clean destruction of the singleton. */
/*
retcode = DDS_DomainParticipantFactory_finalize_instance();
if (retcode != DDS_RETCODE_OK) {
printf("finalize_instance error %d\n", retcode);
status = -1;
}
*/
return status;
}
static int subscriber_main(int domainId, int sample_count)
{
DDS_DomainParticipant *participant = NULL;
DDS_Subscriber *subscriber = NULL;
DDS_Topic *topic = NULL;
struct DDS_DataReaderListener reader_volatile_listener =
DDS_DataReaderListener_INITIALIZER;
struct DDS_DataReaderListener reader_transient_local_listener =
DDS_DataReaderListener_INITIALIZER;
DDS_DataReader *reader_volatile = NULL;
DDS_DataReader *reader_transient_local = NULL;
DDS_ReturnCode_t retcode;
const char *type_name = NULL;
int count = 0;
struct DDS_Duration_t poll_period = { 1, 0 };
int status = 0;
struct DDS_DomainParticipantFactoryQos factory_qos =
DDS_DomainParticipantFactoryQos_INITIALIZER;
static const char *myUrlProfile[NUM_PROFILE_FILES] = {
"file://./my_custom_qos_profiles.xml"
};
/* There are several different approaches for loading QoS profiles from XML
* files (see Configuring QoS with XML chapter in the RTI Connext Core
* Libraries and Utilities User's Manual). In this example we illustrate
* two of them:
*
* 1) Creating a file named USER_QOS_PROFILES.xml, which is loaded,
* automatically by the DomainParticipantFactory. In this case, the file
* defines a QoS profile named volatile_profile that configures reliable,
* volatile DataWriters and DataReaders.
*
* 2) Adding XML documents to the DomainParticipantFactory using its
* Profile QoSPolicy (DDS Extension). In this case, we add
* my_custom_qos_profiles.xml to the url_profile sequence, which stores
* the URLs of all the XML documents with QoS policies that are loaded by
* the DomainParticipantFactory aside from the ones that are automatically
* loaded.
* my_custom_qos_profiles.xml defines a QoS profile named
* transient_local_profile that configures reliable, transient local
* DataWriters and DataReaders.
*/
/* To load my_custom_qos_profiles.xml, as explained above, we need to modify
* the DDSTheParticipantFactory Profile QoSPolicy */
DDS_DomainParticipantFactory_get_qos(
DDS_TheParticipantFactory,
&factory_qos);
/* We are only going to add one XML file to the url_profile sequence, so our
* NUM_PROFILE_FILES is 1 (defined at start) */
DDS_StringSeq_from_array(
&(factory_qos.profile.url_profile),
(const char **) myUrlProfile,
NUM_PROFILE_FILES);
/* The XML file will be loaded from the working directory. That means, you
* need to run the example like this:
* ./objs/<architecture>/profiles_publisher
* (see README.txt for more information on how to run the example).
*
* Note that you can specify the absolute path of the XML QoS file to avoid
* this problem.
*/
retcode = DDS_DomainParticipantFactory_set_qos(
DDS_TheParticipantFactory,
&factory_qos);
if (retcode != DDS_RETCODE_OK) {
printf("set_qos error %d\n", retcode);
subscriber_shutdown(participant, &factory_qos);
return -1;
}
/* Our default Qos profile, volatile_profile, sets the participant name.
* This is the only participant_qos policy that we change in our
* example. As this is done in the default QoS profile, we don't need
* to specify its name, so we can create the participant using the
* create_participant() method rather than using
* create_participant_with_profile(). */
participant = DDS_DomainParticipantFactory_create_participant(
DDS_TheParticipantFactory,
domainId,
&DDS_PARTICIPANT_QOS_DEFAULT,
NULL /* listener */,
DDS_STATUS_MASK_NONE);
if (participant == NULL) {
printf("create_participant error\n");
subscriber_shutdown(participant, &factory_qos);
return -1;
}
/* We haven't changed the subscriber_qos in any of QoS profiles we use in
* this example, so we can just use the create_topic() method. If you want
* to load an specific profile in which you may have changed the
* publisher_qos, use the create_publisher_with_profile() method. */
subscriber = DDS_DomainParticipant_create_subscriber(
participant,
&DDS_SUBSCRIBER_QOS_DEFAULT,
NULL /* listener */,
DDS_STATUS_MASK_NONE);
if (subscriber == NULL) {
printf("create_subscriber error\n");
subscriber_shutdown(participant, &factory_qos);
return -1;
}
/* Register the type before creating the topic */
type_name = profilesTypeSupport_get_type_name();
retcode = profilesTypeSupport_register_type(participant, type_name);
if (retcode != DDS_RETCODE_OK) {
printf("register_type error %d\n", retcode);
subscriber_shutdown(participant, &factory_qos);
return -1;
}
/* We haven't changed the topic_qos in any of QoS profiles we use in this
* example, so we can just use the create_topic() method. If you want to
* load an specific profile in which you may have changed the topic_qos,
* use the create_topic_with_profile() method. */
topic = DDS_DomainParticipant_create_topic(
participant,
"Example profiles",
type_name,
&DDS_TOPIC_QOS_DEFAULT,
NULL /* listener */,
DDS_STATUS_MASK_NONE);
if (topic == NULL) {
printf("create_topic error\n");
subscriber_shutdown(participant, &factory_qos);
return -1;
}
/* Set up a data reader listener */
reader_volatile_listener.on_requested_deadline_missed =
profilesListener_on_requested_deadline_missed;
reader_volatile_listener.on_requested_incompatible_qos =
profilesListener_on_requested_incompatible_qos;
reader_volatile_listener.on_sample_rejected =
profilesListener_on_sample_rejected;
reader_volatile_listener.on_liveliness_changed =
profilesListener_on_liveliness_changed;
reader_volatile_listener.on_sample_lost = profilesListener_on_sample_lost;
reader_volatile_listener.on_subscription_matched =
profilesListener_on_subscription_matched;
reader_volatile_listener.on_data_available =
profilesListener_on_data_available;
reader_transient_local_listener.on_requested_deadline_missed =
profilesListener_on_requested_deadline_missed;
reader_transient_local_listener.on_requested_incompatible_qos =
profilesListener_on_requested_incompatible_qos;
reader_transient_local_listener.on_sample_rejected =
profilesListener_on_sample_rejected;
reader_transient_local_listener.on_liveliness_changed =
profilesListener_on_liveliness_changed;
reader_transient_local_listener.on_sample_lost =
profilesListener_on_sample_lost;
reader_transient_local_listener.on_subscription_matched =
profilesListener_on_subscription_matched;
reader_transient_local_listener.on_data_available =
profilesListener_on_data_available;
/* Volatile reader -- As volatile_profile is the default qos profile
* we don't need to specify the profile we are going to use, we can
* just call create_datareader passing DDS_DATAWRITER_QOS_DEFAULT. */
reader_volatile = DDS_Subscriber_create_datareader(
subscriber,
DDS_Topic_as_topicdescription(topic),
&DDS_DATAREADER_QOS_DEFAULT,
&reader_volatile_listener,
DDS_STATUS_MASK_ALL);
if (reader_volatile == NULL) {
printf("create_datareader error\n");
subscriber_shutdown(participant, &factory_qos);
return -1;
}
/* Transient Local writer -- In this case we use
* create_datareader_with_profile, because we have to use a profile other
* than the default one. This profile has been defined in
* my_custom_qos_profiles.xml, but since we already loaded the XML file
* we don't need to specify anything else. */
reader_transient_local = DDS_Subscriber_create_datareader_with_profile(
subscriber,
DDS_Topic_as_topicdescription(topic),
"profiles_Library", /* library_name */
"transient_local_profile", /* profile_name */
&reader_transient_local_listener, /* listener */
DDS_STATUS_MASK_ALL);
if (reader_transient_local == NULL) {
printf("create_datareader error\n");
subscriber_shutdown(participant, &factory_qos);
return -1;
}
/* Main loop */
for (count = 0; (sample_count == 0) || (count < sample_count); ++count) {
printf("profiles subscriber sleeping for %d sec...\n", poll_period.sec);
NDDS_Utility_sleep(&poll_period);
}
/* Cleanup and delete all entities */
return subscriber_shutdown(participant, &factory_qos);
}
#if defined(RTI_WINCE)
int wmain(int argc, wchar_t **argv)
{
int domainId = 0;
int sample_count = 0; /* infinite loop */
if (argc >= 2) {
domainId = _wtoi(argv[1]);
}
if (argc >= 3) {
sample_count = _wtoi(argv[2]);
}
/* Uncomment this to turn on additional logging
NDDS_Config_Logger_set_verbosity_by_category(
NDDS_Config_Logger_get_instance(),
NDDS_CONFIG_LOG_CATEGORY_API,
NDDS_CONFIG_LOG_VERBOSITY_STATUS_ALL);
*/
return subscriber_main(domainId, sample_count);
}
#elif !(defined(RTI_VXWORKS) && !defined(__RTP__)) && !defined(RTI_PSOS)
int main(int argc, char *argv[])
{
int domainId = 0;
int sample_count = 0; /* infinite loop */
if (argc >= 2) {
domainId = atoi(argv[1]);
}
if (argc >= 3) {
sample_count = atoi(argv[2]);
}
/* Uncomment this to turn on additional logging
NDDS_Config_Logger_set_verbosity_by_category(
NDDS_Config_Logger_get_instance(),
NDDS_CONFIG_LOG_CATEGORY_API,
NDDS_CONFIG_LOG_VERBOSITY_STATUS_ALL);
*/
return subscriber_main(domainId, sample_count);
}
#endif
#ifdef RTI_VX653
const unsigned char *__ctype = NULL;
void usrAppInit()
{
#ifdef USER_APPL_INIT
USER_APPL_INIT; /* for backwards compatibility */
#endif
/* add application specific code here */
taskSpawn(
"sub",
RTI_OSAPI_THREAD_PRIORITY_NORMAL,
0x8,
0x150000,
(FUNCPTR) subscriber_main,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0);
}
#endif
| c |
rticonnextdds-examples | data/projects/rticonnextdds-examples/connext_dds/using_qos_profiles/c++03/profiles_subscriber.cxx | /*******************************************************************************
(c) 2005-2015 Copyright, Real-Time Innovations, Inc. All rights reserved.
RTI grants Licensee a license to use, modify, compile, and create derivative
works of the Software. Licensee has the right to distribute object form only
for use with RTI products. The Software is provided "as is", with no warranty
of any type, including any warranty for fitness for any purpose. RTI is under
no obligation to maintain or support the Software. RTI shall not be liable for
any incidental or consequential damages arising out of the use or inability to
use the software.
******************************************************************************/
#include <cstdlib>
#include <iostream>
#include "profiles.hpp"
#include <dds/dds.hpp>
#include <rti/core/ListenerBinder.hpp>
using namespace dds::core;
using namespace dds::core::status;
using namespace dds::domain;
using namespace dds::topic;
using namespace dds::sub;
class ProfilesListener : public NoOpDataReaderListener<profiles> {
public:
ProfilesListener(std::string name) : listener_name_(name)
{
}
void on_data_available(DataReader<profiles> &reader)
{
// Take all samples
LoanedSamples<profiles> samples = reader.take();
std::cout << "============================================="
<< std::endl
<< listener_name() << " listener received" << std::endl;
for (LoanedSamples<profiles>::iterator sample_it = samples.begin();
sample_it != samples.end();
sample_it++) {
if (sample_it->info().valid()) {
std::cout << sample_it->data() << std::endl;
}
}
std::cout << "============================================="
<< std::endl
<< std::endl;
}
std::string listener_name() const
{
return listener_name_;
}
private:
const std::string listener_name_;
};
void subscriber_main(int domain_id, int sample_count)
{
// Retrieve QoS from custom profile XML and USER_QOS_PROFILES.xml
QosProvider qos_provider("my_custom_qos_profiles.xml");
// Create a DomainParticipant with the default QoS of the provider.
DomainParticipant participant(domain_id, qos_provider.participant_qos());
// Create a Subscriber with default QoS.
Subscriber subscriber(participant, qos_provider.subscriber_qos());
// Create a Topic with default QoS.
Topic<profiles> topic(
participant,
"Example profiles",
qos_provider.topic_qos());
// Create a DataWriter with the QoS profile "transient_local_profile" that
// it is inside the QoS library "profiles_Library".
DataReader<profiles> reader_transient_local(
subscriber,
topic,
qos_provider.datareader_qos(
"profiles_Library::transient_local_profile"));
// Use a ListeberBinder to take care of resetting and deleting the listener.
rti::core::ListenerBinder<DataReader<profiles> > scoped_transient_listener =
rti::core::bind_and_manage_listener(
reader_transient_local,
new ProfilesListener("transient_local_profile"),
StatusMask::data_available());
// Create a DataReader with the QoS profile "volatile_profile" that it is
// inside the QoS library "profiles_Library".
DataReader<profiles> reader_volatile(
subscriber,
topic,
qos_provider.datareader_qos("profiles_Library::volatile_profile"));
// Use a ListeberBinder to take care of resetting and deleting the listener.
rti::core::ListenerBinder<DataReader<profiles> > scoped_volatile_listener =
rti::core::bind_and_manage_listener(
reader_volatile,
new ProfilesListener("volatile_profile"),
StatusMask::data_available());
// Main loop.
for (int count = 0; (sample_count == 0) || (count < sample_count);
++count) {
rti::util::sleep(Duration(1));
}
}
int main(int argc, char *argv[])
{
int domain_id = 0;
int sample_count = 0; // Infinite loop
if (argc >= 2) {
domain_id = atoi(argv[1]);
}
if (argc >= 3) {
sample_count = atoi(argv[2]);
}
// To turn on additional logging, include <rti/config/Logger.hpp> and
// uncomment the following line:
// rti::config::Logger::instance().verbosity(rti::config::Verbosity::STATUS_ALL);
try {
subscriber_main(domain_id, sample_count);
} catch (const std::exception &ex) {
// This will catch DDS exceptions
std::cerr << "Exception in subscriber_main: " << ex.what() << std::endl;
return -1;
}
return 0;
}
| cxx |
rticonnextdds-examples | data/projects/rticonnextdds-examples/connext_dds/using_qos_profiles/c++03/profiles_publisher.cxx | /*******************************************************************************
(c) 2005-2015 Copyright, Real-Time Innovations, Inc. All rights reserved.
RTI grants Licensee a license to use, modify, compile, and create derivative
works of the Software. Licensee has the right to distribute object form only
for use with RTI products. The Software is provided "as is", with no warranty
of any type, including any warranty for fitness for any purpose. RTI is under
no obligation to maintain or support the Software. RTI shall not be liable for
any incidental or consequential damages arising out of the use or inability to
use the software.
******************************************************************************/
#include <cstdlib>
#include <iostream>
#include "profiles.hpp"
#include <dds/dds.hpp>
using namespace dds::core;
using namespace dds::domain;
using namespace dds::topic;
using namespace dds::pub;
void publisher_main(int domain_id, int sample_count)
{
// Retrieve QoS from custom profile XML and USER_QOS_PROFILES.xml
QosProvider qos_provider("my_custom_qos_profiles.xml");
// Create a DomainParticipant with the default QoS of the provider.
DomainParticipant participant(domain_id, qos_provider.participant_qos());
// Create a Publisher with default QoS.
Publisher publisher(participant, qos_provider.publisher_qos());
// Create a Topic with default QoS.
Topic<profiles> topic(
participant,
"Example profiles",
qos_provider.topic_qos());
// Create a DataWriter with the QoS profile "transient_local_profile",
// from QoS library "profiles_Library".
DataWriter<profiles> writer_transient_local(
publisher,
topic,
qos_provider.datawriter_qos(
"profiles_Library::transient_local_profile"));
// Create a DataReader with the QoS profile "volatile_profile",
// from the QoS library "profiles_Library".
DataWriter<profiles> writer_volatile(
publisher,
topic,
qos_provider.datawriter_qos("profiles_Library::volatile_profile"));
// Create a data sample for writing.
profiles instance;
// Main loop.
for (int count = 0; (sample_count == 0) || (count < sample_count);
++count) {
// Update the counter value of the sample.
instance.x(count);
// Send the sample using the DataWriter with "volatile" durability.
std::cout << "Writing profile_name = volatile_profile,\t x = " << count
<< std::endl;
instance.profile_name("volatile_profile");
writer_volatile.write(instance);
// Send the sample using the DataWriter with "transient_local"
// durability.
std::cout << "Writing profile_name = transient_local_profile,\t x = "
<< count << std::endl
<< std::endl;
instance.profile_name("transient_local_profile");
writer_transient_local.write(instance);
// Send the sample every second.
rti::util::sleep(Duration(1));
}
}
int main(int argc, char *argv[])
{
int domain_id = 0;
int sample_count = 0; // Infinite loop
if (argc >= 2) {
domain_id = atoi(argv[1]);
}
if (argc >= 3) {
sample_count = atoi(argv[2]);
}
// To turn on additional logging, include <rti/config/Logger.hpp> and
// uncomment the following line:
// rti::config::Logger::instance().verbosity(rti::config::Verbosity::STATUS_ALL);
try {
publisher_main(domain_id, sample_count);
} catch (const std::exception &ex) {
std::cout << "Exception caught: " << ex.what() << std::endl;
return -1;
}
return 0;
}
| cxx |
rticonnextdds-examples | data/projects/rticonnextdds-examples/connext_dds/using_qos_profiles/c++11/application.hpp | /*
* (c) Copyright, Real-Time Innovations, 2020. All rights reserved.
* RTI grants Licensee a license to use, modify, compile, and create derivative
* works of the software solely for use with RTI Connext DDS. Licensee may
* redistribute copies of the software provided that all such copies are subject
* to this license. The software is provided "as is", with no warranty of any
* type, including any warranty for fitness for any purpose. RTI is under no
* obligation to maintain or support the software. RTI shall not be liable for
* any incidental or consequential damages arising out of the use or inability
* to use the software.
*/
#ifndef APPLICATION_HPP
#define APPLICATION_HPP
#include <iostream>
#include <csignal>
#include <dds/core/ddscore.hpp>
namespace application {
// Catch control-C and tell application to shut down
bool shutdown_requested = false;
inline void stop_handler(int)
{
shutdown_requested = true;
std::cout << "preparing to shut down..." << std::endl;
}
inline void setup_signal_handlers()
{
signal(SIGINT, stop_handler);
signal(SIGTERM, stop_handler);
}
enum class ParseReturn { ok, failure, exit };
enum class Entity { Publisher, Subscriber };
struct ApplicationArguments {
ParseReturn parse_result;
unsigned int domain_id;
unsigned int sample_count;
rti::config::Verbosity verbosity;
ApplicationArguments(
ParseReturn parse_result_param,
unsigned int domain_id_param,
unsigned int sample_count_param,
rti::config::Verbosity verbosity_param)
: parse_result(parse_result_param),
domain_id(domain_id_param),
sample_count(sample_count_param),
verbosity(verbosity_param)
{
}
};
inline void set_verbosity(
rti::config::Verbosity &verbosity,
int verbosity_value)
{
switch (verbosity_value) {
case 0:
verbosity = rti::config::Verbosity::SILENT;
break;
case 1:
verbosity = rti::config::Verbosity::EXCEPTION;
break;
case 2:
verbosity = rti::config::Verbosity::WARNING;
break;
case 3:
verbosity = rti::config::Verbosity::STATUS_ALL;
break;
default:
verbosity = rti::config::Verbosity::EXCEPTION;
break;
}
}
// Parses application arguments for example.
inline ApplicationArguments parse_arguments(
int argc,
char *argv[],
Entity current_entity)
{
int arg_processing = 1;
bool show_usage = false;
ParseReturn parse_result = ParseReturn::ok;
unsigned int domain_id = 0;
unsigned int sample_count = (std::numeric_limits<unsigned int>::max)();
rti::config::Verbosity verbosity(rti::config::Verbosity::EXCEPTION);
while (arg_processing < argc) {
if ((argc > arg_processing + 1)
&& (strcmp(argv[arg_processing], "-d") == 0
|| strcmp(argv[arg_processing], "--domain") == 0)) {
domain_id = atoi(argv[arg_processing + 1]);
arg_processing += 2;
} else if (
(argc > arg_processing + 1)
&& current_entity == Entity::Publisher
&& (strcmp(argv[arg_processing], "-s") == 0
|| strcmp(argv[arg_processing], "--sample-count") == 0)) {
sample_count = atoi(argv[arg_processing + 1]);
arg_processing += 2;
} else if (
(argc > arg_processing + 1)
&& current_entity == Entity::Subscriber
&& (strcmp(argv[arg_processing], "-s") == 0
|| strcmp(argv[arg_processing], "--sleeps") == 0)) {
sample_count = atoi(argv[arg_processing + 1]);
arg_processing += 2;
} else if (
(argc > arg_processing + 1)
&& (strcmp(argv[arg_processing], "-v") == 0
|| strcmp(argv[arg_processing], "--verbosity") == 0)) {
set_verbosity(verbosity, atoi(argv[arg_processing + 1]));
arg_processing += 2;
} else if (
strcmp(argv[arg_processing], "-h") == 0
|| strcmp(argv[arg_processing], "--help") == 0) {
std::cout << "Example application." << std::endl;
show_usage = true;
parse_result = ParseReturn::exit;
break;
} else {
std::cout << "Bad parameter." << std::endl;
show_usage = true;
parse_result = ParseReturn::failure;
break;
}
}
if (show_usage) {
std::string usage =
"Usage:\n"
" -d, --domain <int> Domain ID this application "
"will\n"
" subscribe in. \n"
" Default: 0\n";
if (current_entity == Entity::Publisher) {
usage += " -s, --sample_count <int> Number of samples to send "
"before\n"
" cleanly shutting down. \n"
" Default: infinite\n";
} else if (current_entity == Entity::Subscriber) {
usage += " -s, --sleeps <int> Number of sleeps before "
"cleanly\n"
" shutting down. \n"
" Default: infinite\n";
}
usage += " -v, --verbosity <int> How much debugging output to "
"show.\n"
" Range: 0-3 \n"
" Default: 1\n";
std::cout << usage;
}
return ApplicationArguments(
parse_result,
domain_id,
sample_count,
verbosity);
}
} // namespace application
#endif // APPLICATION_HPP
| hpp |
rticonnextdds-examples | data/projects/rticonnextdds-examples/connext_dds/using_qos_profiles/c++11/profiles_subscriber.cxx | /*******************************************************************************
(c) 2005-2015 Copyright, Real-Time Innovations, Inc. All rights reserved.
RTI grants Licensee a license to use, modify, compile, and create derivative
works of the Software. Licensee has the right to distribute object form only
for use with RTI products. The Software is provided "as is", with no warranty
of any type, including any warranty for fitness for any purpose. RTI is under
no obligation to maintain or support the Software. RTI shall not be liable for
any incidental or consequential damages arising out of the use or inability to
use the software.
******************************************************************************/
#include <dds/sub/ddssub.hpp>
#include <dds/core/ddscore.hpp>
#include <rti/util/util.hpp> // for sleep()
#include <rti/config/Logger.hpp> // for logging
#include "profiles.hpp"
#include "application.hpp" // for command line parsing and ctrl-c
class ProfilesListener : public dds::sub::NoOpDataReaderListener<profiles> {
public:
ProfilesListener(std::string name) : listener_name_(name)
{
}
void on_data_available(dds::sub::DataReader<profiles> &reader)
{
// Take all samples
dds::sub::LoanedSamples<profiles> samples = reader.take();
std::cout << "============================================="
<< std::endl
<< listener_name() << " listener received" << std::endl;
for (const auto &sample : samples) {
if (sample.info().valid()) {
std::cout << sample.data() << std::endl;
}
}
std::cout << "============================================="
<< std::endl
<< std::endl;
}
std::string listener_name() const
{
return listener_name_;
}
private:
const std::string listener_name_;
};
void run_subscriber_application(
unsigned int domain_id,
unsigned int sample_count)
{
// Retrieve QoS from custom profile XML and USER_QOS_PROFILES.xml
dds::core::QosProvider qos_provider("my_custom_qos_profiles.xml");
// Create a DomainParticipant with the default QoS of the provider.
dds::domain::DomainParticipant participant(
domain_id,
qos_provider.participant_qos());
// Create a Subscriber with default QoS.
dds::sub::Subscriber subscriber(participant, qos_provider.subscriber_qos());
// Create a Topic with default QoS.
dds::topic::Topic<profiles> topic(
participant,
"Example profiles",
qos_provider.topic_qos());
// Create a shared pointer for the ProfilesListener Class
auto transient_listener =
std::make_shared<ProfilesListener>("transient_local_profile");
// Create a DataWriter with the QoS profile "transient_local_profile" that
// it is inside the QoS library "profiles_Library".
dds::sub::DataReader<profiles> reader_transient_local(
subscriber,
topic,
qos_provider.datareader_qos(
"profiles_Library::transient_local_profile"),
transient_listener);
// Create a shared pointer for the ProfilesListener Class
auto volatile_listener =
std::make_shared<ProfilesListener>("volatile_profile");
// Create a DataReader with the QoS profile "volatile_profile" that it is
// inside the QoS library "profiles_Library".
dds::sub::DataReader<profiles> reader_volatile(
subscriber,
topic,
qos_provider.datareader_qos("profiles_Library::volatile_profile"),
volatile_listener);
// Main loop.
for (unsigned int samples_read = 0;
!application::shutdown_requested && samples_read < sample_count;
samples_read++) {
rti::util::sleep(dds::core::Duration(1));
}
}
int main(int argc, char *argv[])
{
using namespace application;
// Parse arguments and handle control-C
auto arguments = parse_arguments(argc, argv, Entity::Subscriber);
if (arguments.parse_result == ParseReturn::exit) {
return EXIT_SUCCESS;
} else if (arguments.parse_result == ParseReturn::failure) {
return EXIT_FAILURE;
}
setup_signal_handlers();
// Sets Connext verbosity to help debugging
rti::config::Logger::instance().verbosity(arguments.verbosity);
try {
run_subscriber_application(arguments.domain_id, arguments.sample_count);
} catch (const std::exception &ex) {
// This will catch DDS exceptions
std::cerr << "Exception in run_subscriber_application(): " << ex.what()
<< std::endl;
return EXIT_FAILURE;
}
// Releases the memory used by the participant factory. Optional at
// application exit
dds::domain::DomainParticipant::finalize_participant_factory();
return EXIT_SUCCESS;
}
| cxx |
rticonnextdds-examples | data/projects/rticonnextdds-examples/connext_dds/using_qos_profiles/c++11/profiles_publisher.cxx | /*******************************************************************************
(c) 2005-2015 Copyright, Real-Time Innovations, Inc. All rights reserved.
RTI grants Licensee a license to use, modify, compile, and create derivative
works of the Software. Licensee has the right to distribute object form only
for use with RTI products. The Software is provided "as is", with no warranty
of any type, including any warranty for fitness for any purpose. RTI is under
no obligation to maintain or support the Software. RTI shall not be liable for
any incidental or consequential damages arising out of the use or inability to
use the software.
******************************************************************************/
#include <dds/pub/ddspub.hpp>
#include <rti/util/util.hpp> // for sleep()
#include <rti/config/Logger.hpp> // for logging
#include "application.hpp" // for command line parsing and ctrl-c
#include "profiles.hpp"
void run_publisher_application(
unsigned int domain_id,
unsigned int sample_count)
{
// Retrieve QoS from custom profile XML and USER_QOS_PROFILES.xml
dds::core::QosProvider qos_provider("my_custom_qos_profiles.xml");
// Create a DomainParticipant with the default QoS of the provider.
dds::domain::DomainParticipant participant(
domain_id,
qos_provider.participant_qos());
// Create a Publisher with default QoS.
dds::pub::Publisher publisher(participant, qos_provider.publisher_qos());
// Create a Topic with default QoS.
dds::topic::Topic<profiles> topic(
participant,
"Example profiles",
qos_provider.topic_qos());
// Create a DataWriter with the QoS profile "transient_local_profile",
// from QoS library "profiles_Library".
dds::pub::DataWriter<profiles> writer_transient_local(
publisher,
topic,
qos_provider.datawriter_qos(
"profiles_Library::transient_local_profile"));
// Create a DataReader with the QoS profile "volatile_profile",
// from the QoS library "profiles_Library".
dds::pub::DataWriter<profiles> writer_volatile(
publisher,
topic,
qos_provider.datawriter_qos("profiles_Library::volatile_profile"));
// Create a data sample for writing.
profiles instance;
// Main loop.
for (unsigned int samples_written = 0;
!application::shutdown_requested && samples_written < sample_count;
samples_written++) {
// Update the counter value of the sample.
instance.x(samples_written);
// Send the sample using the DataWriter with "volatile" durability.
std::cout << "Writing profile_name = volatile_profile,\t x = "
<< samples_written << std::endl;
instance.profile_name("volatile_profile");
writer_volatile.write(instance);
// Send the sample using the DataWriter with "transient_local"
// durability.
std::cout << "Writing profile_name = transient_local_profile,\t x = "
<< samples_written << std::endl
<< std::endl;
instance.profile_name("transient_local_profile");
writer_transient_local.write(instance);
// Send the sample every second.
rti::util::sleep(dds::core::Duration(1));
}
}
int main(int argc, char *argv[])
{
using namespace application;
// Parse arguments and handle control-C
auto arguments = parse_arguments(argc, argv, Entity::Publisher);
if (arguments.parse_result == ParseReturn::exit) {
return EXIT_SUCCESS;
} else if (arguments.parse_result == ParseReturn::failure) {
return EXIT_FAILURE;
}
setup_signal_handlers();
// Sets Connext verbosity to help debugging
rti::config::Logger::instance().verbosity(arguments.verbosity);
try {
run_publisher_application(arguments.domain_id, arguments.sample_count);
} catch (const std::exception &ex) {
// This will catch DDS exceptions
std::cerr << "Exception in run_publisher_application(): " << ex.what()
<< std::endl;
return EXIT_FAILURE;
}
// Releases the memory used by the participant factory. Optional at
// application exit
dds::domain::DomainParticipant::finalize_participant_factory();
return EXIT_SUCCESS;
}
| cxx |
rticonnextdds-examples | data/projects/rticonnextdds-examples/connext_dds/polling_querycondition/c++/flights_subscriber.cxx | /*******************************************************************************
(c) 2005-2015 Copyright, Real-Time Innovations, Inc. All rights reserved.
RTI grants Licensee a license to use, modify, compile, and create derivative
works of the Software. Licensee has the right to distribute object form only
for use with RTI products. The Software is provided "as is", with no warranty
of any type, including any warranty for fitness for any purpose. RTI is under
no obligation to maintain or support the Software. RTI shall not be liable for
any incidental or consequential damages arising out of the use or inability to
use the software.
******************************************************************************/
#include <stdio.h>
#include <stdlib.h>
#ifdef RTI_VX653
#include <vThreadsData.h>
#endif
#include "flights.h"
#include "flightsSupport.h"
#include "ndds/ndds_cpp.h"
/* We remove all the listener code as we won't use any listener */
/* Delete all entities */
static int subscriber_shutdown(DDSDomainParticipant *participant)
{
DDS_ReturnCode_t retcode;
int status = 0;
if (participant != NULL) {
retcode = participant->delete_contained_entities();
if (retcode != DDS_RETCODE_OK) {
printf("delete_contained_entities error %d\n", retcode);
status = -1;
}
retcode = DDSTheParticipantFactory->delete_participant(participant);
if (retcode != DDS_RETCODE_OK) {
printf("delete_participant error %d\n", retcode);
status = -1;
}
}
/* RTI Connext provides the finalize_instance() method on
domain participant factory for people who want to release memory used
by the participant factory. Uncomment the following block of code for
clean destruction of the singleton. */
/*
retcode = DDSDomainParticipantFactory::finalize_instance();
if (retcode != DDS_RETCODE_OK) {
printf("finalize_instance error %d\n", retcode);
status = -1;
}
*/
return status;
}
extern "C" int subscriber_main(int domainId, int sample_count)
{
DDSDomainParticipant *participant = NULL;
DDSSubscriber *subscriber = NULL;
DDSTopic *topic = NULL;
DDSDataReader *reader = NULL;
DDS_ReturnCode_t retcode;
const char *type_name = NULL;
int count = 0;
/* Poll for new samples every second. */
DDS_Duration_t receive_period = { 1, 0 };
int status = 0;
/* Create the Participant. */
participant = DDSTheParticipantFactory->create_participant(
domainId,
DDS_PARTICIPANT_QOS_DEFAULT,
NULL /* listener */,
DDS_STATUS_MASK_NONE);
if (participant == NULL) {
printf("create_participant error\n");
subscriber_shutdown(participant);
return -1;
}
/* Create a Subscriber. */
subscriber = participant->create_subscriber(
DDS_SUBSCRIBER_QOS_DEFAULT,
NULL /* listener */,
DDS_STATUS_MASK_NONE);
if (subscriber == NULL) {
printf("create_subscriber error\n");
subscriber_shutdown(participant);
return -1;
}
/* Register the type before creating the topic. */
type_name = FlightTypeSupport::get_type_name();
retcode = FlightTypeSupport::register_type(participant, type_name);
if (retcode != DDS_RETCODE_OK) {
printf("register_type error %d\n", retcode);
subscriber_shutdown(participant);
return -1;
}
/* Create a Topic. */
topic = participant->create_topic(
"Example Flight",
type_name,
DDS_TOPIC_QOS_DEFAULT,
NULL /* listener */,
DDS_STATUS_MASK_NONE);
if (topic == NULL) {
printf("create_topic error\n");
subscriber_shutdown(participant);
return -1;
}
/* Call create_datareader passing NULL in the listener parameter. */
reader = subscriber->create_datareader(
topic,
DDS_DATAREADER_QOS_DEFAULT,
NULL,
DDS_STATUS_MASK_ALL);
if (reader == NULL) {
printf("create_datareader error\n");
subscriber_shutdown(participant);
return -1;
}
FlightDataReader *flight_reader = FlightDataReader::narrow(reader);
if (reader == NULL) {
printf("DataReader narrow error\n");
return -1;
}
/* Query for company named 'CompanyA' and for flights in cruise
* (about 30,000ft). The company parameter will be changed in run-time.
* NOTE: There must be single-quotes in the query parameters around-any
* strings! The single-quote do NOT go in the query condition itself. */
DDS_StringSeq query_parameters;
query_parameters.ensure_length(2, 2);
query_parameters[0] = (char *) "'CompanyA'";
query_parameters[1] = (char *) "30000";
printf("Setting parameter to company %s, altitude bigger or equals to %s\n",
query_parameters[0],
query_parameters[1]);
/* Create the query condition with an expession to MATCH the id field in
* the structure and a numeric comparison. Note that you should make a copy
* of the expression string when creating the query condition - beware it
* going out of scope! */
DDSQueryCondition *query_condition = flight_reader->create_querycondition(
DDS_ANY_SAMPLE_STATE,
DDS_ANY_VIEW_STATE,
DDS_ALIVE_INSTANCE_STATE,
DDS_String_dup("company MATCH %0 AND altitude >= %1"),
query_parameters);
/* Main loop */
for (count = 0; (sample_count == 0) || (count < sample_count); ++count) {
/* Poll for a new samples every second. */
NDDSUtility::sleep(receive_period);
bool update = false;
/* Change the filter parameter after 5 seconds. */
if ((count + 1) % 10 == 5) {
query_parameters[0] = (char *) "'CompanyB'";
update = true;
} else if ((count + 1) % 10 == 0) {
query_parameters[0] = (char *) "'CompanyA'";
update = true;
}
/* Set new parameters. */
if (update) {
printf("Changing parameter to %s\n", query_parameters[0]);
query_condition->set_query_parameters(query_parameters);
}
DDS_SampleInfoSeq info_seq;
FlightSeq data_seq;
/* Iterate through the samples read using the read_w_condition method */
retcode = flight_reader->read_w_condition(
data_seq,
info_seq,
DDS_LENGTH_UNLIMITED,
query_condition);
if (retcode == DDS_RETCODE_NO_DATA) {
// Not an error
continue;
} else if (retcode != DDS_RETCODE_OK) {
// Is an error
printf("take error: %d\n", retcode);
break;
}
for (int i = 0; i < data_seq.length(); ++i) {
if (info_seq[i].valid_data) {
printf("\t[trackId: %d, company: %s, altitude: %d]\n",
data_seq[i].trackId,
data_seq[i].company,
data_seq[i].altitude);
}
}
retcode = flight_reader->return_loan(data_seq, info_seq);
if (retcode != DDS_RETCODE_OK) {
printf("return loan error %d\n", retcode);
}
}
/* Delete all entities */
status = subscriber_shutdown(participant);
return status;
}
#if !(defined(RTI_VXWORKS) && !defined(__RTP__)) && !defined(RTI_PSOS)
int main(int argc, char *argv[])
{
int domainId = 0;
int sample_count = 0; /* infinite loop */
if (argc >= 2) {
domainId = atoi(argv[1]);
}
if (argc >= 3) {
sample_count = atoi(argv[2]);
}
/* Uncomment this to turn on additional logging
NDDSConfigLogger::get_instance()->
set_verbosity_by_category(NDDS_CONFIG_LOG_CATEGORY_API,
NDDS_CONFIG_LOG_VERBOSITY_STATUS_ALL);
*/
return subscriber_main(domainId, sample_count);
}
#endif
#ifdef RTI_VX653
const unsigned char *__ctype = *(__ctypePtrGet());
extern "C" void usrAppInit()
{
#ifdef USER_APPL_INIT
USER_APPL_INIT; /* for backwards compatibility */
#endif
/* add application specific code here */
taskSpawn(
"sub",
RTI_OSAPI_THREAD_PRIORITY_NORMAL,
0x8,
0x150000,
(FUNCPTR) subscriber_main,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0);
}
#endif
| cxx |
rticonnextdds-examples | data/projects/rticonnextdds-examples/connext_dds/polling_querycondition/c++/flights_publisher.cxx | /*******************************************************************************
(c) 2005-2014 Copyright, Real-Time Innovations, Inc. All rights reserved.
RTI grants Licensee a license to use, modify, compile, and create derivative
works of the Software. Licensee has the right to distribute object form only
for use with RTI products. The Software is provided "as is", with no warranty
of any type, including any warranty for fitness for any purpose. RTI is under
no obligation to maintain or support the Software. RTI shall not be liable for
any incidental or consequential damages arising out of the use or inability to
use the software.
******************************************************************************/
#include <stdio.h>
#include <stdlib.h>
#ifdef RTI_VX653
#include <vThreadsData.h>
#endif
#include "flights.h"
#include "flightsSupport.h"
#include "ndds/ndds_cpp.h"
/* Delete all entities */
static int publisher_shutdown(DDSDomainParticipant *participant)
{
DDS_ReturnCode_t retcode;
int status = 0;
if (participant != NULL) {
retcode = participant->delete_contained_entities();
if (retcode != DDS_RETCODE_OK) {
printf("delete_contained_entities error %d\n", retcode);
status = -1;
}
retcode = DDSTheParticipantFactory->delete_participant(participant);
if (retcode != DDS_RETCODE_OK) {
printf("delete_participant error %d\n", retcode);
status = -1;
}
}
/* RTI Connext provides finalize_instance() method on
domain participant factory for people who want to release memory used
by the participant factory. Uncomment the following block of code for
clean destruction of the singleton. */
/*
retcode = DDSDomainParticipantFactory::finalize_instance();
if (retcode != DDS_RETCODE_OK) {
printf("finalize_instance error %d\n", retcode);
status = -1;
}
*/
return status;
}
extern "C" int publisher_main(int domainId, int sample_count)
{
DDSDomainParticipant *participant = NULL;
DDSPublisher *publisher = NULL;
DDSTopic *topic = NULL;
DDSDataWriter *writer = NULL;
FlightDataWriter *flights_writer = NULL;
DDS_ReturnCode_t retcode;
DDS_InstanceHandle_t instance_handle = DDS_HANDLE_NIL;
const char *type_name = NULL;
int count = 0;
/* Send a new sample every second */
DDS_Duration_t send_period = { 1, 0 };
/* Create a Participant. */
participant = DDSTheParticipantFactory->create_participant(
domainId,
DDS_PARTICIPANT_QOS_DEFAULT,
NULL /* listener */,
DDS_STATUS_MASK_NONE);
if (participant == NULL) {
printf("create_participant error\n");
publisher_shutdown(participant);
return -1;
}
/* Create a Publisher. */
publisher = participant->create_publisher(
DDS_PUBLISHER_QOS_DEFAULT,
NULL /* listener */,
DDS_STATUS_MASK_NONE);
if (publisher == NULL) {
printf("create_publisher error\n");
publisher_shutdown(participant);
return -1;
}
/* Register type before creating topic. */
type_name = FlightTypeSupport::get_type_name();
retcode = FlightTypeSupport::register_type(participant, type_name);
if (retcode != DDS_RETCODE_OK) {
printf("register_type error %d\n", retcode);
publisher_shutdown(participant);
return -1;
}
/* Create the Topic. */
topic = participant->create_topic(
"Example Flight",
type_name,
DDS_TOPIC_QOS_DEFAULT,
NULL /* listener */,
DDS_STATUS_MASK_NONE);
if (topic == NULL) {
printf("create_topic error\n");
publisher_shutdown(participant);
return -1;
}
/* Create a DataWriter. */
writer = publisher->create_datawriter(
topic,
DDS_DATAWRITER_QOS_DEFAULT,
NULL /* listener */,
DDS_STATUS_MASK_NONE);
if (writer == NULL) {
printf("create_datawriter error\n");
publisher_shutdown(participant);
return -1;
}
flights_writer = FlightDataWriter::narrow(writer);
if (flights_writer == NULL) {
printf("DataWriter narrow error\n");
publisher_shutdown(participant);
return -1;
}
/* Create the flight info samples. */
const int num_flights = 4;
Flight flights_info[4];
flights_info[0].trackId = 1111;
flights_info[0].company = (char *) "CompanyA";
flights_info[0].altitude = 15000;
flights_info[1].trackId = 2222;
flights_info[1].company = (char *) "CompanyB";
flights_info[1].altitude = 20000;
flights_info[2].trackId = 3333;
flights_info[2].company = (char *) "CompanyA";
flights_info[2].altitude = 30000;
flights_info[3].trackId = 4444;
flights_info[3].company = (char *) "CompanyB";
flights_info[3].altitude = 25000;
/* Main loop */
for (count = 0; (sample_count == 0) || (count < sample_count);
count += num_flights) {
/* Update flight info latitude and write. */
printf("Updating and sending values\n");
for (int i = 0; i < num_flights; i++) {
/* Set the plane altitude lineally
* (usually the max is at 41,000ft). */
flights_info[i].altitude += count * 100;
if (flights_info[i].altitude >= 41000) {
flights_info[i].altitude = 41000;
}
printf("\t[trackId: %d, company: %s, altitude: %d]\n",
flights_info[i].trackId,
flights_info[i].company,
flights_info[i].altitude);
/* Write the instance */
retcode = flights_writer->write(flights_info[i], instance_handle);
if (retcode != DDS_RETCODE_OK) {
printf("write error %d\n", retcode);
}
}
NDDSUtility::sleep(send_period);
}
/* Delete all entities */
return publisher_shutdown(participant);
}
#if !(defined(RTI_VXWORKS) && !defined(__RTP__)) && !defined(RTI_PSOS)
int main(int argc, char *argv[])
{
int domainId = 0;
int sample_count = 0; /* infinite loop */
if (argc >= 2) {
domainId = atoi(argv[1]);
}
if (argc >= 3) {
sample_count = atoi(argv[2]);
}
/* Uncomment this to turn on additional logging
NDDSConfigLogger::get_instance()->
set_verbosity_by_category(NDDS_CONFIG_LOG_CATEGORY_API,
NDDS_CONFIG_LOG_VERBOSITY_STATUS_ALL);
*/
return publisher_main(domainId, sample_count);
}
#endif
#ifdef RTI_VX653
const unsigned char *__ctype = *(__ctypePtrGet());
extern "C" void usrAppInit()
{
#ifdef USER_APPL_INIT
USER_APPL_INIT; /* for backwards compatibility */
#endif
/* add application specific code here */
taskSpawn(
"pub",
RTI_OSAPI_THREAD_PRIORITY_NORMAL,
0x8,
0x150000,
(FUNCPTR) publisher_main,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0);
}
#endif
| cxx |
rticonnextdds-examples | data/projects/rticonnextdds-examples/connext_dds/polling_querycondition/c++98/flights_subscriber.cxx | /*******************************************************************************
(c) 2005-2015 Copyright, Real-Time Innovations, Inc. All rights reserved.
RTI grants Licensee a license to use, modify, compile, and create derivative
works of the Software. Licensee has the right to distribute object form only
for use with RTI products. The Software is provided "as is", with no warranty
of any type, including any warranty for fitness for any purpose. RTI is under
no obligation to maintain or support the Software. RTI shall not be liable for
any incidental or consequential damages arising out of the use or inability to
use the software.
******************************************************************************/
#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include "flights.h"
#include "flightsSupport.h"
#include "ndds/ndds_cpp.h"
#include "application.h"
using namespace application;
static int shutdown_participant(
DDSDomainParticipant *participant,
const char *shutdown_message,
int status);
/* We remove all the listener code as we won't use any listener */
int run_subscriber_application(
unsigned int domain_id,
unsigned int sample_count)
{
/* Poll for new samples every second. */
DDS_Duration_t receive_period = { 1, 0 };
// Start communicating in a domain, usually one participant per application
DDSDomainParticipant *participant =
DDSTheParticipantFactory->create_participant(
domain_id,
DDS_PARTICIPANT_QOS_DEFAULT,
NULL /* listener */,
DDS_STATUS_MASK_NONE);
if (participant == NULL) {
return shutdown_participant(
participant,
"create_participant error",
EXIT_FAILURE);
}
// A Subscriber allows an application to create one or more DataReaders
DDSSubscriber *subscriber = participant->create_subscriber(
DDS_SUBSCRIBER_QOS_DEFAULT,
NULL /* listener */,
DDS_STATUS_MASK_NONE);
if (subscriber == NULL) {
return shutdown_participant(
participant,
"create_subscriber error",
EXIT_FAILURE);
}
// Register the datatype to use when creating the Topic
const char *type_name = FlightTypeSupport::get_type_name();
DDS_ReturnCode_t retcode =
FlightTypeSupport::register_type(participant, type_name);
if (retcode != DDS_RETCODE_OK) {
return shutdown_participant(
participant,
"register_type error",
EXIT_FAILURE);
}
// Create a Topic with a name and a datatype
DDSTopic *topic = participant->create_topic(
"Example Flight",
type_name,
DDS_TOPIC_QOS_DEFAULT,
NULL /* listener */,
DDS_STATUS_MASK_NONE);
if (topic == NULL) {
return shutdown_participant(
participant,
"create_topic error",
EXIT_FAILURE);
}
// This DataReader reads data on "Example flights" Topic
DDSDataReader *untyped_reader = subscriber->create_datareader(
topic,
DDS_DATAREADER_QOS_DEFAULT,
NULL,
DDS_STATUS_MASK_ALL);
if (untyped_reader == NULL) {
return shutdown_participant(
participant,
"create_datareader error",
EXIT_FAILURE);
}
FlightDataReader *typed_reader = FlightDataReader::narrow(untyped_reader);
if (typed_reader == NULL) {
return shutdown_participant(
participant,
"DataReader narrow error",
EXIT_FAILURE);
}
/* Query for company named 'CompanyA' and for flights in cruise
* (about 30,000ft). The company parameter will be changed in run-time.
* NOTE: There must be single-quotes in the query parameters around-any
* strings! The single-quote do NOT go in the query condition itself. */
DDS_StringSeq query_parameters;
query_parameters.ensure_length(2, 2);
query_parameters[0] = (char *) "'CompanyA'";
query_parameters[1] = (char *) "30000";
std::cout << "Setting parameter to company " << query_parameters[0]
<< ", altitude bigger or equals to " << query_parameters[1]
<< std::endl;
/* Create the query condition with an expession to MATCH the id field in
* the structure and a numeric comparison. Note that you should make a copy
* of the expression string when creating the query condition - beware it
* going out of scope! */
DDSQueryCondition *query_condition = typed_reader->create_querycondition(
DDS_ANY_SAMPLE_STATE,
DDS_ANY_VIEW_STATE,
DDS_ALIVE_INSTANCE_STATE,
DDS_String_dup("company MATCH %0 AND altitude >= %1"),
query_parameters);
// Main loop. Wait for data to arrive, and process when it arrives
int iteration_count = 0;
unsigned int samples_read = 0;
while (!shutdown_requested && samples_read < sample_count) {
// Poll for a new samples every second.
NDDSUtility::sleep(receive_period);
bool update = false;
// Change the filter parameter after 5 seconds.
if ((iteration_count + 1) % 10 == 5) {
query_parameters[0] = (char *) "'CompanyB'";
update = true;
} else if ((iteration_count + 1) % 10 == 0) {
query_parameters[0] = (char *) "'CompanyA'";
update = true;
}
iteration_count++;
// Set new parameters.
if (update) {
std::cout << "Changing parameter to " << query_parameters[0]
<< std::endl;
query_condition->set_query_parameters(query_parameters);
}
DDS_SampleInfoSeq info_seq;
FlightSeq data_seq;
// Iterate through the samples read using the read_w_condition method
retcode = typed_reader->read_w_condition(
data_seq,
info_seq,
DDS_LENGTH_UNLIMITED,
query_condition);
if (retcode == DDS_RETCODE_NO_DATA) {
// Not an error
continue;
} else if (retcode != DDS_RETCODE_OK) {
// Is an error
std::cerr << "take error: " << retcode << std::endl;
break;
}
for (int i = 0; i < data_seq.length(); ++i) {
if (info_seq[i].valid_data) {
std::cout << "\t[trackId: " << data_seq[i].trackId
<< ", company: " << data_seq[i].company
<< ", altitude: " << data_seq[i].altitude << "]\n";
samples_read++;
}
}
retcode = typed_reader->return_loan(data_seq, info_seq);
if (retcode != DDS_RETCODE_OK) {
std::cerr << "return loan error " << retcode << std::endl;
}
}
// Cleanup
return shutdown_participant(participant, "Shutting down", 0);
}
// Delete all entities
static int shutdown_participant(
DDSDomainParticipant *participant,
const char *shutdown_message,
int status)
{
DDS_ReturnCode_t retcode;
std::cout << shutdown_message << std::endl;
if (participant != NULL) {
// Cleanup everything created by this Participant
retcode = participant->delete_contained_entities();
if (retcode != DDS_RETCODE_OK) {
std::cerr << "delete_contained_entities error" << retcode
<< std::endl;
status = EXIT_FAILURE;
}
retcode = DDSTheParticipantFactory->delete_participant(participant);
if (retcode != DDS_RETCODE_OK) {
std::cerr << "delete_participant error" << retcode << std::endl;
status = EXIT_FAILURE;
}
}
return status;
}
int main(int argc, char *argv[])
{
// Parse arguments and handle control-C
ApplicationArguments arguments;
parse_arguments(arguments, argc, argv);
if (arguments.parse_result == PARSE_RETURN_EXIT) {
return EXIT_SUCCESS;
} else if (arguments.parse_result == PARSE_RETURN_FAILURE) {
return EXIT_FAILURE;
}
setup_signal_handlers();
// Sets Connext verbosity to help debugging
NDDSConfigLogger::get_instance()->set_verbosity(arguments.verbosity);
int status = run_subscriber_application(
arguments.domain_id,
arguments.sample_count);
// Releases the memory used by the participant factory. Optional at
// application exit
DDS_ReturnCode_t retcode = DDSDomainParticipantFactory::finalize_instance();
if (retcode != DDS_RETCODE_OK) {
std::cerr << "finalize_instance error" << retcode << std::endl;
status = EXIT_FAILURE;
}
return status;
}
| cxx |
rticonnextdds-examples | data/projects/rticonnextdds-examples/connext_dds/polling_querycondition/c++98/flights_publisher.cxx | /*******************************************************************************
(c) 2005-2014 Copyright, Real-Time Innovations, Inc. All rights reserved.
RTI grants Licensee a license to use, modify, compile, and create derivative
works of the Software. Licensee has the right to distribute object form only
for use with RTI products. The Software is provided "as is", with no warranty
of any type, including any warranty for fitness for any purpose. RTI is under
no obligation to maintain or support the Software. RTI shall not be liable for
any incidental or consequential damages arising out of the use or inability to
use the software.
******************************************************************************/
#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include "flights.h"
#include "flightsSupport.h"
#include "ndds/ndds_cpp.h"
#include "application.h"
using namespace application;
static int shutdown_participant(
DDSDomainParticipant *participant,
const char *shutdown_message,
int status);
int run_publisher_application(unsigned int domain_id, unsigned int sample_count)
{
/* Send a new sample every second */
DDS_Duration_t send_period = { 1, 0 };
// Start communicating in a domain, usually one participant per application
DDSDomainParticipant *participant =
DDSTheParticipantFactory->create_participant(
domain_id,
DDS_PARTICIPANT_QOS_DEFAULT,
NULL /* listener */,
DDS_STATUS_MASK_NONE);
if (participant == NULL) {
return shutdown_participant(
participant,
"create_participant error",
EXIT_FAILURE);
}
// A Publisher allows an application to create one or more DataWriters
DDSPublisher *publisher = participant->create_publisher(
DDS_PUBLISHER_QOS_DEFAULT,
NULL /* listener */,
DDS_STATUS_MASK_NONE);
if (publisher == NULL) {
return shutdown_participant(
participant,
"create_publisher error",
EXIT_FAILURE);
}
// Register the datatype to use when creating the Topic
const char *type_name = FlightTypeSupport::get_type_name();
DDS_ReturnCode_t retcode =
FlightTypeSupport::register_type(participant, type_name);
if (retcode != DDS_RETCODE_OK) {
return shutdown_participant(
participant,
"register_type error",
EXIT_FAILURE);
}
// Create a Topic with a name and a datatype
DDSTopic *topic = participant->create_topic(
"Example Flight",
type_name,
DDS_TOPIC_QOS_DEFAULT,
NULL /* listener */,
DDS_STATUS_MASK_NONE);
if (topic == NULL) {
return shutdown_participant(
participant,
"create_topic error",
EXIT_FAILURE);
}
// This DataWriter writes data on "Example flight" Topic
DDSDataWriter *untyped_writer = publisher->create_datawriter(
topic,
DDS_DATAWRITER_QOS_DEFAULT,
NULL /* listener */,
DDS_STATUS_MASK_NONE);
if (untyped_writer == NULL) {
return shutdown_participant(
participant,
"create_datawriter error",
EXIT_FAILURE);
}
FlightDataWriter *typed_writer = FlightDataWriter::narrow(untyped_writer);
if (typed_writer == NULL) {
return shutdown_participant(
participant,
"DataWriter narrow error",
EXIT_FAILURE);
}
/* Create the flight info samples. */
const int num_flights = 4;
Flight flights_info[4];
flights_info[0].trackId = 1111;
flights_info[0].company = (char *) "CompanyA";
flights_info[0].altitude = 15000;
flights_info[1].trackId = 2222;
flights_info[1].company = (char *) "CompanyB";
flights_info[1].altitude = 20000;
flights_info[2].trackId = 3333;
flights_info[2].company = (char *) "CompanyA";
flights_info[2].altitude = 30000;
flights_info[3].trackId = 4444;
flights_info[3].company = (char *) "CompanyB";
flights_info[3].altitude = 25000;
// Main loop, write data
for (unsigned int samples_written = 0;
!shutdown_requested && samples_written < sample_count;
++samples_written) {
/* Update flight info latitude and write. */
std::cout << "Updating and sending values\n";
for (int i = 0; i < num_flights; i++) {
/* Set the plane altitude lineally
* (usually the max is at 41,000ft). */
flights_info[i].altitude += samples_written * 100;
if (flights_info[i].altitude >= 41000) {
flights_info[i].altitude = 41000;
}
std::cout << "\t[trackId: " << flights_info[i].trackId
<< ", company: " << flights_info[i].company
<< ", altitude: " << flights_info[i].altitude << "]\n";
/* Write the instance */
retcode = typed_writer->write(flights_info[i], DDS_HANDLE_NIL);
if (retcode != DDS_RETCODE_OK) {
std::cerr << "write error " << retcode << std::endl;
}
}
NDDSUtility::sleep(send_period);
}
// Delete all entities (DataWriter, Topic, Publisher, DomainParticipant)
return shutdown_participant(participant, "Shutting down", EXIT_SUCCESS);
}
// Delete all entities
static int shutdown_participant(
DDSDomainParticipant *participant,
const char *shutdown_message,
int status)
{
DDS_ReturnCode_t retcode;
std::cout << shutdown_message << std::endl;
if (participant != NULL) {
// Cleanup everything created by this Participant
retcode = participant->delete_contained_entities();
if (retcode != DDS_RETCODE_OK) {
std::cerr << "delete_contained_entities error " << retcode
<< std::endl;
status = EXIT_FAILURE;
}
retcode = DDSTheParticipantFactory->delete_participant(participant);
if (retcode != DDS_RETCODE_OK) {
std::cerr << "delete_participant error " << retcode << std::endl;
status = EXIT_FAILURE;
}
}
return status;
}
int main(int argc, char *argv[])
{
// Parse arguments and handle control-C
ApplicationArguments arguments;
parse_arguments(arguments, argc, argv);
if (arguments.parse_result == PARSE_RETURN_EXIT) {
return EXIT_SUCCESS;
} else if (arguments.parse_result == PARSE_RETURN_FAILURE) {
return EXIT_FAILURE;
}
setup_signal_handlers();
// Sets Connext verbosity to help debugging
NDDSConfigLogger::get_instance()->set_verbosity(arguments.verbosity);
int status = run_publisher_application(
arguments.domain_id,
arguments.sample_count);
// Releases the memory used by the participant factory. Optional at
// application exit
DDS_ReturnCode_t retcode = DDSDomainParticipantFactory::finalize_instance();
if (retcode != DDS_RETCODE_OK) {
std::cerr << "finalize_instance error " << retcode << std::endl;
status = EXIT_FAILURE;
}
return status;
}
| cxx |
rticonnextdds-examples | data/projects/rticonnextdds-examples/connext_dds/polling_querycondition/c++98/application.h | /*
* (c) Copyright, Real-Time Innovations, 2020. All rights reserved.
* RTI grants Licensee a license to use, modify, compile, and create derivative
* works of the software solely for use with RTI Connext DDS. Licensee may
* redistribute copies of the software provided that all such copies are subject
* to this license. The software is provided "as is", with no warranty of any
* type, including any warranty for fitness for any purpose. RTI is under no
* obligation to maintain or support the software. RTI shall not be liable for
* any incidental or consequential damages arising out of the use or inability
* to use the software.
*/
#ifndef APPLICATION_H
#define APPLICATION_H
#include <iostream>
#include <csignal>
#include <climits>
namespace application {
// Catch control-C and tell application to shut down
bool shutdown_requested = false;
inline void stop_handler(int)
{
shutdown_requested = true;
std::cout << "preparing to shut down..." << std::endl;
}
inline void setup_signal_handlers()
{
signal(SIGINT, stop_handler);
signal(SIGTERM, stop_handler);
}
enum ParseReturn { PARSE_RETURN_OK, PARSE_RETURN_FAILURE, PARSE_RETURN_EXIT };
struct ApplicationArguments {
ParseReturn parse_result;
unsigned int domain_id;
unsigned int sample_count;
NDDS_Config_LogVerbosity verbosity;
};
inline void set_verbosity(ApplicationArguments &arguments, int verbosity)
{
switch (verbosity) {
case 0:
arguments.verbosity = NDDS_CONFIG_LOG_VERBOSITY_SILENT;
break;
case 1:
arguments.verbosity = NDDS_CONFIG_LOG_VERBOSITY_ERROR;
break;
case 2:
arguments.verbosity = NDDS_CONFIG_LOG_VERBOSITY_WARNING;
break;
case 3:
arguments.verbosity = NDDS_CONFIG_LOG_VERBOSITY_STATUS_ALL;
break;
default:
arguments.verbosity = NDDS_CONFIG_LOG_VERBOSITY_ERROR;
break;
}
}
// Parses application arguments for example. Returns whether to exit.
inline void parse_arguments(
ApplicationArguments &arguments,
int argc,
char *argv[])
{
int arg_processing = 1;
bool show_usage = false;
arguments.domain_id = 0;
arguments.sample_count = INT_MAX;
arguments.verbosity = NDDS_CONFIG_LOG_VERBOSITY_ERROR;
arguments.parse_result = PARSE_RETURN_OK;
while (arg_processing < argc) {
if ((argc > arg_processing + 1)
&& (strcmp(argv[arg_processing], "-d") == 0
|| strcmp(argv[arg_processing], "--domain") == 0)) {
arguments.domain_id = atoi(argv[arg_processing + 1]);
arg_processing += 2;
} else if (
(argc > arg_processing + 1)
&& (strcmp(argv[arg_processing], "-s") == 0
|| strcmp(argv[arg_processing], "--sample-count") == 0)) {
arguments.sample_count = atoi(argv[arg_processing + 1]);
arg_processing += 2;
} else if (
(argc > arg_processing + 1)
&& (strcmp(argv[arg_processing], "-v") == 0
|| strcmp(argv[arg_processing], "--verbosity") == 0)) {
set_verbosity(arguments, atoi(argv[arg_processing + 1]));
arg_processing += 2;
} else if (
strcmp(argv[arg_processing], "-h") == 0
|| strcmp(argv[arg_processing], "--help") == 0) {
std::cout << "Example application." << std::endl;
show_usage = true;
arguments.parse_result = PARSE_RETURN_EXIT;
break;
} else {
std::cout << "Bad parameter." << std::endl;
show_usage = true;
arguments.parse_result = PARSE_RETURN_FAILURE;
break;
}
}
if (show_usage) {
std::cout << "Usage:\n"
" -d, --domain <int> Domain ID this "
"application will\n"
" subscribe in. \n"
" Default: 0\n"
" -s, --sample_count <int> Number of samples to "
"receive before\n"
" cleanly shutting down. \n"
" Default: infinite\n"
" -v, --verbosity <int> How much debugging output "
"to show.\n"
" Range: 0-3 \n"
" Default: 1"
<< std::endl;
}
}
} // namespace application
#endif // APPLICATION_H
| h |
rticonnextdds-examples | data/projects/rticonnextdds-examples/connext_dds/polling_querycondition/c/flights_publisher.c | /*******************************************************************************
(c) 2005-2015 Copyright, Real-Time Innovations, Inc. All rights reserved.
RTI grants Licensee a license to use, modify, compile, and create derivative
works of the Software. Licensee has the right to distribute object form only
for use with RTI products. The Software is provided "as is", with no warranty
of any type, including any warranty for fitness for any purpose. RTI is under
no obligation to maintain or support the Software. RTI shall not be liable for
any incidental or consequential damages arising out of the use or inability to
use the software.
******************************************************************************/
#include "flights.h"
#include "flightsSupport.h"
#include "ndds/ndds_c.h"
#include <stdio.h>
#include <stdlib.h>
/* Delete all entities */
static int publisher_shutdown(DDS_DomainParticipant *participant)
{
DDS_ReturnCode_t retcode;
int status = 0;
if (participant != NULL) {
retcode = DDS_DomainParticipant_delete_contained_entities(participant);
if (retcode != DDS_RETCODE_OK) {
printf("delete_contained_entities error %d\n", retcode);
status = -1;
}
retcode = DDS_DomainParticipantFactory_delete_participant(
DDS_TheParticipantFactory,
participant);
if (retcode != DDS_RETCODE_OK) {
printf("delete_participant error %d\n", retcode);
status = -1;
}
}
/* RTI Connext provides finalize_instance() method on
domain participant factory for people who want to release memory used
by the participant factory. Uncomment the following block of code for
clean destruction of the singleton. */
/*
retcode = DDS_DomainParticipantFactory_finalize_instance();
if (retcode != DDS_RETCODE_OK) {
printf("finalize_instance error %d\n", retcode);
status = -1;
}
*/
return status;
}
static int publisher_main(int domain_id, int sample_count)
{
DDS_DomainParticipant *participant = NULL;
DDS_Publisher *publisher = NULL;
DDS_Topic *topic = NULL;
DDS_DataWriter *writer = NULL;
FlightDataWriter *flight_writer = NULL;
DDS_ReturnCode_t retcode;
DDS_InstanceHandle_t instance_handle = DDS_HANDLE_NIL;
const char *type_name = NULL;
int count = 0;
/* Send a new sample every second */
struct DDS_Duration_t send_period = { 1, 0 };
/* Create the flight info samples. */
const int num_flights = 4;
Flight flights_info[4];
flights_info[0].trackId = 1111;
flights_info[0].company = "CompanyA";
flights_info[0].altitude = 15000;
flights_info[1].trackId = 2222;
flights_info[1].company = "CompanyB";
flights_info[1].altitude = 20000;
flights_info[2].trackId = 3333;
flights_info[2].company = "CompanyA";
flights_info[2].altitude = 30000;
flights_info[3].trackId = 4444;
flights_info[3].company = "CompanyB";
flights_info[3].altitude = 25000;
/* Create a Participant. */
participant = DDS_DomainParticipantFactory_create_participant(
DDS_TheParticipantFactory,
domain_id,
&DDS_PARTICIPANT_QOS_DEFAULT,
NULL /* listener */,
DDS_STATUS_MASK_NONE);
if (participant == NULL) {
printf("create_participant error\n");
publisher_shutdown(participant);
return -1;
}
/* Create a Publisher. */
publisher = DDS_DomainParticipant_create_publisher(
participant,
&DDS_PUBLISHER_QOS_DEFAULT,
NULL /* listener */,
DDS_STATUS_MASK_NONE);
if (publisher == NULL) {
printf("create_publisher error\n");
publisher_shutdown(participant);
return -1;
}
/* Register type before creating the topic. */
type_name = FlightTypeSupport_get_type_name();
retcode = FlightTypeSupport_register_type(participant, type_name);
if (retcode != DDS_RETCODE_OK) {
printf("register_type error %d\n", retcode);
publisher_shutdown(participant);
return -1;
}
/* Create a Topic. */
topic = DDS_DomainParticipant_create_topic(
participant,
"Example Flight",
type_name,
&DDS_TOPIC_QOS_DEFAULT,
NULL /* listener */,
DDS_STATUS_MASK_NONE);
if (topic == NULL) {
printf("create_topic error\n");
publisher_shutdown(participant);
return -1;
}
/* Create a DataWriter. */
writer = DDS_Publisher_create_datawriter(
publisher,
topic,
&DDS_DATAWRITER_QOS_DEFAULT,
NULL /* listener */,
DDS_STATUS_MASK_NONE);
if (writer == NULL) {
printf("create_datawriter error\n");
publisher_shutdown(participant);
return -1;
}
flight_writer = FlightDataWriter_narrow(writer);
if (flight_writer == NULL) {
printf("DataWriter narrow error\n");
publisher_shutdown(participant);
return -1;
}
/* Main loop */
for (count = 0; (sample_count == 0) || (count < sample_count);
count += num_flights) {
int i;
/* Update flight info latitude and write */
printf("Updating and sending values\n");
for (i = 0; i < num_flights; i++) {
/* Set the plane altitude lineally
* (usually the max is at 41,000ft).
*/
flights_info[i].altitude += count * 100;
if (flights_info[i].altitude >= 41000) {
flights_info[i].altitude = 41000;
}
printf("\t[trackId: %d, company: %s, altitude: %d]\n",
flights_info[i].trackId,
flights_info[i].company,
flights_info[i].altitude);
/* Write the instance */
retcode = FlightDataWriter_write(
flight_writer,
&flights_info[i],
&instance_handle);
if (retcode != DDS_RETCODE_OK) {
printf("write error %d\n", retcode);
}
}
NDDS_Utility_sleep(&send_period);
}
/* Cleanup and delete delete all entities */
return publisher_shutdown(participant);
}
#if !(defined(RTI_VXWORKS) && !defined(__RTP__)) && !defined(RTI_PSOS)
int main(int argc, char *argv[])
{
int domain_id = 0;
int sample_count = 0; /* Infinite loop */
if (argc >= 2) {
domain_id = atoi(argv[1]);
}
if (argc >= 3) {
sample_count = atoi(argv[2]);
}
/* Uncomment this to turn on additional logging
NDDS_Config_Logger_set_verbosity_by_category(
NDDS_Config_Logger_get_instance(),
NDDS_CONFIG_LOG_CATEGORY_API,
NDDS_CONFIG_LOG_VERBOSITY_STATUS_ALL);
*/
return publisher_main(domain_id, sample_count);
}
#endif
#ifdef RTI_VX653
const unsigned char *__ctype = NULL;
void usrAppInit()
{
#ifdef USER_APPL_INIT
USER_APPL_INIT; /* for backwards compatibility */
#endif
/* add application specific code here */
taskSpawn(
"pub",
RTI_OSAPI_THREAD_PRIORITY_NORMAL,
0x8,
0x150000,
(FUNCPTR) publisher_main,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0);
}
#endif
| c |
rticonnextdds-examples | data/projects/rticonnextdds-examples/connext_dds/polling_querycondition/c/flights_subscriber.c | /*******************************************************************************
(c) 2005-2015 Copyright, Real-Time Innovations, Inc. All rights reserved.
RTI grants Licensee a license to use, modify, compile, and create derivative
works of the Software. Licensee has the right to distribute object form only
for use with RTI products. The Software is provided "as is", with no warranty
of any type, including any warranty for fitness for any purpose. RTI is under
no obligation to maintain or support the Software. RTI shall not be liable for
any incidental or consequential damages arising out of the use or inability to
use the software.
******************************************************************************/
#include "flights.h"
#include "flightsSupport.h"
#include "ndds/ndds_c.h"
#include <stdio.h>
#include <stdlib.h>
/* We remove all the listener code as we won't use any listener */
/* Delete all entities */
static int subscriber_shutdown(DDS_DomainParticipant *participant)
{
DDS_ReturnCode_t retcode;
int status = 0;
if (participant != NULL) {
retcode = DDS_DomainParticipant_delete_contained_entities(participant);
if (retcode != DDS_RETCODE_OK) {
printf("delete_contained_entities error %d\n", retcode);
status = -1;
}
retcode = DDS_DomainParticipantFactory_delete_participant(
DDS_TheParticipantFactory,
participant);
if (retcode != DDS_RETCODE_OK) {
printf("delete_participant error %d\n", retcode);
status = -1;
}
}
/* RTI Connext provides the finalize_instance() method on
domain participant factory for users who want to release memory used
by the participant factory. Uncomment the following block of code for
clean destruction of the singleton. */
/*
retcode = DDS_DomainParticipantFactory_finalize_instance();
if (retcode != DDS_RETCODE_OK) {
printf("finalize_instance error %d\n", retcode);
status = -1;
}
*/
return status;
}
static int subscriber_main(int domainId, int sample_count)
{
DDS_DomainParticipant *participant = NULL;
DDS_Subscriber *subscriber = NULL;
DDS_Topic *topic = NULL;
DDS_DataReader *reader = NULL;
FlightDataReader *flight_reader = NULL;
DDS_ReturnCode_t retcode;
const char *type_name = NULL;
int count = 0;
/* Poll for new samples every second. */
struct DDS_Duration_t poll_period = { 1, 0 };
/* Query Condition-specific types */
DDS_QueryCondition *query_condition;
struct DDS_StringSeq query_parameters;
const char *param_list[] = { "'CompanyA'", "30000" };
/* Create a Participant. */
participant = DDS_DomainParticipantFactory_create_participant(
DDS_TheParticipantFactory,
domainId,
&DDS_PARTICIPANT_QOS_DEFAULT,
NULL /* listener */,
DDS_STATUS_MASK_NONE);
if (participant == NULL) {
printf("create_participant error\n");
subscriber_shutdown(participant);
return -1;
}
/* Createa a Subscriber. */
subscriber = DDS_DomainParticipant_create_subscriber(
participant,
&DDS_SUBSCRIBER_QOS_DEFAULT,
NULL /* listener */,
DDS_STATUS_MASK_NONE);
if (subscriber == NULL) {
printf("create_subscriber error\n");
subscriber_shutdown(participant);
return -1;
}
/* Register the type before creating the topic. */
type_name = FlightTypeSupport_get_type_name();
retcode = FlightTypeSupport_register_type(participant, type_name);
if (retcode != DDS_RETCODE_OK) {
printf("register_type error %d\n", retcode);
subscriber_shutdown(participant);
return -1;
}
/* Create a Topic. */
topic = DDS_DomainParticipant_create_topic(
participant,
"Example Flight",
type_name,
&DDS_TOPIC_QOS_DEFAULT,
NULL /* listener */,
DDS_STATUS_MASK_NONE);
if (topic == NULL) {
printf("create_topic error\n");
subscriber_shutdown(participant);
return -1;
}
/* Call create_datareader passing NULL in the listener parameter. */
reader = DDS_Subscriber_create_datareader(
subscriber,
DDS_Topic_as_topicdescription(topic),
&DDS_DATAREADER_QOS_DEFAULT,
NULL,
DDS_STATUS_MASK_ALL);
if (reader == NULL) {
printf("create_datareader error\n");
subscriber_shutdown(participant);
return -1;
}
flight_reader = FlightDataReader_narrow(reader);
if (flight_reader == NULL) {
printf("DataReader narrow error\n");
return -1;
}
/* Query for company named 'CompanyA' and for flights in cruise
* (about 30,000ft). The company parameter will be changed in run-time.
* NOTE: There must be single-quotes in the query parameters around-any
* strings! The single-quote do NOT go in the query condition itself. */
DDS_StringSeq_ensure_length(&query_parameters, 2, 2);
DDS_StringSeq_from_array(&query_parameters, param_list, 2);
printf("Setting parameter to company %s, altitude bigger or equals to %s\n",
DDS_StringSeq_get(&query_parameters, 0),
DDS_StringSeq_get(&query_parameters, 1));
/* Create the query condition with an expession to MATCH the id field in
* the structure and a numeric comparison. Note that you should make a copy
* of the expression string when creating the query condition - beware it
* going out of scope! */
query_condition = DDS_DataReader_create_querycondition(
reader,
DDS_ANY_SAMPLE_STATE,
DDS_ANY_VIEW_STATE,
DDS_ALIVE_INSTANCE_STATE,
DDS_String_dup("company MATCH %0 AND altitude >= %1"),
&query_parameters);
/* Main loop */
for (count = 0; (sample_count == 0) || (count < sample_count); ++count) {
struct DDS_SampleInfoSeq info_seq;
struct FlightSeq data_seq;
DDS_ReturnCode_t retcode;
int update = 0;
int i = 0;
/* Poll for new samples every second. */
NDDS_Utility_sleep(&poll_period);
/* Change the filter parameter after 5 seconds. */
if ((count + 1) % 10 == 5) {
*DDS_StringSeq_get_reference(&query_parameters, 0) =
DDS_String_dup("'CompanyB'");
update = 1;
} else if ((count + 1) % 10 == 0) {
*DDS_StringSeq_get_reference(&query_parameters, 0) =
DDS_String_dup("'CompanyA'");
update = 1;
}
/* Set new parameters. */
if (update) {
printf("Changing parameter to %s\n",
DDS_StringSeq_get(&query_parameters, 0));
retcode = DDS_QueryCondition_set_query_parameters(
query_condition,
&query_parameters);
if (retcode != DDS_RETCODE_OK) {
printf("Error setting new parameters: %d\n", retcode);
}
}
/* Iterate through the samples read using the read_w_condition method */
retcode = FlightDataReader_read_w_condition(
flight_reader,
&data_seq,
&info_seq,
DDS_LENGTH_UNLIMITED,
DDS_QueryCondition_as_readcondition(query_condition));
if (retcode == DDS_RETCODE_NO_DATA) {
/* Not an error */
continue;
} else if (retcode != DDS_RETCODE_OK) {
/* Is an error */
printf("take error: %d\n", retcode);
break;
}
for (i = 0; i < FlightSeq_get_length(&data_seq); ++i) {
if (DDS_SampleInfoSeq_get_reference(&info_seq, i)->valid_data) {
FlightTypeSupport_print_data(
FlightSeq_get_reference(&data_seq, i));
}
}
retcode = FlightDataReader_return_loan(
flight_reader,
&data_seq,
&info_seq);
if (retcode != DDS_RETCODE_OK) {
printf("return loan error %d\n", retcode);
}
}
/* Cleanup and delete all entities */
return subscriber_shutdown(participant);
}
#if !(defined(RTI_VXWORKS) && !defined(__RTP__)) && !defined(RTI_PSOS)
int main(int argc, char *argv[])
{
int domainId = 0;
int sample_count = 0; /* Infinite loop */
if (argc >= 2) {
domainId = atoi(argv[1]);
}
if (argc >= 3) {
sample_count = atoi(argv[2]);
}
/* Uncomment this to turn on additional logging
NDDS_Config_Logger_set_verbosity_by_category(
NDDS_Config_Logger_get_instance(),
NDDS_CONFIG_LOG_CATEGORY_API,
NDDS_CONFIG_LOG_VERBOSITY_STATUS_ALL); */
return subscriber_main(domainId, sample_count);
}
#endif
#ifdef RTI_VX653
const unsigned char *__ctype = NULL;
void usrAppInit()
{
#ifdef USER_APPL_INIT
USER_APPL_INIT; /* for backwards compatibility */
#endif
/* add application specific code here */
taskSpawn(
"sub",
RTI_OSAPI_THREAD_PRIORITY_NORMAL,
0x8,
0x150000,
(FUNCPTR) subscriber_main,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0);
}
#endif
| c |
rticonnextdds-examples | data/projects/rticonnextdds-examples/connext_dds/polling_querycondition/c++03/flights_subscriber.cxx | /*******************************************************************************
(c) 2005-2015 Copyright, Real-Time Innovations, Inc. All rights reserved.
RTI grants Licensee a license to use, modify, compile, and create derivative
works of the Software. Licensee has the right to distribute object form only
for use with RTI products. The Software is provided "as is", with no warranty
of any type, including any warranty for fitness for any purpose. RTI is under
no obligation to maintain or support the Software. RTI shall not be liable for
any incidental or consequential damages arising out of the use or inability to
use the software.
******************************************************************************/
#include "flights.hpp"
#include <dds/dds.hpp>
#include <iostream>
using namespace dds::core;
using namespace dds::core::policy;
using namespace dds::domain;
using namespace dds::topic;
using namespace dds::sub;
using namespace dds::sub::cond;
using namespace dds::sub::qos;
using namespace dds::sub::status;
void subscriber_main(int domain_id, int sample_count)
{
// Create a DomainParticipant with default Qos.
DomainParticipant participant(domain_id);
// Create a Topic -- and automatically register the type.
Topic<Flight> topic(participant, "Example Flight");
// Retrieve the default DataWriter QoS, from USER_QOS_PROFILES.xml
DataReaderQos reader_qos = QosProvider::Default().datareader_qos();
// If you want to change the DataReader's QoS programmatically rather than
// using the XML file, uncomment the following lines.
// reader_qos << Reliability::Reliable();
// Create a DataReader.
DataReader<Flight> reader(Subscriber(participant), topic, reader_qos);
// Query for company named 'CompanyA' and for flights in cruise
// (about 30,000ft). The company parameter will be changed in run-time.
// NOTE: There must be single-quotes in the query parameters around-any
// strings! The single-quote do NOT go in the query condition itself.
std::vector<std::string> query_parameters(2);
query_parameters[0] = "'CompanyA'";
query_parameters[1] = "30000";
std::cout << "Setting parameters to company: " << query_parameters[0]
<< " and altitude bigger or equals to " << query_parameters[1]
<< std::endl;
// Create the query condition with an expession to MATCH the id field in
// the structure and a numeric comparison.
QueryCondition query_condition(
Query(reader,
"company MATCH %0 AND altitude >= %1",
query_parameters),
DataState::any_data());
// Main loop
bool update = false;
for (int count = 0; (sample_count == 0) || (count < sample_count);
count++) {
// Poll for new samples every second.
rti::util::sleep(Duration(1));
// Change the filter parameter after 5 seconds.
if ((count + 1) % 10 == 5) {
query_parameters[0] = "'CompanyB'";
update = true;
} else if ((count + 1) % 10 == 0) {
query_parameters[0] = "'CompanyA'";
update = true;
}
// Set new parameters.
if (update) {
std::cout << "Changing parameter to " << query_parameters[0]
<< std::endl;
query_condition.parameters(
query_parameters.begin(),
query_parameters.end());
update = false;
}
// Get new samples selecting them with a condition.
LoanedSamples<Flight> samples =
reader.select().condition(query_condition).read();
for (LoanedSamples<Flight>::iterator sampleIt = samples.begin();
sampleIt != samples.end();
++sampleIt) {
if (!sampleIt->info().valid())
continue;
std::cout << "\t" << sampleIt->data() << std::endl;
}
}
}
int main(int argc, char *argv[])
{
int domain_id = 0;
int sample_count = 0; // Infinite loop
if (argc >= 2) {
domain_id = atoi(argv[1]);
}
if (argc >= 3) {
sample_count = atoi(argv[2]);
}
// To turn on additional logging, include <rti/config/Logger.hpp> and
// uncomment the following line:
// rti::config::Logger::instance()l.verbosity(rti::config::Verbosity::STATUS_ALL);
try {
subscriber_main(domain_id, sample_count);
} catch (std::exception ex) {
std::cout << "Exception caught: " << ex.what() << std::endl;
return -1;
}
return 0;
}
| cxx |
rticonnextdds-examples | data/projects/rticonnextdds-examples/connext_dds/polling_querycondition/c++03/flights_publisher.cxx | /*******************************************************************************
(c) 2005-2015 Copyright, Real-Time Innovations, Inc. All rights reserved.
RTI grants Licensee a license to use, modify, compile, and create derivative
works of the Software. Licensee has the right to distribute object form only
for use with RTI products. The Software is provided "as is", with no warranty
of any type, including any warranty for fitness for any purpose. RTI is under
no obligation to maintain or support the Software. RTI shall not be liable for
any incidental or consequential damages arising out of the use or inability to
use the software.
******************************************************************************/
#include "flights.hpp"
#include <dds/dds.hpp>
#include <iostream>
using namespace dds::core;
using namespace dds::core::policy;
using namespace dds::domain;
using namespace dds::topic;
using namespace dds::pub;
using namespace dds::pub::qos;
void publisher_main(int domain_id, int sample_count)
{
// Create a DomainParticipant with default Qos.
DomainParticipant participant(domain_id);
// Create a Topic -- and automatically register the type.
Topic<Flight> topic(participant, "Example Flight");
// Retrieve the default DataWriter QoS, from USER_QOS_PROFILES.xml
DataWriterQos writer_qos = QosProvider::Default().datawriter_qos();
// If you want to change the DataReader's QoS programmatically rather than
// using the XML file, uncomment the following lines.
// writer_qos << Reliability::Reliable();
// Create a DataWriter.
DataWriter<Flight> writer(Publisher(participant), topic, writer_qos);
// Create the flight info samples.
std::vector<Flight> flights_info(4);
flights_info[0] = Flight(1111, "CompanyA", 15000);
flights_info[1] = Flight(2222, "CompanyB", 20000);
flights_info[2] = Flight(3333, "CompanyA", 30000);
flights_info[3] = Flight(4444, "CompanyB", 25000);
// Main loop
for (int count = 0; (sample_count == 0) || (count < sample_count);
count += flights_info.size()) {
// Update flight info latitude
std::cout << "Updating and sending values" << std::endl;
for (std::vector<int>::size_type f = 0; f < flights_info.size(); f++) {
// Set the plane altitude lineally (usually the max is at 41,000ft).
int altitude = flights_info[f].altitude() + count * 100;
flights_info[f].altitude(altitude >= 41000 ? 41000 : altitude);
std::cout << "\t" << flights_info[f] << std::endl;
}
writer.write(flights_info.begin(), flights_info.end());
rti::util::sleep(Duration(1));
}
}
int main(int argc, char *argv[])
{
int domain_id = 0;
int sample_count = 0; // Infinite loop
if (argc >= 2) {
domain_id = atoi(argv[1]);
}
if (argc >= 3) {
sample_count = atoi(argv[2]);
}
// To turn on additional logging, include <rti/config/Logger.hpp> and
// uncomment the following line:
// rti::config::Logger::instance().verbosity(rti::config::Verbosity::STATUS_ALL);
try {
publisher_main(domain_id, sample_count);
} catch (std::exception ex) {
std::cout << "Exception caught: " << ex.what() << std::endl;
return -1;
}
return 0;
}
| cxx |
rticonnextdds-examples | data/projects/rticonnextdds-examples/connext_dds/polling_querycondition/c++11/application.hpp | /*
* (c) Copyright, Real-Time Innovations, 2020. All rights reserved.
* RTI grants Licensee a license to use, modify, compile, and create derivative
* works of the software solely for use with RTI Connext DDS. Licensee may
* redistribute copies of the software provided that all such copies are subject
* to this license. The software is provided "as is", with no warranty of any
* type, including any warranty for fitness for any purpose. RTI is under no
* obligation to maintain or support the software. RTI shall not be liable for
* any incidental or consequential damages arising out of the use or inability
* to use the software.
*/
#ifndef APPLICATION_HPP
#define APPLICATION_HPP
#include <iostream>
#include <csignal>
#include <dds/core/ddscore.hpp>
namespace application {
// Catch control-C and tell application to shut down
bool shutdown_requested = false;
inline void stop_handler(int)
{
shutdown_requested = true;
std::cout << "preparing to shut down..." << std::endl;
}
inline void setup_signal_handlers()
{
signal(SIGINT, stop_handler);
signal(SIGTERM, stop_handler);
}
enum class ParseReturn { ok, failure, exit };
struct ApplicationArguments {
ParseReturn parse_result;
unsigned int domain_id;
unsigned int sample_count;
rti::config::Verbosity verbosity;
ApplicationArguments(
ParseReturn parse_result_param,
unsigned int domain_id_param,
unsigned int sample_count_param,
rti::config::Verbosity verbosity_param)
: parse_result(parse_result_param),
domain_id(domain_id_param),
sample_count(sample_count_param),
verbosity(verbosity_param)
{
}
};
inline void set_verbosity(
rti::config::Verbosity &verbosity,
int verbosity_value)
{
switch (verbosity_value) {
case 0:
verbosity = rti::config::Verbosity::SILENT;
break;
case 1:
verbosity = rti::config::Verbosity::EXCEPTION;
break;
case 2:
verbosity = rti::config::Verbosity::WARNING;
break;
case 3:
verbosity = rti::config::Verbosity::STATUS_ALL;
break;
default:
verbosity = rti::config::Verbosity::EXCEPTION;
break;
}
}
// Parses application arguments for example.
inline ApplicationArguments parse_arguments(int argc, char *argv[])
{
int arg_processing = 1;
bool show_usage = false;
ParseReturn parse_result = ParseReturn::ok;
unsigned int domain_id = 0;
unsigned int sample_count = (std::numeric_limits<unsigned int>::max)();
rti::config::Verbosity verbosity(rti::config::Verbosity::EXCEPTION);
while (arg_processing < argc) {
if ((argc > arg_processing + 1)
&& (strcmp(argv[arg_processing], "-d") == 0
|| strcmp(argv[arg_processing], "--domain") == 0)) {
domain_id = atoi(argv[arg_processing + 1]);
arg_processing += 2;
} else if (
(argc > arg_processing + 1)
&& (strcmp(argv[arg_processing], "-s") == 0
|| strcmp(argv[arg_processing], "--sample-count") == 0)) {
sample_count = atoi(argv[arg_processing + 1]);
arg_processing += 2;
} else if (
(argc > arg_processing + 1)
&& (strcmp(argv[arg_processing], "-v") == 0
|| strcmp(argv[arg_processing], "--verbosity") == 0)) {
set_verbosity(verbosity, atoi(argv[arg_processing + 1]));
arg_processing += 2;
} else if (
strcmp(argv[arg_processing], "-h") == 0
|| strcmp(argv[arg_processing], "--help") == 0) {
std::cout << "Example application." << std::endl;
show_usage = true;
parse_result = ParseReturn::exit;
break;
} else {
std::cout << "Bad parameter." << std::endl;
show_usage = true;
parse_result = ParseReturn::failure;
break;
}
}
if (show_usage) {
std::cout << "Usage:\n"
" -d, --domain <int> Domain ID this "
"application will\n"
" subscribe in. \n"
" Default: 0\n"
" -s, --sample_count <int> Number of samples to "
"receive before\n"
" cleanly shutting down. \n"
" Default: infinite\n"
" -v, --verbosity <int> How much debugging output "
"to show.\n"
" Range: 0-3 \n"
" Default: 1"
<< std::endl;
}
return ApplicationArguments(
parse_result,
domain_id,
sample_count,
verbosity);
}
} // namespace application
#endif // APPLICATION_HPP | hpp |
rticonnextdds-examples | data/projects/rticonnextdds-examples/connext_dds/polling_querycondition/c++11/flights_subscriber.cxx | /*******************************************************************************
(c) 2005-2015 Copyright, Real-Time Innovations, Inc. All rights reserved.
RTI grants Licensee a license to use, modify, compile, and create derivative
works of the Software. Licensee has the right to distribute object form only
for use with RTI products. The Software is provided "as is", with no warranty
of any type, including any warranty for fitness for any purpose. RTI is under
no obligation to maintain or support the Software. RTI shall not be liable for
any incidental or consequential damages arising out of the use or inability to
use the software.
******************************************************************************/
#include <dds/sub/ddssub.hpp>
#include <dds/core/ddscore.hpp>
#include <rti/util/util.hpp> // for sleep()
#include <rti/config/Logger.hpp> // for logging
#include "flights.hpp"
#include "application.hpp" // for command line parsing and ctrl-c
void run_subscriber_application(
unsigned int domain_id,
unsigned int sample_count)
{
// Create a DomainParticipant with default Qos.
dds::domain::DomainParticipant participant(domain_id);
// Create a Topic -- and automatically register the type.
dds::topic::Topic<Flight> topic(participant, "Example Flight");
// Retrieve the default DataWriter QoS, from USER_QOS_PROFILES.xml
dds::sub::qos::DataReaderQos reader_qos =
dds::core::QosProvider::Default().datareader_qos();
// If you want to change the DataReader's QoS programmatically rather than
// using the XML file, uncomment the following lines.
// reader_qos << Reliability::Reliable();
// Create a subscriber
dds::sub::Subscriber subscriber(participant);
// Create a DataReader.
dds::sub::DataReader<Flight> reader(subscriber, topic, reader_qos);
// Query for company named 'CompanyA' and for flights in cruise
// (about 30,000ft). The company parameter will be changed in run-time.
// NOTE: There must be single-quotes in the query parameters around-any
// strings! The single-quote do NOT go in the query condition itself.
std::vector<std::string> query_parameters = { "'CompanyA'", "30000" };
std::cout << "Setting parameters to company: " << query_parameters[0]
<< " and altitude bigger or equals to " << query_parameters[1]
<< std::endl;
// Create the query condition with an expession to MATCH the id field in
// the structure and a numeric comparison.
dds::sub::cond::QueryCondition query_condition(
dds::sub::Query(
reader,
"company MATCH %0 AND altitude >= %1",
query_parameters),
dds::sub::status::DataState::any_data());
// Main loop
bool update = false;
int samples_read = 0, count = 0;
while (!application::shutdown_requested && samples_read < sample_count) {
// Poll for new samples every second.
rti::util::sleep(dds::core::Duration(1));
// Change the filter parameter after 5 seconds.
if ((count + 1) % 10 == 5) {
query_parameters[0] = "'CompanyB'";
update = true;
} else if ((count + 1) % 10 == 0) {
query_parameters[0] = "'CompanyA'";
update = true;
}
// Set new parameters.
if (update) {
std::cout << "Changing parameter to " << query_parameters[0]
<< std::endl;
query_condition.parameters(
query_parameters.begin(),
query_parameters.end());
update = false;
}
// Get new samples selecting them with a condition.
dds::sub::LoanedSamples<Flight> samples =
reader.select().condition(query_condition).read();
for (const auto &sample : samples) {
if (sample.info().valid()) {
samples_read++;
std::cout << "\t" << sample.data() << std::endl;
}
}
count++;
}
}
int main(int argc, char *argv[])
{
using namespace application;
// Parse arguments and handle control-C
auto arguments = parse_arguments(argc, argv);
if (arguments.parse_result == ParseReturn::exit) {
return EXIT_SUCCESS;
} else if (arguments.parse_result == ParseReturn::failure) {
return EXIT_FAILURE;
}
setup_signal_handlers();
// Sets Connext verbosity to help debugging
rti::config::Logger::instance().verbosity(arguments.verbosity);
try {
run_subscriber_application(arguments.domain_id, arguments.sample_count);
} catch (const std::exception &ex) {
// This will catch DDS exceptions
std::cerr << "Exception in run_subscriber_application(): " << ex.what()
<< std::endl;
return EXIT_FAILURE;
}
// Releases the memory used by the participant factory. Optional at
// application exit
dds::domain::DomainParticipant::finalize_participant_factory();
return EXIT_SUCCESS;
}
| cxx |
rticonnextdds-examples | data/projects/rticonnextdds-examples/connext_dds/polling_querycondition/c++11/flights_publisher.cxx | /*******************************************************************************
(c) 2005-2015 Copyright, Real-Time Innovations, Inc. All rights reserved.
RTI grants Licensee a license to use, modify, compile, and create derivative
works of the Software. Licensee has the right to distribute object form only
for use with RTI products. The Software is provided "as is", with no warranty
of any type, including any warranty for fitness for any purpose. RTI is under
no obligation to maintain or support the Software. RTI shall not be liable for
any incidental or consequential damages arising out of the use or inability to
use the software.
******************************************************************************/
#include <dds/pub/ddspub.hpp>
#include <rti/util/util.hpp> // for sleep()
#include <rti/config/Logger.hpp> // for logging
#include "application.hpp" // for command line parsing and ctrl-c
#include "flights.hpp"
void run_publisher_application(
unsigned int domain_id,
unsigned int sample_count)
{
// Create a DomainParticipant with default Qos.
dds::domain::DomainParticipant participant(domain_id);
// Create a Topic -- and automatically register the type.
dds::topic::Topic<Flight> topic(participant, "Example Flight");
// Retrieve the default DataWriter QoS, from USER_QOS_PROFILES.xml
dds::pub::qos::DataWriterQos writer_qos =
dds::core::QosProvider::Default().datawriter_qos();
// If you want to change the DataReader's QoS programmatically rather than
// using the XML file, uncomment the following lines.
// writer_qos << Reliability::Reliable();
// Create a publisher
dds::pub::Publisher publisher(participant);
// Create a DataWriter.
dds::pub::DataWriter<Flight> writer(publisher, topic, writer_qos);
// Create the flight info samples.
std::vector<Flight> flights_info { Flight(1111, "CompanyA", 15000),
Flight(2222, "CompanyB", 20000),
Flight(3333, "CompanyA", 30000),
Flight(4444, "CompanyB", 25000) };
// Main loop
for (unsigned int samples_written = 0;
!application::shutdown_requested && samples_written < sample_count;
samples_written++) {
// Update flight info latitude
std::cout << "Updating and sending values" << std::endl;
for (auto &flight : flights_info) {
// Set the plane altitude lineally (usually the max is at 41,000ft).
int altitude = flight.altitude() + samples_written * 100;
flight.altitude(altitude >= 41000 ? 41000 : altitude);
std::cout << "\t" << flight << std::endl;
}
writer.write(flights_info.begin(), flights_info.end());
rti::util::sleep(dds::core::Duration(1));
}
}
int main(int argc, char *argv[])
{
using namespace application;
// Parse arguments and handle control-C
auto arguments = parse_arguments(argc, argv);
if (arguments.parse_result == ParseReturn::exit) {
return EXIT_SUCCESS;
} else if (arguments.parse_result == ParseReturn::failure) {
return EXIT_FAILURE;
}
setup_signal_handlers();
// Sets Connext verbosity to help debugging
rti::config::Logger::instance().verbosity(arguments.verbosity);
try {
run_publisher_application(arguments.domain_id, arguments.sample_count);
} catch (const std::exception &ex) {
// This will catch DDS exceptions
std::cerr << "Exception in run_publisher_application(): " << ex.what()
<< std::endl;
return EXIT_FAILURE;
}
// Releases the memory used by the participant factory. Optional at
// application exit
dds::domain::DomainParticipant::finalize_participant_factory();
return EXIT_SUCCESS;
}
| cxx |
rticonnextdds-examples | data/projects/rticonnextdds-examples/connext_dds/deadline_contentfilter/c++/deadline_contentfilter_subscriber.cxx | /*******************************************************************************
(c) 2005-2014 Copyright, Real-Time Innovations, Inc. All rights reserved.
RTI grants Licensee a license to use, modify, compile, and create derivative
works of the Software. Licensee has the right to distribute object form only
for use with RTI products. The Software is provided "as is", with no warranty
of any type, including any warranty for fitness for any purpose. RTI is under
no obligation to maintain or support the Software. RTI shall not be liable for
any incidental or consequential damages arising out of the use or inability to
use the software.
******************************************************************************/
/* deadline_contentfilter_subscriber.cxx
A subscription example
This file is derived from code automatically generated by the rtiddsgen
command:
rtiddsgen -language C++ -example <arch> deadline_contentfilter.idl
Example subscription of type deadline_contentfilter automatically generated
by 'rtiddsgen'. To test them follow these steps:
(1) Compile this file and the example publication.
(2) Start the subscription on the same domain used for RTI Data Distribution
Service with the command
objs/<arch>/deadline_contentfilter_subscriber <domain_id> <sample_count>
(3) Start the publication on the same domain used for RTI Data Distribution
with the command
objs/<arch>/deadline_contentfilter_publisher <domain_id> <sample_count>
(4) [Optional] Specify the list of discovery initial peers and
multicast receive addresses via an environment variable or a file
(in the current working directory) called NDDS_DISCOVERY_PEERS.
You can run any number of publishers and subscribers programs, and can
add and remove them dynamically from the domain.
Example:
To run the example application on domain <domain_id>:
On Unix:
objs/<arch>/deadline_contentfilter_publisher <domain_id>
objs/<arch>/deadline_contentfilter_subscriber <domain_id>
On Windows:
objs\<arch>\deadline_contentfilter_publisher <domain_id>
objs\<arch>\deadline_contentfilter_subscriber <domain_id>
modification history
------------ -------
* Create clock to show relative timing of events
* Define listener for requested deadline missed status
* Set deadline QoS
* Create content filter that ignores second instance
after 5 seconds
*/
/* This example sets the deadline period to 2 seconds to trigger a deadline if
the DataWriter does not update often enough, or if the content-filter
filters out data so there is no data available within 2 seconds.
This example starts by filtering out instances >= 2, and changes to later
filter out instances >= 1.
*/
#include "deadline_contentfilter.h"
#include "deadline_contentfilterSupport.h"
#include "ndds/ndds_cpp.h"
#include <stdio.h>
#include <stdlib.h>
//// Changes for Deadline
// For timekeeping
#include <time.h>
clock_t init;
class deadline_contentfilterListener : public DDSDataReaderListener {
public:
virtual void on_requested_deadline_missed(
DDSDataReader * /*reader*/,
const DDS_RequestedDeadlineMissedStatus & /*status*/);
virtual void on_requested_incompatible_qos(
DDSDataReader * /*reader*/,
const DDS_RequestedIncompatibleQosStatus & /*status*/)
{
}
virtual void on_sample_rejected(
DDSDataReader * /*reader*/,
const DDS_SampleRejectedStatus & /*status*/)
{
}
virtual void on_liveliness_changed(
DDSDataReader * /*reader*/,
const DDS_LivelinessChangedStatus & /*status*/)
{
}
virtual void on_sample_lost(
DDSDataReader * /*reader*/,
const DDS_SampleLostStatus & /*status*/)
{
}
virtual void on_subscription_matched(
DDSDataReader * /*reader*/,
const DDS_SubscriptionMatchedStatus & /*status*/)
{
}
virtual void on_data_available(DDSDataReader *reader);
};
/* Start changes for Deadline */
void deadline_contentfilterListener::on_requested_deadline_missed(
DDSDataReader *reader,
const DDS_RequestedDeadlineMissedStatus &status)
{
double elapsed_ticks = clock() - init;
double elapsed_secs = elapsed_ticks / CLOCKS_PER_SEC;
/* Creates a temporary object of our structure "deadline_contentfilter"
* in order to find out which instance missed its deadline period. The
* get_key_value call only fills in the values of the key fields inside
* the dummy object.
*/
deadline_contentfilter dummy;
DDS_ReturnCode_t retcode =
((deadline_contentfilterDataReader *) reader)
->get_key_value(dummy, status.last_instance_handle);
if (retcode != DDS_RETCODE_OK) {
printf("get_key_value error %d\n", retcode);
return;
}
/* Print out which instance missed its deadline. */
printf("Missed deadline @ t=%.2fs on instance code = %d\n",
elapsed_secs,
dummy.code);
}
/* End changes for Deadline */
void deadline_contentfilterListener::on_data_available(DDSDataReader *reader)
{
deadline_contentfilterDataReader *deadline_contentfilter_reader = NULL;
deadline_contentfilterSeq data_seq;
DDS_SampleInfoSeq info_seq;
DDS_ReturnCode_t retcode;
int i;
deadline_contentfilter_reader =
deadline_contentfilterDataReader::narrow(reader);
if (deadline_contentfilter_reader == NULL) {
printf("DataReader narrow error\n");
return;
}
retcode = deadline_contentfilter_reader->take(
data_seq,
info_seq,
DDS_LENGTH_UNLIMITED,
DDS_ANY_SAMPLE_STATE,
DDS_ANY_VIEW_STATE,
DDS_ANY_INSTANCE_STATE);
if (retcode == DDS_RETCODE_NO_DATA) {
return;
} else if (retcode != DDS_RETCODE_OK) {
printf("take error %d\n", retcode);
return;
}
for (i = 0; i < data_seq.length(); ++i) {
if (info_seq[i].valid_data) {
/* Start changes for Deadline */
/* print the time we get each sample. */
double elapsed_ticks = clock() - init;
double elapsed_secs = elapsed_ticks / CLOCKS_PER_SEC;
printf("@ t=%.2fs, Instance%d: <%d,%d>\n",
elapsed_secs,
data_seq[i].code,
data_seq[i].x,
data_seq[i].y);
/* deadlineTypeSupport::print_data(&data_seq[i]); */
/* End changes for Deadline */
}
}
retcode = deadline_contentfilter_reader->return_loan(data_seq, info_seq);
if (retcode != DDS_RETCODE_OK) {
printf("return loan error %d\n", retcode);
}
}
/* Delete all entities */
static int subscriber_shutdown(DDSDomainParticipant *participant)
{
DDS_ReturnCode_t retcode;
int status = 0;
if (participant != NULL) {
retcode = participant->delete_contained_entities();
if (retcode != DDS_RETCODE_OK) {
printf("delete_contained_entities error %d\n", retcode);
status = -1;
}
retcode = DDSTheParticipantFactory->delete_participant(participant);
if (retcode != DDS_RETCODE_OK) {
printf("delete_participant error %d\n", retcode);
status = -1;
}
}
/* RTI Data Distribution Service provides finalize_instance() method for
people who want to release memory used by the participant factory
singleton. Uncomment the following block of code for clean destruction of
the participant factory singleton. */
/*
retcode = DDSDomainParticipantFactory::finalize_instance();
if (retcode != DDS_RETCODE_OK) {
printf("finalize_instance error %d\n", retcode);
status = -1;
}
*/
return status;
}
extern "C" int subscriber_main(int domainId, int sample_count)
{
DDSDomainParticipant *participant = NULL;
DDSSubscriber *subscriber = NULL;
DDSTopic *topic = NULL;
deadline_contentfilterListener *reader_listener = NULL;
DDSDataReader *reader = NULL;
DDS_ReturnCode_t retcode;
const char *type_name = NULL;
int count = 0;
struct DDS_Duration_t receive_period = { 1, 0 };
int status = 0;
/* Changes for Deadline */
/* for timekeeping */
init = clock();
/* To customize participant QoS, use
DDSTheParticipantFactory->get_default_participant_qos() */
participant = DDSTheParticipantFactory->create_participant(
domainId,
DDS_PARTICIPANT_QOS_DEFAULT,
NULL /* listener */,
DDS_STATUS_MASK_NONE);
if (participant == NULL) {
printf("create_participant error\n");
subscriber_shutdown(participant);
return -1;
}
/* To customize subscriber QoS, use
participant->get_default_subscriber_qos() */
subscriber = participant->create_subscriber(
DDS_SUBSCRIBER_QOS_DEFAULT,
NULL /* listener */,
DDS_STATUS_MASK_NONE);
if (subscriber == NULL) {
printf("create_subscriber error\n");
subscriber_shutdown(participant);
return -1;
}
/* Register type before creating topic */
type_name = deadline_contentfilterTypeSupport::get_type_name();
retcode = deadline_contentfilterTypeSupport::register_type(
participant,
type_name);
if (retcode != DDS_RETCODE_OK) {
printf("register_type error %d\n", retcode);
subscriber_shutdown(participant);
return -1;
}
/* To customize topic QoS, use
participant->get_default_topic_qos() */
topic = participant->create_topic(
"Example deadline_contentfilter",
type_name,
DDS_TOPIC_QOS_DEFAULT,
NULL /* listener */,
DDS_STATUS_MASK_NONE);
if (topic == NULL) {
printf("create_topic error\n");
subscriber_shutdown(participant);
return -1;
}
/* Create data reader listener */
reader_listener = new deadline_contentfilterListener();
if (reader_listener == NULL) {
printf("listener instantiation error\n");
subscriber_shutdown(participant);
return -1;
}
/* Start changes for Deadline */
/* Set up content filtered topic to show interaction with deadline */
DDS_StringSeq parameters(1);
const char *param_list[] = { "2" };
parameters.from_array(param_list, 1);
DDSContentFilteredTopic *cft = NULL;
cft = participant->create_contentfilteredtopic(
"ContentFilteredTopic",
topic,
"code < %0",
parameters);
/* Get default datareader QoS to customize */
DDS_DataReaderQos datareader_qos;
retcode = subscriber->get_default_datareader_qos(datareader_qos);
if (retcode != DDS_RETCODE_OK) {
printf("get_default_datareader_qos error\n");
subscriber_shutdown(participant);
delete reader_listener;
return -1;
}
reader = subscriber->create_datareader(
cft,
DDS_DATAREADER_QOS_DEFAULT,
reader_listener,
DDS_STATUS_MASK_ALL);
if (reader == NULL) {
printf("create_datareader error\n");
subscriber_shutdown(participant);
delete reader_listener;
return -1;
}
/* If you want to change the DataReader's QoS programmatically rather than
* using the XML file, you will need to add the following lines to your
* code and comment out the create_datareader call above.
*
* In this case, we set the deadline period to 2 seconds to trigger
* a deadline if the DataWriter does not update often enough, or if
* the content-filter filters out data so there is no data available
* with 2 seconds.
*/
/* Set deadline QoS */
/* DDS_Duration_t deadline_period = {2, 0};
datareader_qos.deadline.period = deadline_period;
reader = subscriber->create_datareader(
cft, datareader_qos, reader_listener,
DDS_STATUS_MASK_ALL);
if (reader == NULL) {
printf("create_datareader error\n");
subscriber_shutdown(participant);
delete reader_listener;
return -1;
}
*/
/* Main loop */
for (count = 0; (sample_count == 0) || (count < sample_count); ++count) {
/* printf("deadline_contentfilter subscriber sleeping for %d
sec...\n", receive_period.sec);
*/
/* After 10 seconds, change content filter to accept only instance 0 */
if (count == 10) {
printf("Starting to filter out instance1\n");
parameters[0] = DDS_String_dup("1");
cft->set_expression_parameters(parameters);
}
NDDSUtility::sleep(receive_period);
}
/* End changes for Deadline */
/* Delete all entities */
status = subscriber_shutdown(participant);
delete reader_listener;
return status;
}
#if defined(RTI_WINCE)
int wmain(int argc, wchar_t **argv)
{
int domainId = 0;
int sample_count = 0; /* infinite loop */
if (argc >= 2) {
domainId = _wtoi(argv[1]);
}
if (argc >= 3) {
sample_count = _wtoi(argv[2]);
}
/* Uncomment this to turn on additional logging
NDDSConfigLogger::get_instance()->
set_verbosity_by_category(NDDS_CONFIG_LOG_CATEGORY_API,
NDDS_CONFIG_LOG_VERBOSITY_STATUS_ALL);
*/
return subscriber_main(domainId, sample_count);
}
#elif !(defined(RTI_VXWORKS) && !defined(__RTP__)) && !defined(RTI_PSOS)
int main(int argc, char *argv[])
{
int domainId = 0;
int sample_count = 0; /* infinite loop */
if (argc >= 2) {
domainId = atoi(argv[1]);
}
if (argc >= 3) {
sample_count = atoi(argv[2]);
}
/* Uncomment this to turn on additional logging
NDDSConfigLogger::get_instance()->
set_verbosity_by_category(NDDS_CONFIG_LOG_CATEGORY_API,
NDDS_CONFIG_LOG_VERBOSITY_STATUS_ALL);
*/
return subscriber_main(domainId, sample_count);
}
#endif
| cxx |
rticonnextdds-examples | data/projects/rticonnextdds-examples/connext_dds/deadline_contentfilter/c++/deadline_contentfilter_publisher.cxx | /*******************************************************************************
(c) 2005-2014 Copyright, Real-Time Innovations, Inc. All rights reserved.
RTI grants Licensee a license to use, modify, compile, and create derivative
works of the Software. Licensee has the right to distribute object form only
for use with RTI products. The Software is provided "as is", with no warranty
of any type, including any warranty for fitness for any purpose. RTI is under
no obligation to maintain or support the Software. RTI shall not be liable for
any incidental or consequential damages arising out of the use or inability to
use the software.
******************************************************************************/
/* deadline_contentfilter_publisher.cxx
A publication of data of type deadline_contentfilter
This file is derived from code automatically generated by the rtiddsgen
command:
rtiddsgen -language C++ -example <arch> deadline_contentfilter.idl
Example publication of type deadline_contentfilter automatically generated by
'rtiddsgen'. To test them follow these steps:
(1) Compile this file and the example subscription.
(2) Start the subscription on the same domain used for RTI Data Distribution
with the command
objs/<arch>/deadline_contentfilter_subscriber <domain_id> <sample_count>
(3) Start the publication on the same domain used for RTI Data Distribution
with the command
objs/<arch>/deadline_contentfilter_publisher <domain_id> <sample_count>
(4) [Optional] Specify the list of discovery initial peers and
multicast receive addresses via an environment variable or a file
(in the current working directory) called NDDS_DISCOVERY_PEERS.
You can run any number of publishers and subscribers programs, and can
add and remove them dynamically from the domain.
Example:
To run the example application on domain <domain_id>:
On Unix:
objs/<arch>/deadline_contentfilter_publisher <domain_id> o
objs/<arch>/deadline_contentfilter_subscriber <domain_id>
On Windows:
objs\<arch>\deadline_contentfilter_publisher <domain_id>
objs\<arch>\deadline_contentfilter_subscriber <domain_id>
modification history
------------ -------
* Create and install listener for offered deadline missed status
* Set deadline QoS
*/
/* This example sets the deadline period to 1.5 seconds to trigger a deadline
if the DataWriter does not update often enough. The writer's updates are
dependent on the application code, so the middleware can notify the
application that it has failed to update often enough.
*/
#include "deadline_contentfilter.h"
#include "deadline_contentfilterSupport.h"
#include "ndds/ndds_cpp.h"
#include <stdio.h>
#include <stdlib.h>
/* Start changes for Deadline */
class deadline_contentfilterListener : public DDSDataWriterListener {
public:
virtual void on_offered_deadline_missed(
DDSDataWriter *writer,
const DDS_OfferedDeadlineMissedStatus &status)
{
deadline_contentfilter dummy;
DDS_ReturnCode_t retcode =
((deadline_contentfilterDataWriter *) writer)
->get_key_value(dummy, status.last_instance_handle);
if (retcode != DDS_RETCODE_OK) {
printf("get_key_value error %d\n", retcode);
return;
}
printf("Offered deadline missed on instance code = %d\n", dummy.code);
}
};
/* End changes for Deadline */
/* Delete all entities */
static int publisher_shutdown(DDSDomainParticipant *participant)
{
DDS_ReturnCode_t retcode;
int status = 0;
if (participant != NULL) {
retcode = participant->delete_contained_entities();
if (retcode != DDS_RETCODE_OK) {
printf("delete_contained_entities error %d\n", retcode);
status = -1;
}
retcode = DDSTheParticipantFactory->delete_participant(participant);
if (retcode != DDS_RETCODE_OK) {
printf("delete_participant error %d\n", retcode);
status = -1;
}
}
/* RTI Data Distribution Service provides finalize_instance() method for
people who want to release memory used by the participant factory
singleton. Uncomment the following block of code for clean destruction of
the participant factory singleton. */
/*
retcode = DDSDomainParticipantFactory::finalize_instance();
if (retcode != DDS_RETCODE_OK) {
printf("finalize_instance error %d\n", retcode);
status = -1;
}
*/
return status;
}
extern "C" int publisher_main(int domainId, int sample_count)
{
DDSDomainParticipant *participant = NULL;
DDSPublisher *publisher = NULL;
DDSTopic *topic = NULL;
DDSDataWriter *writer = NULL;
deadline_contentfilterDataWriter *deadline_contentfilter_writer = NULL;
DDS_ReturnCode_t retcode;
const char *type_name = NULL;
int count = 0;
/* To customize participant QoS, use
DDSTheParticipantFactory->get_default_participant_qos() */
participant = DDSTheParticipantFactory->create_participant(
domainId,
DDS_PARTICIPANT_QOS_DEFAULT,
NULL /* listener */,
DDS_STATUS_MASK_NONE);
if (participant == NULL) {
printf("create_participant error\n");
publisher_shutdown(participant);
return -1;
}
/* To customize publisher QoS, use
participant->get_default_publisher_qos() */
publisher = participant->create_publisher(
DDS_PUBLISHER_QOS_DEFAULT,
NULL /* listener */,
DDS_STATUS_MASK_NONE);
if (publisher == NULL) {
printf("create_participant error\n");
publisher_shutdown(participant);
return -1;
}
/* Register type before creating topic */
type_name = deadline_contentfilterTypeSupport::get_type_name();
retcode = deadline_contentfilterTypeSupport::register_type(
participant,
type_name);
if (retcode != DDS_RETCODE_OK) {
printf("register_type error %d\n", retcode);
publisher_shutdown(participant);
return -1;
}
/* To customize topic QoS, use
participant->get_default_topic_qos() */
topic = participant->create_topic(
"Example deadline_contentfilter",
type_name,
DDS_TOPIC_QOS_DEFAULT,
NULL /* listener */,
DDS_STATUS_MASK_NONE);
if (topic == NULL) {
printf("create_topic error\n");
publisher_shutdown(participant);
return -1;
}
/* Start changes for Deadline */
/* Create listener */
deadline_contentfilterListener *writer_listener = NULL;
writer_listener = new deadline_contentfilterListener();
if (writer_listener == NULL) {
printf("listener instantiation error\n");
publisher_shutdown(participant);
return -1;
}
writer = publisher->create_datawriter(
topic,
DDS_DATAWRITER_QOS_DEFAULT,
writer_listener,
DDS_OFFERED_DEADLINE_MISSED_STATUS);
if (writer == NULL) {
printf("create_datawriter error\n");
publisher_shutdown(participant);
return -1;
}
/* If you want to change the DataWriter's QoS programmatically rather than
* using the XML file, you will need to add the following lines to your
* code and comment out the create_datawriter call above.
*
* In this case, we set the deadline period to 1.5 seconds to trigger
* a deadline if the DataWriter does not update often enough.
*/
/*
DDS_DataWriterQos datawriter_qos;
retcode = publisher->get_default_datawriter_qos(datawriter_qos);
if (retcode != DDS_RETCODE_OK) {
printf("get_default_datawriter_qos error\n");
return -1;
}
*/ /* Set deadline QoS */
/* DDS_Duration_t deadline_period = {1, 500000000};
datawriter_qos.deadline.period = deadline_period;
writer = publisher->create_datawriter(
topic, datawriter_qos, writer_listener,
DDS_OFFERED_DEADLINE_MISSED_STATUS);
if (writer == NULL) {
printf("create_datawriter error\n");
publisher_shutdown(participant);
return -1;
}
*/
/* End changes for Deadline */
deadline_contentfilter_writer =
deadline_contentfilterDataWriter::narrow(writer);
if (deadline_contentfilter_writer == NULL) {
printf("DataWriter narrow error\n");
publisher_shutdown(participant);
return -1;
}
/* Start changes for Deadline */
/* Create two instances for writing */
deadline_contentfilter *instance0 = NULL;
deadline_contentfilter *instance1 = NULL;
DDS_InstanceHandle_t handle0 = DDS_HANDLE_NIL;
DDS_InstanceHandle_t handle1 = DDS_HANDLE_NIL;
/* Create data samples for writing */
instance0 = deadline_contentfilterTypeSupport::create_data();
instance1 = deadline_contentfilterTypeSupport::create_data();
if (instance0 == NULL || instance1 == NULL) {
printf("deadline_contentfilterTypeSupport::create_data error\n");
publisher_shutdown(participant);
return -1;
}
/* Set keys -- we specify 'code' as the key field in the .idl*/
instance0->code = 0;
instance1->code = 1;
/* For data type that has key, if the same instance is going to be
written multiple times, initialize the key here
and register the keyed instance prior to writing */
handle0 = deadline_contentfilter_writer->register_instance(*instance0);
handle1 = deadline_contentfilter_writer->register_instance(*instance1);
struct DDS_Duration_t send_period = { 1, 0 };
instance0->x = instance0->y = instance1->x = instance1->y = 0;
/* Main loop */
for (count = 0; (sample_count == 0) || (count < sample_count); ++count) {
NDDSUtility::sleep(send_period);
instance0->x++;
instance0->y++;
instance1->x++;
instance1->y++;
printf("Writing instance0, x = %d, y = %d\n",
instance0->x,
instance0->y);
retcode = deadline_contentfilter_writer->write(*instance0, handle0);
if (retcode != DDS_RETCODE_OK) {
printf("write error %d\n", retcode);
publisher_shutdown(participant);
return -1;
}
if (count < 15) {
printf("Writing instance1, x = %d, y = %d\n",
instance1->x,
instance1->y);
retcode = deadline_contentfilter_writer->write(*instance1, handle1);
if (retcode != DDS_RETCODE_OK) {
printf("write error %d\n", retcode);
publisher_shutdown(participant);
return -1;
}
} else if (count == 15) {
printf("Stopping writes to instance1\n");
}
}
retcode = deadline_contentfilter_writer->unregister_instance(
*instance0,
handle0);
if (retcode != DDS_RETCODE_OK) {
printf("unregister instance error %d\n", retcode);
}
retcode = deadline_contentfilter_writer->unregister_instance(
*instance1,
handle1);
if (retcode != DDS_RETCODE_OK) {
printf("unregister instance error %d\n", retcode);
}
/* Delete data sample */
retcode = deadline_contentfilterTypeSupport::delete_data(instance0);
if (retcode != DDS_RETCODE_OK) {
printf("deadline_contentfilterTypeSupport::delete_data error %d\n",
retcode);
}
retcode = deadline_contentfilterTypeSupport::delete_data(instance1);
if (retcode != DDS_RETCODE_OK) {
printf("deadline_contentfilterTypeSupport::delete_data error %d\n",
retcode);
}
/* End changes for Deadline */
/* Delete all entities */
return publisher_shutdown(participant);
}
#if defined(RTI_WINCE)
int wmain(int argc, wchar_t **argv)
{
int domainId = 0;
int sample_count = 0; /* infinite loop */
if (argc >= 2) {
domainId = _wtoi(argv[1]);
}
if (argc >= 3) {
sample_count = _wtoi(argv[2]);
}
/* Uncomment this to turn on additional logging
NDDSConfigLogger::get_instance()->
set_verbosity_by_category(NDDS_CONFIG_LOG_CATEGORY_API,
NDDS_CONFIG_LOG_VERBOSITY_STATUS_ALL);
*/
return publisher_main(domainId, sample_count);
}
#elif !(defined(RTI_VXWORKS) && !defined(__RTP__)) && !defined(RTI_PSOS)
int main(int argc, char *argv[])
{
int domainId = 0;
int sample_count = 0; /* infinite loop */
if (argc >= 2) {
domainId = atoi(argv[1]);
}
if (argc >= 3) {
sample_count = atoi(argv[2]);
}
/* Uncomment this to turn on additional logging
NDDSConfigLogger::get_instance()->
set_verbosity_by_category(NDDS_CONFIG_LOG_CATEGORY_API,
NDDS_CONFIG_LOG_VERBOSITY_STATUS_ALL);
*/
return publisher_main(domainId, sample_count);
}
#endif
| cxx |
rticonnextdds-examples | data/projects/rticonnextdds-examples/connext_dds/deadline_contentfilter/c++98/deadline_contentfilter_subscriber.cxx | /*******************************************************************************
(c) 2005-2014 Copyright, Real-Time Innovations, Inc. All rights reserved.
RTI grants Licensee a license to use, modify, compile, and create derivative
works of the Software. Licensee has the right to distribute object form only
for use with RTI products. The Software is provided "as is", with no warranty
of any type, including any warranty for fitness for any purpose. RTI is under
no obligation to maintain or support the Software. RTI shall not be liable for
any incidental or consequential damages arising out of the use or inability to
use the software.
******************************************************************************/
/* This example sets the deadline period to 2 seconds to trigger a deadline if
the DataWriter does not update often enough, or if the content-filter
filters out data so there is no data available within 2 seconds.
This example starts by filtering out instances >= 2, and changes to later
filter out instances >= 1.
*/
#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include <iomanip>
#include "deadline_contentfilter.h"
#include "deadline_contentfilterSupport.h"
#include "ndds/ndds_cpp.h"
#include "application.h"
using namespace application;
//// Changes for Deadline
// For timekeeping
#include <time.h>
clock_t init;
static int shutdown_participant(
DDSDomainParticipant *participant,
const char *shutdown_message,
int status);
class deadline_contentfilterListener : public DDSDataReaderListener {
public:
virtual void on_requested_deadline_missed(
DDSDataReader * /*reader*/,
const DDS_RequestedDeadlineMissedStatus & /*status*/);
virtual void on_requested_incompatible_qos(
DDSDataReader * /*reader*/,
const DDS_RequestedIncompatibleQosStatus & /*status*/)
{
}
virtual void on_sample_rejected(
DDSDataReader * /*reader*/,
const DDS_SampleRejectedStatus & /*status*/)
{
}
virtual void on_liveliness_changed(
DDSDataReader * /*reader*/,
const DDS_LivelinessChangedStatus & /*status*/)
{
}
virtual void on_sample_lost(
DDSDataReader * /*reader*/,
const DDS_SampleLostStatus & /*status*/)
{
}
virtual void on_subscription_matched(
DDSDataReader * /*reader*/,
const DDS_SubscriptionMatchedStatus & /*status*/)
{
}
virtual void on_data_available(DDSDataReader *reader);
};
/* Start changes for Deadline */
void deadline_contentfilterListener::on_requested_deadline_missed(
DDSDataReader *reader,
const DDS_RequestedDeadlineMissedStatus &status)
{
double elapsed_ticks = clock() - init;
double elapsed_secs = elapsed_ticks / CLOCKS_PER_SEC;
/* Creates a temporary object of our structure "deadline_contentfilter"
* in order to find out which instance missed its deadline period. The
* get_key_value call only fills in the values of the key fields inside
* the dummy object.
*/
deadline_contentfilter dummy;
DDS_ReturnCode_t retcode =
((deadline_contentfilterDataReader *) reader)
->get_key_value(dummy, status.last_instance_handle);
if (retcode != DDS_RETCODE_OK) {
std::cerr << "get_key_value error " << retcode << std::endl;
return;
}
std::cout << std::fixed;
std::cout << std::setprecision(2);
// Print out which instance missed its deadline.
std::cout << "Missed deadline @ t=" << elapsed_secs
<< " on instance code = " << dummy.code << std::endl;
}
/* End changes for Deadline */
void deadline_contentfilterListener::on_data_available(DDSDataReader *reader)
{
deadline_contentfilterDataReader *typed_reader = NULL;
deadline_contentfilterSeq data_seq;
DDS_SampleInfoSeq info_seq;
DDS_ReturnCode_t retcode;
typed_reader = deadline_contentfilterDataReader::narrow(reader);
if (typed_reader == NULL) {
std::cerr << "DataReader narrow error\n";
return;
}
retcode = typed_reader->take(
data_seq,
info_seq,
DDS_LENGTH_UNLIMITED,
DDS_ANY_SAMPLE_STATE,
DDS_ANY_VIEW_STATE,
DDS_ANY_INSTANCE_STATE);
if (retcode == DDS_RETCODE_NO_DATA) {
return;
} else if (retcode != DDS_RETCODE_OK) {
std::cerr << "take error " << retcode << std::endl;
return;
}
std::cout << std::fixed;
std::cout << std::setprecision(2);
for (int i = 0; i < data_seq.length(); ++i) {
if (info_seq[i].valid_data) {
/* Start changes for Deadline */
/* print the time we get each sample. */
double elapsed_ticks = clock() - init;
double elapsed_secs = elapsed_ticks / CLOCKS_PER_SEC;
std::cout << "@ t=" << elapsed_secs << ", Instance"
<< data_seq[i].code << ": <" << data_seq[i].x << ","
<< data_seq[i].y << ">\n";
/* deadlineTypeSupport::print_data(&data_seq[i]); */
/* End changes for Deadline */
}
}
retcode = typed_reader->return_loan(data_seq, info_seq);
if (retcode != DDS_RETCODE_OK) {
std::cerr << "return loan error " << retcode << std::endl;
}
}
int run_subscriber_application(
unsigned int domain_id,
unsigned int sample_count)
{
struct DDS_Duration_t receive_period = { 1, 0 };
/* Changes for Deadline */
/* for timekeeping */
init = clock();
// Start communicating in a domain, usually one participant per application
DDSDomainParticipant *participant =
DDSTheParticipantFactory->create_participant(
domain_id,
DDS_PARTICIPANT_QOS_DEFAULT,
NULL /* listener */,
DDS_STATUS_MASK_NONE);
if (participant == NULL) {
return shutdown_participant(
participant,
"create_participant error",
EXIT_FAILURE);
}
// A Subscriber allows an application to create one or more DataReaders
DDSSubscriber *subscriber = participant->create_subscriber(
DDS_SUBSCRIBER_QOS_DEFAULT,
NULL /* listener */,
DDS_STATUS_MASK_NONE);
if (subscriber == NULL) {
return shutdown_participant(
participant,
"create_subscriber error",
EXIT_FAILURE);
}
// Register the datatype to use when creating the Topic
const char *type_name = deadline_contentfilterTypeSupport::get_type_name();
DDS_ReturnCode_t retcode = deadline_contentfilterTypeSupport::register_type(
participant,
type_name);
if (retcode != DDS_RETCODE_OK) {
return shutdown_participant(
participant,
"register_type error",
EXIT_FAILURE);
}
// Create a Topic with a name and a datatype
DDSTopic *topic = participant->create_topic(
"Example deadline_contentfilter",
type_name,
DDS_TOPIC_QOS_DEFAULT,
NULL /* listener */,
DDS_STATUS_MASK_NONE);
if (topic == NULL) {
return shutdown_participant(
participant,
"create_topic error",
EXIT_FAILURE);
}
/* Start changes for Deadline */
/* Set up content filtered topic to show interaction with deadline */
DDS_StringSeq parameters(1);
const char *param_list[] = { "2" };
parameters.from_array(param_list, 1);
DDSContentFilteredTopic *cft = NULL;
cft = participant->create_contentfilteredtopic(
"ContentFilteredTopic",
topic,
"code < %0",
parameters);
/* Get default datareader QoS to customize */
DDS_DataReaderQos datareader_qos;
retcode = subscriber->get_default_datareader_qos(datareader_qos);
if (retcode != DDS_RETCODE_OK) {
return shutdown_participant(
participant,
"get_default_datareader_qos error",
EXIT_FAILURE);
}
/* Create data reader listener */
deadline_contentfilterListener *reader_listener =
new deadline_contentfilterListener();
if (reader_listener == NULL) {
return shutdown_participant(
participant,
"listener instantiation error",
EXIT_FAILURE);
}
// This DataReader reads data on "Example deadline_contentfilter" Topic
DDSDataReader *untyped_reader = subscriber->create_datareader(
cft,
DDS_DATAREADER_QOS_DEFAULT,
reader_listener,
DDS_STATUS_MASK_ALL);
if (untyped_reader == NULL) {
return shutdown_participant(
participant,
"create_datareader error",
EXIT_FAILURE);
}
/* If you want to change the DataReader's QoS programmatically rather than
* using the XML file, you will need to add the following lines to your
* code and comment out the create_datareader call above.
*
* In this case, we set the deadline period to 2 seconds to trigger
* a deadline if the DataWriter does not update often enough, or if
* the content-filter filters out data so there is no data available
* with 2 seconds.
*/
/* Set deadline QoS */
/* DDS_Duration_t deadline_period = {2, 0};
datareader_qos.deadline.period = deadline_period;
DDSDataReader *untyped_reader = subscriber->create_datareader(
cft, datareader_qos, reader_listener,
DDS_STATUS_MASK_ALL);
if (untyped_reader == NULL) {
return shutdown_participant(
participant,
"create_datareader error",
EXIT_FAILURE);
}
*/
/* Main loop */
for (int count = 0; count < sample_count && !shutdown_requested; ++count) {
/* After 10 seconds, change content filter to accept only instance 0 */
if (count == 10) {
std::cout << "Starting to filter out instance1\n";
parameters[0] = DDS_String_dup("1");
cft->set_expression_parameters(parameters);
}
NDDSUtility::sleep(receive_period);
}
/* End changes for Deadline */
// Cleanup
return shutdown_participant(participant, "Shutting down", 0);
}
// Delete all entities
static int shutdown_participant(
DDSDomainParticipant *participant,
const char *shutdown_message,
int status)
{
DDS_ReturnCode_t retcode;
std::cout << shutdown_message << std::endl;
if (participant != NULL) {
// Cleanup everything created by this Participant
retcode = participant->delete_contained_entities();
if (retcode != DDS_RETCODE_OK) {
std::cerr << "delete_contained_entities error" << retcode
<< std::endl;
status = EXIT_FAILURE;
}
retcode = DDSTheParticipantFactory->delete_participant(participant);
if (retcode != DDS_RETCODE_OK) {
std::cerr << "delete_participant error" << retcode << std::endl;
status = EXIT_FAILURE;
}
}
return status;
}
int main(int argc, char *argv[])
{
// Parse arguments and handle control-C
ApplicationArguments arguments;
parse_arguments(arguments, argc, argv);
if (arguments.parse_result == PARSE_RETURN_EXIT) {
return EXIT_SUCCESS;
} else if (arguments.parse_result == PARSE_RETURN_FAILURE) {
return EXIT_FAILURE;
}
setup_signal_handlers();
// Sets Connext verbosity to help debugging
NDDSConfigLogger::get_instance()->set_verbosity(arguments.verbosity);
int status = run_subscriber_application(
arguments.domain_id,
arguments.sample_count);
// Releases the memory used by the participant factory. Optional at
// application exit
DDS_ReturnCode_t retcode = DDSDomainParticipantFactory::finalize_instance();
if (retcode != DDS_RETCODE_OK) {
std::cerr << "finalize_instance error" << retcode << std::endl;
status = EXIT_FAILURE;
}
return status;
}
| cxx |
rticonnextdds-examples | data/projects/rticonnextdds-examples/connext_dds/deadline_contentfilter/c++98/deadline_contentfilter_publisher.cxx | /*******************************************************************************
(c) 2005-2014 Copyright, Real-Time Innovations, Inc. All rights reserved.
RTI grants Licensee a license to use, modify, compile, and create derivative
works of the Software. Licensee has the right to distribute object form only
for use with RTI products. The Software is provided "as is", with no warranty
of any type, including any warranty for fitness for any purpose. RTI is under
no obligation to maintain or support the Software. RTI shall not be liable for
any incidental or consequential damages arising out of the use or inability to
use the software.
******************************************************************************/
/* This example sets the deadline period to 1.5 seconds to trigger a deadline
if the DataWriter does not update often enough. The writer's updates are
dependent on the application code, so the middleware can notify the
application that it has failed to update often enough.
*/
#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include "deadline_contentfilter.h"
#include "deadline_contentfilterSupport.h"
#include "ndds/ndds_cpp.h"
#include "application.h"
using namespace application;
static int shutdown_participant(
DDSDomainParticipant *participant,
const char *shutdown_message,
int status);
/* Start changes for Deadline */
class deadline_contentfilterListener : public DDSDataWriterListener {
public:
virtual void on_offered_deadline_missed(
DDSDataWriter *writer,
const DDS_OfferedDeadlineMissedStatus &status)
{
deadline_contentfilter dummy;
DDS_ReturnCode_t retcode =
((deadline_contentfilterDataWriter *) writer)
->get_key_value(dummy, status.last_instance_handle);
if (retcode != DDS_RETCODE_OK) {
std::cerr << "get_key_value error " << retcode << std::endl;
return;
}
std::cout << "Offered deadline missed on instance code = " << dummy.code
<< std::endl;
}
};
/* End changes for Deadline */
int run_publisher_application(unsigned int domain_id, unsigned int sample_count)
{
// Start communicating in a domain, usually one participant per application
DDSDomainParticipant *participant =
DDSTheParticipantFactory->create_participant(
domain_id,
DDS_PARTICIPANT_QOS_DEFAULT,
NULL /* listener */,
DDS_STATUS_MASK_NONE);
if (participant == NULL) {
return shutdown_participant(
participant,
"create_participant error",
EXIT_FAILURE);
}
// A Publisher allows an application to create one or more DataWriters
DDSPublisher *publisher = participant->create_publisher(
DDS_PUBLISHER_QOS_DEFAULT,
NULL /* listener */,
DDS_STATUS_MASK_NONE);
if (publisher == NULL) {
return shutdown_participant(
participant,
"create_publisher error",
EXIT_FAILURE);
}
// Register the datatype to use when creating the Topic
const char *type_name = deadline_contentfilterTypeSupport::get_type_name();
DDS_ReturnCode_t retcode = deadline_contentfilterTypeSupport::register_type(
participant,
type_name);
if (retcode != DDS_RETCODE_OK) {
return shutdown_participant(
participant,
"register_type error",
EXIT_FAILURE);
}
// Create a Topic with a name and a datatype
DDSTopic *topic = participant->create_topic(
"Example deadline_contentfilter",
type_name,
DDS_TOPIC_QOS_DEFAULT,
NULL /* listener */,
DDS_STATUS_MASK_NONE);
if (topic == NULL) {
return shutdown_participant(
participant,
"create_topic error",
EXIT_FAILURE);
}
/* Start changes for Deadline */
// Create listener
deadline_contentfilterListener *writer_listener = NULL;
writer_listener = new deadline_contentfilterListener();
if (writer_listener == NULL) {
return shutdown_participant(
participant,
"listener instantiation error",
EXIT_FAILURE);
}
// This DataWriter writes data on "Example deadline_contentfilter" Topic
DDSDataWriter *untyped_writer = publisher->create_datawriter(
topic,
DDS_DATAWRITER_QOS_DEFAULT,
writer_listener,
DDS_OFFERED_DEADLINE_MISSED_STATUS);
if (untyped_writer == NULL) {
return shutdown_participant(
participant,
"create_datawriter error",
EXIT_FAILURE);
}
/* If you want to change the DataWriter's QoS programmatically rather than
* using the XML file, you will need to add the following lines to your
* code and comment out the create_datawriter call above.
*
* In this case, we set the deadline period to 1.5 seconds to trigger
* a deadline if the DataWriter does not update often enough.
*/
/*
DDS_DataWriterQos datawriter_qos;
retcode = publisher->get_default_datawriter_qos(datawriter_qos);
if (retcode != DDS_RETCODE_OK) {
std::cerr << "get_default_datawriter_qos error\n";
return EXIT_FAILURE;
}
*/ /* Set deadline QoS */
/* DDS_Duration_t deadline_period = {1, 500000000};
datawriter_qos.deadline.period = deadline_period;
DDSDataWriter *untyped_writer = publisher->create_datawriter(
topic, datawriter_qos, writer_listener,
DDS_OFFERED_DEADLINE_MISSED_STATUS);
if (untyped_writer == NULL) {
return shutdown_participant(
participant,
"create_datawriter error",
EXIT_FAILURE);
}
*/
/* End changes for Deadline */
deadline_contentfilterDataWriter *typed_writer =
deadline_contentfilterDataWriter::narrow(untyped_writer);
if (typed_writer == NULL) {
return shutdown_participant(
participant,
"DataWriter narrow error",
EXIT_FAILURE);
}
/* Start changes for Deadline */
/* Create two instances for writing */
deadline_contentfilter *instance0 = NULL;
deadline_contentfilter *instance1 = NULL;
DDS_InstanceHandle_t handle0 = DDS_HANDLE_NIL;
DDS_InstanceHandle_t handle1 = DDS_HANDLE_NIL;
/* Create data samples for writing */
instance0 = deadline_contentfilterTypeSupport::create_data();
instance1 = deadline_contentfilterTypeSupport::create_data();
if (instance0 == NULL || instance1 == NULL) {
return shutdown_participant(
participant,
"deadline_contentfilterTypeSupport::create_data error",
EXIT_FAILURE);
}
/* Set keys -- we specify 'code' as the key field in the .idl*/
instance0->code = 0;
instance1->code = 1;
/* For data type that has key, if the same instance is going to be
written multiple times, initialize the key here
and register the keyed instance prior to writing */
handle0 = typed_writer->register_instance(*instance0);
handle1 = typed_writer->register_instance(*instance1);
struct DDS_Duration_t send_period = { 1, 0 };
instance0->x = instance0->y = instance1->x = instance1->y = 0;
// Main loop, write data
for (unsigned int samples_written = 0;
!shutdown_requested && samples_written < sample_count;
++samples_written) {
NDDSUtility::sleep(send_period);
instance0->x++;
instance0->y++;
instance1->x++;
instance1->y++;
std::cout << "Writing instance0, x = " << instance0->x
<< ", y = " << instance0->y << std::endl;
retcode = typed_writer->write(*instance0, handle0);
if (retcode != DDS_RETCODE_OK) {
return shutdown_participant(
participant,
"write error",
EXIT_FAILURE);
}
if (samples_written < 15) {
std::cout << "Writing instance1, x = " << instance1->x
<< ", y = " << instance1->y << std::endl;
retcode = typed_writer->write(*instance1, handle1);
if (retcode != DDS_RETCODE_OK) {
return shutdown_participant(
participant,
"write error",
EXIT_FAILURE);
}
} else if (samples_written == 15) {
std::cout << "Stopping writes to instance1\n";
}
}
retcode = typed_writer->unregister_instance(*instance0, handle0);
if (retcode != DDS_RETCODE_OK) {
std::cerr << "unregister instance error " << retcode << std::endl;
}
retcode = typed_writer->unregister_instance(*instance1, handle1);
if (retcode != DDS_RETCODE_OK) {
std::cerr << "unregister instance error " << retcode << std::endl;
}
// deadline_contentfilterTypeSupport
// Delete previously allocated data, including all contained elements
retcode = deadline_contentfilterTypeSupport::delete_data(instance0);
if (retcode != DDS_RETCODE_OK) {
std::cerr << "deadline_contentfilterTypeSupport::delete_data error "
<< retcode << std::endl;
}
retcode = deadline_contentfilterTypeSupport::delete_data(instance1);
if (retcode != DDS_RETCODE_OK) {
std::cerr << "deadline_contentfilterTypeSupport::delete_data error "
<< retcode << std::endl;
}
/* End changes for Deadline */
// Delete all entities (DataWriter, Topic, Publisher, DomainParticipant)
return shutdown_participant(participant, "Shutting down", EXIT_SUCCESS);
}
// Delete all entities
static int shutdown_participant(
DDSDomainParticipant *participant,
const char *shutdown_message,
int status)
{
DDS_ReturnCode_t retcode;
std::cout << shutdown_message << std::endl;
if (participant != NULL) {
// Cleanup everything created by this Participant
retcode = participant->delete_contained_entities();
if (retcode != DDS_RETCODE_OK) {
std::cerr << "delete_contained_entities error " << retcode
<< std::endl;
status = EXIT_FAILURE;
}
retcode = DDSTheParticipantFactory->delete_participant(participant);
if (retcode != DDS_RETCODE_OK) {
std::cerr << "delete_participant error " << retcode << std::endl;
status = EXIT_FAILURE;
}
}
return status;
}
int main(int argc, char *argv[])
{
// Parse arguments and handle control-C
ApplicationArguments arguments;
parse_arguments(arguments, argc, argv);
if (arguments.parse_result == PARSE_RETURN_EXIT) {
return EXIT_SUCCESS;
} else if (arguments.parse_result == PARSE_RETURN_FAILURE) {
return EXIT_FAILURE;
}
setup_signal_handlers();
// Sets Connext verbosity to help debugging
NDDSConfigLogger::get_instance()->set_verbosity(arguments.verbosity);
int status = run_publisher_application(
arguments.domain_id,
arguments.sample_count);
// Releases the memory used by the participant factory. Optional at
// application exit
DDS_ReturnCode_t retcode = DDSDomainParticipantFactory::finalize_instance();
if (retcode != DDS_RETCODE_OK) {
std::cerr << "finalize_instance error " << retcode << std::endl;
status = EXIT_FAILURE;
}
return status;
}
| cxx |
rticonnextdds-examples | data/projects/rticonnextdds-examples/connext_dds/deadline_contentfilter/c++98/application.h | /*
* (c) Copyright, Real-Time Innovations, 2020. All rights reserved.
* RTI grants Licensee a license to use, modify, compile, and create derivative
* works of the software solely for use with RTI Connext DDS. Licensee may
* redistribute copies of the software provided that all such copies are subject
* to this license. The software is provided "as is", with no warranty of any
* type, including any warranty for fitness for any purpose. RTI is under no
* obligation to maintain or support the software. RTI shall not be liable for
* any incidental or consequential damages arising out of the use or inability
* to use the software.
*/
#ifndef APPLICATION_H
#define APPLICATION_H
#include <iostream>
#include <csignal>
#include <climits>
namespace application {
// Catch control-C and tell application to shut down
bool shutdown_requested = false;
inline void stop_handler(int)
{
shutdown_requested = true;
std::cout << "preparing to shut down..." << std::endl;
}
inline void setup_signal_handlers()
{
signal(SIGINT, stop_handler);
signal(SIGTERM, stop_handler);
}
enum ParseReturn { PARSE_RETURN_OK, PARSE_RETURN_FAILURE, PARSE_RETURN_EXIT };
struct ApplicationArguments {
ParseReturn parse_result;
unsigned int domain_id;
unsigned int sample_count;
NDDS_Config_LogVerbosity verbosity;
};
inline void set_verbosity(ApplicationArguments &arguments, int verbosity)
{
switch (verbosity) {
case 0:
arguments.verbosity = NDDS_CONFIG_LOG_VERBOSITY_SILENT;
break;
case 1:
arguments.verbosity = NDDS_CONFIG_LOG_VERBOSITY_ERROR;
break;
case 2:
arguments.verbosity = NDDS_CONFIG_LOG_VERBOSITY_WARNING;
break;
case 3:
arguments.verbosity = NDDS_CONFIG_LOG_VERBOSITY_STATUS_ALL;
break;
default:
arguments.verbosity = NDDS_CONFIG_LOG_VERBOSITY_ERROR;
break;
}
}
// Parses application arguments for example. Returns whether to exit.
inline void parse_arguments(
ApplicationArguments &arguments,
int argc,
char *argv[])
{
int arg_processing = 1;
bool show_usage = false;
arguments.domain_id = 0;
arguments.sample_count = INT_MAX;
arguments.verbosity = NDDS_CONFIG_LOG_VERBOSITY_ERROR;
arguments.parse_result = PARSE_RETURN_OK;
while (arg_processing < argc) {
if ((argc > arg_processing + 1)
&& (strcmp(argv[arg_processing], "-d") == 0
|| strcmp(argv[arg_processing], "--domain") == 0)) {
arguments.domain_id = atoi(argv[arg_processing + 1]);
arg_processing += 2;
} else if (
(argc > arg_processing + 1)
&& (strcmp(argv[arg_processing], "-s") == 0
|| strcmp(argv[arg_processing], "--sample-count") == 0)) {
arguments.sample_count = atoi(argv[arg_processing + 1]);
arg_processing += 2;
} else if (
(argc > arg_processing + 1)
&& (strcmp(argv[arg_processing], "-v") == 0
|| strcmp(argv[arg_processing], "--verbosity") == 0)) {
set_verbosity(arguments, atoi(argv[arg_processing + 1]));
arg_processing += 2;
} else if (
strcmp(argv[arg_processing], "-h") == 0
|| strcmp(argv[arg_processing], "--help") == 0) {
std::cout << "Example application." << std::endl;
show_usage = true;
arguments.parse_result = PARSE_RETURN_EXIT;
break;
} else {
std::cout << "Bad parameter." << std::endl;
show_usage = true;
arguments.parse_result = PARSE_RETURN_FAILURE;
break;
}
}
if (show_usage) {
std::cout << "Usage:\n"
" -d, --domain <int> Domain ID this "
"application will\n"
" subscribe in. \n"
" Default: 0\n"
" -s, --sample_count <int> Number of samples to "
"receive before\n"
" cleanly shutting down. \n"
" Default: infinite\n"
" -v, --verbosity <int> How much debugging output "
"to show.\n"
" Range: 0-3 \n"
" Default: 1"
<< std::endl;
}
}
} // namespace application
#endif // APPLICATION_H
| h |
rticonnextdds-examples | data/projects/rticonnextdds-examples/connext_dds/deadline_contentfilter/c/deadline_contentfilter_publisher.c | /*******************************************************************************
(c) 2005-2014 Copyright, Real-Time Innovations, Inc. All rights reserved.
RTI grants Licensee a license to use, modify, compile, and create derivative
works of the Software. Licensee has the right to distribute object form only
for use with RTI products. The Software is provided "as is", with no warranty
of any type, including any warranty for fitness for any purpose. RTI is under
no obligation to maintain or support the Software. RTI shall not be liable for
any incidental or consequential damages arising out of the use or inability to
use the software.
******************************************************************************/
/* deadline_contentfilter_publisher.c
A publication of data of type deadline_contentfilter
This file is derived from code automatically generated by the rtiddsgen
command:
rtiddsgen -language C -example <arch> deadline_contentfilter.idl
Example publication of type deadline_contentfilter automatically generated by
'rtiddsgen'. To test them follow these steps:
(1) Compile this file and the example subscription.
(2) Start the subscription with the command
objs/<arch>/deadline_contentfilter_subscriber <domain_id> <sample_count>
(3) Start the publication with the command
objs/<arch>/deadline_contentfilter_publisher <domain_id> <sample_count>
(4) [Optional] Specify the list of discovery initial peers and
multicast receive addresses via an environment variable or a file
(in the current working directory) called NDDS_DISCOVERY_PEERS.
You can run any number of publishers and subscribers programs, and can
add and remove them dynamically from the domain.
Example:
To run the example application on domain <domain_id>:
On Unix:
objs/<arch>/deadline_contentfilter_publisher <domain_id>
objs/<arch>/deadline_contentfilter_subscriber <domain_id>
On Windows:
objs\<arch>\deadline_contentfilter_publisher <domain_id>
objs\<arch>\deadline_contentfilter_subscriber <domain_id>
modification history
------------ -------
* Create and install listener for offered deadline missed status
* Set deadline QoS
*/
#include "deadline_contentfilter.h"
#include "deadline_contentfilterSupport.h"
#include "ndds/ndds_c.h"
#include <stdio.h>
#include <stdlib.h>
/* Start changes for Deadline */
void deadlineListener_on_offered_deadline_missed(
void *listener_data,
DDS_DataWriter *writer,
const struct DDS_OfferedDeadlineMissedStatus *status)
{
deadline_contentfilter dummy;
DDS_ReturnCode_t retcode = deadline_contentfilterDataWriter_get_key_value(
deadline_contentfilterDataWriter_narrow(writer),
&dummy,
&status->last_instance_handle);
if (retcode != DDS_RETCODE_OK) {
printf("get_key_value error %d\n", retcode);
return;
}
printf("Offered deadline missed on instance code = %d\n", dummy.code);
}
/* End changes for Deadline */
/* Delete all entities */
static int publisher_shutdown(DDS_DomainParticipant *participant)
{
DDS_ReturnCode_t retcode;
int status = 0;
if (participant != NULL) {
retcode = DDS_DomainParticipant_delete_contained_entities(participant);
if (retcode != DDS_RETCODE_OK) {
printf("delete_contained_entities error %d\n", retcode);
status = -1;
}
retcode = DDS_DomainParticipantFactory_delete_participant(
DDS_TheParticipantFactory,
participant);
if (retcode != DDS_RETCODE_OK) {
printf("delete_participant error %d\n", retcode);
status = -1;
}
}
/* RTI Connext provides finalize_instance() method on
domain participant factory for people who want to release memory used
by the participant factory. Uncomment the following block of code for
clean destruction of the singleton. */
/*
retcode = DDS_DomainParticipantFactory_finalize_instance();
if (retcode != DDS_RETCODE_OK) {
printf("finalize_instance error %d\n", retcode);
status = -1;
}
*/
return status;
}
static int publisher_main(int domainId, int sample_count)
{
DDS_DomainParticipant *participant = NULL;
DDS_Publisher *publisher = NULL;
DDS_Topic *topic = NULL;
DDS_DataWriter *writer = NULL;
deadline_contentfilterDataWriter *deadline_contentfilter_writer = NULL;
DDS_ReturnCode_t retcode;
const char *type_name = NULL;
int count = 0;
/* struct DDS_Duration_t deadline_period = {1, 500000000}; */ /* 1.5sec */
struct DDS_Duration_t send_period = { 1, 0 };
deadline_contentfilter *instance0 = NULL;
deadline_contentfilter *instance1 = NULL;
DDS_InstanceHandle_t handle0 = DDS_HANDLE_NIL;
DDS_InstanceHandle_t handle1 = DDS_HANDLE_NIL;
/*struct DDS_DataWriterQos datawriter_qos = DDS_DataWriterQos_INITIALIZER;*/
/* To customize participant QoS, use
the configuration file USER_QOS_PROFILES.xml */
participant = DDS_DomainParticipantFactory_create_participant(
DDS_TheParticipantFactory,
domainId,
&DDS_PARTICIPANT_QOS_DEFAULT,
NULL /* listener */,
DDS_STATUS_MASK_NONE);
if (participant == NULL) {
printf("create_participant error\n");
publisher_shutdown(participant);
return -1;
}
/* To customize publisher QoS, use
the configuration file USER_QOS_PROFILES.xml */
publisher = DDS_DomainParticipant_create_publisher(
participant,
&DDS_PUBLISHER_QOS_DEFAULT,
NULL /* listener */,
DDS_STATUS_MASK_NONE);
if (publisher == NULL) {
printf("create_publisher error\n");
publisher_shutdown(participant);
return -1;
}
/* Register type before creating topic */
type_name = deadline_contentfilterTypeSupport_get_type_name();
retcode = deadline_contentfilterTypeSupport_register_type(
participant,
type_name);
if (retcode != DDS_RETCODE_OK) {
printf("register_type error %d\n", retcode);
publisher_shutdown(participant);
return -1;
}
/* To customize topic QoS, use
the configuration file USER_QOS_PROFILES.xml */
topic = DDS_DomainParticipant_create_topic(
participant,
"Example deadline_contentfilter",
type_name,
&DDS_TOPIC_QOS_DEFAULT,
NULL /* listener */,
DDS_STATUS_MASK_NONE);
if (topic == NULL) {
printf("create_topic error\n");
publisher_shutdown(participant);
return -1;
}
/* To customize data writer QoS, use
the configuration file USER_QOS_PROFILES.xml */
writer = DDS_Publisher_create_datawriter(
publisher,
topic,
&DDS_DATAWRITER_QOS_DEFAULT,
NULL /* listener */,
DDS_STATUS_MASK_NONE);
if (writer == NULL) {
printf("create_datawriter error\n");
publisher_shutdown(participant);
return -1;
}
/* If you want to change the DataWriter's QoS programmatically rather than
* using the XML file, you will need to add the following lines to your
* code and comment out the create_datawriter call above.
*
* In this case, we set the deadline period to 1.5 seconds to trigger
* a deadline if the DataWriter does not update often enough.
*/
/* Start changes for Deadline */
/* writer_listener.on_offered_deadline_missed =
deadlineListener_on_offered_deadline_missed;
retcode = DDS_Publisher_get_default_datawriter_qos(publisher,
&datawriter_qos);
if (retcode != DDS_RETCODE_OK) {
printf("get_default_datawriter_qos error\n");
return -1;
}
*/ /* Set deadline QoS */
/* datawriter_qos.deadline.period = deadline_period;
writer = DDS_Publisher_create_datawriter(
publisher, topic,
&datawriter_qos, &writer_listener,
DDS_OFFERED_DEADLINE_MISSED_STATUS); if (writer == NULL) {
printf("create_datawriter error\n");
publisher_shutdown(participant);
return -1;
}
*/
/* End changes for Deadline */
deadline_contentfilter_writer =
deadline_contentfilterDataWriter_narrow(writer);
if (deadline_contentfilter_writer == NULL) {
printf("DataWriter narrow error\n");
publisher_shutdown(participant);
return -1;
}
/* Start changes for Deadline */
/* Create data sample for writing */
instance0 =
deadline_contentfilterTypeSupport_create_data_ex(DDS_BOOLEAN_TRUE);
instance1 =
deadline_contentfilterTypeSupport_create_data_ex(DDS_BOOLEAN_TRUE);
if (instance0 == NULL || instance1 == NULL) {
printf("deadlineTypeSupport_create_data error\n");
publisher_shutdown(participant);
return -1;
}
/* Set keys -- we specify 'code' as the key field in the .idl */
instance0->code = 0;
instance1->code = 1;
/* For data type that has key, if the same instance is going to be
written multiple times, initialize the key here
and register the keyed instance prior to writing */
handle0 = deadline_contentfilterDataWriter_register_instance(
deadline_contentfilter_writer,
instance0);
handle1 = deadline_contentfilterDataWriter_register_instance(
deadline_contentfilter_writer,
instance1);
instance0->x = instance0->y = instance1->x = instance1->y = 0;
/* Main loop */
for (count = 0; (sample_count == 0) || (count < sample_count); ++count) {
NDDS_Utility_sleep(&send_period);
instance0->x++;
instance0->y++;
instance1->x++;
instance1->y++;
printf("Writing instance0, x = %d, y = %d\n",
instance0->x,
instance0->y);
retcode = deadline_contentfilterDataWriter_write(
deadline_contentfilter_writer,
instance0,
&handle0);
if (retcode != DDS_RETCODE_OK) {
printf("write error %d\n", retcode);
}
if (count < 15) {
printf("Writing instance1, x = %d, y = %d\n",
instance1->x,
instance1->y);
retcode = deadline_contentfilterDataWriter_write(
deadline_contentfilter_writer,
instance1,
&handle1);
if (retcode != DDS_RETCODE_OK) {
printf("write error %d\n", retcode);
}
} else if (count == 15) {
printf("Stopping writes to instance1\n");
}
}
retcode = deadline_contentfilterDataWriter_unregister_instance(
deadline_contentfilter_writer,
instance0,
&handle0);
if (retcode != DDS_RETCODE_OK) {
printf("unregister instance error %d\n", retcode);
}
retcode = deadline_contentfilterDataWriter_unregister_instance(
deadline_contentfilter_writer,
instance1,
&handle1);
if (retcode != DDS_RETCODE_OK) {
printf("unregister instance error %d\n", retcode);
}
/* Delete data sample */
retcode = deadline_contentfilterTypeSupport_delete_data_ex(
instance0,
DDS_BOOLEAN_TRUE);
if (retcode != DDS_RETCODE_OK) {
printf("deadline_contentfilterTypeSupport_delete_data_ex error %d\n",
retcode);
}
retcode = deadline_contentfilterTypeSupport_delete_data_ex(
instance1,
DDS_BOOLEAN_TRUE);
if (retcode != DDS_RETCODE_OK) {
printf("deadline_contentfilterTypeSupport_delete_data_ex error %d\n",
retcode);
}
/* End changes for Deadline */
/* Cleanup and delete delete all entities */
return publisher_shutdown(participant);
}
#if defined(RTI_WINCE)
int wmain(int argc, wchar_t **argv)
{
int domainId = 0;
int sample_count = 0; /* infinite loop */
if (argc >= 2) {
domainId = _wtoi(argv[1]);
}
if (argc >= 3) {
sample_count = _wtoi(argv[2]);
}
/* Uncomment this to turn on additional logging
NDDS_Config_Logger_set_verbosity_by_category(
NDDS_Config_Logger_get_instance(),
NDDS_CONFIG_LOG_CATEGORY_API,
NDDS_CONFIG_LOG_VERBOSITY_STATUS_ALL);
*/
return publisher_main(domainId, sample_count);
}
#elif !(defined(RTI_VXWORKS) && !defined(__RTP__)) && !defined(RTI_PSOS)
int main(int argc, char *argv[])
{
int domainId = 0;
int sample_count = 0; /* infinite loop */
if (argc >= 2) {
domainId = atoi(argv[1]);
}
if (argc >= 3) {
sample_count = atoi(argv[2]);
}
/* Uncomment this to turn on additional logging
NDDS_Config_Logger_set_verbosity_by_category(
NDDS_Config_Logger_get_instance(),
NDDS_CONFIG_LOG_CATEGORY_API,
NDDS_CONFIG_LOG_VERBOSITY_STATUS_ALL);
*/
return publisher_main(domainId, sample_count);
}
#endif
#ifdef RTI_VX653
const unsigned char *__ctype = NULL;
void usrAppInit()
{
#ifdef USER_APPL_INIT
USER_APPL_INIT; /* for backwards compatibility */
#endif
/* add application specific code here */
taskSpawn(
"pub",
RTI_OSAPI_THREAD_PRIORITY_NORMAL,
0x8,
0x150000,
(FUNCPTR) publisher_main,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0);
}
#endif
| c |
rticonnextdds-examples | data/projects/rticonnextdds-examples/connext_dds/deadline_contentfilter/c/deadline_contentfilter_subscriber.c | /*******************************************************************************
(c) 2005-2014 Copyright, Real-Time Innovations, Inc. All rights reserved.
RTI grants Licensee a license to use, modify, compile, and create derivative
works of the Software. Licensee has the right to distribute object form only
for use with RTI products. The Software is provided "as is", with no warranty
of any type, including any warranty for fitness for any purpose. RTI is under
no obligation to maintain or support the Software. RTI shall not be liable for
any incidental or consequential damages arising out of the use or inability to
use the software.
******************************************************************************/
/* deadline_contentfilter_subscriber.c
A subscription example
This file is derived from code automatically generated by the rtiddsgen
command:
rtiddsgen -language C -example <arch> deadline_contentfilter.idl
Example subscription of type deadline_contentfilter automatically generated
by 'rtiddsgen'. To test them, follow these steps:
(1) Compile this file and the example publication.
(2) Start the subscription with the command
objs/<arch>/deadline_contentfilter_subscriber <domain_id> <sample_count>
(3) Start the publication with the command
objs/<arch>/deadline_contentfilter_publisher <domain_id> <sample_count>
(4) [Optional] Specify the list of discovery initial peers and
multicast receive addresses via an environment variable or a file
(in the current working directory) called NDDS_DISCOVERY_PEERS.
You can run any number of publishers and subscribers programs, and can
add and remove them dynamically from the domain.
Example:
To run the example application on domain <domain_id>:
On UNIX systems:
objs/<arch>/deadline_contentfilter_publisher <domain_id>
objs/<arch>/deadline_contentfilter_subscriber <domain_id>
On Windows systems:
objs\<arch>\deadline_contentfilter_publisher <domain_id>
objs\<arch>\deadline_contentfilter_subscriber <domain_id>
modification history
------------ -------
* Create clock to show relative timing of events
* Define listener for requested deadline missed status
* Set deadline QoS
* Create content filter that ignores second instance
after 10 seconds
*/
#include "deadline_contentfilter.h"
#include "deadline_contentfilterSupport.h"
#include "ndds/ndds_c.h"
#include <stdio.h>
#include <stdlib.h>
/* Start changes for Deadline */
/* For timekeeping */
#include <time.h>
clock_t init;
void deadline_contentfilterListener_on_requested_deadline_missed(
void *listener_data,
DDS_DataReader *reader,
const struct DDS_RequestedDeadlineMissedStatus *status)
{
double elapsed_ticks;
double elapsed_secs;
deadline_contentfilter dummy;
DDS_ReturnCode_t retcode = deadline_contentfilterDataReader_get_key_value(
deadline_contentfilterDataReader_narrow(reader),
&dummy,
&status->last_instance_handle);
if (retcode != DDS_RETCODE_OK) {
printf("get_key_value error %d\n", retcode);
return;
}
elapsed_ticks = clock() - init;
elapsed_secs = elapsed_ticks / CLOCKS_PER_SEC;
printf("Missed deadline @ t=%.2fs on instance code = %d\n",
elapsed_secs,
dummy.code);
}
/* End changes for Deadline */
void deadline_contentfilterListener_on_requested_incompatible_qos(
void *listener_data,
DDS_DataReader *reader,
const struct DDS_RequestedIncompatibleQosStatus *status)
{
}
void deadline_contentfilterListener_on_sample_rejected(
void *listener_data,
DDS_DataReader *reader,
const struct DDS_SampleRejectedStatus *status)
{
}
void deadline_contentfilterListener_on_liveliness_changed(
void *listener_data,
DDS_DataReader *reader,
const struct DDS_LivelinessChangedStatus *status)
{
}
void deadline_contentfilterListener_on_sample_lost(
void *listener_data,
DDS_DataReader *reader,
const struct DDS_SampleLostStatus *status)
{
}
void deadline_contentfilterListener_on_subscription_matched(
void *listener_data,
DDS_DataReader *reader,
const struct DDS_SubscriptionMatchedStatus *status)
{
}
void deadline_contentfilterListener_on_data_available(
void *listener_data,
DDS_DataReader *reader)
{
deadline_contentfilterDataReader *deadline_contentfilter_reader = NULL;
struct deadline_contentfilterSeq data_seq = DDS_SEQUENCE_INITIALIZER;
struct DDS_SampleInfoSeq info_seq = DDS_SEQUENCE_INITIALIZER;
DDS_ReturnCode_t retcode;
int i;
double elapsed_ticks;
double elapsed_secs;
deadline_contentfilter_reader =
deadline_contentfilterDataReader_narrow(reader);
if (deadline_contentfilter_reader == NULL) {
printf("DataReader narrow error\n");
return;
}
retcode = deadline_contentfilterDataReader_take(
deadline_contentfilter_reader,
&data_seq,
&info_seq,
DDS_LENGTH_UNLIMITED,
DDS_ANY_SAMPLE_STATE,
DDS_ANY_VIEW_STATE,
DDS_ANY_INSTANCE_STATE);
if (retcode == DDS_RETCODE_NO_DATA) {
return;
} else if (retcode != DDS_RETCODE_OK) {
printf("take error %d\n", retcode);
return;
}
for (i = 0; i < deadline_contentfilterSeq_get_length(&data_seq); ++i) {
if (DDS_SampleInfoSeq_get_reference(&info_seq, i)->valid_data) {
deadline_contentfilter *data =
deadline_contentfilterSeq_get_reference(&data_seq, i);
/* Start changes for Deadline */
/* print the time we get each sample. */
elapsed_ticks = clock() - init;
elapsed_secs = elapsed_ticks / CLOCKS_PER_SEC;
printf("@ t=%.2fs, Instance%d: <%d,%d>\n",
elapsed_secs,
data->code,
data->x,
data->y);
/* End changes for Deadline */
}
}
retcode = deadline_contentfilterDataReader_return_loan(
deadline_contentfilter_reader,
&data_seq,
&info_seq);
if (retcode != DDS_RETCODE_OK) {
printf("return loan error %d\n", retcode);
}
}
/* Delete all entities */
static int subscriber_shutdown(DDS_DomainParticipant *participant)
{
DDS_ReturnCode_t retcode;
int status = 0;
if (participant != NULL) {
retcode = DDS_DomainParticipant_delete_contained_entities(participant);
if (retcode != DDS_RETCODE_OK) {
printf("delete_contained_entities error %d\n", retcode);
status = -1;
}
retcode = DDS_DomainParticipantFactory_delete_participant(
DDS_TheParticipantFactory,
participant);
if (retcode != DDS_RETCODE_OK) {
printf("delete_participant error %d\n", retcode);
status = -1;
}
}
/* RTI Connext provides the finalize_instance() method on
domain participant factory for users who want to release memory used
by the participant factory. Uncomment the following block of code for
clean destruction of the singleton. */
/*
retcode = DDS_DomainParticipantFactory_finalize_instance();
if (retcode != DDS_RETCODE_OK) {
printf("finalize_instance error %d\n", retcode);
status = -1;
}
*/
return status;
}
static int subscriber_main(int domainId, int sample_count)
{
DDS_DomainParticipant *participant = NULL;
DDS_Subscriber *subscriber = NULL;
DDS_Topic *topic = NULL;
struct DDS_DataReaderListener reader_listener =
DDS_DataReaderListener_INITIALIZER;
DDS_DataReader *reader = NULL;
DDS_ReturnCode_t retcode;
const char *type_name = NULL;
int count = 0;
struct DDS_Duration_t poll_period = { 1, 0 };
struct DDS_StringSeq parameters;
const char *param_list[] = { "2" };
DDS_ContentFilteredTopic *cft = NULL;
/* struct DDS_DataReaderQos datareader_qos = DDS_DataReaderQos_INITIALIZER;
struct DDS_Duration_t deadline_period = {2, 0}; */
/* Changes for Deadline */
/* for timekeeping */
init = clock();
/* To customize participant QoS, use
the configuration file USER_QOS_PROFILES.xml */
participant = DDS_DomainParticipantFactory_create_participant(
DDS_TheParticipantFactory,
domainId,
&DDS_PARTICIPANT_QOS_DEFAULT,
NULL /* listener */,
DDS_STATUS_MASK_NONE);
if (participant == NULL) {
printf("create_participant error\n");
subscriber_shutdown(participant);
return -1;
}
/* To customize subscriber QoS, use
the configuration file USER_QOS_PROFILES.xml */
subscriber = DDS_DomainParticipant_create_subscriber(
participant,
&DDS_SUBSCRIBER_QOS_DEFAULT,
NULL /* listener */,
DDS_STATUS_MASK_NONE);
if (subscriber == NULL) {
printf("create_subscriber error\n");
subscriber_shutdown(participant);
return -1;
}
/* Register the type before creating the topic */
type_name = deadline_contentfilterTypeSupport_get_type_name();
retcode = deadline_contentfilterTypeSupport_register_type(
participant,
type_name);
if (retcode != DDS_RETCODE_OK) {
printf("register_type error %d\n", retcode);
subscriber_shutdown(participant);
return -1;
}
/* To customize topic QoS, use
the configuration file USER_QOS_PROFILES.xml */
topic = DDS_DomainParticipant_create_topic(
participant,
"Example deadline_contentfilter",
type_name,
&DDS_TOPIC_QOS_DEFAULT,
NULL /* listener */,
DDS_STATUS_MASK_NONE);
if (topic == NULL) {
printf("create_topic error\n");
subscriber_shutdown(participant);
return -1;
}
/* Set up a data reader listener */
reader_listener.on_requested_deadline_missed =
deadline_contentfilterListener_on_requested_deadline_missed;
reader_listener.on_requested_incompatible_qos =
deadline_contentfilterListener_on_requested_incompatible_qos;
reader_listener.on_sample_rejected =
deadline_contentfilterListener_on_sample_rejected;
reader_listener.on_liveliness_changed =
deadline_contentfilterListener_on_liveliness_changed;
reader_listener.on_sample_lost =
deadline_contentfilterListener_on_sample_lost;
reader_listener.on_subscription_matched =
deadline_contentfilterListener_on_subscription_matched;
reader_listener.on_data_available =
deadline_contentfilterListener_on_data_available;
/* Start changes for Deadline */
/* Set up content filtered topic to show interaction with deadline */
DDS_StringSeq_initialize(¶meters);
DDS_StringSeq_set_maximum(¶meters, 1);
DDS_StringSeq_from_array(¶meters, param_list, 1);
cft = DDS_DomainParticipant_create_contentfilteredtopic(
participant,
"ContentFilteredTopic",
topic,
"code < %0",
¶meters);
if (cft == NULL) {
printf("create_contentfilteredtopic error\n");
subscriber_shutdown(participant);
return -1;
}
/* To customize data reader QoS, use
the configuration file USER_QOS_PROFILES.xml */
reader = DDS_Subscriber_create_datareader(
subscriber,
DDS_Topic_as_topicdescription(cft),
&DDS_DATAREADER_QOS_DEFAULT,
&reader_listener,
DDS_STATUS_MASK_ALL);
if (reader == NULL) {
printf("create_datareader error\n");
subscriber_shutdown(participant);
return -1;
}
/* If you want to change the DataReader's QoS programmatically rather than
* using the XML file, you will need to add the following lines to your
* code and comment out the create_datareader call above.
*
* In this case, we set the deadline period to 2 seconds to trigger
* a deadline if the DataWriter does not update often enough, or if
* the content-filter filters out data so there is no data available
* with 2 seconds.
*/
/*
retcode = DDS_Subscriber_get_default_datareader_qos(subscriber,
&datareader_qos);
if (retcode != DDS_RETCODE_OK) {
printf("get_default_datareader_qos error\n");
return -1;
}
*/ /* Set deadline QoS */
/* datareader_qos.deadline.period = deadline_period;
reader = DDS_Subscriber_create_datareader(
subscriber, DDS_ContentFilteredTopic_as_topicdescription(cft),
&datareader_qos, &reader_listener, DDS_STATUS_MASK_ALL);
if (reader == NULL) {
printf("create_datareader error\n");
subscriber_shutdown(participant);
return -1;
}
*/
/* Main loop */
for (count = 0; (sample_count == 0) || (count < sample_count); ++count) {
if (count == 10) {
printf("Starting to filter out instance1 at time %d\n", count);
DDS_String_free(DDS_StringSeq_get(¶meters, 0));
*DDS_StringSeq_get_reference(¶meters, 0) = DDS_String_dup("1");
DDS_ContentFilteredTopic_set_expression_parameters(
cft,
¶meters);
}
NDDS_Utility_sleep(&poll_period);
}
/* End changes for Deadline */
/* Cleanup and delete all entities */
return subscriber_shutdown(participant);
}
#if defined(RTI_WINCE)
int wmain(int argc, wchar_t **argv)
{
int domainId = 0;
int sample_count = 0; /* infinite loop */
if (argc >= 2) {
domainId = _wtoi(argv[1]);
}
if (argc >= 3) {
sample_count = _wtoi(argv[2]);
}
/* Uncomment this to turn on additional logging
NDDS_Config_Logger_set_verbosity_by_category(
NDDS_Config_Logger_get_instance(),
NDDS_CONFIG_LOG_CATEGORY_API,
NDDS_CONFIG_LOG_VERBOSITY_STATUS_ALL);
*/
return subscriber_main(domainId, sample_count);
}
#elif !(defined(RTI_VXWORKS) && !defined(__RTP__)) && !defined(RTI_PSOS)
int main(int argc, char *argv[])
{
int domainId = 0;
int sample_count = 0; /* infinite loop */
if (argc >= 2) {
domainId = atoi(argv[1]);
}
if (argc >= 3) {
sample_count = atoi(argv[2]);
}
/* Uncomment this to turn on additional logging
NDDS_Config_Logger_set_verbosity_by_category(
NDDS_Config_Logger_get_instance(),
NDDS_CONFIG_LOG_CATEGORY_API,
NDDS_CONFIG_LOG_VERBOSITY_STATUS_ALL);
*/
return subscriber_main(domainId, sample_count);
}
#endif
#ifdef RTI_VX653
const unsigned char *__ctype = NULL;
void usrAppInit()
{
#ifdef USER_APPL_INIT
USER_APPL_INIT; /* for backwards compatibility */
#endif
/* add application specific code here */
taskSpawn(
"sub",
RTI_OSAPI_THREAD_PRIORITY_NORMAL,
0x8,
0x150000,
(FUNCPTR) subscriber_main,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0);
}
#endif
| c |
rticonnextdds-examples | data/projects/rticonnextdds-examples/connext_dds/deadline_contentfilter/c++03/deadline_contentfilter_subscriber.cxx | /*******************************************************************************
(c) 2005-2015 Copyright, Real-Time Innovations, Inc. All rights reserved.
RTI grants Licensee a license to use, modify, compile, and create derivative
works of the Software. Licensee has the right to distribute object form only
for use with RTI products. The Software is provided "as is", with no warranty
of any type, including any warranty for fitness for any purpose. RTI is under
no obligation to maintain or support the Software. RTI shall not be liable for
any incidental or consequential damages arising out of the use or inability to
use the software.
******************************************************************************/
#include <algorithm>
#include <cstdlib>
#include <ctime>
#include <iostream>
#include "deadline_contentfilter.hpp"
#include <dds/dds.hpp>
#include <rti/core/ListenerBinder.hpp>
using namespace dds::core;
using namespace dds::core::policy;
using namespace dds::core::status;
using namespace dds::domain;
using namespace dds::topic;
using namespace dds::sub;
using namespace dds::sub::qos;
clock_t init_time;
class deadline_contentfilterReaderListener
: public NoOpDataReaderListener<deadline_contentfilter> {
public:
void on_data_available(DataReader<deadline_contentfilter> &reader)
{
// Take all samples
LoanedSamples<deadline_contentfilter> samples = reader.take();
for (LoanedSamples<deadline_contentfilter>::iterator sample_it =
samples.begin();
sample_it != samples.end();
sample_it++) {
if (sample_it->info().valid()) {
// Print the time we get each sample.
double elapsed_ticks = clock() - init_time;
double elapsed_secs = elapsed_ticks / CLOCKS_PER_SEC;
const deadline_contentfilter &data = sample_it->data();
std::cout << "@ t=" << elapsed_secs << "s, Instance"
<< data.code() << ": <" << data.x() << "," << data.y()
<< ">" << std::endl;
}
}
}
void on_requested_deadline_missed(
DataReader<deadline_contentfilter> &reader,
const RequestedDeadlineMissedStatus &status)
{
double elapsed_ticks = clock() - init_time;
double elapsed_secs = elapsed_ticks / CLOCKS_PER_SEC;
// Creates a temporary object in order to find out which instance
// missed its deadline period. The 'key_value' call only fills in the
// values of the key fields inside the object.
deadline_contentfilter affected_sample;
reader.key_value(affected_sample, status.last_instance_handle());
// Print out which instance missed its deadline.
std::cout << "Missed deadline @ t=" << elapsed_secs
<< "s on instance code = " << affected_sample.code()
<< std::endl;
}
};
void subscriber_main(int domain_id, int sample_count)
{
// For timekeeping
init_time = clock();
// Create a DomainParticipant with default Qos
DomainParticipant participant(domain_id);
// Create a Topic -- and automatically register the type
Topic<deadline_contentfilter> topic(
participant,
"Example deadline_contentfilter");
// Set up a Content Filtered Topic to show interaction with deadline.
std::vector<std::string> parameters(1);
parameters[0] = "2";
ContentFilteredTopic<deadline_contentfilter> cft_topic(
topic,
"ContentFilteredTopic",
Filter("code < %0", parameters));
// Retrieve the default DataReader's QoS, from USER_QOS_PROFILES.xml
DataReaderQos reader_qos = QosProvider::Default().datareader_qos();
// If you want to change the DataReader's QoS programmatically rather than
// using the XML file, uncomment the following lines.
//
// In this case, we set the deadline period to 2 seconds to trigger
// a deadline if the DataWriter does not update often enough, or if
// the content-filter filters out data so there is no data available
// with 2 seconds.
// reader_qos << Deadline(Duration(2));
// Create a DataReader (Subscriber created in-line)
DataReader<deadline_contentfilter> reader(
Subscriber(participant),
cft_topic,
reader_qos);
// Create a data reader listener using ListenerBinder, a RAII that
// will take care of setting it to NULL on destruction.
rti::core::ListenerBinder<DataReader<deadline_contentfilter> > listener =
rti::core::bind_and_manage_listener(
reader,
new deadline_contentfilterReaderListener,
StatusMask::all());
std::cout << std::fixed;
for (short count = 0; (sample_count == 0) || (count < sample_count);
++count) {
// After 10 seconds, change filter to accept only instance 0.
if (count == 10) {
std::cout << "Starting to filter out instance1" << std::endl;
parameters[0] = "1";
cft_topic.filter_parameters(parameters.begin(), parameters.end());
}
rti::util::sleep(Duration(1));
}
}
int main(int argc, char *argv[])
{
int domain_id = 0;
int sample_count = 0; // Infinite loop
if (argc >= 2) {
domain_id = atoi(argv[1]);
}
if (argc >= 3) {
sample_count = atoi(argv[2]);
}
// To turn on additional logging, include <rti/config/Logger.hpp> and
// uncomment the following line:
// rti::config::Logger::instance().verbosity(rti::config::Verbosity::STATUS_ALL);
try {
subscriber_main(domain_id, sample_count);
} catch (const std::exception &ex) {
// This will catch DDS exceptions
std::cerr << "Exception in subscriber_main: " << ex.what() << std::endl;
return -1;
}
return 0;
}
| cxx |
rticonnextdds-examples | data/projects/rticonnextdds-examples/connext_dds/deadline_contentfilter/c++03/deadline_contentfilter_publisher.cxx | /*******************************************************************************
(c) 2005-2015 Copyright, Real-Time Innovations, Inc. All rights reserved.
RTI grants Licensee a license to use, modify, compile, and create derivative
works of the Software. Licensee has the right to distribute object form only
for use with RTI products. The Software is provided "as is", with no warranty
of any type, including any warranty for fitness for any purpose. RTI is under
no obligation to maintain or support the Software. RTI shall not be liable for
any incidental or consequential damages arising out of the use or inability to
use the software.
******************************************************************************/
#include <iostream>
#include "deadline_contentfilter.hpp"
#include <dds/dds.hpp>
#include <rti/core/ListenerBinder.hpp>
using namespace dds::core;
using namespace dds::core::policy;
using namespace dds::core::status;
using namespace dds::domain;
using namespace dds::topic;
using namespace dds::pub;
using namespace dds::pub::qos;
class DeadlineWriterListener
: public NoOpDataWriterListener<deadline_contentfilter> {
public:
void on_offered_deadline_missed(
DataWriter<deadline_contentfilter> &writer,
const OfferedDeadlineMissedStatus &status)
{
// Creates a temporary object in order to find out which instance
// missed its deadline period. The 'key_value' call only fills in the
// values of the key fields inside the object.
deadline_contentfilter affected_sample;
writer.key_value(affected_sample, status.last_instance_handle());
// Print out which instance missed its deadline.
std::cout << "Offered deadline missed on instance code = "
<< affected_sample.code() << std::endl;
}
};
void publisher_main(int domain_id, int sample_count)
{
// Create a DomainParticipant with default Qos
DomainParticipant participant(domain_id);
// Create a Topic -- and automatically register the type
Topic<deadline_contentfilter> topic(
participant,
"Example deadline_contentfilter");
// Retrieve the default DataWriter QoS, from USER_QOS_PROFILES.xml
DataWriterQos writer_qos = QosProvider::Default().datawriter_qos();
// If you want to change the DataWriter's QoS programmatically rather than
// using the XML file, uncomment the following lines.
// writer_qos << Deadline(Duration::from_millisecs(1500));
// Create a DataWriter (Publisher created in-line)
DataWriter<deadline_contentfilter> writer(Publisher(participant), topic);
// Associate a listener to the DataWriter using ListenerBinder, a RAII that
// will take care of setting it to NULL on destruction.
rti::core::ListenerBinder<DataWriter<deadline_contentfilter> > listener =
rti::core::bind_and_manage_listener(
writer,
new DeadlineWriterListener,
StatusMask::all());
// Create two instances for writing and register them in order to be able
// to recover them from the instance handle in the listener.
deadline_contentfilter sample0(0, 0, 0);
InstanceHandle handle0 = writer.register_instance(sample0);
deadline_contentfilter sample1(1, 0, 0);
InstanceHandle handle1 = writer.register_instance(sample1);
// Main loop.
for (int count = 0; count < sample_count || sample_count == 0; count++) {
rti::util::sleep(Duration(1));
// Update non-key fields.
sample0.x(count);
sample0.y(count);
sample1.x(count);
sample1.y(count);
std::cout << "Writing instance0, x = " << sample0.x()
<< ", y = " << sample0.y() << std::endl;
writer.write(sample0, handle0);
if (count < 15) {
std::cout << "Writing instance1, x = " << sample1.x()
<< ", y = " << sample1.y() << std::endl;
writer.write(sample1, handle1);
} else if (count == 15) {
std::cout << "Stopping writes to instance1" << std::endl;
}
}
// Unregister the instances.
writer.unregister_instance(handle0);
writer.unregister_instance(handle1);
}
int main(int argc, char *argv[])
{
int domain_id = 0;
int sample_count = 0; // Infinite loop
if (argc >= 2) {
domain_id = atoi(argv[1]);
}
if (argc >= 3) {
sample_count = atoi(argv[2]);
}
// To turn on additional logging, include <rti/config/Logger.hpp> and
// uncomment the following line:
// rti::config::Logger::instance().verbosity(rti::config::Verbosity::STATUS_ALL);
try {
publisher_main(domain_id, sample_count);
} catch (const std::exception &ex) {
// This will catch DDS exceptions
std::cerr << "Exception in publisher_main: " << ex.what() << std::endl;
return -1;
}
return 0;
}
| cxx |
rticonnextdds-examples | data/projects/rticonnextdds-examples/connext_dds/deadline_contentfilter/c++11/deadline_contentfilter_subscriber.cxx | /*******************************************************************************
(c) 2005-2015 Copyright, Real-Time Innovations, Inc. All rights reserved.
RTI grants Licensee a license to use, modify, compile, and create derivative
works of the Software. Licensee has the right to distribute object form only
for use with RTI products. The Software is provided "as is", with no warranty
of any type, including any warranty for fitness for any purpose. RTI is under
no obligation to maintain or support the Software. RTI shall not be liable for
any incidental or consequential damages arising out of the use or inability to
use the software.
******************************************************************************/
#include <dds/sub/ddssub.hpp>
#include <dds/core/ddscore.hpp>
#include <rti/util/util.hpp> // for sleep()
#include <rti/config/Logger.hpp> // for logging
#include "deadline_contentfilter.hpp"
#include "application.hpp" // for command line parsing and ctrl-c
clock_t init_time;
class deadline_contentfilterReaderListener
: public dds::sub::NoOpDataReaderListener<deadline_contentfilter> {
public:
void on_data_available(dds::sub::DataReader<deadline_contentfilter> &reader)
{
// Take all samples
dds::sub::LoanedSamples<deadline_contentfilter> samples = reader.take();
for (const auto &sample : samples) {
if (sample.info().valid()) {
// Print the time we get each sample.
double elapsed_ticks = clock() - init_time;
double elapsed_secs = elapsed_ticks / CLOCKS_PER_SEC;
const deadline_contentfilter &data = sample.data();
std::cout << "@ t=" << elapsed_secs << "s, Instance"
<< data.code() << ": <" << data.x() << "," << data.y()
<< ">" << std::endl;
}
}
}
void on_requested_deadline_missed(
dds::sub::DataReader<deadline_contentfilter> &reader,
const dds::core::status::RequestedDeadlineMissedStatus &status)
{
double elapsed_ticks = clock() - init_time;
double elapsed_secs = elapsed_ticks / CLOCKS_PER_SEC;
// Creates a temporary object in order to find out which instance
// missed its deadline period. The 'key_value' call only fills in the
// values of the key fields inside the object.
deadline_contentfilter affected_sample;
reader.key_value(affected_sample, status.last_instance_handle());
// Print out which instance missed its deadline.
std::cout << "Missed deadline @ t=" << elapsed_secs
<< "s on instance code = " << affected_sample.code()
<< std::endl;
}
};
void run_subscriber_application(
unsigned int domain_id,
unsigned int sample_count)
{
// For timekeeping
init_time = clock();
// Create a DomainParticipant with default Qos
dds::domain::DomainParticipant participant(domain_id);
// Create a Topic -- and automatically register the type
dds::topic::Topic<deadline_contentfilter> topic(
participant,
"Example deadline_contentfilter");
// Set up a Content Filtered Topic to show interaction with deadline.
dds::topic::ContentFilteredTopic<deadline_contentfilter> cft_topic(
topic,
"ContentFilteredTopic",
dds::topic::Filter("code < %0", { "2" }));
// Retrieve the default DataReader's QoS, from USER_QOS_PROFILES.xml
dds::sub::qos::DataReaderQos reader_qos =
dds::core::QosProvider::Default().datareader_qos();
// If you want to change the DataReader's QoS programmatically rather than
// using the XML file, uncomment the following lines.
//
// In this case, we set the deadline period to 2 seconds to trigger
// a deadline if the DataWriter does not update often enough, or if
// the content-filter filters out data so there is no data available
// with 2 seconds.
// reader_qos << Deadline(Duration(2));
// Create a subscriber
dds::sub::Subscriber subscriber(participant);
// Create a shared pointer for deadline_contentfilterReaderListener class
auto deadline_listener =
std::make_shared<deadline_contentfilterReaderListener>();
// Create a DataReader
dds::sub::DataReader<deadline_contentfilter> reader(
subscriber,
cft_topic,
reader_qos);
// Set the created listened for the DataReader
reader.set_listener(deadline_listener);
std::cout << std::fixed;
for (unsigned int samples_read = 0;
!application::shutdown_requested && samples_read < sample_count;
samples_read++) {
// After 10 seconds, change filter to accept only instance 0.
if (samples_read == 10) {
std::cout << "Starting to filter out instance1" << std::endl;
std::vector<std::string> parameter { "1" };
cft_topic.filter_parameters(parameter.begin(), parameter.end());
}
rti::util::sleep(dds::core::Duration(1));
}
}
int main(int argc, char *argv[])
{
using namespace application;
// Parse arguments and handle control-C
auto arguments = parse_arguments(argc, argv);
if (arguments.parse_result == ParseReturn::exit) {
return EXIT_SUCCESS;
} else if (arguments.parse_result == ParseReturn::failure) {
return EXIT_FAILURE;
}
setup_signal_handlers();
// Sets Connext verbosity to help debugging
rti::config::Logger::instance().verbosity(arguments.verbosity);
try {
run_subscriber_application(arguments.domain_id, arguments.sample_count);
} catch (const std::exception &ex) {
// This will catch DDS exceptions
std::cerr << "Exception in run_subscriber_application(): " << ex.what()
<< std::endl;
return EXIT_FAILURE;
}
// Releases the memory used by the participant factory. Optional at
// application exit
dds::domain::DomainParticipant::finalize_participant_factory();
return EXIT_SUCCESS;
}
| cxx |
rticonnextdds-examples | data/projects/rticonnextdds-examples/connext_dds/deadline_contentfilter/c++11/application.hpp | /*
* (c) Copyright, Real-Time Innovations, 2020. All rights reserved.
* RTI grants Licensee a license to use, modify, compile, and create derivative
* works of the software solely for use with RTI Connext DDS. Licensee may
* redistribute copies of the software provided that all such copies are subject
* to this license. The software is provided "as is", with no warranty of any
* type, including any warranty for fitness for any purpose. RTI is under no
* obligation to maintain or support the software. RTI shall not be liable for
* any incidental or consequential damages arising out of the use or inability
* to use the software.
*/
#ifndef APPLICATION_HPP
#define APPLICATION_HPP
#include <iostream>
#include <csignal>
#include <dds/core/ddscore.hpp>
namespace application {
// Catch control-C and tell application to shut down
bool shutdown_requested = false;
inline void stop_handler(int)
{
shutdown_requested = true;
std::cout << "preparing to shut down..." << std::endl;
}
inline void setup_signal_handlers()
{
signal(SIGINT, stop_handler);
signal(SIGTERM, stop_handler);
}
enum class ParseReturn { ok, failure, exit };
struct ApplicationArguments {
ParseReturn parse_result;
unsigned int domain_id;
unsigned int sample_count;
rti::config::Verbosity verbosity;
ApplicationArguments(
ParseReturn parse_result_param,
unsigned int domain_id_param,
unsigned int sample_count_param,
rti::config::Verbosity verbosity_param)
: parse_result(parse_result_param),
domain_id(domain_id_param),
sample_count(sample_count_param),
verbosity(verbosity_param)
{
}
};
inline void set_verbosity(
rti::config::Verbosity &verbosity,
int verbosity_value)
{
switch (verbosity_value) {
case 0:
verbosity = rti::config::Verbosity::SILENT;
break;
case 1:
verbosity = rti::config::Verbosity::EXCEPTION;
break;
case 2:
verbosity = rti::config::Verbosity::WARNING;
break;
case 3:
verbosity = rti::config::Verbosity::STATUS_ALL;
break;
default:
verbosity = rti::config::Verbosity::EXCEPTION;
break;
}
}
// Parses application arguments for example.
inline ApplicationArguments parse_arguments(int argc, char *argv[])
{
int arg_processing = 1;
bool show_usage = false;
ParseReturn parse_result = ParseReturn::ok;
unsigned int domain_id = 0;
unsigned int sample_count = (std::numeric_limits<unsigned int>::max)();
rti::config::Verbosity verbosity(rti::config::Verbosity::EXCEPTION);
while (arg_processing < argc) {
if ((argc > arg_processing + 1)
&& (strcmp(argv[arg_processing], "-d") == 0
|| strcmp(argv[arg_processing], "--domain") == 0)) {
domain_id = atoi(argv[arg_processing + 1]);
arg_processing += 2;
} else if (
(argc > arg_processing + 1)
&& (strcmp(argv[arg_processing], "-s") == 0
|| strcmp(argv[arg_processing], "--sample-count") == 0)) {
sample_count = atoi(argv[arg_processing + 1]);
arg_processing += 2;
} else if (
(argc > arg_processing + 1)
&& (strcmp(argv[arg_processing], "-v") == 0
|| strcmp(argv[arg_processing], "--verbosity") == 0)) {
set_verbosity(verbosity, atoi(argv[arg_processing + 1]));
arg_processing += 2;
} else if (
strcmp(argv[arg_processing], "-h") == 0
|| strcmp(argv[arg_processing], "--help") == 0) {
std::cout << "Example application." << std::endl;
show_usage = true;
parse_result = ParseReturn::exit;
break;
} else {
std::cout << "Bad parameter." << std::endl;
show_usage = true;
parse_result = ParseReturn::failure;
break;
}
}
if (show_usage) {
std::cout << "Usage:\n"
" -d, --domain <int> Domain ID this "
"application will\n"
" subscribe in. \n"
" Default: 0\n"
" -s, --sample_count <int> Number of samples to "
"receive before\n"
" cleanly shutting down. \n"
" Default: infinite\n"
" -v, --verbosity <int> How much debugging output "
"to show.\n"
" Range: 0-3 \n"
" Default: 1"
<< std::endl;
}
return ApplicationArguments(
parse_result,
domain_id,
sample_count,
verbosity);
}
} // namespace application
#endif // APPLICATION_HPP | hpp |
rticonnextdds-examples | data/projects/rticonnextdds-examples/connext_dds/deadline_contentfilter/c++11/deadline_contentfilter_publisher.cxx | /*******************************************************************************
(c) 2005-2015 Copyright, Real-Time Innovations, Inc. All rights reserved.
RTI grants Licensee a license to use, modify, compile, and create derivative
works of the Software. Licensee has the right to distribute object form only
for use with RTI products. The Software is provided "as is", with no warranty
of any type, including any warranty for fitness for any purpose. RTI is under
no obligation to maintain or support the Software. RTI shall not be liable for
any incidental or consequential damages arising out of the use or inability to
use the software.
******************************************************************************/
#include <dds/pub/ddspub.hpp>
#include <dds/sub/ddssub.hpp>
#include <rti/util/util.hpp> // for sleep()
#include <rti/config/Logger.hpp> // for logging
#include "application.hpp" // for command line parsing and ctrl-c
#include "deadline_contentfilter.hpp"
class DeadlineWriterListener
: public dds::pub::NoOpDataWriterListener<deadline_contentfilter> {
public:
void on_offered_deadline_missed(
dds::pub::DataWriter<deadline_contentfilter> &writer,
const dds::core::status::OfferedDeadlineMissedStatus &status)
{
// Creates a temporary object in order to find out which instance
// missed its deadline period. The 'key_value' call only fills in the
// values of the key fields inside the object.
deadline_contentfilter affected_sample;
writer.key_value(affected_sample, status.last_instance_handle());
// Print out which instance missed its deadline.
std::cout << "Offered deadline missed on instance code = "
<< affected_sample.code() << std::endl;
}
};
void run_publisher_application(
unsigned int domain_id,
unsigned int sample_count)
{
// Create a DomainParticipant with default Qos
dds::domain::DomainParticipant participant(domain_id);
// Create a Topic -- and automatically register the type
dds::topic::Topic<deadline_contentfilter> topic(
participant,
"Example deadline_contentfilter");
// Retrieve the default DataWriter QoS, from USER_QOS_PROFILES.xml
dds::pub::qos::DataWriterQos writer_qos =
dds::core::QosProvider::Default().datawriter_qos();
// If you want to change the DataWriter's QoS programmatically rather than
// using the XML file, uncomment the following lines.
// writer_qos << Deadline(Duration::from_millisecs(1500));
// Create a publisher
dds::pub::Publisher publisher(participant);
// Create a shared pointer for DeadlineWriterListener class
auto deadline_listener = std::make_shared<DeadlineWriterListener>();
// Create a DataWriter with the listener
dds::pub::DataWriter<deadline_contentfilter> writer(
publisher,
topic,
writer_qos,
deadline_listener);
// Create two instances for writing and register them in order to be able
// to recover them from the instance handle in the listener.
deadline_contentfilter sample0(0, 0, 0);
dds::core::InstanceHandle handle0 = writer.register_instance(sample0);
deadline_contentfilter sample1(1, 0, 0);
dds::core::InstanceHandle handle1 = writer.register_instance(sample1);
// Main loop.
for (unsigned int samples_written = 0;
!application::shutdown_requested && samples_written < sample_count;
samples_written++) {
rti::util::sleep(dds::core::Duration(1));
// Update non-key fields.
sample0.x(samples_written);
sample0.y(samples_written);
sample1.x(samples_written);
sample1.y(samples_written);
std::cout << "Writing instance0, x = " << sample0.x()
<< ", y = " << sample0.y() << std::endl;
writer.write(sample0, handle0);
if (samples_written < 15) {
std::cout << "Writing instance1, x = " << sample1.x()
<< ", y = " << sample1.y() << std::endl;
writer.write(sample1, handle1);
} else if (samples_written == 15) {
std::cout << "Stopping writes to instance1" << std::endl;
}
}
// Unregister the instances.
writer.unregister_instance(handle0);
writer.unregister_instance(handle1);
}
int main(int argc, char *argv[])
{
using namespace application;
// Parse arguments and handle control-C
auto arguments = parse_arguments(argc, argv);
if (arguments.parse_result == ParseReturn::exit) {
return EXIT_SUCCESS;
} else if (arguments.parse_result == ParseReturn::failure) {
return EXIT_FAILURE;
}
setup_signal_handlers();
// Sets Connext verbosity to help debugging
rti::config::Logger::instance().verbosity(arguments.verbosity);
try {
run_publisher_application(arguments.domain_id, arguments.sample_count);
} catch (const std::exception &ex) {
// This will catch DDS exceptions
std::cerr << "Exception in run_publisher_application(): " << ex.what()
<< std::endl;
return EXIT_FAILURE;
}
// Releases the memory used by the participant factory. Optional at
// application exit
dds::domain::DomainParticipant::finalize_participant_factory();
return EXIT_SUCCESS;
}
| cxx |
rticonnextdds-examples | data/projects/rticonnextdds-examples/connext_dds/keyed_data/c++/keys_publisher.cxx | /*******************************************************************************
(c) 2005-2014 Copyright, Real-Time Innovations, Inc. All rights reserved.
RTI grants Licensee a license to use, modify, compile, and create derivative
works of the Software. Licensee has the right to distribute object form only
for use with RTI products. The Software is provided "as is", with no warranty
of any type, including any warranty for fitness for any purpose. RTI is under
no obligation to maintain or support the Software. RTI shall not be liable for
any incidental or consequential damages arising out of the use or inability to
use the software.
******************************************************************************/
/* keys_publisher.cxx
A publication of data of type keys
This file is derived from code automatically generated by the rtiddsgen
command:
rtiddsgen -language C++ -example <arch> keys.idl
Example publication of type keys automatically generated by
'rtiddsgen'. To test them follow these steps:
(1) Compile this file and the example subscription.
(2) Start the subscription with the command
objs/<arch>/keys_subscriber <domain_id> <sample_count>
(3) Start the publication with the command
objs/<arch>/keys_publisher <domain_id> <sample_count>
(4) [Optional] Specify the list of discovery initial peers and
multicast receive addresses via an environment variable or a file
(in the current working directory) called NDDS_DISCOVERY_PEERS.
You can run any number of publishers and subscribers programs, and can
add and remove them dynamically from the domain.
Example:
To run the example application on domain <domain_id>:
On Unix:
objs/<arch>/keys_publisher <domain_id> o
objs/<arch>/keys_subscriber <domain_id>
On Windows:
objs\<arch>\keys_publisher <domain_id>
objs\<arch>\keys_subscriber <domain_id>
modification history
------------ -------
*/
#include <stdio.h>
#include <stdlib.h>
#ifdef RTI_VX653
#include <vThreadsData.h>
#endif
#include "keys.h"
#include "keysSupport.h"
#include "ndds/ndds_cpp.h"
/* Delete all entities */
static int publisher_shutdown(DDSDomainParticipant *participant)
{
DDS_ReturnCode_t retcode;
int status = 0;
if (participant != NULL) {
retcode = participant->delete_contained_entities();
if (retcode != DDS_RETCODE_OK) {
printf("delete_contained_entities error %d\n", retcode);
status = -1;
}
retcode = DDSTheParticipantFactory->delete_participant(participant);
if (retcode != DDS_RETCODE_OK) {
printf("delete_participant error %d\n", retcode);
status = -1;
}
}
/* RTI Connext provides finalize_instance() method on
domain participant factory for people who want to release memory used
by the participant factory. Uncomment the following block of code for
clean destruction of the singleton. */
/*
retcode = DDSDomainParticipantFactory::finalize_instance();
if (retcode != DDS_RETCODE_OK) {
printf("finalize_instance error %d\n", retcode);
status = -1;
}
*/
return status;
}
extern "C" int publisher_main(int domainId, int sample_count)
{
DDSDomainParticipant *participant = NULL;
DDSPublisher *publisher = NULL;
DDSTopic *topic = NULL;
DDSDataWriter *writer = NULL;
keysDataWriter *keys_writer = NULL;
/* Creates three instances */
keys *instance[3] = { NULL, NULL, NULL };
/* Creates three handles for managing the registrations */
DDS_InstanceHandle_t handle[3] = { DDS_HANDLE_NIL,
DDS_HANDLE_NIL,
DDS_HANDLE_NIL };
/* We only will send data over the instances marked as active */
int active[3] = { 1, 0, 0 };
DDS_ReturnCode_t retcode;
const char *type_name = NULL;
int count = 0;
DDS_Duration_t send_period = { 1, 0 };
/* To customize participant QoS, use
the configuration file USER_QOS_PROFILES.xml */
participant = DDSTheParticipantFactory->create_participant(
domainId,
DDS_PARTICIPANT_QOS_DEFAULT,
NULL /* listener */,
DDS_STATUS_MASK_NONE);
if (participant == NULL) {
printf("create_participant error\n");
publisher_shutdown(participant);
return -1;
}
/* To customize publisher QoS, use
the configuration file USER_QOS_PROFILES.xml */
publisher = participant->create_publisher(
DDS_PUBLISHER_QOS_DEFAULT,
NULL /* listener */,
DDS_STATUS_MASK_NONE);
if (publisher == NULL) {
printf("create_publisher error\n");
publisher_shutdown(participant);
return -1;
}
/* Register type before creating topic */
type_name = keysTypeSupport::get_type_name();
retcode = keysTypeSupport::register_type(participant, type_name);
if (retcode != DDS_RETCODE_OK) {
printf("register_type error %d\n", retcode);
publisher_shutdown(participant);
return -1;
}
/* To customize topic QoS, use
the configuration file USER_QOS_PROFILES.xml */
topic = participant->create_topic(
"Example keys",
type_name,
DDS_TOPIC_QOS_DEFAULT,
NULL /* listener */,
DDS_STATUS_MASK_NONE);
if (topic == NULL) {
printf("create_topic error\n");
publisher_shutdown(participant);
return -1;
}
/* To customize data writer QoS, use
the configuration file USER_QOS_PROFILES.xml */
writer = publisher->create_datawriter(
topic,
DDS_DATAWRITER_QOS_DEFAULT,
NULL /* listener */,
DDS_STATUS_MASK_NONE);
if (writer == NULL) {
printf("create_datawriter error\n");
publisher_shutdown(participant);
return -1;
}
/* If you want to set the writer_data_lifecycle QoS settings
* programmatically rather than using the XML, you will need to add
* the following lines to your code and comment out the create_datawriter
* call above.
*/
/*
DDS_DataWriterQos datawriter_qos;
retcode = publisher->get_default_datawriter_qos(datawriter_qos);
if (retcode != DDS_RETCODE_OK) {
printf("get_default_datawriter_qos error\n");
return -1;
}
datawriter_qos.writer_data_lifecycle.autodispose_unregistered_instances =
DDS_BOOLEAN_FALSE;
writer = publisher->create_datawriter(
topic, datawriter_qos, NULL,
DDS_STATUS_MASK_NONE);
if (writer == NULL) {
printf("create_datawriter error\n");
publisher_shutdown(participant);
return -1;
}
*/
keys_writer = keysDataWriter::narrow(writer);
if (keys_writer == NULL) {
printf("DataWriter narrow error\n");
publisher_shutdown(participant);
return -1;
}
/* Create data samples for writing */
instance[0] = keysTypeSupport::create_data();
instance[1] = keysTypeSupport::create_data();
instance[2] = keysTypeSupport::create_data();
if (instance[0] == NULL || instance[1] == NULL || instance[2] == NULL) {
printf("keysTypeSupport::create_data error\n");
publisher_shutdown(participant);
return -1;
}
/* RTI Connext could examine the key fields each time it needs to determine
* which data-instance is being modified.
* However, for performance and semantic reasons, it is better
* for your application to declare all the data-instances it intends to
* modify prior to actually writing any samples. This is known as
* registration.
*/
/* In order to register the instances, we must set their associated keys
* first */
instance[0]->code = 0;
instance[1]->code = 1;
instance[2]->code = 2;
/* The keys must have been set before making this call */
printf("Registering instance %d\n", instance[0]->code);
handle[0] = keys_writer->register_instance(*instance[0]);
/* Modify the data to be sent here */
instance[0]->x = 1000;
instance[1]->x = 2000;
instance[2]->x = 3000;
/* Main loop */
for (count = 0; (sample_count == 0) || (count < sample_count); ++count) {
NDDSUtility::sleep(send_period);
switch (count) {
case 5: { /* Start sending the second and third instances */
printf("----Registering instance %d\n", instance[1]->code);
printf("----Registering instance %d\n", instance[2]->code);
handle[1] = keys_writer->register_instance(*instance[1]);
handle[2] = keys_writer->register_instance(*instance[2]);
active[1] = 1;
active[2] = 1;
} break;
case 10: { /* Unregister the second instance */
printf("----Unregistering instance %d\n", instance[1]->code);
retcode = keys_writer->unregister_instance(*instance[1], handle[1]);
if (retcode != DDS_RETCODE_OK) {
printf("unregister instance error %d\n", retcode);
return -1;
}
active[1] = 0;
} break;
case 15: { /* Dispose the third instance */
printf("----Disposing \\instance %d\n", instance[2]->code);
retcode = keys_writer->dispose(*instance[2], handle[2]);
if (retcode != DDS_RETCODE_OK) {
printf("dispose instance error %d\n", retcode);
return -1;
}
active[2] = 0;
} break;
}
/* Modify the data to be sent here */
instance[0]->y = count;
instance[1]->y = count;
instance[2]->y = count;
for (int i = 0; i < 3; ++i) {
if (active[i]) {
printf("Writing instance %d, x: %d, y: %d\n",
instance[i]->code,
instance[i]->x,
instance[i]->y);
retcode = keys_writer->write(*instance[i], handle[i]);
if (retcode != DDS_RETCODE_OK) {
printf("write error %d\n", retcode);
return -1;
}
}
}
}
/* Delete data samples */
for (int i = 0; i < 3; ++i) {
retcode = keysTypeSupport::delete_data(instance[i]);
if (retcode != DDS_RETCODE_OK) {
printf("keysTypeSupport::delete_data error %d\n", retcode);
}
}
/* Delete all entities */
return publisher_shutdown(participant);
}
#if defined(RTI_WINCE)
int wmain(int argc, wchar_t **argv)
{
int domainId = 0;
int sample_count = 0; /* infinite loop */
if (argc >= 2) {
domainId = _wtoi(argv[1]);
}
if (argc >= 3) {
sample_count = _wtoi(argv[2]);
}
/* Uncomment this to turn on additional logging
NDDSConfigLogger::get_instance()->
set_verbosity_by_category(NDDS_CONFIG_LOG_CATEGORY_API,
NDDS_CONFIG_LOG_VERBOSITY_STATUS_ALL);
*/
return publisher_main(domainId, sample_count);
}
#elif !(defined(RTI_VXWORKS) && !defined(__RTP__)) && !defined(RTI_PSOS)
int main(int argc, char *argv[])
{
int domainId = 0;
int sample_count = 0; /* infinite loop */
if (argc >= 2) {
domainId = atoi(argv[1]);
}
if (argc >= 3) {
sample_count = atoi(argv[2]);
}
/* Uncomment this to turn on additional logging
NDDSConfigLogger::get_instance()->
set_verbosity_by_category(NDDS_CONFIG_LOG_CATEGORY_API,
NDDS_CONFIG_LOG_VERBOSITY_STATUS_ALL);
*/
return publisher_main(domainId, sample_count);
}
#endif
#ifdef RTI_VX653
const unsigned char *__ctype = *(__ctypePtrGet());
extern "C" void usrAppInit()
{
#ifdef USER_APPL_INIT
USER_APPL_INIT; /* for backwards compatibility */
#endif
/* add application specific code here */
taskSpawn(
"pub",
RTI_OSAPI_THREAD_PRIORITY_NORMAL,
0x8,
0x150000,
(FUNCPTR) publisher_main,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0);
}
#endif
| cxx |
rticonnextdds-examples | data/projects/rticonnextdds-examples/connext_dds/keyed_data/c++/keys_subscriber.cxx | /*******************************************************************************
(c) 2005-2014 Copyright, Real-Time Innovations, Inc. All rights reserved.
RTI grants Licensee a license to use, modify, compile, and create derivative
works of the Software. Licensee has the right to distribute object form only
for use with RTI products. The Software is provided "as is", with no warranty
of any type, including any warranty for fitness for any purpose. RTI is under
no obligation to maintain or support the Software. RTI shall not be liable for
any incidental or consequential damages arising out of the use or inability to
use the software.
******************************************************************************/
/* keys_subscriber.cxx
A subscription example
This file is derived from code automatically generated by the rtiddsgen
command:
rtiddsgen -language C++ -example <arch> keys.idl
Example subscription of type keys automatically generated by
'rtiddsgen'. To test them follow these steps:
(1) Compile this file and the example publication.
(2) Start the subscription with the command
objs/<arch>/keys_subscriber <domain_id> <sample_count>
(3) Start the publication with the command
objs/<arch>/keys_publisher <domain_id> <sample_count>
(4) [Optional] Specify the list of discovery initial peers and
multicast receive addresses via an environment variable or a file
(in the current working directory) called NDDS_DISCOVERY_PEERS.
You can run any number of publishers and subscribers programs, and can
add and remove them dynamically from the domain.
Example:
To run the example application on domain <domain_id>:
On Unix:
objs/<arch>/keys_publisher <domain_id>
objs/<arch>/keys_subscriber <domain_id>
On Windows:
objs\<arch>\keys_publisher <domain_id>
objs\<arch>\keys_subscriber <domain_id>
modification history
------------ -------
*/
#include <stdio.h>
#include <stdlib.h>
#ifdef RTI_VX653
#include <vThreadsData.h>
#endif
#include "keys.h"
#include "keysSupport.h"
#include "ndds/ndds_cpp.h"
class keysListener : public DDSDataReaderListener {
public:
virtual void on_requested_deadline_missed(
DDSDataReader * /*reader*/,
const DDS_RequestedDeadlineMissedStatus & /*status*/)
{
}
virtual void on_requested_incompatible_qos(
DDSDataReader * /*reader*/,
const DDS_RequestedIncompatibleQosStatus & /*status*/)
{
}
virtual void on_sample_rejected(
DDSDataReader * /*reader*/,
const DDS_SampleRejectedStatus & /*status*/)
{
}
virtual void on_liveliness_changed(
DDSDataReader * /*reader*/,
const DDS_LivelinessChangedStatus & /*status*/)
{
}
virtual void on_sample_lost(
DDSDataReader * /*reader*/,
const DDS_SampleLostStatus & /*status*/)
{
}
virtual void on_subscription_matched(
DDSDataReader * /*reader*/,
const DDS_SubscriptionMatchedStatus & /*status*/)
{
}
virtual void on_data_available(DDSDataReader *reader);
};
void keysListener::on_data_available(DDSDataReader *reader)
{
keysDataReader *keys_reader = NULL;
keysSeq data_seq;
DDS_SampleInfoSeq info_seq;
DDS_ReturnCode_t retcode;
int i;
keys_reader = keysDataReader::narrow(reader);
if (keys_reader == NULL) {
printf("DataReader narrow error\n");
return;
}
retcode = keys_reader->take(
data_seq,
info_seq,
DDS_LENGTH_UNLIMITED,
DDS_ANY_SAMPLE_STATE,
DDS_ANY_VIEW_STATE,
DDS_ANY_INSTANCE_STATE);
if (retcode == DDS_RETCODE_NO_DATA) {
return;
} else if (retcode != DDS_RETCODE_OK) {
printf("take error %d\n", retcode);
return;
}
for (i = 0; i < data_seq.length(); ++i) {
/* Start changes for Keyed_Data */
/* We first check if the sample includes valid data */
if (info_seq[i].valid_data) {
if (info_seq[i].view_state == DDS_NEW_VIEW_STATE) {
printf("Found new instance; code = %d\n", data_seq[i].code);
}
printf("Instance %d: x: %d, y: %d\n",
data_seq[i].code,
data_seq[i].x,
data_seq[i].y);
} else {
/* Since there is not valid data, it may include metadata */
keys dummy;
retcode = keys_reader->get_key_value(
dummy,
info_seq[i].instance_handle);
if (retcode != DDS_RETCODE_OK) {
printf("get_key_value error %d\n", retcode);
continue;
}
/* Here we print a message if the instance state is ALIVE_NO_WRITERS
* or ALIVE_DISPOSED */
if (info_seq[i].instance_state
== DDS_NOT_ALIVE_NO_WRITERS_INSTANCE_STATE) {
printf("Instance %d has no writers\n", dummy.code);
} else if (
info_seq[i].instance_state
== DDS_NOT_ALIVE_DISPOSED_INSTANCE_STATE) {
printf("Instance %d disposed\n", dummy.code);
}
}
/* End changes for Keyed_Data */
}
retcode = keys_reader->return_loan(data_seq, info_seq);
if (retcode != DDS_RETCODE_OK) {
printf("return loan error %d\n", retcode);
}
}
/* Delete all entities */
static int subscriber_shutdown(DDSDomainParticipant *participant)
{
DDS_ReturnCode_t retcode;
int status = 0;
if (participant != NULL) {
retcode = participant->delete_contained_entities();
if (retcode != DDS_RETCODE_OK) {
printf("delete_contained_entities error %d\n", retcode);
status = -1;
}
retcode = DDSTheParticipantFactory->delete_participant(participant);
if (retcode != DDS_RETCODE_OK) {
printf("delete_participant error %d\n", retcode);
status = -1;
}
}
/* RTI Connext provides the finalize_instance() method on
domain participant factory for people who want to release memory used
by the participant factory. Uncomment the following block of code for
clean destruction of the singleton. */
/*
retcode = DDSDomainParticipantFactory::finalize_instance();
if (retcode != DDS_RETCODE_OK) {
printf("finalize_instance error %d\n", retcode);
status = -1;
}
*/
return status;
}
extern "C" int subscriber_main(int domainId, int sample_count)
{
DDSDomainParticipant *participant = NULL;
DDSSubscriber *subscriber = NULL;
DDSTopic *topic = NULL;
keysListener *reader_listener = NULL;
DDSDataReader *reader = NULL;
DDS_ReturnCode_t retcode;
const char *type_name = NULL;
int count = 0;
DDS_Duration_t receive_period = { 1, 0 };
int status = 0;
/* To customize the participant QoS, use
the configuration file USER_QOS_PROFILES.xml */
participant = DDSTheParticipantFactory->create_participant(
domainId,
DDS_PARTICIPANT_QOS_DEFAULT,
NULL /* listener */,
DDS_STATUS_MASK_NONE);
if (participant == NULL) {
printf("create_participant error\n");
subscriber_shutdown(participant);
return -1;
}
/* To customize the subscriber QoS, use
the configuration file USER_QOS_PROFILES.xml */
subscriber = participant->create_subscriber(
DDS_SUBSCRIBER_QOS_DEFAULT,
NULL /* listener */,
DDS_STATUS_MASK_NONE);
if (subscriber == NULL) {
printf("create_subscriber error\n");
subscriber_shutdown(participant);
return -1;
}
/* Register the type before creating the topic */
type_name = keysTypeSupport::get_type_name();
retcode = keysTypeSupport::register_type(participant, type_name);
if (retcode != DDS_RETCODE_OK) {
printf("register_type error %d\n", retcode);
subscriber_shutdown(participant);
return -1;
}
/* To customize the topic QoS, use
the configuration file USER_QOS_PROFILES.xml */
topic = participant->create_topic(
"Example keys",
type_name,
DDS_TOPIC_QOS_DEFAULT,
NULL /* listener */,
DDS_STATUS_MASK_NONE);
if (topic == NULL) {
printf("create_topic error\n");
subscriber_shutdown(participant);
return -1;
}
/* Create a data reader listener */
reader_listener = new keysListener();
/* To customize the data reader QoS, use
the configuration file USER_QOS_PROFILES.xml */
reader = subscriber->create_datareader(
topic,
DDS_DATAREADER_QOS_DEFAULT,
reader_listener,
DDS_STATUS_MASK_ALL);
if (reader == NULL) {
printf("create_datareader error\n");
subscriber_shutdown(participant);
delete reader_listener;
return -1;
}
/* Main loop */
for (count = 0; (sample_count == 0) || (count < sample_count); ++count) {
// printf("keys subscriber sleeping for %d
// sec...\n",receive_period.sec);
NDDSUtility::sleep(receive_period);
}
/* Delete all entities */
status = subscriber_shutdown(participant);
delete reader_listener;
return status;
}
#if defined(RTI_WINCE)
int wmain(int argc, wchar_t **argv)
{
int domainId = 0;
int sample_count = 0; /* infinite loop */
if (argc >= 2) {
domainId = _wtoi(argv[1]);
}
if (argc >= 3) {
sample_count = _wtoi(argv[2]);
}
/* Uncomment this to turn on additional logging
NDDSConfigLogger::get_instance()->
set_verbosity_by_category(NDDS_CONFIG_LOG_CATEGORY_API,
NDDS_CONFIG_LOG_VERBOSITY_STATUS_ALL);
*/
return subscriber_main(domainId, sample_count);
}
#elif !(defined(RTI_VXWORKS) && !defined(__RTP__)) && !defined(RTI_PSOS)
int main(int argc, char *argv[])
{
int domainId = 0;
int sample_count = 0; /* infinite loop */
if (argc >= 2) {
domainId = atoi(argv[1]);
}
if (argc >= 3) {
sample_count = atoi(argv[2]);
}
/* Uncomment this to turn on additional logging
NDDSConfigLogger::get_instance()->
set_verbosity_by_category(NDDS_CONFIG_LOG_CATEGORY_API,
NDDS_CONFIG_LOG_VERBOSITY_STATUS_ALL);
*/
return subscriber_main(domainId, sample_count);
}
#endif
#ifdef RTI_VX653
const unsigned char *__ctype = *(__ctypePtrGet());
extern "C" void usrAppInit()
{
#ifdef USER_APPL_INIT
USER_APPL_INIT; /* for backwards compatibility */
#endif
/* add application specific code here */
taskSpawn(
"sub",
RTI_OSAPI_THREAD_PRIORITY_NORMAL,
0x8,
0x150000,
(FUNCPTR) subscriber_main,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0);
}
#endif
| cxx |
rticonnextdds-examples | data/projects/rticonnextdds-examples/connext_dds/keyed_data/c++98/keys_publisher.cxx | /*******************************************************************************
(c) 2005-2014 Copyright, Real-Time Innovations, Inc. All rights reserved.
RTI grants Licensee a license to use, modify, compile, and create derivative
works of the Software. Licensee has the right to distribute object form only
for use with RTI products. The Software is provided "as is", with no warranty
of any type, including any warranty for fitness for any purpose. RTI is under
no obligation to maintain or support the Software. RTI shall not be liable for
any incidental or consequential damages arising out of the use or inability to
use the software.
******************************************************************************/
#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include "keys.h"
#include "keysSupport.h"
#include "ndds/ndds_cpp.h"
#include "application.h"
using namespace application;
static int shutdown_participant(
DDSDomainParticipant *participant,
const char *shutdown_message,
int status);
int run_publisher_application(unsigned int domain_id, unsigned int sample_count)
{
// Creates three instances
keys *data[3] = { NULL, NULL, NULL };
// Creates three handles for managing the registrations
DDS_InstanceHandle_t handle[3] = { DDS_HANDLE_NIL,
DDS_HANDLE_NIL,
DDS_HANDLE_NIL };
// We only will send data over the instances marked as active
bool active[3] = { true, false, false };
DDS_Duration_t send_period = { 1, 0 };
// Start communicating in a domain, usually one participant per application
DDSDomainParticipant *participant =
DDSTheParticipantFactory->create_participant(
domain_id,
DDS_PARTICIPANT_QOS_DEFAULT,
NULL /* listener */,
DDS_STATUS_MASK_NONE);
if (participant == NULL) {
return shutdown_participant(
participant,
"create_participant error",
EXIT_FAILURE);
}
// A Publisher allows an application to create one or more DataWriters
DDSPublisher *publisher = participant->create_publisher(
DDS_PUBLISHER_QOS_DEFAULT,
NULL /* listener */,
DDS_STATUS_MASK_NONE);
if (publisher == NULL) {
return shutdown_participant(
participant,
"create_publisher error",
EXIT_FAILURE);
}
// Register the datatype to use when creating the Topic
const char *type_name = keysTypeSupport::get_type_name();
DDS_ReturnCode_t retcode =
keysTypeSupport::register_type(participant, type_name);
if (retcode != DDS_RETCODE_OK) {
return shutdown_participant(
participant,
"register_type error",
EXIT_FAILURE);
}
// Create a Topic with a name and a datatype
DDSTopic *topic = participant->create_topic(
"Example keys",
type_name,
DDS_TOPIC_QOS_DEFAULT,
NULL /* listener */,
DDS_STATUS_MASK_NONE);
if (topic == NULL) {
return shutdown_participant(
participant,
"create_topic error",
EXIT_FAILURE);
}
// This DataWriter writes data on "Example keys" Topic
DDSDataWriter *untyped_writer = publisher->create_datawriter(
topic,
DDS_DATAWRITER_QOS_DEFAULT,
NULL /* listener */,
DDS_STATUS_MASK_NONE);
if (untyped_writer == NULL) {
return shutdown_participant(
participant,
"create_datawriter error",
EXIT_FAILURE);
}
/* If you want to set the writer_data_lifecycle QoS settings
* programmatically rather than using the XML, you will need to add
* the following lines to your code and comment out the create_datawriter
* call above.
*/
/*
DDS_DataWriterQos datawriter_qos;
retcode = publisher->get_default_datawriter_qos(datawriter_qos);
if (retcode != DDS_RETCODE_OK) {
std::cerr << "get_default_datawriter_qos error\n";
return EXIT_FAILURE;
}
datawriter_qos.writer_data_lifecycle.autodispose_unregistered_instances =
DDS_BOOLEAN_FALSE;
DDSDataWriter *untyped_writer = publisher->create_datawriter(
topic, datawriter_qos, NULL,
DDS_STATUS_MASK_NONE);
if (untyped_writer == NULL) {
return shutdown_participant(
participant,
"create_datawriter error",
EXIT_FAILURE);
}
*/
// Narrow casts from an untyped DataWriter to a writer of your type
keysDataWriter *typed_writer = keysDataWriter::narrow(untyped_writer);
if (typed_writer == NULL) {
return shutdown_participant(
participant,
"DataWriter narrow error",
EXIT_FAILURE);
}
// Create data samples for writing
data[0] = keysTypeSupport::create_data();
data[1] = keysTypeSupport::create_data();
data[2] = keysTypeSupport::create_data();
if (data[0] == NULL || data[1] == NULL || data[2] == NULL) {
return shutdown_participant(
participant,
"keysTypeSupport::create_data error",
EXIT_FAILURE);
}
/* RTI Connext could examine the key fields each time it needs to determine
* which data-instance is being modified.
* However, for performance and semantic reasons, it is better
* for your application to declare all the data-instances it intends to
* modify prior to actually writing any samples. This is known as
* registration.
*/
/* In order to register the instances, we must set their associated keys
* first */
data[0]->code = 0;
data[1]->code = 1;
data[2]->code = 2;
// The keys must have been set before making this call
std::cout << "Registering instance " << data[0]->code << std::endl;
handle[0] = typed_writer->register_instance(*data[0]);
// Modify the data to be sent here
data[0]->x = 1000;
data[1]->x = 2000;
data[2]->x = 3000;
// Main loop, write data
for (unsigned int samples_written = 0;
!shutdown_requested && samples_written < sample_count;
++samples_written) {
NDDSUtility::sleep(send_period);
switch (samples_written) {
case 5: { /* Start sending the second and third instances */
std::cout << "----Registering instance " << data[1]->code
<< std::endl;
std::cout << "----Registering instance " << data[2]->code
<< std::endl;
handle[1] = typed_writer->register_instance(*data[1]);
handle[2] = typed_writer->register_instance(*data[2]);
active[1] = true;
active[2] = true;
} break;
case 10: { /* Unregister the second instance */
std::cout << "----Unregistering instance " << data[1]->code
<< std::endl;
retcode = typed_writer->unregister_instance(*data[1], handle[1]);
if (retcode != DDS_RETCODE_OK) {
return shutdown_participant(
participant,
"unregister instance error",
EXIT_FAILURE);
}
active[1] = false;
} break;
case 15: { /* Dispose the third instance */
std::cout << "----Disposing instance " << data[2]->code
<< std::endl;
retcode = typed_writer->dispose(*data[2], handle[2]);
if (retcode != DDS_RETCODE_OK) {
return shutdown_participant(
participant,
"dispose instance error",
EXIT_FAILURE);
}
active[2] = false;
} break;
}
// Modify the data to be sent here
data[0]->y = samples_written;
data[1]->y = samples_written;
data[2]->y = samples_written;
for (int i = 0; i < 3; ++i) {
if (active[i]) {
std::cout << "Writing instance " << data[i]->code
<< ", x: " << data[i]->x << ", y: " << data[i]->y
<< std::endl;
retcode = typed_writer->write(*data[i], handle[i]);
if (retcode != DDS_RETCODE_OK) {
return shutdown_participant(
participant,
"write error",
EXIT_FAILURE);
}
}
}
}
// Delete data samples
for (int i = 0; i < 3; ++i) {
retcode = keysTypeSupport::delete_data(data[i]);
if (retcode != DDS_RETCODE_OK) {
std::cerr << "keysTypeSupport::delete_data error " << retcode
<< std::endl;
}
}
// Delete all entities (DataWriter, Topic, Publisher, DomainParticipant)
return shutdown_participant(participant, "Shutting down", EXIT_SUCCESS);
}
// Delete all entities
static int shutdown_participant(
DDSDomainParticipant *participant,
const char *shutdown_message,
int status)
{
DDS_ReturnCode_t retcode;
std::cout << shutdown_message << std::endl;
if (participant != NULL) {
// Cleanup everything created by this Participant
retcode = participant->delete_contained_entities();
if (retcode != DDS_RETCODE_OK) {
std::cerr << "delete_contained_entities error " << retcode
<< std::endl;
status = EXIT_FAILURE;
}
retcode = DDSTheParticipantFactory->delete_participant(participant);
if (retcode != DDS_RETCODE_OK) {
std::cerr << "delete_participant error " << retcode << std::endl;
status = EXIT_FAILURE;
}
}
return status;
}
int main(int argc, char *argv[])
{
// Parse arguments and handle control-C
ApplicationArguments arguments;
parse_arguments(arguments, argc, argv);
if (arguments.parse_result == PARSE_RETURN_EXIT) {
return EXIT_SUCCESS;
} else if (arguments.parse_result == PARSE_RETURN_FAILURE) {
return EXIT_FAILURE;
}
setup_signal_handlers();
// Sets Connext verbosity to help debugging
NDDSConfigLogger::get_instance()->set_verbosity(arguments.verbosity);
int status = run_publisher_application(
arguments.domain_id,
arguments.sample_count);
// Releases the memory used by the participant factory. Optional at
// application exit
DDS_ReturnCode_t retcode = DDSDomainParticipantFactory::finalize_instance();
if (retcode != DDS_RETCODE_OK) {
std::cerr << "finalize_instance error " << retcode << std::endl;
status = EXIT_FAILURE;
}
return status;
}
| cxx |
rticonnextdds-examples | data/projects/rticonnextdds-examples/connext_dds/keyed_data/c++98/keys_subscriber.cxx | /*******************************************************************************
(c) 2005-2014 Copyright, Real-Time Innovations, Inc. All rights reserved.
RTI grants Licensee a license to use, modify, compile, and create derivative
works of the Software. Licensee has the right to distribute object form only
for use with RTI products. The Software is provided "as is", with no warranty
of any type, including any warranty for fitness for any purpose. RTI is under
no obligation to maintain or support the Software. RTI shall not be liable for
any incidental or consequential damages arising out of the use or inability to
use the software.
******************************************************************************/
#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include "keys.h"
#include "keysSupport.h"
#include "ndds/ndds_cpp.h"
#include "application.h"
using namespace application;
static int shutdown_participant(
DDSDomainParticipant *participant,
const char *shutdown_message,
int status);
unsigned int process_data(keysDataReader *typed_reader)
{
keysSeq data_seq;
DDS_SampleInfoSeq info_seq;
unsigned int samples_read = 0;
DDS_ReturnCode_t retcode;
typed_reader->take(
data_seq,
info_seq,
DDS_LENGTH_UNLIMITED,
DDS_ANY_SAMPLE_STATE,
DDS_ANY_VIEW_STATE,
DDS_ANY_INSTANCE_STATE);
for (int i = 0; i < data_seq.length(); ++i) {
/* Start changes for Keyed_Data */
/* We first check if the sample includes valid data */
if (info_seq[i].valid_data) {
if (info_seq[i].view_state == DDS_NEW_VIEW_STATE) {
std::cout << "Found new instance; code = " << data_seq[i].code
<< std::endl;
}
std::cout << "Instance " << data_seq[i].code
<< ": x: " << data_seq[i].x << ", y: " << data_seq[i].y
<< std::endl;
samples_read++;
} else {
/* Since there is not valid data, it may include metadata */
keys dummy;
retcode = typed_reader->get_key_value(
dummy,
info_seq[i].instance_handle);
if (retcode != DDS_RETCODE_OK) {
std::cout << "get_key_value error " << retcode << std::endl;
continue;
}
/* Here we print a message if the instance state is ALIVE_NO_WRITERS
* or ALIVE_DISPOSED */
if (info_seq[i].instance_state
== DDS_NOT_ALIVE_NO_WRITERS_INSTANCE_STATE) {
std::cout << "Instance " << dummy.code << " has no writers\n";
} else if (
info_seq[i].instance_state
== DDS_NOT_ALIVE_DISPOSED_INSTANCE_STATE) {
std::cout << "Instance " << dummy.code << " disposed\n";
}
}
/* End changes for Keyed_Data */
}
// Data loaned from Connext for performance. Return loan when done.
retcode = typed_reader->return_loan(data_seq, info_seq);
if (retcode != DDS_RETCODE_OK) {
std::cerr << "return loan error " << retcode << std::endl;
}
return samples_read;
}
int run_subscriber_application(
unsigned int domain_id,
unsigned int sample_count)
{
DDS_Duration_t wait_timeout = { 1, 0 };
// Start communicating in a domain, usually one participant per application
DDSDomainParticipant *participant =
DDSTheParticipantFactory->create_participant(
domain_id,
DDS_PARTICIPANT_QOS_DEFAULT,
NULL /* listener */,
DDS_STATUS_MASK_NONE);
if (participant == NULL) {
return shutdown_participant(
participant,
"create_participant error",
EXIT_FAILURE);
}
// A Subscriber allows an application to create one or more DataReaders
DDSSubscriber *subscriber = participant->create_subscriber(
DDS_SUBSCRIBER_QOS_DEFAULT,
NULL /* listener */,
DDS_STATUS_MASK_NONE);
if (subscriber == NULL) {
return shutdown_participant(
participant,
"create_subscriber error",
EXIT_FAILURE);
}
// Register the datatype to use when creating the Topic
const char *type_name = keysTypeSupport::get_type_name();
DDS_ReturnCode_t retcode =
keysTypeSupport::register_type(participant, type_name);
if (retcode != DDS_RETCODE_OK) {
return shutdown_participant(
participant,
"register_type error",
EXIT_FAILURE);
}
// Create a Topic with a name and a datatype
DDSTopic *topic = participant->create_topic(
"Example keys",
type_name,
DDS_TOPIC_QOS_DEFAULT,
NULL /* listener */,
DDS_STATUS_MASK_NONE);
if (topic == NULL) {
return shutdown_participant(
participant,
"create_topic error",
EXIT_FAILURE);
}
// This DataReader reads data on "Example keys" Topic
DDSDataReader *untyped_reader = subscriber->create_datareader(
topic,
DDS_DATAREADER_QOS_DEFAULT,
NULL,
DDS_STATUS_MASK_ALL);
if (untyped_reader == NULL) {
return shutdown_participant(
participant,
"create_datareader error",
EXIT_FAILURE);
}
// Narrow casts from a untyped DataReader to a reader of your type
keysDataReader *typed_reader = keysDataReader::narrow(untyped_reader);
if (typed_reader == NULL) {
return shutdown_participant(
participant,
"DataReader narrow error",
EXIT_FAILURE);
}
// Create ReadCondition that triggers when unread data in reader's queue
DDSReadCondition *read_condition = typed_reader->create_readcondition(
DDS_NOT_READ_SAMPLE_STATE,
DDS_ANY_VIEW_STATE,
DDS_ANY_INSTANCE_STATE);
if (read_condition == NULL) {
return shutdown_participant(
participant,
"create_readcondition error",
EXIT_FAILURE);
}
// WaitSet will be woken when the attached condition is triggered
DDSWaitSet waitset;
retcode = waitset.attach_condition(read_condition);
if (retcode != DDS_RETCODE_OK) {
return shutdown_participant(
participant,
"attach_condition error",
EXIT_FAILURE);
}
// Main loop. Wait for data to arrive, and process when it arrives
unsigned int samples_read = 0;
while (!shutdown_requested && samples_read < sample_count) {
DDSConditionSeq active_conditions_seq;
// Wait for data
retcode = waitset.wait(active_conditions_seq, wait_timeout);
if (retcode == DDS_RETCODE_OK) {
// If the read condition is triggered, process data
samples_read += process_data(typed_reader);
}
}
// Cleanup
return shutdown_participant(participant, "Shutting down", 0);
}
// Delete all entities
static int shutdown_participant(
DDSDomainParticipant *participant,
const char *shutdown_message,
int status)
{
DDS_ReturnCode_t retcode;
std::cout << shutdown_message << std::endl;
if (participant != NULL) {
// Cleanup everything created by this Participant
retcode = participant->delete_contained_entities();
if (retcode != DDS_RETCODE_OK) {
std::cerr << "delete_contained_entities error" << retcode
<< std::endl;
status = EXIT_FAILURE;
}
retcode = DDSTheParticipantFactory->delete_participant(participant);
if (retcode != DDS_RETCODE_OK) {
std::cerr << "delete_participant error" << retcode << std::endl;
status = EXIT_FAILURE;
}
}
return status;
}
int main(int argc, char *argv[])
{
// Parse arguments and handle control-C
ApplicationArguments arguments;
parse_arguments(arguments, argc, argv);
if (arguments.parse_result == PARSE_RETURN_EXIT) {
return EXIT_SUCCESS;
} else if (arguments.parse_result == PARSE_RETURN_FAILURE) {
return EXIT_FAILURE;
}
setup_signal_handlers();
// Sets Connext verbosity to help debugging
NDDSConfigLogger::get_instance()->set_verbosity(arguments.verbosity);
int status = run_subscriber_application(
arguments.domain_id,
arguments.sample_count);
// Releases the memory used by the participant factory. Optional at
// application exit
DDS_ReturnCode_t retcode = DDSDomainParticipantFactory::finalize_instance();
if (retcode != DDS_RETCODE_OK) {
std::cerr << "finalize_instance error" << retcode << std::endl;
status = EXIT_FAILURE;
}
return status;
}
| cxx |
rticonnextdds-examples | data/projects/rticonnextdds-examples/connext_dds/keyed_data/c++98/application.h | /*
* (c) Copyright, Real-Time Innovations, 2020. All rights reserved.
* RTI grants Licensee a license to use, modify, compile, and create derivative
* works of the software solely for use with RTI Connext DDS. Licensee may
* redistribute copies of the software provided that all such copies are subject
* to this license. The software is provided "as is", with no warranty of any
* type, including any warranty for fitness for any purpose. RTI is under no
* obligation to maintain or support the software. RTI shall not be liable for
* any incidental or consequential damages arising out of the use or inability
* to use the software.
*/
#ifndef APPLICATION_H
#define APPLICATION_H
#include <iostream>
#include <csignal>
#include <climits>
namespace application {
// Catch control-C and tell application to shut down
bool shutdown_requested = false;
inline void stop_handler(int)
{
shutdown_requested = true;
std::cout << "preparing to shut down..." << std::endl;
}
inline void setup_signal_handlers()
{
signal(SIGINT, stop_handler);
signal(SIGTERM, stop_handler);
}
enum ParseReturn { PARSE_RETURN_OK, PARSE_RETURN_FAILURE, PARSE_RETURN_EXIT };
struct ApplicationArguments {
ParseReturn parse_result;
unsigned int domain_id;
unsigned int sample_count;
NDDS_Config_LogVerbosity verbosity;
};
inline void set_verbosity(ApplicationArguments &arguments, int verbosity)
{
switch (verbosity) {
case 0:
arguments.verbosity = NDDS_CONFIG_LOG_VERBOSITY_SILENT;
break;
case 1:
arguments.verbosity = NDDS_CONFIG_LOG_VERBOSITY_ERROR;
break;
case 2:
arguments.verbosity = NDDS_CONFIG_LOG_VERBOSITY_WARNING;
break;
case 3:
arguments.verbosity = NDDS_CONFIG_LOG_VERBOSITY_STATUS_ALL;
break;
default:
arguments.verbosity = NDDS_CONFIG_LOG_VERBOSITY_ERROR;
break;
}
}
// Parses application arguments for example. Returns whether to exit.
inline void parse_arguments(
ApplicationArguments &arguments,
int argc,
char *argv[])
{
int arg_processing = 1;
bool show_usage = false;
arguments.domain_id = 0;
arguments.sample_count = INT_MAX;
arguments.verbosity = NDDS_CONFIG_LOG_VERBOSITY_ERROR;
arguments.parse_result = PARSE_RETURN_OK;
while (arg_processing < argc) {
if ((argc > arg_processing + 1)
&& (strcmp(argv[arg_processing], "-d") == 0
|| strcmp(argv[arg_processing], "--domain") == 0)) {
arguments.domain_id = atoi(argv[arg_processing + 1]);
arg_processing += 2;
} else if (
(argc > arg_processing + 1)
&& (strcmp(argv[arg_processing], "-s") == 0
|| strcmp(argv[arg_processing], "--sample-count") == 0)) {
arguments.sample_count = atoi(argv[arg_processing + 1]);
arg_processing += 2;
} else if (
(argc > arg_processing + 1)
&& (strcmp(argv[arg_processing], "-v") == 0
|| strcmp(argv[arg_processing], "--verbosity") == 0)) {
set_verbosity(arguments, atoi(argv[arg_processing + 1]));
arg_processing += 2;
} else if (
strcmp(argv[arg_processing], "-h") == 0
|| strcmp(argv[arg_processing], "--help") == 0) {
std::cout << "Example application." << std::endl;
show_usage = true;
arguments.parse_result = PARSE_RETURN_EXIT;
break;
} else {
std::cout << "Bad parameter." << std::endl;
show_usage = true;
arguments.parse_result = PARSE_RETURN_FAILURE;
break;
}
}
if (show_usage) {
std::cout << "Usage:\n"
" -d, --domain <int> Domain ID this "
"application will\n"
" subscribe in. \n"
" Default: 0\n"
" -s, --sample_count <int> Number of samples to "
"receive before\n"
" cleanly shutting down. \n"
" Default: infinite\n"
" -v, --verbosity <int> How much debugging output "
"to show.\n"
" Range: 0-3 \n"
" Default: 1"
<< std::endl;
}
}
} // namespace application
#endif // APPLICATION_H
| h |
rticonnextdds-examples | data/projects/rticonnextdds-examples/connext_dds/keyed_data/c/keys_publisher.c | /*******************************************************************************
(c) 2005-2014 Copyright, Real-Time Innovations, Inc. All rights reserved.
RTI grants Licensee a license to use, modify, compile, and create derivative
works of the Software. Licensee has the right to distribute object form only
for use with RTI products. The Software is provided "as is", with no warranty
of any type, including any warranty for fitness for any purpose. RTI is under
no obligation to maintain or support the Software. RTI shall not be liable for
any incidental or consequential damages arising out of the use or inability to
use the software.
******************************************************************************/
/* keys_publisher.c
A publication of data of type keys
This file is derived from code automatically generated by the rtiddsgen
command:
rtiddsgen -language C -example <arch> keys.idl
Example publication of type keys automatically generated by
'rtiddsgen'. To test them follow these steps:
(1) Compile this file and the example subscription.
(2) Start the subscription with the command
objs/<arch>/keys_subscriber <domain_id> <sample_count>
(3) Start the publication with the command
objs/<arch>/keys_publisher <domain_id> <sample_count>
(4) [Optional] Specify the list of discovery initial peers and
multicast receive addresses via an environment variable or a file
(in the current working directory) called NDDS_DISCOVERY_PEERS.
You can run any number of publishers and subscribers programs, and can
add and remove them dynamically from the domain.
Example:
To run the example application on domain <domain_id>:
On Unix:
objs/<arch>/keys_publisher <domain_id>
objs/<arch>/keys_subscriber <domain_id>
On Windows:
objs\<arch>\keys_publisher <domain_id>
objs\<arch>\keys_subscriber <domain_id>
modification history
------------ -------
*/
#include "keys.h"
#include "keysSupport.h"
#include "ndds/ndds_c.h"
#include <stdio.h>
#include <stdlib.h>
/* Delete all entities */
static int publisher_shutdown(DDS_DomainParticipant *participant)
{
DDS_ReturnCode_t retcode;
int status = 0;
if (participant != NULL) {
retcode = DDS_DomainParticipant_delete_contained_entities(participant);
if (retcode != DDS_RETCODE_OK) {
printf("delete_contained_entities error %d\n", retcode);
status = -1;
}
retcode = DDS_DomainParticipantFactory_delete_participant(
DDS_TheParticipantFactory,
participant);
if (retcode != DDS_RETCODE_OK) {
printf("delete_participant error %d\n", retcode);
status = -1;
}
}
/* RTI Connext provides finalize_instance() method on
domain participant factory for people who want to release memory used
by the participant factory. Uncomment the following block of code for
clean destruction of the singleton. */
/*
retcode = DDS_DomainParticipantFactory_finalize_instance();
if (retcode != DDS_RETCODE_OK) {
printf("finalize_instance error %d\n", retcode);
status = -1;
}
*/
return status;
}
static int publisher_main(int domainId, int sample_count)
{
DDS_DomainParticipant *participant = NULL;
DDS_Publisher *publisher = NULL;
DDS_Topic *topic = NULL;
DDS_DataWriter *writer = NULL;
keysDataWriter *keys_writer = NULL;
/* Creates three instances */
keys *instance[3] = { NULL, NULL, NULL };
/* Creates three handles for managing the registrations */
DDS_InstanceHandle_t handle[3];
/* We only will send data over the instances marked as active */
int active[3] = { 1, 0, 0 };
DDS_ReturnCode_t retcode;
const char *type_name = NULL;
int count = 0;
struct DDS_Duration_t send_period = { 1, 0 };
int i = 0;
/* If you want to set the writer_data_lifecycle QoS settings
* programmatically rather than using the XML, you will need to add
* the following line to your code
*/
/* struct DDS_DataWriterQos datawriter_qos = DDS_DataWriterQos_INITIALIZER;
*/
/* To customize participant QoS, use
the configuration file USER_QOS_PROFILES.xml */
participant = DDS_DomainParticipantFactory_create_participant(
DDS_TheParticipantFactory,
domainId,
&DDS_PARTICIPANT_QOS_DEFAULT,
NULL /* listener */,
DDS_STATUS_MASK_NONE);
if (participant == NULL) {
printf("create_participant error\n");
publisher_shutdown(participant);
return -1;
}
/* To customize publisher QoS, use
the configuration file USER_QOS_PROFILES.xml */
publisher = DDS_DomainParticipant_create_publisher(
participant,
&DDS_PUBLISHER_QOS_DEFAULT,
NULL /* listener */,
DDS_STATUS_MASK_NONE);
if (publisher == NULL) {
printf("create_publisher error\n");
publisher_shutdown(participant);
return -1;
}
/* Register type before creating topic */
type_name = keysTypeSupport_get_type_name();
retcode = keysTypeSupport_register_type(participant, type_name);
if (retcode != DDS_RETCODE_OK) {
printf("register_type error %d\n", retcode);
publisher_shutdown(participant);
return -1;
}
/* To customize topic QoS, use
the configuration file USER_QOS_PROFILES.xml */
topic = DDS_DomainParticipant_create_topic(
participant,
"Example keys",
type_name,
&DDS_TOPIC_QOS_DEFAULT,
NULL /* listener */,
DDS_STATUS_MASK_NONE);
if (topic == NULL) {
printf("create_topic error\n");
publisher_shutdown(participant);
return -1;
}
/* To customize data writer QoS, use
the configuration file USER_QOS_PROFILES.xml */
writer = DDS_Publisher_create_datawriter(
publisher,
topic,
&DDS_DATAWRITER_QOS_DEFAULT,
NULL /* listener */,
DDS_STATUS_MASK_NONE);
if (writer == NULL) {
printf("create_datawriter error\n");
publisher_shutdown(participant);
return -1;
}
/* If you want to set the writer_data_lifecycle QoS settings
* programmatically rather than using the XML, you will need to add
* the following lines to your code and comment out the create_datawriter
* call above.
*/
/*
retcode = DDS_Publisher_get_default_datawriter_qos(publisher,
&datawriter_qos); if (retcode != DDS_RETCODE_OK) {
printf("get_default_datawriter_qos error\n");
return -1;
}
datawriter_qos.writer_data_lifecycle.autodispose_unregistered_instances =
DDS_BOOLEAN_FALSE;
writer = DDS_Publisher_create_datawriter(
publisher, topic,
&datawriter_qos, NULL, DDS_STATUS_MASK_NONE);
if (writer == NULL) {
printf("create_datawriter error\n");
publisher_shutdown(participant);
return -1;
}
*/
keys_writer = keysDataWriter_narrow(writer);
if (keys_writer == NULL) {
printf("DataWriter narrow error\n");
publisher_shutdown(participant);
return -1;
}
/* Create data samples for writing */
instance[0] = keysTypeSupport_create_data_ex(DDS_BOOLEAN_TRUE);
instance[1] = keysTypeSupport_create_data_ex(DDS_BOOLEAN_TRUE);
instance[2] = keysTypeSupport_create_data_ex(DDS_BOOLEAN_TRUE);
if (instance[0] == NULL || instance[1] == NULL || instance[2] == NULL) {
printf("keysTypeSupport::create_data error\n");
publisher_shutdown(participant);
return -1;
}
/* RTI Connext could examine the key fields each time it needs to determine
* which data-instance is being modified.
* However, for performance and semantic reasons, it is better
* for your application to declare all the data-instances it intends to
* modify prior to actually writing any samples. This is known as
* registration.
*/
/* In order to register the instances, we must set their associated keys
* first */
instance[0]->code = 0;
instance[1]->code = 1;
instance[2]->code = 2;
/* The keys must have been set before making this call */
printf("Registering instance %d\n", instance[0]->code);
handle[0] = keysDataWriter_register_instance(keys_writer, instance[0]);
/* Modify the data to be sent here */
instance[0]->x = 1000;
instance[1]->x = 2000;
instance[2]->x = 3000;
/* Main loop */
for (count = 0; (sample_count == 0) || (count < sample_count); ++count) {
NDDS_Utility_sleep(&send_period);
switch (count) {
case 5: { /* Start sending new instances */
printf("----Registering instance %d\n", instance[1]->code);
printf("----Registering instance %d\n", instance[2]->code);
handle[1] =
keysDataWriter_register_instance(keys_writer, instance[1]);
handle[2] =
keysDataWriter_register_instance(keys_writer, instance[2]);
active[1] = 1;
active[2] = 1;
} break;
case 10: { /* Unregister instance */
printf("----Unregistering instance %d\n", instance[1]->code);
retcode = keysDataWriter_unregister_instance(
keys_writer,
instance[1],
&handle[1]);
if (retcode != DDS_RETCODE_OK) {
printf("unregister instance error %d\n", retcode);
return -1;
}
active[1] = 0;
} break;
case 15: { /* Dispose of instance */
printf("----Disposing instance %d\n", instance[2]->code);
retcode = keysDataWriter_dispose(
keys_writer,
instance[2],
&handle[2]);
if (retcode != DDS_RETCODE_OK) {
printf("dispose instance error %d\n", retcode);
return -1;
}
active[2] = 0;
} break;
}
/* Modify the data to be sent here */
instance[0]->y = count;
instance[1]->y = count;
instance[2]->y = count;
for (i = 0; i < 3; ++i) {
if (active[i]) {
printf("Writing instance %d, x: %d, y: %d\n",
instance[i]->code,
instance[i]->x,
instance[i]->y);
retcode = keysDataWriter_write(
keys_writer,
instance[i],
&handle[i]);
if (retcode != DDS_RETCODE_OK) {
printf("write error %d\n", retcode);
return -1;
}
}
}
}
/* Delete data samples */
for (i = 0; i < 3; ++i) {
retcode = keysTypeSupport_delete_data(instance[i]);
if (retcode != DDS_RETCODE_OK) {
printf("keysTypeSupport::delete_data error %d\n", retcode);
}
}
/* Cleanup and delete delete all entities */
return publisher_shutdown(participant);
}
#if defined(RTI_WINCE)
int wmain(int argc, wchar_t **argv)
{
int domainId = 0;
int sample_count = 0; /* infinite loop */
if (argc >= 2) {
domainId = _wtoi(argv[1]);
}
if (argc >= 3) {
sample_count = _wtoi(argv[2]);
}
/* Uncomment this to turn on additional logging
NDDS_Config_Logger_set_verbosity_by_category(
NDDS_Config_Logger_get_instance(),
NDDS_CONFIG_LOG_CATEGORY_API,
NDDS_CONFIG_LOG_VERBOSITY_STATUS_ALL);
*/
return publisher_main(domainId, sample_count);
}
#elif !(defined(RTI_VXWORKS) && !defined(__RTP__)) && !defined(RTI_PSOS)
int main(int argc, char *argv[])
{
int domainId = 0;
int sample_count = 0; /* infinite loop */
if (argc >= 2) {
domainId = atoi(argv[1]);
}
if (argc >= 3) {
sample_count = atoi(argv[2]);
}
/* Uncomment this to turn on additional logging
NDDS_Config_Logger_set_verbosity_by_category(
NDDS_Config_Logger_get_instance(),
NDDS_CONFIG_LOG_CATEGORY_API,
NDDS_CONFIG_LOG_VERBOSITY_STATUS_ALL);
*/
return publisher_main(domainId, sample_count);
}
#endif
#ifdef RTI_VX653
const unsigned char *__ctype = NULL;
void usrAppInit()
{
#ifdef USER_APPL_INIT
USER_APPL_INIT; /* for backwards compatibility */
#endif
/* add application specific code here */
taskSpawn(
"pub",
RTI_OSAPI_THREAD_PRIORITY_NORMAL,
0x8,
0x150000,
(FUNCPTR) publisher_main,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0);
}
#endif
| c |
rticonnextdds-examples | data/projects/rticonnextdds-examples/connext_dds/keyed_data/c/keys_subscriber.c | /*******************************************************************************
(c) 2005-2014 Copyright, Real-Time Innovations, Inc. All rights reserved.
RTI grants Licensee a license to use, modify, compile, and create derivative
works of the Software. Licensee has the right to distribute object form only
for use with RTI products. The Software is provided "as is", with no warranty
of any type, including any warranty for fitness for any purpose. RTI is under
no obligation to maintain or support the Software. RTI shall not be liable for
any incidental or consequential damages arising out of the use or inability to
use the software.
******************************************************************************/
/* keys_subscriber.c
A subscription example
This file is derived from code automatically generated by the rtiddsgen
command:
rtiddsgen -language C -example <arch> keys.idl
Example subscription of type keys automatically generated by
'rtiddsgen'. To test them, follow these steps:
(1) Compile this file and the example publication.
(2) Start the subscription with the command
objs/<arch>/keys_subscriber <domain_id> <sample_count>
(3) Start the publication with the command
objs/<arch>/keys_publisher <domain_id> <sample_count>
(4) [Optional] Specify the list of discovery initial peers and
multicast receive addresses via an environment variable or a file
(in the current working directory) called NDDS_DISCOVERY_PEERS.
You can run any number of publishers and subscribers programs, and can
add and remove them dynamically from the domain.
Example:
To run the example application on domain <domain_id>:
On UNIX systems:
objs/<arch>/keys_publisher <domain_id>
objs/<arch>/keys_subscriber <domain_id>
On Windows systems:
objs\<arch>\keys_publisher <domain_id>
objs\<arch>\keys_subscriber <domain_id>
modification history
------------ -------
*/
#include "keys.h"
#include "keysSupport.h"
#include "ndds/ndds_c.h"
#include <stdio.h>
#include <stdlib.h>
void keysListener_on_requested_deadline_missed(
void *listener_data,
DDS_DataReader *reader,
const struct DDS_RequestedDeadlineMissedStatus *status)
{
}
void keysListener_on_requested_incompatible_qos(
void *listener_data,
DDS_DataReader *reader,
const struct DDS_RequestedIncompatibleQosStatus *status)
{
}
void keysListener_on_sample_rejected(
void *listener_data,
DDS_DataReader *reader,
const struct DDS_SampleRejectedStatus *status)
{
}
void keysListener_on_liveliness_changed(
void *listener_data,
DDS_DataReader *reader,
const struct DDS_LivelinessChangedStatus *status)
{
}
void keysListener_on_sample_lost(
void *listener_data,
DDS_DataReader *reader,
const struct DDS_SampleLostStatus *status)
{
}
void keysListener_on_subscription_matched(
void *listener_data,
DDS_DataReader *reader,
const struct DDS_SubscriptionMatchedStatus *status)
{
}
void keysListener_on_data_available(void *listener_data, DDS_DataReader *reader)
{
keysDataReader *keys_reader = NULL;
struct keysSeq data_seq = DDS_SEQUENCE_INITIALIZER;
struct DDS_SampleInfoSeq info_seq = DDS_SEQUENCE_INITIALIZER;
DDS_ReturnCode_t retcode;
int i;
keys_reader = keysDataReader_narrow(reader);
if (keys_reader == NULL) {
printf("DataReader narrow error\n");
return;
}
retcode = keysDataReader_take(
keys_reader,
&data_seq,
&info_seq,
DDS_LENGTH_UNLIMITED,
DDS_ANY_SAMPLE_STATE,
DDS_ANY_VIEW_STATE,
DDS_ANY_INSTANCE_STATE);
if (retcode == DDS_RETCODE_NO_DATA) {
return;
} else if (retcode != DDS_RETCODE_OK) {
printf("take error %d\n", retcode);
return;
}
for (i = 0; i < keysSeq_get_length(&data_seq); ++i) {
/* Start changes for Keyed_Data */
struct DDS_SampleInfo *info = NULL;
keys *data = NULL;
info = DDS_SampleInfoSeq_get_reference(&info_seq, i);
data = keysSeq_get_reference(&data_seq, i);
/* We first check if the sample includes valid data */
if (info->valid_data) {
if (info->view_state == DDS_NEW_VIEW_STATE) {
printf("Found new instance; code = %d\n", data->code);
}
printf("Instance %d: x: %d, y: %d\n", data->code, data->x, data->y);
} else {
/* Since there is not valid data, it may include metadata */
keys dummy;
retcode = keysDataReader_get_key_value(
keys_reader,
&dummy,
&info->instance_handle);
if (retcode != DDS_RETCODE_OK) {
printf("get_key_value error %d\n", retcode);
continue;
}
/* Here we print a message if the instance state is ALIVE_NO_WRITERS
* or ALIVE_DISPOSED */
if (info->instance_state
== DDS_NOT_ALIVE_NO_WRITERS_INSTANCE_STATE) {
printf("Instance %d has no writers\n", dummy.code);
} else if (
info->instance_state
== DDS_NOT_ALIVE_DISPOSED_INSTANCE_STATE) {
printf("Instance %d disposed\n", dummy.code);
}
}
/* End changes for Keyed_Data */
}
retcode = keysDataReader_return_loan(keys_reader, &data_seq, &info_seq);
if (retcode != DDS_RETCODE_OK) {
printf("return loan error %d\n", retcode);
}
}
/* Delete all entities */
static int subscriber_shutdown(DDS_DomainParticipant *participant)
{
DDS_ReturnCode_t retcode;
int status = 0;
if (participant != NULL) {
retcode = DDS_DomainParticipant_delete_contained_entities(participant);
if (retcode != DDS_RETCODE_OK) {
printf("delete_contained_entities error %d\n", retcode);
status = -1;
}
retcode = DDS_DomainParticipantFactory_delete_participant(
DDS_TheParticipantFactory,
participant);
if (retcode != DDS_RETCODE_OK) {
printf("delete_participant error %d\n", retcode);
status = -1;
}
}
/* RTI Connext provides the finalize_instance() method on
domain participant factory for users who want to release memory used
by the participant factory. Uncomment the following block of code for
clean destruction of the singleton. */
/*
retcode = DDS_DomainParticipantFactory_finalize_instance();
if (retcode != DDS_RETCODE_OK) {
printf("finalize_instance error %d\n", retcode);
status = -1;
}
*/
return status;
}
static int subscriber_main(int domainId, int sample_count)
{
DDS_DomainParticipant *participant = NULL;
DDS_Subscriber *subscriber = NULL;
DDS_Topic *topic = NULL;
struct DDS_DataReaderListener reader_listener =
DDS_DataReaderListener_INITIALIZER;
DDS_DataReader *reader = NULL;
DDS_ReturnCode_t retcode;
const char *type_name = NULL;
int count = 0;
struct DDS_Duration_t poll_period = { 1, 0 };
/* To customize participant QoS, use
the configuration file USER_QOS_PROFILES.xml */
participant = DDS_DomainParticipantFactory_create_participant(
DDS_TheParticipantFactory,
domainId,
&DDS_PARTICIPANT_QOS_DEFAULT,
NULL /* listener */,
DDS_STATUS_MASK_NONE);
if (participant == NULL) {
printf("create_participant error\n");
subscriber_shutdown(participant);
return -1;
}
/* To customize subscriber QoS, use
the configuration file USER_QOS_PROFILES.xml */
subscriber = DDS_DomainParticipant_create_subscriber(
participant,
&DDS_SUBSCRIBER_QOS_DEFAULT,
NULL /* listener */,
DDS_STATUS_MASK_NONE);
if (subscriber == NULL) {
printf("create_subscriber error\n");
subscriber_shutdown(participant);
return -1;
}
/* Register the type before creating the topic */
type_name = keysTypeSupport_get_type_name();
retcode = keysTypeSupport_register_type(participant, type_name);
if (retcode != DDS_RETCODE_OK) {
printf("register_type error %d\n", retcode);
subscriber_shutdown(participant);
return -1;
}
/* To customize topic QoS, use
the configuration file USER_QOS_PROFILES.xml */
topic = DDS_DomainParticipant_create_topic(
participant,
"Example keys",
type_name,
&DDS_TOPIC_QOS_DEFAULT,
NULL /* listener */,
DDS_STATUS_MASK_NONE);
if (topic == NULL) {
printf("create_topic error\n");
subscriber_shutdown(participant);
return -1;
}
/* Set up a data reader listener */
reader_listener.on_requested_deadline_missed =
keysListener_on_requested_deadline_missed;
reader_listener.on_requested_incompatible_qos =
keysListener_on_requested_incompatible_qos;
reader_listener.on_sample_rejected = keysListener_on_sample_rejected;
reader_listener.on_liveliness_changed = keysListener_on_liveliness_changed;
reader_listener.on_sample_lost = keysListener_on_sample_lost;
reader_listener.on_subscription_matched =
keysListener_on_subscription_matched;
reader_listener.on_data_available = keysListener_on_data_available;
/* To customize data reader QoS, use
the configuration file USER_QOS_PROFILES.xml */
reader = DDS_Subscriber_create_datareader(
subscriber,
DDS_Topic_as_topicdescription(topic),
&DDS_DATAREADER_QOS_DEFAULT,
&reader_listener,
DDS_STATUS_MASK_ALL);
if (reader == NULL) {
printf("create_datareader error\n");
subscriber_shutdown(participant);
return -1;
}
/* Main loop */
for (count = 0; (sample_count == 0) || (count < sample_count); ++count) {
// printf("keys subscriber sleeping for %d sec...\n",poll_period.sec);
NDDS_Utility_sleep(&poll_period);
}
/* Cleanup and delete all entities */
return subscriber_shutdown(participant);
}
#if defined(RTI_WINCE)
int wmain(int argc, wchar_t **argv)
{
int domainId = 0;
int sample_count = 0; /* infinite loop */
if (argc >= 2) {
domainId = _wtoi(argv[1]);
}
if (argc >= 3) {
sample_count = _wtoi(argv[2]);
}
/* Uncomment this to turn on additional logging
NDDS_Config_Logger_set_verbosity_by_category(
NDDS_Config_Logger_get_instance(),
NDDS_CONFIG_LOG_CATEGORY_API,
NDDS_CONFIG_LOG_VERBOSITY_STATUS_ALL);
*/
return subscriber_main(domainId, sample_count);
}
#elif !(defined(RTI_VXWORKS) && !defined(__RTP__)) && !defined(RTI_PSOS)
int main(int argc, char *argv[])
{
int domainId = 0;
int sample_count = 0; /* infinite loop */
if (argc >= 2) {
domainId = atoi(argv[1]);
}
if (argc >= 3) {
sample_count = atoi(argv[2]);
}
/* Uncomment this to turn on additional logging
NDDS_Config_Logger_set_verbosity_by_category(
NDDS_Config_Logger_get_instance(),
NDDS_CONFIG_LOG_CATEGORY_API,
NDDS_CONFIG_LOG_VERBOSITY_STATUS_ALL);
*/
return subscriber_main(domainId, sample_count);
}
#endif
#ifdef RTI_VX653
const unsigned char *__ctype = NULL;
void usrAppInit()
{
#ifdef USER_APPL_INIT
USER_APPL_INIT; /* for backwards compatibility */
#endif
/* add application specific code here */
taskSpawn(
"sub",
RTI_OSAPI_THREAD_PRIORITY_NORMAL,
0x8,
0x150000,
(FUNCPTR) subscriber_main,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0);
}
#endif
| c |
rticonnextdds-examples | data/projects/rticonnextdds-examples/connext_dds/keyed_data/c++03/keys_publisher.cxx | /*******************************************************************************
(c) 2005-2015 Copyright, Real-Time Innovations, Inc. All rights reserved.
RTI grants Licensee a license to use, modify, compile, and create derivative
works of the Software. Licensee has the right to distribute object form only
for use with RTI products. The Software is provided "as is", with no warranty
of any type, including any warranty for fitness for any purpose. RTI is under
no obligation to maintain or support the Software. RTI shall not be liable for
any incidental or consequential damages arising out of the use or inability to
use the software.
******************************************************************************/
#include <cstdlib>
#include <iostream>
#include "keys.hpp"
#include <dds/dds.hpp>
using namespace dds::core;
using namespace dds::core::policy;
using namespace dds::domain;
using namespace dds::topic;
using namespace dds::pub;
using namespace dds::pub::qos;
void publisher_main(int domain_id, int sample_count)
{
// Create a DomainParticipant with default Qos.
DomainParticipant participant(domain_id);
// Create a Topic -- and automatically register the type.
Topic<keys> topic(participant, "Example keys");
// Retrieve the DataWriter QoS, from USER_QOS_PROFILES.xml
DataWriterQos writer_qos = QosProvider::Default().datawriter_qos();
// If you want to change the DataWriter's QoS programmatically rather
// than using the XML file, you will need to comment out the previous
// writer_qos assignment and uncomment this line.
// writer_qos <<
// WriterDataLifecycle::ManuallyDisposeUnregisteredInstances();
// Create a DataWriter with default Qos (Publisher created in-line).
DataWriter<keys> writer(Publisher(participant), topic, writer_qos);
std::vector<keys> samples;
std::vector<InstanceHandle> instance_handles;
// RTI Connext could examine the key fields each time it needs to determine
// which data-instance is being modified. However, for performance and
// semantic reasons, it is better for your application to declare all the
// data-instances it intends to modify prior to actually writing any
// samples. This is known as registration.
int num_samples = 3;
for (int i = 0; i < num_samples; i++) {
// In order to register the instances, we must set their associated
// keys first.
keys k;
k.code(i);
// Initially, we register only the first sample.
if (i == 0) {
// The keys must have been set before making this call.
std::cout << "Registering instance " << k.code() << std::endl;
instance_handles.push_back(writer.register_instance(k));
} else {
instance_handles.push_back(InstanceHandle::nil());
}
// Finally, we modify the data to be sent.
k.x((i + 1) * 1000);
samples.push_back(k);
}
// Main loop
for (int count = 0; count < sample_count || sample_count == 0; count++) {
rti::util::sleep(Duration(1));
if (count == 5) {
// Start sending the second and third instances.
std::cout << "----Registering instance " << samples[1].code()
<< std::endl;
instance_handles[1] = writer.register_instance(samples[1]);
std::cout << "----Registering instance " << samples[2].code()
<< std::endl;
instance_handles[2] = writer.register_instance(samples[2]);
} else if (count == 10) {
// Unregister the second instance.
std::cout << "----Unregistering instance " << samples[1].code()
<< std::endl;
writer.unregister_instance(instance_handles[1]);
instance_handles[1] = InstanceHandle::nil();
} else if (count == 15) {
// Dispose the third instance.
std::cout << "----Disposing instance " << samples[2].code()
<< std::endl;
writer.dispose_instance(instance_handles[2]);
instance_handles[2] = InstanceHandle::nil();
}
// Update sample data field and send if handle is not nil.
for (int i = 0; i < num_samples; i++) {
if (!instance_handles[i].is_nil()) {
samples[i].y(count);
std::cout << "Writing instance " << samples[i].code()
<< ", x: " << samples[i].x()
<< ", y: " << samples[i].y() << std::endl;
writer.write(samples[i], instance_handles[i]);
}
}
}
}
int main(int argc, char *argv[])
{
int domain_id = 0;
int sample_count = 0; // Infinite loop
if (argc >= 2) {
domain_id = atoi(argv[1]);
}
if (argc >= 3) {
sample_count = atoi(argv[2]);
}
// To turn on additional logging, include <rti/config/Logger.hpp> and
// uncomment the following line:
// rti::config::Logger::instance().verbosity(rti::config::Verbosity::STATUS_ALL);
try {
publisher_main(domain_id, sample_count);
} catch (const std::exception &ex) {
// This will catch DDS exceptions
std::cerr << "Exception in publisher_main: " << ex.what() << std::endl;
return -1;
}
return 0;
}
| cxx |
rticonnextdds-examples | data/projects/rticonnextdds-examples/connext_dds/keyed_data/c++03/keys_subscriber.cxx | /*******************************************************************************
(c) 2005-2015 Copyright, Real-Time Innovations, Inc. All rights reserved.
RTI grants Licensee a license to use, modify, compile, and create derivative
works of the Software. Licensee has the right to distribute object form only
for use with RTI products. The Software is provided "as is", with no warranty
of any type, including any warranty for fitness for any purpose. RTI is under
no obligation to maintain or support the Software. RTI shall not be liable for
any incidental or consequential damages arising out of the use or inability to
use the software.
******************************************************************************/
#include <cstdlib>
#include <iostream>
#include "keys.hpp"
#include <dds/dds.hpp>
#include <rti/core/ListenerBinder.hpp>
using namespace dds::core;
using namespace rti::core;
using namespace dds::domain;
using namespace dds::topic;
using namespace dds::sub;
using namespace dds::sub::status;
class KeysReaderListener : public NoOpDataReaderListener<keys> {
public:
void on_data_available(DataReader<keys> &reader)
{
// Take all samples
LoanedSamples<keys> samples = reader.take();
for (LoanedSamples<keys>::iterator sample_it = samples.begin();
sample_it != samples.end();
sample_it++) {
const SampleInfo &info = sample_it->info();
if (info.valid()) {
ViewState view_state = info.state().view_state();
if (view_state == ViewState::new_view()) {
std::cout << "Found new instance; code = "
<< sample_it->data().code() << std::endl;
}
std::cout << "Instance " << sample_it->data().code()
<< ", x: " << sample_it->data().x()
<< ", y: " << sample_it->data().y() << std::endl;
} else {
// Since there is not valid data, it may include metadata.
keys sample;
reader.key_value(sample, info.instance_handle());
// Here we print a message if the instance state is
// 'not_alive_no_writers' or 'not_alive_disposed'.
const InstanceState &state = info.state().instance_state();
if (state == InstanceState::not_alive_no_writers()) {
std::cout << "Instance " << sample.code()
<< " has no writers" << std::endl;
} else if (state == InstanceState::not_alive_disposed()) {
std::cout << "Instance " << sample.code() << " disposed"
<< std::endl;
}
}
}
}
};
void subscriber_main(int domain_id, int sample_count)
{
// Create a DomainParticipant with default Qos
DomainParticipant participant(domain_id);
// Create a Topic -- and automatically register the type
Topic<keys> topic(participant, "Example keys");
// Create a DataReader with default Qos (Subscriber created in-line)
DataReader<keys> reader(Subscriber(participant), topic);
// Associate a listener to the datareader using ListenerBinder, a RAII that
// will take care of setting it to NULL on destruction.
ListenerBinder<DataReader<keys> > reader_listener = bind_and_manage_listener(
reader,
new KeysReaderListener,
dds::core::status::StatusMask::all());
// Main loop
for (int count = 0; count < sample_count || sample_count == 0; count++) {
rti::util::sleep(Duration(1));
}
}
int main(int argc, char *argv[])
{
int domain_id = 0;
int sample_count = 0; // Infinite loop
if (argc >= 2) {
domain_id = atoi(argv[1]);
}
if (argc >= 3) {
sample_count = atoi(argv[2]);
}
// To turn on additional logging, include <rti/config/Logger.hpp> and
// uncomment the following line:
// rti::config::Logger::instance().verbosity(rti::config::Verbosity::STATUS_ALL);
try {
subscriber_main(domain_id, sample_count);
} catch (const std::exception &ex) {
// This will catch DDS exceptions
std::cerr << "Exception in subscriber_main(): " << ex.what()
<< std::endl;
return -1;
}
return 0;
}
| cxx |
rticonnextdds-examples | data/projects/rticonnextdds-examples/connext_dds/keyed_data/c++11/application.hpp | /*
* (c) Copyright, Real-Time Innovations, 2020. All rights reserved.
* RTI grants Licensee a license to use, modify, compile, and create derivative
* works of the software solely for use with RTI Connext DDS. Licensee may
* redistribute copies of the software provided that all such copies are subject
* to this license. The software is provided "as is", with no warranty of any
* type, including any warranty for fitness for any purpose. RTI is under no
* obligation to maintain or support the software. RTI shall not be liable for
* any incidental or consequential damages arising out of the use or inability
* to use the software.
*/
#ifndef APPLICATION_HPP
#define APPLICATION_HPP
#include <iostream>
#include <csignal>
#include <dds/core/ddscore.hpp>
namespace application {
// Catch control-C and tell application to shut down
bool shutdown_requested = false;
inline void stop_handler(int)
{
shutdown_requested = true;
std::cout << "preparing to shut down..." << std::endl;
}
inline void setup_signal_handlers()
{
signal(SIGINT, stop_handler);
signal(SIGTERM, stop_handler);
}
enum class ParseReturn { ok, failure, exit };
struct ApplicationArguments {
ParseReturn parse_result;
unsigned int domain_id;
unsigned int sample_count;
rti::config::Verbosity verbosity;
ApplicationArguments(
ParseReturn parse_result_param,
unsigned int domain_id_param,
unsigned int sample_count_param,
rti::config::Verbosity verbosity_param)
: parse_result(parse_result_param),
domain_id(domain_id_param),
sample_count(sample_count_param),
verbosity(verbosity_param)
{
}
};
inline void set_verbosity(
rti::config::Verbosity &verbosity,
int verbosity_value)
{
switch (verbosity_value) {
case 0:
verbosity = rti::config::Verbosity::SILENT;
break;
case 1:
verbosity = rti::config::Verbosity::EXCEPTION;
break;
case 2:
verbosity = rti::config::Verbosity::WARNING;
break;
case 3:
verbosity = rti::config::Verbosity::STATUS_ALL;
break;
default:
verbosity = rti::config::Verbosity::EXCEPTION;
break;
}
}
// Parses application arguments for example.
inline ApplicationArguments parse_arguments(int argc, char *argv[])
{
int arg_processing = 1;
bool show_usage = false;
ParseReturn parse_result = ParseReturn::ok;
unsigned int domain_id = 0;
unsigned int sample_count = (std::numeric_limits<unsigned int>::max)();
rti::config::Verbosity verbosity(rti::config::Verbosity::EXCEPTION);
while (arg_processing < argc) {
if ((argc > arg_processing + 1)
&& (strcmp(argv[arg_processing], "-d") == 0
|| strcmp(argv[arg_processing], "--domain") == 0)) {
domain_id = atoi(argv[arg_processing + 1]);
arg_processing += 2;
} else if (
(argc > arg_processing + 1)
&& (strcmp(argv[arg_processing], "-s") == 0
|| strcmp(argv[arg_processing], "--sample-count") == 0)) {
sample_count = atoi(argv[arg_processing + 1]);
arg_processing += 2;
} else if (
(argc > arg_processing + 1)
&& (strcmp(argv[arg_processing], "-v") == 0
|| strcmp(argv[arg_processing], "--verbosity") == 0)) {
set_verbosity(verbosity, atoi(argv[arg_processing + 1]));
arg_processing += 2;
} else if (
strcmp(argv[arg_processing], "-h") == 0
|| strcmp(argv[arg_processing], "--help") == 0) {
std::cout << "Example application." << std::endl;
show_usage = true;
parse_result = ParseReturn::exit;
break;
} else {
std::cout << "Bad parameter." << std::endl;
show_usage = true;
parse_result = ParseReturn::failure;
break;
}
}
if (show_usage) {
std::cout << "Usage:\n"
" -d, --domain <int> Domain ID this "
"application will\n"
" subscribe in. \n"
" Default: 0\n"
" -s, --sample_count <int> Number of samples to "
"receive before\n"
" cleanly shutting down. \n"
" Default: infinite\n"
" -v, --verbosity <int> How much debugging output "
"to show.\n"
" Range: 0-3 \n"
" Default: 1"
<< std::endl;
}
return ApplicationArguments(
parse_result,
domain_id,
sample_count,
verbosity);
}
} // namespace application
#endif // APPLICATION_HPP | hpp |
rticonnextdds-examples | data/projects/rticonnextdds-examples/connext_dds/keyed_data/c++11/keys_publisher.cxx | /*******************************************************************************
(c) 2005-2015 Copyright, Real-Time Innovations, Inc. All rights reserved.
RTI grants Licensee a license to use, modify, compile, and create derivative
works of the Software. Licensee has the right to distribute object form only
for use with RTI products. The Software is provided "as is", with no warranty
of any type, including any warranty for fitness for any purpose. RTI is under
no obligation to maintain or support the Software. RTI shall not be liable for
any incidental or consequential damages arising out of the use or inability to
use the software.
******************************************************************************/
#include <dds/pub/ddspub.hpp>
#include <rti/util/util.hpp> // for sleep()
#include <rti/config/Logger.hpp> // for logging
#include "application.hpp" // for command line parsing and ctrl-c
#include "keys.hpp"
void run_publisher_application(
unsigned int domain_id,
unsigned int sample_count)
{
// Create a DomainParticipant with default Qos.
dds::domain::DomainParticipant participant(domain_id);
// Create a Topic -- and automatically register the type.
dds::topic::Topic<keys> topic(participant, "Example keys");
// Retrieve the DataWriter QoS, from USER_QOS_PROFILES.xml
dds::pub::qos::DataWriterQos writer_qos =
dds::core::QosProvider::Default().datawriter_qos();
// If you want to change the DataWriter's QoS programmatically rather
// than using the XML file, you will need to comment out the previous
// writer_qos assignment and uncomment this line.
// writer_qos <<
// WriterDataLifecycle::ManuallyDisposeUnregisteredInstances();
// Create a Publisher
dds::pub::Publisher publisher(participant);
// Create a DataWriter with default Qos.
dds::pub::DataWriter<keys> writer(publisher, topic, writer_qos);
std::vector<keys> samples;
std::vector<dds::core::InstanceHandle> instance_handles;
// RTI Connext could examine the key fields each time it needs to determine
// which data-instance is being modified. However, for performance and
// semantic reasons, it is better for your application to declare all the
// data-instances it intends to modify prior to actually writing any
// samples. This is known as registration.
int num_samples = 3;
for (int i = 0; i < num_samples; i++) {
// In order to register the instances, we must set their associated
// keys first.
keys k;
k.code(i);
// Initially, we register only the first sample.
if (i == 0) {
// The keys must have been set before making this call.
std::cout << "Registering instance " << k.code() << std::endl;
instance_handles.push_back(writer.register_instance(k));
} else {
instance_handles.push_back(dds::core::InstanceHandle::nil());
}
// Finally, we modify the data to be sent.
k.x((i + 1) * 1000);
samples.push_back(k);
}
// Main loop
for (unsigned int samples_written = 0;
!application::shutdown_requested && samples_written < sample_count;
samples_written++) {
rti::util::sleep(dds::core::Duration(1));
if (samples_written == 5) {
// Start sending the second and third instances.
std::cout << "----Registering instance " << samples[1].code()
<< std::endl;
instance_handles[1] = writer.register_instance(samples[1]);
std::cout << "----Registering instance " << samples[2].code()
<< std::endl;
instance_handles[2] = writer.register_instance(samples[2]);
} else if (samples_written == 10) {
// Unregister the second instance.
std::cout << "----Unregistering instance " << samples[1].code()
<< std::endl;
writer.unregister_instance(instance_handles[1]);
instance_handles[1] = dds::core::InstanceHandle::nil();
} else if (samples_written == 15) {
// Dispose the third instance.
std::cout << "----Disposing instance " << samples[2].code()
<< std::endl;
writer.dispose_instance(instance_handles[2]);
instance_handles[2] = dds::core::InstanceHandle::nil();
}
// Update sample data field and send if handle is not nil.
for (int i = 0; i < num_samples; i++) {
if (!instance_handles[i].is_nil()) {
samples[i].y(samples_written);
std::cout << "Writing instance " << samples[i].code()
<< ", x: " << samples[i].x()
<< ", y: " << samples[i].y() << std::endl;
writer.write(samples[i], instance_handles[i]);
}
}
}
}
int main(int argc, char *argv[])
{
using namespace application;
// Parse arguments and handle control-C
auto arguments = parse_arguments(argc, argv);
if (arguments.parse_result == ParseReturn::exit) {
return EXIT_SUCCESS;
} else if (arguments.parse_result == ParseReturn::failure) {
return EXIT_FAILURE;
}
setup_signal_handlers();
// Sets Connext verbosity to help debugging
rti::config::Logger::instance().verbosity(arguments.verbosity);
try {
run_publisher_application(arguments.domain_id, arguments.sample_count);
} catch (const std::exception &ex) {
// This will catch DDS exceptions
std::cerr << "Exception in run_publisher_application(): " << ex.what()
<< std::endl;
return EXIT_FAILURE;
}
// Releases the memory used by the participant factory. Optional at
// application exit
dds::domain::DomainParticipant::finalize_participant_factory();
return EXIT_SUCCESS;
}
| cxx |
rticonnextdds-examples | data/projects/rticonnextdds-examples/connext_dds/keyed_data/c++11/keys_subscriber.cxx | /*******************************************************************************
(c) 2005-2015 Copyright, Real-Time Innovations, Inc. All rights reserved.
RTI grants Licensee a license to use, modify, compile, and create derivative
works of the Software. Licensee has the right to distribute object form only
for use with RTI products. The Software is provided "as is", with no warranty
of any type, including any warranty for fitness for any purpose. RTI is under
no obligation to maintain or support the Software. RTI shall not be liable for
any incidental or consequential damages arising out of the use or inability to
use the software.
******************************************************************************/
#include <dds/sub/ddssub.hpp>
#include <dds/core/ddscore.hpp>
#include <rti/config/Logger.hpp> // for logging
#include "keys.hpp"
#include "application.hpp" // for command line parsing and ctrl-c
int process_data(dds::sub::DataReader<keys> reader)
{
int count = 0;
// Take all samples
dds::sub::LoanedSamples<keys> samples = reader.take();
for (const auto &sample : samples) {
const dds::sub::SampleInfo &info = sample.info();
if (info.valid()) {
dds::sub::status::ViewState view_state = info.state().view_state();
if (view_state == dds::sub::status::ViewState::new_view()) {
std::cout << "Found new instance; code = "
<< sample.data().code() << std::endl;
}
std::cout << "Instance " << sample.data().code()
<< ", x: " << sample.data().x()
<< ", y: " << sample.data().y() << std::endl;
} else {
// Since there is not valid data, it may include metadata.
keys sample;
reader.key_value(sample, info.instance_handle());
// Here we print a message if the instance state is
// 'not_alive_no_writers' or 'not_alive_disposed'.
const dds::sub::status::InstanceState &state =
info.state().instance_state();
if (state
== dds::sub::status::InstanceState::not_alive_no_writers()) {
std::cout << "Instance " << sample.code() << " has no writers"
<< std::endl;
} else if (
state
== dds::sub::status::InstanceState::not_alive_disposed()) {
std::cout << "Instance " << sample.code() << " disposed"
<< std::endl;
}
}
count++;
}
return count;
}
void run_subscriber_application(
unsigned int domain_id,
unsigned int sample_count)
{
// Create a DomainParticipant with default Qos
dds::domain::DomainParticipant participant(domain_id);
// Create a Topic -- and automatically register the type
dds::topic::Topic<keys> topic(participant, "Example keys");
// Create a subscriber
dds::sub::Subscriber subscriber(participant);
// Create a DataReader with default Qos
dds::sub::DataReader<keys> reader(subscriber, topic);
// WaitSet will be woken when the attached condition is triggered
dds::core::cond::WaitSet waitset;
// Create a ReadCondition for any data on this reader, and add to WaitSet
unsigned int samples_read = 0;
dds::sub::cond::ReadCondition read_condition(
reader,
dds::sub::status::DataState::any(),
[reader, &samples_read]() {
samples_read += process_data(reader);
});
waitset += read_condition;
// Main loop
while (!application::shutdown_requested && samples_read < sample_count) {
waitset.dispatch(dds::core::Duration(1));
}
}
int main(int argc, char *argv[])
{
using namespace application;
// Parse arguments and handle control-C
auto arguments = parse_arguments(argc, argv);
if (arguments.parse_result == ParseReturn::exit) {
return EXIT_SUCCESS;
} else if (arguments.parse_result == ParseReturn::failure) {
return EXIT_FAILURE;
}
setup_signal_handlers();
// Sets Connext verbosity to help debugging
rti::config::Logger::instance().verbosity(arguments.verbosity);
try {
run_subscriber_application(arguments.domain_id, arguments.sample_count);
} catch (const std::exception &ex) {
// This will catch DDS exceptions
std::cerr << "Exception in run_subscriber_application(): " << ex.what()
<< std::endl;
return EXIT_FAILURE;
}
// Releases the memory used by the participant factory. Optional at
// application exit
dds::domain::DomainParticipant::finalize_participant_factory();
return EXIT_SUCCESS;
}
| cxx |
rticonnextdds-examples | data/projects/rticonnextdds-examples/connext_dds/real_time_wan_transport/c++/real_time_wan_transport_publisher.cxx | /*
* (c) Copyright, Real-Time Innovations, 2020. All rights reserved.
* RTI grants Licensee a license to use, modify, compile, and create derivative
* works of the software solely for use with RTI Connext DDS. Licensee may
* redistribute copies of the software provided that all such copies are subject
* to this license. The software is provided "as is", with no warranty of any
* type, including any warranty for fitness for any purpose. RTI is under no
* obligation to maintain or support the software. RTI shall not be liable for
* any incidental or consequential damages arising out of the use or inability
* to use the software.
*/
#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include "real_time_wan_transport.h"
#include "real_time_wan_transportSupport.h"
#include "ndds/ndds_cpp.h"
#include "ndds/ndds_namespace_cpp.h"
#include "application.h"
using namespace DDS;
using namespace application;
static int shutdown_participant(
DomainParticipant *participant,
const char *shutdown_message,
int status);
int run_publisher_application(
unsigned int domain_id,
unsigned int sample_count,
unsigned int scenario)
{
const char *libraryName = "RWT_Library";
char profileName[64];
sprintf(profileName, "Publisher_Scenario_%d", scenario);
std::cout << "Executing scenario " << scenario << std::endl;
// Start communicating in a domain, usually one participant per application
DomainParticipant *participant =
TheParticipantFactory->create_participant_with_profile(
domain_id,
libraryName,
profileName,
NULL /* listener */,
STATUS_MASK_NONE);
if (participant == NULL) {
return shutdown_participant(
participant,
"create_participant error",
EXIT_FAILURE);
}
// A Publisher allows an application to create one or more DataWriters
Publisher *publisher = participant->create_publisher(
PUBLISHER_QOS_DEFAULT,
NULL /* listener */,
STATUS_MASK_NONE);
if (publisher == NULL) {
return shutdown_participant(
participant,
"create_publisher error",
EXIT_FAILURE);
}
// Register the datatype to use when creating the Topic
const char *type_name = HelloWorldTypeSupport::get_type_name();
ReturnCode_t retcode =
HelloWorldTypeSupport::register_type(participant, type_name);
if (retcode != RETCODE_OK) {
return shutdown_participant(
participant,
"register_type error",
EXIT_FAILURE);
}
// Create a Topic with a name and a datatype
Topic *topic = participant->create_topic(
"Example HelloWorld",
type_name,
TOPIC_QOS_DEFAULT,
NULL /* listener */,
STATUS_MASK_NONE);
if (topic == NULL) {
return shutdown_participant(
participant,
"create_topic error",
EXIT_FAILURE);
}
// This DataWriter writes data on "Example HelloWorld" Topic
DataWriter *untyped_writer = publisher->create_datawriter_with_profile(
topic,
libraryName,
profileName,
NULL /* listener */,
STATUS_MASK_NONE);
if (untyped_writer == NULL) {
return shutdown_participant(
participant,
"create_datawriter error",
EXIT_FAILURE);
}
// Narrow casts from an untyped DataWriter to a writer of your type
HelloWorldDataWriter *typed_writer =
HelloWorldDataWriter::narrow(untyped_writer);
if (typed_writer == NULL) {
return shutdown_participant(
participant,
"DataWriter narrow error",
EXIT_FAILURE);
}
// Create data for writing, allocating all members
HelloWorld *data = HelloWorldTypeSupport::create_data();
if (data == NULL) {
return shutdown_participant(
participant,
"HelloWorldTypeSupport::create_data error",
EXIT_FAILURE);
}
// Main loop, write data
for (unsigned int samples_written = 0;
!shutdown_requested && samples_written < sample_count;
++samples_written) {
// Modify the data to be written here
sprintf(data->msg, "Hello World %u", samples_written);
std::cout << "Writing HelloWorld, count " << samples_written
<< std::endl;
retcode = typed_writer->write(*data, HANDLE_NIL);
if (retcode != RETCODE_OK) {
std::cerr << "write error " << retcode << std::endl;
}
// Send once every second
Duration_t send_period = { 1, 0 };
NDDSUtility::sleep(send_period);
}
// Delete previously allocated HelloWorld, including all contained elements
retcode = HelloWorldTypeSupport::delete_data(data);
if (retcode != RETCODE_OK) {
std::cerr << "HelloWorldTypeSupport::delete_data error " << retcode
<< std::endl;
}
// Delete all entities (DataWriter, Topic, Publisher, DomainParticipant)
return shutdown_participant(participant, "Shutting down", EXIT_SUCCESS);
}
// Delete all entities
static int shutdown_participant(
DomainParticipant *participant,
const char *shutdown_message,
int status)
{
ReturnCode_t retcode;
std::cout << shutdown_message << std::endl;
if (participant != NULL) {
// Cleanup everything created by this Participant
retcode = participant->delete_contained_entities();
if (retcode != RETCODE_OK) {
std::cerr << "delete_contained_entities error " << retcode
<< std::endl;
status = EXIT_FAILURE;
}
retcode = TheParticipantFactory->delete_participant(participant);
if (retcode != RETCODE_OK) {
std::cerr << "delete_participant error " << retcode << std::endl;
status = EXIT_FAILURE;
}
}
return status;
}
int main(int argc, char *argv[])
{
// Parse arguments and handle control-C
ApplicationArguments arguments;
parse_arguments(arguments, argc, argv);
if (arguments.parse_result == PARSE_RETURN_EXIT) {
return EXIT_SUCCESS;
} else if (arguments.parse_result == PARSE_RETURN_FAILURE) {
return EXIT_FAILURE;
}
setup_signal_handlers();
// Sets Connext verbosity to help debugging
NDDSConfigLogger::get_instance()->set_verbosity(arguments.verbosity);
int status = run_publisher_application(
arguments.domain_id,
arguments.sample_count,
arguments.scenario);
// Releases the memory used by the participant factory. Optional at
// application exit
ReturnCode_t retcode = DomainParticipantFactory::finalize_instance();
if (retcode != RETCODE_OK) {
std::cerr << "finalize_instance error " << retcode << std::endl;
status = EXIT_FAILURE;
}
return status;
}
| cxx |
rticonnextdds-examples | data/projects/rticonnextdds-examples/connext_dds/real_time_wan_transport/c++/real_time_wan_transport_subscriber.cxx | /*
* (c) Copyright, Real-Time Innovations, 2020. All rights reserved.
* RTI grants Licensee a license to use, modify, compile, and create derivative
* works of the software solely for use with RTI Connext DDS. Licensee may
* redistribute copies of the software provided that all such copies are subject
* to this license. The software is provided "as is", with no warranty of any
* type, including any warranty for fitness for any purpose. RTI is under no
* obligation to maintain or support the software. RTI shall not be liable for
* any incidental or consequential damages arising out of the use or inability
* to use the software.
*/
#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include "real_time_wan_transport.h"
#include "real_time_wan_transportSupport.h"
#include "ndds/ndds_cpp.h"
#include "ndds/ndds_namespace_cpp.h"
#include "application.h"
using namespace DDS;
using namespace application;
static int shutdown_participant(
DomainParticipant *participant,
const char *shutdown_message,
int status);
// Process data. Returns number of samples processed.
unsigned int process_data(HelloWorldDataReader *typed_reader)
{
HelloWorldSeq data_seq; // Sequence of received data
SampleInfoSeq info_seq; // Metadata associated with samples in data_seq
unsigned int samples_read = 0;
// Take available data from DataReader's queue
typed_reader->take(
data_seq,
info_seq,
LENGTH_UNLIMITED,
ANY_SAMPLE_STATE,
ANY_VIEW_STATE,
ANY_INSTANCE_STATE);
// Iterate over all available data
for (int i = 0; i < data_seq.length(); ++i) {
// Check if a sample is an instance lifecycle event
if (info_seq[i].valid_data) {
// Print data
std::cout << "Received data" << std::endl;
HelloWorldTypeSupport::print_data(&data_seq[i]);
samples_read++;
} else { // This is an instance lifecycle event with no data payload.
std::cout << "Received instance state notification" << std::endl;
}
}
// Data loaned from Connext for performance. Return loan when done.
ReturnCode_t retcode = typed_reader->return_loan(data_seq, info_seq);
if (retcode != RETCODE_OK) {
std::cerr << "return loan error " << retcode << std::endl;
}
return samples_read;
}
int run_subscriber_application(
unsigned int domain_id,
unsigned int sample_count,
unsigned int scenario)
{
const char *libraryName = "RWT_Library";
char profileName[64];
sprintf(profileName, "Subscriber_Scenario_%d", scenario);
// Start communicating in a domain, usually one participant per application
DomainParticipant *participant =
TheParticipantFactory->create_participant_with_profile(
domain_id,
libraryName,
profileName,
NULL /* listener */,
STATUS_MASK_NONE);
if (participant == NULL) {
return shutdown_participant(
participant,
"create_participant error",
EXIT_FAILURE);
}
// A Subscriber allows an application to create one or more DataReaders
Subscriber *subscriber = participant->create_subscriber(
SUBSCRIBER_QOS_DEFAULT,
NULL /* listener */,
STATUS_MASK_NONE);
if (subscriber == NULL) {
return shutdown_participant(
participant,
"create_subscriber error",
EXIT_FAILURE);
}
// Register the datatype to use when creating the Topic
const char *type_name = HelloWorldTypeSupport::get_type_name();
ReturnCode_t retcode =
HelloWorldTypeSupport::register_type(participant, type_name);
if (retcode != RETCODE_OK) {
return shutdown_participant(
participant,
"register_type error",
EXIT_FAILURE);
}
// Create a Topic with a name and a datatype
Topic *topic = participant->create_topic(
"Example HelloWorld",
type_name,
TOPIC_QOS_DEFAULT,
NULL /* listener */,
STATUS_MASK_NONE);
if (topic == NULL) {
return shutdown_participant(
participant,
"create_topic error",
EXIT_FAILURE);
}
// This DataReader reads data on "Example HelloWorld" Topic
DataReader *untyped_reader = subscriber->create_datareader_with_profile(
topic,
libraryName,
profileName,
NULL,
STATUS_MASK_NONE);
if (untyped_reader == NULL) {
return shutdown_participant(
participant,
"create_datareader error",
EXIT_FAILURE);
}
// Narrow casts from a untyped DataReader to a reader of your type
HelloWorldDataReader *typed_reader =
HelloWorldDataReader::narrow(untyped_reader);
if (typed_reader == NULL) {
return shutdown_participant(
participant,
"DataReader narrow error",
EXIT_FAILURE);
}
// Create ReadCondition that triggers when unread data in reader's queue
ReadCondition *read_condition = typed_reader->create_readcondition(
NOT_READ_SAMPLE_STATE,
ANY_VIEW_STATE,
ANY_INSTANCE_STATE);
if (read_condition == NULL) {
return shutdown_participant(
participant,
"create_readcondition error",
EXIT_FAILURE);
}
// WaitSet will be woken when the attached condition is triggered
WaitSet waitset;
retcode = waitset.attach_condition(read_condition);
if (retcode != RETCODE_OK) {
return shutdown_participant(
participant,
"attach_condition error",
EXIT_FAILURE);
}
// Main loop. Wait for data to arrive, and process when it arrives
unsigned int samples_read = 0;
while (!shutdown_requested && samples_read < sample_count) {
ConditionSeq active_conditions_seq;
// Wait for data and report if it does not arrive in 1 second
Duration_t wait_timeout = { 1, 0 };
retcode = waitset.wait(active_conditions_seq, wait_timeout);
if (retcode == RETCODE_OK) {
// If the read condition is triggered, process data
samples_read += process_data(typed_reader);
} else {
if (retcode == RETCODE_TIMEOUT) {
std::cout << "No data after 1 second" << std::endl;
}
}
}
// Cleanup
return shutdown_participant(participant, "Shutting down", 0);
}
// Delete all entities
static int shutdown_participant(
DomainParticipant *participant,
const char *shutdown_message,
int status)
{
ReturnCode_t retcode;
std::cout << shutdown_message << std::endl;
if (participant != NULL) {
// Cleanup everything created by this Participant
retcode = participant->delete_contained_entities();
if (retcode != RETCODE_OK) {
std::cerr << "delete_contained_entities error" << retcode
<< std::endl;
status = EXIT_FAILURE;
}
retcode = TheParticipantFactory->delete_participant(participant);
if (retcode != RETCODE_OK) {
std::cerr << "delete_participant error" << retcode << std::endl;
status = EXIT_FAILURE;
}
}
return status;
}
int main(int argc, char *argv[])
{
// Parse arguments and handle control-C
ApplicationArguments arguments;
parse_arguments(arguments, argc, argv);
if (arguments.parse_result == PARSE_RETURN_EXIT) {
return EXIT_SUCCESS;
} else if (arguments.parse_result == PARSE_RETURN_FAILURE) {
return EXIT_FAILURE;
}
setup_signal_handlers();
// Sets Connext verbosity to help debugging
NDDSConfigLogger::get_instance()->set_verbosity(arguments.verbosity);
int status = run_subscriber_application(
arguments.domain_id,
arguments.sample_count,
arguments.scenario);
// Releases the memory used by the participant factory. Optional at
// application exit
ReturnCode_t retcode = DomainParticipantFactory::finalize_instance();
if (retcode != RETCODE_OK) {
std::cerr << "finalize_instance error" << retcode << std::endl;
status = EXIT_FAILURE;
}
return status;
}
| cxx |
rticonnextdds-examples | data/projects/rticonnextdds-examples/connext_dds/real_time_wan_transport/c++/application.h | /*
* (c) Copyright, Real-Time Innovations, 2020. All rights reserved.
* RTI grants Licensee a license to use, modify, compile, and create derivative
* works of the software solely for use with RTI Connext DDS. Licensee may
* redistribute copies of the software provided that all such copies are subject
* to this license. The software is provided "as is", with no warranty of any
* type, including any warranty for fitness for any purpose. RTI is under no
* obligation to maintain or support the software. RTI shall not be liable for
* any incidental or consequential damages arising out of the use or inability
* to use the software.
*/
#ifndef APPLICATION_H
#define APPLICATION_H
#include <climits>
#include <csignal>
#include <iostream>
namespace application {
// Catch control-C and tell application to shut down
bool shutdown_requested = false;
inline void stop_handler(int)
{
shutdown_requested = true;
std::cout << "preparing to shut down..." << std::endl;
}
inline void setup_signal_handlers()
{
signal(SIGINT, stop_handler);
signal(SIGTERM, stop_handler);
}
enum ParseReturn { PARSE_RETURN_OK, PARSE_RETURN_FAILURE, PARSE_RETURN_EXIT };
struct ApplicationArguments {
ParseReturn parse_result;
unsigned int domain_id;
unsigned int sample_count;
unsigned int scenario;
NDDS_Config_LogVerbosity verbosity;
};
inline void set_verbosity(ApplicationArguments &arguments, int verbosity)
{
switch (verbosity) {
case 0:
arguments.verbosity = NDDS_CONFIG_LOG_VERBOSITY_SILENT;
break;
case 1:
arguments.verbosity = NDDS_CONFIG_LOG_VERBOSITY_ERROR;
break;
case 2:
arguments.verbosity = NDDS_CONFIG_LOG_VERBOSITY_WARNING;
break;
case 3:
arguments.verbosity = NDDS_CONFIG_LOG_VERBOSITY_STATUS_ALL;
break;
default:
arguments.verbosity = NDDS_CONFIG_LOG_VERBOSITY_ERROR;
break;
}
}
// Parses application arguments for example. Returns whether to exit.
inline void parse_arguments(
ApplicationArguments &arguments,
int argc,
char *argv[])
{
int arg_processing = 1;
bool show_usage = false;
arguments.domain_id = 0;
arguments.sample_count = INT_MAX;
arguments.scenario = 1;
arguments.verbosity = NDDS_CONFIG_LOG_VERBOSITY_ERROR;
arguments.parse_result = PARSE_RETURN_OK;
while (arg_processing < argc) {
if ((argc > arg_processing + 1)
&& (strcmp(argv[arg_processing], "-d") == 0
|| strcmp(argv[arg_processing], "--domain") == 0)) {
arguments.domain_id = atoi(argv[arg_processing + 1]);
arg_processing += 2;
} else if (
(argc > arg_processing + 1)
&& (strcmp(argv[arg_processing], "-s") == 0
|| strcmp(argv[arg_processing], "--sample-count") == 0)) {
arguments.sample_count = atoi(argv[arg_processing + 1]);
arg_processing += 2;
} else if (
(argc > arg_processing + 1)
&& (strcmp(argv[arg_processing], "-c") == 0
|| strcmp(argv[arg_processing], "--scenario") == 0)) {
arguments.scenario = atoi(argv[arg_processing + 1]);
arg_processing += 2;
} else if (
(argc > arg_processing + 1)
&& (strcmp(argv[arg_processing], "-v") == 0
|| strcmp(argv[arg_processing], "--verbosity") == 0)) {
set_verbosity(arguments, atoi(argv[arg_processing + 1]));
arg_processing += 2;
} else if (
strcmp(argv[arg_processing], "-h") == 0
|| strcmp(argv[arg_processing], "--help") == 0) {
std::cout << "Example application." << std::endl;
show_usage = true;
arguments.parse_result = PARSE_RETURN_EXIT;
break;
} else {
std::cout << "Bad parameter." << std::endl;
show_usage = true;
arguments.parse_result = PARSE_RETURN_FAILURE;
break;
}
}
if (show_usage) {
std::cout << "Usage:\n"
" -d, --domain <int> Domain ID this "
"application will\n"
" subscribe in.\n"
" Default: 0\n"
" -s, --sample_count <int> Number of samples to "
"receive before\n"
" cleanly shutting down.\n"
" Default: infinite\n"
" -c, --scenario <int> Test scenario\n"
" Range: 1-4\n"
" Default: 1\n"
" -v, --verbosity <int> How much debugging output "
"to show.\n"
" Range: 0-3\n"
" Default: 1"
<< std::endl;
}
}
} // namespace application
#endif // APPLICATION_H | h |
rticonnextdds-examples | data/projects/rticonnextdds-examples/connext_dds/real_time_wan_transport/c++98/real_time_wan_transport_publisher.cxx | /*
* (c) Copyright, Real-Time Innovations, 2020. All rights reserved.
* RTI grants Licensee a license to use, modify, compile, and create derivative
* works of the software solely for use with RTI Connext DDS. Licensee may
* redistribute copies of the software provided that all such copies are subject
* to this license. The software is provided "as is", with no warranty of any
* type, including any warranty for fitness for any purpose. RTI is under no
* obligation to maintain or support the software. RTI shall not be liable for
* any incidental or consequential damages arising out of the use or inability
* to use the software.
*/
#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include "real_time_wan_transport.h"
#include "real_time_wan_transportSupport.h"
#include "ndds/ndds_cpp.h"
#include "ndds/ndds_namespace_cpp.h"
#include "application.h"
using namespace DDS;
using namespace application;
static int shutdown_participant(
DomainParticipant *participant,
const char *shutdown_message,
int status);
int run_publisher_application(
unsigned int domain_id,
unsigned int sample_count,
unsigned int scenario)
{
const char *libraryName = "RWT_Library";
char profileName[64];
sprintf(profileName, "Publisher_Scenario_%d", scenario);
std::cout << "Executing scenario " << scenario << std::endl;
// Start communicating in a domain, usually one participant per application
DomainParticipant *participant =
TheParticipantFactory->create_participant_with_profile(
domain_id,
libraryName,
profileName,
NULL /* listener */,
STATUS_MASK_NONE);
if (participant == NULL) {
return shutdown_participant(
participant,
"create_participant error",
EXIT_FAILURE);
}
// A Publisher allows an application to create one or more DataWriters
Publisher *publisher = participant->create_publisher(
PUBLISHER_QOS_DEFAULT,
NULL /* listener */,
STATUS_MASK_NONE);
if (publisher == NULL) {
return shutdown_participant(
participant,
"create_publisher error",
EXIT_FAILURE);
}
// Register the datatype to use when creating the Topic
const char *type_name = HelloWorldTypeSupport::get_type_name();
ReturnCode_t retcode =
HelloWorldTypeSupport::register_type(participant, type_name);
if (retcode != RETCODE_OK) {
return shutdown_participant(
participant,
"register_type error",
EXIT_FAILURE);
}
// Create a Topic with a name and a datatype
Topic *topic = participant->create_topic(
"Example HelloWorld",
type_name,
TOPIC_QOS_DEFAULT,
NULL /* listener */,
STATUS_MASK_NONE);
if (topic == NULL) {
return shutdown_participant(
participant,
"create_topic error",
EXIT_FAILURE);
}
// This DataWriter writes data on "Example HelloWorld" Topic
DataWriter *untyped_writer = publisher->create_datawriter_with_profile(
topic,
libraryName,
profileName,
NULL /* listener */,
STATUS_MASK_NONE);
if (untyped_writer == NULL) {
return shutdown_participant(
participant,
"create_datawriter error",
EXIT_FAILURE);
}
// Narrow casts from an untyped DataWriter to a writer of your type
HelloWorldDataWriter *typed_writer =
HelloWorldDataWriter::narrow(untyped_writer);
if (typed_writer == NULL) {
return shutdown_participant(
participant,
"DataWriter narrow error",
EXIT_FAILURE);
}
// Create data for writing, allocating all members
HelloWorld *data = HelloWorldTypeSupport::create_data();
if (data == NULL) {
return shutdown_participant(
participant,
"HelloWorldTypeSupport::create_data error",
EXIT_FAILURE);
}
// Main loop, write data
for (unsigned int samples_written = 0;
!shutdown_requested && samples_written < sample_count;
++samples_written) {
// Modify the data to be written here
sprintf(data->msg, "Hello World %u", samples_written);
std::cout << "Writing HelloWorld, count " << samples_written
<< std::endl;
retcode = typed_writer->write(*data, HANDLE_NIL);
if (retcode != RETCODE_OK) {
std::cerr << "write error " << retcode << std::endl;
}
// Send once every second
Duration_t send_period = { 1, 0 };
NDDSUtility::sleep(send_period);
}
// Delete previously allocated HelloWorld, including all contained elements
retcode = HelloWorldTypeSupport::delete_data(data);
if (retcode != RETCODE_OK) {
std::cerr << "HelloWorldTypeSupport::delete_data error " << retcode
<< std::endl;
}
// Delete all entities (DataWriter, Topic, Publisher, DomainParticipant)
return shutdown_participant(participant, "Shutting down", EXIT_SUCCESS);
}
// Delete all entities
static int shutdown_participant(
DomainParticipant *participant,
const char *shutdown_message,
int status)
{
ReturnCode_t retcode;
std::cout << shutdown_message << std::endl;
if (participant != NULL) {
// Cleanup everything created by this Participant
retcode = participant->delete_contained_entities();
if (retcode != RETCODE_OK) {
std::cerr << "delete_contained_entities error " << retcode
<< std::endl;
status = EXIT_FAILURE;
}
retcode = TheParticipantFactory->delete_participant(participant);
if (retcode != RETCODE_OK) {
std::cerr << "delete_participant error " << retcode << std::endl;
status = EXIT_FAILURE;
}
}
return status;
}
int main(int argc, char *argv[])
{
// Parse arguments and handle control-C
ApplicationArguments arguments;
parse_arguments(arguments, argc, argv);
if (arguments.parse_result == PARSE_RETURN_EXIT) {
return EXIT_SUCCESS;
} else if (arguments.parse_result == PARSE_RETURN_FAILURE) {
return EXIT_FAILURE;
}
setup_signal_handlers();
// Sets Connext verbosity to help debugging
NDDSConfigLogger::get_instance()->set_verbosity(arguments.verbosity);
int status = run_publisher_application(
arguments.domain_id,
arguments.sample_count,
arguments.scenario);
// Releases the memory used by the participant factory. Optional at
// application exit
ReturnCode_t retcode = DomainParticipantFactory::finalize_instance();
if (retcode != RETCODE_OK) {
std::cerr << "finalize_instance error " << retcode << std::endl;
status = EXIT_FAILURE;
}
return status;
}
| cxx |
rticonnextdds-examples | data/projects/rticonnextdds-examples/connext_dds/real_time_wan_transport/c++98/real_time_wan_transport_subscriber.cxx | /*
* (c) Copyright, Real-Time Innovations, 2020. All rights reserved.
* RTI grants Licensee a license to use, modify, compile, and create derivative
* works of the software solely for use with RTI Connext DDS. Licensee may
* redistribute copies of the software provided that all such copies are subject
* to this license. The software is provided "as is", with no warranty of any
* type, including any warranty for fitness for any purpose. RTI is under no
* obligation to maintain or support the software. RTI shall not be liable for
* any incidental or consequential damages arising out of the use or inability
* to use the software.
*/
#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include "real_time_wan_transport.h"
#include "real_time_wan_transportSupport.h"
#include "ndds/ndds_cpp.h"
#include "ndds/ndds_namespace_cpp.h"
#include "application.h"
using namespace DDS;
using namespace application;
static int shutdown_participant(
DomainParticipant *participant,
const char *shutdown_message,
int status);
// Process data. Returns number of samples processed.
unsigned int process_data(HelloWorldDataReader *typed_reader)
{
HelloWorldSeq data_seq; // Sequence of received data
SampleInfoSeq info_seq; // Metadata associated with samples in data_seq
unsigned int samples_read = 0;
// Take available data from DataReader's queue
typed_reader->take(
data_seq,
info_seq,
LENGTH_UNLIMITED,
ANY_SAMPLE_STATE,
ANY_VIEW_STATE,
ANY_INSTANCE_STATE);
// Iterate over all available data
for (int i = 0; i < data_seq.length(); ++i) {
// Check if a sample is an instance lifecycle event
if (info_seq[i].valid_data) {
// Print data
std::cout << "Received data" << std::endl;
HelloWorldTypeSupport::print_data(&data_seq[i]);
samples_read++;
} else { // This is an instance lifecycle event with no data payload.
std::cout << "Received instance state notification" << std::endl;
}
}
// Data loaned from Connext for performance. Return loan when done.
ReturnCode_t retcode = typed_reader->return_loan(data_seq, info_seq);
if (retcode != RETCODE_OK) {
std::cerr << "return loan error " << retcode << std::endl;
}
return samples_read;
}
int run_subscriber_application(
unsigned int domain_id,
unsigned int sample_count,
unsigned int scenario)
{
const char *libraryName = "RWT_Library";
char profileName[64];
sprintf(profileName, "Subscriber_Scenario_%d", scenario);
// Start communicating in a domain, usually one participant per application
DomainParticipant *participant =
TheParticipantFactory->create_participant_with_profile(
domain_id,
libraryName,
profileName,
NULL /* listener */,
STATUS_MASK_NONE);
if (participant == NULL) {
return shutdown_participant(
participant,
"create_participant error",
EXIT_FAILURE);
}
// A Subscriber allows an application to create one or more DataReaders
Subscriber *subscriber = participant->create_subscriber(
SUBSCRIBER_QOS_DEFAULT,
NULL /* listener */,
STATUS_MASK_NONE);
if (subscriber == NULL) {
return shutdown_participant(
participant,
"create_subscriber error",
EXIT_FAILURE);
}
// Register the datatype to use when creating the Topic
const char *type_name = HelloWorldTypeSupport::get_type_name();
ReturnCode_t retcode =
HelloWorldTypeSupport::register_type(participant, type_name);
if (retcode != RETCODE_OK) {
return shutdown_participant(
participant,
"register_type error",
EXIT_FAILURE);
}
// Create a Topic with a name and a datatype
Topic *topic = participant->create_topic(
"Example HelloWorld",
type_name,
TOPIC_QOS_DEFAULT,
NULL /* listener */,
STATUS_MASK_NONE);
if (topic == NULL) {
return shutdown_participant(
participant,
"create_topic error",
EXIT_FAILURE);
}
// This DataReader reads data on "Example HelloWorld" Topic
DataReader *untyped_reader = subscriber->create_datareader_with_profile(
topic,
libraryName,
profileName,
NULL,
STATUS_MASK_NONE);
if (untyped_reader == NULL) {
return shutdown_participant(
participant,
"create_datareader error",
EXIT_FAILURE);
}
// Narrow casts from a untyped DataReader to a reader of your type
HelloWorldDataReader *typed_reader =
HelloWorldDataReader::narrow(untyped_reader);
if (typed_reader == NULL) {
return shutdown_participant(
participant,
"DataReader narrow error",
EXIT_FAILURE);
}
// Create ReadCondition that triggers when unread data in reader's queue
ReadCondition *read_condition = typed_reader->create_readcondition(
NOT_READ_SAMPLE_STATE,
ANY_VIEW_STATE,
ANY_INSTANCE_STATE);
if (read_condition == NULL) {
return shutdown_participant(
participant,
"create_readcondition error",
EXIT_FAILURE);
}
// WaitSet will be woken when the attached condition is triggered
WaitSet waitset;
retcode = waitset.attach_condition(read_condition);
if (retcode != RETCODE_OK) {
return shutdown_participant(
participant,
"attach_condition error",
EXIT_FAILURE);
}
// Main loop. Wait for data to arrive, and process when it arrives
unsigned int samples_read = 0;
while (!shutdown_requested && samples_read < sample_count) {
ConditionSeq active_conditions_seq;
// Wait for data and report if it does not arrive in 1 second
Duration_t wait_timeout = { 1, 0 };
retcode = waitset.wait(active_conditions_seq, wait_timeout);
if (retcode == RETCODE_OK) {
// If the read condition is triggered, process data
samples_read += process_data(typed_reader);
} else {
if (retcode == RETCODE_TIMEOUT) {
std::cout << "No data after 1 second" << std::endl;
}
}
}
// Cleanup
return shutdown_participant(participant, "Shutting down", 0);
}
// Delete all entities
static int shutdown_participant(
DomainParticipant *participant,
const char *shutdown_message,
int status)
{
ReturnCode_t retcode;
std::cout << shutdown_message << std::endl;
if (participant != NULL) {
// Cleanup everything created by this Participant
retcode = participant->delete_contained_entities();
if (retcode != RETCODE_OK) {
std::cerr << "delete_contained_entities error" << retcode
<< std::endl;
status = EXIT_FAILURE;
}
retcode = TheParticipantFactory->delete_participant(participant);
if (retcode != RETCODE_OK) {
std::cerr << "delete_participant error" << retcode << std::endl;
status = EXIT_FAILURE;
}
}
return status;
}
int main(int argc, char *argv[])
{
// Parse arguments and handle control-C
ApplicationArguments arguments;
parse_arguments(arguments, argc, argv);
if (arguments.parse_result == PARSE_RETURN_EXIT) {
return EXIT_SUCCESS;
} else if (arguments.parse_result == PARSE_RETURN_FAILURE) {
return EXIT_FAILURE;
}
setup_signal_handlers();
// Sets Connext verbosity to help debugging
NDDSConfigLogger::get_instance()->set_verbosity(arguments.verbosity);
int status = run_subscriber_application(
arguments.domain_id,
arguments.sample_count,
arguments.scenario);
// Releases the memory used by the participant factory. Optional at
// application exit
ReturnCode_t retcode = DomainParticipantFactory::finalize_instance();
if (retcode != RETCODE_OK) {
std::cerr << "finalize_instance error" << retcode << std::endl;
status = EXIT_FAILURE;
}
return status;
}
| cxx |
rticonnextdds-examples | data/projects/rticonnextdds-examples/connext_dds/real_time_wan_transport/c++98/application.h | /*
* (c) Copyright, Real-Time Innovations, 2020. All rights reserved.
* RTI grants Licensee a license to use, modify, compile, and create derivative
* works of the software solely for use with RTI Connext DDS. Licensee may
* redistribute copies of the software provided that all such copies are subject
* to this license. The software is provided "as is", with no warranty of any
* type, including any warranty for fitness for any purpose. RTI is under no
* obligation to maintain or support the software. RTI shall not be liable for
* any incidental or consequential damages arising out of the use or inability
* to use the software.
*/
#ifndef APPLICATION_H
#define APPLICATION_H
#include <climits>
#include <csignal>
#include <iostream>
namespace application {
// Catch control-C and tell application to shut down
bool shutdown_requested = false;
inline void stop_handler(int)
{
shutdown_requested = true;
std::cout << "preparing to shut down..." << std::endl;
}
inline void setup_signal_handlers()
{
signal(SIGINT, stop_handler);
signal(SIGTERM, stop_handler);
}
enum ParseReturn { PARSE_RETURN_OK, PARSE_RETURN_FAILURE, PARSE_RETURN_EXIT };
struct ApplicationArguments {
ParseReturn parse_result;
unsigned int domain_id;
unsigned int sample_count;
unsigned int scenario;
NDDS_Config_LogVerbosity verbosity;
};
inline void set_verbosity(ApplicationArguments &arguments, int verbosity)
{
switch (verbosity) {
case 0:
arguments.verbosity = NDDS_CONFIG_LOG_VERBOSITY_SILENT;
break;
case 1:
arguments.verbosity = NDDS_CONFIG_LOG_VERBOSITY_ERROR;
break;
case 2:
arguments.verbosity = NDDS_CONFIG_LOG_VERBOSITY_WARNING;
break;
case 3:
arguments.verbosity = NDDS_CONFIG_LOG_VERBOSITY_STATUS_ALL;
break;
default:
arguments.verbosity = NDDS_CONFIG_LOG_VERBOSITY_ERROR;
break;
}
}
// Parses application arguments for example. Returns whether to exit.
inline void parse_arguments(
ApplicationArguments &arguments,
int argc,
char *argv[])
{
int arg_processing = 1;
bool show_usage = false;
arguments.domain_id = 0;
arguments.sample_count = INT_MAX;
arguments.scenario = 1;
arguments.verbosity = NDDS_CONFIG_LOG_VERBOSITY_ERROR;
arguments.parse_result = PARSE_RETURN_OK;
while (arg_processing < argc) {
if ((argc > arg_processing + 1)
&& (strcmp(argv[arg_processing], "-d") == 0
|| strcmp(argv[arg_processing], "--domain") == 0)) {
arguments.domain_id = atoi(argv[arg_processing + 1]);
arg_processing += 2;
} else if (
(argc > arg_processing + 1)
&& (strcmp(argv[arg_processing], "-s") == 0
|| strcmp(argv[arg_processing], "--sample-count") == 0)) {
arguments.sample_count = atoi(argv[arg_processing + 1]);
arg_processing += 2;
} else if (
(argc > arg_processing + 1)
&& (strcmp(argv[arg_processing], "-c") == 0
|| strcmp(argv[arg_processing], "--scenario") == 0)) {
arguments.scenario = atoi(argv[arg_processing + 1]);
arg_processing += 2;
} else if (
(argc > arg_processing + 1)
&& (strcmp(argv[arg_processing], "-v") == 0
|| strcmp(argv[arg_processing], "--verbosity") == 0)) {
set_verbosity(arguments, atoi(argv[arg_processing + 1]));
arg_processing += 2;
} else if (
strcmp(argv[arg_processing], "-h") == 0
|| strcmp(argv[arg_processing], "--help") == 0) {
std::cout << "Example application." << std::endl;
show_usage = true;
arguments.parse_result = PARSE_RETURN_EXIT;
break;
} else {
std::cout << "Bad parameter." << std::endl;
show_usage = true;
arguments.parse_result = PARSE_RETURN_FAILURE;
break;
}
}
if (show_usage) {
std::cout << "Usage:\n"
" -d, --domain <int> Domain ID this "
"application will\n"
" subscribe in.\n"
" Default: 0\n"
" -s, --sample_count <int> Number of samples to "
"receive before\n"
" cleanly shutting down.\n"
" Default: infinite\n"
" -c, --scenario <int> Test scenario\n"
" Range: 1-4\n"
" Default: 1\n"
" -v, --verbosity <int> How much debugging output "
"to show.\n"
" Range: 0-3\n"
" Default: 1"
<< std::endl;
}
}
} // namespace application
#endif // APPLICATION_H
| h |
rticonnextdds-examples | data/projects/rticonnextdds-examples/connext_dds/dynamic_data_access_union_discriminator/c++/dynamic_data_union_example.cxx | /*******************************************************************************
(c) 2005-2014 Copyright, Real-Time Innovations, Inc. All rights reserved.
RTI grants Licensee a license to use, modify, compile, and create derivative
works of the Software. Licensee has the right to distribute object form only
for use with RTI products. The Software is provided "as is", with no warranty
of any type, including any warranty for fitness for any purpose. RTI is under
no obligation to maintain or support the Software. RTI shall not be liable for
any incidental or consequential damages arising out of the use or inability to
use the software.
******************************************************************************/
/* dynamic_data_union_example.cxx
This example
- creates the type code of for a union
- creates a DynamicData instance
- sets one of the members of the union
- shows how to retrieve the discriminator
- access to the value of one member of the union
Example:
To run the example application:
On Unix:
objs/<arch>/union_example
On Windows:
objs\<arch>\union_example
*/
#include <iostream>
#include <ndds_cpp.h>
using namespace std;
DDS_TypeCode *create_type_code(DDS_TypeCodeFactory *tcf)
{
static DDS_TypeCode *unionTC = NULL;
struct DDS_UnionMemberSeq members;
DDS_ExceptionCode_t err;
/* First, we create the typeCode for a union */
/* Default-member index refers to which member of the union
* will be the default one. In this example index = 1 refers
* to the the member 'aLong'. Take into account that index
* starts in 0 */
unionTC = tcf->create_union_tc(
"Foo",
DDS_MUTABLE_EXTENSIBILITY,
tcf->get_primitive_tc(DDS_TK_LONG),
1, /* default-member index */
members, /* For now, it does not have any member */
err);
if (err != DDS_NO_EXCEPTION_CODE) {
cerr << "! Unable to create typecode: " << err << endl;
goto fail;
}
/* Case 1 will be a short named aShort */
unionTC->add_member(
"aShort",
DDS_DYNAMIC_DATA_MEMBER_ID_UNSPECIFIED,
tcf->get_primitive_tc(DDS_TK_SHORT),
DDS_TYPECODE_NONKEY_MEMBER,
err);
if (err != DDS_NO_EXCEPTION_CODE) {
cerr << "! Unable to add member aShort: " << err << endl;
goto fail;
}
/* Case 2, the default, will be a long named aLong */
unionTC->add_member(
"aLong",
2,
tcf->get_primitive_tc(DDS_TK_LONG),
DDS_TYPECODE_NONKEY_MEMBER,
err);
if (err != DDS_NO_EXCEPTION_CODE) {
cerr << "! Unable to add member aLong: " << err << endl;
goto fail;
}
/* Case 3 will be a double named aDouble */
unionTC->add_member(
"aDouble",
3,
tcf->get_primitive_tc(DDS_TK_DOUBLE),
DDS_TYPECODE_NONKEY_MEMBER,
err);
if (err != DDS_NO_EXCEPTION_CODE) {
cerr << "! Unable to add member aDouble: " << err << endl;
goto fail;
}
return unionTC;
fail:
if (unionTC != NULL) {
tcf->delete_tc(unionTC, err);
}
return NULL;
}
int example()
{
/* Creating the union typeCode */
DDS_TypeCodeFactory *tcf = NULL;
tcf = DDS_TypeCodeFactory::get_instance();
if (tcf == NULL) {
cerr << "! Unable to get type code factory singleton" << endl;
return -1;
}
struct DDS_TypeCode *unionTC = create_type_code(tcf);
DDS_ReturnCode_t retcode;
struct DDS_DynamicDataMemberInfo info;
int ret = -1;
DDS_ExceptionCode_t err;
struct DDS_DynamicDataProperty_t myProperty =
DDS_DYNAMIC_DATA_PROPERTY_DEFAULT;
DDS_Short valueTestShort;
/* Creating a new dynamicData instance based on the union type code */
struct DDS_DynamicData data(unionTC, myProperty);
if (!data.is_valid()) {
cerr << "! Unable to create dynamicData" << endl;
goto fail;
}
/* If we get the current discriminator, it will be the default one
* (not the first added) */
retcode = data.get_member_info_by_index(info, 0);
if (retcode != DDS_RETCODE_OK) {
cerr << "! Unable to get member info" << endl;
goto fail;
}
cout << "The member selected is " << info.member_name << endl;
/* When we set a value in one of the members of the union,
* the discriminator updates automatically to point that member. */
retcode = data.set_short(
"aShort",
DDS_DYNAMIC_DATA_MEMBER_ID_UNSPECIFIED,
42);
if (retcode != DDS_RETCODE_OK) {
cerr << "! Unable to set short member " << endl;
goto fail;
}
/* The discriminator should now reflect the new situation */
retcode = data.get_member_info_by_index(info, 0);
if (retcode != DDS_RETCODE_OK) {
cerr << "! Unable to get member info" << endl;
goto fail;
}
cout << "The member selected is " << info.member_name << endl;
/* Getting the value of the target member */
retcode = data.get_short(
valueTestShort,
"aShort",
DDS_DYNAMIC_DATA_MEMBER_ID_UNSPECIFIED);
if (retcode != DDS_RETCODE_OK) {
cerr << "! Unable to get member value" << endl;
goto fail;
}
cout << "The member selected is " << info.member_name
<< "with value: " << valueTestShort << endl;
ret = 1;
fail:
if (unionTC != NULL) {
tcf->delete_tc(unionTC, err);
}
return ret;
}
int main(int argc, char *argv[])
{
return example();
}
| cxx |
rticonnextdds-examples | data/projects/rticonnextdds-examples/connext_dds/dynamic_data_access_union_discriminator/c++98/dynamic_data_union_example.cxx | /*******************************************************************************
(c) 2005-2014 Copyright, Real-Time Innovations, Inc. All rights reserved.
RTI grants Licensee a license to use, modify, compile, and create derivative
works of the Software. Licensee has the right to distribute object form only
for use with RTI products. The Software is provided "as is", with no warranty
of any type, including any warranty for fitness for any purpose. RTI is under
no obligation to maintain or support the Software. RTI shall not be liable for
any incidental or consequential damages arising out of the use or inability to
use the software.
******************************************************************************/
/* dynamic_data_union_example.cxx
This example
- creates the type code of for a union
- creates a DynamicData instance
- sets one of the members of the union
- shows how to retrieve the discriminator
- access to the value of one member of the union
Example:
To run the example application:
On Unix:
objs/<arch>/union_example
On Windows:
objs\<arch>\union_example
*/
#include <iostream>
#include <ndds_cpp.h>
using namespace std;
DDS_TypeCode *create_type_code(DDS_TypeCodeFactory *tcf)
{
static DDS_TypeCode *unionTC = NULL;
struct DDS_UnionMemberSeq members;
DDS_ExceptionCode_t err;
/* First, we create the typeCode for a union */
/* Default-member index refers to which member of the union
* will be the default one. In this example index = 1 refers
* to the the member 'aLong'. Take into account that index
* starts in 0 */
unionTC = tcf->create_union_tc(
"Foo",
DDS_MUTABLE_EXTENSIBILITY,
tcf->get_primitive_tc(DDS_TK_LONG),
1, /* default-member index */
members, /* For now, it does not have any member */
err);
if (err != DDS_NO_EXCEPTION_CODE) {
cerr << "! Unable to create typecode: " << err << endl;
goto fail;
}
/* Case 1 will be a short named aShort */
unionTC->add_member(
"aShort",
DDS_DYNAMIC_DATA_MEMBER_ID_UNSPECIFIED,
tcf->get_primitive_tc(DDS_TK_SHORT),
DDS_TYPECODE_NONKEY_MEMBER,
err);
if (err != DDS_NO_EXCEPTION_CODE) {
cerr << "! Unable to add member aShort: " << err << endl;
goto fail;
}
/* Case 2, the default, will be a long named aLong */
unionTC->add_member(
"aLong",
2,
tcf->get_primitive_tc(DDS_TK_LONG),
DDS_TYPECODE_NONKEY_MEMBER,
err);
if (err != DDS_NO_EXCEPTION_CODE) {
cerr << "! Unable to add member aLong: " << err << endl;
goto fail;
}
/* Case 3 will be a double named aDouble */
unionTC->add_member(
"aDouble",
3,
tcf->get_primitive_tc(DDS_TK_DOUBLE),
DDS_TYPECODE_NONKEY_MEMBER,
err);
if (err != DDS_NO_EXCEPTION_CODE) {
cerr << "! Unable to add member aDouble: " << err << endl;
goto fail;
}
return unionTC;
fail:
if (unionTC != NULL) {
tcf->delete_tc(unionTC, err);
}
return NULL;
}
int example()
{
/* Creating the union typeCode */
DDS_TypeCodeFactory *tcf = NULL;
tcf = DDS_TypeCodeFactory::get_instance();
if (tcf == NULL) {
cerr << "! Unable to get type code factory singleton" << endl;
return -1;
}
struct DDS_TypeCode *unionTC = create_type_code(tcf);
DDS_ReturnCode_t retcode;
struct DDS_DynamicDataMemberInfo info;
int ret = -1;
DDS_ExceptionCode_t err;
struct DDS_DynamicDataProperty_t myProperty =
DDS_DYNAMIC_DATA_PROPERTY_DEFAULT;
DDS_Short valueTestShort;
/* Creating a new dynamicData instance based on the union type code */
struct DDS_DynamicData data(unionTC, myProperty);
if (!data.is_valid()) {
cerr << "! Unable to create dynamicData" << endl;
goto fail;
}
/* If we get the current discriminator, it will be the default one
* (not the first added) */
retcode = data.get_member_info_by_index(info, 0);
if (retcode != DDS_RETCODE_OK) {
cerr << "! Unable to get member info" << endl;
goto fail;
}
cout << "The member selected is " << info.member_name << endl;
/* When we set a value in one of the members of the union,
* the discriminator updates automatically to point that member. */
retcode = data.set_short(
"aShort",
DDS_DYNAMIC_DATA_MEMBER_ID_UNSPECIFIED,
42);
if (retcode != DDS_RETCODE_OK) {
cerr << "! Unable to set short member " << endl;
goto fail;
}
/* The discriminator should now reflect the new situation */
retcode = data.get_member_info_by_index(info, 0);
if (retcode != DDS_RETCODE_OK) {
cerr << "! Unable to get member info" << endl;
goto fail;
}
cout << "The member selected is " << info.member_name << endl;
/* Getting the value of the target member */
retcode = data.get_short(
valueTestShort,
"aShort",
DDS_DYNAMIC_DATA_MEMBER_ID_UNSPECIFIED);
if (retcode != DDS_RETCODE_OK) {
cerr << "! Unable to get member value" << endl;
goto fail;
}
cout << "The member selected is " << info.member_name
<< "with value: " << valueTestShort << endl;
ret = 1;
fail:
if (unionTC != NULL) {
tcf->delete_tc(unionTC, err);
}
return ret;
}
int main(int argc, char *argv[])
{
return example();
}
| cxx |
rticonnextdds-examples | data/projects/rticonnextdds-examples/connext_dds/dynamic_data_access_union_discriminator/c/dynamic_data_union_example.c | /*******************************************************************************
(c) 2005-2014 Copyright, Real-Time Innovations, Inc. All rights reserved.
RTI grants Licensee a license to use, modify, compile, and create derivative
works of the Software. Licensee has the right to distribute object form only
for use with RTI products. The Software is provided "as is", with no warranty
of any type, including any warranty for fitness for any purpose. RTI is under
no obligation to maintain or support the Software. RTI shall not be liable for
any incidental or consequential damages arising out of the use or inability to
use the software.
******************************************************************************/
/* dynamic_data_union_example.c
This example
- creates the type code of for a union
- creates a DynamicData instance
- sets one of the members of the union
- shows how to retrieve the discriminator
- access to the value of one member of the union
Example:
To run the example application:
On Unix:
objs/<arch>/UnionExample
On Windows:
objs\<arch>\UnionExample
*/
#include "ndds/ndds_c.h"
#include <stdio.h>
#include <stdlib.h>
struct DDS_TypeCode *create_type_code(struct DDS_TypeCodeFactory *factory)
{
struct DDS_TypeCode *unionTC = NULL;
DDS_ExceptionCode_t ex;
/* First, we create the typeCode for a union */
/* Default-member index refers to which member of the union
* will be the default one. In this example index = 1 refers
* to the the member 'aLong'. Take into account that index
* starts in 0 */
unionTC = DDS_TypeCodeFactory_create_union_tc(
factory,
"Foo",
DDS_TypeCodeFactory_get_primitive_tc(factory, DDS_TK_LONG),
1, /* default-member index */
NULL, /* For now, it does not have any member */
&ex);
if (ex != DDS_NO_EXCEPTION_CODE) {
fprintf(stderr, "! Unable to create union TC\n");
goto fail;
}
/* Case 1 will be a short named aShort */
DDS_TypeCode_add_member(
unionTC,
"aShort",
DDS_DYNAMIC_DATA_MEMBER_ID_UNSPECIFIED,
DDS_TypeCodeFactory_get_primitive_tc(factory, DDS_TK_SHORT),
DDS_TYPECODE_NONKEY_MEMBER,
&ex);
if (ex != DDS_NO_EXCEPTION_CODE) {
fprintf(stderr, "! Unable to add member aShort\n");
goto fail;
}
/* Case 2, the default, will be a long named aLong */
DDS_TypeCode_add_member(
unionTC,
"aLong",
2,
DDS_TypeCodeFactory_get_primitive_tc(factory, DDS_TK_LONG),
DDS_TYPECODE_NONKEY_MEMBER,
&ex);
if (ex != DDS_NO_EXCEPTION_CODE) {
fprintf(stderr, "! Unable to add member aLong\n");
goto fail;
}
/* Case 3 will be a double named aDouble */
DDS_TypeCode_add_member(
unionTC,
"aDouble",
3,
DDS_TypeCodeFactory_get_primitive_tc(factory, DDS_TK_DOUBLE),
DDS_TYPECODE_NONKEY_MEMBER,
&ex);
if (ex != DDS_NO_EXCEPTION_CODE) {
fprintf(stderr, "! Unable to add member aDouble\n");
goto fail;
}
return unionTC;
fail:
if (unionTC != NULL) {
DDS_TypeCodeFactory_delete_tc(factory, unionTC, &ex);
}
return NULL;
}
int example()
{
struct DDS_TypeCode *unionTC = NULL;
struct DDS_DynamicData data;
DDS_ReturnCode_t retcode;
struct DDS_DynamicDataMemberInfo info;
struct DDS_TypeCodeFactory *factory = NULL;
int ret = -1;
struct DDS_DynamicDataProperty_t myProperty =
DDS_DYNAMIC_DATA_PROPERTY_DEFAULT;
DDS_Short valueTestShort;
DDS_Boolean dynamicDataIsInitialized = DDS_BOOLEAN_FALSE;
/* Getting a reference to the type code factory */
factory = DDS_TypeCodeFactory_get_instance();
if (factory == NULL) {
fprintf(stderr, "! Unable to get type code factory singleton\n");
goto fail;
}
/* Creating the union typeCode */
unionTC = create_type_code(factory);
if (unionTC == NULL) {
fprintf(stderr, "! Unable to create typeCode\n");
goto fail;
}
/* Creating a new dynamicData instance based on the union type code */
dynamicDataIsInitialized =
DDS_DynamicData_initialize(&data, unionTC, &myProperty);
if (!dynamicDataIsInitialized) {
fprintf(stderr, "! Unable to create dynamicData\n");
goto fail;
}
/* If we get the current discriminator, it will be the default one
(not the first added) */
retcode = DDS_DynamicData_get_member_info_by_index(&data, &info, 0);
if (retcode != DDS_RETCODE_OK) {
fprintf(stderr, "! Unable to get member info\n");
goto fail;
}
printf("The member selected is %s\n", info.member_name);
/* When we set a value in one of the members of the union,
* the discriminator updates automatically to point that member. */
retcode = DDS_DynamicData_set_short(
&data,
"aShort",
DDS_DYNAMIC_DATA_MEMBER_ID_UNSPECIFIED,
42);
if (retcode != DDS_RETCODE_OK) {
fprintf(stderr, "! Unable to set value to aShort member\n");
goto fail;
}
/* The discriminator should now reflect the new situation */
retcode = DDS_DynamicData_get_member_info_by_index(&data, &info, 0);
if (retcode != DDS_RETCODE_OK) {
fprintf(stderr, "! Unable to get member info\n");
goto fail;
}
printf("The member selected is %s\n", info.member_name);
/* Getting the value of the target member */
retcode = DDS_DynamicData_get_short(
&data,
&valueTestShort,
"aShort",
DDS_DYNAMIC_DATA_MEMBER_ID_UNSPECIFIED);
if (retcode != DDS_RETCODE_OK) {
fprintf(stderr, "! Unable to get member value\n");
goto fail;
}
printf("The member selected is %s with value: %d\n",
info.member_name,
valueTestShort);
ret = 1;
fail:
if (unionTC != NULL) {
DDS_TypeCodeFactory_delete_tc(factory, unionTC, NULL);
}
if (dynamicDataIsInitialized) {
DDS_DynamicData_finalize(&data);
}
return ret;
}
int main(int argc, char *argv[])
{
return example();
}
| c |
rticonnextdds-examples | data/projects/rticonnextdds-examples/connext_dds/dynamic_data_access_union_discriminator/c++03/dynamic_data_union_example.cxx | /*******************************************************************************
(c) 2005-2015 Copyright, Real-Time Innovations, Inc. All rights reserved.
RTI grants Licensee a license to use, modify, compile, and create derivative
works of the Software. Licensee has the right to distribute object form only
for use with RTI products. The Software is provided "as is", with no warranty
of any type, including any warranty for fitness for any purpose. RTI is under
no obligation to maintain or support the Software. RTI shall not be liable for
any incidental or consequential damages arising out of the use or inability to
use the software.
******************************************************************************/
#include <cstdlib>
#include <iostream>
#include <dds/dds.hpp>
using namespace dds::core::xtypes;
UnionType create_union_type()
{
// First, we create a DynamicType for a union.
UnionType union_type("Foo", primitive_type<int32_t>());
// Case 1 will be a short named aShort.
union_type.add_member(UnionMember("aShort", primitive_type<short>(), 0));
// Case 2 will be a long named aLong.
union_type.add_member(UnionMember(
"aLong",
primitive_type<int>(),
UnionMember::DEFAULT_LABEL));
// Case 3 will be a double named aDouble.
union_type.add_member(UnionMember("aDouble", primitive_type<double>(), 3));
return union_type;
}
void example()
{
using rti::core::xtypes::DynamicDataMemberInfo;
// Create the type of the union
UnionType union_type = create_union_type();
// Create the DynamicData.
DynamicData union_data(union_type);
// Get the current member, it will be the default one.
union_data.value<int>("aLong", 0);
DynamicDataMemberInfo info =
union_data.member_info(union_data.discriminator_value());
std::cout << "The member selected is " << info.member_name() << std::endl;
// When we set a value in one of the members of the union,
// the discriminator updates automatically to point that member.
union_data.value<short>("aShort", 42);
// The discriminator should now reflect the new situation.
info = union_data.member_info(union_data.discriminator_value());
std::cout << "The member selected is " << info.member_name();
// Getting the value of the target member.
short aShort = union_data.value<short>(union_data.discriminator_value());
std::cout << " with value " << aShort << std::endl;
}
int main(int argc, char *argv[])
{
try {
example();
} catch (const std::exception &ex) {
std::cerr << "Caught exception: " << ex.what() << std::endl;
return -1;
}
return 0;
}
| cxx |
rticonnextdds-examples | data/projects/rticonnextdds-examples/connext_dds/dynamic_data_access_union_discriminator/c++11/dynamic_data_union_example.cxx | /*******************************************************************************
(c) 2005-2015 Copyright, Real-Time Innovations, Inc. All rights reserved.
RTI grants Licensee a license to use, modify, compile, and create derivative
works of the Software. Licensee has the right to distribute object form only
for use with RTI products. The Software is provided "as is", with no warranty
of any type, including any warranty for fitness for any purpose. RTI is under
no obligation to maintain or support the Software. RTI shall not be liable for
any incidental or consequential damages arising out of the use or inability to
use the software.
******************************************************************************/
#include <cstdlib>
#include <iostream>
#include <dds/dds.hpp>
using namespace dds::core::xtypes;
UnionType create_union_type()
{
return UnionType(
"Foo",
primitive_type<int32_t>(),
{ UnionMember("aShort", primitive_type<short>(), 0),
UnionMember(
"aLong",
primitive_type<int>(),
UnionMember::DEFAULT_LABEL),
UnionMember("aDouble", primitive_type<double>(), 3) });
}
void example()
{
// Create the type of the union
UnionType union_type = create_union_type();
// Create the DynamicData.
DynamicData union_data(union_type);
// Get the current member, it will be the default one.
union_data.value<int>("aLong", 0);
auto info = union_data.member_info(union_data.discriminator_value());
std::cout << "The member selected is " << info.member_name() << std::endl;
// When we set a value in one of the members of the union,
// the discriminator updates automatically to point that member.
union_data.value<short>("aShort", 42);
// The discriminator should now reflect the new situation.
info = union_data.member_info(union_data.discriminator_value());
std::cout << "The member selected is " << info.member_name();
// Getting the value of the target member.
short aShort = union_data.value<short>(union_data.discriminator_value());
std::cout << " with value " << aShort << std::endl;
}
int main(int argc, char *argv[])
{
try {
example();
} catch (const std::exception &ex) {
std::cerr << "Caught exception: " << ex.what() << std::endl;
return -1;
}
return 0;
}
| cxx |
rticonnextdds-examples | data/projects/rticonnextdds-examples/connext_dds/fragmented_data_statistics/c++/fragment_subscriber.cxx | /*
* (c) Copyright, Real-Time Innovations, 2021. All rights reserved.
* RTI grants Licensee a license to use, modify, compile, and create derivative
* works of the software solely for use with RTI Connext DDS. Licensee may
* redistribute copies of the software provided that all such copies are subject
* to this license. The software is provided "as is", with no warranty of any
* type, including any warranty for fitness for any purpose. RTI is under no
* obligation to maintain or support the software. RTI shall not be liable for
* any incidental or consequential damages arising out of the use or inability
* to use the software.
*/
#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include "fragment.h"
#include "fragmentSupport.h"
#include "ndds/ndds_cpp.h"
#include "application.h"
using namespace application;
static int shutdown_participant(
DDSDomainParticipant *participant,
const char *shutdown_message,
int status);
// Process data. Returns number of samples processed.
unsigned int process_data(fragmentDataReader *typed_reader)
{
fragmentSeq data_seq; // Sequence of received data
DDS_SampleInfoSeq info_seq; // Metadata associated with samples in data_seq
unsigned int samples_read = 0;
// Take available data from DataReader's queue
typed_reader->take(
data_seq,
info_seq,
DDS_LENGTH_UNLIMITED,
DDS_ANY_SAMPLE_STATE,
DDS_ANY_VIEW_STATE,
DDS_ANY_INSTANCE_STATE);
// Iterate over all available data
for (int i = 0; i < data_seq.length(); ++i) {
// Check if a sample is an instance lifecycle event
if (info_seq[i].valid_data) {
// Print data
std::cout << "Received data" << std::endl;
fragmentTypeSupport::print_data(&data_seq[i]);
samples_read++;
} else { // This is an instance lifecycle event with no data payload.
std::cout << "Received instance state notification" << std::endl;
}
}
// Data loaned from Connext for performance. Return loan when done.
DDS_ReturnCode_t retcode = typed_reader->return_loan(data_seq, info_seq);
if (retcode != DDS_RETCODE_OK) {
std::cerr << "return loan error " << retcode << std::endl;
}
return samples_read;
}
int run_subscriber_application(unsigned int domain_id, unsigned int sample_count)
{
// Start communicating in a domain, usually one participant per application
DDSDomainParticipant *participant =
DDSTheParticipantFactory->create_participant(
domain_id,
DDS_PARTICIPANT_QOS_DEFAULT,
NULL, // listener
DDS_STATUS_MASK_NONE);
if (participant == NULL) {
return shutdown_participant(participant, "create_participant error", EXIT_FAILURE);
}
// A Subscriber allows an application to create one or more DataReaders
DDSSubscriber *subscriber = participant->create_subscriber(
DDS_SUBSCRIBER_QOS_DEFAULT,
NULL, // listener
DDS_STATUS_MASK_NONE);
if (subscriber == NULL) {
return shutdown_participant(participant, "create_subscriber error", EXIT_FAILURE);
}
// Register the datatype to use when creating the Topic
const char *type_name = fragmentTypeSupport::get_type_name();
DDS_ReturnCode_t retcode =
fragmentTypeSupport::register_type(participant, type_name);
if (retcode != DDS_RETCODE_OK) {
return shutdown_participant(participant, "register_type error", EXIT_FAILURE);
}
// Create a Topic with a name and a datatype
DDSTopic *topic = participant->create_topic(
"Example fragment",
type_name,
DDS_TOPIC_QOS_DEFAULT,
NULL, // listener
DDS_STATUS_MASK_NONE);
if (topic == NULL) {
return shutdown_participant(participant, "create_topic error", EXIT_FAILURE);
}
// This DataReader reads data on "Example fragment" Topic
DDSDataReader *untyped_reader = subscriber->create_datareader(
topic,
DDS_DATAREADER_QOS_DEFAULT,
NULL,
DDS_STATUS_MASK_NONE);
if (untyped_reader == NULL) {
return shutdown_participant(participant, "create_datareader error", EXIT_FAILURE);
}
// Narrow casts from a untyped DataReader to a reader of your type
fragmentDataReader *typed_reader =
fragmentDataReader::narrow(untyped_reader);
if (typed_reader == NULL) {
return shutdown_participant(participant, "DataReader narrow error", EXIT_FAILURE);
}
// Create ReadCondition that triggers when unread data in reader's queue
DDSReadCondition *read_condition = typed_reader->create_readcondition(
DDS_NOT_READ_SAMPLE_STATE,
DDS_ANY_VIEW_STATE,
DDS_ANY_INSTANCE_STATE);
if (read_condition == NULL) {
return shutdown_participant(participant, "create_readcondition error", EXIT_FAILURE);
}
// WaitSet will be woken when the attached condition is triggered
DDSWaitSet waitset;
retcode = waitset.attach_condition(read_condition);
if (retcode != DDS_RETCODE_OK) {
return shutdown_participant(participant, "attach_condition error", EXIT_FAILURE);
}
// Main loop. Wait for data to arrive, and process when it arrives
unsigned int samples_read = 0;
DDS_DataReaderProtocolStatus status;
while (!shutdown_requested && samples_read < sample_count) {
DDSConditionSeq active_conditions_seq;
// Wait for data and report if it does not arrive in 1 second
DDS_Duration_t wait_timeout = { 1, 0 };
retcode = waitset.wait(active_conditions_seq, wait_timeout);
if (retcode == DDS_RETCODE_OK) {
// If the read condition is triggered, process data
samples_read += process_data(typed_reader);
} else {
if (retcode == DDS_RETCODE_TIMEOUT) {
std::cout << "No data after 1 second" << std::endl;
}
}
retcode = typed_reader->get_datareader_protocol_status(status);
if (retcode != DDS_RETCODE_OK) {
std::cerr << "get_datareader_protocol_status error " << retcode << std::endl;
}
std::cout << "Fragmented Data Statistics:"
<< "\n\t received_fragment_count "
<< status.received_fragment_count
<< "\n\t dropped_fragment_count "
<< status.dropped_fragment_count
<< "\n\t sent_nack_fragment_count "
<< status.sent_nack_fragment_count
<< "\n\t sent_nack_fragment_bytes "
<< status.sent_nack_fragment_bytes << std::endl;
}
// Cleanup
return shutdown_participant(participant, "Shutting down", 0);
}
// Delete all entities
static int shutdown_participant(
DDSDomainParticipant *participant,
const char *shutdown_message,
int status)
{
DDS_ReturnCode_t retcode;
std::cout << shutdown_message << std::endl;
if (participant != NULL) {
// Cleanup everything created by this Participant
retcode = participant->delete_contained_entities();
if (retcode != DDS_RETCODE_OK) {
std::cerr << "delete_contained_entities error" << retcode
<< std::endl;
status = EXIT_FAILURE;
}
retcode = DDSTheParticipantFactory->delete_participant(participant);
if (retcode != DDS_RETCODE_OK) {
std::cerr << "delete_participant error" << retcode << std::endl;
status = EXIT_FAILURE;
}
}
return status;
}
int main(int argc, char *argv[])
{
// Parse arguments and handle control-C
ApplicationArguments arguments;
parse_arguments(arguments, argc, argv);
if (arguments.parse_result == PARSE_RETURN_EXIT) {
return EXIT_SUCCESS;
} else if (arguments.parse_result == PARSE_RETURN_FAILURE) {
return EXIT_FAILURE;
}
setup_signal_handlers();
// Sets Connext verbosity to help debugging
NDDSConfigLogger::get_instance()->set_verbosity(arguments.verbosity);
int status = run_subscriber_application(arguments.domain_id, arguments.sample_count);
// Releases the memory used by the participant factory. Optional at
// application exit
DDS_ReturnCode_t retcode = DDSDomainParticipantFactory::finalize_instance();
if (retcode != DDS_RETCODE_OK) {
std::cerr << "finalize_instance error" << retcode << std::endl;
status = EXIT_FAILURE;
}
return status;
}
| cxx |
rticonnextdds-examples | data/projects/rticonnextdds-examples/connext_dds/fragmented_data_statistics/c++/fragment_publisher.cxx | /*
* (c) Copyright, Real-Time Innovations, 2021. All rights reserved.
* RTI grants Licensee a license to use, modify, compile, and create derivative
* works of the software solely for use with RTI Connext DDS. Licensee may
* redistribute copies of the software provided that all such copies are subject
* to this license. The software is provided "as is", with no warranty of any
* type, including any warranty for fitness for any purpose. RTI is under no
* obligation to maintain or support the software. RTI shall not be liable for
* any incidental or consequential damages arising out of the use or inability
* to use the software.
*/
#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include "fragment.h"
#include "fragmentSupport.h"
#include "ndds/ndds_cpp.h"
#include "application.h"
using namespace application;
static int shutdown_participant(
DDSDomainParticipant *participant,
const char *shutdown_message,
int status);
int run_publisher_application(unsigned int domain_id, unsigned int sample_count)
{
// Start communicating in a domain, usually one participant per application
DDSDomainParticipant *participant =
DDSTheParticipantFactory->create_participant(
domain_id,
DDS_PARTICIPANT_QOS_DEFAULT,
NULL, // listener
DDS_STATUS_MASK_NONE);
if (participant == NULL) {
return shutdown_participant(participant, "create_participant error", EXIT_FAILURE);
}
// A Publisher allows an application to create one or more DataWriters
DDSPublisher *publisher = participant->create_publisher(
DDS_PUBLISHER_QOS_DEFAULT,
NULL, // listener
DDS_STATUS_MASK_NONE);
if (publisher == NULL) {
return shutdown_participant(participant, "create_publisher error", EXIT_FAILURE);
}
// Register the datatype to use when creating the Topic
const char *type_name = fragmentTypeSupport::get_type_name();
DDS_ReturnCode_t retcode =
fragmentTypeSupport::register_type(participant, type_name);
if (retcode != DDS_RETCODE_OK) {
return shutdown_participant(participant, "register_type error", EXIT_FAILURE);
}
// Create a Topic with a name and a datatype
DDSTopic *topic = participant->create_topic(
"Example fragment",
type_name,
DDS_TOPIC_QOS_DEFAULT,
NULL, // listener
DDS_STATUS_MASK_NONE);
if (topic == NULL) {
return shutdown_participant(participant, "create_topic error", EXIT_FAILURE);
}
// This DataWriter writes data on "Example fragment" Topic
DDSDataWriter *untyped_writer = publisher->create_datawriter(
topic,
DDS_DATAWRITER_QOS_DEFAULT,
NULL, // listener
DDS_STATUS_MASK_NONE);
if (untyped_writer == NULL) {
return shutdown_participant(participant, "create_datawriter error", EXIT_FAILURE);
}
// Narrow casts from an untyped DataWriter to a writer of your type
fragmentDataWriter *typed_writer =
fragmentDataWriter::narrow(untyped_writer);
if (typed_writer == NULL) {
return shutdown_participant(participant, "DataWriter narrow error", EXIT_FAILURE);
}
// Create data for writing, allocating all members
fragment *data = fragmentTypeSupport::create_data();
if (data == NULL) {
return shutdown_participant(
participant,
"fragmentTypeSupport::create_data error",
EXIT_FAILURE);
}
// Create the data to be written, ensuring it is larger than message_size_max */
if (!data->data.ensure_length(8000, 8000)) {
return shutdown_participant(
participant,
"fragmentTypeSupport::create_data error",
EXIT_FAILURE);
}
// Main loop, write data
DDS_DataWriterProtocolStatus status;
for (unsigned int samples_written = 0;
!shutdown_requested && samples_written < sample_count;
++samples_written) {
// Modify the data to be written here
data->x = static_cast<DDS_Long>(samples_written);
std::cout << "Writing fragment, count " << samples_written
<< std::endl;
retcode = typed_writer->write(*data, DDS_HANDLE_NIL);
if (retcode != DDS_RETCODE_OK) {
std::cerr << "write error " << retcode << std::endl;
}
// Send once every second
DDS_Duration_t send_period = { 1, 0 };
NDDSUtility::sleep(send_period);
retcode = typed_writer->get_datawriter_protocol_status(status);
if (retcode != DDS_RETCODE_OK) {
std::cerr << "get_datawriter_protocol_status error " << retcode << std::endl;
}
std::cout << "Fragmented Data Statistics:"
<< "\n\t pushed_fragment_count "
<< status.pushed_fragment_count
<< "\n\t pushed_fragment_bytes "
<< status.pushed_fragment_bytes
<< "\n\t pulled_fragment_count "
<< status.pulled_fragment_count
<< "\n\t pulled_fragment_bytes "
<< status.pulled_fragment_bytes
<< "\n\t received_nack_fragment_count "
<< status.received_nack_fragment_count
<< "\n\t received_nack_fragment_bytes "
<< status.received_nack_fragment_bytes << std::endl;
}
// Delete previously allocated fragment, including all contained elements
retcode = fragmentTypeSupport::delete_data(data);
if (retcode != DDS_RETCODE_OK) {
std::cerr << "fragmentTypeSupport::delete_data error " << retcode
<< std::endl;
}
// Delete all entities (DataWriter, Topic, Publisher, DomainParticipant)
return shutdown_participant(participant, "Shutting down", EXIT_SUCCESS);
}
// Delete all entities
static int shutdown_participant(
DDSDomainParticipant *participant,
const char *shutdown_message,
int status)
{
DDS_ReturnCode_t retcode;
std::cout << shutdown_message << std::endl;
if (participant != NULL) {
// Cleanup everything created by this Participant
retcode = participant->delete_contained_entities();
if (retcode != DDS_RETCODE_OK) {
std::cerr << "delete_contained_entities error " << retcode
<< std::endl;
status = EXIT_FAILURE;
}
retcode = DDSTheParticipantFactory->delete_participant(participant);
if (retcode != DDS_RETCODE_OK) {
std::cerr << "delete_participant error " << retcode << std::endl;
status = EXIT_FAILURE;
}
}
return status;
}
int main(int argc, char *argv[])
{
// Parse arguments and handle control-C
ApplicationArguments arguments;
parse_arguments(arguments, argc, argv);
if (arguments.parse_result == PARSE_RETURN_EXIT) {
return EXIT_SUCCESS;
} else if (arguments.parse_result == PARSE_RETURN_FAILURE) {
return EXIT_FAILURE;
}
setup_signal_handlers();
// Sets Connext verbosity to help debugging
NDDSConfigLogger::get_instance()->set_verbosity(arguments.verbosity);
int status = run_publisher_application(arguments.domain_id, arguments.sample_count);
// Releases the memory used by the participant factory. Optional at
// application exit
DDS_ReturnCode_t retcode = DDSDomainParticipantFactory::finalize_instance();
if (retcode != DDS_RETCODE_OK) {
std::cerr << "finalize_instance error " << retcode << std::endl;
status = EXIT_FAILURE;
}
return status;
}
| cxx |
rticonnextdds-examples | data/projects/rticonnextdds-examples/connext_dds/fragmented_data_statistics/c++/application.h | /*
* (c) Copyright, Real-Time Innovations, 2021. All rights reserved.
* RTI grants Licensee a license to use, modify, compile, and create derivative
* works of the software solely for use with RTI Connext DDS. Licensee may
* redistribute copies of the software provided that all such copies are subject
* to this license. The software is provided "as is", with no warranty of any
* type, including any warranty for fitness for any purpose. RTI is under no
* obligation to maintain or support the software. RTI shall not be liable for
* any incidental or consequential damages arising out of the use or inability
* to use the software.
*/
#ifndef APPLICATION_H
#define APPLICATION_H
#include <iostream>
#include <csignal>
#include <climits>
namespace application {
// Catch control-C and tell application to shut down
bool shutdown_requested = false;
inline void stop_handler(int)
{
shutdown_requested = true;
std::cout << "preparing to shut down..." << std::endl;
}
inline void setup_signal_handlers()
{
signal(SIGINT, stop_handler);
signal(SIGTERM, stop_handler);
}
enum ParseReturn { PARSE_RETURN_OK, PARSE_RETURN_FAILURE, PARSE_RETURN_EXIT };
struct ApplicationArguments {
ParseReturn parse_result;
unsigned int domain_id;
unsigned int sample_count;
NDDS_Config_LogVerbosity verbosity;
};
// Parses application arguments for example. Returns whether to exit.
inline void parse_arguments(
ApplicationArguments& arguments,
int argc,
char *argv[])
{
int arg_processing = 1;
bool show_usage = false;
arguments.domain_id = 0;
arguments.sample_count = INT_MAX;
arguments.verbosity = NDDS_CONFIG_LOG_VERBOSITY_ERROR;
arguments.parse_result = PARSE_RETURN_OK;
while (arg_processing < argc) {
if ((argc > arg_processing + 1)
&& (strcmp(argv[arg_processing], "-d") == 0
|| strcmp(argv[arg_processing], "--domain") == 0)) {
arguments.domain_id = atoi(argv[arg_processing + 1]);
arg_processing += 2;
} else if ((argc > arg_processing + 1)
&& (strcmp(argv[arg_processing], "-s") == 0
|| strcmp(argv[arg_processing], "--sample-count") == 0)) {
arguments.sample_count = atoi(argv[arg_processing + 1]);
arg_processing += 2;
} else if ((argc > arg_processing + 1)
&& (strcmp(argv[arg_processing], "-v") == 0
|| strcmp(argv[arg_processing], "--verbosity") == 0)) {
arguments.verbosity =
(NDDS_Config_LogVerbosity) atoi(argv[arg_processing + 1]);
arg_processing += 2;
} else if (strcmp(argv[arg_processing], "-h") == 0
|| strcmp(argv[arg_processing], "--help") == 0) {
std::cout << "Example application." << std::endl;
show_usage = true;
arguments.parse_result = PARSE_RETURN_EXIT;
break;
} else {
std::cout << "Bad parameter." << std::endl;
show_usage = true;
arguments.parse_result = PARSE_RETURN_FAILURE;
break;
}
}
if (show_usage) {
std::cout << "Usage:\n"\
" -d, --domain <int> Domain ID this application will\n" \
" subscribe in. \n"
" Default: 0\n"\
" -s, --sample_count <int> Number of samples to receive before\n"\
" cleanly shutting down. \n"
" Default: infinite\n"
" -v, --verbosity <int> How much debugging output to show.\n"\
" Range: 0-5 \n"
" Default: 0"
<< std::endl;
}
}
} // namespace application
#endif // APPLICATION_H | h |
rticonnextdds-examples | data/projects/rticonnextdds-examples/connext_dds/fragmented_data_statistics/c++98/fragment_subscriber.cxx | /*
* (c) Copyright, Real-Time Innovations, 2021. All rights reserved.
* RTI grants Licensee a license to use, modify, compile, and create derivative
* works of the software solely for use with RTI Connext DDS. Licensee may
* redistribute copies of the software provided that all such copies are subject
* to this license. The software is provided "as is", with no warranty of any
* type, including any warranty for fitness for any purpose. RTI is under no
* obligation to maintain or support the software. RTI shall not be liable for
* any incidental or consequential damages arising out of the use or inability
* to use the software.
*/
#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include "fragment.h"
#include "fragmentSupport.h"
#include "ndds/ndds_cpp.h"
#include "application.h"
using namespace application;
static int shutdown_participant(
DDSDomainParticipant *participant,
const char *shutdown_message,
int status);
// Process data. Returns number of samples processed.
unsigned int process_data(fragmentDataReader *typed_reader)
{
fragmentSeq data_seq; // Sequence of received data
DDS_SampleInfoSeq info_seq; // Metadata associated with samples in data_seq
unsigned int samples_read = 0;
// Take available data from DataReader's queue
typed_reader->take(
data_seq,
info_seq,
DDS_LENGTH_UNLIMITED,
DDS_ANY_SAMPLE_STATE,
DDS_ANY_VIEW_STATE,
DDS_ANY_INSTANCE_STATE);
// Iterate over all available data
for (int i = 0; i < data_seq.length(); ++i) {
// Check if a sample is an instance lifecycle event
if (info_seq[i].valid_data) {
// Print data
std::cout << "Received data" << std::endl;
fragmentTypeSupport::print_data(&data_seq[i]);
samples_read++;
} else { // This is an instance lifecycle event with no data payload.
std::cout << "Received instance state notification" << std::endl;
}
}
// Data loaned from Connext for performance. Return loan when done.
DDS_ReturnCode_t retcode = typed_reader->return_loan(data_seq, info_seq);
if (retcode != DDS_RETCODE_OK) {
std::cerr << "return loan error " << retcode << std::endl;
}
return samples_read;
}
int run_subscriber_application(
unsigned int domain_id,
unsigned int sample_count)
{
// Start communicating in a domain, usually one participant per application
DDSDomainParticipant *participant =
DDSTheParticipantFactory->create_participant(
domain_id,
DDS_PARTICIPANT_QOS_DEFAULT,
NULL, // listener
DDS_STATUS_MASK_NONE);
if (participant == NULL) {
return shutdown_participant(
participant,
"create_participant error",
EXIT_FAILURE);
}
// A Subscriber allows an application to create one or more DataReaders
DDSSubscriber *subscriber = participant->create_subscriber(
DDS_SUBSCRIBER_QOS_DEFAULT,
NULL, // listener
DDS_STATUS_MASK_NONE);
if (subscriber == NULL) {
return shutdown_participant(
participant,
"create_subscriber error",
EXIT_FAILURE);
}
// Register the datatype to use when creating the Topic
const char *type_name = fragmentTypeSupport::get_type_name();
DDS_ReturnCode_t retcode =
fragmentTypeSupport::register_type(participant, type_name);
if (retcode != DDS_RETCODE_OK) {
return shutdown_participant(
participant,
"register_type error",
EXIT_FAILURE);
}
// Create a Topic with a name and a datatype
DDSTopic *topic = participant->create_topic(
"Example fragment",
type_name,
DDS_TOPIC_QOS_DEFAULT,
NULL, // listener
DDS_STATUS_MASK_NONE);
if (topic == NULL) {
return shutdown_participant(
participant,
"create_topic error",
EXIT_FAILURE);
}
// This DataReader reads data on "Example fragment" Topic
DDSDataReader *untyped_reader = subscriber->create_datareader(
topic,
DDS_DATAREADER_QOS_DEFAULT,
NULL,
DDS_STATUS_MASK_NONE);
if (untyped_reader == NULL) {
return shutdown_participant(
participant,
"create_datareader error",
EXIT_FAILURE);
}
// Narrow casts from a untyped DataReader to a reader of your type
fragmentDataReader *typed_reader =
fragmentDataReader::narrow(untyped_reader);
if (typed_reader == NULL) {
return shutdown_participant(
participant,
"DataReader narrow error",
EXIT_FAILURE);
}
// Create ReadCondition that triggers when unread data in reader's queue
DDSReadCondition *read_condition = typed_reader->create_readcondition(
DDS_NOT_READ_SAMPLE_STATE,
DDS_ANY_VIEW_STATE,
DDS_ANY_INSTANCE_STATE);
if (read_condition == NULL) {
return shutdown_participant(
participant,
"create_readcondition error",
EXIT_FAILURE);
}
// WaitSet will be woken when the attached condition is triggered
DDSWaitSet waitset;
retcode = waitset.attach_condition(read_condition);
if (retcode != DDS_RETCODE_OK) {
return shutdown_participant(
participant,
"attach_condition error",
EXIT_FAILURE);
}
// Main loop. Wait for data to arrive, and process when it arrives
unsigned int samples_read = 0;
DDS_DataReaderProtocolStatus status;
while (!shutdown_requested && samples_read < sample_count) {
DDSConditionSeq active_conditions_seq;
// Wait for data and report if it does not arrive in 1 second
DDS_Duration_t wait_timeout = { 1, 0 };
retcode = waitset.wait(active_conditions_seq, wait_timeout);
if (retcode == DDS_RETCODE_OK) {
// If the read condition is triggered, process data
samples_read += process_data(typed_reader);
} else {
if (retcode == DDS_RETCODE_TIMEOUT) {
std::cout << "No data after 1 second" << std::endl;
}
}
retcode = typed_reader->get_datareader_protocol_status(status);
if (retcode != DDS_RETCODE_OK) {
std::cerr << "get_datareader_protocol_status error " << retcode
<< std::endl;
}
std::cout << "Fragmented Data Statistics:"
<< "\n\t received_fragment_count "
<< status.received_fragment_count
<< "\n\t dropped_fragment_count "
<< status.dropped_fragment_count
<< "\n\t sent_nack_fragment_count "
<< status.sent_nack_fragment_count
<< "\n\t sent_nack_fragment_bytes "
<< status.sent_nack_fragment_bytes << std::endl;
}
// Cleanup
return shutdown_participant(participant, "Shutting down", 0);
}
// Delete all entities
static int shutdown_participant(
DDSDomainParticipant *participant,
const char *shutdown_message,
int status)
{
DDS_ReturnCode_t retcode;
std::cout << shutdown_message << std::endl;
if (participant != NULL) {
// Cleanup everything created by this Participant
retcode = participant->delete_contained_entities();
if (retcode != DDS_RETCODE_OK) {
std::cerr << "delete_contained_entities error" << retcode
<< std::endl;
status = EXIT_FAILURE;
}
retcode = DDSTheParticipantFactory->delete_participant(participant);
if (retcode != DDS_RETCODE_OK) {
std::cerr << "delete_participant error" << retcode << std::endl;
status = EXIT_FAILURE;
}
}
return status;
}
int main(int argc, char *argv[])
{
// Parse arguments and handle control-C
ApplicationArguments arguments;
parse_arguments(arguments, argc, argv);
if (arguments.parse_result == PARSE_RETURN_EXIT) {
return EXIT_SUCCESS;
} else if (arguments.parse_result == PARSE_RETURN_FAILURE) {
return EXIT_FAILURE;
}
setup_signal_handlers();
// Sets Connext verbosity to help debugging
NDDSConfigLogger::get_instance()->set_verbosity(arguments.verbosity);
int status = run_subscriber_application(
arguments.domain_id,
arguments.sample_count);
// Releases the memory used by the participant factory. Optional at
// application exit
DDS_ReturnCode_t retcode = DDSDomainParticipantFactory::finalize_instance();
if (retcode != DDS_RETCODE_OK) {
std::cerr << "finalize_instance error" << retcode << std::endl;
status = EXIT_FAILURE;
}
return status;
}
| cxx |
rticonnextdds-examples | data/projects/rticonnextdds-examples/connext_dds/fragmented_data_statistics/c++98/fragment_publisher.cxx | /*
* (c) Copyright, Real-Time Innovations, 2021. All rights reserved.
* RTI grants Licensee a license to use, modify, compile, and create derivative
* works of the software solely for use with RTI Connext DDS. Licensee may
* redistribute copies of the software provided that all such copies are subject
* to this license. The software is provided "as is", with no warranty of any
* type, including any warranty for fitness for any purpose. RTI is under no
* obligation to maintain or support the software. RTI shall not be liable for
* any incidental or consequential damages arising out of the use or inability
* to use the software.
*/
#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include "fragment.h"
#include "fragmentSupport.h"
#include "ndds/ndds_cpp.h"
#include "application.h"
using namespace application;
static int shutdown_participant(
DDSDomainParticipant *participant,
const char *shutdown_message,
int status);
int run_publisher_application(unsigned int domain_id, unsigned int sample_count)
{
// Start communicating in a domain, usually one participant per application
DDSDomainParticipant *participant =
DDSTheParticipantFactory->create_participant(
domain_id,
DDS_PARTICIPANT_QOS_DEFAULT,
NULL, // listener
DDS_STATUS_MASK_NONE);
if (participant == NULL) {
return shutdown_participant(
participant,
"create_participant error",
EXIT_FAILURE);
}
// A Publisher allows an application to create one or more DataWriters
DDSPublisher *publisher = participant->create_publisher(
DDS_PUBLISHER_QOS_DEFAULT,
NULL, // listener
DDS_STATUS_MASK_NONE);
if (publisher == NULL) {
return shutdown_participant(
participant,
"create_publisher error",
EXIT_FAILURE);
}
// Register the datatype to use when creating the Topic
const char *type_name = fragmentTypeSupport::get_type_name();
DDS_ReturnCode_t retcode =
fragmentTypeSupport::register_type(participant, type_name);
if (retcode != DDS_RETCODE_OK) {
return shutdown_participant(
participant,
"register_type error",
EXIT_FAILURE);
}
// Create a Topic with a name and a datatype
DDSTopic *topic = participant->create_topic(
"Example fragment",
type_name,
DDS_TOPIC_QOS_DEFAULT,
NULL, // listener
DDS_STATUS_MASK_NONE);
if (topic == NULL) {
return shutdown_participant(
participant,
"create_topic error",
EXIT_FAILURE);
}
// This DataWriter writes data on "Example fragment" Topic
DDSDataWriter *untyped_writer = publisher->create_datawriter(
topic,
DDS_DATAWRITER_QOS_DEFAULT,
NULL, // listener
DDS_STATUS_MASK_NONE);
if (untyped_writer == NULL) {
return shutdown_participant(
participant,
"create_datawriter error",
EXIT_FAILURE);
}
// Narrow casts from an untyped DataWriter to a writer of your type
fragmentDataWriter *typed_writer =
fragmentDataWriter::narrow(untyped_writer);
if (typed_writer == NULL) {
return shutdown_participant(
participant,
"DataWriter narrow error",
EXIT_FAILURE);
}
// Create data for writing, allocating all members
fragment *data = fragmentTypeSupport::create_data();
if (data == NULL) {
return shutdown_participant(
participant,
"fragmentTypeSupport::create_data error",
EXIT_FAILURE);
}
// Create the data to be written, ensuring it is larger than
// message_size_max */
if (!data->data.ensure_length(8000, 8000)) {
return shutdown_participant(
participant,
"fragmentTypeSupport::create_data error",
EXIT_FAILURE);
}
// Main loop, write data
DDS_DataWriterProtocolStatus status;
for (unsigned int samples_written = 0;
!shutdown_requested && samples_written < sample_count;
++samples_written) {
// Modify the data to be written here
data->x = static_cast<DDS_Long>(samples_written);
std::cout << "Writing fragment, count " << samples_written << std::endl;
retcode = typed_writer->write(*data, DDS_HANDLE_NIL);
if (retcode != DDS_RETCODE_OK) {
std::cerr << "write error " << retcode << std::endl;
}
// Send once every second
DDS_Duration_t send_period = { 1, 0 };
NDDSUtility::sleep(send_period);
retcode = typed_writer->get_datawriter_protocol_status(status);
if (retcode != DDS_RETCODE_OK) {
std::cerr << "get_datawriter_protocol_status error " << retcode
<< std::endl;
}
std::cout << "Fragmented Data Statistics:"
<< "\n\t pushed_fragment_count "
<< status.pushed_fragment_count
<< "\n\t pushed_fragment_bytes "
<< status.pushed_fragment_bytes
<< "\n\t pulled_fragment_count "
<< status.pulled_fragment_count
<< "\n\t pulled_fragment_bytes "
<< status.pulled_fragment_bytes
<< "\n\t received_nack_fragment_count "
<< status.received_nack_fragment_count
<< "\n\t received_nack_fragment_bytes "
<< status.received_nack_fragment_bytes << std::endl;
}
// Delete previously allocated fragment, including all contained elements
retcode = fragmentTypeSupport::delete_data(data);
if (retcode != DDS_RETCODE_OK) {
std::cerr << "fragmentTypeSupport::delete_data error " << retcode
<< std::endl;
}
// Delete all entities (DataWriter, Topic, Publisher, DomainParticipant)
return shutdown_participant(participant, "Shutting down", EXIT_SUCCESS);
}
// Delete all entities
static int shutdown_participant(
DDSDomainParticipant *participant,
const char *shutdown_message,
int status)
{
DDS_ReturnCode_t retcode;
std::cout << shutdown_message << std::endl;
if (participant != NULL) {
// Cleanup everything created by this Participant
retcode = participant->delete_contained_entities();
if (retcode != DDS_RETCODE_OK) {
std::cerr << "delete_contained_entities error " << retcode
<< std::endl;
status = EXIT_FAILURE;
}
retcode = DDSTheParticipantFactory->delete_participant(participant);
if (retcode != DDS_RETCODE_OK) {
std::cerr << "delete_participant error " << retcode << std::endl;
status = EXIT_FAILURE;
}
}
return status;
}
int main(int argc, char *argv[])
{
// Parse arguments and handle control-C
ApplicationArguments arguments;
parse_arguments(arguments, argc, argv);
if (arguments.parse_result == PARSE_RETURN_EXIT) {
return EXIT_SUCCESS;
} else if (arguments.parse_result == PARSE_RETURN_FAILURE) {
return EXIT_FAILURE;
}
setup_signal_handlers();
// Sets Connext verbosity to help debugging
NDDSConfigLogger::get_instance()->set_verbosity(arguments.verbosity);
int status = run_publisher_application(
arguments.domain_id,
arguments.sample_count);
// Releases the memory used by the participant factory. Optional at
// application exit
DDS_ReturnCode_t retcode = DDSDomainParticipantFactory::finalize_instance();
if (retcode != DDS_RETCODE_OK) {
std::cerr << "finalize_instance error " << retcode << std::endl;
status = EXIT_FAILURE;
}
return status;
}
| cxx |
rticonnextdds-examples | data/projects/rticonnextdds-examples/connext_dds/fragmented_data_statistics/c++98/application.h | /*
* (c) Copyright, Real-Time Innovations, 2021. All rights reserved.
* RTI grants Licensee a license to use, modify, compile, and create derivative
* works of the software solely for use with RTI Connext DDS. Licensee may
* redistribute copies of the software provided that all such copies are subject
* to this license. The software is provided "as is", with no warranty of any
* type, including any warranty for fitness for any purpose. RTI is under no
* obligation to maintain or support the software. RTI shall not be liable for
* any incidental or consequential damages arising out of the use or inability
* to use the software.
*/
#ifndef APPLICATION_H
#define APPLICATION_H
#include <iostream>
#include <csignal>
#include <climits>
namespace application {
// Catch control-C and tell application to shut down
bool shutdown_requested = false;
inline void stop_handler(int)
{
shutdown_requested = true;
std::cout << "preparing to shut down..." << std::endl;
}
inline void setup_signal_handlers()
{
signal(SIGINT, stop_handler);
signal(SIGTERM, stop_handler);
}
enum ParseReturn { PARSE_RETURN_OK, PARSE_RETURN_FAILURE, PARSE_RETURN_EXIT };
struct ApplicationArguments {
ParseReturn parse_result;
unsigned int domain_id;
unsigned int sample_count;
NDDS_Config_LogVerbosity verbosity;
};
// Parses application arguments for example. Returns whether to exit.
inline void parse_arguments(
ApplicationArguments &arguments,
int argc,
char *argv[])
{
int arg_processing = 1;
bool show_usage = false;
arguments.domain_id = 0;
arguments.sample_count = INT_MAX;
arguments.verbosity = NDDS_CONFIG_LOG_VERBOSITY_ERROR;
arguments.parse_result = PARSE_RETURN_OK;
while (arg_processing < argc) {
if ((argc > arg_processing + 1)
&& (strcmp(argv[arg_processing], "-d") == 0
|| strcmp(argv[arg_processing], "--domain") == 0)) {
arguments.domain_id = atoi(argv[arg_processing + 1]);
arg_processing += 2;
} else if (
(argc > arg_processing + 1)
&& (strcmp(argv[arg_processing], "-s") == 0
|| strcmp(argv[arg_processing], "--sample-count") == 0)) {
arguments.sample_count = atoi(argv[arg_processing + 1]);
arg_processing += 2;
} else if (
(argc > arg_processing + 1)
&& (strcmp(argv[arg_processing], "-v") == 0
|| strcmp(argv[arg_processing], "--verbosity") == 0)) {
arguments.verbosity =
(NDDS_Config_LogVerbosity) atoi(argv[arg_processing + 1]);
arg_processing += 2;
} else if (
strcmp(argv[arg_processing], "-h") == 0
|| strcmp(argv[arg_processing], "--help") == 0) {
std::cout << "Example application." << std::endl;
show_usage = true;
arguments.parse_result = PARSE_RETURN_EXIT;
break;
} else {
std::cout << "Bad parameter." << std::endl;
show_usage = true;
arguments.parse_result = PARSE_RETURN_FAILURE;
break;
}
}
if (show_usage) {
std::cout << "Usage:\n"
" -d, --domain <int> Domain ID this "
"application will\n"
" subscribe in. \n"
" Default: 0\n"
" -s, --sample_count <int> Number of samples to "
"receive before\n"
" cleanly shutting down. \n"
" Default: infinite\n"
" -v, --verbosity <int> How much debugging output "
"to show.\n"
" Range: 0-5 \n"
" Default: 0"
<< std::endl;
}
}
} // namespace application
#endif // APPLICATION_H
| h |
rticonnextdds-examples | data/projects/rticonnextdds-examples/connext_dds/fragmented_data_statistics/c/fragment_subscriber.c | /*
* (c) Copyright, Real-Time Innovations, 2021. All rights reserved.
* RTI grants Licensee a license to use, modify, compile, and create derivative
* works of the software solely for use with RTI Connext DDS. Licensee may
* redistribute copies of the software provided that all such copies are subject
* to this license. The software is provided "as is", with no warranty of any
* type, including any warranty for fitness for any purpose. RTI is under no
* obligation to maintain or support the software. RTI shall not be liable for
* any incidental or consequential damages arising out of the use or inability
* to use the software.
*/
/* fragment_subscriber.c
A subscription example
This file is derived from code automatically generated by the rtiddsgen
command:
rtiddsgen -language C -example <arch> fragment.idl
Example subscription of type fragment automatically generated by
'rtiddsgen'. To test it, follow these steps:
(1) Compile this file and the example publication.
(2) Start the subscription on the same domain used for RTI Connext
(3) Start the publication on the same domain used for RTI Connext
(4) [Optional] Specify the list of discovery initial peers and
multicast receive addresses via an environment variable or a file
(in the current working directory) called NDDS_DISCOVERY_PEERS.
You can run any number of publisher and subscriber programs, and can
add and remove them dynamically from the domain.
*/
#include "fragment.h"
#include "fragmentSupport.h"
#include "ndds/ndds_c.h"
#include <stdio.h>
#include <stdlib.h>
void fragmentListener_on_requested_deadline_missed(
void *listener_data,
DDS_DataReader *reader,
const struct DDS_RequestedDeadlineMissedStatus *status)
{
}
void fragmentListener_on_requested_incompatible_qos(
void *listener_data,
DDS_DataReader *reader,
const struct DDS_RequestedIncompatibleQosStatus *status)
{
}
void fragmentListener_on_sample_rejected(
void *listener_data,
DDS_DataReader *reader,
const struct DDS_SampleRejectedStatus *status)
{
}
void fragmentListener_on_liveliness_changed(
void *listener_data,
DDS_DataReader *reader,
const struct DDS_LivelinessChangedStatus *status)
{
}
void fragmentListener_on_sample_lost(
void *listener_data,
DDS_DataReader *reader,
const struct DDS_SampleLostStatus *status)
{
}
void fragmentListener_on_subscription_matched(
void *listener_data,
DDS_DataReader *reader,
const struct DDS_SubscriptionMatchedStatus *status)
{
}
void fragmentListener_on_data_available(
void *listener_data,
DDS_DataReader *reader)
{
fragmentDataReader *fragment_reader = NULL;
struct fragmentSeq data_seq = DDS_SEQUENCE_INITIALIZER;
struct DDS_SampleInfoSeq info_seq = DDS_SEQUENCE_INITIALIZER;
DDS_ReturnCode_t retcode;
int i;
fragment_reader = fragmentDataReader_narrow(reader);
if (fragment_reader == NULL) {
printf("DataReader narrow error\n");
return;
}
retcode = fragmentDataReader_take(
fragment_reader,
&data_seq,
&info_seq,
DDS_LENGTH_UNLIMITED,
DDS_ANY_SAMPLE_STATE,
DDS_ANY_VIEW_STATE,
DDS_ANY_INSTANCE_STATE);
if (retcode == DDS_RETCODE_NO_DATA) {
return;
} else if (retcode != DDS_RETCODE_OK) {
printf("take error %d\n", retcode);
return;
}
for (i = 0; i < fragmentSeq_get_length(&data_seq); ++i) {
if (DDS_SampleInfoSeq_get_reference(&info_seq, i)->valid_data) {
printf("Received data %d\n", fragmentSeq_get_reference(&data_seq, i)->x);
}
}
retcode = fragmentDataReader_return_loan(fragment_reader, &data_seq, &info_seq);
if (retcode != DDS_RETCODE_OK) {
printf("return loan error %d\n", retcode);
}
}
/* Delete all entities */
static int subscriber_shutdown(DDS_DomainParticipant *participant)
{
DDS_ReturnCode_t retcode;
int status = 0;
if (participant != NULL) {
retcode = DDS_DomainParticipant_delete_contained_entities(participant);
if (retcode != DDS_RETCODE_OK) {
printf("delete_contained_entities error %d\n", retcode);
status = -1;
}
retcode = DDS_DomainParticipantFactory_delete_participant(
DDS_TheParticipantFactory,
participant);
if (retcode != DDS_RETCODE_OK) {
printf("delete_participant error %d\n", retcode);
status = -1;
}
}
/* RTI Connext provides the finalize_instance() method on
domain participant factory for users who want to release memory used
by the participant factory. Uncomment the following block of code for
clean destruction of the singleton. */
/*
retcode = DDS_DomainParticipantFactory_finalize_instance();
if (retcode != DDS_RETCODE_OK) {
printf("finalize_instance error %d\n", retcode);
status = -1;
}
*/
return status;
}
static int subscriber_main(int domainId, int sample_count)
{
DDS_DomainParticipant *participant = NULL;
DDS_Subscriber *subscriber = NULL;
DDS_Topic *topic = NULL;
struct DDS_DataReaderListener reader_listener =
DDS_DataReaderListener_INITIALIZER;
DDS_DataReader *reader = NULL;
DDS_ReturnCode_t retcode;
const char *type_name = NULL;
int count = 0;
struct DDS_Duration_t poll_period = { 4, 0 };
struct DDS_DataReaderProtocolStatus protocol_status =
DDS_DataReaderProtocolStatus_INITIALIZER;
/* To customize participant QoS, use
the configuration file USER_QOS_PROFILES.xml */
participant = DDS_DomainParticipantFactory_create_participant(
DDS_TheParticipantFactory,
domainId,
&DDS_PARTICIPANT_QOS_DEFAULT,
NULL /* listener */,
DDS_STATUS_MASK_NONE);
if (participant == NULL) {
printf("create_participant error\n");
subscriber_shutdown(participant);
return -1;
}
/* To customize subscriber QoS, use
the configuration file USER_QOS_PROFILES.xml */
subscriber = DDS_DomainParticipant_create_subscriber(
participant,
&DDS_SUBSCRIBER_QOS_DEFAULT,
NULL /* listener */,
DDS_STATUS_MASK_NONE);
if (subscriber == NULL) {
printf("create_subscriber error\n");
subscriber_shutdown(participant);
return -1;
}
/* Register the type before creating the topic */
type_name = fragmentTypeSupport_get_type_name();
retcode = fragmentTypeSupport_register_type(participant, type_name);
if (retcode != DDS_RETCODE_OK) {
printf("register_type error %d\n", retcode);
subscriber_shutdown(participant);
return -1;
}
/* To customize topic QoS, use
the configuration file USER_QOS_PROFILES.xml */
topic = DDS_DomainParticipant_create_topic(
participant,
"Example fragment",
type_name,
&DDS_TOPIC_QOS_DEFAULT,
NULL /* listener */,
DDS_STATUS_MASK_NONE);
if (topic == NULL) {
printf("create_topic error\n");
subscriber_shutdown(participant);
return -1;
}
/* Set up a data reader listener */
reader_listener.on_requested_deadline_missed =
fragmentListener_on_requested_deadline_missed;
reader_listener.on_requested_incompatible_qos =
fragmentListener_on_requested_incompatible_qos;
reader_listener.on_sample_rejected = fragmentListener_on_sample_rejected;
reader_listener.on_liveliness_changed = fragmentListener_on_liveliness_changed;
reader_listener.on_sample_lost = fragmentListener_on_sample_lost;
reader_listener.on_subscription_matched =
fragmentListener_on_subscription_matched;
reader_listener.on_data_available = fragmentListener_on_data_available;
/* To customize data reader QoS, use
the configuration file USER_QOS_PROFILES.xml */
reader = DDS_Subscriber_create_datareader(
subscriber,
DDS_Topic_as_topicdescription(topic),
&DDS_DATAREADER_QOS_DEFAULT,
&reader_listener,
DDS_STATUS_MASK_ALL);
if (reader == NULL) {
printf("create_datareader error\n");
subscriber_shutdown(participant);
return -1;
}
/* Main loop */
for (count = 0; (sample_count == 0) || (count < sample_count); ++count) {
printf("fragment subscriber sleeping for %d sec...\n", poll_period.sec);
NDDS_Utility_sleep(&poll_period);
retcode = DDS_DataReader_get_datareader_protocol_status(
reader,
&protocol_status);
if (retcode != DDS_RETCODE_OK) {
fprintf(stderr, "get_datareader_protocol_status error\n");
subscriber_shutdown(participant);
return -1;
}
printf("Fragmented Data Statistics:\n"
"\t received_fragment_count %lld\n"
"\t dropped_fragment_count %lld\n"
"\t sent_nack_fragment_count %lld\n"
"\t sent_nack_fragment_bytes %lld\n",
protocol_status.received_fragment_count,
protocol_status.dropped_fragment_count,
protocol_status.sent_nack_fragment_count,
protocol_status.sent_nack_fragment_bytes);
}
/* Cleanup and delete all entities */
return subscriber_shutdown(participant);
}
int main(int argc, char *argv[])
{
int domain_id = 0;
int sample_count = 0; /* infinite loop */
if (argc >= 2) {
domain_id = atoi(argv[1]);
}
if (argc >= 3) {
sample_count = atoi(argv[2]);
}
/* Uncomment this to turn on additional logging
NDDS_Config_Logger_set_verbosity_by_category(
NDDS_Config_Logger_get_instance(),
NDDS_CONFIG_LOG_CATEGORY_API,
NDDS_CONFIG_LOG_VERBOSITY_STATUS_ALL);
*/
return subscriber_main(domain_id, sample_count);
}
| c |
rticonnextdds-examples | data/projects/rticonnextdds-examples/connext_dds/fragmented_data_statistics/c/fragment_publisher.c | /*
* (c) Copyright, Real-Time Innovations, 2021. All rights reserved.
* RTI grants Licensee a license to use, modify, compile, and create derivative
* works of the software solely for use with RTI Connext DDS. Licensee may
* redistribute copies of the software provided that all such copies are subject
* to this license. The software is provided "as is", with no warranty of any
* type, including any warranty for fitness for any purpose. RTI is under no
* obligation to maintain or support the software. RTI shall not be liable for
* any incidental or consequential damages arising out of the use or inability
* to use the software.
*/
/* fragment_publisher.c
A publication of data of type fragment
This file is derived from code automatically generated by the rtiddsgen
command:
rtiddsgen -language C -example <arch> fragment.idl
Example publication of type fragment automatically generated by
'rtiddsgen'. To test it, follow these steps:
(1) Compile this file and the example subscription.
(2) Start the subscription on the same domain used for RTI Connext
(3) Start the publication on the same domain used for RTI Connext
(4) [Optional] Specify the list of discovery initial peers and
multicast receive addresses via an environment variable or a file
(in the current working directory) called NDDS_DISCOVERY_PEERS.
You can run any number of publisher and subscriber programs, and can
add and remove them dynamically from the domain.
*/
#include "fragment.h"
#include "fragmentSupport.h"
#include "ndds/ndds_c.h"
#include <stdio.h>
#include <stdlib.h>
/* Delete all entities */
static int publisher_shutdown(DDS_DomainParticipant *participant)
{
DDS_ReturnCode_t retcode;
int status = 0;
if (participant != NULL) {
retcode = DDS_DomainParticipant_delete_contained_entities(participant);
if (retcode != DDS_RETCODE_OK) {
printf("delete_contained_entities error %d\n", retcode);
status = -1;
}
retcode = DDS_DomainParticipantFactory_delete_participant(
DDS_TheParticipantFactory,
participant);
if (retcode != DDS_RETCODE_OK) {
printf("delete_participant error %d\n", retcode);
status = -1;
}
}
/* RTI Connext provides finalize_instance() method on
domain participant factory for people who want to release memory used
by the participant factory. Uncomment the following block of code for
clean destruction of the singleton. */
/*
retcode = DDS_DomainParticipantFactory_finalize_instance();
if (retcode != DDS_RETCODE_OK) {
printf("finalize_instance error %d\n", retcode);
status = -1;
}
*/
return status;
}
static int publisher_main(int domainId, int sample_count)
{
DDS_DomainParticipant *participant = NULL;
DDS_Publisher *publisher = NULL;
DDS_Topic *topic = NULL;
DDS_DataWriter *writer = NULL;
fragmentDataWriter *fragment_writer = NULL;
fragment *instance = NULL;
DDS_ReturnCode_t retcode;
DDS_InstanceHandle_t instance_handle = DDS_HANDLE_NIL;
const char *type_name = NULL;
int count = 0;
struct DDS_Duration_t send_period = { 0, 100000000 };
struct DDS_DataWriterProtocolStatus protocol_status =
DDS_DataWriterProtocolStatus_INITIALIZER;
/* To customize participant QoS, use
the configuration file USER_QOS_PROFILES.xml */
participant = DDS_DomainParticipantFactory_create_participant(
DDS_TheParticipantFactory,
domainId,
&DDS_PARTICIPANT_QOS_DEFAULT,
NULL /* listener */,
DDS_STATUS_MASK_NONE);
if (participant == NULL) {
printf("create_participant error\n");
publisher_shutdown(participant);
return -1;
}
/* To customize publisher QoS, use
the configuration file USER_QOS_PROFILES.xml */
publisher = DDS_DomainParticipant_create_publisher(
participant,
&DDS_PUBLISHER_QOS_DEFAULT,
NULL /* listener */,
DDS_STATUS_MASK_NONE);
if (publisher == NULL) {
printf("create_publisher error\n");
publisher_shutdown(participant);
return -1;
}
/* Register type before creating topic */
type_name = fragmentTypeSupport_get_type_name();
retcode = fragmentTypeSupport_register_type(participant, type_name);
if (retcode != DDS_RETCODE_OK) {
printf("register_type error %d\n", retcode);
publisher_shutdown(participant);
return -1;
}
/* To customize topic QoS, use
the configuration file USER_QOS_PROFILES.xml */
topic = DDS_DomainParticipant_create_topic(
participant,
"Example fragment",
type_name,
&DDS_TOPIC_QOS_DEFAULT,
NULL /* listener */,
DDS_STATUS_MASK_NONE);
if (topic == NULL) {
printf("create_topic error\n");
publisher_shutdown(participant);
return -1;
}
/* To customize data writer QoS, use
the configuration file USER_QOS_PROFILES.xml */
writer = DDS_Publisher_create_datawriter(
publisher,
topic,
&DDS_DATAWRITER_QOS_DEFAULT,
NULL /* listener */,
DDS_STATUS_MASK_NONE);
if (writer == NULL) {
printf("create_datawriter error\n");
publisher_shutdown(participant);
return -1;
}
fragment_writer = fragmentDataWriter_narrow(writer);
if (fragment_writer == NULL) {
printf("DataWriter narrow error\n");
publisher_shutdown(participant);
return -1;
}
/* Create data sample for writing */
instance = fragmentTypeSupport_create_data_ex(DDS_BOOLEAN_TRUE);
if (instance == NULL) {
printf("fragmentTypeSupport_create_data error\n");
publisher_shutdown(participant);
return -1;
}
/* Create the data to be written, ensuring it is larger than message_size_max */
if (!DDS_OctetSeq_ensure_length(&instance->data, 8000, 8000)) {
printf("DDS_OctetSeq_ensure_length error\n");
publisher_shutdown(participant);
return -1;
}
/* For a data type that has a key, if the same instance is going to be
written multiple times, initialize the key here
and register the keyed instance prior to writing */
/*
instance_handle = fragmentDataWriter_register_instance(
fragment_writer, instance);
*/
/* Main loop */
for (count = 0; (sample_count == 0) || (count < sample_count); ++count) {
printf("Writing fragment, count %d\n", count);
/* Modify the data to be written here */
/* send count as data. */
instance->x = count;
/* Write data */
retcode =
fragmentDataWriter_write(fragment_writer, instance, &instance_handle);
if (retcode != DDS_RETCODE_OK) {
printf("write error %d\n", retcode);
}
NDDS_Utility_sleep(&send_period);
retcode = DDS_DataWriter_get_datawriter_protocol_status(
writer,
&protocol_status);
if (retcode != DDS_RETCODE_OK) {
fprintf(stderr, "get_datawriter_protocol_status error\n");
publisher_shutdown(participant);
return -1;
}
printf("Fragmented Data Statistics:\n"
"\t pushed_fragment_count %lld\n"
"\t pushed_fragment_bytes %lld\n"
"\t pulled_fragment_count %lld\n"
"\t pulled_fragment_bytes %lld\n"
"\t received_nack_fragment_count %lld\n"
"\t received_nack_fragment_bytes %lld\n",
protocol_status.pushed_fragment_count,
protocol_status.pushed_fragment_bytes,
protocol_status.pulled_fragment_count,
protocol_status.pulled_fragment_bytes,
protocol_status.received_nack_fragment_count,
protocol_status.received_nack_fragment_bytes);
}
/*
retcode = fragmentDataWriter_unregister_instance(
fragment_writer, instance, &instance_handle);
if (retcode != DDS_RETCODE_OK) {
printf("unregister instance error %d\n", retcode);
}
*/
/* Delete data sample */
retcode = fragmentTypeSupport_delete_data_ex(instance, DDS_BOOLEAN_TRUE);
if (retcode != DDS_RETCODE_OK) {
printf("fragmentTypeSupport_delete_data error %d\n", retcode);
}
/* Cleanup and delete delete all entities */
return publisher_shutdown(participant);
}
int main(int argc, char *argv[])
{
int domain_id = 0;
int sample_count = 0; /* infinite loop */
if (argc >= 2) {
domain_id = atoi(argv[1]);
}
if (argc >= 3) {
sample_count = atoi(argv[2]);
}
/* Uncomment this to turn on additional logging
NDDS_Config_Logger_set_verbosity_by_category(
NDDS_Config_Logger_get_instance(),
NDDS_CONFIG_LOG_CATEGORY_API,
NDDS_CONFIG_LOG_VERBOSITY_STATUS_ALL);
*/
return publisher_main(domain_id, sample_count);
}
| c |
rticonnextdds-examples | data/projects/rticonnextdds-examples/connext_dds/fragmented_data_statistics/c++11/application.hpp | /*
* (c) Copyright, Real-Time Innovations, 2021. All rights reserved.
* RTI grants Licensee a license to use, modify, compile, and create derivative
* works of the software solely for use with RTI Connext DDS. Licensee may
* redistribute copies of the software provided that all such copies are subject
* to this license. The software is provided "as is", with no warranty of any
* type, including any warranty for fitness for any purpose. RTI is under no
* obligation to maintain or support the software. RTI shall not be liable for
* any incidental or consequential damages arising out of the use or inability
* to use the software.
*/
#ifndef APPLICATION_HPP
#define APPLICATION_HPP
#include <iostream>
#include <csignal>
#include <dds/core/ddscore.hpp>
namespace application {
// Catch control-C and tell application to shut down
bool shutdown_requested = false;
inline void stop_handler(int)
{
shutdown_requested = true;
std::cout << "preparing to shut down..." << std::endl;
}
inline void setup_signal_handlers()
{
signal(SIGINT, stop_handler);
signal(SIGTERM, stop_handler);
}
enum class ParseReturn {
ok,
failure,
exit
};
struct ApplicationArguments {
ParseReturn parse_result;
unsigned int domain_id;
unsigned int sample_count;
rti::config::Verbosity verbosity;
ApplicationArguments(
ParseReturn parse_result_param,
unsigned int domain_id_param,
unsigned int sample_count_param,
rti::config::Verbosity verbosity_param)
: parse_result(parse_result_param),
domain_id(domain_id_param),
sample_count(sample_count_param),
verbosity(verbosity_param) {}
};
// Parses application arguments for example.
inline ApplicationArguments parse_arguments(int argc, char *argv[])
{
int arg_processing = 1;
bool show_usage = false;
ParseReturn parse_result = ParseReturn::ok;
unsigned int domain_id = 0;
unsigned int sample_count = (std::numeric_limits<unsigned int>::max)();
rti::config::Verbosity verbosity(rti::config::Verbosity::EXCEPTION);
while (arg_processing < argc) {
if ((argc > arg_processing + 1)
&& (strcmp(argv[arg_processing], "-d") == 0
|| strcmp(argv[arg_processing], "--domain") == 0)) {
domain_id = atoi(argv[arg_processing + 1]);
arg_processing += 2;
} else if ((argc > arg_processing + 1)
&& (strcmp(argv[arg_processing], "-s") == 0
|| strcmp(argv[arg_processing], "--sample-count") == 0)) {
sample_count = atoi(argv[arg_processing + 1]);
arg_processing += 2;
} else if ((argc > arg_processing + 1)
&& (strcmp(argv[arg_processing], "-v") == 0
|| strcmp(argv[arg_processing], "--verbosity") == 0)) {
verbosity =
static_cast<rti::config::Verbosity::inner_enum>(
atoi(argv[arg_processing + 1]));
arg_processing += 2;
} else if (strcmp(argv[arg_processing], "-h") == 0
|| strcmp(argv[arg_processing], "--help") == 0) {
std::cout << "Example application." << std::endl;
show_usage = true;
parse_result = ParseReturn::exit;
break;
} else {
std::cout << "Bad parameter." << std::endl;
show_usage = true;
parse_result = ParseReturn::failure;
break;
}
}
if (show_usage) {
std::cout << "Usage:\n"\
" -d, --domain <int> Domain ID this application will\n" \
" subscribe in. \n"
" Default: 0\n"\
" -s, --sample_count <int> Number of samples to receive before\n"\
" cleanly shutting down. \n"
" Default: infinite\n"
" -v, --verbosity <int> How much debugging output to show.\n"\
" Range: 0-5 \n"
" Default: 0"
<< std::endl;
}
return ApplicationArguments(parse_result, domain_id, sample_count, verbosity);
}
} // namespace application
#endif // APPLICATION_HPP | hpp |
rticonnextdds-examples | data/projects/rticonnextdds-examples/connext_dds/fragmented_data_statistics/c++11/fragment_subscriber.cxx | /*
* (c) Copyright, Real-Time Innovations, 2021. All rights reserved.
* RTI grants Licensee a license to use, modify, compile, and create derivative
* works of the software solely for use with RTI Connext DDS. Licensee may
* redistribute copies of the software provided that all such copies are subject
* to this license. The software is provided "as is", with no warranty of any
* type, including any warranty for fitness for any purpose. RTI is under no
* obligation to maintain or support the software. RTI shall not be liable for
* any incidental or consequential damages arising out of the use or inability
* to use the software.
*/
#include <algorithm>
#include <iostream>
#include <dds/sub/ddssub.hpp>
#include <dds/core/ddscore.hpp>
#include <rti/config/Logger.hpp> // for logging
// alternatively, to include all the standard APIs:
// <dds/dds.hpp>
// or to include both the standard APIs and extensions:
// <rti/rti.hpp>
//
// For more information about the headers and namespaces, see:
// https://community.rti.com/static/documentation/connext-dds/6.1.0/doc/api/connext_dds/api_cpp2/group__DDSNamespaceModule.html
// For information on how to use extensions, see:
// https://community.rti.com/static/documentation/connext-dds/6.1.0/doc/api/connext_dds/api_cpp2/group__DDSCpp2Conventions.html
#include "fragment.hpp"
#include "application.hpp" // for command line parsing and ctrl-c
int process_data(dds::sub::DataReader<fragment> reader)
{
// Take all samples
int count = 0;
dds::sub::LoanedSamples<fragment> samples = reader.take();
for (const auto& sample : samples) {
if (sample.info().valid()) {
count++;
std::cout << sample.data() << std::endl;
} else {
std::cout << "Instance state changed to "
<< sample.info().state().instance_state() << std::endl;
}
}
return count;
} // The LoanedSamples destructor returns the loan
void run_subscriber_application(unsigned int domain_id, unsigned int sample_count)
{
// DDS objects behave like shared pointers or value types
// (see https://community.rti.com/static/documentation/connext-dds/6.1.0/doc/api/connext_dds/api_cpp2/group__DDSCpp2Conventions.html)
// Start communicating in a domain, usually one participant per application
dds::domain::DomainParticipant participant(domain_id);
// Create a Topic with a name and a datatype
dds::topic::Topic<fragment> topic(participant, "Example fragment");
// Create a Subscriber and DataReader with default Qos
dds::sub::Subscriber subscriber(participant);
dds::sub::DataReader<fragment> reader(subscriber, topic);
// WaitSet will be woken when the attached condition is triggered
dds::core::cond::WaitSet waitset;
// Create a ReadCondition for any data on this reader, and add to WaitSet
unsigned int samples_read = 0;
dds::sub::cond::ReadCondition read_condition(
reader,
dds::sub::status::DataState::any(),
[reader, &samples_read]() {
samples_read += process_data(reader);
});
waitset += read_condition;
rti::core::status::DataReaderProtocolStatus status;
while (!application::shutdown_requested && samples_read < sample_count) {
std::cout << "fragment subscriber sleeping up to 1 sec..." << std::endl;
// Wait for data and report if it does not arrive in 1 second
waitset.dispatch(dds::core::Duration(1));
status = reader->datareader_protocol_status();
std::cout << "Fragmented Data Statistics:"
<< "\n\t received_fragment_count "
<< status.received_fragment_count()
<< "\n\t dropped_fragment_count "
<< status.dropped_fragment_count()
<< "\n\t sent_nack_fragment_count "
<< status.sent_nack_fragment_count()
<< "\n\t sent_nack_fragment_bytes "
<< status.sent_nack_fragment_bytes() << std::endl;
}
}
int main(int argc, char *argv[])
{
using namespace application;
// Parse arguments and handle control-C
auto arguments = parse_arguments(argc, argv);
if (arguments.parse_result == ParseReturn::exit) {
return EXIT_SUCCESS;
} else if (arguments.parse_result == ParseReturn::failure) {
return EXIT_FAILURE;
}
setup_signal_handlers();
// Sets Connext verbosity to help debugging
rti::config::Logger::instance().verbosity(arguments.verbosity);
try {
run_subscriber_application(arguments.domain_id, arguments.sample_count);
} catch (const std::exception& ex) {
// This will catch DDS exceptions
std::cerr << "Exception in run_subscriber_application(): " << ex.what()
<< std::endl;
return EXIT_FAILURE;
}
// Releases the memory used by the participant factory. Optional at
// application exit
dds::domain::DomainParticipant::finalize_participant_factory();
return EXIT_SUCCESS;
}
| cxx |
rticonnextdds-examples | data/projects/rticonnextdds-examples/connext_dds/fragmented_data_statistics/c++11/fragment_publisher.cxx | /*
* (c) Copyright, Real-Time Innovations, 2021. All rights reserved.
* RTI grants Licensee a license to use, modify, compile, and create derivative
* works of the software solely for use with RTI Connext DDS. Licensee may
* redistribute copies of the software provided that all such copies are subject
* to this license. The software is provided "as is", with no warranty of any
* type, including any warranty for fitness for any purpose. RTI is under no
* obligation to maintain or support the software. RTI shall not be liable for
* any incidental or consequential damages arising out of the use or inability
* to use the software.
*/
#include <iostream>
#include <dds/pub/ddspub.hpp>
#include <rti/util/util.hpp> // for sleep()
#include <rti/config/Logger.hpp> // for logging
// alternatively, to include all the standard APIs:
// <dds/dds.hpp>
// or to include both the standard APIs and extensions:
// <rti/rti.hpp>
//
// For more information about the headers and namespaces, see:
// https://community.rti.com/static/documentation/connext-dds/6.1.0/doc/api/connext_dds/api_cpp2/group__DDSNamespaceModule.html
// For information on how to use extensions, see:
// https://community.rti.com/static/documentation/connext-dds/6.1.0/doc/api/connext_dds/api_cpp2/group__DDSCpp2Conventions.html
#include "application.hpp" // for command line parsing and ctrl-c
#include "fragment.hpp"
void run_publisher_application(unsigned int domain_id, unsigned int sample_count)
{
// DDS objects behave like shared pointers or value types
// (see https://community.rti.com/static/documentation/connext-dds/6.1.0/doc/api/connext_dds/api_cpp2/group__DDSCpp2Conventions.html)
// Start communicating in a domain, usually one participant per application
dds::domain::DomainParticipant participant(domain_id);
// Create a Topic with a name and a datatype
dds::topic::Topic<fragment> topic(participant, "Example fragment");
// Create a Publisher
dds::pub::Publisher publisher(participant);
// Create a DataWriter with default QoS
dds::pub::DataWriter<fragment> writer(publisher, topic);
fragment data;
// Create the data to be written, ensuring it is larger than message_size_max */
data.data().resize(8000);
rti::core::status::DataWriterProtocolStatus status;
for (unsigned int samples_written = 0;
!application::shutdown_requested && samples_written < sample_count;
samples_written++) {
// Modify the data to be written here
data.x(static_cast<int32_t>(samples_written));
std::cout << "Writing fragment, count " << samples_written << std::endl;
writer.write(data);
// Send once every second
rti::util::sleep(dds::core::Duration(1));
status = writer->datawriter_protocol_status();
std::cout << "Fragmented Data Statistics:"
<< "\n\t pushed_fragment_count "
<< status.pushed_fragment_count()
<< "\n\t pushed_fragment_bytes "
<< status.pushed_fragment_bytes()
<< "\n\t pulled_fragment_count "
<< status.pulled_fragment_count()
<< "\n\t pulled_fragment_bytes "
<< status.pulled_fragment_bytes()
<< "\n\t received_nack_fragment_count "
<< status.received_nack_fragment_count()
<< "\n\t received_nack_fragment_bytes "
<< status.received_nack_fragment_bytes() << std::endl;
}
}
int main(int argc, char *argv[])
{
using namespace application;
// Parse arguments and handle control-C
auto arguments = parse_arguments(argc, argv);
if (arguments.parse_result == ParseReturn::exit) {
return EXIT_SUCCESS;
} else if (arguments.parse_result == ParseReturn::failure) {
return EXIT_FAILURE;
}
setup_signal_handlers();
// Sets Connext verbosity to help debugging
rti::config::Logger::instance().verbosity(arguments.verbosity);
try {
run_publisher_application(arguments.domain_id, arguments.sample_count);
} catch (const std::exception& ex) {
// This will catch DDS exceptions
std::cerr << "Exception in run_publisher_application(): " << ex.what()
<< std::endl;
return EXIT_FAILURE;
}
// Releases the memory used by the participant factory. Optional at
// application exit
dds::domain::DomainParticipant::finalize_participant_factory();
return EXIT_SUCCESS;
}
| cxx |
rticonnextdds-examples | data/projects/rticonnextdds-examples/connext_dds/using_typecodes/c++/msg_publisher.cxx | /*******************************************************************************
(c) 2005-2014 Copyright, Real-Time Innovations, Inc. All rights reserved.
RTI grants Licensee a license to use, modify, compile, and create derivative
works of the Software. Licensee has the right to distribute object form only
for use with RTI products. The Software is provided "as is", with no warranty
of any type, including any warranty for fitness for any purpose. RTI is under
no obligation to maintain or support the Software. RTI shall not be liable for
any incidental or consequential damages arising out of the use or inability to
use the software.
******************************************************************************/
/* msg_publisher.cxx
A publication of data of type msg
This file is derived from code automatically generated by the rtiddsgen
command:
rtiddsgen -language C++ -example <arch> msg.idl
Example publication of type msg automatically generated by
'rtiddsgen'. To test them follow these steps:
(1) Compile this file and the example subscription.
(2) Start the subscription with the command
objs/<arch>/msg_subscriber <domain_id> <sample_count>
(3) Start the publication with the command
objs/<arch>/msg_publisher <domain_id> <sample_count>
(4) [Optional] Specify the list of discovery initial peers and
multicast receive addresses via an environment variable or a file
(in the current working directory) called NDDS_DISCOVERY_PEERS.
You can run any number of publishers and subscribers programs, and can
add and remove them dynamically from the domain.
Example:
To run the example application on domain <domain_id>:
On Unix:
objs/<arch>/msg_publisher <domain_id> o
objs/<arch>/msg_subscriber <domain_id>
On Windows:
objs\<arch>\msg_publisher <domain_id>
objs\<arch>\msg_subscriber <domain_id>
modification history
------------ -------
*/
#include <stdio.h>
#include <stdlib.h>
#ifdef RTI_VX653
#include <vThreadsData.h>
#endif
#include "msg.h"
#include "msgSupport.h"
#include "ndds/ndds_cpp.h"
/* Delete all entities */
static int publisher_shutdown(DDSDomainParticipant *participant)
{
DDS_ReturnCode_t retcode;
int status = 0;
if (participant != NULL) {
retcode = participant->delete_contained_entities();
if (retcode != DDS_RETCODE_OK) {
printf("delete_contained_entities error %d\n", retcode);
status = -1;
}
retcode = DDSTheParticipantFactory->delete_participant(participant);
if (retcode != DDS_RETCODE_OK) {
printf("delete_participant error %d\n", retcode);
status = -1;
}
}
/* RTI Connext provides finalize_instance() method on
domain participant factory for people who want to release memory used
by the participant factory. Uncomment the following block of code for
clean destruction of the singleton. */
/*
retcode = DDSDomainParticipantFactory::finalize_instance();
if (retcode != DDS_RETCODE_OK) {
printf("finalize_instance error %d\n", retcode);
status = -1;
}
*/
return status;
}
extern "C" int publisher_main(int domainId, int sample_count)
{
DDSDomainParticipant *participant = NULL;
DDSPublisher *publisher = NULL;
DDSTopic *topic = NULL;
DDSDataWriter *writer = NULL;
msgDataWriter *msg_writer = NULL;
msg *instance = NULL;
DDS_ReturnCode_t retcode;
DDS_InstanceHandle_t instance_handle = DDS_HANDLE_NIL;
const char *type_name = NULL;
int count = 0;
/* Send a new sample every 4 seconds */
DDS_Duration_t send_period = { 4, 0 };
/* To customize participant QoS, use
the configuration file USER_QOS_PROFILES.xml */
participant = DDSTheParticipantFactory->create_participant(
domainId,
DDS_PARTICIPANT_QOS_DEFAULT,
NULL,
DDS_STATUS_MASK_NONE);
if (participant == NULL) {
printf("create_participant error\n");
publisher_shutdown(participant);
return -1;
}
/* If you want to change the type_code_max_serialized_length
* programmatically (e.g., to 3070) rather than using the XML file, you
* will need to add the following lines to your code and comment out the
* create_participant call above. */
/*
DDS_DomainParticipantQos participant_qos;
retcode =
DDSTheParticipantFactory->get_default_participant_qos(participant_qos); if
(retcode != DDS_RETCODE_OK) { printf("get_default_participant_qos error\n");
return -1;
}
participant_qos.resource_limits.type_code_max_serialized_length = 3070;
participant = DDSTheParticipantFactory->create_participant(
domainId, participant_qos,
NULL, DDS_STATUS_MASK_NONE);
if (participant == NULL) {
printf("create_participant error\n");
publisher_shutdown(participant);
return -1;
}
*/
/* To customize publisher QoS, use
the configuration file USER_QOS_PROFILES.xml */
publisher = participant->create_publisher(
DDS_PUBLISHER_QOS_DEFAULT,
NULL /* listener */,
DDS_STATUS_MASK_NONE);
if (publisher == NULL) {
printf("create_publisher error\n");
publisher_shutdown(participant);
return -1;
}
/* Register type before creating topic */
type_name = msgTypeSupport::get_type_name();
retcode = msgTypeSupport::register_type(participant, type_name);
if (retcode != DDS_RETCODE_OK) {
printf("register_type error %d\n", retcode);
publisher_shutdown(participant);
return -1;
}
/* To customize topic QoS, use
the configuration file USER_QOS_PROFILES.xml */
topic = participant->create_topic(
"Example msg",
type_name,
DDS_TOPIC_QOS_DEFAULT,
NULL /* listener */,
DDS_STATUS_MASK_NONE);
if (topic == NULL) {
printf("create_topic error\n");
publisher_shutdown(participant);
return -1;
}
/* To customize data writer QoS, use
the configuration file USER_QOS_PROFILES.xml */
writer = publisher->create_datawriter(
topic,
DDS_DATAWRITER_QOS_DEFAULT,
NULL /* listener */,
DDS_STATUS_MASK_NONE);
if (writer == NULL) {
printf("create_datawriter error\n");
publisher_shutdown(participant);
return -1;
}
msg_writer = msgDataWriter::narrow(writer);
if (msg_writer == NULL) {
printf("DataWriter narrow error\n");
publisher_shutdown(participant);
return -1;
}
/* Create data sample for writing */
instance = msgTypeSupport::create_data();
if (instance == NULL) {
printf("msgTypeSupport::create_data error\n");
publisher_shutdown(participant);
return -1;
}
/* For a data type that has a key, if the same instance is going to be
written multiple times, initialize the key here
and register the keyed instance prior to writing */
/*
instance_handle = msg_writer->register_instance(*instance);
*/
/* Main loop */
for (count = 0; (sample_count == 0) || (count < sample_count); ++count) {
printf("Writing msg, count %d\n", count);
/* Modify the data to be sent here */
instance->count = count;
retcode = msg_writer->write(*instance, instance_handle);
if (retcode != DDS_RETCODE_OK) {
printf("write error %d\n", retcode);
}
NDDSUtility::sleep(send_period);
}
/*
retcode = msg_writer->unregister_instance(
*instance, instance_handle);
if (retcode != DDS_RETCODE_OK) {
printf("unregister instance error %d\n", retcode);
}
*/
/* Delete data sample */
retcode = msgTypeSupport::delete_data(instance);
if (retcode != DDS_RETCODE_OK) {
printf("msgTypeSupport::delete_data error %d\n", retcode);
}
/* Delete all entities */
return publisher_shutdown(participant);
}
#if defined(RTI_WINCE)
int wmain(int argc, wchar_t **argv)
{
int domainId = 0;
int sample_count = 0; /* infinite loop */
if (argc >= 2) {
domainId = _wtoi(argv[1]);
}
if (argc >= 3) {
sample_count = _wtoi(argv[2]);
}
/* Uncomment this to turn on additional logging
NDDSConfigLogger::get_instance()->
set_verbosity_by_category(NDDS_CONFIG_LOG_CATEGORY_API,
NDDS_CONFIG_LOG_VERBOSITY_STATUS_ALL);
*/
return publisher_main(domainId, sample_count);
}
#elif !(defined(RTI_VXWORKS) && !defined(__RTP__)) && !defined(RTI_PSOS)
int main(int argc, char *argv[])
{
int domainId = 0;
int sample_count = 0; /* infinite loop */
if (argc >= 2) {
domainId = atoi(argv[1]);
}
if (argc >= 3) {
sample_count = atoi(argv[2]);
}
/* Uncomment this to turn on additional logging
NDDSConfigLogger::get_instance()->
set_verbosity_by_category(NDDS_CONFIG_LOG_CATEGORY_API,
NDDS_CONFIG_LOG_VERBOSITY_STATUS_ALL);
*/
return publisher_main(domainId, sample_count);
}
#endif
#ifdef RTI_VX653
const unsigned char *__ctype = *(__ctypePtrGet());
extern "C" void usrAppInit()
{
#ifdef USER_APPL_INIT
USER_APPL_INIT; /* for backwards compatibility */
#endif
/* add application specific code here */
taskSpawn(
"pub",
RTI_OSAPI_THREAD_PRIORITY_NORMAL,
0x8,
0x150000,
(FUNCPTR) publisher_main,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0);
}
#endif
| cxx |
rticonnextdds-examples | data/projects/rticonnextdds-examples/connext_dds/using_typecodes/c++/msg_subscriber.cxx | /*******************************************************************************
(c) 2005-2014 Copyright, Real-Time Innovations, Inc. All rights reserved.
RTI grants Licensee a license to use, modify, compile, and create derivative
works of the Software. Licensee has the right to distribute object form only
for use with RTI products. The Software is provided "as is", with no warranty
of any type, including any warranty for fitness for any purpose. RTI is under
no obligation to maintain or support the Software. RTI shall not be liable for
any incidental or consequential damages arising out of the use or inability to
use the software.
******************************************************************************/
/* msg_subscriber.cxx
A subscription example
This file is derived from code automatically generated by the rtiddsgen
command:
rtiddsgen -language C++ -example <arch> msg.idl
Example subscription of type msg automatically generated by
'rtiddsgen'. To test them follow these steps:
(1) Compile this file and the example publication.
(2) Start the subscription with the command
objs/<arch>/msg_subscriber <domain_id> <sample_count>
(3) Start the publication with the command
objs/<arch>/msg_publisher <domain_id> <sample_count>
(4) [Optional] Specify the list of discovery initial peers and
multicast receive addresses via an environment variable or a file
(in the current working directory) called NDDS_DISCOVERY_PEERS.
You can run any number of publishers and subscribers programs, and can
add and remove them dynamically from the domain.
Example:
To run the example application on domain <domain_id>:
On Unix:
objs/<arch>/msg_publisher <domain_id>
objs/<arch>/msg_subscriber <domain_id>
On Windows:
objs\<arch>\msg_publisher <domain_id>
objs\<arch>\msg_subscriber <domain_id>
modification history
------------ -------
*/
#include <stdio.h>
#include <stdlib.h>
#ifdef RTI_VX653
#include <vThreadsData.h>
#endif
#include "msg.h"
/* We use the typecode from built-in listeners, so we don't need to include
* this code*/
/*
#include "msgSupport.h"
#include "ndds/ndds_cpp.h"
*/
/* We are going to use the BuiltinPublicationListener_on_data_available
* to detect the topics that are being published on the domain
*
* Once we have detected a new topic, we will print out the Topic Name,
* Participant ID, DataWriter id, and Data Type.
*/
class BuiltinPublicationListener : public DDSDataReaderListener {
public:
virtual void on_data_available(DDSDataReader *reader);
};
void BuiltinPublicationListener::on_data_available(DDSDataReader *reader)
{
DDSPublicationBuiltinTopicDataDataReader *builtin_reader =
(DDSPublicationBuiltinTopicDataDataReader *) reader;
DDS_PublicationBuiltinTopicDataSeq data_seq;
DDS_SampleInfoSeq info_seq;
DDS_ReturnCode_t retcode;
DDS_ExceptionCode_t exception_code;
DDSSubscriber *subscriber = NULL;
DDSDomainParticipant *participant = NULL;
retcode = builtin_reader->take(
data_seq,
info_seq,
DDS_LENGTH_UNLIMITED,
DDS_ANY_SAMPLE_STATE,
DDS_ANY_VIEW_STATE,
DDS_ANY_INSTANCE_STATE);
if (retcode != DDS_RETCODE_OK) {
printf("***Error: failed to access data from the built-in reader\n");
return;
}
for (int i = 0; i < data_seq.length(); ++i) {
if (info_seq[i].valid_data) {
printf("-----\nFound topic \"%s\"\nparticipant: "
"%08x%08x%08x\ndatawriter: %08x%08x%08x\ntype:\n",
data_seq[i].topic_name,
data_seq[i].participant_key.value[0],
data_seq[i].participant_key.value[1],
data_seq[i].participant_key.value[2],
data_seq[i].key.value[0],
data_seq[i].key.value[1],
data_seq[i].key.value[2]);
if (data_seq[i].type_code == NULL) {
printf("No type code received, perhaps increase "
"type_code_max_serialized_length?\n");
continue;
}
/* Using the type_code propagated we print the data type
* with print_IDL(). */
data_seq[i].type_code->print_IDL(2, exception_code);
if (exception_code != DDS_NO_EXCEPTION_CODE) {
printf("Error***: print_IDL returns exception code %d",
exception_code);
}
}
}
builtin_reader->return_loan(data_seq, info_seq);
}
/* Delete all entities */
static int subscriber_shutdown(DDSDomainParticipant *participant)
{
DDS_ReturnCode_t retcode;
int status = 0;
if (participant != NULL) {
retcode = participant->delete_contained_entities();
if (retcode != DDS_RETCODE_OK) {
printf("delete_contained_entities error %d\n", retcode);
status = -1;
}
retcode = DDSTheParticipantFactory->delete_participant(participant);
if (retcode != DDS_RETCODE_OK) {
printf("delete_participant error %d\n", retcode);
status = -1;
}
}
/* RTI Connext provides the finalize_instance() method on
domain participant factory for people who want to release memory used
by the participant factory. Uncomment the following block of code for
clean destruction of the singleton. */
/*
retcode = DDSDomainParticipantFactory::finalize_instance();
if (retcode != DDS_RETCODE_OK) {
printf("finalize_instance error %d\n", retcode);
status = -1;
}
*/
return status;
}
extern "C" int subscriber_main(int domainId, int sample_count)
{
DDSDomainParticipant *participant = NULL;
DDSSubscriber *subscriber = NULL;
DDSTopic *topic = NULL;
DDS_ReturnCode_t retcode;
const char *type_name = NULL;
int count = 0;
struct DDS_Duration_t receive_period = { 1, 0 };
int status = 0;
/* To customize the participant QoS, use
the configuration file USER_QOS_PROFILES.xml */
participant = DDSTheParticipantFactory->create_participant(
domainId,
DDS_PARTICIPANT_QOS_DEFAULT,
NULL,
DDS_STATUS_MASK_NONE);
if (participant == NULL) {
printf("create_participant error\n");
subscriber_shutdown(participant);
return -1;
}
/* If you want to change the type_code_max_serialized_length
* programmatically (e.g., to 3070) rather than using the XML file, you
* will need to add the following lines to your code and comment out the
* create_participant call above. */
/*
DDS_DomainParticipantQos participant_qos;
retcode =
DDSTheParticipantFactory->get_default_participant_qos(participant_qos); if
(retcode != DDS_RETCODE_OK) { printf("get_default_participant_qos error\n");
return -1;
}
participant_qos.resource_limits.type_code_max_serialized_length = 3070;
participant = DDSTheParticipantFactory->create_participant(
domainId, participant_qos,
NULL, DDS_STATUS_MASK_NONE);
if (participant == NULL) {
printf("create_participant error\n");
subscriber_shutdown(participant);
return -1;
}
*/
/* We don't actually care about receiving the samples, just the
topic information. To do this, we only need the builtin
datareader for publications.
*/
/* First get the built-in subscriber */
DDSSubscriber *builtin_subscriber = participant->get_builtin_subscriber();
if (builtin_subscriber == NULL) {
printf("***Error: failed to create builtin subscriber\n");
return 0;
}
/* Then get the data reader for the built-in subscriber */
DDSPublicationBuiltinTopicDataDataReader *builtin_publication_datareader =
(DDSPublicationBuiltinTopicDataDataReader *) builtin_subscriber
->lookup_datareader(DDS_PUBLICATION_TOPIC_NAME);
if (builtin_publication_datareader == NULL) {
printf("***Error: failed to create builtin publication data reader\n");
return 0;
}
/* Finally install the listener */
BuiltinPublicationListener *builtin_publication_listener =
new BuiltinPublicationListener();
builtin_publication_datareader->set_listener(
builtin_publication_listener,
DDS_DATA_AVAILABLE_STATUS);
/* Main loop */
for (count = 0; (sample_count == 0) || (count < sample_count); ++count) {
NDDSUtility::sleep(receive_period);
}
/* Delete all entities */
status = subscriber_shutdown(participant);
return status;
}
#if defined(RTI_WINCE)
int wmain(int argc, wchar_t **argv)
{
int domainId = 0;
int sample_count = 0; /* infinite loop */
if (argc >= 2) {
domainId = _wtoi(argv[1]);
}
if (argc >= 3) {
sample_count = _wtoi(argv[2]);
}
/* Uncomment this to turn on additional logging
NDDSConfigLogger::get_instance()->
set_verbosity_by_category(NDDS_CONFIG_LOG_CATEGORY_API,
NDDS_CONFIG_LOG_VERBOSITY_STATUS_ALL);
*/
return subscriber_main(domainId, sample_count);
}
#elif !(defined(RTI_VXWORKS) && !defined(__RTP__)) && !defined(RTI_PSOS)
int main(int argc, char *argv[])
{
int domainId = 0;
int sample_count = 0; /* infinite loop */
if (argc >= 2) {
domainId = atoi(argv[1]);
}
if (argc >= 3) {
sample_count = atoi(argv[2]);
}
/* Uncomment this to turn on additional logging
NDDSConfigLogger::get_instance()->
set_verbosity_by_category(NDDS_CONFIG_LOG_CATEGORY_API,
NDDS_CONFIG_LOG_VERBOSITY_STATUS_ALL);
*/
return subscriber_main(domainId, sample_count);
}
#endif
#ifdef RTI_VX653
const unsigned char *__ctype = *(__ctypePtrGet());
extern "C" void usrAppInit()
{
#ifdef USER_APPL_INIT
USER_APPL_INIT; /* for backwards compatibility */
#endif
/* add application specific code here */
taskSpawn(
"sub",
RTI_OSAPI_THREAD_PRIORITY_NORMAL,
0x8,
0x150000,
(FUNCPTR) subscriber_main,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0);
}
#endif
| cxx |
rticonnextdds-examples | data/projects/rticonnextdds-examples/connext_dds/using_typecodes/c++98/msg_publisher.cxx | /*******************************************************************************
(c) 2005-2014 Copyright, Real-Time Innovations, Inc. All rights reserved.
RTI grants Licensee a license to use, modify, compile, and create derivative
works of the Software. Licensee has the right to distribute object form only
for use with RTI products. The Software is provided "as is", with no warranty
of any type, including any warranty for fitness for any purpose. RTI is under
no obligation to maintain or support the Software. RTI shall not be liable for
any incidental or consequential damages arising out of the use or inability to
use the software.
******************************************************************************/
#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include "msg.h"
#include "msgSupport.h"
#include "ndds/ndds_cpp.h"
#include "application.h"
using namespace application;
static int shutdown_participant(
DDSDomainParticipant *participant,
const char *shutdown_message,
int status);
int run_publisher_application(unsigned int domain_id, unsigned int sample_count)
{
// Send a new sample every 4 seconds
DDS_Duration_t send_period = { 4, 0 };
// Start communicating in a domain, usually one participant per application
DDSDomainParticipant *participant =
DDSTheParticipantFactory->create_participant(
domain_id,
DDS_PARTICIPANT_QOS_DEFAULT,
NULL,
DDS_STATUS_MASK_NONE);
if (participant == NULL) {
return shutdown_participant(
participant,
"create_participant error",
EXIT_FAILURE);
}
/* If you want to change the type_code_max_serialized_length
* programmatically (e.g., to 3070) rather than using the XML file, you
* will need to add the following lines to your code and comment out the
* create_participant call above. */
/*
DDS_DomainParticipantQos participant_qos;
retcode =
DDSTheParticipantFactory->get_default_participant_qos(participant_qos);
if (retcode != DDS_RETCODE_OK) {
std::cerr << "get_default_participant_qos error\n";
return EXIT_FAILURE;
}
participant_qos.resource_limits.type_code_max_serialized_length = 3070;
DDSDomainParticipant * participant =
DDSTheParticipantFactory->create_participant( domain_id, participant_qos,
NULL,
DDS_STATUS_MASK_NONE);
if (participant == NULL) {
return shutdown_participant(
participant,
"create_participant error",
EXIT_FAILURE);
}
*/
// A Publisher allows an application to create one or more DataWriters
DDSPublisher *publisher = participant->create_publisher(
DDS_PUBLISHER_QOS_DEFAULT,
NULL /* listener */,
DDS_STATUS_MASK_NONE);
if (publisher == NULL) {
return shutdown_participant(
participant,
"create_publisher error",
EXIT_FAILURE);
}
// Register the datatype to use when creating the Topic
const char *type_name = msgTypeSupport::get_type_name();
DDS_ReturnCode_t retcode =
msgTypeSupport::register_type(participant, type_name);
if (retcode != DDS_RETCODE_OK) {
return shutdown_participant(
participant,
"register_type error",
EXIT_FAILURE);
}
// Create a Topic with a name and a datatype
DDSTopic *topic = participant->create_topic(
"Example msg",
type_name,
DDS_TOPIC_QOS_DEFAULT,
NULL /* listener */,
DDS_STATUS_MASK_NONE);
if (topic == NULL) {
return shutdown_participant(
participant,
"create_topic error",
EXIT_FAILURE);
}
// This DataWriter writes data on "Example msg" Topic
DDSDataWriter *untyped_writer = publisher->create_datawriter(
topic,
DDS_DATAWRITER_QOS_DEFAULT,
NULL /* listener */,
DDS_STATUS_MASK_NONE);
if (untyped_writer == NULL) {
return shutdown_participant(
participant,
"create_datawriter error",
EXIT_FAILURE);
}
msgDataWriter *typed_writer = msgDataWriter::narrow(untyped_writer);
if (typed_writer == NULL) {
return shutdown_participant(
participant,
"DataWriter narrow error",
EXIT_FAILURE);
}
// Create data for writing, allocating all members
msg *data = msgTypeSupport::create_data();
if (data == NULL) {
return shutdown_participant(
participant,
"msgTypeSupport::create_data error",
EXIT_FAILURE);
}
DDS_InstanceHandle_t instance_handle = DDS_HANDLE_NIL;
/* For a data type that has a key, if the same instance is going to be
written multiple times, initialize the key here
and register the keyed instance prior to writing */
/*
instance_handle = typed_writer->register_instance(*data);
*/
// Main loop, write data
for (unsigned int samples_written = 0;
!shutdown_requested && samples_written < sample_count;
++samples_written) {
std::cout << "Writing msg, count " << samples_written << std::endl;
// Modify the data to be sent here
data->count = samples_written;
retcode = typed_writer->write(*data, instance_handle);
if (retcode != DDS_RETCODE_OK) {
std::cerr << "write error " << retcode << std::endl;
}
NDDSUtility::sleep(send_period);
}
/*
retcode = typed_writer->unregister_instance(
*data, instance_handle);
if (retcode != DDS_RETCODE_OK) {
std::cerr << "unregister instance error " << retcode << std::endl;
}
*/
/* Delete data sample */
retcode = msgTypeSupport::delete_data(data);
if (retcode != DDS_RETCODE_OK) {
std::cerr << "msgTypeSupport::delete_data error " << retcode
<< std::endl;
}
// Delete all entities (DataWriter, Topic, Publisher, DomainParticipant)
return shutdown_participant(participant, "Shutting down", EXIT_SUCCESS);
}
// Delete all entities
static int shutdown_participant(
DDSDomainParticipant *participant,
const char *shutdown_message,
int status)
{
DDS_ReturnCode_t retcode;
std::cout << shutdown_message << std::endl;
if (participant != NULL) {
// Cleanup everything created by this Participant
retcode = participant->delete_contained_entities();
if (retcode != DDS_RETCODE_OK) {
std::cerr << "delete_contained_entities error " << retcode
<< std::endl;
status = EXIT_FAILURE;
}
retcode = DDSTheParticipantFactory->delete_participant(participant);
if (retcode != DDS_RETCODE_OK) {
std::cerr << "delete_participant error " << retcode << std::endl;
status = EXIT_FAILURE;
}
}
return status;
}
int main(int argc, char *argv[])
{
// Parse arguments and handle control-C
ApplicationArguments arguments;
parse_arguments(arguments, argc, argv, publisher);
if (arguments.parse_result == PARSE_RETURN_EXIT) {
return EXIT_SUCCESS;
} else if (arguments.parse_result == PARSE_RETURN_FAILURE) {
return EXIT_FAILURE;
}
setup_signal_handlers();
// Sets Connext verbosity to help debugging
NDDSConfigLogger::get_instance()->set_verbosity(arguments.verbosity);
int status = run_publisher_application(
arguments.domain_id,
arguments.sample_count);
// Releases the memory used by the participant factory. Optional at
// application exit
DDS_ReturnCode_t retcode = DDSDomainParticipantFactory::finalize_instance();
if (retcode != DDS_RETCODE_OK) {
std::cerr << "finalize_instance error " << retcode << std::endl;
status = EXIT_FAILURE;
}
return status;
}
| cxx |
rticonnextdds-examples | data/projects/rticonnextdds-examples/connext_dds/using_typecodes/c++98/msg_subscriber.cxx | /*******************************************************************************
(c) 2005-2014 Copyright, Real-Time Innovations, Inc. All rights reserved.
RTI grants Licensee a license to use, modify, compile, and create derivative
works of the Software. Licensee has the right to distribute object form only
for use with RTI products. The Software is provided "as is", with no warranty
of any type, including any warranty for fitness for any purpose. RTI is under
no obligation to maintain or support the Software. RTI shall not be liable for
any incidental or consequential damages arising out of the use or inability to
use the software.
******************************************************************************/
#include <iostream>
#include <iomanip>
#include <stdio.h>
#include <stdlib.h>
#include "msg.h"
#include "application.h"
/* We use the typecode from built-in listeners, so we don't need to include
* this code*/
/*
#include "msgSupport.h"
#include "ndds/ndds_cpp.h"
*/
/* We are going to use the BuiltinPublicationListener_on_data_available
* to detect the topics that are being published on the domain
*
* Once we have detected a new topic, we will print out the Topic Name,
* Participant ID, DataWriter id, and Data Type.
*/
using namespace application;
static int shutdown_participant(
DDSDomainParticipant *participant,
const char *shutdown_message,
int status);
class BuiltinPublicationListener : public DDSDataReaderListener {
public:
virtual void on_data_available(DDSDataReader *reader);
};
void BuiltinPublicationListener::on_data_available(DDSDataReader *reader)
{
DDSPublicationBuiltinTopicDataDataReader *builtin_reader =
(DDSPublicationBuiltinTopicDataDataReader *) reader;
DDS_PublicationBuiltinTopicDataSeq data_seq;
DDS_SampleInfoSeq info_seq;
DDS_ReturnCode_t retcode;
DDS_ExceptionCode_t exception_code;
DDSSubscriber *subscriber = NULL;
DDSDomainParticipant *participant = NULL;
retcode = builtin_reader->take(
data_seq,
info_seq,
DDS_LENGTH_UNLIMITED,
DDS_ANY_SAMPLE_STATE,
DDS_ANY_VIEW_STATE,
DDS_ANY_INSTANCE_STATE);
if (retcode != DDS_RETCODE_OK) {
printf("***Error: failed to access data from the built-in reader\n");
return;
}
std::cout << std::hex << std::setw(8) << std::setfill('0');
for (int i = 0; i < data_seq.length(); ++i) {
if (info_seq[i].valid_data) {
std::cout << "-----\nFound topic \"" << data_seq[i].topic_name
<< "\"\nparticipant: "
<< data_seq[i].participant_key.value[0]
<< data_seq[i].participant_key.value[1]
<< data_seq[i].participant_key.value[2]
<< "\ndatawriter: " << data_seq[i].key.value[0]
<< data_seq[i].key.value[1] << data_seq[i].key.value[2]
<< "\ntype:\n";
if (data_seq[i].type_code == NULL) {
std::cerr << "No type code received, perhaps increase "
"type_code_max_serialized_length?\n";
continue;
}
/* Using the type_code propagated we print the data type
* with print_IDL(). */
data_seq[i].type_code->print_IDL(2, exception_code);
if (exception_code != DDS_NO_EXCEPTION_CODE) {
std::cerr << "print_IDL returns exception code "
<< exception_code << std::endl;
}
}
}
builtin_reader->return_loan(data_seq, info_seq);
}
int run_subscriber_application(
unsigned int domain_id,
unsigned int sample_count)
{
struct DDS_Duration_t receive_period = { 1, 0 };
// Start communicating in a domain, usually one participant per application
DDSDomainParticipant *participant =
DDSTheParticipantFactory->create_participant(
domain_id,
DDS_PARTICIPANT_QOS_DEFAULT,
NULL,
DDS_STATUS_MASK_NONE);
if (participant == NULL) {
return shutdown_participant(
participant,
"create_participant error",
EXIT_FAILURE);
}
/* If you want to change the type_code_max_serialized_length
* programmatically (e.g., to 3070) rather than using the XML file, you
* will need to add the following lines to your code and comment out the
* create_participant call above. */
/*
DDS_DomainParticipantQos participant_qos;
retcode =
DDSTheParticipantFactory->get_default_participant_qos(participant_qos);
if (retcode != DDS_RETCODE_OK) {
std::cerr << "get_default_participant_qos error\n";
return EXIT_FAILURE;
}
participant_qos.resource_limits.type_code_max_serialized_length = 3070;
DDSDomainParticipant *participant =
DDSTheParticipantFactory->create_participant( domain_id, participant_qos,
NULL,
DDS_STATUS_MASK_NONE);
if (participant == NULL) {
return shutdown_participant(
participant,
"create_participant error",
EXIT_FAILURE);
}
*/
/* We don't actually care about receiving the samples, just the
topic information. To do this, we only need the builtin
datareader for publications.
*/
// First get the built-in subscriber
DDSSubscriber *builtin_subscriber = participant->get_builtin_subscriber();
if (builtin_subscriber == NULL) {
return shutdown_participant(
participant,
"Failed to create builtin subscriber",
EXIT_FAILURE);
}
// Then get the data reader for the built-in subscriber
DDSPublicationBuiltinTopicDataDataReader *builtin_publication_datareader =
(DDSPublicationBuiltinTopicDataDataReader *) builtin_subscriber
->lookup_datareader(DDS_PUBLICATION_TOPIC_NAME);
if (builtin_publication_datareader == NULL) {
return shutdown_participant(
participant,
"Failed to create builtin publication data reader",
EXIT_FAILURE);
}
// Finally install the listener
BuiltinPublicationListener *builtin_publication_listener =
new BuiltinPublicationListener();
builtin_publication_datareader->set_listener(
builtin_publication_listener,
DDS_DATA_AVAILABLE_STATUS);
// Main loop. Wait for data to arrive, and process when it arrives
// Main loop, write data
for (unsigned int count = 0; !shutdown_requested && count < sample_count;
++count) {
NDDSUtility::sleep(receive_period);
}
// Cleanup
return shutdown_participant(participant, "Shutting down", 0);
}
// Delete all entities
static int shutdown_participant(
DDSDomainParticipant *participant,
const char *shutdown_message,
int status)
{
DDS_ReturnCode_t retcode;
std::cout << shutdown_message << std::endl;
if (participant != NULL) {
// Cleanup everything created by this Participant
retcode = participant->delete_contained_entities();
if (retcode != DDS_RETCODE_OK) {
std::cerr << "delete_contained_entities error" << retcode
<< std::endl;
status = EXIT_FAILURE;
}
retcode = DDSTheParticipantFactory->delete_participant(participant);
if (retcode != DDS_RETCODE_OK) {
std::cerr << "delete_participant error" << retcode << std::endl;
status = EXIT_FAILURE;
}
}
return status;
}
int main(int argc, char *argv[])
{
// Parse arguments and handle control-C
ApplicationArguments arguments;
parse_arguments(arguments, argc, argv, subscriber);
if (arguments.parse_result == PARSE_RETURN_EXIT) {
return EXIT_SUCCESS;
} else if (arguments.parse_result == PARSE_RETURN_FAILURE) {
return EXIT_FAILURE;
}
setup_signal_handlers();
// Sets Connext verbosity to help debugging
NDDSConfigLogger::get_instance()->set_verbosity(arguments.verbosity);
int status = run_subscriber_application(
arguments.domain_id,
arguments.sample_count);
// Releases the memory used by the participant factory. Optional at
// application exit
DDS_ReturnCode_t retcode = DDSDomainParticipantFactory::finalize_instance();
if (retcode != DDS_RETCODE_OK) {
std::cerr << "finalize_instance error" << retcode << std::endl;
status = EXIT_FAILURE;
}
return status;
}
| cxx |
rticonnextdds-examples | data/projects/rticonnextdds-examples/connext_dds/using_typecodes/c++98/application.h | /*
* (c) Copyright, Real-Time Innovations, 2020. All rights reserved.
* RTI grants Licensee a license to use, modify, compile, and create derivative
* works of the software solely for use with RTI Connext DDS. Licensee may
* redistribute copies of the software provided that all such copies are subject
* to this license. The software is provided "as is", with no warranty of any
* type, including any warranty for fitness for any purpose. RTI is under no
* obligation to maintain or support the software. RTI shall not be liable for
* any incidental or consequential damages arising out of the use or inability
* to use the software.
*/
#ifndef APPLICATION_H
#define APPLICATION_H
#include <iostream>
#include <csignal>
#include <climits>
namespace application {
// Catch control-C and tell application to shut down
bool shutdown_requested = false;
inline void stop_handler(int)
{
shutdown_requested = true;
std::cout << "preparing to shut down..." << std::endl;
}
inline void setup_signal_handlers()
{
signal(SIGINT, stop_handler);
signal(SIGTERM, stop_handler);
}
enum ParseReturn { PARSE_RETURN_OK, PARSE_RETURN_FAILURE, PARSE_RETURN_EXIT };
enum ApplicationKind { publisher, subscriber };
struct ApplicationArguments {
ParseReturn parse_result;
unsigned int domain_id;
unsigned int sample_count;
NDDS_Config_LogVerbosity verbosity;
};
inline void set_verbosity(ApplicationArguments &arguments, int verbosity)
{
switch (verbosity) {
case 0:
arguments.verbosity = NDDS_CONFIG_LOG_VERBOSITY_SILENT;
break;
case 1:
arguments.verbosity = NDDS_CONFIG_LOG_VERBOSITY_ERROR;
break;
case 2:
arguments.verbosity = NDDS_CONFIG_LOG_VERBOSITY_WARNING;
break;
case 3:
arguments.verbosity = NDDS_CONFIG_LOG_VERBOSITY_STATUS_ALL;
break;
default:
arguments.verbosity = NDDS_CONFIG_LOG_VERBOSITY_ERROR;
break;
}
}
// Parses application arguments for example. Returns whether to exit.
inline void parse_arguments(
ApplicationArguments &arguments,
int argc,
char *argv[],
ApplicationKind current_application)
{
int arg_processing = 1;
bool show_usage = false;
arguments.domain_id = 0;
arguments.sample_count = INT_MAX;
arguments.verbosity = NDDS_CONFIG_LOG_VERBOSITY_ERROR;
arguments.parse_result = PARSE_RETURN_OK;
while (arg_processing < argc) {
if ((argc > arg_processing + 1)
&& (strcmp(argv[arg_processing], "-d") == 0
|| strcmp(argv[arg_processing], "--domain") == 0)) {
arguments.domain_id = atoi(argv[arg_processing + 1]);
arg_processing += 2;
} else if (
(argc > arg_processing + 1)
&& (strcmp(argv[arg_processing], "-s") == 0
|| strcmp(argv[arg_processing], "--sample-count") == 0
|| strcmp(argv[arg_processing], "--sleep-periods") == 0)) {
arguments.sample_count = atoi(argv[arg_processing + 1]);
arg_processing += 2;
} else if (
(argc > arg_processing + 1)
&& (strcmp(argv[arg_processing], "-v") == 0
|| strcmp(argv[arg_processing], "--verbosity") == 0)) {
set_verbosity(arguments, atoi(argv[arg_processing + 1]));
arg_processing += 2;
} else if (
strcmp(argv[arg_processing], "-h") == 0
|| strcmp(argv[arg_processing], "--help") == 0) {
std::cout << "Example application." << std::endl;
show_usage = true;
arguments.parse_result = PARSE_RETURN_EXIT;
break;
} else {
std::cout << "Bad parameter." << std::endl;
show_usage = true;
arguments.parse_result = PARSE_RETURN_FAILURE;
break;
}
}
if (show_usage) {
std::cout << "Usage:\n"
" -d, --domain <int> Domain ID this "
"application will\n"
" subscribe in. \n"
" Default: 0\n";
if (current_application == publisher) {
std::cout << " -s, --sample-count <int> Number of samples to "
"receive before\n"
" cleanly shutting "
"down. \n"
" Default: infinite\n";
} else if (current_application == subscriber) {
std::cout << " -s, --sleep-periods <int> Number of sleeps "
"before cleanly\n"
" shutting down. \n"
" Default: infinite\n";
}
std::cout << " -v, --verbosity <int> How much debugging output "
"to show.\n"
" Range: 0-3 \n"
" Default: 1"
<< std::endl;
}
}
} // namespace application
#endif // APPLICATION_H
| h |
rticonnextdds-examples | data/projects/rticonnextdds-examples/connext_dds/using_typecodes/c/msg_publisher.c | /*******************************************************************************
(c) 2005-2014 Copyright, Real-Time Innovations, Inc. All rights reserved.
RTI grants Licensee a license to use, modify, compile, and create derivative
works of the Software. Licensee has the right to distribute object form only
for use with RTI products. The Software is provided "as is", with no warranty
of any type, including any warranty for fitness for any purpose. RTI is under
no obligation to maintain or support the Software. RTI shall not be liable for
any incidental or consequential damages arising out of the use or inability to
use the software.
******************************************************************************/
/* msg_publisher.c
A publication of data of type msg
This file is derived from code automatically generated by the rtiddsgen
command:
rtiddsgen -language C -example <arch> msg.idl
Example publication of type msg automatically generated by
'rtiddsgen'. To test them follow these steps:
(1) Compile this file and the example subscription.
(2) Start the subscription with the command
objs/<arch>/msg_subscriber <domain_id> <sample_count>
(3) Start the publication with the command
objs/<arch>/msg_publisher <domain_id> <sample_count>
(4) [Optional] Specify the list of discovery initial peers and
multicast receive addresses via an environment variable or a file
(in the current working directory) called NDDS_DISCOVERY_PEERS.
You can run any number of publishers and subscribers programs, and can
add and remove them dynamically from the domain.
Example:
To run the example application on domain <domain_id>:
On Unix:
objs/<arch>/msg_publisher <domain_id>
objs/<arch>/msg_subscriber <domain_id>
On Windows:
objs\<arch>\msg_publisher <domain_id>
objs\<arch>\msg_subscriber <domain_id>
modification history
------------ -------
*/
#include "msg.h"
#include "msgSupport.h"
#include "ndds/ndds_c.h"
#include <stdio.h>
#include <stdlib.h>
/* Delete all entities */
static int publisher_shutdown(DDS_DomainParticipant *participant)
{
DDS_ReturnCode_t retcode;
int status = 0;
if (participant != NULL) {
retcode = DDS_DomainParticipant_delete_contained_entities(participant);
if (retcode != DDS_RETCODE_OK) {
printf("delete_contained_entities error %d\n", retcode);
status = -1;
}
retcode = DDS_DomainParticipantFactory_delete_participant(
DDS_TheParticipantFactory,
participant);
if (retcode != DDS_RETCODE_OK) {
printf("delete_participant error %d\n", retcode);
status = -1;
}
}
/* RTI Connext provides finalize_instance() method on
domain participant factory for people who want to release memory used
by the participant factory. Uncomment the following block of code for
clean destruction of the singleton. */
/*
retcode = DDS_DomainParticipantFactory_finalize_instance();
if (retcode != DDS_RETCODE_OK) {
printf("finalize_instance error %d\n", retcode);
status = -1;
}
*/
return status;
}
static int publisher_main(int domainId, int sample_count)
{
DDS_DomainParticipant *participant = NULL;
DDS_Publisher *publisher = NULL;
DDS_Topic *topic = NULL;
DDS_DataWriter *writer = NULL;
msgDataWriter *msg_writer = NULL;
msg *instance = NULL;
DDS_ReturnCode_t retcode;
DDS_InstanceHandle_t instance_handle = DDS_HANDLE_NIL;
const char *type_name = NULL;
int count = 0;
/* Send a new sample every 4 seconds */
struct DDS_Duration_t send_period = { 4, 0 };
/* If you want to change the type_code_max_serialized_length
* programmatically (e.g., to 3070) rather than using the XML file, you
* will need to add the following lines to your code and comment out the
* create_participant call bellow. */
/*
struct DDS_DomainParticipantQos participant_qos =
DDS_DomainParticipantQos_INITIALIZER;
retcode = DDS_DomainParticipantFactory_get_default_participant_qos(
DDS_TheParticipantFactory, &participant_qos);
if (retcode != DDS_RETCODE_OK) {
printf("get_default_participant_qos error\n");
return -1;
}
participant_qos.resource_limits.type_code_max_serialized_length = 3070;
participant = DDS_DomainParticipantFactory_create_participant(
DDS_TheParticipantFactory, domainId, &participant_qos,
NULL, DDS_STATUS_MASK_NONE);
if (participant == NULL) {
printf("create_participant error\n");
publisher_shutdown(participant);
return -1;
}
*/
/* To customize participant QoS, use
the configuration file USER_QOS_PROFILES.xml */
participant = DDS_DomainParticipantFactory_create_participant(
DDS_TheParticipantFactory,
domainId,
&DDS_PARTICIPANT_QOS_DEFAULT,
NULL,
DDS_STATUS_MASK_NONE);
if (participant == NULL) {
printf("create_participant error\n");
publisher_shutdown(participant);
return -1;
}
/* To customize publisher QoS, use
the configuration file USER_QOS_PROFILES.xml */
publisher = DDS_DomainParticipant_create_publisher(
participant,
&DDS_PUBLISHER_QOS_DEFAULT,
NULL /* listener */,
DDS_STATUS_MASK_NONE);
if (publisher == NULL) {
printf("create_publisher error\n");
publisher_shutdown(participant);
return -1;
}
/* Register type before creating topic */
type_name = msgTypeSupport_get_type_name();
retcode = msgTypeSupport_register_type(participant, type_name);
if (retcode != DDS_RETCODE_OK) {
printf("register_type error %d\n", retcode);
publisher_shutdown(participant);
return -1;
}
/* To customize topic QoS, use
the configuration file USER_QOS_PROFILES.xml */
topic = DDS_DomainParticipant_create_topic(
participant,
"Example msg",
type_name,
&DDS_TOPIC_QOS_DEFAULT,
NULL /* listener */,
DDS_STATUS_MASK_NONE);
if (topic == NULL) {
printf("create_topic error\n");
publisher_shutdown(participant);
return -1;
}
/* To customize data writer QoS, use
the configuration file USER_QOS_PROFILES.xml */
writer = DDS_Publisher_create_datawriter(
publisher,
topic,
&DDS_DATAWRITER_QOS_DEFAULT,
NULL /* listener */,
DDS_STATUS_MASK_NONE);
if (writer == NULL) {
printf("create_datawriter error\n");
publisher_shutdown(participant);
return -1;
}
msg_writer = msgDataWriter_narrow(writer);
if (msg_writer == NULL) {
printf("DataWriter narrow error\n");
publisher_shutdown(participant);
return -1;
}
/* Create data sample for writing */
instance = msgTypeSupport_create_data_ex(DDS_BOOLEAN_TRUE);
if (instance == NULL) {
printf("msgTypeSupport_create_data error\n");
publisher_shutdown(participant);
return -1;
}
/* For a data type that has a key, if the same instance is going to be
written multiple times, initialize the key here
and register the keyed instance prior to writing */
/*
instance_handle = msgDataWriter_register_instance(
msg_writer, instance);
*/
/* Main loop */
for (count = 0; (sample_count == 0) || (count < sample_count); ++count) {
printf("Writing msg, count %d\n", count);
/* Modify the data to be written here */
instance->count = count;
/* Write data */
retcode = msgDataWriter_write(msg_writer, instance, &instance_handle);
if (retcode != DDS_RETCODE_OK) {
printf("write error %d\n", retcode);
}
NDDS_Utility_sleep(&send_period);
}
/*
retcode = msgDataWriter_unregister_instance(
msg_writer, instance, &instance_handle);
if (retcode != DDS_RETCODE_OK) {
printf("unregister instance error %d\n", retcode);
}
*/
/* Delete data sample */
retcode = msgTypeSupport_delete_data_ex(instance, DDS_BOOLEAN_TRUE);
if (retcode != DDS_RETCODE_OK) {
printf("msgTypeSupport_delete_data error %d\n", retcode);
}
/* Cleanup and delete delete all entities */
return publisher_shutdown(participant);
}
#if defined(RTI_WINCE)
int wmain(int argc, wchar_t **argv)
{
int domainId = 0;
int sample_count = 0; /* infinite loop */
if (argc >= 2) {
domainId = _wtoi(argv[1]);
}
if (argc >= 3) {
sample_count = _wtoi(argv[2]);
}
/* Uncomment this to turn on additional logging
NDDS_Config_Logger_set_verbosity_by_category(
NDDS_Config_Logger_get_instance(),
NDDS_CONFIG_LOG_CATEGORY_API,
NDDS_CONFIG_LOG_VERBOSITY_STATUS_ALL);
*/
return publisher_main(domainId, sample_count);
}
#elif !(defined(RTI_VXWORKS) && !defined(__RTP__)) && !defined(RTI_PSOS)
int main(int argc, char *argv[])
{
int domainId = 0;
int sample_count = 0; /* infinite loop */
if (argc >= 2) {
domainId = atoi(argv[1]);
}
if (argc >= 3) {
sample_count = atoi(argv[2]);
}
/* Uncomment this to turn on additional logging
NDDS_Config_Logger_set_verbosity_by_category(
NDDS_Config_Logger_get_instance(),
NDDS_CONFIG_LOG_CATEGORY_API,
NDDS_CONFIG_LOG_VERBOSITY_STATUS_ALL);
*/
return publisher_main(domainId, sample_count);
}
#endif
#ifdef RTI_VX653
const unsigned char *__ctype = NULL;
void usrAppInit()
{
#ifdef USER_APPL_INIT
USER_APPL_INIT; /* for backwards compatibility */
#endif
/* add application specific code here */
taskSpawn(
"pub",
RTI_OSAPI_THREAD_PRIORITY_NORMAL,
0x8,
0x150000,
(FUNCPTR) publisher_main,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0);
}
#endif
| c |
rticonnextdds-examples | data/projects/rticonnextdds-examples/connext_dds/using_typecodes/c/msg_subscriber.c | /*******************************************************************************
(c) 2005-2014 Copyright, Real-Time Innovations, Inc. All rights reserved.
RTI grants Licensee a license to use, modify, compile, and create derivative
works of the Software. Licensee has the right to distribute object form only
for use with RTI products. The Software is provided "as is", with no warranty
of any type, including any warranty for fitness for any purpose. RTI is under
no obligation to maintain or support the Software. RTI shall not be liable for
any incidental or consequential damages arising out of the use or inability to
use the software.
******************************************************************************/
/* msg_subscriber.c
A subscription example
This file is derived from code automatically generated by the rtiddsgen
command:
rtiddsgen -language C -example <arch> msg.idl
Example subscription of type msg automatically generated by
'rtiddsgen'. To test them, follow these steps:
(1) Compile this file and the example publication.
(2) Start the subscription with the command
objs/<arch>/msg_subscriber <domain_id> <sample_count>
(3) Start the publication with the command
objs/<arch>/msg_publisher <domain_id> <sample_count>
(4) [Optional] Specify the list of discovery initial peers and
multicast receive addresses via an environment variable or a file
(in the current working directory) called NDDS_DISCOVERY_PEERS.
You can run any number of publishers and subscribers programs, and can
add and remove them dynamically from the domain.
Example:
To run the example application on domain <domain_id>:
On UNIX systems:
objs/<arch>/msg_publisher <domain_id>
objs/<arch>/msg_subscriber <domain_id>
On Windows systems:
objs\<arch>\msg_publisher <domain_id>
objs\<arch>\msg_subscriber <domain_id>
modification history
------------ -------
*/
#include "ndds/ndds_c.h"
#include <stdio.h>
#include <stdlib.h>
/* We use the typecode from built-in listeners, so we don't need to include
* this code*/
/*
#include "msg.h"
#include "msgSupport.h"
*/
/* We are going to use the BuiltinPublicationListener_on_data_available
* to detect the topics that are being published on the domain
*
* Once we have detected a new topic, we will print out the Topic Name,
* Participant ID, DataWriter id, and Data Type.
*/
void BuiltinPublicationListener_on_data_available(
void *listener_data,
DDS_DataReader *reader)
{
DDS_PublicationBuiltinTopicDataDataReader *builtin_reader = NULL;
struct DDS_PublicationBuiltinTopicDataSeq data_seq =
DDS_SEQUENCE_INITIALIZER;
struct DDS_PublicationBuiltinTopicData *data = NULL;
struct DDS_SampleInfoSeq info_seq = DDS_SEQUENCE_INITIALIZER;
DDS_ReturnCode_t retcode;
DDS_ExceptionCode_t exception_code;
int i, len;
builtin_reader = DDS_PublicationBuiltinTopicDataDataReader_narrow(reader);
retcode = DDS_PublicationBuiltinTopicDataDataReader_take(
builtin_reader,
&data_seq,
&info_seq,
DDS_LENGTH_UNLIMITED,
DDS_ANY_SAMPLE_STATE,
DDS_NEW_VIEW_STATE,
DDS_ANY_INSTANCE_STATE);
if (retcode == DDS_RETCODE_NO_DATA)
return;
if (retcode != DDS_RETCODE_OK) {
printf("***Error: failed to access data from the built-in reader\n");
return;
}
len = DDS_PublicationBuiltinTopicDataSeq_get_length(&data_seq);
for (i = 0; i < len; ++i) {
if (DDS_SampleInfoSeq_get_reference(&info_seq, i)->valid_data) {
data = DDS_PublicationBuiltinTopicDataSeq_get_reference(
&data_seq,
i);
printf("-----\nFound topic \"%s\"\nparticipant: "
"%08x%08x%08x\ndatawriter: %08x%08x%08x\ntype:\n",
data->topic_name,
data->participant_key.value[0],
data->participant_key.value[1],
data->participant_key.value[2],
data->key.value[0],
data->key.value[1],
data->key.value[2]);
if (data->type_code == NULL) {
printf("No type code received, perhaps increase "
"type_code_max_serialized_length?\n");
continue;
}
/* Using the type_code propagated we print the data type
* with print_IDL(). */
DDS_TypeCode_print_IDL(data->type_code, 2, &exception_code);
if (exception_code != DDS_NO_EXCEPTION_CODE) {
printf("Error***: print_IDL returns exception code %d",
exception_code);
}
}
}
DDS_PublicationBuiltinTopicDataDataReader_return_loan(
builtin_reader,
&data_seq,
&info_seq);
}
/* Delete all entities */
static int subscriber_shutdown(DDS_DomainParticipant *participant)
{
DDS_ReturnCode_t retcode;
int status = 0;
if (participant != NULL) {
retcode = DDS_DomainParticipant_delete_contained_entities(participant);
if (retcode != DDS_RETCODE_OK) {
printf("delete_contained_entities error %d\n", retcode);
status = -1;
}
retcode = DDS_DomainParticipantFactory_delete_participant(
DDS_TheParticipantFactory,
participant);
if (retcode != DDS_RETCODE_OK) {
printf("delete_participant error %d\n", retcode);
status = -1;
}
}
/* RTI Connext provides the finalize_instance() method on
domain participant factory for users who want to release memory used
by the participant factory. Uncomment the following block of code for
clean destruction of the singleton. */
/*
retcode = DDS_DomainParticipantFactory_finalize_instance();
if (retcode != DDS_RETCODE_OK) {
printf("finalize_instance error %d\n", retcode);
status = -1;
}
*/
return status;
}
static int subscriber_main(int domainId, int sample_count)
{
DDS_DomainParticipant *participant = NULL;
int count = 0;
struct DDS_Duration_t poll_period = { 4, 0 };
DDS_ReturnCode_t retcode;
DDS_Subscriber *builtin_subscriber = NULL;
DDS_PublicationBuiltinTopicDataDataReader *builtin_publication_datareader =
NULL;
/* Listener for the Built-in Publication Data Reader */
struct DDS_DataReaderListener builtin_publication_listener =
DDS_DataReaderListener_INITIALIZER;
/* If you want to change the type_code_max_serialized_length
* programmatically (e.g., to 3070) rather than using the XML file, you
* will need to add the following lines to your code and comment out the
* create_participant call bellow. */
/*
struct DDS_DomainParticipantQos participant_qos =
DDS_DomainParticipantQos_INITIALIZER;
retcode = DDS_DomainParticipantFactory_get_default_participant_qos(
DDS_TheParticipantFactory, &participant_qos);
if (retcode != DDS_RETCODE_OK) {
printf("get_default_participant_qos error\n");
return -1;
}
participant_qos.resource_limits.type_code_max_serialized_length = 3070;
participant = DDS_DomainParticipantFactory_create_participant(
DDS_TheParticipantFactory, domainId, &participant_qos,
NULL, DDS_STATUS_MASK_NONE);
if (participant == NULL) {
printf("create_participant error\n");
subscriber_shutdown(participant);
return -1;
}
*/
/* To customize participant QoS, use
the configuration file USER_QOS_PROFILES.xml */
participant = DDS_DomainParticipantFactory_create_participant(
DDS_TheParticipantFactory,
domainId,
&DDS_PARTICIPANT_QOS_DEFAULT,
NULL,
DDS_STATUS_MASK_NONE);
if (participant == NULL) {
printf("create_participant error\n");
subscriber_shutdown(participant);
return -1;
}
/* First get the built-in subscriber */
builtin_subscriber =
DDS_DomainParticipant_get_builtin_subscriber(participant);
if (builtin_subscriber == NULL) {
printf("***Error: failed to create builtin subscriber\n");
return 0;
}
/* Then get the data reader for the built-in subscriber */
builtin_publication_datareader =
(DDS_PublicationBuiltinTopicDataDataReader *)
DDS_Subscriber_lookup_datareader(
builtin_subscriber,
DDS_PUBLICATION_TOPIC_NAME);
if (builtin_publication_datareader == NULL) {
printf("***Error: failed to create builtin publication data reader\n");
return 0;
}
/* Finally install the listener */
builtin_publication_listener.on_data_available =
BuiltinPublicationListener_on_data_available;
DDS_DataReader_set_listener(
(DDS_DataReader *) builtin_publication_datareader,
&builtin_publication_listener,
DDS_DATA_AVAILABLE_STATUS);
/* Main loop */
for (count = 0; (sample_count == 0) || (count < sample_count); ++count) {
NDDS_Utility_sleep(&poll_period);
}
/* Cleanup and delete all entities */
return subscriber_shutdown(participant);
}
#if defined(RTI_WINCE)
int wmain(int argc, wchar_t **argv)
{
int domainId = 0;
int sample_count = 0; /* infinite loop */
if (argc >= 2) {
domainId = _wtoi(argv[1]);
}
if (argc >= 3) {
sample_count = _wtoi(argv[2]);
}
/* Uncomment this to turn on additional logging
NDDS_Config_Logger_set_verbosity_by_category(
NDDS_Config_Logger_get_instance(),
NDDS_CONFIG_LOG_CATEGORY_API,
NDDS_CONFIG_LOG_VERBOSITY_STATUS_ALL);
*/
return subscriber_main(domainId, sample_count);
}
#elif !(defined(RTI_VXWORKS) && !defined(__RTP__)) && !defined(RTI_PSOS)
int main(int argc, char *argv[])
{
int domainId = 0;
int sample_count = 0; /* infinite loop */
if (argc >= 2) {
domainId = atoi(argv[1]);
}
if (argc >= 3) {
sample_count = atoi(argv[2]);
}
/* Uncomment this to turn on additional logging
NDDS_Config_Logger_set_verbosity_by_category(
NDDS_Config_Logger_get_instance(),
NDDS_CONFIG_LOG_CATEGORY_API,
NDDS_CONFIG_LOG_VERBOSITY_STATUS_ALL);
*/
return subscriber_main(domainId, sample_count);
}
#endif
#ifdef RTI_VX653
const unsigned char *__ctype = NULL;
void usrAppInit()
{
#ifdef USER_APPL_INIT
USER_APPL_INIT; /* for backwards compatibility */
#endif
/* add application specific code here */
taskSpawn(
"sub",
RTI_OSAPI_THREAD_PRIORITY_NORMAL,
0x8,
0x150000,
(FUNCPTR) subscriber_main,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0);
}
#endif
| c |
rticonnextdds-examples | data/projects/rticonnextdds-examples/connext_dds/using_typecodes/c++03/msg_publisher.cxx | /*******************************************************************************
(c) 2005-2015 Copyright, Real-Time Innovations, Inc. All rights reserved.
RTI grants Licensee a license to use, modify, compile, and create derivative
works of the Software. Licensee has the right to distribute object form only
for use with RTI products. The Software is provided "as is", with no warranty
of any type, including any warranty for fitness for any purpose. RTI is under
no obligation to maintain or support the Software. RTI shall not be liable for
any incidental or consequential damages arising out of the use or inability to
use the software.
******************************************************************************/
#include <cstdlib>
#include <iostream>
#include "msg.hpp"
#include <dds/dds.hpp>
using namespace dds::core;
using namespace rti::core::policy;
using namespace dds::domain;
using namespace dds::domain::qos;
using namespace dds::topic;
using namespace dds::pub;
void publisher_main(int domain_id, int sample_count)
{
// Retrieve the Participant QoS, from USER_QOS_PROFILES.xml
DomainParticipantQos participant_qos =
QosProvider::Default()->participant_qos();
// If you want to change the Participant's QoS programmatically rather than
// using the XML file, uncomment the following lines.
// participant_qos << DomainParticipantResourceLimits().
// type_code_max_serialized_length(3070);
// Create a DomainParticipant.
DomainParticipant participant(domain_id, participant_qos);
// Create a Topic -- and automatically register the type
Topic<msg> topic(participant, "Example msg");
// Create a DataWriter with default Qos (Publisher created in-line)
DataWriter<msg> writer(Publisher(participant), topic);
msg sample;
for (int count = 0; count < sample_count || sample_count == 0; count++) {
// Update sample and send it.
std::cout << "Writing msg, count " << count << std::endl;
sample.count(count);
writer.write(sample);
rti::util::sleep(Duration(4));
}
}
int main(int argc, char *argv[])
{
int domain_id = 0;
int sample_count = 0; // Infinite loop
if (argc >= 2) {
domain_id = atoi(argv[1]);
}
if (argc >= 3) {
sample_count = atoi(argv[2]);
}
// To turn on additional logging, include <rti/config/Logger.hpp> and
// uncomment the following line:
// rti::config::Logger::instance().verbosity(rti::config::Verbosity::STATUS_ALL);
try {
publisher_main(domain_id, sample_count);
} catch (const std::exception &ex) {
// This will catch DDS exceptions
std::cerr << "Exception in publisher_main: " << ex.what() << std::endl;
return -1;
}
return 0;
}
| cxx |
rticonnextdds-examples | data/projects/rticonnextdds-examples/connext_dds/using_typecodes/c++03/msg_subscriber.cxx | /*******************************************************************************
(c) 2005-2015 Copyright, Real-Time Innovations, Inc. All rights reserved.
RTI grants Licensee a license to use, modify, compile, and create derivative
works of the Software. Licensee has the right to distribute object form only
for use with RTI products. The Software is provided "as is", with no warranty
of any type, including any warranty for fitness for any purpose. RTI is under
no obligation to maintain or support the Software. RTI shall not be liable for
any incidental or consequential damages arising out of the use or inability to
use the software.
******************************************************************************/
#include <algorithm>
#include <cstdlib>
#include <iomanip>
#include <iostream>
#include "msg.hpp"
#include <dds/dds.hpp>
#include <rti/core/ListenerBinder.hpp>
using namespace dds::core;
using namespace rti::core::policy;
using namespace dds::domain;
using namespace dds::domain::qos;
using namespace dds::topic;
using namespace dds::sub;
class BuiltinPublicationListener
: public NoOpDataReaderListener<PublicationBuiltinTopicData> {
public:
void on_data_available(DataReader<PublicationBuiltinTopicData> &reader)
{
// Take all samples
LoanedSamples<PublicationBuiltinTopicData> samples = reader.take();
typedef LoanedSamples<PublicationBuiltinTopicData>::iterator SampleIter;
for (SampleIter sample_it = samples.begin(); sample_it != samples.end();
sample_it++) {
if (sample_it->info().valid()) {
const PublicationBuiltinTopicData &data = sample_it->data();
const BuiltinTopicKey &partKey = data.participant_key();
const BuiltinTopicKey &key = sample_it->data().key();
std::cout << std::hex << std::setw(8) << std::setfill('0');
std::cout << "-----" << std::endl
<< "Found topic \"" << data.topic_name() << "\""
<< std::endl
<< "participant: " << partKey.value()[0]
<< partKey.value()[1] << partKey.value()[2]
<< std::endl
<< "datawriter: " << key.value()[0] << key.value()[1]
<< key.value()[2] << std::endl
<< "type:" << std::endl;
if (!data->type().is_set()) {
std::cout << "No type received, perhaps increase "
<< "type_code_max_serialized_length?"
<< std::endl;
} else {
// Using the type propagated we print the data type
// with print_idl()
rti::core::xtypes::print_idl(data->type().get(), 2);
}
}
}
}
};
void subscriber_main(int domain_id, int sample_count)
{
// Retrieve the Participant QoS, from USER_QOS_PROFILES.xml
DomainParticipantQos participant_qos =
QosProvider::Default()->participant_qos();
// If you want to change the Participant's QoS programmatically rather than
// using the XML file, uncomment the following lines.
// participant_qos << DomainParticipantResourceLimits().
// type_code_max_serialized_length(3070);
// Create a DomainParticipant.
DomainParticipant participant(domain_id, participant_qos);
// First get the builtin subscriber.
Subscriber builtin_subscriber = dds::sub::builtin_subscriber(participant);
// Then get builtin subscriber's DataReader for DataWriters.
DataReader<PublicationBuiltinTopicData> publication_reader =
rti::sub::find_datareader_by_topic_name<
DataReader<PublicationBuiltinTopicData> >(
builtin_subscriber,
dds::topic::publication_topic_name());
// Install our listener using ListenerBinder, a RAII that will take care
// of setting it to NULL and deleting it.
rti::core::ListenerBinder<DataReader<PublicationBuiltinTopicData> >
publication_listener = rti::core::bind_and_manage_listener(
publication_reader,
new BuiltinPublicationListener,
dds::core::status::StatusMask::data_available());
for (int count = 0; sample_count == 0 || count < sample_count; ++count) {
rti::util::sleep(Duration(1));
}
}
int main(int argc, char *argv[])
{
int domain_id = 0;
int sample_count = 0; // Infinite loop
if (argc >= 2) {
domain_id = atoi(argv[1]);
}
if (argc >= 3) {
sample_count = atoi(argv[2]);
}
// To turn on additional logging, include <rti/config/Logger.hpp> and
// uncomment the following line:
// rti::config::Logger::instance().verbosity(rti::config::Verbosity::STATUS_ALL);
try {
subscriber_main(domain_id, sample_count);
} catch (const std::exception &ex) {
// This will catch DDS exceptions
std::cerr << "Exception in subscriber_main: " << ex.what() << std::endl;
return -1;
}
return 0;
}
| cxx |
rticonnextdds-examples | data/projects/rticonnextdds-examples/connext_dds/using_typecodes/c++11/application.hpp | /*
* (c) Copyright, Real-Time Innovations, 2020. All rights reserved.
* RTI grants Licensee a license to use, modify, compile, and create derivative
* works of the software solely for use with RTI Connext DDS. Licensee may
* redistribute copies of the software provided that all such copies are subject
* to this license. The software is provided "as is", with no warranty of any
* type, including any warranty for fitness for any purpose. RTI is under no
* obligation to maintain or support the software. RTI shall not be liable for
* any incidental or consequential damages arising out of the use or inability
* to use the software.
*/
#ifndef APPLICATION_HPP
#define APPLICATION_HPP
#include <iostream>
#include <csignal>
#include <dds/core/ddscore.hpp>
namespace application {
// Catch control-C and tell application to shut down
bool shutdown_requested = false;
inline void stop_handler(int)
{
shutdown_requested = true;
std::cout << "preparing to shut down..." << std::endl;
}
inline void setup_signal_handlers()
{
signal(SIGINT, stop_handler);
signal(SIGTERM, stop_handler);
}
enum class ParseReturn { ok, failure, exit };
struct ApplicationArguments {
ParseReturn parse_result;
unsigned int domain_id;
unsigned int sample_count;
rti::config::Verbosity verbosity;
ApplicationArguments(
ParseReturn parse_result_param,
unsigned int domain_id_param,
unsigned int sample_count_param,
rti::config::Verbosity verbosity_param)
: parse_result(parse_result_param),
domain_id(domain_id_param),
sample_count(sample_count_param),
verbosity(verbosity_param)
{
}
};
inline void set_verbosity(
rti::config::Verbosity &verbosity,
int verbosity_value)
{
switch (verbosity_value) {
case 0:
verbosity = rti::config::Verbosity::SILENT;
break;
case 1:
verbosity = rti::config::Verbosity::EXCEPTION;
break;
case 2:
verbosity = rti::config::Verbosity::WARNING;
break;
case 3:
verbosity = rti::config::Verbosity::STATUS_ALL;
break;
default:
verbosity = rti::config::Verbosity::EXCEPTION;
break;
}
}
// Parses application arguments for example.
inline ApplicationArguments parse_arguments(int argc, char *argv[])
{
int arg_processing = 1;
bool show_usage = false;
ParseReturn parse_result = ParseReturn::ok;
unsigned int domain_id = 0;
unsigned int sample_count = (std::numeric_limits<unsigned int>::max)();
rti::config::Verbosity verbosity(rti::config::Verbosity::EXCEPTION);
while (arg_processing < argc) {
if ((argc > arg_processing + 1)
&& (strcmp(argv[arg_processing], "-d") == 0
|| strcmp(argv[arg_processing], "--domain") == 0)) {
domain_id = atoi(argv[arg_processing + 1]);
arg_processing += 2;
} else if (
(argc > arg_processing + 1)
&& (strcmp(argv[arg_processing], "-s") == 0
|| strcmp(argv[arg_processing], "--sample-count") == 0)) {
sample_count = atoi(argv[arg_processing + 1]);
arg_processing += 2;
} else if (
(argc > arg_processing + 1)
&& (strcmp(argv[arg_processing], "-v") == 0
|| strcmp(argv[arg_processing], "--verbosity") == 0)) {
set_verbosity(verbosity, atoi(argv[arg_processing + 1]));
arg_processing += 2;
} else if (
strcmp(argv[arg_processing], "-h") == 0
|| strcmp(argv[arg_processing], "--help") == 0) {
std::cout << "Example application." << std::endl;
show_usage = true;
parse_result = ParseReturn::exit;
break;
} else {
std::cout << "Bad parameter." << std::endl;
show_usage = true;
parse_result = ParseReturn::failure;
break;
}
}
if (show_usage) {
std::cout << "Usage:\n"
" -d, --domain <int> Domain ID this "
"application will\n"
" subscribe in. \n"
" Default: 0\n"
" -s, --sample_count <int> Number of samples to "
"receive before\n"
" cleanly shutting down. \n"
" Default: infinite\n"
" -v, --verbosity <int> How much debugging output "
"to show.\n"
" Range: 0-3 \n"
" Default: 1"
<< std::endl;
}
return ApplicationArguments(
parse_result,
domain_id,
sample_count,
verbosity);
}
} // namespace application
#endif // APPLICATION_HPP | hpp |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.