repo_name
stringclasses 10
values | file_path
stringlengths 29
222
| content
stringlengths 24
926k
| extention
stringclasses 5
values |
---|---|---|---|
rticonnextdds-examples | data/projects/rticonnextdds-examples/persistent_storage/c/hello_world_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.
******************************************************************************/
/* hello_world_subscriber.c
A subscription example
This file is derived from code automatically generated by the rtiddsgen
command:
rtiddsgen -language C -example <arch> hello_world.idl
Example subscription of type hello_world 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>/hello_world_subscriber <domain_id> <sample_count>
(3) Start the publication with the command
objs/<arch>/hello_world_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>/hello_world_publisher <domain_id>
objs/<arch>/hello_world_subscriber <domain_id>
On Windows systems:
objs\<arch>\hello_world_publisher <domain_id>
objs\<arch>\hello_world_subscriber <domain_id>
*/
#include <stdio.h>
#include <stdlib.h>
#include "ndds/ndds_c.h"
#include "hello_world.h"
#include "hello_worldSupport.h"
/******************************************************************************
Macros to read input parameters
******************************************************************************/
#define READ_INTEGER_PARAM(parameter,outValue)\
if (!strcmp(argv[i],parameter)) {\
if (i+1 >= argc) {\
printf("%s",syntax);\
return 1;\
}\
i++;\
outValue = atoi(argv[i]);\
i++;\
continue;\
}
#define READ_STRING_PARAM(parameter,outValue)\
if (!strcmp(argv[i],parameter)) {\
if (i+1 >= argc) {\
printf("%s",syntax);\
return 1;\
}\
i++;\
outValue=argv[i];\
i++;\
continue;\
}
void hello_worldListener_on_requested_deadline_missed(void* listener_data,
DDS_DataReader* reader,
const struct DDS_RequestedDeadlineMissedStatus *status) {
}
void hello_worldListener_on_requested_incompatible_qos(void* listener_data,
DDS_DataReader* reader,
const struct DDS_RequestedIncompatibleQosStatus *status) {
}
void hello_worldListener_on_sample_rejected(void* listener_data,
DDS_DataReader* reader, const struct DDS_SampleRejectedStatus *status) {
}
void hello_worldListener_on_liveliness_changed(void* listener_data,
DDS_DataReader* reader,
const struct DDS_LivelinessChangedStatus *status) {
}
void hello_worldListener_on_sample_lost(void* listener_data,
DDS_DataReader* reader, const struct DDS_SampleLostStatus *status) {
}
void hello_worldListener_on_subscription_matched(void* listener_data,
DDS_DataReader* reader,
const struct DDS_SubscriptionMatchedStatus *status) {
}
void hello_worldListener_on_data_available(void* listener_data,
DDS_DataReader* reader) {
hello_worldDataReader *hello_world_reader = NULL;
struct hello_worldSeq data_seq = DDS_SEQUENCE_INITIALIZER;
struct DDS_SampleInfoSeq info_seq = DDS_SEQUENCE_INITIALIZER;
DDS_ReturnCode_t retcode;
int i;
hello_world_reader = hello_worldDataReader_narrow(reader);
if (hello_world_reader == NULL) {
printf("DataReader narrow error\n");
return;
}
retcode = hello_worldDataReader_take(hello_world_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 < hello_worldSeq_get_length(&data_seq); ++i) {
if (DDS_SampleInfoSeq_get_reference(&info_seq, i)->valid_data) {
hello_worldTypeSupport_print_data(
hello_worldSeq_get_reference(&data_seq, i));
}
}
retcode = hello_worldDataReader_return_loan(hello_world_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 domain_id, int sample_count, int drs) {
DDS_DomainParticipant *participant = NULL;
DDS_Subscriber *subscriber = NULL;
DDS_Topic *topic = NULL;
struct DDS_DataReaderListener reader_listener =
DDS_DataReaderListener_INITIALIZER;
struct DDS_DataReaderQos reader_qos = DDS_DataReaderQos_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 };
/* To customize participant QoS, use
the configuration file USER_QOS_PROFILES.xml */
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");
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 = hello_worldTypeSupport_get_type_name();
retcode = hello_worldTypeSupport_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 hello_world", 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 =
hello_worldListener_on_requested_deadline_missed;
reader_listener.on_requested_incompatible_qos =
hello_worldListener_on_requested_incompatible_qos;
reader_listener.on_sample_rejected = hello_worldListener_on_sample_rejected;
reader_listener.on_liveliness_changed =
hello_worldListener_on_liveliness_changed;
reader_listener.on_sample_lost = hello_worldListener_on_sample_lost;
reader_listener.on_subscription_matched =
hello_worldListener_on_subscription_matched;
reader_listener.on_data_available = hello_worldListener_on_data_available;
/* If you use Durable Reader State, you need to set up several properties.
* In this example, we have modified them using a QoS XML profile. See
* further details in USER_QOS_PROFILES.xml.
*/
if (drs == 1) {
reader = DDS_Subscriber_create_datareader_with_profile(subscriber,
DDS_Topic_as_topicdescription(topic),
"persistence_example_Library", "durable_reader_state_Profile",
&reader_listener, DDS_STATUS_MASK_ALL);
if (reader == NULL) {
printf("create_datareader error\n");
subscriber_shutdown(participant);
return -1;
}
} else {
reader = DDS_Subscriber_create_datareader_with_profile(subscriber,
DDS_Topic_as_topicdescription(topic),
"persistence_example_Library", "persistence_service_Profile",
&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("hello_world subscriber sleeping for %d sec...\n",
poll_period.sec);
NDDS_Utility_sleep(&poll_period);
}
/* Cleanup and delete all entities */
return subscriber_shutdown(participant);
}
int main(int argc, char *argv[]) {
int domain_id = 0;
int drs = 0;
int i;
char syntax[1024];
int sample_count = 0; /* infinite loop */
sprintf(syntax,
"%s [options] \n\
-domain_id <domain ID> (default: 0)\n\
-sample_count <sample_count> (default: infinite => 0) \n\
-drs <1|0> Enable/Disable durable reader state (default: 0)\n",
argv[0]);
for (i = 1; i < argc;) {
READ_INTEGER_PARAM("-sample_count", sample_count);
READ_INTEGER_PARAM("-domain_id", domain_id);
READ_INTEGER_PARAM("-drs", drs);
printf("%s", syntax);
return 0;
}
/* 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, drs);
}
#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/persistent_storage/c++03/hello_world_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 <algorithm>
#include <iostream>
#include <dds/dds.hpp>
#include <rti/core/ListenerBinder.hpp>
#include "hello_world.hpp"
using namespace dds::core;
using namespace dds::core::status;
using namespace dds::domain;
using namespace dds::topic;
using namespace dds::sub;
using namespace dds::sub::qos;
class hello_worldReaderListener : public NoOpDataReaderListener<hello_world> {
public:
void on_data_available(DataReader<hello_world>& reader)
{
// Take all samples
LoanedSamples<hello_world> samples = reader.take();
for (LoanedSamples<hello_world>::iterator sample_it = samples.begin();
sample_it != samples.end();
sample_it++) {
if (sample_it->info().valid()){
std::cout << sample_it->data() << std::endl;
}
}
}
};
void subscriber_main(int domain_id, int sample_count, bool drs)
{
// Create a DomainParticipant with default Qos
DomainParticipant participant(domain_id);
// Create a Topic -- and automatically register the type
Topic<hello_world> topic(participant, "Example hello_world");
// If you use Durable Reader State, you need to set up several properties.
// In this example, we have modified them using a QoS XML profile. See
// further details in USER_QOS_PROFILES.xml.
std::string qos_libname = "persistence_example_Library";
DataReaderQos reader_qos = drs ?
QosProvider::Default().datareader_qos(
qos_libname + "::durable_reader_state_Profile") :
QosProvider::Default().datareader_qos(
qos_libname + "::persistence_service_Profile");
// Create a DataReader (Subscriber created in-line)
DataReader<hello_world> reader(Subscriber(participant), 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<hello_world> > scoped_listener =
rti::core::bind_and_manage_listener(
reader,
new hello_worldReaderListener,
StatusMask::data_available());
for (int count = 0; sample_count == 0 || count < sample_count; ++count) {
std::cout << "hello_world subscriber sleeping for 4 sec..."
<< std::endl;
rti::util::sleep(Duration(4));
}
}
int main(int argc, char *argv[])
{
int domain_id = 0;
int sample_count = 0; // Infinite loop
bool drs = false;
for (int i = 1; i < argc; ) {
const std::string& param = argv[i++];
if (param == "-domain_id" && i < argc) {
domain_id = atoi(argv[i++]);
} else if (param == "-sample_count" && i < argc) {
sample_count = atoi(argv[i++]);
} else if (param == "-drs" && i < argc) {
drs = (atoi(argv[i++]) == 1);
} else {
std::cout << argv[0] << " [options]" << std::endl
<< "\t-domain_id <domain ID> (default: 0)" << std::endl
<< "\t-sample_count <number of published samples> "
<< "(default: 0 (infinite))" << std::endl
<< "\t-drs <1|0> Enable/Disable durable reader state "
<< "(default: 0)" << std::endl;
return -1;
}
}
// 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, drs);
} 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/persistent_storage/c++03/hello_world_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 <dds/dds.hpp>
#include "hello_world.hpp"
using namespace dds::core;
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, int initial_value,
bool use_durable_writer_history, int sleep)
{
// Create a DomainParticipant with default Qos
DomainParticipant participant(domain_id);
// Create a Topic -- and automatically register the type
Topic<hello_world> topic(participant, "Example hello_world");
// If you use Durable Writer History, you need to set several properties.
// These properties are set in the USER_QOS_PROFILE.xml file,
// "durable_writer_history_Profile" profile. See that file for further
// details.
std::string qos_libname = "persistence_example_Library";
DataWriterQos writer_qos = use_durable_writer_history ?
QosProvider::Default().datawriter_qos(
qos_libname + "::durable_writer_history_Profile") :
QosProvider::Default().datawriter_qos(
qos_libname + "::persistence_service_Profile");
// Create a DataWriter (Publisher created in-line)
DataWriter<hello_world> writer(Publisher(participant), topic, writer_qos);
hello_world sample;
for (int count = 0; count < sample_count || sample_count == 0; count++) {
std::cout << "Writing hello_world, count " << count << std::endl;
sample.data(initial_value++);
writer.write(sample);
rti::util::sleep(Duration(1));
}
while (sleep != 0) {
rti::util::sleep(Duration(1));
sleep--;
}
}
int main(int argc, char *argv[])
{
int domain_id = 0;
int sample_count = 0; // Infinite loop
int initial_value = 0;
bool use_durable_writer_history = false;
int sleep = 0;
for (int i = 1; i < argc; ) {
const std::string& param = argv[i++];
if (param == "-sleep" && i < argc) {
sleep = atoi(argv[i++]);
} else if (param == "-domain_id" && i < argc) {
domain_id = atoi(argv[i++]);
} else if (param == "-sample_count" && i < argc) {
sample_count = atoi(argv[i++]);
} else if (param == "-initial_value" && i < argc) {
initial_value = atoi(argv[i++]);
} else if (param == "-dwh" && i < argc) {
use_durable_writer_history = (atoi(argv[i++]) == 1);
} else {
std::cout << argv[0] << " [options]" << std::endl
<< "\t-domain_id <domain ID> (default: 0)" << std::endl
<< "\t-sample_count <number of published samples> "
<< "(default: 0 (infinite))" << std::endl
<< "\t-initial_value <first sample value> (default: 0)"
<< std::endl
<< "\t-sleep <sleep time in seconds before finishing> "
<< "(default: 0)" << std::endl
<< "\t-dwh <1|0> Enable/Disable durable writer history "
<< "(default: 0)" << std::endl;
return -1;
}
}
// 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, initial_value,
use_durable_writer_history, sleep);
} 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/time_based_filter/c++/tbf_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.
******************************************************************************/
/* tbf_subscriber.cxx
A subscription example
This file is derived from code automatically generated by the rtiddsgen
command:
rtiddsgen -language C++ -example <arch> tbf.idl
Example subscription of type tbf 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>/tbf_subscriber <domain_id> <sample_count>
(3) Start the publication with the command
objs/<arch>/tbf_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>/tbf_publisher <domain_id>
objs/<arch>/tbf_subscriber <domain_id>
On Windows:
objs\<arch>\tbf_publisher <domain_id>
objs\<arch>\tbf_subscriber <domain_id>
modification history
------------ -------
*/
#include <stdio.h>
#include <stdlib.h>
#ifdef RTI_VX653
#include <vThreadsData.h>
#endif
#include "tbf.h"
#include "tbfSupport.h"
#include "ndds/ndds_cpp.h"
#define NANOSECOND 1000000000.0
class tbfListener : 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 tbfListener::on_data_available(DDSDataReader* reader)
{
tbfDataReader *tbf_reader = NULL;
tbfSeq data_seq;
DDS_SampleInfoSeq info_seq;
DDS_ReturnCode_t retcode;
int i;
tbf_reader = tbfDataReader::narrow(reader);
if (tbf_reader == NULL) {
printf("DataReader narrow error\n");
return;
}
retcode = tbf_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) {
/* Here we get source timestamp of the sample using the sample info.
*
* info_seq[i].source_timestamp returns DDS_Time_t
* ({seconds,nanoseconds}). We convert nanoseconds to seconds to get
* the decimal part of the timestamp.
*/
double source_timestamp = info_seq[i].source_timestamp.sec +
info_seq[i].source_timestamp.nanosec/NANOSECOND;
printf("%f\t%d\t\t%d\n",
source_timestamp,
data_seq[i].code, data_seq[i].x);
}
}
retcode = tbf_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;
tbfListener *reader_listener = NULL;
DDSDataReader *reader = NULL;
DDS_ReturnCode_t retcode;
const char *type_name = NULL;
int count = 0;
DDS_Duration_t receive_period = {4,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 = tbfTypeSupport::get_type_name();
retcode = tbfTypeSupport::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 tbf",
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 tbfListener();
/* 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;
}
/* If you want to change the time-based filter programmatically (e.g., to
* 2 seconds) 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. */
/*DDS_DataReaderQos datareader_qos;
retcode = subscriber->get_default_datareader_qos(datareader_qos);
if (retcode != DDS_RETCODE_OK) {
printf("get_default_datareader_qos error\n");
return -1;
}
DDS_Duration_t minsep = {2, 0}; // 2 sec
datareader_qos.time_based_filter.minimum_separation = minsep;
reader = subscriber->create_datareader(
topic, datareader_qos, reader_listener,
DDS_STATUS_MASK_ALL);
if (reader == NULL) {
printf("create_datareader error\n");
subscriber_shutdown(participant);
delete reader_listener;
return -1;
}*/
/* Results table header: (1) source timestamp of the sample received;
* (2) instance id (instance.code value); and (3) value of x (instance.x).
*/
printf("================================================\n");
printf("Source Timestamp\tInstance\tX\n");
printf("================================================\n");
/* Main loop */
for (count=0; (sample_count == 0) || (count < sample_count); ++count) {
/*printf("tbf 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/time_based_filter/c++/tbf_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.
******************************************************************************/
/* tbf_publisher.cxx
A publication of data of type tbf
This file is derived from code automatically generated by the rtiddsgen
command:
rtiddsgen -language C++ -example <arch> tbf.idl
Example publication of type tbf 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>/tbf_subscriber <domain_id> <sample_count>
(3) Start the publication with the command
objs/<arch>/tbf_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>/tbf_publisher <domain_id> o
objs/<arch>/tbf_subscriber <domain_id>
On Windows:
objs\<arch>\tbf_publisher <domain_id>
objs\<arch>\tbf_subscriber <domain_id>
modification history
------------ -------
*/
#include <stdio.h>
#include <stdlib.h>
#ifdef RTI_VX653
#include <vThreadsData.h>
#endif
#include "tbf.h"
#include "tbfSupport.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;
tbfDataWriter * tbf_writer = NULL;
tbf *instance = NULL;
DDS_ReturnCode_t retcode;
DDS_InstanceHandle_t instance_handle = DDS_HANDLE_NIL;
const char *type_name = NULL;
int count = 0;
/* send_period sleep of 0.25 second, i.e., the loop where we write
* new samples will sleep for 0.25 second every iteration.*/
DDS_Duration_t send_period = {0,250000000};
/* 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 = tbfTypeSupport::get_type_name();
retcode = tbfTypeSupport::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 tbf",
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;
}
tbf_writer = tbfDataWriter::narrow(writer);
if (tbf_writer == NULL) {
printf("DataWriter narrow error\n");
publisher_shutdown(participant);
return -1;
}
/* Create data sample for writing */
instance = tbfTypeSupport::create_data();
if (instance == NULL) {
printf("tbfTypeSupport::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 = tbf_writer->register_instance(*instance);
*/
/* Main loop */
for (count=0; (sample_count == 0) || (count < sample_count); ++count) {
printf("\nWriting tbf, count %d\n", count);
printf("=======================\n");
/* Modify the data to be sent here */
/* Update instance 1 (code = 1) every 0.5 seconds */
if ((count+1)%2 == 0) {
printf("Publishing instance 1\n");
instance->code = 1;
instance->x = count;
retcode = tbf_writer->write(*instance, instance_handle);
if (retcode != DDS_RETCODE_OK) {
printf("write error %d\n", retcode);
}
}
/* Update instance 0 (code = 0) every 0.25 seconds */
printf ("Publishing instance 0\n");
instance->code = 0;
instance->x = count;
retcode = tbf_writer->write(*instance, instance_handle);
if (retcode != DDS_RETCODE_OK) {
printf("write error %d\n", retcode);
}
NDDSUtility::sleep(send_period);
}
/*
retcode = tbf_writer->unregister_instance(
*instance, instance_handle);
if (retcode != DDS_RETCODE_OK) {
printf("unregister instance error %d\n", retcode);
}
*/
/* Delete data sample */
retcode = tbfTypeSupport::delete_data(instance);
if (retcode != DDS_RETCODE_OK) {
printf("tbfTypeSupport::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/time_based_filter/c/tbf_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.
******************************************************************************/
/* tbf_subscriber.c
A subscription example
This file is derived from code automatically generated by the rtiddsgen
command:
rtiddsgen -language C -example <arch> tbf.idl
Example subscription of type tbf 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>/tbf_subscriber <domain_id> <sample_count>
(3) Start the publication with the command
objs/<arch>/tbf_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>/tbf_publisher <domain_id>
objs/<arch>/tbf_subscriber <domain_id>
On Windows systems:
objs\<arch>\tbf_publisher <domain_id>
objs\<arch>\tbf_subscriber <domain_id>
modification history
------------ -------
*/
#include <stdio.h>
#include <stdlib.h>
#include "ndds/ndds_c.h"
#include "tbf.h"
#include "tbfSupport.h"
#define NANOSECOND 1000000000.0
void tbfListener_on_requested_deadline_missed(
void* listener_data,
DDS_DataReader* reader,
const struct DDS_RequestedDeadlineMissedStatus *status)
{
}
void tbfListener_on_requested_incompatible_qos(
void* listener_data,
DDS_DataReader* reader,
const struct DDS_RequestedIncompatibleQosStatus *status)
{
}
void tbfListener_on_sample_rejected(
void* listener_data,
DDS_DataReader* reader,
const struct DDS_SampleRejectedStatus *status)
{
}
void tbfListener_on_liveliness_changed(
void* listener_data,
DDS_DataReader* reader,
const struct DDS_LivelinessChangedStatus *status)
{
}
void tbfListener_on_sample_lost(
void* listener_data,
DDS_DataReader* reader,
const struct DDS_SampleLostStatus *status)
{
}
void tbfListener_on_subscription_matched(
void* listener_data,
DDS_DataReader* reader,
const struct DDS_SubscriptionMatchedStatus *status)
{
}
void tbfListener_on_data_available(
void* listener_data,
DDS_DataReader* reader)
{
tbfDataReader *tbf_reader = NULL;
struct tbfSeq data_seq = DDS_SEQUENCE_INITIALIZER;
struct DDS_SampleInfoSeq info_seq = DDS_SEQUENCE_INITIALIZER;
DDS_ReturnCode_t retcode;
int i;
double source_timestamp;
tbf* data;
struct DDS_SampleInfo *sample_info;
tbf_reader = tbfDataReader_narrow(reader);
if (tbf_reader == NULL) {
printf("DataReader narrow error\n");
return;
}
retcode = tbfDataReader_take(
tbf_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 < tbfSeq_get_length(&data_seq); ++i) {
sample_info = DDS_SampleInfoSeq_get_reference(&info_seq, i);
if (sample_info->valid_data) {
data = tbfSeq_get_reference(&data_seq, i);
/* Here we get source timestamp of the sample using the sample info.
*
* info_seq[i].source_timestamp returns DDS_Time_t
* ({seconds,nanoseconds}). We convert nanoseconds to seconds to get
* the decimal part of the timestamp.
*/
source_timestamp = sample_info->source_timestamp.sec +
sample_info->source_timestamp.nanosec/NANOSECOND;
printf("%f\t%d\t\t%d\n",
source_timestamp,
data->code, data->x);
}
}
retcode = tbfDataReader_return_loan(
tbf_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};
/* To change the time-based filter programmatically you will need to declare
* the DataReaderQoS */
struct DDS_DataReaderQos datareader_qos = DDS_DataReaderQos_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 = tbfTypeSupport_get_type_name();
retcode = tbfTypeSupport_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 tbf",
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 =
tbfListener_on_requested_deadline_missed;
reader_listener.on_requested_incompatible_qos =
tbfListener_on_requested_incompatible_qos;
reader_listener.on_sample_rejected =
tbfListener_on_sample_rejected;
reader_listener.on_liveliness_changed =
tbfListener_on_liveliness_changed;
reader_listener.on_sample_lost =
tbfListener_on_sample_lost;
reader_listener.on_subscription_matched =
tbfListener_on_subscription_matched;
reader_listener.on_data_available =
tbfListener_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;
}
/* If you want to change the time-based filter programmatically (e.g., to
* 2 seconds) 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. */
/*datareader_qos.time_based_filter.minimum_separation.sec = 2;
datareader_qos.time_based_filter.minimum_separation.nanosec = 0;
reader = DDS_Subscriber_create_datareader(
subscriber, DDS_Topic_as_topicdescription(topic),
&datareader_qos, &reader_listener, DDS_STATUS_MASK_ALL);
if (reader == NULL) {
printf("create_datareader error\n");
subscriber_shutdown(participant);
return -1;
}*/
/* Results table header: (1) source timestamp of the sample received;
* (2) instance id (instance.code value); and (3) value of x (instance.x).
*/
printf("================================================\n");
printf("Source Timestamp\tInstance\tX\n");
printf("================================================\n");
/* Main loop */
for (count=0; (sample_count == 0) || (count < sample_count); ++count) {
/*printf("tbf 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/time_based_filter/c/tbf_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.
******************************************************************************/
/* tbf_publisher.c
A publication of data of type tbf
This file is derived from code automatically generated by the rtiddsgen
command:
rtiddsgen -language C -example <arch> tbf.idl
Example publication of type tbf 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>/tbf_subscriber <domain_id> <sample_count>
(3) Start the publication with the command
objs/<arch>/tbf_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>/tbf_publisher <domain_id>
objs/<arch>/tbf_subscriber <domain_id>
On Windows:
objs\<arch>\tbf_publisher <domain_id>
objs\<arch>\tbf_subscriber <domain_id>
modification history
------------ -------
*/
#include <stdio.h>
#include <stdlib.h>
#include "ndds/ndds_c.h"
#include "tbf.h"
#include "tbfSupport.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;
tbfDataWriter *tbf_writer = NULL;
tbf *instance = NULL;
DDS_ReturnCode_t retcode;
DDS_InstanceHandle_t instance_handle = DDS_HANDLE_NIL;
const char *type_name = NULL;
int count = 0;
/* send_period sleep of 0.25 seconds, i.e., the loop where we write
* new samples will sleep for 0.25 seconds every iteration.*/
struct DDS_Duration_t send_period = {0,250000000};
/* 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 = tbfTypeSupport_get_type_name();
retcode = tbfTypeSupport_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 tbf",
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;
}
tbf_writer = tbfDataWriter_narrow(writer);
if (tbf_writer == NULL) {
printf("DataWriter narrow error\n");
publisher_shutdown(participant);
return -1;
}
/* Create data sample for writing */
instance = tbfTypeSupport_create_data_ex(DDS_BOOLEAN_TRUE);
if (instance == NULL) {
printf("tbfTypeSupport_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 = tbfDataWriter_register_instance(
tbf_writer, instance);
*/
/* Main loop */
for (count=0; (sample_count == 0) || (count < sample_count); ++count) {
printf("\nWriting tbf, count %d\n", count);
printf("=======================\n");
/* Modify the data to be written here */
/* Update instance 1 (code = 1) every 0.50 seconds */
if ((count+1)%2 == 0) {
printf("Publishing instance 1\n");
instance->code = 1;
instance->x = count;
retcode = tbfDataWriter_write(
tbf_writer, instance, &instance_handle);
if (retcode != DDS_RETCODE_OK) {
printf("write error %d\n", retcode);
}
}
/* Update instance 0 (code = 0) every 0.25 seconds */
printf ("Publishing instance 0\n");
instance->code = 0;
instance->x = count;
retcode = tbfDataWriter_write(
tbf_writer, instance, &instance_handle);
if (retcode != DDS_RETCODE_OK) {
printf("write error %d\n", retcode);
}
NDDS_Utility_sleep(&send_period);
}
/*
retcode = tbfDataWriter_unregister_instance(
tbf_writer, instance, &instance_handle);
if (retcode != DDS_RETCODE_OK) {
printf("unregister instance error %d\n", retcode);
}
*/
/* Delete data sample */
retcode = tbfTypeSupport_delete_data_ex(instance, DDS_BOOLEAN_TRUE);
if (retcode != DDS_RETCODE_OK) {
printf("tbfTypeSupport_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/time_based_filter/c++03/tbf_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 <dds/dds.hpp>
#include <rti/core/ListenerBinder.hpp>
#include "tbf.hpp"
using namespace dds::core;
using namespace dds::core::policy;
using namespace rti::core;
using namespace dds::domain;
using namespace dds::topic;
using namespace dds::sub;
using namespace dds::sub::qos;
class tbfReaderListener : public NoOpDataReaderListener<tbf> {
public:
void on_data_available(dds::sub::DataReader<tbf>& reader)
{
// Take all samples
LoanedSamples<tbf> samples = reader.take();
for (LoanedSamples<tbf>::iterator sample_it = samples.begin();
sample_it != samples.end(); sample_it++) {
if (sample_it->info().valid()){
// Here we get source timestamp of the sample using the sample
// info. 'info.source_timestamp()' returns dds::core::Time.
double source_timestamp = sample_it->info()
.source_timestamp().to_secs();
const tbf& data = sample_it->data();
std::cout << source_timestamp << "\t" << data.code()
<< "\t\t" << data.x() << 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<tbf> topic(participant, "Example tbf");
// Retrieve the default DataReader 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 uncomment this line.
// reader_qos << TimeBasedFilter(Duration::from_secs(2));
// Create a DataReader with default Qos (Subscriber created in-line)
DataReader<tbf> reader(Subscriber(participant), topic, reader_qos);
// Associate a listener to the DataReader using ListenerBinder, a RAII that
// will take care of setting it to NULL on destruction.
ListenerBinder< DataReader<tbf> > reader_listener =
rti::core::bind_and_manage_listener(
reader,
new tbfReaderListener,
dds::core::status::StatusMask::all());
std::cout << "================================================" << std::endl
<< "Source Timestamp\tInstance\tX" << std::endl
<< "================================================" << std::endl
<< std::fixed;
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/time_based_filter/c++03/tbf_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 <dds/dds.hpp>
#include "tbf.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)
{
// Create a DomainParticipant with default Qos
DomainParticipant participant (domain_id);
// Create a Topic -- and automatically register the type
Topic<tbf> topic (participant, "Example tbf");
// Create a DataWriter with default Qos (Publisher created in-line)
DataWriter<tbf> writer(Publisher(participant), topic);
// Create a sample to write
tbf sample;
for (int count = 0; count < sample_count || sample_count == 0; count++) {
std::cout << "Writing tbf, count " << count << std::endl;
// Update instance1 (code = 1) every 0.5 seconds => when count is even.
if ((count + 1) % 2 == 0) {
std::cout << "Publishing instance 1" << std::endl;
sample.code(1);
sample.x(count);
writer.write(sample);
}
// Update instance 0 (code = 0) every 0.25 seconds.
std::cout << "Publishing instance 0" << std::endl;
sample.code(0);
sample.x(count);
writer.write(sample);
// The loop to write new samples will sleep for 0.25 second.
rti::util::sleep(Duration::from_millisecs(250));
}
}
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/ordered_presentation/c++/ordered_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.
******************************************************************************/
/* ordered_subscriber.cxx
A subscription example
This file is derived from code automatically generated by the rtiddsgen
command:
rtiddsgen -language C++ -example <arch> ordered.idl
Example subscription of type ordered 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>/ordered_subscriber <domain_id> <sample_count>
(3) Start the publication with the command
objs/<arch>/ordered_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>/ordered_publisher <domain_id>
objs/<arch>/ordered_subscriber <domain_id>
On Windows:
objs\<arch>\ordered_publisher <domain_id>
objs\<arch>\ordered_subscriber <domain_id>
modification history
------------ -------
*/
#include <stdio.h>
#include <stdlib.h>
#ifdef RTI_VX653
#include <vThreadsData.h>
#endif
#include "ordered.h"
#include "orderedSupport.h"
#include "ndds/ndds_cpp.h"
#define MAX_SUBSCRIBERS 2
/* Start changes for Ordered_Presentation */
/* No listener is needed; we poll readers in this function */
void poll_data(orderedDataReader *ordered_reader[], int numreaders) {
DDS_SampleInfoSeq info_seq;
orderedSeq data_seq;
DDS_ReturnCode_t retcode = DDS_RETCODE_OK;
for (int r = 0; r < numreaders; ++r) {
retcode = ordered_reader[r]->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) {
/* Not an error */
continue;
} else if (retcode != DDS_RETCODE_OK) {
/* Is an error */
printf("take error: %d\n", retcode);
return;
}
for (int i = 0; i < data_seq.length(); ++i) {
if (!info_seq[i].valid_data)
continue;
/* Make things a bit easier to read. */
int ident = r;
while (ident--) {
printf("\t");
}
printf("Reader %d: Instance%d->value = %d\n", r, data_seq[i].id,
data_seq[i].value);
}
retcode = ordered_reader[r]->return_loan(data_seq, info_seq);
if (retcode != DDS_RETCODE_OK) {
printf("return loan error %d\n", retcode);
}
info_seq.length(0);
data_seq.length(0);
}
}
/* 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[2] = { 0 };
DDSTopic *topic = NULL;
DDSDataReader *reader[2] = { 0 };
DDS_ReturnCode_t retcode;
const char *type_name = NULL;
int count = 0;
DDS_Duration_t receive_period = { 4, 0 };
int status = 0;
int i = 0;
char* profile_name[] = { "ordered_Profile_subscriber_instance",
"ordered_Profile_subscriber_topic" };
/* 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;
}
/* Register the type before creating the topic */
type_name = orderedTypeSupport::get_type_name();
retcode = orderedTypeSupport::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 ordered", 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;
}
/* Start changes for ordered_presentation */
/* Create two subscribers to illustrate different presentation QoS
* This is a publisher/subscriber level QoS, so we have to
* do it here instead of just making two datareaders
*/
orderedDataReader *ordered_reader[2] = { 0 };
/* Subscriber[0], reader[0] and ordered_reader[0] is getting
* the profile "ordered_Profile_subscriber_instance"
*/
/* Subscriber[1], reader[1] and ordered_reader[1] is getting
* the profile "ordered_Profile_subscriber_topic"
*/
for (i = 0; i < MAX_SUBSCRIBERS; ++i) {
printf("Subscriber %d using %s\n", i, profile_name[i]);
subscriber[i] = participant->create_subscriber_with_profile(
"ordered_Library", profile_name[i], NULL, DDS_STATUS_MASK_NONE);
if (subscriber[i] == NULL) {
printf("create_subscriber%d error\n", i);
subscriber_shutdown(participant);
return -1;
}
reader[i] = subscriber[i]->create_datareader_with_profile(topic,
"ordered_Library", profile_name[i], NULL, DDS_STATUS_MASK_ALL);
if (reader[i] == NULL) {
printf("create_datareader%d error\n", i);
subscriber_shutdown(participant);
return -1;
}
ordered_reader[i] = orderedDataReader::narrow(reader[i]);
if (ordered_reader[i] == NULL) {
printf("DataReader%d narrow error\n", i);
return -1;
}
}
/* If you want to change the Publisher's QoS programmatically rather than
* using the XML file, you will need to add the following lines to your
* code and comment out the above 'for' loop.
*/
/* for (int i = 0; i < MAX_SUBSCRIBERS; ++i) {
*/ /* Get default subscriber QoS to customize */
/* DDS_SubscriberQos subscriber_qos;
retcode = participant->get_default_subscriber_qos(subscriber_qos);
if (retcode != DDS_RETCODE_OK) {
printf("get_default_subscriber_qos error\n");
return -1;
}
*/ /* Set this for both subscribers */
/* subscriber_qos.presentation.ordered_access = DDS_BOOLEAN_TRUE;
if (i == 0) {
printf("Subscriber 0 using Instance access scope\n");
subscriber_qos.presentation.access_scope =
DDS_INSTANCE_PRESENTATION_QOS;
} else {
printf("Subscriber 1 using Topic access scope\n");
subscriber_qos.presentation.access_scope =
DDS_TOPIC_PRESENTATION_QOS;
}
*/ /* To create subscriber with default QoS, use
* DDS_SUBSCRIBER_QOS_DEFAULT instead of subscriber_qos */
/* subscriber[i] = participant->create_subscriber(subscriber_qos, NULL,
DDS_STATUS_MASK_NONE);
if (subscriber[i] == NULL) {
printf("create_subscriber error\n");
subscriber_shutdown(participant);
return -1;
}
*/ /* No listener needed, but we do need to increase history depth */
/* Get default datareader QoS to customize */
/* DDS_DataReaderQos datareader_qos;
retcode = subscriber[i]->get_default_datareader_qos(datareader_qos);
if (retcode != DDS_RETCODE_OK) {
printf("get_default_datareader_qos error\n");
return -1;
}
datareader_qos.history.depth = 10;
*/ /* To create datareader with default QoS,
* use DDS_DATAREADER_QOS_DEFAULT instead of datareader_qos */
/* reader[i] = subscriber[i]->create_datareader(topic, datareader_qos,
NULL, DDS_STATUS_MASK_ALL);
if (reader[i] == NULL) {
printf("create_datareader error\n");
subscriber_shutdown(participant);
return -1;
}
ordered_reader[i] = orderedDataReader::narrow(reader[i]);
if (ordered_reader[i] == NULL) {
printf("DataReader narrow error\n");
return -1;
}
}
*/
/* Poll for data every 4 seconds */
/* Main loop */
for (count = 0; (sample_count == 0) || (count < sample_count); ++count) {
printf("ordered subscriber sleeping for %d sec...\n",
receive_period.sec);
NDDSUtility::sleep(receive_period);
poll_data(ordered_reader, 2);
}
/* 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/ordered_presentation/c++/ordered_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.
******************************************************************************/
/* ordered_publisher.cxx
A publication of data of type ordered
This file is derived from code automatically generated by the rtiddsgen
command:
rtiddsgen -language C++ -example <arch> ordered.idl
Example publication of type ordered 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>/ordered_subscriber <domain_id> <sample_count>
(3) Start the publication with the command
objs/<arch>/ordered_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>/ordered_publisher <domain_id> o
objs/<arch>/ordered_subscriber <domain_id>
On Windows:
objs\<arch>\ordered_publisher <domain_id>
objs\<arch>\ordered_subscriber <domain_id>
modification history
------------ -------
*/
#include <stdio.h>
#include <stdlib.h>
#ifdef RTI_VX653
#include <vThreadsData.h>
#endif
#include "ordered.h"
#include "orderedSupport.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;
orderedDataWriter * ordered_writer = NULL;
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_with_profile("ordered_Library",
"ordered_Profile_subscriber_instance", NULL /* listener */,
DDS_STATUS_MASK_NONE);
if (publisher == NULL) {
printf("create_publisher error\n");
publisher_shutdown(participant);
return -1;
}
/* If you want to change the Publisher'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_publisher call above.
*
* In this case, we set the presentation publish mode ordered in the topic.
*/
/* Get default publisher QoS to customize */
/* DDS_PublisherQos publisher_qos;
retcode = participant->get_default_publisher_qos(publisher_qos);
if (retcode != DDS_RETCODE_OK) {
printf("get_default_publisher_qos error\n");
return -1;
}
publisher_qos.presentation.access_scope = DDS_TOPIC_PRESENTATION_QOS;
publisher_qos.presentation.ordered_access = DDS_BOOLEAN_TRUE;
*/ /* To create publisher with default QoS, use DDS_PUBLISHER_QOS_DEFAULT
instead of publisher_qos */
/* publisher = participant->create_publisher(publisher_qos, NULL,
DDS_STATUS_MASK_NONE);
if (publisher == NULL) {
printf("create_participant error\n");
publisher_shutdown(participant);
return -1;
}
*/
/* Register type before creating topic */
type_name = orderedTypeSupport::get_type_name();
retcode = orderedTypeSupport::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 ordered", 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;
}
ordered_writer = orderedDataWriter::narrow(writer);
if (ordered_writer == NULL) {
printf("DataWriter narrow error\n");
publisher_shutdown(participant);
return -1;
}
/* Start changes for Ordered_Presentation */
/* Create two instances*/
ordered *instance0 = NULL;
ordered *instance1 = NULL;
DDS_InstanceHandle_t handle0 = DDS_HANDLE_NIL;
DDS_InstanceHandle_t handle1 = DDS_HANDLE_NIL;
/* Create data sample for writing */
instance0 = orderedTypeSupport::create_data();
if (instance0 == NULL) {
printf("orderedTypeSupport::create_data0 error\n");
publisher_shutdown(participant);
return -1;
}
instance1 = orderedTypeSupport::create_data();
if (instance1 == NULL) {
printf("orderedTypeSupport::create_data1 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 */
instance0->id = 0;
instance1->id = 1;
handle0 = ordered_writer->register_instance(*instance0);
handle1 = ordered_writer->register_instance(*instance1);
/* Main loop */
for (count = 0; (sample_count == 0) || (count < sample_count); ++count) {
instance0->value = count;
instance1->value = count;
printf("writing instance0, value->%d\n", instance0->value);
retcode = ordered_writer->write(*instance0, handle0);
if (retcode != DDS_RETCODE_OK) {
printf("write error %d\n", retcode);
}
printf("writing instance1, value->%d\n", instance1->value);
retcode = ordered_writer->write(*instance1, handle1);
if (retcode != DDS_RETCODE_OK) {
printf("write error %d\n", retcode);
}
NDDSUtility::sleep(send_period);
}
retcode = ordered_writer->unregister_instance(*instance0, handle0);
if (retcode != DDS_RETCODE_OK) {
printf("unregister instance0 error %d\n", retcode);
}
retcode = ordered_writer->unregister_instance(*instance1, handle1);
if (retcode != DDS_RETCODE_OK) {
printf("unregister instance1 error %d\n", retcode);
}
/* Delete data sample */
retcode = orderedTypeSupport::delete_data(instance0);
if (retcode != DDS_RETCODE_OK) {
printf("orderedTypeSupport::delete_data0 error %d\n", retcode);
}
retcode = orderedTypeSupport::delete_data(instance1);
if (retcode != DDS_RETCODE_OK) {
printf("orderedTypeSupport::delete_data1 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/ordered_presentation/c/ordered_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.
******************************************************************************/
/* ordered_subscriber.c
A subscription example
This file is derived from code automatically generated by the rtiddsgen
command:
rtiddsgen -language C -example <arch> ordered.idl
Example subscription of type ordered 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>/ordered_subscriber <domain_id> <sample_count>
(3) Start the publication with the command
objs/<arch>/ordered_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>/ordered_publisher <domain_id>
objs/<arch>/ordered_subscriber <domain_id>
On Windows systems:
objs\<arch>\ordered_publisher <domain_id>
objs\<arch>\ordered_subscriber <domain_id>
modification history
------------ -------
*/
#include <stdio.h>
#include <stdlib.h>
#include "ndds/ndds_c.h"
#include "ordered.h"
#include "orderedSupport.h"
#define MAX_SUBSCRIBERS 2
/* Start changes for Ordered_Presentation */
/* No listener is needed; we poll readers in this function*/
void poll_data(orderedDataReader *ordered_reader[], int numreaders) {
struct DDS_SampleInfoSeq info_seq;
struct orderedSeq data_seq = DDS_SEQUENCE_INITIALIZER;
DDS_ReturnCode_t retcode = DDS_RETCODE_OK;
int r, i, ident;
for (r = 0; r < numreaders; ++r) {
retcode = orderedDataReader_take(ordered_reader[r], &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) {
/* Not an error */
continue;
} else if (retcode != DDS_RETCODE_OK) {
/* Is an error */
printf("take error: %d\n", retcode);
return;
}
for (i = 0; i < orderedSeq_get_length(&data_seq); ++i) {
ordered* data;
if (DDS_SampleInfoSeq_get_reference(&info_seq, i)->valid_data) {
data = orderedSeq_get_reference(&data_seq, i);
/* Make things a bit easier to read. */
ident = r;
while (ident--) {
printf("\t");
}
printf("Reader %d: Instance%d->value = %d\n", r, data->id,
data->value);
}
}
retcode = orderedDataReader_return_loan(ordered_reader[r], &data_seq,
&info_seq);
if (retcode != DDS_RETCODE_OK) {
printf("return loan error %d\n", retcode);
}
DDS_SampleInfoSeq_set_maximum(&info_seq, 0);
orderedSeq_set_maximum(&data_seq, 0);
}
}
/* End changes for Ordered_Presentation */
/* Delete all entities */
static int subscriber_shutdown(DDS_DomainParticipant *participant,
struct DDS_SubscriberQos *subscriber_qos,
struct DDS_DataReaderQos *datareader_qos) {
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;
}
retcode = DDS_DataReaderQos_finalize(datareader_qos);
if (retcode != DDS_RETCODE_OK) {
printf("DataReaderQos_finalize error %d\n", retcode);
status = -1;
}
retcode = DDS_SubscriberQos_finalize(subscriber_qos);
if (retcode != DDS_RETCODE_OK) {
printf("SubscriberQos_finalize 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[MAX_SUBSCRIBERS] = { 0 };
DDS_Topic *topic = NULL;
DDS_DataReader *reader[MAX_SUBSCRIBERS] = { 0 };
DDS_ReturnCode_t retcode;
const char *type_name = NULL;
int count = 0;
struct DDS_Duration_t poll_period = { 4, 0 };
orderedDataReader *ordered_reader[MAX_SUBSCRIBERS] = { 0 };
int i;
struct DDS_SubscriberQos subscriber_qos = DDS_SubscriberQos_INITIALIZER;
struct DDS_DataReaderQos datareader_qos = DDS_DataReaderQos_INITIALIZER;
char* profile_name[] = { "ordered_Profile_subscriber_instance",
"ordered_Profile_subscriber_topic" };
/* 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, &subscriber_qos, &datareader_qos);
return -1;
}
/* Register the type before creating the topic */
type_name = orderedTypeSupport_get_type_name();
retcode = orderedTypeSupport_register_type(participant, type_name);
if (retcode != DDS_RETCODE_OK) {
printf("register_type error %d\n", retcode);
subscriber_shutdown(participant, &subscriber_qos, &datareader_qos);
return -1;
}
/* To customize topic QoS, use
the configuration file USER_QOS_PROFILES.xml */
topic = DDS_DomainParticipant_create_topic(participant, "Example ordered",
type_name, &DDS_TOPIC_QOS_DEFAULT, NULL /* listener */,
DDS_STATUS_MASK_NONE);
if (topic == NULL) {
printf("create_topic error\n");
subscriber_shutdown(participant, &subscriber_qos, &datareader_qos);
return -1;
}
/* Start changes for ordered_presentation */
/* Create two subscriber to illustrate different presentation QoS
* This is a publisher/subscriber level QoS, so we have to do it
* here instead of just making two datareaders
*/
/* Subscriber[0], reader[0] and ordered_reader[0] is getting
* the profile "ordered_Profile_subscriber_instance"
*/
for (i = 0; i < MAX_SUBSCRIBERS; ++i) {
/* Subscriber[1], reader[1] and ordered_reader[1] is getting
* the profile "ordered_Profile_subscriber_topic"
*/
printf("Subscriber %d using %s\n", i, profile_name[i]);
subscriber[i] = DDS_DomainParticipant_create_subscriber_with_profile(
participant, "ordered_Library", profile_name[i],
NULL /* Listener */, DDS_STATUS_MASK_NONE);
if (subscriber[i] == NULL) {
printf("create_subscriber%d error\n", i);
subscriber_shutdown(participant, &subscriber_qos, &datareader_qos);
return -1;
}
reader[i] = DDS_Subscriber_create_datareader_with_profile(subscriber[i],
DDS_Topic_as_topicdescription(topic), "ordered_Library",
profile_name[i], NULL, DDS_STATUS_MASK_NONE);
if (reader[i] == NULL) {
printf("create_datareader%d error\n", i);
subscriber_shutdown(participant, &subscriber_qos, &datareader_qos);
return -1;
}
ordered_reader[i] = orderedDataReader_narrow(reader[i]);
if (ordered_reader[i] == NULL) {
printf("DataReader%d narrow error\n", i);
return -1;
}
}
/* If you want to change the Publisher's QoS programmatically rather than
* using the XML file, you will need to add the following lines to your
* code and comment out the above 'for' loop.
*/
/*
for (i = 0; i < MAX_SUBSCRIBERS; ++i) {
*/ /* Get default subscriber QoS to customize */
/* retcode = DDS_DomainParticipant_get_default_subscriber_qos(participant,
&subscriber_qos);
if (retcode != DDS_RETCODE_OK) {
printf("get_default_subscriber_qos error\n");
return -1;
}
*/ /* Set ordered_access = TRUE for both subscribers */
/* subscriber_qos.presentation.ordered_access = DDS_BOOLEAN_TRUE;
*/ /* We are assuming there are only 2 subscribers. Otherwise you
* will need to modify the following conditions.
*/
/* if (i == 0) {
printf("Subscriber 0 using Instance access scope\n");
subscriber_qos.presentation.access_scope =
DDS_INSTANCE_PRESENTATION_QOS;
} else {
printf("Subscriber 1 using Topic access scope\n");
subscriber_qos.presentation.access_scope =
DDS_TOPIC_PRESENTATION_QOS;
}
*/ /* To create subscriber with default QoS, use DDS_SUBSCRIBER_QOS_DEFAULT
instead of subscriber_qos */
/* subscriber[i] = DDS_DomainParticipant_create_subscriber(participant,
&subscriber_qos, NULL, DDS_STATUS_MASK_NONE);
if (subscriber == NULL) {
printf("create_subscriber error\n");
subscriber_shutdown(participant, &subscriber_qos, &datareader_qos);
return -1;
}
*/ /* No listener needed, but we do need to increase history depth */
/* Get default datareader QoS to customize */
/* retcode = DDS_Subscriber_get_default_datareader_qos(subscriber[i],
&datareader_qos);
if (retcode != DDS_RETCODE_OK) {
printf("get_default_datareader_qos error\n");
return -1;
}
datareader_qos.history.depth = 10;
*/ /* To create datareader with default QoS, use DDS_DATAREADER_QOS_DEFAULT
instead of datareader_qos */
/* reader[i] = DDS_Subscriber_create_datareader(subscriber[i],
DDS_Topic_as_topicdescription(topic), &datareader_qos, NULL,
DDS_STATUS_MASK_NONE);
if (reader == NULL) {
printf("create_datareader error\n");
subscriber_shutdown(participant, &subscriber_qos, &datareader_qos);
return -1;
}
ordered_reader[i] = orderedDataReader_narrow(reader[i]);
if (ordered_reader[i] == NULL) {
printf("DataReader narrow error\n");
return -1;
}
}
*/
/* Main loop */
for (count = 0; (sample_count == 0) || (count < sample_count); ++count) {
printf("ordered subscriber sleeping for %d sec...\n", poll_period.sec);
NDDS_Utility_sleep(&poll_period);
poll_data(ordered_reader, MAX_SUBSCRIBERS);
}
/* Cleanup and delete all entities */
return subscriber_shutdown(participant, &subscriber_qos, &datareader_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/ordered_presentation/c/ordered_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.
******************************************************************************/
/* ordered_publisher.c
A publication of data of type ordered
This file is derived from code automatically generated by the rtiddsgen
command:
rtiddsgen -language C -example <arch> ordered.idl
Example publication of type ordered 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>/ordered_subscriber <domain_id> <sample_count>
(3) Start the publication with the command
objs/<arch>/ordered_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>/ordered_publisher <domain_id>
objs/<arch>/ordered_subscriber <domain_id>
On Windows:
objs\<arch>\ordered_publisher <domain_id>
objs\<arch>\ordered_subscriber <domain_id>
modification history
------------ -------
*/
#include <stdio.h>
#include <stdlib.h>
#include "ndds/ndds_c.h"
#include "ordered.h"
#include "orderedSupport.h"
/* Delete all entities */
static int publisher_shutdown(DDS_DomainParticipant *participant,
struct DDS_PublisherQos *publisher_qos) {
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;
}
retcode = DDS_PublisherQos_finalize(publisher_qos);
if (retcode != DDS_RETCODE_OK) {
printf("publisherQos_finalize 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;
orderedDataWriter *ordered_writer = NULL;
ordered *instance0 = NULL;
ordered *instance1 = NULL;
DDS_ReturnCode_t retcode;
DDS_InstanceHandle_t instance_handle0 = DDS_HANDLE_NIL;
DDS_InstanceHandle_t instance_handle1 = DDS_HANDLE_NIL;
const char *type_name = NULL;
int count = 0;
struct DDS_Duration_t send_period = { 1, 0 };
struct DDS_PublisherQos publisher_qos = DDS_PublisherQos_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, &publisher_qos);
return -1;
}
publisher = DDS_DomainParticipant_create_publisher_with_profile(participant,
"ordered_Library", "ordered_Profile_subscriber_instance",
NULL /* listener */, DDS_STATUS_MASK_NONE);
if (publisher == NULL) {
printf("create_publisher error\n");
publisher_shutdown(participant, &publisher_qos);
return -1;
}
/* If you want to change the Publisher'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_publisher call above.
*
* In this case, we set the presentation publish mode ordered in the topic.
*/
/*
retcode = DDS_DomainParticipant_get_default_publisher_qos(participant,
&publisher_qos);
if (retcode != DDS_RETCODE_OK) {
printf("get_default_publisher_qos error\n");
return -1;
}
publisher_qos.presentation.access_scope = DDS_TOPIC_PRESENTATION_QOS;
publisher_qos.presentation.ordered_access = DDS_BOOLEAN_TRUE;
publisher = DDS_DomainParticipant_create_publisher(participant,
&publisher_qos, NULL, DDS_STATUS_MASK_NONE);
if (publisher == NULL) {
printf("create_publisher error\n");
publisher_shutdown(participant, &publisher_qos);
return -1;
}
*/
/* Register type before creating topic */
type_name = orderedTypeSupport_get_type_name();
retcode = orderedTypeSupport_register_type(participant, type_name);
if (retcode != DDS_RETCODE_OK) {
printf("register_type error %d\n", retcode);
publisher_shutdown(participant, &publisher_qos);
return -1;
}
/* To customize topic QoS, use
the configuration file USER_QOS_PROFILES.xml */
topic = DDS_DomainParticipant_create_topic(participant, "Example ordered",
type_name, &DDS_TOPIC_QOS_DEFAULT, NULL /* listener */,
DDS_STATUS_MASK_NONE);
if (topic == NULL) {
printf("create_topic error\n");
publisher_shutdown(participant, &publisher_qos);
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, &publisher_qos);
return -1;
}
ordered_writer = orderedDataWriter_narrow(writer);
if (ordered_writer == NULL) {
printf("DataWriter narrow error\n");
publisher_shutdown(participant, &publisher_qos);
return -1;
}
/* Start changes for ordered_presentation */
/* Create data sample for writing */
instance0 = orderedTypeSupport_create_data_ex(DDS_BOOLEAN_TRUE);
instance1 = orderedTypeSupport_create_data_ex(DDS_BOOLEAN_TRUE);
if (instance0 == NULL || instance1 == NULL) {
printf("orderedTypeSupport_create_data error\n");
publisher_shutdown(participant, &publisher_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 */
instance0->id = 0;
instance1->id = 1;
instance_handle0 = orderedDataWriter_register_instance(ordered_writer,
instance0);
instance_handle1 = orderedDataWriter_register_instance(ordered_writer,
instance1);
/* Main loop */
for (count = 0; (sample_count == 0) || (count < sample_count); ++count) {
/* Modify the data to be written here */
instance0->value = count;
instance1->value = count;
printf("Writing instance0, value->%d\n", instance0->value);
retcode = orderedDataWriter_write(ordered_writer, instance0,
&instance_handle0);
if (retcode != DDS_RETCODE_OK) {
printf("write instance0 error %d\n", retcode);
}
printf("Writing instance1, value->%d\n", instance1->value);
retcode = orderedDataWriter_write(ordered_writer, instance1,
&instance_handle1);
if (retcode != DDS_RETCODE_OK) {
printf("write instance0 error %d\n", retcode);
}
NDDS_Utility_sleep(&send_period);
}
retcode = orderedDataWriter_unregister_instance(ordered_writer, instance0,
&instance_handle0);
if (retcode != DDS_RETCODE_OK) {
printf("unregister instance error %d\n", retcode);
}
retcode = orderedDataWriter_unregister_instance(ordered_writer, instance1,
&instance_handle1);
if (retcode != DDS_RETCODE_OK) {
printf("unregister instance error %d\n", retcode);
}
/* Delete data sample */
retcode = orderedTypeSupport_delete_data_ex(instance0, DDS_BOOLEAN_TRUE);
if (retcode != DDS_RETCODE_OK) {
printf("orderedTypeSupport_delete_data instance0 error %d\n", retcode);
}
retcode = orderedTypeSupport_delete_data_ex(instance1, DDS_BOOLEAN_TRUE);
if (retcode != DDS_RETCODE_OK) {
printf("orderedTypeSupport_delete_data instance1 error %d\n", retcode);
}
/* Cleanup and delete delete all entities */
return publisher_shutdown(participant, &publisher_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/ordered_presentation/c++11/ordered_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 "ordered.hpp"
#include <dds/dds.hpp>
using namespace dds::core;
using namespace dds::core::cond;
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;
// Instead of using listeners, we are polling the readers to be able to see
// the order of a set of received samples.
void poll_readers(std::vector< DataReader<ordered> >& readers)
{
for (std::vector<int>::size_type i = 0; i < readers.size(); i++) {
LoanedSamples<ordered> samples = readers[i].take();
for (auto sample : samples) {
if (sample.info().valid()) {
std::cout << std::string(i, '\t') << "Reader " << i
<< ": Instance" << sample.data().id()
<< "->value = " << sample.data().value()
<< std::endl;
}
}
}
}
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<ordered> topic(participant, "Example ordered");
// Create a reader per QoS profile: ordering by topic and instance modes.
std::vector<std::string> profile_names = {
"ordered_Library::ordered_Profile_subscriber_instance",
"ordered_Library::ordered_Profile_subscriber_topic" };
std::vector< DataReader<ordered> > readers;
for (std::vector<int>::size_type i = 0; i < profile_names.size(); i++) {
std::cout << "Subscriber " << i << " using " << profile_names[i]
<< std::endl;
// Retrieve the subscriber QoS from USER_QOS_PROFILES.xml
SubscriberQos subscriber_qos = QosProvider::Default().subscriber_qos(
profile_names[i]);
// If you want to change the Subscriber's QoS programmatically rather
// than using the XML file, you will need to comment out the previous
// subscriber_qos assignment and uncomment these files.
// SubscriberQos subscriber_qos;
// if (i == 0) {
// subscriber_qos << Presentation::InstanceAccessScope(false, true);
// } else if (i == 1) {
// subscriber_qos << Presentation::TopicAccessScope(false, true);
// }
// Create a subscriber with the custom QoS.
Subscriber subscriber(participant, subscriber_qos);
// Retrieve the DataReader QoS from USER_QOS_PROFILES.xml
DataReaderQos reader_qos = QosProvider::Default().datareader_qos(
profile_names[i]);
// If you want to change the DataReader's QoS programmatically rather
// than using the XML file, you will need to comment out the previous
// reader_qos assignment and uncomment these files.
// DataReaderQos reader_qos;
// reader_qos << History::KeepLast(10)
// << Reliability::Reliable();
// Create a DataReader with the custom QoS.
DataReader<ordered> reader(subscriber, topic, reader_qos);
readers.push_back(reader);
}
// Main loop
for (int count = 0; (sample_count == 0) || (count < sample_count); count++){
std::cout << "ordered subscriber sleeping for 4 sec.." << std::endl;
rti::util::sleep(Duration(4));
poll_readers(readers);
}
}
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/ordered_presentation/c++11/ordered_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 "ordered.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);
// Retrieve the custom ordered publisher QoS, from USER_QOS_PROFILES.xml
PublisherQos publisher_qos = QosProvider::Default().publisher_qos(
"ordered_Library::ordered_Profile_subscriber_instance");
// If you want to change the Publisher's QoS programmatically rather
// than using the XML file, you will need to comment out the previous
// publisher_qos assignment and uncomment these files.
// PublisherQos publisher_qos;
// publisher_qos << Presentation::TopicAccessScope(false, true);
// Create a publisher with the ordered QoS.
Publisher publisher(participant, publisher_qos);
// Create a Topic -- and automatically register the type.
Topic<ordered> topic(participant, "Example ordered");
// Retrieve the DataWriter QoS, from USER_QOS_PROFILES.xml
DataWriterQos writer_qos = QosProvider::Default().datawriter_qos(
"ordered_Library::ordered_Profile_subscriber_instance");
// If you want to change the Publisher's QoS programmatically rather
// than using the XML file, you will need to comment out the previous
// writer_qos assignment and uncomment these files.
// DataWriterQos writer_qos;
// writer_qos << Reliability::Reliable();
// Create a DataWriter.
DataWriter<ordered> writer(publisher, topic, writer_qos);
// Create two samples with different ID and register them
ordered instance0(0, 0);
InstanceHandle handle0 = writer.register_instance(instance0);
ordered instance1(1, 0);
InstanceHandle handle1 = writer.register_instance(instance1);
// Main loop
for (int count = 0; (sample_count == 0) || (count < sample_count); ++count){
// Update content.
instance0.value(count);
instance1.value(count);
// Write the two samples.
std::cout << "writing instance0, value->" << instance0.value()
<< std::endl;
writer.write(instance0, handle0);
std::cout << "writing instance1, value->" << instance1.value()
<< std::endl;
writer.write(instance1, handle1);
rti::util::sleep(Duration(1));
}
// Unregister the samples.
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 (std::exception ex) {
std::cout << "Exception caught: " << ex.what() << std::endl;
return -1;
}
return 0;
}
| cxx |
rticonnextdds-examples | data/projects/rticonnextdds-examples/waitset_query_cond/c++/waitset_query_cond_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_query_cond_subscriber.cxx
A subscription example
This file is derived from code automatically generated by the rtiddsgen
command:
rtiddsgen -language C++ -example <arch> waitset_query_cond.idl
Example subscription of type waitset_query_cond 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_query_cond_subscriber <domain_id> <sample_count>
(3) Start the publication with the command
objs/<arch>/waitset_query_cond_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_query_cond_publisher <domain_id>
objs/<arch>/waitset_query_cond_subscriber <domain_id>
On Windows:
objs\<arch>\waitset_query_cond_publisher <domain_id>
objs\<arch>\waitset_query_cond_subscriber <domain_id>
modification history
------------ -------
*/
#include <stdio.h>
#include <stdlib.h>
#ifdef RTI_VX653
#include <vThreadsData.h>
#endif
#include "waitset_query_cond.h"
#include "waitset_query_condSupport.h"
#include "ndds/ndds_cpp.h"
/* We don't need to use listeners as we are going to use WaitSet 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;
DDS_Duration_t wait_timeout = {1,0};
int status = 0;
/* Additional variable for this example */
int i = 1;
DDSQueryCondition* query_condition = NULL;
DDSWaitSet* waitset = NULL;
waitset_query_condDataReader *waitset_query_cond_reader = NULL;
const char* query_expression = DDS_String_dup("name MATCH %0");
DDS_StringSeq query_parameters;
DDSConditionSeq active_conditions_seq;
waitset_query_condSeq data_seq;
DDS_SampleInfoSeq info_seq;
/* Auxiliary variables */
char * odd_string = DDS_String_dup("'ODD'");
char * even_string = DDS_String_dup("'EVEN'");
/* 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_query_condTypeSupport::get_type_name();
retcode = waitset_query_condTypeSupport::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_query_cond",
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;
}
/* Narrow the reader into your specific data type */
waitset_query_cond_reader = waitset_query_condDataReader::narrow(reader);
if (waitset_query_cond_reader == NULL) {
printf("DataReader narrow error\n");
return -1;
}
/* Create query condition */
query_parameters.ensure_length(1,1);
/* The initial value of the parameters is EVEN string */
query_parameters[0] = even_string;
query_condition = waitset_query_cond_reader->create_querycondition(
DDS_NOT_READ_SAMPLE_STATE,
DDS_ANY_VIEW_STATE,
DDS_ANY_INSTANCE_STATE,
query_expression,
query_parameters);
if (query_condition == NULL) {
printf("create_query_condition error\n");
subscriber_shutdown(participant);
return -1;
}
waitset = new DDSWaitSet();
if (waitset == NULL) {
printf("create waitset error\n");
subscriber_shutdown(participant);
return -1;
}
/* Attach Query Conditions */
retcode = waitset->attach_condition(
(DDSCondition*)query_condition);
if (retcode != DDS_RETCODE_OK) {
printf("attach_condition error\n");
subscriber_shutdown(participant);
return -1;
}
printf ("\n>>>Timeout: %.0d sec & %d nanosec\n",wait_timeout.sec,
wait_timeout.nanosec);
printf (">>> Query conditions: name MATCH %%0\n");
printf ("\t%%0 = %s\n", query_parameters[0]);
printf ("---------------------------------\n\n");
/* Main loop */
for (count=0; (sample_count == 0) || (count < sample_count); ++count) {
/* We set a new parameter in the Query Condition after 7 secs */
if (count == 7) {
query_parameters[0] = odd_string;
printf ("CHANGING THE QUERY CONDITION\n");
printf ("\n>>> Query conditions: name MATCH %%0\n");
printf ("\t%%0 = %s\n", query_parameters[0]);
printf (">>> We keep one sample in the history\n");
printf ("-------------------------------------\n\n");
query_condition->set_query_parameters(query_parameters);
}
/* 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, /* active conditions sequence */
wait_timeout); /* 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", retcode);
break;
}
retcode = DDS_RETCODE_OK;
while (retcode != DDS_RETCODE_NO_DATA) {
retcode = waitset_query_cond_reader->take_w_condition(
data_seq, info_seq,
DDS_LENGTH_UNLIMITED,
query_condition);
for (i = 0; i < waitset_query_condSeq_get_length(&data_seq); ++i) {
if (!info_seq[i].valid_data) {
printf("Got metadata\n");
continue;
}
waitset_query_condTypeSupport::print_data(&data_seq[i]);
}
waitset_query_cond_reader->return_loan(data_seq, info_seq);
}
}
/* 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/waitset_query_cond/c++/waitset_query_cond_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_query_cond_publisher.cxx
A publication of data of type waitset_query_cond
This file is derived from code automatically generated by the rtiddsgen
command:
rtiddsgen -language C++ -example <arch> waitset_query_cond.idl
Example publication of type waitset_query_cond 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_query_cond_subscriber <domain_id> <sample_count>
(3) Start the publication with the command
objs/<arch>/waitset_query_cond_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_query_cond_publisher <domain_id> o
objs/<arch>/waitset_query_cond_subscriber <domain_id>
On Windows:
objs\<arch>\waitset_query_cond_publisher <domain_id>
objs\<arch>\waitset_query_cond_subscriber <domain_id>
modification history
------------ -------
*/
#include <stdio.h>
#include <stdlib.h>
#ifdef RTI_VX653
#include <vThreadsData.h>
#endif
#include "waitset_query_cond.h"
#include "waitset_query_condSupport.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;
waitset_query_condDataWriter * waitset_query_cond_writer = NULL;
waitset_query_cond *instance = NULL;
DDS_ReturnCode_t retcode;
DDS_InstanceHandle_t instance_handle = DDS_HANDLE_NIL;
const char *type_name = NULL;
int count = 0;
DDS_Duration_t send_period = {0,500000000};
/* Auxiliary variables */
char * odd_string = DDS_String_dup("ODD");
char * even_string = DDS_String_dup("EVEN");
/* 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_query_condTypeSupport::get_type_name();
retcode = waitset_query_condTypeSupport::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_query_cond",
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;
}
waitset_query_cond_writer = waitset_query_condDataWriter::narrow(writer);
if (waitset_query_cond_writer == NULL) {
printf("DataWriter narrow error\n");
publisher_shutdown(participant);
return -1;
}
/* Create data sample for writing */
instance = waitset_query_condTypeSupport::create_data();
if (instance == NULL) {
printf("waitset_query_condTypeSupport::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_query_cond_writer->register_instance(*instance);
*/
/* Main loop */
for (count=0; (sample_count == 0) || (count < sample_count); ++count) {
printf("Writing waitset_query_cond, count %d\n", count);
/* Modify the data to be sent here */
if(count%2 == 1){
instance->name = odd_string;
} else {
instance->name = even_string;
}
instance->x = count;
retcode = waitset_query_cond_writer->write(*instance, instance_handle);
if (retcode != DDS_RETCODE_OK) {
printf("write error %d\n", retcode);
}
NDDSUtility::sleep(send_period);
}
/*
retcode = waitset_query_cond_writer->unregister_instance(
*instance, instance_handle);
if (retcode != DDS_RETCODE_OK) {
printf("unregister instance error %d\n", retcode);
}
*/
/* Delete data sample */
retcode = waitset_query_condTypeSupport::delete_data(instance);
if (retcode != DDS_RETCODE_OK) {
printf("waitset_query_condTypeSupport::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/waitset_query_cond/c/waitset_query_cond_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_query_cond_publisher.c
A publication of data of type waitset_query_cond
This file is derived from code automatically generated by the rtiddsgen
command:
rtiddsgen -language C -example <arch> waitset_query_cond.idl
Example publication of type waitset_query_cond 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_query_cond_subscriber <domain_id> <sample_count>
(3) Start the publication with the command
objs/<arch>/waitset_query_cond_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_query_cond_publisher <domain_id>
objs/<arch>/waitset_query_cond_subscriber <domain_id>
On Windows:
objs\<arch>\waitset_query_cond_publisher <domain_id>
objs\<arch>\waitset_query_cond_subscriber <domain_id>
modification history
------------ -------
*/
#include <stdio.h>
#include <stdlib.h>
#include "ndds/ndds_c.h"
#include "waitset_query_cond.h"
#include "waitset_query_condSupport.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_query_condDataWriter *waitset_query_cond_writer = NULL;
waitset_query_cond *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,500000000};
/* Auxiliary variables */
char * odd_string = DDS_String_dup("ODD");
char * even_string = DDS_String_dup("EVEN");
/* 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_query_condTypeSupport_get_type_name();
retcode = waitset_query_condTypeSupport_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_query_cond",
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_query_cond_writer = waitset_query_condDataWriter_narrow(writer);
if (waitset_query_cond_writer == NULL) {
printf("DataWriter narrow error\n");
publisher_shutdown(participant);
return -1;
}
/* Create data sample for writing */
instance = waitset_query_condTypeSupport_create_data_ex(DDS_BOOLEAN_TRUE);
if (instance == NULL) {
printf("waitset_query_condTypeSupport_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_query_condDataWriter_register_instance(
waitset_query_cond_writer, instance);
*/
/* Main loop */
for (count=0; (sample_count == 0) || (count < sample_count); ++count) {
printf("Writing waitset_query_cond, count %d\n", count);
/* Modify the data to be written here */
if(count%2 == 1){
instance->name = odd_string;
} else {
instance->name = even_string;
}
instance->x = count;
/* Write data */
retcode = waitset_query_condDataWriter_write(
waitset_query_cond_writer, instance, &instance_handle);
if (retcode != DDS_RETCODE_OK) {
printf("write error %d\n", retcode);
}
NDDS_Utility_sleep(&send_period);
}
/*
retcode = waitset_query_condDataWriter_unregister_instance(
waitset_query_cond_writer, instance, &instance_handle);
if (retcode != DDS_RETCODE_OK) {
printf("unregister instance error %d\n", retcode);
}
*/
/* Delete data sample */
retcode = waitset_query_condTypeSupport_delete_data_ex(instance,
DDS_BOOLEAN_TRUE);
if (retcode != DDS_RETCODE_OK) {
printf("waitset_query_condTypeSupport_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/waitset_query_cond/c/waitset_query_cond_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_query_cond_subscriber.c
A subscription example
This file is derived from code automatically generated by the rtiddsgen
command:
rtiddsgen -language C -example <arch> waitset_query_cond.idl
Example subscription of type waitset_query_cond 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_query_cond_subscriber <domain_id> <sample_count>
(3) Start the publication with the command
objs/<arch>/waitset_query_cond_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_query_cond_publisher <domain_id>
objs/<arch>/waitset_query_cond_subscriber <domain_id>
On Windows systems:
objs\<arch>\waitset_query_cond_publisher <domain_id>
objs\<arch>\waitset_query_cond_subscriber <domain_id>
modification history
------------ -------
*/
#include <stdio.h>
#include <stdlib.h>
#include "ndds/ndds_c.h"
#include "waitset_query_cond.h"
#include "waitset_query_condSupport.h"
/* We don't need to use listeners as we are going to use Waitsets and Conditions
* so we have removed the auto generated code for listeners here
*/
/* 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;
DDS_ReturnCode_t retcode;
const char *type_name = NULL;
int count = 0;
struct DDS_Duration_t wait_timeout = {1,0};
/* Additional variables for this example */
int i;
DDS_WaitSet *waitset = NULL;
DDS_QueryCondition* query_condition = NULL;
waitset_query_condDataReader *waitset_query_cond_reader = NULL;
const char* query_expression = DDS_String_dup("name MATCH %0");
struct DDS_StringSeq query_parameters;
struct DDS_ConditionSeq active_conditions_seq =
DDS_SEQUENCE_INITIALIZER;
struct waitset_query_condSeq data_seq = DDS_SEQUENCE_INITIALIZER;
struct DDS_SampleInfoSeq info_seq = DDS_SEQUENCE_INITIALIZER;
/* Auxiliary variables */
char * odd_string = DDS_String_dup("'ODD'");
char * even_string = DDS_String_dup("'EVEN'");
/* The initial value of the param_list is EVEN string */
const char* param_list[] = {even_string};
/* 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_query_condTypeSupport_get_type_name();
retcode = waitset_query_condTypeSupport_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_query_cond",
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;
}
/* Narrow the reader into your specific data type */
waitset_query_cond_reader = waitset_query_condDataReader_narrow(reader);
if (waitset_query_cond_reader == NULL) {
printf("DataReader narrow error\n");
return -1;
}
/* Create query condition */
DDS_StringSeq_initialize(&query_parameters);
DDS_StringSeq_set_maximum(&query_parameters, 1);
/*Here we set the default filter using the param_list */
DDS_StringSeq_from_array(&query_parameters, param_list, 1);
query_condition = DDS_DataReader_create_querycondition(
reader,
DDS_NOT_READ_SAMPLE_STATE,
DDS_ANY_VIEW_STATE,
DDS_ANY_INSTANCE_STATE,
query_expression,
&query_parameters);
if (query_condition == NULL) {
printf("create_query_condition error\n");
subscriber_shutdown(participant);
return -1;
}
waitset = DDS_WaitSet_new();
if (waitset == NULL) {
printf("create waitset error\n");
subscriber_shutdown(participant);
return -1;
}
/* Attach Query Conditions */
retcode = DDS_WaitSet_attach_condition(waitset,
(DDS_Condition*)query_condition);
if (retcode != DDS_RETCODE_OK) {
printf("attach_condition error\n");
subscriber_shutdown(participant);
return -1;
}
printf ("\n>>>Timeout: %.0d sec & %d nanosec\n",wait_timeout.sec,
wait_timeout.nanosec);
printf (">>> Query conditions: name MATCH %%0\n");
printf ("\t%%0 = %s\n", param_list[0]);
printf ("---------------------------------\n\n");
/* Main loop */
for (count=0; (sample_count == 0) || (count < sample_count); ++count) {
/* We set a new parameter in the Query Condition after 7 secs */
if (count == 7) {
param_list[0] = odd_string;
printf ("CHANGING THE QUERY CONDITION\n");
printf ("\n>>> Query conditions: name MATCH %%0\n");
printf ("\t%%0 = %s\n", param_list[0]);
printf (">>> We keep one sample in the history\n");
printf ("-------------------------------------\n\n");
DDS_StringSeq_from_array(&query_parameters, param_list, 1);
DDS_QueryCondition_set_query_parameters(query_condition,
&query_parameters);
}
/* wait() blocks execution of the thread until one or more attached
* Conditions become true, or until a user-specified timeout expires.
*/
retcode = DDS_WaitSet_wait(
waitset, /* waitset */
&active_conditions_seq, /* active conditions sequence */
&wait_timeout); /* 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", retcode);
break;
}
retcode = DDS_RETCODE_OK;
while (retcode != DDS_RETCODE_NO_DATA) {
retcode =
waitset_query_condDataReader_take_w_condition(
waitset_query_cond_reader, &data_seq, &info_seq,
DDS_LENGTH_UNLIMITED,
DDS_QueryCondition_as_readcondition(query_condition));
for (i = 0; i < waitset_query_condSeq_get_length(&data_seq);
++i) {
if (!DDS_SampleInfoSeq_get_reference(
&info_seq, i)->valid_data) {
printf("Got metadata\n");
continue;
}
waitset_query_condTypeSupport_print_data(
waitset_query_condSeq_get_reference(&data_seq, i));
}
waitset_query_condDataReader_return_loan(
waitset_query_cond_reader, &data_seq, &info_seq);
}
}
/* 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/waitset_query_cond/c++11/waitset_query_cond_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 <dds/dds.hpp>
#include "waitset_query_cond.hpp"
using namespace dds::core;
using namespace dds::core::cond;
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.
DomainParticipant participant(domain_id);
// Create a Topic -- and automatically register the type.
Topic<waitset_query_cond> topic(participant, "Example waitset_query_cond");
// Retrieve the DataReader 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 uncomment the following lines.
// reader_qos << History::KeepLast(1);
// Create a DataReader.
DataReader<waitset_query_cond> reader(
Subscriber(participant),
topic,
reader_qos);
// Create the parameters of the condition.
// The initial value of the parameter is EVEN string to get even numbers.
std::vector<std::string> query_parameters = { "'EVEN'" };
// Create a query condition with a functor handler.
QueryCondition query_condition(
Query(reader, "name MATCH %0", query_parameters),
DataState::any_data(),
[&reader]()
{
// Using only 'take()' method will read all received samples.
// To read only samples that triggered the QueryCondition
// use 'select().condition().read()' as it's done in
// the "polling_querycondition" example.
LoanedSamples<waitset_query_cond> samples = reader.take();
for (auto sample : samples) {
if (!sample.info().valid()) {
std::cout << "Got metadata" << std::endl;
} else {
std::cout << sample.data() << std::endl;
}
}
}
);
// Create the waitset and attach the condition.
WaitSet waitset;
waitset += query_condition;
Duration wait_timeout(1);
std::cout << std::endl << ">>> Timeout: " << wait_timeout.sec() << " sec"
<< std::endl
<< ">>> Query conditions: " << query_condition.expression()
<< std::endl << "\t %%0 = " << query_parameters[0] << std::endl
<< "----------------------------------" << std::endl << std::endl;
for (int count = 0; (sample_count == 0) || (count < sample_count); count++){
// We change the parameter in the Query Condition after 7 secs.
if (count == 7) {
query_parameters[0] = "'ODD'";
query_condition.parameters(
query_parameters.begin(), query_parameters.end());
std::cout << std::endl<< "CHANGING THE QUERY CONDITION" << std::endl
<< ">>> Query conditions: "<< query_condition.expression()
<< std::endl << "\t %%0 = " << query_parameters[0]
<< std::endl << ">>> We keep one sample in the history"
<< std::endl << "-------------------------------------"
<< std::endl << std::endl;
}
// 'dispatch()' blocks execution of the thread until one or more
// attached Conditions become true, or until a user-specified timeout
// expires and then dispatches the events.
// Another way would be to use 'wait()' and check if the QueryCondition
// has been triggered as the "waitsets" example does.
waitset.dispatch(wait_timeout);
}
}
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/waitset_query_cond/c++11/waitset_query_cond_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 <dds/dds.hpp>
#include "waitset_query_cond.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)
{
// Create a DomainParticipant.
DomainParticipant participant(domain_id);
// Create a Topic -- and automatically register the type.
Topic<waitset_query_cond> topic(participant, "Example waitset_query_cond");
// Create a DataWriter.
DataWriter<waitset_query_cond> writer(Publisher(participant), topic);
// Create a data sample for writing.
waitset_query_cond instance;
// Main loop
for (int count = 0; (sample_count == 0) || (count < sample_count); ++count){
std::cout << "Writing waitset_query_cond, count " << count << std::endl;
// Set x value
instance.x(count);
// Set name field
if (count % 2 == 1) {
instance.name("ODD");
} else {
instance.name("EVEN");
}
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/get_publishers/c++/Foo_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.
******************************************************************************/
/* Foo_publisher.cxx
A publication of data of type Foo
This file is derived from code automatically generated by the rtiddsgen
command:
rtiddsgen -language C++ -example <arch> Foo.idl
This example shows how to create some publishers and how to access all
the publishers the participant has.
Example:
To run the example application on domain <domain_id>:
On Unix:
objs/<arch>/Foo_publisher <domain_id>
On Windows:
objs\<arch>\Foo_publisher <domain_id>
modification history
------------ -------
*/
#include <stdio.h>
#include <stdlib.h>
#ifdef RTI_VX653
#include <vThreadsData.h>
#endif
#include "Foo.h"
#include "FooSupport.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, *publisher2 = NULL;
DDSPublisherSeq publisherSeq;
DDSTopic *topic = NULL;
DDSDataWriter *writer = NULL;
FooDataWriter * Foo_writer = NULL;
Foo *instance = NULL;
DDS_ReturnCode_t retcode;
DDS_InstanceHandle_t instance_handle = DDS_HANDLE_NIL;
const char *type_name = NULL;
int count = 0;
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 /* listener */, DDS_STATUS_MASK_NONE);
if (participant == NULL) {
printf("create_participant error\n");
publisher_shutdown(participant);
return -1;
}
/* Start - modifying the generated example to showcase the usage of
* the get_publishers API
*/
/* 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;
}
printf("The first publisher is %p\n", publisher);
publisher2 = participant->create_publisher(DDS_PUBLISHER_QOS_DEFAULT,
NULL /* listener */, DDS_STATUS_MASK_NONE);
if (publisher2 == NULL) {
printf("create_publisher2 error\n");
publisher_shutdown(participant);
return -1;
}
printf("The second publisher is %p\n", publisher2);
printf(
"Let's call get_publisher() now and check if I get all my publishers...\n");
retcode = participant->get_publishers(publisherSeq);
if (retcode != DDS_RETCODE_OK) {
printf("get_publishers error\n");
publisher_shutdown(participant);
return -1;
/* Start modifying the generated example to showcase the usage of
* the get_publishers
*/
}
printf("I found %d publisher on this participant!\n",
publisherSeq.length());
for (count = 0; count < publisherSeq.length(); count++) {
DDSPublisher *tmp = publisherSeq[count];
printf("The %d publisher I found is: %p\n", count, tmp);
}
/* exiting */
return publisher_shutdown(participant);
/* End - modifying the generated example to showcase the usage of
* the get_publishers API
*/
}
#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/get_publishers/c/Foo_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.
******************************************************************************/
/* Foo_publisher.c
A publication of data of type Foo
This file is derived from code automatically generated by the rtiddsgen
command:
rtiddsgen -language C -example <arch> Foo.idl
This example shows how to create some publshers and how to access all
the publishers the participant has.
Example:
To run the example application on domain <domain_id>:
On Unix:
objs/<arch>/Foo_publisher <domain_id>
On Windows:
objs\<arch>\Foo_publisher <domain_id>
modification history
------------ -------
*/
#include <stdio.h>
#include <stdlib.h>
#include "ndds/ndds_c.h"
#include "Foo.h"
#include "FooSupport.h"
/* Delete all entities */
static int publisher_shutdown(DDS_DomainParticipant *participant,
struct DDS_PublisherSeq publisherSeq) {
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;
}
if (DDS_PublisherSeq_finalize(&publisherSeq)) {
printf("finalize publisherSeq error\n");
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, *publisher2 = NULL;
/* We will use this temporal publisher to print all created publishers */
DDS_Publisher *tmp = NULL;
struct DDS_PublisherSeq publisherSeq = DDS_SEQUENCE_INITIALIZER;
Foo *instance = NULL;
DDS_ReturnCode_t retcode;
const char *type_name = NULL;
int count = 0;
struct DDS_Duration_t send_period = { 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");
publisher_shutdown(participant, publisherSeq);
return -1;
}
/* Start - modifying the generated example to showcase the usage of the
* get_publishers API
*/
/* 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, publisherSeq);
return -1;
}
printf("The first publisher is %p\n", publisher);
publisher2 = DDS_DomainParticipant_create_publisher(participant,
&DDS_PUBLISHER_QOS_DEFAULT, NULL /* listener */,
DDS_STATUS_MASK_NONE);
if (publisher2 == NULL) {
printf("create_publisher2 error\n");
publisher_shutdown(participant, publisherSeq);
return -1;
}
printf("The second publisher is %p\n", publisher2);
printf("Let's call get_publisher() now and check if I get all my ");
printf("publisher...\n");
retcode = DDS_DomainParticipant_get_publishers(participant, &publisherSeq);
if (retcode != DDS_RETCODE_OK) {
printf("get_publishers error\n");
publisher_shutdown(participant, publisherSeq);
return -1;
}
/* We print the publishers obtained */
for (count = 0; count < DDS_PublisherSeq_get_length(&publisherSeq);
++count) {
tmp = DDS_PublisherSeq_get(&publisherSeq, count);
printf("The %d publisher I foud is: %p\n", count, tmp);
}
/* Cleanup and delete delete all entities */
return publisher_shutdown(participant, publisherSeq);
/* End - modifying the generated example to showcase the usage of the
* get_publishers API
*/
}
#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/get_publishers/c++03/Foo_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 <cstdlib>
#include <dds/dds.hpp>
#include "Foo.hpp"
using namespace dds::core;
using namespace dds::domain;
using namespace dds::topic;
using namespace dds::pub;
using namespace dds::pub::qos;
using namespace rti::core::policy;
void publisher_main(int domain_id)
{
// Create a DomainParticipant with default QoS.
DomainParticipant participant(domain_id);
// Retrieve publisher QoS to set names.
PublisherQos publisher_qos = QosProvider::Default().publisher_qos();
// Create the first publisher.
publisher_qos << EntityName("Foo");
Publisher publisher1(participant, publisher_qos);
std::cout << "The first publisher name is "
<< publisher1.qos().policy<EntityName>().name().get()
<< std::endl;
// Create the second publisher.
publisher_qos << EntityName("Bar");
Publisher publisher2(participant, publisher_qos);
std::cout << "The second publisher name is "
<< publisher2.qos().policy<EntityName>().name().get()
<< std::endl;
// Find the publishers.
std::cout << std::endl << "Calling to find_publishers()..." << std::endl
<< std::endl;
std::vector<Publisher> publishers;
rti::pub::find_publishers(participant, std::back_inserter(publishers));
// Iterate over the publishers and print the name.
std::cout << "Found " << publishers.size()
<< " publishers on this participant" << std::endl;
for (std::vector<int>::size_type i = 0; i < publishers.size(); i++) {
std::cout << "The " << i << " publisher name is "
<< publishers[i].qos().policy<EntityName>().name().get()
<< std::endl;
}
}
int main(int argc, char* argv[])
{
int domain_id = 0;
if (argc >= 2) {
domain_id = atoi(argv[1]);
}
// 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);
} catch (std::exception ex) {
std::cout << "Exception caught: " << ex.what() << std::endl;
return -1;
}
return 0;
}
| cxx |
rticonnextdds-examples | data/projects/rticonnextdds-examples/partitions/c++/partitions_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.
******************************************************************************/
/* partitions_publisher.cxx
A publication of data of type partitions
This file is derived from code automatically generated by the rtiddsgen
command:
rtiddsgen -language C++ -example <arch> partitions.idl
Example publication of type partitions 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>/partitions_subscriber <domain_id> <sample_count>
(3) Start the publication with the command
objs/<arch>/partitions_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>/partitions_publisher <domain_id> o
objs/<arch>/partitions_subscriber <domain_id>
On Windows:
objs\<arch>\partitions_publisher <domain_id>
objs\<arch>\partitions_subscriber <domain_id>
modification history
------------ -------
*/
#include <stdio.h>
#include <stdlib.h>
#ifdef RTI_VX653
#include <vThreadsData.h>
#endif
#include "partitions.h"
#include "partitionsSupport.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;
partitionsDataWriter * partitions_writer = NULL;
partitions *instance = NULL;
DDS_ReturnCode_t retcode;
DDS_InstanceHandle_t instance_handle = DDS_HANDLE_NIL;
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;
}
DDS_PublisherQos publisher_qos;
retcode = participant->get_default_publisher_qos(publisher_qos);
if (retcode != DDS_RETCODE_OK) {
printf("get_default_publisher_qos error\n");
return -1;
}
/* If you want to change the Partition name programmatically rather than
* using the XML, you will need to add the following lines to your code
* and comment out the create_publisher() call bellow.
*/
publisher_qos.partition.name.ensure_length(2, 2);
publisher_qos.partition.name[0] = DDS_String_dup("ABC");
publisher_qos.partition.name[1] = DDS_String_dup("foo");
printf("Setting partition to '%s', '%s'...\n",
publisher_qos.partition.name[0],
publisher_qos.partition.name[1]);
publisher = participant->create_publisher(publisher_qos,
NULL,
DDS_STATUS_MASK_NONE);
if (publisher == NULL) {
printf("create_participant error\n");
publisher_shutdown(participant);
return -1;
}
/*
publisher = participant->create_publisher(DDS_PUBLISHER_QOS_DEFAULT,
NULL,
DDS_STATUS_MASK_NONE);
if (publisher == NULL) {
printf("create_publisher error\n");
publisher_shutdown(participant);
return -1;
}
*/
/* Register type before creating topic */
type_name = partitionsTypeSupport::get_type_name();
retcode = partitionsTypeSupport::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 partitions",
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;
}
/* In this example we set a Reliable datawriter, with Transient Local
* durability. By default we set up these QoS settings via XML. If you
* want to to it programmatically, use the following code, and comment out
* the create_datawriter call bellow.
*/
/*
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.reliability.kind = DDS_RELIABLE_RELIABILITY_QOS;
datawriter_qos.durability.kind = DDS_TRANSIENT_LOCAL_DURABILITY_QOS;
datawriter_qos.history.kind = DDS_KEEP_LAST_HISTORY_QOS;
datawriter_qos.history.depth = 3;
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;
}
*/
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;
}
partitions_writer = partitionsDataWriter::narrow(writer);
if (partitions_writer == NULL) {
printf("DataWriter narrow error\n");
publisher_shutdown(participant);
return -1;
}
/* Create data sample for writing */
instance = partitionsTypeSupport::create_data();
if (instance == NULL) {
printf("partitionsTypeSupport::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 = partitions_writer->register_instance(*instance);
*/
/* Main loop */
for (count=0; (sample_count == 0) || (count < sample_count); ++count) {
printf("Writing partitions, count %d\n", count);
instance->x = count;
retcode = partitions_writer->write(*instance, instance_handle);
if (retcode != DDS_RETCODE_OK) {
printf("write error %d\n", retcode);
}
/* Every 5 samples we will change the Partition name. These are the
* partition expressions we are going to try:
* "bar", "A*", "A?C", "X*Z", "zzz", "A*C"
*/
if ((count+1) % 25 == 0) {
// Matches "ABC" -- name[1] here can match name[0] there,
// as long as there is some overlapping name
publisher_qos.partition.name[0] = DDS_String_dup("zzz");
publisher_qos.partition.name[1] = DDS_String_dup("A*C");
printf("Setting partition to '%s', '%s'...\n",
publisher_qos.partition.name[0],
publisher_qos.partition.name[1]);
publisher->set_qos(publisher_qos);
}
else if ((count+1) % 20 == 0) {
// Strings that are regular expressions aren't tested for
// literal matches, so this won't match "X*Z"
publisher_qos.partition.name[0] = DDS_String_dup("X*Z");
printf("Setting partition to '%s', '%s'...\n",
publisher_qos.partition.name[0],
publisher_qos.partition.name[1]);
publisher->set_qos(publisher_qos);
}
else if ((count+1) % 15 == 0) {
// Matches "ABC"
publisher_qos.partition.name[0] = DDS_String_dup("A?C");
printf("Setting partition to '%s', '%s'...\n",
publisher_qos.partition.name[0],
publisher_qos.partition.name[1]);
publisher->set_qos(publisher_qos);
}
else if ((count+1) % 10 == 0) {
// Matches "ABC"
publisher_qos.partition.name[0] = DDS_String_dup("A*");
printf("Setting partition to '%s', '%s'...\n",
publisher_qos.partition.name[0],
publisher_qos.partition.name[1]);
publisher->set_qos(publisher_qos);
}
else if ((count+1) % 5 == 0) {
// No literal match for "bar"
publisher_qos.partition.name[0] = DDS_String_dup("bar");
printf("Setting partition to '%s', '%s'...\n",
publisher_qos.partition.name[0],
publisher_qos.partition.name[1]);
publisher->set_qos(publisher_qos);
}
NDDSUtility::sleep(send_period);
}
/*
retcode = partitions_writer->unregister_instance(
*instance, instance_handle);
if (retcode != DDS_RETCODE_OK) {
printf("unregister instance error %d\n", retcode);
}
*/
/* Delete data sample */
retcode = partitionsTypeSupport::delete_data(instance);
if (retcode != DDS_RETCODE_OK) {
printf("partitionsTypeSupport::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/partitions/c++/partitions_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.
******************************************************************************/
/* partitions_subscriber.cxx
A subscription example
This file is derived from code automatically generated by the rtiddsgen
command:
rtiddsgen -language C++ -example <arch> partitions.idl
Example subscription of type partitions 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>/partitions_subscriber <domain_id> <sample_count>
(3) Start the publication with the command
objs/<arch>/partitions_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>/partitions_publisher <domain_id>
objs/<arch>/partitions_subscriber <domain_id>
On Windows:
objs\<arch>\partitions_publisher <domain_id>
objs\<arch>\partitions_subscriber <domain_id>
modification history
------------ -------
*/
#include <stdio.h>
#include <stdlib.h>
#ifdef RTI_VX653
#include <vThreadsData.h>
#endif
#include "partitions.h"
#include "partitionsSupport.h"
#include "ndds/ndds_cpp.h"
class partitionsListener : 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 partitionsListener::on_data_available(DDSDataReader* reader)
{
partitionsDataReader *partitions_reader = NULL;
partitionsSeq data_seq;
DDS_SampleInfoSeq info_seq;
DDS_ReturnCode_t retcode;
int i;
partitions_reader = partitionsDataReader::narrow(reader);
if (partitions_reader == NULL) {
printf("DataReader narrow error\n");
return;
}
retcode = partitions_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) {
if (info_seq[i].view_state == DDS_NEW_VIEW_STATE) {
printf("Found new instance\n");
}
partitionsTypeSupport::print_data(&data_seq[i]);
}
}
retcode = partitions_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;
partitionsListener *reader_listener = NULL;
DDSDataReader *reader = NULL;
DDS_ReturnCode_t retcode;
const char *type_name = NULL;
int count = 0;
DDS_Duration_t receive_period = {4,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;
}
DDS_SubscriberQos subscriber_qos;
retcode = participant->get_default_subscriber_qos(subscriber_qos);
if (retcode != DDS_RETCODE_OK) {
printf("get_default_subscriber_qos error\n");
return -1;
}
/* If you want to change the Partition name programmatically rather than
* using the XML, you will need to add the following lines to your code
* and comment out the create_subscriber() call bellow.
*/
/*
subscriber_qos.partition.name.ensure_length(2, 2);
subscriber_qos.partition.name[0] = DDS_String_dup("ABC");
subscriber_qos.partition.name[1] = DDS_String_dup("X*Z");
subscriber = participant->create_subscriber(subscriber_qos,
NULL,
DDS_STATUS_MASK_NONE);
if (subscriber == NULL) {
printf("create_subscriber error\n");
subscriber_shutdown(participant);
return -1;
}
*/
subscriber = participant->create_subscriber(
DDS_SUBSCRIBER_QOS_DEFAULT, NULL, DDS_STATUS_MASK_NONE);
if (subscriber == NULL) {
printf("create_subscriber error\n");
subscriber_shutdown(participant);
return -1;
}
printf("Setting partition to '%s', '%s'...\n",
subscriber_qos.partition.name[0],
subscriber_qos.partition.name[1]);
/* Register the type before creating the topic */
type_name = partitionsTypeSupport::get_type_name();
retcode = partitionsTypeSupport::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 partitions",
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 partitionsListener();
/* If you want to change the Datareader QoS programmatically rather than
* using the XML, you will need to add the following lines to your code
* and comment out the create_datareader() call bellow.
*/
/*
DDS_DataReaderQos datareader_qos;
retcode = subscriber->get_default_datareader_qos(datareader_qos);
if (retcode != DDS_RETCODE_OK) {
printf("get_default_datareader_qos error\n");
return -1;
}
datareader_qos.reliability.kind = DDS_RELIABLE_RELIABILITY_QOS;
datareader_qos.durability.kind = DDS_TRANSIENT_LOCAL_DURABILITY_QOS;
datareader_qos.history.kind = DDS_KEEP_ALL_HISTORY_QOS;
reader = subscriber->create_datareader(topic, datareader_qos, reader_listener,
DDS_STATUS_MASK_ALL);
if (reader == NULL) {
printf("create_datareader error\n");
subscriber_shutdown(participant);
delete reader_listener;
return -1;
}
*/
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) {
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/partitions/c/partitions_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.
******************************************************************************/
/* partitions_subscriber.c
A subscription example
This file is derived from code automatically generated by the rtiddsgen
command:
rtiddsgen -language C -example <arch> partitions.idl
Example subscription of type partitions 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>/partitions_subscriber <domain_id> <sample_count>
(3) Start the publication with the command
objs/<arch>/partitions_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>/partitions_publisher <domain_id>
objs/<arch>/partitions_subscriber <domain_id>
On Windows systems:
objs\<arch>\partitions_publisher <domain_id>
objs\<arch>\partitions_subscriber <domain_id>
modification history
------------ -------
*/
#include <stdio.h>
#include <stdlib.h>
#include "ndds/ndds_c.h"
#include "partitions.h"
#include "partitionsSupport.h"
void partitionsListener_on_requested_deadline_missed(
void* listener_data,
DDS_DataReader* reader,
const struct DDS_RequestedDeadlineMissedStatus *status)
{
}
void partitionsListener_on_requested_incompatible_qos(
void* listener_data,
DDS_DataReader* reader,
const struct DDS_RequestedIncompatibleQosStatus *status)
{
}
void partitionsListener_on_sample_rejected(
void* listener_data,
DDS_DataReader* reader,
const struct DDS_SampleRejectedStatus *status)
{
}
void partitionsListener_on_liveliness_changed(
void* listener_data,
DDS_DataReader* reader,
const struct DDS_LivelinessChangedStatus *status)
{
}
void partitionsListener_on_sample_lost(
void* listener_data,
DDS_DataReader* reader,
const struct DDS_SampleLostStatus *status)
{
}
void partitionsListener_on_subscription_matched(
void* listener_data,
DDS_DataReader* reader,
const struct DDS_SubscriptionMatchedStatus *status)
{
}
void partitionsListener_on_data_available(
void* listener_data,
DDS_DataReader* reader)
{
partitionsDataReader *partitions_reader = NULL;
struct partitionsSeq data_seq = DDS_SEQUENCE_INITIALIZER;
struct DDS_SampleInfoSeq info_seq = DDS_SEQUENCE_INITIALIZER;
DDS_ReturnCode_t retcode;
int i;
struct DDS_SampleInfo* info;
partitions_reader = partitionsDataReader_narrow(reader);
if (partitions_reader == NULL) {
printf("DataReader narrow error\n");
return;
}
retcode = partitionsDataReader_take(
partitions_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 < partitionsSeq_get_length(&data_seq); ++i) {
info = DDS_SampleInfoSeq_get_reference(&info_seq, i);
if (info->valid_data) {
if (info->view_state == DDS_NEW_VIEW_STATE) {
printf("Found new instance\n");
}
partitionsTypeSupport_print_data(partitionsSeq_get_reference(&data_seq,
i));
}
}
retcode = partitionsDataReader_return_loan(
partitions_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_SubscriberQos subscriber_qos = DDS_SubscriberQos_INITIALIZER;
struct DDS_DataReaderQos datareader_qos = DDS_DataReaderQos_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;
}
retcode = DDS_DomainParticipant_get_default_subscriber_qos(participant,
&subscriber_qos);
if (retcode != DDS_RETCODE_OK) {
printf("get_default_subscriber_qos error\n");
return -1;
}
/* If you want to change the Partition name programmatically rather than
* using the XML, you will need to add the following lines to your code
* and comment out the create_subscriber() call bellow.
*/
/*
DDS_StringSeq_ensure_length(&subscriber_qos.partition.name, 2, 2);
*DDS_StringSeq_get_reference(&subscriber_qos.partition.name, 0) =
DDS_String_dup("ABC");
*DDS_StringSeq_get_reference(&subscriber_qos.partition.name, 1) =
DDS_String_dup("X*Z");
subscriber = DDS_DomainParticipant_create_subscriber(participant,
&subscriber_qos,
NULL,
DDS_STATUS_MASK_NONE);
if (subscriber == NULL) {
printf("create_subscriber error\n");
subscriber_shutdown(participant);
return -1;
}
*/
subscriber = DDS_DomainParticipant_create_subscriber(participant,
&DDS_SUBSCRIBER_QOS_DEFAULT,
NULL,
DDS_STATUS_MASK_NONE);
if (subscriber == NULL) {
printf("create_subscriber error\n");
subscriber_shutdown(participant);
return -1;
}
printf("Setting partition to '%s', '%s'...\n",
DDS_StringSeq_get(&subscriber_qos.partition.name, 0),
DDS_StringSeq_get(&subscriber_qos.partition.name, 1));
/* Register the type before creating the topic */
type_name = partitionsTypeSupport_get_type_name();
retcode = partitionsTypeSupport_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 partitions",
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 =
partitionsListener_on_requested_deadline_missed;
reader_listener.on_requested_incompatible_qos =
partitionsListener_on_requested_incompatible_qos;
reader_listener.on_sample_rejected =
partitionsListener_on_sample_rejected;
reader_listener.on_liveliness_changed =
partitionsListener_on_liveliness_changed;
reader_listener.on_sample_lost =
partitionsListener_on_sample_lost;
reader_listener.on_subscription_matched =
partitionsListener_on_subscription_matched;
reader_listener.on_data_available =
partitionsListener_on_data_available;
/* If you want to change the Datareader QoS programmatically rather than
* using the XML, you will need to add the following lines to your code
* and comment out the create_datareader() call bellow.
*/
/*
retcode = DDS_Subscriber_get_default_datareader_qos(subscriber, &datareader_qos);
if (retcode != DDS_RETCODE_OK) {
printf("get_default_datareader_qos error\n");
return -1;
}
datareader_qos.reliability.kind = DDS_RELIABLE_RELIABILITY_QOS;
datareader_qos.durability.kind = DDS_TRANSIENT_LOCAL_DURABILITY_QOS;
datareader_qos.history.kind = DDS_KEEP_ALL_HISTORY_QOS;
reader = DDS_Subscriber_create_datareader(subscriber,
DDS_Topic_as_topicdescription(topic),
&datareader_qos,
&reader_listener,
DDS_STATUS_MASK_ALL);
if (reader == NULL) {
printf("create_datareader error\n");
subscriber_shutdown(participant);
return -1;
}
*/
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) {
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/partitions/c/partitions_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.
******************************************************************************/
/* partitions_publisher.c
A publication of data of type partitions
This file is derived from code automatically generated by the rtiddsgen
command:
rtiddsgen -language C -example <arch> partitions.idl
Example publication of type partitions 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>/partitions_subscriber <domain_id> <sample_count>
(3) Start the publication with the command
objs/<arch>/partitions_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>/partitions_publisher <domain_id>
objs/<arch>/partitions_subscriber <domain_id>
On Windows:
objs\<arch>\partitions_publisher <domain_id>
objs\<arch>\partitions_subscriber <domain_id>
modification history
------------ -------
*/
#include <stdio.h>
#include <stdlib.h>
#include "ndds/ndds_c.h"
#include "partitions.h"
#include "partitionsSupport.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;
partitionsDataWriter *partitions_writer = NULL;
partitions *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};
struct DDS_PublisherQos publisher_qos = DDS_PublisherQos_INITIALIZER;
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;
}
/* If you want to change the Partition name programmatically rather than
* using the XML, you will need to add the following lines to your code
* and comment out the create_publisher() call bellow.
*/
retcode = DDS_DomainParticipant_get_default_publisher_qos(participant,
&publisher_qos);
if (retcode != DDS_RETCODE_OK) {
printf("get_default_publisher_qos error\n");
return -1;
}
/* We modify the Publisher QoS to include two partition names. By
* default these will be "ABC" and "foo". */
/*
DDS_StringSeq_ensure_length(&publisher_qos.partition.name, 2, 2);
*DDS_StringSeq_get_reference(&publisher_qos.partition.name, 0) =
DDS_String_dup("ABC");
*DDS_StringSeq_get_reference(&publisher_qos.partition.name, 1) =
DDS_String_dup("foo");
publisher = DDS_DomainParticipant_create_publisher(participant,
&publisher_qos,
NULL,
DDS_STATUS_MASK_NONE);
if (publisher == NULL) {
printf("create_publisher 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,
DDS_STATUS_MASK_NONE);
if (publisher == NULL) {
printf("create_publisher error\n");
publisher_shutdown(participant);
return -1;
}
/* Register type before creating topic */
type_name = partitionsTypeSupport_get_type_name();
retcode = partitionsTypeSupport_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 partitions",
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;
}
retcode = DDS_Publisher_get_default_datawriter_qos(publisher, &datawriter_qos);
if (retcode != DDS_RETCODE_OK) {
printf("get_default_datawriter_qos error\n");
return -1;
}
/* In this example we set a Reliable datawriter, with Transient Local
* durability. By default we set up these QoS settings via XML. If you
* want to to it programmatically, use the following code, and comment out
* the create_datawriter call bellow.
*/
/*
datawriter_qos.reliability.kind = DDS_RELIABLE_RELIABILITY_QOS;
datawriter_qos.durability.kind = DDS_TRANSIENT_LOCAL_DURABILITY_QOS;
datawriter_qos.history.kind = DDS_KEEP_LAST_HISTORY_QOS;
datawriter_qos.history.depth = 3;
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;
}
*/
writer = DDS_Publisher_create_datawriter(publisher,
topic,
&DDS_DATAWRITER_QOS_DEFAULT,
NULL,
DDS_STATUS_MASK_NONE);
if (writer == NULL) {
printf("create_datawriter error\n");
publisher_shutdown(participant);
return -1;
}
printf("Setting partition to '%s', '%s'...\n",
DDS_StringSeq_get(&publisher_qos.partition.name, 0),
DDS_StringSeq_get(&publisher_qos.partition.name, 1));
partitions_writer = partitionsDataWriter_narrow(writer);
if (partitions_writer == NULL) {
printf("DataWriter narrow error\n");
publisher_shutdown(participant);
return -1;
}
/* Create data sample for writing */
instance = partitionsTypeSupport_create_data_ex(DDS_BOOLEAN_TRUE);
if (instance == NULL) {
printf("partitionsTypeSupport_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 = partitionsDataWriter_register_instance(
partitions_writer, instance);
*/
/* Main loop */
for (count=0; (sample_count == 0) || (count < sample_count); ++count) {
printf("Writing partitions, count %d\n", count);
instance->x = count;
retcode = partitionsDataWriter_write(partitions_writer,
instance,
&instance_handle);
if (retcode != DDS_RETCODE_OK) {
printf("write error %d\n", retcode);
}
/* Every 5 samples we will change the Partition name. These are the
* partition expressions we are going to try:
* "bar", "A*", "A?C", "X*Z", "zzz", "A*C"
*/
if ((count+1) % 25 == 0) {
/* Matches "ABC" -- name[1] here can match name[0] there,
* as long as there is some overlapping name */
*DDS_StringSeq_get_reference(&publisher_qos.partition.name, 0) =
DDS_String_dup("zzz");
*DDS_StringSeq_get_reference(&publisher_qos.partition.name, 1) =
DDS_String_dup("A*C");
printf("Setting partition to '%s', '%s'...\n",
DDS_StringSeq_get(&publisher_qos.partition.name, 0),
DDS_StringSeq_get(&publisher_qos.partition.name, 1));
DDS_Publisher_set_qos(publisher, &publisher_qos);
}
else if ((count+1) % 20 == 0) {
/* Strings that are regular expressions aren't tested for
* literal matches, so this won't match "X*Z" */
*DDS_StringSeq_get_reference(&publisher_qos.partition.name, 0) =
DDS_String_dup("X*Z");
printf("Setting partition to '%s', '%s'...\n",
DDS_StringSeq_get(&publisher_qos.partition.name, 0),
DDS_StringSeq_get(&publisher_qos.partition.name, 1));
DDS_Publisher_set_qos(publisher, &publisher_qos);
}
else if ((count+1) % 15 == 0) {
/* Matches "ABC" */
*DDS_StringSeq_get_reference(&publisher_qos.partition.name, 0) =
DDS_String_dup("A?C");
printf("Setting partition to '%s', '%s'...\n",
DDS_StringSeq_get(&publisher_qos.partition.name, 0),
DDS_StringSeq_get(&publisher_qos.partition.name, 1));
DDS_Publisher_set_qos(publisher, &publisher_qos);
}
else if ((count+1) % 10 == 0) {
/* Matches "ABC" */
*DDS_StringSeq_get_reference(&publisher_qos.partition.name, 0) =
DDS_String_dup("A*");
printf("Setting partition to '%s', '%s'...\n",
DDS_StringSeq_get(&publisher_qos.partition.name, 0),
DDS_StringSeq_get(&publisher_qos.partition.name, 1));
DDS_Publisher_set_qos(publisher, &publisher_qos);
}
else if ((count+1) % 5 == 0) {
/* No literal match for "bar"*/
*DDS_StringSeq_get_reference(&publisher_qos.partition.name, 0) =
DDS_String_dup("bar");
printf("Setting partition to '%s', '%s'...\n",
DDS_StringSeq_get(&publisher_qos.partition.name, 0),
DDS_StringSeq_get(&publisher_qos.partition.name, 1));
DDS_Publisher_set_qos(publisher, &publisher_qos);
}
NDDS_Utility_sleep(&send_period);
}
/*
retcode = partitionsDataWriter_unregister_instance(
partitions_writer, instance, &instance_handle);
if (retcode != DDS_RETCODE_OK) {
printf("unregister instance error %d\n", retcode);
}
*/
/* Delete data sample */
retcode = partitionsTypeSupport_delete_data_ex(instance, DDS_BOOLEAN_TRUE);
if (retcode != DDS_RETCODE_OK) {
printf("partitionsTypeSupport_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/partitions/c++03/partitions_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 "partitions.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);
// Retrieve the default Publisher QoS, from USER_QOS_PROFILES.xml
PublisherQos publisher_qos = QosProvider::Default().publisher_qos();
Partition partition = publisher_qos.policy<Partition>();
std::vector<std::string> partition_names = partition.name();
// If you want to change the Publisher QoS programmatically rather
// than using the XML file, you will need to comment out these lines.
// partition_names[0] = "ABC";
// partition_names[1] = "foo";
// partition.name(partition_names);
// publisher_qos << partition;
std::cout << "Setting partition to";
for (int i = 0; i < partition_names.size(); i++) {
std::cout << " '" << partition_names[i] << "'";
}
std::cout << std::endl;
// Create a Publisher.
Publisher publisher(participant, publisher_qos);
// Create a Topic -- and automatically register the type.
Topic<partitions> topic(participant, "Example partitions");
// Retrieve the default DataWriter QoS, from USER_QOS_PROFILES.xml
DataWriterQos writer_qos = QosProvider::Default().datawriter_qos();
// If you want to change the DataWriter QoS programmatically rather
// than using the XML file, you will need to comment out these lines.
// writer_qos << Reliability::Reliable()
// << History::KeepLast(3)
// << Durability::TransientLocal();
// Create a Datawriter.
DataWriter<partitions> writer(publisher, topic, writer_qos);
// Create a data sample for writing.
partitions instance;
// Main loop
bool update_qos = false;
for (int count = 0; (sample_count == 0) || (count < sample_count); count++){
std::cout << "Writing partitions, count " << count << std::endl;
// Modify and send the sample.
instance.x(count);
writer.write(instance);
// Every 5 samples we will change the partition name.
// These are the partition expressions we are going to try:
// "bar", "A*", "A?C", "X*Z", "zzz" and "A*C".
if ((count + 1) % 25 == 0) {
// Matches "ABC", name[1] here can match name[0] there,
// as long as there is some overlapping name.
partition_names.resize(2);
partition_names[0] = "zzz";
partition_names[1] = "A*C";
update_qos = true;
} else if ((count + 1) % 25 == 20) {
// Strings that are regular expressions aren't tested for
// literal matches, so this won't match "X*Z".
partition_names[0] = "X*Z";
update_qos = true;
} else if ((count + 1) % 25 == 15) {
// Matches "ABC".
partition_names[0] = "A?C";
update_qos = true;
} else if ((count + 1) % 25 == 10) {
// Matches "ABC".
partition_names[0] = "A*";
update_qos = true;
} else if ((count + 1) % 25 == 5) {
// No literal match for "bar".
// For the next iterations we are using only one partition.
partition_names.resize(1);
partition_names[0] = "bar";
update_qos = true;
}
// Set the new partition names to the publisher QoS.
if (update_qos) {
std::cout << "Setting partition to";
for (int i = 0; i < partition_names.size(); i++) {
std::cout << " '" << partition_names[i] << "'";
}
std::cout << std::endl;
partition.name(partition_names);
publisher.qos(publisher_qos << partition);
update_qos = false;
}
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/partitions/c++03/partitions_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 "partitions.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;
using namespace dds::sub::status;
using namespace rti::core;
class PartitionsListener : public NoOpDataReaderListener<partitions> {
public:
void on_data_available(DataReader<partitions>& reader)
{
// Take all samples
LoanedSamples<partitions> samples = reader.take();
for (LoanedSamples<partitions>::iterator sample_it = samples.begin();
sample_it != samples.end(); sample_it++) {
if (sample_it->info().valid()) {
// After partition mismatch unpair,
// it detects the instance as new.
ViewState view_state = sample_it->info().state().view_state();
if (view_state == ViewState::new_view()) {
std::cout << "Found new instance" << std::endl;
}
std::cout << sample_it->data() << std::endl;
}
}
}
};
void subscriber_main(int domain_id, int sample_count)
{
// Create a participant with default QoS.
DomainParticipant participant(domain_id);
// Retrieve the default Subscriber QoS, from USER_QOS_PROFILES.xml
SubscriberQos subscriber_qos = QosProvider::Default().subscriber_qos();
Partition partition = subscriber_qos.policy<Partition>();
std::vector<std::string> partition_names = partition.name();
// If you want to change the Subscriber QoS programmatically rather
// than using the XML file, you will need to comment out these lines.
// partition_names[0] = "ABC";
// partition_names[1] = "X*Z";
// partition.name(partition_names);
// subscriber_qos << partition;
std::cout << "Setting partition to "
<< "'" << partition_names[0] << "', "
<< "'" << partition_names[1] << "'..." << std::endl;
// Create a subscriber.
Subscriber subscriber(participant, subscriber_qos);
// Create a Topic -- and automatically register the type.
Topic<partitions> topic(participant, "Example partitions");
// Retrieve the default DataReader QoS, from USER_QOS_PROFILES.xml
DataReaderQos reader_qos = QosProvider::Default().datareader_qos();
// If you want to change the Subscriber QoS programmatically rather
// than using the XML file, you will need to comment out these lines.
// reader_qos << Reliability::Reliable()
// << History::KeepAll()
// << Durability::TransientLocal();
// Create a DataReader.
DataReader<partitions> reader(subscriber, topic, reader_qos);
// Create a DataReader listener using ListenerBinder, a RAII utility that
// will take care of reseting it from the reader and deleting it.
ListenerBinder<DataReader<partitions> > scoped_listener =
bind_and_manage_listener(
reader,
new PartitionsListener,
StatusMask::data_available());
// Main loop
for (int count = 0; (sample_count == 0) || (count < sample_count); count++){
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 {
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/routing_service/routing_service_shapes_processor/cpp/ShapesProcessor.cxx | /*
* (c) 2018 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 <iterator>
#include <stdio.h>
#include <stdlib.h>
#include <dds/core/corefwd.hpp>
#include <dds/core/xtypes/DynamicData.hpp>
#include <dds/core/xtypes/StructType.hpp>
#include <rti/routing/processor/Processor.hpp>
#include <rti/routing/processor/ProcessorPlugin.hpp>
#include "ShapesProcessor.hpp"
using namespace rti::routing;
using namespace rti::routing::processor;
using namespace rti::routing::adapter;
using namespace dds::core::xtypes;
using namespace dds::sub::status;
/*
* --- ShapesAggregatorSimple -------------------------------------------------
*/
ShapesAggregatorSimple::ShapesAggregatorSimple()
{
}
ShapesAggregatorSimple::~ShapesAggregatorSimple()
{
}
void ShapesAggregatorSimple::on_output_enabled(
rti::routing::processor::Route &route,
rti::routing::processor::Output &output)
{
// initialize the output_data buffer using the type from the output
output_data_ = output.get<DynamicData>().create_data();
}
void ShapesAggregatorSimple::on_data_available(
rti::routing::processor::Route &route)
{
// Use squares as 'leading' input. For each Square instance, get the
// equivalent instance from the Circle topic
auto squares = route.input<DynamicData>("Square").read();
for (auto square_sample : squares) {
if (square_sample.info().valid()) {
output_data_ = square_sample.data();
// read equivalent existing instance in the Circles stream
auto circles =
route.input<DynamicData>("Circle")
.select()
.instance(square_sample.info().instance_handle())
.read();
if (circles.length() != 0 && circles[0].info().valid()) {
output_data_.get().value<int32_t>(
"shapesize",
circles[0].data().value<int32_t>("y"));
}
// Write aggregated sample intro Triangles
route.output<DynamicData>("Triangle").write(output_data_.get());
} else {
// propagate the dispose
route.output<DynamicData>("Triangle")
.write(output_data_.get(), square_sample.info());
// clear instance instance
route.input<DynamicData>("Square")
.select()
.instance(square_sample.info().instance_handle())
.take();
}
}
}
/*
* --- ShapesAggregatorAdv
* -------------------------------------------------------
*/
ShapesAggregatorAdv::ShapesAggregatorAdv(int32_t leading_input_index)
: leading_input_index_(leading_input_index)
{
}
ShapesAggregatorAdv::~ShapesAggregatorAdv()
{
}
void ShapesAggregatorAdv::on_output_enabled(
rti::routing::processor::Route &route,
rti::routing::processor::Output &output)
{
// initialize the output_data buffer using the type from the output
output_data_ = output.get<DynamicData>().create_data();
}
void ShapesAggregatorAdv::on_data_available(
rti::routing::processor::Route &route)
{
// Read all data from leading input, then select equivalent instance from
// other inputs
DataState new_data = DataState(
SampleState::not_read(),
ViewState::any(),
InstanceState::any());
auto leading_samples = route.input<DynamicData>(leading_input_index_)
.select()
.state(new_data)
.read();
for (auto leading : leading_samples) {
std::pair<int, int> output_xy(0, 0);
if (leading.info().valid()) {
output_data_ = leading.data();
output_xy.first += leading.data().value<int32_t>("x");
output_xy.second += leading.data().value<int32_t>("y");
for (int32_t i = 0; i < route.input_count(); i++) {
if (i == leading_input_index_) {
continue;
}
auto aggregated_samples =
route.input<DynamicData>(i)
.select()
.instance(leading.info().instance_handle())
.read();
if (aggregated_samples.length() != 0) {
// use last value cached
output_xy.first +=
aggregated_samples[0].data().value<int32_t>("x");
output_xy.second +=
aggregated_samples[0].data().value<int32_t>("y");
}
}
output_xy.first /= route.input_count();
output_xy.second /= route.input_count();
output_data_.get().value<int32_t>("x", output_xy.first);
output_data_.get().value<int32_t>("y", output_xy.second);
// Write aggregated sample into single output
route.output<DynamicData>(0).write(output_data_.get());
} else {
// propagate the dispose
route.output<DynamicData>(0).write(
output_data_.get(),
leading.info());
}
}
}
/*
* --- ShapesSplitter ---------------------------------------------------------
*/
ShapesSplitter::ShapesSplitter()
{
}
ShapesSplitter::~ShapesSplitter()
{
}
void ShapesSplitter::on_input_enabled(
rti::routing::processor::Route &route,
rti::routing::processor::Input &input)
{
// The type this processor works with is the ShapeType, which shall
// be the type the input as well as the two outputs. Hence we can use
// the input type to initialize the output data buffer
output_data_ = input.get<DynamicData>().create_data();
}
void ShapesSplitter::on_data_available(rti::routing::processor::Route &route)
{
// Split input shapes into mono-dimensional output shapes
auto input_samples = route.input<DynamicData>(0).take();
for (auto sample : input_samples) {
if (sample.info().valid()) {
// split into first output
output_data_ = sample.data();
output_data_.get().value<int32_t>("y", 0);
route.output<DynamicData>(0).write(
output_data_.get(),
sample.info());
// split into second output
output_data_ = sample.data();
output_data_.get().value<int32_t>("x", 0);
route.output<DynamicData>(1).write(
output_data_.get(),
sample.info());
} else {
// propagate dispose
route.output<DynamicData>(0).write(
output_data_.get(),
sample.info());
route.output<DynamicData>(1).write(
output_data_.get(),
sample.info());
}
}
}
/*
* --- ShapesProcessorPlugin --------------------------------------------------
*/
const std::string ShapesProcessorPlugin::PROCESSOR_KIND_PROPERTY_NAME =
"shapes_processor.kind";
const std::string ShapesProcessorPlugin::PROCESSOR_LEADING_INPUT_PROPERTY_NAME =
"shapes_processor.leading_input_index";
const std::string ShapesProcessorPlugin::PROCESSOR_AGGREGATOR_SIMPLE_NAME =
"aggregator_simple";
const std::string ShapesProcessorPlugin::PROCESSOR_AGGREGATOR_ADV_NAME =
"aggregator_adv";
const std::string ShapesProcessorPlugin::PROCESSOR_SPLITTER_NAME = "splitter";
ShapesProcessorPlugin::ShapesProcessorPlugin(const rti::routing::PropertySet &)
{
}
rti::routing::processor::Processor *ShapesProcessorPlugin::create_processor(
rti::routing::processor::Route &,
const rti::routing::PropertySet &properties)
{
PropertySet::const_iterator it =
properties.find(PROCESSOR_KIND_PROPERTY_NAME);
if (it != properties.end()) {
if (it->second == PROCESSOR_AGGREGATOR_ADV_NAME) {
int32_t leading_input_index = 0;
it = properties.find(PROCESSOR_LEADING_INPUT_PROPERTY_NAME);
if (it != properties.end()) {
std::stringstream stream;
stream << it->second;
stream >> leading_input_index;
}
return new ShapesAggregatorAdv(leading_input_index);
} else if (it->second == PROCESSOR_AGGREGATOR_SIMPLE_NAME) {
return new ShapesAggregatorSimple();
} else if (it->second != PROCESSOR_SPLITTER_NAME) {
throw dds::core::InvalidArgumentError(
"unknown processor kind with name=" + it->second);
}
}
return new ShapesSplitter();
}
void ShapesProcessorPlugin::delete_processor(
rti::routing::processor::Route &,
rti::routing::processor::Processor *processor)
{
delete processor;
}
RTI_PROCESSOR_PLUGIN_CREATE_FUNCTION_DEF(ShapesProcessorPlugin); | cxx |
rticonnextdds-examples | data/projects/rticonnextdds-examples/routing_service/routing_service_shapes_processor/cpp/ShapesProcessor.hpp | /*
* (c) 2018 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.
*/
#ifndef SHAPES_PROCESSOR_HPP_
#define SHAPES_PROCESSOR_HPP_
#include <iterator>
#include <stdio.h>
#include <stdlib.h>
#include <dds/core/corefwd.hpp>
#include <dds/core/Optional.hpp>
#include <dds/core/xtypes/DynamicData.hpp>
#include <dds/core/xtypes/StructType.hpp>
#include <rti/routing/processor/Processor.hpp>
#include <rti/routing/processor/ProcessorPlugin.hpp>
class ShapesAggregatorSimple : public rti::routing::processor::NoOpProcessor {
public:
void on_data_available(rti::routing::processor::Route &);
void on_output_enabled(
rti::routing::processor::Route &route,
rti::routing::processor::Output &output);
ShapesAggregatorSimple();
~ShapesAggregatorSimple();
private:
// Optional member for deferred initialization: this object can be created
// only when the output is enabled.
// You can use std::optional if supported in your platform
dds::core::optional<dds::core::xtypes::DynamicData> output_data_;
};
class ShapesAggregatorAdv : public rti::routing::processor::NoOpProcessor {
public:
void on_data_available(rti::routing::processor::Route &);
void on_output_enabled(
rti::routing::processor::Route &route,
rti::routing::processor::Output &output);
ShapesAggregatorAdv(int32_t leading_input_index);
~ShapesAggregatorAdv();
private:
// Optional member for deferred initialization: this object can be created
// only when the output is enabled.
// You can use std::optional if supported in your platform
dds::core::optional<dds::core::xtypes::DynamicData> output_data_;
// index of leading input from which data is read first
int32_t leading_input_index_;
};
class ShapesSplitter : public rti::routing::processor::NoOpProcessor {
public:
void on_data_available(rti::routing::processor::Route &) override;
void on_input_enabled(
rti::routing::processor::Route &route,
rti::routing::processor::Input &input) override;
ShapesSplitter();
~ShapesSplitter();
private:
// Optional member for deferred initialization: this object can be created
// only when the output is enabled.
// You can use std::optional if supported in your platform
dds::core::optional<dds::core::xtypes::DynamicData> output_data_;
};
class ShapesProcessorPlugin : public rti::routing::processor::ProcessorPlugin {
public:
static const std::string PROCESSOR_KIND_PROPERTY_NAME;
static const std::string PROCESSOR_LEADING_INPUT_PROPERTY_NAME;
static const std::string PROCESSOR_AGGREGATOR_SIMPLE_NAME;
static const std::string PROCESSOR_AGGREGATOR_ADV_NAME;
static const std::string PROCESSOR_SPLITTER_NAME;
rti::routing::processor::Processor *create_processor(
rti::routing::processor::Route &route,
const rti::routing::PropertySet &properties) override;
void delete_processor(
rti::routing::processor::Route &route,
rti::routing::processor::Processor *processor) override;
ShapesProcessorPlugin(const rti::routing::PropertySet &properties);
};
/**
* This macro defines a C-linkage symbol that can be used as create function
* for plug-in registration through XML.
*
* The generated symbol has the name:
*
* \code
* ShapesProcessorPlugin_create_processor_plugin
* \endcode
*/
RTI_PROCESSOR_PLUGIN_CREATE_FUNCTION_DECL(ShapesProcessorPlugin);
#endif | hpp |
rticonnextdds-examples | data/projects/rticonnextdds-examples/routing_service/routing_service_shapes_processor/cpp/ShapesAggregator.cxx | /*
* (c) 2018 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 <iterator>
#include <stdio.h>
#include <stdlib.h>
#include <dds/core/corefwd.hpp>
#include <dds/core/xtypes/DynamicData.hpp>
#include <dds/core/xtypes/StructType.hpp>
#include <rti/routing/Logger.hpp>
#include <rti/routing/processor/Processor.hpp>
#include <rti/routing/processor/ProcessorPlugin.hpp>
#include "ShapesAggregator.hpp"
using namespace rti::routing;
using namespace rti::routing::processor;
using namespace rti::routing::adapter;
using namespace dds::core::xtypes;
using namespace dds::sub::status;
/*
* --- ShapesAggregator -------------------------------------------------
*/
ShapesAggregator::ShapesAggregator()
{
}
ShapesAggregator::~ShapesAggregator()
{
}
void ShapesAggregator::on_output_enabled(
rti::routing::processor::Route &route,
rti::routing::processor::Output &output)
{
// initialize the output_data buffer using the type from the output
output_data_ = output.get<DynamicData>().create_data();
}
void ShapesAggregator::on_data_available(
rti::routing::processor::Route &route)
{
// Use squares as 'leading' input. For each Square instance, get the
// equivalent instance from the Circle topic
auto squares = route.input<DynamicData>("Square").read();
for (auto square_sample : squares) {
if (square_sample.info().valid()) {
output_data_ = square_sample.data();
// read equivalent existing instance in the Circles stream
auto circles =
route.input<DynamicData>("Circle")
.select()
.instance(square_sample.info().instance_handle())
.read();
if (circles.length() != 0 && circles[0].info().valid()) {
output_data_.get().value<int32_t>(
"shapesize",
circles[0].data().value<int32_t>("y"));
}
// Write aggregated sample intro Triangles
route.output<DynamicData>("Triangle").write(output_data_.get());
} else {
// propagate the dispose
route.output<DynamicData>("Triangle")
.write(output_data_.get(), square_sample.info());
// clear instance instance
route.input<DynamicData>("Square")
.select()
.instance(square_sample.info().instance_handle())
.take();
}
}
}
/*
* --- ShapesAggregatorPlugin --------------------------------------------------
*/
ShapesAggregatorPlugin::ShapesAggregatorPlugin(const rti::routing::PropertySet &)
{
rti::routing::Logger::instance().local("ShapesAggregator Plugin loaded");
}
rti::routing::processor::Processor *ShapesAggregatorPlugin::create_processor(
rti::routing::processor::Route &,
const rti::routing::PropertySet &)
{
rti::routing::Logger::instance().local("ShapesAggregator Processor created");
return new ShapesAggregator();
}
void ShapesAggregatorPlugin::delete_processor(
rti::routing::processor::Route &,
rti::routing::processor::Processor *processor)
{
delete processor;
}
RTI_PROCESSOR_PLUGIN_CREATE_FUNCTION_DEF(ShapesAggregatorPlugin); | cxx |
rticonnextdds-examples | data/projects/rticonnextdds-examples/routing_service/routing_service_shapes_processor/cpp/ShapesSplitter.cxx | /*
* (c) 2018 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 <iterator>
#include <stdio.h>
#include <stdlib.h>
#include <dds/core/corefwd.hpp>
#include <dds/core/xtypes/DynamicData.hpp>
#include <dds/core/xtypes/StructType.hpp>
#include <rti/routing/Logger.hpp>
#include <rti/routing/processor/Processor.hpp>
#include <rti/routing/processor/ProcessorPlugin.hpp>
#include "ShapesSplitter.hpp"
using namespace rti::routing;
using namespace rti::routing::processor;
using namespace rti::routing::adapter;
using namespace dds::core::xtypes;
using namespace dds::sub::status;
/*
* --- ShapesSplitter ---------------------------------------------------------
*/
ShapesSplitter::ShapesSplitter()
{
}
ShapesSplitter::~ShapesSplitter()
{
}
void ShapesSplitter::on_input_enabled(
rti::routing::processor::Route &route,
rti::routing::processor::Input &input)
{
// The type this processor works with is the ShapeType, which shall
// be the type the input as well as the two outputs. Hence we can use
// the input type to initialize the output data buffer
output_data_ = input.get<DynamicData>().create_data();
}
void ShapesSplitter::on_data_available(rti::routing::processor::Route &route)
{
// Split input shapes into mono-dimensional output shapes
auto input_samples = route.input<DynamicData>(0).take();
for (auto sample : input_samples) {
if (sample.info().valid()) {
// split into first output
output_data_ = sample.data();
output_data_.get().value<int32_t>("y", 0);
route.output<DynamicData>(0).write(
output_data_.get(),
sample.info());
// split into second output
output_data_ = sample.data();
output_data_.get().value<int32_t>("x", 0);
route.output<DynamicData>(1).write(
output_data_.get(),
sample.info());
} else {
// propagate dispose
route.output<DynamicData>(0).write(
output_data_.get(),
sample.info());
route.output<DynamicData>(1).write(
output_data_.get(),
sample.info());
}
}
}
/*
* --- ShapesSplitterPlugin --------------------------------------------------
*/
ShapesSplitterPlugin::ShapesSplitterPlugin(const rti::routing::PropertySet &)
{
rti::routing::Logger::instance().local("ShapesSplitter Plugin loaded");
}
rti::routing::processor::Processor *ShapesSplitterPlugin::create_processor(
rti::routing::processor::Route &,
const rti::routing::PropertySet &properties)
{
rti::routing::Logger::instance().local("ShapesSplitter Processor created");
return new ShapesSplitter();
}
void ShapesSplitterPlugin::delete_processor(
rti::routing::processor::Route &,
rti::routing::processor::Processor *processor)
{
delete processor;
}
RTI_PROCESSOR_PLUGIN_CREATE_FUNCTION_DEF(ShapesSplitterPlugin); | cxx |
rticonnextdds-examples | data/projects/rticonnextdds-examples/routing_service/routing_service_shapes_processor/cpp/ShapesSplitter.hpp | /*
* (c) 2018 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.
*/
#ifndef SHAPES_PROCESSOR_HPP_
#define SHAPES_PROCESSOR_HPP_
#include <iterator>
#include <stdio.h>
#include <stdlib.h>
#include <dds/core/corefwd.hpp>
#include <dds/core/Optional.hpp>
#include <dds/core/xtypes/DynamicData.hpp>
#include <dds/core/xtypes/StructType.hpp>
#include <rti/routing/processor/Processor.hpp>
#include <rti/routing/processor/ProcessorPlugin.hpp>
class ShapesSplitter : public rti::routing::processor::NoOpProcessor {
public:
void on_data_available(rti::routing::processor::Route &) override;
void on_input_enabled(
rti::routing::processor::Route &route,
rti::routing::processor::Input &input) override;
ShapesSplitter();
~ShapesSplitter();
private:
// Optional member for deferred initialization: this object can be created
// only when the output is enabled.
// You can use std::optional if supported in your platform
dds::core::optional<dds::core::xtypes::DynamicData> output_data_;
};
class ShapesSplitterPlugin : public rti::routing::processor::ProcessorPlugin {
public:
rti::routing::processor::Processor *create_processor(
rti::routing::processor::Route &route,
const rti::routing::PropertySet &properties) override;
void delete_processor(
rti::routing::processor::Route &route,
rti::routing::processor::Processor *processor) override;
ShapesSplitterPlugin(const rti::routing::PropertySet &properties);
};
/**
* This macro defines a C-linkage symbol that can be used as create function
* for plug-in registration through XML.
*
* The generated symbol has the name:
*
* \code
* ShapesSplitter_create_processor_plugin
* \endcode
*/
RTI_PROCESSOR_PLUGIN_CREATE_FUNCTION_DECL(ShapesSplitterPlugin);
#endif | hpp |
rticonnextdds-examples | data/projects/rticonnextdds-examples/routing_service/routing_service_shapes_processor/cpp/ShapesAggregator.hpp | /*
* (c) 2018 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.
*/
#ifndef SHAPES_PROCESSOR_HPP_
#define SHAPES_PROCESSOR_HPP_
#include <iterator>
#include <stdio.h>
#include <stdlib.h>
#include <dds/core/corefwd.hpp>
#include <dds/core/Optional.hpp>
#include <dds/core/xtypes/DynamicData.hpp>
#include <dds/core/xtypes/StructType.hpp>
#include <rti/routing/processor/Processor.hpp>
#include <rti/routing/processor/ProcessorPlugin.hpp>
class ShapesAggregator : public rti::routing::processor::NoOpProcessor {
public:
void on_data_available(rti::routing::processor::Route &);
void on_output_enabled(
rti::routing::processor::Route &route,
rti::routing::processor::Output &output);
ShapesAggregator();
~ShapesAggregator();
private:
// Optional member for deferred initialization: this object can be created
// only when the output is enabled.
// You can use std::optional if supported in your platform
dds::core::optional<dds::core::xtypes::DynamicData> output_data_;
};
class ShapesAggregatorPlugin : public rti::routing::processor::ProcessorPlugin {
public:
rti::routing::processor::Processor *create_processor(
rti::routing::processor::Route &route,
const rti::routing::PropertySet &properties) override;
void delete_processor(
rti::routing::processor::Route &route,
rti::routing::processor::Processor *processor) override;
ShapesAggregatorPlugin(const rti::routing::PropertySet &properties);
};
/**
* This macro defines a C-linkage symbol that can be used as create function
* for plug-in registration through XML.
*
* The generated symbol has the name:
*
* \code
* ShapesAggregatorPlugin_create_processor_plugin
* \endcode
*/
RTI_PROCESSOR_PLUGIN_CREATE_FUNCTION_DECL(ShapesAggregatorPlugin);
#endif | hpp |
rticonnextdds-examples | data/projects/rticonnextdds-examples/routing_service/routing_service_mongo_db/cpp/MongoConnection.hpp | /*
* (c) 2019 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.
*/
#ifndef MONGO_CONNECTION_HPP
#define MONGO_CONNECTION_HPP
#include <dds/core/macros.hpp>
#include <mongocxx/database.hpp>
#include <mongocxx/pool.hpp>
#include <rti/routing/adapter/AdapterPlugin.hpp>
#include <rti/routing/adapter/Connection.hpp>
#include "MongoConfig.hpp"
namespace rti { namespace community { namespace examples {
class MongoStreamWriter;
/***
* @brief Implementation of the adapter Connection. Represents a pool of client
* connections to MongoDB.
*
* This is a key class since it establishes the actual connection to a specific
* MongoDB database, given a user-provided URI.
*
* It uses a pool of clients to read and write from the DB. This is required to
* support concurrency between the created StreamReaders and StreamWriters, that
* can operate under multiple threads–either within the same Session's thread
* pool or separate Sessions-.
*
* The current strategy is to have StreamReaders and StreamWriters to ask for an
* available client database connection for the current calling context, using
* the database() operation.
*
* The MongoConnection can receive the following configuration properties:
*
* - MongoConfig::CLUSTER_ADDRESS
* - MongoConfig::DB_NAME
* - MongoConfig::USER_AND_PASS
* - MongoConfig::URI_PARAMS
*
* @see MongoConfig
*/
class MongoConnection : public rti::routing::adapter::Connection {
public:
/**
* @brief Creates the connection given its configuration properites
* @param properties
* Configuration properites provided by the <property> tag within
* <connection>.
*
*/
MongoConnection(const rti::routing::PropertySet &properties);
/*
* --- Connection interface
* ---------------------------------------------------------
*/
rti::routing::adapter::StreamWriter *create_stream_writer(
rti::routing::adapter::Session *session,
const rti::routing::StreamInfo &info,
const rti::routing::PropertySet &properties) override final;
void delete_stream_writer(
rti::routing::adapter::StreamWriter *writer) override final;
rti::routing::adapter::StreamReader *create_stream_reader(
rti::routing::adapter::Session *session,
const rti::routing::StreamInfo &info,
const rti::routing::PropertySet &properties,
rti::routing::adapter::StreamReaderListener *listener)
override final;
void delete_stream_reader(
rti::routing::adapter::StreamReader *reader) override final;
/*
* --- Private Interface
* ------------------------------------------------------------
*/
const std::string &db_name() const;
mongocxx::pool::entry client();
private:
friend MongoStreamWriter;
private:
mongocxx::pool client_pool_;
std::string db_name_;
};
}}} // namespace rti::community::examples
#endif
| hpp |
rticonnextdds-examples | data/projects/rticonnextdds-examples/routing_service/routing_service_mongo_db/cpp/MongoConfig.hpp | /*
* (c) 2019 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.
*/
#ifndef MONGO_CONFIG_HPP
#define MONGO_CONFIG_HPP
#include <rti/routing/PropertySet.hpp>
namespace rti { namespace community { namespace examples {
/**
* @brief Static class that represents a directory for all configuration
* properties part of the MongoDB adapter.
*
* This class provides operations to obtain property names and their associated
* value when they are present in a PropertySet.
*/
class MongoConfig {
public:
enum property {
/*
* @brief Host address to a specific cluster or database.
* Optional. Default: localhost:27017
*/
CLUSTER_ADDRESS,
/*
* @brief Name of the database to connect and access.
* Required.
*/
DB_NAME,
/**
* @brief User name and passwored in format <user>:<password>
* Required.
*/
USER_AND_PASS,
/**
* @brief Additional DB connection options in MongoDB URI parameters
* format. Optional. Default: retryWrites=true&w=majority
*/
URI_PARAMS
};
template <MongoConfig::property Prop, typename Type = std::string>
static Type parse(const rti::routing::PropertySet &properties);
template <MongoConfig::property Prop>
static const std::string &name();
};
}}} // namespace rti::community::examples
#endif /* MONGO_CONFIG_HPP */
| hpp |
rticonnextdds-examples | data/projects/rticonnextdds-examples/routing_service/routing_service_mongo_db/cpp/MongoStreamReader.hpp | /*
* (c) 2019 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.
*/
#ifndef MONGO_MONGOSTREAMREADER_HPP
#define MONGO_MONGOSTREAMREADER_HPP
#include <mongocxx/client.hpp>
#include <mongocxx/cursor.hpp>
#include <rti/routing/adapter/AdapterPlugin.hpp>
#include <rti/routing/adapter/StreamReader.hpp>
#include "MongoConnection.hpp"
namespace rti { namespace community { namespace examples {
/**
* @brief Implementation of the adapter Stream to read DDS from MongoDB document
* objects.
*
* This class is responsible for retrieving stream samples from MongoDB database
* as as part of a collection identified by the associated stream name. This
* class is responsible for converting a sample from a mongocxx:document that
* has a structure {data: {}, info: {}} into a stream smpale (represented as a
* pair [DynamicData,SampleInfo]).
*
* The samples are read from the database where the parent Connection is
* connected and from the collection identified by the stream name.
*
* The set of samples is defined by all the samples whose *reception timestamp*
* is between [t1,t2], where:
* - t1: time from the last read. Initially this is set to the StreamReader
* creation time.
* - t2: current time, that is, the time at which the read operation is called.
*
* To perform database reads, this class obtains client handle through
* the parent factory MongoConnection, which is provided on object construction,
* an uses a cursor with a filter to satisfy the time condition above.
*
* A key behavior aspect of this class is its absence of asynchronous data
* available notifications. The current implementation relies on periodic
* polling from the parent Route, which must enable the periodic action and have
* a Processor that class take() upon dispatch of such event.
*
* Therefore, this class makes no use of the StreamReaderListener that
* RoutingService provides to listen for asynchronous notifications. A possible
* enhancement of this implementation could be to create a
* mongocxx::change_stream to listen for changes in the DB, and generate data
* available notifications based on that.
*
*/
class MongoStreamReader
: public rti::routing::adapter::DynamicDataStreamReader {
public:
/**
* @brief Creates the StreamWriter from the required parameters.
*
* @param connection
* The parent factory connection
* @param stream_info
* Information for the associated Stream, provided by Routing Service.
* @param properties
* Configuration properites provided by the <property> tag within
* <output>.
*/
MongoStreamReader(
MongoConnection &connection,
const rti::routing::StreamInfo &stream_info,
const rti::routing::PropertySet &properties);
/*
* --- StreamREader interface
* ---------------------------------------------------------
*/
/**
* @brief Reads a set of samples from MongoDB.
*
*
* The provided list of samples are the result of converting the MongoDB
* documents into dynamic data. The conversion process is best-effort. It
* attempts to set each document element into a DynamicData member:
*
* - If a document element is not part of the DynamicData member, it will
* be ignored (a debug log is emitted)
* - If a document is missing elements that are present in the DynamicData
* object, the latter will be left to their initialization default
* (typically zero-ed memory).
*
* Members are populated based on the current context. The document::data
* object is the top-level context. From there:
* 1. A primitive element is set to the equivalent DynamicData primitive
* member with the same name.
* 2. A document element is set to the equivalent DynamicData complex member
* with the same name. A new context is created and repeats the process
* starting at 1.
* 3. An array element is set to the equivalent DynamicData array member
* with the same name. A new context is created and repeats the process
* starting at 1. *for each element in the array*.
*/
void
take(std::vector<dds::core::xtypes::DynamicData *> &samples,
std::vector<dds::sub::SampleInfo *> &infos) override final;
/**
* @brief Returns the memory used to generate the output samples in take().
*/
void return_loan(
std::vector<dds::core::xtypes::DynamicData *> &samples,
std::vector<dds::sub::SampleInfo *> &) override final;
private:
bsoncxx::document::value find_filter();
static mongocxx::options::find find_options();
MongoConnection &connection_;
std::string stream_name_;
bsoncxx::types::b_date last_read_;
dds::core::xtypes::DynamicType type_;
};
}}} // namespace rti::community::examples
#endif // MONGO_MONGOSTREAMREADER_HPP
| hpp |
rticonnextdds-examples | data/projects/rticonnextdds-examples/routing_service/routing_service_mongo_db/cpp/MongoStreamWriter.cxx | /*
* (c) 2019 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 <bsoncxx/builder/stream/document.hpp>
#include <mongocxx/client.hpp>
#include <mongocxx/collection.hpp>
#include <mongocxx/database.hpp>
#include <rti/core/Exception.hpp>
#include <rti/routing/Logger.hpp>
#include <rti/topic/to_string.hpp>
#include "MongoStreamWriter.hpp"
#include "SampleConverter.hpp"
using namespace rti::routing;
using namespace rti::routing::adapter;
using namespace rti::community::examples;
using namespace bsoncxx;
MongoStreamWriter::MongoStreamWriter(
MongoConnection &connection,
const StreamInfo &stream_info,
const PropertySet &)
: connection_(connection), stream_name_(stream_info.stream_name())
{
rti::routing::Logger::instance().local(
"created StreamWriter for stream: " + stream_info.stream_name());
}
/*
* --- Adapter Interface ------------------------------------------------------
*/
int MongoStreamWriter::write(
const std::vector<dds::core::xtypes::DynamicData *> &samples,
const std::vector<dds::sub::SampleInfo *> &infos)
{
/*
* This is a blocking operation: calling database() will query the
* mongo pool and wait until a client is available.
* We will keep the obtained client locked to write all the sample sequence
*/
auto client = connection_.client();
mongocxx::database database = client->database(connection_.db_name());
mongocxx::collection db_collection = database[stream_name_];
for (uint32_t i = 0; i < samples.size(); i++) {
builder::stream::document document_sample {};
document_sample << "data"
<< types::b_document { SampleConverter::to_document(
*samples[i]) };
if (infos[i] != NULL) {
document_sample << "info"
<< types::b_document { SampleConverter::to_document(
*infos[i]) };
}
db_collection.insert_one(document_sample << builder::stream::finalize);
}
return samples.size();
}
| cxx |
rticonnextdds-examples | data/projects/rticonnextdds-examples/routing_service/routing_service_mongo_db/cpp/MongoConfig.cxx | /*
* (c) 2019 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 <mongocxx/uri.hpp>
#include "MongoConfig.hpp"
using namespace rti::community::examples;
/*
* --- Cluster address
* -----------------------------------------------------------------
*/
template <>
const std::string &MongoConfig::name<MongoConfig::CLUSTER_ADDRESS>()
{
static std::string __name("mongo.cluster_address");
return __name;
}
template <>
std::string MongoConfig::parse<MongoConfig::CLUSTER_ADDRESS>(
const rti::routing::PropertySet &properties)
{
rti::routing::PropertySet::const_iterator it =
properties.find(MongoConfig::name<MongoConfig::CLUSTER_ADDRESS>());
if (it != properties.end()) {
return it->second;
}
return "localhost:27017";
}
/*
* --- User & Pass
* ---------------------------------------------------------------------
*/
template <>
const std::string &MongoConfig::name<MongoConfig::USER_AND_PASS>()
{
static std::string __name("mongo.uri_params");
return __name;
}
template <>
std::string MongoConfig::parse<MongoConfig::USER_AND_PASS>(
const rti::routing::PropertySet &properties)
{
rti::routing::PropertySet::const_iterator it =
properties.find(MongoConfig::name<MongoConfig::USER_AND_PASS>());
if (it != properties.end()) {
return it->second;
}
return "rti_example:adapter";
}
/*
* --- Uri params
* ---------------------------------------------------------------------
*/
template <>
const std::string &MongoConfig::name<MongoConfig::URI_PARAMS>()
{
static std::string __name("mongo.uri_params");
return __name;
}
template <>
std::string MongoConfig::parse<MongoConfig::URI_PARAMS>(
const rti::routing::PropertySet &properties)
{
rti::routing::PropertySet::const_iterator it =
properties.find(MongoConfig::name<MongoConfig::URI_PARAMS>());
if (it != properties.end()) {
return it->second;
}
return "retryWrites=true&w=majority";
}
/*
* --- Database name
* -------------------------------------------------------------------
*/
template <>
const std::string &MongoConfig::name<MongoConfig::DB_NAME>()
{
static std::string __name("mongo.db_name");
return __name;
}
template <>
std::string MongoConfig::parse<MongoConfig::DB_NAME>(
const rti::routing::PropertySet &properties)
{
rti::routing::PropertySet::const_iterator it =
properties.find(MongoConfig::name<MongoConfig::DB_NAME>());
if (it == properties.end()) {
throw dds::core::InvalidArgumentError(
"database name is mandatory (property name: "
+ MongoConfig::name<MongoConfig::DB_NAME>());
}
return it->second;
}
| cxx |
rticonnextdds-examples | data/projects/rticonnextdds-examples/routing_service/routing_service_mongo_db/cpp/MongoAdapter.hpp | /*
* (c) 2019 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.
*/
#ifndef FILEADAPTER_HPP
#define FILEADAPTER_HPP
#include <dds/core/corefwd.hpp>
#include <dds/core/macros.hpp>
#include <mongocxx/instance.hpp>
#include <rti/routing/PropertySet.hpp>
#include <rti/routing/RoutingService.hpp>
#include <rti/routing/adapter/AdapterPlugin.hpp>
namespace rti { namespace community { namespace examples {
/**
* @brief Implementation of the AdapterPlugin plugin entry point to provide
* access to MongoDB using the mongocxx driver.
*
* The implementation represents a holder to the mongocxx::instance, which is a
* singleton that shall be instantiated before performing any other operation on
* the driver. This implies that in a given Routing Service, only one instance
* of this plugin can be loaded, that is, only one <plugin> entry is allowed (or
* one call to rti::routing::Service::register_plugin() when embedding the
* service into your application).
*
* Other than that, this class purely implements the AdapterPlugin interface
* behavior to create and delete connections. There are currently no
* configuration properties for this class.
*
*/
class MongoAdapter : public rti::routing::adapter::AdapterPlugin {
public:
explicit MongoAdapter(rti::routing::PropertySet &);
/*
* --- AdapterPlugin interface
* ------------------------------------------------------
*/
rti::routing::adapter::Connection *create_connection(
rti::routing::adapter::detail::StreamReaderListener *,
rti::routing::adapter::detail::StreamReaderListener *,
const rti::routing::PropertySet &) final;
void delete_connection(
rti::routing::adapter::Connection *connection) override final;
rti::config::LibraryVersion get_version() const override final;
private:
mongocxx::instance instance_;
};
}}} // namespace rti::community::examples
/**
* This macro defines a C-linkage symbol that can be used as create function
* for plug-in registration through XML.
*
* The generated symbol has the name:
*
* \code
* MongoAdapterPlugin_create_adapter_plugin
* \endcode
*/
RTI_ADAPTER_PLUGIN_CREATE_FUNCTION_DECL(MongoAdapter)
#endif
| hpp |
rticonnextdds-examples | data/projects/rticonnextdds-examples/routing_service/routing_service_mongo_db/cpp/SampleConverter.hpp | /*
* (c) 2019 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.
*/
#ifndef DYNAMICDATACONVERTER_HPP
#define DYNAMICDATACONVERTER_HPP
#include <unordered_map>
#include <vector>
#include <dds/core/xtypes/DynamicData.hpp>
#include <dds/sub/SampleInfo.hpp>
#include <bsoncxx/builder/stream/document.hpp>
#include <bsoncxx/builder/stream/array.hpp>
namespace rti { namespace community { namespace examples {
/**
* @brief Helper to convert data from the DDS space to the MongoDB space.
*
*/
class SampleConverter {
public:
/**
* @brief Converts a DynamicData object into a BSON document.
*
* The general mapping is:
* - Structure -> bsoncxx::document
* - Sequences and multi-dimensional arrays -> bsoncxx::array
* - String -> bsoncxx::utf8
* - primitive types: A corresponding bson primitive, except:
* + uint32_t -> bsoncxx::b_int64
* + enum -> bsoncxx::b_int64
*
* Unions and wide strings are not currently supported.
*/
static bsoncxx::document::value to_document(
const dds::core::xtypes::DynamicData& data);
/**
* @brief Converts a SampleInfo object into a BSON document
*
* The general mapping is:
* - InstanceHandle -> bsoncxx::binary (md5)
* - GUID -> bsoncxx::binary (md5)
* - Sequence Number -> {high:int32, low:int64}
* - Time_t -> Date
*
* Only a subset of fields are currently converted.
*/
static bsoncxx::document::value to_document(
const dds::sub::SampleInfo& info);
/**
* @brief Converts a bson Document into a DynamicData object.
*
* It expected that the DynamiData object has a type compatible with the Document,
* that is, it's either a subset or superset of the document.
*
* This operation attempts to set members existing in the input document into
* members in DynamicData that are present.
*
* @param data destination typed DynamicData
* @param document input document
*/
static dds::core::xtypes::DynamicData & from_document(
dds::core::xtypes::DynamicData& data,
bsoncxx::document::view document);
private:
SampleConverter();
};
} // namespace examples
} // namespace community
} // namespace rti
#endif /* DYNAMICDATACONVERTER_HPP */
| hpp |
rticonnextdds-examples | data/projects/rticonnextdds-examples/routing_service/routing_service_mongo_db/cpp/MongoStreamReader.cpp | /*
* (c) 2019 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 <bsoncxx/builder/stream/document.hpp>
#include <bsoncxx/json.hpp>
#include <mongocxx/client.hpp>
#include <mongocxx/collection.hpp>
#include "MongoStreamReader.hpp"
#include "SampleConverter.hpp"
using namespace rti::routing;
using namespace rti::routing::adapter;
using namespace rti::community::examples;
using namespace bsoncxx;
document::value MongoStreamReader::find_filter()
{
types::b_date current_date { std::chrono::system_clock::now() };
builder::stream::document find_exp {};
find_exp << "info.reception_timestamp" << builder::stream::open_document
<< "$gte" << last_read_ << "$lt" << current_date
<< builder::stream::close_document;
last_read_ = current_date;
return (find_exp << builder::stream::finalize);
}
mongocxx::options::find MongoStreamReader::find_options()
{
static mongocxx::options::find cursor_options {};
static bool inited = false;
if (!inited) {
cursor_options.max_time(std::chrono::milliseconds(50000));
inited = true;
}
return cursor_options;
}
MongoStreamReader::MongoStreamReader(
MongoConnection &connection,
const rti::routing::StreamInfo &stream_info,
const rti::routing::PropertySet &properties)
: connection_(connection),
stream_name_(stream_info.stream_name()),
last_read_(std::chrono::system_clock::now()),
type_(stream_info.type_info().dynamic_type())
{
}
/*
* --- Adapter Interface ------------------------------------------------------
*/
void MongoStreamReader::take(
std::vector<dds::core::xtypes::DynamicData *> &samples,
std::vector<dds::sub::SampleInfo *> &infos)
{
auto client = connection_.client();
mongocxx::database database = client->database(connection_.db_name());
auto cursor =
database.collection(stream_name_)
.find(find_filter(), MongoStreamReader::find_options());
for (const bsoncxx::document::view &document : cursor) {
samples.push_back(new dds::core::xtypes::DynamicData(type_));
SampleConverter::from_document(
*samples.back(),
document["data"].get_document().view());
}
}
void MongoStreamReader::return_loan(
std::vector<dds::core::xtypes::DynamicData *> &samples,
std::vector<dds::sub::SampleInfo *> &infos)
{
for (uint32_t i = 0; i < samples.size(); ++i) {
delete samples[i];
if (i < infos.size()) {
delete infos[i];
}
}
samples.resize(0);
infos.resize(0);
}
| cpp |
rticonnextdds-examples | data/projects/rticonnextdds-examples/routing_service/routing_service_mongo_db/cpp/SampleConverter.cxx | /*
* (c) 2019 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/core/xtypes/CollectionTypes.hpp>
#include <rti/routing/Logger.hpp>
#include <bsoncxx/builder/stream/document.hpp>
#include <bsoncxx/builder/stream/array.hpp>
#include "SampleConverter.hpp"
using namespace dds::core::xtypes;
using namespace bsoncxx;
using namespace rti::community::examples;
/*
* -- From DDS to MongoDB conversion ----------------------------------------------------
*/
/* --- DynamicData --------------------------------------------------------------------*/
/**
* @brief Helper to add a primitive member to either a document or an array
*
* Template specializations are expected to have a single static set() operation
* to perform the insertion.
*
* @tparam Primitive
* one of the valid DDS primitive types
* @tparam DocOrArray
* Either a bsoncxx::document or bsoncxx::array.
*/
template<typename Primitive, typename DocOrArray>
struct primitive_setter;
template<typename Primitive>
struct primitive_setter<Primitive, bsoncxx::builder::stream::document> {
/**
* @brief Obtains the value for the specified primitive member from _data_ and
* adds it to a document.
*
* @param[in] data
* DynamicData complex member containing the primitive member
* @param[in] member_info
* Description of the primitive member. Must hold a valid member index and name.
* @param[out] document
* Output document
*/
static void set(
const dds::core::xtypes::DynamicData& data,
const rti::core::xtypes::DynamicDataMemberInfo& member_info,
bsoncxx::builder::stream::document& document)
{
document << member_info.member_name()
<< data.value<Primitive>(member_info.member_index());
}
};
template<typename Primitive>
struct primitive_setter<Primitive, bsoncxx::builder::stream::array> {
/**
* @brief Obtains the value for the specified sequence/array item from _data_ and
* adds it to an array.
*
* @param[in] data
* DynamicData sequence.array member containing the primitive element.
* @param[in] member_info
* Description of the primitive element. Must contain a valid member index.
* @param[out] array
* Output array
*/
static void set(
const dds::core::xtypes::DynamicData& data,
const rti::core::xtypes::DynamicDataMemberInfo& member_info,
bsoncxx::builder::stream::array& array)
{
array << data.value<Primitive>(member_info.member_index());
}
};
/**
* @brief Helper function to extra a primitive member or element from DynamicData and
* inset it into a BSON document or array.
*/
template<typename Primitive, typename DocOrArray = bsoncxx::builder::stream::document>
void set_primitive(
const dds::core::xtypes::DynamicData& data,
const rti::core::xtypes::DynamicDataMemberInfo& member_info,
DocOrArray& doc_or_array)
{
primitive_setter<Primitive, DocOrArray>::set(data, member_info, doc_or_array);
}
/**
* @brief Helper function that obtains the value from the specified primitive
* member and adds it to a bson document or an array.
*
* This operation selects the appropriate primitive_setter based on the TypeKind
* of the primitive member. If the specified member is of an unsupported type, this
* operation simply logs a message and returns.
*/
template<typename DocOrArray = bsoncxx::builder::stream::document>
void demultiplex_primitive_member(
const dds::core::xtypes::DynamicData& data,
const rti::core::xtypes::DynamicDataMemberInfo& member_info,
DocOrArray& doc_or_array)
{
using dds::core::xtypes::TypeKind;
using dds::core::xtypes::DynamicData;
using rti::core::xtypes::DynamicDataMemberInfo;
typedef std::function<void(
const DynamicData&,
const DynamicDataMemberInfo&,
DocOrArray&)> FromPrimitiveFunc;
static std::unordered_map<int32_t, FromPrimitiveFunc> demux_table{
{
TypeKind::BOOLEAN_TYPE,
set_primitive<DDS_Boolean, DocOrArray>
},
{
TypeKind::CHAR_8_TYPE,
set_primitive<DDS_Char, DocOrArray>
},
{
TypeKind::UINT_8_TYPE,
set_primitive<uint8_t, DocOrArray>
},
{
TypeKind::INT_16_TYPE,
set_primitive<int16_t, DocOrArray>
},
{
TypeKind::UINT_16_TYPE,
set_primitive<uint16_t, DocOrArray>
},
{
TypeKind::INT_32_TYPE,
set_primitive<int32_t, DocOrArray>
},
{
TypeKind::UINT_32_TYPE,
set_primitive<int64_t, DocOrArray>
},
{
TypeKind::INT_64_TYPE,
set_primitive<int64_t, DocOrArray>
},
{
TypeKind::ENUMERATION_TYPE,
set_primitive<int32_t, DocOrArray>
},
{
TypeKind::STRING_TYPE,
set_primitive<std::string, DocOrArray>
},
{
TypeKind::FLOAT_32_TYPE,
set_primitive<float_t, DocOrArray>
},
{
TypeKind::FLOAT_64_TYPE,
set_primitive<double, DocOrArray>
}
};
typename std::unordered_map<int32_t, FromPrimitiveFunc>::iterator it =
demux_table.find(member_info.member_kind().underlying());
if (it == demux_table.end()) {
// log unsupported
std::ostringstream string_stream;
string_stream << "unsupported type for member=" << member_info.member_name();
rti::routing::Logger::instance().debug(string_stream.str());
return;
}
it->second(data, member_info, doc_or_array);
}
/**
* @brief Helper to add a BSON element to either a document or an array
*
* Template specializations are expected to have a single static set() operation
* to perform the insertion.
*
* @tparam ElementType
* one of the valid bsoncxx::types
* @tparam DocOrArray
* Either a bsoncxx::document or bsoncxx::array.
*/
template<typename ElementType, typename DocOrArray>
struct element_setter;
template<typename ElementType>
struct element_setter<ElementType, bsoncxx::builder::stream::array> {
/**
* @brief Adds the specified element to a bson array.
*
* @param[in] element
* Instance of a a valid BSON type.
* @param[in] member_info
* Description of the element, as its associated DynamicData member
* @param[out] array
* Output array
*/
static void set(
ElementType& element,
const rti::core::xtypes::DynamicDataMemberInfo&,
bsoncxx::builder::stream::array& array)
{
array << element;
}
};
template<typename ElementType>
struct element_setter<ElementType, bsoncxx::builder::stream::document> {
/**
* @brief Adds the specified element to a bson document.
*
* @param[in] element
* Instance of a a valid BSON type.
* @param[in] member_info
* Description of the element, as its associated DynamicData member
* @param[out] document
* Output document
*/
static void set(
ElementType& element,
const rti::core::xtypes::DynamicDataMemberInfo& member_info,
bsoncxx::builder::stream::document& document)
{
document << member_info.member_name()
<< element;
}
};
/**
* @brief Abstract class that represent a member context, used to build
* a bsoncxx::document or bsoncxx::array from DynamicData.
*
* This class defines the behavior required by the build_document() operation in order
* to keep track of the nesting level of a member and perform the proper operation to
* add the member into an output bson document and array.
*/
class ToBsonContext {
public:
/**
* @brief Creates the context given the total number of members.
* The underlying _member_index_ is set to 1, the minimum valid index for a DynamicData
* member.
*/
ToBsonContext(uint32_t the_member_count)
: member_index(1),
member_count(the_member_count)
{}
/**
* @brief Sets the primitive member for this context.
*
* @param[in] data
* The source DynamicData object
* @param[in] member_info
* Description of the member inside _data_
*/
virtual void set_primitive(
const dds::core::xtypes::DynamicData& data,
const rti::core::xtypes::DynamicDataMemberInfo& member_info) = 0;
/**
* @brief Sets a bson document in this context.
*
* @param[in] document
* The source bson document
* @param[in] member_info
* Description of the complex member
*/
virtual void set_document(
bsoncxx::builder::stream::document& document,
const rti::core::xtypes::DynamicDataMemberInfo& member_info) = 0;
/**
* @brief Sets a bson array in this context.
*
* @param[in] array
* The source bson array
* @param[in] member_info
* Description of the array/sequence member
*/
virtual void set_array(
bsoncxx::builder::stream::array& array,
const rti::core::xtypes::DynamicDataMemberInfo& member_info) = 0;
// @brief index of the member whose value is retrieved from the DynData object
uint32_t member_index;
// @brief total number of members belonging to this complex member context.
uint32_t member_count;
};
/**
* @brief Implementation of the ToBsonContext that chooses the proper setter
* specialization based on the destination document or array.
*
* The class provides a holder to a destination object instance that is either bson
* document or array, based on the specialization.
*
* @tparam DocOrArray
* The type of the destination where members are set.
*/
template<typename DocOrArray>
class ToBsonTypedContext : public ToBsonContext {
public:
/**
* @see ToBsonContext(uint32_t)
*/
ToBsonTypedContext(uint32_t the_member_count)
: ToBsonContext(the_member_count)
{
}
/**
* @brief calls demultiplex_primitive_member
*/
void set_primitive(
const dds::core::xtypes::DynamicData& data,
const rti::core::xtypes::DynamicDataMemberInfo& member_info) override
{
demultiplex_primitive_member(data, member_info, doc_or_array);
}
/**
* @brief calls element_setter<array>set()
*/
void set_array(
bsoncxx::builder::stream::array& array,
const rti::core::xtypes::DynamicDataMemberInfo& member_info) override
{
bsoncxx::types::b_array array_view{array};
element_setter<bsoncxx::types::b_array, DocOrArray>::set(
array_view,
member_info,
doc_or_array);
}
/***
* @brief calls element_setter<document>set()
*/
void set_document(
bsoncxx::builder::stream::document& document,
const rti::core::xtypes::DynamicDataMemberInfo& member_info) override
{
bsoncxx::types::b_document doc_view{document};
element_setter<bsoncxx::types::b_document, DocOrArray>::set(
doc_view,
member_info,
doc_or_array);
}
// @brief instance to the bson object destination
DocOrArray doc_or_array;
};
/**
* @brief Specialization of ToBsonTypedContext for a bson document
*/
typedef ToBsonTypedContext<bsoncxx::builder::stream::document> ToDocumentContext;
/**
* @brief Specialization of ToBsonTypedContext for a bson array.
*
* The class also adds additional state needed to properly set items within the destination
* array.
*/
class ToArrayContext : public ToBsonTypedContext<bsoncxx::builder::stream::array>
{
public:
ToArrayContext(
uint32_t the_member_index = 1,
std::vector<uint32_t> the_dimensions = {},
uint32_t the_dimension_index = 0,
uint32_t the_element_index = 1)
: ToBsonTypedContext<bsoncxx::builder::stream::array>(the_member_index),
dimensions(the_dimensions),
dimension_index(the_dimension_index),
element_index(the_element_index)
{
member_index = the_member_index;
}
// @brief current dimension for which elements are set
uint32_t dimension_index;
// @brief list of dimensions
std::vector<uint32_t> dimensions;
// @brief index within the destination array where the element is set
uint32_t element_index;
};
/***
* @brief Builds a document from the content of the specified DynamicData object.
*
* This is a recursive operation that traverses a DynamicData object using DFS approach.
* It automatically generates the appropriate complex member–either document or array–
* based on the type of each member.
*
* It is expected that the first call to this operation receives a ToDocumentContext
* and the top-level DynamicData object. Subsequent operations are self-made to build
* the full bson document.
*
* @param[in] context
* Current complex member context
* @param[in] data
* DynamicData object holding the content for the complex or array member. In
* recursive calls, this will be a loaned member.
*/
inline
void build_document(
ToBsonContext& context,
DynamicData &data)
{
using rti::core::xtypes::LoanedDynamicData;
using rti::core::xtypes::DynamicDataMemberInfo;
using dds::core::xtypes::ArrayType;
using bsoncxx::builder::stream::document;
if (context.member_index == context.member_count + 1) {
// end of members/items
return;
}
// Handle sub-array state
if (typeid(context) == typeid(ToArrayContext)) {
ToArrayContext& as_array_context =
static_cast<ToArrayContext&>(context);
if (as_array_context.dimension_index <
as_array_context.dimensions.size()) {
uint32_t current_dimension = as_array_context.dimension_index;
// Arrays can have too many elements for a recursive approach, hence
// we iterate on the elements to avoid stack overflow
for (uint32_t i = 0;
i < as_array_context.dimensions[current_dimension];
++i) {
if (as_array_context.dimension_index
< as_array_context.dimensions.size() - 1) {
ToArrayContext nested_context(
as_array_context.element_index,
as_array_context.dimensions,
as_array_context.dimension_index + 1,
as_array_context.element_index);
build_document(nested_context, data);
context.set_array(
nested_context.doc_or_array,
data.member_info(as_array_context.element_index));
// advance the element iterator index
as_array_context.element_index = nested_context.element_index;
} else {
// mark the end of dimensions
++as_array_context.dimension_index;
// Set member_count to allow only one recursion
context.member_count = as_array_context.element_index;
context.member_index = as_array_context.element_index;
build_document(context, data);
++as_array_context.element_index;
}
}
// end of elements, at this point we have reached the maximum
// at the current dimension
return;
}
}
if (!data.member_exists(context.member_index)) {
++context.member_index;
return build_document(context,data);
}
DynamicDataMemberInfo member_info =
data.member_info(context.member_index);
switch (member_info.member_kind().underlying()) {
case TypeKind::STRUCTURE_TYPE: {
LoanedDynamicData loaned_member =
data.loan_value(member_info.member_index());
ToDocumentContext nested_context(
loaned_member.get().member_count());
build_document(nested_context,loaned_member.get());
context.set_document(
nested_context.doc_or_array,
member_info);
}
break;
case TypeKind::SEQUENCE_TYPE: {
LoanedDynamicData loaned_array =
data.loan_value(member_info.member_name());
// Sequences can have too many elements for a recursive approach, hence
// we iterate on the elements to avoid stack overflow
ToArrayContext nested_context(1);
for (uint32_t i = 0; i < member_info.element_count(); ++i) {
// Set member_count to allow only one recursion
nested_context.member_count = i;
build_document(nested_context, loaned_array.get());
}
context.set_array(
nested_context.doc_or_array,
member_info);
}
break;
case TypeKind::ARRAY_TYPE: {
LoanedDynamicData loaned_array =
data.loan_value(member_info.member_name());
// Get dimensions as an array
const ArrayType& array_type =
static_cast<const ArrayType &> (loaned_array.get().type());
std::vector<uint32_t> dimensions;
dimensions.resize(array_type.dimension_count());
for (uint32_t j = 0; j < array_type.dimension_count(); j++) {
dimensions[j] = array_type.dimension(j);
}
ToArrayContext nested_context(1, dimensions);
build_document(nested_context, loaned_array.get());
context.set_array(
nested_context.doc_or_array,
member_info);
}
break;
default:
context.set_primitive(data, member_info);
}
++context.member_index;
build_document(context, data);
}
bsoncxx::document::value SampleConverter::to_document(
const dds::core::xtypes::DynamicData& data)
{
dds::core::xtypes::DynamicData& casted_data =
const_cast<dds::core::xtypes::DynamicData&>(data);
ToDocumentContext context(data.member_count());
build_document(context,casted_data);
return (context.doc_or_array << builder::stream::finalize);
}
/* --- SampleInfo --------------------------------------------------------------------*/
/**
* @brief Helper to add a DDS info member to either a document or an array
*
* Template specializations are expected to have a single static set() operation
* to perform the insertion.
*
* @tparam InfoType
* one of the valid DDS infrastructure types (e.g., Guid, InstanceHandle, Time_t, etc).
* @tparam DocOrArray
* Either a bsoncxx::document or bsoncxx::array.
*/
template<typename InfoType, typename DocOrArray = bsoncxx::builder::stream::document>
struct info_member_setter;
template<typename DocOrArray>
struct info_member_setter<dds::core::InstanceHandle, DocOrArray> {
/**
* @brief Sets the specified handle as an MD5 binary element into a destination
* document or array.
*
* @param[in] name
* Name of the member. Can be empty for array destinations.
* @param[in] handle
* InstanceHandle to be set
* @param[out] doc_or_array
* Destination object
*/
static void set(
const std::string& name,
const dds::core::InstanceHandle& handle,
DocOrArray& doc_or_array)
{
doc_or_array << name << types::b_binary{
bsoncxx::binary_sub_type::k_md5,
handle->native().keyHash.length,
static_cast<const uint8_t *>(&handle->native().keyHash.value[0])};
}
};
template<typename DocOrArray>
struct info_member_setter<rti::core::Guid, DocOrArray> {
/**
* @brief Sets the specified guid as an MD5 binary element into a destination
* document or array.
*
* @param[in] name
* Name of the member. Can be empty for array destinations.
* @param[in] guid
* Guid to be set
* @param[out] doc_or_array
* Destination object
*/
static void set(
const std::string& name,
const rti::core::Guid& guid,
DocOrArray& doc_or_array)
{
doc_or_array << name << types::b_binary{
bsoncxx::binary_sub_type::k_md5,
rti::core::Guid::LENGTH,
static_cast<const uint8_t *>(&guid.native().value[0])};
}
};
template<typename DocOrArray>
struct info_member_setter<rti::core::SequenceNumber, DocOrArray> {
/**
* @brief Sets the specified sequence number as a document element into a destination
* document or array.
*
* @param[in] name
* Name of the member. Can be empty for array destinations.
* @param[in] sn
* SequenceNumber to be set
* @param[out] doc_or_array
* Destination object
*/
static void set(
const std::string& name,
const rti::core::SequenceNumber& sn,
DocOrArray& doc_or_array)
{
doc_or_array << name
<< builder::stream::open_document
<< "high" << types::b_int32{sn.high()}
<< "low" << types::b_int64{sn.low()}
<< builder::stream::close_document;
}
};
template<typename DocOrArray>
struct info_member_setter<dds::core::Time, DocOrArray> {
/**
* @brief Sets the specified time as a document element into a destination
* document or array.
*
* @param[in] name
* Name of the member. Can be empty for array destinations.
* @param[in] time
* Time to be set
* @param[out] doc_or_array
* Destination object
*/
static void set(
const std::string& name,
const dds::core::Time& time,
DocOrArray& doc_or_array)
{
std::chrono::milliseconds chrono_millis(time.to_millisecs());
doc_or_array << name << types::b_date{chrono_millis};
}
};
bsoncxx::document::value SampleConverter::to_document(
const dds::sub::SampleInfo& info)
{
using dds::core::InstanceHandle;
using rti::core::Guid;
using rti::core::SequenceNumber;
bsoncxx::builder::stream::document info_doc{};
#define SAMPLE_CONVERT_ADD_DOC_MEMBER(TYPE, MEMBER) \
{ \
info_member_setter<TYPE>::set( \
#MEMBER, \
info->MEMBER(), \
info_doc); \
}
SAMPLE_CONVERT_ADD_DOC_MEMBER(
dds::core::InstanceHandle,
instance_handle);
SAMPLE_CONVERT_ADD_DOC_MEMBER(
dds::core::Time,
source_timestamp);
SAMPLE_CONVERT_ADD_DOC_MEMBER(
dds::core::Time,
reception_timestamp);
SAMPLE_CONVERT_ADD_DOC_MEMBER(
rti::core::Guid,
original_publication_virtual_guid);
SAMPLE_CONVERT_ADD_DOC_MEMBER(
rti::core::SequenceNumber,
original_publication_virtual_sequence_number);
SAMPLE_CONVERT_ADD_DOC_MEMBER(
rti::core::Guid,
related_original_publication_virtual_guid);
SAMPLE_CONVERT_ADD_DOC_MEMBER(
rti::core::SequenceNumber,
related_original_publication_virtual_sequence_number);
SAMPLE_CONVERT_ADD_DOC_MEMBER(
rti::core::Guid,
topic_query_guid);
return (info_doc << builder::stream::finalize);
}
/*
* -- From MongoDB to DDS conversion ----------------------------------------------------
*/
/* --- DynamicData --------------------------------------------------------------------*/
/**
* @brief Helper obtain the primitive value from a Cursor iterator, either array or
* document.
*
* Template specializations are expected to have a single static get() operation
* to obtain the value
*
* @tparam Primitive
* one of the valid element primitive types. Default behavior assumes the element
* value is an int32_t.
* @tparam ItType
* Either a document::view::iterator or array::view::iterator.
*/
template<typename Primitive, typename ItType>
struct cursor_get {
/**
* @brief Returns the element value to which the iterator pints.
* @param it Iterator positioned to the element whose value is returned
*/
static Primitive get(ItType it)
{
return static_cast<Primitive>(it->get_int32());
}
};
template<typename ItType>
struct cursor_get<int64_t, ItType> {
/**
* @brief Returns the value of an element that holds an 64-bit integer from its
* positioned iterator.
*
* @param it Iterator positioned to the element whose value is returned
*/
static int64_t get(ItType it)
{
return it->get_int64().value;
}
};
template<typename ItType>
struct cursor_get<std::string, ItType> {
/**
* @brief Returns the value of an element that holds a string from its
* positioned iterator.
*
* @param it Iterator positioned to the element whose value is returned
*/
static std::string get(ItType it)
{
return it->get_utf8().value.to_string();
}
};
template<typename ItType>
struct cursor_get<float, ItType> {
/**
* @brief Returns the value of an element that holds a float from its
* positioned iterator.
*
* @param it Iterator positioned to the element whose value is returned
*/
static float get(ItType it)
{
return static_cast<float>(it->get_double());
}
};
template<typename ItType>
struct cursor_get<double, ItType> {
/**
* @brief Returns the value of an element that holds a double from its
* positioned iterator.
*
* @param it Iterator positioned to the element whose value is returned
*/
static double get(ItType it)
{
return it->get_double();
}
};
template<typename ItType>
struct cursor_get<DDS_Boolean, ItType> {
/**
* @brief Returns the value of an element that holds a bolean from its
* positioned iterator.
*
* @param it Iterator positioned to the element whose value is returned
*/
static DDS_Boolean get(ItType it)
{
return static_cast<DDS_Boolean>(it->get_bool());
}
};
/**
* @brief Helper function to set a primitive member in a DynamicData object, provided
* a document or array positioned iterator
* @tparam Primitive
* Primitive type
* @tparam ItType
* Iterator type (document or array it)
* @param data
* Destination DynamicData object
* @param member_info
* Information of the destination member within _data_
* @param it
* Iterator positioned
*/
template<typename Primitive, typename ItType>
void from_primitive_element(
dds::core::xtypes::DynamicData& data,
const rti::core::xtypes::DynamicDataMemberInfo& member_info,
ItType it)
{
data.value(member_info.member_index(), cursor_get<Primitive, ItType>::get(it));
}
/**
* @brief Helper function that selects the proper cursor getter function based on the
* type of the destination DynamicData member
* @tparam ItType
* Iterator type (document or array it)
* @param data
* Destination DynamicData object
* @param member_info
* Information of the destination member within _data_
* @param it
* Iterator positioned
*/
template<typename ItType>
void demultiplex_primitive_element(
dds::core::xtypes::DynamicData& data,
const rti::core::xtypes::DynamicDataMemberInfo& member_info,
ItType it)
{
using rti::core::xtypes::DynamicDataMemberInfo;
typedef std::function<void(
DynamicData&,
const DynamicDataMemberInfo&,
ItType&)> FromPrimitiveFunc;
static std::unordered_map <int32_t, FromPrimitiveFunc> demux_table{
{
TypeKind::BOOLEAN_TYPE,
from_primitive_element<DDS_Boolean, ItType>
},
{
TypeKind::CHAR_8_TYPE,
from_primitive_element<DDS_Char, ItType>
},
{
TypeKind::UINT_8_TYPE,
from_primitive_element<uint8_t, ItType>
},
{
TypeKind::INT_16_TYPE,
from_primitive_element<int16_t, ItType>
},
{
TypeKind::UINT_16_TYPE,
from_primitive_element<uint16_t, ItType>
},
{
TypeKind::ENUMERATION_TYPE,
from_primitive_element<int32_t, ItType>
},
{
TypeKind::INT_32_TYPE,
from_primitive_element<int32_t, ItType>
},
{
TypeKind::INT_64_TYPE,
from_primitive_element<int64_t, ItType>
},
{
TypeKind::FLOAT_32_TYPE,
from_primitive_element<float, ItType>
},
{
TypeKind::FLOAT_64_TYPE,
from_primitive_element<double, ItType>
},
{
TypeKind::STRING_TYPE,
from_primitive_element<std::string, ItType>
}
};
typename std::unordered_map<int32_t, FromPrimitiveFunc>::iterator table_it =
demux_table.find(member_info.member_kind().underlying());
if (table_it == demux_table.end()) {
// log unsupported
std::ostringstream string_stream;
string_stream << "unsupported type for member=" << member_info.member_name();
rti::routing::Logger::instance().debug(string_stream.str());
return;
}
table_it->second(data, member_info, it);
}
/**
* @brief Helper obtain the associated member info from an array or document element,
* represnted by a positioned iterator.
*
* Template specializations are expected to have a single static get() operation
* to obtain the member info
*
* @tparam DocOrArray
* Either a document::view or array::view.
*/
template<typename DocOrArray>
struct member_info_from_element;
template<>
struct member_info_from_element<document::view> {
/**
* @brief Returns the member info for an iterator belonging to a document element.
*
* @param data
* associated DynamicData object
* @param it
* iterator positioned
*/
rti::core::xtypes::DynamicDataMemberInfo get(
dds::core::xtypes::DynamicData& data,
document::view::const_iterator& it)
{
return data.member_info(it->key().to_string());
}
};
template<>
struct member_info_from_element<array::view> {
/**
* @brief Returns the member info for an iterator belonging to an array element.
*
* @param data
* associated DynamicData object
* @param it
* iterator positioned
*/
rti::core::xtypes::DynamicDataMemberInfo get(
dds::core::xtypes::DynamicData& data,
array::view::const_iterator& it)
{
return data.member_info(it->offset());
}
};
/**
* @brief Represents of the context used to set a DynamicData element given a Document
* or Array element.
*/
class FromBsonContext {
public:
virtual rti::core::xtypes::DynamicDataMemberInfo member_info(
dds::core::xtypes::DynamicData& data) = 0;
virtual bool end() = 0;
virtual void operator++() = 0;
virtual void from_primitive(dds::core::xtypes::DynamicData& data) = 0;
virtual enum type type() = 0;
virtual document::view document() = 0;
virtual array::view array() = 0;
};
template<typename DocOrArray>
class FromBsonTypedContext : public FromBsonContext {
public:
FromBsonTypedContext(
DocOrArray the_doc_or_array,
int32_t the_element_index = 1)
:doc_or_array(the_doc_or_array),
it(the_doc_or_array.begin()),
element_index(the_element_index)
{}
void operator++() override
{
++it;
++element_index;
}
bool end() override
{
return (it == doc_or_array.end());
}
void from_primitive(dds::core::xtypes::DynamicData& data) override
{
demultiplex_primitive_element(data, member_info(data), it);
}
enum type type() override
{
return it->type();
}
document::view document() override
{
return it->get_document();
}
array::view array() override
{
return it->get_array();
}
DocOrArray doc_or_array;
typename DocOrArray::const_iterator it;
int32_t element_index;
};
class FromDocumentContext : public FromBsonTypedContext<document::view>{
public:
FromDocumentContext(document::view document)
: FromBsonTypedContext<document::view>(document)
{}
rti::core::xtypes::DynamicDataMemberInfo member_info(
dds::core::xtypes::DynamicData& data) override
{
return data.member_info(it->key().to_string());
}
};
class FromArrayContext : public FromBsonTypedContext<array::view>{
public:
FromArrayContext(
array::view array,
int32_t the_element_index = 1)
: FromBsonTypedContext<array::view>(array, the_element_index),
is_new_context(true),
finished(false)
{}
bool end() override
{
return FromBsonTypedContext<array::view>::end() || finished;
}
void operator++() override
{
FromBsonTypedContext<array::view>::operator++();
finished = true;
}
rti::core::xtypes::DynamicDataMemberInfo member_info(
dds::core::xtypes::DynamicData& data) override
{
return data.member_info(element_index);
}
bool is_new_context;
bool finished;
};
/***
* @brief Builds a DynamicData object from the content of the specified bson object.
*
* This is a recursive operation that traverses a bson document/array using DFS approach.
* It automatically sets the appropriate member based on the type of each element.
*
* It is expected that the first call to this operation receives a FromDocumentContext
* and the top-level DynamicData object. Subsequent operations are self-made to
* populate the DynamicData object.
*
*
* @param[in] data
* DynamicData object destination the content for the current element context. In
* recursive calls, this will be a loaned member.
* @param[in] context
* Current from-element context
*/
void build_dynamic_data(
dds::core::xtypes::DynamicData& data,
FromBsonContext& context)
{
using dds::core::xtypes::TypeKind;
using rti::core::xtypes::LoanedDynamicData;
using rti::core::xtypes::DynamicDataMemberInfo;
if (context.end()) {
return;
}
// find a corresponding member/item in dynamic data
try {
// This case occurs when we have a multidimensional array. The bson document
// has a nested element structure whereas DynamicData is all represented in a single
// multidimensional array. Hence, we need to create ArrayContext for each array
// element while using the same DynamicData loaned array member.
if (typeid(context) == typeid(FromArrayContext)) {
auto& array_context = dynamic_cast<FromArrayContext&>(context);
if (array_context.is_new_context) {
array_context.is_new_context = false;
// iteratively set each member, to avoid stack overlow on big sequences/arrays
while (!context.end()) {
if (context.type() == type::k_array) {
// need to set an array and start a new context
FromArrayContext nested_context(
context.array(),
array_context.element_index);
build_dynamic_data(data, nested_context);
array_context.element_index = nested_context.element_index - 1;
++array_context;
} else {
build_dynamic_data(data, array_context);
}
// reset the context, so it can move to the next available item
array_context.finished = false;
}
//end of processing the array context
return;
}
}
DynamicDataMemberInfo member_info = context.member_info(data);
switch (member_info.member_kind().underlying()) {
case TypeKind::STRUCTURE_TYPE: {
// need to set a complex member and start a new context
LoanedDynamicData loaned_member = data.loan_value(member_info.member_index());
FromDocumentContext nested_context(context.document());
build_dynamic_data(loaned_member.get(), nested_context);
}
break;
case TypeKind::SEQUENCE_TYPE:
case TypeKind::ARRAY_TYPE: {
// need to set an array and start a new context
LoanedDynamicData loaned_member = data.loan_value(member_info.member_index());
FromArrayContext nested_context(context.array());
build_dynamic_data(loaned_member.get(), nested_context);
}
break;
default:
context.from_primitive(data);
break;
}
} catch(const std::exception& ex) {
// member does not exist / not present
rti::routing::Logger::instance().error(
std::string("member mismatch: ") + std::string(ex.what()));
}
// move to the next
++context;
build_dynamic_data(data, context);
}
dds::core::xtypes::DynamicData& SampleConverter::from_document(
dds::core::xtypes::DynamicData& data,
const document::view document)
{
FromDocumentContext context(document);
build_dynamic_data(data, context);
return data;
}
| cxx |
rticonnextdds-examples | data/projects/rticonnextdds-examples/routing_service/routing_service_mongo_db/cpp/MongoConnection.cxx | /*
* (c) 2019 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 "MongoConnection.hpp"
#include "MongoStreamReader.hpp"
#include "MongoStreamWriter.hpp"
using namespace rti::community::examples;
using namespace rti::routing;
using namespace rti::routing::adapter;
/*
* --- MongoConnection -------------------------------------------------------
*/
std::string build_uri(const PropertySet &properties)
{
std::string cluster_addr =
MongoConfig::parse<MongoConfig::CLUSTER_ADDRESS>(properties);
std::string user_and_pass =
MongoConfig::parse<MongoConfig::USER_AND_PASS>(properties);
std::string uri_params =
MongoConfig::parse<MongoConfig::URI_PARAMS>(properties);
return "mongodb+srv://" + user_and_pass + "@" + cluster_addr
+ "/<database>?" + uri_params;
}
MongoConnection::MongoConnection(const PropertySet &properties)
: client_pool_(mongocxx::uri(build_uri(properties))),
db_name_(MongoConfig::parse<MongoConfig::DB_NAME>(properties))
{
}
/* --- Private interface ---*/
const std::string &MongoConnection::db_name() const
{
return db_name_;
}
mongocxx::pool::entry MongoConnection::client()
{
return client_pool_.acquire();
}
/* --- Adapter Interface --- */
StreamWriter *MongoConnection::create_stream_writer(
Session *,
const StreamInfo &stream_info,
const PropertySet &properties)
{
return new MongoStreamWriter(*this, stream_info, properties);
};
void MongoConnection::delete_stream_writer(StreamWriter *writer)
{
delete writer;
}
rti::routing::adapter::StreamReader *MongoConnection::create_stream_reader(
rti::routing::adapter::Session *,
const StreamInfo &stream_info,
const PropertySet &properties,
rti::routing::adapter::StreamReaderListener *)
{
return new MongoStreamReader(*this, stream_info, properties);
}
void MongoConnection::delete_stream_reader(
rti::routing::adapter::StreamReader *reader)
{
delete reader;
}
| cxx |
rticonnextdds-examples | data/projects/rticonnextdds-examples/routing_service/routing_service_mongo_db/cpp/MongoStreamWriter.hpp | /*
* (c) 2019 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.
*/
#ifndef MONGO_STREAMWRITER_HPP
#define MONGO_STREAMWRITER_HPP
#include <iostream>
#include <rti/routing/adapter/AdapterPlugin.hpp>
#include <rti/routing/adapter/StreamWriter.hpp>
#include "MongoConnection.hpp"
namespace rti { namespace community { namespace examples {
/**
* @brief Implementation of the adapter StreamWriter to write DDS samples as
* MongoDB objects.
*
* This class is responsible for inserting samples into a MongoDB database as
* as part of a collection identified by the associated stream name. This class
* is responsible for converting a stream sample (represented as a pair
* [DynamicData,SampleInfo]) into a mongocxx::document.
*
* To perform database insertions, this class obtains a client handle through
* the parent factory MongoConnection, which is provided on object construction.
*/
class MongoStreamWriter
: public rti::routing::adapter::DynamicDataStreamWriter {
public:
/**
* @brief Creates the StreamWriter from the required parameters.
*
* @param connection
* The parent factory connection
* @param stream_info
* Information for the associated Stream, provided by Routing Service.
* @param properties
* Configuration properites provided by the <property> tag within
* <output>.
*/
MongoStreamWriter(
MongoConnection &connection,
const rti::routing::StreamInfo &stream_info,
const rti::routing::PropertySet &properties);
/*
* --- StreamWriter interface
* ---------------------------------------------------------
*/
/**
* @brief Performs the insertion of DDS samples into MongoDB.
*
* For each sample DynamicData::SampleInfo, a new document object is added
* to the collection whose name is the name of the associated stream. Each
* sample _i_ is represented as:
*
* ```
* {
* data: bson{samples[i]}
* info: bson{infos[i]}
* }
* ```
*
* where _bson{samples[i]}_ is the BSON representation of a DDS data item
* and _bson_{infos[i]} is the BSON representation of a DDS info item.
*
* @see SampleConverter
*
*/
int write(
const std::vector<dds::core::xtypes::DynamicData *> &samples,
const std::vector<dds::sub::SampleInfo *> &infos) override final;
private:
MongoConnection &connection_;
std::string stream_name_;
};
}}} // namespace rti::community::examples
#endif
| hpp |
rticonnextdds-examples | data/projects/rticonnextdds-examples/routing_service/routing_service_mongo_db/cpp/MongoAdapter.cxx | /*
* (c) 2019 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 <memory>
#include "MongoAdapter.hpp"
#include "MongoConnection.hpp"
#include <mongocxx/logger.hpp>
#include <rti/routing/Logger.hpp>
using namespace rti::community::examples;
using namespace rti::routing;
using namespace rti::routing::adapter;
/**
* @brief Implementation of the MongoDB driver logger that redirects messages to
* the Connext logger.
*/
class MongoLogger : public mongocxx::logger {
public:
void operator()(
mongocxx::log_level level,
mongocxx::stdx::string_view domain,
mongocxx::stdx::string_view message) noexcept override final
{
using mongocxx::log_level;
switch (level) {
case log_level::k_debug:
case log_level::k_trace:
rti::routing::Logger::instance().debug(
domain.to_string() + ":" + message.to_string());
break;
case log_level::k_info:
rti::routing::Logger::instance().remote(
domain.to_string() + ":" + message.to_string());
break;
case log_level::k_message:
rti::routing::Logger::instance().local(
domain.to_string() + ":" + message.to_string());
break;
case log_level::k_warning:
rti::routing::Logger::instance().warn(
domain.to_string() + ":" + message.to_string());
break;
default:
rti::routing::Logger::instance().error(
domain.to_string() + ":" + message.to_string());
break;
}
}
};
MongoAdapter::MongoAdapter(PropertySet &)
: instance_(std::unique_ptr<MongoLogger>())
{
}
Connection *MongoAdapter::create_connection(
rti::routing::adapter::detail::StreamReaderListener *,
rti::routing::adapter::detail::StreamReaderListener *,
const PropertySet &properties)
{
return new MongoConnection(properties);
}
void MongoAdapter::delete_connection(Connection *connection)
{
delete connection;
}
rti::config::LibraryVersion MongoAdapter::get_version() const
{
return { 1, 0, 0, 'r' };
};
RTI_ADAPTER_PLUGIN_CREATE_FUNCTION_DEF(MongoAdapter)
| cxx |
rticonnextdds-examples | data/projects/rticonnextdds-examples/routing_service/routing_service_file_adapter/cpp/FileAdapter.cxx | /*
* (c) 2019 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 "FileAdapter.hpp"
#include "FileConnection.hpp"
using namespace rti::community::examples;
using namespace rti::routing;
using namespace rti::routing::adapter;
FileAdapter::FileAdapter(PropertySet &properties)
{
}
Connection *FileAdapter::create_connection(
rti::routing::adapter::detail::StreamReaderListener
*input_stream_discovery_listener,
rti::routing::adapter::detail::StreamReaderListener
*output_stream_discovery_listener,
const PropertySet &properties)
{
FileConnection *fc = new FileConnection(
input_stream_discovery_listener,
output_stream_discovery_listener,
properties);
return fc;
}
void FileAdapter::delete_connection(Connection *connection)
{
/**
* Perform cleanup pertaining to the connection object here.
*/
delete connection;
}
rti::config::LibraryVersion FileAdapter::get_version() const
{
return { 1, 0, 0, 'r' };
}
RTI_ADAPTER_PLUGIN_CREATE_FUNCTION_DEF(FileAdapter)
| cxx |
rticonnextdds-examples | data/projects/rticonnextdds-examples/routing_service/routing_service_file_adapter/cpp/FileAdapter.hpp | /*
* (c) 2019 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.
*/
#ifndef FILEADAPTER_HPP
#define FILEADAPTER_HPP
#include <dds/core/corefwd.hpp>
#include <dds/core/macros.hpp>
#include <rti/routing/PropertySet.hpp>
#include <rti/routing/RoutingService.hpp>
#include <rti/routing/adapter/AdapterPlugin.hpp>
namespace rti { namespace community { namespace examples {
class FileAdapter : public rti::routing::adapter::AdapterPlugin {
public:
explicit FileAdapter(rti::routing::PropertySet &);
rti::routing::adapter::Connection *create_connection(
rti::routing::adapter::detail::StreamReaderListener *,
rti::routing::adapter::detail::StreamReaderListener *,
const rti::routing::PropertySet &) final;
void delete_connection(rti::routing::adapter::Connection *connection) final;
rti::config::LibraryVersion get_version() const;
};
}}} // namespace rti::community::examples
/**
* This macro defines a C-linkage symbol that can be used as create function
* for plug-in registration through XML.
*
* The generated symbol has the name:
*
* \code
* FileAdapterPlugin_create_adapter_plugin
* \endcode
*/
RTI_ADAPTER_PLUGIN_CREATE_FUNCTION_DECL(FileAdapter)
#endif
| hpp |
rticonnextdds-examples | data/projects/rticonnextdds-examples/routing_service/routing_service_file_adapter/cpp/FileConnection.hpp | /*
* (c) 2019 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.
*/
#ifndef FILECONNECTION_HPP
#define FILECONNECTION_HPP
#include <rti/routing/adapter/AdapterPlugin.hpp>
#include <rti/routing/adapter/Connection.hpp>
#include "FileInputDiscoveryStreamReader.hpp"
namespace rti { namespace community { namespace examples {
class FileConnection : public rti::routing::adapter::Connection {
public:
FileConnection(
rti::routing::adapter::StreamReaderListener
*input_stream_discovery_listener,
rti::routing::adapter::StreamReaderListener
*output_stream_discovery_listener,
const rti::routing::PropertySet &properties);
rti::routing::adapter::StreamReader *create_stream_reader(
rti::routing::adapter::Session *session,
const rti::routing::StreamInfo &info,
const rti::routing::PropertySet &properties,
rti::routing::adapter::StreamReaderListener *listener) final;
void delete_stream_reader(
rti::routing::adapter::StreamReader *reader) final;
rti::routing::adapter::StreamWriter *create_stream_writer(
rti::routing::adapter::Session *session,
const rti::routing::StreamInfo &info,
const rti::routing::PropertySet &properties) final;
void delete_stream_writer(
rti::routing::adapter::StreamWriter *writer) final;
rti::routing::adapter::DiscoveryStreamReader *
input_stream_discovery_reader() final;
rti::routing::adapter::DiscoveryStreamReader *
output_stream_discovery_reader() final;
/**
* @brief This function is called by the FileStreamReader to indicate that
* it has reached EOF and its time to dispose the route. The dispose set by
* the FileInputDiscoveryStreamReader starts the chain of cleanup procedure.
* Remember that the <creation_mode> for <output> should be ON_ROUTE_MATCH
* for the cleanup to be propagated to the StreamWriter as well.
*
* @param stream_info \b in. Reference to a StreamInfo object which should
* be used when creating a new StreamInfo sample with disposed set to true
*/
void dispose_discovery_stream(
const rti::routing::StreamInfo &stream_info);
private:
FileInputDiscoveryStreamReader input_discovery_reader_;
};
}}} // namespace rti::community::examples
#endif
| hpp |
rticonnextdds-examples | data/projects/rticonnextdds-examples/routing_service/routing_service_file_adapter/cpp/FileInputDiscoveryStreamReader.hpp | /*
* (c) 2019 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.
*/
#ifndef FILEDISCOVERYSTREAMREADER_HPP
#define FILEDISCOVERYSTREAMREADER_HPP
#include <fstream>
#include <mutex>
#include <rti/routing/adapter/AdapterPlugin.hpp>
#include <rti/routing/adapter/DiscoveryStreamReader.hpp>
namespace rti { namespace community { namespace examples {
/**
* This class implements a DiscoveryStreamReader, a special kind of StreamReader
* that provide discovery information about the available streams and their
* types.
*/
class FileInputDiscoveryStreamReader
: public rti::routing::adapter::DiscoveryStreamReader {
public:
FileInputDiscoveryStreamReader(
const rti::routing::PropertySet &,
rti::routing::adapter::StreamReaderListener
*input_stream_discovery_listener);
void take(std::vector<rti::routing::StreamInfo *> &) final;
void return_loan(std::vector<rti::routing::StreamInfo *> &) final;
/**
* @brief Custom operation defined to indicate disposing off an <input>
* when the FileStreamReader has finished reading from a file.
* The FileInputDiscoveryStreamReader will then create a new
* discovery sample indicating that the stream has been disposed.
* This will cause the Routing Service to start tearing down the Routes
* associated with <input> having the corresponding <registered_type_name>
* and <stream_name>.
*
* @param stream_info \b in. Reference to a StreamInfo object which should
* be used when creating a new StreamInfo sample with disposed set to true
*/
void dispose(const rti::routing::StreamInfo &stream_info);
bool fexists(const std::string filename);
private:
static const std::string SQUARE_FILE_NAME;
static const std::string CIRCLE_FILE_NAME;
static const std::string TRIANGLE_FILE_NAME;
std::mutex data_samples_mutex_;
std::vector<std::unique_ptr<rti::routing::StreamInfo>> data_samples_;
rti::routing::adapter::StreamReaderListener
*input_stream_discovery_listener_;
};
}}} // namespace rti::community::examples
#endif
| hpp |
rticonnextdds-examples | data/projects/rticonnextdds-examples/routing_service/routing_service_file_adapter/cpp/FileInputDiscoveryStreamReader.cxx | /*
* (c) 2019 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 "FileInputDiscoveryStreamReader.hpp"
using namespace rti::routing;
using namespace rti::routing::adapter;
using namespace rti::community::examples;
const std::string FileInputDiscoveryStreamReader::SQUARE_FILE_NAME =
"Input_Square.csv";
const std::string FileInputDiscoveryStreamReader::CIRCLE_FILE_NAME =
"Input_Circle.csv";
const std::string FileInputDiscoveryStreamReader::TRIANGLE_FILE_NAME =
"Input_Triangle.csv";
bool FileInputDiscoveryStreamReader::fexists(const std::string filename)
{
std::ifstream input_file;
input_file.open(filename);
return input_file.is_open();
}
FileInputDiscoveryStreamReader::FileInputDiscoveryStreamReader(
const PropertySet &,
StreamReaderListener *input_stream_discovery_listener)
{
input_stream_discovery_listener_ = input_stream_discovery_listener;
/**
* In our example, we provide statically the stream information available.
* We do not have a mechanism demonstrating how to perform discovery after
* startup. However, as an idea you can have a thread monitoring the file
* system and updating the list of StreamInfo samples and calling
* input_stream_discovery_listener_->on_data_available(this); to notify that
* new files have been discovered.
*/
if (fexists(SQUARE_FILE_NAME)) {
this->data_samples_.push_back(std::unique_ptr<rti::routing::StreamInfo>(
new StreamInfo("Square", "ShapeType")));
}
if (fexists(CIRCLE_FILE_NAME)) {
this->data_samples_.push_back(std::unique_ptr<rti::routing::StreamInfo>(
new StreamInfo("Circle", "ShapeType")));
}
if (fexists(TRIANGLE_FILE_NAME)) {
this->data_samples_.push_back(std::unique_ptr<rti::routing::StreamInfo>(
new StreamInfo("Triangle", "ShapeType")));
}
/**
* Once the FileInputDiscoveryStreamReader is initialized, we trigger an
* event to notify that the streams are ready.
*/
input_stream_discovery_listener_->on_data_available(this);
}
void FileInputDiscoveryStreamReader::dispose(
const rti::routing::StreamInfo &stream_info)
{
/**
* This guard is essential since the take() and return_loan() operations
* triggered by calling on_data_available() execute on an internal Routing
* Service thread. The custom dispose() operation doesn't run on that
* thread. Since the take() and return_loan() operations also need to access
* the data_samples_ list this protection is required.
*/
std::lock_guard<std::mutex> guard(data_samples_mutex_);
std::unique_ptr<rti::routing::StreamInfo> stream_info_disposed(
new StreamInfo(
stream_info.stream_name(),
stream_info.type_info().type_name()));
stream_info_disposed.get()->disposed(true);
this->data_samples_.push_back(std::move(stream_info_disposed));
input_stream_discovery_listener_->on_data_available(this);
}
void FileInputDiscoveryStreamReader::take(
std::vector<rti::routing::StreamInfo *> &stream)
{
/**
* This guard is essential since the take() and return_loan() operations
* triggered by calling on_data_available() execute on an internal Routing
* Service thread. The custom dispose() operation doesn't run on that
* thread. Since the take() and return_loan() operations also need to access
* the data_samples_ list this protection is required.
*/
std::lock_guard<std::mutex> guard(data_samples_mutex_);
std::transform(
data_samples_.begin(),
data_samples_.end(),
std::back_inserter(stream),
[](const std::unique_ptr<rti::routing::StreamInfo> &element) {
return element.get();
});
}
void FileInputDiscoveryStreamReader::return_loan(
std::vector<rti::routing::StreamInfo *> &stream)
{
/**
* This guard is essential since the take() and return_loan() operations
* triggered by calling on_data_available() execute on an internal Routing
* Service thread. The custom dispose() operation doesn't run on that
* thread. Since the take() and return_loan() operations also need to access
* the data_samples_ list this protection is required.
*/
std::lock_guard<std::mutex> guard(data_samples_mutex_);
/**
* For discovery streams there will never be any outstanding return_loan().
* Thus we can be sure that each take() will be followed by a call to
* return_loan(), before the next take() executes.
*/
this->data_samples_.erase(
data_samples_.begin(),
data_samples_.begin() + stream.size());
stream.clear();
}
| cxx |
rticonnextdds-examples | data/projects/rticonnextdds-examples/routing_service/routing_service_file_adapter/cpp/FileConnection.cxx | /*
* (c) 2019 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 "FileConnection.hpp"
#include "FileStreamReader.hpp"
#include "FileStreamWriter.hpp"
using namespace rti::community::examples;
using namespace rti::routing;
using namespace rti::routing::adapter;
FileConnection::FileConnection(
StreamReaderListener *input_stream_discovery_listener,
StreamReaderListener *output_stream_discovery_listener,
const PropertySet &properties)
: input_discovery_reader_(
properties,
input_stream_discovery_listener) {};
StreamReader *FileConnection::create_stream_reader(
Session *session,
const StreamInfo &info,
const PropertySet &properties,
StreamReaderListener *listener)
{
return new FileStreamReader(this, info, properties, listener);
}
void FileConnection::delete_stream_reader(StreamReader *reader)
{
FileStreamReader *file_reader = dynamic_cast<FileStreamReader *>(reader);
file_reader->shutdown_file_reader_thread();
delete reader;
}
StreamWriter *FileConnection::create_stream_writer(
Session *session,
const StreamInfo &info,
const PropertySet &properties)
{
return new FileStreamWriter(properties);
}
void FileConnection::delete_stream_writer(StreamWriter *writer)
{
delete writer;
}
DiscoveryStreamReader *FileConnection::output_stream_discovery_reader()
{
return nullptr;
}
DiscoveryStreamReader *FileConnection::input_stream_discovery_reader()
{
return &input_discovery_reader_;
}
void FileConnection::dispose_discovery_stream(
const rti::routing::StreamInfo &stream_info)
{
input_discovery_reader_.dispose(stream_info);
}
| cxx |
rticonnextdds-examples | data/projects/rticonnextdds-examples/routing_service/routing_service_file_adapter/cpp/FileStreamWriter.hpp | /*
* (c) 2019 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.
*/
#ifndef FILESTREAMWRITER_HPP
#define FILESTREAMWRITER_HPP
#include <iostream>
#include <fstream>
#include <rti/routing/adapter/AdapterPlugin.hpp>
#include <rti/routing/adapter/StreamWriter.hpp>
namespace rti { namespace community { namespace examples {
class FileStreamWriter : public rti::routing::adapter::DynamicDataStreamWriter {
public:
explicit FileStreamWriter(const rti::routing::PropertySet &);
int
write(const std::vector<dds::core::xtypes::DynamicData *> &samples,
const std::vector<dds::sub::SampleInfo *> &infos) final;
~FileStreamWriter();
private:
static const std::string OUTPUT_FILE_PROPERTY_NAME;
std::ofstream output_file_;
};
}}} // namespace rti::community::examples
#endif
| hpp |
rticonnextdds-examples | data/projects/rticonnextdds-examples/routing_service/routing_service_file_adapter/cpp/FileStreamReader.hpp | /*
* (c) 2019 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.
*/
#ifndef FILESTREAMREADER_HPP
#define FILESTREAMREADER_HPP
#include <fstream>
#include <iostream>
#include <thread>
#include "FileConnection.hpp"
#include <rti/routing/adapter/AdapterPlugin.hpp>
#include <rti/routing/adapter/StreamReader.hpp>
namespace rti { namespace community { namespace examples {
class FileStreamReader : public rti::routing::adapter::DynamicDataStreamReader {
public:
FileStreamReader(
FileConnection *connection,
const rti::routing::StreamInfo &info,
const rti::routing::PropertySet &,
rti::routing::adapter::StreamReaderListener *listener);
void
take(std::vector<dds::core::xtypes::DynamicData *> &,
std::vector<dds::sub::SampleInfo *> &) final;
void take(
std::vector<dds::core::xtypes::DynamicData *> &,
std::vector<dds::sub::SampleInfo *> &,
const rti::routing::adapter::SelectorState &selector_state) final;
void return_loan(
std::vector<dds::core::xtypes::DynamicData *> &,
std::vector<dds::sub::SampleInfo *> &) final;
void shutdown_file_reader_thread();
bool check_csv_file_line_format(const std::string &line);
bool is_digit(const std::string &value);
~FileStreamReader();
private:
static const std::string INPUT_FILE_PROPERTY_NAME;
static const std::string SAMPLE_PERIOD_PROPERTY_NAME;
/**
* @brief Function used by filereader_thread_ to read samples from the
* CSV formatted file one line at a time. The file only contains data and
* no meta data information.
*/
void file_reading_thread();
FileConnection *file_connection_;
rti::routing::adapter::StreamReaderListener *reader_listener_;
std::thread filereader_thread_;
bool stop_thread_;
std::chrono::seconds sampling_period_;
std::ifstream input_file_stream_;
std::string input_file_name_;
std::string buffer_;
std::mutex buffer_mutex_;
rti::routing::StreamInfo stream_info_;
dds::core::xtypes::DynamicType *adapter_type_;
};
}}} // namespace rti::community::examples
#endif
| hpp |
rticonnextdds-examples | data/projects/rticonnextdds-examples/routing_service/routing_service_file_adapter/cpp/FileStreamReader.cxx | /*
* (c) 2019 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 <cctype>
#include <sstream>
#include <thread>
#include "FileStreamReader.hpp"
#include <rti/core/Exception.hpp>
using namespace dds::core::xtypes;
using namespace rti::routing;
using namespace rti::routing::adapter;
using namespace rti::community::examples;
const std::string FileStreamReader::INPUT_FILE_PROPERTY_NAME =
"example.adapter.input_file";
const std::string FileStreamReader::SAMPLE_PERIOD_PROPERTY_NAME =
"example.adapter.sample_period_sec";
bool FileStreamReader::check_csv_file_line_format(const std::string &line)
{
return (!line.empty()) && (std::count(line.begin(), line.end(), ',') == 3);
}
bool FileStreamReader::is_digit(const std::string &value)
{
return std::find_if(
value.begin(),
value.end(),
[](unsigned char c) { return !std::isdigit(c); })
== value.end();
}
void FileStreamReader::file_reading_thread()
{
while (!stop_thread_) {
if (input_file_stream_.is_open()) {
{
/**
* Essential to protect against concurrent data access to
* buffer_ from the take() methods running on a different
* Routing Service thread.
*/
std::lock_guard<std::mutex> guard(buffer_mutex_);
std::getline(input_file_stream_, buffer_);
}
/**
* Here we notify Routing Service, that there is data available
* on the StreamReader, triggering a call to take().
*/
if (!input_file_stream_.eof()) {
reader_listener_->on_data_available(this);
} else {
stop_thread_ = true;
}
}
std::this_thread::sleep_for(sampling_period_);
}
std::cout << "Reached end of stream for file: " << input_file_name_
<< std::endl;
file_connection_->dispose_discovery_stream(stream_info_);
}
FileStreamReader::FileStreamReader(
FileConnection *connection,
const StreamInfo &info,
const PropertySet &properties,
StreamReaderListener *listener)
: sampling_period_(1),
stop_thread_(false),
stream_info_(info.stream_name(), info.type_info().type_name())
{
file_connection_ = connection;
reader_listener_ = listener;
adapter_type_ =
static_cast<DynamicType *>(info.type_info().type_representation());
// Parse the properties provided in the xml configuration file
for (const auto &property : properties) {
if (property.first == INPUT_FILE_PROPERTY_NAME) {
input_file_name_ = property.second;
input_file_stream_.open(property.second);
} else if (property.first == SAMPLE_PERIOD_PROPERTY_NAME) {
sampling_period_ = std::chrono::seconds(std::stoi(property.second));
}
}
if (input_file_name_.empty()) {
throw dds::core::IllegalOperationError(
"Error property not found: " + INPUT_FILE_PROPERTY_NAME);
} else if (!input_file_stream_.is_open()) {
throw dds::core::IllegalOperationError(
"Error opening input file: " + input_file_name_);
} else {
std::cout << "Input file name: " << input_file_name_ << std::endl;
}
filereader_thread_ =
std::thread(&FileStreamReader::file_reading_thread, this);
}
void FileStreamReader::take(
std::vector<dds::core::xtypes::DynamicData *> &samples,
std::vector<dds::sub::SampleInfo *> &infos)
{
/**
* This protection is required since take() executes on a different
* Routing Service thread.
*/
std::lock_guard<std::mutex> guard(buffer_mutex_);
if (!check_csv_file_line_format(buffer_)) {
std::cout << "Incorrect format for line: " << buffer_ << std::endl;
return;
}
std::istringstream s(buffer_);
std::string color;
std::string x;
std::string y;
std::string shapesize;
// Reading input from the CSV file
std::getline(s, color, ',');
std::getline(s, x, ',');
std::getline(s, y, ',');
std::getline(s, shapesize, ',');
if (!(is_digit(x) && is_digit(y) && is_digit(shapesize))) {
std::cout << "Incorrect values found at line: " << buffer_ << std::endl;
return;
}
/**
* Note that we read one line at a time from the CSV file in the
* function file_reading_thread()
*/
samples.resize(1);
infos.resize(1);
std::unique_ptr<DynamicData> sample(new DynamicData(*adapter_type_));
/**
* This is the hardcoded type information about ShapeType.
* You are advised to change this as per your type definition
*/
sample->value("color", color);
sample->value("x", std::stoi(x));
sample->value("y", std::stoi(y));
sample->value("shapesize", std::stoi(shapesize));
samples[0] = sample.release();
return;
}
void FileStreamReader::take(
std::vector<dds::core::xtypes::DynamicData *> &samples,
std::vector<dds::sub::SampleInfo *> &infos,
const SelectorState &selector_state)
{
take(samples, infos);
}
void FileStreamReader::return_loan(
std::vector<dds::core::xtypes::DynamicData *> &samples,
std::vector<dds::sub::SampleInfo *> &infos)
{
for (int i = 0; i < samples.size(); ++i) {
delete samples[i];
delete infos[i];
}
samples.clear();
infos.clear();
}
void FileStreamReader::shutdown_file_reader_thread()
{
stop_thread_ = true;
filereader_thread_.join();
}
FileStreamReader::~FileStreamReader()
{
input_file_stream_.close();
}
| cxx |
rticonnextdds-examples | data/projects/rticonnextdds-examples/routing_service/routing_service_file_adapter/cpp/FileStreamWriter.cxx | /*
* (c) 2019 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 "FileStreamWriter.hpp"
#include <rti/core/Exception.hpp>
#include <rti/topic/to_string.hpp>
using namespace rti::routing;
using namespace rti::routing::adapter;
using namespace rti::community::examples;
const std::string FileStreamWriter::OUTPUT_FILE_PROPERTY_NAME =
"example.adapter.output_file";
FileStreamWriter::FileStreamWriter(const PropertySet &properties)
{
std::string output_file_name;
for (const auto &property : properties) {
if (property.first == OUTPUT_FILE_PROPERTY_NAME) {
output_file_name = property.second;
output_file_.open(output_file_name);
break;
}
}
if (!output_file_.is_open()) {
throw dds::core::IllegalOperationError(
"Error opening output file: " + output_file_name);
} else {
std::cout << "Output file name: " << output_file_name << std::endl;
}
}
int FileStreamWriter::write(
const std::vector<dds::core::xtypes::DynamicData *> &samples,
const std::vector<dds::sub::SampleInfo *> &infos)
{
for (auto sample : samples) {
std::cout << "Received Sample: " << std::endl
<< rti::topic::to_string(*sample) << std::endl;
output_file_ << sample->value<std::string>("color") << ","
<< sample->value<int32_t>("x") << ","
<< sample->value<int32_t>("y") << ","
<< sample->value<int32_t>("shapesize") << std::endl;
}
return 0;
}
FileStreamWriter::~FileStreamWriter()
{
output_file_.close();
}
| cxx |
rticonnextdds-examples | data/projects/rticonnextdds-examples/routing_service/routing_service_file_adapter/c/file_adapter.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.
******************************************************************************/
/* ========================================================================= */
/* RTI Routing Service File Adapter */
/* ========================================================================= */
/* This is a pluggable adapter that reads blocks from a file */
/* providing them to Routing Service as DynamicData samples */
/* and receives samples from Routing Service to write them in a file */
/* */
/* To customize to your data format, edit LineConversion.c */
/* */
/* ========================================================================= */
#include <stdio.h>
#include <string.h>
#include "data_structures.h"
#include "line_conversion.h"
#include "ndds/ndds_c.h"
#include "routingservice/routingservice_adapter.h"
#include <pthread.h>
#include <semaphore.h>
#include <sys/select.h>
/* This function creates the typecode */
DDS_TypeCode *RTI_RoutingServiceFileAdapter_create_type_code()
{
struct DDS_TypeCodeFactory *factory = NULL;
struct DDS_TypeCode *sequence_tc = NULL; /* type code for octet */
struct DDS_TypeCode *struct_tc = NULL; /* Top-level typecode */
struct DDS_StructMemberSeq member_seq = DDS_SEQUENCE_INITIALIZER;
DDS_ExceptionCode_t ex = DDS_NO_EXCEPTION_CODE;
/* we get the instance of the type code factory */
factory = DDS_TypeCodeFactory_get_instance();
if (factory == NULL) {
fprintf(stderr, "ERROR: Unable to get type code factory singleton\n");
goto done;
}
/* create a sequence for DDS_Octet, so we use a general type */
sequence_tc = DDS_TypeCodeFactory_create_sequence_tc(
factory,
MAX_PAYLOAD_SIZE,
DDS_TypeCodeFactory_get_primitive_tc(factory, DDS_TK_OCTET),
&ex);
if (ex != DDS_NO_EXCEPTION_CODE) {
fprintf(stderr,
"ERROR: Unable to create 'payload' sequence typecode:"
" %d\n",
ex);
goto done;
}
/* create top-level typecode */
struct_tc = DDS_TypeCodeFactory_create_struct_tc(
factory,
"TextLine",
&member_seq,
&ex);
if (ex != DDS_NO_EXCEPTION_CODE) {
fprintf(stderr, "Unable to create struct typecode, error = %d\n", ex);
goto done;
}
DDS_TypeCode_add_member(
struct_tc,
"value",
DDS_MEMBER_ID_INVALID,
sequence_tc,
DDS_TYPECODE_NONKEY_MEMBER,
&ex);
if (ex != DDS_NO_EXCEPTION_CODE) {
fprintf(stderr,
"Error adding member to struct typecode, error=%d\n",
ex);
goto done;
}
if (sequence_tc != NULL) {
DDS_TypeCodeFactory_delete_tc(factory, sequence_tc, &ex);
}
return struct_tc;
done:
if (sequence_tc != NULL) {
DDS_TypeCodeFactory_delete_tc(factory, sequence_tc, &ex);
}
if (struct_tc != NULL) {
DDS_TypeCodeFactory_delete_tc(factory, struct_tc, &ex);
}
return NULL;
}
void RTI_RoutingServiceFileAdapter_delete_type_code(DDS_TypeCode *type_code)
{
DDS_TypeCodeFactory *factory = NULL;
DDS_ExceptionCode_t ex = DDS_NO_EXCEPTION_CODE;
factory = DDS_TypeCodeFactory_get_instance();
if (factory == NULL) {
fprintf(stdout,
"ERROR getting instance DDS_TypeCodeFactory deleting typecode\n");
return;
} else {
if (type_code != NULL) {
DDS_TypeCodeFactory_delete_tc(factory, type_code, &ex);
}
if (ex != DDS_NO_EXCEPTION_CODE) {
fprintf(stderr, "Unable to delete typecode\n");
return;
}
}
}
/* ========================================================================= */
/* */
/* Stream reader methods */
/* */
/* ========================================================================= */
void *RTI_RoutingServiceFileStreamReader_run(void *threadParam)
{
struct RTI_RoutingServiceFileStreamReader *self =
(struct RTI_RoutingServiceFileStreamReader *) threadParam;
/* This thread will notify periodically data availability in the file */
while (self->is_running_enabled) {
NDDS_Utility_sleep(&self->read_period);
if (!feof(self->file)) {
self->listener.on_data_available(
self,
self->listener.listener_data);
}
}
return NULL;
}
/*****************************************************************************/
/*
* This function gets called inside the function read or by the return loan,
* it frees the dynamic array of dynamic data, when we return the loan,
* or when we have some errors, after allocating memory for the sample
* list
*/
void RTI_RoutingServiceFileStreamReader_freeDynamicDataArray(
struct DDS_DynamicData **samples,
int count)
{
int i = 0;
for (i = 0; i < count; i++) {
if (samples[i] != NULL) {
DDS_DynamicData_delete(samples[i]);
samples[i] = NULL;
}
}
free(samples);
samples = NULL;
}
/*****************************************************************************/
/*
* The read function gets called every time the routing service
* gets notified of data available by the function on_data_available
* of every stream reader's listener
*/
void RTI_RoutingServiceFileStreamReader_read(
RTI_RoutingServiceStreamReader stream_reader,
RTI_RoutingServiceSample **sample_list,
RTI_RoutingServiceSampleInfo **info_list,
int *count,
RTI_RoutingServiceEnvironment *env)
{
int i = 0, sample_counter = 0;
struct DDS_DynamicData *sample = NULL;
struct DDS_DynamicDataProperty_t dynamic_data_props =
DDS_DynamicDataProperty_t_INITIALIZER;
struct RTI_RoutingServiceFileStreamReader *self =
(struct RTI_RoutingServiceFileStreamReader *) stream_reader;
/*
* We don't provide sample info in this adapter, which
* is an optional feature
*/
*info_list = NULL;
/*
* if the function read it is called because we have discovery data,
* the pointer or the stream reader that calls the
*/
if ((self->connection->input_discovery_reader == self)) {
int new_discovered_samples = 0;
fprintf(stdout,
"DiscoveryReader: called function read "
"for input discovery\n");
/*
* we keep track in the checking thread of the number of file names
* inside the discovery_data array, every new discovered file, we
* increase this counter (discovery_data_counter), and we keep track
* of the files we have already read, and created the relative streams,
* with the discovery_data_counter_read, subtracting one to another, we
* know how many new discovered files we have
*/
new_discovered_samples = self->discovery_data_counter
- self->discovery_data_counter_read;
/*
* we receive as a parameter the pointer to an array, and we need to
* allocate memory for it, first for the array, then for the single
* elements we put in it.
*/
*sample_list =
calloc(new_discovered_samples,
sizeof(struct RTI_RoutingServiceStreamInfo *));
if (*sample_list == NULL) {
RTI_RoutingServiceEnvironment_set_error(
env,
"Failure creating dynamic data sample in read "
"function for discovery");
return;
}
/*
* inside this loop we create the sample info structures,
* to describe the new stream to be created
*/
for (i = 0; i < new_discovered_samples; i++) {
struct RTI_RoutingServiceStreamInfo *streaminfo;
/*
* here we create the stream info type, passing as string name
* the name of the file taken from the discovery_data array
* filled by the checking thread.
*/
streaminfo = RTI_RoutingServiceStreamInfo_new_discovered(
self->discovery_data[self->discovery_data_counter_read],
"TextLine", /*typename*/
RTI_ROUTING_SERVICE_TYPE_REPRESENTATION_DYNAMIC_TYPE,
self->type_code);
if (streaminfo == NULL) {
continue;
}
(*sample_list)[*count] = streaminfo;
/*
* we increment the count of the sample info generated and returned
* inside the sample_list dynamic array.
*/
(*count)++;
/*
* we increment the index as we have already read that
* position of the array
*/
self->discovery_data_counter_read++;
}
} else {
fprintf(stdout, "StreamReader: called function read for data\n");
*sample_list =
calloc(self->samples_per_read, sizeof(DDS_DynamicData *));
if (*sample_list == NULL) {
RTI_RoutingServiceEnvironment_set_error(
env,
"Failure creating dynamic data "
"sample list in read function");
return;
}
/*
* Read as many times as samples_per_read
* (or less if we encounter the end of file)
*/
for (i = 0; i < self->samples_per_read && !feof(self->file); i++) {
/*
* Create a dynamic data sample for every buffer we read. We use
* the type we received when the stream reader was created
*/
sample = DDS_DynamicData_new(self->type_code, &dynamic_data_props);
if (sample == NULL) {
RTI_RoutingServiceEnvironment_set_error(
env,
"Failure creating dynamic data sample in read "
"function");
RTI_RoutingServiceFileStreamReader_freeDynamicDataArray(
(struct DDS_DynamicData **) *sample_list,
sample_counter);
*sample_list = NULL;
return;
}
/*
* Fill the dynamic data sample fields
* with the buffer read from the file.
*/
if (!RTI_RoutingServiceFileAdapter_read_sample(
sample,
self->file,
env)) {
/* No sample read */
DDS_DynamicData_delete(sample);
continue;
}
(*sample_list)[sample_counter++] = sample;
}
/* Set the count to the actual number of samples we have generated */
*count = sample_counter;
}
/*
* If there are no samples to read we free the memory allocated straight
* away as the routing service wouldn't call return_loan
*/
if (*count == 0) {
/* If we report zero samples we have to free the array now */
free(*sample_list);
*sample_list = NULL;
}
}
/*****************************************************************************/
void RTI_RoutingServiceFileStreamReader_return_loan(
RTI_RoutingServiceStreamReader stream_reader,
RTI_RoutingServiceSample *sample_list,
RTI_RoutingServiceSampleInfo *info_list,
int count,
RTI_RoutingServiceEnvironment *env)
{
/* Release all the memory allocated with read() */
int i;
struct RTI_RoutingServiceFileStreamReader *self =
(struct RTI_RoutingServiceFileStreamReader *) stream_reader;
fprintf(stdout, "StreamReader: called function return_loan\n");
/*
* In case this is called on the discovery data, we free the memory for
* sample info otherwise we delete the dynamic data.
*/
if (self->connection->input_discovery_reader == self) {
for (i = 0; i < count; i++) {
RTI_RoutingServiceStreamInfo_delete(sample_list[i]);
}
free(sample_list);
sample_list = NULL;
} else {
RTI_RoutingServiceFileStreamReader_freeDynamicDataArray(
(struct DDS_DynamicData **) sample_list,
count);
}
}
/* ========================================================================= */
/* */
/* Stream stream_writer methods */
/* */
/* ========================================================================= */
int RTI_RoutingServiceFileStreamWriter_write(
RTI_RoutingServiceStreamWriter stream_writer,
const RTI_RoutingServiceSample *sample_list,
const RTI_RoutingServiceSampleInfo *info_list,
int count,
RTI_RoutingServiceEnvironment *env)
{
struct DDS_DynamicData *sample = NULL;
int i = 0;
int written_sample = 0;
struct RTI_RoutingServiceFileStreamWriter *self =
(struct RTI_RoutingServiceFileStreamWriter *) stream_writer;
fprintf(stdout, "StreamWriter: called function write\n");
/* we explore the sample_list dynamic array we received */
for (i = 0; i < count; i++) {
/*we convert to dynamic data as we can read it*/
sample = (struct DDS_DynamicData *) sample_list[i];
/*
* the function RTI_RoutingServiceFileAdapter_write_sample will take
* care to write to the file with the name of the stream.
*/
if (!RTI_RoutingServiceFileAdapter_write_sample(
sample,
self->file,
env)) {
continue;
}
if (self->flush_enabled) {
fflush(self->file);
}
written_sample++;
}
return written_sample;
}
/* ========================================================================= */
/* */
/* Connection methods */
/* */
/* ========================================================================= */
RTI_RoutingServiceSession RTI_RoutingServiceFileConnection_create_session(
RTI_RoutingServiceConnection connection,
const struct RTI_RoutingServiceProperties *properties,
RTI_RoutingServiceEnvironment *env)
{
pthread_attr_t thread_attribute;
struct RTI_RoutingServiceFileConnection *file_connection =
(struct RTI_RoutingServiceFileConnection *) connection;
fprintf(stdout, "Connection: called function create_session\n");
if (file_connection->is_input == 1) {
pthread_attr_init(&thread_attribute);
pthread_attr_setdetachstate(&thread_attribute, PTHREAD_CREATE_JOINABLE);
if (pthread_create(
&file_connection->tid,
NULL,
RTI_RoutingServiceFileAdapter_discovery_thread,
(void *) file_connection)
< 0) {
RTI_RoutingServiceEnvironment_set_error(
env,
"Error creating thread for directory"
"scanning");
return NULL;
}
}
/*
* we don't actually use session, we return the Thread identifier
* as for us that is the concept of session. We start here the thread
* because we need to be sure that we already have the discovery reader
* ready, and in this case this happens, as the create session function
* gets called after the getInputDiscoveryReader
*/
return &file_connection->tid;
}
/*****************************************************************************/
void RTI_RoutingServiceFileConnection_delete_session(
RTI_RoutingServiceConnection connection,
RTI_RoutingServiceSession session,
RTI_RoutingServiceEnvironment *env)
{
struct RTI_RoutingServiceFileConnection *file_connection =
(struct RTI_RoutingServiceFileConnection *) connection;
/* we wait for the discovery thread to end */
if (file_connection->is_input) {
file_connection->is_running_enabled = 0;
pthread_join(file_connection->tid, NULL);
fprintf(stdout, "thread discovery ended\n");
}
fprintf(stdout, "Connection: called function delete_session\n");
/* We don't need sessions in this example */
}
/*****************************************************************************/
void RTI_RoutingServiceFileStreamReader_delete(
struct RTI_RoutingServiceFileStreamReader *self)
{
if (self->file != NULL) {
fclose(self->file);
}
free(self);
}
/*****************************************************************************/
RTI_RoutingServiceStreamReader
RTI_RoutingServiceFileConnection_create_stream_reader(
RTI_RoutingServiceConnection connection,
RTI_RoutingServiceSession session,
const struct RTI_RoutingServiceStreamInfo *stream_info,
const struct RTI_RoutingServiceProperties *properties,
const struct RTI_RoutingServiceStreamReaderListener *listener,
RTI_RoutingServiceEnvironment *env)
{
struct RTI_RoutingServiceFileStreamReader *stream_reader = NULL;
int read_period = 0;
int samples_per_read = 0;
int error = 0;
const char *read_period_property = NULL;
const char *samples_per_read_property = NULL;
char *filename = NULL;
FILE *file = NULL;
pthread_attr_t thread_attribute;
struct RTI_RoutingServiceFileConnection *file_connection =
(struct RTI_RoutingServiceFileConnection *) connection;
fprintf(stdout, "Connection: called function create_stream_reader\n");
/* Get the configuration properties in <route>/<input>/<property> */
read_period_property = RTI_RoutingServiceProperties_lookup_property(
properties,
FILE_ADAPTER_READ_PERIOD);
if (read_period_property == NULL) {
read_period = 1000;
} else {
read_period = atoi(read_period_property);
if (read_period <= 0) {
RTI_RoutingServiceEnvironment_set_error(
env,
"Error: read_period property value not valid");
return NULL;
}
}
samples_per_read_property = RTI_RoutingServiceProperties_lookup_property(
properties,
FILE_ADAPTER_SAMPLES_PER_READ);
if (samples_per_read_property == NULL) {
samples_per_read = 1;
} else {
samples_per_read = atoi(samples_per_read_property);
if (samples_per_read <= 0) {
RTI_RoutingServiceEnvironment_set_error(
env,
"ERROR:samples_per_read property value not valid");
return NULL;
}
}
/*
* now we create the string of the perfect size, the filename is formed by
* path that we already have by the connection, the / as separator between
* path and filename, and \0 as terminator. after that we create the string
* with sprintf
*/
filename =
malloc(strlen(file_connection->path) + 1
+ strlen(stream_info->stream_name) + 1);
if (filename == NULL) {
RTI_RoutingServiceEnvironment_set_error(
env,
"Error allocating memory for filename in write function");
return NULL;
}
sprintf(filename, "%s/%s", file_connection->path, stream_info->stream_name);
file = fopen(filename, "r");
if (file == NULL) {
RTI_RoutingServiceEnvironment_set_error(
env,
"Could not open file %s for read",
filename);
free(filename);
filename = NULL;
return NULL;
}
free(filename);
filename = NULL;
/* Check that the type representation is DDS dynamic type code */
if (stream_info->type_info.type_representation_kind
!= RTI_ROUTING_SERVICE_TYPE_REPRESENTATION_DYNAMIC_TYPE) {
RTI_RoutingServiceEnvironment_set_error(
env,
"Unsupported type format creating stream reader");
fclose(file);
return NULL;
}
/* Create the stream reader object */
stream_reader =
calloc(1, sizeof(struct RTI_RoutingServiceFileStreamReader));
if (stream_reader == NULL) {
RTI_RoutingServiceEnvironment_set_error(
env,
"Memory allocation error creating stream reader");
fclose(file);
return NULL;
}
stream_reader->connection = file_connection;
stream_reader->samples_per_read = samples_per_read;
stream_reader->read_period.sec = read_period / 1000;
stream_reader->read_period.nanosec = (read_period % 1000) * 1000000;
stream_reader->file = file;
stream_reader->listener = *listener;
stream_reader->type_code =
(struct DDS_TypeCode *) stream_info->type_info.type_representation;
stream_reader->is_running_enabled = 1;
stream_reader->info = stream_info;
pthread_attr_init(&thread_attribute);
pthread_attr_setdetachstate(&thread_attribute, PTHREAD_CREATE_JOINABLE);
error = pthread_create(
&stream_reader->tid,
&thread_attribute,
RTI_RoutingServiceFileStreamReader_run,
(void *) stream_reader);
pthread_attr_destroy(&thread_attribute);
if (error) {
RTI_RoutingServiceEnvironment_set_error(
env,
"Error creating thread for data_available notification");
fclose(stream_reader->file);
free(stream_reader);
return NULL;
}
return (RTI_RoutingServiceStreamReader) stream_reader;
}
/*****************************************************************************/
void RTI_RoutingServiceFileConnection_delete_stream_reader(
RTI_RoutingServiceConnection connection,
RTI_RoutingServiceStreamReader stream_reader,
RTI_RoutingServiceEnvironment *env)
{
struct RTI_RoutingServiceFileStreamReader *self =
(struct RTI_RoutingServiceFileStreamReader *) stream_reader;
fprintf(stdout,
"Connection: called function delete_stream_reader:%s\n",
self->info->stream_name);
self->is_running_enabled = 0;
pthread_join(self->tid, NULL);
RTI_RoutingServiceFileStreamReader_delete(self);
}
/*****************************************************************************/
RTI_RoutingServiceStreamWriter
RTI_RoutingServiceFileConnection_create_stream_writer(
RTI_RoutingServiceConnection connection,
RTI_RoutingServiceSession session,
const struct RTI_RoutingServiceStreamInfo *stream_info,
const struct RTI_RoutingServiceProperties *properties,
RTI_RoutingServiceEnvironment *env)
{
struct RTI_RoutingServiceFileStreamWriter *stream_writer = NULL;
const char *mode_property = NULL;
const char *flush_property = NULL;
char *filename = NULL;
FILE *file = NULL;
int flush_enabled = 0;
int error = 0;
struct RTI_RoutingServiceFileConnection *file_connection =
(struct RTI_RoutingServiceFileConnection *) connection;
fprintf(stdout, "Connection: called function create_stream_writer\n");
mode_property = RTI_RoutingServiceProperties_lookup_property(
properties,
FILE_ADAPTER_WRITE_MODE);
if (mode_property != NULL) {
if (strcmp(mode_property, "overwrite")
&& strcmp(mode_property, "append")
&& strcmp(mode_property, "keep")) {
RTI_RoutingServiceEnvironment_set_error(
env,
"Invalid value for %s (%s). "
"Allowed values: keep (default), overwrite, append",
FILE_ADAPTER_WRITE_MODE,
mode_property);
return NULL;
}
} else {
mode_property = "keep";
}
/* Get the configuration properties in <route>/<output>/<property> */
flush_property = RTI_RoutingServiceProperties_lookup_property(
properties,
FILE_ADAPTER_FLUSH);
if (flush_property != NULL) {
if (!strcmp(flush_property, "yes") || !strcmp(flush_property, "true")
|| !strcmp(flush_property, "1")) {
flush_enabled = 1;
}
}
/* we prepare the string with the whole path */
filename =
malloc(strlen(file_connection->path) + 1
+ strlen(stream_info->stream_name) + 1);
if (filename == NULL) {
RTI_RoutingServiceEnvironment_set_error(
env,
"Error allocating memory"
"for filename create_stream_writer");
}
sprintf(filename, "%s/%s", file_connection->path, stream_info->stream_name);
/*
* if property is keep we try to open the file in read mode, if the result
* is not null, means that the file exists, and we cannot overwrite (keep)
* so we don't create the stream writer
*/
if (!strcmp(mode_property, "keep")) {
file = fopen(filename, "r");
if (file != NULL) {
RTI_RoutingServiceEnvironment_set_error(
env,
"File exists and WriteMode is keep");
fclose(file);
free(filename);
return NULL;
}
}
/*
* if the first fopen returns null, means that the file doesn't exist, so
* we can open it for writing.
*/
file = fopen(filename, !strcmp(mode_property, "append") ? "a" : "w");
if (file == NULL) {
RTI_RoutingServiceEnvironment_set_error(
env,
"Could not open file for write: %s",
filename);
return NULL;
}
free(filename);
stream_writer =
calloc(1, sizeof(struct RTI_RoutingServiceFileStreamWriter));
if (stream_writer == NULL) {
RTI_RoutingServiceEnvironment_set_error(env, "Memory allocation error");
fclose(file);
return NULL;
}
stream_writer->file = file;
stream_writer->flush_enabled = flush_enabled;
stream_writer->info = stream_info;
return stream_writer;
}
/*****************************************************************************/
void RTI_RoutingServiceFileConnection_delete_stream_writer(
RTI_RoutingServiceConnection connection,
RTI_RoutingServiceStreamWriter stream_writer,
RTI_RoutingServiceEnvironment *env)
{
struct RTI_RoutingServiceFileStreamWriter *self =
(struct RTI_RoutingServiceFileStreamWriter *) stream_writer;
fclose(self->file);
fprintf(stdout,
"Connection: called function delete_stream_writer:%s\n",
self->info->stream_name);
free(self);
}
/* ========================================================================= */
/* */
/* AdapterPlugin methods */
/* */
/* ========================================================================= */
RTI_RoutingServiceConnection
RTI_RoutingServiceFileAdapterPlugin_create_connection(
struct RTI_RoutingServiceAdapterPlugin *adapter,
const char *routing_service_name,
const char *routing_service_group_name,
const struct RTI_RoutingServiceStreamReaderListener
*output_disc_listener,
const struct RTI_RoutingServiceStreamReaderListener
*input_disc_listener,
const struct RTI_RoutingServiceTypeInfo **registeredTypes,
int registeredTypeCount,
const struct RTI_RoutingServiceProperties *properties,
RTI_RoutingServiceEnvironment *env)
{
const char *is_input_connection = NULL;
const char *path = NULL;
const char *sleep_period = NULL;
struct RTI_RoutingServiceFileConnection *connection = NULL;
fprintf(stdout, "FileAdapter: called function create_connection\n");
connection = calloc(1, sizeof(struct RTI_RoutingServiceFileConnection));
if (connection == NULL) {
RTI_RoutingServiceEnvironment_set_error(
env,
"Error allocating memory"
"for connection");
return NULL;
}
sleep_period = RTI_RoutingServiceProperties_lookup_property(
properties,
FILE_ADAPTER_CONNECTION_DISCOVERY_THREAD_SLEEP_PERIOD);
if (sleep_period == NULL) {
connection->sleep_period = 5;
} else {
connection->sleep_period = atoi(sleep_period);
if (connection->sleep_period <= 0) {
RTI_RoutingServiceEnvironment_set_error(
env,
"Error creating "
"Connection: sleep_period value not valid");
}
}
path = RTI_RoutingServiceProperties_lookup_property(
properties,
FILE_ADAPTER_CONNECTION_FOLDER_PATH);
/*
* if the property is not found, then we are going to assign default value.
* As the default value is different depending of the connection, so we
* are going to assign the default value later, when we know which
* connection this is
*/
/* we recover properties from the xml file configuration */
is_input_connection = RTI_RoutingServiceProperties_lookup_property(
properties,
FILE_ADAPTER_CONNECTION_DIRECTION);
/*
* now we check if it is the connection that we use as
* input connection or not
*/
if ((is_input_connection != NULL)
&& !strcmp(
is_input_connection,
FILE_ADAPTER_CONNECTION_DIRECTION_INPUT)) {
fprintf(stdout, "Connection: This is an input connection\n");
connection->is_input = 1;
connection->is_running_enabled = 1;
/*
* we copy the listeners inside our connection,
* not the pointers, but the contained structure
*/
connection->input_discovery_listener = *input_disc_listener;
if (path == NULL) {
/* we assign the default value*/
strcpy(connection->path, ".");
} else {
strcpy(connection->path, path);
}
} else {
/*either it is output, or we assign default as output*/
fprintf(stdout, "Connection: This is an output connection\n");
connection->is_input = 0;
connection->is_running_enabled = 0;
if (path == NULL) {
/* we assign the default value*/
strcpy(connection->path, "./filewrite");
} else {
strcpy(connection->path, path);
}
}
return connection;
}
/*****************************************************************************/
void RTI_RoutingServiceFileAdapterPlugin_delete_connection(
struct RTI_RoutingServiceAdapterPlugin *adapter,
RTI_RoutingServiceConnection connection,
RTI_RoutingServiceEnvironment *env)
{
struct RTI_RoutingServiceFileConnection *file_connection =
(struct RTI_RoutingServiceFileConnection *) connection;
fprintf(stdout, "FileAdapter: called function delete connection\n");
if (file_connection->is_input) {
RTI_RoutingServiceFileAdapter_delete_type_code(
file_connection->input_discovery_reader->type_code);
}
/* delete input discovery stream reader */
if (file_connection->input_discovery_reader != NULL) {
RTI_RoutingServiceFileStreamReader_delete(
file_connection->input_discovery_reader);
}
free(file_connection);
}
/*****************************************************************************/
void RTI_RoutingServiceFileAdapterPlugin_delete(
struct RTI_RoutingServiceAdapterPlugin *adapter,
RTI_RoutingServiceEnvironment *env)
{
fprintf(stdout, "RoutingService: called function delete plugin\n");
free(adapter);
}
/*****************************************************************************/
/*
* Discovery Functions gets called just once for every connection
* That is why we delete them inside the
*/
RTI_RoutingServiceStreamReader RTI_RoutingService_getInputDiscoveryReader(
RTI_RoutingServiceConnection connection,
RTI_RoutingServiceEnvironment *env)
{
struct RTI_RoutingServiceFileStreamReader *stream_reader = NULL;
struct RTI_RoutingServiceFileConnection *file_connection =
(struct RTI_RoutingServiceFileConnection *) connection;
fprintf(stdout, "Connection: called function getInputDiscoveryReader\n");
if (file_connection->is_input) {
stream_reader =
calloc(1, sizeof(struct RTI_RoutingServiceFileStreamReader));
if (stream_reader == NULL) {
RTI_RoutingServiceEnvironment_set_error(
env,
"Failure creating discovery stream_reader");
return NULL;
}
/*
* Once created the stream_reader we should delete assign him to
* the connection, so once if we have some further problem, for
* instance even in the creation of the typecode, the connection has
* the reference to it to delete it
*/
file_connection->input_discovery_reader = stream_reader;
stream_reader->connection = file_connection;
stream_reader->discovery_data_counter_read = 0;
stream_reader->discovery_data_counter = 0;
stream_reader->type_code =
RTI_RoutingServiceFileAdapter_create_type_code();
if (stream_reader->type_code == NULL) {
RTI_RoutingServiceEnvironment_set_error(
env,
"Failure creating Typecode");
free(stream_reader);
stream_reader = NULL;
return NULL;
}
}
return (RTI_RoutingServiceStreamReader) stream_reader;
}
/* Entry point to the adapter plugin */
struct RTI_RoutingServiceAdapterPlugin *
RTI_RoutingServiceFileAdapterPlugin_create(
const struct RTI_RoutingServiceProperties *properties,
RTI_RoutingServiceEnvironment *env)
{
struct RTI_RoutingServiceFileAdapterPlugin *adapter = NULL;
struct RTI_RoutingServiceVersion adapterVersion = { 1, 0, 0, 0 };
fprintf(stdout, "RoutingService: called function create_plugin\n");
adapter = calloc(1, sizeof(struct RTI_RoutingServiceFileAdapterPlugin));
if (adapter == NULL) {
RTI_RoutingServiceEnvironment_set_error(
env,
"Memory allocation error creating plugin");
return NULL;
}
RTI_RoutingServiceAdapterPlugin_initialize(&adapter->_base);
adapter->_base.plugin_version = adapterVersion;
/* delete plugin function */
adapter->_base.adapter_plugin_delete =
RTI_RoutingServiceFileAdapterPlugin_delete;
/* connection functions */
adapter->_base.adapter_plugin_create_connection =
RTI_RoutingServiceFileAdapterPlugin_create_connection;
adapter->_base.adapter_plugin_delete_connection =
RTI_RoutingServiceFileAdapterPlugin_delete_connection;
adapter->_base.connection_create_stream_reader =
RTI_RoutingServiceFileConnection_create_stream_reader;
adapter->_base.connection_delete_stream_reader =
RTI_RoutingServiceFileConnection_delete_stream_reader;
adapter->_base.connection_create_stream_writer =
RTI_RoutingServiceFileConnection_create_stream_writer;
adapter->_base.connection_delete_stream_writer =
RTI_RoutingServiceFileConnection_delete_stream_writer;
/* session functions */
adapter->_base.connection_create_session =
RTI_RoutingServiceFileConnection_create_session;
adapter->_base.connection_delete_session =
RTI_RoutingServiceFileConnection_delete_session;
/* stream reader functions */
adapter->_base.stream_reader_read = RTI_RoutingServiceFileStreamReader_read;
adapter->_base.stream_reader_return_loan =
RTI_RoutingServiceFileStreamReader_return_loan;
/* stream writer functions */
adapter->_base.stream_writer_write =
RTI_RoutingServiceFileStreamWriter_write;
/* discovery functions */
adapter->_base.connection_get_input_stream_discovery_reader =
RTI_RoutingService_getInputDiscoveryReader;
return (struct RTI_RoutingServiceAdapterPlugin *) adapter;
}
#undef ROUTER_CURRENT_SUBMODULE
| c |
rticonnextdds-examples | data/projects/rticonnextdds-examples/routing_service/routing_service_file_adapter/c/directory_reading.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.
******************************************************************************/
#include "directory_reading.h"
#include <dirent.h>
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <unistd.h>
/*
* check if there is already a file with the same name inside the directory.
* This function takes as a parameter the array containing the names of the
* files previously discovered, the name of the file to check, and how many
* entries we have in the array
*/
int RTI_RoutingServiceFileAdapter_is_file_present(
char **array_files,
char *filename,
int index)
{
int i;
if (index == 0) {
return 0;
}
/*
* This is inefficient, it could be done with a more efficient algorithm,
* our focus now is on showing how RoutingService works
*/
for (i = 0; i < index; i++) {
if ((array_files[i] != NULL) && (!strcmp(filename, array_files[i]))) {
return 1;
}
}
return 0;
}
/*
* Inside this function we write the code that we want to be executed every time
* this thread discovers a new file in the scanned folder. For now we call
* on_data_available on the discovery listener and we print that a new
* file has been discovered
*/
void RTI_RoutingServiceFileAdapter_send_event(
char *fname,
struct RTI_RoutingServiceFileConnection *connection)
{
connection->input_discovery_listener.on_data_available(
connection->input_discovery_reader,
connection->input_discovery_listener.listener_data);
fprintf(stdout,
"checkingThread: new file discovered,"
" new stream will be created:%s\n",
fname);
}
/*
* The core execution of the thread that every five seconds checks
* if there are new files in the directory
*/
void *RTI_RoutingServiceFileAdapter_discovery_thread(void *arg)
{
int i, index = 0;
int count = 0;
char fname[MAX_NAME_SIZE];
char dirpath[MAX_NAME_SIZE]; /*when we use a struct stat element, we need
the full path to
pass as a parameter to
know if it is a
file or directory*/
char **array_files = NULL;
struct RTI_RoutingServiceFileConnection *connection =
(struct RTI_RoutingServiceFileConnection *) arg;
struct dirent *directory_info = NULL;
DIR *dir = NULL;
struct stat dir_stat; /*we use it for getting information about the file
we have already read*/
/*
* initialize the array that is going to contain the
* discovery information with the names of the files inside the
* directory. the array will be constantly increasing.
* We don't notify the Routing Service in case something goes wrong, we just
* print a warning on stderr when executing look at the warning if nothing
* happens in the Routing Service have look at the warning received.
*/
array_files = (char **) malloc(MAX_VEC_SIZE * sizeof(char *));
if (array_files == NULL) {
fprintf(stderr, "checkingThread: error allocating memory\n");
return NULL;
}
/*
* we assign to the discovery_data pointer inside the structure
* stream_reader, the pointer to array_files, which contains the list of the
* files inside the input folder
*/
connection->input_discovery_reader->discovery_data = array_files;
dir = opendir(connection->path);
if (dir == NULL) {
fprintf(stderr, "checkingThread: error opening directory\n");
}
/*every 5 seconds we check if there are new files in the directory*/
while (connection->is_running_enabled) {
sleep(connection->sleep_period);
while ((directory_info = readdir(dir)) != NULL) {
strcpy(fname, directory_info->d_name);
sprintf(dirpath, "%s/%s", connection->path, fname);
stat(dirpath, &dir_stat);
/*
* when we read a name inside the directory
* if it is not present inside the array array_files
* we put the name file in the next free position.
* We also check that it is a file and not a directory, as we
* don't copy directory to destination, just files, we use stat
* function for getting that informations
*/
if ((fname[0] != '.') && (!S_ISDIR(dir_stat.st_mode))) {
/* we don't consider hidden files and directories */
/* Then we check if the file is already in our array */
if (!RTI_RoutingServiceFileAdapter_is_file_present(
array_files,
fname,
index)) {
array_files[index] = (char *) malloc(MAX_NAME_SIZE);
if (array_files[index] == NULL) {
fprintf(stderr,
"checkingThread:"
"Error allocating memory for discovery array\n");
continue;
}
strcpy(array_files[index], fname);
/*
* in this example to take it easy we set a maximum
* number of file we can discover. That number is
* defined by the MAX_VEC_SIZE macro. If you prefer
* you can increase it.
*/
if (index < MAX_VEC_SIZE) {
RTI_RoutingServiceFileAdapter_send_event(
fname,
connection);
index++;
} else {
fprintf(stdout,
"checkingThread: You reached the "
"maximum number of files in the directory "
"you can have (>= %d)!\n RoutingService no longer "
"gets notified for creating new streams\n"
"For increasing number of files, increase "
"the size of MAX_VEC_FILE in the header "
"file ",
MAX_VEC_SIZE);
}
connection->input_discovery_reader->discovery_data_counter =
index;
}
}
}
/*
* now we reset the position of the directory stream
* to the beginning of the directory
*/
rewinddir(dir);
}
closedir(dir);
fprintf(stdout, "checkingThread: directory closed\n");
for (i = 0; i < index; i++) {
free(array_files[i]);
}
free(array_files);
pthread_exit(NULL);
return NULL; /*just because the compiler wants a return*/
}
| c |
rticonnextdds-examples | data/projects/rticonnextdds-examples/routing_service/routing_service_file_adapter/c/data_structures.h | /*******************************************************************************
(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.
******************************************************************************/
/*
* DataStructures.h
*/
#ifndef DATASTRUCTURES_H_
#define DATASTRUCTURES_H_
#include "directory_reading.h"
#define MAX_PAYLOAD_SIZE 1024
// Adapter plugin configuration property names
#define FILE_ADAPTER_CONNECTION_DIRECTION "Direction"
#define FILE_ADAPTER_CONNECTION_DIRECTION_INPUT "Input"
#define FILE_ADAPTER_CONNECTION_DIRECTION_OUTPUT "Output"
#define FILE_ADAPTER_CONNECTION_FOLDER_PATH "FolderPath"
#define FILE_ADAPTER_CONNECTION_DISCOVERY_THREAD_SLEEP_PERIOD "SleepPeriod"
#define FILE_ADAPTER_READ_PERIOD "ReadPeriod"
#define FILE_ADAPTER_SAMPLES_PER_READ "SamplesPerRead"
#define FILE_ADAPTER_WRITE_MODE "WriteMode"
#define FILE_ADAPTER_FLUSH "Flush"
/* ========================================================================= */
/* */
/* Data types */
/* */
/* ========================================================================= */
#include "ndds/ndds_c.h"
#include "routingservice/routingservice_adapter.h"
struct RTI_RoutingServiceFileAdapterPlugin {
struct RTI_RoutingServiceAdapterPlugin _base;
};
/*****************************************************************************/
struct RTI_RoutingServiceFileConnection {
/* the path of the directory to scan */
char path[256];
/*
* thread identifier and running parameter, is_running_enabled is 1 when the
* thread starts, when it turns to 0 the thread stops
*/
pthread_t tid;
int is_running_enabled;
int sleep_period;
/*pointer to input and output discovery reader*/
struct RTI_RoutingServiceFileStreamReader *input_discovery_reader;
/*input and output discovery listener (not pointer)*/
struct RTI_RoutingServiceStreamReaderListener input_discovery_listener;
/*
*this field is used to distinguish the connection,
*this basically if it is the connection 1 or 2
*/
int is_input;
};
/*****************************************************************************/
struct RTI_RoutingServiceFileStreamWriter {
/* streamInfo associated with the stream reader */
const struct RTI_RoutingServiceStreamInfo *info;
/* file where we are writing */
FILE *file;
/* properties flush for writing on the file */
int flush_enabled;
};
/*****************************************************************************/
struct RTI_RoutingServiceFileStreamReader {
/*
* listener associated to the stream reader, got as a parameter in the
* function create_stream_reader
*/
struct RTI_RoutingServiceStreamReaderListener listener;
/* streamInfo associated with the stream reader */
const struct RTI_RoutingServiceStreamInfo *info;
/* typecode associated with the stream */
struct DDS_TypeCode *type_code;
/*
* parameters for the execution of the thread that periodically
* notify on_data_available
*/
pthread_t tid;
int is_running_enabled;
/*parameters for opening the file and reading it */
struct DDS_Duration_t read_period;
int samples_per_read;
/*file we are reading */
FILE *file;
/*connection which the stream reader belongs to */
struct RTI_RoutingServiceFileConnection *connection;
/*the array of filenames present in the source directory*/
char **discovery_data;
/*
* counter for discovery_data array, indicate the last entry that has been read
*/
int discovery_data_counter_read;
/* counter for discovery data array, indicate the
* total number of entry (file names) inside the array*/
int discovery_data_counter;
/*
* The discovery_data array, is populated with the name of all files
* present inside the directory monitored, then every new file discovered
* gets on the top of the array, so, if there is something new, we realize
* it because there is something "after" the discovery data index, as it
* represent the last position of the array that we have read to build
* new stream.
*/
};
#endif /* DATASTRUCTURES_H_ */
| h |
rticonnextdds-examples | data/projects/rticonnextdds-examples/routing_service/routing_service_file_adapter/c/line_conversion.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.
******************************************************************************/
#include <ctype.h>
#include <stdio.h>
#include <string.h>
#include "data_structures.h"
#include "line_conversion.h"
/* ========================================================================= */
/* */
/* Read line */
/* */
/* ========================================================================= */
int RTI_RoutingServiceFileAdapter_read_sample(
struct DDS_DynamicData *sampleOut,
FILE *file,
RTI_RoutingServiceEnvironment *env)
{
DDS_Octet *ptr_payload = NULL;
struct DDS_OctetSeq payload_sequence;
long data_read = 0;
DDS_ReturnCode_t retCode = DDS_RETCODE_OK;
DDS_OctetSeq_initialize(&payload_sequence);
DDS_OctetSeq_ensure_length(
&payload_sequence,
MAX_PAYLOAD_SIZE,
MAX_PAYLOAD_SIZE);
ptr_payload = DDS_OctetSeq_get_contiguous_buffer(&payload_sequence);
data_read = fread(ptr_payload, 1, MAX_PAYLOAD_SIZE, file);
if (data_read == 0) {
if (ferror(file)) {
fprintf(stderr, "ERROR: reading file\n");
return 0;
}
}
DDS_OctetSeq_ensure_length(&payload_sequence, data_read, MAX_PAYLOAD_SIZE);
DDS_DynamicData_set_octet_seq(
sampleOut,
"value",
DDS_DYNAMIC_DATA_MEMBER_ID_UNSPECIFIED,
&payload_sequence);
if (retCode != DDS_RETCODE_OK) {
DDS_OctetSeq_finalize(&payload_sequence);
return 0;
}
DDS_OctetSeq_finalize(&payload_sequence);
return 1;
}
/* ========================================================================= */
/* */
/* Write line */
/* */
/* ========================================================================= */
int RTI_RoutingServiceFileAdapter_write_sample(
struct DDS_DynamicData *sample,
FILE *file,
RTI_RoutingServiceEnvironment *env)
{
DDS_ReturnCode_t retCode = DDS_RETCODE_OK;
struct DDS_DynamicDataMemberInfo info;
DDS_UnsignedLong ulongValue = 0;
DDS_Octet *ptr_payload = NULL;
struct DDS_OctetSeq payload;
DDS_Long sample_length = 0;
DDS_OctetSeq_initialize(&payload);
DDS_DynamicData_get_octet_seq(
sample,
&payload,
"value",
DDS_DYNAMIC_DATA_MEMBER_ID_UNSPECIFIED);
sample_length = DDS_OctetSeq_get_length(&payload);
ptr_payload = DDS_OctetSeq_get_contiguous_buffer(&payload);
/*it writes the retrieved string to the file*/
if (retCode == DDS_RETCODE_OK) {
if (fwrite(ptr_payload, 1, sample_length, file) < sample_length) {
return 0;
}
}
DDS_OctetSeq_finalize(&payload);
return 1;
}
| c |
rticonnextdds-examples | data/projects/rticonnextdds-examples/routing_service/routing_service_file_adapter/c/line_conversion.h | /*******************************************************************************
(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.
******************************************************************************/
/* ========================================================================= */
/* RTI Routing Service File Adapter */
/* ========================================================================= */
/* */
/* See LineConversion.c */
/* */
/* ========================================================================= */
#ifndef _lineconversion_h_
#define _lineconversion_h_
#include "ndds/ndds_c.h"
#include "routingservice/routingservice_adapter.h"
#include <stdio.h>
#include <string.h>
/* ========================================================================= */
/* */
/* Read line */
/* */
/* ========================================================================= */
int RTI_RoutingServiceFileAdapter_read_sample(
struct DDS_DynamicData *sampleOut,
FILE *file,
RTI_RoutingServiceEnvironment *env);
/* ========================================================================= */
/* */
/* Write line */
/* */
/* ========================================================================= */
int RTI_RoutingServiceFileAdapter_write_sample(
struct DDS_DynamicData *sample,
FILE *file,
RTI_RoutingServiceEnvironment *env);
#endif
| h |
rticonnextdds-examples | data/projects/rticonnextdds-examples/routing_service/routing_service_file_adapter/c/directory_reading.h | /*******************************************************************************
(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.
******************************************************************************/
/*
* DirectoryReading.h
*/
#ifndef DIRECTORYREADING_H_
#define DIRECTORYREADING_H_
#define MAX_VEC_SIZE 256
#define MAX_NAME_SIZE 256
#include "data_structures.h"
/*Definition of the function implemented in the file DirectoryReading.c*/
void *RTI_RoutingServiceFileAdapter_discovery_thread(void *arg);
#endif /* DIRECTORYREADING_H_ */
| h |
rticonnextdds-examples | data/projects/rticonnextdds-examples/routing_service/routing_service_struct_array_transf/cpp/SensorAttributesCollectionPublisher.cxx | /*
* (c) 2021 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 <dds/pub/ddspub.hpp>
#include <rti/util/util.hpp> // for sleep()
#include "SensorData.hpp"
void publisher_main(int domain_id, 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<SensorAttributesCollection> topic(
participant,
"Example SensorAttributesCollection");
// Create a DataWriter with default Qos (Publisher created in-line)
dds::pub::DataWriter<SensorAttributesCollection> writer(
dds::pub::Publisher(participant),
topic);
SensorAttributesCollection data;
for (int count = 0; count < sample_count || sample_count == 0; count++) {
for (size_t i = 0; i < data.sensor_array().size(); i++) {
data.sensor_array().at(i).id(count);
data.sensor_array().at(i).value((float) i / count);
data.sensor_array().at(i).is_active(true);
}
std::cout << "Writing SensorAttributesCollection, count " << count
<< std::endl;
writer.write(data);
std::cout << data << std::endl;
rti::util::sleep(dds::core::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;
}
// RTI Connext provides a finalize_participant_factory() method
// if you want to release memory used by the participant factory singleton.
// Uncomment the following line to release the singleton:
//
// dds::domain::DomainParticipant::finalize_participant_factory();
return 0;
}
| cxx |
rticonnextdds-examples | data/projects/rticonnextdds-examples/routing_service/routing_service_struct_array_transf/cpp/StructArrayTransformation.cxx | /*
* (c) 2021 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 "StructArrayTransformation.hpp"
#include "SensorData.hpp"
using dds::core::xtypes::DynamicData;
using dds::sub::SampleInfo;
/*
* @brief Maps each element of struct SensorData from
* SensorDataExample (see SensorDataExample.idl) into the separate
* arrays of TransformedSensorDataExample
* (see TransformedSensorDataExample.idl).
*
*/
DynamicData *StructArrayTransformation::convert_sample(
const DynamicData *input_sample)
{
SensorAttributesCollection native_collection =
rti::core::xtypes::convert<SensorAttributesCollection>(
*input_sample);
SensorData native_sensor_data;
/* Map elements from SensorAttributesCollection to SensorData */
for (int32_t count = 0; count < native_collection.sensor_array().size();
++count) {
native_sensor_data.id().at(count) =
native_collection.sensor_array().at(count).id();
native_sensor_data.value().at(count) =
native_collection.sensor_array().at(count).value();
native_sensor_data.is_active().at(count) =
native_collection.sensor_array().at(count).is_active();
}
return new DynamicData(rti::core::xtypes::convert(native_sensor_data));
}
void StructArrayTransformation::transform(
std::vector<DynamicData *> &output_sample_seq,
std::vector<SampleInfo *> &output_info_seq,
const std::vector<DynamicData *> &input_sample_seq,
const std::vector<SampleInfo *> &input_info_seq)
{
// resize the output sample and info sequences to hold as many samples
// as the input sequences
output_sample_seq.resize(input_sample_seq.size());
output_info_seq.resize(input_info_seq.size());
// Convert each individual input sample
for (size_t i = 0; i < input_sample_seq.size(); ++i) {
// convert data
output_sample_seq[i] = convert_sample(input_sample_seq[i]);
// copy info as is
output_info_seq[i] = new SampleInfo(*input_info_seq[i]);
}
}
void StructArrayTransformation::return_loan(
std::vector<DynamicData *> &sample_seq,
std::vector<SampleInfo *> &info_seq)
{
for (size_t i = 0; i < sample_seq.size(); ++i) {
delete sample_seq[i];
delete info_seq[i];
}
}
/*
* --- StructArrayTransformationPlugin ----------------------------------------
*/
StructArrayTransformationPlugin::StructArrayTransformationPlugin(
const rti::routing::PropertySet &)
{
// no configuration properties for this plug-in
}
rti::routing::transf::Transformation *
StructArrayTransformationPlugin::create_transformation(
const rti::routing::TypeInfo &,
const rti::routing::TypeInfo &,
const rti::routing::PropertySet &)
{
return new StructArrayTransformation();
}
void StructArrayTransformationPlugin::delete_transformation(
rti::routing::transf::Transformation *transformation)
{
delete transformation;
}
RTI_TRANSFORMATION_PLUGIN_CREATE_FUNCTION_DEF(StructArrayTransformationPlugin); | cxx |
rticonnextdds-examples | data/projects/rticonnextdds-examples/routing_service/routing_service_struct_array_transf/cpp/SensorDataSubscriber.cxx | /*
* (c) 2021 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>
#include "SensorData.hpp"
int subscriber_main(int domain_id, 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<SensorData> topic(participant, "Example SensorData");
// Create a DataReader with default Qos (Subscriber created in-line)
dds::sub::DataReader<SensorData> reader(
dds::sub::Subscriber(participant),
topic);
// Create a ReadCondition for any data on this reader and associate a
// handler
int count = 0;
dds::sub::cond::ReadCondition read_condition(
reader,
dds::sub::status::DataState::any(),
[&reader, &count]() {
// Take all samples
dds::sub::LoanedSamples<SensorData> samples = reader.take();
for (auto sample : samples) {
if (sample.info().valid()) {
count++;
std::cout << sample.data() << std::endl;
}
}
} // The LoanedSamples destructor returns the loan
);
// Create a WaitSet and attach the ReadCondition
dds::core::cond::WaitSet waitset;
waitset += read_condition;
while (count < sample_count || sample_count == 0) {
// Dispatch will call the handlers associated to the WaitSet conditions
// when they activate
std::cout << "SensorData subscriber sleeping for 4 sec..." << std::endl;
waitset.dispatch(dds::core::Duration(4)); // Wait up to 4s each time
}
return 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;
}
// RTI Connext provides a finalize_participant_factory() method
// if you want to release memory used by the participant factory singleton.
// Uncomment the following line to release the singleton:
//
// dds::domain::DomainParticipant::finalize_participant_factory();
return 0;
}
| cxx |
rticonnextdds-examples | data/projects/rticonnextdds-examples/routing_service/routing_service_struct_array_transf/cpp/StructArrayTransformation.hpp | /*
* (c) 2021 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.
*/
#ifndef STRUCT_ARRAY_TRANSF_HPP_
#define STRUCT_ARRAY_TRANSF_HPP_
#include <rti/routing/transf/TransformationPlugin.hpp>
/**
* @class StructArrayTransformation
*
* @brief implementation of the Transformation.
*
* This example preforms a transformation from type SensorAttributesCollection
* to SensorData (see SensorData.idl in source folder).
*/
class StructArrayTransformation
: public rti::routing::transf::DynamicDataTransformation {
public:
void transform(
std::vector<dds::core::xtypes::DynamicData *> &output_sample_seq,
std::vector<dds::sub::SampleInfo *> &output_info_seq,
const std::vector<dds::core::xtypes::DynamicData *>
&input_sample_seq,
const std::vector<dds::sub::SampleInfo *> &input_info_seq);
void return_loan(
std::vector<dds::core::xtypes::DynamicData *> &sample_seq,
std::vector<dds::sub::SampleInfo *> &info_seq);
private:
dds::core::xtypes::DynamicData *
convert_sample(const dds::core::xtypes::DynamicData *input_sample);
};
/**
* @class StructArrayTransformationPlugin
*
* @brief This class will be used by Routing Service to create and initialize
* our custom Transformation Subclass. In this example, that class is
* StructArrayTransformation.
*
* This class must use the macro
* RTI_TRANSFORMATION_PLUGIN_CREATE_FUNCTION_DECL(classname) in order to
* create a C wrapper function that will be the dynamic library entry point
* used by Routing Service.
*
*/
class StructArrayTransformationPlugin
: public rti::routing::transf::TransformationPlugin {
public:
StructArrayTransformationPlugin(
const rti::routing::PropertySet &properties);
/*
* @brief Creates an instance of StructArrayTransformation
*/
rti::routing::transf::Transformation *create_transformation(
const rti::routing::TypeInfo &input_type_info,
const rti::routing::TypeInfo &output_type_info,
const rti::routing::PropertySet &properties);
void delete_transformation(
rti::routing::transf::Transformation *transformation);
};
/**
* This macro defines a C-linkage symbol that can be used as create function
* for plug-in registration through XML.
*
* The generated symbol has the name:
*
* \code
* StructArrayTransformationPlugin_create_transformation_plugin
* \endcode
*/
RTI_TRANSFORMATION_PLUGIN_CREATE_FUNCTION_DECL(StructArrayTransformationPlugin)
#endif /* STRUCT_ARRAY_TRANSF_HPP_ */ | hpp |
rticonnextdds-examples | data/projects/rticonnextdds-examples/routing_service/routing_service_monitoring/c++11/RoutingServiceMonitoring_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.
*/
/*
* RoutingServiceMonitoring_subscriber.cxx
*
* A subscription example to the Routing Service Monitoring topics
*
* */
#include <algorithm>
#include <dds/dds.hpp>
#include <exception>
#include <iostream>
#include <map>
#include "RoutingServiceMonitoring.hpp"
/*
* Get the Configuration sample (rti/service/monitoring/config topic) from its
* Instance Handle. The reader for that topic is passed as a parameter. Also the
* Instance Handle.
* */
RTI::RoutingService::Monitoring::Config getConfig(
dds::sub::DataReader<RTI::RoutingService::Monitoring::Config>
&configReader,
const dds::core::InstanceHandle &handle)
{
// Get the configuration for an instance handle to use this information to
// complement what is received in the event or periodic topic
auto cSamples = configReader.select()
.instance(handle)
.state(dds::sub::status::DataState::any_data())
.read();
if (cSamples.length() == 0) {
std::stringstream errorMsg;
errorMsg << "The configuration for the instance handle " << handle
<< " has not being received";
throw std::runtime_error((errorMsg.str()));
}
// We are interested only in the last config sample received
return cSamples[cSamples.length() - 1].data();
}
/* Process the samples from the "rti/service/monitoring/periodic" topic. It
* shows in the console information related to the Domain Route, and Routing
* Service process.
* */
int processPeriodicData(
dds::sub::DataReader<RTI::RoutingService::Monitoring::Periodic>
&periodicReader,
dds::sub::DataReader<RTI::RoutingService::Monitoring::Config>
&configReader)
{
int count = 0;
try {
// Take all samples
dds::sub::LoanedSamples<RTI::RoutingService::Monitoring::Periodic>
samples = periodicReader.take();
for (const auto &sample : samples) {
if (sample.info().valid()) {
count++;
switch (sample.data().value()._d()) {
case (RTI::Service::Monitoring::ResourceKind::
ROUTING_DOMAIN_ROUTE): {
auto config = getConfig(
configReader,
sample.info().instance_handle());
std::cout << "Periodic data:\n\tDomain Route: ";
if (config.value()
.routing_domain_route()
.connections()
.value()
.size()
> 0) {
std::cout << " { ";
for (const auto &connection :
config.value()
.routing_domain_route()
.connections()
.value()) {
std::cout << connection.name() << ", ";
}
std::cout << " } " << std::endl;
}
std::cout << "\n\t\t in samples/s (mean): "
<< sample.data()
.value()
.routing_domain_route()
.in_samples_per_sec()
.value()
.publication_period_metrics()
.mean()
<< ", out samples/s (mean): "
<< sample.data()
.value()
.routing_domain_route()
.out_samples_per_sec()
.value()
.publication_period_metrics()
.mean()
<< std::endl;
break;
}
case (RTI::Service::Monitoring::ResourceKind::
ROUTING_SERVICE): {
auto config = getConfig(
configReader,
sample.info().instance_handle());
std::cout << "Periodic data:\n\t > Routing Service "
<< config.value()
.routing_service()
.application_name()
<< "\n\t\t cpu usage (mean): "
<< sample.data()
.value()
.routing_service()
.process()
.value()
.cpu_usage_percentage()
.value()
.publication_period_metrics()
.mean()
<< " %" << std::endl;
break;
}
default:
// Nothing to show
break;
}
}
}
} catch (const dds::core::Exception &e) {
std::cerr << "A Connext exception has been thrown: " << e.what()
<< std::endl;
} catch (const std::exception &e) {
std::cerr << "An std exception has been thrown: " << e.what()
<< std::endl;
}
return count;
// The LoanedSamples destructor returns the loan
}
/*
* Process the samples from the "rti/service/monitoring/event" topic. It shows
* in the console information related to the Domain Route, Inputs and Outputs
* (Routing Service).
* */
int processEventData(
dds::sub::DataReader<RTI::RoutingService::Monitoring::Event>
&eventReader,
dds::sub::DataReader<RTI::RoutingService::Monitoring::Config>
&configReader)
{
int count = 0;
try {
// Take all samples
dds::sub::LoanedSamples<RTI::RoutingService::Monitoring::Event>
samples = eventReader.take();
for (const auto &sample : samples) {
if (sample.info().valid()) {
count++;
switch (sample.data().value()._d()) {
case (RTI::Service::Monitoring::ResourceKind::
ROUTING_DOMAIN_ROUTE): {
std::cout << "\t > The Domain Route status is "
<< sample.data()
.value()
.routing_domain_route()
.state()
<< std::endl;
if (sample.data()
.value()
.routing_domain_route()
.connections()
.value()
.size()
> 0) {
std::cout << "\t\t Connections available: { ";
for (const auto &connection :
sample.data()
.value()
.routing_domain_route()
.connections()
.value()) {
std::cout << " Participant name: "
<< connection.name() << ", ";
}
std::cout << " } " << std::endl;
}
break;
}
case (RTI::Service::Monitoring::ResourceKind::ROUTING_INPUT): {
auto config = getConfig(
configReader,
sample.info().instance_handle());
if (config.value()._d()
== RTI::Service::Monitoring::ResourceKind::
ROUTING_INPUT) {
std::cout
<< "\t > The Input "
<< config.value().routing_input().resource_id()
<< std::endl;
std::cout
<< "\t\t status is "
<< sample.data().value().routing_input().state()
<< std::endl;
std::cout
<< "\t\t Topic: "
<< config.value().routing_input().stream_name()
<< ", Type: "
<< config.value()
.routing_input()
.registered_type_name()
<< ", Participant name: "
<< config.value()
.routing_input()
.connection_name()
<< std::endl;
}
break;
}
case (RTI::Service::Monitoring::ResourceKind::ROUTING_OUTPUT): {
auto config = getConfig(
configReader,
sample.info().instance_handle());
if (config.value()._d()
== RTI::Service::Monitoring::ResourceKind::
ROUTING_OUTPUT) {
std::cout
<< "\t > The Output "
<< config.value().routing_output().resource_id()
<< std::endl;
std::cout << "\t > status is "
<< sample.data()
.value()
.routing_output()
.state()
<< std::endl;
std::cout
<< "\t\t Topic: "
<< config.value().routing_output().stream_name()
<< ", Type: "
<< config.value()
.routing_output()
.registered_type_name()
<< ", Participant name: "
<< config.value()
.routing_output()
.connection_name()
<< std::endl;
}
break;
}
default:
// Nothing to show
break;
}
}
}
}
catch (const dds::core::Exception &e) {
std::cerr << "A Connext exception has been thrown: " << e.what()
<< std::endl;
} catch (const std::exception &e) {
std::cerr << "An std exception has been thrown: " << e.what()
<< std::endl;
}
return count;
// The LoanedSamples destructor returns the loan
}
int subscriberMain(int domain_id, int sample_count)
{
auto qosProvider = dds::core::QosProvider::Default();
// Create a DomainParticipant with default Qos
dds::domain::DomainParticipant participant(domain_id);
// Create the Topics -- and automatically register the type
dds::topic::Topic<RTI::RoutingService::Monitoring::Event> eventTopic(
participant,
"rti/service/monitoring/event");
dds::topic::Topic<RTI::RoutingService::Monitoring::Config> configTopic(
participant,
"rti/service/monitoring/config");
dds::topic::Topic<RTI::RoutingService::Monitoring::Periodic> periodicTopic(
participant,
"rti/service/monitoring/periodic");
// Create a DataReaders
dds::sub::Subscriber subscriber(
participant,
qosProvider.subscriber_qos("monitoring_Library::event_Profile"));
dds::sub::DataReader<RTI::RoutingService::Monitoring::Event> eventReader(
subscriber,
eventTopic,
qosProvider.datareader_qos("monitoring_Library::event_Profile"));
dds::sub::DataReader<RTI::RoutingService::Monitoring::Config> configReader(
subscriber,
configTopic,
qosProvider.datareader_qos("monitoring_Library::config_Profile"));
dds::sub::DataReader<RTI::RoutingService::Monitoring::Periodic>
periodicReader(
subscriber,
periodicTopic,
qosProvider.datareader_qos(
"monitoring_Library::periodic_Profile"));
int count = 0;
// Create a ReadCondition for any data on this reader
dds::sub::cond::ReadCondition eventReadCondition(
eventReader,
dds::sub::status::DataState::any(),
[&eventReader, &configReader, &count]() {
count += processEventData(eventReader, configReader);
});
dds::sub::cond::ReadCondition periodicReadCondition(
periodicReader,
dds::sub::status::DataState::any(),
[&periodicReader, &configReader, &count]() {
count += processPeriodicData(periodicReader, configReader);
});
// Create a WaitSet and attach the ReadCondition
dds::core::cond::WaitSet waitset;
waitset += eventReadCondition;
waitset += periodicReadCondition;
std::cout << "RTI::RoutingService::Monitoring::Event subscriber is running"
<< std::endl;
while (count < sample_count || sample_count == 0) {
// Dispatch calls the conditions WaitSet handlers when they activate
waitset.dispatch(dds::core::Duration(4));
}
return 1;
}
int main(int argc, char *argv[])
{
int domain_id = 0;
// infinite loop
int sample_count = 0;
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 {
subscriberMain(domain_id, sample_count);
} catch (const std::exception &ex) {
// This will catch DDS exceptions
std::cerr << "Exception in subscriberMain(): " << ex.what()
<< std::endl;
return -1;
}
/* RTI Connext provides a finalize_participant_factory() method
if you want to release memory used by the participant factory singleton.
Uncomment the following line to release the singleton:*/
// dds::domain::DomainParticipant::finalize_participant_factory();
return 0;
}
| cxx |
rticonnextdds-examples | data/projects/rticonnextdds-examples/waitsets/c++/waitsets_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.
******************************************************************************/
/* waitsets_publisher.cxx
A publication of data of type waitsets
This file is derived from code automatically generated by the rtiddsgen
command:
rtiddsgen -language C++ -example <arch> waitsets.idl
Example publication of type waitsets 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>/waitsets_subscriber <domain_id> <sample_count>
(3) Start the publication with the command
objs/<arch>/waitsets_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>/waitsets_publisher <domain_id> o
objs/<arch>/waitsets_subscriber <domain_id>
On Windows:
objs\<arch>\waitsets_publisher <domain_id>
objs\<arch>\waitsets_subscriber <domain_id>
modification history
------------ -------
*/
#include <stdio.h>
#include <stdlib.h>
#ifdef RTI_VX653
#include <vThreadsData.h>
#endif
#include "waitsets.h"
#include "waitsetsSupport.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;
waitsetsDataWriter * waitsets_writer = NULL;
waitsets *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 = waitsetsTypeSupport::get_type_name();
retcode = waitsetsTypeSupport::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 waitsets",
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;
}
/* 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 reduce the liveliness timeout period to trigger the
* StatusCondition DDS_LIVELINESS_CHANGED_STATUS */
/*
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.liveliness.lease_duration.sec = 1;
datawriter_qos.liveliness.lease_duration.nanosec = 0;
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;
}
*/
waitsets_writer = waitsetsDataWriter::narrow(writer);
if (waitsets_writer == NULL) {
printf("DataWriter narrow error\n");
publisher_shutdown(participant);
return -1;
}
/* Create data sample for writing */
instance = waitsetsTypeSupport::create_data();
if (instance == NULL) {
printf("waitsetsTypeSupport::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 = waitsets_writer->register_instance(*instance);
*/
/* Main loop */
for (count=0; (sample_count == 0) || (count < sample_count); ++count) {
printf("Writing waitsets, count %d\n", count);
/* Modify the data to be sent here */
instance->x = count;
retcode = waitsets_writer->write(*instance, instance_handle);
if (retcode != DDS_RETCODE_OK) {
printf("write error %d\n", retcode);
}
NDDSUtility::sleep(send_period);
}
/*
retcode = waitsets_writer->unregister_instance(
*instance, instance_handle);
if (retcode != DDS_RETCODE_OK) {
printf("unregister instance error %d\n", retcode);
}
*/
/* Delete data sample */
retcode = waitsetsTypeSupport::delete_data(instance);
if (retcode != DDS_RETCODE_OK) {
printf("waitsetsTypeSupport::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/waitsets/c++/waitsets_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.
******************************************************************************/
/* waitsets_subscriber.cxx
A subscription example
This file is derived from code automatically generated by the rtiddsgen
command:
rtiddsgen -language C++ -example <arch> waitsets.idl
Example subscription of type waitsets 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>/waitsets_subscriber <domain_id> <sample_count>
(3) Start the publication with the command
objs/<arch>/waitsets_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>/waitsets_publisher <domain_id>
objs/<arch>/waitsets_subscriber <domain_id>
On Windows:
objs\<arch>\waitsets_publisher <domain_id>
objs\<arch>\waitsets_subscriber <domain_id>
modification history
------------ -------
*/
#include <stdio.h>
#include <stdlib.h>
#ifdef RTI_VX653
#include <vThreadsData.h>
#endif
#include "waitsets.h"
#include "waitsetsSupport.h"
#include "ndds/ndds_cpp.h"
/* We don't need to use listeners as we are going to use Waitsets 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 = waitsetsTypeSupport::get_type_name();
retcode = waitsetsTypeSupport::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 waitsets",
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;
}
/* 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 reduce the liveliness timeout period to trigger the
* StatusCondition DDS_LIVELINESS_CHANGED_STATUS
*/
/*
DDS_DataReaderQos datareader_qos;
retcode = subscriber->get_default_datareader_qos(datareader_qos);
if (retcode != DDS_RETCODE_OK) {
printf("get_default_datareader_qos error\n");
return -1;
}
datareader_qos.liveliness.lease_duration.sec = 2;
datareader_qos.liveliness.lease_duration.nanosec = 0;
reader = subscriber->create_datareader(
topic, datareader_qos, NULL,
DDS_STATUS_MASK_NONE);
if (reader == NULL) {
printf("create_datareader error\n");
subscriber_shutdown(participant);
return -1;
}
*/
/* Create read condition
* ---------------------
* Note that the Read Conditions are dependent on both incoming
* data as well as sample state. Thus, this method has more
* overhead than adding a DDS_DATA_AVAILABLE_STATUS StatusCondition.
* We show it here purely for reference
*/
DDSReadCondition* read_condition = reader->create_readcondition(
DDS_NOT_READ_SAMPLE_STATE,
DDS_ANY_VIEW_STATE,
DDS_ANY_INSTANCE_STATE);
if (read_condition == NULL) {
printf("create_readcondition 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
* statuses we are interested in: DDS_SUBSCRIPTION_MATCHED_STATUS and
* DDS_LIVELINESS_CHANGED_STATUS.
*/
retcode = status_condition->set_enabled_statuses(
DDS_SUBSCRIPTION_MATCHED_STATUS | DDS_LIVELINESS_CHANGED_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 Read Conditions */
retcode = waitset->attach_condition(read_condition);
if (retcode != DDS_RETCODE_OK) {
printf("attach_condition error\n");
subscriber_shutdown(participant);
return -1;
}
/* 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 */
waitsetsDataReader *waitsets_reader = waitsetsDataReader::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) {
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);
for (int i = 0; i < active_conditions; ++i) {
/* Now we compare the current condition with the Status
* Conditions and the Read Conditions previously defined. If
* they match, we print the condition that was triggered.*/
/* 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 =
waitsets_reader->get_status_changes();
/* Liveliness changed */
if (triggeredmask & DDS_LIVELINESS_CHANGED_STATUS) {
DDS_LivelinessChangedStatus st;
waitsets_reader->get_liveliness_changed_status(st);
printf("Liveliness changed => Active writers = %d\n",
st.alive_count);
}
/* Subscription matched */
if (triggeredmask & DDS_SUBSCRIPTION_MATCHED_STATUS) {
DDS_SubscriptionMatchedStatus st;
waitsets_reader->get_subscription_matched_status(st);
printf("Subscription matched => Cumulative matches = %d\n",
st.total_count);
}
}
/* Compare with Read Conditions */
else if (active_conditions_seq[i] == read_condition) {
/* Current conditions match our conditions to read data, so
* we can read data just like we would do in any other
* example. */
waitsetsSeq data_seq;
DDS_SampleInfoSeq info_seq;
/* You may want to call take_w_condition() or
* read_w_condition() on the Data Reader. This way you will use
* the same status masks that were set on the Read Condition.
* This is just a suggestion, you can always use
* read() or take() like in any other example.
*/
retcode = DDS_RETCODE_OK;
while (retcode != DDS_RETCODE_NO_DATA) {
retcode = waitsets_reader->take_w_condition(
data_seq, info_seq, DDS_LENGTH_UNLIMITED,
read_condition);
for (int j = 0; j < data_seq.length(); ++j) {
if (!info_seq[j].valid_data) {
printf("Got metadata\n");
continue;
}
waitsetsTypeSupport::print_data(&data_seq[j]);
}
waitsets_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/waitsets/c/waitsets_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.
******************************************************************************/
/* waitsets_subscriber.c
A subscription example
This file is derived from code automatically generated by the rtiddsgen
command:
rtiddsgen -language C -example <arch> waitsets.idl
Example subscription of type waitsets 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>/waitsets_subscriber <domain_id> <sample_count>
(3) Start the publication with the command
objs/<arch>/waitsets_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>/waitsets_publisher <domain_id>
objs/<arch>/waitsets_subscriber <domain_id>
On Windows systems:
objs\<arch>\waitsets_publisher <domain_id>
objs\<arch>\waitsets_subscriber <domain_id>
modification history
------------ -------
*/
#include <stdio.h>
#include <stdlib.h>
#include "ndds/ndds_c.h"
#include "waitsets.h"
#include "waitsetsSupport.h"
/* We don't need to use listeners as we are going to use Waitsets and Conditions
* so we have removed the auto generated code for listeners here */
/* 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;
DDS_ReturnCode_t retcode;
const char *type_name = NULL;
int count = 0;
DDS_ReadCondition *read_condition;
DDS_StatusCondition *status_condition;
DDS_WaitSet *waitset = NULL;
waitsetsDataReader *waitsets_reader = NULL;
struct DDS_Duration_t wait_timeout = {1,500000000};
/* To change the DataReader's QoS programmatically you will need to
* declare and initialize datareader_qos here. */
struct DDS_DataReaderQos datareader_qos = DDS_DataReaderQos_INITIALIZER;
struct waitsetsSeq data_seq = DDS_SEQUENCE_INITIALIZER;
struct DDS_SampleInfoSeq info_seq = DDS_SEQUENCE_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 = waitsetsTypeSupport_get_type_name();
retcode = waitsetsTypeSupport_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 waitsets",
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;
}
/* 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 reduce the liveliness timeout period to trigger the
* StatusCondition DDS_LIVELINESS_CHANGED_STATUS
*/
/*
retcode = DDS_Subscriber_get_default_datareader_qos(subscriber,
&datareader_qos);
if (retcode != DDS_RETCODE_OK) {
printf("get_default_datareader_qos error\n");
return -1;
}
datareader_qos.liveliness.lease_duration.sec = 2;
datareader_qos.liveliness.lease_duration.nanosec = 0;
reader = DDS_Subscriber_create_datareader(
subscriber, DDS_Topic_as_topicdescription(topic),
&datareader_qos, NULL, DDS_STATUS_MASK_NONE);
if (reader == NULL) {
printf("create_datareader error\n");
subscriber_shutdown(participant);
return -1;
}
*/
/* Create read condition
* ---------------------
* Note that the Read Conditions are dependent on both incoming
* data as well as sample state. Thus, this method has more
* overhead than adding a DDS_DATA_AVAILABLE_STATUS StatusCondition.
* We show it here purely for reference
*/
read_condition = DDS_DataReader_create_readcondition(
reader,
DDS_NOT_READ_SAMPLE_STATE,
DDS_ANY_VIEW_STATE,
DDS_ANY_INSTANCE_STATE);
if (read_condition == NULL) {
printf("create_readcondition 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.
*/
status_condition = DDS_Entity_get_statuscondition((DDS_Entity*) reader);
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
* statuses we are interested in: DDS_SUBSCRIPTION_MATCHED_STATUS and
* DDS_LIVELINESS_CHANGED_STATUS.
*/
retcode = DDS_StatusCondition_set_enabled_statuses(
status_condition,
DDS_SUBSCRIPTION_MATCHED_STATUS | DDS_LIVELINESS_CHANGED_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.
*/
waitset = DDS_WaitSet_new();
if (waitset == NULL) {
printf("create waitset error\n");
subscriber_shutdown(participant);
return -1;
}
/* Attach Read Conditions */
retcode = DDS_WaitSet_attach_condition(waitset,
(DDS_Condition*)read_condition);
if (retcode != DDS_RETCODE_OK) {
printf("attach_condition error\n");
subscriber_shutdown(participant);
return -1;
}
/* Attach Status Conditions */
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;
}
/* Narrow the reader into your specific data type */
waitsets_reader = waitsetsDataReader_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_seq =
DDS_SEQUENCE_INITIALIZER;
int i, j, active_conditions;
/* wait() blocks execution of the thread until one or more attached
* Conditions become true, or until a user-specified timeout expires.
*/
retcode = DDS_WaitSet_wait(
waitset, /* waitset */
&active_conditions_seq, /* active conditions sequence */
&wait_timeout); /* 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", retcode);
break;
}
/* Get the number of active conditions */
active_conditions =
DDS_ConditionSeq_get_length(&active_conditions_seq);
printf("Got %d active conditions\n", active_conditions);
for (i = 0; i<active_conditions; ++i) {
/* Get the current condition and compare it with the Status
* Conditions and the Read Conditions previously defined. If
* they match, we print the condition that was triggered.*/
DDS_Condition * current_condition =
DDS_ConditionSeq_get(&active_conditions_seq, i);
/* Compare with Status Conditions */
if (current_condition == (DDS_Condition *) status_condition) {
DDS_StatusMask triggeredmask;
/* Get the status changes so we can check which status
* condition triggered. */
triggeredmask =
DDS_Entity_get_status_changes(
(DDS_Entity*)waitsets_reader);
/* Liveliness changed */
if (triggeredmask & DDS_LIVELINESS_CHANGED_STATUS) {
struct DDS_LivelinessChangedStatus st;
DDS_DataReader_get_liveliness_changed_status(
(DDS_DataReader*)waitsets_reader, &st);
printf("Liveliness changed => Active writers = %d\n",
st.alive_count);
}
/* Subscription matched */
if (triggeredmask & DDS_SUBSCRIPTION_MATCHED_STATUS) {
struct DDS_SubscriptionMatchedStatus st;
DDS_DataReader_get_subscription_matched_status(
(DDS_DataReader*)waitsets_reader, &st);
printf("Subscription matched => Cumulative matches = %d\n",
st.total_count);
}
}
/* Compare with Read Conditions */
else if (current_condition == (DDS_Condition *) read_condition) {
printf("Read condition\n");
/* Current conditions match our conditions to read data, so
* we can read data just like we would do in any other
* example. We use data_seq and info_seq to this task
* defined at start.
*/
/* You may want to call take_w_condition() or
* read_w_condition() on the Data Reader. This way you will use
* the same status masks that were set on the Read Condition.
* This is just a suggestion, you can always use
* read() or take() like in any other example.
*/
retcode = DDS_RETCODE_OK;
while (retcode != DDS_RETCODE_NO_DATA) {
retcode = waitsetsDataReader_take_w_condition(
waitsets_reader, &data_seq, &info_seq,
DDS_LENGTH_UNLIMITED, read_condition);
for (j = 0; j < waitsetsSeq_get_length(&data_seq); ++j) {
if (!DDS_SampleInfoSeq_get_reference(
&info_seq, j)->valid_data) {
printf("Got metadata\n");
continue;
}
waitsetsTypeSupport_print_data(
waitsetsSeq_get_reference(&data_seq, j));
}
waitsetsDataReader_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/waitsets/c/waitsets_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.
******************************************************************************/
/* waitsets_publisher.c
A publication of data of type waitsets
This file is derived from code automatically generated by the rtiddsgen
command:
rtiddsgen -language C -example <arch> waitsets.idl
Example publication of type waitsets 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>/waitsets_subscriber <domain_id> <sample_count>
(3) Start the publication with the command
objs/<arch>/waitsets_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>/waitsets_publisher <domain_id>
objs/<arch>/waitsets_subscriber <domain_id>
On Windows:
objs\<arch>\waitsets_publisher <domain_id>
objs\<arch>\waitsets_subscriber <domain_id>
modification history
------------ -------
*/
#include <stdio.h>
#include <stdlib.h>
#include "ndds/ndds_c.h"
#include "waitsets.h"
#include "waitsetsSupport.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;
waitsetsDataWriter *waitsets_writer = NULL;
waitsets *instance = NULL;
DDS_ReturnCode_t retcode;
DDS_InstanceHandle_t instance_handle = DDS_HANDLE_NIL;
const char *type_name = NULL;
int count = 0;
/* We publish a new sample every second */
struct DDS_Duration_t send_period = {1,0};
/* To change the DataWriter's QoS programmatically you will need to
* declare and initialize datawriter_qos here. */
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 = waitsetsTypeSupport_get_type_name();
retcode = waitsetsTypeSupport_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 waitsets",
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, 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 reduce the liveliness timeout period to trigger the
* StatusCondition DDS_LIVELINESS_CHANGED_STATUS */
/*
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.liveliness.lease_duration.sec = 1;
datawriter_qos.liveliness.lease_duration.nanosec = 0;
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;
}
*/
waitsets_writer = waitsetsDataWriter_narrow(writer);
if (waitsets_writer == NULL) {
printf("DataWriter narrow error\n");
publisher_shutdown(participant);
return -1;
}
/* Create data sample for writing */
instance = waitsetsTypeSupport_create_data_ex(DDS_BOOLEAN_TRUE);
if (instance == NULL) {
printf("waitsetsTypeSupport_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 = waitsetsDataWriter_register_instance(
waitsets_writer, instance);
*/
/* Main loop */
for (count=0; (sample_count == 0) || (count < sample_count); ++count) {
printf("Writing waitsets, count %d\n", count);
/* Modify the data to be written here */
instance->x = count;
/* Write data */
retcode = waitsetsDataWriter_write(
waitsets_writer, instance, &instance_handle);
if (retcode != DDS_RETCODE_OK) {
printf("write error %d\n", retcode);
}
NDDS_Utility_sleep(&send_period);
}
/*
retcode = waitsetsDataWriter_unregister_instance(
waitsets_writer, instance, &instance_handle);
if (retcode != DDS_RETCODE_OK) {
printf("unregister instance error %d\n", retcode);
}
*/
/* Delete data sample */
retcode = waitsetsTypeSupport_delete_data_ex(instance, DDS_BOOLEAN_TRUE);
if (retcode != DDS_RETCODE_OK) {
printf("waitsetsTypeSupport_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/waitsets/c++03/waitsets_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 <cstdlib>
#include <dds/dds.hpp>
#include "waitsets.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<waitsets> topic(participant, "Example waitsets");
// Retrieve the default DataWriter QoS, from USER_QOS_PROFILES.xml
DataWriterQos writer_qos = QosProvider::Default().datawriter_qos();
// If you want to change the DataWriter QoS programmatically rather
// than using the XML file, you will need to uncomment these lines.
// writer_qos << Reliability::Reliable()
// << History::KeepAll()
// << Liveliness::Automatic().lease_duration(Duration(1));
// Create a DataWriter.
DataWriter<waitsets> writer(Publisher(participant), topic, writer_qos);
// Create a data sample for writing.
waitsets instance;
// Main loop.
for (int count = 0; (sample_count == 0) || (count < sample_count); count++){
std::cout << "Writing waitsets, count " << count << std::endl;
// Modify sample and send the sample.
instance.x(count);
writer.write(instance);
// Send a new 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 (std::exception ex) {
std::cout << "Exception caught: " << ex.what() << std::endl;
return -1;
}
return 0;
}
| cxx |
rticonnextdds-examples | data/projects/rticonnextdds-examples/waitsets/c++03/waitsets_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 <cstdlib>
#include <dds/dds.hpp>
#include "waitsets.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::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<waitsets> topic(participant, "Example waitsets");
// Retrieve the default DataReader QoS, from USER_QOS_PROFILES.xml
DataReaderQos reader_qos = QosProvider::Default().datareader_qos();
// If you want to change the DataWriter QoS programmatically rather
// than using the XML file, you will need to uncomment these lines.
// reader_qos << Reliability::Reliable()
// << History::KeepAll()
// << Liveliness::Automatic().lease_duration(Duration(2));
// Create a DataReader.
DataReader<waitsets> reader(Subscriber(participant), topic, reader_qos);
// Create a Read Condition.
// Note that the Read Conditions are dependent on both incoming data as
// well as sample state.
ReadCondition read_cond(
reader, DataState(
SampleState::not_read(),
ViewState::any(),
InstanceState::any()));
// 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.
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::subscription_matched() | StatusMask::liveliness_changed());
// Create and attach conditions to the WaitSet
// Finally, we create the WaitSet and attach both the Read Conditions and
// the Status Condition to it. We can use the operator '+=' or the method
// 'attach_condition'.
WaitSet waitset;
waitset += read_cond;
waitset.attach_condition(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.
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;
for (std::vector<int>::size_type i=0; i<active_conditions.size(); i++) {
// Now we compare the current condition with the Status Conditions
// and the Read Conditions previously defined. If they match, we
// print the condition that was triggered.
if (active_conditions[i] == status_condition) {
// Get the status changes so we can check witch status condition
// triggered.
StatusMask status_mask = reader.status_changes();
// Liveliness changed
if ((status_mask & StatusMask::liveliness_changed()).any()) {
LivelinessChangedStatus st =
reader.liveliness_changed_status();
std::cout << "Liveliness changed => Active writers = "
<< st.alive_count() << std::endl;
}
// Subscription matched
if ((status_mask & StatusMask::subscription_matched()).any()) {
SubscriptionMatchedStatus st =
reader.subscription_matched_status();
std::cout << "Subscription matched => Cumulative matches = "
<< st.total_count() << std::endl;
}
}
else if (active_conditions[i] == read_cond) {
// Current conditions match our conditions to read data, so we
// can read data just like we would do in any other example.
LoanedSamples<waitsets> samples = reader.take();
for (LoanedSamples<waitsets>::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/using_sequences/c++/sequences_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.
******************************************************************************/
/* sequences_publisher.cxx
A publication of data of type sequences
This file is derived from code automatically generated by the rtiddsgen
command:
rtiddsgen -language C++ -example <arch> sequences.idl
Example publication of type sequences 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>/sequences_subscriber <domain_id> <sample_count>
(3) Start the publication with the command
objs/<arch>/sequences_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>/sequences_publisher <domain_id> o
objs/<arch>/sequences_subscriber <domain_id>
On Windows:
objs\<arch>\sequences_publisher <domain_id>
objs\<arch>\sequences_subscriber <domain_id>
modification history
------------ -------
*/
#include <stdio.h>
#include <stdlib.h>
#ifdef RTI_VX653
#include <vThreadsData.h>
#endif
#include "sequences.h"
#include "sequencesSupport.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;
sequencesDataWriter * sequences_writer = NULL;
/* We define two instances to illustrate the different memory use of
* sequences: owner_instance and borrower_instance. */
sequences *owner_instance = NULL;
sequences *borrower_instance = NULL;
DDS_InstanceHandle_t owner_instance_handle = DDS_HANDLE_NIL;
DDS_InstanceHandle_t borrower_instance_handle = DDS_HANDLE_NIL;
DDS_ReturnCode_t retcode;
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 = sequencesTypeSupport::get_type_name();
retcode = sequencesTypeSupport::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 sequences",
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;
}
sequences_writer = sequencesDataWriter::narrow(writer);
if (sequences_writer == NULL) {
printf("DataWriter narrow error\n");
publisher_shutdown(participant);
return -1;
}
/* Here we define two instances: owner_instance and borrower_instance. */
/* owner_instance.data uses its own memory, as by default, a sequence
* you create owns its memory unless you explicitly loan memory of your
* own to it.
*/
owner_instance = sequencesTypeSupport::create_data();
if (owner_instance == NULL) {
printf("sequencesTypeSupport::create_data error\n");
publisher_shutdown(participant);
return -1;
}
/* borrower_instance.data "borrows" memory from a buffer of shorts,
* previously allocated, using DDS_ShortSeq_loan_contiguous(). */
borrower_instance = sequencesTypeSupport::create_data();
if (borrower_instance == NULL) {
printf("sequencesTypeSupport::create_data error\n");
publisher_shutdown(participant);
return -1;
}
/* If we want borrower_instance.data to loan a buffer of shorts, first we
* have to allocate the buffer. Here we allocate a buffer of
* MAX_SEQUENCE_LEN. */
short * short_buffer = new short[MAX_SEQUENCE_LEN];
/* Before calling loan_contiguous(), we need to set Seq.maximum to
* 0, i.e., the sequence won't have memory allocated to it. */
borrower_instance->data.maximum(0);
/* Now that the sequence doesn't have memory allocated to it, we can use
* loan_contiguous() to loan short_buffer to borrower_instance.
* We set the allocated number of elements to MAX_SEQUENCE_LEN, the size of
* the buffer and the maximum size of the sequence as we declared in the
* IDL. */
bool return_result = borrower_instance->data.loan_contiguous(
short_buffer, // Pointer to the sequence
0, // Initial Length
MAX_SEQUENCE_LEN // New maximum
);
if (return_result != DDS_BOOLEAN_TRUE) {
printf("loan_contiguous error\n");
publisher_shutdown(participant);
return -1;
}
/* Before starting to publish samples, set the instance id of each
* instance*/
strcpy(owner_instance->id, "owner_instance");
strcpy(borrower_instance->id, "borrower_instance");
/* To illustrate the use of the sequences, in the main loop we set a
* new sequence length every iteration to the sequences contained in
* both instances (instance->data). The sequence length value cycles between
* 0 and MAX_SEQUENCE_LEN. We assign a random number between 0 and 100 to
* each sequence's elements. */
for (count=0; (sample_count == 0) || (count < sample_count); ++count) {
/* We set a different sequence_length for both instances every
* iteration. sequence_length is based on the value of count and
* its value cycles between the values of 1 and MAX_SEQUENCE_LEN. */
short sequence_length = (count % MAX_SEQUENCE_LEN) + 1;
printf("Writing sequences, count %d...\n",
count);
owner_instance->count = count;
borrower_instance->count = count;
/* Here we set the new length of each sequence */
owner_instance->data.length(sequence_length);
borrower_instance->data.length(sequence_length);
/* Now that the sequences have a new length, we assign a
* random number between 0 and 100 to each element of
* owner_instance->data and borrower_instance->data. */
for (int i = 0; i < sequence_length; ++i) {
owner_instance->data[i] =
(short) (rand()/(RAND_MAX/100));
borrower_instance->data[i] =
(short) (rand()/(RAND_MAX/100));
}
/* Both sequences have the same length, so we only print the length
* of one of them. */
printf("Instances length = %d\n",
owner_instance->data.length()
);
/* Write for each instance */
retcode = sequences_writer->write(*owner_instance,
owner_instance_handle);
if (retcode != DDS_RETCODE_OK) {
printf("write error %d\n", retcode);
}
retcode = sequences_writer->write(*borrower_instance,
borrower_instance_handle);
if (retcode != DDS_RETCODE_OK) {
printf("write error %d\n", retcode);
}
NDDSUtility::sleep(send_period);
}
/* Once we are done with the sequence, we unloan and free the buffer. Make
* sure you don't call delete before unloan(); the next time you
* access the sequence, you will be accessing freed memory. */
return_result = borrower_instance->data.unloan();
if (return_result != DDS_BOOLEAN_TRUE) {
printf("unloan error \n");
}
delete short_buffer;
/* Delete data samples */
retcode = sequencesTypeSupport::delete_data(owner_instance);
if (retcode != DDS_RETCODE_OK) {
printf("sequencesTypeSupport::delete_data error %d\n", retcode);
}
retcode = sequencesTypeSupport::delete_data(borrower_instance);
if (retcode != DDS_RETCODE_OK) {
printf("sequencesTypeSupport::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/using_sequences/c++/sequences_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.
******************************************************************************/
/* sequences_subscriber.cxx
A subscription example
This file is derived from code automatically generated by the rtiddsgen
command:
rtiddsgen -language C++ -example <arch> sequences.idl
Example subscription of type sequences 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>/sequences_subscriber <domain_id> <sample_count>
(3) Start the publication with the command
objs/<arch>/sequences_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>/sequences_publisher <domain_id>
objs/<arch>/sequences_subscriber <domain_id>
On Windows:
objs\<arch>\sequences_publisher <domain_id>
objs\<arch>\sequences_subscriber <domain_id>
modification history
------------ -------
*/
#include <stdio.h>
#include <stdlib.h>
#ifdef RTI_VX653
#include <vThreadsData.h>
#endif
#include "sequences.h"
#include "sequencesSupport.h"
#include "ndds/ndds_cpp.h"
class sequencesListener : 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 sequencesListener::on_data_available(DDSDataReader* reader)
{
sequencesDataReader *sequences_reader = NULL;
sequencesSeq data_seq;
DDS_SampleInfoSeq info_seq;
DDS_ReturnCode_t retcode;
int i;
sequences_reader = sequencesDataReader::narrow(reader);
if (sequences_reader == NULL) {
printf("DataReader narrow error\n");
return;
}
retcode = sequences_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) {
sequencesTypeSupport::print_data(&data_seq[i]);
}
}
retcode = sequences_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;
sequencesListener *reader_listener = NULL;
DDSDataReader *reader = NULL;
DDS_ReturnCode_t retcode;
const char *type_name = NULL;
int count = 0;
DDS_Duration_t receive_period = {4,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 = sequencesTypeSupport::get_type_name();
retcode = sequencesTypeSupport::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 sequences",
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 sequencesListener();
/* 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("sequences 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/using_sequences/c/sequences_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.
******************************************************************************/
/* sequences_publisher.c
A publication of data of type sequences
This file is derived from code automatically generated by the rtiddsgen
command:
rtiddsgen -language C -example <arch> sequences.idl
Example publication of type sequences 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>/sequences_subscriber <domain_id> <sample_count>
(3) Start the publication with the command
objs/<arch>/sequences_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>/sequences_publisher <domain_id>
objs/<arch>/sequences_subscriber <domain_id>
On Windows:
objs\<arch>\sequences_publisher <domain_id>
objs\<arch>\sequences_subscriber <domain_id>
modification history
------------ -------
*/
#include <stdio.h>
#include <stdlib.h>
#include "ndds/ndds_c.h"
#include "sequences.h"
#include "sequencesSupport.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;
sequencesDataWriter *sequences_writer = NULL;
/* We define two instances to illustrate the different memory use of
* sequences: owner_instance and borrower_instance. */
sequences *owner_instance = NULL;
sequences *borrower_instance = NULL;
DDS_InstanceHandle_t owner_instance_handle = DDS_HANDLE_NIL;
DDS_InstanceHandle_t borrower_instance_handle = DDS_HANDLE_NIL;
DDS_ReturnCode_t retcode;
const char *type_name = NULL;
int i, count = 0;
/* Send a new sample every second */
struct DDS_Duration_t send_period = {1,0};
/* Buffer of shorts that borrower_instance loans */
short *short_buffer = NULL;
/* 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 = sequencesTypeSupport_get_type_name();
retcode = sequencesTypeSupport_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 sequences",
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;
}
sequences_writer = sequencesDataWriter_narrow(writer);
if (sequences_writer == NULL) {
printf("DataWriter narrow error\n");
publisher_shutdown(participant);
return -1;
}
/* Here we define two instances: owner_instance and borrower_instance. */
/* owner_instance.data uses its own memory, as by default, a sequence
* you create owns its memory unless you explicitly loan memory of your
* own to it. */
owner_instance = sequencesTypeSupport_create_data_ex(DDS_BOOLEAN_TRUE);
if (owner_instance == NULL) {
printf("sequencesTypeSupport_create_data error\n");
publisher_shutdown(participant);
return -1;
}
/* borrower_instance.data "borrows" memory from a buffer of shorts,
* previously allocated, using DDS_ShortSeq_loan_contiguous(). */
borrower_instance = sequencesTypeSupport_create_data_ex(DDS_BOOLEAN_TRUE);
if (borrower_instance == NULL) {
printf("sequencesTypeSupport_create_data error\n");
publisher_shutdown(participant);
return -1;
}
/* If we want borrower_instance.data to loan a buffer of shorts, first we
* have to allocate the buffer. Here we allocate a buffer of
* MAX_SEQUENCE_LEN. */
short_buffer = (short *) malloc(MAX_SEQUENCE_LEN * sizeof(short));
if (short_buffer == NULL) {
printf("short_buffer malloc error\n");
publisher_shutdown(participant);
return -1;
}
/* Before calling DDS_ShortSeq_loan_contiguous(), we need to set
* DDS_ShortSeq_get_maximum() to 0, i.e., the sequence won't have
* memory allocated to it. */
DDS_ShortSeq_set_maximum(&borrower_instance->data,0);
/* Now that the sequence doesn't have memory allocated to it, we can use
* DDS_ShortSeq_loan_contiguous() to loan short_buffer to borrower_instance.
* We set the allocated number of elements to MAX_SEQUENCE_LEN, the size of
* the buffer and the maximum size of the sequence as we declared in the
* IDL. */
DDS_ShortSeq_loan_contiguous(
&borrower_instance->data, /* Pointer to the sequence */
short_buffer, /* Buffer it loans */
0, /* Initial Length */
MAX_SEQUENCE_LEN /* New maximum */
);
/* Before starting to publish samples, set the instance id of each
* instance */
strcpy(owner_instance->id, "owner_instance");
strcpy(borrower_instance->id, "borrower_instance");
/* To illustrate the use of the sequences, in the main loop we set a
* new sequence length every iteration to the sequences contained in
* both instances (instance->data). The sequence length value cycles between
* 0 and MAX_SEQUENCE_LEN. We assign a random number between 0 and 100 to
* each sequence's elements. */
for (count=0; (sample_count == 0) || (count < sample_count); ++count) {
/* We set a different sequence_length for both instances every
* iteration. sequence_length is based on the value of count and
* its value cycles between the values of 1 and MAX_SEQUENCE_LEN. */
short sequence_length = (count % MAX_SEQUENCE_LEN) + 1;
printf("Writing sequences, count %d...\n",
count);
owner_instance->count = (short) count;
borrower_instance->count = (short) count;
/* Here we set the new length of each sequence */
DDS_ShortSeq_set_length(&owner_instance->data, sequence_length);
DDS_ShortSeq_set_length(&borrower_instance->data, sequence_length);
/* Now that the sequences have a new length, we assign a
* random number between 0 and 100 to each element of
* owner_instance->data and borrower_instance->data. */
for (i = 0; i < sequence_length; ++i) {
*DDS_ShortSeq_get_reference(&owner_instance->data, i) =
(short) (rand()/(RAND_MAX/100));
*DDS_ShortSeq_get_reference(&borrower_instance->data, i) =
(short) (rand()/(RAND_MAX/100));
}
/* Both sequences have the same length, so we only print the length
* of one of them. */
printf("Instances length = %d\n",
DDS_ShortSeq_get_length(&owner_instance->data)
);
/* Write for each instance */
retcode = sequencesDataWriter_write(
sequences_writer, owner_instance, &owner_instance_handle);
if (retcode != DDS_RETCODE_OK) {
printf("write error %d\n", retcode);
}
retcode = sequencesDataWriter_write(
sequences_writer, borrower_instance, &borrower_instance_handle);
if (retcode != DDS_RETCODE_OK) {
printf("write error %d\n", retcode);
}
NDDS_Utility_sleep(&send_period);
}
/* Once we are done with the sequence, we unloan and free the buffer. Make
* sure you don't call free before DDS_ShortSeq_unloan(); the next time you
* access the sequence, you will be accessing freed memory. */
if (!DDS_ShortSeq_unloan(&borrower_instance->data)) {
printf("Unloan error\n");
}
free(short_buffer);
/* Delete data samples */
retcode = sequencesTypeSupport_delete_data_ex(owner_instance,
DDS_BOOLEAN_TRUE);
if (retcode != DDS_RETCODE_OK) {
printf("sequencesTypeSupport_delete_data error %d\n", retcode);
}
retcode = sequencesTypeSupport_delete_data_ex(borrower_instance,
DDS_BOOLEAN_TRUE);
if (retcode != DDS_RETCODE_OK) {
printf("sequencesTypeSupport_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/using_sequences/c/sequences_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.
******************************************************************************/
/* sequences_subscriber.c
A subscription example
This file is derived from code automatically generated by the rtiddsgen
command:
rtiddsgen -language C -example <arch> sequences.idl
Example subscription of type sequences 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>/sequences_subscriber <domain_id> <sample_count>
(3) Start the publication with the command
objs/<arch>/sequences_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>/sequences_publisher <domain_id>
objs/<arch>/sequences_subscriber <domain_id>
On Windows systems:
objs\<arch>\sequences_publisher <domain_id>
objs\<arch>\sequences_subscriber <domain_id>
modification history
------------ -------
*/
#include <stdio.h>
#include <stdlib.h>
#include "ndds/ndds_c.h"
#include "sequences.h"
#include "sequencesSupport.h"
void sequencesListener_on_requested_deadline_missed(
void* listener_data,
DDS_DataReader* reader,
const struct DDS_RequestedDeadlineMissedStatus *status)
{
}
void sequencesListener_on_requested_incompatible_qos(
void* listener_data,
DDS_DataReader* reader,
const struct DDS_RequestedIncompatibleQosStatus *status)
{
}
void sequencesListener_on_sample_rejected(
void* listener_data,
DDS_DataReader* reader,
const struct DDS_SampleRejectedStatus *status)
{
}
void sequencesListener_on_liveliness_changed(
void* listener_data,
DDS_DataReader* reader,
const struct DDS_LivelinessChangedStatus *status)
{
}
void sequencesListener_on_sample_lost(
void* listener_data,
DDS_DataReader* reader,
const struct DDS_SampleLostStatus *status)
{
}
void sequencesListener_on_subscription_matched(
void* listener_data,
DDS_DataReader* reader,
const struct DDS_SubscriptionMatchedStatus *status)
{
}
void sequencesListener_on_data_available(
void* listener_data,
DDS_DataReader* reader)
{
sequencesDataReader *sequences_reader = NULL;
struct sequencesSeq data_seq = DDS_SEQUENCE_INITIALIZER;
struct DDS_SampleInfoSeq info_seq = DDS_SEQUENCE_INITIALIZER;
DDS_ReturnCode_t retcode;
int i;
sequences_reader = sequencesDataReader_narrow(reader);
if (sequences_reader == NULL) {
printf("DataReader narrow error\n");
return;
}
retcode = sequencesDataReader_take(
sequences_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 < sequencesSeq_get_length(&data_seq); ++i) {
if (DDS_SampleInfoSeq_get_reference(&info_seq, i)->valid_data) {
sequencesTypeSupport_print_data(
sequencesSeq_get_reference(&data_seq, i));
}
}
retcode = sequencesDataReader_return_loan(
sequences_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};
/* 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 = sequencesTypeSupport_get_type_name();
retcode = sequencesTypeSupport_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 sequences",
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 =
sequencesListener_on_requested_deadline_missed;
reader_listener.on_requested_incompatible_qos =
sequencesListener_on_requested_incompatible_qos;
reader_listener.on_sample_rejected =
sequencesListener_on_sample_rejected;
reader_listener.on_liveliness_changed =
sequencesListener_on_liveliness_changed;
reader_listener.on_sample_lost =
sequencesListener_on_sample_lost;
reader_listener.on_subscription_matched =
sequencesListener_on_subscription_matched;
reader_listener.on_data_available =
sequencesListener_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("sequences 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/recursive_data_type/c++/RecursiveType_publisher.cxx |
/* RecursiveType_publisher.cxx
A publication of data of type Tree
This file is derived from code automatically generated by the rtiddsgen
command:
rtiddsgen -language C++ -example <arch> RecursiveType.idl
Example publication of type Tree 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>/RecursiveType_subscriber <domain_id> <sample_count>
(3) Start the publication with the command
objs/<arch>/RecursiveType_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>/RecursiveType_publisher <domain_id> o
objs/<arch>/RecursiveType_subscriber <domain_id>
On Windows:
objs\<arch>\RecursiveType_publisher <domain_id>
objs\<arch>\RecursiveType_subscriber <domain_id>
*/
#include <stdio.h>
#include <stdlib.h>
#include "RecursiveType.h"
#include "RecursiveTypeSupport.h"
#include "ndds/ndds_cpp.h"
#include "ndds/ndds_namespace_cpp.h"
using namespace DDS;
/* 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) {
printf("delete_contained_entities error %d\n", retcode);
status = -1;
}
retcode = TheParticipantFactory->delete_participant(participant);
if (retcode != 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 = DomainParticipantFactory::finalize_instance();
if (retcode != RETCODE_OK) {
printf("finalize_instance error %d\n", retcode);
status = -1;
}
*/
return status;
}
void fill_tree(Tree *instance, int childcount, int depth, int value) {
instance->node.data = value;
if ( depth == 0 ) {
return;
}
if ( instance->children == NULL ) {
instance->children = new TreeSeq();
}
instance->children->ensure_length(childcount, childcount);
for (int i=0; i< childcount; ++i) {
Tree &child = (*instance->children)[i];
fill_tree(&child, childcount, depth-1, value);
}
}
extern "C" int publisher_main(int domainId, int sample_count)
{
DomainParticipant *participant = NULL;
Publisher *publisher = NULL;
Topic *topic = NULL;
DataWriter *writer = NULL;
TreeDataWriter * Tree_writer = NULL;
Tree *instance = NULL;
ReturnCode_t retcode;
InstanceHandle_t instance_handle = HANDLE_NIL;
const char *type_name = NULL;
int count = 0;
Duration_t send_period = {4,0};
/* To customize participant QoS, use
the configuration file USER_QOS_PROFILES.xml */
participant = TheParticipantFactory->create_participant(
domainId, PARTICIPANT_QOS_DEFAULT,
NULL /* listener */, 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(
PUBLISHER_QOS_DEFAULT, NULL /* listener */, STATUS_MASK_NONE);
if (publisher == NULL) {
printf("create_publisher error\n");
publisher_shutdown(participant);
return -1;
}
/* Register type before creating topic */
type_name = TreeTypeSupport::get_type_name();
retcode = TreeTypeSupport::register_type(
participant, type_name);
if (retcode != 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 Tree",
type_name, TOPIC_QOS_DEFAULT, NULL /* listener */,
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, DATAWRITER_QOS_DEFAULT, NULL /* listener */,
STATUS_MASK_NONE);
if (writer == NULL) {
printf("create_datawriter error\n");
publisher_shutdown(participant);
return -1;
}
Tree_writer = TreeDataWriter::narrow(writer);
if (Tree_writer == NULL) {
printf("DataWriter narrow error\n");
publisher_shutdown(participant);
return -1;
}
/* Create data sample for writing */
instance = TreeTypeSupport::create_data();
if (instance == NULL) {
printf("TreeTypeSupport::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 = Tree_writer->register_instance(*instance);
*/
/* Main loop */
for (count=0; (sample_count == 0) || (count < sample_count); ++count) {
printf("Writing Tree, count %d\n", count);
/* Modify the data to be sent here */
fill_tree(instance, 1, count, count);
retcode = Tree_writer->write(*instance, instance_handle);
if (retcode != RETCODE_OK) {
printf("write error %d\n", retcode);
}
NDDSUtility::sleep(send_period);
}
/*
retcode = Tree_writer->unregister_instance(
*instance, instance_handle);
if (retcode != RETCODE_OK) {
printf("unregister instance error %d\n", retcode);
}
*/
/* Delete data sample */
retcode = TreeTypeSupport::delete_data(instance);
if (retcode != RETCODE_OK) {
printf("TreeTypeSupport::delete_data error %d\n", retcode);
}
/* Delete all entities */
return publisher_shutdown(participant);
}
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);
}
| cxx |
rticonnextdds-examples | data/projects/rticonnextdds-examples/recursive_data_type/c++/RecursiveType_subscriber.cxx |
/* RecursiveType_subscriber.cxx
A subscription example
This file is derived from code automatically generated by the rtiddsgen
command:
rtiddsgen -language C++ -example <arch> RecursiveType.idl
Example subscription of type Tree 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>/RecursiveType_subscriber <domain_id> <sample_count>
(3) Start the publication with the command
objs/<arch>/RecursiveType_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>/RecursiveType_publisher <domain_id>
objs/<arch>/RecursiveType_subscriber <domain_id>
On Windows:
objs\<arch>\RecursiveType_publisher <domain_id>
objs\<arch>\RecursiveType_subscriber <domain_id>
*/
#include <stdio.h>
#include <stdlib.h>
#include "RecursiveType.h"
#include "RecursiveTypeSupport.h"
#include "ndds/ndds_cpp.h"
#include "ndds/ndds_namespace_cpp.h"
using namespace DDS;
class TreeListener : public DataReaderListener {
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_subscription_matched(
DataReader* /*reader*/,
const SubscriptionMatchedStatus& /*status*/) {}
virtual void on_data_available(DataReader* reader);
};
void TreeListener::on_data_available(DataReader* reader)
{
TreeDataReader *Tree_reader = NULL;
TreeSeq data_seq;
SampleInfoSeq info_seq;
ReturnCode_t retcode;
int i;
Tree_reader = TreeDataReader::narrow(reader);
if (Tree_reader == NULL) {
printf("DataReader narrow error\n");
return;
}
retcode = Tree_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) {
printf("take error %d\n", retcode);
return;
}
for (i = 0; i < data_seq.length(); ++i) {
if (info_seq[i].valid_data) {
printf("Received data\n");
TreeTypeSupport::print_data(&data_seq[i]);
}
}
retcode = Tree_reader->return_loan(data_seq, info_seq);
if (retcode != RETCODE_OK) {
printf("return loan error %d\n", retcode);
}
}
/* 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) {
printf("delete_contained_entities error %d\n", retcode);
status = -1;
}
retcode = TheParticipantFactory->delete_participant(participant);
if (retcode != 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 = DomainParticipantFactory::finalize_instance();
if (retcode != RETCODE_OK) {
printf("finalize_instance error %d\n", retcode);
status = -1;
}
*/
return status;
}
extern "C" int subscriber_main(int domainId, int sample_count)
{
DomainParticipant *participant = NULL;
Subscriber *subscriber = NULL;
Topic *topic = NULL;
TreeListener *reader_listener = NULL;
DataReader *reader = NULL;
ReturnCode_t retcode;
const char *type_name = NULL;
int count = 0;
Duration_t receive_period = {4,0};
int status = 0;
/* To customize the participant QoS, use
the configuration file USER_QOS_PROFILES.xml */
participant = TheParticipantFactory->create_participant(
domainId, PARTICIPANT_QOS_DEFAULT,
NULL /* listener */, 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(
SUBSCRIBER_QOS_DEFAULT, NULL /* listener */, 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 = TreeTypeSupport::get_type_name();
retcode = TreeTypeSupport::register_type(
participant, type_name);
if (retcode != 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 Tree",
type_name, TOPIC_QOS_DEFAULT, NULL /* listener */,
STATUS_MASK_NONE);
if (topic == NULL) {
printf("create_topic error\n");
subscriber_shutdown(participant);
return -1;
}
/* Create a data reader listener */
reader_listener = new TreeListener();
/* To customize the data reader QoS, use
the configuration file USER_QOS_PROFILES.xml */
reader = subscriber->create_datareader(
topic, DATAREADER_QOS_DEFAULT, reader_listener,
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("Tree 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;
}
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);
}
| cxx |
rticonnextdds-examples | data/projects/rticonnextdds-examples/recursive_data_type/c/RecursiveType_publisher.c |
/* RecursiveType_publisher.c
A publication of data of type Tree
This file is derived from code automatically generated by the rtiddsgen
command:
rtiddsgen -language C -example <arch> RecursiveType.idl
Example publication of type Tree 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
Service with the command
objs/<arch>/RecursiveType_subscriber <domain_id> <sample_count>
(3) Start the publication on the same domain used for RTI Data Distribution
Service with the command
objs/<arch>/RecursiveType_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>/RecursiveType_publisher <domain_id>
objs/<arch>/RecursiveType_subscriber <domain_id>
On Windows:
objs\<arch>\RecursiveType_publisher <domain_id>
objs\<arch>\RecursiveType_subscriber <domain_id>
*/
#include <stdio.h>
#include <stdlib.h>
#include "ndds/ndds_c.h"
#include "RecursiveType.h"
#include "RecursiveTypeSupport.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 Data Distribution Service 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;
}
void fill_tree(Tree *instance, int childcount, int depth, int value)
{
int i = 0;
instance->node.data = value;
if ( depth == 0 ) {
return;
}
if ( instance->children == NULL ) {
instance->children = (struct TreeSeq *)malloc(sizeof(struct TreeSeq));
TreeSeq_initialize(instance->children);
}
TreeSeq_ensure_length(instance->children, childcount, childcount);
for (i = 0; i < childcount; ++i) {
Tree *child = TreeSeq_get_reference(instance->children, i);
fill_tree(child, childcount, depth-1, value);
}
}
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;
TreeDataWriter *Tree_writer = NULL;
Tree *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 = {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");
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 = TreeTypeSupport_get_type_name();
retcode = TreeTypeSupport_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 Tree",
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;
}
Tree_writer = TreeDataWriter_narrow(writer);
if (Tree_writer == NULL) {
printf("DataWriter narrow error\n");
publisher_shutdown(participant);
return -1;
}
/* Create data sample for writing */
instance = TreeTypeSupport_create_data_ex(DDS_BOOLEAN_TRUE);
if (instance == NULL) {
printf("TreeTypeSupport_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 = TreeDataWriter_register_instance(
Tree_writer, instance);
*/
/* Main loop */
for (count=0; (sample_count == 0) || (count < sample_count); ++count) {
printf("Writing Tree, count %d\n", count);
/* Modify the data to be written here */
fill_tree(instance, 1, count, count);
/* Write data */
retcode = TreeDataWriter_write(
Tree_writer, instance, &instance_handle);
if (retcode != DDS_RETCODE_OK) {
printf("write error %d\n", retcode);
}
NDDS_Utility_sleep(&send_period);
}
/*
retcode = TreeDataWriter_unregister_instance(
Tree_writer, instance, &instance_handle);
if (retcode != DDS_RETCODE_OK) {
printf("unregister instance error %d\n", retcode);
}
*/
/* Delete data sample */
retcode = TreeTypeSupport_delete_data_ex(instance, DDS_BOOLEAN_TRUE);
if (retcode != DDS_RETCODE_OK) {
printf("TreeTypeSupport_delete_data error %d\n", retcode);
}
/* Cleanup and delete delete all entities */
return publisher_shutdown(participant);
}
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);
}
| c |
rticonnextdds-examples | data/projects/rticonnextdds-examples/recursive_data_type/c/RecursiveType_subscriber.c |
/* RecursiveType_subscriber.c
A subscription example
This file is derived from code automatically generated by the rtiddsgen
command:
rtiddsgen -language C -example <arch> RecursiveType.idl
Example subscription of type Tree 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>/RecursiveType_subscriber <domain_id> <sample_count>
(3) Start the publication on the same domain used for RTI Data Distribution
Service with the command
objs/<arch>/RecursiveType_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>/RecursiveType_publisher <domain_id>
objs/<arch>/RecursiveType_subscriber <domain_id>
On Windows systems:
objs\<arch>\RecursiveType_publisher <domain_id>
objs\<arch>\RecursiveType_subscriber <domain_id>
*/
#include <stdio.h>
#include <stdlib.h>
#include "ndds/ndds_c.h"
#include "RecursiveType.h"
#include "RecursiveTypeSupport.h"
void TreeListener_on_requested_deadline_missed(
void* listener_data,
DDS_DataReader* reader,
const struct DDS_RequestedDeadlineMissedStatus *status)
{
}
void TreeListener_on_requested_incompatible_qos(
void* listener_data,
DDS_DataReader* reader,
const struct DDS_RequestedIncompatibleQosStatus *status)
{
}
void TreeListener_on_sample_rejected(
void* listener_data,
DDS_DataReader* reader,
const struct DDS_SampleRejectedStatus *status)
{
}
void TreeListener_on_liveliness_changed(
void* listener_data,
DDS_DataReader* reader,
const struct DDS_LivelinessChangedStatus *status)
{
}
void TreeListener_on_sample_lost(
void* listener_data,
DDS_DataReader* reader,
const struct DDS_SampleLostStatus *status)
{
}
void TreeListener_on_subscription_matched(
void* listener_data,
DDS_DataReader* reader,
const struct DDS_SubscriptionMatchedStatus *status)
{
}
void TreeListener_on_data_available(
void* listener_data,
DDS_DataReader* reader)
{
TreeDataReader *Tree_reader = NULL;
struct TreeSeq data_seq = DDS_SEQUENCE_INITIALIZER;
struct DDS_SampleInfoSeq info_seq = DDS_SEQUENCE_INITIALIZER;
DDS_ReturnCode_t retcode;
int i;
Tree_reader = TreeDataReader_narrow(reader);
if (Tree_reader == NULL) {
printf("DataReader narrow error\n");
return;
}
retcode = TreeDataReader_take(
Tree_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 < TreeSeq_get_length(&data_seq); ++i) {
if (DDS_SampleInfoSeq_get_reference(&info_seq, i)->valid_data) {
printf("Received data\n");
TreeTypeSupport_print_data(
TreeSeq_get_reference(&data_seq, i));
}
}
retcode = TreeDataReader_return_loan(
Tree_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 Data Distribution Service 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};
/* 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 = TreeTypeSupport_get_type_name();
retcode = TreeTypeSupport_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 Tree",
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 =
TreeListener_on_requested_deadline_missed;
reader_listener.on_requested_incompatible_qos =
TreeListener_on_requested_incompatible_qos;
reader_listener.on_sample_rejected =
TreeListener_on_sample_rejected;
reader_listener.on_liveliness_changed =
TreeListener_on_liveliness_changed;
reader_listener.on_sample_lost =
TreeListener_on_sample_lost;
reader_listener.on_subscription_matched =
TreeListener_on_subscription_matched;
reader_listener.on_data_available =
TreeListener_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("Tree subscriber sleeping for %d sec...\n",
poll_period.sec);
NDDS_Utility_sleep(&poll_period);
}
/* Cleanup and delete all entities */
return subscriber_shutdown(participant);
}
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);
}
| c |
rticonnextdds-examples | data/projects/rticonnextdds-examples/recursive_data_type/c++03/RecursiveType_publisher.cxx | /* RecursiveType_publisher.cxx
A publication of data of type Tree
This file is derived from code automatically generated by the rtiddsgen
command:
rtiddsgen -language C++03 -example <arch> RecursiveType.idl
Example publication of type Tree 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
Service with the command
objs/<arch>/RecursiveType_subscriber <domain_id> <sample_count>
(3) Start the publication on the same domain used for RTI Data Distribution
Service with the command
objs/<arch>/RecursiveType_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>/RecursiveType_publisher <domain_id>
objs/<arch>/RecursiveType_subscriber <domain_id>
On Windows:
objs\<arch>\RecursiveType_publisher <domain_id>
objs\<arch>\RecursiveType_subscriber <domain_id>
*/
#include <iostream>
#include <dds/pub/ddspub.hpp>
#include <rti/util/util.hpp> // for sleep()
#include "RecursiveType.hpp"
void fill_tree(Tree &tree, int childcount, int depth, int value) {
tree.node().data(value);
if ( depth == 0 ) {
return;
}
if ( !tree.children().is_set() ) {
// Initialize Tree with empty vector of children. This
// call makes a copy of the (empty) vector
dds::core::vector<Tree> children;
tree.children(children);
}
// Resize the list of children to the desired length
tree.children().get().resize(childcount);
for (int i=0; i< childcount; ++i) {
fill_tree(tree.children().get()[i], childcount, depth-1, value);
}
}
void publisher_main(int domain_id, 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<Tree> topic (participant, "Example Tree");
// Create a DataWriter with default Qos (Publisher created in-line)
dds::pub::DataWriter<Tree> writer(dds::pub::Publisher(participant), topic);
Tree sample;
for (int count = 0; count < sample_count || sample_count == 0; count++) {
// Modify the data to be written here
fill_tree(sample, 1, count, count);
std::cout << "Writing Tree, count " << count << std::endl;
writer.write(sample);
rti::util::sleep(dds::core::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;
}
// RTI Connext provides a finalize_participant_factory() method
// if you want to release memory used by the participant factory singleton.
// Uncomment the following line to release the singleton:
//
// dds::domain::DomainParticipant::finalize_participant_factory();
return 0;
}
| cxx |
rticonnextdds-examples | data/projects/rticonnextdds-examples/recursive_data_type/c++03/RecursiveType_subscriber.cxx | /* RecursiveType_subscriber.cxx
A subscription example
This file is derived from code automatically generated by the rtiddsgen
command:
rtiddsgen -language C++03 -example <arch> RecursiveType.idl
Example subscription of type Tree 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>/RecursiveType_subscriber <domain_id> <sample_count>
(3) Start the publication on the same domain used for RTI Data Distribution
Service with the command
objs/<arch>/RecursiveType_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>/RecursiveType_publisher <domain_id>
objs/<arch>/RecursiveType_subscriber <domain_id>
On Windows systems:
objs\<arch>\RecursiveType_publisher <domain_id>
objs\<arch>\RecursiveType_subscriber <domain_id>
*/
#include <algorithm>
#include <iostream>
#include <dds/sub/ddssub.hpp>
#include <dds/core/ddscore.hpp>
// Or simply include <dds/dds.hpp>
#include "RecursiveType.hpp"
class TreeReaderListener : public dds::sub::NoOpDataReaderListener<Tree> {
public:
TreeReaderListener() : count_ (0)
{
}
void on_data_available(dds::sub::DataReader<Tree>& reader)
{
// Take all samples
dds::sub::LoanedSamples<Tree> samples = reader.take();
for ( dds::sub::LoanedSamples<Tree>::iterator sample_it = samples.begin();
sample_it != samples.end(); sample_it++) {
if (sample_it->info().valid()){
count_++;
std::cout << sample_it->data() << std::endl;
}
}
}
int count() const
{
return count_;
}
private:
int count_;
};
void subscriber_main(int domain_id, 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<Tree> topic(participant, "Example Tree");
// Create a DataReader with default Qos (Subscriber created in-line)
TreeReaderListener listener;
dds::sub::DataReader<Tree> reader(
dds::sub::Subscriber(participant),
topic,
dds::core::QosProvider::Default().datareader_qos(),
&listener,
dds::core::status::StatusMask::data_available());
while (listener.count() < sample_count || sample_count == 0) {
std::cout << "Tree subscriber sleeping for 4 sec..." << std::endl;
rti::util::sleep(dds::core::Duration(4));
}
// Unset the listener to allow the reader destruction
// (rti::core::ListenerBinder can do this automatically)
reader.listener(NULL, dds::core::status::StatusMask::none());
}
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;
}
// RTI Connext provides a finalize_participant_factory() method
// if you want to release memory used by the participant factory singleton.
// Uncomment the following line to release the singleton:
//
// dds::domain::DomainParticipant::finalize_participant_factory();
return 0;
}
| cxx |
rticonnextdds-examples | data/projects/rticonnextdds-examples/asyncwaitset/c++03/AwsExample_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 <dds/core/ddscore.hpp>
#include <dds/pub/ddspub.hpp>
#include <dds/sub/ddssub.hpp>
#include <rti/core/cond/AsyncWaitSet.hpp>
#include <rti/util/util.hpp> // for sleep()
#include <rti/config/Logger.hpp>
#include "AwsExample.hpp"
class AwsSubscriber {
public:
static const std::string TOPIC_NAME;
AwsSubscriber(
DDS_DomainId_t domain_id,
rti::core::cond::AsyncWaitSet async_waitset);
void process_received_samples();
int received_count();
~AwsSubscriber();
public:
// Entities to receive data
dds::sub::DataReader<AwsExample> receiver_;
// Reference to the AWS used for processing the events
rti::core::cond::AsyncWaitSet async_waitset_;
};
class DataAvailableHandler {
public:
/* Handles the reception of samples */
void operator()()
{
subscriber_.process_received_samples();
}
DataAvailableHandler(AwsSubscriber& subscriber) : subscriber_(subscriber)
{
}
private:
AwsSubscriber& subscriber_;
};
// AwsSubscriberPlayer implementation
const std::string AwsSubscriber::TOPIC_NAME = "AwsExample Example";
AwsSubscriber::AwsSubscriber(
DDS_DomainId_t domain_id,
rti::core::cond::AsyncWaitSet async_waitset)
: receiver_(dds::core::null),
async_waitset_(async_waitset)
{
// Create a DomainParticipant with default Qos
dds::domain::DomainParticipant participant(domain_id);
// Create a Topic -- and automatically register the type
dds::topic::Topic<AwsExample> topic(participant, TOPIC_NAME);
// Create a DataReader with default Qos (Subscriber created in-line)
receiver_ = dds::sub::DataReader<AwsExample>(
dds::sub::Subscriber(participant),
topic);
// DataReader status condition: to process the reception of samples
dds::core::cond::StatusCondition reader_status_condition(receiver_);
reader_status_condition.enabled_statuses(
dds::core::status::StatusMask::data_available());
reader_status_condition->handler(DataAvailableHandler(*this));
async_waitset_.attach_condition(reader_status_condition);
}
void AwsSubscriber::process_received_samples()
{
// Take all samples This will reset the StatusCondition
dds::sub::LoanedSamples<AwsExample> samples = receiver_.take();
// Release status condition in case other threads can process outstanding
// samples
async_waitset_.unlock_condition(dds::core::cond::StatusCondition(receiver_));
// Process sample
for (dds::sub::LoanedSamples<AwsExample>::iterator sample_it = samples.begin();
sample_it != samples.end();
sample_it++) {
if (sample_it->info().valid()) {
std::cout
<< "Received sample:\n\t"
<< sample_it->data()
<< std::endl;
}
}
// Sleep a random amount of time between 1 and 10 secs. This is
// intended to cause the handling thread of the AWS to take a long
// time dispatching
rti::util::sleep(dds::core::Duration::from_secs(rand() % 10 + 1));
}
int AwsSubscriber::received_count()
{
return receiver_->datareader_protocol_status()
.received_sample_count().total();
}
AwsSubscriber::~AwsSubscriber()
{
async_waitset_.detach_condition(dds::core::cond::StatusCondition(receiver_));
}
int main(int argc, char *argv[])
{
int domain_id = 0;
int thread_pool_size = 4;
int sample_count = 0; // infinite loop
const std::string USAGE(
"AwsSubscriber_subscriber [options]\n"
"Options:\n"
"\t-d, -domainId: Domain ID\n"
"\t-t, -threads: Number of threads used to process sample reception\n"
"\t-s, -samples: Total number of received samples before exiting\n");
srand(time(NULL));
for (int i = 0; i < argc; i++) {
if (strcmp(argv[i], "-d") == 0
|| strcmp(argv[i], "-domainId") == 0) {
if (i == argc - 1) {
std::cerr << "missing domain ID parameter value " << std::endl;
return -1;
} else {
domain_id = atoi(argv[++i]);
}
} else if (strcmp(argv[i], "-t") == 0
|| strcmp(argv[i], "-threads") == 0) {
if (i == argc - 1) {
std::cerr << "missing threads parameter value " << std::endl;
return -1;
} else {
thread_pool_size = atoi(argv[++i]);
}
} else if (strcmp(argv[i], "-s") == 0
|| strcmp(argv[i], "-samples") == 0) {
if (i == argc - 1) {
std::cerr << "missing samples parameter value " << std::endl;
return -1;
} else {
sample_count = atoi(argv[++i]);
}
} else if (strcmp(argv[i], "-h") == 0
|| strcmp(argv[i], "-help") == 0) {
std::cout << USAGE << std::endl;
return 0;
}
}
// 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 {
// An AsyncWaitSet (AWS) for multi-threaded events .
// The AWS will provide the infrastructure to receive samples using
// multiple threads.
rti::core::cond::AsyncWaitSet async_waitset(
rti::core::cond::AsyncWaitSetProperty()
.thread_pool_size(thread_pool_size));
async_waitset.start();
AwsSubscriber subscriber(
domain_id,
async_waitset);
std::cout << "Wait for samples..." << std::endl;
while (subscriber.received_count() < sample_count || sample_count == 0) {
rti::util::sleep(dds::core::Duration(1));
}
} catch (const std::exception& ex) {
// This will catch DDS exceptions
std::cerr << "Exception in main(): " << ex.what() << std::endl;
return -1;
}
// RTI Connext provides a finalize_participant_factory() method
// if you want to release memory used by the participant factory singleton.
// Uncomment the following line to release the singleton:
//
// dds::domain::DomainParticipant::finalize_participant_factory();
return 0;
}
| cxx |
rticonnextdds-examples | data/projects/rticonnextdds-examples/asyncwaitset/c++03/AwsExample_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 <dds/core/ddscore.hpp>
#include <dds/pub/ddspub.hpp>
#include <dds/sub/ddssub.hpp>
#include <rti/core/cond/AsyncWaitSet.hpp>
#include <rti/util/util.hpp> // for sleep()
#include "AwsExample.hpp"
class AwsPublisher {
public:
static const std::string TOPIC_NAME;
AwsPublisher(
DDS_DomainId_t domain_id,
int publisher_id,
rti::core::cond::AsyncWaitSet async_waitset);
void generate_send_event();
void send_sample();
~AwsPublisher();
private:
// A writer to send data
dds::pub::DataWriter<AwsExample> sender_;
// Sample buffer
AwsExample sample_;
// A GuardCondition to generate app-driven sends
dds::core::cond::GuardCondition send_condition_;
// Reference to the AWS used for writing the samples
rti::core::cond::AsyncWaitSet async_waitset_;
};
class SendRequestHandler {
public:
// Handles the send sample condition
void operator()(dds::core::cond::Condition condition)
{
// condition is the same than sendCondition_ so it is safe to
// perform the downcast. It is important to reset the condition trigger
// to avoid continuous wakeup and dispatch
dds::core::cond::GuardCondition guard_condition =
dds::core::polymorphic_cast<dds::core::cond::GuardCondition>(condition);
guard_condition.trigger_value(false);
publisher_.send_sample();
}
SendRequestHandler(AwsPublisher& publisher) : publisher_(publisher)
{
}
private:
AwsPublisher& publisher_;
};
// AwsPublisher implementation
const std::string AwsPublisher::TOPIC_NAME = "AwsExample Example";
AwsPublisher::AwsPublisher(
DDS_DomainId_t domain_id,
int publisher_id,
rti::core::cond::AsyncWaitSet async_waitset)
: sender_(dds::core::null),
async_waitset_(async_waitset)
{
// Create a DomainParticipant with default Qos
dds::domain::DomainParticipant participant(domain_id);
// Create a Topic -- and automatically register the type
dds::topic::Topic<AwsExample> topic(participant, TOPIC_NAME);
// Create a DataWriter with default Qos (Publisher created in-line)
sender_ = dds::pub::DataWriter<AwsExample>(
dds::pub::Publisher(participant),
topic);
// set sample key value:
sample_.key(publisher_id);
// Send condition: to generate application-driven events to send samples
send_condition_.handler(SendRequestHandler(*this));
async_waitset_.attach_condition(send_condition_);
}
void AwsPublisher::generate_send_event()
{
send_condition_.trigger_value(true);
}
void AwsPublisher::send_sample()
{
std::cout << "Send Sample: " << sample_.number() << std::endl;
sample_.number(sample_.number() + 1);
sender_.write(sample_);
}
AwsPublisher::~AwsPublisher()
{
async_waitset_.detach_condition(send_condition_);
}
int main(int argc, char *argv[])
{
int domain_id = 0;
int publisher_id = 0;
int sample_count = 0; // infinite loop
const std::string USAGE(
"Aws_publisher [options]\n"
"Options:\n"
"\t-d, -domainId: Domain ID\n"
"\t-p, -publisherId: Key value for the Aws samples\n"
"\t-s, -samples: Total number of published samples\n");
srand(time(NULL));
publisher_id = rand() % RAND_MAX;
for (int i = 0; i < argc; i++) {
if (strcmp(argv[i], "-d") == 0
|| strcmp(argv[i], "-domainId") == 0) {
if (i == argc - 1) {
std::cerr << "missing domain ID parameter value " << std::endl;
return -1;
} else {
domain_id = atoi(argv[++i]);
}
} else if (strcmp(argv[i], "-p") == 0
|| strcmp(argv[i], "-publisherId") == 0) {
if (i == argc - 1) {
std::cerr << "missing publisher ID parameter value " << std::endl;
return -1;
} else {
publisher_id = atoi(argv[++i]);
}
} else if (strcmp(argv[i], "-s") == 0
|| strcmp(argv[i], "-samples") == 0) {
if (i == argc - 1) {
std::cerr << "missing samples parameter value " << std::endl;
return -1;
} else {
sample_count = atoi(argv[++i]);
}
} else if (strcmp(argv[i], "-h") == 0
|| strcmp(argv[i], "-help") == 0) {
std::cout << USAGE << std::endl;
return 0;
}
}
// 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 {
// An AsyncWaitSet (AWS) to send samples in a separate thread
rti::core::cond::AsyncWaitSet async_waitset;
async_waitset.start();
AwsPublisher publisher(domain_id, publisher_id, async_waitset);
// Generate periodic send events
for (int count = 0; count < sample_count || sample_count == 0; count++) {
publisher.generate_send_event();
rti::util::sleep(dds::core::Duration(1));
}
} catch (const std::exception& ex) {
// This will catch DDS exceptions
std::cerr << "Exception in publisher_main(): " << ex.what() << std::endl;
return -1;
}
// RTI Connext provides a finalize_participant_factory() method
// if you want to release memory used by the participant factory singleton.
// Uncomment the following line to release the singleton:
//
// dds::domain::DomainParticipant::finalize_participant_factory();
return 0;
}
| cxx |
rticonnextdds-robot-helpers | data/projects/rticonnextdds-robot-helpers/rclcpp_dds_examples/src/chatter/listener.cpp | // Copyright 2014 Open Source Robotics Foundation, Inc.
// Copyright 2021 Real-Time Innovations, Inc. (RTI)
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "rclcpp_dds/rclcpp_dds.hpp"
#include "rclcpp_components/register_node_macro.hpp"
#include "rclcpp_dds_examples/visibility_control.h"
#include "std_msgs/msg/String.hpp"
namespace rclcpp_dds_examples
{
// Create a Listener class that subclasses the generic rclcpp::Node base class.
// The main function below will instantiate the class as a ROS node.
class DdsListener : public rclcpp_dds::DDSNode
{
public:
RCLCPP_DDS_EXAMPLES_PUBLIC
explicit DdsListener(const rclcpp::NodeOptions & options)
: DDSNode("dds_listener", options)
{
setvbuf(stdout, NULL, _IONBF, BUFSIZ);
using std_msgs::msg::String;
auto reader_qos = this->get_default_datareader_qos();
reader_qos << dds::core::policy::Reliability::Reliable();
reader_qos << dds::core::policy::History::KeepLast(7);
sub_ = this->create_datareader<String>("chatter", reader_qos);
this->set_data_callback<String>(
sub_, [this](const String & msg) {
RCLCPP_INFO(this->get_logger(), "I heard from Connext: [%s]", msg.data().c_str());
});
}
private:
dds::sub::DataReader<std_msgs::msg::String> sub_{nullptr};
};
} // namespace rclcpp_dds_examples
RCLCPP_COMPONENTS_REGISTER_NODE(rclcpp_dds_examples::DdsListener)
| cpp |
rticonnextdds-robot-helpers | data/projects/rticonnextdds-robot-helpers/rclcpp_dds_examples/src/chatter/talker.cpp | // Copyright 2014 Open Source Robotics Foundation, Inc.
// Copyright 2021 Real-Time Innovations, Inc. (RTI)
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include <chrono>
#include <cstdio>
#include <memory>
#include <utility>
#include "rclcpp_dds/rclcpp_dds.hpp"
#include "rclcpp_components/register_node_macro.hpp"
#include "rclcpp_dds_examples/visibility_control.h"
// Include type support code generated by rtiddsgen
#include "std_msgs/msg/String.hpp"
namespace rclcpp_dds_examples
{
// Create a Talker class that subclasses the generic rclcpp::Node base class.
// The main function below will instantiate the class as a ROS node.
// Use Connext's Modern C++ API to create a DataWriter to publish messages.
class DdsTalker : public rclcpp_dds::DDSNode
{
public:
RCLCPP_DDS_EXAMPLES_PUBLIC
explicit DdsTalker(const rclcpp::NodeOptions & options)
: DDSNode("talker", options)
{
// Create a function for when messages are to be sent.
setvbuf(stdout, NULL, _IONBF, BUFSIZ);
auto publish_message =
[this]() -> void
{
std_msgs::msg::String msg("Hello World: " + std::to_string(count_++));
RCLCPP_INFO(this->get_logger(), "Publishing: '%s'", msg.data().c_str());
writer_.write(msg);
};
auto writer_qos = this->get_default_datawriter_qos();
writer_qos << dds::core::policy::Reliability::Reliable();
writer_qos << dds::core::policy::History::KeepLast(7);
writer_ = this->create_datawriter<std_msgs::msg::String>("chatter", writer_qos);
// Use a timer to schedule periodic message publishing.
using namespace std::chrono_literals;
timer_ = this->create_wall_timer(1s, publish_message);
}
private:
size_t count_ = 1;
dds::pub::DataWriter<std_msgs::msg::String> writer_{nullptr};
rclcpp::TimerBase::SharedPtr timer_;
};
} // namespace rclcpp_dds_examples
RCLCPP_COMPONENTS_REGISTER_NODE(rclcpp_dds_examples::DdsTalker)
| cpp |
rticonnextdds-robot-helpers | data/projects/rticonnextdds-robot-helpers/rclcpp_dds_examples/src/chatter/listener_main.cpp | // Copyright 2016 Open Source Robotics Foundation, Inc.
// Copyright 2021 Real-Time Innovations, Inc. (RTI)
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include <memory>
#include "rclcpp_dds/rclcpp_dds.hpp"
// Include type support code generated by rtiddsgen
#include "std_msgs/msg/String.hpp"
using std::placeholders::_1;
namespace rclcpp_dds_examples
{
class DdsListener : public rclcpp_dds::DDSNode
{
public:
DdsListener()
: DDSNode("dds_listener")
{
using std_msgs::msg::String;
auto reader_qos = this->get_default_datareader_qos();
reader_qos << dds::core::policy::Reliability::Reliable();
reader_ = this->create_datareader<String>("chatter", reader_qos);
this->set_data_callback<String>(
reader_, [this](const String & msg)
{
RCLCPP_INFO(
this->get_logger(),
"I heard from Connext: [%s]", msg.data().c_str());
});
}
private:
dds::sub::DataReader<std_msgs::msg::String> reader_{nullptr};
};
} // namespace rclcpp_dds_examples
int main(int argc, char * argv[])
{
rclcpp::init(argc, argv);
rclcpp::spin(std::make_shared<rclcpp_dds_examples::DdsListener>());
rclcpp::shutdown();
return 0;
}
| cpp |
rticonnextdds-robot-helpers | data/projects/rticonnextdds-robot-helpers/rclcpp_dds_examples/src/chatter/talker_main.cpp | // Copyright 2016 Open Source Robotics Foundation, Inc.
// Copyright 2021 Real-Time Innovations, Inc. (RTI)
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include <chrono>
#include <cstdio>
#include <memory>
#include <utility>
#include "rclcpp_dds/rclcpp_dds.hpp"
#include "std_msgs/msg/String.hpp"
namespace rclcpp_dds_examples
{
class DdsTalker : public rclcpp_dds::DDSNode
{
public:
DdsTalker()
: DDSNode("dds_talker"),
count_(0)
{
// Create a function to send messages periodically.
setvbuf(stdout, NULL, _IONBF, BUFSIZ);
auto publish_message =
[this]() -> void
{
std_msgs::msg::String msg("Hello World: " + std::to_string(count_++));
RCLCPP_INFO(this->get_logger(), "Publishing: '%s'", msg.data().c_str());
writer_.write(msg);
};
auto writer_qos = this->get_default_datawriter_qos();
writer_qos << dds::core::policy::Reliability::Reliable();
writer_qos << dds::core::policy::History::KeepLast(7);
writer_ = this->create_datawriter<std_msgs::msg::String>("chatter", writer_qos);
using namespace std::chrono_literals;
// Use a timer to schedule periodic message publishing.
timer_ = this->create_wall_timer(1s, publish_message);
}
private:
size_t count_ = 1;
dds::pub::DataWriter<std_msgs::msg::String> writer_{nullptr};
rclcpp::TimerBase::SharedPtr timer_;
};
} // namespace rclcpp_dds_examples
int main(int argc, char * argv[])
{
rclcpp::init(argc, argv);
rclcpp::spin(std::make_shared<rclcpp_dds_examples::DdsTalker>());
rclcpp::shutdown();
return 0;
}
| cpp |
rticonnextdds-robot-helpers | data/projects/rticonnextdds-robot-helpers/rclcpp_dds_examples/src/ping/ping_string.cpp | // Copyright 2021 Real-Time Innovations, Inc. (RTI)
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include <string>
#include "std_msgs/msg/String.hpp"
#include "rclcpp/rclcpp.hpp"
#include "rclcpp_components/register_node_macro.hpp"
#include "rclcpp_dds_examples/ping/publisher.hpp"
#include "rclcpp_dds_examples/ping/subscriber.hpp"
#include "rclcpp_dds_examples/visibility_control.h"
/******************************************************************************
* PingPongPublisher implementation for std_msgs::msg::String
******************************************************************************/
class StringPingPublisher
: public rclcpp_dds_examples::PingPongPublisher<std_msgs::msg::String>
{
public:
RCLCPP_DDS_EXAMPLES_PUBLIC
explicit StringPingPublisher(const rclcpp::NodeOptions & options)
: PingPongPublisher("string_pub", options)
{
this->init_test();
}
protected:
virtual std_msgs::msg::String * alloc_sample()
{
return &msg_;
}
virtual void prepare_ping(std_msgs::msg::String & ping, const bool final)
{
if (final) {
ping.data(std::to_string(0));
return;
}
ping.data(std::to_string(this->ts_now()));
}
// Process received pong sample and return the timestamp
virtual void process_pong(
dds::sub::LoanedSamples<std_msgs::msg::String> & pong_samples,
uint64_t & pong_timestamp)
{
pong_timestamp = std::stoull(pong_samples[0].data().data(), nullptr, 0);
}
std_msgs::msg::String msg_;
};
RCLCPP_COMPONENTS_REGISTER_NODE(StringPingPublisher)
/******************************************************************************
* PingPongSubscriber implementation for std_msgs::msg::String
******************************************************************************/
class StringPingSubscriber
: public rclcpp_dds_examples::PingPongSubscriber<std_msgs::msg::String>
{
public:
RCLCPP_DDS_EXAMPLES_PUBLIC
explicit StringPingSubscriber(const rclcpp::NodeOptions & options)
: PingPongSubscriber("string_sub", options)
{
this->init_test();
}
protected:
virtual std_msgs::msg::String * alloc_sample()
{
return &msg_;
}
virtual void prepare_pong(
std_msgs::msg::String * const pong, const uint64_t ping_ts)
{
pong->data(std::to_string(ping_ts));
}
virtual void process_ping(
dds::sub::LoanedSamples<std_msgs::msg::String> & ping_samples,
uint64_t & ping_timestamp)
{
ping_timestamp = std::stoull(ping_samples[0].data().data(), nullptr, 0);
}
virtual void dump_ping(
dds::sub::LoanedSamples<std_msgs::msg::String> & ping_samples,
std::ostringstream & msg)
{
msg << ping_samples[0].data().data();
}
std_msgs::msg::String msg_;
};
RCLCPP_COMPONENTS_REGISTER_NODE(StringPingSubscriber)
| cpp |
rticonnextdds-robot-helpers | data/projects/rticonnextdds-robot-helpers/rclcpp_dds_examples/src/camera/camera_pub_flat.cpp | // Copyright 2021 Real-Time Innovations, Inc. (RTI)
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "rclcpp_dds_examples/visibility_control.h"
#include "rclcpp_dds_examples/ping/publisher.hpp"
#include "camera/CameraImageFlat.hpp"
#include "rclcpp_components/register_node_macro.hpp"
using rti::camera::flat::CameraImage;
namespace rclcpp_dds_examples
{
class CameraImagePublisherFlat
: public rclcpp_dds_examples::PingPongPublisher<CameraImage>
{
public:
RCLCPP_DDS_EXAMPLES_PUBLIC
explicit CameraImagePublisherFlat(const rclcpp::NodeOptions & options)
: PingPongPublisher("camera_pub_flat", options)
{
this->init_test();
}
protected:
virtual CameraImage * alloc_sample()
{
return writer_.extensions().get_loan();
}
virtual void prepare_ping(CameraImage & ping, const bool final)
{
auto sample = ping.root();
if (final) {
sample.timestamp(0);
return;
}
sample.format(rti::camera::common::Format::RGB);
sample.resolution().height(rti::camera::common::CAMERA_HEIGHT_DEFAULT);
sample.resolution().width(rti::camera::common::CAMERA_WIDTH_DEFAULT);
// Just set the first 4 bytes
for (int i = 0; i < 4; i++) {
uint8_t image_value = (48 + this->count_) % 124;
sample.data().set_element(i, image_value);
}
// Update timestamp
sample.timestamp(this->ts_now());
}
// Process received pong sample and return the timestamp
virtual void process_pong(
dds::sub::LoanedSamples<CameraImage> & pong_samples,
uint64_t & pong_timestamp)
{
pong_timestamp = pong_samples[0].data().root().timestamp();
}
};
} // namespace rclcpp_dds_examples
RCLCPP_COMPONENTS_REGISTER_NODE(rclcpp_dds_examples::CameraImagePublisherFlat)
| cpp |
rticonnextdds-robot-helpers | data/projects/rticonnextdds-robot-helpers/rclcpp_dds_examples/src/camera/camera_sub_plain.cpp | // Copyright 2021 Real-Time Innovations, Inc. (RTI)
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "rclcpp_dds_examples/visibility_control.h"
#include "rclcpp_dds_examples/ping/subscriber.hpp"
#include "camera/CameraImage.hpp"
#include "rclcpp_components/register_node_macro.hpp"
using rti::camera::plain::CameraImage;
namespace rclcpp_dds_examples
{
class CameraImageSubscriberPlain
: public rclcpp_dds_examples::PingPongSubscriber<CameraImage>
{
public:
RCLCPP_DDS_EXAMPLES_PUBLIC
explicit CameraImageSubscriberPlain(const rclcpp::NodeOptions & options)
: PingPongSubscriber("camera_sub_plain", options)
{
this->init_test();
}
protected:
virtual CameraImage * alloc_sample()
{
return &ping_msg_;
}
virtual void prepare_pong(CameraImage * const pong, const uint64_t ping_ts)
{
pong->timestamp(ping_ts);
}
virtual void process_ping(
dds::sub::LoanedSamples<CameraImage> & ping_samples,
uint64_t & ping_timestamp)
{
ping_timestamp = ping_samples[0].data().timestamp();
}
virtual void dump_ping(
dds::sub::LoanedSamples<CameraImage> & ping_samples,
std::ostringstream & msg)
{
auto & sample = ping_samples[0].data();
msg << "[" << sample.timestamp() << "] " << sample.format();
for (int i = 0; i < 4; i++) {
msg << "0x" <<
std::hex << std::uppercase <<
std::setfill('0') << std::setw(2) <<
static_cast<int>(sample.data()[i]) <<
std::nouppercase << std::dec <<
" ";
}
}
CameraImage ping_msg_;
};
} // namespace rclcpp_dds_examples
RCLCPP_COMPONENTS_REGISTER_NODE(rclcpp_dds_examples::CameraImageSubscriberPlain)
| cpp |
rticonnextdds-robot-helpers | data/projects/rticonnextdds-robot-helpers/rclcpp_dds_examples/src/camera/camera_pub_flat_zc.cpp | // Copyright 2021 Real-Time Innovations, Inc. (RTI)
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "rclcpp_dds_examples/visibility_control.h"
#include "rclcpp_dds_examples/ping/publisher.hpp"
#include "camera/CameraImageFlatZc.hpp"
#include "rclcpp_components/register_node_macro.hpp"
using rti::camera::flat_zc::CameraImage;
namespace rclcpp_dds_examples
{
class CameraImagePublisherFlatZc
: public rclcpp_dds_examples::PingPongPublisher<CameraImage>
{
public:
RCLCPP_DDS_EXAMPLES_PUBLIC
explicit CameraImagePublisherFlatZc(const rclcpp::NodeOptions & options)
: PingPongPublisher("camera_pub_flat_zc", options)
{
this->init_test();
}
protected:
virtual CameraImage * alloc_sample()
{
return writer_.extensions().get_loan();
}
virtual void prepare_ping(CameraImage & ping, const bool final)
{
auto sample = ping.root();
if (final) {
sample.timestamp(0);
return;
}
sample.format(rti::camera::common::Format::RGB);
sample.resolution().height(rti::camera::common::CAMERA_HEIGHT_DEFAULT);
sample.resolution().width(rti::camera::common::CAMERA_WIDTH_DEFAULT);
// Just set the first 4 bytes
for (int i = 0; i < 4; i++) {
uint8_t image_value = (48 + this->count_) % 124;
sample.data().set_element(i, image_value);
}
// Update timestamp
sample.timestamp(this->ts_now());
}
// Process received pong sample and return the timestamp
virtual void process_pong(
dds::sub::LoanedSamples<CameraImage> & pong_samples,
uint64_t & pong_timestamp)
{
pong_timestamp = pong_samples[0].data().root().timestamp();
}
};
} // namespace rclcpp_dds_examples
RCLCPP_COMPONENTS_REGISTER_NODE(rclcpp_dds_examples::CameraImagePublisherFlatZc)
| cpp |
rticonnextdds-robot-helpers | data/projects/rticonnextdds-robot-helpers/rclcpp_dds_examples/src/camera/camera_sub_flat_zc.cpp | // Copyright 2021 Real-Time Innovations, Inc. (RTI)
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "rclcpp_dds_examples/visibility_control.h"
#include "rclcpp_dds_examples/ping/subscriber.hpp"
#include "camera/CameraImageFlatZc.hpp"
#include "rclcpp_components/register_node_macro.hpp"
using rti::camera::flat_zc::CameraImage;
namespace rclcpp_dds_examples
{
class CameraImageSubscriberFlatZc
: public rclcpp_dds_examples::PingPongSubscriber<CameraImage>
{
public:
RCLCPP_DDS_EXAMPLES_PUBLIC
explicit CameraImageSubscriberFlatZc(const rclcpp::NodeOptions & options)
: PingPongSubscriber("camera_sub_flat_zc", options)
{
this->init_test();
}
protected:
virtual CameraImage * alloc_sample()
{
return writer_.extensions().get_loan();
}
virtual void prepare_pong(CameraImage * const pong, const uint64_t ping_ts)
{
pong->root().timestamp(ping_ts);
}
virtual void process_ping(
dds::sub::LoanedSamples<CameraImage> & ping_samples,
uint64_t & ping_timestamp)
{
ping_timestamp = ping_samples[0].data().root().timestamp();
}
virtual void dump_ping(
dds::sub::LoanedSamples<CameraImage> & ping_samples,
std::ostringstream & msg)
{
auto sample = ping_samples[0].data().root();
msg << "[" << sample.timestamp() << "] " << sample.format();
for (int i = 0; i < 4; i++) {
msg << "0x" <<
std::hex << std::uppercase <<
std::setfill('0') << std::setw(2) <<
static_cast<int>(sample.data().get_elements()[i]) <<
std::nouppercase << std::dec <<
" ";
}
}
};
} // namespace rclcpp_dds_examples
RCLCPP_COMPONENTS_REGISTER_NODE(rclcpp_dds_examples::CameraImageSubscriberFlatZc)
| cpp |
rticonnextdds-robot-helpers | data/projects/rticonnextdds-robot-helpers/rclcpp_dds_examples/src/camera/camera_sub_zc.cpp | // Copyright 2021 Real-Time Innovations, Inc. (RTI)
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "rclcpp_dds_examples/visibility_control.h"
#include "rclcpp_dds_examples/ping/subscriber.hpp"
#include "camera/CameraImageZc.hpp"
#include "rclcpp_components/register_node_macro.hpp"
using rti::camera::zc::CameraImage;
namespace rclcpp_dds_examples
{
class CameraImageSubscriberZc
: public rclcpp_dds_examples::PingPongSubscriber<CameraImage>
{
public:
RCLCPP_DDS_EXAMPLES_PUBLIC
explicit CameraImageSubscriberZc(const rclcpp::NodeOptions & options)
: PingPongSubscriber("camera_sub_zc", options)
{
this->init_test();
}
protected:
virtual CameraImage * alloc_sample()
{
return writer_.extensions().get_loan();
}
virtual void prepare_pong(CameraImage * const pong, const uint64_t ping_ts)
{
pong->timestamp(ping_ts);
}
virtual void process_ping(
dds::sub::LoanedSamples<CameraImage> & ping_samples,
uint64_t & ping_timestamp)
{
ping_timestamp = ping_samples[0].data().timestamp();
}
virtual void dump_ping(
dds::sub::LoanedSamples<CameraImage> & ping_samples,
std::ostringstream & msg)
{
auto & sample = ping_samples[0].data();
msg << "[" << sample.timestamp() << "] " << sample.format();
for (int i = 0; i < 4; i++) {
msg << "0x" <<
std::hex << std::uppercase <<
std::setfill('0') << std::setw(2) <<
static_cast<int>(sample.data()[i]) <<
std::nouppercase << std::dec <<
" ";
}
}
};
} // namespace rclcpp_dds_examples
RCLCPP_COMPONENTS_REGISTER_NODE(rclcpp_dds_examples::CameraImageSubscriberZc)
| cpp |
rticonnextdds-robot-helpers | data/projects/rticonnextdds-robot-helpers/rclcpp_dds_examples/src/camera/camera_pub_plain.cpp | // Copyright 2021 Real-Time Innovations, Inc. (RTI)
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "rclcpp_dds_examples/visibility_control.h"
#include "rclcpp_dds_examples/ping/publisher.hpp"
#include "camera/CameraImage.hpp"
#include "rclcpp_components/register_node_macro.hpp"
using rti::camera::plain::CameraImage;
namespace rclcpp_dds_examples
{
class CameraImagePublisherPlain
: public rclcpp_dds_examples::PingPongPublisher<CameraImage>
{
public:
RCLCPP_DDS_EXAMPLES_PUBLIC
explicit CameraImagePublisherPlain(const rclcpp::NodeOptions & options)
: PingPongPublisher("camera_pub_plain", options)
{
this->init_test();
}
protected:
virtual CameraImage * alloc_sample()
{
return &ping_msg_;
}
virtual void prepare_ping(CameraImage & sample, const bool final)
{
if (final) {
sample.timestamp(0);
return;
}
sample.format(rti::camera::common::Format::RGB);
sample.resolution().height(rti::camera::common::CAMERA_HEIGHT_DEFAULT);
sample.resolution().width(rti::camera::common::CAMERA_WIDTH_DEFAULT);
// Just set the first 4 bytes
for (int i = 0; i < 4; i++) {
uint8_t image_value = (48 + this->count_) % 124;
sample.data()[i] = image_value;
}
// Update timestamp
sample.timestamp(this->ts_now());
}
// Process received pong sample and return the timestamp
virtual void process_pong(
dds::sub::LoanedSamples<CameraImage> & pong_samples,
uint64_t & pong_timestamp)
{
pong_timestamp = pong_samples[0].data().timestamp();
}
CameraImage ping_msg_;
};
} // namespace rclcpp_dds_examples
RCLCPP_COMPONENTS_REGISTER_NODE(rclcpp_dds_examples::CameraImagePublisherPlain)
| cpp |
rticonnextdds-robot-helpers | data/projects/rticonnextdds-robot-helpers/rclcpp_dds_examples/src/camera/camera_sub_flat.cpp | // Copyright 2021 Real-Time Innovations, Inc. (RTI)
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "rclcpp_dds_examples/visibility_control.h"
#include "rclcpp_dds_examples/ping/subscriber.hpp"
#include "camera/CameraImageFlat.hpp"
#include "rclcpp_components/register_node_macro.hpp"
using rti::camera::flat::CameraImage;
namespace rclcpp_dds_examples
{
class CameraImageSubscriberFlat
: public rclcpp_dds_examples::PingPongSubscriber<CameraImage>
{
public:
RCLCPP_DDS_EXAMPLES_PUBLIC
explicit CameraImageSubscriberFlat(const rclcpp::NodeOptions & options)
: PingPongSubscriber("camera_sub_flat", options)
{
this->init_test();
}
protected:
virtual CameraImage * alloc_sample()
{
return writer_.extensions().get_loan();
}
virtual void prepare_pong(CameraImage * const pong, const uint64_t ping_ts)
{
pong->root().timestamp(ping_ts);
}
virtual void process_ping(
dds::sub::LoanedSamples<CameraImage> & ping_samples,
uint64_t & ping_timestamp)
{
ping_timestamp = ping_samples[0].data().root().timestamp();
}
virtual void dump_ping(
dds::sub::LoanedSamples<CameraImage> & ping_samples,
std::ostringstream & msg)
{
auto sample = ping_samples[0].data().root();
msg << "[" << sample.timestamp() << "] " << sample.format();
for (int i = 0; i < 4; i++) {
msg << "0x" <<
std::hex << std::uppercase <<
std::setfill('0') << std::setw(2) <<
static_cast<int>(sample.data().get_elements()[i]) <<
std::nouppercase << std::dec <<
" ";
}
}
};
} // namespace rclcpp_dds_examples
RCLCPP_COMPONENTS_REGISTER_NODE(rclcpp_dds_examples::CameraImageSubscriberFlat)
| cpp |
rticonnextdds-robot-helpers | data/projects/rticonnextdds-robot-helpers/rclcpp_dds_examples/src/camera/camera_pub_zc.cpp | // Copyright 2021 Real-Time Innovations, Inc. (RTI)
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "rclcpp_dds_examples/visibility_control.h"
#include "rclcpp_dds_examples/ping/publisher.hpp"
#include "camera/CameraImageZc.hpp"
#include "rclcpp_components/register_node_macro.hpp"
using rti::camera::zc::CameraImage;
namespace rclcpp_dds_examples
{
class CameraImagePublisherZc
: public rclcpp_dds_examples::PingPongPublisher<CameraImage>
{
public:
RCLCPP_DDS_EXAMPLES_PUBLIC
explicit CameraImagePublisherZc(const rclcpp::NodeOptions & options)
: PingPongPublisher("camera_pub_zc", options)
{
this->init_test();
}
protected:
virtual CameraImage * alloc_sample()
{
return writer_.extensions().get_loan();
}
virtual void prepare_ping(CameraImage & sample, const bool final)
{
if (final) {
sample.timestamp(0);
return;
}
sample.format(rti::camera::common::Format::RGB);
sample.resolution().height(rti::camera::common::CAMERA_HEIGHT_DEFAULT);
sample.resolution().width(rti::camera::common::CAMERA_WIDTH_DEFAULT);
// Just set the first 4 bytes
for (int i = 0; i < 4; i++) {
uint8_t image_value = (48 + this->count_) % 124;
sample.data()[i] = image_value;
}
// Update timestamp
sample.timestamp(this->ts_now());
}
// Process received pong sample and return the timestamp
virtual void process_pong(
dds::sub::LoanedSamples<CameraImage> & pong_samples,
uint64_t & pong_timestamp)
{
pong_timestamp = pong_samples[0].data().timestamp();
}
};
} // namespace rclcpp_dds_examples
RCLCPP_COMPONENTS_REGISTER_NODE(rclcpp_dds_examples::CameraImagePublisherZc)
| cpp |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.