repo_name
stringclasses 10
values | file_path
stringlengths 29
222
| content
stringlengths 24
926k
| extention
stringclasses 5
values |
---|---|---|---|
rticonnextdds-examples | data/projects/rticonnextdds-examples/persistence_service/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 <algorithm>
#include <cstdlib>
#include <iostream>
#include "hello_world.hpp"
#include <dds/dds.hpp>
#include <rti/core/ListenerBinder.hpp>
using namespace dds::core;
using namespace dds::core::status;
using namespace dds::domain;
using namespace dds::topic;
using namespace dds::sub;
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 ¶m = 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/persistence_service/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 "hello_world.hpp"
#include <dds/dds.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 ¶m = 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/polling_read/c++/poll_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.
******************************************************************************/
/* poll_publisher.cxx
A publication of data of type poll
This file is derived from code automatically generated by the rtiddsgen
command:
rtiddsgen -language C++ -example <arch> poll.idl
Example publication of type poll 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>/poll_subscriber <domain_id> <sample_count>
(3) Start the publication with the command
objs/<arch>/poll_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>/poll_publisher <domain_id> o
objs/<arch>/poll_subscriber <domain_id>
On Windows:
objs\<arch>\poll_publisher <domain_id>
objs\<arch>\poll_subscriber <domain_id>
modification history
------------ -------
*/
#include <stdio.h>
#include <stdlib.h>
#ifdef RTI_VX653
#include <vThreadsData.h>
#endif
#include "poll.h"
#include "pollSupport.h"
#include "ndds/ndds_cpp.h"
#include <ctime>
/* 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;
pollDataWriter * poll_writer = NULL;
poll *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 = pollTypeSupport::get_type_name();
retcode = pollTypeSupport::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 poll",
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;
}
poll_writer = pollDataWriter::narrow(writer);
if (poll_writer == NULL) {
printf("DataWriter narrow error\n");
publisher_shutdown(participant);
return -1;
}
/* Create data sample for writing */
instance = pollTypeSupport::create_data();
if (instance == NULL) {
printf("pollTypeSupport::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 = poll_writer->register_instance(*instance);
*/
/* Initialize random seed before entering the loop */
srand(time(NULL));
/* Main loop */
for (count=0; (sample_count == 0) || (count < sample_count); ++count) {
/* Modify the data to be written here */
/* Set x to a random number between 0 and 9 */
instance->x = (int)(rand()/(RAND_MAX/10.0));
printf("Writing poll, count %d, x = %d\n", count, instance->x);
retcode = poll_writer->write(*instance, instance_handle);
if (retcode != DDS_RETCODE_OK) {
printf("write error %d\n", retcode);
}
NDDSUtility::sleep(send_period);
}
/*
retcode = poll_writer->unregister_instance(
*instance, instance_handle);
if (retcode != DDS_RETCODE_OK) {
printf("unregister instance error %d\n", retcode);
}
*/
/* Delete data sample */
retcode = pollTypeSupport::delete_data(instance);
if (retcode != DDS_RETCODE_OK) {
printf("pollTypeSupport::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/polling_read/c++/poll_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.
******************************************************************************/
/* poll_subscriber.cxx
A subscription example
This file is derived from code automatically generated by the rtiddsgen
command:
rtiddsgen -language C++ -example <arch> poll.idl
Example subscription of type poll 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>/poll_subscriber <domain_id> <sample_count>
(3) Start the publication with the command
objs/<arch>/poll_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>/poll_publisher <domain_id>
objs/<arch>/poll_subscriber <domain_id>
On Windows:
objs\<arch>\poll_publisher <domain_id>
objs\<arch>\poll_subscriber <domain_id>
modification history
------------ -------
*/
#include <stdio.h>
#include <stdlib.h>
#ifdef RTI_VX653
#include <vThreadsData.h>
#endif
#include "poll.h"
#include "pollSupport.h"
#include "ndds/ndds_cpp.h"
/* We remove all the listener code as we won't use any listener */
/* Delete all entities */
static int subscriber_shutdown(
DDSDomainParticipant *participant)
{
DDS_ReturnCode_t retcode;
int status = 0;
if (participant != NULL) {
retcode = participant->delete_contained_entities();
if (retcode != DDS_RETCODE_OK) {
printf("delete_contained_entities error %d\n", retcode);
status = -1;
}
retcode = DDSTheParticipantFactory->delete_participant(participant);
if (retcode != DDS_RETCODE_OK) {
printf("delete_participant error %d\n", retcode);
status = -1;
}
}
/* RTI Connext provides the finalize_instance() method on
domain participant factory for people who want to release memory used
by the participant factory. Uncomment the following block of code for
clean destruction of the singleton. */
/*
retcode = DDSDomainParticipantFactory::finalize_instance();
if (retcode != DDS_RETCODE_OK) {
printf("finalize_instance error %d\n", retcode);
status = -1;
}
*/
return status;
}
extern "C" int subscriber_main(int domainId, int sample_count)
{
DDSDomainParticipant *participant = NULL;
DDSSubscriber *subscriber = NULL;
DDSTopic *topic = NULL;
DDSDataReader *reader = NULL;
DDS_ReturnCode_t retcode;
const char *type_name = NULL;
int count = 0;
/* Poll for new samples every 5 seconds */
DDS_Duration_t receive_period = {5,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 = pollTypeSupport::get_type_name();
retcode = pollTypeSupport::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 poll",
type_name, DDS_TOPIC_QOS_DEFAULT, NULL /* listener */,
DDS_STATUS_MASK_NONE);
if (topic == NULL) {
printf("create_topic error\n");
subscriber_shutdown(participant);
return -1;
}
/* Call create_datareader passing NULL in the listener parameter */
reader = subscriber->create_datareader(
topic, DDS_DATAREADER_QOS_DEFAULT, NULL,
DDS_STATUS_MASK_ALL);
if (reader == NULL) {
printf("create_datareader error\n");
subscriber_shutdown(participant);
return -1;
}
/* If you want to change datareader_qos.history.kind 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. */
/*
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.history.kind = DDS_KEEP_ALL_HISTORY_QOS;
reader = subscriber->create_datareader(
topic, datareader_qos, NULL,
DDS_STATUS_MASK_ALL);
if (reader == NULL) {
printf("create_datareader error\n");
subscriber_shutdown(participant);
return -1;
}
*/
pollDataReader *poll_reader = pollDataReader::narrow(reader);
if (poll_reader == NULL) {
printf("DataReader narrow error\n");
return -1;
}
/* Main loop */
for (count=0; (sample_count == 0) || (count < sample_count); ++count) {
NDDSUtility::sleep(receive_period);
DDS_SampleInfoSeq info_seq;
pollSeq data_seq;
/* Check for new data calling the DataReader's take() method */
retcode = poll_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) {
/// Not an error
continue;
} else if (retcode != DDS_RETCODE_OK) {
// Is an error
printf("take error: %d\n", retcode);
break;
}
int len = 0;
double sum = 0;
/* Iterate through the samples read using the take() method, getting
* the number of samples got and, adding the value of x on each of
* them to calculate the average afterwards. */
for (int i = 0; i < data_seq.length(); ++i) {
if (!info_seq[i].valid_data)
continue;
len ++;
sum += data_seq[i].x;
}
if (len > 0)
printf("Got %d samples. Avg = %.1f\n", len, sum/len);
retcode = poll_reader->return_loan(data_seq, info_seq);
if (retcode != DDS_RETCODE_OK) {
printf("return loan error %d\n", retcode);
}
}
/* Delete all entities */
status = subscriber_shutdown(participant);
return status;
}
#if defined(RTI_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/polling_read/c/poll_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.
******************************************************************************/
/* poll_publisher.c
A publication of data of type poll
This file is derived from code automatically generated by the rtiddsgen
command:
rtiddsgen -language C -example <arch> poll.idl
Example publication of type poll 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>/poll_subscriber <domain_id> <sample_count>
(3) Start the publication with the command
objs/<arch>/poll_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>/poll_publisher <domain_id>
objs/<arch>/poll_subscriber <domain_id>
On Windows:
objs\<arch>\poll_publisher <domain_id>
objs\<arch>\poll_subscriber <domain_id>
modification history
------------ -------
*/
#include <stdio.h>
#include <stdlib.h>
#include "ndds/ndds_c.h"
#include "poll.h"
#include "pollSupport.h"
#include <time.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;
pollDataWriter *poll_writer = NULL;
poll *instance = NULL;
DDS_ReturnCode_t retcode;
DDS_InstanceHandle_t instance_handle = DDS_HANDLE_NIL;
const char *type_name = NULL;
int count = 0;
/* Send a new sample every second */
struct DDS_Duration_t send_period = {1,0};
/* 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 = pollTypeSupport_get_type_name();
retcode = pollTypeSupport_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 poll",
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;
}
poll_writer = pollDataWriter_narrow(writer);
if (poll_writer == NULL) {
printf("DataWriter narrow error\n");
publisher_shutdown(participant);
return -1;
}
/* Create data sample for writing */
instance = pollTypeSupport_create_data_ex(DDS_BOOLEAN_TRUE);
if (instance == NULL) {
printf("pollTypeSupport_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 = pollDataWriter_register_instance(
poll_writer, instance);
*/
/* Initialize random seed before entering the loop */
srand(time(NULL));
/* Main loop */
for (count=0; (sample_count == 0) || (count < sample_count); ++count) {
/* Modify the data to be written here */
/* Set x to a random number between 0 and 9 */
instance->x = (int)(rand()/(RAND_MAX/10.0));
printf("Writing poll, count %d, x = %d\n", count, instance->x);
/* Write data */
retcode = pollDataWriter_write(
poll_writer, instance, &instance_handle);
if (retcode != DDS_RETCODE_OK) {
printf("write error %d\n", retcode);
}
NDDS_Utility_sleep(&send_period);
}
/*
retcode = pollDataWriter_unregister_instance(
poll_writer, instance, &instance_handle);
if (retcode != DDS_RETCODE_OK) {
printf("unregister instance error %d\n", retcode);
}
*/
/* Delete data sample */
retcode = pollTypeSupport_delete_data_ex(instance, DDS_BOOLEAN_TRUE);
if (retcode != DDS_RETCODE_OK) {
printf("pollTypeSupport_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/polling_read/c/poll_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.
******************************************************************************/
/* poll_subscriber.c
A subscription example
This file is derived from code automatically generated by the rtiddsgen
command:
rtiddsgen -language C -example <arch> poll.idl
Example subscription of type poll 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>/poll_subscriber <domain_id> <sample_count>
(3) Start the publication with the command
objs/<arch>/poll_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>/poll_publisher <domain_id>
objs/<arch>/poll_subscriber <domain_id>
On Windows systems:
objs\<arch>\poll_publisher <domain_id>
objs\<arch>\poll_subscriber <domain_id>
modification history
------------ -------
*/
#include <stdio.h>
#include <stdlib.h>
#include "ndds/ndds_c.h"
#include "poll.h"
#include "pollSupport.h"
/* We remove all the listener code as we won't use any listener */
/* Delete all entities */
static int subscriber_shutdown(
DDS_DomainParticipant *participant)
{
DDS_ReturnCode_t retcode;
int status = 0;
if (participant != NULL) {
retcode = DDS_DomainParticipant_delete_contained_entities(participant);
if (retcode != DDS_RETCODE_OK) {
printf("delete_contained_entities error %d\n", retcode);
status = -1;
}
retcode = DDS_DomainParticipantFactory_delete_participant(
DDS_TheParticipantFactory, participant);
if (retcode != DDS_RETCODE_OK) {
printf("delete_participant error %d\n", retcode);
status = -1;
}
}
/* RTI Connext provides the finalize_instance() method on
domain participant factory for users who want to release memory used
by the participant factory. Uncomment the following block of code for
clean destruction of the singleton. */
/*
retcode = DDS_DomainParticipantFactory_finalize_instance();
if (retcode != DDS_RETCODE_OK) {
printf("finalize_instance error %d\n", retcode);
status = -1;
}
*/
return status;
}
static int subscriber_main(int domainId, int sample_count)
{
DDS_DomainParticipant *participant = NULL;
DDS_Subscriber *subscriber = NULL;
DDS_Topic *topic = NULL;
struct DDS_DataReaderListener reader_listener =
DDS_DataReaderListener_INITIALIZER;
DDS_DataReader *reader = NULL;
pollDataReader *poll_reader = NULL;
DDS_ReturnCode_t retcode;
const char *type_name = NULL;
int count = 0;
/* Poll for new samples every 5 seconds */
struct DDS_Duration_t poll_period = {5,0};
/* We need to change the datareader_qos for this example.
* If you want to do it programmatically, you will need to declare to
* use the following struct.*/
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 = pollTypeSupport_get_type_name();
retcode = pollTypeSupport_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 poll",
type_name, &DDS_TOPIC_QOS_DEFAULT, NULL /* listener */,
DDS_STATUS_MASK_NONE);
if (topic == NULL) {
printf("create_topic error\n");
subscriber_shutdown(participant);
return -1;
}
/* Call create_datareader passing NULL in the listener parameter */
reader = DDS_Subscriber_create_datareader(
subscriber, DDS_Topic_as_topicdescription(topic),
&DDS_DATAREADER_QOS_DEFAULT, NULL, DDS_STATUS_MASK_ALL);
if (reader == NULL) {
printf("create_datareader error\n");
subscriber_shutdown(participant);
return -1;
}
/* If you want to change datareader_qos.history.kind 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. */
/*
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.history.kind = DDS_KEEP_ALL_HISTORY_QOS;
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;
}
*/
poll_reader = pollDataReader_narrow(reader);
if (poll_reader == NULL) {
printf("DataReader narrow error\n");
return -1;
}
/* Main loop */
for (count=0; (sample_count == 0) || (count < sample_count); ++count) {
struct DDS_SampleInfoSeq info_seq;
struct pollSeq data_seq;
int i, len;
double sum;
DDS_ReturnCode_t retcode;
NDDS_Utility_sleep(&poll_period);
/* Check for new data calling the DataReader's take() method */
retcode = pollDataReader_take(
poll_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) {
/* Not an error */
continue;
} else if (retcode != DDS_RETCODE_OK) {
/* Is an error */
printf("take error: %d\n", retcode);
break;
}
sum = 0;
len = 0;
/* Iterate through the samples read using the take() method, getting
* the number of samples got and, adding the value of x on each of
* them to calculate the average afterwards. */
for (i = 0; i < pollSeq_get_length(&data_seq); ++i) {
if (DDS_SampleInfoSeq_get_reference(&info_seq, i)->valid_data) {
len++;
sum += pollSeq_get_reference(&data_seq, i)->x;
}
}
if (len > 0)
printf("Got %d samples. Avg = %.1f\n", len, sum/len);
retcode = pollDataReader_return_loan(
poll_reader, &data_seq, &info_seq);
if (retcode != DDS_RETCODE_OK) {
printf("return loan error %d\n", retcode);
}
}
/* Cleanup and delete all entities */
return subscriber_shutdown(participant);
}
#if defined(RTI_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/polling_read/c++03/poll_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 "poll.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<poll> topic (participant, "Example poll");
// Create a DataWriter with default Qos (Publisher created in-line)
DataWriter<poll> writer(Publisher(participant), topic);
poll sample;
for (int count = 0; count < sample_count || sample_count == 0; count++) {
// Set x to a random number between 0 and 9.
sample.x((int)(rand() / (RAND_MAX/10.0)));
std::cout << "Writing poll, count " << count << ", x = " << sample.x()
<< std::endl;
writer.write(sample);
rti::util::sleep(Duration(1));
}
}
int main(int argc, char *argv[])
{
int domain_id = 0;
int sample_count = 0; // Infinite loop
if (argc >= 2) {
domain_id = atoi(argv[1]);
}
if (argc >= 3) {
sample_count = atoi(argv[2]);
}
// To turn on additional logging, include <rti/config/Logger.hpp> and
// uncomment the following line:
// rti::config::Logger::instance().verbosity(rti::config::Verbosity::STATUS_ALL);
try {
publisher_main(domain_id, sample_count);
} catch (const std::exception& ex) {
// 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/polling_read/c++03/poll_subscriber.cxx | /*******************************************************************************
(c) 2005-2015 Copyright, Real-Time Innovations, Inc. All rights reserved.
RTI grants Licensee a license to use, modify, compile, and create derivative
works of the Software. Licensee has the right to distribute object form only
for use with RTI products. The Software is provided "as is", with no warranty
of any type, including any warranty for fitness for any purpose. RTI is under
no obligation to maintain or support the Software. RTI shall not be liable for
any incidental or consequential damages arising out of the use or inability to
use the software.
******************************************************************************/
#include <algorithm>
#include <iostream>
#include <dds/dds.hpp>
#include "poll.hpp"
using namespace dds::core;
using namespace dds::domain;
using namespace dds::topic;
using namespace dds::sub;
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<poll> topic(participant, "Example poll");
// Create a DataReader with default Qos (Subscriber created in-line)
DataReader<poll> reader(Subscriber(participant), topic);
std::cout << std::fixed;
for (int count = 0; sample_count == 0 || count < sample_count; ++count) {
// Poll for new data every 5 seconds.
rti::util::sleep(Duration(5));
// Check for new data calling the DataReader's take() method.
LoanedSamples<poll> samples = reader.take();
// Iterate through the samples read using the 'take()' method and
// adding the value of x on each of them to calculate the average
// afterwards.
double sum = 0;
for (LoanedSamples<poll>::iterator sample_it = samples.begin();
sample_it != samples.end();
sample_it++) {
if (sample_it->info().valid()){
sum += sample_it->data().x();
}
}
if (samples.length() > 0) {
std::cout << "Got " << samples.length() << " samples. "
<< "Avg = " << sum / samples.length() << 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 (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_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 <sys/select.h>
#include <semaphore.h>
#include <pthread.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");
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 sampli_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_RoutingServiceFileAdpater_checking_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, "ReadPeriod");
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, "SamplesPerRead");
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, "WriteMode");
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 WriteMode (%s). "
"Allowed values: keep (default), overwrite, append",
mode_property);
return NULL;
}
} else {
mode_property = "keep";
}
/* Get the configuration properties in <route>/<output>/<property> */
flush_property = RTI_RoutingServiceProperties_lookup_property(
properties, "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,
"sleepPeriod");
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,"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,"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,"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_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<stdio.h>
#include<sys/types.h>
#include<sys/stat.h>
#include<dirent.h>
#include<string.h>
#include<stdlib.h>
#include<unistd.h>
#include<pthread.h>
#include"directory_reading.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 discover 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_RoutingServiceFileAdpater_checking_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 discoveryData 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");
}
/*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");
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 file in the directory "
"you can have!\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 ");
}
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_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
/* ========================================================================= */
/* */
/* 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_daata 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_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 <stdio.h>
#include <string.h>
#include <ctype.h>
#include "line_conversion.h"
#include "data_structures.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");
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_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 <stdio.h>
#include <string.h>
#include "ndds/ndds_c.h"
#include "routingservice/routingservice_adapter.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_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_RoutingServiceFileAdpater_checking_thread(void* arg);
#endif /* DIRECTORYREADING_H_ */
| h |
rticonnextdds-examples | data/projects/rticonnextdds-examples/custom_flow_controller/c++/cfc_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.
******************************************************************************/
/* cfc_subscriber.cxx
A subscription example
This file is derived from code automatically generated by the rtiddsgen
command:
rtiddsgen -language C++ -example <arch> cfc.idl
Example subscription of type cfc 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>/cfc_subscriber <domain_id> <sample_count>
(3) Start the publication with the command
objs/<arch>/cfc_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>/cfc_publisher <domain_id>
objs/<arch>/cfc_subscriber <domain_id>
On Windows:
objs\<arch>\cfc_publisher <domain_id>
objs\<arch>\cfc_subscriber <domain_id>
modification history
------------ -------
*/
#include <stdio.h>
#include <stdlib.h>
#ifdef RTI_VX653
#include <vThreadsData.h>
#endif
#include "cfc.h"
#include "cfcSupport.h"
#include "ndds/ndds_cpp.h"
/* Changes for Custom_Flowcontroller */
/* For timekeeping */
#include <time.h>
clock_t init;
class cfcListener: 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 cfcListener::on_data_available(DDSDataReader* reader) {
cfcDataReader *cfc_reader = NULL;
cfcSeq data_seq;
DDS_SampleInfoSeq info_seq;
DDS_ReturnCode_t retcode;
int i;
cfc_reader = cfcDataReader::narrow(reader);
if (cfc_reader == NULL) {
printf("DataReader narrow error\n");
return;
}
retcode = cfc_reader->take(data_seq, info_seq, DDS_LENGTH_UNLIMITED,
DDS_ANY_SAMPLE_STATE, DDS_ANY_VIEW_STATE, DDS_ANY_INSTANCE_STATE);
if (retcode == DDS_RETCODE_NO_DATA) {
return;
} else if (retcode != DDS_RETCODE_OK) {
printf("take error %d\n", retcode);
return;
}
for (i = 0; i < data_seq.length(); ++i) {
if (info_seq[i].valid_data) {
/* Start changes for Custom_Flowcontroller */
/* print the time we get each sample. */
double elapsed_ticks = clock() - init;
double elapsed_secs = elapsed_ticks / CLOCKS_PER_SEC;
printf("@ t=%.2fs, got x = %d\n", elapsed_secs, data_seq[i].x);
/* End changes for Custom_Flowcontroller */
}
}
retcode = cfc_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;
cfcListener *reader_listener = NULL;
DDSDataReader *reader = NULL;
DDS_ReturnCode_t retcode;
const char *type_name = NULL;
int count = 0;
DDS_Duration_t receive_period = { 1, 0 };
int status = 0;
/* Start changes for Custom_Flowcontroller */
/* for timekeeping */
init = clock();
/* 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;
}
/* If you want to change the Participant'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_participant call above.
*/
/* By default, discovery will communicate via shared memory for platforms
* that support it. Because we disable shared memory on the publishing
* side, we do so here to ensure the reader and writer discover each other.
*/
/* Get default participant QoS to customize */
/* DDS_DomainParticipantQos participant_qos;
retcode = DDSTheParticipantFactory->get_default_participant_qos(
participant_qos);
if (retcode != DDS_RETCODE_OK) {
printf("get_default_participant_qos error\n");
return -1;
}
participant_qos.transport_builtin.mask = DDS_TRANSPORTBUILTIN_UDPv4;
*/ /* To create participant with default QoS, use DDS_PARTICIPANT_QOS_DEFAULT
instead of participant_qos */
/* participant = DDSTheParticipantFactory->create_participant(domainId,
participant_qos, NULL, DDS_STATUS_MASK_NONE);
if (participant == NULL) {
printf("create_participant error\n");
subscriber_shutdown(participant);
return -1;
}
*/
/* End changes for custom_flowcontroller */
/* To customize the subscriber QoS, use
the configuration file USER_QOS_PROFILES.xml */
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;
}
/* Register the type before creating the topic */
type_name = cfcTypeSupport::get_type_name();
retcode = cfcTypeSupport::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 cfc", 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 cfcListener();
/* 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) {
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/custom_flow_controller/c++/cfc_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.
******************************************************************************/
/* cfc_publisher.cxx
A publication of data of type cfc
This file is derived from code automatically generated by the rtiddsgen
command:
rtiddsgen -language C++ -example <arch> cfc.idl
Example publication of type cfc 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>/cfc_subscriber <domain_id> <sample_count>
(3) Start the publication with the command
objs/<arch>/cfc_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>/cfc_publisher <domain_id> o
objs/<arch>/cfc_subscriber <domain_id>
On Windows:
objs\<arch>\cfc_publisher <domain_id>
objs\<arch>\cfc_subscriber <domain_id>
modification history
------------ -------
*/
#include <stdio.h>
#include <stdlib.h>
#ifdef RTI_VX653
#include <vThreadsData.h>
#endif
#include "cfc.h"
#include "cfcSupport.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;
cfcDataWriter * cfc_writer = NULL;
cfc *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 };
int i;
int sample;
const char* cfc_name = "custom_flowcontroller";
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 changes for custom_flowcontroller */
/* If you want to change the Participant'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_participant call above.
*/
/* Get default participant QoS to customize */
/* DDS_DomainParticipantQos participant_qos;
retcode = DDSTheParticipantFactory->get_default_participant_qos(
participant_qos);
if (retcode != DDS_RETCODE_OK) {
printf("get_default_participant_qos error\n");
return -1;
}
*/ /* By default, data will be sent via shared memory _and_ UDPv4. Because
* the flowcontroller limits writes across all interfaces, this halves the
* effective send rate. To avoid this, we enable only the UDPv4 transport
*/
/* participant_qos.transport_builtin.mask = DDS_TRANSPORTBUILTIN_UDPv4;
*/ /* To create participant with default QoS, use DDS_PARTICIPANT_QOS_DEFAULT
instead of participant_qos */
/* participant = DDSTheParticipantFactory->create_participant(domainId,
participant_qos, NULL, DDS_STATUS_MASK_NONE);
if (participant == NULL) {
printf("create_participant error\n");
publisher_shutdown(participant);
return -1;
}
*/
/* End changes for custom_flowcontroller
/* 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 = cfcTypeSupport::get_type_name();
retcode = cfcTypeSupport::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 cfc", 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;
}
/* Start changes for custom_flowcontroller */
/* 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 create the flowcontroller and the neccesary QoS
* for the datawriter.
*/
/* DDS_FlowControllerProperty_t custom_fcp;
retcode = participant->get_default_flowcontroller_property(custom_fcp);
if (retcode != DDS_RETCODE_OK) {
printf("get_default_flowcontroller_property error \n");
return -1;
}
*/ /* Don't allow too many tokens to accumulate */
/* custom_fcp.token_bucket.max_tokens =
custom_fcp.token_bucket.tokens_added_per_period = 2;
custom_fcp.token_bucket.tokens_leaked_per_period = DDS_LENGTH_UNLIMITED;
*/ /* 100ms */
/* custom_fcp.token_bucket.period.sec = 0;
custom_fcp.token_bucket.period.nanosec = 100000000;
*/ /* The sample size is 1000, but the minimum bytes_per_token is 1024.
* Furthermore, we want to allow some overhead.
*/
/* custom_fcp.token_bucket.bytes_per_token = 1024;
*/ /* So, in summary, each token can be used to send about one message,
* and we get 2 tokens every 100ms, so this limits transmissions to
* about 20 messages per second.
*/
/* Create flowcontroller and set properties */
/* DDSFlowController* cfc = NULL;
cfc = participant->create_flowcontroller(DDS_String_dup(cfc_name),
custom_fcp);
if (cfc == NULL) {
printf("create_flowcontroller error\n");
return -1;
}
*/ /* Get default datawriter QoS to customize */
/* 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;
}
*/ /* As an alternative to increasing h istory depth, we can just
* set the qos to keep all samples
*/
/* datawriter_qos.history.kind = DDS_KEEP_ALL_HISTORY_QOS;
*/ /* Set flowcontroller for datawriter */
/* datawriter_qos.publish_mode.kind = DDS_ASYNCHRONOUS_PUBLISH_MODE_QOS;
datawriter_qos.publish_mode.flow_controller_name = DDS_String_dup(cfc_name);
*/ /* To create datawriter with default QoS, use DDS_DATAWRITER_QOS_DEFAULT
instead of datawriter_qos */
/* 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;
}
*/
/* End changes for custom_flowcontroller */
cfc_writer = cfcDataWriter::narrow(writer);
if (cfc_writer == NULL) {
printf("DataWriter narrow error\n");
publisher_shutdown(participant);
return -1;
}
/* Create data sample for writing */
instance = cfcTypeSupport::create_data();
if (instance == NULL) {
printf("cfcTypeSupport::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 = cfc_writer->register_instance(*instance);
*/
/* Main loop */
for (count = 0; (sample_count == 0) || (count < sample_count); ++count) {
/* Changes for custom_flowcontroller */
/* Simulate bursty writer */
NDDSUtility::sleep(send_period);
for (i = 0; i < 10; ++i) {
sample = count * 10 + i;
printf("Writing cfc, sample %d\n", sample);
instance->x = sample;
memset(instance->str, 1, 999);
instance->str[999] = 0;
retcode = cfc_writer->write(*instance, instance_handle);
if (retcode != DDS_RETCODE_OK) {
printf("write error %d\n", retcode);
}
}
}
/* This new sleep it is for let time to the subscriber to read all the
* sent samples.
*/
send_period.sec = 4;
NDDS_Utility_sleep(&send_period);
/*
retcode = cfc_writer->unregister_instance(
*instance, instance_handle);
if (retcode != DDS_RETCODE_OK) {
printf("unregister instance error %d\n", retcode);
}
*/
/* Delete data sample */
retcode = cfcTypeSupport::delete_data(instance);
if (retcode != DDS_RETCODE_OK) {
printf("cfcTypeSupport::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/custom_flow_controller/c/cfc_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.
******************************************************************************/
/* cfc_publisher.c
A publication of data of type cfc
This file is derived from code automatically generated by the rtiddsgen
command:
rtiddsgen -language C -example <arch> cfc.idl
Example publication of type cfc 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>/cfc_subscriber <domain_id> <sample_count>
(3) Start the publication with the command
objs/<arch>/cfc_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>/cfc_publisher <domain_id>
objs/<arch>/cfc_subscriber <domain_id>
On Windows:
objs\<arch>\cfc_publisher <domain_id>
objs\<arch>\cfc_subscriber <domain_id>
modification history
------------ -------
*/
#include <stdio.h>
#include <stdlib.h>
#include "ndds/ndds_c.h"
#include "cfc.h"
#include "cfcSupport.h"
/* Delete all entities */
static int publisher_shutdown(DDS_DomainParticipant *participant,
struct DDS_DomainParticipantQos *participant_qos,
struct DDS_DataWriterQos *datawriter_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_DomainParticipantQos_finalize(participant_qos);
if (retcode != DDS_RETCODE_OK) {
printf("participantQos_finalize error %d\n", retcode);
status = -1;
}
retcode = DDS_DataWriterQos_finalize(datawriter_qos);
if (retcode != DDS_RETCODE_OK) {
printf("dataWriterQos_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;
cfcDataWriter *cfc_writer = NULL;
cfc *instance = NULL;
DDS_ReturnCode_t retcode;
DDS_InstanceHandle_t instance_handle = DDS_HANDLE_NIL;
const char *type_name = NULL;
int count = 0;
int i;
int sample;
struct DDS_Duration_t send_period = { 1, 0 };
const char* cfc_name = "custom_flowcontroller";
struct DDS_FlowControllerProperty_t custom_fcp;
DDS_FlowController* cfc = NULL;
struct DDS_DataWriterQos datawriter_qos = DDS_DataWriterQos_INITIALIZER;
struct DDS_DomainParticipantQos participant_qos =
DDS_DomainParticipantQos_INITIALIZER;
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, &participant_qos, &datawriter_qos);
return -1;
}
/* Start changes for custom_flowcontroller */
/* If you want to change the Participant'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_participant call above.
*/
/* Get default participant QoS to customize */
/* retcode = DDS_DomainParticipantFactory_get_default_participant_qos(
DDS_TheParticipantFactory, &participant_qos);
if (retcode != DDS_RETCODE_OK) {
printf("get_default_participant_qos error\n");
return -1;
}
*/ /* By default, data will be sent via shared memory _and_ UDPv4. Because
* the flowcontroller limits writes across all interfaces, this halves the
* effective send rate. To avoid this, we enable only the UDPv4 transport
*/
/* participant_qos.transport_builtin.mask = DDS_TRANSPORTBUILTIN_UDPv4;
*/ /* To create participant with default QoS, use DDS_PARTICIPANT_QOS_DEFAULT
instead of participant_qos */
/* participant = DDS_DomainParticipantFactory_create_participant(
DDS_TheParticipantFactory, domainId, &participant_qos,
NULL, DDS_STATUS_MASK_NONE);
if (participant == NULL) {
printf("create_participant error\n");
publisher_shutdown(participant, &participant_qos, &datawriter_qos);
return -1;
}
*/
/* End changes for Custom_Flowcontroller */
/* 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, &participant_qos, &datawriter_qos);
return -1;
}
/* Register type before creating topic */
type_name = cfcTypeSupport_get_type_name();
retcode = cfcTypeSupport_register_type(participant, type_name);
if (retcode != DDS_RETCODE_OK) {
printf("register_type error %d\n", retcode);
publisher_shutdown(participant, &participant_qos, &datawriter_qos);
return -1;
}
/* To customize topic QoS, use
the configuration file USER_QOS_PROFILES.xml */
topic = DDS_DomainParticipant_create_topic(participant, "Example cfc",
type_name, &DDS_TOPIC_QOS_DEFAULT, NULL /* listener */,
DDS_STATUS_MASK_NONE);
if (topic == NULL) {
printf("create_topic error\n");
publisher_shutdown(participant, &participant_qos, &datawriter_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, &participant_qos, &datawriter_qos);
return -1;
}
/* Start changes for custom_flowcontroller */
/* 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 create the flowcontroller and the neccesary QoS
* for the datawriter.
*/
/* retcode = DDS_DomainParticipant_get_default_flowcontroller_property(
participant, &custom_fcp);
if (retcode != DDS_RETCODE_OK) {
printf("get_default_flowcontroller_property error \n");
return -1;
}
*/ /* Don't allow too many tokens to accumulate */
/* custom_fcp.token_bucket.max_tokens =
custom_fcp.token_bucket.tokens_added_per_period = 2;
custom_fcp.token_bucket.tokens_leaked_per_period = DDS_LENGTH_UNLIMITED;
*/ /* 100ms */
/* custom_fcp.token_bucket.period.sec = 0;
custom_fcp.token_bucket.period.nanosec = 100000000;
*/ /* The sample size is 1000, but the minimum bytes_per_token is 1024.
* Furthermore, we want to allow some overhead.
*/
/* custom_fcp.token_bucket.bytes_per_token = 1024;
*/ /* So, in summary, each token can be used to send about one message,
* and we get 2 tokens every 100ms, so this limits transmissions to
* about 20 messages per second.
*/
/* Create flowcontroller and set properties */
/* cfc = DDS_DomainParticipant_create_flowcontroller(
participant, DDS_String_dup(cfc_name), &custom_fcp);
if (cfc == NULL) {
printf("create_flowcontroller error\n");
return -1;
}
*/ /* Get default datawriter QoS to customize */
/* retcode = DDS_Publisher_get_default_datawriter_qos(publisher,
&datawriter_qos);
if (retcode != DDS_RETCODE_OK) {
printf("get_default_datawriter_qos error\n");
return -1;
}
*/ /* As an alternative to increasing history depth, we can just
* set the qos to keep all samples
*/
/* datawriter_qos.history.kind = DDS_KEEP_ALL_HISTORY_QOS;
*/
/* Set flowcontroller for datawriter */
/* datawriter_qos.publish_mode.kind = DDS_ASYNCHRONOUS_PUBLISH_MODE_QOS;
datawriter_qos.publish_mode.flow_controller_name = DDS_String_dup(cfc_name);
*/ /* To create datawriter with default QoS, use DDS_DATAWRITER_QOS_DEFAULT
instead of datawriter_qos */
/* 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, &participant_qos, &datawriter_qos);
return -1;
}
*/
/* End changes for Custom_Flowcontroller */
cfc_writer = cfcDataWriter_narrow(writer);
if (cfc_writer == NULL) {
printf("DataWriter narrow error\n");
publisher_shutdown(participant, &participant_qos, &datawriter_qos);
return -1;
}
/* Create data sample for writing */
instance = cfcTypeSupport_create_data_ex(DDS_BOOLEAN_TRUE);
if (instance == NULL) {
printf("cfcTypeSupport_create_data error\n");
publisher_shutdown(participant, &participant_qos, &datawriter_qos);
return -1;
}
/* For a data type that has a key, if the same instance is going to be
written multiple times, initialize the key here
and register the keyed instance prior to writing */
/*
instance_handle = cfcDataWriter_register_instance(
cfc_writer, instance);
*/
/* Main loop */
for (count = 0; (sample_count == 0) || (count < sample_count); ++count) {
/* Changes for custom_flowcontroller */
/* Simulate bursty writer */
NDDS_Utility_sleep(&send_period);
for (i = 0; i < 10; ++i) {
sample = count * 10 + i;
printf("Writing cfc, sample %d\n", sample);
instance->x = sample;
memset(instance->str, 1, 999);
instance->str[999] = 0;
retcode = cfcDataWriter_write(cfc_writer, instance,
&instance_handle);
if (retcode != DDS_RETCODE_OK) {
printf("write error %d\n", retcode);
}
}
}
/* This new sleep it is for let time to the subscriber to read all the
* sent samples.
*/
send_period.sec = 4;
NDDS_Utility_sleep(&send_period);
/*
retcode = cfcDataWriter_unregister_instance(
cfc_writer, instance, &instance_handle);
if (retcode != DDS_RETCODE_OK) {
printf("unregister instance error %d\n", retcode);
}
*/
/* Delete data sample */
retcode = cfcTypeSupport_delete_data_ex(instance, DDS_BOOLEAN_TRUE);
if (retcode != DDS_RETCODE_OK) {
printf("cfcTypeSupport_delete_data error %d\n", retcode);
}
/* Cleanup and delete delete all entities */
return publisher_shutdown(participant, &participant_qos, &datawriter_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/custom_flow_controller/c/cfc_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.
******************************************************************************/
/* cfc_subscriber.c
A subscription example
This file is derived from code automatically generated by the rtiddsgen
command:
rtiddsgen -language C -example <arch> cfc.idl
Example subscription of type cfc 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>/cfc_subscriber <domain_id> <sample_count>
(3) Start the publication with the command
objs/<arch>/cfc_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>/cfc_publisher <domain_id>
objs/<arch>/cfc_subscriber <domain_id>
On Windows systems:
objs\<arch>\cfc_publisher <domain_id>
objs\<arch>\cfc_subscriber <domain_id>
modification history
------------ -------
*/
#include <stdio.h>
#include <stdlib.h>
#include "ndds/ndds_c.h"
#include "cfc.h"
#include "cfcSupport.h"
/* Changes for Custom_Flowcontroller */
/* For timekeeping */
#include <time.h>
clock_t init;
void cfcListener_on_requested_deadline_missed(void* listener_data,
DDS_DataReader* reader,
const struct DDS_RequestedDeadlineMissedStatus *status) {
}
void cfcListener_on_requested_incompatible_qos(void* listener_data,
DDS_DataReader* reader,
const struct DDS_RequestedIncompatibleQosStatus *status) {
}
void cfcListener_on_sample_rejected(void* listener_data, DDS_DataReader* reader,
const struct DDS_SampleRejectedStatus *status) {
}
void cfcListener_on_liveliness_changed(void* listener_data,
DDS_DataReader* reader,
const struct DDS_LivelinessChangedStatus *status) {
}
void cfcListener_on_sample_lost(void* listener_data, DDS_DataReader* reader,
const struct DDS_SampleLostStatus *status) {
}
void cfcListener_on_subscription_matched(void* listener_data,
DDS_DataReader* reader,
const struct DDS_SubscriptionMatchedStatus *status) {
}
void cfcListener_on_data_available(void* listener_data, DDS_DataReader* reader)
{
cfcDataReader *cfc_reader = NULL;
struct cfcSeq data_seq = DDS_SEQUENCE_INITIALIZER;
struct DDS_SampleInfoSeq info_seq = DDS_SEQUENCE_INITIALIZER;
DDS_ReturnCode_t retcode;
int i;
double elapsed_ticks, elapsed_secs;
cfc_reader = cfcDataReader_narrow(reader);
if (cfc_reader == NULL) {
printf("DataReader narrow error\n");
return;
}
retcode = cfcDataReader_take(cfc_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 < cfcSeq_get_length(&data_seq); ++i) {
if (DDS_SampleInfoSeq_get_reference(&info_seq, i)->valid_data) {
/* Start changes for flow_controller */
/* print the time we get each sample */
elapsed_ticks = clock() - init;
elapsed_secs = elapsed_ticks / CLOCKS_PER_SEC;
printf("@ t=%.2fs, got x = %d\n", elapsed_secs,
cfcSeq_get_reference(&data_seq, i)->x);
/* End changes for flow_controller */
}
}
retcode = cfcDataReader_return_loan(cfc_reader, &data_seq, &info_seq);
if (retcode != DDS_RETCODE_OK) {
printf("return loan error %d\n", retcode);
}
}
/* Delete all entities */
static int subscriber_shutdown(DDS_DomainParticipant *participant,
struct DDS_DomainParticipantQos *participant_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_DomainParticipantQos_finalize(participant_qos);
if (retcode != DDS_RETCODE_OK) {
printf("participantQos_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 = NULL;
DDS_Topic *topic = NULL;
struct DDS_DataReaderListener reader_listener =
DDS_DataReaderListener_INITIALIZER;
DDS_DataReader *reader = NULL;
DDS_ReturnCode_t retcode;
const char *type_name = NULL;
int count = 0;
struct DDS_Duration_t poll_period = { 1, 0 };
struct DDS_DomainParticipantQos participant_qos =
DDS_DomainParticipantQos_INITIALIZER;
/* Start changes for Custom_Flowcontroller */
/* for timekeeping */
init = clock();
/* To customize participant QoS, use
the configuration file USER_QOS_PROFILES.xml */
participant = DDS_DomainParticipantFactory_create_participant(
DDS_TheParticipantFactory, domainId, &DDS_PARTICIPANT_QOS_DEFAULT,
NULL /* listener */, DDS_STATUS_MASK_NONE);
if (participant == NULL) {
printf("create_participant error\n");
subscriber_shutdown(participant, &participant_qos);
return -1;
}
/* If you want to change the Participant'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_participant call above.
*/
/* By default, discovery will communicate via shared memory for platforms
* that support it. Because we disable shared memory on the publishing
* side, we do so here to ensure the reader and writer discover each other.
*/
/* retcode = DDS_DomainParticipantFactory_get_default_participant_qos(
DDS_TheParticipantFactory, &participant_qos);
if (retcode != DDS_RETCODE_OK) {
printf("get_default_participant_qos error\n");
return -1;
}
participant_qos.transport_builtin.mask = DDS_TRANSPORTBUILTIN_UDPv4;
*/ /* To create participant with default QoS, use DDS_PARTICIPANT_QOS_DEFAULT
instead of participant_qos */
/* participant = DDS_DomainParticipantFactory_create_participant(
DDS_TheParticipantFactory, domainId, &participant_qos,
NULL, DDS_STATUS_MASK_NONE);
if (participant == NULL) {
printf("create_participant error\n");
subscriber_shutdown(participant, &participant_qos);
return -1;
}
*/
/* End changes for Custom_Flowcontroller */
/* 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, &participant_qos);
return -1;
}
/* Register the type before creating the topic */
type_name = cfcTypeSupport_get_type_name();
retcode = cfcTypeSupport_register_type(participant, type_name);
if (retcode != DDS_RETCODE_OK) {
printf("register_type error %d\n", retcode);
subscriber_shutdown(participant, &participant_qos);
return -1;
}
/* To customize topic QoS, use
the configuration file USER_QOS_PROFILES.xml */
topic = DDS_DomainParticipant_create_topic(participant, "Example cfc",
type_name, &DDS_TOPIC_QOS_DEFAULT, NULL /* listener */,
DDS_STATUS_MASK_NONE);
if (topic == NULL) {
printf("create_topic error\n");
subscriber_shutdown(participant, &participant_qos);
return -1;
}
/* Set up a data reader listener */
reader_listener.on_requested_deadline_missed =
cfcListener_on_requested_deadline_missed;
reader_listener.on_requested_incompatible_qos =
cfcListener_on_requested_incompatible_qos;
reader_listener.on_sample_rejected = cfcListener_on_sample_rejected;
reader_listener.on_liveliness_changed = cfcListener_on_liveliness_changed;
reader_listener.on_sample_lost = cfcListener_on_sample_lost;
reader_listener.on_subscription_matched =
cfcListener_on_subscription_matched;
reader_listener.on_data_available = cfcListener_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, &participant_qos);
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, &participant_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/custom_flow_controller/c++03/cfc_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 <ctime>
#include <dds/dds.hpp>
#include <rti/core/ListenerBinder.hpp>
#include "cfc.hpp"
using namespace dds::core;
using namespace rti::core;
using namespace dds::core::status;
using namespace dds::domain;
using namespace dds::domain::qos;
using namespace dds::sub;
using namespace dds::topic;
clock_t Init_time;
class cfcReaderListener : public NoOpDataReaderListener<cfc> {
public:
void on_data_available(DataReader<cfc>& reader)
{
// Take all samples
LoanedSamples<cfc> samples = reader.take();
for (LoanedSamples<cfc>::iterator sample_it = samples.begin();
sample_it != samples.end();
sample_it++) {
if (sample_it->info().valid()){
// Print the time we get each sample.
double elapsed_ticks = clock() - Init_time;
double elapsed_secs = elapsed_ticks / CLOCKS_PER_SEC;
std::cout << "@ t=" << elapsed_secs << "s, got x = "
<< sample_it->data().x() << std::endl;
}
}
}
};
void subscriber_main(int domain_id, int sample_count)
{
// For timekeeping.
Init_time = clock();
// Retrieve the default Participant QoS, from USER_QOS_PROFILES.xml
DomainParticipantQos participant_qos = QosProvider::Default()
.participant_qos();
// If you want to change the Participant's QoS programmatically rather than
// using the XML file, uncomment the following lines.
//
// By default, data will be sent via shared memory "and" UDPv4.
// Because the flowcontroller limits writes across all interfaces,
// this halves the effective send rate. To avoid this, we enable only the
// UDPv4 transport.
// participant_qos << TransportBuiltin::UDPv4();
// Create a DomainParticipant.
DomainParticipant participant(domain_id, participant_qos);
// Create a Topic -- and automatically register the type
Topic<cfc> topic(participant, "Example cfc");
// Create a DataReader with default Qos (Subscriber created in-line)
DataReader<cfc> reader(Subscriber(participant), topic);
// Associate a listener to the DataReader using ListenerBinder, a RAII that
// will take care of setting it to NULL on destruction.
ListenerBinder< DataReader<cfc> > reader_listener =
rti::core::bind_and_manage_listener(
reader,
new cfcReaderListener,
StatusMask::all());
std::cout << std::fixed;
for (int count = 0; sample_count == 0 || count < sample_count; ++count) {
rti::util::sleep(dds::core::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;
}
// 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/custom_flow_controller/c++03/cfc_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 <rti/pub/FlowController.hpp>
#include "cfc.hpp"
using namespace dds::core;
using namespace dds::core::policy;
using namespace rti::core::policy;
using namespace dds::domain;
using namespace dds::domain::qos;
using namespace dds::topic;
using namespace dds::pub;
using namespace rti::pub;
using namespace dds::pub::qos;
const std::string flow_controller_name = "custom_flowcontroller";
FlowControllerProperty define_flowcontroller(DomainParticipant& participant)
{
// Create a custom FlowController based on tocken-bucket mechanism.
// First specify the token-bucket configuration.
// In summary, each token can be used to send about one message,
// and we get 2 tokens every 100 ms, so this limits transmissions to
// about 20 messages per second.
FlowControllerTokenBucketProperty flowcontroller_tokenbucket;
// Don't allow too many tokens to accumulate.
flowcontroller_tokenbucket.max_tokens(2);
flowcontroller_tokenbucket.tokens_added_per_period(2);
flowcontroller_tokenbucket.tokens_leaked_per_period(LENGTH_UNLIMITED);
// Period of 100 ms.
flowcontroller_tokenbucket.period(Duration::from_millisecs(100));
// The sample size is 1000, but the minimum bytes_per_token is 1024.
// Furthermore, we want to allow some overhead.
flowcontroller_tokenbucket.bytes_per_token(1024);
// Create a FlowController Property to set the TokenBucket definition.
FlowControllerProperty flowcontroller_property(
FlowControllerSchedulingPolicy::EARLIEST_DEADLINE_FIRST,
flowcontroller_tokenbucket);
return flowcontroller_property;
}
void publisher_main(int domain_id, int sample_count)
{
// Retrieve the default Participant QoS, from USER_QOS_PROFILES.xml
DomainParticipantQos participant_qos = QosProvider::Default()
.participant_qos();
// If you want to change the Participant's QoS programmatically rather than
// using the XML file, uncomment the following lines.
//
// By default, data will be sent via shared memory "and" UDPv4.
// Because the flowcontroller limits writes across all interfaces,
// this halves the effective send rate. To avoid this, we enable only the
// UDPv4 transport.
// participant_qos << TransportBuiltin::UDPv4();
// Create a DomainParticipant.
DomainParticipant participant(domain_id, participant_qos);
// Create the FlowController by code instead of from USER_QOS_PROFILES.xml.
FlowControllerProperty flow_controller_property =
define_flowcontroller(participant);
FlowController flowcontroller(
participant,
flow_controller_name,
flow_controller_property);
// Create a Topic -- and automatically register the type
Topic<cfc> topic(participant, "Example cfc");
// Retrieve the default DataWriter QoS, from USER_QOS_PROFILES.xml
DataWriterQos writer_qos = QosProvider::Default().datawriter_qos();
// If you want to change the DataWriter's QoS programmatically rather than
// using the XML file, uncomment the following lines.
// writer_qos << History::KeepAll()
// << PublishMode::Asynchronous(flow_controller_name);
// Create a DataWriter (Publisher created in-line)
DataWriter<cfc> writer(Publisher(participant), topic, writer_qos);
// Create a sample to write with a long payload.
cfc sample;
sample.str(std::string(999, 'A'));
for (int count = 0; count < sample_count || sample_count == 0; count++) {
// Simulate bursty writer.
rti::util::sleep(Duration(1));
for (int i = 0; i < 10; i++) {
sample.x(count * 10 + i);
std::cout << "Writing cfc, sample " << sample.x() << std::endl;
writer.write(sample);
}
}
// This new sleep is to give the subscriber time to read all the samples.
rti::util::sleep(Duration(4));
}
int main(int argc, char *argv[])
{
int domain_id = 0;
int sample_count = 0; // Infinite loop
if (argc >= 2) {
domain_id = atoi(argv[1]);
}
if (argc >= 3) {
sample_count = atoi(argv[2]);
}
// To turn on additional logging, include <rti/config/Logger.hpp> and
// uncomment the following line:
// rti::config::Logger::instance().verbosity(rti::config::Verbosity::STATUS_ALL);
try {
publisher_main(domain_id, sample_count);
} catch (const std::exception& ex) {
// This will catch DDS exceptions
std::cerr << "Exception in publisher_main: " << ex.what() << std::endl;
return -1;
}
return 0;
}
| cxx |
rticonnextdds-examples | data/projects/rticonnextdds-examples/custom_content_filter/c++/ccf_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.
******************************************************************************/
/* ccf_subscriber.cxx
A subscription example
This file is derived from code automatically generated by the rtiddsgen
command:
rtiddsgen -language C++ -example <arch> ccf.idl
Example subscription of type ccf 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>/ccf_subscriber <domain_id> <sample_count>
(3) Start the publication with the command
objs/<arch>/ccf_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>/ccf_publisher <domain_id>
objs/<arch>/ccf_subscriber <domain_id>
On Windows:
objs\<arch>\ccf_publisher <domain_id>
objs\<arch>\ccf_subscriber <domain_id>
modification history
------------ -------
21May2014,amb Example adapted for RTI Connext DDS 5.1
*/
#include <stdio.h>
#include <stdlib.h>
#ifdef RTI_VX653
#include <vThreadsData.h>
#endif
#include "ccf.h"
#include "ccfSupport.h"
#include "ndds/ndds_cpp.h"
/* Custom filter defined here */
#include "filter.cxx"
class ccfListener: 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 ccfListener::on_data_available(DDSDataReader* reader) {
ccfDataReader *ccf_reader = NULL;
ccfSeq data_seq;
DDS_SampleInfoSeq info_seq;
DDS_ReturnCode_t retcode;
int i;
ccf_reader = ccfDataReader::narrow(reader);
if (ccf_reader == NULL) {
printf("DataReader narrow error\n");
return;
}
retcode = ccf_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) {
ccfTypeSupport::print_data(&data_seq[i]);
}
}
retcode = ccf_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;
ccfListener *reader_listener = NULL;
DDSDataReader *reader = NULL;
DDS_ReturnCode_t retcode;
const char *type_name = NULL;
int count = 0;
DDS_Duration_t receive_period = { 1, 0 };
int status = 0;
/* To customize the participant QoS, use
the configuration file USER_QOS_PROFILES.xml */
participant = DDSTheParticipantFactory->create_participant(domainId,
DDS_PARTICIPANT_QOS_DEFAULT, NULL /* listener */,
DDS_STATUS_MASK_NONE);
if (participant == NULL) {
printf("create_participant error\n");
subscriber_shutdown(participant);
return -1;
}
/* To customize the subscriber QoS, use
the configuration file USER_QOS_PROFILES.xml */
subscriber = participant->create_subscriber(DDS_SUBSCRIBER_QOS_DEFAULT,
NULL /* listener */, DDS_STATUS_MASK_NONE);
if (subscriber == NULL) {
printf("create_subscriber error\n");
subscriber_shutdown(participant);
return -1;
}
/* Register the type before creating the topic */
type_name = ccfTypeSupport::get_type_name();
retcode = ccfTypeSupport::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 ccf", 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 Custom Content Filter */
/* Create and register custom filter */
custom_filter_type* custom_filter = new custom_filter_type();
retcode = participant->register_contentfilter("CustomFilter",
custom_filter);
if (retcode != DDS_RETCODE_OK) {
printf("Failed to register custom content filter");
subscriber_shutdown(participant);
return -1;
}
DDS_StringSeq parameters(2);
const char* param_list[] = { "2", "divides" };
parameters.from_array(param_list, 2);
/* Create content filtered topic */
DDSContentFilteredTopic *cft = NULL;
cft = participant->create_contentfilteredtopic_with_filter(
"ContentFilteredTopic", topic, "%0 %1 x", parameters,
"CustomFilter");
if (cft == NULL) {
printf("create_contentfilteredtopic error\n");
subscriber_shutdown(participant);
return -1;
}
printf("Filter: 2 divides x\n");
/* Also note that we pass 'cft' rather than 'topic' to the datareader
* below
*/
/* End changes for Custom_Content_Filter */
/* Create a data reader listener */
reader_listener = new ccfListener();
/*
* NOTE THAT WE USE THE PREVIOUSLY CREATED CUSTOM FILTERED TOPIC TO READ
* NEW SAMPLES
*/
reader = subscriber->create_datareader(cft, DDS_DATAREADER_QOS_DEFAULT,
reader_listener, DDS_STATUS_MASK_ALL);
if (reader == NULL) {
printf("create_datareader error\n");
subscriber_shutdown(participant);
delete reader_listener;
return -1;
}
/* Start Topics/ContentFilter changes */
/* Main loop */
for (count = 0; (sample_count == 0) || (count < sample_count); ++count) {
if (count == 10) {
printf("changing filter parameters\n");
printf("Filter: 15 greater-than x\n");
DDS_String_free(parameters[0]);
DDS_String_free(parameters[1]);
parameters[0] = DDS_String_dup("15");
parameters[1] = DDS_String_dup("greater-than");
retcode = cft->set_expression_parameters(parameters);
if (retcode != DDS_RETCODE_OK) {
printf("set_expression_parameters error\n");
subscriber_shutdown(participant);
return -1;
}
} else if (count == 20) {
printf("changing filter parameters\n");
printf("Filter: 3 divides x\n");
DDS_StringSeq oldParameters;
cft->get_expression_parameters(oldParameters);
DDS_String_free(oldParameters[0]);
DDS_String_free(oldParameters[1]);
oldParameters[0] = DDS_String_dup("3");
oldParameters[1] = DDS_String_dup("divides");
retcode = cft->set_expression_parameters(oldParameters);
if (retcode != DDS_RETCODE_OK) {
printf("set_expression_parameters error\n");
subscriber_shutdown(participant);
return -1;
}
}
NDDSUtility::sleep(receive_period);
}
/* End Topics/ContentFilter changes */
/* 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/custom_content_filter/c++/ccf_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.
******************************************************************************/
/* ccf_publisher.cxx
A publication of data of type ccf
This file is derived from code automatically generated by the rtiddsgen
command:
rtiddsgen -language C++ -example <arch> ccf.idl
Example publication of type ccf 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>/ccf_subscriber <domain_id> <sample_count>
(3) Start the publication with the command
objs/<arch>/ccf_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>/ccf_publisher <domain_id> o
objs/<arch>/ccf_subscriber <domain_id>
On Windows:
objs\<arch>\ccf_publisher <domain_id>
objs\<arch>\ccf_subscriber <domain_id>
modification history
------------ -------
21May2014,amb Example adapted for RTI Connext DDS 5.1
*/
#include <stdio.h>
#include <stdlib.h>
#ifdef RTI_VX653
#include <vThreadsData.h>
#endif
#include "ccf.h"
#include "ccfSupport.h"
#include "ndds/ndds_cpp.h"
/* Custom filter defined here */
#include "filter.cxx"
/* 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;
ccfDataWriter * ccf_writer = NULL;
ccf *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;
}
/* 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 = ccfTypeSupport::get_type_name();
retcode = ccfTypeSupport::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 ccf", type_name,
DDS_TOPIC_QOS_DEFAULT, NULL /* listener */, DDS_STATUS_MASK_NONE);
if (topic == NULL) {
printf("create_topic error\n");
publisher_shutdown(participant);
return -1;
}
/* Start changes for Custom_Content_Filter */
/* Create and register custom filter */
custom_filter_type* custom_filter = new custom_filter_type();
retcode = participant->register_contentfilter("CustomFilter",
custom_filter);
if (retcode != DDS_RETCODE_OK) {
printf("Failed to register custom content filter");
publisher_shutdown(participant);
return -1;
}
/* End changes for Custom_Content_Filter */
/* 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;
}
ccf_writer = ccfDataWriter::narrow(writer);
if (ccf_writer == NULL) {
printf("DataWriter narrow error\n");
publisher_shutdown(participant);
return -1;
}
/* Create data sample for writing */
instance = ccfTypeSupport::create_data();
if (instance == NULL) {
printf("ccfTypeSupport::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 = ccf_writer->register_instance(*instance);
*/
/* Main loop */
for (count = 0; (sample_count == 0) || (count < sample_count); ++count) {
printf("Writing ccf, count %d\n", count);
/* Modify the data to be sent here */
instance->x = count;
retcode = ccf_writer->write(*instance, instance_handle);
if (retcode != DDS_RETCODE_OK) {
printf("write error %d\n", retcode);
}
NDDSUtility::sleep(send_period);
}
/*
retcode = ccf_writer->unregister_instance(
*instance, instance_handle);
if (retcode != DDS_RETCODE_OK) {
printf("unregister instance error %d\n", retcode);
}
*/
/* Delete data sample */
retcode = ccfTypeSupport::delete_data(instance);
if (retcode != DDS_RETCODE_OK) {
printf("ccfTypeSupport::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/custom_content_filter/c++/filter.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.
******************************************************************************/
/* filter.cxx
*
* This file contains the functions needed by the Custom Content Filter to work.
*
* See the example README.txt file for details about each of these functions.
*
* modification history
* ------------ -------
* 21May2014,amb Example adapted for RTI Connext DDS 5.1
*/
class custom_filter_type: public DDSContentFilter {
public:
virtual DDS_ReturnCode_t compile(void** new_compile_data,
const char *expression, const DDS_StringSeq& parameters,
const DDS_TypeCode* type_code, const char* type_class_name,
void *old_compile_data);
virtual DDS_Boolean evaluate(void* compile_data, const void* sample,
const struct DDS_FilterSampleInfo * meta_data);
virtual void finalize(void* compile_data);
};
bool divide_test(long sample_data, long p) {
return (sample_data % p == 0);
}
bool gt_test(long sample_data, long p) {
return (p > sample_data);
}
/* Custom compile data */
struct cdata {
long param;
bool (*eval_func)(long, long);
};
/* Called when Custom Filter is created, or when parameters are changed */
DDS_ReturnCode_t custom_filter_type::compile(void** new_compile_data,
const char *expression, const DDS_StringSeq& parameters,
const DDS_TypeCode* type_code, const char* type_class_name,
void *old_compile_data) {
struct cdata* cd = NULL;
/* First free old data, if any */
delete old_compile_data;
/* We expect an expression of the form "%0 %1 <var>"
* where %1 = "divides" or "greater-than"
* and <var> is an integral member of the msg structure.
*
* We don't actually check that <var> has the correct typecode,
* (or even that it exists!). See example Typecodes to see
* how to work with typecodes.
*
* The compile information is a structure including the first filter
* parameter (%0) and a function pointer to evaluate the sample
*/
/* Check form: */
if (strncmp(expression, "%0 %1 ", 6) != 0) {
goto err;
}
if (strlen(expression) < 7) {
goto err;
}
/* Check that we have params */
if (parameters.length() < 2) {
goto err;
}
cd = (struct cdata*) malloc(sizeof(struct cdata));
sscanf(parameters[0], "%ld", &cd->param);
if (strcmp(parameters[1], "greater-than") == 0) {
cd->eval_func = gt_test;
} else if (strcmp(parameters[1], "divides") == 0) {
cd->eval_func = divide_test;
} else {
goto err;
}
*new_compile_data = cd;
return DDS_RETCODE_OK;
err:
printf("CustomFilter: Unable to compile expression '%s'\n",
expression);
printf(" with parameters '%s' '%s'\n", parameters[0],
parameters[1]);
*new_compile_data = NULL;
return DDS_RETCODE_BAD_PARAMETER;
}
/* Called to evaluated each sample */
DDS_Boolean custom_filter_type::evaluate(void* compile_data, const void* sample,
const struct DDS_FilterSampleInfo * meta_data) {
cdata* cd = (cdata*) compile_data;
ccf* msg = (ccf*) sample;
if (cd->eval_func(msg->x, cd->param))
return DDS_BOOLEAN_TRUE;
else
return DDS_BOOLEAN_FALSE;
}
void custom_filter_type::finalize(void* compile_data) {
if (compile_data != NULL)
delete compile_data;
}
| cxx |
rticonnextdds-examples | data/projects/rticonnextdds-examples/custom_content_filter/c/ccf_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.
******************************************************************************/
/* ccf_publisher.c
A publication of data of type ccf
This file is derived from code automatically generated by the rtiddsgen
command:
rtiddsgen -language C -example <arch> ccf.idl
Example publication of type ccf 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>/ccf_subscriber <domain_id> <sample_count>
(3) Start the publication with the command
objs/<arch>/ccf_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>/ccf_publisher <domain_id>
objs/<arch>/ccf_subscriber <domain_id>
On Windows:
objs\<arch>\ccf_publisher <domain_id>
objs\<arch>\ccf_subscriber <domain_id>
modification history
------------ -------
20May2014,amb Example adapted for RTI Connext DDS 5.1
*/
#include <stdio.h>
#include <stdlib.h>
#include "ndds/ndds_c.h"
#include "ccf.h"
#include "ccfSupport.h"
/* Custom filter defined here */
#include "filter.c"
/* 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;
ccfDataWriter *ccf_writer = NULL;
ccf *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_ContentFilter custom_filter = DDS_ContentFilter_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 = ccfTypeSupport_get_type_name();
retcode = ccfTypeSupport_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 ccf",
type_name, &DDS_TOPIC_QOS_DEFAULT, NULL /* listener */,
DDS_STATUS_MASK_NONE);
if (topic == NULL) {
printf("create_topic error\n");
publisher_shutdown(participant);
return -1;
}
/*------ Start changes for Custom_Content_Filter ------*/
/* Create and register custom filter */
custom_filter.compile = custom_filter_compile_function;
custom_filter.evaluate = custom_filter_evaluate_function;
custom_filter.finalize = custom_filter_finalize_function;
custom_filter.filter_data = NULL;
retcode = DDS_DomainParticipant_register_contentfilter(participant,
"CustomFilter", &custom_filter);
if (retcode != DDS_RETCODE_OK) {
printf("Failed to register custom content filter");
publisher_shutdown(participant);
return -1;
}
/*------ End changes for Custom_Content_Filter ------*/
/* 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;
}
ccf_writer = ccfDataWriter_narrow(writer);
if (ccf_writer == NULL) {
printf("DataWriter narrow error\n");
publisher_shutdown(participant);
return -1;
}
/* Create data sample for writing */
instance = ccfTypeSupport_create_data_ex(DDS_BOOLEAN_TRUE);
if (instance == NULL) {
printf("ccfTypeSupport_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 = ccfDataWriter_register_instance(
ccf_writer, instance);
*/
/* Main loop */
for (count = 0; (sample_count == 0) || (count < sample_count); ++count) {
printf("Writing ccf, count %d\n", count);
/* Modify the data to be written here */
instance->x = count;
/* Write data */
retcode = ccfDataWriter_write(ccf_writer, instance, &instance_handle);
if (retcode != DDS_RETCODE_OK) {
printf("write error %d\n", retcode);
}
NDDS_Utility_sleep(&send_period);
}
/*
retcode = ccfDataWriter_unregister_instance(
ccf_writer, instance, &instance_handle);
if (retcode != DDS_RETCODE_OK) {
printf("unregister instance error %d\n", retcode);
}
*/
/* Delete data sample */
retcode = ccfTypeSupport_delete_data_ex(instance, DDS_BOOLEAN_TRUE);
if (retcode != DDS_RETCODE_OK) {
printf("ccfTypeSupport_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/custom_content_filter/c/ccf_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.
******************************************************************************/
/* ccf_subscriber.c
A subscription example
This file is derived from code automatically generated by the rtiddsgen
command:
rtiddsgen -language C -example <arch> ccf.idl
Example subscription of type ccf 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>/ccf_subscriber <domain_id> <sample_count>
(3) Start the publication with the command
objs/<arch>/ccf_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>/ccf_publisher <domain_id>
objs/<arch>/ccf_subscriber <domain_id>
On Windows systems:
objs\<arch>\ccf_publisher <domain_id>
objs\<arch>\ccf_subscriber <domain_id>
modification history
------------ -------
21May2014,amb Example adapted for RTI Connext DDS 5.1
*/
#include <stdio.h>
#include <stdlib.h>
#include "ndds/ndds_c.h"
#include "ccf.h"
#include "ccfSupport.h"
/* Custom filter defined here */
#include "filter.c"
void ccfListener_on_requested_deadline_missed(void* listener_data,
DDS_DataReader* reader,
const struct DDS_RequestedDeadlineMissedStatus *status) {
}
void ccfListener_on_requested_incompatible_qos(void* listener_data,
DDS_DataReader* reader,
const struct DDS_RequestedIncompatibleQosStatus *status) {
}
void ccfListener_on_sample_rejected(void* listener_data, DDS_DataReader* reader,
const struct DDS_SampleRejectedStatus *status) {
}
void ccfListener_on_liveliness_changed(void* listener_data,
DDS_DataReader* reader,
const struct DDS_LivelinessChangedStatus *status) {
}
void ccfListener_on_sample_lost(void* listener_data, DDS_DataReader* reader,
const struct DDS_SampleLostStatus *status) {
}
void ccfListener_on_subscription_matched(void* listener_data,
DDS_DataReader* reader,
const struct DDS_SubscriptionMatchedStatus *status) {
}
void ccfListener_on_data_available(void* listener_data,
DDS_DataReader* reader) {
ccfDataReader *ccf_reader = NULL;
struct ccfSeq data_seq = DDS_SEQUENCE_INITIALIZER;
struct DDS_SampleInfoSeq info_seq = DDS_SEQUENCE_INITIALIZER;
DDS_ReturnCode_t retcode;
int i;
ccf_reader = ccfDataReader_narrow(reader);
if (ccf_reader == NULL) {
printf("DataReader narrow error\n");
return;
}
retcode = ccfDataReader_take(ccf_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 < ccfSeq_get_length(&data_seq); ++i) {
if (DDS_SampleInfoSeq_get_reference(&info_seq, i)->valid_data) {
ccfTypeSupport_print_data(ccfSeq_get_reference(&data_seq, i));
}
}
retcode = ccfDataReader_return_loan(ccf_reader, &data_seq, &info_seq);
if (retcode != DDS_RETCODE_OK) {
printf("return loan error %d\n", retcode);
}
}
/* Delete all entities */
static int subscriber_shutdown(DDS_DomainParticipant *participant) {
DDS_ReturnCode_t retcode;
int status = 0;
if (participant != NULL) {
retcode = DDS_DomainParticipant_delete_contained_entities(participant);
if (retcode != DDS_RETCODE_OK) {
printf("delete_contained_entities error %d\n", retcode);
status = -1;
}
retcode = DDS_DomainParticipantFactory_delete_participant(
DDS_TheParticipantFactory, participant);
if (retcode != DDS_RETCODE_OK) {
printf("delete_participant error %d\n", retcode);
status = -1;
}
}
/* RTI Connext provides the finalize_instance() method on
domain participant factory for users who want to release memory used
by the participant factory. Uncomment the following block of code for
clean destruction of the singleton. */
/*
retcode = DDS_DomainParticipantFactory_finalize_instance();
if (retcode != DDS_RETCODE_OK) {
printf("finalize_instance error %d\n", retcode);
status = -1;
}
*/
return status;
}
static int subscriber_main(int domainId, int sample_count) {
DDS_DomainParticipant *participant = NULL;
DDS_Subscriber *subscriber = NULL;
DDS_Topic *topic = NULL;
struct DDS_DataReaderListener reader_listener =
DDS_DataReaderListener_INITIALIZER;
DDS_DataReader *reader = NULL;
DDS_ReturnCode_t retcode;
const char *type_name = NULL;
int count = 0;
struct DDS_Duration_t poll_period = { 1, 0 };
const char* param_list[] = { "2", "divides" };
DDS_ContentFilteredTopic *cft = NULL;
struct DDS_StringSeq parameters;
struct DDS_ContentFilter custom_filter = DDS_ContentFilter_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 = ccfTypeSupport_get_type_name();
retcode = ccfTypeSupport_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 ccf",
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 Custom_Content_Filter ------*/
/* Create and register custom filter */
custom_filter.compile = custom_filter_compile_function;
custom_filter.evaluate = custom_filter_evaluate_function;
custom_filter.finalize = custom_filter_finalize_function;
custom_filter.filter_data = NULL;
retcode = DDS_DomainParticipant_register_contentfilter(participant,
"CustomFilter", &custom_filter);
if (retcode != DDS_RETCODE_OK) {
printf("Failed to register custom content filter");
subscriber_shutdown(participant);
return -1;
}
DDS_StringSeq_initialize(¶meters);
DDS_StringSeq_set_maximum(¶meters, 2);
DDS_StringSeq_from_array(¶meters, param_list, 2);
cft = DDS_DomainParticipant_create_contentfilteredtopic_with_filter(
participant, "ContentFilteredTopic", topic, "%0 %1 x", ¶meters,
"CustomFilter");
if (cft == NULL) {
printf("create_contentfilteredtopic error\n");
subscriber_shutdown(participant);
return -1;
}
printf("Filter: 2 divides x\n");
/* Note that we pass 'ccf' rather than 'topic' to the datareader below */
/*------ End changes for Custom_Content_Filter ------*/
/* Set up a data reader listener */
reader_listener.on_requested_deadline_missed =
ccfListener_on_requested_deadline_missed;
reader_listener.on_requested_incompatible_qos =
ccfListener_on_requested_incompatible_qos;
reader_listener.on_sample_rejected = ccfListener_on_sample_rejected;
reader_listener.on_liveliness_changed = ccfListener_on_liveliness_changed;
reader_listener.on_sample_lost = ccfListener_on_sample_lost;
reader_listener.on_subscription_matched =
ccfListener_on_subscription_matched;
reader_listener.on_data_available = ccfListener_on_data_available;
/*
* NOTE THAT WE USE THE PREVIOUSLY CREATED CUSTOM FILTERED TOPIC TO READ
* NEW SAMPLES
*/
reader = DDS_Subscriber_create_datareader(subscriber,
DDS_Topic_as_topicdescription(cft), &DDS_DATAREADER_QOS_DEFAULT,
&reader_listener, DDS_STATUS_MASK_ALL);
if (reader == NULL) {
printf("create_datareader error\n");
subscriber_shutdown(participant);
return -1;
}
/* Start changes for Custom_Content_Filter */
/* Main loop */
for (count = 0; (sample_count == 0) || (count < sample_count); ++count) {
if (count == 10) {
printf("changing filter parameters\n");
printf("Filter: 15 greater-than x\n");
DDS_String_free(DDS_StringSeq_get(¶meters, 0));
DDS_String_free(DDS_StringSeq_get(¶meters, 1));
*DDS_StringSeq_get_reference(¶meters, 0) = DDS_String_dup("15");
*DDS_StringSeq_get_reference(¶meters, 1) = DDS_String_dup(
"greater-than");
retcode = DDS_ContentFilteredTopic_set_expression_parameters(cft,
¶meters);
if (retcode != DDS_RETCODE_OK) {
printf("set_expression_parameters error\n");
subscriber_shutdown(participant);
return -1;
}
} else if (count == 20) {
struct DDS_StringSeq oldParameters;
printf("changing filter parameters\n");
printf("Filter: 3 divides x\n");
DDS_ContentFilteredTopic_get_expression_parameters(cft,
&oldParameters);
DDS_String_free(DDS_StringSeq_get(&oldParameters, 0));
*DDS_StringSeq_get_reference(&oldParameters, 0) = DDS_String_dup(
"3");
*DDS_StringSeq_get_reference(&oldParameters, 1) = DDS_String_dup(
"divides");
retcode = DDS_ContentFilteredTopic_set_expression_parameters(cft,
&oldParameters);
if (retcode != DDS_RETCODE_OK) {
printf("set_expression_parameters error\n");
subscriber_shutdown(participant);
return -1;
}
}
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/custom_content_filter/c/filter.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.
******************************************************************************/
/* filter.c
*
* This file contains the functions needed by the Custom Content Filter to work.
*
* See the example README.txt file for details about each of these functions.
*
* modification history
* ------------ -------
* 21May2014,amb Example adapted for RTI Connext DDS 5.1
*/
/* Custom compile data */
struct cdata {
long param;
int (*eval_func)(long, long);
};
/* Evaluation function for 'divides' filter */
int divide_test(long sample_data, long p) {
return (sample_data % p == 0);
}
/* Evaluation function for 'greater than' filter */
int gt_test(long sample_data, long p) {
return (p > sample_data);
}
DDS_ReturnCode_t custom_filter_compile_function(void *filter_data,
void **new_compile_data, const char *expression,
const struct DDS_StringSeq *parameters,
const struct DDS_TypeCode *type_code, const char *type_class_name,
void *old_compile_data) {
struct cdata* cd;
/* First free old data, if any */
if (old_compile_data != NULL) {
free(old_compile_data);
}
/* We expect an expression of the form "%0 %1 <var>"
* where %1 = "divides" or "greater-than"
* and <var> is an integral member of the msg structure.
*
* We don't actually check that <var> has the correct typecode,
* (or even that it exists!). See example Typecodes to see
* how to work with typecodes.
*
* The compile information is a structure including the first filter
* parameter (%0) and a function pointer to evaluate the sample
*/
/* Check form: */
if (strncmp(expression, "%0 %1 ", 6) != 0) {
goto err;
}
if (strlen(expression) < 7) {
goto err;
}
/* Check that we have params */
if (DDS_StringSeq_get_length(parameters) < 2) {
goto err;
}
cd = (struct cdata*) malloc(sizeof(struct cdata));
sscanf(DDS_StringSeq_get(parameters, 0), "%ld", &cd->param);
/* Establish the correct evaluation function depending on the filter */
if (strcmp(DDS_StringSeq_get(parameters, 1), "greater-than") == 0) {
cd->eval_func = gt_test;
} else if (strcmp(DDS_StringSeq_get(parameters, 1), "divides") == 0) {
cd->eval_func = divide_test;
} else {
goto err;
}
*new_compile_data = cd;
return DDS_RETCODE_OK;
err: printf("CustomFilter: Unable to compile expression '%s'\n",
expression);
printf(" with parameters '%s' '%s'\n",
DDS_StringSeq_get(parameters, 0), DDS_StringSeq_get(parameters, 1));
*new_compile_data = NULL;
return DDS_RETCODE_BAD_PARAMETER;
}
/* Called to evaluated each sample. Will vary depending on the filter. */
DDS_Boolean custom_filter_evaluate_function(void *filter_data,
void* compile_data, const void* sample,
const struct DDS_FilterSampleInfo * meta_data) {
struct cdata* cd;
struct ccf* msg;
cd = (struct cdata*) compile_data;
msg = (struct ccf*) sample;
if (cd->eval_func(msg->x, cd->param)) {
return DDS_BOOLEAN_TRUE;
} else {
return DDS_BOOLEAN_FALSE;
}
}
void custom_filter_finalize_function(void *filter_data, void *compile_data) {
if (compile_data != NULL) {
free(compile_data);
}
}
| c |
rticonnextdds-examples | data/projects/rticonnextdds-examples/custom_content_filter/c++03/ccf_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 "ccf.hpp"
#include "filter.hpp"
using namespace dds::core;
using namespace dds::core::status;
using namespace dds::domain;
using namespace dds::topic;
using namespace dds::sub;
class CcfListener : public NoOpDataReaderListener<Foo> {
public:
void on_data_available(DataReader<Foo> &reader)
{
// Take the available data
LoanedSamples<Foo> samples = reader.take();
for (LoanedSamples<Foo>::iterator sampleIt = samples.begin();
sampleIt != samples.end();
++sampleIt) {
if (sampleIt->info().valid()) {
std::cout << sampleIt->data() << 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<Foo> topic(participant, "Example ccf");
// Register the custom filter type. It must be registered in both sides.
participant->register_contentfilter(
CustomFilter<CustomFilterType>(new CustomFilterType()),
"CustomFilter");
// The default filter parameters will filter values that are divisible by 2.
std::vector<std::string> parameters(2);
parameters[0] = "2";
parameters[1] = "divides";
// Create the filter with the expression and the type registered.
Filter filter("%0 %1 x", parameters);
filter->name("CustomFilter");
// Create the content filtered topic.
ContentFilteredTopic<Foo> cft_topic(
topic,
"ContentFilteredTopic",
filter);
std::cout << "Filter: 2 divides x" << std::endl;
// Create a DataReader. Note that we are using the content filtered topic.
DataReader<Foo> reader(Subscriber(participant), cft_topic);
// Create a data reader listener using ListenerBinder, a RAII that
// will take care of setting it to NULL on destruction.
rti::core::ListenerBinder< DataReader<Foo> > scoped_listener =
rti::core::bind_and_manage_listener(
reader,
new CcfListener,
StatusMask::data_available());
// Main loop
for (int count = 0; (sample_count == 0) || (count < sample_count); ++count){
if (count == 10) {
std::cout << "Changing filter parameters" << std::endl
<< "Filter: 15 greater-than x" << std::endl;
parameters[0] = "15";
parameters[1] = "greater-than";
cft_topic.filter_parameters(parameters.begin(), parameters.end());
} else if (count == 20) {
std::cout << "Changing filter parameters" << std::endl
<< "Filter: 3 divides x" << std::endl;
parameters[0] = "3";
parameters[1] = "divides";
cft_topic.filter_parameters(parameters.begin(), parameters.end());
}
rti::util::sleep(Duration(1));
}
}
int main(int argc, char *argv[])
{
int domain_id = 0;
int sample_count = 0; // Infinite loop
if (argc >= 2) {
domain_id = atoi(argv[1]);
}
if (argc >= 3) {
sample_count = atoi(argv[2]);
}
// To turn on additional logging, include <rti/config/Logger.hpp> and
// uncomment the following line:
// rti::config::Logger::instance()l.verbosity(rti::config::Verbosity::STATUS_ALL);
try {
subscriber_main(domain_id, sample_count);
} catch (std::exception ex) {
std::cout << "Exception caught: " << ex.what() << std::endl;
return -1;
}
return 0;
}
| cxx |
rticonnextdds-examples | data/projects/rticonnextdds-examples/custom_content_filter/c++03/filter.hpp | /*******************************************************************************
(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 <dds/dds.hpp>
#include "ccf.hpp"
using namespace dds::core;
using namespace dds::core::xtypes;
using namespace rti::topic;
struct CustomCompileData {
long param;
bool (*eval_func)(long, long);
};
bool divide_test(long sample_data, long p) {
return (sample_data % p == 0);
}
bool gt_test(long sample_data, long p) {
return (p > sample_data);
}
class CustomFilterType: public ContentFilter<Foo, CustomCompileData> {
public:
// Called when Custom Filter is created, or when parameters are changed.
virtual CustomCompileData& compile(const std::string& expression,
const StringSeq& parameters,
const optional<DynamicType>& type_code,
const std::string& type_class_name,
CustomCompileData* old_compile_data)
{
// First free old data, if any.
if (old_compile_data != NULL)
delete old_compile_data;
// We expect an expression of the form "%0 %1 <var>" where
// %1 = "divides" or "greater-than" and <var> is an integral member of
// the msg structure.
// We don't actually check that <var> has the correct typecode,
// (or even that it exists!). See example Typecodes to see
// how to work with typecodes.
// The compile information is a structure including the first filter
// parameter (%0) and a function pointer to evaluate the sample
// Check form.
if (expression.compare(0, 6, "%0 %1 ") != 0) {
throw std::invalid_argument("Invalid filter expression");
}
if (expression.size() < 7) {
throw std::invalid_argument("Invalid filter expression size");
}
/* Check that we have params */
if (parameters.size() < 2) {
throw std::invalid_argument("Invalid filter parameters number");
}
CustomCompileData* cd = new CustomCompileData();
cd->param = atol(parameters[0].c_str());
if (parameters[1] == "greater-than") {
cd->eval_func = >_test;
} else if (parameters[1] == "divides") {
cd->eval_func = ÷_test;
} else {
throw std::invalid_argument("Invad filter operation");
}
return *cd;
}
// Called to evaluated each sample.
virtual bool evaluate(CustomCompileData& compile_data, const Foo& sample,
const FilterSampleInfo& meta_data)
{
return compile_data.eval_func(sample.x(), compile_data.param);
}
virtual void finalize(CustomCompileData& compile_data)
{
// This is the pointer allocated in "compile" method.
// For this reason we need to take the address.
if (&compile_data != NULL)
delete &compile_data;
}
};
| hpp |
rticonnextdds-examples | data/projects/rticonnextdds-examples/custom_content_filter/c++03/ccf_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 "ccf.hpp"
#include "filter.hpp"
using namespace dds::core;
using namespace dds::core::policy;
using namespace dds::domain;
using namespace rti::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);
// Register the custom filter type. It must be registered in both sides.
participant->register_contentfilter(
CustomFilter<CustomFilterType>(new CustomFilterType()),
"CustomFilter");
// Create a Topic -- and automatically register the type.
Topic<Foo> topic(participant, "Example ccf");
// Create a DataWriter.
DataWriter<Foo> writer(Publisher(participant), topic);
// Create an instance for writing.
Foo instance;
// Main loop
for (int count = 0; (sample_count == 0) || (count < sample_count); count++){
std::cout << "Writing ccf, count " << count << std::endl;
instance.x(count);
writer.write(instance);
rti::util::sleep(Duration(1));
}
}
int main(int argc, char *argv[])
{
int domain_id = 0;
int sample_count = 0; // Infinite loop
if (argc >= 2) {
domain_id = atoi(argv[1]);
}
if (argc >= 3) {
sample_count = atoi(argv[2]);
}
// To turn on additional logging, include <rti/config/Logger.hpp> and
// uncomment the following line:
// rti::config::Logger::instance().verbosity(rti::config::Verbosity::STATUS_ALL);
try {
publisher_main(domain_id, sample_count);
} catch (std::exception ex) {
std::cout << "Exception caught: " << ex.what() << std::endl;
return -1;
}
return 0;
}
| cxx |
rticonnextdds-examples | data/projects/rticonnextdds-examples/custom_content_filter/c++03/filter.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 <dds/dds.hpp>
#include "ccf.hpp"
using namespace dds::core;
using namespace dds::core::xtypes;
using namespace rti::topic;
// Custom compile data
struct cdata {
long param;
bool (*eval_func)(long, long);
};
bool divide_test(long sample_data, long p) {
return (sample_data % p == 0);
}
bool gt_test(long sample_data, long p) {
return (p > sample_data);
}
class CustomFilterType: public ContentFilter<Foo, cdata> {
public:
// Called when Custom Filter is created, or when parameters are changed.
virtual cdata& compile(const std::string& expression,
const StringSeq& parameters,
const optional<DynamicType>& type_code,
const std::string& type_class_name,
cdata* old_compile_data)
{
// First free old data, if any.
delete old_compile_data;
// We expect an expression of the form "%0 %1 <var>" where
// %1 = "divides" or "greater-than" and <var> is an integral member of
// the msg structure.
// We don't actually check that <var> has the correct typecode,
// (or even that it exists!). See example Typecodes to see
// how to work with typecodes.
// The compile information is a structure including the first filter
// parameter (%0) and a function pointer to evaluate the sample
// Check form.
if (expression.compare(0, 6, "%0 %1 ") != 0) {
throw std::invalid_argument("Invalid filter expression");
}
if (expression.size() < 7) {
throw std::invalid_argument("Invalid filter expression size");
}
/* Check that we have params */
if (parameters.size() < 2) {
throw std::invalid_argument("Invalid filter parameters number");
}
cdata* cd = new cdata();
cd->param = atol(parameters[0].c_str());
if (parameters[1] == "greater-than") {
cd->eval_func = >_test;
} else if (parameters[1] == "divides") {
cd->eval_func = ÷_test;
} else {
throw std::invalid_argument("Invad filter operation");
}
return *cd;
}
// Called to evaluated each sample.
virtual bool evaluate(cdata& compile_data, const Foo& sample,
const FilterSampleInfo& meta_data)
{
return compile_data.eval_func(sample.x(), compile_data.param);
}
virtual void finalize(cdata& compile_data)
{
}
};
| cxx |
rticonnextdds-examples | data/projects/rticonnextdds-examples/multichannel/c++/market_data_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.
******************************************************************************/
/* market_data_subscriber.cxx
A subscription example
This file is derived from code automatically generated by the rtiddsgen
command:
rtiddsgen -language C++ -example <arch> market_data.idl
Example subscription of type market_data 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>/market_data_subscriber <domain_id> <sample_count>
(3) Start the publication with the command
objs/<arch>/market_data_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>/market_data_publisher <domain_id>
objs/<arch>/market_data_subscriber <domain_id>
On Windows:
objs\<arch>\market_data_publisher <domain_id>
objs\<arch>\market_data_subscriber <domain_id>
modification history
------------ -------
*/
#include <stdio.h>
#include <stdlib.h>
#ifdef RTI_VX653
#include <vThreadsData.h>
#endif
#include "market_data.h"
#include "market_dataSupport.h"
#include "ndds/ndds_cpp.h"
class market_dataListener: 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 market_dataListener::on_data_available(DDSDataReader* reader) {
market_dataDataReader *market_data_reader = NULL;
market_dataSeq data_seq;
DDS_SampleInfoSeq info_seq;
DDS_ReturnCode_t retcode;
int i;
market_data_reader = market_dataDataReader::narrow(reader);
if (market_data_reader == NULL) {
printf("DataReader narrow error\n");
return;
}
retcode = market_data_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) {
market_dataTypeSupport::print_data(&data_seq[i]);
}
}
retcode = market_data_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;
DDSContentFilteredTopic *filtered_topic = NULL;
DDS_StringSeq expression_parameters;
market_dataListener *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 = market_dataTypeSupport::get_type_name();
retcode = market_dataTypeSupport::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 market_data", 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 MultiChannel */
filtered_topic = participant->create_contentfilteredtopic_with_filter(
"Example market_data", topic, "Symbol MATCH 'A'",
expression_parameters, DDS_STRINGMATCHFILTER_NAME);
if (filtered_topic == NULL) {
printf("create_contentfilteredtopic error\n");
subscriber_shutdown(participant);
return -1;
}
/* Create a data reader listener */
reader_listener = new market_dataListener();
/* To customize the data reader QoS, use
the configuration file USER_QOS_PROFILES.xml */
reader = subscriber->create_datareader(filtered_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;
}
printf("filter is Symbol MATCH 'A'\n");
/* Main loop */
for (count = 0; (sample_count == 0) || (count < sample_count); ++count) {
/* printf("market_data subscriber sleeping for %d sec...\n",
* receive_period.sec);
*/
if (count == 3) {
retcode = filtered_topic->append_to_expression_parameter(0, "D");
if (retcode != DDS_RETCODE_OK) {
printf("append_to_expression_parameter %d\n", retcode);
subscriber_shutdown(participant);
return -1;
}
printf("changed filter to Symbol MATCH 'AD'\n");
}
if (count == 6) {
retcode = filtered_topic->remove_from_expression_parameter(0, "A");
if (retcode != DDS_RETCODE_OK) {
printf("append_to_expression_parameter %d\n", retcode);
subscriber_shutdown(participant);
return -1;
}
printf("changed filter to Symbol MATCH 'D'\n");
}
NDDSUtility::sleep(receive_period);
}
/* End changes for MultiChannel */
/* 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/multichannel/c++/market_data_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.
******************************************************************************/
/* market_data_publisher.cxx
A publication of data of type market_data
This file is derived from code automatically generated by the rtiddsgen
command:
rtiddsgen -language C++ -example <arch> market_data.idl
Example publication of type market_data 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>/market_data_subscriber <domain_id> <sample_count>
(3) Start the publication with the command
objs/<arch>/market_data_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>/market_data_publisher <domain_id> o
objs/<arch>/market_data_subscriber <domain_id>
On Windows:
objs\<arch>\market_data_publisher <domain_id>
objs\<arch>\market_data_subscriber <domain_id>
modification history
------------ -------
*/
#include <stdio.h>
#include <stdlib.h>
#ifdef RTI_VX653
#include <vThreadsData.h>
#endif
#include "market_data.h"
#include "market_dataSupport.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;
DDS_DataWriterQos writer_qos;
DDSDataWriter *writer = NULL;
market_dataDataWriter * market_data_writer = NULL;
market_data *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, 100000000 };
/* 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 = market_dataTypeSupport::get_type_name();
retcode = market_dataTypeSupport::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 market_data", 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;
}
/* 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 modify the datawriter creation fuction using writer_qos.
*
* In this case, we set the publish as multichannel using the differents
* channel to send differents symbol. Every channel have a IP to send the
* data.
*/
/* Start changes for MultiChannel */
/*
retcode = publisher->get_default_datawriter_qos(writer_qos);
if (retcode != DDS_RETCODE_OK) {
printf("get_default_datawriter_qos error\n");
publisher_shutdown(participant);
return -1;
}
*/
/* Create 8 channels based on Symbol */
/*
writer_qos.multi_channel.channels.ensure_length(8, 8);
writer_qos.multi_channel.channels[0].filter_expression = DDS_String_dup(
"Symbol MATCH '[A-C]*'");
writer_qos.multi_channel.channels[0].multicast_settings.ensure_length(1, 1);
writer_qos.multi_channel.channels[0].multicast_settings[0].receive_address =
DDS_String_dup("239.255.0.2");
writer_qos.multi_channel.channels[1].filter_expression = DDS_String_dup(
"Symbol MATCH '[D-F]*'");
writer_qos.multi_channel.channels[1].multicast_settings.ensure_length(1, 1);
writer_qos.multi_channel.channels[1].multicast_settings[0].receive_address =
DDS_String_dup("239.255.0.3");
writer_qos.multi_channel.channels[2].filter_expression = DDS_String_dup(
"Symbol MATCH '[G-I]*'");
writer_qos.multi_channel.channels[2].multicast_settings.ensure_length(1, 1);
writer_qos.multi_channel.channels[2].multicast_settings[0].receive_address =
DDS_String_dup("239.255.0.4");
writer_qos.multi_channel.channels[3].filter_expression = DDS_String_dup(
"Symbol MATCH '[J-L]*'");
writer_qos.multi_channel.channels[3].multicast_settings.ensure_length(1, 1);
writer_qos.multi_channel.channels[3].multicast_settings[0].receive_address =
DDS_String_dup("239.255.0.5");
writer_qos.multi_channel.channels[4].filter_expression = DDS_String_dup(
"Symbol MATCH '[M-O]*'");
writer_qos.multi_channel.channels[4].multicast_settings.ensure_length(1, 1);
writer_qos.multi_channel.channels[4].multicast_settings[0].receive_address =
DDS_String_dup("239.255.0.6");
writer_qos.multi_channel.channels[5].filter_expression = DDS_String_dup(
"Symbol MATCH '[P-S]*'");
writer_qos.multi_channel.channels[5].multicast_settings.ensure_length(1, 1);
writer_qos.multi_channel.channels[5].multicast_settings[0].receive_address =
DDS_String_dup("239.255.0.7");
writer_qos.multi_channel.channels[6].filter_expression = DDS_String_dup(
"Symbol MATCH '[T-V]*'");
writer_qos.multi_channel.channels[6].multicast_settings.ensure_length(1, 1);
writer_qos.multi_channel.channels[6].multicast_settings[0].receive_address =
DDS_String_dup("239.255.0.8");
writer_qos.multi_channel.channels[7].filter_expression = DDS_String_dup(
"Symbol MATCH '[W-Z]*'");
writer_qos.multi_channel.channels[7].multicast_settings.ensure_length(1, 1);
writer_qos.multi_channel.channels[7].multicast_settings[0].receive_address =
DDS_String_dup("239.255.0.9");
*/
/* To customize data writer QoS, use
the configuration file USER_QOS_PROFILES.xml */
/* toggle between writer_qos and DDS_DATAWRITER_QOS_DEFAULT to alternate
* between using code and using XML to specify the Qos */
writer = publisher->create_datawriter(topic,
/*writer_qos*/DDS_DATAWRITER_QOS_DEFAULT, NULL /* listener */,
DDS_STATUS_MASK_NONE);
if (writer == NULL) {
printf("create_datawriter error\n");
publisher_shutdown(participant);
return -1;
}
/* End changes for MultiChannel */
market_data_writer = market_dataDataWriter::narrow(writer);
if (market_data_writer == NULL) {
printf("DataWriter narrow error\n");
publisher_shutdown(participant);
return -1;
}
/* Create data sample for writing */
instance = market_dataTypeSupport::create_data();
if (instance == NULL) {
printf("market_dataTypeSupport::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 = market_data_writer->register_instance(*instance);
*/
/* Main loop */
for (count = 0; (sample_count == 0) || (count < sample_count); ++count) {
/* Changes for MultiChannel */
/* Modify the data to be sent here */
sprintf(instance->Symbol, "%c", 'A' + (count % 26));
instance->Price = count;
retcode = market_data_writer->write(*instance, instance_handle);
if (retcode != DDS_RETCODE_OK) {
printf("write error %d\n", retcode);
}
NDDSUtility::sleep(send_period);
}
/*
retcode = market_data_writer->unregister_instance(
*instance, instance_handle);
if (retcode != DDS_RETCODE_OK) {
printf("unregister instance error %d\n", retcode);
}
*/
/* Delete data sample */
retcode = market_dataTypeSupport::delete_data(instance);
if (retcode != DDS_RETCODE_OK) {
printf("market_dataTypeSupport::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/multichannel/c/market_data_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.
******************************************************************************/
/* market_data_publisher.c
A publication of data of type market_data
This file is derived from code automatically generated by the rtiddsgen
command:
rtiddsgen -language C -example <arch> market_data.idl
Example publication of type market_data 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>/market_data_subscriber <domain_id> <sample_count>
(3) Start the publication with the command
objs/<arch>/market_data_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>/market_data_publisher <domain_id>
objs/<arch>/market_data_subscriber <domain_id>
On Windows:
objs\<arch>\market_data_publisher <domain_id>
objs\<arch>\market_data_subscriber <domain_id>
modification history
------------ -------
*/
#include <stdio.h>
#include <stdlib.h>
#include "ndds/ndds_c.h"
#include "market_data.h"
#include "market_dataSupport.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;
market_dataDataWriter *market_data_writer = NULL;
market_data *instance = NULL;
DDS_ReturnCode_t retcode;
DDS_InstanceHandle_t instance_handle = DDS_HANDLE_NIL;
const char *type_name = NULL;
int count = 0;
struct DDS_DataWriterQos writer_qos = DDS_DataWriterQos_INITIALIZER;
struct DDS_ChannelSettings_t *curr_channel;
/* Changes for MultiChannel */
struct DDS_Duration_t send_period = { 0, 100000000 };
/* 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 = market_dataTypeSupport_get_type_name();
retcode = market_dataTypeSupport_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 market_data", 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;
}
/* 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 modify the datawriter creation fuction using writer_qos.
*
* In this case, we set the publish as multichannel using the differents
* channel to send differents symbol. Every channel have a IP to send the
* data.
*/
/* Start changes for MultiChannel */
/*
retcode = DDS_Publisher_get_default_datawriter_qos(publisher, &writer_qos);
if (retcode != DDS_RETCODE_OK) {
printf("get_default_datawriter_qos error\n");
publisher_shutdown(participant);
return -1;
}
*/
/* Create 8 channels based on Symbol */
/*
DDS_ChannelSettingsSeq_ensure_length(&writer_qos.multi_channel.channels, 8,
8);
curr_channel = DDS_ChannelSettingsSeq_get_reference(
&writer_qos.multi_channel.channels, 0);
curr_channel->filter_expression = DDS_String_dup("Symbol MATCH '[A-C]*'");
DDS_TransportMulticastSettingsSeq_ensure_length(
&curr_channel->multicast_settings, 1, 1);
DDS_TransportMulticastSettingsSeq_get_reference(
&curr_channel->multicast_settings, 0)->receive_address =
DDS_String_dup("239.255.0.2");
curr_channel = DDS_ChannelSettingsSeq_get_reference(
&writer_qos.multi_channel.channels, 1);
curr_channel->filter_expression = DDS_String_dup("Symbol MATCH '[D-F]*'");
DDS_TransportMulticastSettingsSeq_ensure_length(
&curr_channel->multicast_settings, 1, 1);
DDS_TransportMulticastSettingsSeq_get_reference(
&curr_channel->multicast_settings, 0)->receive_address =
DDS_String_dup("239.255.0.3");
curr_channel = DDS_ChannelSettingsSeq_get_reference(
&writer_qos.multi_channel.channels, 2);
curr_channel->filter_expression = DDS_String_dup("Symbol MATCH '[G-I]*'");
DDS_TransportMulticastSettingsSeq_ensure_length(
&curr_channel->multicast_settings, 1, 1);
DDS_TransportMulticastSettingsSeq_get_reference(
&curr_channel->multicast_settings, 0)->receive_address =
DDS_String_dup("239.255.0.4");
curr_channel = DDS_ChannelSettingsSeq_get_reference(
&writer_qos.multi_channel.channels, 3);
curr_channel->filter_expression = DDS_String_dup("Symbol MATCH '[J-L]*'");
DDS_TransportMulticastSettingsSeq_ensure_length(
&curr_channel->multicast_settings, 1, 1);
DDS_TransportMulticastSettingsSeq_get_reference(
&curr_channel->multicast_settings, 0)->receive_address =
DDS_String_dup("239.255.0.5");
curr_channel = DDS_ChannelSettingsSeq_get_reference(
&writer_qos.multi_channel.channels, 4);
curr_channel->filter_expression = DDS_String_dup("Symbol MATCH '[M-O]*'");
DDS_TransportMulticastSettingsSeq_ensure_length(
&curr_channel->multicast_settings, 1, 1);
DDS_TransportMulticastSettingsSeq_get_reference(
&curr_channel->multicast_settings, 0)->receive_address =
DDS_String_dup("239.255.0.6");
curr_channel = DDS_ChannelSettingsSeq_get_reference(
&writer_qos.multi_channel.channels, 5);
curr_channel->filter_expression = DDS_String_dup("Symbol MATCH '[P-S]*'");
DDS_TransportMulticastSettingsSeq_ensure_length(
&curr_channel->multicast_settings, 1, 1);
DDS_TransportMulticastSettingsSeq_get_reference(
&curr_channel->multicast_settings, 0)->receive_address =
DDS_String_dup("239.255.0.7");
curr_channel = DDS_ChannelSettingsSeq_get_reference(
&writer_qos.multi_channel.channels, 6);
curr_channel->filter_expression = DDS_String_dup("Symbol MATCH '[T-V]*'");
DDS_TransportMulticastSettingsSeq_ensure_length(
&curr_channel->multicast_settings, 1, 1);
DDS_TransportMulticastSettingsSeq_get_reference(
&curr_channel->multicast_settings, 0)->receive_address =
DDS_String_dup("239.255.0.8");
curr_channel = DDS_ChannelSettingsSeq_get_reference(
&writer_qos.multi_channel.channels, 7);
curr_channel->filter_expression = DDS_String_dup("Symbol MATCH '[W-Z]*'");
DDS_TransportMulticastSettingsSeq_ensure_length(
&curr_channel->multicast_settings, 1, 1);
DDS_TransportMulticastSettingsSeq_get_reference(
&curr_channel->multicast_settings, 0)->receive_address =
DDS_String_dup("239.255.0.9");
*/
/* To customize data writer QoS, use
* the configuration file USER_QOS_PROFILES.xml */
/* toggle between writer_qos and DDS_DATAWRITER_QOS_DEFAULT to alternate
* between using code and using XML to specify the Qos */
writer = DDS_Publisher_create_datawriter(publisher, topic,
/*&writer_qos*/&DDS_DATAWRITER_QOS_DEFAULT, NULL /* listener */,
DDS_STATUS_MASK_NONE);
if (writer == NULL) {
printf("create_datawriter error\n");
publisher_shutdown(participant);
return -1;
}
/* End changes for MultiChannel */
market_data_writer = market_dataDataWriter_narrow(writer);
if (market_data_writer == NULL) {
printf("DataWriter narrow error\n");
publisher_shutdown(participant);
return -1;
}
/* Create data sample for writing */
instance = market_dataTypeSupport_create_data_ex(DDS_BOOLEAN_TRUE);
if (instance == NULL) {
printf("market_dataTypeSupport_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 = market_dataDataWriter_register_instance(
market_data_writer, instance);
*/
/* Main loop */
for (count = 0; (sample_count == 0) || (count < sample_count); ++count) {
/* printf("Writing market_data, count %d\n", count); */
/* Changes for MultiChannel */
/* Everey time a character is sent between ['A'-'Z'] */
sprintf(instance->Symbol, "%c", 'A' + (count % 26));
instance->Price = count;
/* Write data */
retcode = market_dataDataWriter_write(market_data_writer, instance,
&instance_handle);
if (retcode != DDS_RETCODE_OK) {
printf("write error %d\n", retcode);
}
NDDS_Utility_sleep(&send_period);
}
/*
retcode = market_dataDataWriter_unregister_instance(
market_data_writer, instance, &instance_handle);
if (retcode != DDS_RETCODE_OK) {
printf("unregister instance error %d\n", retcode);
}
*/
/* Delete data sample */
retcode = market_dataTypeSupport_delete_data_ex(instance, DDS_BOOLEAN_TRUE);
if (retcode != DDS_RETCODE_OK) {
printf("market_dataTypeSupport_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/multichannel/c/market_data_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.
******************************************************************************/
/* market_data_subscriber.c
A subscription example
This file is derived from code automatically generated by the rtiddsgen
command:
rtiddsgen -language C -example <arch> market_data.idl
Example subscription of type market_data 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>/market_data_subscriber <domain_id> <sample_count>
(3) Start the publication with the command
objs/<arch>/market_data_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>/market_data_publisher <domain_id>
objs/<arch>/market_data_subscriber <domain_id>
On Windows systems:
objs\<arch>\market_data_publisher <domain_id>
objs\<arch>\market_data_subscriber <domain_id>
modification history
------------ -------
*/
#include <stdio.h>
#include <stdlib.h>
#include "ndds/ndds_c.h"
#include "market_data.h"
#include "market_dataSupport.h"
void market_dataListener_on_requested_deadline_missed(void* listener_data,
DDS_DataReader* reader,
const struct DDS_RequestedDeadlineMissedStatus *status) {
}
void market_dataListener_on_requested_incompatible_qos(void* listener_data,
DDS_DataReader* reader,
const struct DDS_RequestedIncompatibleQosStatus *status) {
}
void market_dataListener_on_sample_rejected(void* listener_data,
DDS_DataReader* reader, const struct DDS_SampleRejectedStatus *status) {
}
void market_dataListener_on_liveliness_changed(void* listener_data,
DDS_DataReader* reader,
const struct DDS_LivelinessChangedStatus *status) {
}
void market_dataListener_on_sample_lost(void* listener_data,
DDS_DataReader* reader, const struct DDS_SampleLostStatus *status) {
}
void market_dataListener_on_subscription_matched(void* listener_data,
DDS_DataReader* reader,
const struct DDS_SubscriptionMatchedStatus *status) {
}
void market_dataListener_on_data_available(void* listener_data,
DDS_DataReader* reader) {
market_dataDataReader *market_data_reader = NULL;
struct market_dataSeq data_seq = DDS_SEQUENCE_INITIALIZER;
struct DDS_SampleInfoSeq info_seq = DDS_SEQUENCE_INITIALIZER;
DDS_ReturnCode_t retcode;
int i;
market_data_reader = market_dataDataReader_narrow(reader);
if (market_data_reader == NULL) {
printf("DataReader narrow error\n");
return;
}
retcode = market_dataDataReader_take(market_data_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 < market_dataSeq_get_length(&data_seq); ++i) {
if (DDS_SampleInfoSeq_get_reference(&info_seq, i)->valid_data) {
market_dataTypeSupport_print_data(
market_dataSeq_get_reference(&data_seq, i));
}
}
retcode = market_dataDataReader_return_loan(market_data_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 };
DDS_ContentFilteredTopic *filtered_topic = NULL;
struct DDS_StringSeq expression_parameters;
/* 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 = market_dataTypeSupport_get_type_name();
retcode = market_dataTypeSupport_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 market_data", 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 MultiChannel */
filtered_topic =
DDS_DomainParticipant_create_contentfilteredtopic_with_filter(
participant, "Example market_data", topic,
"Symbol MATCH 'A'", &expression_parameters,
DDS_STRINGMATCHFILTER_NAME);
if (filtered_topic == NULL) {
printf("create_contentfilteredtopic error\n");
subscriber_shutdown(participant);
return -1;
}
/* Set up a data reader listener */
reader_listener.on_requested_deadline_missed =
market_dataListener_on_requested_deadline_missed;
reader_listener.on_requested_incompatible_qos =
market_dataListener_on_requested_incompatible_qos;
reader_listener.on_sample_rejected = market_dataListener_on_sample_rejected;
reader_listener.on_liveliness_changed =
market_dataListener_on_liveliness_changed;
reader_listener.on_sample_lost = market_dataListener_on_sample_lost;
reader_listener.on_subscription_matched =
market_dataListener_on_subscription_matched;
reader_listener.on_data_available = market_dataListener_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(filtered_topic),
&DDS_DATAREADER_QOS_DEFAULT, &reader_listener, DDS_STATUS_MASK_ALL);
if (reader == NULL) {
printf("create_datareader error\n");
subscriber_shutdown(participant);
return -1;
}
printf("filter is Symbol MATCH 'A'\n");
/* Main loop */
for (count = 0; (sample_count == 0) || (count < sample_count); ++count) {
/* printf("market_data subscriber sleeping for %d sec...\n",
poll_period.sec);
*/
if (count == 3) {
retcode = DDS_ContentFilteredTopic_append_to_expression_parameter(
filtered_topic, 0, "D");
if (retcode != DDS_RETCODE_OK) {
printf("append_to_expression_parameter %d\n", retcode);
subscriber_shutdown(participant);
return -1;
}
printf("changed filter to Symbol MATCH 'AD'\n");
}
if (count == 6) {
retcode = DDS_ContentFilteredTopic_remove_from_expression_parameter(
filtered_topic, 0, "A");
if (retcode != DDS_RETCODE_OK) {
printf("append_to_expression_parameter %d\n", retcode);
subscriber_shutdown(participant);
return -1;
}
printf("changed filter to Symbol MATCH 'D'\n");
}
NDDS_Utility_sleep(&poll_period);
}
/* End changes for MultiChannel */
/* 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/multichannel/c++03/market_data_subscriber.cxx | /*******************************************************************************
(c) 2005-2015 Copyright, Real-Time Innovations, Inc. All rights reserved.
RTI grants Licensee a license to use, modify, compile, and create derivative
works of the Software. Licensee has the right to distribute object form only
for use with RTI products. The Software is provided "as is", with no warranty
of any type, including any warranty for fitness for any purpose. RTI is under
no obligation to maintain or support the Software. RTI shall not be liable for
any incidental or consequential damages arising out of the use or inability to
use the software.
******************************************************************************/
#include <algorithm>
#include <iostream>
#include <dds/dds.hpp>
#include <rti/core/ListenerBinder.hpp>
#include "market_data.hpp"
using namespace dds::core;
using namespace rti::core;
using namespace dds::core::status;
using namespace dds::domain;
using namespace dds::sub;
using namespace dds::topic;
class MarketDataReaderListener : public NoOpDataReaderListener<market_data> {
public:
void on_data_available(DataReader<market_data>& reader)
{
// Take all samples
LoanedSamples<market_data> samples = reader.take();
for (LoanedSamples<market_data>::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)
{
// Create a DomainParticipant with default Qos
DomainParticipant participant(domain_id);
// Create a Topic -- and automatically register the type
Topic<market_data> topic(participant, "Example market_data");
// Create a ContentFiltered Topic and specify the STRINGMATCH filter name
// to use a built-in filter for matching multiple strings.
// More information can be found in the example
// 'content_filtered_topic_string_filter'.
Filter filter("Symbol MATCH 'A'", std::vector<std::string>());
filter->name(rti::topic::stringmatch_filter_name());
std::cout << "filter is " << filter.expression() << std::endl;
ContentFilteredTopic<market_data> cft_topic(
topic,
"ContentFilteredTopic",
filter);
// Create a DataReader with default Qos (Subscriber created in-line)
DataReader<market_data> reader(Subscriber(participant), cft_topic);
// Create a data reader listener using ListenerBinder, a RAII that
// will take care of setting it to NULL on destruction.
rti::core::ListenerBinder< DataReader<market_data> > scoped_listener =
rti::core::bind_and_manage_listener(
reader,
new MarketDataReaderListener,
StatusMask::data_available());
// Main loop.
for (int count = 0; sample_count == 0 || count < sample_count; count++) {
if (count == 3) {
// On t=3 we add the symbol 'D' to the filter parameter
// to match 'A' and 'D'.
cft_topic->append_to_expression_parameter(0, "D");
std::cout << "changed filter to Symbol MATCH 'AD'" << std::endl;
} else if (count == 6) {
// On t=6 we remove the symbol 'A' to the filter paramter
// to match only 'D'.
cft_topic->remove_from_expression_parameter(0, "A");
std::cout << "changed filter to Symbol MATCH 'D'" << std::endl;
}
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/multichannel/c++03/market_data_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/dds.hpp>
#include "market_data.hpp"
using namespace dds::core;
using namespace rti::core;
using namespace rti::core::policy;
using namespace dds::domain;
using namespace dds::topic;
using namespace dds::pub;
using namespace dds::pub::qos;
MultiChannel create_multichannel_qos()
{
// We set the publish as multichannel using the different
// channels to send different symbols. Every channel have a IP to send the
// data.
// Create 8 channels based on Symbol.
std::vector<ChannelSettings> channels;
channels.push_back(ChannelSettings(
std::vector<TransportMulticastSettings>(
1,
TransportMulticastSettings(
std::vector<std::string>(), // All the transports available
"239.255.0.2",
0)), // Port determined automatically
"Symbol MATCH '[A-C]*'",
PUBLICATION_PRIORITY_UNDEFINED));
channels.push_back(ChannelSettings(
std::vector<TransportMulticastSettings>(
1,
TransportMulticastSettings(
std::vector<std::string>(),
"239.255.0.3",
0)),
"Symbol MATCH '[D-F]*'",
PUBLICATION_PRIORITY_UNDEFINED));
channels.push_back(ChannelSettings(
std::vector<TransportMulticastSettings>(
1,
TransportMulticastSettings(
std::vector<std::string>(),
"239.255.0.4",
0)),
"Symbol MATCH '[G-I]*'",
PUBLICATION_PRIORITY_UNDEFINED));
channels.push_back(ChannelSettings(
std::vector<TransportMulticastSettings>(
1,
TransportMulticastSettings(
std::vector<std::string>(),
"239.255.0.5",
0)),
"Symbol MATCH '[J-L]*'",
PUBLICATION_PRIORITY_UNDEFINED));
channels.push_back(ChannelSettings(
std::vector<TransportMulticastSettings>(
1,
TransportMulticastSettings(
std::vector<std::string>(),
"239.255.0.6",
0)),
"Symbol MATCH '[M-O]*'",
PUBLICATION_PRIORITY_UNDEFINED));
channels.push_back(ChannelSettings(
std::vector<TransportMulticastSettings>(
1,
TransportMulticastSettings(
std::vector<std::string>(),
"239.255.0.7",
0)),
"Symbol MATCH '[P-S]*'",
PUBLICATION_PRIORITY_UNDEFINED));
channels.push_back(ChannelSettings(
std::vector<TransportMulticastSettings>(
1,
TransportMulticastSettings(
std::vector<std::string>(),
"239.255.0.8",
0)),
"Symbol MATCH '[T-V]*'",
PUBLICATION_PRIORITY_UNDEFINED));
channels.push_back(ChannelSettings(
std::vector<TransportMulticastSettings>(
1,
TransportMulticastSettings(
std::vector<std::string>(),
"239.255.0.9",
0)),
"Symbol MATCH '[W-Z]*'",
PUBLICATION_PRIORITY_UNDEFINED));
// Set the MultiChannel QoS.
return MultiChannel(channels, rti::topic::stringmatch_filter_name());
}
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<market_data> topic (participant, "Example market_data");
// Retrieve the default DataWriter QoS, from USER_QOS_PROFILES.xml
DataWriterQos writer_qos = QosProvider::Default().datawriter_qos();
// If you want to change the DataWriter's QoS programmatically rather than
// using the XML file, uncomment the following line.
// writer_qos << create_multichannel_qos();
// Create a DataWriter (Publisher created in-line)
DataWriter<market_data> writer(Publisher(participant), topic, writer_qos);
// Create a data sample for writing.
market_data sample;
// Main loop.
for (int count = 0; count < sample_count || sample_count == 0; count++) {
// Update the sample.
char symbol = (char)('A' + (count % 26));
sample.Symbol(std::string(1, symbol));
sample.Price(count);
// Send and wait.
writer.write(sample);
rti::util::sleep(Duration::from_millisecs(100));
}
}
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/recording_service/pluggable_storage/cpp/FileStorageReader.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 "FileStorageReader.hpp"
#include "dds/dds.hpp"
#include <limits>
#define NANOSECS_PER_SEC 1000000000ll
namespace rti { namespace recording { namespace cpp_example {
/*
* Convenience macro to define the C-style function that will be called by RTI
* Recording Service to create your class.
*/
RTI_RECORDING_STORAGE_READER_CREATE_DEF(FileStorageReader);
/*
* In the XML configuration, under the property tag for the storage plugin, a
* collection of name/value pairs can be passed. In this case, this example
* chooses to define a property to name the filename to use.
*/
FileStorageReader::FileStorageReader(
const rti::routing::PropertySet &properties)
: StorageReader(properties)
{
rti::routing::PropertySet::const_iterator found =
properties.find("example.cpp_pluggable_storage.filename");
if (found == properties.end()) {
throw std::runtime_error("Failed to get file name from properties");
}
file_name_ = std::string(found->second);
info_file_.open(
(file_name_ + ".info").c_str(),
std::ios::in | std::ios::binary);
if (!info_file_.good()) {
throw std::runtime_error("Failed to open metadata file");
}
data_file_.open(file_name_.c_str(), std::ios::in | std::ios::binary);
if (!data_file_.good()) {
throw std::runtime_error("Failed to open data file");
}
}
FileStorageReader::~FileStorageReader()
{
}
rti::recording::storage::StorageStreamInfoReader *
FileStorageReader::create_stream_info_reader(
const rti::routing::PropertySet &)
{
return new FileStorageStreamInfoReader(&info_file_);
}
void FileStorageReader::delete_stream_info_reader(
rti::recording::storage::StorageStreamInfoReader *stream_info_reader)
{
delete stream_info_reader;
}
rti::recording::storage::StorageStreamReader *
FileStorageReader::create_stream_reader(
const rti::routing::StreamInfo &,
const rti::routing::PropertySet &)
{
return new FileStorageStreamReader(&data_file_);
}
void FileStorageReader::delete_stream_reader(
rti::recording::storage::StorageStreamReader *stream_reader)
{
delete stream_reader;
}
using namespace dds::core::xtypes;
/*
* Create a data stream reader. For each discovered stream that matches the set
* of interest defined in the configuration, Replay or Converter will ask us to
* create a reader for that stream (a stream reader).
* The start and stop timestamp parameters define the time range for which the
* application is asking for data. For simplicity, this example doesn't do
* anything with these parameters. But the correct way to implement this API
* would be to not read any data recorded before the given start time or after
* the given end time.
*/
FileStorageStreamReader::FileStorageStreamReader(std::ifstream *data_file)
: data_file_(data_file), type_("HelloMsg")
{
type_.add_member(Member("id", primitive_type<int32_t>()).key(true));
type_.add_member(Member("msg", StringType(256)));
/* read-ahead, EOF is not an error */
if (!read_sample()) {
std::cout << "info: no first sample, storage file seems to be empty"
<< std::endl;
}
}
FileStorageStreamReader::~FileStorageStreamReader()
{
}
bool FileStorageStreamReader::read_sample()
{
// read sample into cache
std::string prefix;
uint64_t sample_nr = 0;
*data_file_ >> prefix;
// we won't accept partial data, but it's no error to find the end of data
if (data_file_->eof()) {
return false;
}
if (data_file_->fail()) {
throw std::runtime_error(
"Failed to read prefix for sample number from file");
}
if (prefix != std::string("Sample")) {
throw std::runtime_error(
"Failed to match prefix for sample number from file");
}
*data_file_ >> prefix;
if (data_file_->fail()) {
throw std::runtime_error(
"Failed to read prefix for sample number from file");
}
if (prefix != std::string("number:")) {
throw std::runtime_error(
"Failed to match prefix for sample number from file");
}
*data_file_ >> sample_nr;
if (data_file_->fail()) {
throw std::runtime_error("Failed to read sample number from file");
}
*data_file_ >> prefix;
if (data_file_->fail()) {
throw std::runtime_error(
"Failed to read prefix for reception timestamp from file");
}
if (prefix != std::string("Reception")) {
throw std::runtime_error(
"Failed to match prefix for reception timestamp from file");
}
*data_file_ >> prefix;
if (data_file_->fail()) {
throw std::runtime_error(
"Failed to read prefix for reception timestamp from file");
}
if (prefix != std::string("timestamp:")) {
throw std::runtime_error(
"Failed to match prefix for reception timestamp from file");
}
*data_file_ >> current_timestamp_;
if (data_file_->fail()) {
throw std::runtime_error("Failed to read current timestamp from file");
}
*data_file_ >> prefix;
if (data_file_->fail()) {
throw std::runtime_error(
"Failed to read prefix for valid data from file");
}
if (prefix != std::string("Valid")) {
throw std::runtime_error(
"Failed to match prefix for valid data from file");
}
*data_file_ >> prefix;
if (data_file_->fail()) {
throw std::runtime_error(
"Failed to read prefix for valid data from file");
}
if (prefix != std::string("data:")) {
throw std::runtime_error(
"Failed to match prefix for valid data from file");
}
*data_file_ >> current_valid_data_;
if (data_file_->fail()) {
throw std::runtime_error(
"Failed to read current valid data flag from file");
}
if (current_valid_data_) {
*data_file_ >> prefix;
if (data_file_->fail()) {
throw std::runtime_error(
"Failed to read prefix for Data.id from file");
}
if (prefix != std::string("Data.id:")) {
throw std::runtime_error(
"Failed to match prefix for Data.id from file");
}
*data_file_ >> current_data_id_;
if (data_file_->fail()) {
throw std::runtime_error(
"Failed to read current data.id field from file");
}
*data_file_ >> prefix;
if (data_file_->fail()) {
throw std::runtime_error(
"Failed to read prefix for Data.msg from file");
}
if (prefix != std::string("Data.msg:")) {
throw std::runtime_error(
"Failed to match prefix for Data.msg from file");
}
std::getline(*data_file_, current_data_msg_);
if (data_file_->fail()) {
throw std::runtime_error(
"Failed to read current data.msg field from file");
}
std::getline(*data_file_, prefix);
if (prefix != std::string("")) {
throw std::runtime_error(
"Failed to terminator for sample from file");
}
}
return true;
}
/* In this call, the timestamp argument provides the end-timestamp that the
* Replay Service or Converter is querying. The plugin should provide only
* stream information that has not already been taken, and has a timestamp less
* than or equal to the timestamp_limit. */
void FileStorageStreamReader::read(
std::vector<dds::core::xtypes::DynamicData *> &sample_seq,
std::vector<dds::sub::SampleInfo *> &info_seq,
const rti::recording::storage::SelectorState &selector)
{
int64_t timestamp_limit = selector.timestamp_range_end();
/*
* Add the currently read sample and sample info values to the taken data
* and info collections (sequences), as long as their timestamp does not
* exceed the timestamp_limit provided
*/
if (current_timestamp_ > timestamp_limit) {
return;
}
if (finished()) {
return;
}
int32_t read_samples = 0;
/*
* The value of the sample selector's max samples could be
* dds::core::LENGTH_UNLIMITED, indicating that no maximum number of
* samples. But this value is actually negative, so a straight comparison
* against it could yield unexpected results. Transform the value into
* something we can compare against.
*/
const int32_t max_samples =
(selector.max_samples() == dds::core::LENGTH_UNLIMITED)
? std::numeric_limits<int32_t>::max()
: selector.max_samples();
/*
* Check if the currently cached sample's reception timestamp is within the
* selector's time limit and number of samples. If that is the case, it will
* be added to the collection of samples to be returned by this call.
*/
while (current_timestamp_ <= timestamp_limit
&& read_samples < max_samples) {
read_samples++;
using namespace dds::core::xtypes;
DynamicData *read_data = new DynamicData(type_);
read_data->value("id", current_data_id_);
read_data->value("msg", current_data_msg_);
sample_seq.push_back(read_data);
DDS_SampleInfo read_sampleInfo = DDS_SAMPLEINFO_DEFAULT;
read_sampleInfo.valid_data =
current_valid_data_ ? DDS_BOOLEAN_TRUE : DDS_BOOLEAN_FALSE;
read_sampleInfo.reception_timestamp.sec =
(DDS_Long)(current_timestamp_ / (int64_t) NANOSECS_PER_SEC);
read_sampleInfo.reception_timestamp.nanosec =
current_timestamp_ % (int64_t) NANOSECS_PER_SEC;
dds::sub::SampleInfo *cpp_sample_info = new dds::sub::SampleInfo;
(*cpp_sample_info)->native(read_sampleInfo);
info_seq.push_back(cpp_sample_info);
/* Read ahead next sample, until EOF */
if (!read_sample()) {
break;
}
}
}
void FileStorageStreamReader::return_loan(
std::vector<dds::core::xtypes::DynamicData *> &sample_seq,
std::vector<dds::sub::SampleInfo *> &info_seq)
{
for (size_t i = 0; i < sample_seq.size(); i++) {
delete sample_seq[i];
delete info_seq[i];
}
sample_seq.clear();
info_seq.clear();
}
bool FileStorageStreamReader::finished()
{
if (data_file_->eof()) {
return true;
} else {
return false;
}
}
void FileStorageStreamReader::reset()
{
data_file_->clear();
data_file_->seekg(0);
/* read-ahead, EOF is not an error */
if (!read_sample()) {
std::cout << "info: no first sample, storage file seems to be empty"
<< std::endl;
}
}
FileStorageStreamInfoReader::FileStorageStreamInfoReader(
std::ifstream *info_file)
: info_file_(info_file),
stream_info_taken_(false),
example_stream_info_("Example_Cpp_Storage", "HelloMsg"),
example_type_("HelloMsg")
{
using namespace dds::core::xtypes;
example_stream_info_.type_info().type_representation_kind(
rti::routing::TypeRepresentationKind::DYNAMIC_TYPE);
// Manually add members of the type
example_type_.add_member(
dds::core::xtypes::Member("id", primitive_type<int32_t>())
.key(true));
example_type_.add_member(Member("msg", StringType(256)));
example_stream_info_.type_info().type_representation(
&example_type_.native());
}
FileStorageStreamInfoReader::~FileStorageStreamInfoReader()
{
}
/*
* Replay (or Converter) will periodically ask for any newly discovered data
* streams.
* This function receives a time limit parameter. It should return any
* discovery event not having been taken yet and within the given time limit
* (associated time of the event should be less or equal to the time limit).
* In our example we only store one topic and type, described in the provided
* IDL file (HelloMsg.idl). We simulate we discover that stream in the very
* first call to this function. Every other call to this function will return
* an empty count of taken elements.
*/
void FileStorageStreamInfoReader::read(
std::vector<rti::routing::StreamInfo *> &sample_seq,
const rti::recording::storage::SelectorState &)
{
/*
* In this call, we would walk the stored data and discover what streams
* are there with timestamps that do not exceed the given timestamp_limit.
*
* This example does not read the type code for the saved stream from the
* file; instead, it defines the type code programmatically here. In a real
* implementation, it could be read from the database if it was written
* when store() got called.
*
* For this example, we will just assume there is a single stream (because
* we know this from the writer side of the example plugin), so we populate
* here a single sample and associated sample_info into the vectors passed
* by reference directly instead of reading them from a file, to signal the
* creation of the stream we want to replay, but after the first call,
* we'll set a flag so we return early and dont "discover" any more streams
* after the first call.
*/
if (stream_info_taken_) {
return;
}
// here we populate a stream info corresponding to the recorded topic
// we will need to free this in this discovery stream reader's return_loan
sample_seq.push_back(&example_stream_info_);
// in this example, we simulate a single stream so from this point on dont
// yield results in this discovery reader.
stream_info_taken_ = true;
}
void FileStorageStreamInfoReader::return_loan(
std::vector<rti::routing::StreamInfo *> &sample_seq)
{
sample_seq.clear();
}
/*
* Replay and Converter need to know the initial and final timestamps of the
* recording being read.
* In the case of our example, this information is stored in the associated
* '.info' file.
*/
int64_t FileStorageStreamInfoReader::service_start_time()
{
std::string line;
int64_t timestamp = 0;
std::getline(*info_file_, line, ':');
std::getline(*info_file_, line);
std::stringstream stream(line);
stream >> timestamp;
return timestamp;
}
/*
* Replay and Converter need to know the initial and final timestamps of the
* recording being read.
* In the case of our example, this information is stored in the associated
* '.info' file.
*/
int64_t FileStorageStreamInfoReader::service_stop_time()
{
std::string line;
int64_t timestamp = 0;
std::getline(*info_file_, line, ':');
std::getline(*info_file_, line);
std::stringstream stream(line);
stream >> timestamp;
return timestamp;
}
bool FileStorageStreamInfoReader::finished()
{
return stream_info_taken_;
}
void FileStorageStreamInfoReader::reset()
{
stream_info_taken_ = false;
}
}}} // namespace rti::recording::cpp_example
| cxx |
rticonnextdds-examples | data/projects/rticonnextdds-examples/recording_service/pluggable_storage/cpp/HelloMsg_subscriber.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 <iostream>
#include <dds/core/ddscore.hpp>
#include <dds/sub/ddssub.hpp>
// Or simply include <dds/dds.hpp>
#include "HelloMsg.hpp"
class HelloMsgReaderListener
: public dds::sub::NoOpDataReaderListener<HelloMsg> {
public:
HelloMsgReaderListener() : count_(0)
{
}
void on_data_available(dds::sub::DataReader<HelloMsg> &reader)
{
// Take all samples
dds::sub::LoanedSamples<HelloMsg> samples = reader.take();
for (dds::sub::LoanedSamples<HelloMsg>::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<HelloMsg> topic(participant, "Example_Cpp_Storage");
// Create a DataReader with default Qos (Subscriber created in-line)
HelloMsgReaderListener listener;
dds::sub::DataReader<HelloMsg> 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 << "HelloMsg 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/recording_service/pluggable_storage/cpp/FileStorageWriter.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.
*/
#include "rti/recording/storage/StorageDiscoveryStreamWriter.hpp"
#include "rti/recording/storage/StorageStreamWriter.hpp"
#include "rti/recording/storage/StorageWriter.hpp"
#include <fstream>
namespace rti { namespace recording { namespace cpp_example {
/*
* Convenience macro to forward-declare the C-style function that will be
* called by RTI Recording Service to create your class.
*/
RTI_RECORDING_STORAGE_WRITER_CREATE_DECL(FileStorageWriter);
/*
* This class acts as a factory for Stream Writer objects, that store data
* samples in a text file, transforming them from dynamic data representation
* into text.
* This storage writer creates three files: 1) a data file with the text
* samples; 2) a publication file, containing a subset of the information in the
* DCPSPublication built-in discovery topic samples; and 3) an info file, that
* only contains the starting and ending points in time where there are data
* samples.
*/
class FileStorageWriter : public rti::recording::storage::StorageWriter {
public:
FileStorageWriter(const rti::routing::PropertySet &properties);
virtual ~FileStorageWriter();
/*
* Recording Service will call this method to create a Stream Writer object
* associated with a user-data topic that has been discovered.
* The property set passed as a parameter contains information about the
* stream not provided by the stream info object. For example, Recording
* Service will add the DDS domain ID as a property to this set.
*/
rti::recording::storage::StorageStreamWriter *create_stream_writer(
const rti::routing::StreamInfo &stream_info,
const rti::routing::PropertySet &properties);
/*
* Recording Service will call this method to obtain a stream writer for the
* DDS publication built-in discovery topic.
* Note that we're not defining a participant or subscription creation
* method. That is telling Recording Service that we're not going to store
* samples for those two built-in topics.
*/
rti::recording::storage::PublicationStorageWriter *
create_publication_writer();
/*
* Recording Service will call this method to delete a previously created
* Stream Writer (no matter if it was created with the
* create_stream_writer() or create_discovery_stream_writer() method).
*/
void delete_stream_writer(
rti::recording::storage::StorageStreamWriter *writer);
private:
std::ofstream data_file_;
std::ofstream info_file_;
std::ofstream pub_file_;
};
/**
* This class implements the provided DynamicData specialization of a
* StorageStreamWriter to transform dynamic data objects into a text
* representation that it stores into a file. It also stores some of the
* sample info fields (reception timestamp, valid data flag) so that this info
* is later available for StorageStreamReaders (see file FileStorageReader.hpp)
* to convert or replay samples within a specified time range.
*/
class FileStreamWriter :
public rti::recording::storage::DynamicDataStorageStreamWriter {
public:
FileStreamWriter(std::ofstream &data_file, const std::string &stream_info);
virtual ~FileStreamWriter();
/*
* This method receives a collection of Dynamic Data objects that are
* transformed into a textual representation and stored in a text file.
* Some of the fields in the SampleInfo object are also transformed.
*/
void store(
const std::vector<dds::core::xtypes::DynamicData *> &sample_seq,
const std::vector<dds::sub::SampleInfo *> &info_seq);
private:
uint64_t stored_sample_count_;
std::ofstream &data_file_;
std::string stream_name_;
};
/*
* This class is created by the FileStorageWriter factory class when the
* DCPSPublication built-in discovery topic is detected. This example stores
* these samples in a separate file. Unlike with the user-data samples, the
* discovery types are represented by their specific types (in the case of
* DCPSPublication, dds::topic::PublicationBuiltinTopicData). The API provides
* strongly-typed classes to store the different discovery types for your
* convenience. In the case of this class, we've extended the
* PublicationStorageDiscoveryStreamWriter class.
*/
class PubDiscoveryFileStreamWriter :
public rti::recording::storage::PublicationStorageWriter {
public:
PubDiscoveryFileStreamWriter(std::ofstream &pub_file);
~PubDiscoveryFileStreamWriter();
void store(
const std::vector<dds::topic::PublicationBuiltinTopicData *> &sample_seq,
const std::vector<dds::sub::SampleInfo *> &info_seq);
private:
std::ofstream &pub_file_;
uint32_t stored_sample_count_;
};
} } } // namespace rti::recording::cpp_example
| hpp |
rticonnextdds-examples | data/projects/rticonnextdds-examples/recording_service/pluggable_storage/cpp/FileStorageWriter.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 "FileStorageWriter.hpp"
#define FILESTORAGEWRITER_INDENT_LEVEL (4)
#define NANOSECS_PER_SEC 1000000000ll
namespace rti { namespace recording { namespace cpp_example {
/*
* Convenience macro to define the C-style function that will be called by RTI
* Recording Service to create your class.
*/
RTI_RECORDING_STORAGE_WRITER_CREATE_DEF(FileStorageWriter);
/*
* In the XML configuration, under the property tag for the storage plugin, a
* collection of name/value pairs can be passed. In this case, this example
* chooses to define a property to name the filename to use.
*/
FileStorageWriter::FileStorageWriter(
const rti::routing::PropertySet &properties)
: StorageWriter(properties)
{
rti::routing::PropertySet::const_iterator found =
properties.find("example.cpp_pluggable_storage.filename");
if (found == properties.end()) {
throw std::runtime_error("Failed to get file name from properties");
}
std::string data_filename_ = found->second;
data_file_.open(data_filename_.c_str(), std::ios::out);
if (!data_file_.good()) {
throw std::runtime_error("Failed to open file to store data samples");
}
std::string pub_filename_ = data_filename_ + ".pub";
pub_file_.open(pub_filename_.c_str(), std::ios::out);
if (!pub_file_.good()) {
throw std::runtime_error(
"Failed to open file to store publication data samples");
}
std::string info_filename_ = data_filename_ + ".info";
info_file_.open(info_filename_.c_str(), std::ios::out);
if (!info_file_.good()) {
throw std::runtime_error("Failed to open file to store metadata");
}
// populate the info file with start timestamp
/* Obtain current time */
int64_t current_time = (int64_t) time(NULL);
if (current_time == -1) {
throw std::runtime_error("Failed to obtain the current time");
}
/* Time was returned in seconds. Transform to nanoseconds */
current_time *= NANOSECS_PER_SEC;
info_file_ << "Start timestamp: " << current_time << std::endl;
if (info_file_.fail()) {
throw std::runtime_error("Failed to write start timestamp");
}
}
FileStorageWriter::~FileStorageWriter()
{
if (info_file_.good()) {
/* Obtain current time */
int64_t current_time = (int64_t) time(NULL);
if (current_time == -1) {
// can't throw in a destructor
std::cerr << "Failed to obtain the current time";
}
/* Time was returned in seconds. Transform to nanoseconds */
current_time *= NANOSECS_PER_SEC;
info_file_ << "End timestamp: " << current_time << std::endl;
}
}
rti::recording::storage::StorageStreamWriter *
FileStorageWriter::create_stream_writer(
const rti::routing::StreamInfo &stream_info,
const rti::routing::PropertySet &)
{
return new FileStreamWriter(data_file_, stream_info.stream_name());
}
rti::recording::storage::PublicationStorageWriter *
FileStorageWriter::create_publication_writer()
{
return new PubDiscoveryFileStreamWriter(pub_file_);
}
void FileStorageWriter::delete_stream_writer(
rti::recording::storage::StorageStreamWriter *writer)
{
delete writer;
}
FileStreamWriter::FileStreamWriter(
std::ofstream &data_file,
const std::string &stream_name)
: stored_sample_count_(0),
data_file_(data_file),
stream_name_(stream_name)
{
}
FileStreamWriter::~FileStreamWriter()
{
}
/*
* This function is called by Recorder whenever there are samples available for
* one of the streams previously discovered and accepted (see the
* FileStorageWriter_create_stream_writer() function below). Recorder provides
* the samples and their associated information objects in Routing Service
* format, this is, untyped format.
* In our case we know that, except for the built-in DDS discovery topics which
* are received in their own format - and that we're not really storing -, that
* the format of the data we're receiving is DDS Dynamic Data. This will always
* be the format received for types recorded from DDS.
* The function traverses the collection of samples and stores the data in a
* textual format.
*/
void FileStreamWriter::store(
const std::vector<dds::core::xtypes::DynamicData *> &sample_seq,
const std::vector<dds::sub::SampleInfo *> &info_seq)
{
using namespace dds::core::xtypes;
using namespace rti::core::xtypes;
using namespace dds::sub;
const int32_t count = sample_seq.size();
for (int32_t i = 0; i < count; ++i) {
const SampleInfo &sample_info = *(info_seq[i]);
// we first first print the sample's metadata
int64_t timestamp = (int64_t) sample_info->reception_timestamp().sec()
* NANOSECS_PER_SEC;
timestamp += sample_info->reception_timestamp().nanosec();
data_file_ << "Sample number: " << stored_sample_count_ << std::endl;
data_file_ << "Reception timestamp: " << timestamp << std::endl;
data_file_ << "Valid data: " << sample_info->valid() << std::endl;
// now print sample data
if (sample_info->valid()) {
data_file_ << " Data.id: " << sample_seq[i]->value<int32_t>("id")
<< std::endl;
// Get and store the sample's msg field
data_file_ << " Data.msg: "
<< sample_seq[i]->value<dds::core::string>("msg").c_str()
<< std::endl;
}
stored_sample_count_++;
}
}
PubDiscoveryFileStreamWriter::PubDiscoveryFileStreamWriter(
std::ofstream &pub_file)
: pub_file_(pub_file), stored_sample_count_(0)
{
}
PubDiscoveryFileStreamWriter::~PubDiscoveryFileStreamWriter()
{
}
void PubDiscoveryFileStreamWriter::store(
const std::vector<dds::topic::PublicationBuiltinTopicData *>
&sample_seq,
const std::vector<dds::sub::SampleInfo *> &info_seq)
{
using namespace dds::sub;
const int32_t count = sample_seq.size();
for (int32_t i = 0; i < count; ++i) {
const SampleInfo &sample_info = *(info_seq[i]);
// we first first print the sample's metadata
int64_t timestamp = (int64_t) sample_info->reception_timestamp().sec()
* NANOSECS_PER_SEC;
timestamp += sample_info->reception_timestamp().nanosec();
pub_file_ << "Sample number: " << stored_sample_count_ << std::endl;
pub_file_ << "Reception timestamp: " << timestamp << std::endl;
pub_file_ << "Valid data: " << sample_info->valid() << std::endl;
// now print sample data
if (sample_info->valid()) {
pub_file_ << "Topic name: " << sample_seq[i]->topic_name()
<< std::endl;
pub_file_ << "Type name: " << sample_seq[i]->type_name()
<< std::endl;
}
stored_sample_count_++;
}
}
}}} // namespace rti::recording::cpp_example
| cxx |
rticonnextdds-examples | data/projects/rticonnextdds-examples/recording_service/pluggable_storage/cpp/FileStorageReader.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.
*/
#include "rti/recording/storage/StorageReader.hpp"
#include <fstream>
namespace rti { namespace recording { namespace cpp_example {
/*
* Convenience macro to forward-declare the C-style function that will be
* called by RTI Recording Service to create your class.
*/
RTI_RECORDING_STORAGE_READER_CREATE_DECL(FileStorageReader);
/**
* This class acts as a factory for objects of classes FileStorageStreamReader
* and FileStorageStreamInfoReader. These objects are used by Replay and/or
* Converter to retrieve data from the storage.
*/
class FileStorageReader : public rti::recording::storage::StorageReader {
public:
FileStorageReader(const rti::routing::PropertySet &properties);
~FileStorageReader();
rti::recording::storage::StorageStreamInfoReader *create_stream_info_reader(
const rti::routing::PropertySet &properties);
void delete_stream_info_reader(
rti::recording::storage::StorageStreamInfoReader
*stream_info_reader);
rti::recording::storage::StorageStreamReader *create_stream_reader(
const rti::routing::StreamInfo &stream_info,
const rti::routing::PropertySet &properties);
void delete_stream_reader(
rti::recording::storage::StorageStreamReader *stream_reader);
private:
std::ifstream info_file_;
std::ifstream data_file_;
std::string file_name_;
};
/*
* This class uses the provided DynamicData specialization of a
* StorageStreamReader to read data stored by the classes in file
* FileStorageWriter.hpp, for a given data stream (DDS topic).
* All data is stored in a text file. Data is serialized to a text format.
* Note: this example is only fit to work with the provided type definition
* (type HelloMsg - see HelloMsg.idl for more information).
*/
class FileStorageStreamReader
: public rti::recording::storage::DynamicDataStorageStreamReader {
public:
FileStorageStreamReader(std::ifstream *data_file);
virtual ~FileStorageStreamReader();
/*
* Implementation of the read operation. It should interpret the selector
* state object that expresses the specific needs of Replay/Converter about
* the data to be provided (data not read before vs data of any kind, lower
* and upper time limits, etc).
*/
virtual void
read(std::vector<dds::core::xtypes::DynamicData *> &sample_seq,
std::vector<dds::sub::SampleInfo *> &info_seq,
const rti::recording::storage::SelectorState &selector);
/*
* The return loan operation should free any resources allocated by the
* read() operation.
*/
virtual void return_loan(
std::vector<dds::core::xtypes::DynamicData *> &sample_seq,
std::vector<dds::sub::SampleInfo *> &info_seq);
/*
* This method should flag Replay/Converter that all data related to the
* data stream has been read and that we're ready for termination.
*/
virtual bool finished();
virtual void reset();
private:
std::ifstream *data_file_;
int64_t current_timestamp_;
int current_valid_data_;
DDS_Long current_data_id_;
std::string current_data_msg_;
dds::core::xtypes::StructType type_;
/*
* Read one single sample from the data file. This method deserializes the
* textual format of the sample into a dynamic data object that is going to
* be returned to Replay/Converter for processing.
*/
bool read_sample();
};
/*
* The discovery stream readers have to provide Replay/Converter with all the
* different streams contained in the storage. In the case of our example, we
* only provide one stream, for the only topic that's recorded (see the type
* definition in file HelloMsg.idl).
* This class is also in charge of providing information about the total range
* of time where valid recorded data can be found, or for which the Recorder app
* executed.
*/
class FileStorageStreamInfoReader :
public rti::recording::storage::StorageStreamInfoReader {
public:
FileStorageStreamInfoReader(std::ifstream *info_file);
virtual ~FileStorageStreamInfoReader();
/*
* Implementation of the read operation. It should interpret the selector
* state object that expresses the specific needs of Replay/Converter about
* the data to be provided (data not read before vs data of any kind, lower
* and upper time limits, etc).
*/
virtual void read(
std::vector<rti::routing::StreamInfo *> &sample_seq,
const rti::recording::storage::SelectorState &selector);
/*
* The return loan operation should free any resources allocated by the
* read() operation.
*/
virtual void return_loan(
std::vector<rti::routing::StreamInfo *> &sample_seq);
/*
* An int64-represented time-stamp (in nanoseconds) representing the
* starting point in time where recorded data exists, or when the service
* started executing.
*/
virtual int64_t service_start_time();
/*
* An int64-represented time-stamp (in nanoseconds) representing the
* final point in time where recorded data exists, or when the service
* finished executing.
*/
virtual int64_t service_stop_time();
/*
* When this storage stream reader has finished reading all the available
* samples, this function should return true.
*/
virtual bool finished();
/*
* If Replay is going to be used with the looping capability, then this
* method has to be implemented. It restores the storage stream reader to
* a point where it will start reading samples from the beginning of the
* storage.
*/
virtual void reset();
private:
std::ifstream *info_file_;
bool stream_info_taken_;
rti::routing::StreamInfo example_stream_info_;
dds::core::xtypes::StructType example_type_;
};
} } } // namespace rti::recording::cpp_example
| hpp |
rticonnextdds-examples | data/projects/rticonnextdds-examples/recording_service/pluggable_storage/cpp/HelloMsg_publisher.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 <iostream>
#include <dds/pub/ddspub.hpp>
#include <rti/util/util.hpp> // for sleep()
#include "HelloMsg.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<HelloMsg> topic(participant, "Example_Cpp_Storage");
// Create a DataWriter with default Qos (Publisher created in-line)
dds::pub::DataWriter<HelloMsg> writer(
dds::pub::Publisher(participant),
topic);
HelloMsg sample;
for (int count = 0; count < sample_count || sample_count == 0; count++) {
// Modify the data to be written here
std::stringstream string_builder;
string_builder << std::string("Sample string ") << count << std::endl;
sample.id(count);
sample.msg(string_builder.str());
std::cout << "Writing HelloMsg, count " << count << std::endl;
writer.write(sample);
rti::util::sleep(dds::core::Duration(1));
}
}
int main(int argc, char *argv[])
{
int domain_id = 0;
int sample_count = 0; // infinite loop
if (argc >= 2) {
domain_id = atoi(argv[1]);
}
if (argc >= 3) {
sample_count = atoi(argv[2]);
}
// To turn on additional logging, include <rti/config/Logger.hpp> and
// uncomment the following line:
// rti::config::Logger::instance().verbosity(rti::config::Verbosity::STATUS_ALL);
try {
publisher_main(domain_id, sample_count);
} catch (const std::exception &ex) {
// 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/recording_service/pluggable_storage/c/FileStorageReader.c | /*
* (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 <errno.h>
#include <limits.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "ndds/ndds_c.h"
#include "recordingservice/recordingservice_storagereader.h"
#include "routingservice/routingservice_infrastructure.h"
#include "FileStorageReader.h"
#include "HelloMsg.h"
#define NANOSECS_PER_SEC 1000000000
#ifdef _WIN32
#define SCNi64 "I64i"
#define SCNu64 "I64u"
#else
#include <inttypes.h>
#endif
#ifndef FALSE
#define FALSE 0
#endif
#ifndef TRUE
#define TRUE 1
#endif
struct FileRecord {
char fileName[FILENAME_MAX];
FILE *file;
};
struct FileStorageStreamReader {
struct FileRecord file_record;
int64_t current_timestamp;
int current_valid_data;
DDS_Long current_data_id;
char current_data_msg[256];
struct DDS_DynamicDataSeq taken_data;
struct DDS_SampleInfoSeq taken_info;
DDS_TypeCode *type_code;
struct RTI_RecordingServiceStorageStreamReader as_stream_reader;
};
struct FileStorageStreamInfoReader {
struct FileRecord file_record;
int32_t domain_id;
struct RTI_RoutingServiceStreamInfo *stream_info;
int stream_info_taken;
struct FileRecord info_file_record;
struct RTI_RecordingServiceStorageStreamInfoReader
base_discovery_stream_reader;
};
#define FileStorageReader_FILE_NAME_MAX 1024
struct FileStorageReader {
char file_name[FileStorageReader_FILE_NAME_MAX];
struct RTI_RecordingServiceStorageReader as_storage_reader;
};
#define FILENAME_PROPERTY_NAME "example.c_pluggable_storage.filename"
#pragma warning(disable : 4996)
/******************************************************************************/
/**
* Replay will periodically ask for any newly discovered data streams.
* This function receives a time limit parameter. It should return any stream
* info event not having been taken yet and within the given time limit
* (associated time of the event should be less or equal to the time limit).
* In our example we only store one topic and type, described in the provided
* IDL file (HelloMsg.idl). We simulate we discover that stream in the very
* first call to this function. Every other call to this function will return
* an empty count of taken elements.
*/
void FileStorageStreamInfoReader_read(
void *stream_reader_data,
struct RTI_RoutingServiceStreamInfo ***stream_info_array,
int *count,
const struct RTI_RecordingServiceSelectorState *selector)
{
struct FileStorageStreamInfoReader *stream_reader =
(struct FileStorageStreamInfoReader *) stream_reader_data;
RTI_UNUSED_PARAMETER(selector);
if (!stream_reader->stream_info_taken) {
*stream_info_array = &stream_reader->stream_info;
*count = 1;
stream_reader->stream_info_taken = TRUE;
} else {
*count = 0;
}
}
void FileStorageStreamInfoReader_return_loan(
void *stream_reader_data,
struct RTI_RoutingServiceStreamInfo **stream_info_array,
const int count)
{
RTI_UNUSED_PARAMETER(stream_reader_data);
RTI_UNUSED_PARAMETER(stream_info_array);
RTI_UNUSED_PARAMETER(count);
}
/**
* Replay and Converter need to know the initial and final timestamps of the
* recording being read.
* In the case of our example, this information is stored in the associated
* '.info' file.
*/
long long FileStorageStreamInfoReader_get_service_start_time(
void *stream_reader_data)
{
struct FileStorageStreamInfoReader *stream_reader =
(struct FileStorageStreamInfoReader *) stream_reader_data;
int64_t timestamp = 0;
if (fscanf(stream_reader->info_file_record.file,
"Start timestamp: %" SCNi64 "\n",
×tamp)
!= 1) {
printf("Failed to read start timestamp from info file\n");
}
return timestamp;
}
/**
* Replay and Converter need to know the initial and final timestamps of the
* recording being read.
* In the case of our example, this information is stored in the associated
* '.info' file.
*/
long long FileStorageStreamInfoReader_get_service_stop_time(
void *stream_reader_data)
{
struct FileStorageStreamInfoReader *stream_reader =
(struct FileStorageStreamInfoReader *) stream_reader_data;
int64_t timestamp = 0;
if (fscanf(stream_reader->info_file_record.file,
"End timestamp: %" SCNi64 "\n",
×tamp)
!= 1) {
printf("Failed to read end timestamp from info file\n");
}
return timestamp;
}
void FileStorageStreamInfoReader_reset(void *stream_reader_data)
{
struct FileStorageStreamInfoReader *stream_reader =
(struct FileStorageStreamInfoReader *) stream_reader_data;
stream_reader->stream_info_taken = FALSE;
}
int FileStorageStreamInfoReader_finished(void *stream_reader_data)
{
struct FileStorageStreamInfoReader *stream_reader =
(struct FileStorageStreamInfoReader *) stream_reader_data;
return stream_reader->stream_info_taken;
}
/* Discovery */
/* Discovery information: Implementing these methods will allow the Replay
* Service to scan the discovery information from storage, and create the
* user data streams
*/
int FileStorageStreamInfoReader_initialize(
struct FileStorageStreamInfoReader *stream_reader,
const char *fileName)
{
if (fileName == NULL) {
printf("%s: null file passed as a parameter\n", RTI_FUNCTION_NAME);
return FALSE;
}
RTI_RecordingServiceStorageStreamInfoReader_initialize(
&stream_reader->base_discovery_stream_reader);
stream_reader->base_discovery_stream_reader.read =
FileStorageStreamInfoReader_read;
stream_reader->base_discovery_stream_reader.return_loan =
FileStorageStreamInfoReader_return_loan;
stream_reader->base_discovery_stream_reader.get_service_start_time =
FileStorageStreamInfoReader_get_service_start_time;
stream_reader->base_discovery_stream_reader.get_service_stop_time =
FileStorageStreamInfoReader_get_service_stop_time;
stream_reader->base_discovery_stream_reader.reset =
FileStorageStreamInfoReader_reset;
stream_reader->base_discovery_stream_reader.finished =
FileStorageStreamInfoReader_finished;
stream_reader->base_discovery_stream_reader.stream_reader_data =
stream_reader;
stream_reader->file_record.file = fopen(fileName, "r");
if (stream_reader->file_record.file == NULL) {
perror("Failed to open file");
return FALSE;
}
strcpy(stream_reader->file_record.fileName, fileName);
strcpy(stream_reader->info_file_record.fileName, fileName);
strcat(stream_reader->info_file_record.fileName, ".info");
stream_reader->info_file_record.file =
fopen(stream_reader->info_file_record.fileName, "r");
if (stream_reader->info_file_record.file == NULL) {
perror("Failed to open info file");
return FALSE;
}
stream_reader->domain_id = 0;
stream_reader->stream_info = RTI_RoutingServiceStreamInfo_new_discovered(
"Example_C_Storage",
"HelloMsg",
RTI_ROUTING_SERVICE_TYPE_REPRESENTATION_DYNAMIC_TYPE,
HelloMsg_get_typecode());
if (stream_reader->stream_info == NULL) {
printf("Failed to create StreamInfo object for stream\n");
return FALSE;
}
stream_reader->stream_info->partition.element_array = NULL;
stream_reader->stream_info->partition.element_count = 0;
stream_reader->stream_info->partition.element_count_max = 0;
stream_reader->stream_info_taken = FALSE;
return TRUE;
}
/*
* --- User-data StreamReader
* -------------------------------------------------------
*/
/**
* The example implementation of a stream reader caches the current values read
* from the data file. This function reads the next data and info values from
* the opened file.
*/
int FileStorageStreamReader_readSample(
struct FileStorageStreamReader *stream_reader)
{
uint64_t sampleNr = 0;
if (feof(stream_reader->file_record.file)) {
return FALSE;
}
if (fscanf(stream_reader->file_record.file,
"Sample number: %" SCNu64 "\n",
&sampleNr)
!= 1) {
printf("Failed to read sample number from file\n");
return FALSE;
}
if (fscanf(stream_reader->file_record.file,
"Reception timestamp: %" SCNi64 "\n",
&stream_reader->current_timestamp)
!= 1) {
printf("Failed to read current timestamp from file\n");
return FALSE;
}
if (fscanf(stream_reader->file_record.file,
"Valid data: %u\n",
&stream_reader->current_valid_data)
!= 1) {
printf("Failed to read current valid data flag from file\n");
return FALSE;
}
if (stream_reader->current_valid_data) {
if (fscanf(stream_reader->file_record.file,
" Data.id: %i\n",
&stream_reader->current_data_id)
!= 1) {
printf("Failed to read current data.id field from file\n");
return FALSE;
}
if (fscanf(stream_reader->file_record.file,
" Data.msg: %256[^\n]\n",
stream_reader->current_data_msg)
!= 1) {
printf("Failed to read current data.msg field from file\n");
return FALSE;
}
}
return TRUE;
}
/**
* When the next sample cached fulfills the condition to be taken (its timestamp
* is within the provided limit) this method adds it to the sequence used to
* store the current taken samples.
*/
int FileStorageStreamReader_addSampleToData(
struct FileStorageStreamReader *stream_reader)
{
DDS_Long current_length =
DDS_DynamicDataSeq_get_length(&stream_reader->taken_data);
DDS_Long target_length = current_length + 1;
DDS_Long current_maximum =
DDS_DynamicDataSeq_get_maximum(&stream_reader->taken_data);
DDS_DynamicData *current_data = NULL;
struct DDS_SampleInfo *current_info = NULL;
DDS_ReturnCode_t ret_code = DDS_RETCODE_OK;
/* Every time the targeted length exceeds the current sequence capacity
* (maximum), we double the capacity */
if (current_maximum < target_length) {
if (!DDS_DynamicDataSeq_set_maximum(
&stream_reader->taken_data,
2 * current_maximum)) {
printf("Failed to set new capacity (%d) for data sequence\n",
2 * current_maximum);
return FALSE;
}
if (!DDS_SampleInfoSeq_set_maximum(
&stream_reader->taken_info,
2 * current_maximum)) {
printf("Failed to set new capacity (%d) for info sequence\n",
2 * current_maximum);
return FALSE;
}
}
/* Extend the sequences' length, we know that the current maximum will allow
* us to hold the length */
DDS_DynamicDataSeq_set_length(&stream_reader->taken_data, target_length);
DDS_SampleInfoSeq_set_length(&stream_reader->taken_info, target_length);
/* Get the current dynamic data object */
current_data = DDS_DynamicDataSeq_get_reference(
&stream_reader->taken_data,
current_length);
DDS_DynamicData_finalize(current_data);
DDS_DynamicData_initialize(
current_data,
stream_reader->type_code,
&DDS_DYNAMIC_DATA_PROPERTY_DEFAULT);
/* Get the current sample info object */
current_info = DDS_SampleInfoSeq_get_reference(
&stream_reader->taken_info,
current_length);
current_info->reception_timestamp.sec = (DDS_Long)(
stream_reader->current_timestamp / (int64_t) NANOSECS_PER_SEC);
current_info->reception_timestamp.nanosec = (DDS_Long)(
stream_reader->current_timestamp % (int64_t) NANOSECS_PER_SEC);
current_info->valid_data =
(stream_reader->current_valid_data ? DDS_BOOLEAN_TRUE
: DDS_BOOLEAN_FALSE);
if (stream_reader->current_valid_data) {
/* Set the current data ID */
ret_code = DDS_DynamicData_set_long(
current_data,
"id",
DDS_DYNAMIC_DATA_MEMBER_ID_UNSPECIFIED,
stream_reader->current_data_id);
if (ret_code != DDS_RETCODE_OK) {
/* Not a show-stopper */
printf("Failed to set data.id member value\n");
}
ret_code = DDS_DynamicData_set_string(
current_data,
"msg",
DDS_DYNAMIC_DATA_MEMBER_ID_UNSPECIFIED,
stream_reader->current_data_msg);
if (ret_code != DDS_RETCODE_OK) {
/* Not a show-stopper */
printf("Failed to set data.msg member value\n");
}
}
/* Clear the cached values until we read the next sample */
stream_reader->current_timestamp = INT64_MAX;
stream_reader->current_valid_data = FALSE;
stream_reader->current_data_id = 0;
stream_reader->current_data_msg[0] = '\0';
return TRUE;
}
/**
* Replay or Converter will call this stream reader function when asking for the
* next batch of data samples that should be provided to the output connection.
* The function receives a pointer to a collection of samples and a pointer to
* a collection of their respective sample information objects - both in Routing
* Service types, this is, untyped. More interestingly, the function receives a
* timestamp limit parameter. The function should provide any data not taken
* yet for which the associated timestamp is less or equal to this timestamp
* limit. This is especially important for Replay, because respecting time
* separation between samples requires this functionality to be implemented
* correctly.
* Replay and Converter expect to receive Dynamic Data samples for the data
* objects and DDS_SampleInfo objects for the associated sample information
* objects.
*/
void FileStorageStreamReader_read(
void *stream_reader_data,
RTI_RoutingServiceSample **out_samples,
RTI_RoutingServiceSampleInfo **out_sample_infos,
int *count,
const struct RTI_RecordingServiceSelectorState *selector)
{
struct FileStorageStreamReader *stream_reader =
(struct FileStorageStreamReader *) stream_reader_data;
int i = 0;
long long timestamp_limit =
(long long) selector->time_range_end.sec * NANOSECS_PER_SEC
+ selector->time_range_end.nanosec;
int read_samples = 0;
/*
* The value of the sample selector's max samples could be
* DDS_LENGTH_UNLIMITED, indicating that no maximum number of samples. But
* this value is actually negative, so a straight comparison against it
* could yield unexpected results. Transform the value into something we
* can compare against.
*/
const int max_samples = (selector->max_samples == DDS_LENGTH_UNLIMITED)
? INT_MAX
: selector->max_samples;
if (stream_reader->current_timestamp > timestamp_limit) {
*count = 0;
return;
}
/* Add the currently read sample and sample info values to the taken data
* and info collections (sequences) */
do {
FileStorageStreamReader_addSampleToData(stream_reader);
FileStorageStreamReader_readSample(stream_reader);
read_samples++;
} while (stream_reader->current_timestamp <= timestamp_limit
&& read_samples < max_samples);
/* The number of taken samples is the current length of the data sequence */
*count = (int) DDS_DynamicDataSeq_get_length(&stream_reader->taken_data);
*out_samples = malloc(*count * sizeof(RTI_RoutingServiceSample));
if (*out_samples == NULL) {
printf("Failed to allocate sample array\n");
*count = 0;
return;
}
for (i = 0; i < *count; i++) {
(*out_samples)[i] =
DDS_DynamicDataSeq_get_reference(&stream_reader->taken_data, i);
}
*out_sample_infos = malloc(*count * sizeof(RTI_RoutingServiceSampleInfo));
if (*out_sample_infos == NULL) {
printf("Failed to allocate sample info array\n");
*count = 0;
return;
}
for (i = 0; i < *count; i++) {
(*out_sample_infos)[i] =
DDS_SampleInfoSeq_get_reference(&stream_reader->taken_info, i);
}
}
void FileStorageStreamReader_return_loan(
void *stream_reader_data,
RTI_RoutingServiceSample *samples,
RTI_RoutingServiceSampleInfo *sample_infos,
int count)
{
struct FileStorageStreamReader *stream_reader =
(struct FileStorageStreamReader *) stream_reader_data;
RTI_UNUSED_PARAMETER(count);
DDS_DynamicDataSeq_set_length(&stream_reader->taken_data, 0);
DDS_SampleInfoSeq_set_length(&stream_reader->taken_info, 0);
free(samples);
free(sample_infos);
}
int FileStorageStreamReader_finished(void *stream_reader_data)
{
struct FileStorageStreamReader *stream_reader =
(struct FileStorageStreamReader *) stream_reader_data;
if (feof(stream_reader->file_record.file)) {
return TRUE;
} else {
return FALSE;
}
}
void FileStorageStreamReader_reset(void *stream_reader_data)
{
struct FileStorageStreamReader *stream_reader =
(struct FileStorageStreamReader *) stream_reader_data;
fseek(stream_reader->file_record.file, 0, SEEK_SET);
}
int FileStorageStreamReader_initialize(
struct FileStorageStreamReader *stream_reader,
const char *file_name,
const struct RTI_RoutingServiceStreamInfo *stream_info,
int domain_id)
{
RTI_UNUSED_PARAMETER(domain_id);
if (stream_info->stream_name == NULL) {
return FALSE;
}
strcpy(stream_reader->file_record.fileName, file_name);
stream_reader->file_record.file =
fopen(stream_reader->file_record.fileName, "r");
if (stream_reader->file_record.file == NULL) {
return FALSE;
}
/*
* Initialize the data and info holders (sequences)
* Reserve space for at least 1 element, initially
*/
DDS_DynamicDataSeq_initialize(&stream_reader->taken_data);
DDS_SampleInfoSeq_initialize(&stream_reader->taken_info);
if (!DDS_DynamicDataSeq_set_maximum(&stream_reader->taken_data, 1)) {
printf("Failed to set new capacity (1) for data sequence\n");
return FALSE;
}
if (!DDS_SampleInfoSeq_set_maximum(&stream_reader->taken_info, 1)) {
printf("Failed to set new capacity (1) for info sequence\n");
return FALSE;
}
stream_reader->type_code =
(DDS_TypeCode *) stream_info->type_info.type_representation;
/* Bootstrap the take loop: read the first sample */
if (!FileStorageStreamReader_readSample(stream_reader)) {
printf("Failed to get first sample from file, maybe EOF was reached\n");
}
RTI_RecordingServiceStorageStreamReader_initialize(
&stream_reader->as_stream_reader);
stream_reader->as_stream_reader.read = FileStorageStreamReader_read;
stream_reader->as_stream_reader.return_loan =
FileStorageStreamReader_return_loan;
stream_reader->as_stream_reader.finished = FileStorageStreamReader_finished;
stream_reader->as_stream_reader.reset = FileStorageStreamReader_reset;
stream_reader->as_stream_reader.stream_reader_data = stream_reader;
return TRUE;
}
/**
* Delete an instance of a data stream reader created by this plugin.
* Close any file handles opened and free any allocated resources and memory.
*/
void FileStorageReader_delete_stream_reader(
void *storage_reader_data,
struct RTI_RecordingServiceStorageStreamReader *stream_reader)
{
struct FileStorageStreamReader *file_stream_reader =
(struct FileStorageStreamReader *)
stream_reader->stream_reader_data;
RTI_UNUSED_PARAMETER(storage_reader_data);
if (fclose(file_stream_reader->file_record.file) != 0) {
perror("Error closing replay C plugin file: ");
} else {
file_stream_reader->file_record.file = NULL;
}
DDS_DynamicDataSeq_finalize(&file_stream_reader->taken_data);
DDS_SampleInfoSeq_finalize(&file_stream_reader->taken_info);
free(file_stream_reader);
}
/**
* Create a data stream reader. For each discovered stream that matches the set
* of interest defined in the configuration, Replay or Converter will ask us to
* create a reader for that stream (a stream reader).
* The start and stop timestamp parameters define the time range for which the
* application is asking for data. For simplicity, this example doesn't do
* anything with these parameters. But the correct way to implement this API
* would be to not read any data recorded before the given start time or after
* the given end time.
*/
struct RTI_RecordingServiceStorageStreamReader *
FileStorageReader_create_stream_reader(
void *storage_reader_data,
const struct RTI_RoutingServiceStreamInfo *stream_info,
const struct RTI_RoutingServiceProperties *properties)
{
struct FileStorageReader *storage_reader =
(struct FileStorageReader *) storage_reader_data;
struct FileStorageStreamReader *stream_reader = NULL;
int domain_id = 0;
/*
* Look up the 'rti.recording_service.domain_id' property in the property
* set. Attempt to parse the value as an integer.
*/
const char *domain_id_str = RTI_RoutingServiceProperties_lookup_property(
properties,
RTI_RECORDING_SERVICE_DOMAIN_ID_PROPERTY_NAME);
if (domain_id_str == NULL) {
printf("%s: could not find %s property in property set\n",
RTI_FUNCTION_NAME,
RTI_RECORDING_SERVICE_DOMAIN_ID_PROPERTY_NAME);
}
errno = 0;
domain_id = strtol(domain_id_str, NULL, 10);
if (errno == ERANGE) {
printf("Failed to parse domain ID from string: '%s'. Range error.\n",
domain_id_str);
}
stream_reader = (struct FileStorageStreamReader *) malloc(
sizeof(struct FileStorageStreamReader));
if (stream_reader == NULL) {
printf("Failed to allocate FileStorageStreamReader instance\n");
return NULL;
}
if (!FileStorageStreamReader_initialize(
stream_reader,
storage_reader->file_name,
stream_info,
domain_id)) {
printf("%s: !init %s\n", RTI_FUNCTION_NAME, "FileStorageStreamReader");
FileStorageReader_delete_stream_reader(
storage_reader_data,
&stream_reader->as_stream_reader);
return NULL;
}
return &stream_reader->as_stream_reader;
}
/**
* Delete an instance of a discovery stream reader created by this plugin. Close
* any opened files and return the allocated memory and resources.
*/
void FileStorageReader_delete_stream_info_reader(
void *storage_reader_data,
struct RTI_RecordingServiceStorageStreamInfoReader *stream_reader)
{
struct FileStorageStreamInfoReader *example_stream_reader =
(struct FileStorageStreamInfoReader *)
stream_reader->stream_reader_data;
RTI_UNUSED_PARAMETER(storage_reader_data);
RTI_RoutingServiceStreamInfo_delete(example_stream_reader->stream_info);
if (example_stream_reader != NULL) {
if (example_stream_reader->file_record.file != NULL) {
if (fclose(example_stream_reader->file_record.file) != 0) {
perror("Error closing replay C plugin file:");
} else {
example_stream_reader->file_record.file = NULL;
}
}
if (example_stream_reader->info_file_record.file != NULL) {
if (fclose(example_stream_reader->info_file_record.file) != 0) {
perror("Error closing replay C plugin info file:");
} else {
example_stream_reader->info_file_record.file = NULL;
}
}
} else {
printf("Error: invalid DB discovery stream reader instance\n");
}
free(example_stream_reader);
}
/**
* Create a discovery stream reader. This function is called by Replay or
* Converter when the connection between input and output is being created. The
* discovery stream reader is in charge or traversing the storage looking for
* stored data streams to be accessed.
* A set of properties is passed. It contains built-in properties like the
* start and stop timestamps, in the form of strings (64-bit integers as text).
* The start and stop timestamp parameters define the time range for which the
* application is asking for data. To simplify the example, we have not made any
* use of these parameters, but the correct way to implement a discovery
* stream reader would be to use them to constrain the streams found to that
* specific time range (streams found before the start time or after the end
* time should be ignored - this is, not discovered).
*/
struct RTI_RecordingServiceStorageStreamInfoReader *
FileStorageReader_create_stream_info_reader(
void *storage_reader_data,
const struct RTI_RoutingServiceProperties *properties)
{
struct FileStorageReader *storage_reader =
(struct FileStorageReader *) storage_reader_data;
struct FileStorageStreamInfoReader *stream_reader = NULL;
RTI_UNUSED_PARAMETER(properties);
stream_reader = (struct FileStorageStreamInfoReader *) malloc(
sizeof(struct FileStorageStreamInfoReader));
if (stream_reader == NULL) {
printf("Failed to allocate FileStorageStreamInfoReader instance\n");
return NULL;
}
if (!FileStorageStreamInfoReader_initialize(
stream_reader,
storage_reader->file_name)) {
printf("Failed to initialize FileStorageStreamInfoReader instance\n");
FileStorageReader_delete_stream_info_reader(
storage_reader_data,
&stream_reader->base_discovery_stream_reader);
return NULL;
}
return &stream_reader->base_discovery_stream_reader;
}
/**
* Free the resources allocated by this plugin instance.
*/
void FileStorageReader_delete_instance(
struct RTI_RecordingServiceStorageReader *storage_reader)
{
if (storage_reader == NULL) {
return;
}
free(storage_reader->storage_reader_data);
}
/**
* This function creates an instance of the StorageReader plugin to be used by
* Replay or Converter to read the data, as was stored by the storage part of
* this example (see FileStorageWriter.c).
* The plugin provides methods to create two types of reader objects, called
* StreamReaders: the discovery stream readers and the data stream readers. This
* function is in charge of setting up the plugin functions to create and delete
* each type of stream reader (FileStorageDiscoveryStreamReader type for
* the discovery stream reader, FileStorageStreamReader for the data
* stream reader).
* This plugin needs the file name to be passed to Replay or Converter in the
* <property> XML tag of the storage configuration. The name of the property
* is defined in the FILENAME_PROPERTY_NAME constant above.
*/
struct RTI_RecordingServiceStorageReader *FileStorageReader_create(
const struct RTI_RoutingServiceProperties *properties)
{
struct FileStorageReader *storage_reader = NULL;
const char *file_name = NULL;
storage_reader = malloc(sizeof(struct FileStorageReader));
if (storage_reader == NULL) {
printf("Failed to allocate FileStorageReader instance\n");
return NULL;
}
/* Look up the file name property in the properties. These are the
* properties defined in the XML configuration */
file_name = RTI_RoutingServiceProperties_lookup_property(
properties,
FILENAME_PROPERTY_NAME);
if (file_name == NULL) {
printf("Failed to find property with name=%s\n",
FILENAME_PROPERTY_NAME);
free(storage_reader);
return NULL;
}
if (strlen(file_name) >= FileStorageReader_FILE_NAME_MAX) {
printf("File name too long (%s)\n", file_name);
free(storage_reader);
return NULL;
}
strcpy(storage_reader->file_name, file_name);
RTI_RecordingServiceStorageReader_initialize(
&storage_reader->as_storage_reader);
storage_reader->as_storage_reader.create_stream_info_reader =
FileStorageReader_create_stream_info_reader;
storage_reader->as_storage_reader.delete_stream_info_reader =
FileStorageReader_delete_stream_info_reader;
storage_reader->as_storage_reader.create_stream_reader =
FileStorageReader_create_stream_reader;
storage_reader->as_storage_reader.delete_stream_reader =
FileStorageReader_delete_stream_reader;
storage_reader->as_storage_reader.delete_instance =
FileStorageReader_delete_instance;
storage_reader->as_storage_reader.storage_reader_data = storage_reader;
return &storage_reader->as_storage_reader;
}
| c |
rticonnextdds-examples | data/projects/rticonnextdds-examples/recording_service/pluggable_storage/c/HelloMsg_publisher.c | /*
* (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 "HelloMsg.h"
#include "HelloMsgSupport.h"
#include "ndds/ndds_c.h"
#include <stdio.h>
#include <stdlib.h>
/* Delete all entities */
static int publisher_shutdown(DDS_DomainParticipant *participant)
{
DDS_ReturnCode_t retcode;
int status = 0;
if (participant != NULL) {
retcode = DDS_DomainParticipant_delete_contained_entities(participant);
if (retcode != DDS_RETCODE_OK) {
fprintf(stderr, "delete_contained_entities error %d\n", retcode);
status = -1;
}
retcode = DDS_DomainParticipantFactory_delete_participant(
DDS_TheParticipantFactory,
participant);
if (retcode != DDS_RETCODE_OK) {
fprintf(stderr, "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) {
fprintf(stderr, "finalize_instance error %d\n", retcode);
status = -1;
}
*/
return status;
}
int publisher_main(int domainId, int sample_count)
{
DDS_DomainParticipant *participant = NULL;
DDS_Publisher *publisher = NULL;
DDS_Topic *topic = NULL;
DDS_DataWriter *writer = NULL;
HelloMsgDataWriter *HelloMsg_writer = NULL;
HelloMsg *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 = { 2, 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) {
fprintf(stderr, "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) {
fprintf(stderr, "create_publisher error\n");
publisher_shutdown(participant);
return -1;
}
/* Register type before creating topic */
type_name = HelloMsgTypeSupport_get_type_name();
retcode = HelloMsgTypeSupport_register_type(participant, type_name);
if (retcode != DDS_RETCODE_OK) {
fprintf(stderr, "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_C_Storage",
type_name,
&DDS_TOPIC_QOS_DEFAULT,
NULL /* listener */,
DDS_STATUS_MASK_NONE);
if (topic == NULL) {
fprintf(stderr, "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) {
fprintf(stderr, "create_datawriter error\n");
publisher_shutdown(participant);
return -1;
}
HelloMsg_writer = HelloMsgDataWriter_narrow(writer);
if (HelloMsg_writer == NULL) {
fprintf(stderr, "DataWriter narrow error\n");
publisher_shutdown(participant);
return -1;
}
/* Create data sample for writing */
instance = HelloMsgTypeSupport_create_data_ex(DDS_BOOLEAN_TRUE);
if (instance == NULL) {
fprintf(stderr, "HelloMsgTypeSupport_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 = HelloMsgDataWriter_register_instance(
HelloMsg_writer, instance);
*/
/* Main loop */
for (count = 0; (sample_count == 0) || (count < sample_count); ++count) {
printf("Writing HelloMsg, count %d\n", count);
/* Modify the data to be written here */
instance->id = count;
RTIOsapiUtility_snprintf(instance->msg, 256, "Sample string %i", count);
/* Write data */
retcode = HelloMsgDataWriter_write(
HelloMsg_writer,
instance,
&instance_handle);
if (retcode != DDS_RETCODE_OK) {
fprintf(stderr, "write error %d\n", retcode);
}
NDDS_Utility_sleep(&send_period);
}
/*
retcode = HelloMsgDataWriter_unregister_instance(
HelloMsg_writer, instance, &instance_handle);
if (retcode != DDS_RETCODE_OK) {
fprintf(stderr, "unregister instance error %d\n", retcode);
}
*/
/* Delete data sample */
retcode = HelloMsgTypeSupport_delete_data_ex(instance, DDS_BOOLEAN_TRUE);
if (retcode != DDS_RETCODE_OK) {
fprintf(stderr, "HelloMsgTypeSupport_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/recording_service/pluggable_storage/c/FileStorageReader.h | /*
* (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 "routingservice/routingservice_infrastructure.h"
/**
* Entry-point function to the C reader plugin. This function will create an
* instance of the StorageReader example. This example opens a file passed in by
* the configuration in the storage property tag. The file contains samples in
* a textual format that is understood by the example StorageReader classes.
* This example works exclusively with the type defined in the provided IDL
* file, HelloMsg.idl.
*/
RTI_USER_DLL_EXPORT
struct RTI_RecordingServiceStorageReader *FileStorageReader_create(
const struct RTI_RoutingServiceProperties *properties);
/**
* Function to delete a C reader plugin, previously created by calling
* FileStorageReader_create().
* This function should return any resources allocated by the creation function
* and exit cleanly.
*/
RTI_USER_DLL_EXPORT
void FileStorageReader_delete_instance(
struct RTI_RecordingServiceStorageReader *storage_reader);
| h |
rticonnextdds-examples | data/projects/rticonnextdds-examples/recording_service/pluggable_storage/c/FileStorageWriter.h | /*
* (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 "routingservice/routingservice_infrastructure.h"
/**
* Entry-point function to the C storage plugin. This method will create an
* instance of the StorageWriter example.
* When a valid stream is found, a StorageStreamWriter instance will be created
* attached to that stream that is able to store the data in the file passed in
* by the configuration in the storage property tag. Then for every sample that
* it receives it stores a text entry with the sample number, the count, the
* reception timestamp, the valid data flag and if the latter is true, then the
* sample's data. This example works exclusively with the type defined in the
* provided IDL file, HelloMsg.idl.
*/
RTI_USER_DLL_EXPORT
struct RTI_RecordingServiceStorageWriter *FileStorageWriter_create_instance(
const struct RTI_RoutingServiceProperties *properties);
/**
* This function deletes a StorageWriter instance that has been created by this
* plugin. All allocated resources should be freed.
*/
RTI_USER_DLL_EXPORT
void FileStorageWriter_delete_instance(
struct RTI_RecordingServiceStorageWriter *storage_writer);
| h |
rticonnextdds-examples | data/projects/rticonnextdds-examples/recording_service/pluggable_storage/c/FileStorageWriter.c | /*
* (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 <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include "ndds/ndds_c.h"
#include "recordingservice/recordingservice_storagewriter.h"
#include "FileStorageWriter.h"
#ifdef _WIN32
#define PRIu64 "I64u"
#define PRIi64 "I64i"
#else
#include <inttypes.h>
#endif
#ifndef FALSE
#define FALSE 0
#endif
#ifndef TRUE
#define TRUE 1
#endif
#define NANOSECS_PER_SEC 1000000000ll
#define FileStorageWriter_FILE_NAME_MAX 1024
#define FILENAME_PROPERTY_NAME "example.c_pluggable_storage.filename"
struct FileRecord {
char file_name[FileStorageWriter_FILE_NAME_MAX];
FILE *file;
};
struct PublicationFileStorageStreamWriter {
struct RTI_RecordingServiceStorageStreamWriter as_storage_stream_writer;
};
struct FileStorageStreamWriter {
FILE *file;
uint64_t stored_sample_count;
struct RTI_RecordingServiceStorageStreamWriter as_storage_stream_writer;
};
struct FileStorageWriter {
struct FileRecord file;
struct FileRecord info_file;
struct RTI_RecordingServiceStorageWriter as_storage_writer;
};
/*
* This stream writer store() method will be used by Recording Service to store
* DCPSPublication samples.
*/
void FileStorageStreamWriter_store_publication(
void *stream_writer_data,
const DDS_PublicationBuiltinTopicData **samples,
const RTI_RoutingServiceSampleInfo *sample_infos,
const int count)
{
RTI_UNUSED_PARAMETER(stream_writer_data);
RTI_UNUSED_PARAMETER(samples);
RTI_UNUSED_PARAMETER(sample_infos);
RTI_UNUSED_PARAMETER(count);
/*
* There are specializations for each of the three built-in DDS discovery
* topics in the API. Here we have shown how it would be like to implement
* storage of the DCPSPublication data samples. The pattern for the other
* types is the same.
* Recording Service will call this method when new publication data samples
* are received.
*/
}
/**
* This function is called by Recorder whenever there are samples available for
* one of the streams previously discovered and accepted (see the
* FileStorageWriter_create_stream_writer() function below). Recorder provides
* the samples and their associated information objects in Routing Service
* format, this is, untyped format.
* In our case we know that, except for the built-in DDS discovery topics which
* are received in their own format - and that we're not really storing -, that
* the format of the data we're receiving is DDS Dynamic Data. This will always
* be the format received for types recorded from DDS.
* The function traverses the collection of samples (of length defined by the
* 'count' parameter) and stores the data in a textual format.
*/
void FileStorageStreamWriter_store(
void *stream_writer_data,
const RTI_RoutingServiceSample *samples,
const RTI_RoutingServiceSampleInfo *sample_infos,
const int count)
{
struct FileStorageStreamWriter *stream_writer =
(struct FileStorageStreamWriter *) stream_writer_data;
const struct DDS_SampleInfo **sample_info_array =
(const struct DDS_SampleInfo **) sample_infos;
DDS_DynamicData **sampleArray = (DDS_DynamicData **) samples;
int i = 0;
for (; i < count; i++) {
DDS_ReturnCode_t ret_code = DDS_RETCODE_OK;
DDS_Long id = 0;
char *msg = NULL;
const struct DDS_SampleInfo *sample_info = sample_info_array[i];
DDS_DynamicData *sample = sampleArray[i];
DDS_Octet valid_data = sample_info->valid_data;
int64_t timestamp = (int64_t) sample_info->reception_timestamp.sec
* NANOSECS_PER_SEC;
timestamp += sample_info->reception_timestamp.nanosec;
fprintf(stream_writer->file,
"Sample number: %" PRIu64 "\n",
stream_writer->stored_sample_count);
fprintf(stream_writer->file,
"Reception timestamp: %" PRIi64 "\n",
timestamp);
fprintf(stream_writer->file, "Valid data: %u\n", valid_data);
if (valid_data) {
/* Get and store the sample's id field */
ret_code = DDS_DynamicData_get_long(
sample,
&id,
"id",
DDS_DYNAMIC_DATA_MEMBER_ID_UNSPECIFIED);
if (ret_code != DDS_RETCODE_OK) {
printf("Failed to find 'id' field in sample\n");
}
fprintf(stream_writer->file, " Data.id: %i\n", id);
/* Get and store the sample's msg field */
ret_code = DDS_DynamicData_get_string(
sample,
&msg,
NULL,
"msg",
DDS_DYNAMIC_DATA_MEMBER_ID_UNSPECIFIED);
if (ret_code != DDS_RETCODE_OK) {
printf("Failed to find 'msg' field in sample\n");
}
fprintf(stream_writer->file, " Data.msg: %s\n", msg);
DDS_String_free(msg);
}
stream_writer->stored_sample_count++;
}
fflush(stream_writer->file);
}
/**
* Initialize this instance of a StreamWriter. See that we're setting ourselves
* in the stream_writer_data field for later easy access via simple cast.
*/
int FileStorageStreamWriter_initialize(
struct FileStorageStreamWriter *stream_writer,
FILE *file)
{
RTI_RecordingServiceStorageStreamWriter_initialize(
&stream_writer->as_storage_stream_writer);
/* init implementation */
stream_writer->as_storage_stream_writer.store =
FileStorageStreamWriter_store;
stream_writer->as_storage_stream_writer.stream_writer_data = stream_writer;
stream_writer->file = file;
stream_writer->stored_sample_count = 0;
return TRUE;
}
/******************************************************************************/
/**
* Internal function used by this plugin called upon creation and initialization
* of the plugin instance.This is the place where the storage space should
* be created and/or opened.
* In our case, we open the file that will hold the data samples we record and
* a meta-data file (it uses the same file name but we append a '.info' at the
* end) that we'll use to mark the start and end timestamps of the recording.
*/
int FileStorageWriter_connect(void *storage_writer_data)
{
struct FileStorageWriter *writer =
(struct FileStorageWriter *) storage_writer_data;
int64_t current_time = -1;
writer->file.file = fopen(writer->file.file_name, "w");
if (writer->file.file == NULL) {
printf("%s: %s\n",
"Failed to open file for writing",
writer->file.file_name);
return FALSE;
}
strcpy(writer->info_file.file_name, writer->file.file_name);
strcat(writer->info_file.file_name, ".info");
writer->info_file.file = fopen(writer->info_file.file_name, "w");
if (writer->info_file.file == NULL) {
printf("%s: %s\n",
"Failed to open file for writing",
writer->info_file.file_name);
/* Cleanup if error */
fclose(writer->file.file);
return FALSE;
}
/* Obtain current time */
current_time = (int64_t) time(NULL);
if (current_time == -1) {
fprintf(stderr, "Failed to obtain the current time\n");
/* Cleanup if error */
fclose(writer->file.file);
fclose(writer->info_file.file);
return FALSE;
}
/* Time was returned in seconds. Transform to nanoseconds */
current_time *= NANOSECS_PER_SEC;
fprintf(writer->info_file.file,
"Start timestamp: %" PRIi64 "\n",
current_time);
return TRUE;
}
/**
* Internal function used by our plugin to disconnect from the storage resources
* that have been allocated (e.g. files).
* For this example's purposes, we need to close the main data file, and then
* we get the current timestamp from the system and store it in the meta-data
* file. Then we also close this meta-data file.
*/
int FileStorageWriter_disconnect(void *storage_writer_data)
{
struct FileStorageWriter *writer =
(struct FileStorageWriter *) storage_writer_data;
int64_t current_time = -1;
if (fclose(writer->file.file) != 0) {
perror("Failed to close output file");
return FALSE;
}
/* Obtain current time */
current_time = (int64_t) time(NULL);
if (current_time == -1) {
fprintf(stderr, "Failed to obtain the current time\n");
}
/* Time was returned in seconds. Transform to nanoseconds */
current_time *= NANOSECS_PER_SEC;
fprintf(writer->info_file.file,
"End timestamp: %" PRIi64 "\n",
current_time);
if (fclose(writer->info_file.file) != 0) {
perror("Failed to close output info file");
return FALSE;
}
return TRUE;
}
/**
* This function is called by Recorder whenever a new DDS discovery stream has
* been discovered. Recorder will ask this plugin to create a
* StorageStreamWriter object attached to the discovery stream.
* Recorder calls this method only for the DDS discovery streams:
* DCPSParticipant, DCPSPublication and DCPSSubscription. Note that the type
* received in this case is not a Dynamic Data object, but a pointer to the
* respective specific discovery topic types (DDS_ParticipantBuiltinTopicData,
* DDS_PublicationBuitinTopicData and DDS_SubscriptionBuiltinTopicData).
* For our example's purpose, we don't actually need to store the discovery data
* because we don't need any information from it later. However, also for
* example purposes, we create a different object than the one that's created in
* the case of the user-data creation function.
*/
struct RTI_RecordingServiceStoragePublicationWriter *
FileStorageWriter_create_publication_writer(void *storage_writer_data)
{
struct RTI_RecordingServiceStoragePublicationWriter *stream_writer = NULL;
RTI_UNUSED_PARAMETER(storage_writer_data);
stream_writer =
malloc(sizeof(struct RTI_RecordingServiceStoragePublicationWriter));
if (stream_writer == NULL) {
printf("Failed to allocate "
"RTI_RecordingServiceStoragePublicationWriter "
"instance\n");
return NULL;
}
RTI_RecordingServiceStoragePublicationWriter_initialize(stream_writer);
/* init implementation */
stream_writer->store = FileStorageStreamWriter_store_publication;
stream_writer->stream_writer_data = stream_writer;
return NULL;
}
/**
* This function is called by Recorder whenever a new user data stream has been
* discovered. Recorder will ask this plugin to create a StorageStreamWriter
* object attached to the stream. This function is in charge of preparing any
* context necessary for the stream writer to store data directly. In this
* example, the file to store the samples to is provided to the stream writer on
* initialization.
* Generally, this function should accept every stream and type. Stream name
* (topic) and type name filters should be applied at configuration level. The
* goal of the create_stream_writer() function is to prepare the storage for the
* reception of samples of a previously undiscovered type, and to create a
* StreamWriter that can store those samples.
* This function receives a set of properties as a parameter. Recorder will
* provide some built-in properties in this set, like the DDS domain ID the
* stream was found in (as a 32-bit integer in text format).
* For simplification purposes, in this example we just accept this type: the
* HelloMsg topic/type defined in the example.
*/
struct RTI_RecordingServiceStorageStreamWriter *
FileStorageWriter_create_stream_writer(
void *storage_writer_data,
const struct RTI_RoutingServiceStreamInfo *stream_info,
const struct RTI_RoutingServiceProperties *properties)
{
struct FileStorageWriter *writer =
(struct FileStorageWriter *) storage_writer_data;
struct FileStorageStreamWriter *stream_writer = NULL;
/*
* We're not using any of the provided properties in this example, but if
* you need to do so, you can use the
* RTI_RoutingServiceProperties_lookup_property() function to obtain a
* property's value. The built-in properties passed by Recorder can be found
* in the storage_writer.h file
* (e.g. RTI_RECORDING_SERVICE_DOMAIN_ID_PROPERTY_NAME for the property
* holding the associated DDS domain ID value). In order to obtain the
* numeric value, just parse the text integer normally (e.g. by using
* strtol(). See the reading side example's
* FileStorageReader_create_stream_reader() function to see the code in
* action.
*/
RTI_UNUSED_PARAMETER(properties);
if (strcmp(stream_info->type_info.type_name, "HelloMsg") == 0) {
stream_writer = malloc(sizeof(struct FileStorageStreamWriter));
if (stream_writer == NULL) {
printf("Failed to allocate FileStorageStreamWriter instance\n");
return NULL;
}
if (!FileStorageStreamWriter_initialize(
stream_writer,
writer->file.file)) {
free(stream_writer);
printf("Failed to initialize FileStorageStreamWriter instance\n");
return NULL;
}
return &stream_writer->as_storage_stream_writer;
}
return NULL;
}
/**
* The plugin is also in charge of deleting the StorageStreamWriter instances it
* has created. It's a good practice to use the stream_writer_data field in the
* RTI_RecordingServiceStorageStreamWriter to store the specific instance we
* created, so we can use it directly if necessary with a simple cast.
* In the case of this example, we're setting the created StreamWriter instances
* in this field so we can call free() on that field directly.
*/
void FileStorageWriter_delete_stream_writer(
void *storage_writer_data,
struct RTI_RecordingServiceStorageStreamWriter *stream_writer)
{
RTI_UNUSED_PARAMETER(storage_writer_data);
/* We always assign the allocated instance to the stream_writer_data holder.
* Thus, free that directly. */
free(stream_writer->stream_writer_data);
}
/**
* This function initializes the StorageWriter plugin with the adequate
* functions. These plugin functions will be used by Recorder's C-wrapping
* class.
* This function depends on a property passed in the Recorder XML
* configuration's <property> tag (see the FILENAME_PROPERTY_NAME constant
* above), and it will fail if it's not found. It has been added to the example
* XML file provided (pluggable_storage_example.xml).
* This function, however, is not in charge of opening that file. That's done
* in the FileStorageWriter_connect() function defined above. The same way,
* the file is closed in the FileStorageWriter_disconnect() function above.
*/
int FileStorageWriter_initialize(
struct FileStorageWriter *writer,
const struct RTI_RoutingServiceProperties *properties)
{
const char *file_name = NULL;
RTIOsapiMemory_zero(writer, sizeof(struct FileStorageWriter));
RTI_RecordingServiceStorageWriter_initialize(&writer->as_storage_writer);
/* init implementation */
writer->as_storage_writer.create_stream_writer =
FileStorageWriter_create_stream_writer;
writer->as_storage_writer.create_publication_writer =
FileStorageWriter_create_publication_writer;
writer->as_storage_writer.delete_stream_writer =
FileStorageWriter_delete_stream_writer;
writer->as_storage_writer.delete_instance =
FileStorageWriter_delete_instance;
writer->as_storage_writer.storage_writer_data = writer;
file_name = RTI_RoutingServiceProperties_lookup_property(
properties,
FILENAME_PROPERTY_NAME);
if (file_name == NULL) {
printf("Failed to find property with name=%s\n",
FILENAME_PROPERTY_NAME);
/* Cleanup on failure */
free(writer);
return FALSE;
}
if (strlen(file_name) >= FileStorageWriter_FILE_NAME_MAX) {
printf("File name too long (%s)\n", file_name);
/* Cleanup on failure */
free(writer);
return FALSE;
}
strcpy(writer->file.file_name, file_name);
if (!FileStorageWriter_connect(writer)) {
printf("Failed to connect to storage\n");
free(writer);
return FALSE;
}
return TRUE;
}
void FileStorageWriter_delete_instance(
struct RTI_RecordingServiceStorageWriter *storageWriter)
{
struct FileStorageWriter *writer =
(struct FileStorageWriter *) storageWriter->storage_writer_data;
if (!FileStorageWriter_disconnect(writer)) {
printf("Failed to disconnect from storage\n");
}
free(writer);
}
/**
* Create and initialize an instance of type FileStorageWriter. This type will
* handle management of the database files and storage of the received samples.
* Note: the example only works with samples of the provided HelloMsg type,
* described in file HelloMsg.idl.
*/
struct RTI_RecordingServiceStorageWriter *FileStorageWriter_create_instance(
const struct RTI_RoutingServiceProperties *properties)
{
struct FileStorageWriter *writer = NULL;
writer = malloc(sizeof(struct FileStorageWriter));
if (writer == NULL) {
printf("Failed to allocate FileStorageWriter instance\n");
return NULL;
}
if (!FileStorageWriter_initialize(writer, properties)) {
printf("Failed to initialize FileStorageWriter instance\n");
FileStorageWriter_delete_instance(&writer->as_storage_writer);
return NULL;
}
return &writer->as_storage_writer;
}
| c |
rticonnextdds-examples | data/projects/rticonnextdds-examples/recording_service/pluggable_storage/c/HelloMsg_subscriber.c | /*
* (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 "HelloMsg.h"
#include "HelloMsgSupport.h"
#include "ndds/ndds_c.h"
#include <stdio.h>
#include <stdlib.h>
void HelloMsgListener_on_requested_deadline_missed(
void *listener_data,
DDS_DataReader *reader,
const struct DDS_RequestedDeadlineMissedStatus *status)
{
}
void HelloMsgListener_on_requested_incompatible_qos(
void *listener_data,
DDS_DataReader *reader,
const struct DDS_RequestedIncompatibleQosStatus *status)
{
}
void HelloMsgListener_on_sample_rejected(
void *listener_data,
DDS_DataReader *reader,
const struct DDS_SampleRejectedStatus *status)
{
}
void HelloMsgListener_on_liveliness_changed(
void *listener_data,
DDS_DataReader *reader,
const struct DDS_LivelinessChangedStatus *status)
{
}
void HelloMsgListener_on_sample_lost(
void *listener_data,
DDS_DataReader *reader,
const struct DDS_SampleLostStatus *status)
{
}
void HelloMsgListener_on_subscription_matched(
void *listener_data,
DDS_DataReader *reader,
const struct DDS_SubscriptionMatchedStatus *status)
{
}
void HelloMsgListener_on_data_available(
void *listener_data,
DDS_DataReader *reader)
{
HelloMsgDataReader *HelloMsg_reader = NULL;
struct HelloMsgSeq data_seq = DDS_SEQUENCE_INITIALIZER;
struct DDS_SampleInfoSeq info_seq = DDS_SEQUENCE_INITIALIZER;
DDS_ReturnCode_t retcode;
int i;
HelloMsg_reader = HelloMsgDataReader_narrow(reader);
if (HelloMsg_reader == NULL) {
fprintf(stderr, "DataReader narrow error\n");
return;
}
retcode = HelloMsgDataReader_take(
HelloMsg_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) {
fprintf(stderr, "take error %d\n", retcode);
return;
}
for (i = 0; i < HelloMsgSeq_get_length(&data_seq); ++i) {
if (DDS_SampleInfoSeq_get_reference(&info_seq, i)->valid_data) {
printf("Received data\n");
HelloMsgTypeSupport_print_data(
HelloMsgSeq_get_reference(&data_seq, i));
}
}
retcode = HelloMsgDataReader_return_loan(
HelloMsg_reader,
&data_seq,
&info_seq);
if (retcode != DDS_RETCODE_OK) {
fprintf(stderr, "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) {
fprintf(stderr, "delete_contained_entities error %d\n", retcode);
status = -1;
}
retcode = DDS_DomainParticipantFactory_delete_participant(
DDS_TheParticipantFactory,
participant);
if (retcode != DDS_RETCODE_OK) {
fprintf(stderr, "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) {
fprintf(stderr, "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) {
fprintf(stderr, "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) {
fprintf(stderr, "create_subscriber error\n");
subscriber_shutdown(participant);
return -1;
}
/* Register the type before creating the topic */
type_name = HelloMsgTypeSupport_get_type_name();
retcode = HelloMsgTypeSupport_register_type(participant, type_name);
if (retcode != DDS_RETCODE_OK) {
fprintf(stderr, "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_C_Storage",
type_name,
&DDS_TOPIC_QOS_DEFAULT,
NULL /* listener */,
DDS_STATUS_MASK_NONE);
if (topic == NULL) {
fprintf(stderr, "create_topic error\n");
subscriber_shutdown(participant);
return -1;
}
/* Set up a data reader listener */
reader_listener.on_requested_deadline_missed =
HelloMsgListener_on_requested_deadline_missed;
reader_listener.on_requested_incompatible_qos =
HelloMsgListener_on_requested_incompatible_qos;
reader_listener.on_sample_rejected = HelloMsgListener_on_sample_rejected;
reader_listener.on_liveliness_changed =
HelloMsgListener_on_liveliness_changed;
reader_listener.on_sample_lost = HelloMsgListener_on_sample_lost;
reader_listener.on_subscription_matched =
HelloMsgListener_on_subscription_matched;
reader_listener.on_data_available = HelloMsgListener_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) {
fprintf(stderr, "create_datareader error\n");
subscriber_shutdown(participant);
return -1;
}
/* Main loop */
for (count = 0; (sample_count == 0) || (count < sample_count); ++count) {
printf("HelloMsg 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/recording_service/service_admin/cpp/Requester.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.
*/
#include <dds/core/types.hpp>
#include <dds/core/External.hpp>
#include <dds/domain/domainfwd.hpp>
#include <rti/request/Requester.hpp>
#include "rti/idlgen/RecordingServiceTypes.hpp"
#include "rti/idlgen/ServiceAdmin.hpp"
#include "rti/idlgen/ServiceCommon.hpp"
enum OctetKind {
DATATAG,
BREAKPOINT,
CONTINUE,
TIMESTAMPHOLDER,
NONE
};
/*
* This class acts as an interpreter between the command-line arguments provided
* to the executable call and the main application (class Application).
*/
class ArgumentsParser {
public:
ArgumentsParser(int argc, char *argv[]);
~ArgumentsParser();
RTI::Service::Admin::CommandActionKind command_kind() const;
const std::string &resource_identifier() const;
const std::string &command_params() const;
uint32_t admin_domain_id() const;
const RTI::RecordingService::DataTagParams& data_tag_params() const;
const OctetKind octet_kind() const;
const RTI::RecordingService::BreakpointParams& br_params() const;
const RTI::RecordingService::ContinueParams& continue_params() const;
const RTI::RecordingService::TimestampHolder& timestamp_holder() const;
private:
RTI::Service::Admin::CommandActionKind command_kind_;
std::string resource_id_;
std::string command_params_;
uint32_t admin_domain_id_;
OctetKind octet_kind_;
RTI::RecordingService::DataTagParams data_tag_params_;
RTI::RecordingService::TimestampHolder timestamp_holder_;
RTI::RecordingService::ContinueParams continue_params_;
RTI::RecordingService::BreakpointParams br_params_;
void print_usage(const std::string& program_name);
void report_argument_error(
const std::string& program_name,
const std::string& tag,
const std::string& error);
static RTI::Service::Admin::CommandActionKind parse_command_kind(char *arg);
static uint64_t parse_number(char *arg);
static bool is_number(char *arg);
};
/*
* The main application class. This application can be understood as a one-shot
* application. It will use the ArgumentsParser facade to access the parameters
* necessary to generate a service administration command request, and then send
* that request. It will wait to receive replies for the sent command and print
* those out. Then it will exit.
*/
class Application {
public:
/*
* A requester type that can send command requests and receive replies to
* those requests.
*/
typedef rti::request::Requester<
RTI::Service::Admin::CommandRequest,
RTI::Service::Admin::CommandReply>
ServiceAdminRequester;
Application(ArgumentsParser &args_parser);
~Application();
private:
ArgumentsParser &args_parser_;
dds::domain::DomainParticipant participant_;
rti::request::RequesterParams requester_params_;
/*
* This is the main Request/Reply type that will be used to ask the
* service administration to execute commands.
*
*/
dds::core::external<ServiceAdminRequester>::shared_ptr command_requester_;
};
| hpp |
rticonnextdds-examples | data/projects/rticonnextdds-examples/recording_service/service_admin/cpp/Requester.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 <sstream>
#include <stdexcept>
#include <stdio.h>
#include <stdlib.h>
#include "Requester.hpp"
using namespace RTI::Service::Admin;
using namespace RTI::RecordingService;
CommandActionKind ArgumentsParser::parse_command_kind(char *arg)
{
std::string arg_str(arg);
CommandActionKind command_kind;
if (arg_str.compare("CREATE") == 0) {
command_kind = CommandActionKind::CREATE_ACTION;
} else if (arg_str.compare("GET") == 0) {
command_kind = CommandActionKind::GET_ACTION;
} else if (arg_str.compare("UPDATE") == 0) {
command_kind = CommandActionKind::UPDATE_ACTION;
} else if (arg_str.compare("DELETE") == 0) {
command_kind = CommandActionKind::DELETE_ACTION;
} else {
std::string ex_what("Invalid command action kind: ");
ex_what += arg;
throw std::runtime_error(ex_what);
}
return command_kind;
}
uint64_t ArgumentsParser::parse_number(char *arg)
{
std::stringstream stream(arg);
uint64_t value;
if (!(stream >> value)) {
std::stringstream error_stream;
error_stream << "Error: could not parse uint64 value provided, '" << arg
<< "'";
throw std::runtime_error(error_stream.str());
}
return value;
}
bool ArgumentsParser::is_number(char *arg)
{
bool value = true;
std::stringstream stream(arg);
uint64_t value_number;
if (!(stream >> value_number)) {
value = false;
}
return value;
}
void ArgumentsParser::print_usage(const std::string &program_name)
{
std::cout << "Usage:" << std::endl;
std::cout
<< " " << program_name
<< " <COMMAND_KIND> <RESOURCE_ID> <COMMAND_PARAMS> [optional args]"
<< std::endl;
std::cout << " Where:" << std::endl;
std::cout << " COMMAND_KIND = {CREATE|GET|UPDATE|DELETE}; required"
<< std::endl;
std::cout
<< " RESOURCE_ID = the identity of the target resource "
"in "
<< std::endl
<< " the service's resource tree that the "
<< std::endl
<< " command action should be applied to; "
<< std::endl
<< " required" << std::endl;
std::cout << " COMMAND_PARAMS = additional parameters needed by the "
<< std::endl
<< " command action, e.g. 'pause'; "
"optional "
<< std::endl
<< " (some command kinds need no "
"parameters)"
<< std::endl;
std::cout << " The following is a list of additional arguments that can "
<< std::endl
<< " be provided to the application:" << std::endl;
std::cout << " --domain-id:" << std::endl;
std::cout << " Format: --domain-id <uint32>" << std::endl;
std::cout
<< " Description: the DDS domain ID to use with the "
<< std::endl
<< " requester (has to be the same as the service's "
<< std::endl
<< " administration domain ID). Default: 0."
<< std::endl;
std::cout << " --time-tag:" << std::endl;
std::cout << " Format: --time-tag <name> [<description>]"
<< std::endl;
std::cout
<< " Description: have Recorder create a symbolic "
<< std::endl
<< " time-stamp with the given name and description "
<< std::endl
<< " and use the current time at the moment of "
<< std::endl
<< " sending the command. Description is optional."
<< std::endl;
std::cout << " --add-breakpoint:" << std::endl;
std::cout << " Format: --add-breakpoint <timestamp> [<label>]"
<< std::endl;
std::cout << " Description: the breakpoint to be added in the "
"replay."
<< std::endl
<< " The timestamp have to be provided in "
"nanosecond "
<< std::endl
<< " format. Label is optional." << std::endl;
std::cout << " --remove-breakpoint:" << std::endl;
std::cout << " Format: --remove-breakpoint <timestamp>|<label>"
<< std::endl;
std::cout
<< " Description: the breakpoint to be removed of the "
"replay."
<< std::endl
<< " You can specify the breakpoint to be removed by"
<< std::endl
<< " timestamp or by label." << std::endl;
std::cout << " --goto-breakpoint:" << std::endl;
std::cout << " Format: --goto-breakpoint <timestamp>|<label>"
<< std::endl;
std::cout << " Description: Jump to an existed breakpoint"
<< std::endl
<< " You can jump by the breakpoint timestamp"
<< std::endl
<< " or by the breakpoint label." << std::endl;
std::cout << " --continue-seconds:" << std::endl;
std::cout << " Format: --continue-seconds <seconds>"
<< std::endl;
std::cout << " Description: To resume the replay after hit a "
<< std::endl
<< " breakpoint. You can resume the replay for "
<< std::endl
<< " a number of seconds. " << std::endl;
std::cout << " --continue-slices:" << std::endl;
std::cout << " Format: --continue-slices <slices>" << std::endl;
std::cout << " Description: To resume the replay after hit a "
<< std::endl
<< " breakpoint. You can resume the replay for "
<< std::endl
<< " a number of slices. " << std::endl;
std::cout << " --current-timestamp:" << std::endl;
std::cout << " Format: --current-timestamp <timestamp_nanos>"
<< std::endl;
std::cout << " Description: To jump in time during the replay. "
<< std::endl
<< " The timestamp have to be provided in "
"nanosecond "
<< std::endl
<< " format. " << std::endl;
}
void ArgumentsParser::report_argument_error(
const std::string &program_name,
const std::string &tag,
const std::string &error)
{
print_usage(program_name);
std::stringstream error_stream;
error_stream << "Error: " << error << tag << " parameter";
throw std::runtime_error(error_stream.str());
}
ArgumentsParser::ArgumentsParser(int argc, char *argv[])
: admin_domain_id_(0), octet_kind_(OctetKind::NONE)
{
const std::string DOMAIN_ID_ARG_NAME("--domain-id");
const std::string TIME_TAG_ARG_NAME("--time-tag");
const std::string ADD_BR_ARG_NAME("--add-breakpoint");
const std::string RM_BR_ARG_NAME("--remove-breakpoint");
const std::string GOTO_BR_ARG_NAME("--goto-breakpoint");
const std::string CONTINUE_SEC_ARG_NAME("--continue-seconds");
const std::string CONTINUE_SLICE_ARG_NAME("--continue-slices");
const std::string JUMP_TIME_ARG_NAME("--current-timestamp");
int current_arg = 0;
// Parse mandatory arguments, we at least need 4 (includes program name)
if (argc < 3) {
print_usage(argv[0]);
throw std::runtime_error("Error: invalid number of arguments");
}
// Command action kind
command_kind_ = parse_command_kind(argv[1]);
// Resource identifier
resource_id_ = argv[2];
// The following code requires more arguments than just the required ones
if (argc > 3) {
// Command parameters; it's optional
if (DOMAIN_ID_ARG_NAME.compare(argv[3]) != 0
&& TIME_TAG_ARG_NAME.compare(argv[3]) != 0
&& ADD_BR_ARG_NAME.compare(argv[3]) != 0
&& RM_BR_ARG_NAME.compare(argv[3]) != 0
&& GOTO_BR_ARG_NAME.compare(argv[3]) != 0
&& CONTINUE_SEC_ARG_NAME.compare(argv[3]) != 0
&& CONTINUE_SLICE_ARG_NAME.compare(argv[3]) != 0
&& JUMP_TIME_ARG_NAME.compare(argv[3]) != 0) {
/*
* If this parameter is not one of the extra arguments, it has to be
* the optional command parameters string
*/
command_params_ = argv[3];
current_arg = 4;
} else {
current_arg = 3;
}
// Extra arguments
while (current_arg < argc) {
if (DOMAIN_ID_ARG_NAME.compare(argv[current_arg]) == 0) {
// This parameter needs one argument
if (current_arg + 1 >= argc) {
print_usage(argv[0]);
std::stringstream error_stream;
error_stream << "Error: no uint32 value provided for "
<< DOMAIN_ID_ARG_NAME << " parameter";
throw std::runtime_error(error_stream.str());
}
admin_domain_id_ = parse_number(argv[current_arg + 1]);
current_arg += 2;
} else if (TIME_TAG_ARG_NAME.compare(argv[current_arg]) == 0) {
// This parameter may use one or two arguments
if (current_arg + 1 < argc) {
octet_kind_ = OctetKind::DATATAG;
data_tag_params_.tag_name(argv[current_arg + 1]);
data_tag_params_.timestamp_offset(0);
// Check if a description has been provided
if (current_arg + 2 < argc) {
data_tag_params_.tag_description(argv[current_arg + 2]);
current_arg += 3;
} else {
current_arg += 2;
}
} else {
// No name provided for the time tag
report_argument_error(
argv[0],
TIME_TAG_ARG_NAME,
"no name provided for ");
}
} else if (ADD_BR_ARG_NAME.compare(argv[current_arg]) == 0) {
if (current_arg + 1 < argc) {
octet_kind_ = OctetKind::BREAKPOINT;
// This parameter may use one or two arguments
br_params_.value().timestamp_nanos(
parse_number(argv[current_arg + 1]));
// Check if a label has been provided
if (current_arg + 2 < argc) {
br_params_.label(std::string(argv[current_arg + 2]));
current_arg += 3;
} else {
current_arg += 2;
}
} else {
// No timestamp provided for the breakpoint
report_argument_error(
argv[0],
ADD_BR_ARG_NAME,
"no timestamp provided for ");
}
} else if (RM_BR_ARG_NAME.compare(argv[current_arg]) == 0) {
octet_kind_ = OctetKind::BREAKPOINT;
if (current_arg + 2 == argc) {
// This parameter may use one or two arguments
if (is_number(argv[current_arg + 1])) {
br_params_.value().timestamp_nanos(
parse_number(argv[current_arg + 1]));
} else {
br_params_.label(std::string(argv[current_arg + 1]));
}
current_arg += 2;
} else if (current_arg + 2 < argc) {
br_params_.value().timestamp_nanos(
parse_number(argv[current_arg + 1]));
br_params_.label(std::string(argv[current_arg + 2]));
current_arg += 3;
} else {
// No information for the breakpoint
report_argument_error(
argv[0],
RM_BR_ARG_NAME,
"no information provided for ");
}
} else if (GOTO_BR_ARG_NAME.compare(argv[current_arg]) == 0) {
octet_kind_ = OctetKind::BREAKPOINT;
if (current_arg + 2 == argc) {
// This parameter may use one or two arguments
if (is_number(argv[current_arg + 1])) {
br_params_.value().timestamp_nanos(
parse_number(argv[current_arg + 1]));
} else {
br_params_.label(std::string(argv[current_arg + 1]));
}
current_arg += 2;
} else if (current_arg + 2 < argc) {
br_params_.value().timestamp_nanos(
parse_number(argv[current_arg + 1]));
br_params_.label(std::string(argv[current_arg + 2]));
current_arg += 3;
} else {
// No information for the breakpoint
report_argument_error(
argv[0],
GOTO_BR_ARG_NAME,
"no information provided for ");
}
} else if (CONTINUE_SEC_ARG_NAME.compare(argv[current_arg]) == 0) {
if (current_arg + 1 < argc) {
octet_kind_ = OctetKind::CONTINUE;
continue_params_.value().offset(
parse_number(argv[current_arg + 1]));
current_arg += 2;
} else {
// No number of seconds for the continue param
report_argument_error(
argv[0],
CONTINUE_SEC_ARG_NAME,
"no number of seconds provided for ");
}
} else if (
CONTINUE_SLICE_ARG_NAME.compare(argv[current_arg]) == 0) {
if (current_arg + 1 < argc) {
octet_kind_ = OctetKind::CONTINUE;
continue_params_.value().slices(
parse_number(argv[current_arg + 1]));
current_arg += 2;
} else {
// No number of slices for the continue param
report_argument_error(
argv[0],
CONTINUE_SLICE_ARG_NAME,
"no number of slices provided for ");
}
} else if (JUMP_TIME_ARG_NAME.compare(argv[current_arg]) == 0) {
if (current_arg + 1 < argc) {
octet_kind_ = OctetKind::TIMESTAMPHOLDER;
timestamp_holder_.timestamp_nanos(
parse_number(argv[current_arg + 1]));
current_arg += 2;
} else {
// No timestamp for the jump in time
report_argument_error(
argv[0],
JUMP_TIME_ARG_NAME,
"no timestamp provided for ");
}
} else {
// Unrecognised parameter
print_usage(argv[0]);
std::stringstream error_stream;
error_stream << "Error: unrecognized parameter, '"
<< argv[current_arg] << "'";
throw std::runtime_error(error_stream.str());
}
}
}
}
ArgumentsParser::~ArgumentsParser()
{
}
CommandActionKind ArgumentsParser::command_kind() const
{
return command_kind_;
}
const std::string &ArgumentsParser::resource_identifier() const
{
return resource_id_;
}
const std::string &ArgumentsParser::command_params() const
{
return command_params_;
}
uint32_t ArgumentsParser::admin_domain_id() const
{
return admin_domain_id_;
}
const DataTagParams &ArgumentsParser::data_tag_params() const
{
return data_tag_params_;
}
const OctetKind ArgumentsParser::octet_kind() const
{
return octet_kind_;
}
const BreakpointParams &ArgumentsParser::br_params() const
{
return br_params_;
}
const ContinueParams &ArgumentsParser::continue_params() const
{
return continue_params_;
}
const TimestampHolder &ArgumentsParser::timestamp_holder() const
{
return timestamp_holder_;
}
Application::Application(ArgumentsParser &args_parser)
: args_parser_(args_parser),
participant_(args_parser.admin_domain_id()),
requester_params_(participant_)
{
/*
* Prepare the requester params: we need topic names for the request and
* reply types. These are defined in the ServiceAdmin.idl file and generated
* when RTI DDS Code Generator is run.
*/
requester_params_.request_topic_name(COMMAND_REQUEST_TOPIC_NAME);
requester_params_.reply_topic_name(COMMAND_REPLY_TOPIC_NAME);
/*
* Note: the QoS library and profile we are using comes from the
* request/reply example provided in the Connext installation.
* Recall that the profile must be augmented with the properties needed
* for unbounded support in the Data Writer QoS.
*/
requester_params_.datareader_qos(
dds::core::QosProvider::Default().datareader_qos(
"ServiceAdministrationProfiles::"
"ServiceAdminRequesterProfile"));
requester_params_.datawriter_qos(
dds::core::QosProvider::Default().datawriter_qos(
"ServiceAdministrationProfiles::"
"ServiceAdminRequesterProfile"));
/*
* Now that we have set up all the parameters for the requester instance, we
* can create it.
*/
command_requester_ = dds::core::external<ServiceAdminRequester>::shared_ptr(
new ServiceAdminRequester(requester_params_));
CommandRequest command_request;
// Check if we have time tag parameters
OctetKind kind = args_parser.octet_kind();
switch (kind) {
case OctetKind::DATATAG:
dds::topic::topic_type_support<DataTagParams>::to_cdr_buffer(
reinterpret_cast<std::vector<char> &>(
command_request.octet_body()),
args_parser_.data_tag_params());
break;
case OctetKind::BREAKPOINT:
dds::topic::topic_type_support<BreakpointParams>::to_cdr_buffer(
reinterpret_cast<std::vector<char> &>(
command_request.octet_body()),
args_parser_.br_params());
break;
case OctetKind::CONTINUE:
dds::topic::topic_type_support<ContinueParams>::to_cdr_buffer(
reinterpret_cast<std::vector<char> &>(
command_request.octet_body()),
args_parser_.continue_params());
break;
case OctetKind::TIMESTAMPHOLDER:
dds::topic::topic_type_support<TimestampHolder>::to_cdr_buffer(
reinterpret_cast<std::vector<char> &>(
command_request.octet_body()),
args_parser_.timestamp_holder());
break;
case OctetKind::NONE:
default:
break;
}
command_request.action(args_parser_.command_kind());
command_request.resource_identifier(args_parser_.resource_identifier());
command_request.string_body(args_parser_.command_params());
/*
* Wait until the command requester's request data writer has matched at
* least one publication.
*/
int32_t current_pub_matches = command_requester_->request_datawriter()
.publication_matched_status()
.current_count();
int32_t wait_cycles = 1200;
while (current_pub_matches < 1 && wait_cycles > 0) {
rti::util::sleep(dds::core::Duration::from_millisecs(50));
current_pub_matches = command_requester_->request_datawriter()
.publication_matched_status()
.current_count();
wait_cycles--;
}
if (wait_cycles == 0) {
throw std::runtime_error(
"Error: command requester's request data "
"writer matched no subscriptions");
}
/*
* Wait until the command requester's reply data reader has matched at least
* one subscription.
*/
int32_t current_sub_matches = command_requester_->reply_datareader()
.subscription_matched_status()
.current_count();
wait_cycles = 1200;
while (current_sub_matches < 1 && wait_cycles > 0) {
rti::util::sleep(dds::core::Duration::from_millisecs(50));
current_sub_matches = command_requester_->reply_datareader()
.subscription_matched_status()
.current_count();
wait_cycles--;
}
if (wait_cycles == 0) {
throw std::runtime_error(
"Error: command requester's reply data "
"reader matched no publications");
}
std::cout << "Command request about to be sent:" << std::endl
<< command_request << std::endl;
/*
* Send the request, obtaining this request's ID. We will use it later to
* correlate the replies with the request.
*/
rti::core::SampleIdentity request_id =
command_requester_->send_request(command_request);
/*
* Wait for replies. This version of the method waits for the first reply
* directed to the request we produced, a maximum of 60 seconds.
*/
if (!command_requester_->wait_for_replies(
1,
dds::core::Duration::from_secs(60),
request_id)) {
throw std::runtime_error(
"Error: no reply received for request "
"(60 seconds timeout)");
}
// Getting to this point means we have received reply(ies) for our request
dds::sub::LoanedSamples<CommandReply> replies =
command_requester_->take_replies(request_id);
std::cout << "Received " << replies.length() << " replies from service"
<< std::endl;
for (unsigned int i = 0; i < replies.length(); ++i) {
std::cout << " Reply " << i + 1 << ":" << std::endl;
if (replies[i].info().valid()) {
std::cout << " Retcode = "
<< replies[i].data().retcode() << std::endl;
std::cout << " Native retcode = "
<< replies[i].data().native_retcode() << std::endl;
std::cout << " String body = "
<< replies[i].data().string_body() << std::endl;
} else {
std::cout << " Sample Invalid" << std::endl;
}
}
}
Application::~Application()
{
}
int main(int argc, char *argv[])
{
try {
/*
* The main method is quite simple. We have a class that is a
* command-line interpreter (ArgumentsParser) for the main application
* class (Application). This class will produce a command request with
* the given command-line parameters and wait for any replies. It will
* then exit. This can be understand as a one-shot application,
* producing just one service administration request.
*/
ArgumentsParser args_parser(argc, argv);
Application requester_app(args_parser);
} catch (std::exception &ex) {
std::cerr << ex.what() << std::endl;
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
}
| cxx |
rticonnextdds-examples | data/projects/rticonnextdds-examples/recording_service/service_as_lib/cpp/ServiceAsLibExample.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 <cstdlib>
#include <iostream>
#include <sstream>
#include <stdexcept>
#include <thread>
#include <rti/recording/Service.hpp>
#include <rti/recording/ServiceProperty.hpp>
void print_usage(const char *executable)
{
std::cout << "Usage: " << executable
<< " {record,replay} <Domain ID (int)> "
<< "[running secs (uint, optional, default: 60)]" << std::endl;
}
void process_role(
int argc,
char *argv[],
rti::recording::ServiceProperty &service_property,
uint32_t &running_seconds)
{
const std::string recorder_role("record");
const std::string replay_role("replay");
// Check if a role argument has been provided
if (argc > 1) {
if (recorder_role.compare(argv[1]) == 0) {
service_property.application_role(
rti::recording::ApplicationRoleKind::RECORD_APPLICATION);
service_property.cfg_file("recorder_config.xml");
} else if (replay_role.compare(argv[1]) == 0) {
service_property.application_role(
rti::recording::ApplicationRoleKind::REPLAY_APPLICATION);
service_property.cfg_file("replay_config.xml");
} else {
throw std::runtime_error(
"Unsupported role arg: one of {record,replay} expected");
}
} else {
throw std::runtime_error("Service role arg not provided");
}
// Check if a DDS domain ID has been provided
if (argc > 2) {
std::stringstream domain_id_stream(argv[2]);
int32_t domain_id = 0;
domain_id_stream >> domain_id;
if (domain_id_stream.bad()) {
throw std::runtime_error(
"Invalid arg value provided for domain ID");
}
// Set up domain ID base, admin domain ID and monitoring domain ID
service_property.domain_id_base(domain_id);
service_property.administration_domain_id(domain_id);
service_property.enable_administration(true);
service_property.monitoring_domain_id(domain_id);
service_property.enable_monitoring(true);
} else {
throw std::runtime_error("Domain ID arg not provided");
}
// Check if the running seconds have been provided
if (argc > 3) {
std::stringstream running_secs_stream(argv[3]);
running_secs_stream >> running_seconds;
if (running_secs_stream.bad()) {
throw std::runtime_error(
"Invalid arg value provided for running secs");
}
}
}
int main(int argc, char *argv[])
{
/*
* The ServiceProperty class defines runtime parameters for the service
* instance, like the configuration file, the configuration name,
* administration and monitoring DDS domain IDs, the DDS domain ID base
* (offset) for the domain participants defined in the configuration, etc
*/
rti::recording::ServiceProperty service_property;
uint32_t running_seconds = 60;
try {
process_role(argc, argv, service_property, running_seconds);
} catch (const std::exception &ex) {
std::cerr << "Exception: " << ex.what() << std::endl;
print_usage(argv[0]);
return EXIT_FAILURE;
}
// The service configuration, regardless of the role, is always the same
service_property.service_name("service_as_lib");
try {
/*
* Create the instance of the Recording Service. It won't start
* executing until we call the start() method.
*/
rti::recording::Service embedded_service(service_property);
embedded_service.start();
// Wait for 'running_seconds' seconds
std::this_thread::sleep_for(std::chrono::seconds(running_seconds));
embedded_service.stop();
} catch (const std::exception &ex) {
std::cerr << "Exception: " << ex.what() << std::endl;
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
}
| cxx |
rticonnextdds-examples | data/projects/rticonnextdds-examples/flat_data_latency/c++11/CameraImage_publisher.cxx | /*
* (c) 2018 Copyright, Real-Time Innovations, Inc. All rights reserved.
* Subject to Eclipse Public License v1.0; see LICENSE.md for details.
*/
#include <iostream>
#include <memory> // for shared_ptr and unique_ptr
#include <signal.h>
#include <dds/pub/ddspub.hpp>
#include <dds/sub/ddssub.hpp>
#include <dds/core/ddscore.hpp>
#include <rti/config/Logger.hpp>
#include <rti/util/util.hpp> // for sleep()
#include <rti/core/ListenerBinder.hpp>
#include "CameraImage.hpp"
#include <rti/zcopy/sub/ZcopyDataReader.hpp>
#include <rti/zcopy/pub/ZcopyDataWriter.hpp>
#include "Common.hpp"
void publisher_flat(const ApplicationOptions &options)
{
using namespace flat_types;
using namespace dds::core::policy;
std::cout << "Running publisher_flat\n";
auto participant_qos = dds::core::QosProvider::Default().participant_qos();
configure_nic(participant_qos, options.nic);
dds::domain::DomainParticipant participant(
options.domain_id,
participant_qos);
// Create the ping DataWriter
dds::topic::Topic<CameraImage> ping_topic(participant, "CameraImagePing");
dds::pub::DataWriter<CameraImage> writer(
dds::pub::Publisher(participant),
ping_topic);
// Create the pong DataReader
dds::topic::Topic<CameraImage> pong_topic(participant, "CameraImagePong");
dds::sub::DataReader<CameraImage> reader(
dds::sub::Subscriber(participant),
pong_topic);
// Create a ReadCondition for any data on the pong reader, and attach it to
// a Waitset
dds::sub::cond::ReadCondition read_condition(
reader,
dds::sub::status::DataState::any());
dds::core::cond::WaitSet waitset;
waitset += read_condition;
std::cout<< "Waiting for the subscriber application\n";
wait_for_reader(writer);
wait_for_writer(reader);
std::cout << "Discovery complete\n";
int count = 0;
uint64_t total_latency = 0;
uint64_t latency_interval_start_time = 0;
uint64_t start_ts = participant->current_time().to_microsecs();
while(count <= options.sample_count || options.sample_count == -1) {
// Get and populate the sample
auto ping_sample = writer.extensions().get_loan();
populate_flat_sample(*ping_sample, count);
// Write the ping sample:
auto ping = ping_sample->root();
uint64_t send_ts = participant->current_time().to_microsecs();
if ((count == options.sample_count)
|| (send_ts - start_ts >= options.execution_time)) {
// notify reader about last sample
ping.timestamp(0);
writer.write(*ping_sample);
break;
}
ping.timestamp(send_ts);
// Write the ping sample.
//
// The DataWriter now owns the buffer and the application should not
// reuse the sample.
writer.write(*ping_sample);
if (latency_interval_start_time == 0) {
latency_interval_start_time = send_ts;
}
// Wait for the pong
auto conditions = waitset.wait(dds::core::Duration(10));
if (conditions.empty()) {
std::cout << "Wait for pong: timeout\n";
}
auto pong_samples = reader.take();
if (pong_samples.length() > 0 && pong_samples[0].info().valid()) {
count++;
auto pong = pong_samples[0].data().root();
uint64_t receive_ts = participant->current_time().to_microsecs();
uint64_t latency = receive_ts - pong.timestamp();
total_latency += latency;
if (receive_ts - latency_interval_start_time > 4000000) {
std::cout << "Average end-to-end latency: "
<< total_latency / (count * 2) << " microseconds\n";
latency_interval_start_time = 0;
}
}
}
std::cout << "Average end-to-end latency: "
<< total_latency / (count * 2) << " microseconds\n";
// Wait for unmatch
wait_for_reader(writer, false);
std::cout << "Publisher shutting down\n";
}
void publisher_zero_copy(const ApplicationOptions &options)
{
using namespace zero_copy_types;
using namespace rti::core::policy;
std::cout << "Running publisher_zero_copy\n";
dds::domain::DomainParticipant participant(options.domain_id);
// Create the ping DataWriter.
dds::topic::Topic<CameraImage> ping_topic(participant, "CameraImagePing");
dds::pub::DataWriter<CameraImage> writer(
dds::pub::Publisher(participant),
ping_topic);
// Create the pong DataReader
dds::topic::Topic<CameraImage> pong_topic(participant, "CameraImagePong");
dds::sub::DataReader<CameraImage> reader(
dds::sub::Subscriber(participant),
pong_topic);
// Create a ReadCondition for any data on the pong reader, and attach it to
// a Waitset
dds::sub::cond::ReadCondition read_condition(
reader,
dds::sub::status::DataState::any());
dds::core::cond::WaitSet waitset;
waitset += read_condition;
std::cout<< "Waiting for the subscriber application\n";
wait_for_reader(writer);
wait_for_writer(reader);
std::cout << "Discovery complete\n";
// In this loop we write pings and wait for pongs, measuring the end-to-end
// latency
uint64_t total_latency = 0;
uint64_t latency_interval_start_time = 0;
int count = 0;
uint64_t start_ts = participant->current_time().to_microsecs();
while (count <= options.sample_count || options.sample_count == -1) {
// Create and write the ping sample:
// The DataWriter gets a sample from its shared memory sample pool. This
// operation does not allocate memory. Samples are returned to the sample
// pool when they are returned from the DataWriter queue.
CameraImage *ping_sample = writer.extensions().get_loan();
// Populate the sample
populate_plain_sample(*ping_sample, count);
uint64_t send_ts = participant->current_time().to_microsecs();
if ((count == options.sample_count)
|| (send_ts - start_ts >= options.execution_time)) {
// notify reader about last sample
ping_sample->timestamp(0);
writer.write(*ping_sample);
break;
}
ping_sample->timestamp(send_ts);
writer.write(*ping_sample);
if (latency_interval_start_time == 0) {
latency_interval_start_time = send_ts;
}
// Wait for the pong
auto conditions = waitset.wait(dds::core::Duration(10));
if (conditions.empty()) {
std::cout << "Wait for pong: timeout\n";
}
auto pong_samples = reader.take();
if (pong_samples.length() > 0 && pong_samples[0].info().valid()) {
count++;
uint64_t recv_ts = participant->current_time().to_microsecs();
uint64_t latency = recv_ts - pong_samples[0].data().timestamp();
total_latency += latency;
if (recv_ts - latency_interval_start_time > 4000000) {
std::cout << "Average end-to-end latency: "
<< total_latency / (count * 2) << " microseconds\n";
latency_interval_start_time = 0;
}
}
}
std::cout << "Average end-to-end latency: "
<< total_latency / (count * 2) << " microseconds\n";
// Wait for unmatch
wait_for_reader(writer, false);
std::cout << "Publisher shutting down\n";
}
void publisher_flat_zero_copy(const ApplicationOptions &options)
{
using namespace flat_zero_copy_types;
using namespace rti::core::policy;
using namespace dds::core::policy;
std::cout << "Running publisher_flat_zero_copy\n";
auto participant_qos = dds::core::QosProvider::Default().participant_qos();
configure_nic(participant_qos, options.nic);
dds::domain::DomainParticipant participant(
options.domain_id,
participant_qos);
// Create the ping DataWriter. We configure the pool of shared-memory
// samples to contain 10 at all times.
dds::topic::Topic<CameraImage> ping_topic(participant, "CameraImagePing");
dds::pub::DataWriter<CameraImage> writer(
dds::pub::Publisher(participant),
ping_topic);
// Create the pong DataReader
dds::topic::Topic<CameraImage> pong_topic(participant, "CameraImagePong");
dds::sub::DataReader<CameraImage> reader(
dds::sub::Subscriber(participant),
pong_topic);
// Create a ReadCondition for any data on the pong reader, and attach it to
// a Waitset
dds::sub::cond::ReadCondition read_condition(
reader,
dds::sub::status::DataState::any());
dds::core::cond::WaitSet waitset;
waitset += read_condition;
std::cout<< "Waiting for the subscriber application\n";
wait_for_reader(writer);
wait_for_writer(reader);
std::cout << "Discovery complete\n";
// In this loop we write pings and wait for pongs, measuring the end-to-end
// latency
uint64_t total_latency = 0;
int count = 0;
uint64_t latency_interval_start_time = 0;
uint64_t start_ts = participant->current_time().to_microsecs();
while (count <= options.sample_count || options.sample_count == -1) {
// Create and write the ping sample:
CameraImage *ping_sample = writer.extensions().get_loan();
// Populate the sample
populate_flat_sample(*ping_sample, count);
auto ping = ping_sample->root();
uint64_t send_ts = participant->current_time().to_microsecs();
if ((count == options.sample_count)
|| (send_ts - start_ts >= options.execution_time)) {
// notify reader about last sample
ping.timestamp(0);
writer.write(*ping_sample);
break;
}
ping.timestamp(send_ts);
writer.write(*ping_sample);
if (latency_interval_start_time == 0) {
latency_interval_start_time = send_ts;
}
// Wait for the pong
auto conditions = waitset.wait(dds::core::Duration(10));
if (conditions.empty()) {
std::cout << "Wait for pong: timeout\n";
}
auto pong_samples = reader.take();
if (pong_samples.length() > 0 && pong_samples[0].info().valid()) {
count++;
auto pong = pong_samples[0].data().root();
uint64_t recv_ts = participant->current_time().to_microsecs();
uint64_t latency = recv_ts - pong.timestamp();
total_latency += latency;
if (recv_ts - latency_interval_start_time > 4000000) {
std::cout << "Average end-to-end latency: "
<< total_latency / (count * 2) << " microseconds\n";
latency_interval_start_time = 0;
}
}
}
std::cout << "Average end-to-end latency: "
<< total_latency / (count * 2) << " microseconds\n";
// Wait for unmatch
wait_for_reader(writer, false);
std::cout << "Publisher shutting down\n";
}
void publisher_plain(const ApplicationOptions &options)
{
using namespace plain_types;
using namespace dds::core::policy;
std::cout << "Running publisher_plain\n";
auto participant_qos = dds::core::QosProvider::Default().participant_qos();
configure_nic(participant_qos, options.nic);
dds::domain::DomainParticipant participant(
options.domain_id,
participant_qos);
// Create the ping DataWriter
dds::topic::Topic<CameraImage> ping_topic(participant, "CameraImagePing");
// Create the pong DataWriter with a profile from USER_QOS_PROFILES.xml
dds::pub::DataWriter<CameraImage> writer(
dds::pub::Publisher(participant),
ping_topic);
// Create the pong DataReader
dds::topic::Topic<CameraImage> pong_topic(participant, "CameraImagePong");
dds::sub::DataReader<CameraImage> reader(
dds::sub::Subscriber(participant),
pong_topic);
// Create a ReadCondition for any data on the pong reader, and attach it to
// a Waitset
dds::sub::cond::ReadCondition read_condition(
reader,
dds::sub::status::DataState::any());
dds::core::cond::WaitSet waitset;
waitset += read_condition;
std::unique_ptr<CameraImage> ping_sample(new CameraImage);
std::cout<< "Waiting for the subscriber application\n";
wait_for_reader(writer);
wait_for_writer(reader);
std::cout << "Discovery complete\n";
int count = 0;
uint64_t total_latency = 0;
uint64_t latency_interval_start_time = 0;
uint64_t start_ts = participant->current_time().to_microsecs();
while(count <= options.sample_count || options.sample_count == -1) {
uint64_t send_ts = participant->current_time().to_microsecs();
if ((count == options.sample_count)
|| (send_ts - start_ts >= options.execution_time)) {
ping_sample->timestamp(0);
writer.write(*ping_sample);
break;
}
// Write the ping sample:
ping_sample->timestamp(send_ts);
writer.write(*ping_sample);
if (latency_interval_start_time == 0) {
latency_interval_start_time = send_ts;
}
// Wait for the pong
auto conditions = waitset.wait(dds::core::Duration(10));
if (conditions.empty()) {
std::cout << "Wait for pong: timeout\n";
}
auto pong_samples = reader.take();
if (pong_samples.length() > 0 && pong_samples[0].info().valid()) {
count++;
uint64_t recv_ts = participant->current_time().to_microsecs();
uint64_t latency = recv_ts - pong_samples[0].data().timestamp();
total_latency += latency;
if (recv_ts - latency_interval_start_time > 4000000) {
std::cout << "Average end-to-end latency: "
<< total_latency / (count * 2) << " microseconds\n";
latency_interval_start_time = 0;
}
}
}
std::cout << "Average end-to-end latency: "
<< total_latency / (count * 2) << " microseconds\n";
// Wait for unmatch
wait_for_reader(writer, false);
std::cout << "Publisher shutting down\n";
}
void publisher_copy_sample(int domain_id, int sample_count)
{
using namespace plain_types;
std::cout << "Running publisher_copy_sample\n";
dds::domain::DomainParticipant participant (domain_id);
std::unique_ptr<CameraImage> ping_sample(new CameraImage);
std::unique_ptr<CameraImage> copy(new CameraImage);
int count = 0;
uint64_t total_latency = 0;
while(count < sample_count || sample_count == 0) {
ping_sample->data()[45345] = count + sample_count + 100;
ping_sample->timestamp(participant->current_time().to_microsecs());
*copy = *ping_sample;
if (copy->data()[45345] == 3) {
return;
}
count++;
uint64_t latency = participant->current_time().to_microsecs()
- ping_sample->timestamp();
total_latency += latency;
if (count % 10 == 0) {
std::cout << "Average end-to-end latency: "
<< total_latency / (count * 1) << " microseconds\n";
}
}
}
void print_help(const char *program_name) {
std::cout << "Usage: " << program_name << "[options]\nOptions:\n";
std::cout << " -domainId <domain ID> Domain ID\n";
std::cout << " -mode <1,2,3,4> Publisher modes\n";
std::cout << " 1. publisher_flat\n";
std::cout << " 2. publisher_zero_copy\n";
std::cout << " 3. publisher_flat_zero_copy\n";
std::cout << " 4. publisher_plain\n";
std::cout << " -sampleCount <sample count> Sample count\n";
std::cout << " Default: -1 (infinite)\n";
std::cout << " -executionTime <sec> Execution time in seconds\n";
std::cout << " Default: 30\n";
std::cout << " -nic <IP address> Use the nic specified by <ipaddr> to send\n";
std::cout << " Default: automatic\n";
std::cout << " -help Displays this information\n";
}
int main(int argc, char *argv[])
{
ApplicationOptions options;
for (int i = 1; i < argc; i++) {
if (strstr(argv[i],"-h") == argv[i]) {
print_help(argv[0]);
return 0;
} else if (strstr(argv[i],"-d") == argv[i]) {
options.domain_id = atoi(argv[++i]);
} else if (strstr(argv[i],"-m") == argv[i]) {
options.mode = atoi(argv[++i]);
} else if (strstr(argv[i],"-s") == argv[i]) {
options.sample_count = atoi(argv[++i]);
} else if (strstr(argv[i],"-e") == argv[i]) {
options.execution_time = atoi(argv[++i])*1000000;
} else if (strstr(argv[i],"-n") == argv[i]) {
options.nic = (argv[++i]);
} else {
std::cout << "unexpected option: " << argv[i] << 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::WARNING);
try {
switch (options.mode) {
case 1:
publisher_flat(options);
break;
case 2:
publisher_zero_copy(options);
break;
case 3:
publisher_flat_zero_copy(options);
break;
case 4:
publisher_plain(options);
break;
case 5:
publisher_copy_sample(0, 0);
break;
}
} catch (const std::exception& ex) {
// This will catch DDS exceptions
std::cerr << "Exception in publisher: " << 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/flat_data_latency/c++11/Common.hpp | /*
* (c) 2018 Copyright, Real-Time Innovations, Inc. All rights reserved.
* Subject to Eclipse Public License v1.0; see LICENSE.md for details.
*/
/* Common.hpp
Utilities used by CameraImage_publisher.cxx and CameraImage_subscriber.cxx.
*/
#include <dds/core/cond/GuardCondition.hpp>
#include <dds/pub/DataWriter.hpp>
#include <dds/pub/DataWriterListener.hpp>
/*
Wait for discovery
*/
template <typename T>
void wait_for_reader(dds::pub::DataWriter<T>& writer, bool match = true)
{
while((match && dds::pub::matched_subscriptions(writer).empty())
|| (!match && !dds::pub::matched_subscriptions(writer).empty())) {
rti::util::sleep(dds::core::Duration::from_millisecs(100));
}
}
template <typename T>
void wait_for_writer(dds::sub::DataReader<T>& reader)
{
while(dds::sub::matched_publications(reader).empty()) {
rti::util::sleep(dds::core::Duration::from_millisecs(100));
}
}
/*
DataWriterListener that implements on_sample_removed
This callback allows the application writting flat-data samples to know when it
is safe to reuse a sample that was previously written. The listener triggers
a GuardCondition that can be attached to a Waitset.
*/
template <typename TopicType>
class FlatDataSampleRemovedListener :
public dds::pub::NoOpDataWriterListener<TopicType> {
public:
void on_sample_removed(
dds::pub::DataWriter<TopicType>& writer,
const rti::core::Cookie& cookie) override
{
guard_condition.trigger_value(true);
}
/*
* Gets the condition that can be attached to a waitset
*/
dds::core::cond::GuardCondition get_condition()
{
return guard_condition;
}
/*
* Sets the condition back to false
*
* This should be called after the condition triggers a Waitset.
*/
void reset_condition()
{
guard_condition.trigger_value(false);
}
private:
dds::core::cond::GuardCondition guard_condition;
};
// CameraImageType can be flat_types::CameraImage or flat_zero_copy_types::CameraImage
template <typename CameraImageType>
void populate_flat_sample(CameraImageType& sample, int count)
{
auto image = sample.root();
image.format(common::Format::RGB);
image.resolution().height(4320);
image.resolution().width(7680);
auto image_data = image.data();
for (int i = 0; i < 4; i++) {
uint8_t image_value = (48 + count) % 124;
image_data.set_element(i, image_value);
}
}
// CameraImageType can be zero_copy_types::CameraImage or plain_types::CameraImage
template <typename CameraImageType>
void populate_plain_sample(CameraImageType& sample, int count)
{
sample.format(common::Format::RGB);
sample.resolution().height(4320);
sample.resolution().width(7680);
for (int i = 0; i < 4; i++) {
uint8_t image_value = (48 + count) % 124;
sample.data()[i] = image_value;
}
}
template <typename CameraImageType>
void display_flat_sample(const CameraImageType &sample)
{
auto image = sample.root();
std::cout << "\nTimestamp " << image.timestamp() << " "
<< image.format();
std::cout << " Data (4 Bytes) ";
const uint8_t *image_data = image.data().get_elements();
for (int i = 0; i < 4; i++) {
std::cout << image_data[i];
}
std::cout << std::endl;
}
template <typename CameraImageType>
void display_plain_sample(const CameraImageType &sample)
{
std::cout << "\nTimestamp " << sample.timestamp() << " "
<< sample.format();
std::cout << " Data (4 Bytes) ";
for (int i = 0; i < 4; i++) {
std::cout << sample.data()[i];
}
std::cout << std::endl;
}
struct ApplicationOptions {
ApplicationOptions() :
domain_id(0),
mode(0),
sample_count(-1), // infinite
execution_time(30000000),
display_sample(false)
{
}
int domain_id;
int mode;
int sample_count;
uint64_t execution_time;
bool display_sample;
std::string nic; // default: empty (no nic will be explicitly picked)
};
inline void configure_nic(
dds::domain::qos::DomainParticipantQos& qos,
const std::string& nic)
{
using rti::core::policy::Property;
if (!nic.empty()) {
qos.policy<Property>().set({
"dds.transport.UDPv4.builtin.parent.allow_interfaces",
nic});
}
}
| hpp |
rticonnextdds-examples | data/projects/rticonnextdds-examples/flat_data_latency/c++11/CameraImage_subscriber.cxx | /*
* (c) 2018 Copyright, Real-Time Innovations, Inc. All rights reserved.
* Subject to Eclipse Public License v1.0; see LICENSE.md for details.
*/
#include <algorithm>
#include <iostream>
#include <memory> // for unique_ptr
#include <signal.h>
#include "CameraImage.hpp"
#include <dds/sub/ddssub.hpp>
#include <dds/pub/ddspub.hpp>
#include <dds/core/ddscore.hpp>
#include <rti/config/Logger.hpp>
#include <rti/zcopy/sub/ZcopyDataReader.hpp>
#include <rti/zcopy/pub/ZcopyDataWriter.hpp>
#include "Common.hpp"
void subscriber_flat(const ApplicationOptions &options)
{
using namespace flat_types;
using namespace dds::core::policy;
std::cout << "Running subscriber_flat\n";
auto participant_qos = dds::core::QosProvider::Default().participant_qos();
configure_nic(participant_qos, options.nic);
dds::domain::DomainParticipant participant(
options.domain_id,
participant_qos);
// Create the ping DataReader
dds::topic::Topic<CameraImage> ping_topic(participant, "CameraImagePing");
dds::sub::DataReader<CameraImage> reader(
dds::sub::Subscriber(participant),
ping_topic);
// Create the pong DataWriter
dds::topic::Topic<CameraImage> pong_topic(participant, "CameraImagePong");
dds::pub::DataWriter<CameraImage> writer(
dds::pub::Publisher(participant),
pong_topic);
// Create a ReadCondition for any data on the ping reader, and attach it to
// a Waitset
dds::sub::cond::ReadCondition read_condition(
reader,
dds::sub::status::DataState::any());
dds::core::cond::WaitSet waitset;
waitset += read_condition;
std::cout<< "Waiting for the publisher application\n";
wait_for_reader(writer);
wait_for_writer(reader);
std::cout << "Discovery complete\n";
while (1) {
// Wait for a ping
auto conditions = waitset.wait(dds::core::Duration(10));
if (conditions.empty()) {
std::cout << "Wait for ping: timeout\n";
continue;
}
auto ping_samples = reader.take();
if ((ping_samples.length() > 0) && (ping_samples[0].info().valid())) {
auto ping = ping_samples[0].data().root();
if (ping.timestamp() == 0) {
//last sample received, break out of receive loop
break;
}
if (options.display_sample){
display_flat_sample(ping_samples[0].data());
}
auto pong_sample = writer.extensions().get_loan();
auto pong = pong_sample->root();
pong.timestamp(ping.timestamp());
writer.write(*pong_sample);
}
}
std::cout << "Subscriber shutting down\n";
}
void subscriber_zero_copy(const ApplicationOptions &options)
{
using namespace zero_copy_types;
using namespace rti::core::policy;
std::cout << "Running subscriber_zero_copy\n";
dds::domain::DomainParticipant participant(options.domain_id);
// Create the ping DataReader
dds::topic::Topic<CameraImage> ping_topic(participant, "CameraImagePing");
dds::sub::DataReader<CameraImage> reader(
dds::sub::Subscriber(participant),
ping_topic);
// Create the pong DataWriter
dds::topic::Topic<CameraImage> pong_topic(participant, "CameraImagePong");
dds::pub::DataWriter<CameraImage> writer(
dds::pub::Publisher(participant),
pong_topic);
// Create a ReadCondition for any data on the ping reader, and attach it to
// a Waitset
dds::sub::cond::ReadCondition read_condition(
reader,
dds::sub::status::DataState::any());
dds::core::cond::WaitSet waitset;
waitset += read_condition;
std::cout<< "Waiting for the publisher application\n";
wait_for_reader(writer);
wait_for_writer(reader);
std::cout << "Discovery complete\n";
while (1) {
// Wait for a ping
auto conditions = waitset.wait(dds::core::Duration(10));
if (conditions.empty()) {
std::cout << "Wait for ping: timeout\n";
}
auto ping_samples = reader.take();
if (ping_samples.length() > 0 && ping_samples[0].info().valid()) {
if (ping_samples[0].data().timestamp() == 0) {
// last sample received, break out of receive loop
break;
}
if (options.display_sample){
display_plain_sample(ping_samples[0].data());
}
// Write the pong sample:
CameraImage *pong_sample = writer.extensions().get_loan();
pong_sample->timestamp(ping_samples[0].data().timestamp());
if (reader->is_data_consistent(ping_samples[0])) {
writer.write(*pong_sample);
}
}
}
std::cout << "Subscriber shutting down\n";
}
void subscriber_flat_zero_copy(const ApplicationOptions &options)
{
using namespace flat_zero_copy_types;
using namespace rti::core::policy;
std::cout << "Running subscriber_flat_zero_copy\n";
auto participant_qos = dds::core::QosProvider::Default().participant_qos();
configure_nic(participant_qos, options.nic);
dds::domain::DomainParticipant participant(
options.domain_id,
participant_qos);
// Create the ping DataReader
dds::topic::Topic<CameraImage> ping_topic(participant, "CameraImagePing");
dds::sub::DataReader<CameraImage> reader(
dds::sub::Subscriber(participant),
ping_topic);
// Create the pong DataWriter
dds::topic::Topic<CameraImage> pong_topic(participant, "CameraImagePong");
dds::pub::DataWriter<CameraImage> writer(
dds::pub::Publisher(participant),
pong_topic);
// Create a ReadCondition for any data on the ping reader, and attach it to
// a Waitset
dds::sub::cond::ReadCondition read_condition(
reader,
dds::sub::status::DataState::any());
dds::core::cond::WaitSet waitset;
waitset += read_condition;
std::cout<< "Waiting for the publisher application\n";
wait_for_reader(writer);
wait_for_writer(reader);
std::cout << "Discovery complete\n";
while (1) {
// Wait for a ping
auto conditions = waitset.wait(dds::core::Duration(10));
if (conditions.empty()) {
std::cout << "Wait for ping: timeout\n";
continue;
}
auto ping_samples = reader.take();
if (ping_samples.length() > 0 && ping_samples[0].info().valid()) {
if (ping_samples[0].info().valid()) {
auto ping = ping_samples[0].data().root();
if (ping.timestamp() == 0) {
//last sample received, break out of receive loop
break;
}
if (options.display_sample){
display_flat_sample(ping_samples[0].data());
}
// Write the pong sample:
CameraImage *pong_sample = writer.extensions().get_loan();
auto pong = pong_sample->root();
pong.timestamp(ping.timestamp());
if (reader->is_data_consistent(ping_samples[0])) {
writer.write(*pong_sample);
}
}
}
}
std::cout << "Subscriber shutting down\n";
}
void subscriber_plain(const ApplicationOptions &options)
{
using namespace plain_types;
using namespace dds::core::policy;
std::cout << "Running subscriber_plain\n";
auto participant_qos = dds::core::QosProvider::Default().participant_qos();
configure_nic(participant_qos, options.nic);
dds::domain::DomainParticipant participant(
options.domain_id,
participant_qos);
// Create the ping DataReader
dds::topic::Topic<CameraImage> ping_topic(participant, "CameraImagePing");
dds::sub::DataReader<CameraImage> reader(
dds::sub::Subscriber(participant),
ping_topic);
// Create the pong DataWriter
dds::topic::Topic<CameraImage> pong_topic(participant, "CameraImagePong");
dds::pub::DataWriter<CameraImage> writer(
dds::pub::Publisher(participant),
pong_topic);
// Create a ReadCondition for any data on the ping reader, and attach it to
// a Waitset
dds::sub::cond::ReadCondition read_condition(
reader,
dds::sub::status::DataState::any());
dds::core::cond::WaitSet waitset;
waitset += read_condition;
// We create the sample in the heap because is to large to be in the stack
std::unique_ptr<CameraImage> pong_sample(new CameraImage);
std::cout<< "Waiting for the publisher application\n";
wait_for_reader(writer);
wait_for_writer(reader);
std::cout << "Discovery complete\n";
int count = 0;
while (1) {
// Wait for a ping
auto conditions = waitset.wait(dds::core::Duration(10));
if (conditions.empty()) {
std::cout << "Wait for ping: timeout\n";
}
auto ping_samples = reader.take();
// Write the pong sample
if (ping_samples.length() && ping_samples[0].info().valid()) {
if (ping_samples[0].data().timestamp() == 0) {
//last sample received, break out of receive loop
break;
}
if (options.display_sample){
display_plain_sample(ping_samples[0].data());
}
pong_sample->timestamp(ping_samples[0].data().timestamp());
writer.write(*pong_sample);
count++;
}
}
std::cout << "Subscriber shutting down\n";
}
void print_help(const char *program_name) {
std::cout << "Usage: " << program_name << "[options]\nOptions:\n";
std::cout << " -domainId <domain ID> Domain ID\n";
std::cout << " -mode <1,2,3,4> Subscriber modes\n";
std::cout << " 1. subscriber_flat\n";
std::cout << " 2. subscriber_zero_copy\n";
std::cout << " 3. subscriber_flat_zero_copy\n";
std::cout << " 4. subscriber_plain\n";
std::cout << " -displaySample Displays the sample\n";
std::cout << " -nic <IP address> Use the nic specified by <ipaddr> to send\n";
std::cout << " Default: 127.0.0.1\n";
std::cout << " -help Displays this information\n";
}
int main(int argc, char *argv[])
{
ApplicationOptions options;
for (int i = 1; i < argc; i++) {
if (strstr(argv[i],"-h") == argv[i]) {
print_help(argv[0]);
return 0;
} else if (strstr(argv[i],"-di") == argv[i]) {
options.display_sample = true;
} else if (strstr(argv[i],"-d") == argv[i]) {
options.domain_id = atoi(argv[++i]);
} else if (strstr(argv[i],"-m") == argv[i]) {
options.mode = atoi(argv[++i]);
} else if (strstr(argv[i],"-n") == argv[i]) {
options.nic = (argv[++i]);
} else {
std::cout << "unexpected option: " << argv[i] << 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::WARNING);
try {
switch(options.mode) {
case 1:
subscriber_flat(options);
break;
case 2:
subscriber_zero_copy(options);
break;
case 3:
subscriber_flat_zero_copy(options);
break;
case 4:
subscriber_plain(options);
break;
}
} catch (const std::exception& ex) {
// This will catch DDS exceptions
std::cerr << "Exception in subscriber: " << 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/dynamic_data_nested_structs/c++/dynamic_data_nested_struct_example.cxx | /*******************************************************************************
(c) 2005-2014 Copyright, Real-Time Innovations, Inc. All rights reserved.
RTI grants Licensee a license to use, modify, compile, and create derivative
works of the Software. Licensee has the right to distribute object form only
for use with RTI products. The Software is provided "as is", with no warranty
of any type, including any warranty for fitness for any purpose. RTI is under
no obligation to maintain or support the Software. RTI shall not be liable for
any incidental or consequential damages arising out of the use or inability to
use the software.
******************************************************************************/
/* dynamic_data_nested_struct_example.cxx
This example
- creates the type code of for a nested struct
(with inner and outer structs)
- creates a DynamicData instance
- sets the values of the inner struct
- shows the differences between set_complex_member and bind_complex_member
Example:
To run the example application:
On Unix:
objs/<arch>/NestedStructExample
On Windows:
objs\<arch>\NestedStructExample
*/
/********* IDL representation for this example ************
struct InnerStruct {
double x;
double y;
};
struct OuterStruct {
InnerStruct inner;
};
*/
#include <iostream>
#include <ndds_cpp.h>
using namespace std;
DDS_TypeCode *
inner_struct_get_typecode(DDS_TypeCodeFactory *tcf) {
static DDS_TypeCode *tc = NULL;
DDS_StructMemberSeq members;
DDS_ExceptionCode_t err;
/* First, we create the typeCode for a struct */
tc = tcf->create_struct_tc("InnerStruct", members, err);
if (err != DDS_NO_EXCEPTION_CODE) {
cerr << "! Unable to create struct TC" << endl;
goto fail;
}
/* Member 1 will be a double named x */
tc->add_member("x", DDS_TYPECODE_MEMBER_ID_INVALID,
DDS_TypeCodeFactory_get_primitive_tc(tcf, DDS_TK_DOUBLE),
DDS_TYPECODE_NONKEY_REQUIRED_MEMBER, err);
if (err != DDS_NO_EXCEPTION_CODE) {
cerr << "! Unable to add member x" << endl;
goto fail;
}
/* Member 2 will be a double named y */
tc->add_member("y", DDS_TYPECODE_MEMBER_ID_INVALID,
DDS_TypeCodeFactory_get_primitive_tc(tcf, DDS_TK_DOUBLE),
DDS_TYPECODE_NONKEY_REQUIRED_MEMBER, err);
if (err != DDS_NO_EXCEPTION_CODE) {
cerr << "! Unable to add member y" << endl;
goto fail;
}
DDS_StructMemberSeq_finalize(&members);
return tc;
fail: if (tc != NULL) {
tcf->delete_tc(tc, err);
}
DDS_StructMemberSeq_finalize(&members);
return NULL;
}
DDS_TypeCode *
outer_struct_get_typecode(DDS_TypeCodeFactory * tcf) {
static DDS_TypeCode *tc = NULL;
DDS_TypeCode *innerTC = NULL;
struct DDS_StructMemberSeq members;
DDS_ExceptionCode_t err;
/* First, we create the typeCode for a struct */
tc = tcf->create_struct_tc("OuterStruct", members, err);
if (err != DDS_NO_EXCEPTION_CODE) {
cerr << "! Unable to create struct TC" << endl;
goto fail;
}
innerTC = inner_struct_get_typecode(tcf);
if (innerTC == NULL) {
cerr << "! Unable to create innerTC" << endl;
goto fail;
}
/* Member 1 of outer struct will be a struct of type inner_struct
* called inner*/
tc->add_member("inner", DDS_TYPECODE_MEMBER_ID_INVALID, innerTC,
DDS_TYPECODE_NONKEY_REQUIRED_MEMBER, err);
if (err != DDS_NO_EXCEPTION_CODE) {
cerr << "! Unable to add member inner struct" << endl;
goto fail;
}
if (innerTC != NULL) {
tcf->delete_tc(innerTC, err);
}
DDS_StructMemberSeq_finalize(&members);
return tc;
fail: if (tc != NULL) {
tcf->delete_tc(tc, err);
}
DDS_StructMemberSeq_finalize(&members);
if (innerTC != NULL) {
tcf->delete_tc(innerTC, err);
}
return NULL;
}
int main() {
DDS_TypeCodeFactory *tcf = NULL;
DDS_ExceptionCode_t err;
/* Getting a reference to the type code factory */
tcf = DDS_TypeCodeFactory::get_instance();
if (tcf == NULL) {
cerr << "! Unable to get type code factory singleton" << endl;
return -1;
}
/* Creating the typeCode of the inner_struct */
struct DDS_TypeCode *inner_tc = inner_struct_get_typecode(tcf);
if (inner_tc == NULL) {
cerr << "! Unable to create inner typecode " << endl;
return -1;
}
/* Creating the typeCode of the outer_struct that contains an inner_struct */
struct DDS_TypeCode *outer_tc = outer_struct_get_typecode(tcf);
if (inner_tc == NULL) {
cerr << "! Unable to create outer typecode " << endl;
tcf->delete_tc(outer_tc, err);
return -1;
}
DDS_ReturnCode_t retcode;
int ret = -1;
/* Now, we create a dynamicData instance for each type */
DDS_DynamicData outer_data(outer_tc, DDS_DYNAMIC_DATA_PROPERTY_DEFAULT);
DDS_DynamicData inner_data(inner_tc, DDS_DYNAMIC_DATA_PROPERTY_DEFAULT);
DDS_DynamicData bounded_data(NULL, DDS_DYNAMIC_DATA_PROPERTY_DEFAULT);
cout << " Connext Dynamic Data Nested Struct Example" << endl
<< "--------------------------------------------" << endl;
cout << " Data Types" << endl << "------------------" << endl;
inner_tc->print_IDL(0, err);
outer_tc->print_IDL(0, err);
/* Setting the inner data */
retcode = inner_data.set_double("x", DDS_DYNAMIC_DATA_MEMBER_ID_UNSPECIFIED,
3.14159);
if (retcode != DDS_RETCODE_OK) {
cerr << "! Unable to set value 'x' in the inner struct" << endl;
goto fail;
}
retcode = inner_data.set_double("y", DDS_DYNAMIC_DATA_MEMBER_ID_UNSPECIFIED,
2.71828);
if (retcode != DDS_RETCODE_OK) {
cerr << "! Unable to set value 'y' in the inner struct" << endl;
goto fail;
}
cout << endl << endl << " get/set_complex_member API" << endl
<< "------------------" << endl;
/* Using set_complex_member, we copy inner_data values in inner_struct of
* outer_data */
cout << "Setting the initial values of struct with set_complex_member()"
<< endl;
retcode = outer_data.set_complex_member("inner",
DDS_DYNAMIC_DATA_MEMBER_ID_UNSPECIFIED, inner_data);
if (retcode != DDS_RETCODE_OK) {
cerr << "! Unable to set complex struct value "
<< "(member inner in the outer struct)" << endl;
goto fail;
}
outer_data.print(stdout, 1);
retcode = inner_data.clear_all_members();
if (retcode != DDS_RETCODE_OK) {
cerr << "! Unable to clear all member in the inner struct" << endl;
goto fail;
}
cout << endl << " + get_complex_member() called" << endl;
retcode = outer_data.get_complex_member(inner_data, "inner",
DDS_DYNAMIC_DATA_MEMBER_ID_UNSPECIFIED);
if (retcode != DDS_RETCODE_OK) {
cerr << "! Unable to get complex struct value"
<< "(member inner in the outer struct)" << endl;
goto fail;
}
cout << endl << " + inner_data value" << endl;
inner_data.print(stdout, 1);
/* get_complex_member made a copy of the inner_struct. If we modify
* inner_data values, outer_data inner_struct WILL NOT be modified. */
cout << endl << " + setting new values to inner_data" << endl;
retcode = inner_data.set_double("x", DDS_DYNAMIC_DATA_MEMBER_ID_UNSPECIFIED,
1.00000);
if (retcode != DDS_RETCODE_OK) {
cerr << "! Unable to set value 'x' in the inner struct" << endl;
goto fail;
}
retcode = inner_data.set_double("y", DDS_DYNAMIC_DATA_MEMBER_ID_UNSPECIFIED,
0.00001);
if (retcode != DDS_RETCODE_OK) {
cerr << "! Unable to set value 'y' in the inner struct" << endl;
goto fail;
}
/* Current value of outer_data
* outer:
* inner:
* x: 3.141590
* y: 2.718280
* inner_data:
* x: 1.000000
* y: 0.000010
*/
cout << endl << " + current outer_data value " << endl;
outer_data.print(stdout, 1);
/* Bind/Unbind member API */
cout << endl << endl << "bind/unbind API" << endl << "------------------"
<< endl;
/* Using bind_complex_member, we do not copy inner_struct, but bind it.
* So, if we modify bounded_data, the inner member inside outer_data WILL
* also be modified */
cout << endl << " + bind complex member called" << endl;
retcode = outer_data.bind_complex_member(bounded_data, "inner",
DDS_DYNAMIC_DATA_MEMBER_ID_UNSPECIFIED);
if (retcode != DDS_RETCODE_OK) {
cerr << "! Unable to bind the structs" << endl;
goto fail;
}
bounded_data.print(stdout, 1);
cout << endl << " + setting new values to bounded_data" << endl;
retcode = bounded_data.set_double("x",
DDS_DYNAMIC_DATA_MEMBER_ID_UNSPECIFIED, 1.00000);
if (retcode != DDS_RETCODE_OK) {
cerr << "! Unable to set value to 'x' with the bounded data" << endl;
goto fail;
}
retcode = bounded_data.set_double("y",
DDS_DYNAMIC_DATA_MEMBER_ID_UNSPECIFIED, 0.00001);
if (retcode != DDS_RETCODE_OK) {
cerr << "! Unable to set value to 'y' in the bounded data" << endl;
goto fail;
}
/* Current value of outer data
* outer:
* inner:
* x: 1.000000
* y: 0.000010
*/
bounded_data.print(stdout, 1);
retcode = outer_data.unbind_complex_member(bounded_data);
if (retcode != DDS_RETCODE_OK) {
cerr << "! Unable to unbind the data" << endl;
goto fail;
}
cout << endl << " + current outer_data value " << endl;
outer_data.print(stdout, 1);
ret = 1;
fail: if (inner_tc != NULL) {
tcf->delete_tc(inner_tc, err);
}
if (outer_tc != NULL) {
tcf->delete_tc(outer_tc, err);
}
return ret;
}
| cxx |
rticonnextdds-examples | data/projects/rticonnextdds-examples/dynamic_data_nested_structs/c/dynamic_data_nested_struct_example.c | /*******************************************************************************
(c) 2005-2014 Copyright, Real-Time Innovations, Inc. All rights reserved.
RTI grants Licensee a license to use, modify, compile, and create derivative
works of the Software. Licensee has the right to distribute object form only
for use with RTI products. The Software is provided "as is", with no warranty
of any type, including any warranty for fitness for any purpose. RTI is under
no obligation to maintain or support the Software. RTI shall not be liable for
any incidental or consequential damages arising out of the use or inability to
use the software.
******************************************************************************/
/* dynamic_data_nested_struct_example.c
This example
- creates the type code of for a nested struct
(with inner and outer structs)
- creates a DynamicData instance
- sets the values of the inner struct
- shows the differences between set_complex_member and bind_complex_member
Example:
To run the example application:
On Unix:
objs/<arch>/UnionExample
On Windows:
objs\<arch>\UnionExample
*/
/********* IDL representation for this example ************
struct InnerStruct {
double x;
double y;
};
struct OuterStruct {
InnerStruct inner;
};
*/
#include <ndds_c.h>
DDS_TypeCode *
inner_struct_get_typecode(struct DDS_TypeCodeFactory *tcf) {
static DDS_TypeCode *tc = NULL;
struct DDS_StructMemberSeq members = DDS_SEQUENCE_INITIALIZER;
DDS_ExceptionCode_t ex;
/* First, we create the typeCode for a struct */
tc = DDS_TypeCodeFactory_create_struct_tc(tcf, "InnerStruct", &members,
&ex);
if (ex != DDS_NO_EXCEPTION_CODE) {
fprintf(stderr, "! Unable to create struct TC\n");
goto fail;
}
/* Member 1 will be a double named x */
DDS_TypeCode_add_member(tc, "x", DDS_TYPECODE_MEMBER_ID_INVALID,
DDS_TypeCodeFactory_get_primitive_tc(tcf, DDS_TK_DOUBLE),
DDS_TYPECODE_NONKEY_REQUIRED_MEMBER, &ex);
if (ex != DDS_NO_EXCEPTION_CODE) {
fprintf(stderr, "! Unable to add member x\n");
goto fail;
}
/* Member 2 will be a double named y */
DDS_TypeCode_add_member(tc, "y", DDS_TYPECODE_MEMBER_ID_INVALID,
DDS_TypeCodeFactory_get_primitive_tc(tcf, DDS_TK_DOUBLE),
DDS_TYPECODE_NONKEY_REQUIRED_MEMBER, &ex);
if (ex != DDS_NO_EXCEPTION_CODE) {
fprintf(stderr, "! Unable to add member y\n");
goto fail;
}
DDS_StructMemberSeq_finalize(&members);
return tc;
fail:
if (tc != NULL) {
DDS_TypeCodeFactory_delete_tc(tcf, tc, &ex);
}
DDS_StructMemberSeq_finalize(&members);
return NULL;
}
DDS_TypeCode * outer_struct_get_typecode(struct DDS_TypeCodeFactory *tcf) {
static DDS_TypeCode *tc = NULL;
DDS_TypeCode *innerTC = NULL;
struct DDS_StructMemberSeq members = DDS_SEQUENCE_INITIALIZER;
DDS_ExceptionCode_t ex;
/* First, we create the typeCode for a struct */
tc = DDS_TypeCodeFactory_create_struct_tc(tcf, "OuterStruct", &members,
&ex);
if (ex != DDS_NO_EXCEPTION_CODE) {
fprintf(stderr, "! Unable to create struct TC\n");
goto fail;
}
innerTC = inner_struct_get_typecode(tcf);
if (innerTC == NULL) {
fprintf(stderr, "! Unable to create struct TC\n");
goto fail;
}
/* Member 1 of outer struct will be a struct of type inner_struct
* called inner*/
DDS_TypeCode_add_member(tc, "inner", DDS_TYPECODE_MEMBER_ID_INVALID,
innerTC, DDS_TYPECODE_NONKEY_REQUIRED_MEMBER, &ex);
if (ex != DDS_NO_EXCEPTION_CODE) {
fprintf(stderr, "! Unable to add member x\n");
goto fail;
}
if (innerTC != NULL) {
DDS_TypeCodeFactory_delete_tc(tcf, innerTC, NULL);
}
DDS_StructMemberSeq_finalize(&members);
return tc;
fail:
if (tc != NULL) {
DDS_TypeCodeFactory_delete_tc(tcf, tc, &ex);
}
if (innerTC != NULL) {
DDS_TypeCodeFactory_delete_tc(tcf, innerTC, NULL);
}
DDS_StructMemberSeq_finalize(&members);
return NULL;
}
int main() {
struct DDS_TypeCode *inner_tc = NULL;
struct DDS_TypeCode *outer_tc = NULL;
struct DDS_TypeCodeFactory *factory = NULL;
DDS_ExceptionCode_t err;
DDS_ReturnCode_t retcode;
int ret = -1;
DDS_DynamicData *outer_data = NULL;
DDS_DynamicData *inner_data = NULL;
DDS_DynamicData *bounded_data = NULL;
/* Getting a reference to the type code factory */
factory = DDS_TypeCodeFactory_get_instance();
if (factory == NULL) {
fprintf(stderr, "! Unable to get type code factory singleton\n");
goto fail;
}
/* Creating the typeCode of the inner_struct */
inner_tc = inner_struct_get_typecode(factory);
if (inner_tc == NULL) {
fprintf(stderr, "! Unable to create typeCode\n");
goto fail;
}
/* Creating the typeCode of the outer_struct that contains an inner_struct */
outer_tc = outer_struct_get_typecode(factory);
if (inner_tc == NULL) {
fprintf(stderr, "! Unable to create typeCode\n");
goto fail;
}
printf(" Connext Dynamic Data Nested Struct Example \n"
"--------------------------------------------\n");
printf(" Data Types\n"
"------------------\n");
DDS_TypeCode_print_IDL(inner_tc, 0, &err);
DDS_TypeCode_print_IDL(outer_tc, 0, &err);
/* Now, we create a dynamicData instance for each type */
outer_data = DDS_DynamicData_new(outer_tc,
&DDS_DYNAMIC_DATA_PROPERTY_DEFAULT);
if (outer_data == NULL) {
fprintf(stderr, "! Unable to create outer dynamicData\n");
goto fail;
}
inner_data = DDS_DynamicData_new(inner_tc,
&DDS_DYNAMIC_DATA_PROPERTY_DEFAULT);
if (outer_data == NULL) {
fprintf(stderr, "! Unable to create inner dynamicData\n");
goto fail;
}
/* Setting the inner data */
retcode = DDS_DynamicData_set_double(inner_data, "x",
DDS_DYNAMIC_DATA_MEMBER_ID_UNSPECIFIED, 3.14159);
if (retcode != DDS_RETCODE_OK) {
fprintf(stderr, "! Unable to set value 'x' in the inner struct \n");
goto fail;
}
retcode = DDS_DynamicData_set_double(inner_data, "y",
DDS_DYNAMIC_DATA_MEMBER_ID_UNSPECIFIED, 2.71828);
if (retcode != DDS_RETCODE_OK) {
fprintf(stderr, "! Unable to set value 'y' in the inner struct\n");
goto fail;
}
printf("\n\n get/set_complex_member API\n"
"----------------------------\n");
/* Using set_complex_member, we copy inner_data values in inner_struct of
* outer_data */
printf("Setting initial values of outer_data with "
"set_complex_member()\n");
retcode = DDS_DynamicData_set_complex_member(outer_data, "inner",
DDS_DYNAMIC_DATA_MEMBER_ID_UNSPECIFIED, inner_data);
if (retcode != DDS_RETCODE_OK) {
fprintf(stderr, "! Unable to set complex struct value "
"(member inner in the outer struct)\n");
goto fail;
}
DDS_DynamicData_print(outer_data, stdout, 1);
retcode = DDS_DynamicData_clear_all_members(inner_data);
if (retcode != DDS_RETCODE_OK) {
fprintf(stderr, "! Unable to clear all member in the inner data\n");
goto fail;
}
printf("\n + get_complex_member() called\n");
retcode = DDS_DynamicData_get_complex_member(outer_data, inner_data,
"inner", DDS_DYNAMIC_DATA_MEMBER_ID_UNSPECIFIED);
if (retcode != DDS_RETCODE_OK) {
fprintf(stderr, "! Unable to get complex struct value "
"(member inner in the outer struct)\n");
goto fail;
}
printf("\n + inner_data value\n");
DDS_DynamicData_print(inner_data, stdout, 1);
/* get_complex_member made a copy of the inner_struct. If we modify
* inner_data values, outer_data inner_struct WILL NOT be modified. */
printf("\n + setting new values to inner_data\n");
retcode = DDS_DynamicData_set_double(inner_data, "x",
DDS_DYNAMIC_DATA_MEMBER_ID_UNSPECIFIED, 1.00000);
if (retcode != DDS_RETCODE_OK) {
fprintf(stderr, "! Unable to set value 'x' in the inner struct \n");
goto fail;
}
retcode = DDS_DynamicData_set_double(inner_data, "y",
DDS_DYNAMIC_DATA_MEMBER_ID_UNSPECIFIED, 0.00001);
if (retcode != DDS_RETCODE_OK) {
fprintf(stderr, "! Unable to set value 'y' in the inner struct \n");
goto fail;
}
DDS_DynamicData_print(inner_data, stdout, 1);
/* Current value of outer_data
* outer_data:
* inner:
* x: 3.141590
* y: 2.718280
*
* inner_data:
* x: 1.000000
* y: 0.000010
*/
printf("\n + current outer_data value \n");
DDS_DynamicData_print(outer_data, stdout, 1);
/* Bind/Unbind member API */
printf("\n\n bind/unbind API\n"
"------------------\n");
printf("Creating a new dynamic data called bounded_data\n");
bounded_data = DDS_DynamicData_new(NULL,
&DDS_DYNAMIC_DATA_PROPERTY_DEFAULT);
if (bounded_data == NULL) {
fprintf(stderr, "! Unable to create new dynamic data\n");
goto fail;
}
printf("\n + binding bounded_data to outer_data's inner_struct\n");
/* Using bind_complex_member, we do not copy inner_struct, but bind it.
* So, if we modify bounded_data, the inner member inside outer_data WILL
* also be modified */
retcode = DDS_DynamicData_bind_complex_member(outer_data, bounded_data,
"inner", DDS_DYNAMIC_DATA_MEMBER_ID_UNSPECIFIED);
if (retcode != DDS_RETCODE_OK) {
fprintf(stderr, "! Unable to bind the structs\n");
goto fail;
}
DDS_DynamicData_print(bounded_data, stdout, 1);
printf("\n + setting new values to bounded_data\n");
retcode = DDS_DynamicData_set_double(bounded_data, "x",
DDS_DYNAMIC_DATA_MEMBER_ID_UNSPECIFIED, 1.00000);
if (retcode != DDS_RETCODE_OK) {
fprintf(stderr, "! Unable to set value to 'x' with the bounded data\n");
goto fail;
}
retcode = DDS_DynamicData_set_double(bounded_data, "y",
DDS_DYNAMIC_DATA_MEMBER_ID_UNSPECIFIED, 0.00001);
if (retcode != DDS_RETCODE_OK) {
fprintf(stderr, "! Unable to set value to 'x' with the bounded data\n");
goto fail;
}
/* Current value of outer data
* outer:
* inner:
* x: 1.000000
* y: 0.000010
*/
DDS_DynamicData_print(bounded_data, stdout, 1);
retcode = DDS_DynamicData_unbind_complex_member(outer_data, bounded_data);
if (retcode != DDS_RETCODE_OK) {
fprintf(stderr, "! Unable to unbind the data\n");
goto fail;
}
printf("\n + current outer_data value \n");
DDS_DynamicData_print(outer_data, stdout, 1);
ret = 1;
fail:
if (inner_tc != NULL) {
DDS_TypeCodeFactory_delete_tc(factory, inner_tc, NULL);
}
if (outer_tc != NULL) {
DDS_TypeCodeFactory_delete_tc(factory, outer_tc, NULL);
}
if (inner_data != NULL) {
DDS_DynamicData_delete(inner_data);
}
if (outer_data != NULL) {
DDS_DynamicData_delete(outer_data);
}
if (bounded_data != NULL) {
DDS_DynamicData_delete(bounded_data);
}
return ret;
}
| c |
rticonnextdds-examples | data/projects/rticonnextdds-examples/dynamic_data_nested_structs/c++03/dynamic_data_nested_struct_example.cxx | /*******************************************************************************
(c) 2005-2015 Copyright, Real-Time Innovations, Inc. All rights reserved.
RTI grants Licensee a license to use, modify, compile, and create derivative
works of the Software. Licensee has the right to distribute object form only
for use with RTI products. The Software is provided "as is", with no warranty
of any type, including any warranty for fitness for any purpose. RTI is under
no obligation to maintain or support the Software. RTI shall not be liable for
any incidental or consequential damages arising out of the use or inability to
use the software.
******************************************************************************/
#include <iostream>
#include <dds/dds.hpp>
using namespace dds::core::xtypes;
using namespace rti::core::xtypes;
DynamicType create_typecode_inner_struct()
{
// First create the type code for a struct
StructType inner_struct("InnerStruct");
// Member 1 will be a double named x
inner_struct.add_member(Member("x", primitive_type<double>()));
// Member 2 will be a double named y
inner_struct.add_member(Member("y", primitive_type<double>()));
return inner_struct;
}
DynamicType create_typecode_outer_struct()
{
// First create the type code for a struct
StructType outer_struct("OuterStruct");
// Member 1 of outer struct will be a struct of type InnerStruct
outer_struct.add_member(Member("inner", create_typecode_inner_struct()));
return outer_struct;
}
int main()
{
// Create the type code of the InnerStruct and OuterStruct
DynamicType inner_type = create_typecode_inner_struct();
DynamicType outer_type = create_typecode_outer_struct();
// Create a DynamicData instance for each type
DynamicData outer_data(outer_type);
DynamicData inner_data(inner_type);
std::cout << " Connext Dynamic Data Nested Struct Example " << std::endl
<< "--------------------------------------------" << std::endl
<< " Data Type " << std::endl
<< "-----------" << std::endl;
print_idl(inner_type);
print_idl(outer_type);
std::cout << std::endl;
// Setting the inner data
inner_data.value("x", 3.14159);
inner_data.value("y", 2.71828);
// Copy inner_data values in inner_struct of outer_data
std::cout << " Setting the initial values of struct " << std::endl
<< "--------------------------------------" << std::endl;
outer_data.value("inner", inner_data);
std::cout << outer_data;
// Clear inner_data members to copy data from outer_data
inner_data.clear_all_members();
inner_data = outer_data.value<DynamicData>("inner");
std::cout << std::endl
<< " + copied struct from outer_data" << std::endl
<< " + inner_data value" << std::endl;
std::cout << inner_data;
// inner_data is a copy of the values. If we modify it, outer_data inner
// field WILL NOT be modified.
std::cout << std::endl
<< " + setting new values to inner_data" << std::endl;
inner_data.value("x", 1.00000);
inner_data.value("y", 0.00001);
std::cout << inner_data << std::endl
<< " + current outer_data value " << std::endl
<< outer_data << std::endl << std::endl;
// Using loan_value, we do not copy inner, but bind it.
// So, if we modify loaned_inner, the inner member inside outer_data WILL
// also be modified.
std::cout << " loan/unloan API" << std::endl
<< "-----------------" << std::endl
<< " + loan member called" << std::endl;
LoanedDynamicData loaned_inner = outer_data.loan_value("inner");
std::cout << loaned_inner.get() << std::endl
<< " + setting new values to loaned_data" << std::endl;
loaned_inner.get().value("x", 1.00000);
loaned_inner.get().value("y", 0.00001);
std::cout << loaned_inner.get() << std::endl
<< " + current outer_data value" << std::endl;
std::cout << outer_data;
// The destructor will unloan the member
return 0;
}
| cxx |
rticonnextdds-examples | data/projects/rticonnextdds-examples/listeners/c++/listeners_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.
******************************************************************************/
/* listeners_publisher.cxx
A publication of data of type listeners
This file is derived from code automatically generated by the rtiddsgen
command:
rtiddsgen -language C++ -example <arch> listeners.idl
Example publication of type listeners 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>/listeners_subscriber <domain_id> <sample_count>
(3) Start the publication with the command
objs/<arch>/listeners_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>/listeners_publisher <domain_id> o
objs/<arch>/listeners_subscriber <domain_id>
On Windows:
objs\<arch>\listeners_publisher <domain_id>
objs\<arch>\listeners_subscriber <domain_id>
modification history
------------ -------
*/
#include <stdio.h>
#include <stdlib.h>
#ifdef RTI_VX653
#include <vThreadsData.h>
#endif
#include "listeners.h"
#include "listenersSupport.h"
#include "ndds/ndds_cpp.h"
class DataWriterListener : public DDSDataWriterListener {
public:
virtual void on_offered_deadline_missed(
DDSDataWriter* /*writer*/,
const DDS_OfferedDeadlineMissedStatus& /*status*/)
{
printf("DataWriterListener: on_offered_deadline_missed()\n");
}
virtual void on_liveliness_lost(
DDSDataWriter* /*writer*/,
const DDS_LivelinessLostStatus& /*status*/)
{
printf("DataWriterListener: on_liveliness_lost()\n");
}
virtual void on_offered_incompatible_qos(
DDSDataWriter* /*writer*/,
const DDS_OfferedIncompatibleQosStatus& /*status*/)
{
printf("DataWriterListener: on_offered_incompatible_qos()\n");
}
virtual void on_publication_matched(
DDSDataWriter* writer,
const DDS_PublicationMatchedStatus& status)
{
printf("DataWriterListener: on_publication_matched()\n");
if (status.current_count_change < 0) {
printf("lost a subscription\n");
}
else {
printf("found a subscription\n");
}
}
virtual void on_reliable_writer_cache_changed(
DDSDataWriter *writer,
const DDS_ReliableWriterCacheChangedStatus &status)
{
printf("DataWriterListener: on_reliable_writer_cache_changed()\n");
}
virtual void on_reliable_reader_activity_changed(
DDSDataWriter *writer,
const DDS_ReliableReaderActivityChangedStatus &status)
{
printf("DataWriterListener: on_reliable_reader_activity_changed()\n");
}
};
/* 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;
listenersDataWriter * listeners_writer = NULL;
listeners *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};
DDS_Duration_t sleep_period = {2,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;
}
/* Create ande Delete Inconsistent Topic
* ---------------------------------------------------------------
* Here we create an inconsistent topic to trigger the subscriber
* application's callback.
* The inconsistent topic is created with the topic name used in
* the Subscriber application, but with a different data type --
* the msg data type defined in partitions.idl.
* Once it is created, we sleep to ensure the applications discover
* each other and delete the Data Writer and Topic.
*/
/* First we register the msg type -- we name it
* inconsistent_topic_type_name to avoid confusion.
*/
printf("Creating Inconsistent Topic... \n");
const char *inconsistent_type_name;
inconsistent_type_name = msgTypeSupport::get_type_name();
retcode = msgTypeSupport::register_type(participant,
inconsistent_type_name);
if (retcode != DDS_RETCODE_OK) {
printf("register_type error %d\n", retcode);
publisher_shutdown(participant);
return -1;
}
DDSTopic *inconsistent_topic = NULL;
inconsistent_topic = participant->create_topic("Example listeners",
inconsistent_type_name,
DDS_TOPIC_QOS_DEFAULT,
NULL /* listener */,
DDS_STATUS_MASK_NONE);
if (inconsistent_topic == NULL) {
printf("create_topic error\n");
publisher_shutdown(participant);
return -1;
}
/* We have to associate a writer to the topic, as Topic information is not
* actually propagated until the creation of an associated writer.
*/
DDSDataWriter *inconsistent_topic_writer = NULL;
inconsistent_topic_writer = publisher->create_datawriter(inconsistent_topic,
DDS_DATAWRITER_QOS_DEFAULT,
NULL /* listener */,
DDS_STATUS_MASK_NONE);
if (inconsistent_topic == NULL) {
printf("create_datawriter error\n");
publisher_shutdown(participant);
return -1;
}
msgDataWriter *msg_writer = NULL;
msg_writer = msgDataWriter::narrow(inconsistent_topic_writer);
if (msg_writer == NULL) {
printf("DataWriter narrow error\n");
publisher_shutdown(participant);
return -1;
}
/* Sleep to leave time for applications to discover each other */
NDDSUtility::sleep(sleep_period);
retcode = publisher->delete_datawriter(inconsistent_topic_writer);
if (retcode != DDS_RETCODE_OK) {
printf("delete_datawriter error %d\n", retcode);
publisher_shutdown(participant);
return -1;
}
retcode = participant->delete_topic(inconsistent_topic);
if (retcode != DDS_RETCODE_OK) {
printf("delete_topic error %d\n", retcode);
publisher_shutdown(participant);
return -1;
}
printf("... Deleted Inconsistent Topic\n\n");
/* Create Consistent Topic
* -----------------------------------------------------------------
* Once we have created the inconsistent topic with the wrong type,
* we create a topic with the right type name -- listeners -- that we
* will use to publish data.
*/
/* Register type before creating topic */
type_name = listenersTypeSupport::get_type_name();
retcode = listenersTypeSupport::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 listeners",
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;
}
/* We will use the Data Writer Listener defined above to print
* a message when some of events are triggered in the DataWriter.
* To do that, first we have to pass the writer_listener and then
* we have to enable all status in the status mask.
*/
DataWriterListener *writer_listener = new DataWriterListener();
writer = publisher->create_datawriter(topic,
DDS_DATAWRITER_QOS_DEFAULT,
writer_listener /* listener */,
DDS_STATUS_MASK_ALL /* enable all statuses */);
if (writer == NULL) {
printf("create_datawriter error\n");
publisher_shutdown(participant);
delete writer_listener;
return -1;
}
listeners_writer = listenersDataWriter::narrow(writer);
if (listeners_writer == NULL) {
printf("DataWriter narrow error\n");
publisher_shutdown(participant);
delete writer_listener;
return -1;
}
/* Create data sample for writing */
instance = listenersTypeSupport::create_data();
if (instance == NULL) {
printf("listenersTypeSupport::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 = listeners_writer->register_instance(*instance);
*/
/* Main loop */
for (count=0; (sample_count == 0) || (count < sample_count); ++count) {
printf("Writing listeners, count %d\n", count);
/* Modify the data to be sent here */
instance->x = count;
retcode = listeners_writer->write(*instance, instance_handle);
if (retcode != DDS_RETCODE_OK) {
printf("write error %d\n", retcode);
}
NDDSUtility::sleep(send_period);
}
/*
retcode = listeners_writer->unregister_instance(
*instance, instance_handle);
if (retcode != DDS_RETCODE_OK) {
printf("unregister instance error %d\n", retcode);
}
*/
/* Delete data sample */
retcode = listenersTypeSupport::delete_data(instance);
if (retcode != DDS_RETCODE_OK) {
printf("listenersTypeSupport::delete_data error %d\n", retcode);
}
/* Delete all entities */
return publisher_shutdown(participant);
delete writer_listener;
}
#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/listeners/c++/listeners_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.
******************************************************************************/
/* listeners_subscriber.cxx
A subscription example
This file is derived from code automatically generated by the rtiddsgen
command:
rtiddsgen -language C++ -example <arch> listeners.idl
Example subscription of type listeners 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>/listeners_subscriber <domain_id> <sample_count>
(3) Start the publication with the command
objs/<arch>/listeners_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>/listeners_publisher <domain_id>
objs/<arch>/listeners_subscriber <domain_id>
On Windows:
objs\<arch>\listeners_publisher <domain_id>
objs\<arch>\listeners_subscriber <domain_id>
modification history
------------ -------
*/
#include <stdio.h>
#include <stdlib.h>
#ifdef RTI_VX653
#include <vThreadsData.h>
#endif
#include "listeners.h"
#include "listenersSupport.h"
#include "ndds/ndds_cpp.h"
class ParticipantListener : public DDSDomainParticipantListener {
public:
virtual void on_requested_deadline_missed(
DDSDataReader* /*reader*/,
const DDS_RequestedDeadlineMissedStatus& /*status*/)
{
printf("ParticipantListener: on_requested_deadline_missed()\n");
}
virtual void on_requested_incompatible_qos(
DDSDataReader* /*reader*/,
const DDS_RequestedIncompatibleQosStatus& /*status*/)
{
printf("ParticipantListener: on_requested_incompatible_qos()\n");
}
virtual void on_sample_rejected(
DDSDataReader* /*reader*/,
const DDS_SampleRejectedStatus& /*status*/)
{
printf("ParticipantListener: on_sample_rejected()\n");
}
virtual void on_liveliness_changed(
DDSDataReader* /*reader*/,
const DDS_LivelinessChangedStatus& /*status*/)
{
printf("ParticipantListener: on_liveliness_changed()\n");
}
virtual void on_sample_lost(
DDSDataReader* /*reader*/,
const DDS_SampleLostStatus& /*status*/)
{
printf("ParticipantListener: on_sample_lost()\n");
}
virtual void on_subscription_matched(
DDSDataReader* /*reader*/,
const DDS_SubscriptionMatchedStatus& /*status*/)
{
printf("ParticipantListener: on_subscription_matched()\n");
}
virtual void on_data_available(DDSDataReader* reader)
{
printf("ParticipantListener: on_data_available()\n");
}
virtual void on_data_on_readers(DDSSubscriber *subscriber /*subscriber*/)
{
printf("ParticipantListener: on_data_on_readers()\n");
/* notify_datareaders() only calls on_data_available for
* DataReaders with unread samples
*/
DDS_ReturnCode_t retcode = subscriber->notify_datareaders();
if (retcode != DDS_RETCODE_OK) {
printf("notify_datareaders() error: %d\n", retcode);
}
}
virtual void on_inconsistent_topic(
DDSTopic *topic,
const DDS_InconsistentTopicStatus &status)
{
printf("ParticipantListener: on_inconsistent_topic()\n");
}
};
class SubscriberListener : public DDSSubscriberListener {
public:
virtual void on_requested_deadline_missed(
DDSDataReader* /*reader*/,
const DDS_RequestedDeadlineMissedStatus& /*status*/)
{
printf("SubscriberListener: on_requested_deadline_missed()\n");
}
virtual void on_requested_incompatible_qos(
DDSDataReader* /*reader*/,
const DDS_RequestedIncompatibleQosStatus& /*status*/)
{
printf("SubscriberListener: on_requested_incompatible_qos()\n");
}
virtual void on_sample_rejected(
DDSDataReader* /*reader*/,
const DDS_SampleRejectedStatus& /*status*/)
{
printf("SubscriberListener: on_sample_rejected()\n");
}
virtual void on_liveliness_changed(
DDSDataReader* /*reader*/,
const DDS_LivelinessChangedStatus& /*status*/)
{
printf("SubscriberListener: on_liveliness_changed()\n");
}
virtual void on_sample_lost(
DDSDataReader* /*reader*/,
const DDS_SampleLostStatus& /*status*/)
{
printf("SubscriberListener: on_sample_lost()\n");
}
virtual void on_subscription_matched(
DDSDataReader* /*reader*/,
const DDS_SubscriptionMatchedStatus& /*status*/)
{
printf("SubscriberListener: on_subscription_matched()\n");
}
virtual void on_data_available(DDSDataReader* reader)
{
printf("SubscriberListener: on_data_available()\n");
}
virtual void on_data_on_readers(DDSSubscriber *sub /*subscriber*/)
{
static int count = 0;
printf("SubscriberListener: on_data_on_readers()\n");
// notify_datareaders() only calls on_data_available for
// DataReaders with unread samples
DDS_ReturnCode_t retcode = sub->notify_datareaders();
if (retcode != DDS_RETCODE_OK) {
printf("notify_datareaders() error: %d\n", retcode);
}
if (++count > 3) {
DDS_StatusMask newmask = DDS_STATUS_MASK_ALL;
// 'Unmask' DATA_ON_READERS status for listener
newmask &= ~DDS_DATA_ON_READERS_STATUS;
sub->set_listener(this, newmask);
printf("Unregistering SubscriberListener::on_data_on_readers()\n");
}
}
};
class ReaderListener : public DDSDataReaderListener {
public:
virtual void on_requested_deadline_missed(
DDSDataReader* /*reader*/,
const DDS_RequestedDeadlineMissedStatus& /*status*/)
{
printf("ReaderListener: on_requested_deadline_missed()\n");
}
virtual void on_requested_incompatible_qos(
DDSDataReader* /*reader*/,
const DDS_RequestedIncompatibleQosStatus& /*status*/)
{
printf("ReaderListener: on_requested_incompatible_qos()\n");
}
virtual void on_sample_rejected(
DDSDataReader* /*reader*/,
const DDS_SampleRejectedStatus& /*status*/)
{
printf("ReaderListener: on_sample_rejected()\n");
}
virtual void on_liveliness_changed(
DDSDataReader* /*reader*/,
const DDS_LivelinessChangedStatus& status)
{
printf("ReaderListener: on_liveliness_changed()\n");
printf(" Alive writers: %d\n", status.alive_count);
}
virtual void on_sample_lost(
DDSDataReader* /*reader*/,
const DDS_SampleLostStatus& /*status*/)
{
printf("ReaderListener: on_sample_lost()\n");
}
virtual void on_subscription_matched(
DDSDataReader* /*reader*/,
const DDS_SubscriptionMatchedStatus& /*status*/)
{
printf("ReaderListener: on_subscription_matched()\n");
}
virtual void on_data_available(DDSDataReader* reader);
};
void ReaderListener::on_data_available(DDSDataReader* reader)
{
listenersDataReader *listeners_reader = NULL;
listenersSeq data_seq;
DDS_SampleInfoSeq info_seq;
DDS_ReturnCode_t retcode;
int i;
listeners_reader = listenersDataReader::narrow(reader);
if (listeners_reader == NULL) {
printf("DataReader narrow error\n");
return;
}
retcode = listeners_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 the reference we get is valid data, it means we have actual
* data available, otherwise we got metadata */
if (info_seq[i].valid_data) {
listenersTypeSupport::print_data(&data_seq[i]);
} else {
printf(" Got metadata\n");
}
}
retcode = listeners_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;
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;
/* Create Particiant Listener */
ParticipantListener *participant_listener = new ParticipantListener();
if (participant_listener == NULL) {
printf("participant listener instantiation error\n");
subscriber_shutdown(participant);
return -1;
}
/* We associate the participant_listener to the participant and set the
* status mask to get all the statuses */
participant =
DDSTheParticipantFactory->create_participant(domainId,
DDS_PARTICIPANT_QOS_DEFAULT,
participant_listener /* listener */,
DDS_STATUS_MASK_ALL /* get all statuses */);
if (participant == NULL) {
printf("create_participant error\n");
subscriber_shutdown(participant);
delete participant_listener;
return -1;
}
/* Create Subscriber Listener */
SubscriberListener *subscriber_listener = new SubscriberListener();
if (subscriber_listener == NULL) {
printf("subscriber listener instantiation error\n");
subscriber_shutdown(participant);
delete participant_listener;
return -1;
}
/* Here we associate the subscriber listener to the subscriber and set the
* status mask to get all the statuses */
subscriber = participant->create_subscriber(DDS_SUBSCRIBER_QOS_DEFAULT,
subscriber_listener /* listener */,
DDS_STATUS_MASK_ALL /* get all statuses */);
if (subscriber == NULL) {
printf("create_subscriber error\n");
subscriber_shutdown(participant);
delete participant_listener;
delete subscriber_listener;
return -1;
}
/* Register the type before creating the topic */
type_name = listenersTypeSupport::get_type_name();
retcode = listenersTypeSupport::register_type(
participant, type_name);
if (retcode != DDS_RETCODE_OK) {
printf("register_type error %d\n", retcode);
subscriber_shutdown(participant);
delete participant_listener;
delete subscriber_listener;
return -1;
}
/* To customize the topic QoS, use
the configuration file USER_QOS_PROFILES.xml */
topic = participant->create_topic(
"Example listeners",
type_name, DDS_TOPIC_QOS_DEFAULT, NULL /* listener */,
DDS_STATUS_MASK_NONE);
if (topic == NULL) {
printf("create_topic error\n");
subscriber_shutdown(participant);
delete participant_listener;
delete subscriber_listener;
return -1;
}
/* Create a data reader listener */
ReaderListener *reader_listener = new ReaderListener();
if (reader_listener == NULL) {
printf("reader listener instantiation error\n");
subscriber_shutdown(participant);
delete participant_listener;
delete subscriber_listener;
return -1;
}
/* Here we associate the data reader listener to the reader.
* We just listen for liveliness changed and data available,
* since most specific listeners will get called */
reader =
subscriber->create_datareader(topic,
DDS_DATAREADER_QOS_DEFAULT,
reader_listener /* listener */,
DDS_LIVELINESS_CHANGED_STATUS |
DDS_DATA_AVAILABLE_STATUS /* statuses */);
if (reader == NULL) {
printf("create_datareader error\n");
subscriber_shutdown(participant);
delete participant_listener;
delete subscriber_listener;
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;
delete subscriber_listener;
delete participant_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/listeners/c/listeners_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.
******************************************************************************/
/* listeners_subscriber.c
A subscription example
This file is derived from code automatically generated by the rtiddsgen
command:
rtiddsgen -language C -example <arch> listeners.idl
Example subscription of type listeners 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>/listeners_subscriber <domain_id> <sample_count>
(3) Start the publication with the command
objs/<arch>/listeners_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>/listeners_publisher <domain_id>
objs/<arch>/listeners_subscriber <domain_id>
On Windows systems:
objs\<arch>\listeners_publisher <domain_id>
objs\<arch>\listeners_subscriber <domain_id>
modification history
------------ -------
*/
#include <stdio.h>
#include <stdlib.h>
#include "ndds/ndds_c.h"
#include "listeners.h"
#include "listenersSupport.h"
/* -------------------------------------------------------
* Participant Listener events
* ------------------------------------------------------- */
void
ParticipantListener_on_requested_deadline_missed(
void* listener_data,
DDS_DataReader* reader,
const struct DDS_RequestedDeadlineMissedStatus *status)
{
printf("ParticipantListener: on_requested_deadline_missed()\n");
}
void ParticipantListener_on_requested_incompatible_qos(
void* listener_data,
DDS_DataReader* reader,
const struct DDS_RequestedIncompatibleQosStatus *status)
{
printf("ParticipantListener: on_requested_incompatible_qos()\n");
}
void ParticipantListener_on_sample_rejected(
void* listener_data,
DDS_DataReader* reader,
const struct DDS_SampleRejectedStatus *status)
{
printf("ParticipantListener: on_sample_rejected()\n");
}
void ParticipantListener_on_liveliness_changed(
void* listener_data,
DDS_DataReader* reader,
const struct DDS_LivelinessChangedStatus *status)
{
printf("ParticipantListener: on_liveliness_changed()\n");
}
void ParticipantListener_on_sample_lost(
void* listener_data,
DDS_DataReader* reader,
const struct DDS_SampleLostStatus *status)
{
printf("ParticipantListener: on_sample_lost()\n");
}
void ParticipantListener_on_subscription_matched(
void* listener_data,
DDS_DataReader* reader,
const struct DDS_SubscriptionMatchedStatus *status)
{
printf("ParticipantListener: on_subscription_matched()\n");
}
void ParticipantListener_on_data_available(
void* listener_data,
DDS_DataReader* reader)
{
printf("ParticipantListener: on_data_available()\n");
}
void ParticipantListener_on_data_on_readers(
void* listener_data,
DDS_Subscriber* sub)
{
DDS_ReturnCode_t retcode;
printf("ParticipantListener: on_data_on_readers()\n");
/* notify_datareaders() only calls on_data_available for
* DataReaders with unread samples
*/
retcode = DDS_Subscriber_notify_datareaders(sub);
if (retcode != DDS_RETCODE_OK) {
printf("notify_datareaders() error: %d\n", retcode);
}
}
void ParticipantListener_on_inconsistent_topic(
void* listener_data,
DDS_Topic* topic,
const struct DDS_InconsistentTopicStatus *status)
{
printf("ParticipantListener: on_inconsistent_topic()\n");
}
/* -------------------------------------------------------
* Subscriber Listener events
* ------------------------------------------------------- */
void SubscriberListener_on_requested_deadline_missed(
void* listener_data,
DDS_DataReader* reader,
const struct DDS_RequestedDeadlineMissedStatus *status)
{
printf("SubscriberListener: on_requested_deadline_missed()\n");
}
void SubscriberListener_on_requested_incompatible_qos(
void* listener_data,
DDS_DataReader* reader,
const struct DDS_RequestedIncompatibleQosStatus *status)
{
printf("SubscriberListener: on_requested_incompatible_qos()\n");
}
void SubscriberListener_on_sample_rejected(
void* listener_data,
DDS_DataReader* reader,
const struct DDS_SampleRejectedStatus *status)
{
printf("SubscriberListener: on_sample_rejected()\n");
}
void SubscriberListener_on_liveliness_changed(
void* listener_data,
DDS_DataReader* reader,
const struct DDS_LivelinessChangedStatus *status)
{
printf("SubscriberListener: on_liveliness_changed()\n");
}
void SubscriberListener_on_sample_lost(
void* listener_data,
DDS_DataReader* reader,
const struct DDS_SampleLostStatus *status)
{
printf("SubscriberListener: on_sample_lost()\n");
}
void SubscriberListener_on_subscription_matched(
void* listener_data,
DDS_DataReader* reader,
const struct DDS_SubscriptionMatchedStatus *status)
{
printf("SubscriberListener: on_subscription_matched()\n");
}
void SubscriberListener_on_data_available(
void* listener_data,
DDS_DataReader* reader)
{
printf("SubscriberListener: on_data_available()\n");
}
void SubscriberListener_on_data_on_readers(
void* listener_data,
DDS_Subscriber* sub)
{
DDS_ReturnCode_t retcode;
static int count = 0;
printf("SubscriberListener: on_data_on_readers()\n");
/* notify_datareaders() only calls on_data_available for
* DataReaders with unread samples */
retcode = DDS_Subscriber_notify_datareaders(sub);
if (retcode != DDS_RETCODE_OK) {
printf("notify_datareaders() error: %d\n", retcode);
}
if (++count > 3) {
/* Stop receiving DATA_ON_READERS status */
DDS_StatusMask newmask = DDS_REQUESTED_DEADLINE_MISSED_STATUS | DDS_REQUESTED_INCOMPATIBLE_QOS_STATUS |
DDS_SAMPLE_REJECTED_STATUS | DDS_LIVELINESS_CHANGED_STATUS | DDS_SAMPLE_LOST_STATUS |
DDS_SUBSCRIPTION_MATCHED_STATUS | DDS_DATA_AVAILABLE_STATUS;
DDS_Subscriber_set_listener(sub, listener_data, newmask);
printf("Unregistering SubscriberListener::on_data_on_readers()\n");
}
}
/* -------------------------------------------------------
* Reader Listener events
* ------------------------------------------------------- */
void ReaderListener_on_requested_deadline_missed(
void* listener_data,
DDS_DataReader* reader,
const struct DDS_RequestedDeadlineMissedStatus *status)
{
printf("ReaderListener: on_requested_deadline_missed()\n");
}
void ReaderListener_on_requested_incompatible_qos(
void* listener_data,
DDS_DataReader* reader,
const struct DDS_RequestedIncompatibleQosStatus *status)
{
printf("ReaderListener: on_requested_incompatible_qos()\n");
}
void ReaderListener_on_sample_rejected(
void* listener_data,
DDS_DataReader* reader,
const struct DDS_SampleRejectedStatus *status)
{
printf("ReaderListener: on_sample_rejected()\n");
}
void ReaderListener_on_liveliness_changed(
void* listener_data,
DDS_DataReader* reader,
const struct DDS_LivelinessChangedStatus *status)
{
printf("ReaderListener: on_liveliness_changed()\n");
printf(" Alive writers: %d\n", status->alive_count);
}
void ReaderListener_on_sample_lost(
void* listener_data,
DDS_DataReader* reader,
const struct DDS_SampleLostStatus *status)
{
printf("ReaderListener: on_sample_lost()\n");
}
void ReaderListener_on_subscription_matched(
void* listener_data,
DDS_DataReader* reader,
const struct DDS_SubscriptionMatchedStatus *status)
{
printf("ReaderListener: on_subscription_matched()\n");
}
void ReaderListener_on_data_available(
void* listener_data,
DDS_DataReader* reader)
{
listenersDataReader *listeners_reader = NULL;
struct listenersSeq data_seq = DDS_SEQUENCE_INITIALIZER;
struct DDS_SampleInfoSeq info_seq = DDS_SEQUENCE_INITIALIZER;
DDS_ReturnCode_t retcode;
int i;
printf("ReaderListener: on_data_available()\n");
listeners_reader = listenersDataReader_narrow(reader);
if (listeners_reader == NULL) {
printf("DataReader narrow error\n");
return;
}
retcode = listenersDataReader_take(
listeners_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 < listenersSeq_get_length(&data_seq); ++i) {
/* If the reference we get is valid data, it means we have actual
* data available, otherwise we got metadata */
if (DDS_SampleInfoSeq_get_reference(&info_seq, i)->valid_data) {
listenersTypeSupport_print_data(
listenersSeq_get_reference(&data_seq, i));
} else {
printf(" Got metadata\n");
}
}
retcode = listenersDataReader_return_loan(
listeners_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_DomainParticipantListener participant_listener =
DDS_DomainParticipantListener_INITIALIZER;
struct DDS_SubscriberListener subscriber_listener =
DDS_SubscriberListener_INITIALIZER;
struct DDS_DataReaderListener reader_listener =
DDS_DataReaderListener_INITIALIZER;
DDS_StatusMask mask;
DDS_DataReader *reader = NULL;
DDS_ReturnCode_t retcode;
const char *type_name = NULL;
int count = 0;
struct DDS_Duration_t poll_period = {1,0};
/* Set up participant listener */
participant_listener.as_subscriberlistener.as_datareaderlistener.on_requested_deadline_missed =
ParticipantListener_on_requested_deadline_missed;
participant_listener.as_subscriberlistener.as_datareaderlistener.on_requested_incompatible_qos =
ParticipantListener_on_requested_incompatible_qos;
participant_listener.as_subscriberlistener.as_datareaderlistener.on_sample_rejected =
ParticipantListener_on_sample_rejected;
participant_listener.as_subscriberlistener.as_datareaderlistener.on_liveliness_changed =
ParticipantListener_on_liveliness_changed;
participant_listener.as_subscriberlistener.as_datareaderlistener.on_sample_lost =
ParticipantListener_on_sample_lost;
participant_listener.as_subscriberlistener.as_datareaderlistener.on_subscription_matched =
ParticipantListener_on_subscription_matched;
participant_listener.as_subscriberlistener.as_datareaderlistener.on_data_available =
ParticipantListener_on_data_available;
participant_listener.as_subscriberlistener.on_data_on_readers =
ParticipantListener_on_data_on_readers;
participant_listener.as_topiclistener.on_inconsistent_topic =
ParticipantListener_on_inconsistent_topic;
participant_listener.as_subscriberlistener.as_datareaderlistener.as_listener.listener_data =
&participant_listener;
mask = DDS_REQUESTED_DEADLINE_MISSED_STATUS |
DDS_REQUESTED_INCOMPATIBLE_QOS_STATUS |
DDS_SAMPLE_REJECTED_STATUS |
DDS_LIVELINESS_CHANGED_STATUS |
DDS_SAMPLE_LOST_STATUS |
DDS_SUBSCRIPTION_MATCHED_STATUS |
DDS_DATA_AVAILABLE_STATUS |
DDS_DATA_ON_READERS_STATUS |
DDS_INCONSISTENT_TOPIC_STATUS;
/* We associate the participant_listener to the participant and set the
* status mask just defined */
participant =
DDS_DomainParticipantFactory_create_participant(DDS_TheParticipantFactory,
domainId,
&DDS_PARTICIPANT_QOS_DEFAULT,
&participant_listener /* listener */,
mask /* status mask */);
if (participant == NULL) {
printf("create_participant error\n");
subscriber_shutdown(participant);
return -1;
}
/* Setup subscriber listener */
subscriber_listener.as_datareaderlistener.on_requested_deadline_missed =
SubscriberListener_on_requested_deadline_missed;
subscriber_listener.as_datareaderlistener.on_requested_incompatible_qos =
SubscriberListener_on_requested_incompatible_qos;
subscriber_listener.as_datareaderlistener.on_sample_rejected =
SubscriberListener_on_sample_rejected;
subscriber_listener.as_datareaderlistener.on_liveliness_changed =
SubscriberListener_on_liveliness_changed;
subscriber_listener.as_datareaderlistener.on_sample_lost =
SubscriberListener_on_sample_lost;
subscriber_listener.as_datareaderlistener.on_subscription_matched =
SubscriberListener_on_subscription_matched;
subscriber_listener.as_datareaderlistener.on_data_available =
SubscriberListener_on_data_available;
subscriber_listener.on_data_on_readers =
SubscriberListener_on_data_on_readers;
subscriber_listener.as_datareaderlistener.as_listener.listener_data =
&subscriber_listener;
mask = DDS_REQUESTED_DEADLINE_MISSED_STATUS |
DDS_REQUESTED_INCOMPATIBLE_QOS_STATUS |
DDS_SAMPLE_REJECTED_STATUS |
DDS_LIVELINESS_CHANGED_STATUS |
DDS_SAMPLE_LOST_STATUS |
DDS_SUBSCRIPTION_MATCHED_STATUS |
DDS_DATA_AVAILABLE_STATUS |
DDS_DATA_ON_READERS_STATUS;
/* Here we associate the subscriber listener to the subscriber and set the
* status mask to the mask we have just defined */
subscriber = DDS_DomainParticipant_create_subscriber(participant,
&DDS_SUBSCRIBER_QOS_DEFAULT,
&subscriber_listener /* listener */,
mask /* status mask */);
if (subscriber == NULL) {
printf("create_subscriber error\n");
subscriber_shutdown(participant);
return -1;
}
/* Register the type before creating the topic */
type_name = listenersTypeSupport_get_type_name();
retcode = listenersTypeSupport_register_type(participant, type_name);
if (retcode != DDS_RETCODE_OK) {
printf("register_type error %d\n", retcode);
subscriber_shutdown(participant);
return -1;
}
topic = DDS_DomainParticipant_create_topic(
participant, "Example listeners",
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;
}
/* Setup data reader listener */
reader_listener.on_requested_deadline_missed =
ReaderListener_on_requested_deadline_missed;
reader_listener.on_requested_incompatible_qos =
ReaderListener_on_requested_incompatible_qos;
reader_listener.on_sample_rejected =
ReaderListener_on_sample_rejected;
reader_listener.on_liveliness_changed =
ReaderListener_on_liveliness_changed;
reader_listener.on_sample_lost =
ReaderListener_on_sample_lost;
reader_listener.on_subscription_matched =
ReaderListener_on_subscription_matched;
reader_listener.on_data_available =
ReaderListener_on_data_available;
reader_listener.as_listener.listener_data =
&reader_listener;
/* Just listen for liveliness changed and data available,
* since most specific listeners will get called */
mask = DDS_LIVELINESS_CHANGED_STATUS |
DDS_DATA_AVAILABLE_STATUS;
/* In the data reader we change the status mask to the mask
* we have just defined */
reader = DDS_Subscriber_create_datareader(
subscriber, DDS_Topic_as_topicdescription(topic),
&DDS_DATAREADER_QOS_DEFAULT, &reader_listener, mask);
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/listeners/c/listeners_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.
******************************************************************************/
/* listeners_publisher.c
A publication of data of type listeners
This file is derived from code automatically generated by the rtiddsgen
command:
rtiddsgen -language C -example <arch> listeners.idl
Example publication of type listeners 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>/listeners_subscriber <domain_id> <sample_count>
(3) Start the publication with the command
objs/<arch>/listeners_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>/listeners_publisher <domain_id>
objs/<arch>/listeners_subscriber <domain_id>
On Windows:
objs\<arch>\listeners_publisher <domain_id>
objs\<arch>\listeners_subscriber <domain_id>
modification history
------------ -------
*/
#include <stdio.h>
#include <stdlib.h>
#include "ndds/ndds_c.h"
#include "listeners.h"
#include "listenersSupport.h"
void DataWriterListener_on_offered_deadline_missed(
void *listener_data,
DDS_DataWriter *writer,
const struct DDS_OfferedDeadlineMissedStatus *status)
{
printf("DataWriterListener: on_offered_deadline_missed()\n");
}
void DataWriterListener_on_liveliness_lost(
void *listener_data,
DDS_DataWriter *writer,
const struct DDS_LivelinessLostStatus *status)
{
printf("DataWriterListener: on_liveliness_lost()\n");
}
void DataWriterListener_on_offered_incompatible_qos(
void *listener_data,
DDS_DataWriter *writer,
const struct DDS_OfferedIncompatibleQosStatus *status)
{
printf("DataWriterListener: on_offered_incompatible_qos()\n");
}
void DataWriterListener_on_publication_matched(
void *listener_data,
DDS_DataWriter *writer,
const struct DDS_PublicationMatchedStatus *status)
{
printf("DataWriterListener: on_publication_matched()\n");
if (status->current_count_change < 0) {
printf("lost a subscription\n");
}
else {
printf("found a subscription\n");
}
}
void DataWriterListener_on_reliable_writer_cache_changed(
void *listener_data,
DDS_DataWriter *writer,
const struct DDS_ReliableWriterCacheChangedStatus *status)
{
printf("DataWriterListener: on_reliable_writer_cache_changed()\n");
}
void DataWriterListener_on_reliable_reader_activity_changed(
void *listener_data,
DDS_DataWriter *writer,
const struct DDS_ReliableReaderActivityChangedStatus *status)
{
printf("DataWriterListener: on_reliable_reader_activity_changed()\n");
}
/* 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;
listenersDataWriter *listeners_writer = NULL;
listeners *instance = NULL;
DDS_ReturnCode_t retcode;
DDS_InstanceHandle_t instance_handle = DDS_HANDLE_NIL;
const char *type_name = NULL;
struct DDS_DataWriterListener writer_listener =
DDS_DataWriterListener_INITIALIZER;
DDS_Topic *inconsistent_topic = NULL;
DDS_DataWriter *inconsistent_topic_writer = NULL;
const char *inconsistent_topic_type_name = NULL;
msgDataWriter *msg_writer = NULL;
int count = 0;
struct DDS_Duration_t send_period = {1,0};
struct DDS_Duration_t sleep_period = {2,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;
}
/* Create ande Delete Inconsistent Topic
* ---------------------------------------------------------------
* Here we create an inconsistent topic to trigger the subscriber
* application's callback.
* The inconsistent topic is created with the topic name used in
* the Subscriber application, but with a different data type --
* the msg data type defined in partitions.idl.
* Once it is created, we sleep to ensure the applications discover
* each other and delete the Data Writer and Topic.
*/
/* First we register the msg type -- we name it
* inconsistent_topic_type_name to avoid confusion.
*/
printf("Creating Inconsistent Topic... \n");
inconsistent_topic_type_name = msgTypeSupport_get_type_name();
retcode = msgTypeSupport_register_type(participant,
inconsistent_topic_type_name);
if (retcode != DDS_RETCODE_OK) {
printf("register_type error %d\n", retcode);
publisher_shutdown(participant);
return -1;
}
inconsistent_topic =
DDS_DomainParticipant_create_topic(participant,
"Example listeners",
inconsistent_topic_type_name,
&DDS_TOPIC_QOS_DEFAULT,
NULL,
DDS_STATUS_MASK_NONE);
if (inconsistent_topic == NULL) {
printf("create_topic error (inconsistent topic)\n");
publisher_shutdown(participant);
return -1;
}
/* We have to associate a writer to the topic, as Topic information is not
* actually propagated until the creation of an associated writer.
*/
inconsistent_topic_writer = DDS_Publisher_create_datawriter(publisher,
inconsistent_topic,
&DDS_DATAWRITER_QOS_DEFAULT,
NULL /* listener */,
DDS_STATUS_MASK_NONE);
if (inconsistent_topic_writer == NULL) {
printf("create_datawriter error\n");
publisher_shutdown(participant);
return -1;
}
msg_writer = msgDataWriter_narrow(inconsistent_topic_writer);
if (msg_writer == NULL) {
printf("DataWriter narrow error\n");
publisher_shutdown(participant);
return -1;
}
/* Sleep to leave time for applications to discover each other */
NDDS_Utility_sleep(&sleep_period);
/* Before creating the "consistent" topic, we delete the Data Writer and the
* inconsistent topic.
*/
retcode = DDS_Publisher_delete_datawriter(publisher, inconsistent_topic_writer);
if (retcode != DDS_RETCODE_OK) {
printf("delete_datawriter error %d\n", retcode);
publisher_shutdown(participant);
return -1;
}
retcode = DDS_DomainParticipant_delete_topic(participant, inconsistent_topic);
if (retcode != DDS_RETCODE_OK) {
printf("delete_topic error %d\n", retcode);
publisher_shutdown(participant);
return -1;
}
printf("... Deleted Inconsistent Topic\n\n");
/* Create Consistent Topic
* -----------------------------------------------------------------
* Once we have created the inconsistent topic with the wrong type,
* we create a topic with the right type name -- listeners -- that we
* will use to publish data.
*/
/* Register type before creating topic */
type_name = listenersTypeSupport_get_type_name();
retcode = listenersTypeSupport_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 listeners",
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;
}
/* We will use the Data Writer Listener defined above to print
* a message when some of events are triggered in the DataWriter.
* To do that, first we have to pass the writer_listener and then
* we have to enable all status in the status mask.
*/
/* Set up participant listener */
writer_listener.on_offered_deadline_missed =
DataWriterListener_on_offered_deadline_missed;
writer_listener.on_liveliness_lost =
DataWriterListener_on_liveliness_lost;
writer_listener.on_offered_incompatible_qos =
DataWriterListener_on_offered_incompatible_qos;
writer_listener.on_publication_matched =
DataWriterListener_on_publication_matched;
writer_listener.on_reliable_writer_cache_changed =
DataWriterListener_on_reliable_writer_cache_changed;
writer_listener.on_reliable_reader_activity_changed =
DataWriterListener_on_reliable_reader_activity_changed;
writer = DDS_Publisher_create_datawriter(publisher,
topic,
&DDS_DATAWRITER_QOS_DEFAULT,
&writer_listener /* listener */,
DDS_STATUS_MASK_ALL /* enable all statuses */);
if (writer == NULL) {
printf("create_datawriter error\n");
publisher_shutdown(participant);
return -1;
}
listeners_writer = listenersDataWriter_narrow(writer);
if (listeners_writer == NULL) {
printf("DataWriter narrow error\n");
publisher_shutdown(participant);
return -1;
}
/* Create data sample for writing */
instance = listenersTypeSupport_create_data_ex(DDS_BOOLEAN_TRUE);
if (instance == NULL) {
printf("listenersTypeSupport_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 = listenersDataWriter_register_instance(
listeners_writer, instance);
*/
printf("Publishing data using Consinstent Topic... \n");
/* Main loop */
for (count=0; (sample_count == 0) || (count < sample_count); ++count) {
printf("Writing listeners, count %d\n", count);
/* Modify the data to be written here */
instance->x = count;
/* Write data */
retcode = listenersDataWriter_write(
listeners_writer, instance, &instance_handle);
if (retcode != DDS_RETCODE_OK) {
printf("write error %d\n", retcode);
}
NDDS_Utility_sleep(&send_period);
}
/*
retcode = listenersDataWriter_unregister_instance(
listeners_writer, instance, &instance_handle);
if (retcode != DDS_RETCODE_OK) {
printf("unregister instance error %d\n", retcode);
}
*/
/* Delete data sample */
retcode = listenersTypeSupport_delete_data_ex(instance, DDS_BOOLEAN_TRUE);
if (retcode != DDS_RETCODE_OK) {
printf("listenersTypeSupport_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/listeners/c++03/listeners_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 "listeners.hpp"
#include <dds/dds.hpp>
#include <rti/core/ListenerBinder.hpp>
using namespace dds::core;
using namespace dds::domain;
using namespace dds::pub;
using namespace dds::topic;
class MyDataWriterListener : public NoOpDataWriterListener<listeners> {
public:
virtual void on_offered_deadline_missed(
dds::pub::DataWriter<listeners>& writer,
const dds::core::status::OfferedDeadlineMissedStatus& status)
{
std::cout << "DataWriterListener: on_offered_deadline_missed()"
<< std::endl;
}
virtual void on_liveliness_lost(
dds::pub::DataWriter<listeners>& writer,
const dds::core::status::LivelinessLostStatus& status)
{
std::cout << "DataWriterListener: on_liveliness_lost()"
<< std::endl;
}
virtual void on_offered_incompatible_qos(
dds::pub::DataWriter<listeners>& writer,
const dds::core::status::OfferedIncompatibleQosStatus& status)
{
std::cout << "DataWriterListener: on_offered_incompatible_qos()"
<< std::endl;
}
virtual void on_publication_matched(
dds::pub::DataWriter<listeners>& writer,
const dds::core::status::PublicationMatchedStatus& status)
{
std::cout << "DataWriterListener: on_publication_matched()"
<< std::endl;
if (status.current_count_change() < 0) {
std::cout << "lost a subscription" << std::endl;
} else {
std::cout << "found a subscription" << std::endl;
}
}
virtual void on_reliable_writer_cache_changed(
dds::pub::DataWriter<listeners>& writer,
const rti::core::status::ReliableWriterCacheChangedStatus& status)
{
std::cout << "DataWriterListener: on_reliable_writer_cache_changed()"
<< std::endl;
}
virtual void on_reliable_reader_activity_changed(
dds::pub::DataWriter<listeners>& writer,
const rti::core::status::ReliableReaderActivityChangedStatus& status)
{
std::cout << "DataWriterListener: on_reliable_reader_activity_changed()"
<< std::endl;
}
};
void publisher_main(int domain_id, int sample_count)
{
// Create the participant.
// To customize QoS, use the configuration file USER_QOS_PROFILES.xml
DomainParticipant participant (domain_id);
// Create the publisher
// To customize QoS, use the configuration file USER_QOS_PROFILES.xml
Publisher publisher (participant);
// Create ande Delete Inconsistent Topic
// ---------------------------------------------------------------
// Here we create an inconsistent topic to trigger the subscriber
// application's callback.
// The inconsistent topic is created with the topic name used in
// the Subscriber application, but with a different data type --
// the msg data type defined in listener.idl.
// Once it is created, we sleep to ensure the applications discover
// each other and delete the Data Writer and Topic.
std::cout << "Creating Inconsistent Topic..." << std::endl;
Topic<msg> inconsistent_topic (participant, "Example listeners");
// We have to associate a writer to the topic, as Topic information is not
// actually propagated until the creation of an associated writer.
DataWriter<msg> inconsistent_writer (publisher, inconsistent_topic);
// Sleep to leave time for applications to discover each other.
rti::util::sleep(Duration(2));
inconsistent_writer.close();
inconsistent_topic.close();
std::cout << "... Deleted Incosistent Topic" << std::endl << std::endl;
// Create Consistent Topic
// -----------------------------------------------------------------
// Once we have created the inconsistent topic with the wrong type,
// we create a topic with the right type name -- listeners -- that we
// will use to publish data.
Topic<listeners> topic (participant, "Example listeners");
// We will use the Data Writer Listener defined above to print
// a message when some of events are triggered in the DataWriter.
// By using ListenerBinder (a RAII) it will take care of setting the
// listener to NULL on destruction.
DataWriter<listeners> writer (publisher, topic);
rti::core::ListenerBinder< DataWriter<listeners> > writer_listener =
rti::core::bind_and_manage_listener(
writer,
new MyDataWriterListener,
dds::core::status::StatusMask::all());
// Create data sample for writing
listeners instance;
// Main loop
for (int count = 0; (sample_count == 0) || (count < sample_count); ++count){
std::cout << "Writing listeners, count " << count << std::endl;
// Modify data and send it.
instance.x(count);
writer.write(instance);
rti::util::sleep(Duration(2));
}
}
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/listeners/c++03/listeners_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 "listeners.hpp"
#include <dds/dds.hpp>
#include <rti/core/ListenerBinder.hpp>
using namespace dds::core;
using namespace rti::core;
using namespace dds::core::status;
using namespace dds::domain;
using namespace dds::sub;
using namespace dds::topic;
class MyParticipantListener : public NoOpDomainParticipantListener {
public:
virtual void on_requested_deadline_missed(
dds::pub::AnyDataWriter& writer,
const dds::core::status::OfferedDeadlineMissedStatus& status)
{
std::cout << "ParticipantListener: on_requested_deadline_missed()"
<< std::endl;
}
virtual void on_offered_incompatible_qos(
dds::pub::AnyDataWriter& writer,
const ::dds::core::status::OfferedIncompatibleQosStatus& status)
{
std::cout << "ParticipantListener: on_offered_incompatible_qos()"
<< std::endl;
}
virtual void on_sample_rejected(
dds::sub::AnyDataReader& the_reader,
const dds::core::status::SampleRejectedStatus& status)
{
std::cout << "ParticipantListener: on_sample_rejected()"
<< std::endl;
}
virtual void on_liveliness_changed(
dds::sub::AnyDataReader& the_reader,
const dds::core::status::LivelinessChangedStatus& status)
{
std::cout << "ParticipantListener: on_liveliness_changed()"
<< std::endl;
}
virtual void on_sample_lost(
dds::sub::AnyDataReader& the_reader,
const dds::core::status::SampleLostStatus& status)
{
std::cout << "ParticipantListener: on_sample_lost()"
<< std::endl;
}
virtual void on_subscription_matched(
dds::sub::AnyDataReader& the_reader,
const dds::core::status::SubscriptionMatchedStatus& status)
{
std::cout << "ParticipantListener: on_subscription_matched()"
<< std::endl;
}
virtual void on_data_available(dds::sub::AnyDataReader& the_reader)
{
std::cout << "ParticipantListener: on_data_available()"
<< std::endl;
}
virtual void on_data_on_readers(dds::sub::Subscriber& sub)
{
// Notify DataReaders only calls on_data_available for
// DataReaders with unread samples.
sub.notify_datareaders();
std::cout << "ParticipantListener: on_data_on_readers()"
<< std::endl;
}
virtual void on_inconsistent_topic(
dds::topic::AnyTopic& topic,
const dds::core::status::InconsistentTopicStatus& status)
{
std::cout << "ParticipantListener: on_inconsistent_topic()"
<< std::endl;
}
};
class MySubscriberListener : public NoOpSubscriberListener {
public:
virtual void on_requested_deadline_missed(
AnyDataReader& the_reader,
const dds::core::status::RequestedDeadlineMissedStatus& status)
{
std::cout << "SubscriberListener: on_requested_deadline_missed()"
<< std::endl;
}
virtual void on_requested_incompatible_qos(
AnyDataReader& the_reader,
const dds::core::status::RequestedIncompatibleQosStatus& status)
{
std::cout << "SubscriberListener: on_requested_incompatible_qos()"
<< std::endl;
}
virtual void on_sample_rejected(
AnyDataReader& the_reader,
const dds::core::status::SampleRejectedStatus& status)
{
std::cout << "SubscriberListener: on_sample_rejected()"
<< std::endl;
}
virtual void on_liveliness_changed(
AnyDataReader& the_reader,
const dds::core::status::LivelinessChangedStatus& status)
{
std::cout << "SubscriberListener: on_liveliness_changed()"
<< std::endl;
}
virtual void on_sample_lost(
AnyDataReader& the_reader,
const dds::core::status::SampleLostStatus& status)
{
std::cout << "SubscriberListener: on_sample_lost()"
<< std::endl;
}
virtual void on_subscription_matched(
AnyDataReader& the_reader,
const dds::core::status::SubscriptionMatchedStatus& status)
{
std::cout << "SubscriberListener: on_subscription_matched()"
<< std::endl;
}
virtual void on_data_available(AnyDataReader& the_reader)
{
std::cout << "SubscriberListener: on_data_available()"
<< std::endl;
}
virtual void on_data_on_readers(Subscriber& sub)
{
static int count = 0;
std::cout << "SubscriberListener: on_data_on_readers()"
<< std::endl;
sub->notify_datareaders();
if (++count > 3) {
StatusMask new_mask = StatusMask::all();
new_mask &= ~StatusMask::data_on_readers();
sub.listener(this, new_mask);
}
}
};
class MyDataReaderListener : public NoOpDataReaderListener<listeners> {
virtual void on_requested_deadline_missed(
DataReader<listeners>& reader,
const dds::core::status::RequestedDeadlineMissedStatus& status)
{
std::cout << "ReaderListener: on_requested_deadline_missed()"
<< std::endl;
}
virtual void on_requested_incompatible_qos(
DataReader<listeners>& reader,
const dds::core::status::RequestedIncompatibleQosStatus& status)
{
std::cout << "ReaderListener: on_requested_incompatible_qos()"
<< std::endl;
}
virtual void on_sample_rejected(
DataReader<listeners>& reader,
const dds::core::status::SampleRejectedStatus& status)
{
std::cout << "ReaderListener: on_sample_rejected()"
<< std::endl;
}
virtual void on_liveliness_changed(
DataReader<listeners>& reader,
const dds::core::status::LivelinessChangedStatus& status)
{
std::cout << "ReaderListener: on_liveliness_changed()" << std::endl
<< " Alive writers: " << status.alive_count() << std::endl;
}
virtual void on_sample_lost(
DataReader<listeners>& reader,
const dds::core::status::SampleLostStatus& status)
{
std::cout << "ReaderListener: on_sample_lost()"
<< std::endl;
}
virtual void on_subscription_matched(
DataReader<listeners>& reader,
const dds::core::status::SubscriptionMatchedStatus& status)
{
std::cout << "ReaderListener: on_subscription_matched()"
<< std::endl;
}
virtual void on_data_available(DataReader<listeners>& reader)
{
LoanedSamples<listeners> samples = reader.take();
for (LoanedSamples<listeners>::iterator sampleIt = samples.begin();
sampleIt != samples.end();
++sampleIt) {
// If the reference we get is valid data, it means we have actual
// data available, otherwise we got metadata.
if (sampleIt->info().valid()) {
std::cout << sampleIt->data() << std::endl;
} else {
std::cout << " Got metadata" << std::endl;
}
}
}
};
void subscriber_main(int domain_id, int sample_count)
{
// Create the participant
DomainParticipant participant (domain_id);
// Associate a listener to the participant using ListenerBinder, a RAII that
// will take care of setting it to NULL on destruction.
ListenerBinder<DomainParticipant> participant_listener =
rti::core::bind_and_manage_listener(
participant,
new MyParticipantListener,
dds::core::status::StatusMask::all());
// To customize topic QoS, use the configuration file USER_QOS_PROFILES.xml
Topic<listeners> topic (participant, "Example listeners");
// Create the subscriber and associate a listener
Subscriber subscriber (participant);
ListenerBinder<Subscriber> subscriber_listener =
rti::core::bind_and_manage_listener(
subscriber,
new MySubscriberListener,
dds::core::status::StatusMask::all());
// Create the DataReader and associate a listener
DataReader<listeners> reader (subscriber, topic);
ListenerBinder< DataReader<listeners> > datareader_listener =
rti::core::bind_and_manage_listener(
reader,
new MyDataReaderListener,
dds::core::status::StatusMask::all());
// Main loop
for (int count = 0; (sample_count == 0) || (count < sample_count); ++count){
// Each "sample_count" is four seconds.
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 (std::exception ex) {
std::cout << "Exception caught: " << ex.what() << std::endl;
return -1;
}
return 0;
}
| cxx |
rticonnextdds-examples | data/projects/rticonnextdds-examples/custom_transport/c/FileTransport.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.
******************************************************************************/
/* $Id: Intra.c,v 1.20 2008/10/22 19:16:46 jim Exp $
(c) Copyright, Real-Time Innovations, $Date: 2008/10/22 19:16:46 $.
All rights reserved.
No duplications, whole or partial, manual or electronic, may be made
without express written permission. Any such copies, or
revisions thereof, must display this notice unaltered.
This code contains trade secrets of Real-Time Innovations, Inc.
modification history
------------ -------
18apr2013,gpc Written
=========================================================================*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "sys/stat.h"
#include "sys/errno.h"
#include "signal.h"
#include "ndds/osapi/osapi_process.h"
#include "ndds/ndds_c.h"
#include "FileTransport.h"
/* =====================================================================
* FILE Transport-Plugin
*
* See:
* http://community.rti.com/rti-doc/500/RTI_Transport_Plugin_5.0.0/doc/html/index.html
*
* for general documentation on the RTI Connext DDS Transport Plugin API
*
* Overview:
* --------
*
* The FileTransport Plugin is intended as an example of how to use the
* the transport plugin API. The emphasis is on simplicity and
* understandability. There has been no effort to make this a "real"
* transport with any reasonable performance. Rather the goal was to use
* simple APIs for communications that would not distract from the APIs
* required to interface with the Connext DDS Core.
*
* The transport is limited to communicate between computers that have
* access to a common file-system.
*
* The transport was implemented for Unix systems (Linux, MacOSX) in that
* it uses some Unix system calls to do things like lock files and read/write
* bytes to the file. It should be possible to port to other operating systems
* as long as they offer similar functionality.
*
* Design:
* ------
*
* The FileTransport uses simple files for communication. Each address/port
* combination maps to a separate file placed in an agreed location in the
* file-system. To send to an address/port the transport opens the file and
* appends to the end. To receive, the transport opens the file and reads
* whatever was written beyond the position previously read.
*
* The access to the files is serialized using file locking. So that multiple
* applications can send "simultaneously" to the same address/port and the
* bytes sent are serialized in the corresponding file. The receiver also
* used file-locking to ensure it does not read from a file that is being
* concurrently updated.
*
* The "receive" operation on the TransportPlugin is required to block until
* data is available. To keep things simple the FileTransport implements
* this by polling the file to see if there were changes and if not
* sleeping 1 second before checking again. This is obviously not efficient
* but it keep the code simple which is the main goal.
*
* The transport can be configured via properties. These properties control
* the location in the file-system where the files are placed, the network
* address of the transport, and the tracing verbosity.
*
* A single participant can instantiate more then one FileTransports, each
* should be given a different name and network address.
*
* Configuration
* -------------
*
* The simplest way to load and configure the transport is do it using the
* DomainParticipantQos and moreover specify the DomainParticipantQos using
* the XML file USER_QOS_PROFILES.xml that is automatically loaded by the
* application.
*
* You can find the USER_QOS_PROFILES.xml used with this example in the
* same directoryRoot where this source file is.
*
* Properties:
* ----------
*
* In this properties the string "myPlugin" represents an arbitrary name that
* is given in order to name a particular instantiation of the transport plugin
* such that it can be distinguished from other instantiations. The choice of name
* is arbitrary as long as the same name is used consistenty in all the properties
* that configure a particular transport instance.
*
* Property: Meaning:
* ds.transport.load_plugins Property common to all transport plugins
* used to indicate there is a new plugin to
* load and give it a name
* (in this example we assume the name
* chosen is "myPlugin" )
*
* dds.transport.FILE.myPlugin.library Defines the name of the library
* that contains the plugin implementation
* for the plugin named in the load_plugins
* property
*
* dds.transport.FILE.myPlugin.create_function Defines the name of the entry-function
* in the library defined by the previous
* property. This function must conform to
* the signature:
*
* NDDS_Transport_Plugin* TransportPluginCreateFunctionName(
* NDDS_Transport_Address_t *default_network_address_out,
* const struct DDS_PropertyQosPolicy *property_in);
*
* dds.transport.FILE.myPlugin.address The network address given to the instance of the
* transport plugin. Each FILE plugin instance
* can have a single network address. This is also
* propagated via discovery and must be used
* in the NDDS_DISCOVERY_PEERS environment variable.
* By default: "1.1.1.1"
*
* dds.transport.FILE.myPlugin.dirname The 'home' directoryRoot under which the files used
* to hold the received messages are written
* By default: "/tmp/dds/<address>"
*
* ===================================================================== */
#define NDDS_Transport_FILE_DIRROOT "/tmp/dds"
#define NDDS_Transport_FILE_DIRBASE NDDS_Transport_FILE_DIRROOT "/FileTransport"
/* Max length of the signature message is placed as the first message to mark/identify
* how the file was created
*/
#define NDDS_Transport_FILE_SIGNATURE_MAX_LEN (256)
/* The NDDS_Transport_RecvResource represents the state needed to receive
* information to a given address/port. It is intended to be defined
* by each transport plugin implementation. In the case of UDP the
* NDDS_Transport_RecvResource would wrap a receive socket bound to
* that port.
*
* NDDS_Transport_RecvResource_FILE is created by the operation
* NDDS_Transport_FILE_create_recvresource_rrEA()
*/
struct NDDS_Transport_RecvResource_FILE {
/* The file associated with the resource. It is kept open in read mode */
FILE *_file;
/* The port number associated with the resource */
int _portNum;
int _fileDescriptor;
int _receiveMessageCount;
};
/* The NDDS_Transport_SendResource represents the state needed to send
* information to a given address/port. It is intended to be defined
* by each transport plugin implementation. In the case of UDP the
* NDDS_Transport_SendResource would wrap a send socket.
*
* NDDS_Transport_SendResource_FILE is created by the operation
* NDDS_Transport_FILE_create_sendresource_rrEA()
*/
struct NDDS_Transport_SendResource_FILE {
/* The destination port number */
int _portNum;
/* The destination address */
NDDS_Transport_Address_t _address;
/* The file name associated with the resource */
char _fileName[NDDS_TRANSPORT_FILE_MAX_FILEPATH_LEN];
int _sendMessageCount;
};
/* The NDDS_Transport_Plugin structure is intended to be implemented in
* a different way by each transport plugin implementation.
*
* NDDS_Transport_Pugin_FILE represents the state of the transport as it
* it instantiated. It contains any necessary resources that would
* be required to create send and receive resources.
*
* NDDS_Transport_Pugin_FILE must extend the NDDS_Transport_Plugin structure
* by including it as its fist member with the conventional name "_parent"
*
*/
struct NDDS_Transport_FILE {
NDDS_Transport_Plugin parent; /* must be first entry! */
struct NDDS_Transport_FILE_Property_t _property;
char *_buffer;
};
/* ================================================================= */
/* Debugging utilities */
/* ================================================================= */
/* ----------------------------------------------------------------- */
/* Test whether the transport us enabled logging at level 1 */
#define NDDS_Transport_Log1Enabled(self) ( self->_property.trace_level >= 1)
#define NDDS_Transport_Log2Enabled(self) ( self->_property.trace_level >= 2)
/* ----------------------------------------------------------------- */
/* Conditionally Log a message id the transport us enabled logging at level 1 */
#define NDDS_Transport_Log0printf printf
#define NDDS_Transport_Log1print(self, message) \
if ( NDDS_Transport_Log1Enabled(self) ) printf("%s: %s\n", METHOD_NAME, message);
#define NDDS_Transport_Log2print(self, message) \
if ( NDDS_Transport_Log2Enabled(self) ) printf("%s: %s\n", METHOD_NAME, message);
/* ----------------------------------------------------------------- */
/* Utility function to print NDDS_Transport_Address_t and NDDS_Transport_Port_t
*/
static
void NDDS_Transport_FILE_print_address(
const NDDS_Transport_Address_t *address_in,
const NDDS_Transport_Port_t port_in,
int verbosity )
{
unsigned const char *addressBytes = address_in->network_ordered_value;
if ( port_in != -1 ) {
NDDS_Transport_Log0printf("port= %d, ", port_in);
}
NDDS_Transport_Log0printf("address= %d.%d.%d.%d",
addressBytes[12], addressBytes[13], addressBytes[14], addressBytes[15]);
if ( verbosity >= 2 ) {
char ifaddr[256];
NDDS_Transport_Address_to_string(address_in, ifaddr, 256);
NDDS_Transport_Log0printf(" (%s)\n", ifaddr);
} else {
NDDS_Transport_Log0printf("\n");
}
}
/* ----------------------------------------------------------------- */
/* Member function to retrieve the directoryRoot where to put the files used
* to write the data sent by the transport.
*/
const char *NDDS_Transport_FILE_getdirname(
const struct NDDS_Transport_FILE *me)
{
return me->_property.directoryRoot;
}
/* ----------------------------------------------------------------- */
/* Utility function to construct the filename that will be read by
* the transport when receiving on a port.
*/
void NDDS_Transport_FILE_getfilename_for_port(
const struct NDDS_Transport_FILE *me,
char *fname_out,
int fname_out_len,
const NDDS_Transport_Port_t port_in)
{
const char *METHOD_NAME="NDDS_Transport_FILE_getfilename_for_port";
if ( strlen(NDDS_Transport_FILE_getdirname(me)) + 16 >= fname_out_len ) {
NDDS_Transport_Log0printf("%s: %s\n", METHOD_NAME, "fname_out is not big enough for filename");
}
sprintf(fname_out, "%s/%s/%d", NDDS_Transport_FILE_getdirname(me), me->_property.address, port_in);
}
/* ----------------------------------------------------------------- */
/* Utility function to construct the filename that will be read by
* the transport when receiving on a port.
*/
void NDDS_Transport_FILE_getfilename_for_address_and_port(
const struct NDDS_Transport_FILE *me,
char *fname_out,
int fname_out_len,
const NDDS_Transport_Address_t *address_in,
const NDDS_Transport_Port_t port_in)
{
const char *METHOD_NAME="NDDS_Transport_FILE_getfilename_for_port";
unsigned const char *addrBytes = address_in->network_ordered_value;
if ( strlen(NDDS_Transport_FILE_getdirname(me)) + 6 >= fname_out_len ) {
NDDS_Transport_Log0printf("%s: %s\n", METHOD_NAME, "fname_out is not big enough for filename");
}
sprintf(fname_out, "%s/%d.%d.%d.%d/%d", NDDS_Transport_FILE_getdirname(me),
addrBytes[12], addrBytes[13], addrBytes[14], addrBytes[15],
port_in);
}
/* ----------------------------------------------------------------- */
/* Utility function to create the directoryRoot that will contain the
* files used by the transport to send/receive date
*/
RTIBool NDDS_Transport_FILE_ensure_directory_exists(const char *path)
{
const char *METHOD_NAME="NDDS_Transport_FILE_ensure_directory_exists";
mode_t mode = S_IRWXU | S_IRWXG | S_IRWXO;
RTIBool returnValue = RTI_TRUE;
// Set the mask for file creation to allow full configuration of permissions
mode_t oldmask = umask(~mode);
if ( mkdir(path, mode) == -1 ) {
if (errno != EEXIST ) {
NDDS_Transport_Log0printf("%s: failed to create directory \"%s\" errno= %d (%s)\n",
METHOD_NAME, path, errno, strerror(errno));
returnValue = RTI_FALSE; // fail
}
}
/* restore mask */
umask(oldmask);
return returnValue;
}
RTIBool NDDS_Transport_FILE_ensure_receive_directory_exists(
struct NDDS_Transport_FILE *me)
{
char directoryPath[NDDS_TRANSPORT_FILE_MAX_FILEPATH_LEN];
char *ptrToBegin, *ptrToEnd;
sprintf(directoryPath, "%s/%s", NDDS_Transport_FILE_getdirname(me), me->_property.address);
ptrToBegin = directoryPath;
while ( (ptrToEnd = strchr(ptrToBegin+1, '/')) != NULL ) {
*ptrToEnd = '\0';
if ( !NDDS_Transport_FILE_ensure_directory_exists(directoryPath) ) {
return RTI_FALSE;
}
*ptrToEnd = '/';
ptrToBegin = ptrToEnd;
}
/* One last one in case directoryPath does not end in '/' */
if ( !NDDS_Transport_FILE_ensure_directory_exists(directoryPath) ) {
return RTI_FALSE;
}
return RTI_TRUE;
}
/* ----------------------------------------------------------------- */
/* When sending a message, the transport writes the corresponding
* bytes to a file. But it puts a 10-Byte header before to frame the message.
*
* This is not strictly required as it would be sufficient to rely
* on the fact the the messages are RTPS messages and have a well-known
* structure. However adding this simplifies the visual inspection
* of the file and makes the transport implementation independent of
* of the fact that it will be used to send only RTPS messages
*
* The 10-byte header introduced around each message is:
* "\nFILE"<lengthOfMessage>"\n" where <lengthOfMessage> is the length of
* the message wrapped by the header expressed as a 4-byte integer in the
* native endianess of the computer that writes the file.
*/
const char *NDDS_Transport_FILE_writeMessageHeaderPREFIX="\nFILE";
const char *NDDS_Transport_FILE_writeMessageHeaderSUFFIX="\n";
/* ----------------------------------------------------------------- */
/* Returns the length of the message header (10 Bytes in our case)
*/
static RTI_INT32 NDDS_Transport_FILE_messageHeaderLength()
{
return ( strlen(NDDS_Transport_FILE_writeMessageHeaderPREFIX)
+ 4 /* length of message */
+ strlen(NDDS_Transport_FILE_writeMessageHeaderSUFFIX));
}
/* ----------------------------------------------------------------- */
/* Write the (10-Byte) message header to the file
*/
static void NDDS_Transport_FILE_writeMessageHeader(FILE *file, int messageLen)
{
fwrite(NDDS_Transport_FILE_writeMessageHeaderPREFIX, 1,
strlen(NDDS_Transport_FILE_writeMessageHeaderPREFIX), file);
fwrite(&messageLen, 4, 1, file);
fwrite(NDDS_Transport_FILE_writeMessageHeaderSUFFIX, 1,
strlen(NDDS_Transport_FILE_writeMessageHeaderSUFFIX), file);
}
/* ----------------------------------------------------------------- */
/* Utility function to read the next message header from the file and
* return the number of bytes of the message that follow the message header.
*
* There are 3 possible return values:
* 0 ==> indicates there is no data in the file beyond the last byte read
* this is normal. Should not be considered an error
*
* -1 ==> indicates an error occurred. For example bytes were read but
* not enough for a complete header or the header signature is wrong
*
* Positive Int ==> indicates success and the return is the size of the
* message that appears in the file right after the header.
*
* The function verifies that the file position is pointing to a valid
* transport message header. If that is not the case the function returns -1 and leaves
* the file position unaltered.
*
* If the file position is pointing is pointing to a message header then the
* function returns the number of bytes belonging to the message
* that follow the message header and leaves the file seek position to
* the next byte after the message header
*/
static RTI_INT32 NDDS_Transport_FILE_readMessageHeader(FILE *file)
{
const char *METHOD_NAME="NDDS_Transport_FILE_readMessageHeader";
char headerBuffer[256];
char *messageSizePtr;
int filePos;
RTI_INT32 headerLength = NDDS_Transport_FILE_messageHeaderLength();
RTI_INT32 bytesRead;
if ( sizeof(headerBuffer) < headerLength) {
NDDS_Transport_Log0printf("%s: header buffer of size %d is too small. It needs to be at least %d bytes\n",
METHOD_NAME, (int)sizeof(headerBuffer), headerLength);
return -1;
}
filePos = ftell(file);
if ( filePos == -1 ) {
NDDS_Transport_Log0printf("%s: failed to get file position\n", METHOD_NAME);
return -1;
}
bytesRead = fread(headerBuffer, 1, headerLength, file);
if ( bytesRead == 0 ) {
/* This may be and EOF or an error. We need to distinguish between the two. */
if ( feof(file) ) {
/* End of file was reached. It just indicates there is no new data */
/* Important: Clear the EOF "error" otherwise subsequent reads will fail */
clearerr(file);
return 0;
} else {
/* This is a real error */
NDDS_Transport_Log0printf("%s: failed, errno= %d (%s)\n", METHOD_NAME, errno, strerror(errno));
return -1;
}
}
if ( bytesRead != headerLength ) {
NDDS_Transport_Log0printf("%s: at file position= %d failed to read %d bytes of header. Got only %d\n",
METHOD_NAME, (int)filePos, headerLength, bytesRead);
fseek(file, filePos, SEEK_SET);
return -1;
}
if ( strncmp (NDDS_Transport_FILE_writeMessageHeaderPREFIX, headerBuffer,
strlen(NDDS_Transport_FILE_writeMessageHeaderPREFIX) ) != 0 ) {
NDDS_Transport_Log0printf("%s: the message does not contain the transport header "
"position = %d\n", METHOD_NAME, (int)filePos);
fseek(file, filePos, SEEK_SET);
return -1;
}
messageSizePtr = ((char *)headerBuffer) + strlen(NDDS_Transport_FILE_writeMessageHeaderPREFIX);
return *(RTI_INT32 *)messageSizePtr;
}
/* ----------------------------------------------------------------- */
/*
* This function reads the next message from the file.
* The FILE position must be pointing to a transport message header.
* If this is not the case the function will return -1 and leave
* the file position unaltered
*
* On input:
* outBuffer - points to an allocated buffer to receive the message body
* outBufferLen - contains the size in bytes of outBuffer.
*
* On output:
* outBuffer - is filled with the message body on success and left
* unchanged on failure
*
* Return Value: Indicates weather there was an error and if not
* the numbers of bytes copied into the output buffer:
* -1 ==> Indicates an error occurred. For example the caller passed
* outBuffer==NULL
*
* 0 ==> Indicates no data was copied. This can be either a normal
* return or an error:
* - If *neededBufferSize is also set to zero it indicates
* there was no data to read. This is normal
* - If *neededBufferSize is not set to zero it indicates that
* the provided buffer was too small.
*
* Positive Int ==> Indicates a message was read successfully.
* The returned value is the number of bytes in teh message
* which are the ones copied to outBuffer.
* Arguments:
* The function verifies that the next message
* in the file fits in the provided outBuffer
* - If it fits the function :
* a) copies the message body into outBuffer
* (skipping the transport header)
* b) fills the output parameter neededBufferSize with the
* number of bytes copied into outBuffer
* c) moves the file position to point to the transport header
* of the next message
* d) returns the number of bytes copied into outBuffer
* (which differs from the ones read from the file by size
* of the message header)
*
* - If it does not fit, the function:
* a) leaves outBuffer unchanged
* b) fills the output parameter neededBufferSize with the
* number of bytes that would be required to receive the message
* c) leaves the file position unchanged
* d) returns 0.
*
* - The situation where there is no message in the file can be detected
* because the will return 0 with a *neededBufferSize==0
*/
static int NDDS_Transport_FILE_readNextMessage(
struct NDDS_Transport_FILE *me,
FILE *file, int portNum,
char *outBuffer, int outBufferSize, int *messageSize)
{
const char *METHOD_NAME="NDDS_Transport_FILE_readNextMessage";
int filePos;
RTI_INT32 messageLenght;
RTI_INT32 bytesRead;
*messageSize = 0;
if ( outBuffer == NULL ) {
NDDS_Transport_Log0printf("%s (port %d): error specified outBuffer is NULL\n", METHOD_NAME, portNum);
return -1;
}
filePos = ftell(file);
if ( filePos == -1 ) {
NDDS_Transport_Log0printf("%s (port %d): failed to get file position errno=%d (%s)\n",
METHOD_NAME, portNum, errno, strerror(errno));
return -1;
}
messageLenght = NDDS_Transport_FILE_readMessageHeader(file);
/* Check for errors */
if ( messageLenght == -1 ) {
NDDS_Transport_Log0printf("%s (port %d): failed to read transport message header\n", METHOD_NAME, portNum);
return -1;
}
/* Check for no data */
if ( messageLenght == 0 ) {
if ( NDDS_Transport_Log2Enabled(me) ) {
printf("%s (port %d): no data found\n", METHOD_NAME, portNum);
}
return 0;
}
/* Check message fits in output buffer */
if ( outBufferSize < messageLenght ) {
/* It does not fit. This is an error. Print it and revert file position */
fseek(file, filePos, SEEK_SET);
*messageSize = messageLenght;
NDDS_Transport_Log0printf("%s (port %d): buffer of size %d is too small for message. It needs at least %d\n",
METHOD_NAME, portNum, outBufferSize, messageLenght);
return -1;
}
/* All is good, Read the message */
bytesRead = fread(outBuffer, 1, messageLenght, file);
if ( bytesRead != messageLenght ) {
/* There was an error. Leave the file position unchanged */
fseek(file, filePos, SEEK_SET);
NDDS_Transport_Log0printf("%s (port %d): position= %d, read only %d bytes, expected %d bytes\n",
METHOD_NAME, portNum, (int)ftell(file), bytesRead, messageLenght);
return -1;
}
/* Success */
*messageSize = messageLenght;
return messageLenght;
}
/* ----------------------------------------------------------------- */
/* Utility function to check whether the process that created
* the receive resource associated with the file is still running
*
* The first message in the file contains the process id of the
* process that created the file as a result of the call to
* NDDS_Transport_FILE_open_file_for_port() which is called from
* NDDS_Transport_FILE_create_recvresource_rrEA.
*
* This function parses that message to locate the process Id
* and then checks if the process is still running
*/
RTIBool NDDS_Transport_FILE_check_file_in_active_use(
struct NDDS_Transport_FILE *me,
FILE *file, int portNum)
{
RTI_INT32 readResult;
char signatureBuffer[NDDS_Transport_FILE_SIGNATURE_MAX_LEN];
int messageSize;
const char *processIdStr;
char *processIdEndStr;
int processId;
int killReturn;
/* By default we return true indicating file is active. This is safest */
RTIBool result = RTI_TRUE;
const char *METHOD_NAME="NDDS_Transport_FILE_check_file_in_active_use";
/* First get the position so we can restore it prior to return */
int filePos = ftell(file);
if ( filePos == -1 ) {
NDDS_Transport_Log0printf("%s (port %d): file=%p, failed to get file position errno=%d (%s)\n",
METHOD_NAME, portNum, file, errno, strerror(errno));
return -1;
}
if ( fseek(file, 0, SEEK_SET) != 0 ) {
NDDS_Transport_Log0printf("%s (port %d): failed to set file position to begining errno=%d (%s)\n",
METHOD_NAME, portNum, errno, strerror(errno));
return -1;
}
readResult = NDDS_Transport_FILE_readNextMessage(
me, file, portNum,
signatureBuffer, NDDS_Transport_FILE_SIGNATURE_MAX_LEN, &messageSize);
/* Since the file exists, it must have at least the first message.
* if it does not then there is some error.
*/
if ( readResult <= 0 ) {
NDDS_Transport_Log0printf("%s: failed to read first message in file\n", METHOD_NAME);
goto restoreFilePosAndReturn;
}
/* Parse the first message to find the processId*/
processIdStr = strstr(signatureBuffer, "processId=\"");
if ( processIdStr == NULL ) {
NDDS_Transport_Log0printf("%s: failed to find \"processId\" in fist message\n", METHOD_NAME);
NDDS_Transport_Log0printf("..... first message was: %s\n", signatureBuffer);
goto restoreFilePosAndReturn;
}
/* get the PID */
processIdStr += strlen("processId=\"");
processId = strtoul(processIdStr, &processIdEndStr, 10);
if ( *processIdEndStr != '"' ) {
NDDS_Transport_Log0printf("%s: Value of \"processId\" was not followed by \"\n", METHOD_NAME);
NDDS_Transport_Log0printf("..... first message was: %s\n", signatureBuffer);
goto restoreFilePosAndReturn;
}
/* Send signal "0" to the process. Which is not really sending a signal but it can be used
* to test if the process exists.
* If the process does not exist kill sets errno to ESRCH.
*/
if ( kill(processId, 0) != 0 ) {
result = (errno != ESRCH);
}
if ( NDDS_Transport_Log1Enabled(me) ) {
printf("%s: file=%p (port %d) owned by process %d. Process is %s\n",
METHOD_NAME, file, portNum, processId,
result?"ALIVE":"NOT ALIVE");
}
restoreFilePosAndReturn:
fseek(file, 0, SEEK_SET);
return result;
}
/* ----------------------------------------------------------------- */
/*
* Each port maps to a filename. We check if the file already exists
* if it exists we fail. If it does not exist we create it and succeed.
*/
struct NDDS_Transport_RecvResource_FILE *NDDS_Transport_FILE_open_file_for_port(
struct NDDS_Transport_FILE *me,
const NDDS_Transport_Port_t port_in)
{
const char *METHOD_NAME="NDDS_Transport_FILE_open_file_for_port";
char fileName[256];
char tinfo[NDDS_Transport_FILE_SIGNATURE_MAX_LEN];
FILE *file;
struct NDDS_Transport_RecvResource_FILE *recvResourceStruct;
int tInfoBytes;
NDDS_Transport_FILE_getfilename_for_port(me, fileName, 256, port_in);
file = fopen(fileName, "r");
/* file != NULL indicates the file already exists */
if ( file != NULL ) {
if ( NDDS_Transport_Log1Enabled(me) ) {
printf("%s: file '%s' already exists\n", METHOD_NAME, fileName);
}
/* Check if the owing PID is still alive. If not then cleanup the content and
* reuse it.
*/
if ( NDDS_Transport_FILE_check_file_in_active_use(me, file, port_in)) {
if ( NDDS_Transport_Log1Enabled(me) ) {
printf("%s: file '%s' actively being used\n", METHOD_NAME, fileName);
}
fclose(file);
return NULL;
}
/* Else. File exists and not in active. Reuse it */
if ( NDDS_Transport_Log1Enabled(me) ) {
printf("%s: file '%s' not actively being used. Reclaiming it.\n", METHOD_NAME, fileName);
}
fclose(file);
}
/* Either the file did not exist or else the owning process is no longer active
* either way we open the file (wiping any contents if the file existed) and
* initialize the to be used by this process
* */
file = fopen(fileName, "wb+");
if ( file == NULL ) {
/* Failed to create a file that did not exist. This should not happen */
NDDS_Transport_Log0printf("%s: Error failed to create file '%s' errno= %d (%s)\n",
METHOD_NAME, fileName, errno, strerror(errno));
return NULL;
}
/* We successfully opened the file. Write a HEADER to mark the file and the owner */
sprintf(tinfo, "transportClass=\"%d\";transportName=\"%s\";address=\"%s\";portNum=\"%d\";"
"fileName=\"%s\";processId=\"%d\"",
NDDS_TRANSPORT_CLASSID_FILE, NDDS_TRANSPORT_FILE_CLASS_NAME,
me->_property.address, port_in,
fileName, RTIOsapiProcess_getId());
tInfoBytes = strlen(tinfo);
NDDS_Transport_FILE_writeMessageHeader(file, tInfoBytes);
/* Write the initial message containing file details */
fprintf(file, "%s", tinfo);
/* In principle we could reopen file as read-only because from not on we will only
* fread() from it. However we cannot because we use use lockf() to lock the file
* and serialize reads and writes to it. And in some platforms lockf() requires
* the process have write access to the file
*/
/* Rewind to the beginning of the file */
fseek(file, 0, SEEK_SET);
/* Create the receive resource */
recvResourceStruct = (struct NDDS_Transport_RecvResource_FILE *)calloc(1, sizeof(*recvResourceStruct));
recvResourceStruct->_portNum = port_in;
recvResourceStruct->_file = file;
recvResourceStruct->_fileDescriptor = fileno(file);
if ( NDDS_Transport_Log1Enabled(me) ) {
printf("%s (port %d): initialized file=%p, descriptor=%d, fileName: \"%s\"\n",
METHOD_NAME, port_in, recvResourceStruct->_file,
recvResourceStruct->_fileDescriptor, fileName);
}
return recvResourceStruct;
}
/* ----------------------------------------------------------------- */
/*i \ingroup NDDS_Transport_FILE
@brief Validate properties
*/
RTI_INT32 NDDS_Transport_FILE_Property_verify(
const struct NDDS_Transport_FILE_Property_t *property )
{
RTI_INT32 ok = 1;
const char *const METHOD_NAME = "NDDS_Transport_FILE_Property_verify";
if (property == NULL) {
NDDS_Transport_Log0printf("%s: Error, NULL property\n", METHOD_NAME);
return 0;
}
ok = NDDS_Transport_Property_verify(&property->parent);
if (property->parent.classid != NDDS_TRANSPORT_CLASSID_FILE) {
NDDS_Transport_Log0printf("%s: %s\n", METHOD_NAME, "classid is incorrect");
ok = 0;
}
if (property->parent.address_bit_count != NDDS_TRANSPORT_FILE_ADDRESS_BIT_COUNT) {
NDDS_Transport_Log0printf("%s: %s\n", METHOD_NAME, "address_bit_count is incorrect");
ok = 0;
}
if (property->received_message_count_max < 1) {
NDDS_Transport_Log0printf("%s: %s\n", METHOD_NAME, "received_message_count_max < 1");
ok = 0;
}
if (property->receive_buffer_size < property->parent.message_size_max ) {
NDDS_Transport_Log0printf("%s: %s\n", METHOD_NAME, "receive_buffer_size < message_size_max");
ok = 0;
}
return ok;
}
/* ----------------------------------------------------------------- */
/*i \ingroup NDDS_Transport_FILE
@brief Send a message over the transport-plugin.
*/
static
RTI_INT32 NDDS_Transport_FILE_send(
NDDS_Transport_Plugin *self,
const NDDS_Transport_SendResource_t *sendresource_in,
const NDDS_Transport_Address_t *dest_address_in,
const NDDS_Transport_Port_t dest_port_in,
RTI_INT32 transport_priority_in,
const NDDS_Transport_Buffer_t buffer_in[],
RTI_INT32 buffer_count_in,
void *reserved )
{
const char *METHOD_NAME = "NDDS_Transport_FILE_send";
struct NDDS_Transport_FILE *me = (struct NDDS_Transport_FILE *)self;
struct NDDS_Transport_SendResource_FILE *sendResourceStruct =
(struct NDDS_Transport_SendResource_FILE *)*sendresource_in;
int i = 0, bytesToSend = 0;
RTI_INT32 returnValue = 0; /* Indicates error */
/* Verify pre-conditions */
if ( me == NULL || buffer_in == NULL || buffer_count_in <= 0
|| (*sendresource_in == NULL) || dest_address_in == NULL ) {
NDDS_Transport_Log0printf("%s: RTIOsapiSemaphore_give error\n", METHOD_NAME);
return returnValue;
}
REDABufferArray_getSize(&bytesToSend, buffer_in, buffer_count_in);
if ( NDDS_Transport_Log2Enabled(me) ) {
printf("%s: sending %d bytes using resource %p to destination:\n",
METHOD_NAME, bytesToSend, sendResourceStruct);
NDDS_Transport_FILE_print_address(dest_address_in, dest_port_in, me->_property.trace_level);
}
/* First check the file exists */
FILE *file = fopen(sendResourceStruct->_fileName, "rb+");
if ( file == NULL ) {
/* This is normal. Indicates that there is no receiver at a particular address/port
* it may indicate that discovery is sending to a port that is not there, or that
* the application that was receiving data is no longer there
*/
if ( NDDS_Transport_Log2Enabled(me) ) {
printf("%s: file \"%s\" does not exist\n", METHOD_NAME, sendResourceStruct->_fileName);
}
return returnValue;
}
/* Now we know the file exists, reopen for writing */
file = freopen ( NULL, "ab", file);
if ( file == NULL ) {
NDDS_Transport_Log0printf("%s: error opening file for write filename= \"%s\" errno= %d (%s)\n", METHOD_NAME,
sendResourceStruct->_fileName, errno, strerror(errno));
goto doneClose;
}
/**** After this point we have to return via "goto doneClose" to ensure we close the file ****/
/* Lock the file to make sure there is only one application writing to it */
int fd = fileno(file);
if ( fd == -1 ) {
NDDS_Transport_Log0printf("%s: error in fileno. filename= \"%s\" errno= %d (%s)\n", METHOD_NAME,
sendResourceStruct->_fileName, errno, strerror(errno));
}
/* This blocks until file can be locked. Use F_TLOCK to just test */
if ( lockf(fd, F_LOCK, 0) == -1 ) { /* zero offset indicates lock whole file */
NDDS_Transport_Log0printf("%s: error locking filename= \"%s\" fd= %d, errno= %d (%s)\n", METHOD_NAME,
sendResourceStruct->_fileName, fd, errno, strerror(errno));
goto doneClose;
}
/* File successfully locked. */
/**** After this point we have to return via "goto doneUnlock" to ensure we release the lock ****/
/* Write a TransportMessageHeader that frames the packet to send (This is similar intent to the
* UDP/IP header that the UDP transport puts around each message
* '\n' 'F' 'I' 'F' '0' <messageSize> '\n'
*/
NDDS_Transport_FILE_writeMessageHeader(file, bytesToSend);
/* Write bytes to the end of the file */
for (i = 0; i < buffer_count_in; ++i) { /* write data from each iovec */
if ( fwrite(buffer_in[i].pointer, 1, buffer_in[i].length, file) != buffer_in[i].length ) {
NDDS_Transport_Log0printf("%s: error writing to file filename= \"%s\" errno= %d (%s)\n", METHOD_NAME,
sendResourceStruct->_fileName, errno, strerror(errno));
goto doneUnlock;
}
}
++sendResourceStruct->_sendMessageCount;
if ( NDDS_Transport_Log2Enabled(me) ) {
printf("%s: sent message count=%d of %d bytes to destination: ",
METHOD_NAME, sendResourceStruct->_sendMessageCount, bytesToSend);
NDDS_Transport_FILE_print_address(dest_address_in, dest_port_in, me->_property.trace_level);
}
returnValue = 1; /* Indicates success */
doneUnlock:
if ( lockf(fd, F_ULOCK, 0) == -1 ) { /* zero offset indicates lock whole file */
NDDS_Transport_Log0printf("%s: error unlocking filename= \"%s\" errno= %d (%s)\n", METHOD_NAME,
sendResourceStruct->_fileName, errno, strerror(errno));
}
doneClose:
fclose(file);
return returnValue;
}
/* ----------------------------------------------------------------- */
/*i \ingroup NDDS_Transport_FILE
@brief Called to receive messages from a ReceiveResource.
According to the API this function should block until there is data
to return. To keep thisn simple in this example rather than block
the function polls the file each 1 second until it gets new data.
*/
static
RTI_INT32 NDDS_Transport_FILE_receive_rEA(
NDDS_Transport_Plugin *self,
NDDS_Transport_Message_t *message_out,
const NDDS_Transport_Buffer_t *buffer_in,
const NDDS_Transport_RecvResource_t *recvresource_in,
void *reserved )
{
struct NDDS_Transport_FILE *me = (struct NDDS_Transport_FILE *)self;
const char *METHOD_NAME = "NDDS_Transport_FILE_receive_rEA";
struct NDDS_Transport_RecvResource_FILE *receiveResourceStruct
= (struct NDDS_Transport_RecvResource_FILE *)*recvresource_in;
int bytesNeededToRead = 0;
int bytesCopiedToBuffer = 0;
RTI_INT32 returnErrorValue = 0; /* Indicates an error return */
RTI_INT32 returnSuccessValue = 1; /* Indicates a successful return */
/* Verify pre-conditions */
if ( me == NULL || message_out == NULL
|| receiveResourceStruct == NULL || buffer_in == NULL ) {
NDDS_Transport_Log0printf("%s: precondition error\n", METHOD_NAME);
return returnErrorValue;
}
if ( NDDS_Transport_Log2Enabled(me) ) {
printf("%s (port %d): file= %p, position= %d. Receive buffer can hold %d bytes\n",
METHOD_NAME, receiveResourceStruct->_portNum, receiveResourceStruct->_file,
(int)ftell(receiveResourceStruct->_file),
buffer_in->length );
}
while ( bytesCopiedToBuffer == 0 ) {
if ( NDDS_Transport_Log2Enabled(me) ) {
printf("%s (port %d): Waiting for message (received so far %d), file= %p, position= %d...\n",
METHOD_NAME, receiveResourceStruct->_portNum,
receiveResourceStruct->_receiveMessageCount,
receiveResourceStruct->_file,
(int)ftell(receiveResourceStruct->_file));
}
/* BEGIN of FILE LOCK ------------->>> */
/* This blocks until file can be locked. Use F_TLOCK to just test */
if ( lockf(receiveResourceStruct->_fileDescriptor, F_LOCK, 0) == -1 ) { /* zero offset indicates lock whole file */
NDDS_Transport_Log0printf("%s (port %d): error locking file fd= %d, errno= %d (%s)\n", METHOD_NAME,
receiveResourceStruct->_portNum, receiveResourceStruct->_fileDescriptor,
errno, strerror(errno));
return returnErrorValue;
}
bytesCopiedToBuffer = NDDS_Transport_FILE_readNextMessage(
me,
receiveResourceStruct->_file,
receiveResourceStruct->_portNum,
buffer_in->pointer, buffer_in->length,
&bytesNeededToRead);
if ( lockf(receiveResourceStruct->_fileDescriptor, F_ULOCK, 0) == -1 ) { /* zero offset indicates lock whole file */
NDDS_Transport_Log0printf("%s (port %d): error unlocking file errno= %d (%s)\n", METHOD_NAME,
receiveResourceStruct->_portNum, errno, strerror(errno));
}
/* END of FILE LOCK -------------<<< */
if ( NDDS_Transport_Log2Enabled(me) ) {
printf("%s (port %d): NDDS_Transport_FILE_readNextMessage returned %d, bytesNeeded= %d\n",
METHOD_NAME, receiveResourceStruct->_portNum, bytesCopiedToBuffer, bytesNeededToRead);
}
/* Check for errors */
if ( bytesCopiedToBuffer == -1) {
NDDS_Transport_Log0printf("%s (%d): unknown error\n", METHOD_NAME, receiveResourceStruct->_portNum);
return returnErrorValue;
}
/* Check if there was something copied to buffer */
if ( bytesCopiedToBuffer == 0 ) {
if (bytesNeededToRead == 0) {
/* There was no data. Sleep a bit and try again */
sleep(1);
continue;
}
else {
/* Indicates buffer was not big enough to copy message */
NDDS_Transport_Log0printf("%s (port %d): buffer of size %d is too small, it needs %d\n",
METHOD_NAME, receiveResourceStruct->_portNum,
buffer_in->length, bytesNeededToRead);
return returnErrorValue;
}
}
}
/* If we exit the loop here it is because we copied a message
* to the buffer_in->pointer
*/
message_out->buffer.pointer = buffer_in->pointer;
message_out->buffer.length = bytesCopiedToBuffer;
/* The loaned_buffer_param is only needed if the transport is zero-copy and
* wants to loan a buffer to the middleware. In that case it should save in
* loaned_buffer_param any information needed to retuer that loan when the
* middleware calls return_loaned_buffer_rEA().
* The FileTransport does not loan buffers so we can leave this unset or
* put some arbitrary value
*/
message_out->loaned_buffer_param = (void *)-1;
++receiveResourceStruct->_receiveMessageCount;
if ( NDDS_Transport_Log2Enabled(me) ) {
printf("%s (port %d): received message count=%d of %d bytes\n",
METHOD_NAME, receiveResourceStruct->_portNum,
receiveResourceStruct->_receiveMessageCount, bytesCopiedToBuffer );
}
return returnSuccessValue;
}
/* ----------------------------------------------------------------- */
/*i \ingroup NDDS_Transport_FILE
@brief Returns a loaned buffer.
*/
static
void NDDS_Transport_FILE_return_loaned_buffer_rEA(
NDDS_Transport_Plugin *self,
const NDDS_Transport_RecvResource_t *recvresource_in,
NDDS_Transport_Message_t *message_in,
void *reserved)
{
/* This transport does not loan buffers on the receive_rEA() call
* so there is really nothing to do here
*/
message_in->loaned_buffer_param = NULL;
}
/* ----------------------------------------------------------------- */
/*i \ingroup NDDS_Transport_FILE
@brief Unblocks a receive thread.
*/
static
RTI_INT32 NDDS_Transport_FILE_unblock_receive_rrEA(
NDDS_Transport_Plugin *self,
const NDDS_Transport_RecvResource_t *recvresource_in,
void *reserved )
{
const char *METHOD_NAME="NDDS_Transport_FILE_unblock_receive_rrEA";
struct NDDS_Transport_RecvResource_FILE *recvRes =
(struct NDDS_Transport_RecvResource_FILE *)*recvresource_in;
RTI_INT32 ok = 0;
if (self == NULL || NDDS_Transport_Plugin_is_polled(self) ) {
NDDS_Transport_Log0printf("%s: cannot unblock polled transport\n", METHOD_NAME);
goto done;
}
NDDS_Transport_FILE_writeMessageHeader(recvRes->_file, 0);
ok = 1;
done:
return ok;
}
/* ----------------------------------------------------------------- */
/*i \ingroup NDDS_Transport_FILE
@brief Creates a ReceiveResource for a given port with a given
transport_priority.
Doesn't support multicast.
*/
static
RTI_INT32 NDDS_Transport_FILE_create_recvresource_rrEA(
NDDS_Transport_Plugin *self,
NDDS_Transport_RecvResource_t *recvresource_out,
NDDS_Transport_Port_t *dest_port_inout,
const NDDS_Transport_Address_t *multicast_address_in,
RTI_INT32 reserved )
{
const char *METHOD_NAME="NDDS_Transport_FILE_create_recvresource_rrEA";
struct NDDS_Transport_FILE *me = (struct NDDS_Transport_FILE *) self;
if (*dest_port_inout == NDDS_TRANSPORT_PORT_INVALID) {
char str[256];
sprintf(str, "invalid port specified: %d", *dest_port_inout);
NDDS_Transport_Log1print(me, str);
return 0;
}
/* FileTransport does not support multicast. Fail if a multicast address is
* specified
*/
if ( multicast_address_in != NULL ) {
NDDS_Transport_Log1print(me, "transport does not support multicast. ");
if ( NDDS_Transport_Log2Enabled(me) ) {
NDDS_Transport_FILE_print_address(multicast_address_in, *dest_port_inout,
me->_property.trace_level);
}
return 0;
}
/* Each port maps to a filename. We check if the file already exists
* if it exists we fail. If it does not exist we create it and succeed.
*/
*recvresource_out = NDDS_Transport_FILE_open_file_for_port(me, *dest_port_inout);
if ( *recvresource_out == NULL) {
NDDS_Transport_Log0printf("%s: failed to create receive resource for address= \"%s\", port= %d\n",
METHOD_NAME, me->_property.address, *dest_port_inout);
return 0;
}
/* Success */
if ( NDDS_Transport_Log1Enabled(me) ) {
printf("%s: created receive resource for address= \"%s\", port= %d\n",
METHOD_NAME, me->_property.address, *dest_port_inout);
}
return 1;
}
/* ----------------------------------------------------------------- */
/*i \ingroup NDDS_Transport_FILE
@brief Try to share a ReceiveResource for receiving messages on a
port.
Doesn't support multicast.
Each port maps to a different file so only suceed if the same port
is specified.
*/
static
RTI_INT32 NDDS_Transport_FILE_share_recvresource_rrEA(
NDDS_Transport_Plugin *self,
const NDDS_Transport_RecvResource_t *recvresource_in,
const NDDS_Transport_Port_t recv_port_in,
const NDDS_Transport_Address_t *multicast_address_in,
RTI_INT32 reserved )
{
const char *METHOD_NAME="NDDS_Transport_FILE_share_recvresource_rrEA";
const struct NDDS_Transport_FILE *me = (struct NDDS_Transport_FILE *) self;
struct NDDS_Transport_RecvResource_FILE *recvRes =
(struct NDDS_Transport_RecvResource_FILE *)*recvresource_in;
/* Transport does nor support multicast */
if (multicast_address_in != NULL) {
return 0;
}
/* This transport can only use a NDDS_Transport_RecvResource_t for a single port
* so this function can only return TRUE if the requested port matches the one
* in the NDDS_Transport_RecvResource_t
*/
if ( recvRes->_portNum != recv_port_in ) {
if ( NDDS_Transport_Log1Enabled(me) ) {
printf("%s: resource at port '%d' not reused for port %d\n",
METHOD_NAME, recvRes->_portNum , recv_port_in);
}
return 0;
}
/* It is exactly the same port and we only have one address per transport
* so you can reuse
*/
if ( NDDS_Transport_Log1Enabled(me) ) {
printf("%s: resource at port '%d' reused for port '%d'\n",
METHOD_NAME, recvRes->_portNum, recv_port_in);
}
return 1;
}
/* ----------------------------------------------------------------- */
/*i \ingroup NDDS_Transport_FILE
@brief Unshares a recvresource.
*/
static
RTI_INT32 NDDS_Transport_FILE_unshare_recvresource_rrEA(
NDDS_Transport_Plugin *self,
const NDDS_Transport_RecvResource_t *recvresource_in,
const NDDS_Transport_Port_t dest_port_in,
const NDDS_Transport_Address_t *multicast_address_in,
RTI_INT32 reserved )
{
const char *METHOD_NAME="NDDS_Transport_FILE_unshare_recvresource_rrEA";
const struct NDDS_Transport_FILE *me = (struct NDDS_Transport_FILE *) self;
NDDS_Transport_Log1print(me, "");
/* If we had done something special to share a resource on a prior call
* to NDDS_Transport_FILE_share_recvresource_rrEA() we would undo that
* here. Since we did not this function is a NOOP
*/
return 1;
}
/* ----------------------------------------------------------------- */
/*i \ingroup NDDS_Transport_FILE
@brief Creates a SendResource for the given destination address
and port.
*/
static
RTI_INT32 NDDS_Transport_FILE_create_sendresource_srEA(
NDDS_Transport_Plugin *self,
NDDS_Transport_SendResource_t *sendresource_out,
const NDDS_Transport_Address_t *dest_address_in,
const NDDS_Transport_Port_t dest_port_in,
RTI_INT32 transport_priority_in )
{
const char *METHOD_NAME="NDDS_Transport_FILE_create_sendresource_srEA";
const struct NDDS_Transport_FILE *me = (struct NDDS_Transport_FILE *) self;
struct NDDS_Transport_SendResource_FILE *sendResourceStruct;
*sendresource_out = NULL;
/* multicast not supported */
if ( NDDS_Transport_Address_is_multicast(dest_address_in) ) {
if ( NDDS_Transport_Log1Enabled(me) ) {
printf("%s: specified address is multicast and transport does not support multicast: ",
METHOD_NAME);
NDDS_Transport_FILE_print_address(dest_address_in, dest_port_in, me->_property.trace_level);
}
return 0;
}
sendResourceStruct = (struct NDDS_Transport_SendResource_FILE *)
calloc(1, sizeof(*sendResourceStruct));
NDDS_Transport_Address_copy(&sendResourceStruct->_address, dest_address_in);
sendResourceStruct->_portNum = dest_port_in;
NDDS_Transport_FILE_getfilename_for_address_and_port(me, sendResourceStruct->_fileName,
NDDS_TRANSPORT_FILE_MAX_FILEPATH_LEN, dest_address_in, dest_port_in);
if ( NDDS_Transport_Log1Enabled(me) ) {
printf("%s: Send resource %p (file =\"%s\") created for ",
METHOD_NAME, sendResourceStruct, sendResourceStruct->_fileName);
NDDS_Transport_FILE_print_address(dest_address_in, dest_port_in, 2);
}
*sendresource_out = sendResourceStruct;
return 1;
}
/* ----------------------------------------------------------------- */
/*i \ingroup NDDS_Transport_FILE
@brief Try to share a SendResource for sending messages to a
destination.
*/
static
RTI_INT32 NDDS_Transport_FILE_share_sendresource_srEA(
NDDS_Transport_Plugin *self,
const NDDS_Transport_SendResource_t *sendresource_in,
const NDDS_Transport_Address_t *dest_address_in,
const NDDS_Transport_Port_t dest_port_in,
RTI_INT32 transport_priority_in )
{
const char *METHOD_NAME="NDDS_Transport_FILE_share_sendresource_srEA";
const struct NDDS_Transport_FILE *me = (struct NDDS_Transport_FILE *) self;
struct NDDS_Transport_SendResource_FILE *sendResourceStruct =
(struct NDDS_Transport_SendResource_FILE *)*sendresource_in;
/* multicast not supported */
if ( NDDS_Transport_Address_is_multicast(dest_address_in) ) {
return 0;
}
/* This transport can only share a NDDS_Transport_SendResource_t if the destination
* address and port number match
*/
if ( ( sendResourceStruct->_portNum != dest_port_in )
|| (!NDDS_Transport_Address_is_equal(&sendResourceStruct->_address, dest_address_in)) ) {
if ( NDDS_Transport_Log2Enabled(me) ) {
printf("%s: Send resource (%p) not reused for:\n", METHOD_NAME, sendResourceStruct);
NDDS_Transport_FILE_print_address(dest_address_in, dest_port_in, me->_property.trace_level);
}
return 0;
}
if ( NDDS_Transport_Log1Enabled(me) ) {
printf("%s: Send resource (%p) reused for \n", METHOD_NAME, sendResourceStruct);
NDDS_Transport_FILE_print_address(dest_address_in, dest_port_in, me->_property.trace_level);
}
/* OK. Reuse */
return 1;
}
/* ----------------------------------------------------------------- */
/*i \ingroup NDDS_Transport_FILE
@brief Unshares a sendresource.
*/
static
RTI_INT32 NDDS_Transport_FILE_unshare_sendresource_srEA(
NDDS_Transport_Plugin *self,
const NDDS_Transport_SendResource_t *sendresource_in,
const NDDS_Transport_Address_t *dest_address_in,
const NDDS_Transport_Port_t dest_port_in,
RTI_INT32 transport_priority_in )
{
const char *METHOD_NAME="NDDS_Transport_FILE_unshare_sendresource_srEA";
const struct NDDS_Transport_FILE *me = (struct NDDS_Transport_FILE *) self;
/* If we had done something special to share a resource on a prior call
* to NDDS_Transport_FILE_share_sendresource_srEA() we would undo that
* here. Since we did not this function is a NOOP
*/
if ( NDDS_Transport_Log1Enabled(me) ) {
struct NDDS_Transport_SendResource_FILE *sendResourceStruct =
(struct NDDS_Transport_SendResource_FILE *)*sendresource_in;
printf("%s: Send resource (%p) unshared for: \n", METHOD_NAME, sendResourceStruct);
NDDS_Transport_FILE_print_address(dest_address_in, dest_port_in, me->_property.trace_level);
}
/* no op */
return 1;
}
/* ----------------------------------------------------------------- */
/*i \ingroup NDDS_Transport_FILE
@brief Destroys send or receive resource.
*/
static
void NDDS_Transport_FILE_destroy_sendresource_srEA(
NDDS_Transport_Plugin *self,
const NDDS_Transport_SendResource_t *resource_in )
{
const char *METHOD_NAME="NDDS_Transport_FILE_destroy_sendresource_srEA";
const struct NDDS_Transport_FILE *me = (struct NDDS_Transport_FILE *) self;
struct NDDS_Transport_SendResource_FILE *sendResourceStruct
= (struct NDDS_Transport_SendResource_FILE *)resource_in;
if ( NDDS_Transport_Log1Enabled(me) ) {
printf("%s: Send resource (%p) for port %d destroyed: ",
METHOD_NAME, sendResourceStruct, sendResourceStruct->_portNum);
NDDS_Transport_FILE_print_address(&sendResourceStruct->_address, sendResourceStruct->_portNum,
me->_property.trace_level);
}
free(sendResourceStruct);
}
/* ----------------------------------------------------------------- */
/*i \ingroup NDDS_Transport_FILE
@brief Destroys send or receive resource.
*/
static
void NDDS_Transport_FILE_destroy_recvresource_rrEA(
NDDS_Transport_Plugin *self,
const NDDS_Transport_RecvResource_t *resource_in )
{
const char *METHOD_NAME="NDDS_Transport_FILE_destroy_recvresource_rrEA";
const struct NDDS_Transport_FILE *me = (struct NDDS_Transport_FILE *) self;
struct NDDS_Transport_RecvResource_FILE *recvResourceStruct =
(struct NDDS_Transport_RecvResource_FILE *)resource_in;
if ( NDDS_Transport_Log1Enabled(me) ) {
printf("%s: Receive resource (%p) for port %d destroyed\n",
METHOD_NAME, recvResourceStruct, recvResourceStruct->_portNum);
}
fclose(recvResourceStruct->_file);
free(recvResourceStruct);
}
/* ----------------------------------------------------------------- */
/*i \ingroup NDDS_Transport_FILE
@brief Returns the string class name of the transport.
*/
const char *NDDS_Transport_FILE_get_class_name_cEA(
NDDS_Transport_Plugin *self )
{
const char *METHOD_NAME="NDDS_Transport_FILE_get_class_name_cEA";
const struct NDDS_Transport_FILE *me = (struct NDDS_Transport_FILE *) self;
NDDS_Transport_Log1print(me, NDDS_TRANSPORT_FILE_CLASS_NAME);
return NDDS_TRANSPORT_FILE_CLASS_NAME;
}
/* ----------------------------------------------------------------- */
/*i \ingroup NDDS_Transport_FILE
@brief Converts a Transport-Plugin-specific address string to an
IPv6 address.
*/
RTI_INT32 NDDS_Transport_FILE_string_to_address_cEA(
NDDS_Transport_Plugin *self,
NDDS_Transport_Address_t *address_out,
const char *address_in )
{
const char *METHOD_NAME = "NDDS_Transport_FILE_string_to_address_cEA";
struct NDDS_Transport_FILE *me = (struct NDDS_Transport_FILE *) self;
NDDS_Transport_Log1print(me, "");
if ( address_out == NULL || address_in == NULL) {
printf("%s: precondition error\n", METHOD_NAME);
return 0;
}
if ( NDDS_Transport_Log1Enabled(me) ) {
printf("%s: Conversion of addresses not supported. Requested \"%s\"\n", METHOD_NAME, address_in);
/* NDDS_Transport_FILE_print_address(address_out, -1, 2); */
}
/* Does not support string to IPv6 address conversion */
return 0;
}
/* ----------------------------------------------------------------- */
/*i \ingroup NDDS_Transport_FILE
@brief Returns a list of network interfaces represented by this
transport-plugin instance.
The FILE NIF is represented by the address of this transport plugin
instance.
The FileTransport IPv6 address address is made globally unique
by concatenating:
(
4-bytes: <network address configured by end user>
4 bytes: <RTPS Host Id>, // or IPv4 address
4-bytes: Process Id // Note: could also be <RTPS App Id>
4-bytes: <plugin_address truncated to 4 bytes>
)
So the FILE address uses only the last 12 bytes (96 bits) of the
IPv6 address space.
*/
RTI_INT32 NDDS_Transport_FILE_get_receive_interfaces_cEA(
NDDS_Transport_Plugin *self,
RTI_INT32 *found_more_than_provided_for_out,
RTI_INT32 *interface_reported_count_out,
NDDS_Transport_Interface_t interface_array_inout[],
RTI_INT32 interface_array_size_in )
{
const char *METHOD_NAME = "NDDS_Transport_FILE_get_receive_interfaces_cEA";
struct NDDS_Transport_FILE *me = (struct NDDS_Transport_FILE *) self;
if ( self == NULL || interface_array_size_in < 0 ||
interface_array_inout == NULL || found_more_than_provided_for_out == NULL
|| interface_reported_count_out == NULL ) {
NDDS_Transport_Log0printf("%s: precondition error\n", METHOD_NAME);
return 0;
}
if (interface_array_size_in < 1) {
*found_more_than_provided_for_out = 1;
goto success;
}
*found_more_than_provided_for_out = 0;
/* --- output the interface --- */
*interface_reported_count_out = 1;
interface_array_inout[0].transport_classid = NDDS_TRANSPORT_CLASSID_FILE;
/* Zero bytes */
memset(&interface_array_inout[0].address.network_ordered_value, 0, NDDS_TRANSPORT_ADDRESS_LENGTH);
/* Set the meaningful bytes of the address */
{
struct in_addr ipAddr;
unsigned int ipAddrNetworkOrder;
inet_aton(me->_property.address, &ipAddr);
ipAddrNetworkOrder = ipAddr.s_addr;
interface_array_inout[0].address.network_ordered_value[15] = (ipAddrNetworkOrder )% 256;
interface_array_inout[0].address.network_ordered_value[14] = (ipAddrNetworkOrder >> 8)% 256;
interface_array_inout[0].address.network_ordered_value[13] = (ipAddrNetworkOrder >> 16)% 256;
interface_array_inout[0].address.network_ordered_value[12] = (ipAddrNetworkOrder >> 24)% 256;
}
success:
if ( NDDS_Transport_Log1Enabled(me) ) {
int i;
printf("%s: num receive interfaces: %d\n", METHOD_NAME, *interface_reported_count_out);
for (i=0; i< *interface_reported_count_out; ++i ) {
char ifaddr[256];
NDDS_Transport_Address_to_string(&interface_array_inout[i].address,
ifaddr, 256);
printf(" interface[%d] = \"%s\" (%s)\n", i, me->_property.address, ifaddr);
}
}
return 1;
}
/* ----------------------------------------------------------------- */
/*i \ingroup NDDS_Transport_FILE
@brief Register a callback to be notified of the changes in the
availability of interfaces supported by the plugin.
Doesn't do anything with a listener.
*/
static
RTI_INT32 NDDS_Transport_FILE_register_listener_cEA(
NDDS_Transport_Plugin *self,
NDDS_Transport_Listener *listener )
{
const char *METHOD_NAME = "NDDS_Transport_FILE_register_listener_cEA";
if (self == NULL) {
printf("%s: NULL transport\n", METHOD_NAME);
return 0;
}
/* Transport is static */
return 1;
}
/* ---------------------------------------------------------------------- */
/*i \ingroup NDDS_Transport_FILE
@brief (Destructor) Called to destroy the Transport-Plugin.
@pre No RecvResources or SendResources exist for this transport
@post Transport has been deleted. It should not be used after this call.
Deletes the memory allocated when NDDS_Transport_FILE_new()
was called. Does not take care of deleting any RecvResources or
SendResources associated with the transport. It is the
responsibility NDDS to delete all SendResources and RecvResources
associated with the transport prior to deleting the transport
itself.
*/
static
void NDDS_Transport_FILE_delete_cEA(
NDDS_Transport_Plugin *self,
void *reserved )
{
const char *METHOD_NAME = "NDDS_Transport_FILE_delete_cEA";
struct NDDS_Transport_FILE *me = (struct NDDS_Transport_FILE *)self;
if (me == NULL) {
printf("%s: NULL transport\n", METHOD_NAME);
return;
}
if (me->_buffer != NULL) {
free(me->_buffer);
}
if ( NDDS_Transport_Log1Enabled(me) ) {
printf("%s: Transport (%p) for address %s destroyed\n",
METHOD_NAME, me, me->_property.address);
}
free(me);
}
/* ---------------------------------------------------------------------- */
/*i \ingroup NDDS_Transport_FILE
@brief (Constructor) Create a intra-transport-plugin instance.
*/
NDDS_Transport_Plugin* NDDS_Transport_FILE_newPlugin(
const struct NDDS_Transport_FILE_Property_t *property_in)
{
const char *METHOD_NAME = "NDDS_Transport_FILE_newI";
struct NDDS_Transport_FILE *me = NULL;
const struct NDDS_Transport_FILE_Property_t defaultProp
= NDDS_TRANSPORT_FILE_PROPERTY_DEFAULT;
int bufferSize = 0;
int pid = 0;
/* allocate instance */
me = (struct NDDS_Transport_FILE *)calloc(1, sizeof(*me));
if (me == NULL) {
printf("%s: malloc(%d) failed\n", METHOD_NAME, (int)sizeof(*me));
goto failed;
}
/* Set the property */
if (property_in == NULL) {
me->_property = defaultProp;
} else {
me->_property = *property_in;
}
me->parent.property = (struct NDDS_Transport_Property_t *)&me->_property;
if ( !NDDS_Transport_FILE_Property_verify(&me->_property) ) {
printf("%s: %s\n", METHOD_NAME, "Invalid transport properties.");
goto failed;
}
pid = RTIOsapiProcess_getId();
{
char str[256];
sprintf(str, "pid: %d bound to address: \"%s\"", pid, me->_property.address);
NDDS_Transport_Log1print(me, str);
}
/* Ensure existence of directoryRoot that will contain the files associated with receive resource */
if ( !NDDS_Transport_FILE_ensure_receive_directory_exists(me) ) {
goto failed;
}
/* create receive buffer */
bufferSize = me->_property.receive_buffer_size + NDDS_Transport_FILE_messageHeaderLength();
/* The extra 8 is to compensate for the worst case alignments that are required
* when serializing to the buffer */
me->_buffer = (char *)calloc(1, bufferSize + 8);
if (me->_buffer == NULL) {
printf("%s: RTIOsapiHeap_allocateBuffer semaphore error\n", METHOD_NAME);
goto failed;
}
me->parent.send = NDDS_Transport_FILE_send;
me->parent.receive_rEA = NDDS_Transport_FILE_receive_rEA;
me->parent.return_loaned_buffer_rEA =
NDDS_Transport_FILE_return_loaned_buffer_rEA;
me->parent.unblock_receive_rrEA =
NDDS_Transport_FILE_unblock_receive_rrEA;
me->parent.create_recvresource_rrEA =
NDDS_Transport_FILE_create_recvresource_rrEA;
me->parent.destroy_recvresource_rrEA =
NDDS_Transport_FILE_destroy_recvresource_rrEA;
me->parent.share_recvresource_rrEA =
NDDS_Transport_FILE_share_recvresource_rrEA;
me->parent.unshare_recvresource_rrEA =
NDDS_Transport_FILE_unshare_recvresource_rrEA;
me->parent.create_sendresource_srEA =
NDDS_Transport_FILE_create_sendresource_srEA;
me->parent.destroy_sendresource_srEA =
NDDS_Transport_FILE_destroy_sendresource_srEA;
me->parent.share_sendresource_srEA =
NDDS_Transport_FILE_share_sendresource_srEA;
me->parent.unshare_sendresource_srEA =
NDDS_Transport_FILE_unshare_sendresource_srEA;
me->parent.get_class_name_cEA =
NDDS_Transport_FILE_get_class_name_cEA;
me->parent.string_to_address_cEA =
NDDS_Transport_FILE_string_to_address_cEA;
me->parent.get_receive_interfaces_cEA =
NDDS_Transport_FILE_get_receive_interfaces_cEA;
me->parent.register_listener_cEA =
NDDS_Transport_FILE_register_listener_cEA;
me->parent.delete_cEA = NDDS_Transport_FILE_delete_cEA;
return (NDDS_Transport_Plugin*) me;
failed:
NDDS_Transport_FILE_delete_cEA((NDDS_Transport_Plugin*)me, NULL);
return NULL;
}
NDDS_Transport_Plugin *NDDS_Transport_FILE_create(
NDDS_Transport_Address_t *default_network_address_out,
const struct DDS_PropertyQosPolicy *property_in)
{
struct NDDS_Transport_FILE_Property_t fifoProperty
= NDDS_TRANSPORT_FILE_PROPERTY_DEFAULT;
const struct DDS_Property_t *p;
p = DDS_PropertyQosPolicyHelper_lookup_property((struct DDS_PropertyQosPolicy *)property_in, "address");
if ( p != NULL ) {
strncpy(fifoProperty.address, p->value, NDDS_TRANSPORT_FILE_MAX_ADDR_LEN-1);
fifoProperty.address[NDDS_TRANSPORT_FILE_MAX_ADDR_LEN-1] = '\0';
} else {
char defaultAddress[] = NDDS_TRANSPORT_FILE_ADDRESS_DEFAULT;
strcpy(fifoProperty.address, defaultAddress);
}
p = DDS_PropertyQosPolicyHelper_lookup_property((struct DDS_PropertyQosPolicy *)property_in, "trace_level");
if ( p != NULL ) {
fifoProperty.trace_level = strtoul(p->value, NULL, 10);
} else {
fifoProperty.trace_level = 0;
}
p = DDS_PropertyQosPolicyHelper_lookup_property((struct DDS_PropertyQosPolicy *)property_in, "directory");
if ( p != NULL ) {
strncpy(fifoProperty.directoryRoot, p->value, NDDS_TRANSPORT_FILE_MAX_FILEPATH_LEN-1);
fifoProperty.directoryRoot[NDDS_TRANSPORT_FILE_MAX_FILEPATH_LEN-1] = '\0';
} else {
char defaultDirectoryRoot[] = NDDS_TRANSPORT_FILE_DIRECTORY_ROOT_DEFAULT;
strcpy(fifoProperty.directoryRoot, defaultDirectoryRoot);
}
NDDS_Transport_Plugin *plugin = NDDS_Transport_FILE_newPlugin(&fifoProperty);
return plugin;
}
/* end of $Id: FILE.c,v 1.20 2008/10/22 19:16:46 jim Exp $ */
| c |
rticonnextdds-examples | data/projects/rticonnextdds-examples/custom_transport/c/FileTransport.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.
******************************************************************************/
#include "transport/transport_interface.h"
/* ================================================================= */
/* Intra Process Transport-Plugin */
/* ================================================================= */
#define NDDS_TRANSPORT_CLASSID_FILE (20)
#define NDDS_TRANSPORT_FILE_CLASS_NAME "FileTransport"
/* Indicates the number of bits that are significant to the FIFO
transport. In other words the size of the FileTransport addresses.
We make the FileTrasport use 4-byte addresses like IPv4.
This means that we leave the remaining 96 bits configurable for
a "network" address
*/
#define NDDS_TRANSPORT_FILE_ADDRESS_BIT_COUNT (32)
#define NDDS_TRANSPORT_FILE_PROPERTIES_BITMAP_DEFAULT \
( NDDS_TRANSPORT_PROPERTY_BIT_BUFFER_ALWAYS_LOANED )
#define NDDS_TRANSPORT_FILE_GATHER_SEND_BUFFER_COUNT_MAX_DEFAULT (1024)
#define NDDS_TRANSPORT_FILE_MESSAGE_SIZE_MAX_DEFAULT (9216)
#define NDDS_TRANSPORT_FILE_RECEIVED_MESSAGE_COUNT_MAX_DEFAULT (10)
#define NDDS_TRANSPORT_FILE_TRACE_LEVEL_DEFAULT (1)
#define NDDS_TRANSPORT_FILE_RECEIVE_BUFFER_SIZE_DEFAULT \
(NDDS_TRANSPORT_FILE_RECEIVED_MESSAGE_COUNT_MAX_DEFAULT * \
NDDS_TRANSPORT_FILE_MESSAGE_SIZE_MAX_DEFAULT)
#define NDDS_TRANSPORT_FILE_MAX_ADDR_LEN (32)
#define NDDS_TRANSPORT_FILE_ADDRESS_DEFAULT \
{'1','.','1','.','1','.','1','\0'}
#define NDDS_TRANSPORT_FILE_DIRECTORY_ROOT_DEFAULT \
{'/','t','m','p','/','d','d','s','/','F','i','l','e','T','r','a','n','s','p','o','r','t','\0'}
#define NDDS_TRANSPORT_FILE_MAX_FILEPATH_LEN (128)
struct NDDS_Transport_FILE_Property_t {
/*e @brief Generic properties of all Transport Plugins.
*/
struct NDDS_Transport_Property_t parent;
RTI_INT32 received_message_count_max;
RTI_INT32 receive_buffer_size;
RTI_INT32 trace_level;
char address[NDDS_TRANSPORT_FILE_MAX_ADDR_LEN];
char directoryRoot[NDDS_TRANSPORT_FILE_MAX_FILEPATH_LEN];
};
#define NDDS_TRANSPORT_FILE_PROPERTY_DEFAULT { \
{ NDDS_TRANSPORT_CLASSID_FILE, \
NDDS_TRANSPORT_FILE_ADDRESS_BIT_COUNT, \
NDDS_TRANSPORT_FILE_PROPERTIES_BITMAP_DEFAULT, \
NDDS_TRANSPORT_FILE_GATHER_SEND_BUFFER_COUNT_MAX_DEFAULT, \
NDDS_TRANSPORT_FILE_MESSAGE_SIZE_MAX_DEFAULT, \
NULL, 0, /* allow_interfaces_list */ \
NULL, 0, /* deny_interfaces_list */ \
NULL, 0, /* allow_multicast_interfaces_list */ \
NULL, 0, /* deny_multicast_interfaces_list */ \
}, \
NDDS_TRANSPORT_FILE_RECEIVED_MESSAGE_COUNT_MAX_DEFAULT, \
NDDS_TRANSPORT_FILE_RECEIVE_BUFFER_SIZE_DEFAULT, \
NDDS_TRANSPORT_FILE_TRACE_LEVEL_DEFAULT, \
NDDS_TRANSPORT_FILE_ADDRESS_DEFAULT, \
NDDS_TRANSPORT_FILE_DIRECTORY_ROOT_DEFAULT \
}
NDDS_Transport_Plugin* NDDS_Transport_FILE_newPlugin(
const struct NDDS_Transport_FILE_Property_t *property_in);
struct DDS_PropertyQosPolicy;
NDDS_Transport_Plugin *NDDS_Transport_FILE_create(
NDDS_Transport_Address_t *default_network_address_out,
const struct DDS_PropertyQosPolicy *property_in);
| h |
rticonnextdds-examples | data/projects/rticonnextdds-examples/flat_data_api/c++11/CameraImage_publisher.cxx | /* CameraImage_publisher.cxx
A publication of data of type CameraImage
This file uses code automatically generated by the rtiddsgen command:
rtiddsgen -language C++11 -example <arch> CameraImage.idl
(Ignore messages warning about CameraImage_publisher.cxx,
CameraImage_subscriber.cxx, and USER_QOS_PROFILES.xml already existing.
These files contain the example code.)
Instructions:
(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>/CameraImage_subscriber <domain_id> <sample_count>
(3) Start the publication on the same domain used for RTI Data Distribution
Service with the command
objs/<arch>/CameraImage_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>/CameraImage_publisher <domain_id>
objs/<arch>/CameraImage_subscriber <domain_id>
On Windows:
objs\<arch>\CameraImage_publisher <domain_id>
objs\<arch>\CameraImage_subscriber <domain_id>
*/
#include <iostream>
#include <dds/pub/ddspub.hpp>
#include <rti/util/util.hpp> // for sleep()
#include <rti/config/Logger.hpp>
#include "CameraImage.hpp"
const int PIXEL_COUNT = 10;
// Simplest way to create the data sample
void build_data_sample(CameraImageBuilder& builder, int seed)
{
builder.add_format(Format::RGB);
auto resolution_offset = builder.add_resolution();
resolution_offset.height(100);
resolution_offset.width(200);
auto string_builder = builder.build_source();
string_builder.set_string("CAM-1");
string_builder.finish();
// Method 1 - Build the pixel sequence element by element
auto pixels_builder = builder.build_pixels();
for (int i = 0; i < PIXEL_COUNT; i++) {
auto pixel = pixels_builder.add_next();
pixel.red((seed + i) % 100);
pixel.green((seed + i + 1) % 100);
pixel.blue((seed + i + 2) % 100);
}
pixels_builder.finish();
}
// Creates the same data sample using a faster method
// to populate the pixel sequence
void build_data_sample_fast(CameraImageBuilder& builder, int seed)
{
// The initialization of these members doesn't change
builder.build_source().set_string("CAM-1");
builder.add_format(Format::RGB);
auto resolution_offset = builder.add_resolution();
resolution_offset.height(100);
resolution_offset.width(200);
// Populate the pixel sequence accessing the byte buffer directly, instead
// of iterating through each element Offset
// 1) Use the builder to add all the elements at once. This operation is
// cheap (it just advances the underlying buffer without initializing anything)
auto pixels_builder = builder.build_pixels();
pixels_builder.add_n(PIXEL_COUNT);
auto pixels = pixels_builder.finish();
// 2) Use plain_cast to access the buffer as an array of regular C++ Pixels
// (pixel_array's type is PixelPlainHelper*)
auto pixel_array = rti::flat::plain_cast(pixels);
for (int i = 0; i < PIXEL_COUNT; i++) {
auto& pixel = pixel_array[i];
pixel.red((seed + i) % 100);
pixel.green((seed + i + 1) % 100);
pixel.blue((seed + i + 2) % 100);
}
}
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<CameraImage> topic (participant, "Example CameraImage");
// Create a DataWriter with default Qos (Publisher created in-line)
dds::pub::DataWriter<CameraImage> writer(dds::pub::Publisher(participant), topic);
for (int count = 0; count < sample_count || sample_count == 0; count++) {
CameraImageBuilder builder = rti::flat::build_data(writer);
// Build the CameraImage data sample using the builder
if (count % 2 == 0) {
build_data_sample(builder, count); // method 1
} else {
build_data_sample_fast(builder, count); // method 2
}
// Create the sample
CameraImage *sample = builder.finish_sample();
std::cout << "Writing CameraImage, 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::WARNING);
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/flat_data_api/c++11/CameraImage_subscriber.cxx | /* CameraImage_subscriber.cxx
A subscription example
This file uses code automatically generated by the rtiddsgen command:
rtiddsgen -language C++11 -example <arch> CameraImage.idl
(Ignore messages warning about CameraImage_publisher.cxx,
CameraImage_subscriber.cxx, and USER_QOS_PROFILES.xml already existing.
These files contain the example code.)
Instructions:
(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>/CameraImage_subscriber <domain_id> <sample_count>
(3) Start the publication on the same domain used for RTI Data Distribution
Service with the command
objs/<arch>/CameraImage_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>/CameraImage_publisher <domain_id>
objs/<arch>/CameraImage_subscriber <domain_id>
On Windows systems:
objs\<arch>\CameraImage_publisher <domain_id>
objs\<arch>\CameraImage_subscriber <domain_id>
*/
#include <algorithm>
#include <iostream>
#include <dds/sub/ddssub.hpp>
#include <dds/core/ddscore.hpp>
// Or simply include <dds/dds.hpp>
#include "CameraImage.hpp"
// Shows how to access a flat data sample (this is the simplest code, for
// a more efficient implementation, see print_average_pixel_fast).
void print_average_pixel_simple(const CameraImage& sample)
{
auto pixels = sample.root().pixels();
auto pixel_count = pixels.element_count();
unsigned int red_sum = 0, green_sum = 0, blue_sum = 0;
for (auto&& pixel : pixels) {
red_sum += pixel.red();
green_sum += pixel.green();
blue_sum += pixel.blue();
}
std::cout << "Avg. pixel: (" << red_sum / pixel_count << ", "
<< green_sum / pixel_count << ", "
<< blue_sum / pixel_count << ")";
}
// Shows how to access a flat data sample in a more efficient way
void print_average_pixel_fast(const CameraImage& sample)
{
auto pixels = sample.root().pixels();
auto pixel_count = pixels.element_count();
auto pixel_array = rti::flat::plain_cast(pixels);
unsigned int red_sum = 0, green_sum = 0, blue_sum = 0;
for (unsigned int i = 0; i < pixel_count; i++) {
const auto& pixel = pixel_array[i];
red_sum += pixel.red();
green_sum += pixel.green();
blue_sum += pixel.blue();
}
std::cout << "Avg. pixel: (" << red_sum / pixel_count << ", "
<< green_sum / pixel_count << ", "
<< blue_sum / pixel_count << ")";
}
int process_data(dds::sub::DataReader<CameraImage>& reader)
{
// Take all samples
int count = 0;
auto samples = rti::sub::valid_data(reader.take());
for (const auto& sample : samples) {
count++;
auto root = sample.data().root();
std::cout << root.source().get_string() << ": ";
// print_average_pixel_simple(sample.data()); // Method 1
print_average_pixel_fast(sample.data()); // Method 2
std::cout << std::endl;
}
return 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<CameraImage> topic(participant, "Example CameraImage");
// Create a DataReader with default Qos (Subscriber created in-line)
dds::sub::DataReader<CameraImage> 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](/* dds::core::cond::Condition condition */)
{
count += process_data(reader);
}
);
// 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 << "CameraImage subscriber sleeping for 4 sec..." << std::endl;
waitset.dispatch(dds::core::Duration(4)); // Wait up to 4s each time
}
}
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/coherent_presentation/c++/coherent_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.
******************************************************************************/
/* coherent_subscriber.cxx
A subscription example
This file is derived from code automatically generated by the rtiddsgen
command:
rtiddsgen -language C++ -example <arch> coherent.idl
Example subscription of type coherent 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>/coherent_subscriber <domain_id> <sample_count>
(3) Start the publication with the command
objs/<arch>/coherent_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>/coherent_publisher <domain_id>
objs/<arch>/coherent_subscriber <domain_id>
On Windows:
objs\<arch>\coherent_publisher <domain_id>
objs\<arch>\coherent_subscriber <domain_id>
modification history
------------ -------
*/
#include <stdio.h>
#include <stdlib.h>
#ifdef RTI_VX653
#include <vThreadsData.h>
#endif
#include "coherent.h"
#include "coherentSupport.h"
#include "ndds/ndds_cpp.h"
/* Start changes for coherent_presentation */
static const unsigned int STATENVALS = 6;
int statevals[STATENVALS] = { 0 };
void print_state() {
char c = 'a';
unsigned int i = 0;
for (i = 0; i < STATENVALS; ++i) {
printf(" %c = %d;", c++, statevals[i]);
}
}
void set_state(char c, int value) {
unsigned int idx = c - 'a';
if (idx < 0 || idx >= STATENVALS) {
printf("error: invalid field '%c'\n", c);
return;
}
statevals[idx] = value;
}
/* End changes for coherent_presentation */
class coherentListener: 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 coherentListener::on_data_available(DDSDataReader* reader) {
coherentDataReader *coherent_reader = NULL;
coherentSeq data_seq;
DDS_SampleInfoSeq info_seq;
DDS_ReturnCode_t retcode;
int i;
int len = 0;
coherent_reader = coherentDataReader::narrow(reader);
if (coherent_reader == NULL) {
printf("DataReader narrow error\n");
return;
}
retcode = coherent_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;
}
/* Start changes for coherent_presentation */
/* Firstly process all samples */
for (i = 0; i < data_seq.length(); ++i) {
if (info_seq[i].valid_data) {
len++;
set_state(data_seq[i].field, data_seq[i].value);
}
}
/* Then, we print the results */
if (len > 0) {
printf("Received %d updates\n", len);
print_state();
printf("\n");
}
/* End changes for coherent_presentation */
retcode = coherent_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;
coherentListener *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;
DDS_SubscriberQos subscriber_qos;
DDS_DataReaderQos datareader_qos;
/* 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;
}
/* 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_subscriber call above.
*/
/* Start changes for coherent_presentation */
/* retcode = participant->get_default_subscriber_qos(subscriber_qos);
if (retcode != DDS_RETCODE_OK) {
printf("get_default_subscriber_qos error\n");
return -1;
}
subscriber_qos.presentation.access_scope = DDS_TOPIC_PRESENTATION_QOS;
subscriber_qos.presentation.coherent_access = DDS_BOOLEAN_TRUE;
subscriber = participant->create_subscriber(subscriber_qos, NULL,
DDS_STATUS_MASK_NONE);
if (subscriber == NULL) {
printf("create_subscriber error\n");
subscriber_shutdown(participant);
return -1;
}
*/
/* End changes for coherent_presentation */
/* Register the type before creating the topic */
type_name = coherentTypeSupport::get_type_name();
retcode = coherentTypeSupport::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 coherent", 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 coherentListener();
/* 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 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_datareader call above.
*/
/* 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.history.depth = 10;
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;
}
*/ /* End changes for coherent_presentation */
/* 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/coherent_presentation/c++/coherent_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.
******************************************************************************/
/* coherent_publisher.cxx
A publication of data of type coherent
This file is derived from code automatically generated by the rtiddsgen
command:
rtiddsgen -language C++ -example <arch> coherent.idl
Example publication of type coherent 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>/coherent_subscriber <domain_id> <sample_count>
(3) Start the publication with the command
objs/<arch>/coherent_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>/coherent_publisher <domain_id> o
objs/<arch>/coherent_subscriber <domain_id>
On Windows:
objs\<arch>\coherent_publisher <domain_id>
objs\<arch>\coherent_subscriber <domain_id>
modification history
------------ -------
* Change presentation scope in publisher QoS
* Use reliable communication (currently required for coherency QoS)
* Surround coherent changes with calls to {begin, end}_coherent_changes
* All QoS are in the xml file
*/
#include <stdio.h>
#include <stdlib.h>
#ifdef RTI_VX653
#include <vThreadsData.h>
#endif
#include "coherent.h"
#include "coherentSupport.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;
coherentDataWriter * coherent_writer = NULL;
coherent *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 };
DDS_PublisherQos publisher_qos;
DDS_DataWriterQos datawriter_qos;
int mod = 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;
}
/* 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_publisher call above.
*/
/* Start changes for coherent_presentation */
/* Get default publisher QoS to customize */
/* retcode = participant->get_default_publisher_qos(publisher_qos);
if (retcode != DDS_RETCODE_OK) {
printf("get_default_publisher_qos error\n");
return -1;
}
*/ /* Topic access scope means that writes from a particular datawriter to
* multiple instances will be viewed coherently.
*/
/* publisher_qos.presentation.access_scope = DDS_TOPIC_PRESENTATION_QOS;
publisher_qos.presentation.coherent_access = DDS_BOOLEAN_TRUE;
publisher = participant->create_publisher(publisher_qos, NULL,
DDS_STATUS_MASK_NONE);
if (publisher == NULL) {
printf("create_participant error\n");
publisher_shutdown(participant);
return -1;
}
*/ /* End changes for coherent_presentation */
/* Register type before creating topic */
type_name = coherentTypeSupport::get_type_name();
retcode = coherentTypeSupport::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 coherent", type_name,
DDS_TOPIC_QOS_DEFAULT, NULL /* listener */, DDS_STATUS_MASK_NONE);
if (topic == NULL) {
printf("create_topic error\n");
publisher_shutdown(participant);
return -1;
}
/* To customize data writer QoS, use
the configuration file USER_QOS_PROFILES.xml */
writer = publisher->create_datawriter(topic, DDS_DATAWRITER_QOS_DEFAULT,
NULL /* listener */, DDS_STATUS_MASK_NONE);
if (writer == NULL) {
printf("create_datawriter error\n");
publisher_shutdown(participant);
return -1;
}
/* If you want to 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.
*/
/* Start changes for coheren_presentation */
/* 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.history.depth = 10;
datawriter_qos.protocol.rtps_reliable_writer.heartbeats_per_max_samples = 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;
}
*/ /* End changes for coherent_presentation */
coherent_writer = coherentDataWriter::narrow(writer);
if (coherent_writer == NULL) {
printf("DataWriter narrow error\n");
publisher_shutdown(participant);
return -1;
}
/* Create data sample for writing */
instance = coherentTypeSupport::create_data();
if (instance == NULL) {
printf("coherentTypeSupport::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->id = 0;
instance_handle = coherent_writer->register_instance(*instance);
publisher->begin_coherent_changes();
printf("Begin Coherent Changes\n");
/* Main loop */
for (count = 0; (sample_count == 0) || (count < sample_count); ++count) {
NDDSUtility::sleep(send_period);
mod = count % 7;
if (mod == 6) {
publisher->begin_coherent_changes();
printf("Begin Coherent Changes\n");
continue;
}
/* Choose a random value for each field */
instance->field = 'a' + mod;
instance->value = (int) (rand() / (RAND_MAX / 10.0));
printf(" Updating instance, %c->%d\n", instance->field,
instance->value);
retcode = coherent_writer->write(*instance, instance_handle);
if (retcode != DDS_RETCODE_OK) {
printf("write error %d\n", retcode);
}
if (mod == 5) {
publisher->end_coherent_changes();
printf("End Coherent Changes\n\n");
}
}
retcode = coherent_writer->unregister_instance(*instance, instance_handle);
if (retcode != DDS_RETCODE_OK) {
printf("unregister instance error %d\n", retcode);
}
/* Delete data sample */
retcode = coherentTypeSupport::delete_data(instance);
if (retcode != DDS_RETCODE_OK) {
printf("coherentTypeSupport::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/coherent_presentation/c/coherent_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.
******************************************************************************/
/* coherent_subscriber.c
A subscription example
This file is derived from code automatically generated by the rtiddsgen
command:
rtiddsgen -language C -example <arch> coherent.idl
Example subscription of type coherent 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>/coherent_subscriber <domain_id> <sample_count>
(3) Start the publication with the command
objs/<arch>/coherent_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>/coherent_publisher <domain_id>
objs/<arch>/coherent_subscriber <domain_id>
On Windows systems:
objs\<arch>\coherent_publisher <domain_id>
objs\<arch>\coherent_subscriber <domain_id>
modification history
------------ -------
* Modify listener callback to update Object State
* Change presentation scope in subscriber QoS
* Use reliable communication (currently required for coherency QoS)
* All QoS are in the xml file
*/
#include <stdio.h>
#include <stdlib.h>
#include "ndds/ndds_c.h"
#include "coherent.h"
#include "coherentSupport.h"
/* Start changes for coherent_presentation */
#define STATENVALS 6
int statevals[STATENVALS] = { 0 };
void print_state() {
unsigned int i;
char c = 'a';
for (i = 0; i < STATENVALS; ++i) {
printf(" %c = %d;", c++, statevals[i]);
}
}
void set_state(char c, int value) {
unsigned int idx = c - 'a';
if (idx < 0 || idx >= STATENVALS) {
printf("error: invalid field '%c'\n", c);
return;
}
statevals[idx] = value;
}
/* End changes for coherent_presentation */
void coherentListener_on_requested_deadline_missed(void* listener_data,
DDS_DataReader* reader,
const struct DDS_RequestedDeadlineMissedStatus *status) {
}
void coherentListener_on_requested_incompatible_qos(void* listener_data,
DDS_DataReader* reader,
const struct DDS_RequestedIncompatibleQosStatus *status) {
}
void coherentListener_on_sample_rejected(void* listener_data,
DDS_DataReader* reader, const struct DDS_SampleRejectedStatus *status) {
}
void coherentListener_on_liveliness_changed(void* listener_data,
DDS_DataReader* reader,
const struct DDS_LivelinessChangedStatus *status) {
}
void coherentListener_on_sample_lost(void* listener_data,
DDS_DataReader* reader, const struct DDS_SampleLostStatus *status) {
}
void coherentListener_on_subscription_matched(void* listener_data,
DDS_DataReader* reader,
const struct DDS_SubscriptionMatchedStatus *status) {
}
void coherentListener_on_data_available(void* listener_data,
DDS_DataReader* reader) {
coherentDataReader *coherent_reader = NULL;
struct coherentSeq data_seq = DDS_SEQUENCE_INITIALIZER;
struct DDS_SampleInfoSeq info_seq = DDS_SEQUENCE_INITIALIZER;
DDS_ReturnCode_t retcode;
int i;
int len = 0;
coherent* data;
coherent_reader = coherentDataReader_narrow(reader);
if (coherent_reader == NULL) {
printf("DataReader narrow error\n");
return;
}
retcode = coherentDataReader_take(coherent_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;
}
/* Start changes for coherent_presentation */
/* Firstly, we process all samples */
len = 0;
for (i = 0; i < DDS_SampleInfoSeq_get_length(&info_seq); ++i) {
if (DDS_SampleInfoSeq_get_reference(&info_seq, i)->valid_data) {
data = coherentSeq_get_reference(&data_seq, i);
len++;
set_state(data->field, data->value);
}
}
/* Then, we print the results */
if (len > 0) {
printf("Received %d updates\n", len);
print_state();
printf("\n");
}
/* End changes for coherent_presentation */
retcode = coherentDataReader_return_loan(coherent_reader, &data_seq,
&info_seq);
if (retcode != DDS_RETCODE_OK) {
printf("return loan error %d\n", retcode);
}
}
/* Delete all entities */
static int subscriber_shutdown(DDS_DomainParticipant *participant,
struct DDS_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_SubscriberQos_finalize(subscriber_qos);
if (retcode != DDS_RETCODE_OK) {
printf("DDS_SubscriberQos_finalize error %d\n", retcode);
status = -1;
}
retcode = DDS_DataReaderQos_finalize(datareader_qos);
if (retcode != DDS_RETCODE_OK) {
printf("DDS_DataReaderQos_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 = 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, &subscriber_qos, &datareader_qos);
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, &subscriber_qos, &datareader_qos);
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_subscriber call above.
*/
/* Start changes for coherent_presentation */
/* 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;
}
subscriber_qos.presentation.access_scope = DDS_TOPIC_PRESENTATION_QOS;
subscriber_qos.presentation.coherent_access = DDS_BOOLEAN_TRUE;
subscriber = 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;
}
*/ /* End changes for coherent_presentation */
/* Register the type before creating the topic */
type_name = coherentTypeSupport_get_type_name();
retcode = coherentTypeSupport_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 coherent",
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;
}
/* Set up a data reader listener */
reader_listener.on_requested_deadline_missed =
coherentListener_on_requested_deadline_missed;
reader_listener.on_requested_incompatible_qos =
coherentListener_on_requested_incompatible_qos;
reader_listener.on_sample_rejected = coherentListener_on_sample_rejected;
reader_listener.on_liveliness_changed =
coherentListener_on_liveliness_changed;
reader_listener.on_sample_lost = coherentListener_on_sample_lost;
reader_listener.on_subscription_matched =
coherentListener_on_subscription_matched;
reader_listener.on_data_available = coherentListener_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, &subscriber_qos, &datareader_qos);
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_datareader call above.
*/
/* Start changes for coherent_presentation */
/* Get default datareader QoS to customize */
/* 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.history.depth = 10;
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, &subscriber_qos, &datareader_qos);
return -1;
}
*/ /* End changes for coherent_presentation */
/* 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, &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/coherent_presentation/c/coherent_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.
******************************************************************************/
/* coherent_publisher.c
A publication of data of type coherent
This file is derived from code automatically generated by the rtiddsgen
command:
rtiddsgen -language C -example <arch> coherent.idl
Example publication of type coherent 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>/coherent_subscriber <domain_id> <sample_count>
(3) Start the publication with the command
objs/<arch>/coherent_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>/coherent_publisher <domain_id>
objs/<arch>/coherent_subscriber <domain_id>
On Windows:
objs\<arch>\coherent_publisher <domain_id>
objs\<arch>\coherent_subscriber <domain_id>
modification history
------------ -------
* Change presentation scope in publisher QoS
* Use reliable communication (currently required for coherency QoS)
* Surround coherent changes with calls to {begin, end}_coherent_changes
* All QoS are in the xml file
*/
#include <stdio.h>
#include <stdlib.h>
#include "ndds/ndds_c.h"
#include "coherent.h"
#include "coherentSupport.h"
/* Delete all entities */
static int publisher_shutdown(DDS_DomainParticipant *participant,
struct DDS_PublisherQos *publisher_qos,
struct DDS_DataWriterQos *datawriter_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;
}
retcode = DDS_DataWriterQos_finalize(datawriter_qos);
if (retcode != DDS_RETCODE_OK) {
printf("DataWriterQos_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;
coherentDataWriter *coherent_writer = NULL;
coherent *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;
int mod = 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, &publisher_qos, &datawriter_qos);
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, &publisher_qos, &datawriter_qos);
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_publisher call above.
*/
/* Start changes for coherent_presentation */
/* Get default publisher QoS to customize */
/* retcode = DDS_DomainParticipant_get_default_publisher_qos(participant,
&publisher_qos);
if (retcode != DDS_RETCODE_OK) {
printf("get_default_publisher_qos error\n");
return -1;
}
*/ /* Topic access scope means that writes from a particular datawriter to
* multiple instances will be viewed coherently.
*/
/* publisher_qos.presentation.access_scope = DDS_TOPIC_PRESENTATION_QOS;
publisher_qos.presentation.coherent_access = DDS_BOOLEAN_TRUE;
*/ /* To customize publisher QoS, use
the configuration file USER_QOS_PROFILES.xml */
/* 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, &datawriter_qos);
return -1;
}
*/ /* End changes for coherent_presentation */
/* Register type before creating topic */
type_name = coherentTypeSupport_get_type_name();
retcode = coherentTypeSupport_register_type(participant, type_name);
if (retcode != DDS_RETCODE_OK) {
printf("register_type error %d\n", retcode);
publisher_shutdown(participant, &publisher_qos, &datawriter_qos);
return -1;
}
/* To customize topic QoS, use
the configuration file USER_QOS_PROFILES.xml */
topic = DDS_DomainParticipant_create_topic(participant, "Example coherent",
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, &datawriter_qos);
return -1;
}
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, &datawriter_qos);
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.
*/
/* Start changes for coherent_presentation */
/* Get default datawriter QoS to customize */
/* 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.reliability.kind = DDS_RELIABLE_RELIABILITY_QOS;
datawriter_qos.history.kind = DDS_KEEP_ALL_HISTORY_QOS;
datawriter_qos.protocol.rtps_reliable_writer.heartbeats_per_max_samples = 0;
*/ /* To customize data writer QoS, use
the configuration file USER_QOS_PROFILES.xml */
/* 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, &publisher_qos, &datawriter_qos);
return -1;
}
*/ /* End changes for coherent_presentation */
coherent_writer = coherentDataWriter_narrow(writer);
if (coherent_writer == NULL) {
printf("DataWriter narrow error\n");
publisher_shutdown(participant, &publisher_qos, &datawriter_qos);
return -1;
}
/* Create data sample for writing */
instance = coherentTypeSupport_create_data_ex(DDS_BOOLEAN_TRUE);
if (instance == NULL) {
printf("coherentTypeSupport_create_data error\n");
publisher_shutdown(participant, &publisher_qos, &datawriter_qos);
return -1;
}
/* Start changes for coherent_presentation */
/* 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->id = 0;
instance_handle = coherentDataWriter_register_instance(coherent_writer,
instance);
DDS_Publisher_begin_coherent_changes(publisher);
printf("Begin Coherent Changes\n");
/* Main loop */
for (count = 0; (sample_count == 0) || (count < sample_count); ++count) {
NDDS_Utility_sleep(&send_period);
mod = count % 7;
if (mod == 6) {
DDS_Publisher_begin_coherent_changes(publisher);
printf("Begin Coherent Changes\n");
continue;
}
/* Choose a random value for each field */
instance->field = 'a' + mod;
instance->value = (int) (rand() / (RAND_MAX / 10.0));
printf(" Updating instance, %c->%d\n", instance->field,
instance->value);
/* Write data */
retcode = coherentDataWriter_write(coherent_writer, instance,
&instance_handle);
if (retcode != DDS_RETCODE_OK) {
printf("write error %d\n", retcode);
}
/* Begin a new change group after sending 6 samples */
if (mod == 5) {
DDS_Publisher_end_coherent_changes(publisher);
printf("End Coherent Changes\n\n");
}
}
retcode = coherentDataWriter_unregister_instance(coherent_writer, instance,
&instance_handle);
if (retcode != DDS_RETCODE_OK) {
printf("unregister instance error %d\n", retcode);
}
/* Delete data sample */
retcode = coherentTypeSupport_delete_data_ex(instance, DDS_BOOLEAN_TRUE);
if (retcode != DDS_RETCODE_OK) {
printf("coherentTypeSupport_delete_data error %d\n", retcode);
}
/* End changes for coherent_presentation */
/* Cleanup and delete delete all entities */
return publisher_shutdown(participant, &publisher_qos, &datawriter_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/coherent_presentation/c++03/coherent_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 "coherent.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;
using namespace rti::sub;
// Transform a DDS sample into a pair value for a dictionary.
std::pair<char, int> sample2map(const coherent& data) {
return std::make_pair(data.field(), data.value());
}
class CoherentListener : public NoOpDataReaderListener<coherent> {
public:
void on_data_available(DataReader<coherent>& reader)
{
// Take all samples
LoanedSamples<coherent> samples = reader.take();
// Process samples and add to a dictionary
std::map<char, int> values;
std::transform(
rti::sub::valid_samples(samples.begin()),
rti::sub::valid_samples(samples.end()),
std::inserter(values, values.begin()),
sample2map);
std::cout << std::endl;
// Print result
std::cout << "Received updates:" << std::endl;
typedef std::map<char, int>::const_iterator MapIterator;
for (MapIterator iter = values.begin(); iter != values.end(); iter++) {
std::cout << " " << iter->first << " = " << iter->second << ";";
}
std::cout << 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();
// If you want to change the Subscriber QoS programmatically rather
// than using the XML file, you will need to comment out these lines.
// subscriber_qos << Presentation::TopicAccessScope(true, false);
// Create a subscriber.
Subscriber subscriber(participant, subscriber_qos);
// Create a Topic -- and automatically register the type.
Topic<coherent> topic(participant, "Example coherent");
// 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::KeepLast(10);
// Create a DataReader.
DataReader<coherent> 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<coherent> > scoped_listener =
bind_and_manage_listener(
reader,
new CoherentListener,
StatusMask::data_available());
// Main loop
for (int count = 0; (sample_count == 0) || (count < sample_count); count++){
rti::util::sleep(Duration(1));
}
}
int main(int argc, char *argv[])
{
int domain_id = 0;
int sample_count = 0; // Infinite loop
if (argc >= 2) {
domain_id = atoi(argv[1]);
}
if (argc >= 3) {
sample_count = atoi(argv[2]);
}
// To turn on additional logging, include <rti/config/Logger.hpp> and
// uncomment the following line:
// rti::config::Logger::instance().verbosity(rti::config::Verbosity::STATUS_ALL);
try {
subscriber_main(domain_id, sample_count);
} catch (std::exception ex) {
std::cout << "Exception caught: " << ex.what() << std::endl;
return -1;
}
return 0;
}
| cxx |
rticonnextdds-examples | data/projects/rticonnextdds-examples/coherent_presentation/c++03/coherent_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 "coherent.hpp"
using namespace dds::core;
using namespace dds::core::policy;
using namespace rti::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<coherent> topic (participant, "Example coherent");
// Retrieve the Publisher QoS, from USER_QOS_PROFILES.xml.
PublisherQos publisher_qos = QosProvider::Default().publisher_qos();
// If you want to change the Publisher's QoS programmatically rather
// than using the XML file, you will need to uncomment the following lines.
// publisher_qos << Presentation::TopicAccessScope(true, false);
Publisher publisher(participant, publisher_qos);
// Retrieve the DataWriter QoS, from USER_QOS_PROFILES.xml.
DataWriterQos writer_qos = QosProvider::Default().datawriter_qos();
// If you want to change the DataWriter's QoS programmatically rather
// than using the XML file, you will need to uncomment the following lines.
// writer_qos << Reliability::Reliable()
// << History::KeepLast(10)
// << DataWriterProtocol().rtps_reliable_writer(
// RtpsReliableWriterProtocol().heartbeats_per_max_samples(0));
// Create a DataWriter with default Qos
DataWriter<coherent> writer(publisher, topic, writer_qos);
coherent sample;
sample.id(0);
InstanceHandle handle = writer.register_instance(sample);
int num_samples = 7;
for (int count = 0; count < sample_count || sample_count == 0; ) {
CoherentSet coherent_set(publisher);
std::cout << "Begin Coherent Changes" << std::endl;
for (int i = 0; i < num_samples; i++, count++) {
rti::util::sleep(Duration(1));
sample.field('a' + i);
sample.value((int)(rand() / (RAND_MAX / 10.0)));
std::cout << "\tUpdating instance, " << sample.field() << "->"
<< sample.value() << std::endl;
writer.write(sample, handle);
}
// `coherent_set.end()` will be called by the destructor.
std::cout << "End Coherent Changes" << std::endl << std::endl;
}
writer.unregister_instance(handle);
}
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/keyed_data_advanced/c++/keys_publisher.cxx | /*******************************************************************************
(c) 2005-2014 Copyright, Real-Time Innovations, Inc. All rights reserved.
RTI grants Licensee a license to use, modify, compile, and create derivative
works of the Software. Licensee has the right to distribute object form only
for use with RTI products. The Software is provided "as is", with no warranty
of any type, including any warranty for fitness for any purpose. RTI is under
no obligation to maintain or support the Software. RTI shall not be liable for
any incidental or consequential damages arising out of the use or inability to
use the software.
******************************************************************************/
/* keys_publisher.cxx
A publication of data of type keys
This file is derived from code automatically generated by the rtiddsgen
command:
rtiddsgen -language C++ -example <arch> keys.idl
Example publication of type keys automatically generated by
'rtiddsgen'. To test them follow these steps:
(1) Compile this file and the example subscription.
(2) Start the subscription with the command
objs/<arch>/keys_subscriber <domain_id> <sample_count>
(3) Start the publication with the command
objs/<arch>/keys_publisher <domain_id> <sample_count>
(4) [Optional] Specify the list of discovery initial peers and
multicast receive addresses via an environment variable or a file
(in the current working directory) called NDDS_DISCOVERY_PEERS.
You can run any number of publishers and subscribers programs, and can
add and remove them dynamically from the domain.
Example:
To run the example application on domain <domain_id>:
On Unix:
objs/<arch>/keys_publisher <domain_id> o
objs/<arch>/keys_subscriber <domain_id>
On Windows:
objs\<arch>\keys_publisher <domain_id>
objs\<arch>\keys_subscriber <domain_id>
modification history
------------ -------
*/
#include <stdio.h>
#include <stdlib.h>
#ifdef RTI_VX653
#include <vThreadsData.h>
#endif
#include "keys.h"
#include "keysSupport.h"
#include "ndds/ndds_cpp.h"
/* Delete all entities */
static int publisher_shutdown(
DDSDomainParticipant *participant)
{
DDS_ReturnCode_t retcode;
int status = 0;
if (participant != NULL) {
retcode = participant->delete_contained_entities();
if (retcode != DDS_RETCODE_OK) {
printf("delete_contained_entities error %d\n", retcode);
status = -1;
}
retcode = DDSTheParticipantFactory->delete_participant(participant);
if (retcode != DDS_RETCODE_OK) {
printf("delete_participant error %d\n", retcode);
status = -1;
}
}
/* RTI Connext provides finalize_instance() method on
domain participant factory for people who want to release memory used
by the participant factory. Uncomment the following block of code for
clean destruction of the singleton. */
/*
retcode = DDSDomainParticipantFactory::finalize_instance();
if (retcode != DDS_RETCODE_OK) {
printf("finalize_instance error %d\n", retcode);
status = -1;
}
*/
return status;
}
extern "C" int publisher_main(int domainId, int sample_count)
{
DDSDomainParticipant *participant = NULL;
DDSPublisher *publisher = NULL;
DDSTopic *topic = NULL;
DDSDataWriter *writer = NULL;
keysDataWriter * keys_writer = NULL;
DDSDataWriter *writer2 = NULL;
keysDataWriter *keys_writer2 = NULL;
/* Creates three instances */
keys* instance[3] = {NULL, NULL, NULL};
/* Creates three handles for managing the registrations */
DDS_InstanceHandle_t handle[3] = {DDS_HANDLE_NIL, DDS_HANDLE_NIL, DDS_HANDLE_NIL};
/* We only will send data over the instances marked as active */
int active[3] = {1, 0, 0};
DDS_ReturnCode_t retcode;
const char *type_name = NULL;
int count = 0;
DDS_Duration_t send_period = {1,0};
/* To customize participant QoS, use
the configuration file USER_QOS_PROFILES.xml */
participant = DDSTheParticipantFactory->create_participant(
domainId, DDS_PARTICIPANT_QOS_DEFAULT,
NULL /* listener */, DDS_STATUS_MASK_NONE);
if (participant == NULL) {
printf("create_participant error\n");
publisher_shutdown(participant);
return -1;
}
/* To customize publisher QoS, use
the configuration file USER_QOS_PROFILES.xml */
publisher = participant->create_publisher(
DDS_PUBLISHER_QOS_DEFAULT, NULL /* listener */, DDS_STATUS_MASK_NONE);
if (publisher == NULL) {
printf("create_publisher error\n");
publisher_shutdown(participant);
return -1;
}
/* Register type before creating topic */
type_name = keysTypeSupport::get_type_name();
retcode = keysTypeSupport::register_type(
participant, type_name);
if (retcode != DDS_RETCODE_OK) {
printf("register_type error %d\n", retcode);
publisher_shutdown(participant);
return -1;
}
/* To customize topic QoS, use
the configuration file USER_QOS_PROFILES.xml */
topic = participant->create_topic(
"Example keys",
type_name, DDS_TOPIC_QOS_DEFAULT, NULL /* listener */,
DDS_STATUS_MASK_NONE);
if (topic == NULL) {
printf("create_topic error\n");
publisher_shutdown(participant);
return -1;
}
/* We are going to load different QoS profiles for the two DWs */
DDS_DataWriterQos datawriter_qos;
/* 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);
retcode = DDSTheParticipantFactory->get_datawriter_qos_from_profile(datawriter_qos,"keys_Library","keys_Profile_dw2");
if (retcode != DDS_RETCODE_OK) {
printf("get_datawriter_qos_from_profile error\n");
return -1;
}
/* If you want to set the writer_data_lifecycle QoS settings
* programmatically rather than using the XML, you will need to add
* the following lines to your code and comment out the create_datawriter
* and get_datawriter_qos_from_profile calls above.
*/
/*
retcode = publisher->get_default_datawriter_qos(datawriter_qos);
if (retcode != DDS_RETCODE_OK) {
printf("get_default_datawriter_qos error\n");
return -1;
}
datawriter_qos.writer_data_lifecycle.autodispose_unregistered_instances = DDS_BOOLEAN_FALSE;
datawriter_qos.ownership.kind = DDS_EXCLUSIVE_OWNERSHIP_QOS;
datawriter_qos.ownership_strength.value = 10;
writer = publisher->create_datawriter(
topic, datawriter_qos, NULL,
DDS_STATUS_MASK_NONE);
datawriter_qos.ownership_strength.value = 5;
*/
writer2 = publisher->create_datawriter(
topic, datawriter_qos, NULL,
DDS_STATUS_MASK_NONE);
if (writer == NULL) {
printf("create_datawriter1 error\n");
publisher_shutdown(participant);
return -1;
}
if (writer2 == NULL) {
printf("create_datawriter2 error\n");
publisher_shutdown(participant);
return -1;
}
keys_writer = keysDataWriter::narrow(writer);
if (keys_writer == NULL) {
printf("DataWriter narrow error\n");
publisher_shutdown(participant);
return -1;
}
keys_writer2 = keysDataWriter::narrow(writer2);
if (keys_writer2 == NULL) {
printf("DataWriter narrow error\n");
publisher_shutdown(participant);
return -1;
}
/* Create data samples for writing */
instance[0] = keysTypeSupport::create_data();
instance[1] = keysTypeSupport::create_data();
instance[2] = keysTypeSupport::create_data();
if (instance[0] == NULL || instance[1] == NULL || instance[2] == NULL) {
printf("keysTypeSupport::create_data error\n");
publisher_shutdown(participant);
return -1;
}
/* RTI Connext could examine the key fields each time it needs to determine
* which data-instance is being modified.
* However, for performance and semantic reasons, it is better
* for your application to declare all the data-instances it intends to
* modify prior to actually writing any samples. This is known as registration.
*/
/* In order to register the instances, we must set their associated keys first */
instance[0]->code = 0;
instance[1]->code = 1;
instance[2]->code = 2;
/* The keys must have been set before making this call */
printf("----DW1 registering instance %d\n", instance[0]->code);
handle[0] = keys_writer->register_instance(*instance[0]);
/* Modify the data to be sent here */
instance[0]->x = 1;
instance[1]->x = 1;
instance[2]->x = 1;
/* Make variables for the instance for the second datawriter to use.
Note that it actually refers to the same logical instance, but
because we're running both datawriters in the same thread, we
to create separate variables so they don't clobber each other.
*/
keys* instance_dw2 = NULL;
instance_dw2 = keysTypeSupport::create_data();
if (instance_dw2 == NULL) {
printf("keysTypeSupport::create_data error\n");
publisher_shutdown(participant);
return -1;
}
/* instance_dw2 and instance[1] have the same key, and thus
will write to the same instance (ins1).
*/
instance_dw2->code = instance[1]->code;
instance_dw2->x = 2;
DDS_InstanceHandle_t handle_dw2 =
keys_writer2->register_instance(*instance_dw2);
int active_dw2 = 1;
/* Main loop */
for (count=0; (sample_count == 0) || (count < sample_count); ++count) {
NDDSUtility::sleep(send_period);
/* Modify the data to be sent here */
instance[0]->y = count;
instance[1]->y = count + 1000;
instance[2]->y = count + 2000;
instance_dw2->y = -count - 1000;
/* We control two datawriters via a state machine here rather than
introducing separate threads.
*/
/* Control first DataWriter */
switch (count) {
case 4: { /* Start sending the second (ins1) and third instances (ins2) */
printf("----DW1 registering instance %d\n", instance[1]->code);
printf("----DW1 registering instance %d\n", instance[2]->code);
handle[1] = keys_writer->register_instance(*instance[1]);
handle[2] = keys_writer->register_instance(*instance[2]);
active[1] = 1;
active[2] = 1;
} break;
case 8: { /* Dispose the second instance (ins1) */
printf("----DW1 disposing instance %d\n", instance[1]->code);
retcode = keys_writer->dispose(*instance[1], handle[1]);
if (retcode != DDS_RETCODE_OK) {
printf("dispose instance error %d\n", retcode);
return -1;
}
active[1] = 0;
} break;
case 10: { /* Unregister the second instance (ins1) */
printf("----DW1 unregistering instance %d\n", instance[1]->code);
retcode = keys_writer->unregister_instance(*instance[1], handle[1]);
if (retcode != DDS_RETCODE_OK) {
printf("unregister instance error %d\n", retcode);
return -1;
}
active[1] = 0;
} break;
case 12: { /* Unregister the third instance (ins2) */
printf("----DW1 unregistering instance %d\n", instance[2]->code);
retcode = keys_writer->unregister_instance(*instance[2], handle[2]);
if (retcode != DDS_RETCODE_OK) {
printf("unregister instance error %d\n", retcode);
return -1;
}
active[2] = 0;
/* Re-register the second instance (ins1) */
printf("----DW1 re-registering instance %d\n", instance[1]->code);
handle[1] = keys_writer->register_instance(*instance[1]);
active[1] = 1;
} break;
case 16: { /* Re-register the third instance (ins2) */
printf("----DW1 re-registering instance %d\n", instance[2]->code);
handle[2] = keys_writer->register_instance(*instance[2]);
active[2] = 1;
} break;
}
for (int i = 0; i < 3; ++i) {
if (active[i]) {
printf("DW1 write; code: %d, x: %d, y: %d\n",
instance[i]->code, instance[i]->x, instance[i]->y);
retcode = keys_writer->write(*instance[i], handle[i]);
if (retcode != DDS_RETCODE_OK) {
printf("write error %d\n", retcode);
return -1;
}
}
}
/* Control second datawriter */
switch (count) {
case 16: { /* Dispose the instance (ins1).
Since it has lower ownership strength, this does nothing */
printf("----DW2 disposing instance %d\n", instance_dw2->code);
retcode = keys_writer2->dispose(*instance_dw2, handle_dw2);
if (retcode != DDS_RETCODE_OK) {
printf("DW2 dispose instance error %d\n", retcode);
}
active_dw2 = 0;
} break;
}
if (active_dw2) {
printf("DW2 write; code: %d, x: %d, y: %d\n",
instance_dw2->code, instance_dw2->x, instance_dw2->y);
retcode = keys_writer2->write(*instance_dw2, handle_dw2);
if (retcode != DDS_RETCODE_OK) {
printf("write error %d\n", retcode);
return -1;
}
}
}
/* Delete data samples */
for (int i = 0; i < 3; ++i) {
retcode = keysTypeSupport::delete_data(instance[i]);
if (retcode != DDS_RETCODE_OK) {
printf("keysTypeSupport::delete_data error %d\n", retcode);
}
}
/* Delete all entities */
return publisher_shutdown(participant);
}
#if defined(RTI_WINCE)
int wmain(int argc, wchar_t** argv)
{
int domainId = 0;
int sample_count = 0; /* infinite loop */
if (argc >= 2) {
domainId = _wtoi(argv[1]);
}
if (argc >= 3) {
sample_count = _wtoi(argv[2]);
}
/* Uncomment this to turn on additional logging
NDDSConfigLogger::get_instance()->
set_verbosity_by_category(NDDS_CONFIG_LOG_CATEGORY_API,
NDDS_CONFIG_LOG_VERBOSITY_STATUS_ALL);
*/
return publisher_main(domainId, sample_count);
}
#elif !(defined(RTI_VXWORKS) && !defined(__RTP__)) && !defined(RTI_PSOS)
int main(int argc, char *argv[])
{
int domainId = 0;
int sample_count = 0; /* infinite loop */
if (argc >= 2) {
domainId = atoi(argv[1]);
}
if (argc >= 3) {
sample_count = atoi(argv[2]);
}
/* Uncomment this to turn on additional logging
NDDSConfigLogger::get_instance()->
set_verbosity_by_category(NDDS_CONFIG_LOG_CATEGORY_API,
NDDS_CONFIG_LOG_VERBOSITY_STATUS_ALL);
*/
return publisher_main(domainId, sample_count);
}
#endif
#ifdef RTI_VX653
const unsigned char* __ctype = *(__ctypePtrGet());
extern "C" void usrAppInit ()
{
#ifdef USER_APPL_INIT
USER_APPL_INIT; /* for backwards compatibility */
#endif
/* add application specific code here */
taskSpawn("pub", RTI_OSAPI_THREAD_PRIORITY_NORMAL, 0x8, 0x150000, (FUNCPTR)publisher_main, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
}
#endif
| cxx |
rticonnextdds-examples | data/projects/rticonnextdds-examples/keyed_data_advanced/c++/keys_subscriber.cxx | /*******************************************************************************
(c) 2005-2014 Copyright, Real-Time Innovations, Inc. All rights reserved.
RTI grants Licensee a license to use, modify, compile, and create derivative
works of the Software. Licensee has the right to distribute object form only
for use with RTI products. The Software is provided "as is", with no warranty
of any type, including any warranty for fitness for any purpose. RTI is under
no obligation to maintain or support the Software. RTI shall not be liable for
any incidental or consequential damages arising out of the use or inability to
use the software.
******************************************************************************/
/* keys_subscriber.cxx
A subscription example
This file is derived from code automatically generated by the rtiddsgen
command:
rtiddsgen -language C++ -example <arch> keys.idl
Example subscription of type keys automatically generated by
'rtiddsgen'. To test them follow these steps:
(1) Compile this file and the example publication.
(2) Start the subscription with the command
objs/<arch>/keys_subscriber <domain_id> <sample_count>
(3) Start the publication with the command
objs/<arch>/keys_publisher <domain_id> <sample_count>
(4) [Optional] Specify the list of discovery initial peers and
multicast receive addresses via an environment variable or a file
(in the current working directory) called NDDS_DISCOVERY_PEERS.
You can run any number of publishers and subscribers programs, and can
add and remove them dynamically from the domain.
Example:
To run the example application on domain <domain_id>:
On Unix:
objs/<arch>/keys_publisher <domain_id>
objs/<arch>/keys_subscriber <domain_id>
On Windows:
objs\<arch>\keys_publisher <domain_id>
objs\<arch>\keys_subscriber <domain_id>
modification history
------------ -------
*/
#include <stdio.h>
#include <stdlib.h>
#ifdef RTI_VX653
#include <vThreadsData.h>
#endif
#include "keys.h"
#include "keysSupport.h"
#include "ndds/ndds_cpp.h"
class keysListener : public DDSDataReaderListener {
public:
virtual void on_requested_deadline_missed(
DDSDataReader* /*reader*/,
const DDS_RequestedDeadlineMissedStatus& /*status*/) {}
virtual void on_requested_incompatible_qos(
DDSDataReader* /*reader*/,
const DDS_RequestedIncompatibleQosStatus& /*status*/) {}
virtual void on_sample_rejected(
DDSDataReader* /*reader*/,
const DDS_SampleRejectedStatus& /*status*/) {}
virtual void on_liveliness_changed(
DDSDataReader* /*reader*/,
const DDS_LivelinessChangedStatus& /*status*/) {}
virtual void on_sample_lost(
DDSDataReader* /*reader*/,
const DDS_SampleLostStatus& /*status*/) {}
virtual void on_subscription_matched(
DDSDataReader* /*reader*/,
const DDS_SubscriptionMatchedStatus& /*status*/) {}
virtual void on_data_available(DDSDataReader* reader);
/**** Start changes for Advanced_Keys ****/
/* These are not called by DDS. on_data_available() calls
the appropriate function when it gets updates about
an instances' status
*/
virtual void new_instance_found(keysDataReader* keys_reader,
const DDS_SampleInfo* info,
const keys* msg);
virtual void instance_lost_writers(keysDataReader* keys_reader,
const DDS_SampleInfo* info,
const keys* msg);
virtual void instance_disposed(keysDataReader* keys_reader,
const DDS_SampleInfo* info,
const keys* msg);
/* Called to handle relevant data samples */
virtual void handle_data(keysDataReader* keys_reader,
const DDS_SampleInfo* info,
const keys* msg);
/* Called to determine if a key is relevant to this application */
virtual bool key_is_relevant(const keys* msg);
/* Initialize instance states */
keysListener() {
for(int i = 0; i < 3; ++i)
states[i] = inactive;
}
protected:
/* Track instance state */
enum Instance_State {inactive, active, no_writers, disposed};
Instance_State states[3];
/**** End changes for Advanced_Keys ****/
};
/**** Start changes for Advanced_Keys ****/
void keysListener::on_data_available(DDSDataReader* reader)
{
keysDataReader *keys_reader = NULL;
keysSeq data_seq;
DDS_SampleInfoSeq info_seq;
DDS_ReturnCode_t retcode;
int i;
keys_reader = keysDataReader::narrow(reader);
if (keys_reader == NULL) {
printf("DataReader narrow error\n");
return;
}
while(true) {
/* Given DDS_HANDLE_NIL as a parameter, take_next_instance returns
a sequence containing samples from only the next (in a well-determined
but unspecified order) un-taken instance.
*/
retcode = keys_reader->take_next_instance(
data_seq, info_seq, DDS_LENGTH_UNLIMITED, DDS_HANDLE_NIL,
DDS_ANY_SAMPLE_STATE, DDS_ANY_VIEW_STATE, DDS_ANY_INSTANCE_STATE);
if (retcode == DDS_RETCODE_NO_DATA) {
break;
} else if (retcode != DDS_RETCODE_OK) {
printf("read error %d\n", retcode);
break;
}
/* We process all the obtained samples for a particular instance */
for (i = 0; i < data_seq.length(); ++i) {
/* We first check if the sample includes valid data */
if (info_seq[i].valid_data) {
if (info_seq[i].view_state == DDS_NEW_VIEW_STATE) {
new_instance_found(keys_reader, &info_seq[i], &data_seq[i]);
}
/* We check if the obtained samples are associated to one
of the instances of interest.
Since take_next_instance gives sequences of the same instance,
we only need to test this for the first sample obtained.
*/
if (i == 0 && !key_is_relevant(&data_seq[i])) {
break;
}
handle_data(keys_reader, &info_seq[i], &data_seq[i]);
} else {
/* Since there is not valid data, it may include metadata */
keys dummy;
retcode = keys_reader->get_key_value(dummy, info_seq[i].instance_handle);
if (retcode != DDS_RETCODE_OK) {
printf("get_key_value error %d\n", retcode);
continue;
}
/* Here we print a message and change the instance state
if the instance state is ALIVE_NO_WRITERS or ALIVE_DISPOSED */
if (info_seq[i].instance_state == DDS_NOT_ALIVE_NO_WRITERS_INSTANCE_STATE) {
instance_lost_writers(keys_reader, &info_seq[i], &dummy);
} else if (info_seq[i].instance_state == DDS_NOT_ALIVE_DISPOSED_INSTANCE_STATE) {
instance_disposed(keys_reader, &info_seq[i], &dummy);
}
}
}
/* Prepare sequences for next take_next_instance */
retcode = keys_reader->return_loan(data_seq, info_seq);
if (retcode != DDS_RETCODE_OK) {
printf("return loan error %d\n", retcode);
}
data_seq.maximum(0);
info_seq.maximum(0);
}
}
void keysListener::new_instance_found(keysDataReader* keys_reader,
const DDS_SampleInfo* info,
const keys* msg)
{
/* There are three cases here:
1.) truly new instance
2.) instance lost all writers, but now we're getting data again
3.) instance was disposed, but a new one has been created
We distinguish these cases by examining generation counts, BUT
note that if the instance resources have been reclaimed, the
generation counts may be reset to 0.
Instances are eligible for resource cleanup if there are no
active writers and all samples have been taken. To reliably
determine which case a 'new' instance falls into, the application
must store state information on a per-instance basis.
Note that this example assumes that state changes only occur via
explicit register_instance(), unregister_instance() and dispose()
calls from the datawriter. In reality, these changes could also
occur due to lost liveliness or missed deadlines, so those
listeners would also need to update the instance state.
*/
switch (states[msg->code]) {
case inactive:
printf("New instance found; code = %d\n", msg->code);
break;
case active:
/* An active instance should never be interpreted as new */
printf("Error, 'new' already-active instance found; code = %d\n", msg->code);
break;
case no_writers:
printf("Found writer for instance; code = %d\n", msg->code);
break;
case disposed:
printf("Found reborn instance; code = %d\n", msg->code);
break;
}
states[msg->code] = active;
}
void keysListener::instance_lost_writers(keysDataReader* keys_reader,
const DDS_SampleInfo* info,
const keys* msg)
{
printf("Instance has no writers; code = %d\n", msg->code);
states[msg->code] = no_writers;
}
void keysListener::instance_disposed(keysDataReader* keys_reader,
const DDS_SampleInfo* info,
const keys* msg)
{
printf("Instance disposed; code = %d\n", msg->code);
states[msg->code] = disposed;
}
/* Called to handle relevant data samples */
void keysListener::handle_data(keysDataReader* keys_reader,
const DDS_SampleInfo* info,
const keys* msg) {
printf("code: %d, x: %d, y: %d\n", msg->code,
msg->x, msg->y);
}
bool keysListener::key_is_relevant(const keys* msg)
{
/* For this example we just care about codes > 0,
which are the ones related to instances ins1 and ins2 .*/
return (msg->code > 0);
}
/**** End changes for Advanced_Keys ****/
/* Delete all entities */
static int subscriber_shutdown(
DDSDomainParticipant *participant)
{
DDS_ReturnCode_t retcode;
int status = 0;
if (participant != NULL) {
retcode = participant->delete_contained_entities();
if (retcode != DDS_RETCODE_OK) {
printf("delete_contained_entities error %d\n", retcode);
status = -1;
}
retcode = DDSTheParticipantFactory->delete_participant(participant);
if (retcode != DDS_RETCODE_OK) {
printf("delete_participant error %d\n", retcode);
status = -1;
}
}
/* RTI Connext provides the finalize_instance() method on
domain participant factory for people who want to release memory used
by the participant factory. Uncomment the following block of code for
clean destruction of the singleton. */
/*
retcode = DDSDomainParticipantFactory::finalize_instance();
if (retcode != DDS_RETCODE_OK) {
printf("finalize_instance error %d\n", retcode);
status = -1;
}
*/
return status;
}
extern "C" int subscriber_main(int domainId, int sample_count)
{
DDSDomainParticipant *participant = NULL;
DDSSubscriber *subscriber = NULL;
DDSTopic *topic = NULL;
keysListener *reader_listener = NULL;
DDSDataReader *reader = NULL;
DDS_ReturnCode_t retcode;
const char *type_name = NULL;
int count = 0;
DDS_Duration_t receive_period = {1,0};
int status = 0;
/* To customize the participant QoS, use
the configuration file USER_QOS_PROFILES.xml */
participant = DDSTheParticipantFactory->create_participant(
domainId, DDS_PARTICIPANT_QOS_DEFAULT,
NULL /* listener */, DDS_STATUS_MASK_NONE);
if (participant == NULL) {
printf("create_participant error\n");
subscriber_shutdown(participant);
return -1;
}
/* To customize the subscriber QoS, use
the configuration file USER_QOS_PROFILES.xml */
subscriber = participant->create_subscriber(
DDS_SUBSCRIBER_QOS_DEFAULT, NULL /* listener */, DDS_STATUS_MASK_NONE);
if (subscriber == NULL) {
printf("create_subscriber error\n");
subscriber_shutdown(participant);
return -1;
}
/* Register the type before creating the topic */
type_name = keysTypeSupport::get_type_name();
retcode = keysTypeSupport::register_type(
participant, type_name);
if (retcode != DDS_RETCODE_OK) {
printf("register_type error %d\n", retcode);
subscriber_shutdown(participant);
return -1;
}
/* To customize the topic QoS, use
the configuration file USER_QOS_PROFILES.xml */
topic = participant->create_topic(
"Example keys",
type_name, DDS_TOPIC_QOS_DEFAULT, NULL /* listener */,
DDS_STATUS_MASK_NONE);
if (topic == NULL) {
printf("create_topic error\n");
subscriber_shutdown(participant);
return -1;
}
/* Create a data reader listener */
reader_listener = new keysListener();
/* To customize the data reader QoS, use
the configuration file USER_QOS_PROFILES.xml */
reader = subscriber->create_datareader(
topic, DDS_DATAREADER_QOS_DEFAULT, reader_listener,
DDS_STATUS_MASK_ALL);
/* If you want to set the writer_data_lifecycle QoS settings
* programmatically rather than using the XML, you will need to add
* the following lines to your code and comment out the create_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;
}
datareader_qos.ownership.kind = DDS_EXCLUSIVE_OWNERSHIP_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;
}
/* Main loop */
for (count=0; (sample_count == 0) || (count < sample_count); ++count) {
//printf("keys subscriber sleeping for %d sec...\n", receive_period.sec);
NDDSUtility::sleep(receive_period);
}
/* Delete all entities */
status = subscriber_shutdown(participant);
delete reader_listener;
return status;
}
#if defined(RTI_WINCE)
int wmain(int argc, wchar_t** argv)
{
int domainId = 0;
int sample_count = 0; /* infinite loop */
if (argc >= 2) {
domainId = _wtoi(argv[1]);
}
if (argc >= 3) {
sample_count = _wtoi(argv[2]);
}
/* Uncomment this to turn on additional logging
NDDSConfigLogger::get_instance()->
set_verbosity_by_category(NDDS_CONFIG_LOG_CATEGORY_API,
NDDS_CONFIG_LOG_VERBOSITY_STATUS_ALL);
*/
return subscriber_main(domainId, sample_count);
}
#elif !(defined(RTI_VXWORKS) && !defined(__RTP__)) && !defined(RTI_PSOS)
int main(int argc, char *argv[])
{
int domainId = 0;
int sample_count = 0; /* infinite loop */
if (argc >= 2) {
domainId = atoi(argv[1]);
}
if (argc >= 3) {
sample_count = atoi(argv[2]);
}
/* Uncomment this to turn on additional logging
NDDSConfigLogger::get_instance()->
set_verbosity_by_category(NDDS_CONFIG_LOG_CATEGORY_API,
NDDS_CONFIG_LOG_VERBOSITY_STATUS_ALL);
*/
return subscriber_main(domainId, sample_count);
}
#endif
#ifdef RTI_VX653
const unsigned char* __ctype = *(__ctypePtrGet());
extern "C" void usrAppInit ()
{
#ifdef USER_APPL_INIT
USER_APPL_INIT; /* for backwards compatibility */
#endif
/* add application specific code here */
taskSpawn("sub", RTI_OSAPI_THREAD_PRIORITY_NORMAL, 0x8, 0x150000, (FUNCPTR)subscriber_main, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
}
#endif
| cxx |
rticonnextdds-examples | data/projects/rticonnextdds-examples/keyed_data_advanced/c/keys_publisher.c | /*******************************************************************************
(c) 2005-2014 Copyright, Real-Time Innovations, Inc. All rights reserved.
RTI grants Licensee a license to use, modify, compile, and create derivative
works of the Software. Licensee has the right to distribute object form only
for use with RTI products. The Software is provided "as is", with no warranty
of any type, including any warranty for fitness for any purpose. RTI is under
no obligation to maintain or support the Software. RTI shall not be liable for
any incidental or consequential damages arising out of the use or inability to
use the software.
******************************************************************************/
/* keys_publisher.c
A publication of data of type keys
This file is derived from code automatically generated by the rtiddsgen
command:
rtiddsgen -language C -example <arch> keys.idl
Example publication of type keys automatically generated by
'rtiddsgen'. To test them follow these steps:
(1) Compile this file and the example subscription.
(2) Start the subscription with the command
objs/<arch>/keys_subscriber <domain_id> <sample_count>
(3) Start the publication with the command
objs/<arch>/keys_publisher <domain_id> <sample_count>
(4) [Optional] Specify the list of discovery initial peers and
multicast receive addresses via an environment variable or a file
(in the current working directory) called NDDS_DISCOVERY_PEERS.
You can run any number of publishers and subscribers programs, and can
add and remove them dynamically from the domain.
Example:
To run the example application on domain <domain_id>:
On Unix:
objs/<arch>/keys_publisher <domain_id>
objs/<arch>/keys_subscriber <domain_id>
On Windows:
objs\<arch>\keys_publisher <domain_id>
objs\<arch>\keys_subscriber <domain_id>
modification history
------------ -------
*/
#include <stdio.h>
#include <stdlib.h>
#include "ndds/ndds_c.h"
#include "keys.h"
#include "keysSupport.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;
DDS_DataWriter *writer2 = NULL;
keysDataWriter *keys_writer = NULL;
keysDataWriter *keys_writer2 = NULL;
DDS_ReturnCode_t retcode;
/* Creates three instances */
keys* instance[3] = {NULL, NULL, NULL};
/* Creates three handles for managing the registrations */
DDS_InstanceHandle_t handle[3];
/* Make variables for the instance for the second datawriter to use.
Note that it actually refers to the same logical instance, but
because we're running both datawriters in the same thread, we
to create separate variables so they don't clobber each other.
*/
keys* instance_dw2 = NULL;
DDS_InstanceHandle_t handle_dw2 = DDS_HANDLE_NIL;
/* We only will send data over the instances marked as active */
int active[3] = {1, 0, 0};
int active_dw2 = 1;
/* We are going to load different QoS profiles for the two DWs */
struct DDS_DataWriterQos datawriter_qos = DDS_DataWriterQos_INITIALIZER;
const char *type_name = NULL;
int count = 0;
struct DDS_Duration_t send_period = {1,0};
int i = 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 = keysTypeSupport_get_type_name();
retcode = keysTypeSupport_register_type(
participant, type_name);
if (retcode != DDS_RETCODE_OK) {
printf("register_type error %d\n", retcode);
publisher_shutdown(participant);
return -1;
}
/* To customize topic QoS, use
the configuration file USER_QOS_PROFILES.xml */
topic = DDS_DomainParticipant_create_topic(
participant, "Example keys",
type_name, &DDS_TOPIC_QOS_DEFAULT, NULL /* listener */,
DDS_STATUS_MASK_NONE);
if (topic == NULL) {
printf("create_topic error\n");
publisher_shutdown(participant);
return -1;
}
/* To customize data writer QoS, use
the configuration file USER_QOS_PROFILES.xml */
writer = DDS_Publisher_create_datawriter(
publisher, topic,
&DDS_DATAWRITER_QOS_DEFAULT, NULL /* listener */, DDS_STATUS_MASK_NONE);
retcode = DDS_DomainParticipantFactory_get_datawriter_qos_from_profile(
DDS_TheParticipantFactory,&datawriter_qos,"keys_Library","keys_Profile_dw2");
if (retcode != DDS_RETCODE_OK) {
printf("get_datawriter_qos_from_profile error\n");
return -1;
}
/* If you want to set the writer_data_lifecycle QoS settings
* programmatically rather than using the XML, you will need to add
* the following lines to your code and comment out the create_datawriter
* and get_datawriter_qos_from_profile calls above.
*/
/*
retcode = DDS_Publisher_get_default_datawriter_qos(publisher, &datawriter_qos);
if (retcode != DDS_RETCODE_OK) {
printf("get_default_datawriter_qos error\n");
return -1;
}
datawriter_qos.writer_data_lifecycle.autodispose_unregistered_instances =
DDS_BOOLEAN_FALSE;
datawriter_qos.ownership.kind = DDS_EXCLUSIVE_OWNERSHIP_QOS;
datawriter_qos.ownership_strength.value = 10;
writer = DDS_Publisher_create_datawriter(
publisher, topic,
&datawriter_qos, NULL, DDS_STATUS_MASK_NONE);
datawriter_qos.ownership_strength.value = 5;
*/
writer2 = DDS_Publisher_create_datawriter(
publisher, topic,
&datawriter_qos, NULL, DDS_STATUS_MASK_NONE);
if (writer == NULL) {
printf("create_datawriter1 error\n");
publisher_shutdown(participant);
return -1;
}
if (writer2 == NULL) {
printf("create_datawriter2 error\n");
publisher_shutdown(participant);
return -1;
}
keys_writer = keysDataWriter_narrow(writer);
if (keys_writer == NULL) {
printf("DataWriter narrow error\n");
publisher_shutdown(participant);
return -1;
}
keys_writer2 = keysDataWriter_narrow(writer2);
if (keys_writer2 == NULL) {
printf("DataWriter narrow error\n");
publisher_shutdown(participant);
return -1;
}
/* Create data sample for writing */
instance[0] = keysTypeSupport_create_data_ex(DDS_BOOLEAN_TRUE);
instance[1] = keysTypeSupport_create_data_ex(DDS_BOOLEAN_TRUE);
instance[2] = keysTypeSupport_create_data_ex(DDS_BOOLEAN_TRUE);
if (instance[0] == NULL || instance[1] == NULL || instance[2] == NULL) {
printf("keysTypeSupport_create_data error\n");
publisher_shutdown(participant);
return -1;
}
/* RTI Connext could examine the key fields each time it needs to determine
* which data-instance is being modified.
* However, for performance and semantic reasons, it is better
* for your application to declare all the data-instances it intends to
* modify prior to actually writing any samples. This is known as registration.
*/
/* In order to register the instances, we must set their associated keys first */
instance[0]->code = 0;
instance[1]->code = 1;
instance[2]->code = 2;
handle[0] = DDS_HANDLE_NIL;
handle[1] = DDS_HANDLE_NIL;
handle[2] = DDS_HANDLE_NIL;
/* The keys must have been set before making this call */
printf("Registering instance %d\n", instance[0]->code);
handle[0] = keysDataWriter_register_instance(keys_writer, instance[0]);
/* Modify the data to be sent here */
instance[0]->x = 1;
instance[1]->x = 1;
instance[2]->x = 1;
/* Make variables for the instance for the second datawriter to use.
Note that it actually refers to the same logical instance, but
because we're running both datawriters in the same thread, we
to create separate variables so they don't clobber each other.
*/
instance_dw2 = keysTypeSupport_create_data_ex(DDS_BOOLEAN_TRUE);
if (instance_dw2 == NULL) {
printf("keysTypeSupport_create_data error\n");
publisher_shutdown(participant);
return -1;
}
/* instance_dw2 and instance[1] have the same key, and thus
will write to the same instance (ins1).
*/
instance_dw2->code = instance[1]->code;
instance_dw2->x = 2;
handle_dw2 = keysDataWriter_register_instance(keys_writer2, instance_dw2);
/* Main loop */
for (count=0; (sample_count == 0) || (count < sample_count); ++count) {
NDDS_Utility_sleep(&send_period);
/* Modify the data to be sent here */
instance[0]->y = count;
instance[1]->y = count + 1000;
instance[2]->y = count + 2000;
instance_dw2->y = -count - 1000;
/* We control two datawriters via a state machine here rather than
introducing separate threads.
*/
/* Control first DataWriter */
switch (count) {
case 4: { /* Start sending the second (ins1) and third instances (ins2) */
printf("----DW1 registering instance %d\n", instance[1]->code);
printf("----DW1 registering instance %d\n", instance[2]->code);
handle[1] = keysDataWriter_register_instance(keys_writer, instance[1]);
handle[2] = keysDataWriter_register_instance(keys_writer, instance[2]);
active[1] = 1;
active[2] = 1;
} break;
case 8: { /* Dispose the second instance (ins1) */
printf("----DW1 disposing instance %d\n", instance[1]->code);
retcode = keysDataWriter_dispose(keys_writer, instance[1], &handle[1]);
if (retcode != DDS_RETCODE_OK) {
printf("dispose instance error %d\n", retcode);
return -1;
}
active[1] = 0;
} break;
case 10: { /* Unregister the second instance (ins1) */
printf("----DW1 unregistering instance %d\n", instance[1]->code);
retcode = keysDataWriter_unregister_instance(keys_writer, instance[1], &handle[1]);
if (retcode != DDS_RETCODE_OK) {
printf("unregister instance error %d\n", retcode);
return -1;
}
active[1] = 0;
} break;
case 12: { /* Unregister the third instance (ins2) */
printf("----DW1 unregistering instance %d\n", instance[2]->code);
retcode = keysDataWriter_unregister_instance(keys_writer, instance[2], &handle[2]);
if (retcode != DDS_RETCODE_OK) {
printf("dispose instance error %d\n", retcode);
return -1;
}
active[2] = 0;
/* Re-register the second instance (ins1) */
printf("----DW1 re-registering instance %d\n", instance[1]->code);
handle[1] = keysDataWriter_register_instance(keys_writer, instance[1]);
active[1] = 1;
} break;
case 16: { /* Re-register the third instance (ins2) */
printf("----DW1 re-registering instance %d\n", instance[2]->code);
handle[2] = keysDataWriter_register_instance(keys_writer, instance[2]);
active[2] = 1;
} break;
}
for (i = 0; i < 3; ++i) {
if (active[i]) {
printf("DW1 write; code: %d, x: %d, y: %d\n",
instance[i]->code, instance[i]->x, instance[i]->y);
retcode = keysDataWriter_write(keys_writer, instance[i], &handle[i]);
if (retcode != DDS_RETCODE_OK) {
printf("write error %d\n", retcode);
return -1;
}
}
}
/* Control second datawriter */
switch (count) {
case 16: { /* Dispose the instance (ins1).
Since it has lower ownership strength, this does nothing */
printf("----DW2 disposing instance %d\n", instance_dw2->code);
retcode = keysDataWriter_dispose(keys_writer2, instance_dw2, &handle_dw2);
if (retcode != DDS_RETCODE_OK) {
printf("DW2 dispose instance error %d\n", retcode);
}
active_dw2 = 0;
} break;
}
if (active_dw2) {
printf("DW2 write; code: %d, x: %d, y: %d\n",
instance_dw2->code, instance_dw2->x, instance_dw2->y);
retcode = keysDataWriter_write(keys_writer2, instance_dw2, &handle_dw2);
if (retcode != DDS_RETCODE_OK) {
printf("write error %d\n", retcode);
return -1;
}
}
}
/* Delete data samples */
for (i = 0; i < 3; ++i) {
retcode = keysTypeSupport_delete_data(instance[i]);
if (retcode != DDS_RETCODE_OK) {
printf("keysTypeSupport::delete_data error %d\n", retcode);
}
}
retcode = keysTypeSupport_delete_data(instance_dw2);
if (retcode != DDS_RETCODE_OK) {
printf("keysTypeSupport::delete_data error %d\n", retcode);
}
/* Cleanup and delete delete all entities */
return publisher_shutdown(participant);
}
#if defined(RTI_WINCE)
int wmain(int argc, wchar_t** argv)
{
int domainId = 0;
int sample_count = 0; /* infinite loop */
if (argc >= 2) {
domainId = _wtoi(argv[1]);
}
if (argc >= 3) {
sample_count = _wtoi(argv[2]);
}
/* Uncomment this to turn on additional logging
NDDS_Config_Logger_set_verbosity_by_category(
NDDS_Config_Logger_get_instance(),
NDDS_CONFIG_LOG_CATEGORY_API,
NDDS_CONFIG_LOG_VERBOSITY_STATUS_ALL);
*/
return publisher_main(domainId, sample_count);
}
#elif !(defined(RTI_VXWORKS) && !defined(__RTP__)) && !defined(RTI_PSOS)
int main(int argc, char *argv[])
{
int domainId = 0;
int sample_count = 0; /* infinite loop */
if (argc >= 2) {
domainId = atoi(argv[1]);
}
if (argc >= 3) {
sample_count = atoi(argv[2]);
}
/* Uncomment this to turn on additional logging
NDDS_Config_Logger_set_verbosity_by_category(
NDDS_Config_Logger_get_instance(),
NDDS_CONFIG_LOG_CATEGORY_API,
NDDS_CONFIG_LOG_VERBOSITY_STATUS_ALL);
*/
return publisher_main(domainId, sample_count);
}
#endif
#ifdef RTI_VX653
const unsigned char* __ctype = NULL;
void usrAppInit ()
{
#ifdef USER_APPL_INIT
USER_APPL_INIT; /* for backwards compatibility */
#endif
/* add application specific code here */
taskSpawn("pub", RTI_OSAPI_THREAD_PRIORITY_NORMAL, 0x8, 0x150000, (FUNCPTR)publisher_main, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
}
#endif
| c |
rticonnextdds-examples | data/projects/rticonnextdds-examples/keyed_data_advanced/c/keys_subscriber.c | /*******************************************************************************
(c) 2005-2014 Copyright, Real-Time Innovations, Inc. All rights reserved.
RTI grants Licensee a license to use, modify, compile, and create derivative
works of the Software. Licensee has the right to distribute object form only
for use with RTI products. The Software is provided "as is", with no warranty
of any type, including any warranty for fitness for any purpose. RTI is under
no obligation to maintain or support the Software. RTI shall not be liable for
any incidental or consequential damages arising out of the use or inability to
use the software.
******************************************************************************/
/* keys_subscriber.c
A subscription example
This file is derived from code automatically generated by the rtiddsgen
command:
rtiddsgen -language C -example <arch> keys.idl
Example subscription of type keys automatically generated by
'rtiddsgen'. To test them, follow these steps:
(1) Compile this file and the example publication.
(2) Start the subscription with the command
objs/<arch>/keys_subscriber <domain_id> <sample_count>
(3) Start the publication with the command
objs/<arch>/keys_publisher <domain_id> <sample_count>
(4) [Optional] Specify the list of discovery initial peers and
multicast receive addresses via an environment variable or a file
(in the current working directory) called NDDS_DISCOVERY_PEERS.
You can run any number of publishers and subscribers programs, and can
add and remove them dynamically from the domain.
Example:
To run the example application on domain <domain_id>:
On UNIX systems:
objs/<arch>/keys_publisher <domain_id>
objs/<arch>/keys_subscriber <domain_id>
On Windows systems:
objs\<arch>\keys_publisher <domain_id>
objs\<arch>\keys_subscriber <domain_id>
modification history
------------ -------
*/
#include <stdio.h>
#include <stdlib.h>
#include "ndds/ndds_c.h"
#include "keys.h"
#include "keysSupport.h"
void keysListener_on_requested_deadline_missed(
void* listener_data,
DDS_DataReader* reader,
const struct DDS_RequestedDeadlineMissedStatus *status)
{
}
void keysListener_on_requested_incompatible_qos(
void* listener_data,
DDS_DataReader* reader,
const struct DDS_RequestedIncompatibleQosStatus *status)
{
}
void keysListener_on_sample_rejected(
void* listener_data,
DDS_DataReader* reader,
const struct DDS_SampleRejectedStatus *status)
{
}
void keysListener_on_liveliness_changed(
void* listener_data,
DDS_DataReader* reader,
const struct DDS_LivelinessChangedStatus *status)
{
}
void keysListener_on_sample_lost(
void* listener_data,
DDS_DataReader* reader,
const struct DDS_SampleLostStatus *status)
{
}
void keysListener_on_subscription_matched(
void* listener_data,
DDS_DataReader* reader,
const struct DDS_SubscriptionMatchedStatus *status)
{
}
/**** Start changes for Advanced_Keys ****/
/* Track instance state */
#define INSTANCE_STATE_INACTIVE 0
#define INSTANCE_STATE_ACTIVE 1
#define INSTANCE_STATE_NO_WRITERS 2
#define INSTANCE_STATE_DISPOSED 3
int states[3] = {INSTANCE_STATE_INACTIVE, INSTANCE_STATE_INACTIVE, INSTANCE_STATE_INACTIVE};
/* These are not called by DDS. on_data_available() calls
the appropriate function when it gets updates about
an instances' status
*/
void keysListener_new_instance_found(keysDataReader* keys_reader,
const struct DDS_SampleInfo* info,
const struct keys* msg);
void keysListener_instance_lost_writers(keysDataReader* keys_reader,
const struct DDS_SampleInfo* info,
const struct keys* msg);
void keysListener_instance_disposed(keysDataReader* keys_reader,
const struct DDS_SampleInfo* info,
const struct keys* msg);
/* Called to handle relevant data samples */
void keysListener_handle_data(keysDataReader* keys_reader,
const struct DDS_SampleInfo* info,
const struct keys* msg);
/* Called to determine if a key is relevant to this application */
int keysListener_key_is_relevant(const struct keys* msg);
void keysListener_on_data_available(
void* listener_data,
DDS_DataReader* reader)
{
keysDataReader *keys_reader = NULL;
struct keysSeq data_seq = DDS_SEQUENCE_INITIALIZER;
struct DDS_SampleInfoSeq info_seq = DDS_SEQUENCE_INITIALIZER;
DDS_ReturnCode_t retcode;
int i;
keys_reader = keysDataReader_narrow(reader);
if (keys_reader == NULL) {
printf("DataReader narrow error\n");
return;
}
while(1) {
/* Given DDS_HANDLE_NIL as a parameter, take_next_instance returns
a sequence containing samples from only the next (in a well-determined
but unspecified order) un-taken instance.
*/
retcode = keysDataReader_take_next_instance(
keys_reader, &data_seq, &info_seq, DDS_LENGTH_UNLIMITED, &DDS_HANDLE_NIL,
DDS_ANY_SAMPLE_STATE, DDS_ANY_VIEW_STATE, DDS_ANY_INSTANCE_STATE);
if (retcode == DDS_RETCODE_NO_DATA) {
break;
} else if (retcode != DDS_RETCODE_OK) {
printf("read error %d\n", retcode);
break;
}
/* We process all the obtained samples for a particular instance */
for (i = 0; i < keysSeq_get_length(&data_seq); ++i) {
struct DDS_SampleInfo* info = NULL;
struct keys* data = NULL;
info = DDS_SampleInfoSeq_get_reference(&info_seq, i);
data = keysSeq_get_reference(&data_seq, i);
/* We first check if the sample includes valid data */
if (info->valid_data) {
if (info->view_state == DDS_NEW_VIEW_STATE) {
keysListener_new_instance_found(keys_reader, info, data);
}
/* We check if the obtained samples are associated to one
of the instances of interest.
Since take_next_instance gives sequences of the same instance,
we only need to test this for the first sample obtained.
*/
if (i == 0 && !keysListener_key_is_relevant(data)) {
break;
}
keysListener_handle_data(keys_reader, info, data);
} else {
/* Since there is not valid data, it may include metadata */
keys dummy;
retcode = keysDataReader_get_key_value(keys_reader, &dummy, &info->instance_handle);
if (retcode != DDS_RETCODE_OK) {
printf("get_key_value error %d\n", retcode);
continue;
}
/* Here we print a message and change the instance state
if the instance state is ALIVE_NO_WRITERS or ALIVE_DISPOSED */
if (info->instance_state == DDS_NOT_ALIVE_NO_WRITERS_INSTANCE_STATE) {
keysListener_instance_lost_writers(keys_reader, info, &dummy);
} else if (info->instance_state == DDS_NOT_ALIVE_DISPOSED_INSTANCE_STATE) {
keysListener_instance_disposed(keys_reader, info, &dummy);
}
}
}
/* Prepare sequences for next take_next_instance */
retcode = keysDataReader_return_loan(keys_reader, &data_seq, &info_seq);
if (retcode != DDS_RETCODE_OK) {
printf("return loan error %d\n", retcode);
}
keysSeq_set_maximum(&data_seq, 0);
DDS_SampleInfoSeq_set_maximum(&info_seq, 0);
}
}
void keysListener_new_instance_found(keysDataReader* keys_reader,
const struct DDS_SampleInfo* info,
const struct keys* msg)
{
/* There are really three cases here:
1.) truly new instance
2.) instance lost all writers, but now we're getting data again
3.) instance was disposed, but a new one has been created
We distinguish these cases by examining generation counts, BUT
note that if the instance resources have been reclaimed, the
generation counts may be reset to 0.
Instances are eligible for resource cleanup if there are no
active writers and all samples have been taken. To reliably
determine which case a 'new' instance falls into, the application
must store state information on a per-instance basis.
Note that this example assumes that state changes only occur via
explicit register_instance(), unregister_instance() and dispose()
calls from the datawriter. In reality, these changes could also
occur due to lost liveliness or missed deadlines, so those
listeners would also need to update the instance state.
*/
switch (states[msg->code]) {
case INSTANCE_STATE_INACTIVE:
printf("New instance found; code = %d\n", msg->code);
break;
case INSTANCE_STATE_ACTIVE:
/* An active instance should never be interpreted as new */
printf("Error, 'new' already-active instance found; code = %d\n", msg->code);
break;
case INSTANCE_STATE_NO_WRITERS:
printf("Found writer for instance; code = %d\n", msg->code);
break;
case INSTANCE_STATE_DISPOSED:
printf("Found reborn instance; code = %d\n", msg->code);
break;
}
states[msg->code] = INSTANCE_STATE_ACTIVE;
}
void keysListener_instance_lost_writers(keysDataReader* keys_reader,
const struct DDS_SampleInfo* info,
const struct keys* msg)
{
printf("Instance has no writers; code = %d\n", msg->code);
states[msg->code] = INSTANCE_STATE_NO_WRITERS;
}
void keysListener_instance_disposed(keysDataReader* keys_reader,
const struct DDS_SampleInfo* info,
const struct keys* msg)
{
printf("Instance disposed; code = %d\n", msg->code);
states[msg->code] = INSTANCE_STATE_DISPOSED;
}
/* Called to handle relevant data samples */
void keysListener_handle_data(keysDataReader* keys_reader,
const struct DDS_SampleInfo* info,
const struct keys* msg)
{
printf("code: %d, x: %d, y: %d\n", msg->code,
msg->x, msg->y);
}
int keysListener_key_is_relevant(const struct keys* msg)
{
/* For this example we just care about codes > 0,
which are the ones related to instances ins1 and ins2 .*/
return (msg->code > 0)?1:0;
}
/**** End changes for Advanced_Keys ****/
/* Delete all entities */
static int subscriber_shutdown(
DDS_DomainParticipant *participant)
{
DDS_ReturnCode_t retcode;
int status = 0;
if (participant != NULL) {
retcode = DDS_DomainParticipant_delete_contained_entities(participant);
if (retcode != DDS_RETCODE_OK) {
printf("delete_contained_entities error %d\n", retcode);
status = -1;
}
retcode = DDS_DomainParticipantFactory_delete_participant(
DDS_TheParticipantFactory, participant);
if (retcode != DDS_RETCODE_OK) {
printf("delete_participant error %d\n", retcode);
status = -1;
}
}
/* RTI Connext provides the finalize_instance() method on
domain participant factory for users who want to release memory used
by the participant factory. Uncomment the following block of code for
clean destruction of the singleton. */
/*
retcode = DDS_DomainParticipantFactory_finalize_instance();
if (retcode != DDS_RETCODE_OK) {
printf("finalize_instance error %d\n", retcode);
status = -1;
}
*/
return status;
}
static int subscriber_main(int domainId, int sample_count)
{
DDS_DomainParticipant *participant = NULL;
DDS_Subscriber *subscriber = NULL;
DDS_Topic *topic = NULL;
struct DDS_DataReaderListener reader_listener =
DDS_DataReaderListener_INITIALIZER;
DDS_DataReader *reader = NULL;
DDS_ReturnCode_t retcode;
const char *type_name = NULL;
int count = 0;
struct DDS_Duration_t poll_period = {1,0};
/* If you want to set the DataReader QoS settings
* programmatically rather than using the XML, you will need to add
* the following line to your code
*/
/*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 = keysTypeSupport_get_type_name();
retcode = keysTypeSupport_register_type(participant, type_name);
if (retcode != DDS_RETCODE_OK) {
printf("register_type error %d\n", retcode);
subscriber_shutdown(participant);
return -1;
}
/* To customize topic QoS, use
the configuration file USER_QOS_PROFILES.xml */
topic = DDS_DomainParticipant_create_topic(
participant, "Example keys",
type_name, &DDS_TOPIC_QOS_DEFAULT, NULL /* listener */,
DDS_STATUS_MASK_NONE);
if (topic == NULL) {
printf("create_topic error\n");
subscriber_shutdown(participant);
return -1;
}
/* Set up a data reader listener */
reader_listener.on_requested_deadline_missed =
keysListener_on_requested_deadline_missed;
reader_listener.on_requested_incompatible_qos =
keysListener_on_requested_incompatible_qos;
reader_listener.on_sample_rejected =
keysListener_on_sample_rejected;
reader_listener.on_liveliness_changed =
keysListener_on_liveliness_changed;
reader_listener.on_sample_lost =
keysListener_on_sample_lost;
reader_listener.on_subscription_matched =
keysListener_on_subscription_matched;
reader_listener.on_data_available =
keysListener_on_data_available;
/* To customize data reader QoS, use
the configuration file USER_QOS_PROFILES.xml */
reader = DDS_Subscriber_create_datareader(
subscriber, DDS_Topic_as_topicdescription(topic),
&DDS_DATAREADER_QOS_DEFAULT, &reader_listener, DDS_STATUS_MASK_ALL);
/* If you want to set the writer_data_lifecycle QoS settings
* programmatically rather than using the XML, you will need to add
* the following lines to your code and comment out the create_datareader
* call above.
*/
/*
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.ownership.kind = DDS_EXCLUSIVE_OWNERSHIP_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;
}
/* Main loop */
for (count=0; (sample_count == 0) || (count < sample_count); ++count) {
//printf("keys subscriber sleeping for %d sec...\n",poll_period.sec);
NDDS_Utility_sleep(&poll_period);
}
/* Cleanup and delete all entities */
return subscriber_shutdown(participant);
}
#if defined(RTI_WINCE)
int wmain(int argc, wchar_t** argv)
{
int domainId = 0;
int sample_count = 0; /* infinite loop */
if (argc >= 2) {
domainId = _wtoi(argv[1]);
}
if (argc >= 3) {
sample_count = _wtoi(argv[2]);
}
/* Uncomment this to turn on additional logging
NDDS_Config_Logger_set_verbosity_by_category(
NDDS_Config_Logger_get_instance(),
NDDS_CONFIG_LOG_CATEGORY_API,
NDDS_CONFIG_LOG_VERBOSITY_STATUS_ALL);
*/
return subscriber_main(domainId, sample_count);
}
#elif !(defined(RTI_VXWORKS) && !defined(__RTP__)) && !defined(RTI_PSOS)
int main(int argc, char *argv[])
{
int domainId = 0;
int sample_count = 0; /* infinite loop */
if (argc >= 2) {
domainId = atoi(argv[1]);
}
if (argc >= 3) {
sample_count = atoi(argv[2]);
}
/* Uncomment this to turn on additional logging
NDDS_Config_Logger_set_verbosity_by_category(
NDDS_Config_Logger_get_instance(),
NDDS_CONFIG_LOG_CATEGORY_API,
NDDS_CONFIG_LOG_VERBOSITY_STATUS_ALL);
*/
return subscriber_main(domainId, sample_count);
}
#endif
#ifdef RTI_VX653
const unsigned char* __ctype = NULL;
void usrAppInit ()
{
#ifdef USER_APPL_INIT
USER_APPL_INIT; /* for backwards compatibility */
#endif
/* add application specific code here */
taskSpawn("sub", RTI_OSAPI_THREAD_PRIORITY_NORMAL, 0x8, 0x150000, (FUNCPTR)subscriber_main, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
}
#endif
| c |
rticonnextdds-examples | data/projects/rticonnextdds-examples/keyed_data_advanced/c++03/keys_publisher.cxx | /*******************************************************************************
(c) 2005-2015 Copyright, Real-Time Innovations, Inc. All rights reserved.
RTI grants Licensee a license to use, modify, compile, and create derivative
works of the Software. Licensee has the right to distribute object form only
for use with RTI products. The Software is provided "as is", with no warranty
of any type, including any warranty for fitness for any purpose. RTI is under
no obligation to maintain or support the Software. RTI shall not be liable for
any incidental or consequential damages arising out of the use or inability to
use the software.
******************************************************************************/
#include <cstdlib>
#include <iostream>
#include <dds/dds.hpp>
#include "keys.hpp"
using namespace dds::core;
using namespace dds::core::policy;
using namespace rti::core::policy;
using namespace dds::domain;
using namespace dds::topic;
using namespace dds::pub;
using namespace dds::pub::qos;
void publisher_main(int domain_id, int sample_count)
{
// Create a DomainParticipant with default Qos
DomainParticipant participant (domain_id);
// Create a Topic -- and automatically register the type
Topic<keys> topic (participant, "Example keys");
// Create a publisher for both DataWriters.
Publisher publisher(participant);
// Retrieve the default DataWriter QoS profile from USER_QOS_PROFILES.xml
// for the first writer.
DataWriterQos writer1_qos = QosProvider::Default().datawriter_qos();
// If you want to change the DataWriter's QoS programmatically rather than
// using the XML file, uncomment the following lines.
// writer1_qos << WriterDataLifecycle::ManuallyDisposeUnregisteredInstances()
// << Ownership::Exclusive()
// << OwnershipStrength(10)
// << Reliability::Reliable(Duration(60))
// << History::KeepAll()
// << DataWriterProtocol().rtps_reliable_writer(
// RtpsReliableWriterProtocol()
// .min_send_window_size(50)
// .max_send_window_size(50));
// Create a DataWriter with default Qos.
DataWriter<keys> writer1(publisher, topic, writer1_qos);
// Retrieve the keys_Profile_dw2 QoS profile from USER_QOS_PROFILES.xml
// for the second writer.
DataWriterQos writer2_qos = QosProvider::Default().datawriter_qos(
"keys_Library::keys_Profile_dw2");
// If you want to change the DataWriter's QoS programmatically rather than
// using the XML file, uncomment the following lines.
// writer2_qos << WriterDataLifecycle::ManuallyDisposeUnregisteredInstances()
// << Ownership::Exclusive()
// << OwnershipStrength(5);
DataWriter<keys> writer2(publisher, topic, writer2_qos);
std::vector<keys> samples1;
std::vector<InstanceHandle> instance_handles1;
std::vector<bool> samples1_active;
// RTI Connext could examine the key fields each time it needs to determine
// which data-instance is being modified. However, for performance and
// semantic reasons, it is better for your application to declare all the
// data-instances it intends to modify prior to actually writing any
// samples. This is known as registration.
int num_samples = 3;
for (int i = 0; i < num_samples; i++) {
// In order to register the instances, we must set their associated
// keys first.
keys k;
k.code(i);
// Initially, we register only the first sample.
if (i == 0) {
// The keys must have been set before making this call.
std::cout << "----DW1 registering instance " << k.code()
<< std::endl;
instance_handles1.push_back(writer1.register_instance(k));
samples1_active.push_back(true);
} else {
instance_handles1.push_back(InstanceHandle::nil());
samples1_active.push_back(false);
}
// Finally, we modify the data to be sent.
k.x(1);
samples1.push_back(k);
}
keys sample2(samples1[1].code(), 2, 0);
std::cout << "----DW2 registering instance " << sample2.code() << std::endl;
InstanceHandle instance_handle2 = writer2.register_instance(sample2);
bool sample2_active = true;
for (int count = 0; count < sample_count || sample_count == 0; count++) {
rti::util::sleep(Duration(2));
// Control first DataWriter.
if (count == 4) {
// Start sending the second and third instances.
std::cout << "----DW1 registering instance " << samples1[1].code()
<< std::endl
<< "----DW1 registering instance " << samples1[2].code()
<< std::endl;
instance_handles1[1] = writer1.register_instance(samples1[1]);
instance_handles1[2] = writer1.register_instance(samples1[2]);
samples1_active[1] = true;
samples1_active[2] = true;
} else if (count == 8) {
// Dispose the second instance.
std::cout << "----DW1 disposing instance " << samples1[1].code()
<< std::endl;
writer1.dispose_instance(instance_handles1[1]);
samples1_active[1] = false;
} else if (count == 10) {
// Unregister the second instance.
std::cout << "----DW1 unregistering instance " << samples1[1].code()
<< std::endl;
writer1.unregister_instance(instance_handles1[1]);
samples1_active[1] = false;
} else if (count == 12) {
// Unregister the third instance.
std::cout << "----DW1 unregistering instance " << samples1[2].code()
<< std::endl;
writer1.unregister_instance(instance_handles1[2]);
samples1_active[2] = false;
std::cout << "----DW1 re-registering instance "
<< samples1[1].code() << std::endl;
instance_handles1[1] = writer1.register_instance(samples1[1]);
samples1_active[1] = true;
} else if (count == 16) {
std::cout << "----DW1 re-registering instance "
<< samples1[2].code() << std::endl;
instance_handles1[2] = writer1.register_instance(samples1[2]);
samples1_active[2] = true;
}
// Send samples for writer 1
for (int i = 0; i < num_samples; i++) {
if (samples1_active[i]) {
samples1[i].y(count + i * 1000);
std::cout << "DW1 write; code: " << samples1[i].code()
<< ", x: " << samples1[i].x() << ", y: "
<< samples1[i].y() << std::endl;
writer1.write(samples1[i], instance_handles1[i]);
}
}
// Control second DataWriter
if (count == 16) {
// Dispose the instance.
// Since it has lower ownership strength, this does nothing.
std::cout << "----DW2 disposing instance " << sample2.code()
<< std::endl;
writer2.dispose_instance(instance_handle2);
sample2_active = false;
}
// Send sample for writer 2
sample2.y(-count - 1000);
if (sample2_active) {
std::cout << "DW2 write; code: " << sample2.code() << ", x: "
<< sample2.x() << ", y: " << sample2.y() << std::endl;
writer2.write(sample2, instance_handle2);
}
}
}
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/keyed_data_advanced/c++03/keys_subscriber.cxx | /*******************************************************************************
(c) 2005-2015 Copyright, Real-Time Innovations, Inc. All rights reserved.
RTI grants Licensee a license to use, modify, compile, and create derivative
works of the Software. Licensee has the right to distribute object form only
for use with RTI products. The Software is provided "as is", with no warranty
of any type, including any warranty for fitness for any purpose. RTI is under
no obligation to maintain or support the Software. RTI shall not be liable for
any incidental or consequential damages arising out of the use or inability to
use the software.
******************************************************************************/
#include <iostream>
#include <dds/dds.hpp>
#include <rti/core/ListenerBinder.hpp>
#include "keys.hpp"
using namespace dds::core;
using namespace dds::core::policy;
using namespace dds::domain;
using namespace dds::topic;
using namespace dds::sub;
using namespace rti::sub;
using namespace dds::sub::cond;
using namespace dds::sub::qos;
using namespace dds::sub::status;
class KeysReaderListener : public NoOpDataReaderListener<keys> {
public:
void on_data_available(DataReader<keys>& reader)
{
// To read the first instance the handle must be InstanceHandle::nil()
InstanceHandle previous_handle = InstanceHandle::nil();
LoanedSamples<keys> samples;
do {
samples = reader.select()
.next_instance(previous_handle)
.take();
// Update the previous handle to read the next instance.
if (samples.length() > 0) {
previous_handle = samples[0].info().instance_handle();
}
for (LoanedSamples<keys>::iterator sampleIt = samples.begin();
sampleIt != samples.end();
++sampleIt) {
const SampleInfo& info = sampleIt->info();
if (info.valid()) {
if (info.state().view_state() == ViewState::new_view()) {
new_instance_found(sampleIt->data());
}
handle_data(sampleIt->data());
} else {
// Since there is not valid data, it may include metadata.
keys key_sample;
reader.key_value(key_sample, info.instance_handle());
// Here we print a message and change the instance state
// if the instance state is
InstanceState inst_state = info.state().instance_state();
if (inst_state == InstanceState::not_alive_no_writers()) {
instance_lost_writers(key_sample);
} else if (inst_state==InstanceState::not_alive_disposed()){
instance_disposed(key_sample);
}
}
}
} while (samples.length() > 0);
}
void new_instance_found(const keys& msg)
{
// There are three cases here:
// 1.) truly new instance.
// 2.) instance lost all writers, but now we're getting data again.
// 3.) instance was disposed, but a new one has been created.
//
// We distinguish these cases by examining generation counts, BUT
// note that if the instance resources have been reclaimed, the
// generation counts may be reset to 0.
//
// Instances are eligible for resource cleanup if there are no
// active writers and all samples have been taken. To reliably
// determine which case a 'new' instance falls into, the application
// must store state information on a per-instance basis.
//
// Note that this example assumes that state changes only occur via
// explicit register_instance(), unregister_instance() and dispose()
// calls from the DataWriter. In reality, these changes could also
// occur due to lost liveliness or missed deadlines, so those
// listeners would also need to update the instance state.
int code = msg.code();
// If we don't have any information about it, it's a new instance.
if (sampleState.count(code) == 0) {
std::cout << "New instance found; code = " << code << std::endl;
} else if (sampleState[code] == InstanceState::alive()) {
std::cout << "Error, 'new' already-active instance found; code = "
<< code << std::endl;
} else if (sampleState[code] == InstanceState::not_alive_no_writers()) {
std::cout << "Found writer for instance; code = " << code
<< std::endl;
} else if (sampleState[code] == InstanceState::not_alive_disposed()) {
std::cout << "Found reborn instance; code = " << code << std::endl;
}
sampleState[code] = InstanceState::alive();
}
void instance_lost_writers(const keys& msg)
{
std::cout << "Instance has no writers; code = " << msg.code()
<< std::endl;
sampleState[msg.code()] = InstanceState::not_alive_no_writers();
}
void instance_disposed(const keys& msg)
{
std::cout << "Instance disposed; code = " << msg.code() << std::endl;
sampleState[msg.code()] = InstanceState::not_alive_disposed();
}
void handle_data(const keys& msg)
{
std::cout << "code: " << msg.code() << ", x: " << msg.x()
<< ", y: " << msg.y() << std::endl;
}
private:
std::map<int, InstanceState> sampleState;
};
void subscriber_main(int domain_id, int sample_count)
{
// Create a DomainParticipant with default Qos
DomainParticipant participant(domain_id);
// Create a Topic -- and automatically register the type
Topic<keys> topic(participant, "Example keys");
// Retrieve the default DataWriter QoS, from USER_QOS_PROFILES.xml
DataReaderQos reader_qos = QosProvider::Default().datareader_qos();
// If you want to change the DataReader's QoS programmatically rather than
// using the XML file, uncomment the following lines.
// reader_qos << Ownership::Exclusive();
// Create a DataReader with default Qos (Subscriber created in-line)
DataReader<keys> reader(Subscriber(participant), topic, reader_qos);
// Associate a listener using ListenerBinder, a RAII that will take care of
// setting it to NULL on destruction.
rti::core::ListenerBinder< DataReader<keys> > reader_listener =
rti::core::bind_and_manage_listener(
reader,
new KeysReaderListener,
dds::core::status::StatusMask::all());
// Main loop.
for (int count = 0; (sample_count == 0) || (count < sample_count); count++){
rti::util::sleep(Duration(2));
}
}
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/property_qos/c++/numbers_common.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.
******************************************************************************/
#ifndef NUMBERS_COMMON_H
#define NUMBERS_COMMON_H
/* numbers_common.h
*
* This file contains few macros that are used to configure the transport
* in the following files:
* - numbers_publisher.c++
* - numbers_subscriber.c++
*/
/* Comment the following macro to allow compilation on RTI DDS older than 4.2 */
#define USE_NDDS42_API
/* The new value of the transport socket size */
#define NEW_SOCKET_BUFFER_SIZE (65507)
#define NEW_SOCKET_BUFFER_SIZE_STRING ("65507")
/* Creates the domain participant, modifying the transport qos properties
* to increase the send and receive socket buffer size to 64k.
* Returns zero if success, non-zero in case of error.
*/
extern DDSDomainParticipant *numbers_common_create_participant(int domainId);
/* Reads the transport QoS and verify that are correctly set
* Returns zero if success, non-zero in case of error.
*/
extern int numbers_common_verify_qos(DDSDomainParticipant *part);
#endif | h |
rticonnextdds-examples | data/projects/rticonnextdds-examples/property_qos/c++/numbers_common.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.
******************************************************************************/
/* numbers_common.c
*
* This file contains the body of the numbers_common_create_participant
* function.
*/
#include <stdio.h>
#include <stdlib.h>
#include "ndds/ndds_cpp.h"
#include "numbers.h"
#include "numbersSupport.h"
#include "numbers_common.h"
#ifdef USE_NDDS42_API
/************************************************************************
* The following code modifies the transport QoS using the
* PropertyQoS, introduced in RTI DDS 4.2.
************************************************************************/
DDSDomainParticipant * numbers_common_create_participant(int domainId) {
struct DDS_DomainParticipantQos domainparticipant_qos = DDS_PARTICIPANT_QOS_DEFAULT;
DDS_ReturnCode_t retcode;
DDSDomainParticipant * part = NULL;
/* To customize participant QoS, use
DDS_DomainParticipantFactory_get_default_participant_qos() */
retcode = DDSTheParticipantFactory->get_default_participant_qos(domainparticipant_qos);
if (retcode != DDS_RETCODE_OK) {
puts("Error, impossible get default participant qos");
return NULL;
}
/* Set the send socket buffer size */
retcode = DDSPropertyQosPolicyHelper::add_property(domainparticipant_qos.property,
"dds.transport.UDPv4.builtin.send_socket_buffer_size" ,
NEW_SOCKET_BUFFER_SIZE_STRING,
DDS_BOOLEAN_FALSE);
if (retcode != DDS_RETCODE_OK) {
printf("Error, impossible add property");
return NULL;
}
/* Set the receive socket buffer size */
retcode = DDSPropertyQosPolicyHelper::add_property(domainparticipant_qos.property,
"dds.transport.UDPv4.builtin.recv_socket_buffer_size" ,
NEW_SOCKET_BUFFER_SIZE_STRING,
DDS_BOOLEAN_FALSE);
if (retcode != DDS_RETCODE_OK) {
printf("Error, impossible add property");
return NULL;
}
/* Create the participant */
part = DDSTheParticipantFactory->create_participant(
domainId, domainparticipant_qos,
NULL /* listener */, DDS_STATUS_MASK_NONE);
if (part == NULL) {
puts("create_participant error");
return NULL;
}
return part;
}
#else
/************************************************************************
* This is the "classic" method for changing the transport QoS.
*
* It shows how to change QoS without using the
* PropertyQoS, which was added in 4.2.
* This method is still available in 4.2 and later.
*
* To modify the transport QoS using this classic method:
* - turn off auto-enable using the DomainParticipantFactory QoS
* - create the DomainParticipant (disabled)
* - get the transport QoS
* - modify the transport QoS
* - set the new transport QoS
* - enable the DomainParticipant
*
************************************************************************/
DDSDomainParticipant * numbers_common_create_participant(int domainId) {
struct NDDS_Transport_UDPv4_Property_t transport_UDPv4_property = NDDS_TRANSPORT_UDPV4_PROPERTY_DEFAULT;
struct DDS_DomainParticipantFactoryQos factory_qos = DDS_DomainParticipantFactoryQos_INITIALIZER;
DDS_ReturnCode_t retcode;
DDSDomainParticipant * part = NULL;
/* Get the current DomainParticipantFactory QoS */
retcode = DDSTheParticipantFactory->get_qos(factory_qos);
if (retcode != DDS_RETCODE_OK) {
puts("Error, impossible get domain participant factory qos");
return NULL;
}
/* Turn off auto-enabling of entities */
factory_qos.entity_factory.autoenable_created_entities = DDS_BOOLEAN_FALSE;
/* Set the DomainParticipantFactory QoS */
retcode = DDSTheParticipantFactory->set_qos(factory_qos);
if (retcode != DDS_RETCODE_OK) {
puts("Error, impossible set domain participant factory qos");
return NULL;
}
/* Create the DomainParticipant */
part = DDSTheParticipantFactory->create_participant(
domainId, DDS_PARTICIPANT_QOS_DEFAULT,
NULL /* listener */, DDS_STATUS_MASK_NONE);
if (part == NULL) {
printf("create_participant error\n");
return NULL;
}
/* Get current transport QoS */
retcode = NDDSTransportSupport::get_builtin_transport_property(part,
DDS_TRANSPORTBUILTIN_UDPv4,
(struct NDDS_Transport_Property_t &)transport_UDPv4_property);
if (part == NULL) {
printf("NDDS_Transport_Support_get_builtin_transport_property error\n");
return NULL;
}
/* Modify the transport QoS */
transport_UDPv4_property.send_socket_buffer_size = NEW_SOCKET_BUFFER_SIZE;
transport_UDPv4_property.recv_socket_buffer_size = NEW_SOCKET_BUFFER_SIZE;
/* Set the transport QoS */
retcode = NDDSTransportSupport::set_builtin_transport_property(part,
DDS_TRANSPORTBUILTIN_UDPv4,
(struct NDDS_Transport_Property_t &)transport_UDPv4_property);
if (retcode != DDS_RETCODE_OK) {
printf("NDDS_Transport_Support_set_builtin_transport_property error\n");
return NULL;
}
/* Enable the DomainParticipant */
//retcode = DDS_Entity_enable(DDS_DomainParticipant_as_entity(part));
retcode = part->enable();
if (retcode != DDS_RETCODE_OK) {
printf("DDS_Entity_enable error\n");
return NULL;
}
return part;
}
#endif
/************************************************************************
* The following code read back the transport QoS (accessing it through
* the DDS transport QoS) and verify that are the same as the one set
* before.
************************************************************************/
int numbers_common_verify_qos(DDSDomainParticipant * part) {
struct NDDS_Transport_UDPv4_Property_t transport_UDPv4_property = NDDS_TRANSPORT_UDPV4_PROPERTY_DEFAULT;
DDS_ReturnCode_t retcode;
retcode = NDDSTransportSupport::get_builtin_transport_property(part,
DDS_TRANSPORTBUILTIN_UDPv4,
reinterpret_cast<NDDS_Transport_Property_t &>(transport_UDPv4_property));
if (retcode != DDS_RETCODE_OK) {
puts("Error, impossible to get builtin transport property");
return -1;
} else {
if (transport_UDPv4_property.send_socket_buffer_size != NEW_SOCKET_BUFFER_SIZE) {
puts("Error, send_socket_buffer_size...not modified");
return -1;
} else {
puts("Ok, send_socket_buffer_size....modified");
}
if (transport_UDPv4_property.recv_socket_buffer_size != NEW_SOCKET_BUFFER_SIZE) {
puts("Error, recv_socket_buffer_size...not modified");
return -1;
} else {
puts("Ok, recv_socket_buffer_size....modified");
}
}
printf("New UDPv4 send socket buffer size is: %d \n", transport_UDPv4_property.send_socket_buffer_size);
printf("New UDPv4 receive socket buffer size is: %d \n", transport_UDPv4_property.recv_socket_buffer_size);
return 0;
}
| cxx |
rticonnextdds-examples | data/projects/rticonnextdds-examples/property_qos/c++/numbers_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.
******************************************************************************/
/* numbers_subscriber.cxx
A subscription example
This file is derived from code automatically generated by the rtiddsgen
command:
rtiddsgen -language C++ -example <arch> numbers.idl
Example subscription of type numbers 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>/numbers_subscriber <domain_id> <sample_count>
(3) Start the publication on the same domain used for RTI Data Distribution
with the command
objs/<arch>/numbers_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>/numbers_publisher <domain_id>
objs/<arch>/numbers_subscriber <domain_id>
On Windows:
objs\<arch>\numbers_publisher <domain_id>
objs\<arch>\numbers_subscriber <domain_id>
modification history
------------ -------
*/
#include <stdio.h>
#include <stdlib.h>
#include "numbers.h"
#include "numbersSupport.h"
#include "ndds/ndds_cpp.h"
#include "numbers_common.cxx"
class numbersListener : 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 numbersListener::on_data_available(DDSDataReader* reader)
{
numbersDataReader *numbers_reader = NULL;
numbersSeq data_seq;
DDS_SampleInfoSeq info_seq;
DDS_ReturnCode_t retcode;
int i;
numbers_reader = numbersDataReader::narrow(reader);
if (numbers_reader == NULL) {
printf("DataReader narrow error\n");
return;
}
retcode = numbers_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) {
numbersTypeSupport::print_data(&data_seq[i]);
}
}
retcode = numbers_reader->return_loan(data_seq, info_seq);
if (retcode != DDS_RETCODE_OK) {
printf("return loan error %d\n", retcode);
}
}
/* Delete all entities */
static int subscriber_shutdown(
DDSDomainParticipant *participant)
{
DDS_ReturnCode_t retcode;
int status = 0;
if (participant != NULL) {
retcode = participant->delete_contained_entities();
if (retcode != DDS_RETCODE_OK) {
printf("delete_contained_entities error %d\n", retcode);
status = -1;
}
retcode = DDSTheParticipantFactory->delete_participant(participant);
if (retcode != DDS_RETCODE_OK) {
printf("delete_participant error %d\n", retcode);
status = -1;
}
}
/* RTI Data Distribution Service provides finalize_instance() method on
domain participant factory and finalize() method on type support for
people who want to release memory used by the participant factory and
type support singletons. Uncomment the following block of code for
clean destruction of the singletons. */
/*
numbersTypeSupport::finalize();
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;
numbersListener *reader_listener = NULL;
DDSDataReader *reader = NULL;
DDS_ReturnCode_t retcode;
const char *type_name = NULL;
int count = 0;
struct DDS_Duration_t receive_period = {4,0};
int status = 0;
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;
}
/* If you want to change the DomainParticipant'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_participant call above.
*
* In this case, we set the transport settings in the XML by default, but
* in the numbers_common_create_participant call, we set up the transport
* properties either using the Properties QoS or with the transport
* property objects.
*/
/*
participant = numbers_common_create_participant(domainId);
if (participant == NULL) {
subscriber_shutdown(participant);
return -1;
}*/
if (numbers_common_verify_qos(participant) != 0) {
subscriber_shutdown(participant);
return -1;
}
/* To customize subscriber QoS, use
participant->get_default_subscriber_qos() */
subscriber = participant->create_subscriber(
DDS_SUBSCRIBER_QOS_DEFAULT, NULL /* listener */, DDS_STATUS_MASK_NONE);
if (subscriber == NULL) {
printf("create_subscriber error\n");
subscriber_shutdown(participant);
return -1;
}
/* Register type before creating topic */
type_name = numbersTypeSupport::get_type_name();
retcode = numbersTypeSupport::register_type(
participant, type_name);
if (retcode != DDS_RETCODE_OK) {
printf("register_type error %d\n", retcode);
subscriber_shutdown(participant);
return -1;
}
/* To customize topic QoS, use
participant->get_default_topic_qos() */
topic = participant->create_topic(
"Example numbers",
type_name, DDS_TOPIC_QOS_DEFAULT, NULL /* listener */,
DDS_STATUS_MASK_NONE);
if (topic == NULL) {
printf("create_topic error\n");
subscriber_shutdown(participant);
return -1;
}
/* Create data reader listener */
reader_listener = new numbersListener();
if (reader_listener == NULL) {
printf("listener instantiation error\n");
subscriber_shutdown(participant);
return -1;
}
/* To customize data reader QoS, use
subscriber->get_default_datareader_qos() */
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("numbers 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
| cxx |
rticonnextdds-examples | data/projects/rticonnextdds-examples/property_qos/c++/numbers_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.
******************************************************************************/
/* numbers_publisher.cxx
A publication of data of type numbers
This file is derived from code automatically generated by the rtiddsgen
command:
rtiddsgen -language C++ -example <arch> numbers.idl
Example publication of type numbers automatically generated by
'rtiddsgen'. To test them follow these steps:
(1) Compile this file and the example subscription.
(2) Start the subscription on the same domain used for RTI Data Distribution
with the command
objs/<arch>/numbers_subscriber <domain_id> <sample_count>
(3) Start the publication on the same domain used for RTI Data Distribution
with the command
objs/<arch>/numbers_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>/numbers_publisher <domain_id> o
objs/<arch>/numbers_subscriber <domain_id>
On Windows:
objs\<arch>\numbers_publisher <domain_id>
objs\<arch>\numbers_subscriber <domain_id>
modification history
------------ -------
*/
#include <stdio.h>
#include <stdlib.h>
#include "numbers.h"
#include "numbersSupport.h"
#include "ndds/ndds_cpp.h"
#include "numbers_common.cxx"
/* Delete all entities */
static int publisher_shutdown(
DDSDomainParticipant *participant)
{
DDS_ReturnCode_t retcode;
int status = 0;
if (participant != NULL) {
retcode = participant->delete_contained_entities();
if (retcode != DDS_RETCODE_OK) {
printf("delete_contained_entities error %d\n", retcode);
status = -1;
}
retcode = DDSTheParticipantFactory->delete_participant(participant);
if (retcode != DDS_RETCODE_OK) {
printf("delete_participant error %d\n", retcode);
status = -1;
}
}
/* RTI Data Distribution Service provides finalize_instance() method on
domain participant factory and finalize() method on type support for
people who want to release memory used by the participant factory and
type support singletons. Uncomment the following block of code for
clean destruction of the singletons. */
/*
numbersTypeSupport::finalize();
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;
numbersDataWriter * numbers_writer = NULL;
numbers *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};
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;
}
/* If you want to change the DomainParticipant'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_participant call above.
*
* In this case, we set the transport settings in the XML by default, but
* in the numbers_common_create_participant call, we set up the transport
* properties either using the Properties QoS or with the transport
* property objects.
*/
/*
participant = numbers_common_create_participant(domainId);
if (participant == NULL) {
publisher_shutdown(participant);
return -1;
}
*/
if (numbers_common_verify_qos(participant) != 0) {
publisher_shutdown(participant);
return -1;
}
/* To customize publisher QoS, use
participant->get_default_publisher_qos() */
publisher = participant->create_publisher(
DDS_PUBLISHER_QOS_DEFAULT, NULL /* listener */, DDS_STATUS_MASK_NONE);
if (publisher == NULL) {
printf("create_publisher error\n");
publisher_shutdown(participant);
return -1;
}
/* Register type before creating topic */
type_name = numbersTypeSupport::get_type_name();
retcode = numbersTypeSupport::register_type(
participant, type_name);
if (retcode != DDS_RETCODE_OK) {
printf("register_type error %d\n", retcode);
publisher_shutdown(participant);
return -1;
}
/* To customize topic QoS, use
participant->get_default_topic_qos() */
topic = participant->create_topic(
"Example numbers",
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
publisher->get_default_datawriter_qos() */
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;
}
numbers_writer = numbersDataWriter::narrow(writer);
if (numbers_writer == NULL) {
printf("DataWriter narrow error\n");
publisher_shutdown(participant);
return -1;
}
/* Create data sample for writing */
instance = numbersTypeSupport::create_data();
if (instance == NULL) {
printf("numbersTypeSupport::create_data error\n");
publisher_shutdown(participant);
return -1;
}
/* For data type that has key, if the same instance is going to be
written multiple times, initialize the key here
and register the keyed instance prior to writing */
/*
instance_handle = numbers_writer->register_instance(*instance);
*/
instance->number = 1000;
instance->halfNumber = (float)(instance->number)/2;
/* Main loop */
for (count=0; (sample_count == 0) || (count < sample_count); ++count) {
printf("Writing numbers, count %d\n", count);
/* Modify the data to be sent here */
retcode = numbers_writer->write(*instance, instance_handle);
if (retcode != DDS_RETCODE_OK) {
printf("write error %d\n", retcode);
}
instance->number = (DDS_Long)instance->halfNumber;
instance->halfNumber = (float)(instance->number)/2;
NDDSUtility::sleep(send_period);
}
/*
retcode = numbers_writer->unregister_instance(
*instance, instance_handle);
if (retcode != DDS_RETCODE_OK) {
printf("unregister instance error %d\n", retcode);
}
*/
/* Delete data sample */
retcode = numbersTypeSupport::delete_data(instance);
if (retcode != DDS_RETCODE_OK) {
printf("numbersTypeSupport::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
| cxx |
rticonnextdds-examples | data/projects/rticonnextdds-examples/property_qos/c/numbers_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.
******************************************************************************/
/* numbers_publisher.c
A publication of data of type numbers
This file is derived from code automatically generated by the rtiddsgen
command:
rtiddsgen -language C -example <arch> numbers.idl
Example publication of type numbers 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>/numbers_subscriber <domain_id> <sample_count>
(3) Start the publication on the same domain used for RTI Data Distribution
Service with the command
objs/<arch>/numbers_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>/numbers_publisher <domain_id>
objs/<arch>/numbers_subscriber <domain_id>
On Windows:
objs\<arch>\numbers_publisher <domain_id>
objs\<arch>\numbers_subscriber <domain_id>
modification history
------------ -------
*/
#include <stdio.h>
#include <stdlib.h>
#include "ndds/ndds_c.h"
#include "numbers.h"
#include "numbersSupport.h"
#include "numbers_common.c"
/* 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 and finalize() method on type support for
people who want to release memory used by the participant factory and
type support singletons. Uncomment the following block of code for
clean destruction of the singletons. */
/*
numbersTypeSupport_finalize();
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;
numbersDataWriter *numbers_writer = NULL;
numbers *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;
}
/* If you want to change the DomainParticipant'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_participant call above.
*
* In this case, we set the transport settings in the XML by default, but
* in the numbers_common_create_participant call, we set up the transport
* properties either using the Properties QoS or with the transport
* property objects.
*/
/*participant = numbers_common_create_participant(domainId);
if (participant == NULL) {
publisher_shutdown(participant);
return -1;
}*/
if (numbers_common_verify_qos(participant) != 0) {
publisher_shutdown(participant);
return -1;
}
/* To customize publisher QoS, use
DDS_DomainParticipant_get_default_publisher_qos() */
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 = numbersTypeSupport_get_type_name();
retcode = numbersTypeSupport_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
DDS_DomainParticipant_get_default_topic_qos() */
topic = DDS_DomainParticipant_create_topic(
participant, "Example numbers",
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
DDS_Publisher_get_default_datawriter_qos() */
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;
}
numbers_writer = numbersDataWriter_narrow(writer);
if (numbers_writer == NULL) {
printf("DataWriter narrow error\n");
publisher_shutdown(participant);
return -1;
}
/* Create data sample for writing */
instance = numbersTypeSupport_create_data_ex(DDS_BOOLEAN_TRUE);
if (instance == NULL) {
printf("numbersTypeSupport_create_data error\n");
publisher_shutdown(participant);
return -1;
}
/* For data type that has key, if the same instance is going to be
written multiple times, initialize the key here
and register the keyed instance prior to writing */
/*
instance_handle = numbersDataWriter_register_instance(
numbers_writer, instance);
*/
instance->number = 1000;
instance->halfNumber = (float)(instance->number)/2;
/* Main loop */
for (count=0; (sample_count == 0) || (count < sample_count); ++count) {
printf("Writing numbers, count %d\n", count);
/* Modify the data to be written here */
/* Write data */
retcode = numbersDataWriter_write(
numbers_writer, instance, &instance_handle);
if (retcode != DDS_RETCODE_OK) {
printf("write error %d\n", retcode);
}
instance->number = instance->halfNumber;
instance->halfNumber = (float)(instance->number)/2;
NDDS_Utility_sleep(&send_period);
}
/*
retcode = numbersDataWriter_unregister_instance(
numbers_writer, instance, &instance_handle);
if (retcode != DDS_RETCODE_OK) {
printf("unregister instance error %d\n", retcode);
}
*/
/* Delete data sample */
retcode = numbersTypeSupport_delete_data_ex(instance, DDS_BOOLEAN_TRUE);
if (retcode != DDS_RETCODE_OK) {
printf("numbersTypeSupport_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
| c |
rticonnextdds-examples | data/projects/rticonnextdds-examples/property_qos/c/numbers_common.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.
******************************************************************************/
/* numbers_common.h
*
* This file contains few macros that are used to configure the transport
* in the following files:
* - numbers_publisher.c
* - numbers_subscriber.c
*/
/* Comment the following macro to allow compilation on RTI DDS older than 4.2 */
//#define USE_NDDS42_API
/* The new value of the transport socket size */
#define NEW_SOCKET_BUFFER_SIZE (65507)
#define NEW_SOCKET_BUFFER_SIZE_STRING ("65507")
/* Creates the domain participant, modifying the transport qos properties
* to increase the send and receive socket buffer size to 64k.
* Returns zero if success, non-zero in case of error.
*/
extern DDS_DomainParticipant *numbers_common_create_participant(int domainId);
/* Reads the transport QoS and verify that are correctly set
* Returns zero if success, non-zero in case of error.
*/
extern int numbers_common_verify_qos(DDS_DomainParticipant *part);
| h |
rticonnextdds-examples | data/projects/rticonnextdds-examples/property_qos/c/numbers_common.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.
******************************************************************************/
/* numbers_common.c
*
* This file contains the body of the numbers_common_create_participant
* function.
*/
#include <stdio.h>
#include <stdlib.h>
#include "ndds/ndds_c.h"
#include "numbers.h"
#include "numbersSupport.h"
#include "numbers_common.h"
#ifdef USE_NDDS42_API
/************************************************************************
* The following code modifies the transport QoS using the
* PropertyQoS, introduced in RTI DDS 4.2.
************************************************************************/
DDS_DomainParticipant * numbers_common_create_participant(int domainId) {
struct NDDS_Transport_UDPv4_Property_t transport_UDPv4_property = NDDS_TRANSPORT_UDPV4_PROPERTY_DEFAULT;
struct DDS_DomainParticipantQos domainparticipant_qos = DDS_DomainParticipantQos_INITIALIZER;
struct DDS_PropertySeq *propertySeq = NULL;
struct DDS_Property_t *propertyElement = NULL;
DDS_ReturnCode_t retcode;
DDS_DomainParticipant * part = NULL;
/* To customize participant QoS, use
DDS_DomainParticipantFactory_get_default_participant_qos() */
retcode = DDS_DomainParticipantFactory_get_default_participant_qos(
DDS_TheParticipantFactory, &domainparticipant_qos);
if (retcode != DDS_RETCODE_OK) {
puts("Error, impossible get default participant qos");
return NULL;
}
propertySeq = &domainparticipant_qos.property.value;
DDS_PropertySeq_ensure_length(propertySeq, 2, 2);
/* Set the send socket buffer size */
propertyElement = DDS_PropertySeq_get_reference(propertySeq, 0);
propertyElement->name = DDS_String_dup("dds.transport.UDPv4.builtin.send_socket_buffer_size");
propertyElement->value = DDS_String_dup(NEW_SOCKET_BUFFER_SIZE_STRING);
propertyElement->propagate = DDS_BOOLEAN_FALSE;
/* Set the send socket buffer size */
propertyElement = DDS_PropertySeq_get_reference(propertySeq, 1);
propertyElement->name = DDS_String_dup("dds.transport.UDPv4.builtin.recv_socket_buffer_size");
propertyElement->value = DDS_String_dup(NEW_SOCKET_BUFFER_SIZE_STRING);
propertyElement->propagate = DDS_BOOLEAN_FALSE;
/* Create the participant */
part = DDS_DomainParticipantFactory_create_participant(
DDS_TheParticipantFactory, domainId, &domainparticipant_qos,
NULL /* listener */, DDS_STATUS_MASK_NONE);
if (part == NULL) {
puts("create_participant error");
return NULL;
}
return part;
}
#else
/************************************************************************
* This is the "classic" method for changing the transport QoS.
*
* It shows how to change QoS without using the
* PropertyQoS, which was added in 4.2.
* This method is still available in 4.2 and later.
*
* To modify the transport QoS using this classic method:
* - turn off auto-enable using the DomainParticipantFactory QoS
* - create the DomainParticipant (disabled)
* - get the transport QoS
* - modify the transport QoS
* - set the new transport QoS
* - enable the DomainParticipant
*
************************************************************************/
DDS_DomainParticipant * numbers_common_create_participant(int domainId) {
struct NDDS_Transport_UDPv4_Property_t transport_UDPv4_property = NDDS_TRANSPORT_UDPV4_PROPERTY_DEFAULT;
struct DDS_DomainParticipantFactoryQos factory_qos = DDS_DomainParticipantFactoryQos_INITIALIZER;
DDS_ReturnCode_t retcode;
DDS_DomainParticipant * part = NULL;
/* Get the DomainParticipantFactory QoS */
retcode = DDS_DomainParticipantFactory_get_qos(DDS_TheParticipantFactory, &factory_qos);
if (retcode != DDS_RETCODE_OK) {
puts("Error, impossible get domain participant factory qos");
return NULL;
}
/* Turn off auto-enabling of entities */
factory_qos.entity_factory.autoenable_created_entities = DDS_BOOLEAN_FALSE;
/* Set the DomainParticipantFactory QoS */
retcode = DDS_DomainParticipantFactory_set_qos(DDS_TheParticipantFactory, &factory_qos);
if (retcode != DDS_RETCODE_OK) {
puts("Error, impossible set domain participant factory qos");
return NULL;
}
/* Create the DomainParticipant */
part = DDS_DomainParticipantFactory_create_participant(
DDS_TheParticipantFactory, domainId, &DDS_PARTICIPANT_QOS_DEFAULT,
NULL /* listener */, DDS_STATUS_MASK_NONE);
if (part == NULL) {
printf("create_participant error\n");
return NULL;
}
/* Get current transport QoS */
retcode = NDDS_Transport_Support_get_builtin_transport_property(part,
DDS_TRANSPORTBUILTIN_UDPv4,
(struct NDDS_Transport_Property_t *)&transport_UDPv4_property);
if (part == NULL) {
printf("NDDS_Transport_Support_get_builtin_transport_property error\n");
return NULL;
}
/* Modify the transport QoS */
transport_UDPv4_property.send_socket_buffer_size = NEW_SOCKET_BUFFER_SIZE;
transport_UDPv4_property.recv_socket_buffer_size = NEW_SOCKET_BUFFER_SIZE;
/* Set the transport QoS */
retcode = NDDS_Transport_Support_set_builtin_transport_property(part,
DDS_TRANSPORTBUILTIN_UDPv4,
(struct NDDS_Transport_Property_t *)&transport_UDPv4_property);
if (retcode != DDS_RETCODE_OK) {
printf("NDDS_Transport_Support_set_builtin_transport_property error\n");
return NULL;
}
/* Enable the DomainParticipant */
retcode = DDS_Entity_enable(DDS_DomainParticipant_as_entity(part));
if (retcode != DDS_RETCODE_OK) {
printf("DDS_Entity_enable error\n");
return NULL;
}
return part;
}
#endif
/************************************************************************
* The following code read back the transport QoS (accessing it through
* the DDS transport QoS) and verify that are the same as the one set
* before.
************************************************************************/
int numbers_common_verify_qos(DDS_DomainParticipant * part) {
struct NDDS_Transport_UDPv4_Property_t transport_UDPv4_property = NDDS_TRANSPORT_UDPV4_PROPERTY_DEFAULT;
DDS_ReturnCode_t retcode;
retcode = NDDS_Transport_Support_get_builtin_transport_property(part,
DDS_TRANSPORTBUILTIN_UDPv4,
(struct NDDS_Transport_Property_t *)&transport_UDPv4_property);
if (retcode != DDS_RETCODE_OK) {
puts("Error, impossible to get builtin transport property");
return -1;
} else {
if (transport_UDPv4_property.send_socket_buffer_size != NEW_SOCKET_BUFFER_SIZE) {
puts("Error, send_socket_buffer_size...not modified");
return -1;
} else {
puts("Ok, send_socket_buffer_size....modified");
}
if (transport_UDPv4_property.recv_socket_buffer_size != NEW_SOCKET_BUFFER_SIZE) {
puts("Error, recv_socket_buffer_size...not modified");
return -1;
} else {
puts("Ok, recv_socket_buffer_size....modified");
}
}
printf("New UDPv4 send socket buffer size is: %d \n", transport_UDPv4_property.send_socket_buffer_size);
printf("New UDPv4 receive socket buffer size is: %d \n", transport_UDPv4_property.recv_socket_buffer_size);
return 0;
}
| c |
rticonnextdds-examples | data/projects/rticonnextdds-examples/property_qos/c/numbers_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.
******************************************************************************/
/* numbers_subscriber.c
A subscription example
This file is derived from code automatically generated by the rtiddsgen
command:
rtiddsgen -language C -example <arch> numbers.idl
Example subscription of type numbers 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>/numbers_subscriber <domain_id> <sample_count>
(3) Start the publication on the same domain used for RTI Data Distribution
Service with the command
objs/<arch>/numbers_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>/numbers_publisher <domain_id>
objs/<arch>/numbers_subscriber <domain_id>
On Windows:
objs\<arch>\numbers_publisher <domain_id>
objs\<arch>\numbers_subscriber <domain_id>
modification history
------------ -------
*/
#include <stdio.h>
#include <stdlib.h>
#include "ndds/ndds_c.h"
#include "numbers.h"
#include "numbersSupport.h"
#include "numbers_common.c"
void numbersListener_on_requested_deadline_missed(
void* listener_data,
DDS_DataReader* reader,
const struct DDS_RequestedDeadlineMissedStatus *status)
{
}
void numbersListener_on_requested_incompatible_qos(
void* listener_data,
DDS_DataReader* reader,
const struct DDS_RequestedIncompatibleQosStatus *status)
{
}
void numbersListener_on_sample_rejected(
void* listener_data,
DDS_DataReader* reader,
const struct DDS_SampleRejectedStatus *status)
{
}
void numbersListener_on_liveliness_changed(
void* listener_data,
DDS_DataReader* reader,
const struct DDS_LivelinessChangedStatus *status)
{
}
void numbersListener_on_sample_lost(
void* listener_data,
DDS_DataReader* reader,
const struct DDS_SampleLostStatus *status)
{
}
void numbersListener_on_subscription_matched(
void* listener_data,
DDS_DataReader* reader,
const struct DDS_SubscriptionMatchedStatus *status)
{
}
void numbersListener_on_data_available(
void* listener_data,
DDS_DataReader* reader)
{
numbersDataReader *numbers_reader = NULL;
struct numbersSeq data_seq = DDS_SEQUENCE_INITIALIZER;
struct DDS_SampleInfoSeq info_seq = DDS_SEQUENCE_INITIALIZER;
DDS_ReturnCode_t retcode;
int i;
numbers_reader = numbersDataReader_narrow(reader);
if (numbers_reader == NULL) {
printf("DataReader narrow error\n");
return;
}
retcode = numbersDataReader_take(
numbers_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 < numbersSeq_get_length(&data_seq); ++i) {
if (DDS_SampleInfoSeq_get_reference(&info_seq, i)->valid_data) {
numbersTypeSupport_print_data(
numbersSeq_get_reference(&data_seq, i));
}
}
retcode = numbersDataReader_return_loan(
numbers_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 finalize_instance() method on
domain participant factory and finalize() method on type support for
people who want to release memory used by the participant factory and
type support singletons. Uncomment the following block of code for
clean destruction of the singletons. */
/*
numbersTypeSupport_finalize();
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;
}
/* If you want to change the DomainParticipant'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_participant call above.
*
* In this case, we set the transport settings in the XML by default, but
* in the numbers_common_create_participant call, we set up the transport
* properties either using the Properties QoS or with the transport
* property objects.
*/
/*participant = numbers_common_create_participant(domainId);
if (participant == NULL) {
subscriber_shutdown(participant);
return -1; }
*/
if (numbers_common_verify_qos(participant) != 0) {
subscriber_shutdown(participant);
return -1;
}
/* To customize subscriber QoS, use
DDS_DomainParticipant_get_default_subscriber_qos() */
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 type before creating topic */
type_name = numbersTypeSupport_get_type_name();
retcode = numbersTypeSupport_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
DDS_DomainParticipant_get_default_topic_qos() */
topic = DDS_DomainParticipant_create_topic(
participant, "Example numbers",
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;
}
/* Setup data reader listener */
reader_listener.on_requested_deadline_missed =
numbersListener_on_requested_deadline_missed;
reader_listener.on_requested_incompatible_qos =
numbersListener_on_requested_incompatible_qos;
reader_listener.on_sample_rejected =
numbersListener_on_sample_rejected;
reader_listener.on_liveliness_changed =
numbersListener_on_liveliness_changed;
reader_listener.on_sample_lost =
numbersListener_on_sample_lost;
reader_listener.on_subscription_matched =
numbersListener_on_subscription_matched;
reader_listener.on_data_available =
numbersListener_on_data_available;
/* To customize data reader QoS, use
DDS_Subscriber_get_default_datareader_qos() */
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("numbers subscriber sleeping for %d sec...\n",
poll_period.sec);
NDDS_Utility_sleep(&poll_period);
}
/* Cleanup and delete 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
| c |
rticonnextdds-examples | data/projects/rticonnextdds-examples/routing_service_struct_array_transf/cpp/SensorAttributesCollectionPublisher.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 <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_struct_array_transf/cpp/StructArrayTransformation.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 "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_struct_array_transf/cpp/SensorDataSubscriber.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 <algorithm>
#include <iostream>
#include <dds/sub/ddssub.hpp>
#include <dds/core/ddscore.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_struct_array_transf/cpp/StructArrayTransformation.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 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/builtin_qos_profiles/c++/profiles_subscriber.cxx | /*******************************************************************************
(c) 2005-2014 Copyright, Real-Time Innovations, Inc. All rights reserved.
RTI grants Licensee a license to use, modify, compile, and create derivative
works of the Software. Licensee has the right to distribute object form only
for use with RTI products. The Software is provided "as is", with no warranty
of any type, including any warranty for fitness for any purpose. RTI is under
no obligation to maintain or support the Software. RTI shall not be liable for
any incidental or consequential damages arising out of the use or inability to
use the software.
******************************************************************************/
/* profiles_subscriber.cxx
A subscription example
This file is derived from code automatically generated by the rtiddsgen
command:
rtiddsgen -language C++ -example <arch> profiles.idl
Example subscription of type profiles automatically generated by
'rtiddsgen'. To test them follow these steps:
(1) Compile this file and the example publication.
(2) Start the subscription with the command
objs/<arch>/profiles_subscriber <domain_id> <sample_count>
(3) Start the publication with the command
objs/<arch>/profiles_publisher <domain_id> <sample_count>
(4) [Optional] Specify the list of discovery initial peers and
multicast receive addresses via an environment variable or a file
(in the current working directory) called NDDS_DISCOVERY_PEERS.
You can run any number of publishers and subscribers programs, and can
add and remove them dynamically from the domain.
!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
!!! NOTE: This example will only work when dynamically linking. !!!
In Visual Studio, change the target to "Debug DLL" or "Release DLL"
to build.
!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
Example:
To run the example application on domain <domain_id>:
On Unix:
objs/<arch>/profiles_publisher <domain_id>
objs/<arch>/profiles_subscriber <domain_id>
On Windows:
objs\<arch>\profiles_publisher <domain_id>
objs\<arch>\profiles_subscriber <domain_id>
modification history
------------ -------
*/
#include <stdio.h>
#include <stdlib.h>
#ifdef RTI_VX653
#include <vThreadsData.h>
#endif
#include "profiles.h"
#include "profilesSupport.h"
#include "ndds/ndds_cpp.h"
class profilesListener : 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*/) {
printf("Discovered writer wit incompatible QoS\n");}
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 profilesListener::on_data_available(DDSDataReader* reader)
{
profilesDataReader *profiles_reader = NULL;
profilesSeq data_seq;
DDS_SampleInfoSeq info_seq;
DDS_ReturnCode_t retcode;
int i;
profiles_reader = profilesDataReader::narrow(reader);
if (profiles_reader == NULL) {
printf("DataReader narrow error\n");
return;
}
retcode = profiles_reader->take(
data_seq, info_seq, DDS_LENGTH_UNLIMITED,
DDS_ANY_SAMPLE_STATE, DDS_ANY_VIEW_STATE, DDS_ANY_INSTANCE_STATE);
if (retcode == DDS_RETCODE_NO_DATA) {
return;
} else if (retcode != DDS_RETCODE_OK) {
printf("take error %d\n", retcode);
return;
}
for (i = 0; i < data_seq.length(); ++i) {
if (info_seq[i].valid_data) {
profilesTypeSupport::print_data(&data_seq[i]);
}
}
retcode = profiles_reader->return_loan(data_seq, info_seq);
if (retcode != DDS_RETCODE_OK) {
printf("return loan error %d\n", retcode);
}
}
/* Delete all entities */
static int subscriber_shutdown(
DDSDomainParticipant *participant)
{
DDS_ReturnCode_t retcode;
int status = 0;
if (participant != NULL) {
retcode = participant->delete_contained_entities();
if (retcode != DDS_RETCODE_OK) {
printf("delete_contained_entities error %d\n", retcode);
status = -1;
}
retcode = DDSTheParticipantFactory->delete_participant(participant);
if (retcode != DDS_RETCODE_OK) {
printf("delete_participant error %d\n", retcode);
status = -1;
}
}
/* RTI Connext provides the finalize_instance() method on
domain participant factory for people who want to release memory used
by the participant factory. Uncomment the following block of code for
clean destruction of the singleton. */
/*
retcode = DDSDomainParticipantFactory::finalize_instance();
if (retcode != DDS_RETCODE_OK) {
printf("finalize_instance error %d\n", retcode);
status = -1;
}
*/
return status;
}
extern "C" int subscriber_main(int domainId, int sample_count)
{
DDSDomainParticipant *participant = NULL;
DDSSubscriber *subscriber = NULL;
DDSTopic *topic = NULL;
profilesListener *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;
/*
* This example uses a built-in QoS profile to enable monitoring on the
* DomainParticipant. The code below loads the XML QoS from the
* USER_QOS_PROFILES.xml file, which is inheriting from the
* "BuiltinQoSLib::Generic.Monitoring.Common" profile to enable monitoring.
*
* !!!! NOTE: This example will only work when dynamically linking !!!
* In Visual Studio, change the target to "Debug DLL" or "Release DLL"
* to build.
*/
participant = DDSTheParticipantFactory->create_participant(
domainId, DDS_PARTICIPANT_QOS_DEFAULT,
NULL /* listener */, DDS_STATUS_MASK_NONE);
/* If you want to change the DomainParticipant's QoS programatically rather
* than using the XML file, you will need to add the following lines to
* your code and comment out the create_participant call above.
*
* This example uses a built-in QoS profile to enable
* monitoring on the DomainParticipant.*/
/* participant = DDSTheParticipantFactory->create_participant_with_profile(
domainId, "BuiltinQosLib", "Generic.Monitoring.Common",
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 = profilesTypeSupport::get_type_name();
retcode = profilesTypeSupport::register_type(
participant, type_name);
if (retcode != DDS_RETCODE_OK) {
printf("register_type error %d\n", retcode);
subscriber_shutdown(participant);
return -1;
}
/* To customize the topic QoS, use
the configuration file USER_QOS_PROFILES.xml */
topic = participant->create_topic(
"Example profiles",
type_name, DDS_TOPIC_QOS_DEFAULT, NULL /* listener */,
DDS_STATUS_MASK_NONE);
if (topic == NULL) {
printf("create_topic error\n");
subscriber_shutdown(participant);
return -1;
}
/* Create a data reader listener */
reader_listener = new profilesListener();
/* 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 you want to change the DataReader's QoS programatically 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.
*
* This example uses a built-in QoS profile to enable reliable streaming
* data.*/
/* reader = subscriber->create_datareader_with_profile(
topic, DDS_BUILTIN_QOS_LIB_EXP,
DDS_PROFILE_PATTERN_RELIABLE_STREAMING, 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("profiles 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/builtin_qos_profiles/c++/profiles_publisher.cxx | /*******************************************************************************
(c) 2005-2014 Copyright, Real-Time Innovations, Inc. All rights reserved.
RTI grants Licensee a license to use, modify, compile, and create derivative
works of the Software. Licensee has the right to distribute object form only
for use with RTI products. The Software is provided "as is", with no warranty
of any type, including any warranty for fitness for any purpose. RTI is under
no obligation to maintain or support the Software. RTI shall not be liable for
any incidental or consequential damages arising out of the use or inability to
use the software.
******************************************************************************/
/* profiles_publisher.cxx
A publication of data of type profiles
This file is derived from code automatically generated by the rtiddsgen
command:
rtiddsgen -language C++ -example <arch> profiles.idl
Example publication of type profiles automatically generated by
'rtiddsgen'. To test them follow these steps:
(1) Compile this file and the example subscription.
(2) Start the subscription with the command
objs/<arch>/profiles_subscriber <domain_id> <sample_count>
(3) Start the publication with the command
objs/<arch>/profiles_publisher <domain_id> <sample_count>
(4) [Optional] Specify the list of discovery initial peers and
multicast receive addresses via an environment variable or a file
(in the current working directory) called NDDS_DISCOVERY_PEERS.
You can run any number of publishers and subscribers programs, and can
add and remove them dynamically from the domain.
!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
!!! NOTE: This example will only work when dynamically linking. !!!
In Visual Studio, change the target to "Debug DLL" or "Release DLL"
to build.
!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
Example:
To run the example application on domain <domain_id>:
On Unix:
objs/<arch>/profiles_publisher <domain_id> o
objs/<arch>/profiles_subscriber <domain_id>
On Windows:
objs\<arch>\profiles_publisher <domain_id>
objs\<arch>\profiles_subscriber <domain_id>
modification history
------------ -------
*/
#include <stdio.h>
#include <stdlib.h>
#ifdef RTI_VX653
#include <vThreadsData.h>
#endif
#include "profiles.h"
#include "profilesSupport.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;
profilesDataWriter * profiles_writer = NULL;
profiles *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};
/*
* This example uses a built-in QoS profile to enable monitoring on the
* DomainParticipant. The code below loads the XML QoS from the
* USER_QOS_PROFILES.xml file, which is inheriting from the
* "BuiltinQoSLib::Generic.Monitoring.Common" profile to enable monitoring.
*
* !!!! NOTE: This example will only work when dynamically linking !!!
* In Visual Studio, change the target to "Debug DLL" or "Release DLL"
* to build.
*/
participant = DDSTheParticipantFactory->create_participant(
domainId, DDS_PARTICIPANT_QOS_DEFAULT,
NULL /* listener */, DDS_STATUS_MASK_NONE);
/* If you want to change the DomainParticipant's QoS programatically rather
* than using the XML file, you will need to add the following lines to
* your code and comment out the create_participant call above.
*
* This example uses a built-in QoS profile to enable
* monitoring on the DomainParticipant.*/
/* participant = DDSTheParticipantFactory->create_participant_with_profile(
domainId, "BuiltinQosLib", "Generic.Monitoring.Common",
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 = profilesTypeSupport::get_type_name();
retcode = profilesTypeSupport::register_type(
participant, type_name);
if (retcode != DDS_RETCODE_OK) {
printf("register_type error %d\n", retcode);
publisher_shutdown(participant);
return -1;
}
/* To customize topic QoS, use
the configuration file USER_QOS_PROFILES.xml */
topic = participant->create_topic(
"Example profiles",
type_name, DDS_TOPIC_QOS_DEFAULT, NULL /* listener */,
DDS_STATUS_MASK_NONE);
if (topic == NULL) {
printf("create_topic error\n");
publisher_shutdown(participant);
return -1;
}
/* 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 you want to change the DataWriter's QoS programatically 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.
*
* This example uses a built-in QoS profile to tune QoS for
* reliable streaming data.*/
/* To customize data writer QoS, use
the configuration file USER_QOS_PROFILES.xml */
/* writer = publisher->create_datawriter_with_profile(
topic, DDS_BUILTIN_QOS_LIB_EXP,
DDS_PROFILE_PATTERN_RELIABLE_STREAMING, NULL /* listener * /,
DDS_STATUS_MASK_NONE);
*/
if (writer == NULL) {
printf("create_datawriter error\n");
publisher_shutdown(participant);
return -1;
}
profiles_writer = profilesDataWriter::narrow(writer);
if (profiles_writer == NULL) {
printf("DataWriter narrow error\n");
publisher_shutdown(participant);
return -1;
}
/* Create data sample for writing */
instance = profilesTypeSupport::create_data();
if (instance == NULL) {
printf("profilesTypeSupport::create_data error\n");
publisher_shutdown(participant);
return -1;
}
/* For a data type that has a key, if the same instance is going to be
written multiple times, initialize the key here
and register the keyed instance prior to writing */
/*
instance_handle = profiles_writer->register_instance(*instance);
*/
/* Main loop */
for (count=0; (sample_count == 0) || (count < sample_count); ++count) {
printf("Writing profiles, count %d\n", count);
/* Modify the data to be sent here */
retcode = profiles_writer->write(*instance, instance_handle);
if (retcode != DDS_RETCODE_OK) {
printf("write error %d\n", retcode);
}
NDDSUtility::sleep(send_period);
}
/*
retcode = profiles_writer->unregister_instance(
*instance, instance_handle);
if (retcode != DDS_RETCODE_OK) {
printf("unregister instance error %d\n", retcode);
}
*/
/* Delete data sample */
retcode = profilesTypeSupport::delete_data(instance);
if (retcode != DDS_RETCODE_OK) {
printf("profilesTypeSupport::delete_data error %d\n", retcode);
}
/* Delete all entities */
return publisher_shutdown(participant);
}
#if defined(RTI_WINCE)
int wmain(int argc, wchar_t** argv)
{
int domainId = 0;
int sample_count = 0; /* infinite loop */
if (argc >= 2) {
domainId = _wtoi(argv[1]);
}
if (argc >= 3) {
sample_count = _wtoi(argv[2]);
}
/* Uncomment this to turn on additional logging
NDDSConfigLogger::get_instance()->
set_verbosity_by_category(NDDS_CONFIG_LOG_CATEGORY_API,
NDDS_CONFIG_LOG_VERBOSITY_STATUS_ALL);
*/
return publisher_main(domainId, sample_count);
}
#elif !(defined(RTI_VXWORKS) && !defined(__RTP__)) && !defined(RTI_PSOS)
int main(int argc, char *argv[])
{
int domainId = 0;
int sample_count = 0; /* infinite loop */
if (argc >= 2) {
domainId = atoi(argv[1]);
}
if (argc >= 3) {
sample_count = atoi(argv[2]);
}
/* Uncomment this to turn on additional logging
NDDSConfigLogger::get_instance()->
set_verbosity_by_category(NDDS_CONFIG_LOG_CATEGORY_API,
NDDS_CONFIG_LOG_VERBOSITY_STATUS_ALL);
*/
return publisher_main(domainId, sample_count);
}
#endif
#ifdef RTI_VX653
const unsigned char* __ctype = *(__ctypePtrGet());
extern "C" void usrAppInit ()
{
#ifdef USER_APPL_INIT
USER_APPL_INIT; /* for backwards compatibility */
#endif
/* add application specific code here */
taskSpawn("pub", RTI_OSAPI_THREAD_PRIORITY_NORMAL, 0x8, 0x150000, (FUNCPTR)publisher_main, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
}
#endif
| cxx |
rticonnextdds-examples | data/projects/rticonnextdds-examples/builtin_qos_profiles/c/profiles_publisher.c | /*******************************************************************************
(c) 2005-2014 Copyright, Real-Time Innovations, Inc. All rights reserved.
RTI grants Licensee a license to use, modify, compile, and create derivative
works of the Software. Licensee has the right to distribute object form only
for use with RTI products. The Software is provided "as is", with no warranty
of any type, including any warranty for fitness for any purpose. RTI is under
no obligation to maintain or support the Software. RTI shall not be liable for
any incidental or consequential damages arising out of the use or inability to
use the software.
******************************************************************************/
/* profiles_publisher.c
A publication of data of type profiles
This file is derived from code automatically generated by the rtiddsgen
command:
rtiddsgen -language C -example <arch> profiles.idl
Example publication of type profiles automatically generated by
'rtiddsgen'. To test them follow these steps:
(1) Compile this file and the example subscription.
(2) Start the subscription with the command
objs/<arch>/profiles_subscriber <domain_id> <sample_count>
(3) Start the publication with the command
objs/<arch>/profiles_publisher <domain_id> <sample_count>
(4) [Optional] Specify the list of discovery initial peers and
multicast receive addresses via an environment variable or a file
(in the current working directory) called NDDS_DISCOVERY_PEERS.
You can run any number of publishers and subscribers programs, and can
add and remove them dynamically from the domain.
!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
!!! NOTE: This example will only work when dynamically linking. !!!
In Visual Studio, change the target to "Debug DLL" or "Release DLL"
to build.
!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
Example:
To run the example application on domain <domain_id>:
On Unix:
objs/<arch>/profiles_publisher <domain_id>
objs/<arch>/profiles_subscriber <domain_id>
On Windows:
objs\<arch>\profiles_publisher <domain_id>
objs\<arch>\profiles_subscriber <domain_id>
modification history
------------ -------
*/
#include <stdio.h>
#include <stdlib.h>
#include "ndds/ndds_c.h"
#include "profiles.h"
#include "profilesSupport.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;
profilesDataWriter *profiles_writer = NULL;
profiles *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};
/*
* This example uses a built-in QoS profile to enable monitoring on the
* DomainParticipant. The code below loads the XML QoS from the
* USER_QOS_PROFILES.xml file, which is inheriting from the
* "BuiltinQoSLib::Generic.Monitoring.Common" profile to enable monitoring.
*
* !!!! NOTE: This example will only work when dynamically linking !!!
* In Visual Studio, change the target to "Debug DLL" or "Release DLL"
* to build.
*/
/* 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 you want to change the DomainParticipant's QoS programatically rather
* than using the XML file, you will need to add the following lines to
* your code and comment out the create_participant call above.
*
* This example uses a built-in QoS profile to enable
* monitoring on the DomainParticipant.*/
/*participant = DDS_DomainParticipantFactory_create_participant_with_profile(
DDS_TheParticipantFactory, domainId,
DDS_BUILTIN_QOS_LIB, DDS_PROFILE_GENERIC_MONITORING_COMMON,
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 = profilesTypeSupport_get_type_name();
retcode = profilesTypeSupport_register_type(
participant, type_name);
if (retcode != DDS_RETCODE_OK) {
printf("register_type error %d\n", retcode);
publisher_shutdown(participant);
return -1;
}
/* To customize topic QoS, use
the configuration file USER_QOS_PROFILES.xml */
topic = DDS_DomainParticipant_create_topic(
participant, "Example profiles",
type_name, &DDS_TOPIC_QOS_DEFAULT, NULL /* listener */,
DDS_STATUS_MASK_NONE);
if (topic == NULL) {
printf("create_topic error\n");
publisher_shutdown(participant);
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 you want to change the DataWriter's QoS programatically 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.
*
* This example uses a built-in QoS profile to tune the QoS for
* reliable streaming data. */
/*writer = DDS_Publisher_create_datawriter_with_profile(
publisher,
topic, DDS_BUILTIN_QOS_LIB_EXP,
DDS_PROFILE_PATTERN_RELIABLE_STREAMING, NULL /* listener * /,
DDS_STATUS_MASK_NONE);*/
if (writer == NULL) {
printf("create_datawriter error\n");
publisher_shutdown(participant);
return -1;
}
profiles_writer = profilesDataWriter_narrow(writer);
if (profiles_writer == NULL) {
printf("DataWriter narrow error\n");
publisher_shutdown(participant);
return -1;
}
/* Create data sample for writing */
instance = profilesTypeSupport_create_data_ex(DDS_BOOLEAN_TRUE);
if (instance == NULL) {
printf("profilesTypeSupport_create_data error\n");
publisher_shutdown(participant);
return -1;
}
/* For a data type that has a key, if the same instance is going to be
written multiple times, initialize the key here
and register the keyed instance prior to writing */
/*
instance_handle = profilesDataWriter_register_instance(
profiles_writer, instance);
*/
/* Main loop */
for (count=0; (sample_count == 0) || (count < sample_count); ++count) {
printf("Writing profiles, count %d\n", count);
/* Modify the data to be written here */
/* Write data */
retcode = profilesDataWriter_write(
profiles_writer, instance, &instance_handle);
if (retcode != DDS_RETCODE_OK) {
printf("write error %d\n", retcode);
}
NDDS_Utility_sleep(&send_period);
}
/*
retcode = profilesDataWriter_unregister_instance(
profiles_writer, instance, &instance_handle);
if (retcode != DDS_RETCODE_OK) {
printf("unregister instance error %d\n", retcode);
}
*/
/* Delete data sample */
retcode = profilesTypeSupport_delete_data_ex(instance, DDS_BOOLEAN_TRUE);
if (retcode != DDS_RETCODE_OK) {
printf("profilesTypeSupport_delete_data error %d\n", retcode);
}
/* Cleanup and delete delete all entities */
return publisher_shutdown(participant);
}
#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/builtin_qos_profiles/c/profiles_subscriber.c | /*******************************************************************************
(c) 2005-2014 Copyright, Real-Time Innovations, Inc. All rights reserved.
RTI grants Licensee a license to use, modify, compile, and create derivative
works of the Software. Licensee has the right to distribute object form only
for use with RTI products. The Software is provided "as is", with no warranty
of any type, including any warranty for fitness for any purpose. RTI is under
no obligation to maintain or support the Software. RTI shall not be liable for
any incidental or consequential damages arising out of the use or inability to
use the software.
******************************************************************************/
/* profiles_subscriber.c
A subscription example
This file is derived from code automatically generated by the rtiddsgen
command:
rtiddsgen -language C -example <arch> profiles.idl
Example subscription of type profiles automatically generated by
'rtiddsgen'. To test them, follow these steps:
(1) Compile this file and the example publication.
(2) Start the subscription with the command
objs/<arch>/profiles_subscriber <domain_id> <sample_count>
(3) Start the publication with the command
objs/<arch>/profiles_publisher <domain_id> <sample_count>
(4) [Optional] Specify the list of discovery initial peers and
multicast receive addresses via an environment variable or a file
(in the current working directory) called NDDS_DISCOVERY_PEERS.
You can run any number of publishers and subscribers programs, and can
add and remove them dynamically from the domain.
!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
!!! NOTE: This example will only work when dynamically linking. !!!
In Visual Studio, change the target to "Debug DLL" or "Release DLL"
to build.
!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
Example:
To run the example application on domain <domain_id>:
On UNIX systems:
objs/<arch>/profiles_publisher <domain_id>
objs/<arch>/profiles_subscriber <domain_id>
On Windows systems:
objs\<arch>\profiles_publisher <domain_id>
objs\<arch>\profiles_subscriber <domain_id>
modification history
------------ -------
*/
#include <stdio.h>
#include <stdlib.h>
#include "ndds/ndds_c.h"
#include "profiles.h"
#include "profilesSupport.h"
void profilesListener_on_requested_deadline_missed(
void* listener_data,
DDS_DataReader* reader,
const struct DDS_RequestedDeadlineMissedStatus *status)
{
}
void profilesListener_on_requested_incompatible_qos(
void* listener_data,
DDS_DataReader* reader,
const struct DDS_RequestedIncompatibleQosStatus *status)
{
}
void profilesListener_on_sample_rejected(
void* listener_data,
DDS_DataReader* reader,
const struct DDS_SampleRejectedStatus *status)
{
}
void profilesListener_on_liveliness_changed(
void* listener_data,
DDS_DataReader* reader,
const struct DDS_LivelinessChangedStatus *status)
{
}
void profilesListener_on_sample_lost(
void* listener_data,
DDS_DataReader* reader,
const struct DDS_SampleLostStatus *status)
{
}
void profilesListener_on_subscription_matched(
void* listener_data,
DDS_DataReader* reader,
const struct DDS_SubscriptionMatchedStatus *status)
{
}
void profilesListener_on_data_available(
void* listener_data,
DDS_DataReader* reader)
{
profilesDataReader *profiles_reader = NULL;
struct profilesSeq data_seq = DDS_SEQUENCE_INITIALIZER;
struct DDS_SampleInfoSeq info_seq = DDS_SEQUENCE_INITIALIZER;
DDS_ReturnCode_t retcode;
int i;
profiles_reader = profilesDataReader_narrow(reader);
if (profiles_reader == NULL) {
printf("DataReader narrow error\n");
return;
}
retcode = profilesDataReader_take(
profiles_reader,
&data_seq, &info_seq, DDS_LENGTH_UNLIMITED,
DDS_ANY_SAMPLE_STATE, DDS_ANY_VIEW_STATE, DDS_ANY_INSTANCE_STATE);
if (retcode == DDS_RETCODE_NO_DATA) {
return;
} else if (retcode != DDS_RETCODE_OK) {
printf("take error %d\n", retcode);
return;
}
for (i = 0; i < profilesSeq_get_length(&data_seq); ++i) {
if (DDS_SampleInfoSeq_get_reference(&info_seq, i)->valid_data) {
profilesTypeSupport_print_data(
profilesSeq_get_reference(&data_seq, i));
}
}
retcode = profilesDataReader_return_loan(
profiles_reader,
&data_seq, &info_seq);
if (retcode != DDS_RETCODE_OK) {
printf("return loan error %d\n", retcode);
}
}
/* Delete all entities */
static int subscriber_shutdown(
DDS_DomainParticipant *participant)
{
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};
/*
* This example uses a built-in QoS profile to enable monitoring on the
* DomainParticipant. The code below loads the XML QoS from the
* USER_QOS_PROFILES.xml file, which is inheriting from the
* "BuiltinQoSLib::Generic.Monitoring.Common" profile to enable monitoring.
*
* !!!! NOTE: This example will only work when dynamically linking !!!
* In Visual Studio, change the target to "Debug DLL" or "Release DLL"
* to build.
*/
/* 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 you want to change the DomainParticipant's QoS programatically rather
* than using the XML file, you will need to add the following lines to
* your code and comment out the create_participant call above.
*
* This example uses a built-in QoS profile to enable
* monitoring on the DomainParticipant.*/
/*participant = DDS_DomainParticipantFactory_create_participant_with_profile(
DDS_TheParticipantFactory, domainId,
DDS_BUILTIN_QOS_LIB, DDS_PROFILE_GENERIC_MONITORING_COMMON,
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 = profilesTypeSupport_get_type_name();
retcode = profilesTypeSupport_register_type(participant, type_name);
if (retcode != DDS_RETCODE_OK) {
printf("register_type error %d\n", retcode);
subscriber_shutdown(participant);
return -1;
}
/* To customize topic QoS, use
the configuration file USER_QOS_PROFILES.xml */
topic = DDS_DomainParticipant_create_topic(
participant, "Example profiles",
type_name, &DDS_TOPIC_QOS_DEFAULT, NULL /* listener */,
DDS_STATUS_MASK_NONE);
if (topic == NULL) {
printf("create_topic error\n");
subscriber_shutdown(participant);
return -1;
}
/* Set up a data reader listener */
reader_listener.on_requested_deadline_missed =
profilesListener_on_requested_deadline_missed;
reader_listener.on_requested_incompatible_qos =
profilesListener_on_requested_incompatible_qos;
reader_listener.on_sample_rejected =
profilesListener_on_sample_rejected;
reader_listener.on_liveliness_changed =
profilesListener_on_liveliness_changed;
reader_listener.on_sample_lost =
profilesListener_on_sample_lost;
reader_listener.on_subscription_matched =
profilesListener_on_subscription_matched;
reader_listener.on_data_available =
profilesListener_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 you want to change the DataReader's QoS programatically 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.
*
* This example uses a built-in QoS profile to tune the QoS for
* reliable streaming data. */
/*reader = DDS_Subscriber_create_datareader_with_profile(
subscriber, DDS_Topic_as_topicdescription(topic),
DDS_BUILTIN_QOS_LIB_EXP, DDS_PROFILE_PATTERN_RELIABLE_STREAMING,
&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("profiles 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/builtin_qos_profiles/c++03/profiles_subscriber.cxx | /*******************************************************************************
(c) 2005-2015 Copyright, Real-Time Innovations, Inc. All rights reserved.
RTI grants Licensee a license to use, modify, compile, and create derivative
works of the Software. Licensee has the right to distribute object form only
for use with RTI products. The Software is provided "as is", with no warranty
of any type, including any warranty for fitness for any purpose. RTI is under
no obligation to maintain or support the Software. RTI shall not be liable for
any incidental or consequential damages arising out of the use or inability to
use the software.
******************************************************************************/
#include <iostream>
#include <dds/dds.hpp>
#include <rti/core/ListenerBinder.hpp>
#include "profiles.hpp"
using namespace dds::core;
using namespace dds::core::status;
using namespace dds::domain;
using namespace dds::domain::qos;
using namespace dds::topic;
using namespace dds::sub;
using namespace dds::sub::qos;
class ProfilesListener : public NoOpDataReaderListener<HelloWorld> {
public:
void on_data_available(DataReader<HelloWorld>& reader)
{
// Take all samples
LoanedSamples<HelloWorld> samples = reader.take();
for (LoanedSamples<HelloWorld>::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)
{
// Retrieve the Participant QoS from USER_QOS_PROFILES.xml
DomainParticipantQos participant_qos = QosProvider::Default()
.participant_qos();
// This example uses a built-in QoS profile to enable monitoring on the
// DomainParticipant. This profile is specified in USER_QOS_PROFILES.xml.
// To enable it programmatically uncomment these lines.
// participant_qos = QosProvider::Default().participant_qos(
// "BuiltinQosLib::Generic.Monitoring.Common");
// Create a DomainParticipant.
DomainParticipant participant(domain_id, participant_qos);
// Create a Topic -- and automatically register the type.
Topic<HelloWorld> topic(participant, "Example profiles");
// Retrieve the DataReader QoS from USER_QOS_PROFILES.xml
DataReaderQos reader_qos = QosProvider::Default().datareader_qos();
// This example uses a built-in QoS profile to tune QoS for reliable
// streaming data. To enable it programmatically uncomment these lines.
// reader_qos = QosProvider::Default().datareader_qos(
// "BuiltinQosLibExp::Pattern.ReliableStreaming");
// Create a DataReader.
DataReader<HelloWorld> reader(Subscriber(participant), 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.
rti::core::ListenerBinder< DataReader<HelloWorld> > scoped_listener =
rti::core::bind_and_manage_listener(
reader,
new ProfilesListener,
StatusMask::data_available());
// Main loop
for (int count = 0; (sample_count == 0) || (count < sample_count); ++count){
std::cout << "profiles 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
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/builtin_qos_profiles/c++03/profiles_publisher.cxx | /*******************************************************************************
(c) 2005-2015 Copyright, Real-Time Innovations, Inc. All rights reserved.
RTI grants Licensee a license to use, modify, compile, and create derivative
works of the Software. Licensee has the right to distribute object form only
for use with RTI products. The Software is provided "as is", with no warranty
of any type, including any warranty for fitness for any purpose. RTI is under
no obligation to maintain or support the Software. RTI shall not be liable for
any incidental or consequential damages arising out of the use or inability to
use the software.
******************************************************************************/
#include <iostream>
#include <dds/dds.hpp>
#include "profiles.hpp"
using namespace dds::core;
using namespace dds::domain;
using namespace dds::domain::qos;
using namespace dds::topic;
using namespace dds::pub;
using namespace dds::pub::qos;
void publisher_main(int domain_id, int sample_count)
{
// Retrieve the Participant QoS from USER_QOS_PROFILES.xml
DomainParticipantQos participant_qos = QosProvider::Default()
.participant_qos();
// This example uses a built-in QoS profile to enable monitoring on the
// DomainParticipant. This profile is specified in USER_QOS_PROFILES.xml.
// To enable it programmatically uncomment these lines.
// participant_qos = QosProvider::Default().participant_qos(
// "BuiltinQosLib::Generic.Monitoring.Common");
// Create a DomainParticipant.
DomainParticipant participant(domain_id, participant_qos);
// Create a Topic -- and automatically register the type.
Topic<HelloWorld> topic(participant, "Example profiles");
// Retrieve the DataWriter QoS from USER_QOS_PROFILES.xml
DataWriterQos writer_qos = QosProvider::Default().datawriter_qos();
// This example uses a built-in QoS profile to tune QoS for reliable
// streaming data. To enable it programmatically uncomment these lines.
// writer_qos = QosProvider::Default().datawriter_qos(
// "BuiltinQosLibExp::Pattern.ReliableStreaming");
// Create a Datawriter.
DataWriter<HelloWorld> writer(Publisher(participant), topic, writer_qos);
// Create a data sample for writing.
HelloWorld instance;
// Main loop
for (int count = 0; (sample_count == 0) || (count < sample_count); ++count){
std::cout << "Writing profiles, count " << count << std::endl;
instance.msg("Hello World!");
writer.write(instance);
rti::util::sleep(Duration(4));
}
}
int main(int argc, char *argv[])
{
int domain_id = 0;
int sample_count = 0; // Infinite loop
if (argc >= 2) {
domain_id = atoi(argv[1]);
}
if (argc >= 3) {
sample_count = atoi(argv[2]);
}
// To turn on additional logging, include <rti/config/Logger.hpp> and
// uncomment the following line:
// rti::config::Logger::instance().verbosity(rti::config::Verbosity::STATUS_ALL);
try {
publisher_main(domain_id, sample_count);
} catch (std::exception ex) {
std::cout << "Exception caught: " << ex.what() << std::endl;
return -1;
}
return 0;
}
| cxx |
rticonnextdds-examples | data/projects/rticonnextdds-examples/persistent_storage/c++/hello_world_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.
******************************************************************************/
/* hello_world_subscriber.cxx
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:
objs/<arch>/hello_world_publisher <domain_id>
objs/<arch>/hello_world_subscriber <domain_id>
On Windows:
objs\<arch>\hello_world_publisher <domain_id>
objs\<arch>\hello_world_subscriber <domain_id>
modification history
------------ -------
*/
#include <stdio.h>
#include <stdlib.h>
#ifdef RTI_VX653
#include <vThreadsData.h>
#endif
#include "hello_world.h"
#include "hello_worldSupport.h"
#include "ndds/ndds_cpp.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;\
}
class hello_worldListener: 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 hello_worldListener::on_data_available(DDSDataReader* reader) {
hello_worldDataReader *hello_world_reader = NULL;
hello_worldSeq data_seq;
DDS_SampleInfoSeq info_seq;
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_world_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) {
hello_worldTypeSupport::print_data(&data_seq[i]);
}
}
retcode = hello_world_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 domain_id, int sample_count, int drs) {
DDSDomainParticipant *participant = NULL;
DDSSubscriber *subscriber = NULL;
DDSTopic *topic = NULL;
hello_worldListener *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(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 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 = 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 the topic QoS, use
the configuration file USER_QOS_PROFILES.xml */
topic = participant->create_topic("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;
}
/* Create a data reader listener */
reader_listener = new hello_worldListener();
/* 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 = subscriber->create_datareader_with_profile(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);
delete reader_listener;
return -1;
}
} else {
reader = subscriber->create_datareader_with_profile(topic,
"persistence_example_Library", "persistence_service_Profile",
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("hello_world 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 domain_id = 0;
int sample_count = 0; /* infinite loop */
int drs = 0;
int i;
char syntax[1024];
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
NDDSConfigLogger::get_instance()->
set_verbosity_by_category(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 = *(__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/persistent_storage/c++/hello_world_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.
******************************************************************************/
/* hello_world_publisher.cxx
A publication of data of type hello_world
This file is derived from code automatically generated by the rtiddsgen
command:
rtiddsgen -language C++ -example <arch> hello_world.idl
Example publication of type hello_world 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>/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:
objs/<arch>/hello_world_publisher <domain_id> o
objs/<arch>/hello_world_subscriber <domain_id>
On Windows:
objs\<arch>\hello_world_publisher <domain_id>
objs\<arch>\hello_world_subscriber <domain_id>
modification history
------------ -------
*/
#include <stdio.h>
#include <stdlib.h>
#ifdef RTI_VX653
#include <vThreadsData.h>
#endif
#include "hello_world.h"
#include "hello_worldSupport.h"
#include "ndds/ndds_cpp.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=rgv[i];\
i++;\
continue;\
}
/* 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 domain_id, int sample_count, int initial_count,
int dwh, int sleep) {
DDSDomainParticipant *participant = NULL;
DDSPublisher *publisher = NULL;
DDSTopic *topic = NULL;
DDSDataWriter *writer = NULL;
hello_worldDataWriter * hello_world_writer = NULL;
hello_world *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 };
struct DDS_Duration_t one_sec = { 1, 0 };
/* To customize participant QoS, use
* the configuration file USER_QOS_PROFILES.xml */
participant = DDSTheParticipantFactory->create_participant(domain_id,
DDS_PARTICIPANT_QOS_DEFAULT, NULL /* listener */,
DDS_STATUS_MASK_NONE);
if (participant == NULL) {
printf("create_participant error\n");
publisher_shutdown(participant);
return -1;
}
/* 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 = 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);
publisher_shutdown(participant);
return -1;
}
/* To customize topic QoS, use
* the configuration file USER_QOS_PROFILES.xml */
topic = participant->create_topic("Example hello_world", 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;
}
/* 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.
*/
if (dwh == 1) {
writer = publisher->create_datawriter_with_profile(topic,
"persistence_example_Library", "durable_writer_history_Profile",
NULL /* listener */, DDS_STATUS_MASK_NONE);
if (writer == NULL) {
printf("create_datawriter error\n");
publisher_shutdown(participant);
return -1;
}
} else {
writer = publisher->create_datawriter_with_profile(topic,
"persistence_example_Library", "persistence_service_Profile",
NULL /* listener */, DDS_STATUS_MASK_NONE);
if (writer == NULL) {
printf("create_datawriter error\n");
publisher_shutdown(participant);
return -1;
}
}
hello_world_writer = hello_worldDataWriter::narrow(writer);
if (hello_world_writer == NULL) {
printf("DataWriter narrow error\n");
publisher_shutdown(participant);
return -1;
}
/* Create data sample for writing */
instance = hello_worldTypeSupport::create_data();
if (instance == NULL) {
printf("hello_worldTypeSupport::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 = hello_world_writer->register_instance(*instance);
*/
/* Main loop */
for (count = 0; (sample_count == 0) || (count < sample_count); ++count) {
printf("Writing hello_world, count %d\n", count);
/* Modify the data to be sent here */
instance->data = initial_count;
initial_count++;
retcode = hello_world_writer->write(*instance, instance_handle);
if (retcode != DDS_RETCODE_OK) {
printf("write error %d\n", retcode);
}
NDDSUtility::sleep(send_period);
}
while (sleep != 0) {
NDDS_Utility_sleep(&one_sec);
sleep--;
}
/*
retcode = hello_world_writer->unregister_instance(
*instance, instance_handle);
if (retcode != DDS_RETCODE_OK) {
printf("unregister instance error %d\n", retcode);
}
*/
/* Delete data sample */
retcode = hello_worldTypeSupport::delete_data(instance);
if (retcode != DDS_RETCODE_OK) {
printf("hello_worldTypeSupport::delete_data error %d\n", retcode);
}
/* Delete all entities */
return publisher_shutdown(participant);
}
int main(int argc, char *argv[]) {
int domain_id = 0;
int sample_count = 0; /* infinite loop */
int initial_value = 0;
int dwh = 0;
int sleep = 0;
char syntax[1024];
int i;
sprintf(syntax,
"%s [options] \n\
-domain_id <domain ID> (default: 0)\n\
-sample_count <number of published samples> (default: infinite)\n\
-initial_value <first sample value> (default: 0)\n\
-sleep <sleep time in seconds before finishing> (default: 0)\n\
-dwh <1|0> Enable/Disable durable writer history (default: 0)\n",
argv[0]);
for (i = 1; i < argc;) {
READ_INTEGER_PARAM("-sleep", sleep);
READ_INTEGER_PARAM("-domain_id", domain_id);
READ_INTEGER_PARAM("-sample_count", sample_count);
READ_INTEGER_PARAM("-initial_value", initial_value);
READ_INTEGER_PARAM("-dwh", dwh);
printf("%s", syntax);
return 0;
}
/* 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(domain_id, sample_count, initial_value, dwh, sleep);
}
#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/persistent_storage/c/hello_world_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.
******************************************************************************/
/* hello_world_publisher.c
A publication of data of type hello_world
This file is derived from code automatically generated by the rtiddsgen
command:
rtiddsgen -language C -example <arch> hello_world.idl
Example publication of type hello_world 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>/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:
objs/<arch>/hello_world_publisher <domain_id>
objs/<arch>/hello_world_subscriber <domain_id>
On Windows:
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=rgv[i];\
i++;\
continue;\
}
/* Delete all entities */
static int publisher_shutdown(DDS_DomainParticipant *participant) {
DDS_ReturnCode_t retcode;
int status = 0;
if (participant != NULL) {
retcode = DDS_DomainParticipant_delete_contained_entities(participant);
if (retcode != DDS_RETCODE_OK) {
printf("delete_contained_entities error %d\n", retcode);
status = -1;
}
retcode = DDS_DomainParticipantFactory_delete_participant(
DDS_TheParticipantFactory, participant);
if (retcode != DDS_RETCODE_OK) {
printf("delete_participant error %d\n", retcode);
status = -1;
}
}
/* RTI Connext provides finalize_instance() method on
domain participant factory for people who want to release memory used
by the participant factory. Uncomment the following block of code for
clean destruction of the singleton. */
/*
retcode = DDS_DomainParticipantFactory_finalize_instance();
if (retcode != DDS_RETCODE_OK) {
printf("finalize_instance error %d\n", retcode);
status = -1;
}
*/
return status;
}
static int publisher_main(int domain_id, int sample_count, int initial_count,
int dwh, int sleep) {
DDS_DomainParticipant *participant = NULL;
DDS_Publisher *publisher = NULL;
DDS_Topic *topic = NULL;
DDS_DataWriter *writer = NULL;
struct DDS_DataWriterQos writer_qos = DDS_DataWriterQos_INITIALIZER;
hello_worldDataWriter *hello_world_writer = NULL;
hello_world *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_Duration_t one_sec = { 1, 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");
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 = 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);
publisher_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");
publisher_shutdown(participant);
return -1;
}
/* 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.
*/
if (dwh == 1) {
writer = DDS_Publisher_create_datawriter_with_profile(publisher, topic,
"persistence_example_Library", "durable_writer_history_Profile",
NULL /* listener */, DDS_STATUS_MASK_NONE);
if (writer == NULL) {
printf("create_datawriter error\n");
publisher_shutdown(participant);
return -1;
}
} else {
writer = DDS_Publisher_create_datawriter_with_profile(publisher, topic,
"persistence_example_Library", "persistence_service_Profile",
NULL /* listener */, DDS_STATUS_MASK_NONE);
if (writer == NULL) {
printf("create_datawriter error\n");
publisher_shutdown(participant);
return -1;
}
}
hello_world_writer = hello_worldDataWriter_narrow(writer);
if (hello_world_writer == NULL) {
printf("DataWriter narrow error\n");
publisher_shutdown(participant);
return -1;
}
/* Create data sample for writing */
instance = hello_worldTypeSupport_create_data_ex(DDS_BOOLEAN_TRUE);
if (instance == NULL) {
printf("hello_worldTypeSupport_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 = hello_worldDataWriter_register_instance(
hello_world_writer, instance);
*/
/* Main loop */
for (count = 0; (sample_count == 0) || (count < sample_count); ++count) {
printf("Writing hello_world, count %d\n", initial_count);
/* Modify the data to be written here */
instance->data = initial_count;
initial_count++;
/* Write data */
retcode = hello_worldDataWriter_write(hello_world_writer, instance,
&instance_handle);
if (retcode != DDS_RETCODE_OK) {
printf("write error %d\n", retcode);
}
NDDS_Utility_sleep(&send_period);
}
while (sleep != 0) {
NDDS_Utility_sleep(&one_sec);
sleep--;
}
/*
retcode = hello_worldDataWriter_unregister_instance(
hello_world_writer, instance, &instance_handle);
if (retcode != DDS_RETCODE_OK) {
printf("unregister instance error %d\n", retcode);
}
*/
/* Delete data sample */
retcode = hello_worldTypeSupport_delete_data_ex(instance, DDS_BOOLEAN_TRUE);
if (retcode != DDS_RETCODE_OK) {
printf("hello_worldTypeSupport_delete_data error %d\n", retcode);
}
/* Cleanup and delete delete all entities */
return publisher_shutdown(participant);
}
int main(int argc, char *argv[]) {
int domain_id = 0;
int sample_count = 0; /* infinite loop */
int initial_value = 0;
int dwh = 0;
int sleep = 0;
char syntax[1024];
int i;
sprintf(syntax,
"%s [options] \n\
-domain_id <domain ID> (default: 0)\n\
-sample_count <number of published samples> (default: infinite)\n\
-initial_value <first sample value> (default: 0)\n\
-sleep <sleep time in seconds before finishing> (default: 0)\n\
-dwh <1|0> Enable/Disable durable writer history (default: 0)\n",
argv[0]);
for (i = 1; i < argc;) {
READ_INTEGER_PARAM("-sleep", sleep);
READ_INTEGER_PARAM("-domain_id", domain_id);
READ_INTEGER_PARAM("-sample_count", sample_count);
READ_INTEGER_PARAM("-initial_value", initial_value);
READ_INTEGER_PARAM("-dwh", dwh);
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 publisher_main(domain_id, sample_count, initial_value, dwh, sleep);
}
#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 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.