repo_name
stringclasses 10
values | file_path
stringlengths 29
222
| content
stringlengths 24
926k
| extention
stringclasses 5
values |
---|---|---|---|
rticonnextdds-examples | data/projects/rticonnextdds-examples/connext_dds/ordered_presentation/c/ordered_publisher.c | /*******************************************************************************
(c) 2005-2014 Copyright, Real-Time Innovations, Inc. All rights reserved.
RTI grants Licensee a license to use, modify, compile, and create derivative
works of the Software. Licensee has the right to distribute object form only
for use with RTI products. The Software is provided "as is", with no warranty
of any type, including any warranty for fitness for any purpose. RTI is under
no obligation to maintain or support the Software. RTI shall not be liable for
any incidental or consequential damages arising out of the use or inability to
use the software.
******************************************************************************/
/* ordered_publisher.c
A publication of data of type ordered
This file is derived from code automatically generated by the rtiddsgen
command:
rtiddsgen -language C -example <arch> ordered.idl
Example publication of type ordered automatically generated by
'rtiddsgen'. To test them follow these steps:
(1) Compile this file and the example subscription.
(2) Start the subscription with the command
objs/<arch>/ordered_subscriber <domain_id> <sample_count>
(3) Start the publication with the command
objs/<arch>/ordered_publisher <domain_id> <sample_count>
(4) [Optional] Specify the list of discovery initial peers and
multicast receive addresses via an environment variable or a file
(in the current working directory) called NDDS_DISCOVERY_PEERS.
You can run any number of publishers and subscribers programs, and can
add and remove them dynamically from the domain.
Example:
To run the example application on domain <domain_id>:
On Unix:
objs/<arch>/ordered_publisher <domain_id>
objs/<arch>/ordered_subscriber <domain_id>
On Windows:
objs\<arch>\ordered_publisher <domain_id>
objs\<arch>\ordered_subscriber <domain_id>
modification history
------------ -------
*/
#include "ndds/ndds_c.h"
#include "ordered.h"
#include "orderedSupport.h"
#include <stdio.h>
#include <stdlib.h>
/* Delete all entities */
static int publisher_shutdown(
DDS_DomainParticipant *participant,
struct DDS_PublisherQos *publisher_qos)
{
DDS_ReturnCode_t retcode;
int status = 0;
if (participant != NULL) {
retcode = DDS_DomainParticipant_delete_contained_entities(participant);
if (retcode != DDS_RETCODE_OK) {
printf("delete_contained_entities error %d\n", retcode);
status = -1;
}
retcode = DDS_DomainParticipantFactory_delete_participant(
DDS_TheParticipantFactory,
participant);
if (retcode != DDS_RETCODE_OK) {
printf("delete_participant error %d\n", retcode);
status = -1;
}
retcode = DDS_PublisherQos_finalize(publisher_qos);
if (retcode != DDS_RETCODE_OK) {
printf("publisherQos_finalize error %d\n", retcode);
status = -1;
}
}
/* RTI Connext provides finalize_instance() method on
domain participant factory for people who want to release memory used
by the participant factory. Uncomment the following block of code for
clean destruction of the singleton. */
/*
retcode = DDS_DomainParticipantFactory_finalize_instance();
if (retcode != DDS_RETCODE_OK) {
printf("finalize_instance error %d\n", retcode);
status = -1;
}
*/
return status;
}
static int publisher_main(int domainId, int sample_count)
{
DDS_DomainParticipant *participant = NULL;
DDS_Publisher *publisher = NULL;
DDS_Topic *topic = NULL;
DDS_DataWriter *writer = NULL;
orderedDataWriter *ordered_writer = NULL;
ordered *instance0 = NULL;
ordered *instance1 = NULL;
DDS_ReturnCode_t retcode;
DDS_InstanceHandle_t instance_handle0 = DDS_HANDLE_NIL;
DDS_InstanceHandle_t instance_handle1 = DDS_HANDLE_NIL;
const char *type_name = NULL;
int count = 0;
struct DDS_Duration_t send_period = { 1, 0 };
struct DDS_PublisherQos publisher_qos = DDS_PublisherQos_INITIALIZER;
/* To customize participant QoS, use
the configuration file USER_QOS_PROFILES.xml */
participant = DDS_DomainParticipantFactory_create_participant(
DDS_TheParticipantFactory,
domainId,
&DDS_PARTICIPANT_QOS_DEFAULT,
NULL /* listener */,
DDS_STATUS_MASK_NONE);
if (participant == NULL) {
printf("create_participant error\n");
publisher_shutdown(participant, &publisher_qos);
return -1;
}
publisher = DDS_DomainParticipant_create_publisher_with_profile(
participant,
"ordered_Library",
"ordered_Profile_subscriber_instance",
NULL /* listener */,
DDS_STATUS_MASK_NONE);
if (publisher == NULL) {
printf("create_publisher error\n");
publisher_shutdown(participant, &publisher_qos);
return -1;
}
/* If you want to change the Publisher's QoS programmatically rather than
* using the XML file, you will need to add the following lines to your
* code and comment out the create_publisher call above.
*
* In this case, we set the presentation publish mode ordered in the topic.
*/
/*
retcode = DDS_DomainParticipant_get_default_publisher_qos(participant,
&publisher_qos);
if (retcode != DDS_RETCODE_OK) {
printf("get_default_publisher_qos error\n");
return -1;
}
publisher_qos.presentation.access_scope = DDS_TOPIC_PRESENTATION_QOS;
publisher_qos.presentation.ordered_access = DDS_BOOLEAN_TRUE;
publisher = DDS_DomainParticipant_create_publisher(participant,
&publisher_qos, NULL, DDS_STATUS_MASK_NONE);
if (publisher == NULL) {
printf("create_publisher error\n");
publisher_shutdown(participant, &publisher_qos);
return -1;
}
*/
/* Register type before creating topic */
type_name = orderedTypeSupport_get_type_name();
retcode = orderedTypeSupport_register_type(participant, type_name);
if (retcode != DDS_RETCODE_OK) {
printf("register_type error %d\n", retcode);
publisher_shutdown(participant, &publisher_qos);
return -1;
}
/* To customize topic QoS, use
the configuration file USER_QOS_PROFILES.xml */
topic = DDS_DomainParticipant_create_topic(
participant,
"Example ordered",
type_name,
&DDS_TOPIC_QOS_DEFAULT,
NULL /* listener */,
DDS_STATUS_MASK_NONE);
if (topic == NULL) {
printf("create_topic error\n");
publisher_shutdown(participant, &publisher_qos);
return -1;
}
/* To customize data writer QoS, use
the configuration file USER_QOS_PROFILES.xml */
writer = DDS_Publisher_create_datawriter(
publisher,
topic,
&DDS_DATAWRITER_QOS_DEFAULT,
NULL /* listener */,
DDS_STATUS_MASK_NONE);
if (writer == NULL) {
printf("create_datawriter error\n");
publisher_shutdown(participant, &publisher_qos);
return -1;
}
ordered_writer = orderedDataWriter_narrow(writer);
if (ordered_writer == NULL) {
printf("DataWriter narrow error\n");
publisher_shutdown(participant, &publisher_qos);
return -1;
}
/* Start changes for ordered_presentation */
/* Create data sample for writing */
instance0 = orderedTypeSupport_create_data_ex(DDS_BOOLEAN_TRUE);
instance1 = orderedTypeSupport_create_data_ex(DDS_BOOLEAN_TRUE);
if (instance0 == NULL || instance1 == NULL) {
printf("orderedTypeSupport_create_data error\n");
publisher_shutdown(participant, &publisher_qos);
return -1;
}
/* For a data type that has a key, if the same instance is going to be
written multiple times, initialize the key here
and register the keyed instance prior to writing */
instance0->id = 0;
instance1->id = 1;
instance_handle0 =
orderedDataWriter_register_instance(ordered_writer, instance0);
instance_handle1 =
orderedDataWriter_register_instance(ordered_writer, instance1);
/* Main loop */
for (count = 0; (sample_count == 0) || (count < sample_count); ++count) {
/* Modify the data to be written here */
instance0->value = count;
instance1->value = count;
printf("Writing instance0, value->%d\n", instance0->value);
retcode = orderedDataWriter_write(
ordered_writer,
instance0,
&instance_handle0);
if (retcode != DDS_RETCODE_OK) {
printf("write instance0 error %d\n", retcode);
}
printf("Writing instance1, value->%d\n", instance1->value);
retcode = orderedDataWriter_write(
ordered_writer,
instance1,
&instance_handle1);
if (retcode != DDS_RETCODE_OK) {
printf("write instance0 error %d\n", retcode);
}
NDDS_Utility_sleep(&send_period);
}
retcode = orderedDataWriter_unregister_instance(
ordered_writer,
instance0,
&instance_handle0);
if (retcode != DDS_RETCODE_OK) {
printf("unregister instance error %d\n", retcode);
}
retcode = orderedDataWriter_unregister_instance(
ordered_writer,
instance1,
&instance_handle1);
if (retcode != DDS_RETCODE_OK) {
printf("unregister instance error %d\n", retcode);
}
/* Delete data sample */
retcode = orderedTypeSupport_delete_data_ex(instance0, DDS_BOOLEAN_TRUE);
if (retcode != DDS_RETCODE_OK) {
printf("orderedTypeSupport_delete_data instance0 error %d\n", retcode);
}
retcode = orderedTypeSupport_delete_data_ex(instance1, DDS_BOOLEAN_TRUE);
if (retcode != DDS_RETCODE_OK) {
printf("orderedTypeSupport_delete_data instance1 error %d\n", retcode);
}
/* Cleanup and delete delete all entities */
return publisher_shutdown(participant, &publisher_qos);
}
#if defined(RTI_WINCE)
int wmain(int argc, wchar_t **argv)
{
int domainId = 0;
int sample_count = 0; /* infinite loop */
if (argc >= 2) {
domainId = _wtoi(argv[1]);
}
if (argc >= 3) {
sample_count = _wtoi(argv[2]);
}
/* Uncomment this to turn on additional logging
NDDS_Config_Logger_set_verbosity_by_category(
NDDS_Config_Logger_get_instance(),
NDDS_CONFIG_LOG_CATEGORY_API,
NDDS_CONFIG_LOG_VERBOSITY_STATUS_ALL);
*/
return publisher_main(domainId, sample_count);
}
#elif !(defined(RTI_VXWORKS) && !defined(__RTP__)) && !defined(RTI_PSOS)
int main(int argc, char *argv[])
{
int domainId = 0;
int sample_count = 0; /* infinite loop */
if (argc >= 2) {
domainId = atoi(argv[1]);
}
if (argc >= 3) {
sample_count = atoi(argv[2]);
}
/* Uncomment this to turn on additional logging
NDDS_Config_Logger_set_verbosity_by_category(
NDDS_Config_Logger_get_instance(),
NDDS_CONFIG_LOG_CATEGORY_API,
NDDS_CONFIG_LOG_VERBOSITY_STATUS_ALL);
*/
return publisher_main(domainId, sample_count);
}
#endif
#ifdef RTI_VX653
const unsigned char *__ctype = NULL;
void usrAppInit()
{
#ifdef USER_APPL_INIT
USER_APPL_INIT; /* for backwards compatibility */
#endif
/* add application specific code here */
taskSpawn(
"pub",
RTI_OSAPI_THREAD_PRIORITY_NORMAL,
0x8,
0x150000,
(FUNCPTR) publisher_main,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0);
}
#endif
| c |
rticonnextdds-examples | data/projects/rticonnextdds-examples/connext_dds/ordered_presentation/c++11/application.hpp | /*
* (c) Copyright, Real-Time Innovations, 2020. All rights reserved.
* RTI grants Licensee a license to use, modify, compile, and create derivative
* works of the software solely for use with RTI Connext DDS. Licensee may
* redistribute copies of the software provided that all such copies are subject
* to this license. The software is provided "as is", with no warranty of any
* type, including any warranty for fitness for any purpose. RTI is under no
* obligation to maintain or support the software. RTI shall not be liable for
* any incidental or consequential damages arising out of the use or inability
* to use the software.
*/
#ifndef APPLICATION_HPP
#define APPLICATION_HPP
#include <iostream>
#include <csignal>
#include <dds/core/ddscore.hpp>
namespace application {
// Catch control-C and tell application to shut down
bool shutdown_requested = false;
inline void stop_handler(int)
{
shutdown_requested = true;
std::cout << "preparing to shut down..." << std::endl;
}
inline void setup_signal_handlers()
{
signal(SIGINT, stop_handler);
signal(SIGTERM, stop_handler);
}
enum class ParseReturn { ok, failure, exit };
struct ApplicationArguments {
ParseReturn parse_result;
unsigned int domain_id;
unsigned int sample_count;
rti::config::Verbosity verbosity;
ApplicationArguments(
ParseReturn parse_result_param,
unsigned int domain_id_param,
unsigned int sample_count_param,
rti::config::Verbosity verbosity_param)
: parse_result(parse_result_param),
domain_id(domain_id_param),
sample_count(sample_count_param),
verbosity(verbosity_param)
{
}
};
inline void set_verbosity(
rti::config::Verbosity &verbosity,
int verbosity_value)
{
switch (verbosity_value) {
case 0:
verbosity = rti::config::Verbosity::SILENT;
break;
case 1:
verbosity = rti::config::Verbosity::EXCEPTION;
break;
case 2:
verbosity = rti::config::Verbosity::WARNING;
break;
case 3:
verbosity = rti::config::Verbosity::STATUS_ALL;
break;
default:
verbosity = rti::config::Verbosity::EXCEPTION;
break;
}
}
// Parses application arguments for example.
inline ApplicationArguments parse_arguments(int argc, char *argv[])
{
int arg_processing = 1;
bool show_usage = false;
ParseReturn parse_result = ParseReturn::ok;
unsigned int domain_id = 0;
unsigned int sample_count = (std::numeric_limits<unsigned int>::max)();
rti::config::Verbosity verbosity(rti::config::Verbosity::EXCEPTION);
while (arg_processing < argc) {
if ((argc > arg_processing + 1)
&& (strcmp(argv[arg_processing], "-d") == 0
|| strcmp(argv[arg_processing], "--domain") == 0)) {
domain_id = atoi(argv[arg_processing + 1]);
arg_processing += 2;
} else if (
(argc > arg_processing + 1)
&& (strcmp(argv[arg_processing], "-s") == 0
|| strcmp(argv[arg_processing], "--sample-count") == 0)) {
sample_count = atoi(argv[arg_processing + 1]);
arg_processing += 2;
} else if (
(argc > arg_processing + 1)
&& (strcmp(argv[arg_processing], "-v") == 0
|| strcmp(argv[arg_processing], "--verbosity") == 0)) {
set_verbosity(verbosity, atoi(argv[arg_processing + 1]));
arg_processing += 2;
} else if (
strcmp(argv[arg_processing], "-h") == 0
|| strcmp(argv[arg_processing], "--help") == 0) {
std::cout << "Example application." << std::endl;
show_usage = true;
parse_result = ParseReturn::exit;
break;
} else {
std::cout << "Bad parameter." << std::endl;
show_usage = true;
parse_result = ParseReturn::failure;
break;
}
}
if (show_usage) {
std::cout << "Usage:\n"
" -d, --domain <int> Domain ID this "
"application will\n"
" subscribe in. \n"
" Default: 0\n"
" -s, --sample_count <int> Number of samples to "
"receive before\n"
" cleanly shutting down. \n"
" Default: infinite\n"
" -v, --verbosity <int> How much debugging output "
"to show.\n"
" Range: 0-3 \n"
" Default: 1"
<< std::endl;
}
return ApplicationArguments(
parse_result,
domain_id,
sample_count,
verbosity);
}
} // namespace application
#endif // APPLICATION_HPP
| hpp |
rticonnextdds-examples | data/projects/rticonnextdds-examples/connext_dds/ordered_presentation/c++11/ordered_subscriber.cxx | /*******************************************************************************
(c) 2005-2015 Copyright, Real-Time Innovations, Inc. All rights reserved.
RTI grants Licensee a license to use, modify, compile, and create derivative
works of the Software. Licensee has the right to distribute object form only
for use with RTI products. The Software is provided "as is", with no warranty
of any type, including any warranty for fitness for any purpose. RTI is under
no obligation to maintain or support the Software. RTI shall not be liable for
any incidental or consequential damages arising out of the use or inability to
use the software.
******************************************************************************/
#include <iostream>
#include <dds/sub/ddssub.hpp>
#include <dds/core/ddscore.hpp>
#include <rti/util/util.hpp> // for sleep()
#include <rti/config/Logger.hpp> // for logging
#include "ordered.hpp"
#include "application.hpp" // for command line parsing and ctrl-c
// Instead of using listeners, we are polling the readers to be able to see
// the order of a set of received samples.
unsigned int poll_readers(std::vector<dds::sub::DataReader<ordered>> &readers)
{
unsigned int samples_read = 0;
for (std::vector<int>::size_type i = 0; i < readers.size(); i++) {
dds::sub::LoanedSamples<ordered> samples = readers[i].take();
for (auto sample : samples) {
if (sample.info().valid()) {
std::cout << std::string(i, '\t') << "Reader " << i
<< ": Instance" << sample.data().id()
<< "->value = " << sample.data().value() << std::endl;
samples_read++;
}
}
}
return samples_read;
}
void run_subscriber_application(
unsigned int domain_id,
unsigned int sample_count)
{
// Create a DomainParticipant.
dds::domain::DomainParticipant participant(domain_id);
// Create a Topic -- and automatically register the type.
dds::topic::Topic<ordered> topic(participant, "Example ordered");
// Create a reader per QoS profile: ordering by topic and instance modes.
std::vector<std::string> profile_names = {
"ordered_Library::ordered_Profile_subscriber_instance",
"ordered_Library::ordered_Profile_subscriber_topic"
};
std::vector<dds::sub::DataReader<ordered>> readers;
for (std::vector<int>::size_type i = 0; i < profile_names.size(); i++) {
std::cout << "Subscriber " << i << " using " << profile_names[i]
<< std::endl;
// Retrieve the subscriber QoS from USER_QOS_PROFILES.xml
dds::sub::qos::SubscriberQos subscriber_qos =
dds::core::QosProvider::Default().subscriber_qos(
profile_names[i]);
// If you want to change the Subscriber's QoS programmatically rather
// than using the XML file, you will need to comment out the previous
// subscriber_qos assignment and uncomment these files.
// SubscriberQos subscriber_qos;
// if (i == 0) {
// subscriber_qos << Presentation::InstanceAccessScope(false, true);
// } else if (i == 1) {
// subscriber_qos << Presentation::TopicAccessScope(false, true);
// }
// Create a subscriber with the custom QoS.
dds::sub::Subscriber subscriber(participant, subscriber_qos);
// Retrieve the DataReader QoS from USER_QOS_PROFILES.xml
dds::sub::qos::DataReaderQos reader_qos =
dds::core::QosProvider::Default().datareader_qos(
profile_names[i]);
// If you want to change the DataReader's QoS programmatically rather
// than using the XML file, you will need to comment out the previous
// reader_qos assignment and uncomment these files.
// DataReaderQos reader_qos;
// reader_qos << History::KeepLast(10)
// << Reliability::Reliable();
// Create a DataReader with the custom QoS.
dds::sub::DataReader<ordered> reader(subscriber, topic, reader_qos);
readers.push_back(reader);
}
// Main loop
unsigned int samples_read = 0;
while (!application::shutdown_requested && samples_read < sample_count) {
std::cout << "ordered subscriber sleeping for 4 sec.." << std::endl;
rti::util::sleep(dds::core::Duration(4));
samples_read += poll_readers(readers);
}
}
int main(int argc, char *argv[])
{
using namespace application;
// Parse arguments and handle control-C
auto arguments = parse_arguments(argc, argv);
if (arguments.parse_result == ParseReturn::exit) {
return EXIT_SUCCESS;
} else if (arguments.parse_result == ParseReturn::failure) {
return EXIT_FAILURE;
}
setup_signal_handlers();
// Sets Connext verbosity to help debugging
rti::config::Logger::instance().verbosity(arguments.verbosity);
try {
run_subscriber_application(arguments.domain_id, arguments.sample_count);
} catch (const std::exception &ex) {
// This will catch DDS exceptions
std::cerr << "Exception in run_subscriber_application(): " << ex.what()
<< std::endl;
return EXIT_FAILURE;
}
// Releases the memory used by the participant factory. Optional at
// application exit
dds::domain::DomainParticipant::finalize_participant_factory();
return EXIT_SUCCESS;
}
| cxx |
rticonnextdds-examples | data/projects/rticonnextdds-examples/connext_dds/ordered_presentation/c++11/ordered_publisher.cxx | /*******************************************************************************
(c) 2005-2015 Copyright, Real-Time Innovations, Inc. All rights reserved.
RTI grants Licensee a license to use, modify, compile, and create derivative
works of the Software. Licensee has the right to distribute object form only
for use with RTI products. The Software is provided "as is", with no warranty
of any type, including any warranty for fitness for any purpose. RTI is under
no obligation to maintain or support the Software. RTI shall not be liable for
any incidental or consequential damages arising out of the use or inability to
use the software.
******************************************************************************/
#include <dds/pub/ddspub.hpp>
#include <rti/util/util.hpp> // for sleep()
#include <rti/config/Logger.hpp> // for logging
#include "application.hpp" // for command line parsing and ctrl-c
#include "ordered.hpp"
void run_publisher_application(
unsigned int domain_id,
unsigned int sample_count)
{
// Create a DomainParticipant.
dds::domain::DomainParticipant participant(domain_id);
// Retrieve the custom ordered publisher QoS, from USER_QOS_PROFILES.xml
dds::pub::qos::PublisherQos publisher_qos =
dds::core::QosProvider::Default().publisher_qos(
"ordered_Library::ordered_Profile_subscriber_instance");
// If you want to change the Publisher's QoS programmatically rather
// than using the XML file, you will need to comment out the previous
// publisher_qos assignment and uncomment these files.
// PublisherQos publisher_qos;
// publisher_qos << Presentation::TopicAccessScope(false, true);
// Create a publisher with the ordered QoS.
dds::pub::Publisher publisher(participant, publisher_qos);
// Create a Topic -- and automatically register the type.
dds::topic::Topic<ordered> topic(participant, "Example ordered");
// Retrieve the DataWriter QoS, from USER_QOS_PROFILES.xml
dds::pub::qos::DataWriterQos writer_qos =
dds::core::QosProvider::Default().datawriter_qos(
"ordered_Library::ordered_Profile_subscriber_instance");
// If you want to change the Publisher's QoS programmatically rather
// than using the XML file, you will need to comment out the previous
// writer_qos assignment and uncomment these files.
// DataWriterQos writer_qos;
// writer_qos << Reliability::Reliable();
// Create a DataWriter.
dds::pub::DataWriter<ordered> writer(publisher, topic, writer_qos);
// Create two samples with different ID and register them
ordered instance0(0, 0);
dds::core::InstanceHandle handle0 = writer.register_instance(instance0);
ordered instance1(1, 0);
dds::core::InstanceHandle handle1 = writer.register_instance(instance1);
// Main loop
for (unsigned int samples_written = 0;
!application::shutdown_requested && samples_written < sample_count;
samples_written++) {
// Update content.
instance0.value(samples_written);
instance1.value(samples_written);
// Write the two samples.
std::cout << "writing instance0, value->" << instance0.value()
<< std::endl;
writer.write(instance0, handle0);
std::cout << "writing instance1, value->" << instance1.value()
<< std::endl;
writer.write(instance1, handle1);
rti::util::sleep(dds::core::Duration(1));
}
// Unregister the samples.
writer.unregister_instance(handle0);
writer.unregister_instance(handle1);
}
int main(int argc, char *argv[])
{
using namespace application;
// Parse arguments and handle control-C
auto arguments = parse_arguments(argc, argv);
if (arguments.parse_result == ParseReturn::exit) {
return EXIT_SUCCESS;
} else if (arguments.parse_result == ParseReturn::failure) {
return EXIT_FAILURE;
}
setup_signal_handlers();
// Sets Connext verbosity to help debugging
rti::config::Logger::instance().verbosity(arguments.verbosity);
try {
run_publisher_application(arguments.domain_id, arguments.sample_count);
} catch (const std::exception &ex) {
// This will catch DDS exceptions
std::cerr << "Exception in run_publisher_application(): " << ex.what()
<< std::endl;
return EXIT_FAILURE;
}
// Releases the memory used by the participant factory. Optional at
// application exit
dds::domain::DomainParticipant::finalize_participant_factory();
return EXIT_SUCCESS;
}
| cxx |
rticonnextdds-examples | data/projects/rticonnextdds-examples/connext_dds/waitset_query_cond/c++/waitset_query_cond_subscriber.cxx | /*******************************************************************************
(c) 2005-2014 Copyright, Real-Time Innovations, Inc. All rights reserved.
RTI grants Licensee a license to use, modify, compile, and create derivative
works of the Software. Licensee has the right to distribute object form only
for use with RTI products. The Software is provided "as is", with no warranty
of any type, including any warranty for fitness for any purpose. RTI is under
no obligation to maintain or support the Software. RTI shall not be liable for
any incidental or consequential damages arising out of the use or inability to
use the software.
******************************************************************************/
/* waitset_query_cond_subscriber.cxx
A subscription example
This file is derived from code automatically generated by the rtiddsgen
command:
rtiddsgen -language C++ -example <arch> waitset_query_cond.idl
Example subscription of type waitset_query_cond automatically generated by
'rtiddsgen'. To test them follow these steps:
(1) Compile this file and the example publication.
(2) Start the subscription with the command
objs/<arch>/waitset_query_cond_subscriber <domain_id> <sample_count>
(3) Start the publication with the command
objs/<arch>/waitset_query_cond_publisher <domain_id> <sample_count>
(4) [Optional] Specify the list of discovery initial peers and
multicast receive addresses via an environment variable or a file
(in the current working directory) called NDDS_DISCOVERY_PEERS.
You can run any number of publishers and subscribers programs, and can
add and remove them dynamically from the domain.
Example:
To run the example application on domain <domain_id>:
On Unix:
objs/<arch>/waitset_query_cond_publisher <domain_id>
objs/<arch>/waitset_query_cond_subscriber <domain_id>
On Windows:
objs\<arch>\waitset_query_cond_publisher <domain_id>
objs\<arch>\waitset_query_cond_subscriber <domain_id>
modification history
------------ -------
*/
#include <stdio.h>
#include <stdlib.h>
#ifdef RTI_VX653
#include <vThreadsData.h>
#endif
#include "ndds/ndds_cpp.h"
#include "waitset_query_cond.h"
#include "waitset_query_condSupport.h"
/* We don't need to use listeners as we are going to use WaitSet and Conditions
* so we have removed the auto generated code for listeners here
*/
/* Delete all entities */
static int subscriber_shutdown(DDSDomainParticipant *participant)
{
DDS_ReturnCode_t retcode;
int status = 0;
if (participant != NULL) {
retcode = participant->delete_contained_entities();
if (retcode != DDS_RETCODE_OK) {
printf("delete_contained_entities error %d\n", retcode);
status = -1;
}
retcode = DDSTheParticipantFactory->delete_participant(participant);
if (retcode != DDS_RETCODE_OK) {
printf("delete_participant error %d\n", retcode);
status = -1;
}
}
/* RTI Connext provides the finalize_instance() method on
domain participant factory for people who want to release memory used
by the participant factory. Uncomment the following block of code for
clean destruction of the singleton. */
/*
retcode = DDSDomainParticipantFactory::finalize_instance();
if (retcode != DDS_RETCODE_OK) {
printf("finalize_instance error %d\n", retcode);
status = -1;
}
*/
return status;
}
extern "C" int subscriber_main(int domainId, int sample_count)
{
DDSDomainParticipant *participant = NULL;
DDSSubscriber *subscriber = NULL;
DDSTopic *topic = NULL;
DDSDataReader *reader = NULL;
DDS_ReturnCode_t retcode;
const char *type_name = NULL;
int count = 0;
DDS_Duration_t wait_timeout = { 1, 0 };
int status = 0;
/* Additional variable for this example */
int i = 1;
DDSQueryCondition *query_condition = NULL;
DDSWaitSet *waitset = NULL;
waitset_query_condDataReader *waitset_query_cond_reader = NULL;
const char *query_expression = DDS_String_dup("name MATCH %0");
DDS_StringSeq query_parameters;
DDSConditionSeq active_conditions_seq;
waitset_query_condSeq data_seq;
DDS_SampleInfoSeq info_seq;
/* Auxiliary variables */
char *odd_string = DDS_String_dup("'ODD'");
char *even_string = DDS_String_dup("'EVEN'");
/* To customize the participant QoS, use
the configuration file USER_QOS_PROFILES.xml */
participant = DDSTheParticipantFactory->create_participant(
domainId,
DDS_PARTICIPANT_QOS_DEFAULT,
NULL /* listener */,
DDS_STATUS_MASK_NONE);
if (participant == NULL) {
printf("create_participant error\n");
subscriber_shutdown(participant);
return -1;
}
/* To customize the subscriber QoS, use
the configuration file USER_QOS_PROFILES.xml */
subscriber = participant->create_subscriber(
DDS_SUBSCRIBER_QOS_DEFAULT,
NULL /* listener */,
DDS_STATUS_MASK_NONE);
if (subscriber == NULL) {
printf("create_subscriber error\n");
subscriber_shutdown(participant);
return -1;
}
/* Register the type before creating the topic */
type_name = waitset_query_condTypeSupport::get_type_name();
retcode = waitset_query_condTypeSupport::register_type(
participant,
type_name);
if (retcode != DDS_RETCODE_OK) {
printf("register_type error %d\n", retcode);
subscriber_shutdown(participant);
return -1;
}
/* To customize the topic QoS, use
the configuration file USER_QOS_PROFILES.xml */
topic = participant->create_topic(
"Example waitset_query_cond",
type_name,
DDS_TOPIC_QOS_DEFAULT,
NULL /* listener */,
DDS_STATUS_MASK_NONE);
if (topic == NULL) {
printf("create_topic error\n");
subscriber_shutdown(participant);
return -1;
}
/* To customize the data reader QoS, use
the configuration file USER_QOS_PROFILES.xml */
reader = subscriber->create_datareader(
topic,
DDS_DATAREADER_QOS_DEFAULT,
NULL,
DDS_STATUS_MASK_NONE);
if (reader == NULL) {
printf("create_datareader error\n");
subscriber_shutdown(participant);
return -1;
}
/* Narrow the reader into your specific data type */
waitset_query_cond_reader = waitset_query_condDataReader::narrow(reader);
if (waitset_query_cond_reader == NULL) {
printf("DataReader narrow error\n");
return -1;
}
/* Create query condition */
query_parameters.ensure_length(1, 1);
/* The initial value of the parameters is EVEN string */
query_parameters[0] = even_string;
query_condition = waitset_query_cond_reader->create_querycondition(
DDS_NOT_READ_SAMPLE_STATE,
DDS_ANY_VIEW_STATE,
DDS_ANY_INSTANCE_STATE,
query_expression,
query_parameters);
if (query_condition == NULL) {
printf("create_query_condition error\n");
subscriber_shutdown(participant);
return -1;
}
waitset = new DDSWaitSet();
if (waitset == NULL) {
printf("create waitset error\n");
subscriber_shutdown(participant);
return -1;
}
/* Attach Query Conditions */
retcode = waitset->attach_condition((DDSCondition *) query_condition);
if (retcode != DDS_RETCODE_OK) {
printf("attach_condition error\n");
subscriber_shutdown(participant);
return -1;
}
printf("\n>>>Timeout: %.0d sec & %d nanosec\n",
wait_timeout.sec,
wait_timeout.nanosec);
printf(">>> Query conditions: name MATCH %%0\n");
printf("\t%%0 = %s\n", query_parameters[0]);
printf("---------------------------------\n\n");
/* Main loop */
for (count = 0; (sample_count == 0) || (count < sample_count); ++count) {
/* We set a new parameter in the Query Condition after 7 secs */
if (count == 7) {
query_parameters[0] = odd_string;
printf("CHANGING THE QUERY CONDITION\n");
printf("\n>>> Query conditions: name MATCH %%0\n");
printf("\t%%0 = %s\n", query_parameters[0]);
printf(">>> We keep one sample in the history\n");
printf("-------------------------------------\n\n");
query_condition->set_query_parameters(query_parameters);
}
/* wait() blocks execution of the thread until one or more attached
* Conditions become true, or until a user-specified timeout expires.
*/
retcode = waitset->wait(
active_conditions_seq, /* active conditions sequence */
wait_timeout); /* timeout */
/* We get to timeout if no conditions were triggered */
if (retcode == DDS_RETCODE_TIMEOUT) {
printf("Wait timed out!! No conditions were triggered.\n");
continue;
} else if (retcode != DDS_RETCODE_OK) {
printf("wait returned error: %d", retcode);
break;
}
retcode = DDS_RETCODE_OK;
while (retcode != DDS_RETCODE_NO_DATA) {
retcode = waitset_query_cond_reader->take_w_condition(
data_seq,
info_seq,
DDS_LENGTH_UNLIMITED,
query_condition);
for (i = 0; i < waitset_query_condSeq_get_length(&data_seq); ++i) {
if (!info_seq[i].valid_data) {
printf("Got metadata\n");
continue;
}
waitset_query_condTypeSupport::print_data(&data_seq[i]);
}
waitset_query_cond_reader->return_loan(data_seq, info_seq);
}
}
/* Delete all entities */
status = subscriber_shutdown(participant);
return status;
}
#if defined(RTI_WINCE)
int wmain(int argc, wchar_t **argv)
{
int domainId = 0;
int sample_count = 0; /* infinite loop */
if (argc >= 2) {
domainId = _wtoi(argv[1]);
}
if (argc >= 3) {
sample_count = _wtoi(argv[2]);
}
/* Uncomment this to turn on additional logging
NDDSConfigLogger::get_instance()->
set_verbosity_by_category(NDDS_CONFIG_LOG_CATEGORY_API,
NDDS_CONFIG_LOG_VERBOSITY_STATUS_ALL);
*/
return subscriber_main(domainId, sample_count);
}
#elif !(defined(RTI_VXWORKS) && !defined(__RTP__)) && !defined(RTI_PSOS)
int main(int argc, char *argv[])
{
int domainId = 0;
int sample_count = 0; /* infinite loop */
if (argc >= 2) {
domainId = atoi(argv[1]);
}
if (argc >= 3) {
sample_count = atoi(argv[2]);
}
/* Uncomment this to turn on additional logging
NDDSConfigLogger::get_instance()->
set_verbosity_by_category(NDDS_CONFIG_LOG_CATEGORY_API,
NDDS_CONFIG_LOG_VERBOSITY_STATUS_ALL);
*/
return subscriber_main(domainId, sample_count);
}
#endif
#ifdef RTI_VX653
const unsigned char *__ctype = *(__ctypePtrGet());
extern "C" void usrAppInit()
{
#ifdef USER_APPL_INIT
USER_APPL_INIT; /* for backwards compatibility */
#endif
/* add application specific code here */
taskSpawn(
"sub",
RTI_OSAPI_THREAD_PRIORITY_NORMAL,
0x8,
0x150000,
(FUNCPTR) subscriber_main,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0);
}
#endif
| cxx |
rticonnextdds-examples | data/projects/rticonnextdds-examples/connext_dds/waitset_query_cond/c++/waitset_query_cond_publisher.cxx | /*******************************************************************************
(c) 2005-2014 Copyright, Real-Time Innovations, Inc. All rights reserved.
RTI grants Licensee a license to use, modify, compile, and create derivative
works of the Software. Licensee has the right to distribute object form only
for use with RTI products. The Software is provided "as is", with no warranty
of any type, including any warranty for fitness for any purpose. RTI is under
no obligation to maintain or support the Software. RTI shall not be liable for
any incidental or consequential damages arising out of the use or inability to
use the software.
******************************************************************************/
/* waitset_query_cond_publisher.cxx
A publication of data of type waitset_query_cond
This file is derived from code automatically generated by the rtiddsgen
command:
rtiddsgen -language C++ -example <arch> waitset_query_cond.idl
Example publication of type waitset_query_cond automatically generated by
'rtiddsgen'. To test them follow these steps:
(1) Compile this file and the example subscription.
(2) Start the subscription with the command
objs/<arch>/waitset_query_cond_subscriber <domain_id> <sample_count>
(3) Start the publication with the command
objs/<arch>/waitset_query_cond_publisher <domain_id> <sample_count>
(4) [Optional] Specify the list of discovery initial peers and
multicast receive addresses via an environment variable or a file
(in the current working directory) called NDDS_DISCOVERY_PEERS.
You can run any number of publishers and subscribers programs, and can
add and remove them dynamically from the domain.
Example:
To run the example application on domain <domain_id>:
On Unix:
objs/<arch>/waitset_query_cond_publisher <domain_id> o
objs/<arch>/waitset_query_cond_subscriber <domain_id>
On Windows:
objs\<arch>\waitset_query_cond_publisher <domain_id>
objs\<arch>\waitset_query_cond_subscriber <domain_id>
modification history
------------ -------
*/
#include <stdio.h>
#include <stdlib.h>
#ifdef RTI_VX653
#include <vThreadsData.h>
#endif
#include "ndds/ndds_cpp.h"
#include "waitset_query_cond.h"
#include "waitset_query_condSupport.h"
/* Delete all entities */
static int publisher_shutdown(DDSDomainParticipant *participant)
{
DDS_ReturnCode_t retcode;
int status = 0;
if (participant != NULL) {
retcode = participant->delete_contained_entities();
if (retcode != DDS_RETCODE_OK) {
printf("delete_contained_entities error %d\n", retcode);
status = -1;
}
retcode = DDSTheParticipantFactory->delete_participant(participant);
if (retcode != DDS_RETCODE_OK) {
printf("delete_participant error %d\n", retcode);
status = -1;
}
}
/* RTI Connext provides finalize_instance() method on
domain participant factory for people who want to release memory used
by the participant factory. Uncomment the following block of code for
clean destruction of the singleton. */
/*
retcode = DDSDomainParticipantFactory::finalize_instance();
if (retcode != DDS_RETCODE_OK) {
printf("finalize_instance error %d\n", retcode);
status = -1;
}
*/
return status;
}
extern "C" int publisher_main(int domainId, int sample_count)
{
DDSDomainParticipant *participant = NULL;
DDSPublisher *publisher = NULL;
DDSTopic *topic = NULL;
DDSDataWriter *writer = NULL;
waitset_query_condDataWriter *waitset_query_cond_writer = NULL;
waitset_query_cond *instance = NULL;
DDS_ReturnCode_t retcode;
DDS_InstanceHandle_t instance_handle = DDS_HANDLE_NIL;
const char *type_name = NULL;
int count = 0;
DDS_Duration_t send_period = { 0, 500000000 };
/* Auxiliary variables */
char *odd_string = DDS_String_dup("ODD");
char *even_string = DDS_String_dup("EVEN");
/* To customize participant QoS, use
the configuration file USER_QOS_PROFILES.xml */
participant = DDSTheParticipantFactory->create_participant(
domainId,
DDS_PARTICIPANT_QOS_DEFAULT,
NULL /* listener */,
DDS_STATUS_MASK_NONE);
if (participant == NULL) {
printf("create_participant error\n");
publisher_shutdown(participant);
return -1;
}
/* To customize publisher QoS, use
the configuration file USER_QOS_PROFILES.xml */
publisher = participant->create_publisher(
DDS_PUBLISHER_QOS_DEFAULT,
NULL /* listener */,
DDS_STATUS_MASK_NONE);
if (publisher == NULL) {
printf("create_publisher error\n");
publisher_shutdown(participant);
return -1;
}
/* Register type before creating topic */
type_name = waitset_query_condTypeSupport::get_type_name();
retcode = waitset_query_condTypeSupport::register_type(
participant,
type_name);
if (retcode != DDS_RETCODE_OK) {
printf("register_type error %d\n", retcode);
publisher_shutdown(participant);
return -1;
}
/* To customize topic QoS, use
the configuration file USER_QOS_PROFILES.xml */
topic = participant->create_topic(
"Example waitset_query_cond",
type_name,
DDS_TOPIC_QOS_DEFAULT,
NULL /* listener */,
DDS_STATUS_MASK_NONE);
if (topic == NULL) {
printf("create_topic error\n");
publisher_shutdown(participant);
return -1;
}
/* To customize data writer QoS, use
the configuration file USER_QOS_PROFILES.xml */
writer = publisher->create_datawriter(
topic,
DDS_DATAWRITER_QOS_DEFAULT,
NULL /* listener */,
DDS_STATUS_MASK_NONE);
if (writer == NULL) {
printf("create_datawriter error\n");
publisher_shutdown(participant);
return -1;
}
waitset_query_cond_writer = waitset_query_condDataWriter::narrow(writer);
if (waitset_query_cond_writer == NULL) {
printf("DataWriter narrow error\n");
publisher_shutdown(participant);
return -1;
}
/* Create data sample for writing */
instance = waitset_query_condTypeSupport::create_data();
if (instance == NULL) {
printf("waitset_query_condTypeSupport::create_data error\n");
publisher_shutdown(participant);
return -1;
}
/* For a data type that has a key, if the same instance is going to be
written multiple times, initialize the key here
and register the keyed instance prior to writing */
/*
instance_handle =
waitset_query_cond_writer->register_instance(*instance);
*/
/* Main loop */
for (count = 0; (sample_count == 0) || (count < sample_count); ++count) {
printf("Writing waitset_query_cond, count %d\n", count);
/* Modify the data to be sent here */
if (count % 2 == 1) {
instance->name = odd_string;
} else {
instance->name = even_string;
}
instance->x = count;
retcode = waitset_query_cond_writer->write(*instance, instance_handle);
if (retcode != DDS_RETCODE_OK) {
printf("write error %d\n", retcode);
}
NDDSUtility::sleep(send_period);
}
/*
retcode = waitset_query_cond_writer->unregister_instance(
*instance, instance_handle);
if (retcode != DDS_RETCODE_OK) {
printf("unregister instance error %d\n", retcode);
}
*/
/* Delete data sample */
retcode = waitset_query_condTypeSupport::delete_data(instance);
if (retcode != DDS_RETCODE_OK) {
printf("waitset_query_condTypeSupport::delete_data error %d\n",
retcode);
}
/* Delete all entities */
return publisher_shutdown(participant);
}
#if defined(RTI_WINCE)
int wmain(int argc, wchar_t **argv)
{
int domainId = 0;
int sample_count = 0; /* infinite loop */
if (argc >= 2) {
domainId = _wtoi(argv[1]);
}
if (argc >= 3) {
sample_count = _wtoi(argv[2]);
}
/* Uncomment this to turn on additional logging
NDDSConfigLogger::get_instance()->
set_verbosity_by_category(NDDS_CONFIG_LOG_CATEGORY_API,
NDDS_CONFIG_LOG_VERBOSITY_STATUS_ALL);
*/
return publisher_main(domainId, sample_count);
}
#elif !(defined(RTI_VXWORKS) && !defined(__RTP__)) && !defined(RTI_PSOS)
int main(int argc, char *argv[])
{
int domainId = 0;
int sample_count = 0; /* infinite loop */
if (argc >= 2) {
domainId = atoi(argv[1]);
}
if (argc >= 3) {
sample_count = atoi(argv[2]);
}
/* Uncomment this to turn on additional logging
NDDSConfigLogger::get_instance()->
set_verbosity_by_category(NDDS_CONFIG_LOG_CATEGORY_API,
NDDS_CONFIG_LOG_VERBOSITY_STATUS_ALL);
*/
return publisher_main(domainId, sample_count);
}
#endif
#ifdef RTI_VX653
const unsigned char *__ctype = *(__ctypePtrGet());
extern "C" void usrAppInit()
{
#ifdef USER_APPL_INIT
USER_APPL_INIT; /* for backwards compatibility */
#endif
/* add application specific code here */
taskSpawn(
"pub",
RTI_OSAPI_THREAD_PRIORITY_NORMAL,
0x8,
0x150000,
(FUNCPTR) publisher_main,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0);
}
#endif
| cxx |
rticonnextdds-examples | data/projects/rticonnextdds-examples/connext_dds/waitset_query_cond/c++98/waitset_query_cond_subscriber.cxx | /*******************************************************************************
(c) 2005-2014 Copyright, Real-Time Innovations, Inc. All rights reserved.
RTI grants Licensee a license to use, modify, compile, and create derivative
works of the Software. Licensee has the right to distribute object form only
for use with RTI products. The Software is provided "as is", with no warranty
of any type, including any warranty for fitness for any purpose. RTI is under
no obligation to maintain or support the Software. RTI shall not be liable for
any incidental or consequential damages arising out of the use or inability to
use the software.
******************************************************************************/
#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include "ndds/ndds_cpp.h"
#include "waitset_query_cond.h"
#include "waitset_query_condSupport.h"
#include "application.h"
using namespace application;
static int shutdown_participant(
DDSDomainParticipant *participant,
const char *shutdown_message,
int status);
/* We don't need to use listeners as we are going to use WaitSet and Conditions
* so we have removed the auto generated code for listeners here
*/
int run_subscriber_application(
unsigned int domain_id,
unsigned int sample_count)
{
DDS_Duration_t wait_timeout = { 1, 0 };
const char *query_expression = DDS_String_dup("name MATCH %0");
char *odd_string = DDS_String_dup("'ODD'");
char *even_string = DDS_String_dup("'EVEN'");
// Start communicating in a domain, usually one participant per application
DDSDomainParticipant *participant =
DDSTheParticipantFactory->create_participant(
domain_id,
DDS_PARTICIPANT_QOS_DEFAULT,
NULL /* listener */,
DDS_STATUS_MASK_NONE);
if (participant == NULL) {
return shutdown_participant(
participant,
"create_participant error",
EXIT_FAILURE);
}
// A Subscriber allows an application to create one or more DataReaders
DDSSubscriber *subscriber = participant->create_subscriber(
DDS_SUBSCRIBER_QOS_DEFAULT,
NULL /* listener */,
DDS_STATUS_MASK_NONE);
if (subscriber == NULL) {
return shutdown_participant(
participant,
"create_subscriber error",
EXIT_FAILURE);
}
// Register the datatype to use when creating the Topic
const char *type_name = waitset_query_condTypeSupport::get_type_name();
DDS_ReturnCode_t retcode = waitset_query_condTypeSupport::register_type(
participant,
type_name);
if (retcode != DDS_RETCODE_OK) {
return shutdown_participant(
participant,
"register_type error",
EXIT_FAILURE);
}
// Create a Topic with a name and a datatype
DDSTopic *topic = participant->create_topic(
"Example waitset_query_cond",
type_name,
DDS_TOPIC_QOS_DEFAULT,
NULL /* listener */,
DDS_STATUS_MASK_NONE);
if (topic == NULL) {
return shutdown_participant(
participant,
"create_topic error",
EXIT_FAILURE);
}
// This DataReader reads data on "Example waitset_query_cond" Topic
DDSDataReader *untyped_reader = subscriber->create_datareader(
topic,
DDS_DATAREADER_QOS_DEFAULT,
NULL,
DDS_STATUS_MASK_NONE);
if (untyped_reader == NULL) {
return shutdown_participant(
participant,
"create_datareader error",
EXIT_FAILURE);
}
// Narrow casts from a untyped DataReader to a reader of your type
waitset_query_condDataReader *typed_reader =
waitset_query_condDataReader::narrow(untyped_reader);
if (typed_reader == NULL) {
return shutdown_participant(
participant,
"DataReader narrow error",
EXIT_FAILURE);
}
// Create query condition
DDS_StringSeq query_parameters;
query_parameters.ensure_length(1, 1);
// The initial value of the parameters is EVEN string
query_parameters[0] = even_string;
DDSQueryCondition *query_condition = typed_reader->create_querycondition(
DDS_NOT_READ_SAMPLE_STATE,
DDS_ANY_VIEW_STATE,
DDS_ANY_INSTANCE_STATE,
query_expression,
query_parameters);
if (query_condition == NULL) {
return shutdown_participant(
participant,
"create_query_condition narrow error",
EXIT_FAILURE);
}
DDSWaitSet *waitset = new DDSWaitSet();
if (waitset == NULL) {
return shutdown_participant(
participant,
"create waitset error",
EXIT_FAILURE);
}
// Attach Query Conditions
retcode = waitset->attach_condition((DDSCondition *) query_condition);
if (retcode != DDS_RETCODE_OK) {
return shutdown_participant(
participant,
"attach_condition error",
EXIT_FAILURE);
}
std::cout << "\n>>>Timeout: " << wait_timeout.sec << " sec & "
<< wait_timeout.nanosec << " nanosec\n";
std::cout << ">>> Query conditions: name MATCH %%0\n";
std::cout << "\t%%0 = " << query_parameters[0] << std::endl;
std::cout << "---------------------------------\n\n";
// Main loop. Wait for data to arrive, and process when it arrives
unsigned int samples_read = 0;
int count = 0;
DDS_SampleInfoSeq info_seq;
waitset_query_condSeq data_seq;
DDSConditionSeq active_conditions_seq;
while (!shutdown_requested && samples_read < sample_count) {
count++;
// We set a new parameter in the Query Condition after 7 secs
if (count == 7) {
query_parameters[0] = odd_string;
std::cout << "CHANGING THE QUERY CONDITION\n";
std::cout << "\n>>> Query conditions: name MATCH %%0\n";
std::cout << "\t%%0 = " << query_parameters[0] << std::endl;
std::cout << ">>> We keep one sample in the history\n";
std::cout << "-------------------------------------\n\n";
query_condition->set_query_parameters(query_parameters);
}
/* wait() blocks execution of the thread until one or more attached
* Conditions become true, or until a user-specified timeout expires.
*/
retcode = waitset->wait(
active_conditions_seq, /* active conditions sequence */
wait_timeout); /* timeout */
/* We get to timeout if no conditions were triggered */
if (retcode == DDS_RETCODE_TIMEOUT) {
std::cout << "Wait timed out!! No conditions were triggered.\n";
continue;
} else if (retcode != DDS_RETCODE_OK) {
std::cerr << "wait returned error: " << retcode << std::endl;
break;
}
retcode = DDS_RETCODE_OK;
while (retcode != DDS_RETCODE_NO_DATA) {
retcode = typed_reader->take_w_condition(
data_seq,
info_seq,
DDS_LENGTH_UNLIMITED,
query_condition);
for (int i = 0; i < waitset_query_condSeq_get_length(&data_seq);
++i) {
if (!info_seq[i].valid_data) {
std::cout << "Got metadata\n";
continue;
}
waitset_query_condTypeSupport::print_data(&data_seq[i]);
samples_read++;
}
typed_reader->return_loan(data_seq, info_seq);
}
}
// Cleanup
return shutdown_participant(participant, "Shutting down", 0);
}
// Delete all entities
static int shutdown_participant(
DDSDomainParticipant *participant,
const char *shutdown_message,
int status)
{
DDS_ReturnCode_t retcode;
std::cout << shutdown_message << std::endl;
if (participant != NULL) {
// Cleanup everything created by this Participant
retcode = participant->delete_contained_entities();
if (retcode != DDS_RETCODE_OK) {
std::cerr << "delete_contained_entities error" << retcode
<< std::endl;
status = EXIT_FAILURE;
}
retcode = DDSTheParticipantFactory->delete_participant(participant);
if (retcode != DDS_RETCODE_OK) {
std::cerr << "delete_participant error" << retcode << std::endl;
status = EXIT_FAILURE;
}
}
return status;
}
int main(int argc, char *argv[])
{
// Parse arguments and handle control-C
ApplicationArguments arguments;
parse_arguments(arguments, argc, argv);
if (arguments.parse_result == PARSE_RETURN_EXIT) {
return EXIT_SUCCESS;
} else if (arguments.parse_result == PARSE_RETURN_FAILURE) {
return EXIT_FAILURE;
}
setup_signal_handlers();
// Sets Connext verbosity to help debugging
NDDSConfigLogger::get_instance()->set_verbosity(arguments.verbosity);
int status = run_subscriber_application(
arguments.domain_id,
arguments.sample_count);
// Releases the memory used by the participant factory. Optional at
// application exit
DDS_ReturnCode_t retcode = DDSDomainParticipantFactory::finalize_instance();
if (retcode != DDS_RETCODE_OK) {
std::cerr << "finalize_instance error" << retcode << std::endl;
status = EXIT_FAILURE;
}
return status;
}
| cxx |
rticonnextdds-examples | data/projects/rticonnextdds-examples/connext_dds/waitset_query_cond/c++98/application.h | /*
* (c) Copyright, Real-Time Innovations, 2020. All rights reserved.
* RTI grants Licensee a license to use, modify, compile, and create derivative
* works of the software solely for use with RTI Connext DDS. Licensee may
* redistribute copies of the software provided that all such copies are subject
* to this license. The software is provided "as is", with no warranty of any
* type, including any warranty for fitness for any purpose. RTI is under no
* obligation to maintain or support the software. RTI shall not be liable for
* any incidental or consequential damages arising out of the use or inability
* to use the software.
*/
#ifndef APPLICATION_H
#define APPLICATION_H
#include <iostream>
#include <csignal>
#include <climits>
namespace application {
// Catch control-C and tell application to shut down
bool shutdown_requested = false;
inline void stop_handler(int)
{
shutdown_requested = true;
std::cout << "preparing to shut down..." << std::endl;
}
inline void setup_signal_handlers()
{
signal(SIGINT, stop_handler);
signal(SIGTERM, stop_handler);
}
enum ParseReturn { PARSE_RETURN_OK, PARSE_RETURN_FAILURE, PARSE_RETURN_EXIT };
struct ApplicationArguments {
ParseReturn parse_result;
unsigned int domain_id;
unsigned int sample_count;
NDDS_Config_LogVerbosity verbosity;
};
inline void set_verbosity(ApplicationArguments &arguments, int verbosity)
{
switch (verbosity) {
case 0:
arguments.verbosity = NDDS_CONFIG_LOG_VERBOSITY_SILENT;
break;
case 1:
arguments.verbosity = NDDS_CONFIG_LOG_VERBOSITY_ERROR;
break;
case 2:
arguments.verbosity = NDDS_CONFIG_LOG_VERBOSITY_WARNING;
break;
case 3:
arguments.verbosity = NDDS_CONFIG_LOG_VERBOSITY_STATUS_ALL;
break;
default:
arguments.verbosity = NDDS_CONFIG_LOG_VERBOSITY_ERROR;
break;
}
}
// Parses application arguments for example. Returns whether to exit.
inline void parse_arguments(
ApplicationArguments &arguments,
int argc,
char *argv[])
{
int arg_processing = 1;
bool show_usage = false;
arguments.domain_id = 0;
arguments.sample_count = INT_MAX;
arguments.verbosity = NDDS_CONFIG_LOG_VERBOSITY_ERROR;
arguments.parse_result = PARSE_RETURN_OK;
while (arg_processing < argc) {
if ((argc > arg_processing + 1)
&& (strcmp(argv[arg_processing], "-d") == 0
|| strcmp(argv[arg_processing], "--domain") == 0)) {
arguments.domain_id = atoi(argv[arg_processing + 1]);
arg_processing += 2;
} else if (
(argc > arg_processing + 1)
&& (strcmp(argv[arg_processing], "-s") == 0
|| strcmp(argv[arg_processing], "--sample-count") == 0)) {
arguments.sample_count = atoi(argv[arg_processing + 1]);
arg_processing += 2;
} else if (
(argc > arg_processing + 1)
&& (strcmp(argv[arg_processing], "-v") == 0
|| strcmp(argv[arg_processing], "--verbosity") == 0)) {
set_verbosity(arguments, atoi(argv[arg_processing + 1]));
arg_processing += 2;
} else if (
strcmp(argv[arg_processing], "-h") == 0
|| strcmp(argv[arg_processing], "--help") == 0) {
std::cout << "Example application." << std::endl;
show_usage = true;
arguments.parse_result = PARSE_RETURN_EXIT;
break;
} else {
std::cout << "Bad parameter." << std::endl;
show_usage = true;
arguments.parse_result = PARSE_RETURN_FAILURE;
break;
}
}
if (show_usage) {
std::cout << "Usage:\n"
" -d, --domain <int> Domain ID this "
"application will\n"
" subscribe in. \n"
" Default: 0\n"
" -s, --sample_count <int> Number of samples to "
"receive before\n"
" cleanly shutting down. \n"
" Default: infinite\n"
" -v, --verbosity <int> How much debugging output "
"to show.\n"
" Range: 0-3 \n"
" Default: 1"
<< std::endl;
}
}
} // namespace application
#endif // APPLICATION_H
| h |
rticonnextdds-examples | data/projects/rticonnextdds-examples/connext_dds/waitset_query_cond/c++98/waitset_query_cond_publisher.cxx | /*******************************************************************************
(c) 2005-2014 Copyright, Real-Time Innovations, Inc. All rights reserved.
RTI grants Licensee a license to use, modify, compile, and create derivative
works of the Software. Licensee has the right to distribute object form only
for use with RTI products. The Software is provided "as is", with no warranty
of any type, including any warranty for fitness for any purpose. RTI is under
no obligation to maintain or support the Software. RTI shall not be liable for
any incidental or consequential damages arising out of the use or inability to
use the software.
******************************************************************************/
#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include "waitset_query_cond.h"
#include "waitset_query_condSupport.h"
#include "ndds/ndds_cpp.h"
#include "application.h"
using namespace application;
static int shutdown_participant(
DDSDomainParticipant *participant,
const char *shutdown_message,
int status);
int run_publisher_application(unsigned int domain_id, unsigned int sample_count)
{
DDS_Duration_t send_period = { 0, 500000000 };
/* Auxiliary variables */
char *odd_string = DDS_String_dup("ODD");
char *even_string = DDS_String_dup("EVEN");
// Start communicating in a domain, usually one participant per application
DDSDomainParticipant *participant =
DDSTheParticipantFactory->create_participant(
domain_id,
DDS_PARTICIPANT_QOS_DEFAULT,
NULL /* listener */,
DDS_STATUS_MASK_NONE);
if (participant == NULL) {
return shutdown_participant(
participant,
"create_participant error",
EXIT_FAILURE);
}
// A Publisher allows an application to create one or more DataWriters
DDSPublisher *publisher = participant->create_publisher(
DDS_PUBLISHER_QOS_DEFAULT,
NULL /* listener */,
DDS_STATUS_MASK_NONE);
if (publisher == NULL) {
return shutdown_participant(
participant,
"create_publisher error",
EXIT_FAILURE);
}
// Register the datatype to use when creating the Topic
const char *type_name = waitset_query_condTypeSupport::get_type_name();
DDS_ReturnCode_t retcode = waitset_query_condTypeSupport::register_type(
participant,
type_name);
if (retcode != DDS_RETCODE_OK) {
return shutdown_participant(
participant,
"register_type error",
EXIT_FAILURE);
}
// Create a Topic with a name and a datatype
DDSTopic *topic = participant->create_topic(
"Example waitset_query_cond",
type_name,
DDS_TOPIC_QOS_DEFAULT,
NULL /* listener */,
DDS_STATUS_MASK_NONE);
if (topic == NULL) {
return shutdown_participant(
participant,
"create_topic error",
EXIT_FAILURE);
}
// This DataWriter writes data on "Example waitset_query_cond" Topic
DDSDataWriter *untyped_writer = publisher->create_datawriter(
topic,
DDS_DATAWRITER_QOS_DEFAULT,
NULL /* listener */,
DDS_STATUS_MASK_NONE);
if (untyped_writer == NULL) {
return shutdown_participant(
participant,
"create_datawriter error",
EXIT_FAILURE);
}
waitset_query_condDataWriter *typed_writer =
waitset_query_condDataWriter::narrow(untyped_writer);
if (typed_writer == NULL) {
return shutdown_participant(
participant,
"DataWriter narrow error",
EXIT_FAILURE);
}
// Create data for writing, allocating all members
waitset_query_cond *data = waitset_query_condTypeSupport::create_data();
if (data == NULL) {
return shutdown_participant(
participant,
"waitset_query_condTypeSupport::create_data error",
EXIT_FAILURE);
}
DDS_InstanceHandle_t instance_handle = DDS_HANDLE_NIL;
/* For a data type that has a key, if the same instance is going to be
written multiple times, initialize the key here
and register the keyed instance prior to writing */
/*
instance_handle = typed_writer->register_instance(*data);
*/
// Main loop, write data
for (unsigned int samples_written = 0;
!shutdown_requested && samples_written < sample_count;
++samples_written) {
std::cout << "Writing waitset_query_cond, count " << samples_written
<< std::endl;
/* Modify the data to be sent here */
if (samples_written % 2 == 1) {
data->name = odd_string;
} else {
data->name = even_string;
}
data->x = samples_written;
retcode = typed_writer->write(*data, instance_handle);
if (retcode != DDS_RETCODE_OK) {
std::cerr << "write error " << retcode << std::endl;
}
NDDSUtility::sleep(send_period);
}
/*
retcode = typed_writer->unregister_instance(
*data, instance_handle);
if (retcode != DDS_RETCODE_OK) {
std::cerr << "unregister instance error " << retcode << std::endl;
}
*/
// Delete previously allocated data, including all contained elements
retcode = waitset_query_condTypeSupport::delete_data(data);
if (retcode != DDS_RETCODE_OK) {
std::cerr << "waitset_query_condTypeSupport::delete_data error "
<< retcode << std::endl;
}
// Delete all entities (DataWriter, Topic, Publisher, DomainParticipant)
return shutdown_participant(participant, "Shutting down", EXIT_SUCCESS);
}
// Delete all entities
static int shutdown_participant(
DDSDomainParticipant *participant,
const char *shutdown_message,
int status)
{
DDS_ReturnCode_t retcode;
std::cout << shutdown_message << std::endl;
if (participant != NULL) {
// Cleanup everything created by this Participant
retcode = participant->delete_contained_entities();
if (retcode != DDS_RETCODE_OK) {
std::cerr << "delete_contained_entities error " << retcode
<< std::endl;
status = EXIT_FAILURE;
}
retcode = DDSTheParticipantFactory->delete_participant(participant);
if (retcode != DDS_RETCODE_OK) {
std::cerr << "delete_participant error " << retcode << std::endl;
status = EXIT_FAILURE;
}
}
return status;
}
int main(int argc, char *argv[])
{
// Parse arguments and handle control-C
ApplicationArguments arguments;
parse_arguments(arguments, argc, argv);
if (arguments.parse_result == PARSE_RETURN_EXIT) {
return EXIT_SUCCESS;
} else if (arguments.parse_result == PARSE_RETURN_FAILURE) {
return EXIT_FAILURE;
}
setup_signal_handlers();
// Sets Connext verbosity to help debugging
NDDSConfigLogger::get_instance()->set_verbosity(arguments.verbosity);
int status = run_publisher_application(
arguments.domain_id,
arguments.sample_count);
// Releases the memory used by the participant factory. Optional at
// application exit
DDS_ReturnCode_t retcode = DDSDomainParticipantFactory::finalize_instance();
if (retcode != DDS_RETCODE_OK) {
std::cerr << "finalize_instance error " << retcode << std::endl;
status = EXIT_FAILURE;
}
return status;
}
| cxx |
rticonnextdds-examples | data/projects/rticonnextdds-examples/connext_dds/waitset_query_cond/c/waitset_query_cond_publisher.c | /*******************************************************************************
(c) 2005-2014 Copyright, Real-Time Innovations, Inc. All rights reserved.
RTI grants Licensee a license to use, modify, compile, and create derivative
works of the Software. Licensee has the right to distribute object form only
for use with RTI products. The Software is provided "as is", with no warranty
of any type, including any warranty for fitness for any purpose. RTI is under
no obligation to maintain or support the Software. RTI shall not be liable for
any incidental or consequential damages arising out of the use or inability to
use the software.
******************************************************************************/
/* waitset_query_cond_publisher.c
A publication of data of type waitset_query_cond
This file is derived from code automatically generated by the rtiddsgen
command:
rtiddsgen -language C -example <arch> waitset_query_cond.idl
Example publication of type waitset_query_cond automatically generated by
'rtiddsgen'. To test them follow these steps:
(1) Compile this file and the example subscription.
(2) Start the subscription with the command
objs/<arch>/waitset_query_cond_subscriber <domain_id> <sample_count>
(3) Start the publication with the command
objs/<arch>/waitset_query_cond_publisher <domain_id> <sample_count>
(4) [Optional] Specify the list of discovery initial peers and
multicast receive addresses via an environment variable or a file
(in the current working directory) called NDDS_DISCOVERY_PEERS.
You can run any number of publishers and subscribers programs, and can
add and remove them dynamically from the domain.
Example:
To run the example application on domain <domain_id>:
On Unix:
objs/<arch>/waitset_query_cond_publisher <domain_id>
objs/<arch>/waitset_query_cond_subscriber <domain_id>
On Windows:
objs\<arch>\waitset_query_cond_publisher <domain_id>
objs\<arch>\waitset_query_cond_subscriber <domain_id>
modification history
------------ -------
*/
#include "ndds/ndds_c.h"
#include "waitset_query_cond.h"
#include "waitset_query_condSupport.h"
#include <stdio.h>
#include <stdlib.h>
/* Delete all entities */
static int publisher_shutdown(DDS_DomainParticipant *participant)
{
DDS_ReturnCode_t retcode;
int status = 0;
if (participant != NULL) {
retcode = DDS_DomainParticipant_delete_contained_entities(participant);
if (retcode != DDS_RETCODE_OK) {
printf("delete_contained_entities error %d\n", retcode);
status = -1;
}
retcode = DDS_DomainParticipantFactory_delete_participant(
DDS_TheParticipantFactory,
participant);
if (retcode != DDS_RETCODE_OK) {
printf("delete_participant error %d\n", retcode);
status = -1;
}
}
/* RTI Connext provides finalize_instance() method on
domain participant factory for people who want to release memory used
by the participant factory. Uncomment the following block of code for
clean destruction of the singleton. */
/*
retcode = DDS_DomainParticipantFactory_finalize_instance();
if (retcode != DDS_RETCODE_OK) {
printf("finalize_instance error %d\n", retcode);
status = -1;
}
*/
return status;
}
static int publisher_main(int domainId, int sample_count)
{
DDS_DomainParticipant *participant = NULL;
DDS_Publisher *publisher = NULL;
DDS_Topic *topic = NULL;
DDS_DataWriter *writer = NULL;
waitset_query_condDataWriter *waitset_query_cond_writer = NULL;
waitset_query_cond *instance = NULL;
DDS_ReturnCode_t retcode;
DDS_InstanceHandle_t instance_handle = DDS_HANDLE_NIL;
const char *type_name = NULL;
int count = 0;
struct DDS_Duration_t send_period = { 0, 500000000 };
/* Auxiliary variables */
char *odd_string = DDS_String_dup("ODD");
char *even_string = DDS_String_dup("EVEN");
/* To customize participant QoS, use
the configuration file USER_QOS_PROFILES.xml */
participant = DDS_DomainParticipantFactory_create_participant(
DDS_TheParticipantFactory,
domainId,
&DDS_PARTICIPANT_QOS_DEFAULT,
NULL /* listener */,
DDS_STATUS_MASK_NONE);
if (participant == NULL) {
printf("create_participant error\n");
publisher_shutdown(participant);
return -1;
}
/* To customize publisher QoS, use
the configuration file USER_QOS_PROFILES.xml */
publisher = DDS_DomainParticipant_create_publisher(
participant,
&DDS_PUBLISHER_QOS_DEFAULT,
NULL /* listener */,
DDS_STATUS_MASK_NONE);
if (publisher == NULL) {
printf("create_publisher error\n");
publisher_shutdown(participant);
return -1;
}
/* Register type before creating topic */
type_name = waitset_query_condTypeSupport_get_type_name();
retcode =
waitset_query_condTypeSupport_register_type(participant, type_name);
if (retcode != DDS_RETCODE_OK) {
printf("register_type error %d\n", retcode);
publisher_shutdown(participant);
return -1;
}
/* To customize topic QoS, use
the configuration file USER_QOS_PROFILES.xml */
topic = DDS_DomainParticipant_create_topic(
participant,
"Example waitset_query_cond",
type_name,
&DDS_TOPIC_QOS_DEFAULT,
NULL /* listener */,
DDS_STATUS_MASK_NONE);
if (topic == NULL) {
printf("create_topic error\n");
publisher_shutdown(participant);
return -1;
}
/* To customize data writer QoS, use
the configuration file USER_QOS_PROFILES.xml */
writer = DDS_Publisher_create_datawriter(
publisher,
topic,
&DDS_DATAWRITER_QOS_DEFAULT,
NULL /* listener */,
DDS_STATUS_MASK_NONE);
if (writer == NULL) {
printf("create_datawriter error\n");
publisher_shutdown(participant);
return -1;
}
waitset_query_cond_writer = waitset_query_condDataWriter_narrow(writer);
if (waitset_query_cond_writer == NULL) {
printf("DataWriter narrow error\n");
publisher_shutdown(participant);
return -1;
}
/* Create data sample for writing */
instance = waitset_query_condTypeSupport_create_data_ex(DDS_BOOLEAN_TRUE);
if (instance == NULL) {
printf("waitset_query_condTypeSupport_create_data error\n");
publisher_shutdown(participant);
return -1;
}
/* For a data type that has a key, if the same instance is going to be
written multiple times, initialize the key here
and register the keyed instance prior to writing */
/*
instance_handle = waitset_query_condDataWriter_register_instance(
waitset_query_cond_writer, instance);
*/
/* Main loop */
for (count = 0; (sample_count == 0) || (count < sample_count); ++count) {
printf("Writing waitset_query_cond, count %d\n", count);
/* Modify the data to be written here */
if (count % 2 == 1) {
instance->name = odd_string;
} else {
instance->name = even_string;
}
instance->x = count;
/* Write data */
retcode = waitset_query_condDataWriter_write(
waitset_query_cond_writer,
instance,
&instance_handle);
if (retcode != DDS_RETCODE_OK) {
printf("write error %d\n", retcode);
}
NDDS_Utility_sleep(&send_period);
}
/*
retcode = waitset_query_condDataWriter_unregister_instance(
waitset_query_cond_writer, instance, &instance_handle);
if (retcode != DDS_RETCODE_OK) {
printf("unregister instance error %d\n", retcode);
}
*/
/* Delete data sample */
retcode = waitset_query_condTypeSupport_delete_data_ex(
instance,
DDS_BOOLEAN_TRUE);
if (retcode != DDS_RETCODE_OK) {
printf("waitset_query_condTypeSupport_delete_data error %d\n", retcode);
}
/* Cleanup and delete delete all entities */
return publisher_shutdown(participant);
}
#if defined(RTI_WINCE)
int wmain(int argc, wchar_t **argv)
{
int domainId = 0;
int sample_count = 0; /* infinite loop */
if (argc >= 2) {
domainId = _wtoi(argv[1]);
}
if (argc >= 3) {
sample_count = _wtoi(argv[2]);
}
/* Uncomment this to turn on additional logging
NDDS_Config_Logger_set_verbosity_by_category(
NDDS_Config_Logger_get_instance(),
NDDS_CONFIG_LOG_CATEGORY_API,
NDDS_CONFIG_LOG_VERBOSITY_STATUS_ALL);
*/
return publisher_main(domainId, sample_count);
}
#elif !(defined(RTI_VXWORKS) && !defined(__RTP__)) && !defined(RTI_PSOS)
int main(int argc, char *argv[])
{
int domainId = 0;
int sample_count = 0; /* infinite loop */
if (argc >= 2) {
domainId = atoi(argv[1]);
}
if (argc >= 3) {
sample_count = atoi(argv[2]);
}
/* Uncomment this to turn on additional logging
NDDS_Config_Logger_set_verbosity_by_category(
NDDS_Config_Logger_get_instance(),
NDDS_CONFIG_LOG_CATEGORY_API,
NDDS_CONFIG_LOG_VERBOSITY_STATUS_ALL);
*/
return publisher_main(domainId, sample_count);
}
#endif
#ifdef RTI_VX653
const unsigned char *__ctype = NULL;
void usrAppInit()
{
#ifdef USER_APPL_INIT
USER_APPL_INIT; /* for backwards compatibility */
#endif
/* add application specific code here */
taskSpawn(
"pub",
RTI_OSAPI_THREAD_PRIORITY_NORMAL,
0x8,
0x150000,
(FUNCPTR) publisher_main,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0);
}
#endif
| c |
rticonnextdds-examples | data/projects/rticonnextdds-examples/connext_dds/waitset_query_cond/c/waitset_query_cond_subscriber.c | /*******************************************************************************
(c) 2005-2014 Copyright, Real-Time Innovations, Inc. All rights reserved.
RTI grants Licensee a license to use, modify, compile, and create derivative
works of the Software. Licensee has the right to distribute object form only
for use with RTI products. The Software is provided "as is", with no warranty
of any type, including any warranty for fitness for any purpose. RTI is under
no obligation to maintain or support the Software. RTI shall not be liable for
any incidental or consequential damages arising out of the use or inability to
use the software.
******************************************************************************/
/* waitset_query_cond_subscriber.c
A subscription example
This file is derived from code automatically generated by the rtiddsgen
command:
rtiddsgen -language C -example <arch> waitset_query_cond.idl
Example subscription of type waitset_query_cond automatically generated by
'rtiddsgen'. To test them, follow these steps:
(1) Compile this file and the example publication.
(2) Start the subscription with the command
objs/<arch>/waitset_query_cond_subscriber <domain_id> <sample_count>
(3) Start the publication with the command
objs/<arch>/waitset_query_cond_publisher <domain_id> <sample_count>
(4) [Optional] Specify the list of discovery initial peers and
multicast receive addresses via an environment variable or a file
(in the current working directory) called NDDS_DISCOVERY_PEERS.
You can run any number of publishers and subscribers programs, and can
add and remove them dynamically from the domain.
Example:
To run the example application on domain <domain_id>:
On UNIX systems:
objs/<arch>/waitset_query_cond_publisher <domain_id>
objs/<arch>/waitset_query_cond_subscriber <domain_id>
On Windows systems:
objs\<arch>\waitset_query_cond_publisher <domain_id>
objs\<arch>\waitset_query_cond_subscriber <domain_id>
modification history
------------ -------
*/
#include "ndds/ndds_c.h"
#include "waitset_query_cond.h"
#include "waitset_query_condSupport.h"
#include <stdio.h>
#include <stdlib.h>
/* We don't need to use listeners as we are going to use Waitsets and Conditions
* so we have removed the auto generated code for listeners here
*/
/* Delete all entities */
static int subscriber_shutdown(DDS_DomainParticipant *participant)
{
DDS_ReturnCode_t retcode;
int status = 0;
if (participant != NULL) {
retcode = DDS_DomainParticipant_delete_contained_entities(participant);
if (retcode != DDS_RETCODE_OK) {
printf("delete_contained_entities error %d\n", retcode);
status = -1;
}
retcode = DDS_DomainParticipantFactory_delete_participant(
DDS_TheParticipantFactory,
participant);
if (retcode != DDS_RETCODE_OK) {
printf("delete_participant error %d\n", retcode);
status = -1;
}
}
/* RTI Connext provides the finalize_instance() method on
domain participant factory for users who want to release memory used
by the participant factory. Uncomment the following block of code for
clean destruction of the singleton. */
/*
retcode = DDS_DomainParticipantFactory_finalize_instance();
if (retcode != DDS_RETCODE_OK) {
printf("finalize_instance error %d\n", retcode);
status = -1;
}
*/
return status;
}
static int subscriber_main(int domainId, int sample_count)
{
DDS_DomainParticipant *participant = NULL;
DDS_Subscriber *subscriber = NULL;
DDS_Topic *topic = NULL;
DDS_DataReader *reader = NULL;
DDS_ReturnCode_t retcode;
const char *type_name = NULL;
int count = 0;
struct DDS_Duration_t wait_timeout = { 1, 0 };
/* Additional variables for this example */
int i;
DDS_WaitSet *waitset = NULL;
DDS_QueryCondition *query_condition = NULL;
waitset_query_condDataReader *waitset_query_cond_reader = NULL;
const char *query_expression = DDS_String_dup("name MATCH %0");
struct DDS_StringSeq query_parameters;
struct DDS_ConditionSeq active_conditions_seq = DDS_SEQUENCE_INITIALIZER;
struct waitset_query_condSeq data_seq = DDS_SEQUENCE_INITIALIZER;
struct DDS_SampleInfoSeq info_seq = DDS_SEQUENCE_INITIALIZER;
/* Auxiliary variables */
char *odd_string = DDS_String_dup("'ODD'");
char *even_string = DDS_String_dup("'EVEN'");
/* The initial value of the param_list is EVEN string */
const char *param_list[] = { even_string };
/* To customize participant QoS, use
the configuration file USER_QOS_PROFILES.xml */
participant = DDS_DomainParticipantFactory_create_participant(
DDS_TheParticipantFactory,
domainId,
&DDS_PARTICIPANT_QOS_DEFAULT,
NULL /* listener */,
DDS_STATUS_MASK_NONE);
if (participant == NULL) {
printf("create_participant error\n");
subscriber_shutdown(participant);
return -1;
}
/* To customize subscriber QoS, use
the configuration file USER_QOS_PROFILES.xml */
subscriber = DDS_DomainParticipant_create_subscriber(
participant,
&DDS_SUBSCRIBER_QOS_DEFAULT,
NULL /* listener */,
DDS_STATUS_MASK_NONE);
if (subscriber == NULL) {
printf("create_subscriber error\n");
subscriber_shutdown(participant);
return -1;
}
/* Register the type before creating the topic */
type_name = waitset_query_condTypeSupport_get_type_name();
retcode =
waitset_query_condTypeSupport_register_type(participant, type_name);
if (retcode != DDS_RETCODE_OK) {
printf("register_type error %d\n", retcode);
subscriber_shutdown(participant);
return -1;
}
/* To customize topic QoS, use
the configuration file USER_QOS_PROFILES.xml */
topic = DDS_DomainParticipant_create_topic(
participant,
"Example waitset_query_cond",
type_name,
&DDS_TOPIC_QOS_DEFAULT,
NULL /* listener */,
DDS_STATUS_MASK_NONE);
if (topic == NULL) {
printf("create_topic error\n");
subscriber_shutdown(participant);
return -1;
}
/* To customize data reader QoS, use
the configuration file USER_QOS_PROFILES.xml */
reader = DDS_Subscriber_create_datareader(
subscriber,
DDS_Topic_as_topicdescription(topic),
&DDS_DATAREADER_QOS_DEFAULT,
NULL,
DDS_STATUS_MASK_NONE);
if (reader == NULL) {
printf("create_datareader error\n");
subscriber_shutdown(participant);
return -1;
}
/* Narrow the reader into your specific data type */
waitset_query_cond_reader = waitset_query_condDataReader_narrow(reader);
if (waitset_query_cond_reader == NULL) {
printf("DataReader narrow error\n");
return -1;
}
/* Create query condition */
DDS_StringSeq_initialize(&query_parameters);
DDS_StringSeq_set_maximum(&query_parameters, 1);
/*Here we set the default filter using the param_list */
DDS_StringSeq_from_array(&query_parameters, param_list, 1);
query_condition = DDS_DataReader_create_querycondition(
reader,
DDS_NOT_READ_SAMPLE_STATE,
DDS_ANY_VIEW_STATE,
DDS_ANY_INSTANCE_STATE,
query_expression,
&query_parameters);
if (query_condition == NULL) {
printf("create_query_condition error\n");
subscriber_shutdown(participant);
return -1;
}
waitset = DDS_WaitSet_new();
if (waitset == NULL) {
printf("create waitset error\n");
subscriber_shutdown(participant);
return -1;
}
/* Attach Query Conditions */
retcode = DDS_WaitSet_attach_condition(
waitset,
(DDS_Condition *) query_condition);
if (retcode != DDS_RETCODE_OK) {
printf("attach_condition error\n");
subscriber_shutdown(participant);
return -1;
}
printf("\n>>>Timeout: %.0d sec & %d nanosec\n",
wait_timeout.sec,
wait_timeout.nanosec);
printf(">>> Query conditions: name MATCH %%0\n");
printf("\t%%0 = %s\n", param_list[0]);
printf("---------------------------------\n\n");
/* Main loop */
for (count = 0; (sample_count == 0) || (count < sample_count); ++count) {
/* We set a new parameter in the Query Condition after 7 secs */
if (count == 7) {
param_list[0] = odd_string;
printf("CHANGING THE QUERY CONDITION\n");
printf("\n>>> Query conditions: name MATCH %%0\n");
printf("\t%%0 = %s\n", param_list[0]);
printf(">>> We keep one sample in the history\n");
printf("-------------------------------------\n\n");
DDS_StringSeq_from_array(&query_parameters, param_list, 1);
DDS_QueryCondition_set_query_parameters(
query_condition,
&query_parameters);
}
/* wait() blocks execution of the thread until one or more attached
* Conditions become true, or until a user-specified timeout expires.
*/
retcode = DDS_WaitSet_wait(
waitset, /* waitset */
&active_conditions_seq, /* active conditions sequence */
&wait_timeout); /* timeout */
/* We get to timeout if no conditions were triggered */
if (retcode == DDS_RETCODE_TIMEOUT) {
printf("Wait timed out!! No conditions were triggered.\n");
continue;
} else if (retcode != DDS_RETCODE_OK) {
printf("wait returned error: %d", retcode);
break;
}
retcode = DDS_RETCODE_OK;
while (retcode != DDS_RETCODE_NO_DATA) {
retcode = waitset_query_condDataReader_take_w_condition(
waitset_query_cond_reader,
&data_seq,
&info_seq,
DDS_LENGTH_UNLIMITED,
DDS_QueryCondition_as_readcondition(query_condition));
for (i = 0; i < waitset_query_condSeq_get_length(&data_seq); ++i) {
if (!DDS_SampleInfoSeq_get_reference(&info_seq, i)
->valid_data) {
printf("Got metadata\n");
continue;
}
waitset_query_condTypeSupport_print_data(
waitset_query_condSeq_get_reference(&data_seq, i));
}
waitset_query_condDataReader_return_loan(
waitset_query_cond_reader,
&data_seq,
&info_seq);
}
}
/* Cleanup and delete all entities */
return subscriber_shutdown(participant);
}
#if defined(RTI_WINCE)
int wmain(int argc, wchar_t **argv)
{
int domainId = 0;
int sample_count = 0; /* infinite loop */
if (argc >= 2) {
domainId = _wtoi(argv[1]);
}
if (argc >= 3) {
sample_count = _wtoi(argv[2]);
}
/* Uncomment this to turn on additional logging
NDDS_Config_Logger_set_verbosity_by_category(
NDDS_Config_Logger_get_instance(),
NDDS_CONFIG_LOG_CATEGORY_API,
NDDS_CONFIG_LOG_VERBOSITY_STATUS_ALL);
*/
return subscriber_main(domainId, sample_count);
}
#elif !(defined(RTI_VXWORKS) && !defined(__RTP__)) && !defined(RTI_PSOS)
int main(int argc, char *argv[])
{
int domainId = 0;
int sample_count = 0; /* infinite loop */
if (argc >= 2) {
domainId = atoi(argv[1]);
}
if (argc >= 3) {
sample_count = atoi(argv[2]);
}
/* Uncomment this to turn on additional logging
NDDS_Config_Logger_set_verbosity_by_category(
NDDS_Config_Logger_get_instance(),
NDDS_CONFIG_LOG_CATEGORY_API,
NDDS_CONFIG_LOG_VERBOSITY_STATUS_ALL);
*/
return subscriber_main(domainId, sample_count);
}
#endif
#ifdef RTI_VX653
const unsigned char *__ctype = NULL;
void usrAppInit()
{
#ifdef USER_APPL_INIT
USER_APPL_INIT; /* for backwards compatibility */
#endif
/* add application specific code here */
taskSpawn(
"sub",
RTI_OSAPI_THREAD_PRIORITY_NORMAL,
0x8,
0x150000,
(FUNCPTR) subscriber_main,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0);
}
#endif
| c |
rticonnextdds-examples | data/projects/rticonnextdds-examples/connext_dds/waitset_query_cond/c++11/application.hpp | /*
* (c) Copyright, Real-Time Innovations, 2020. All rights reserved.
* RTI grants Licensee a license to use, modify, compile, and create derivative
* works of the software solely for use with RTI Connext DDS. Licensee may
* redistribute copies of the software provided that all such copies are subject
* to this license. The software is provided "as is", with no warranty of any
* type, including any warranty for fitness for any purpose. RTI is under no
* obligation to maintain or support the software. RTI shall not be liable for
* any incidental or consequential damages arising out of the use or inability
* to use the software.
*/
#ifndef APPLICATION_HPP
#define APPLICATION_HPP
#include <iostream>
#include <csignal>
#include <dds/core/ddscore.hpp>
namespace application {
// Catch control-C and tell application to shut down
bool shutdown_requested = false;
inline void stop_handler(int)
{
shutdown_requested = true;
std::cout << "preparing to shut down..." << std::endl;
}
inline void setup_signal_handlers()
{
signal(SIGINT, stop_handler);
signal(SIGTERM, stop_handler);
}
enum class ParseReturn { ok, failure, exit };
struct ApplicationArguments {
ParseReturn parse_result;
unsigned int domain_id;
unsigned int sample_count;
rti::config::Verbosity verbosity;
ApplicationArguments(
ParseReturn parse_result_param,
unsigned int domain_id_param,
unsigned int sample_count_param,
rti::config::Verbosity verbosity_param)
: parse_result(parse_result_param),
domain_id(domain_id_param),
sample_count(sample_count_param),
verbosity(verbosity_param)
{
}
};
inline void set_verbosity(
rti::config::Verbosity &verbosity,
int verbosity_value)
{
switch (verbosity_value) {
case 0:
verbosity = rti::config::Verbosity::SILENT;
break;
case 1:
verbosity = rti::config::Verbosity::EXCEPTION;
break;
case 2:
verbosity = rti::config::Verbosity::WARNING;
break;
case 3:
verbosity = rti::config::Verbosity::STATUS_ALL;
break;
default:
verbosity = rti::config::Verbosity::EXCEPTION;
break;
}
}
// Parses application arguments for example.
inline ApplicationArguments parse_arguments(int argc, char *argv[])
{
int arg_processing = 1;
bool show_usage = false;
ParseReturn parse_result = ParseReturn::ok;
unsigned int domain_id = 0;
unsigned int sample_count = (std::numeric_limits<unsigned int>::max)();
rti::config::Verbosity verbosity(rti::config::Verbosity::EXCEPTION);
while (arg_processing < argc) {
if ((argc > arg_processing + 1)
&& (strcmp(argv[arg_processing], "-d") == 0
|| strcmp(argv[arg_processing], "--domain") == 0)) {
domain_id = atoi(argv[arg_processing + 1]);
arg_processing += 2;
} else if (
(argc > arg_processing + 1)
&& (strcmp(argv[arg_processing], "-s") == 0
|| strcmp(argv[arg_processing], "--sample-count") == 0)) {
sample_count = atoi(argv[arg_processing + 1]);
arg_processing += 2;
} else if (
(argc > arg_processing + 1)
&& (strcmp(argv[arg_processing], "-v") == 0
|| strcmp(argv[arg_processing], "--verbosity") == 0)) {
set_verbosity(verbosity, atoi(argv[arg_processing + 1]));
arg_processing += 2;
} else if (
strcmp(argv[arg_processing], "-h") == 0
|| strcmp(argv[arg_processing], "--help") == 0) {
std::cout << "Example application." << std::endl;
show_usage = true;
parse_result = ParseReturn::exit;
break;
} else {
std::cout << "Bad parameter." << std::endl;
show_usage = true;
parse_result = ParseReturn::failure;
break;
}
}
if (show_usage) {
std::cout << "Usage:\n"
" -d, --domain <int> Domain ID this "
"application will\n"
" subscribe in. \n"
" Default: 0\n"
" -s, --sample_count <int> Number of samples to "
"receive before\n"
" cleanly shutting down. \n"
" Default: infinite\n"
" -v, --verbosity <int> How much debugging output "
"to show.\n"
" Range: 0-3 \n"
" Default: 1"
<< std::endl;
}
return ApplicationArguments(
parse_result,
domain_id,
sample_count,
verbosity);
}
} // namespace application
#endif // APPLICATION_HPP | hpp |
rticonnextdds-examples | data/projects/rticonnextdds-examples/connext_dds/waitset_query_cond/c++11/waitset_query_cond_subscriber.cxx | /*******************************************************************************
(c) 2005-2015 Copyright, Real-Time Innovations, Inc. All rights reserved.
RTI grants Licensee a license to use, modify, compile, and create derivative
works of the Software. Licensee has the right to distribute object form only
for use with RTI products. The Software is provided "as is", with no warranty
of any type, including any warranty for fitness for any purpose. RTI is under
no obligation to maintain or support the Software. RTI shall not be liable for
any incidental or consequential damages arising out of the use or inability to
use the software.
******************************************************************************/
#include <dds/sub/ddssub.hpp>
#include <dds/core/ddscore.hpp>
#include <rti/config/Logger.hpp> // for logging
#include "waitset_query_cond.hpp"
#include "application.hpp" // for command line parsing and ctrl-c
void run_subscriber_application(
unsigned int domain_id,
unsigned int sample_count)
{
// Create a DomainParticipant.
dds::domain::DomainParticipant participant(domain_id);
// Create a Topic -- and automatically register the type.
dds::topic::Topic<waitset_query_cond> topic(
participant,
"Example waitset_query_cond");
// Retrieve the DataReader QoS, from USER_QOS_PROFILES.xml
dds::sub::qos::DataReaderQos reader_qos =
dds::core::QosProvider::Default().datareader_qos();
// If you want to change the DataReader's QoS programmatically rather
// than using the XML file, you will need to uncomment the following lines.
// reader_qos << History::KeepLast(1);
// Create a subscriber
dds::sub::Subscriber subscriber(participant);
// Create a DataReader.
dds::sub::DataReader<waitset_query_cond> reader(
subscriber,
topic,
reader_qos);
// Create the parameters of the condition.
// The initial value of the parameter is EVEN string to get even numbers.
std::vector<std::string> query_parameters = { "'EVEN'" };
int samples_read = 0;
// Create a query condition with a functor handler.
dds::sub::cond::QueryCondition query_condition(
dds::sub::Query(reader, "name MATCH %0", query_parameters),
dds::sub::status::DataState::any_data(),
[&reader, &samples_read](dds::core::cond::Condition condition) {
// We take only samples that triggered the QueryCondition
auto condition_as_qc = dds::core::polymorphic_cast<
dds::sub::cond::QueryCondition>(condition);
dds::sub::LoanedSamples<waitset_query_cond> samples =
reader.select().condition(condition_as_qc).take();
for (auto sample : samples) {
if (!sample.info().valid()) {
std::cout << "Got metadata" << std::endl;
} else {
std::cout << sample.data() << std::endl;
samples_read++;
}
}
});
// Create the waitset and attach the condition.
dds::core::cond::WaitSet waitset;
waitset += query_condition;
dds::core::Duration wait_timeout(1);
std::cout << std::endl
<< ">>> Timeout: " << wait_timeout.sec() << " sec" << std::endl
<< ">>> Query conditions: " << query_condition.expression()
<< std::endl
<< "\t %%0 = " << query_parameters[0] << std::endl
<< "----------------------------------" << std::endl
<< std::endl;
bool condition_changed = false;
while (!application::shutdown_requested && samples_read < sample_count) {
// We change the parameter in the Query Condition after 7 secs.
if (samples_read == 7 && !condition_changed) {
query_parameters[0] = "'ODD'";
query_condition.parameters(
query_parameters.begin(),
query_parameters.end());
std::cout << std::endl
<< "CHANGING THE QUERY CONDITION" << std::endl
<< ">>> Query conditions: "
<< query_condition.expression() << std::endl
<< "\t %%0 = " << query_parameters[0] << std::endl
<< ">>> We keep one sample in the history" << std::endl
<< "-------------------------------------" << std::endl
<< std::endl;
condition_changed = true;
}
// 'dispatch()' blocks execution of the thread until one or more
// attached Conditions become true, or until a user-specified timeout
// expires and then dispatches the events.
// Another way would be to use 'wait()' and check if the QueryCondition
// has been triggered as the "waitsets" example does.
waitset.dispatch(wait_timeout);
}
}
int main(int argc, char *argv[])
{
using namespace application;
// Parse arguments and handle control-C
auto arguments = parse_arguments(argc, argv);
if (arguments.parse_result == ParseReturn::exit) {
return EXIT_SUCCESS;
} else if (arguments.parse_result == ParseReturn::failure) {
return EXIT_FAILURE;
}
setup_signal_handlers();
// Sets Connext verbosity to help debugging
rti::config::Logger::instance().verbosity(arguments.verbosity);
try {
run_subscriber_application(arguments.domain_id, arguments.sample_count);
} catch (const std::exception &ex) {
// This will catch DDS exceptions
std::cerr << "Exception in run_subscriber_application(): " << ex.what()
<< std::endl;
return EXIT_FAILURE;
}
// Releases the memory used by the participant factory. Optional at
// application exit
dds::domain::DomainParticipant::finalize_participant_factory();
return EXIT_SUCCESS;
}
| cxx |
rticonnextdds-examples | data/projects/rticonnextdds-examples/connext_dds/waitset_query_cond/c++11/waitset_query_cond_publisher.cxx | /*******************************************************************************
(c) 2005-2015 Copyright, Real-Time Innovations, Inc. All rights reserved.
RTI grants Licensee a license to use, modify, compile, and create derivative
works of the Software. Licensee has the right to distribute object form only
for use with RTI products. The Software is provided "as is", with no warranty
of any type, including any warranty for fitness for any purpose. RTI is under
no obligation to maintain or support the Software. RTI shall not be liable for
any incidental or consequential damages arising out of the use or inability to
use the software.
******************************************************************************/
#include <dds/pub/ddspub.hpp>
#include <rti/util/util.hpp> // for sleep()
#include <rti/config/Logger.hpp> // for logging
#include "application.hpp" // for command line parsing and ctrl-c
#include "waitset_query_cond.hpp"
void run_publisher_application(
unsigned int domain_id,
unsigned int sample_count)
{
// Create a DomainParticipant.
dds::domain::DomainParticipant participant(domain_id);
// Create a Topic -- and automatically register the type.
dds::topic::Topic<waitset_query_cond> topic(
participant,
"Example waitset_query_cond");
// Create a Subscriber
dds::pub::Publisher publisher(participant);
// Create a DataWriter.
dds::pub::DataWriter<waitset_query_cond> writer(publisher, topic);
// Create a data sample for writing.
waitset_query_cond instance;
// Main loop
for (unsigned int samples_written = 0;
!application::shutdown_requested && samples_written < sample_count;
samples_written++) {
std::cout << "Writing waitset_query_cond, count " << samples_written
<< std::endl;
// Set x value
instance.x(samples_written);
// Set name field
if (samples_written % 2 == 1) {
instance.name("ODD");
} else {
instance.name("EVEN");
}
writer.write(instance);
rti::util::sleep(dds::core::Duration(1));
}
}
int main(int argc, char *argv[])
{
using namespace application;
// Parse arguments and handle control-C
auto arguments = parse_arguments(argc, argv);
if (arguments.parse_result == ParseReturn::exit) {
return EXIT_SUCCESS;
} else if (arguments.parse_result == ParseReturn::failure) {
return EXIT_FAILURE;
}
setup_signal_handlers();
// Sets Connext verbosity to help debugging
rti::config::Logger::instance().verbosity(arguments.verbosity);
try {
run_publisher_application(arguments.domain_id, arguments.sample_count);
} catch (const std::exception &ex) {
// This will catch DDS exceptions
std::cerr << "Exception in run_publisher_application(): " << ex.what()
<< std::endl;
return EXIT_FAILURE;
}
// Releases the memory used by the participant factory. Optional at
// application exit
dds::domain::DomainParticipant::finalize_participant_factory();
return EXIT_SUCCESS;
}
| cxx |
rticonnextdds-examples | data/projects/rticonnextdds-examples/connext_dds/get_publishers/c++/Foo_publisher.cxx | /*******************************************************************************
(c) 2005-2014 Copyright, Real-Time Innovations, Inc. All rights reserved.
RTI grants Licensee a license to use, modify, compile, and create derivative
works of the Software. Licensee has the right to distribute object form only
for use with RTI products. The Software is provided "as is", with no warranty
of any type, including any warranty for fitness for any purpose. RTI is under
no obligation to maintain or support the Software. RTI shall not be liable for
any incidental or consequential damages arising out of the use or inability to
use the software.
******************************************************************************/
/* Foo_publisher.cxx
A publication of data of type Foo
This file is derived from code automatically generated by the rtiddsgen
command:
rtiddsgen -language C++ -example <arch> Foo.idl
This example shows how to create some publishers and how to access all
the publishers the participant has.
Example:
To run the example application on domain <domain_id>:
On Unix:
objs/<arch>/Foo_publisher <domain_id>
On Windows:
objs\<arch>\Foo_publisher <domain_id>
modification history
------------ -------
*/
#include <stdio.h>
#include <stdlib.h>
#ifdef RTI_VX653
#include <vThreadsData.h>
#endif
#include "Foo.h"
#include "FooSupport.h"
#include "ndds/ndds_cpp.h"
/* Delete all entities */
static int publisher_shutdown(DDSDomainParticipant *participant)
{
DDS_ReturnCode_t retcode;
int status = 0;
if (participant != NULL) {
retcode = participant->delete_contained_entities();
if (retcode != DDS_RETCODE_OK) {
printf("delete_contained_entities error %d\n", retcode);
status = -1;
}
retcode = DDSTheParticipantFactory->delete_participant(participant);
if (retcode != DDS_RETCODE_OK) {
printf("delete_participant error %d\n", retcode);
status = -1;
}
}
/* RTI Connext provides finalize_instance() method on
* domain participant factory for people who want to release memory used
* by the participant factory. Uncomment the following block of code for
* clean destruction of the singleton.
*/
/*
retcode = DDSDomainParticipantFactory::finalize_instance();
if (retcode != DDS_RETCODE_OK) {
printf("finalize_instance error %d\n", retcode);
status = -1;
}
*/
return status;
}
extern "C" int publisher_main(int domainId, int sample_count)
{
DDSDomainParticipant *participant = NULL;
DDSPublisher *publisher = NULL, *publisher2 = NULL;
int count = 0;
DDSPublisherSeq publisherSeq;
DDS_ReturnCode_t retcode;
/* To customize participant QoS, use
* the configuration file USER_QOS_PROFILES.xml */
participant = DDSTheParticipantFactory->create_participant(
domainId,
DDS_PARTICIPANT_QOS_DEFAULT,
NULL /* listener */,
DDS_STATUS_MASK_NONE);
if (participant == NULL) {
printf("create_participant error\n");
publisher_shutdown(participant);
return -1;
}
/* Start - modifying the generated example to showcase the usage of
* the get_publishers API
*/
/* To customize publisher QoS, use
* the configuration file USER_QOS_PROFILES.xml */
publisher = participant->create_publisher(
DDS_PUBLISHER_QOS_DEFAULT,
NULL /* listener */,
DDS_STATUS_MASK_NONE);
if (publisher == NULL) {
printf("create_publisher error\n");
publisher_shutdown(participant);
return -1;
}
printf("The first publisher is %p\n", publisher);
publisher2 = participant->create_publisher(
DDS_PUBLISHER_QOS_DEFAULT,
NULL /* listener */,
DDS_STATUS_MASK_NONE);
if (publisher2 == NULL) {
printf("create_publisher2 error\n");
publisher_shutdown(participant);
return -1;
}
printf("The second publisher is %p\n", publisher2);
printf("Let's call get_publisher() now and check if I get all my "
"publishers...\n");
retcode = participant->get_publishers(publisherSeq);
if (retcode != DDS_RETCODE_OK) {
printf("get_publishers error\n");
publisher_shutdown(participant);
return -1;
/* Start modifying the generated example to showcase the usage of
* the get_publishers
*/
}
printf("I found %d publisher on this participant!\n",
publisherSeq.length());
for (size_t count = 0; count < publisherSeq.length(); count++) {
DDSPublisher *tmp = publisherSeq[count];
printf("The %d publisher I found is: %p\n", count, tmp);
}
/* exiting */
return publisher_shutdown(participant);
/* End - modifying the generated example to showcase the usage of
* the get_publishers API
*/
}
#if defined(RTI_WINCE)
int wmain(int argc, wchar_t **argv)
{
int domainId = 0;
int sample_count = 0; /* infinite loop */
if (argc >= 2) {
domainId = _wtoi(argv[1]);
}
if (argc >= 3) {
sample_count = _wtoi(argv[2]);
}
/* Uncomment this to turn on additional logging
NDDSConfigLogger::get_instance()->
set_verbosity_by_category(NDDS_CONFIG_LOG_CATEGORY_API,
NDDS_CONFIG_LOG_VERBOSITY_STATUS_ALL);
*/
return publisher_main(domainId, sample_count);
}
#elif !(defined(RTI_VXWORKS) && !defined(__RTP__)) && !defined(RTI_PSOS)
int main(int argc, char *argv[])
{
int domainId = 0;
int sample_count = 0; /* infinite loop */
if (argc >= 2) {
domainId = atoi(argv[1]);
}
if (argc >= 3) {
sample_count = atoi(argv[2]);
}
/* Uncomment this to turn on additional logging
NDDSConfigLogger::get_instance()->
set_verbosity_by_category(NDDS_CONFIG_LOG_CATEGORY_API,
NDDS_CONFIG_LOG_VERBOSITY_STATUS_ALL);
*/
return publisher_main(domainId, sample_count);
}
#endif
#ifdef RTI_VX653
const unsigned char *__ctype = *(__ctypePtrGet());
extern "C" void usrAppInit()
{
#ifdef USER_APPL_INIT
USER_APPL_INIT; /* for backwards compatibility */
#endif
/* add application specific code here */
taskSpawn(
"pub",
RTI_OSAPI_THREAD_PRIORITY_NORMAL,
0x8,
0x150000,
(FUNCPTR) publisher_main,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0);
}
#endif
| cxx |
rticonnextdds-examples | data/projects/rticonnextdds-examples/connext_dds/get_publishers/c++98/Foo_publisher.cxx | /*******************************************************************************
(c) 2005-2014 Copyright, Real-Time Innovations, Inc. All rights reserved.
RTI grants Licensee a license to use, modify, compile, and create derivative
works of the Software. Licensee has the right to distribute object form only
for use with RTI products. The Software is provided "as is", with no warranty
of any type, including any warranty for fitness for any purpose. RTI is under
no obligation to maintain or support the Software. RTI shall not be liable for
any incidental or consequential damages arising out of the use or inability to
use the software.
******************************************************************************/
#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include "Foo.h"
#include "FooSupport.h"
#include "ndds/ndds_cpp.h"
#include "application.h"
using namespace application;
static int shutdown_participant(
DDSDomainParticipant *participant,
const char *shutdown_message,
int status);
int run_publisher_application(unsigned int domain_id)
{
DDSPublisherSeq publisherSeq;
DDS_ReturnCode_t retcode;
// Start communicating in a domain, usually one participant per application
DDSDomainParticipant *participant =
DDSTheParticipantFactory->create_participant(
domain_id,
DDS_PARTICIPANT_QOS_DEFAULT,
NULL /* listener */,
DDS_STATUS_MASK_NONE);
if (participant == NULL) {
return shutdown_participant(
participant,
"create_participant error",
EXIT_FAILURE);
}
/* Start - modifying the generated example to showcase the usage of
* the get_publishers API
*/
// A Publisher allows an application to create one or more DataWriters
DDSPublisher *publisher = participant->create_publisher(
DDS_PUBLISHER_QOS_DEFAULT,
NULL /* listener */,
DDS_STATUS_MASK_NONE);
if (publisher == NULL) {
return shutdown_participant(
participant,
"create_publisher error",
EXIT_FAILURE);
}
std::cout << "The first publisher is " << publisher << std::endl;
DDSPublisher *publisher2 = participant->create_publisher(
DDS_PUBLISHER_QOS_DEFAULT,
NULL /* listener */,
DDS_STATUS_MASK_NONE);
if (publisher2 == NULL) {
return shutdown_participant(
participant,
"create_publisher error",
EXIT_FAILURE);
}
std::cout << "The second publisher is " << publisher2 << std::endl;
std::cout << "Let's call get_publisher() now and check if I get all my "
"publishers...\n";
retcode = participant->get_publishers(publisherSeq);
if (retcode != DDS_RETCODE_OK) {
return shutdown_participant(
participant,
"get_publishers error",
EXIT_FAILURE);
/* Start modifying the generated example to showcase the usage of
* the get_publishers
*/
}
std::cout << "I found " << publisherSeq.length()
<< " publishers on this participant!\n";
for (int i = 0; i < publisherSeq.length(); i++) {
DDSPublisher *tmp = publisherSeq[i];
std::cout << "The " << i << " publisher I found is: " << tmp
<< std::endl;
}
// Delete all entities (DataWriter, Topic, Publisher, DomainParticipant)
return shutdown_participant(participant, "Shutting down", EXIT_SUCCESS);
/* End - modifying the generated example to showcase the usage of
* the get_publishers API
*/
}
// Delete all entities
static int shutdown_participant(
DDSDomainParticipant *participant,
const char *shutdown_message,
int status)
{
DDS_ReturnCode_t retcode;
std::cout << shutdown_message << std::endl;
if (participant != NULL) {
// Cleanup everything created by this Participant
retcode = participant->delete_contained_entities();
if (retcode != DDS_RETCODE_OK) {
std::cerr << "delete_contained_entities error " << retcode
<< std::endl;
status = EXIT_FAILURE;
}
retcode = DDSTheParticipantFactory->delete_participant(participant);
if (retcode != DDS_RETCODE_OK) {
std::cerr << "delete_participant error " << retcode << std::endl;
status = EXIT_FAILURE;
}
}
return status;
}
int main(int argc, char *argv[])
{
// Parse arguments and handle control-C
ApplicationArguments arguments;
parse_arguments(arguments, argc, argv);
if (arguments.parse_result == PARSE_RETURN_EXIT) {
return EXIT_SUCCESS;
} else if (arguments.parse_result == PARSE_RETURN_FAILURE) {
return EXIT_FAILURE;
}
setup_signal_handlers();
// Sets Connext verbosity to help debugging
NDDSConfigLogger::get_instance()->set_verbosity(arguments.verbosity);
int status = run_publisher_application(arguments.domain_id);
// Releases the memory used by the participant factory. Optional at
// application exit
DDS_ReturnCode_t retcode = DDSDomainParticipantFactory::finalize_instance();
if (retcode != DDS_RETCODE_OK) {
std::cerr << "finalize_instance error " << retcode << std::endl;
status = EXIT_FAILURE;
}
return status;
}
| cxx |
rticonnextdds-examples | data/projects/rticonnextdds-examples/connext_dds/get_publishers/c++98/application.h | /*
* (c) Copyright, Real-Time Innovations, 2020. All rights reserved.
* RTI grants Licensee a license to use, modify, compile, and create derivative
* works of the software solely for use with RTI Connext DDS. Licensee may
* redistribute copies of the software provided that all such copies are subject
* to this license. The software is provided "as is", with no warranty of any
* type, including any warranty for fitness for any purpose. RTI is under no
* obligation to maintain or support the software. RTI shall not be liable for
* any incidental or consequential damages arising out of the use or inability
* to use the software.
*/
#ifndef APPLICATION_H
#define APPLICATION_H
#include <iostream>
#include <csignal>
#include <climits>
namespace application {
// Catch control-C and tell application to shut down
bool shutdown_requested = false;
inline void stop_handler(int)
{
shutdown_requested = true;
std::cout << "preparing to shut down..." << std::endl;
}
inline void setup_signal_handlers()
{
signal(SIGINT, stop_handler);
signal(SIGTERM, stop_handler);
}
enum ParseReturn { PARSE_RETURN_OK, PARSE_RETURN_FAILURE, PARSE_RETURN_EXIT };
struct ApplicationArguments {
ParseReturn parse_result;
unsigned int domain_id;
NDDS_Config_LogVerbosity verbosity;
};
inline void set_verbosity(ApplicationArguments &arguments, int verbosity)
{
switch (verbosity) {
case 0:
arguments.verbosity = NDDS_CONFIG_LOG_VERBOSITY_SILENT;
break;
case 1:
arguments.verbosity = NDDS_CONFIG_LOG_VERBOSITY_ERROR;
break;
case 2:
arguments.verbosity = NDDS_CONFIG_LOG_VERBOSITY_WARNING;
break;
case 3:
arguments.verbosity = NDDS_CONFIG_LOG_VERBOSITY_STATUS_ALL;
break;
default:
arguments.verbosity = NDDS_CONFIG_LOG_VERBOSITY_ERROR;
break;
}
}
// Parses application arguments for example. Returns whether to exit.
inline void parse_arguments(
ApplicationArguments &arguments,
int argc,
char *argv[])
{
int arg_processing = 1;
bool show_usage = false;
arguments.domain_id = 0;
arguments.verbosity = NDDS_CONFIG_LOG_VERBOSITY_ERROR;
arguments.parse_result = PARSE_RETURN_OK;
while (arg_processing < argc) {
if ((argc > arg_processing + 1)
&& (strcmp(argv[arg_processing], "-d") == 0
|| strcmp(argv[arg_processing], "--domain") == 0)) {
arguments.domain_id = atoi(argv[arg_processing + 1]);
arg_processing += 2;
} else if (
(argc > arg_processing + 1)
&& (strcmp(argv[arg_processing], "-v") == 0
|| strcmp(argv[arg_processing], "--verbosity") == 0)) {
set_verbosity(arguments, atoi(argv[arg_processing + 1]));
arg_processing += 2;
} else if (
strcmp(argv[arg_processing], "-h") == 0
|| strcmp(argv[arg_processing], "--help") == 0) {
std::cout << "Example application." << std::endl;
show_usage = true;
arguments.parse_result = PARSE_RETURN_EXIT;
break;
} else {
std::cout << "Bad parameter." << std::endl;
show_usage = true;
arguments.parse_result = PARSE_RETURN_FAILURE;
break;
}
}
if (show_usage) {
std::cout << "Usage:\n"
" -d, --domain <int> Domain ID this "
"application will\n"
" subscribe in. \n"
" Default: 0\n"
" -v, --verbosity <int> How much debugging output "
"to show.\n"
" Range: 0-3 \n"
" Default: 1"
<< std::endl;
}
}
} // namespace application
#endif // APPLICATION_H
| h |
rticonnextdds-examples | data/projects/rticonnextdds-examples/connext_dds/get_publishers/c/Foo_publisher.c | /*******************************************************************************
(c) 2005-2014 Copyright, Real-Time Innovations, Inc. All rights reserved.
RTI grants Licensee a license to use, modify, compile, and create derivative
works of the Software. Licensee has the right to distribute object form only
for use with RTI products. The Software is provided "as is", with no warranty
of any type, including any warranty for fitness for any purpose. RTI is under
no obligation to maintain or support the Software. RTI shall not be liable for
any incidental or consequential damages arising out of the use or inability to
use the software.
******************************************************************************/
/* Foo_publisher.c
A publication of data of type Foo
This file is derived from code automatically generated by the rtiddsgen
command:
rtiddsgen -language C -example <arch> Foo.idl
This example shows how to create some publshers and how to access all
the publishers the participant has.
Example:
To run the example application on domain <domain_id>:
On Unix:
objs/<arch>/Foo_publisher <domain_id>
On Windows:
objs\<arch>\Foo_publisher <domain_id>
modification history
------------ -------
*/
#include "Foo.h"
#include "FooSupport.h"
#include "ndds/ndds_c.h"
#include <stdio.h>
#include <stdlib.h>
/* Delete all entities */
static int publisher_shutdown(
DDS_DomainParticipant *participant,
struct DDS_PublisherSeq publisherSeq)
{
DDS_ReturnCode_t retcode;
int status = 0;
if (participant != NULL) {
retcode = DDS_DomainParticipant_delete_contained_entities(participant);
if (retcode != DDS_RETCODE_OK) {
printf("delete_contained_entities error %d\n", retcode);
status = -1;
}
retcode = DDS_DomainParticipantFactory_delete_participant(
DDS_TheParticipantFactory,
participant);
if (retcode != DDS_RETCODE_OK) {
printf("delete_participant error %d\n", retcode);
status = -1;
}
if (DDS_PublisherSeq_finalize(&publisherSeq)) {
printf("finalize publisherSeq error\n");
status = -1;
}
}
/* RTI Connext provides finalize_instance() method on
* domain participant factory for people who want to release memory used
* by the participant factory. Uncomment the following block of code for
* clean destruction of the singleton. */
/*
retcode = DDS_DomainParticipantFactory_finalize_instance();
if (retcode != DDS_RETCODE_OK) {
printf("finalize_instance error %d\n", retcode);
status = -1;
}
*/
return status;
}
static int publisher_main(int domainId, int sample_count)
{
DDS_DomainParticipant *participant = NULL;
DDS_Publisher *publisher = NULL, *publisher2 = NULL;
/* We will use this temporal publisher to print all created publishers */
DDS_Publisher *tmp = NULL;
struct DDS_PublisherSeq publisherSeq = DDS_SEQUENCE_INITIALIZER;
Foo *instance = NULL;
DDS_ReturnCode_t retcode;
const char *type_name = NULL;
int count = 0;
/* To customize participant QoS, use
* the configuration file USER_QOS_PROFILES.xml */
participant = DDS_DomainParticipantFactory_create_participant(
DDS_TheParticipantFactory,
domainId,
&DDS_PARTICIPANT_QOS_DEFAULT,
NULL /* listener */,
DDS_STATUS_MASK_NONE);
if (participant == NULL) {
printf("create_participant error\n");
publisher_shutdown(participant, publisherSeq);
return -1;
}
/* Start - modifying the generated example to showcase the usage of the
* get_publishers API
*/
/* To customize publisher QoS, use
the configuration file USER_QOS_PROFILES.xml */
publisher = DDS_DomainParticipant_create_publisher(
participant,
&DDS_PUBLISHER_QOS_DEFAULT,
NULL /* listener */,
DDS_STATUS_MASK_NONE);
if (publisher == NULL) {
printf("create_publisher error\n");
publisher_shutdown(participant, publisherSeq);
return -1;
}
printf("The first publisher is %p\n", publisher);
publisher2 = DDS_DomainParticipant_create_publisher(
participant,
&DDS_PUBLISHER_QOS_DEFAULT,
NULL /* listener */,
DDS_STATUS_MASK_NONE);
if (publisher2 == NULL) {
printf("create_publisher2 error\n");
publisher_shutdown(participant, publisherSeq);
return -1;
}
printf("The second publisher is %p\n", publisher2);
printf("Let's call get_publisher() now and check if I get all my ");
printf("publisher...\n");
retcode = DDS_DomainParticipant_get_publishers(participant, &publisherSeq);
if (retcode != DDS_RETCODE_OK) {
printf("get_publishers error\n");
publisher_shutdown(participant, publisherSeq);
return -1;
}
/* We print the publishers obtained */
for (count = 0; count < DDS_PublisherSeq_get_length(&publisherSeq);
++count) {
tmp = DDS_PublisherSeq_get(&publisherSeq, count);
printf("The %d publisher I foud is: %p\n", count, tmp);
}
/* Cleanup and delete delete all entities */
return publisher_shutdown(participant, publisherSeq);
/* End - modifying the generated example to showcase the usage of the
* get_publishers API
*/
}
#if defined(RTI_WINCE)
int wmain(int argc, wchar_t **argv)
{
int domainId = 0;
int sample_count = 0; /* infinite loop */
if (argc >= 2) {
domainId = _wtoi(argv[1]);
}
if (argc >= 3) {
sample_count = _wtoi(argv[2]);
}
/* Uncomment this to turn on additional logging
NDDS_Config_Logger_set_verbosity_by_category(
NDDS_Config_Logger_get_instance(),
NDDS_CONFIG_LOG_CATEGORY_API,
NDDS_CONFIG_LOG_VERBOSITY_STATUS_ALL);
*/
return publisher_main(domainId, sample_count);
}
#elif !(defined(RTI_VXWORKS) && !defined(__RTP__)) && !defined(RTI_PSOS)
int main(int argc, char *argv[])
{
int domainId = 0;
int sample_count = 0; /* infinite loop */
if (argc >= 2) {
domainId = atoi(argv[1]);
}
if (argc >= 3) {
sample_count = atoi(argv[2]);
}
/* Uncomment this to turn on additional logging
NDDS_Config_Logger_set_verbosity_by_category(
NDDS_Config_Logger_get_instance(),
NDDS_CONFIG_LOG_CATEGORY_API,
NDDS_CONFIG_LOG_VERBOSITY_STATUS_ALL);
*/
return publisher_main(domainId, sample_count);
}
#endif
#ifdef RTI_VX653
const unsigned char *__ctype = NULL;
void usrAppInit()
{
#ifdef USER_APPL_INIT
USER_APPL_INIT; /* for backwards compatibility */
#endif
/* add application specific code here */
taskSpawn(
"pub",
RTI_OSAPI_THREAD_PRIORITY_NORMAL,
0x8,
0x150000,
(FUNCPTR) publisher_main,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0);
}
#endif
| c |
rticonnextdds-examples | data/projects/rticonnextdds-examples/connext_dds/get_publishers/c++03/Foo_publisher.cxx | /*******************************************************************************
(c) 2005-2015 Copyright, Real-Time Innovations, Inc. All rights reserved.
RTI grants Licensee a license to use, modify, compile, and create derivative
works of the Software. Licensee has the right to distribute object form only
for use with RTI products. The Software is provided "as is", with no warranty
of any type, including any warranty for fitness for any purpose. RTI is under
no obligation to maintain or support the Software. RTI shall not be liable for
any incidental or consequential damages arising out of the use or inability to
use the software.
******************************************************************************/
#include <cstdlib>
#include <iostream>
#include "Foo.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;
using namespace rti::core::policy;
void publisher_main(int domain_id)
{
// Create a DomainParticipant with default QoS.
DomainParticipant participant(domain_id);
// Retrieve publisher QoS to set names.
PublisherQos publisher_qos = QosProvider::Default().publisher_qos();
// Create the first publisher.
publisher_qos << EntityName("Foo");
Publisher publisher1(participant, publisher_qos);
std::cout << "The first publisher name is "
<< publisher1.qos().policy<EntityName>().name().get()
<< std::endl;
// Create the second publisher.
publisher_qos << EntityName("Bar");
Publisher publisher2(participant, publisher_qos);
std::cout << "The second publisher name is "
<< publisher2.qos().policy<EntityName>().name().get()
<< std::endl;
// Find the publishers.
std::cout << std::endl
<< "Calling to find_publishers()..." << std::endl
<< std::endl;
std::vector<Publisher> publishers;
rti::pub::find_publishers(participant, std::back_inserter(publishers));
// Iterate over the publishers and print the name.
std::cout << "Found " << publishers.size()
<< " publishers on this participant" << std::endl;
for (std::vector<int>::size_type i = 0; i < publishers.size(); i++) {
std::cout << "The " << i << " publisher name is "
<< publishers[i].qos().policy<EntityName>().name().get()
<< std::endl;
}
}
int main(int argc, char *argv[])
{
int domain_id = 0;
if (argc >= 2) {
domain_id = atoi(argv[1]);
}
// To turn on additional logging, include <rti/config/Logger.hpp> and
// uncomment the following line:
// rti::config::Logger::instance().verbosity(rti::config::Verbosity::STATUS_ALL);
try {
publisher_main(domain_id);
} catch (std::exception ex) {
std::cout << "Exception caught: " << ex.what() << std::endl;
return -1;
}
return 0;
}
| cxx |
rticonnextdds-examples | data/projects/rticonnextdds-examples/connext_dds/get_publishers/c++11/Foo_publisher.cxx | /*******************************************************************************
(c) 2005-2015 Copyright, Real-Time Innovations, Inc. All rights reserved.
RTI grants Licensee a license to use, modify, compile, and create derivative
works of the Software. Licensee has the right to distribute object form only
for use with RTI products. The Software is provided "as is", with no warranty
of any type, including any warranty for fitness for any purpose. RTI is under
no obligation to maintain or support the Software. RTI shall not be liable for
any incidental or consequential damages arising out of the use or inability to
use the software.
******************************************************************************/
#include <dds/pub/ddspub.hpp>
#include <rti/util/util.hpp> // for sleep()
#include <rti/config/Logger.hpp> // for logging
#include "application.hpp" // for command line parsing and ctrl-c
#include "Foo.hpp"
void run_publisher_application(unsigned int domain_id)
{
using namespace rti::core::policy;
// Create a DomainParticipant with default QoS.
dds::domain::DomainParticipant participant(domain_id);
// Retrieve publisher QoS to set names.
dds::pub::qos::PublisherQos publisher_qos =
dds::core::QosProvider::Default().publisher_qos();
// Create the first publisher.
publisher_qos << EntityName("Foo");
dds::pub::Publisher publisher1(participant, publisher_qos);
std::cout << "The first publisher name is "
<< publisher1.qos().policy<EntityName>().name().get()
<< std::endl;
// Create the second publisher.
publisher_qos << EntityName("Bar");
dds::pub::Publisher publisher2(participant, publisher_qos);
std::cout << "The second publisher name is "
<< publisher2.qos().policy<EntityName>().name().get()
<< std::endl;
// Find the publishers.
std::cout << std::endl
<< "Calling to find_publishers()..." << std::endl
<< std::endl;
std::vector<dds::pub::Publisher> publishers;
rti::pub::find_publishers(participant, std::back_inserter(publishers));
// Iterate over the publishers and print the name.
std::cout << "Found " << publishers.size()
<< " publishers on this participant" << std::endl;
for (std::vector<int>::size_type i = 0; i < publishers.size(); i++) {
std::cout << "The " << i << " publisher name is "
<< publishers[i].qos().policy<EntityName>().name().get()
<< std::endl;
}
}
int main(int argc, char *argv[])
{
using namespace application;
// Parse arguments and handle control-C
auto arguments = parse_arguments(argc, argv);
if (arguments.parse_result == ParseReturn::exit) {
return EXIT_SUCCESS;
} else if (arguments.parse_result == ParseReturn::failure) {
return EXIT_FAILURE;
}
setup_signal_handlers();
// Sets Connext verbosity to help debugging
rti::config::Logger::instance().verbosity(arguments.verbosity);
try {
run_publisher_application(arguments.domain_id);
} catch (const std::exception &ex) {
// This will catch DDS exceptions
std::cerr << "Exception in run_publisher_application(): " << ex.what()
<< std::endl;
return EXIT_FAILURE;
}
// Releases the memory used by the participant factory. Optional at
// application exit
dds::domain::DomainParticipant::finalize_participant_factory();
return EXIT_SUCCESS;
}
| cxx |
rticonnextdds-examples | data/projects/rticonnextdds-examples/connext_dds/get_publishers/c++11/application.hpp | /*
* (c) Copyright, Real-Time Innovations, 2020. All rights reserved.
* RTI grants Licensee a license to use, modify, compile, and create derivative
* works of the software solely for use with RTI Connext DDS. Licensee may
* redistribute copies of the software provided that all such copies are subject
* to this license. The software is provided "as is", with no warranty of any
* type, including any warranty for fitness for any purpose. RTI is under no
* obligation to maintain or support the software. RTI shall not be liable for
* any incidental or consequential damages arising out of the use or inability
* to use the software.
*/
#ifndef APPLICATION_HPP
#define APPLICATION_HPP
#include <iostream>
#include <csignal>
#include <dds/core/ddscore.hpp>
namespace application {
// Catch control-C and tell application to shut down
bool shutdown_requested = false;
inline void stop_handler(int)
{
shutdown_requested = true;
std::cout << "preparing to shut down..." << std::endl;
}
inline void setup_signal_handlers()
{
signal(SIGINT, stop_handler);
signal(SIGTERM, stop_handler);
}
enum class ParseReturn {
ok,
failure,
exit
};
struct ApplicationArguments {
ParseReturn parse_result;
unsigned int domain_id;
rti::config::Verbosity verbosity;
ApplicationArguments(
ParseReturn parse_result_param,
unsigned int domain_id_param,
rti::config::Verbosity verbosity_param)
: parse_result(parse_result_param),
domain_id(domain_id_param),
verbosity(verbosity_param) {}
};
inline void set_verbosity(
rti::config::Verbosity& verbosity,
int verbosity_value)
{
switch (verbosity_value) {
case 0:
verbosity = rti::config::Verbosity::SILENT;
break;
case 1:
verbosity = rti::config::Verbosity::EXCEPTION;
break;
case 2:
verbosity = rti::config::Verbosity::WARNING;
break;
case 3:
verbosity = rti::config::Verbosity::STATUS_ALL;
break;
default:
verbosity = rti::config::Verbosity::EXCEPTION;
break;
}
}
// Parses application arguments for example.
inline ApplicationArguments parse_arguments(int argc, char *argv[])
{
int arg_processing = 1;
bool show_usage = false;
ParseReturn parse_result = ParseReturn::ok;
unsigned int domain_id = 0;
unsigned int sample_count = (std::numeric_limits<unsigned int>::max)();
rti::config::Verbosity verbosity(rti::config::Verbosity::EXCEPTION);
while (arg_processing < argc) {
if ((argc > arg_processing + 1)
&& (strcmp(argv[arg_processing], "-d") == 0
|| strcmp(argv[arg_processing], "--domain") == 0)) {
domain_id = atoi(argv[arg_processing + 1]);
arg_processing += 2;
} else if ((argc > arg_processing + 1)
&& (strcmp(argv[arg_processing], "-v") == 0
|| strcmp(argv[arg_processing], "--verbosity") == 0)) {
set_verbosity(verbosity, atoi(argv[arg_processing + 1]));
arg_processing += 2;
} else if (strcmp(argv[arg_processing], "-h") == 0
|| strcmp(argv[arg_processing], "--help") == 0) {
std::cout << "Example application." << std::endl;
show_usage = true;
parse_result = ParseReturn::exit;
break;
} else {
std::cout << "Bad parameter." << std::endl;
show_usage = true;
parse_result = ParseReturn::failure;
break;
}
}
if (show_usage) {
std::cout << "Usage:\n"\
" -d, --domain <int> Domain ID this application will\n" \
" subscribe in. \n"
" Default: 0\n"\
" -v, --verbosity <int> How much debugging output to show.\n"\
" Range: 0-3 \n"
" Default: 1"
<< std::endl;
}
return ApplicationArguments(parse_result, domain_id, verbosity);
}
} // namespace application
#endif // APPLICATION_HPP | hpp |
rticonnextdds-examples | data/projects/rticonnextdds-examples/connext_dds/partitions/c++/partitions_publisher.cxx | /*******************************************************************************
(c) 2005-2014 Copyright, Real-Time Innovations, Inc. All rights reserved.
RTI grants Licensee a license to use, modify, compile, and create derivative
works of the Software. Licensee has the right to distribute object form only
for use with RTI products. The Software is provided "as is", with no warranty
of any type, including any warranty for fitness for any purpose. RTI is under
no obligation to maintain or support the Software. RTI shall not be liable for
any incidental or consequential damages arising out of the use or inability to
use the software.
******************************************************************************/
/* partitions_publisher.cxx
A publication of data of type partitions
This file is derived from code automatically generated by the rtiddsgen
command:
rtiddsgen -language C++ -example <arch> partitions.idl
Example publication of type partitions automatically generated by
'rtiddsgen'. To test them follow these steps:
(1) Compile this file and the example subscription.
(2) Start the subscription with the command
objs/<arch>/partitions_subscriber <domain_id> <sample_count>
(3) Start the publication with the command
objs/<arch>/partitions_publisher <domain_id> <sample_count>
(4) [Optional] Specify the list of discovery initial peers and
multicast receive addresses via an environment variable or a file
(in the current working directory) called NDDS_DISCOVERY_PEERS.
You can run any number of publishers and subscribers programs, and can
add and remove them dynamically from the domain.
Example:
To run the example application on domain <domain_id>:
On Unix:
objs/<arch>/partitions_publisher <domain_id> o
objs/<arch>/partitions_subscriber <domain_id>
On Windows:
objs\<arch>\partitions_publisher <domain_id>
objs\<arch>\partitions_subscriber <domain_id>
modification history
------------ -------
*/
#include <stdio.h>
#include <stdlib.h>
#ifdef RTI_VX653
#include <vThreadsData.h>
#endif
#include "ndds/ndds_cpp.h"
#include "partitions.h"
#include "partitionsSupport.h"
/* Delete all entities */
static int publisher_shutdown(DDSDomainParticipant *participant)
{
DDS_ReturnCode_t retcode;
int status = 0;
if (participant != NULL) {
retcode = participant->delete_contained_entities();
if (retcode != DDS_RETCODE_OK) {
printf("delete_contained_entities error %d\n", retcode);
status = -1;
}
retcode = DDSTheParticipantFactory->delete_participant(participant);
if (retcode != DDS_RETCODE_OK) {
printf("delete_participant error %d\n", retcode);
status = -1;
}
}
/* RTI Connext provides finalize_instance() method on
domain participant factory for people who want to release memory used
by the participant factory. Uncomment the following block of code for
clean destruction of the singleton. */
/*
retcode = DDSDomainParticipantFactory::finalize_instance();
if (retcode != DDS_RETCODE_OK) {
printf("finalize_instance error %d\n", retcode);
status = -1;
}
*/
return status;
}
extern "C" int publisher_main(int domainId, int sample_count)
{
DDSDomainParticipant *participant = NULL;
DDSPublisher *publisher = NULL;
DDSTopic *topic = NULL;
DDSDataWriter *writer = NULL;
partitionsDataWriter *partitions_writer = NULL;
partitions *instance = NULL;
DDS_ReturnCode_t retcode;
DDS_InstanceHandle_t instance_handle = DDS_HANDLE_NIL;
const char *type_name = NULL;
int count = 0;
DDS_Duration_t send_period = { 1, 0 };
/* To customize participant QoS, use
the configuration file USER_QOS_PROFILES.xml */
participant = DDSTheParticipantFactory->create_participant(
domainId,
DDS_PARTICIPANT_QOS_DEFAULT,
NULL /* listener */,
DDS_STATUS_MASK_NONE);
if (participant == NULL) {
printf("create_participant error\n");
publisher_shutdown(participant);
return -1;
}
DDS_PublisherQos publisher_qos;
retcode = participant->get_default_publisher_qos(publisher_qos);
if (retcode != DDS_RETCODE_OK) {
printf("get_default_publisher_qos error\n");
return -1;
}
/* If you want to change the Partition name programmatically rather than
* using the XML, you will need to add the following lines to your code
* and comment out the create_publisher() call bellow.
*/
publisher_qos.partition.name.ensure_length(2, 2);
publisher_qos.partition.name[0] = DDS_String_dup("ABC");
publisher_qos.partition.name[1] = DDS_String_dup("foo");
printf("Setting partition to '%s', '%s'...\n",
publisher_qos.partition.name[0],
publisher_qos.partition.name[1]);
publisher = participant->create_publisher(
publisher_qos,
NULL,
DDS_STATUS_MASK_NONE);
if (publisher == NULL) {
printf("create_participant error\n");
publisher_shutdown(participant);
return -1;
}
/*
publisher = participant->create_publisher(DDS_PUBLISHER_QOS_DEFAULT,
NULL,
DDS_STATUS_MASK_NONE);
if (publisher == NULL) {
printf("create_publisher error\n");
publisher_shutdown(participant);
return -1;
}
*/
/* Register type before creating topic */
type_name = partitionsTypeSupport::get_type_name();
retcode = partitionsTypeSupport::register_type(participant, type_name);
if (retcode != DDS_RETCODE_OK) {
printf("register_type error %d\n", retcode);
publisher_shutdown(participant);
return -1;
}
/* To customize topic QoS, use
the configuration file USER_QOS_PROFILES.xml */
topic = participant->create_topic(
"Example partitions",
type_name,
DDS_TOPIC_QOS_DEFAULT,
NULL /* listener */,
DDS_STATUS_MASK_NONE);
if (topic == NULL) {
printf("create_topic error\n");
publisher_shutdown(participant);
return -1;
}
/* In this example we set a Reliable datawriter, with Transient Local
* durability. By default we set up these QoS settings via XML. If you
* want to to it programmatically, use the following code, and comment out
* the create_datawriter call bellow.
*/
/*
DDS_DataWriterQos datawriter_qos;
retcode = publisher->get_default_datawriter_qos(datawriter_qos);
if (retcode != DDS_RETCODE_OK) {
printf("get_default_datawriter_qos error\n");
return -1;
}
datawriter_qos.reliability.kind = DDS_RELIABLE_RELIABILITY_QOS;
datawriter_qos.durability.kind = DDS_TRANSIENT_LOCAL_DURABILITY_QOS;
datawriter_qos.history.kind = DDS_KEEP_LAST_HISTORY_QOS;
datawriter_qos.history.depth = 3;
writer = publisher->create_datawriter(topic,
datawriter_qos,
NULL,
DDS_STATUS_MASK_NONE);
if (writer == NULL) {
printf("create_datawriter error\n");
publisher_shutdown(participant);
return -1;
}
*/
writer = publisher->create_datawriter(
topic,
DDS_DATAWRITER_QOS_DEFAULT,
NULL,
DDS_STATUS_MASK_NONE);
if (writer == NULL) {
printf("create_datawriter error\n");
publisher_shutdown(participant);
return -1;
}
partitions_writer = partitionsDataWriter::narrow(writer);
if (partitions_writer == NULL) {
printf("DataWriter narrow error\n");
publisher_shutdown(participant);
return -1;
}
/* Create data sample for writing */
instance = partitionsTypeSupport::create_data();
if (instance == NULL) {
printf("partitionsTypeSupport::create_data error\n");
publisher_shutdown(participant);
return -1;
}
/* For a data type that has a key, if the same instance is going to be
written multiple times, initialize the key here
and register the keyed instance prior to writing */
/*
instance_handle = partitions_writer->register_instance(*instance);
*/
/* Main loop */
for (count = 0; (sample_count == 0) || (count < sample_count); ++count) {
printf("Writing partitions, count %d\n", count);
instance->x = count;
retcode = partitions_writer->write(*instance, instance_handle);
if (retcode != DDS_RETCODE_OK) {
printf("write error %d\n", retcode);
}
/* Every 5 samples we will change the Partition name. These are the
* partition expressions we are going to try:
* "bar", "A*", "A?C", "X*Z", "zzz", "A*C"
*/
if ((count + 1) % 25 == 0) {
// Matches "ABC" -- name[1] here can match name[0] there,
// as long as there is some overlapping name
publisher_qos.partition.name[0] = DDS_String_dup("zzz");
publisher_qos.partition.name[1] = DDS_String_dup("A*C");
printf("Setting partition to '%s', '%s'...\n",
publisher_qos.partition.name[0],
publisher_qos.partition.name[1]);
publisher->set_qos(publisher_qos);
} else if ((count + 1) % 20 == 0) {
// Strings that are regular expressions aren't tested for
// literal matches, so this won't match "X*Z"
publisher_qos.partition.name[0] = DDS_String_dup("X*Z");
printf("Setting partition to '%s', '%s'...\n",
publisher_qos.partition.name[0],
publisher_qos.partition.name[1]);
publisher->set_qos(publisher_qos);
} else if ((count + 1) % 15 == 0) {
// Matches "ABC"
publisher_qos.partition.name[0] = DDS_String_dup("A?C");
printf("Setting partition to '%s', '%s'...\n",
publisher_qos.partition.name[0],
publisher_qos.partition.name[1]);
publisher->set_qos(publisher_qos);
} else if ((count + 1) % 10 == 0) {
// Matches "ABC"
publisher_qos.partition.name[0] = DDS_String_dup("A*");
printf("Setting partition to '%s', '%s'...\n",
publisher_qos.partition.name[0],
publisher_qos.partition.name[1]);
publisher->set_qos(publisher_qos);
} else if ((count + 1) % 5 == 0) {
// No literal match for "bar"
publisher_qos.partition.name[0] = DDS_String_dup("bar");
printf("Setting partition to '%s', '%s'...\n",
publisher_qos.partition.name[0],
publisher_qos.partition.name[1]);
publisher->set_qos(publisher_qos);
}
NDDSUtility::sleep(send_period);
}
/*
retcode = partitions_writer->unregister_instance(
*instance, instance_handle);
if (retcode != DDS_RETCODE_OK) {
printf("unregister instance error %d\n", retcode);
}
*/
/* Delete data sample */
retcode = partitionsTypeSupport::delete_data(instance);
if (retcode != DDS_RETCODE_OK) {
printf("partitionsTypeSupport::delete_data error %d\n", retcode);
}
/* Delete all entities */
return publisher_shutdown(participant);
}
#if defined(RTI_WINCE)
int wmain(int argc, wchar_t **argv)
{
int domainId = 0;
int sample_count = 0; /* infinite loop */
if (argc >= 2) {
domainId = _wtoi(argv[1]);
}
if (argc >= 3) {
sample_count = _wtoi(argv[2]);
}
/* Uncomment this to turn on additional logging
NDDSConfigLogger::get_instance()->
set_verbosity_by_category(NDDS_CONFIG_LOG_CATEGORY_API,
NDDS_CONFIG_LOG_VERBOSITY_STATUS_ALL);
*/
return publisher_main(domainId, sample_count);
}
#elif !(defined(RTI_VXWORKS) && !defined(__RTP__)) && !defined(RTI_PSOS)
int main(int argc, char *argv[])
{
int domainId = 0;
int sample_count = 0; /* infinite loop */
if (argc >= 2) {
domainId = atoi(argv[1]);
}
if (argc >= 3) {
sample_count = atoi(argv[2]);
}
/* Uncomment this to turn on additional logging
NDDSConfigLogger::get_instance()->
set_verbosity_by_category(NDDS_CONFIG_LOG_CATEGORY_API,
NDDS_CONFIG_LOG_VERBOSITY_STATUS_ALL);
*/
return publisher_main(domainId, sample_count);
}
#endif
#ifdef RTI_VX653
const unsigned char *__ctype = *(__ctypePtrGet());
extern "C" void usrAppInit()
{
#ifdef USER_APPL_INIT
USER_APPL_INIT; /* for backwards compatibility */
#endif
/* add application specific code here */
taskSpawn(
"pub",
RTI_OSAPI_THREAD_PRIORITY_NORMAL,
0x8,
0x150000,
(FUNCPTR) publisher_main,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0);
}
#endif
| cxx |
rticonnextdds-examples | data/projects/rticonnextdds-examples/connext_dds/partitions/c++/partitions_subscriber.cxx | /*******************************************************************************
(c) 2005-2014 Copyright, Real-Time Innovations, Inc. All rights reserved.
RTI grants Licensee a license to use, modify, compile, and create derivative
works of the Software. Licensee has the right to distribute object form only
for use with RTI products. The Software is provided "as is", with no warranty
of any type, including any warranty for fitness for any purpose. RTI is under
no obligation to maintain or support the Software. RTI shall not be liable for
any incidental or consequential damages arising out of the use or inability to
use the software.
******************************************************************************/
/* partitions_subscriber.cxx
A subscription example
This file is derived from code automatically generated by the rtiddsgen
command:
rtiddsgen -language C++ -example <arch> partitions.idl
Example subscription of type partitions automatically generated by
'rtiddsgen'. To test them follow these steps:
(1) Compile this file and the example publication.
(2) Start the subscription with the command
objs/<arch>/partitions_subscriber <domain_id> <sample_count>
(3) Start the publication with the command
objs/<arch>/partitions_publisher <domain_id> <sample_count>
(4) [Optional] Specify the list of discovery initial peers and
multicast receive addresses via an environment variable or a file
(in the current working directory) called NDDS_DISCOVERY_PEERS.
You can run any number of publishers and subscribers programs, and can
add and remove them dynamically from the domain.
Example:
To run the example application on domain <domain_id>:
On Unix:
objs/<arch>/partitions_publisher <domain_id>
objs/<arch>/partitions_subscriber <domain_id>
On Windows:
objs\<arch>\partitions_publisher <domain_id>
objs\<arch>\partitions_subscriber <domain_id>
modification history
------------ -------
*/
#include <stdio.h>
#include <stdlib.h>
#ifdef RTI_VX653
#include <vThreadsData.h>
#endif
#include "ndds/ndds_cpp.h"
#include "partitions.h"
#include "partitionsSupport.h"
class partitionsListener : public DDSDataReaderListener {
public:
virtual void on_requested_deadline_missed(
DDSDataReader * /*reader*/,
const DDS_RequestedDeadlineMissedStatus & /*status*/)
{
}
virtual void on_requested_incompatible_qos(
DDSDataReader * /*reader*/,
const DDS_RequestedIncompatibleQosStatus & /*status*/)
{
}
virtual void on_sample_rejected(
DDSDataReader * /*reader*/,
const DDS_SampleRejectedStatus & /*status*/)
{
}
virtual void on_liveliness_changed(
DDSDataReader * /*reader*/,
const DDS_LivelinessChangedStatus & /*status*/)
{
}
virtual void on_sample_lost(
DDSDataReader * /*reader*/,
const DDS_SampleLostStatus & /*status*/)
{
}
virtual void on_subscription_matched(
DDSDataReader * /*reader*/,
const DDS_SubscriptionMatchedStatus & /*status*/)
{
}
virtual void on_data_available(DDSDataReader *reader);
};
void partitionsListener::on_data_available(DDSDataReader *reader)
{
partitionsDataReader *partitions_reader = NULL;
partitionsSeq data_seq;
DDS_SampleInfoSeq info_seq;
DDS_ReturnCode_t retcode;
int i;
partitions_reader = partitionsDataReader::narrow(reader);
if (partitions_reader == NULL) {
printf("DataReader narrow error\n");
return;
}
retcode = partitions_reader->take(
data_seq,
info_seq,
DDS_LENGTH_UNLIMITED,
DDS_ANY_SAMPLE_STATE,
DDS_ANY_VIEW_STATE,
DDS_ANY_INSTANCE_STATE);
if (retcode == DDS_RETCODE_NO_DATA) {
return;
} else if (retcode != DDS_RETCODE_OK) {
printf("take error %d\n", retcode);
return;
}
for (i = 0; i < data_seq.length(); ++i) {
if (info_seq[i].valid_data) {
if (info_seq[i].view_state == DDS_NEW_VIEW_STATE) {
printf("Found new instance\n");
}
partitionsTypeSupport::print_data(&data_seq[i]);
}
}
retcode = partitions_reader->return_loan(data_seq, info_seq);
if (retcode != DDS_RETCODE_OK) {
printf("return loan error %d\n", retcode);
}
}
/* Delete all entities */
static int subscriber_shutdown(DDSDomainParticipant *participant)
{
DDS_ReturnCode_t retcode;
int status = 0;
if (participant != NULL) {
retcode = participant->delete_contained_entities();
if (retcode != DDS_RETCODE_OK) {
printf("delete_contained_entities error %d\n", retcode);
status = -1;
}
retcode = DDSTheParticipantFactory->delete_participant(participant);
if (retcode != DDS_RETCODE_OK) {
printf("delete_participant error %d\n", retcode);
status = -1;
}
}
/* RTI Connext provides the finalize_instance() method on
domain participant factory for people who want to release memory used
by the participant factory. Uncomment the following block of code for
clean destruction of the singleton. */
/*
retcode = DDSDomainParticipantFactory::finalize_instance();
if (retcode != DDS_RETCODE_OK) {
printf("finalize_instance error %d\n", retcode);
status = -1;
}
*/
return status;
}
extern "C" int subscriber_main(int domainId, int sample_count)
{
DDSDomainParticipant *participant = NULL;
DDSSubscriber *subscriber = NULL;
DDSTopic *topic = NULL;
partitionsListener *reader_listener = NULL;
DDSDataReader *reader = NULL;
DDS_ReturnCode_t retcode;
const char *type_name = NULL;
int count = 0;
DDS_Duration_t receive_period = { 4, 0 };
int status = 0;
/* To customize the participant QoS, use
the configuration file USER_QOS_PROFILES.xml */
participant = DDSTheParticipantFactory->create_participant(
domainId,
DDS_PARTICIPANT_QOS_DEFAULT,
NULL /* listener */,
DDS_STATUS_MASK_NONE);
if (participant == NULL) {
printf("create_participant error\n");
subscriber_shutdown(participant);
return -1;
}
DDS_SubscriberQos subscriber_qos;
retcode = participant->get_default_subscriber_qos(subscriber_qos);
if (retcode != DDS_RETCODE_OK) {
printf("get_default_subscriber_qos error\n");
return -1;
}
/* If you want to change the Partition name programmatically rather than
* using the XML, you will need to add the following lines to your code
* and comment out the create_subscriber() call bellow.
*/
/*
subscriber_qos.partition.name.ensure_length(2, 2);
subscriber_qos.partition.name[0] = DDS_String_dup("ABC");
subscriber_qos.partition.name[1] = DDS_String_dup("X*Z");
subscriber = participant->create_subscriber(subscriber_qos,
NULL,
DDS_STATUS_MASK_NONE);
if (subscriber == NULL) {
printf("create_subscriber error\n");
subscriber_shutdown(participant);
return -1;
}
*/
subscriber = participant->create_subscriber(
DDS_SUBSCRIBER_QOS_DEFAULT,
NULL,
DDS_STATUS_MASK_NONE);
if (subscriber == NULL) {
printf("create_subscriber error\n");
subscriber_shutdown(participant);
return -1;
}
printf("Setting partition to '%s', '%s'...\n",
subscriber_qos.partition.name[0],
subscriber_qos.partition.name[1]);
/* Register the type before creating the topic */
type_name = partitionsTypeSupport::get_type_name();
retcode = partitionsTypeSupport::register_type(participant, type_name);
if (retcode != DDS_RETCODE_OK) {
printf("register_type error %d\n", retcode);
subscriber_shutdown(participant);
return -1;
}
/* To customize the topic QoS, use
the configuration file USER_QOS_PROFILES.xml */
topic = participant->create_topic(
"Example partitions",
type_name,
DDS_TOPIC_QOS_DEFAULT,
NULL /* listener */,
DDS_STATUS_MASK_NONE);
if (topic == NULL) {
printf("create_topic error\n");
subscriber_shutdown(participant);
return -1;
}
/* Create a data reader listener */
reader_listener = new partitionsListener();
/* If you want to change the Datareader QoS programmatically rather than
* using the XML, you will need to add the following lines to your code
* and comment out the create_datareader() call bellow.
*/
/*
DDS_DataReaderQos datareader_qos;
retcode = subscriber->get_default_datareader_qos(datareader_qos);
if (retcode != DDS_RETCODE_OK) {
printf("get_default_datareader_qos error\n");
return -1;
}
datareader_qos.reliability.kind = DDS_RELIABLE_RELIABILITY_QOS;
datareader_qos.durability.kind = DDS_TRANSIENT_LOCAL_DURABILITY_QOS;
datareader_qos.history.kind = DDS_KEEP_ALL_HISTORY_QOS;
reader = subscriber->create_datareader(topic, datareader_qos,
reader_listener, DDS_STATUS_MASK_ALL); if (reader == NULL) {
printf("create_datareader error\n");
subscriber_shutdown(participant);
delete reader_listener;
return -1;
}
*/
reader = subscriber->create_datareader(
topic,
DDS_DATAREADER_QOS_DEFAULT,
reader_listener,
DDS_STATUS_MASK_ALL);
if (reader == NULL) {
printf("create_datareader error\n");
subscriber_shutdown(participant);
delete reader_listener;
return -1;
}
/* Main loop */
for (count = 0; (sample_count == 0) || (count < sample_count); ++count) {
NDDSUtility::sleep(receive_period);
}
/* Delete all entities */
status = subscriber_shutdown(participant);
delete reader_listener;
return status;
}
#if defined(RTI_WINCE)
int wmain(int argc, wchar_t **argv)
{
int domainId = 0;
int sample_count = 0; /* infinite loop */
if (argc >= 2) {
domainId = _wtoi(argv[1]);
}
if (argc >= 3) {
sample_count = _wtoi(argv[2]);
}
/* Uncomment this to turn on additional logging
NDDSConfigLogger::get_instance()->
set_verbosity_by_category(NDDS_CONFIG_LOG_CATEGORY_API,
NDDS_CONFIG_LOG_VERBOSITY_STATUS_ALL);
*/
return subscriber_main(domainId, sample_count);
}
#elif !(defined(RTI_VXWORKS) && !defined(__RTP__)) && !defined(RTI_PSOS)
int main(int argc, char *argv[])
{
int domainId = 0;
int sample_count = 0; /* infinite loop */
if (argc >= 2) {
domainId = atoi(argv[1]);
}
if (argc >= 3) {
sample_count = atoi(argv[2]);
}
/* Uncomment this to turn on additional logging
NDDSConfigLogger::get_instance()->
set_verbosity_by_category(NDDS_CONFIG_LOG_CATEGORY_API,
NDDS_CONFIG_LOG_VERBOSITY_STATUS_ALL);
*/
return subscriber_main(domainId, sample_count);
}
#endif
#ifdef RTI_VX653
const unsigned char *__ctype = *(__ctypePtrGet());
extern "C" void usrAppInit()
{
#ifdef USER_APPL_INIT
USER_APPL_INIT; /* for backwards compatibility */
#endif
/* add application specific code here */
taskSpawn(
"sub",
RTI_OSAPI_THREAD_PRIORITY_NORMAL,
0x8,
0x150000,
(FUNCPTR) subscriber_main,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0);
}
#endif
| cxx |
rticonnextdds-examples | data/projects/rticonnextdds-examples/connext_dds/partitions/c++98/partitions_publisher.cxx | /*******************************************************************************
(c) 2005-2014 Copyright, Real-Time Innovations, Inc. All rights reserved.
RTI grants Licensee a license to use, modify, compile, and create derivative
works of the Software. Licensee has the right to distribute object form only
for use with RTI products. The Software is provided "as is", with no warranty
of any type, including any warranty for fitness for any purpose. RTI is under
no obligation to maintain or support the Software. RTI shall not be liable for
any incidental or consequential damages arising out of the use or inability to
use the software.
******************************************************************************/
#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include "partitions.h"
#include "partitionsSupport.h"
#include "ndds/ndds_cpp.h"
#include "application.h"
using namespace application;
static int shutdown_participant(
DDSDomainParticipant *participant,
const char *shutdown_message,
int status);
int run_publisher_application(unsigned int domain_id, unsigned int sample_count)
{
DDS_Duration_t send_period = { 1, 0 };
// Start communicating in a domain, usually one participant per application
DDSDomainParticipant *participant =
DDSTheParticipantFactory->create_participant(
domain_id,
DDS_PARTICIPANT_QOS_DEFAULT,
NULL /* listener */,
DDS_STATUS_MASK_NONE);
if (participant == NULL) {
return shutdown_participant(
participant,
"create_participant error",
EXIT_FAILURE);
}
DDS_PublisherQos publisher_qos;
DDS_ReturnCode_t retcode =
participant->get_default_publisher_qos(publisher_qos);
if (retcode != DDS_RETCODE_OK) {
return shutdown_participant(
participant,
"get_default_publisher_qos error",
EXIT_FAILURE);
}
/* If you want to change the Partition name programmatically rather than
* using the XML, you will need to add the following lines to your code
* and comment out the create_publisher() call bellow.
*/
publisher_qos.partition.name.ensure_length(2, 2);
publisher_qos.partition.name[0] = DDS_String_dup("ABC");
publisher_qos.partition.name[1] = DDS_String_dup("foo");
std::cout << "Setting partition to '" << publisher_qos.partition.name[0]
<< "', '" << publisher_qos.partition.name[1] << "'...\n";
// A Publisher allows an application to create one or more DataWriters
DDSPublisher *publisher = participant->create_publisher(
publisher_qos,
NULL,
DDS_STATUS_MASK_NONE);
if (publisher == NULL) {
return shutdown_participant(
participant,
"create_publisher error",
EXIT_FAILURE);
}
/*
DDSPublisher *publisher = participant->create_publisher(
DDS_PUBLISHER_QOS_DEFAULT,
NULL,
DDS_STATUS_MASK_NONE);
if (publisher == NULL) {
return shutdown_participant(
participant,
"create_publisher error",
EXIT_FAILURE);
}
*/
// Register the datatype to use when creating the Topic
const char *type_name = partitionsTypeSupport::get_type_name();
retcode = partitionsTypeSupport::register_type(participant, type_name);
if (retcode != DDS_RETCODE_OK) {
return shutdown_participant(
participant,
"register_type error",
EXIT_FAILURE);
}
// Create a Topic with a name and a datatype
DDSTopic *topic = participant->create_topic(
"Example partitions",
type_name,
DDS_TOPIC_QOS_DEFAULT,
NULL /* listener */,
DDS_STATUS_MASK_NONE);
if (topic == NULL) {
return shutdown_participant(
participant,
"create_topic error",
EXIT_FAILURE);
}
/* In this example we set a Reliable datawriter, with Transient Local
* durability. By default we set up these QoS settings via XML. If you
* want to to it programmatically, use the following code, and comment out
* the create_datawriter call bellow.
*/
/*
DDS_DataWriterQos datawriter_qos;
retcode = publisher->get_default_datawriter_qos(datawriter_qos);
if (retcode != DDS_RETCODE_OK) {
return shutdown_participant(
participant,
"get_default_datawriter_qos error",
EXIT_FAILURE);
}
datawriter_qos.reliability.kind = DDS_RELIABLE_RELIABILITY_QOS;
datawriter_qos.durability.kind = DDS_TRANSIENT_LOCAL_DURABILITY_QOS;
datawriter_qos.history.kind = DDS_KEEP_LAST_HISTORY_QOS;
datawriter_qos.history.depth = 3;
DDSDataWriter *untyped_writer = publisher->create_datawriter(
topic,
datawriter_qos,
NULL,
DDS_STATUS_MASK_NONE);
if (untyped_writer == NULL) {
return shutdown_participant(
participant,
"create_datawriter error",
EXIT_FAILURE);
}
*/
// This DataWriter writes data on "Example partitions" Topic
DDSDataWriter *untyped_writer = publisher->create_datawriter(
topic,
DDS_DATAWRITER_QOS_DEFAULT,
NULL,
DDS_STATUS_MASK_NONE);
if (untyped_writer == NULL) {
return shutdown_participant(
participant,
"create_datawriter error",
EXIT_FAILURE);
}
partitionsDataWriter *typed_writer =
partitionsDataWriter::narrow(untyped_writer);
if (typed_writer == NULL) {
return shutdown_participant(
participant,
"DataWriter narrow error",
EXIT_FAILURE);
}
// Create data for writing, allocating all members
partitions *data = partitionsTypeSupport::create_data();
if (data == NULL) {
return shutdown_participant(
participant,
"partitionsTypeSupport::create_data error",
EXIT_FAILURE);
}
DDS_InstanceHandle_t instance_handle = DDS_HANDLE_NIL;
/* For a data type that has a key, if the same instance is going to be
written multiple times, initialize the key here
and register the keyed instance prior to writing */
/*
instance_handle = typed_writer->register_instance(*data);
*/
/// Main loop, write data
for (unsigned int samples_written = 0;
!shutdown_requested && samples_written < sample_count;
++samples_written) {
std::cout << "Writing partitions, count " << samples_written
<< std::endl;
data->x = samples_written;
retcode = typed_writer->write(*data, instance_handle);
if (retcode != DDS_RETCODE_OK) {
std::cerr << "write error " << retcode << std::endl;
}
/* Every 5 samples we will change the Partition name. These are the
* partition expressions we are going to try:
* "bar", "A*", "A?C", "X*Z", "zzz", "A*C"
*/
if ((samples_written + 1) % 25 == 0) {
// Matches "ABC" -- name[1] here can match name[0] there,
// as long as there is some overlapping name
publisher_qos.partition.name[0] = DDS_String_dup("zzz");
publisher_qos.partition.name[1] = DDS_String_dup("A*C");
std::cout << "Setting partition to '"
<< publisher_qos.partition.name[0] << "', '"
<< publisher_qos.partition.name[1] << "'...\n";
publisher->set_qos(publisher_qos);
} else if ((samples_written + 1) % 20 == 0) {
// Strings that are regular expressions aren't tested for
// literal matches, so this won't match "X*Z"
publisher_qos.partition.name[0] = DDS_String_dup("X*Z");
std::cout << "Setting partition to '"
<< publisher_qos.partition.name[0] << "', '"
<< publisher_qos.partition.name[1] << "'...\n";
publisher->set_qos(publisher_qos);
} else if ((samples_written + 1) % 15 == 0) {
// Matches "ABC"
publisher_qos.partition.name[0] = DDS_String_dup("A?C");
std::cout << "Setting partition to '"
<< publisher_qos.partition.name[0] << "', '"
<< publisher_qos.partition.name[1] << "'...\n";
publisher->set_qos(publisher_qos);
} else if ((samples_written + 1) % 10 == 0) {
// Matches "ABC"
publisher_qos.partition.name[0] = DDS_String_dup("A*");
std::cout << "Setting partition to '"
<< publisher_qos.partition.name[0] << "', '"
<< publisher_qos.partition.name[1] << "'...\n";
publisher->set_qos(publisher_qos);
} else if ((samples_written + 1) % 5 == 0) {
// No literal match for "bar"
publisher_qos.partition.name[0] = DDS_String_dup("bar");
std::cout << "Setting partition to '"
<< publisher_qos.partition.name[0] << "', '"
<< publisher_qos.partition.name[1] << "'...\n";
publisher->set_qos(publisher_qos);
}
NDDSUtility::sleep(send_period);
}
/*
retcode = partitions_writer->unregister_instance(
*data, instance_handle);
if (retcode != DDS_RETCODE_OK) {
std::cerr << "unregister instance error " << retcode << std::endl;
}
*/
/* Delete data sample */
retcode = partitionsTypeSupport::delete_data(data);
if (retcode != DDS_RETCODE_OK) {
std::cerr << "partitionsTypeSupport::delete_data error " << retcode
<< std::endl;
}
// Delete all entities (DataWriter, Topic, Publisher, DomainParticipant)
return shutdown_participant(participant, "Shutting down", EXIT_SUCCESS);
}
// Delete all entities
static int shutdown_participant(
DDSDomainParticipant *participant,
const char *shutdown_message,
int status)
{
DDS_ReturnCode_t retcode;
std::cout << shutdown_message << std::endl;
if (participant != NULL) {
// Cleanup everything created by this Participant
retcode = participant->delete_contained_entities();
if (retcode != DDS_RETCODE_OK) {
std::cerr << "delete_contained_entities error " << retcode
<< std::endl;
status = EXIT_FAILURE;
}
retcode = DDSTheParticipantFactory->delete_participant(participant);
if (retcode != DDS_RETCODE_OK) {
std::cerr << "delete_participant error " << retcode << std::endl;
status = EXIT_FAILURE;
}
}
return status;
}
int main(int argc, char *argv[])
{
// Parse arguments and handle control-C
ApplicationArguments arguments;
parse_arguments(arguments, argc, argv);
if (arguments.parse_result == PARSE_RETURN_EXIT) {
return EXIT_SUCCESS;
} else if (arguments.parse_result == PARSE_RETURN_FAILURE) {
return EXIT_FAILURE;
}
setup_signal_handlers();
// Sets Connext verbosity to help debugging
NDDSConfigLogger::get_instance()->set_verbosity(arguments.verbosity);
int status = run_publisher_application(
arguments.domain_id,
arguments.sample_count);
// Releases the memory used by the participant factory. Optional at
// application exit
DDS_ReturnCode_t retcode = DDSDomainParticipantFactory::finalize_instance();
if (retcode != DDS_RETCODE_OK) {
std::cerr << "finalize_instance error " << retcode << std::endl;
status = EXIT_FAILURE;
}
return status;
}
| cxx |
rticonnextdds-examples | data/projects/rticonnextdds-examples/connext_dds/partitions/c++98/partitions_subscriber.cxx | /*******************************************************************************
(c) 2005-2014 Copyright, Real-Time Innovations, Inc. All rights reserved.
RTI grants Licensee a license to use, modify, compile, and create derivative
works of the Software. Licensee has the right to distribute object form only
for use with RTI products. The Software is provided "as is", with no warranty
of any type, including any warranty for fitness for any purpose. RTI is under
no obligation to maintain or support the Software. RTI shall not be liable for
any incidental or consequential damages arising out of the use or inability to
use the software.
******************************************************************************/
#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include "partitions.h"
#include "partitionsSupport.h"
#include "ndds/ndds_cpp.h"
#include "application.h"
using namespace application;
static int shutdown_participant(
DDSDomainParticipant *participant,
const char *shutdown_message,
int status);
unsigned int process_data(partitionsDataReader *typed_reader)
{
partitionsSeq data_seq;
DDS_SampleInfoSeq info_seq;
unsigned int samples_read = 0;
typed_reader->take(
data_seq,
info_seq,
DDS_LENGTH_UNLIMITED,
DDS_ANY_SAMPLE_STATE,
DDS_ANY_VIEW_STATE,
DDS_ANY_INSTANCE_STATE);
for (int i = 0; i < data_seq.length(); ++i) {
if (info_seq[i].valid_data) {
if (info_seq[i].view_state == DDS_NEW_VIEW_STATE) {
std::cout << "Found new instance\n";
}
partitionsTypeSupport::print_data(&data_seq[i]);
samples_read++;
}
}
DDS_ReturnCode_t retcode = typed_reader->return_loan(data_seq, info_seq);
if (retcode != DDS_RETCODE_OK) {
std::cerr << "return loan error " << retcode << std::endl;
}
return samples_read;
}
int run_subscriber_application(
unsigned int domain_id,
unsigned int sample_count)
{
DDS_Duration_t wait_timeout = { 4, 0 };
// Start communicating in a domain, usually one participant per application
DDSDomainParticipant *participant =
DDSTheParticipantFactory->create_participant(
domain_id,
DDS_PARTICIPANT_QOS_DEFAULT,
NULL /* listener */,
DDS_STATUS_MASK_NONE);
if (participant == NULL) {
return shutdown_participant(
participant,
"create_participant error",
EXIT_FAILURE);
}
DDS_SubscriberQos subscriber_qos;
DDS_ReturnCode_t retcode =
participant->get_default_subscriber_qos(subscriber_qos);
if (retcode != DDS_RETCODE_OK) {
return shutdown_participant(
participant,
"get_default_subscriber_qos error",
EXIT_FAILURE);
}
/* If you want to change the Partition name programmatically rather than
* using the XML, you will need to add the following lines to your code
* and comment out the create_subscriber() call bellow.
*/
/*
subscriber_qos.partition.name.ensure_length(2, 2);
subscriber_qos.partition.name[0] = DDS_String_dup("ABC");
subscriber_qos.partition.name[1] = DDS_String_dup("X*Z");
DDSSubscriber *subscriber = participant->create_subscriber(
subscriber_qos,
NULL,
DDS_STATUS_MASK_NONE);
if (subscriber == NULL) {
return shutdown_participant(
participant,
"create_subscriber error",
EXIT_FAILURE);
}
*/
DDSSubscriber *subscriber = participant->create_subscriber(
DDS_SUBSCRIBER_QOS_DEFAULT,
NULL,
DDS_STATUS_MASK_NONE);
if (subscriber == NULL) {
return shutdown_participant(
participant,
"create_subscriber error",
EXIT_FAILURE);
}
std::cout << "Setting partition to '" << subscriber_qos.partition.name[0]
<< "', '" << subscriber_qos.partition.name[1] << "'...\n";
// Register the datatype to use when creating the Topic
const char *type_name = partitionsTypeSupport::get_type_name();
retcode = partitionsTypeSupport::register_type(participant, type_name);
if (retcode != DDS_RETCODE_OK) {
return shutdown_participant(
participant,
"register_type error",
EXIT_FAILURE);
}
// Create a Topic with a name and a datatype
DDSTopic *topic = participant->create_topic(
"Example partitions",
type_name,
DDS_TOPIC_QOS_DEFAULT,
NULL /* listener */,
DDS_STATUS_MASK_NONE);
if (topic == NULL) {
return shutdown_participant(
participant,
"create_topic error",
EXIT_FAILURE);
}
/* If you want to change the Datareader QoS programmatically rather than
* using the XML, you will need to add the following lines to your code
* and comment out the create_datareader() call bellow.
*/
/*
DDS_DataReaderQos datareader_qos;
retcode = subscriber->get_default_datareader_qos(datareader_qos);
if (retcode != DDS_RETCODE_OK) {
return shutdown_participant(
participant,
"get_default_datareader_qos error",
EXIT_FAILURE);
}
datareader_qos.reliability.kind = DDS_RELIABLE_RELIABILITY_QOS;
datareader_qos.durability.kind = DDS_TRANSIENT_LOCAL_DURABILITY_QOS;
datareader_qos.history.kind = DDS_KEEP_ALL_HISTORY_QOS;
DDSDataReader *untyped_reader = subscriber->create_datareader(
topic,
datareader_qos,
NULL,
DDS_STATUS_MASK_ALL);
if (reader == NULL) {
return shutdown_participant(
participant,
"create_datareader error",
EXIT_FAILURE);
}
*/
DDSDataReader *untyped_reader = subscriber->create_datareader(
topic,
DDS_DATAREADER_QOS_DEFAULT,
NULL,
DDS_STATUS_MASK_ALL);
if (untyped_reader == NULL) {
return shutdown_participant(
participant,
"create_datareader error",
EXIT_FAILURE);
}
partitionsDataReader *typed_reader =
partitionsDataReader::narrow(untyped_reader);
if (typed_reader == NULL) {
return shutdown_participant(
participant,
"DataReader narrow error",
EXIT_FAILURE);
}
// Create ReadCondition that triggers when unread data in reader's queue
DDSReadCondition *read_condition = typed_reader->create_readcondition(
DDS_NOT_READ_SAMPLE_STATE,
DDS_ANY_VIEW_STATE,
DDS_ANY_INSTANCE_STATE);
if (read_condition == NULL) {
return shutdown_participant(
participant,
"create_readcondition error",
EXIT_FAILURE);
}
// WaitSet will be woken when the attached condition is triggered
DDSWaitSet waitset;
retcode = waitset.attach_condition(read_condition);
if (retcode != DDS_RETCODE_OK) {
return shutdown_participant(
participant,
"attach_condition error",
EXIT_FAILURE);
}
// Main loop. Wait for data to arrive, and process when it arrives
unsigned int samples_read = 0;
while (!shutdown_requested && samples_read < sample_count) {
DDSConditionSeq active_conditions_seq;
// Wait for data
retcode = waitset.wait(active_conditions_seq, wait_timeout);
if (retcode == DDS_RETCODE_OK) {
// If the read condition is triggered, process data
samples_read += process_data(typed_reader);
}
}
// Cleanup
return shutdown_participant(participant, "Shutting down", 0);
}
// Delete all entities
static int shutdown_participant(
DDSDomainParticipant *participant,
const char *shutdown_message,
int status)
{
DDS_ReturnCode_t retcode;
std::cout << shutdown_message << std::endl;
if (participant != NULL) {
// Cleanup everything created by this Participant
retcode = participant->delete_contained_entities();
if (retcode != DDS_RETCODE_OK) {
std::cerr << "delete_contained_entities error" << retcode
<< std::endl;
status = EXIT_FAILURE;
}
retcode = DDSTheParticipantFactory->delete_participant(participant);
if (retcode != DDS_RETCODE_OK) {
std::cerr << "delete_participant error" << retcode << std::endl;
status = EXIT_FAILURE;
}
}
return status;
}
int main(int argc, char *argv[])
{
// Parse arguments and handle control-C
ApplicationArguments arguments;
parse_arguments(arguments, argc, argv);
if (arguments.parse_result == PARSE_RETURN_EXIT) {
return EXIT_SUCCESS;
} else if (arguments.parse_result == PARSE_RETURN_FAILURE) {
return EXIT_FAILURE;
}
setup_signal_handlers();
// Sets Connext verbosity to help debugging
NDDSConfigLogger::get_instance()->set_verbosity(arguments.verbosity);
int status = run_subscriber_application(
arguments.domain_id,
arguments.sample_count);
// Releases the memory used by the participant factory. Optional at
// application exit
DDS_ReturnCode_t retcode = DDSDomainParticipantFactory::finalize_instance();
if (retcode != DDS_RETCODE_OK) {
std::cerr << "finalize_instance error" << retcode << std::endl;
status = EXIT_FAILURE;
}
return status;
}
| cxx |
rticonnextdds-examples | data/projects/rticonnextdds-examples/connext_dds/partitions/c++98/application.h | /*
* (c) Copyright, Real-Time Innovations, 2020. All rights reserved.
* RTI grants Licensee a license to use, modify, compile, and create derivative
* works of the software solely for use with RTI Connext DDS. Licensee may
* redistribute copies of the software provided that all such copies are subject
* to this license. The software is provided "as is", with no warranty of any
* type, including any warranty for fitness for any purpose. RTI is under no
* obligation to maintain or support the software. RTI shall not be liable for
* any incidental or consequential damages arising out of the use or inability
* to use the software.
*/
#ifndef APPLICATION_H
#define APPLICATION_H
#include <iostream>
#include <csignal>
#include <climits>
namespace application {
// Catch control-C and tell application to shut down
bool shutdown_requested = false;
inline void stop_handler(int)
{
shutdown_requested = true;
std::cout << "preparing to shut down..." << std::endl;
}
inline void setup_signal_handlers()
{
signal(SIGINT, stop_handler);
signal(SIGTERM, stop_handler);
}
enum ParseReturn { PARSE_RETURN_OK, PARSE_RETURN_FAILURE, PARSE_RETURN_EXIT };
struct ApplicationArguments {
ParseReturn parse_result;
unsigned int domain_id;
unsigned int sample_count;
NDDS_Config_LogVerbosity verbosity;
};
inline void set_verbosity(ApplicationArguments &arguments, int verbosity)
{
switch (verbosity) {
case 0:
arguments.verbosity = NDDS_CONFIG_LOG_VERBOSITY_SILENT;
break;
case 1:
arguments.verbosity = NDDS_CONFIG_LOG_VERBOSITY_ERROR;
break;
case 2:
arguments.verbosity = NDDS_CONFIG_LOG_VERBOSITY_WARNING;
break;
case 3:
arguments.verbosity = NDDS_CONFIG_LOG_VERBOSITY_STATUS_ALL;
break;
default:
arguments.verbosity = NDDS_CONFIG_LOG_VERBOSITY_ERROR;
break;
}
}
// Parses application arguments for example. Returns whether to exit.
inline void parse_arguments(
ApplicationArguments &arguments,
int argc,
char *argv[])
{
int arg_processing = 1;
bool show_usage = false;
arguments.domain_id = 0;
arguments.sample_count = INT_MAX;
arguments.verbosity = NDDS_CONFIG_LOG_VERBOSITY_ERROR;
arguments.parse_result = PARSE_RETURN_OK;
while (arg_processing < argc) {
if ((argc > arg_processing + 1)
&& (strcmp(argv[arg_processing], "-d") == 0
|| strcmp(argv[arg_processing], "--domain") == 0)) {
arguments.domain_id = atoi(argv[arg_processing + 1]);
arg_processing += 2;
} else if (
(argc > arg_processing + 1)
&& (strcmp(argv[arg_processing], "-s") == 0
|| strcmp(argv[arg_processing], "--sample-count") == 0)) {
arguments.sample_count = atoi(argv[arg_processing + 1]);
arg_processing += 2;
} else if (
(argc > arg_processing + 1)
&& (strcmp(argv[arg_processing], "-v") == 0
|| strcmp(argv[arg_processing], "--verbosity") == 0)) {
set_verbosity(arguments, atoi(argv[arg_processing + 1]));
arg_processing += 2;
} else if (
strcmp(argv[arg_processing], "-h") == 0
|| strcmp(argv[arg_processing], "--help") == 0) {
std::cout << "Example application." << std::endl;
show_usage = true;
arguments.parse_result = PARSE_RETURN_EXIT;
break;
} else {
std::cout << "Bad parameter." << std::endl;
show_usage = true;
arguments.parse_result = PARSE_RETURN_FAILURE;
break;
}
}
if (show_usage) {
std::cout << "Usage:\n"
" -d, --domain <int> Domain ID this "
"application will\n"
" subscribe in. \n"
" Default: 0\n"
" -s, --sample_count <int> Number of samples to "
"receive before\n"
" cleanly shutting down. \n"
" Default: infinite\n"
" -v, --verbosity <int> How much debugging output "
"to show.\n"
" Range: 0-3 \n"
" Default: 1"
<< std::endl;
}
}
} // namespace application
#endif // APPLICATION_H
| h |
rticonnextdds-examples | data/projects/rticonnextdds-examples/connext_dds/partitions/c/partitions_subscriber.c | /*******************************************************************************
(c) 2005-2014 Copyright, Real-Time Innovations, Inc. All rights reserved.
RTI grants Licensee a license to use, modify, compile, and create derivative
works of the Software. Licensee has the right to distribute object form only
for use with RTI products. The Software is provided "as is", with no warranty
of any type, including any warranty for fitness for any purpose. RTI is under
no obligation to maintain or support the Software. RTI shall not be liable for
any incidental or consequential damages arising out of the use or inability to
use the software.
******************************************************************************/
/* partitions_subscriber.c
A subscription example
This file is derived from code automatically generated by the rtiddsgen
command:
rtiddsgen -language C -example <arch> partitions.idl
Example subscription of type partitions automatically generated by
'rtiddsgen'. To test them, follow these steps:
(1) Compile this file and the example publication.
(2) Start the subscription with the command
objs/<arch>/partitions_subscriber <domain_id> <sample_count>
(3) Start the publication with the command
objs/<arch>/partitions_publisher <domain_id> <sample_count>
(4) [Optional] Specify the list of discovery initial peers and
multicast receive addresses via an environment variable or a file
(in the current working directory) called NDDS_DISCOVERY_PEERS.
You can run any number of publishers and subscribers programs, and can
add and remove them dynamically from the domain.
Example:
To run the example application on domain <domain_id>:
On UNIX systems:
objs/<arch>/partitions_publisher <domain_id>
objs/<arch>/partitions_subscriber <domain_id>
On Windows systems:
objs\<arch>\partitions_publisher <domain_id>
objs\<arch>\partitions_subscriber <domain_id>
modification history
------------ -------
*/
#include "ndds/ndds_c.h"
#include "partitions.h"
#include "partitionsSupport.h"
#include <stdio.h>
#include <stdlib.h>
void partitionsListener_on_requested_deadline_missed(
void *listener_data,
DDS_DataReader *reader,
const struct DDS_RequestedDeadlineMissedStatus *status)
{
}
void partitionsListener_on_requested_incompatible_qos(
void *listener_data,
DDS_DataReader *reader,
const struct DDS_RequestedIncompatibleQosStatus *status)
{
}
void partitionsListener_on_sample_rejected(
void *listener_data,
DDS_DataReader *reader,
const struct DDS_SampleRejectedStatus *status)
{
}
void partitionsListener_on_liveliness_changed(
void *listener_data,
DDS_DataReader *reader,
const struct DDS_LivelinessChangedStatus *status)
{
}
void partitionsListener_on_sample_lost(
void *listener_data,
DDS_DataReader *reader,
const struct DDS_SampleLostStatus *status)
{
}
void partitionsListener_on_subscription_matched(
void *listener_data,
DDS_DataReader *reader,
const struct DDS_SubscriptionMatchedStatus *status)
{
}
void partitionsListener_on_data_available(
void *listener_data,
DDS_DataReader *reader)
{
partitionsDataReader *partitions_reader = NULL;
struct partitionsSeq data_seq = DDS_SEQUENCE_INITIALIZER;
struct DDS_SampleInfoSeq info_seq = DDS_SEQUENCE_INITIALIZER;
DDS_ReturnCode_t retcode;
int i;
struct DDS_SampleInfo *info;
partitions_reader = partitionsDataReader_narrow(reader);
if (partitions_reader == NULL) {
printf("DataReader narrow error\n");
return;
}
retcode = partitionsDataReader_take(
partitions_reader,
&data_seq,
&info_seq,
DDS_LENGTH_UNLIMITED,
DDS_ANY_SAMPLE_STATE,
DDS_ANY_VIEW_STATE,
DDS_ANY_INSTANCE_STATE);
if (retcode == DDS_RETCODE_NO_DATA) {
return;
} else if (retcode != DDS_RETCODE_OK) {
printf("take error %d\n", retcode);
return;
}
for (i = 0; i < partitionsSeq_get_length(&data_seq); ++i) {
info = DDS_SampleInfoSeq_get_reference(&info_seq, i);
if (info->valid_data) {
if (info->view_state == DDS_NEW_VIEW_STATE) {
printf("Found new instance\n");
}
partitionsTypeSupport_print_data(
partitionsSeq_get_reference(&data_seq, i));
}
}
retcode = partitionsDataReader_return_loan(
partitions_reader,
&data_seq,
&info_seq);
if (retcode != DDS_RETCODE_OK) {
printf("return loan error %d\n", retcode);
}
}
/* Delete all entities */
static int subscriber_shutdown(DDS_DomainParticipant *participant)
{
DDS_ReturnCode_t retcode;
int status = 0;
if (participant != NULL) {
retcode = DDS_DomainParticipant_delete_contained_entities(participant);
if (retcode != DDS_RETCODE_OK) {
printf("delete_contained_entities error %d\n", retcode);
status = -1;
}
retcode = DDS_DomainParticipantFactory_delete_participant(
DDS_TheParticipantFactory,
participant);
if (retcode != DDS_RETCODE_OK) {
printf("delete_participant error %d\n", retcode);
status = -1;
}
}
/* RTI Connext provides the finalize_instance() method on
domain participant factory for users who want to release memory used
by the participant factory. Uncomment the following block of code for
clean destruction of the singleton. */
/*
retcode = DDS_DomainParticipantFactory_finalize_instance();
if (retcode != DDS_RETCODE_OK) {
printf("finalize_instance error %d\n", retcode);
status = -1;
}
*/
return status;
}
static int subscriber_main(int domainId, int sample_count)
{
DDS_DomainParticipant *participant = NULL;
DDS_Subscriber *subscriber = NULL;
DDS_Topic *topic = NULL;
struct DDS_DataReaderListener reader_listener =
DDS_DataReaderListener_INITIALIZER;
DDS_DataReader *reader = NULL;
DDS_ReturnCode_t retcode;
const char *type_name = NULL;
int count = 0;
struct DDS_Duration_t poll_period = { 4, 0 };
struct DDS_SubscriberQos subscriber_qos = DDS_SubscriberQos_INITIALIZER;
/* struct DDS_DataReaderQos datareader_qos = DDS_DataReaderQos_INITIALIZER;
*/
/* To customize participant QoS, use
the configuration file USER_QOS_PROFILES.xml */
participant = DDS_DomainParticipantFactory_create_participant(
DDS_TheParticipantFactory,
domainId,
&DDS_PARTICIPANT_QOS_DEFAULT,
NULL /* listener */,
DDS_STATUS_MASK_NONE);
if (participant == NULL) {
printf("create_participant error\n");
subscriber_shutdown(participant);
return -1;
}
retcode = DDS_DomainParticipant_get_default_subscriber_qos(
participant,
&subscriber_qos);
if (retcode != DDS_RETCODE_OK) {
printf("get_default_subscriber_qos error\n");
return -1;
}
/* If you want to change the Partition name programmatically rather than
* using the XML, you will need to add the following lines to your code
* and comment out the create_subscriber() call bellow.
*/
/*
DDS_StringSeq_ensure_length(&subscriber_qos.partition.name, 2, 2);
*DDS_StringSeq_get_reference(&subscriber_qos.partition.name, 0) =
DDS_String_dup("ABC");
*DDS_StringSeq_get_reference(&subscriber_qos.partition.name, 1) =
DDS_String_dup("X*Z");
subscriber = DDS_DomainParticipant_create_subscriber(participant,
&subscriber_qos,
NULL,
DDS_STATUS_MASK_NONE);
if (subscriber == NULL) {
printf("create_subscriber error\n");
subscriber_shutdown(participant);
return -1;
}
*/
subscriber = DDS_DomainParticipant_create_subscriber(
participant,
&DDS_SUBSCRIBER_QOS_DEFAULT,
NULL,
DDS_STATUS_MASK_NONE);
if (subscriber == NULL) {
printf("create_subscriber error\n");
subscriber_shutdown(participant);
return -1;
}
printf("Setting partition to '%s', '%s'...\n",
DDS_StringSeq_get(&subscriber_qos.partition.name, 0),
DDS_StringSeq_get(&subscriber_qos.partition.name, 1));
/* Register the type before creating the topic */
type_name = partitionsTypeSupport_get_type_name();
retcode = partitionsTypeSupport_register_type(participant, type_name);
if (retcode != DDS_RETCODE_OK) {
printf("register_type error %d\n", retcode);
subscriber_shutdown(participant);
return -1;
}
/* To customize topic QoS, use
the configuration file USER_QOS_PROFILES.xml */
topic = DDS_DomainParticipant_create_topic(
participant,
"Example partitions",
type_name,
&DDS_TOPIC_QOS_DEFAULT,
NULL /* listener */,
DDS_STATUS_MASK_NONE);
if (topic == NULL) {
printf("create_topic error\n");
subscriber_shutdown(participant);
return -1;
}
/* Set up a data reader listener */
reader_listener.on_requested_deadline_missed =
partitionsListener_on_requested_deadline_missed;
reader_listener.on_requested_incompatible_qos =
partitionsListener_on_requested_incompatible_qos;
reader_listener.on_sample_rejected = partitionsListener_on_sample_rejected;
reader_listener.on_liveliness_changed =
partitionsListener_on_liveliness_changed;
reader_listener.on_sample_lost = partitionsListener_on_sample_lost;
reader_listener.on_subscription_matched =
partitionsListener_on_subscription_matched;
reader_listener.on_data_available = partitionsListener_on_data_available;
/* If you want to change the Datareader QoS programmatically rather than
* using the XML, you will need to add the following lines to your code
* and comment out the create_datareader() call bellow.
*/
/*
retcode = DDS_Subscriber_get_default_datareader_qos(subscriber,
&datareader_qos); if (retcode != DDS_RETCODE_OK) {
printf("get_default_datareader_qos error\n");
return -1;
}
datareader_qos.reliability.kind = DDS_RELIABLE_RELIABILITY_QOS;
datareader_qos.durability.kind = DDS_TRANSIENT_LOCAL_DURABILITY_QOS;
datareader_qos.history.kind = DDS_KEEP_ALL_HISTORY_QOS;
reader = DDS_Subscriber_create_datareader(subscriber,
DDS_Topic_as_topicdescription(topic),
&datareader_qos,
&reader_listener,
DDS_STATUS_MASK_ALL);
if (reader == NULL) {
printf("create_datareader error\n");
subscriber_shutdown(participant);
return -1;
}
*/
reader = DDS_Subscriber_create_datareader(
subscriber,
DDS_Topic_as_topicdescription(topic),
&DDS_DATAREADER_QOS_DEFAULT,
&reader_listener,
DDS_STATUS_MASK_ALL);
if (reader == NULL) {
printf("create_datareader error\n");
subscriber_shutdown(participant);
return -1;
}
/* Main loop */
for (count = 0; (sample_count == 0) || (count < sample_count); ++count) {
NDDS_Utility_sleep(&poll_period);
}
/* Cleanup and delete all entities */
return subscriber_shutdown(participant);
}
#if defined(RTI_WINCE)
int wmain(int argc, wchar_t **argv)
{
int domainId = 0;
int sample_count = 0; /* infinite loop */
if (argc >= 2) {
domainId = _wtoi(argv[1]);
}
if (argc >= 3) {
sample_count = _wtoi(argv[2]);
}
/* Uncomment this to turn on additional logging
NDDS_Config_Logger_set_verbosity_by_category(
NDDS_Config_Logger_get_instance(),
NDDS_CONFIG_LOG_CATEGORY_API,
NDDS_CONFIG_LOG_VERBOSITY_STATUS_ALL);
*/
return subscriber_main(domainId, sample_count);
}
#elif !(defined(RTI_VXWORKS) && !defined(__RTP__)) && !defined(RTI_PSOS)
int main(int argc, char *argv[])
{
int domainId = 0;
int sample_count = 0; /* infinite loop */
if (argc >= 2) {
domainId = atoi(argv[1]);
}
if (argc >= 3) {
sample_count = atoi(argv[2]);
}
/* Uncomment this to turn on additional logging
NDDS_Config_Logger_set_verbosity_by_category(
NDDS_Config_Logger_get_instance(),
NDDS_CONFIG_LOG_CATEGORY_API,
NDDS_CONFIG_LOG_VERBOSITY_STATUS_ALL);
*/
return subscriber_main(domainId, sample_count);
}
#endif
#ifdef RTI_VX653
const unsigned char *__ctype = NULL;
void usrAppInit()
{
#ifdef USER_APPL_INIT
USER_APPL_INIT; /* for backwards compatibility */
#endif
/* add application specific code here */
taskSpawn(
"sub",
RTI_OSAPI_THREAD_PRIORITY_NORMAL,
0x8,
0x150000,
(FUNCPTR) subscriber_main,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0);
}
#endif
| c |
rticonnextdds-examples | data/projects/rticonnextdds-examples/connext_dds/partitions/c/partitions_publisher.c | /*******************************************************************************
(c) 2005-2014 Copyright, Real-Time Innovations, Inc. All rights reserved.
RTI grants Licensee a license to use, modify, compile, and create derivative
works of the Software. Licensee has the right to distribute object form only
for use with RTI products. The Software is provided "as is", with no warranty
of any type, including any warranty for fitness for any purpose. RTI is under
no obligation to maintain or support the Software. RTI shall not be liable for
any incidental or consequential damages arising out of the use or inability to
use the software.
******************************************************************************/
/* partitions_publisher.c
A publication of data of type partitions
This file is derived from code automatically generated by the rtiddsgen
command:
rtiddsgen -language C -example <arch> partitions.idl
Example publication of type partitions automatically generated by
'rtiddsgen'. To test them follow these steps:
(1) Compile this file and the example subscription.
(2) Start the subscription with the command
objs/<arch>/partitions_subscriber <domain_id> <sample_count>
(3) Start the publication with the command
objs/<arch>/partitions_publisher <domain_id> <sample_count>
(4) [Optional] Specify the list of discovery initial peers and
multicast receive addresses via an environment variable or a file
(in the current working directory) called NDDS_DISCOVERY_PEERS.
You can run any number of publishers and subscribers programs, and can
add and remove them dynamically from the domain.
Example:
To run the example application on domain <domain_id>:
On Unix:
objs/<arch>/partitions_publisher <domain_id>
objs/<arch>/partitions_subscriber <domain_id>
On Windows:
objs\<arch>\partitions_publisher <domain_id>
objs\<arch>\partitions_subscriber <domain_id>
modification history
------------ -------
*/
#include "ndds/ndds_c.h"
#include "partitions.h"
#include "partitionsSupport.h"
#include <stdio.h>
#include <stdlib.h>
/* Delete all entities */
static int publisher_shutdown(DDS_DomainParticipant *participant)
{
DDS_ReturnCode_t retcode;
int status = 0;
if (participant != NULL) {
retcode = DDS_DomainParticipant_delete_contained_entities(participant);
if (retcode != DDS_RETCODE_OK) {
printf("delete_contained_entities error %d\n", retcode);
status = -1;
}
retcode = DDS_DomainParticipantFactory_delete_participant(
DDS_TheParticipantFactory,
participant);
if (retcode != DDS_RETCODE_OK) {
printf("delete_participant error %d\n", retcode);
status = -1;
}
}
/* RTI Connext provides finalize_instance() method on
domain participant factory for people who want to release memory used
by the participant factory. Uncomment the following block of code for
clean destruction of the singleton. */
/*
retcode = DDS_DomainParticipantFactory_finalize_instance();
if (retcode != DDS_RETCODE_OK) {
printf("finalize_instance error %d\n", retcode);
status = -1;
}
*/
return status;
}
static int publisher_main(int domainId, int sample_count)
{
DDS_DomainParticipant *participant = NULL;
DDS_Publisher *publisher = NULL;
DDS_Topic *topic = NULL;
DDS_DataWriter *writer = NULL;
partitionsDataWriter *partitions_writer = NULL;
partitions *instance = NULL;
DDS_ReturnCode_t retcode;
DDS_InstanceHandle_t instance_handle = DDS_HANDLE_NIL;
const char *type_name = NULL;
int count = 0;
struct DDS_Duration_t send_period = { 1, 0 };
struct DDS_PublisherQos publisher_qos = DDS_PublisherQos_INITIALIZER;
struct DDS_DataWriterQos datawriter_qos = DDS_DataWriterQos_INITIALIZER;
/* To customize participant QoS, use
the configuration file USER_QOS_PROFILES.xml */
participant = DDS_DomainParticipantFactory_create_participant(
DDS_TheParticipantFactory,
domainId,
&DDS_PARTICIPANT_QOS_DEFAULT,
NULL /* listener */,
DDS_STATUS_MASK_NONE);
if (participant == NULL) {
printf("create_participant error\n");
publisher_shutdown(participant);
return -1;
}
/* If you want to change the Partition name programmatically rather than
* using the XML, you will need to add the following lines to your code
* and comment out the create_publisher() call bellow.
*/
retcode = DDS_DomainParticipant_get_default_publisher_qos(
participant,
&publisher_qos);
if (retcode != DDS_RETCODE_OK) {
printf("get_default_publisher_qos error\n");
return -1;
}
/* We modify the Publisher QoS to include two partition names. By
* default these will be "ABC" and "foo". */
/*
DDS_StringSeq_ensure_length(&publisher_qos.partition.name, 2, 2);
*DDS_StringSeq_get_reference(&publisher_qos.partition.name, 0) =
DDS_String_dup("ABC");
*DDS_StringSeq_get_reference(&publisher_qos.partition.name, 1) =
DDS_String_dup("foo");
publisher = DDS_DomainParticipant_create_publisher(participant,
&publisher_qos,
NULL,
DDS_STATUS_MASK_NONE);
if (publisher == NULL) {
printf("create_publisher error\n");
publisher_shutdown(participant);
return -1;
}
*/
/* To customize publisher QoS, use
the configuration file USER_QOS_PROFILES.xml */
publisher = DDS_DomainParticipant_create_publisher(
participant,
&DDS_PUBLISHER_QOS_DEFAULT,
NULL,
DDS_STATUS_MASK_NONE);
if (publisher == NULL) {
printf("create_publisher error\n");
publisher_shutdown(participant);
return -1;
}
/* Register type before creating topic */
type_name = partitionsTypeSupport_get_type_name();
retcode = partitionsTypeSupport_register_type(participant, type_name);
if (retcode != DDS_RETCODE_OK) {
printf("register_type error %d\n", retcode);
publisher_shutdown(participant);
return -1;
}
/* To customize topic QoS, use
the configuration file USER_QOS_PROFILES.xml */
topic = DDS_DomainParticipant_create_topic(
participant,
"Example partitions",
type_name,
&DDS_TOPIC_QOS_DEFAULT,
NULL /* listener */,
DDS_STATUS_MASK_NONE);
if (topic == NULL) {
printf("create_topic error\n");
publisher_shutdown(participant);
return -1;
}
retcode = DDS_Publisher_get_default_datawriter_qos(
publisher,
&datawriter_qos);
if (retcode != DDS_RETCODE_OK) {
printf("get_default_datawriter_qos error\n");
return -1;
}
/* In this example we set a Reliable datawriter, with Transient Local
* durability. By default we set up these QoS settings via XML. If you
* want to to it programmatically, use the following code, and comment out
* the create_datawriter call bellow.
*/
/*
datawriter_qos.reliability.kind = DDS_RELIABLE_RELIABILITY_QOS;
datawriter_qos.durability.kind = DDS_TRANSIENT_LOCAL_DURABILITY_QOS;
datawriter_qos.history.kind = DDS_KEEP_LAST_HISTORY_QOS;
datawriter_qos.history.depth = 3;
writer = DDS_Publisher_create_datawriter(publisher,
topic,
&datawriter_qos,
NULL,
DDS_STATUS_MASK_NONE);
if (writer == NULL) {
printf("create_datawriter error\n");
publisher_shutdown(participant);
return -1;
}
*/
writer = DDS_Publisher_create_datawriter(
publisher,
topic,
&DDS_DATAWRITER_QOS_DEFAULT,
NULL,
DDS_STATUS_MASK_NONE);
if (writer == NULL) {
printf("create_datawriter error\n");
publisher_shutdown(participant);
return -1;
}
printf("Setting partition to '%s', '%s'...\n",
DDS_StringSeq_get(&publisher_qos.partition.name, 0),
DDS_StringSeq_get(&publisher_qos.partition.name, 1));
partitions_writer = partitionsDataWriter_narrow(writer);
if (partitions_writer == NULL) {
printf("DataWriter narrow error\n");
publisher_shutdown(participant);
return -1;
}
/* Create data sample for writing */
instance = partitionsTypeSupport_create_data_ex(DDS_BOOLEAN_TRUE);
if (instance == NULL) {
printf("partitionsTypeSupport_create_data error\n");
publisher_shutdown(participant);
return -1;
}
/* For a data type that has a key, if the same instance is going to be
written multiple times, initialize the key here
and register the keyed instance prior to writing */
/*
instance_handle = partitionsDataWriter_register_instance(
partitions_writer, instance);
*/
/* Main loop */
for (count = 0; (sample_count == 0) || (count < sample_count); ++count) {
printf("Writing partitions, count %d\n", count);
instance->x = count;
retcode = partitionsDataWriter_write(
partitions_writer,
instance,
&instance_handle);
if (retcode != DDS_RETCODE_OK) {
printf("write error %d\n", retcode);
}
/* Every 5 samples we will change the Partition name. These are the
* partition expressions we are going to try:
* "bar", "A*", "A?C", "X*Z", "zzz", "A*C"
*/
if ((count + 1) % 25 == 0) {
/* Matches "ABC" -- name[1] here can match name[0] there,
* as long as there is some overlapping name */
*DDS_StringSeq_get_reference(&publisher_qos.partition.name, 0) =
DDS_String_dup("zzz");
*DDS_StringSeq_get_reference(&publisher_qos.partition.name, 1) =
DDS_String_dup("A*C");
printf("Setting partition to '%s', '%s'...\n",
DDS_StringSeq_get(&publisher_qos.partition.name, 0),
DDS_StringSeq_get(&publisher_qos.partition.name, 1));
DDS_Publisher_set_qos(publisher, &publisher_qos);
} else if ((count + 1) % 20 == 0) {
/* Strings that are regular expressions aren't tested for
* literal matches, so this won't match "X*Z" */
*DDS_StringSeq_get_reference(&publisher_qos.partition.name, 0) =
DDS_String_dup("X*Z");
printf("Setting partition to '%s', '%s'...\n",
DDS_StringSeq_get(&publisher_qos.partition.name, 0),
DDS_StringSeq_get(&publisher_qos.partition.name, 1));
DDS_Publisher_set_qos(publisher, &publisher_qos);
} else if ((count + 1) % 15 == 0) {
/* Matches "ABC" */
*DDS_StringSeq_get_reference(&publisher_qos.partition.name, 0) =
DDS_String_dup("A?C");
printf("Setting partition to '%s', '%s'...\n",
DDS_StringSeq_get(&publisher_qos.partition.name, 0),
DDS_StringSeq_get(&publisher_qos.partition.name, 1));
DDS_Publisher_set_qos(publisher, &publisher_qos);
} else if ((count + 1) % 10 == 0) {
/* Matches "ABC" */
*DDS_StringSeq_get_reference(&publisher_qos.partition.name, 0) =
DDS_String_dup("A*");
printf("Setting partition to '%s', '%s'...\n",
DDS_StringSeq_get(&publisher_qos.partition.name, 0),
DDS_StringSeq_get(&publisher_qos.partition.name, 1));
DDS_Publisher_set_qos(publisher, &publisher_qos);
} else if ((count + 1) % 5 == 0) {
/* No literal match for "bar"*/
*DDS_StringSeq_get_reference(&publisher_qos.partition.name, 0) =
DDS_String_dup("bar");
printf("Setting partition to '%s', '%s'...\n",
DDS_StringSeq_get(&publisher_qos.partition.name, 0),
DDS_StringSeq_get(&publisher_qos.partition.name, 1));
DDS_Publisher_set_qos(publisher, &publisher_qos);
}
NDDS_Utility_sleep(&send_period);
}
/*
retcode = partitionsDataWriter_unregister_instance(
partitions_writer, instance, &instance_handle);
if (retcode != DDS_RETCODE_OK) {
printf("unregister instance error %d\n", retcode);
}
*/
/* Delete data sample */
retcode = partitionsTypeSupport_delete_data_ex(instance, DDS_BOOLEAN_TRUE);
if (retcode != DDS_RETCODE_OK) {
printf("partitionsTypeSupport_delete_data error %d\n", retcode);
}
/* Cleanup and delete delete all entities */
return publisher_shutdown(participant);
}
#if defined(RTI_WINCE)
int wmain(int argc, wchar_t **argv)
{
int domainId = 0;
int sample_count = 0; /* infinite loop */
if (argc >= 2) {
domainId = _wtoi(argv[1]);
}
if (argc >= 3) {
sample_count = _wtoi(argv[2]);
}
/* Uncomment this to turn on additional logging
NDDS_Config_Logger_set_verbosity_by_category(
NDDS_Config_Logger_get_instance(),
NDDS_CONFIG_LOG_CATEGORY_API,
NDDS_CONFIG_LOG_VERBOSITY_STATUS_ALL);
*/
return publisher_main(domainId, sample_count);
}
#elif !(defined(RTI_VXWORKS) && !defined(__RTP__)) && !defined(RTI_PSOS)
int main(int argc, char *argv[])
{
int domainId = 0;
int sample_count = 0; /* infinite loop */
if (argc >= 2) {
domainId = atoi(argv[1]);
}
if (argc >= 3) {
sample_count = atoi(argv[2]);
}
/* Uncomment this to turn on additional logging
NDDS_Config_Logger_set_verbosity_by_category(
NDDS_Config_Logger_get_instance(),
NDDS_CONFIG_LOG_CATEGORY_API,
NDDS_CONFIG_LOG_VERBOSITY_STATUS_ALL);
*/
return publisher_main(domainId, sample_count);
}
#endif
#ifdef RTI_VX653
const unsigned char *__ctype = NULL;
void usrAppInit()
{
#ifdef USER_APPL_INIT
USER_APPL_INIT; /* for backwards compatibility */
#endif
/* add application specific code here */
taskSpawn(
"pub",
RTI_OSAPI_THREAD_PRIORITY_NORMAL,
0x8,
0x150000,
(FUNCPTR) publisher_main,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0);
}
#endif
| c |
rticonnextdds-examples | data/projects/rticonnextdds-examples/connext_dds/partitions/c++03/partitions_publisher.cxx | /*******************************************************************************
(c) 2005-2015 Copyright, Real-Time Innovations, Inc. All rights reserved.
RTI grants Licensee a license to use, modify, compile, and create derivative
works of the Software. Licensee has the right to distribute object form only
for use with RTI products. The Software is provided "as is", with no warranty
of any type, including any warranty for fitness for any purpose. RTI is under
no obligation to maintain or support the Software. RTI shall not be liable for
any incidental or consequential damages arising out of the use or inability to
use the software.
******************************************************************************/
#include <iostream>
#include "partitions.hpp"
#include <dds/dds.hpp>
using namespace dds::core;
using namespace dds::core::policy;
using namespace dds::domain;
using namespace dds::topic;
using namespace dds::pub;
using namespace dds::pub::qos;
void publisher_main(int domain_id, int sample_count)
{
// Create a DomainParticipant with default Qos.
DomainParticipant participant(domain_id);
// Retrieve the default Publisher QoS, from USER_QOS_PROFILES.xml
PublisherQos publisher_qos = QosProvider::Default().publisher_qos();
Partition partition = publisher_qos.policy<Partition>();
std::vector<std::string> partition_names = partition.name();
// If you want to change the Publisher QoS programmatically rather
// than using the XML file, you will need to comment out these lines.
// partition_names[0] = "ABC";
// partition_names[1] = "foo";
// partition.name(partition_names);
// publisher_qos << partition;
std::cout << "Setting partition to";
for (int i = 0; i < partition_names.size(); i++) {
std::cout << " '" << partition_names[i] << "'";
}
std::cout << std::endl;
// Create a Publisher.
Publisher publisher(participant, publisher_qos);
// Create a Topic -- and automatically register the type.
Topic<partitions> topic(participant, "Example partitions");
// Retrieve the default DataWriter QoS, from USER_QOS_PROFILES.xml
DataWriterQos writer_qos = QosProvider::Default().datawriter_qos();
// If you want to change the DataWriter QoS programmatically rather
// than using the XML file, you will need to comment out these lines.
// writer_qos << Reliability::Reliable()
// << History::KeepLast(3)
// << Durability::TransientLocal();
// Create a Datawriter.
DataWriter<partitions> writer(publisher, topic, writer_qos);
// Create a data sample for writing.
partitions instance;
// Main loop
bool update_qos = false;
for (int count = 0; (sample_count == 0) || (count < sample_count);
count++) {
std::cout << "Writing partitions, count " << count << std::endl;
// Modify and send the sample.
instance.x(count);
writer.write(instance);
// Every 5 samples we will change the partition name.
// These are the partition expressions we are going to try:
// "bar", "A*", "A?C", "X*Z", "zzz" and "A*C".
if ((count + 1) % 25 == 0) {
// Matches "ABC", name[1] here can match name[0] there,
// as long as there is some overlapping name.
partition_names.resize(2);
partition_names[0] = "zzz";
partition_names[1] = "A*C";
update_qos = true;
} else if ((count + 1) % 25 == 20) {
// Strings that are regular expressions aren't tested for
// literal matches, so this won't match "X*Z".
partition_names[0] = "X*Z";
update_qos = true;
} else if ((count + 1) % 25 == 15) {
// Matches "ABC".
partition_names[0] = "A?C";
update_qos = true;
} else if ((count + 1) % 25 == 10) {
// Matches "ABC".
partition_names[0] = "A*";
update_qos = true;
} else if ((count + 1) % 25 == 5) {
// No literal match for "bar".
// For the next iterations we are using only one partition.
partition_names.resize(1);
partition_names[0] = "bar";
update_qos = true;
}
// Set the new partition names to the publisher QoS.
if (update_qos) {
std::cout << "Setting partition to";
for (int i = 0; i < partition_names.size(); i++) {
std::cout << " '" << partition_names[i] << "'";
}
std::cout << std::endl;
partition.name(partition_names);
publisher.qos(publisher_qos << partition);
update_qos = false;
}
rti::util::sleep(Duration(1));
}
}
int main(int argc, char *argv[])
{
int domain_id = 0;
int sample_count = 0; // Infinite loop
if (argc >= 2) {
domain_id = atoi(argv[1]);
}
if (argc >= 3) {
sample_count = atoi(argv[2]);
}
// To turn on additional logging, include <rti/config/Logger.hpp> and
// uncomment the following line:
// rti::config::Logger::instance().verbosity(rti::config::Verbosity::STATUS_ALL);
try {
publisher_main(domain_id, sample_count);
} catch (std::exception ex) {
std::cout << "Exception caught: " << ex.what() << std::endl;
return -1;
}
return 0;
}
| cxx |
rticonnextdds-examples | data/projects/rticonnextdds-examples/connext_dds/partitions/c++03/partitions_subscriber.cxx | /*******************************************************************************
(c) 2005-2015 Copyright, Real-Time Innovations, Inc. All rights reserved.
RTI grants Licensee a license to use, modify, compile, and create derivative
works of the Software. Licensee has the right to distribute object form only
for use with RTI products. The Software is provided "as is", with no warranty
of any type, including any warranty for fitness for any purpose. RTI is under
no obligation to maintain or support the Software. RTI shall not be liable for
any incidental or consequential damages arising out of the use or inability to
use the software.
******************************************************************************/
#include <algorithm>
#include <iostream>
#include "partitions.hpp"
#include <dds/dds.hpp>
#include <rti/core/ListenerBinder.hpp>
using namespace dds::core;
using namespace dds::core::policy;
using namespace dds::core::status;
using namespace dds::domain;
using namespace dds::topic;
using namespace dds::sub;
using namespace dds::sub::qos;
using namespace dds::sub::status;
using namespace rti::core;
class PartitionsListener : public NoOpDataReaderListener<partitions> {
public:
void on_data_available(DataReader<partitions> &reader)
{
// Take all samples
LoanedSamples<partitions> samples = reader.take();
for (LoanedSamples<partitions>::iterator sample_it = samples.begin();
sample_it != samples.end();
sample_it++) {
if (sample_it->info().valid()) {
// After partition mismatch unpair,
// it detects the instance as new.
ViewState view_state = sample_it->info().state().view_state();
if (view_state == ViewState::new_view()) {
std::cout << "Found new instance" << std::endl;
}
std::cout << sample_it->data() << std::endl;
}
}
}
};
void subscriber_main(int domain_id, int sample_count)
{
// Create a participant with default QoS.
DomainParticipant participant(domain_id);
// Retrieve the default Subscriber QoS, from USER_QOS_PROFILES.xml
SubscriberQos subscriber_qos = QosProvider::Default().subscriber_qos();
Partition partition = subscriber_qos.policy<Partition>();
std::vector<std::string> partition_names = partition.name();
// If you want to change the Subscriber QoS programmatically rather
// than using the XML file, you will need to comment out these lines.
// partition_names[0] = "ABC";
// partition_names[1] = "X*Z";
// partition.name(partition_names);
// subscriber_qos << partition;
std::cout << "Setting partition to "
<< "'" << partition_names[0] << "', "
<< "'" << partition_names[1] << "'..." << std::endl;
// Create a subscriber.
Subscriber subscriber(participant, subscriber_qos);
// Create a Topic -- and automatically register the type.
Topic<partitions> topic(participant, "Example partitions");
// Retrieve the default DataReader QoS, from USER_QOS_PROFILES.xml
DataReaderQos reader_qos = QosProvider::Default().datareader_qos();
// If you want to change the Subscriber QoS programmatically rather
// than using the XML file, you will need to comment out these lines.
// reader_qos << Reliability::Reliable()
// << History::KeepAll()
// << Durability::TransientLocal();
// Create a DataReader.
DataReader<partitions> reader(subscriber, topic, reader_qos);
// Create a DataReader listener using ListenerBinder, a RAII utility that
// will take care of reseting it from the reader and deleting it.
ListenerBinder<DataReader<partitions> > scoped_listener =
bind_and_manage_listener(
reader,
new PartitionsListener,
StatusMask::data_available());
// Main loop
for (int count = 0; (sample_count == 0) || (count < sample_count);
count++) {
rti::util::sleep(Duration(4));
}
}
int main(int argc, char *argv[])
{
int domain_id = 0;
int sample_count = 0; // Infinite loop
if (argc >= 2) {
domain_id = atoi(argv[1]);
}
if (argc >= 3) {
sample_count = atoi(argv[2]);
}
// To turn on additional logging, include <rti/config/Logger.hpp> and
// uncomment the following line:
// rti::config::Logger::instance().verbosity(rti::config::Verbosity::STATUS_ALL);
try {
subscriber_main(domain_id, sample_count);
} catch (const std::exception &ex) {
// This will catch DDS exceptions
std::cerr << "Exception in subscriber_main(): " << ex.what()
<< std::endl;
return -1;
}
return 0;
}
| cxx |
rticonnextdds-examples | data/projects/rticonnextdds-examples/connext_dds/partitions/c++11/partitions_publisher.cxx | /*******************************************************************************
(c) 2005-2015 Copyright, Real-Time Innovations, Inc. All rights reserved.
RTI grants Licensee a license to use, modify, compile, and create derivative
works of the Software. Licensee has the right to distribute object form only
for use with RTI products. The Software is provided "as is", with no warranty
of any type, including any warranty for fitness for any purpose. RTI is under
no obligation to maintain or support the Software. RTI shall not be liable for
any incidental or consequential damages arising out of the use or inability to
use the software.
******************************************************************************/
#include <dds/pub/ddspub.hpp>
#include <rti/util/util.hpp> // for sleep()
#include <rti/config/Logger.hpp> // for logging
#include "application.hpp" // for command line parsing and ctrl-c
#include "partitions.hpp"
void run_publisher_application(
unsigned int domain_id,
unsigned int sample_count)
{
// Create a DomainParticipant with default Qos.
dds::domain::DomainParticipant participant(domain_id);
// Retrieve the default Publisher QoS, from USER_QOS_PROFILES.xml
dds::pub::qos::PublisherQos publisher_qos =
dds::core::QosProvider::Default().publisher_qos();
auto &partition = publisher_qos.policy<dds::core::policy::Partition>();
std::vector<std::string> partition_names = partition.name();
// If you want to change the Publisher QoS programmatically rather
// than using the XML file, you will need to comment out these lines.
// partition_names[0] = "ABC";
// partition_names[1] = "foo";
// partition.name(partition_names);
// publisher_qos << partition;
std::cout << "Setting partition to";
for (const auto &name : partition_names) {
std::cout << " '" << name << "'";
}
std::cout << std::endl;
// Create a Publisher.
dds::pub::Publisher publisher(participant, publisher_qos);
// Create a Topic -- and automatically register the type.
dds::topic::Topic<partitions> topic(participant, "Example partitions");
// Retrieve the default DataWriter QoS, from USER_QOS_PROFILES.xml
dds::pub::qos::DataWriterQos writer_qos =
dds::core::QosProvider::Default().datawriter_qos();
// If you want to change the DataWriter QoS programmatically rather
// than using the XML file, you will need to comment out these lines.
// writer_qos << Reliability::Reliable()
// << History::KeepLast(3)
// << Durability::TransientLocal();
// Create a Datawriter.
dds::pub::DataWriter<partitions> writer(publisher, topic, writer_qos);
// Create a data sample for writing.
partitions instance;
// Main loop
bool update_qos = false;
for (unsigned int samples_written = 0;
!application::shutdown_requested && samples_written < sample_count;
samples_written++) {
std::cout << "Writing partitions, count " << samples_written
<< std::endl;
// Modify and send the sample.
instance.x(samples_written);
writer.write(instance);
// Every 5 samples we will change the partition name.
// These are the partition expressions we are going to try:
// "bar", "A*", "A?C", "X*Z", "zzz" and "A*C".
if ((samples_written + 1) % 25 == 0) {
// Matches "ABC", name[1] here can match name[0] there,
// as long as there is some overlapping name.
partition_names.resize(2);
partition_names[0] = "zzz";
partition_names[1] = "A*C";
update_qos = true;
} else if ((samples_written + 1) % 25 == 20) {
// Strings that are regular expressions aren't tested for
// literal matches, so this won't match "X*Z".
partition_names[0] = "X*Z";
update_qos = true;
} else if ((samples_written + 1) % 25 == 15) {
// Matches "ABC".
partition_names[0] = "A?C";
update_qos = true;
} else if ((samples_written + 1) % 25 == 10) {
// Matches "ABC".
partition_names[0] = "A*";
update_qos = true;
} else if ((samples_written + 1) % 25 == 5) {
// No literal match for "bar".
// For the next iterations we are using only one partition.
partition_names.resize(1);
partition_names[0] = "bar";
update_qos = true;
}
// Set the new partition names to the publisher QoS.
if (update_qos) {
std::cout << "Setting partition to";
for (int i = 0; i < partition_names.size(); i++) {
std::cout << " '" << partition_names[i] << "'";
}
std::cout << std::endl;
partition.name(partition_names);
publisher.qos(publisher_qos << partition);
update_qos = false;
}
rti::util::sleep(dds::core::Duration(1));
}
}
int main(int argc, char *argv[])
{
using namespace application;
// Parse arguments and handle control-C
auto arguments = parse_arguments(argc, argv);
if (arguments.parse_result == ParseReturn::exit) {
return EXIT_SUCCESS;
} else if (arguments.parse_result == ParseReturn::failure) {
return EXIT_FAILURE;
}
setup_signal_handlers();
// Sets Connext verbosity to help debugging
rti::config::Logger::instance().verbosity(arguments.verbosity);
try {
run_publisher_application(arguments.domain_id, arguments.sample_count);
} catch (const std::exception &ex) {
// This will catch DDS exceptions
std::cerr << "Exception in run_publisher_application(): " << ex.what()
<< std::endl;
return EXIT_FAILURE;
}
// Releases the memory used by the participant factory. Optional at
// application exit
dds::domain::DomainParticipant::finalize_participant_factory();
return EXIT_SUCCESS;
}
| cxx |
rticonnextdds-examples | data/projects/rticonnextdds-examples/connext_dds/partitions/c++11/application.hpp | /*
* (c) Copyright, Real-Time Innovations, 2020. All rights reserved.
* RTI grants Licensee a license to use, modify, compile, and create derivative
* works of the software solely for use with RTI Connext DDS. Licensee may
* redistribute copies of the software provided that all such copies are subject
* to this license. The software is provided "as is", with no warranty of any
* type, including any warranty for fitness for any purpose. RTI is under no
* obligation to maintain or support the software. RTI shall not be liable for
* any incidental or consequential damages arising out of the use or inability
* to use the software.
*/
#ifndef APPLICATION_HPP
#define APPLICATION_HPP
#include <iostream>
#include <csignal>
#include <dds/core/ddscore.hpp>
namespace application {
// Catch control-C and tell application to shut down
bool shutdown_requested = false;
inline void stop_handler(int)
{
shutdown_requested = true;
std::cout << "preparing to shut down..." << std::endl;
}
inline void setup_signal_handlers()
{
signal(SIGINT, stop_handler);
signal(SIGTERM, stop_handler);
}
enum class ParseReturn {
ok,
failure,
exit
};
struct ApplicationArguments {
ParseReturn parse_result;
unsigned int domain_id;
unsigned int sample_count;
rti::config::Verbosity verbosity;
ApplicationArguments(
ParseReturn parse_result_param,
unsigned int domain_id_param,
unsigned int sample_count_param,
rti::config::Verbosity verbosity_param)
: parse_result(parse_result_param),
domain_id(domain_id_param),
sample_count(sample_count_param),
verbosity(verbosity_param) {}
};
inline void set_verbosity(
rti::config::Verbosity& verbosity,
int verbosity_value)
{
switch (verbosity_value) {
case 0:
verbosity = rti::config::Verbosity::SILENT;
break;
case 1:
verbosity = rti::config::Verbosity::EXCEPTION;
break;
case 2:
verbosity = rti::config::Verbosity::WARNING;
break;
case 3:
verbosity = rti::config::Verbosity::STATUS_ALL;
break;
default:
verbosity = rti::config::Verbosity::EXCEPTION;
break;
}
}
// Parses application arguments for example.
inline ApplicationArguments parse_arguments(int argc, char *argv[])
{
int arg_processing = 1;
bool show_usage = false;
ParseReturn parse_result = ParseReturn::ok;
unsigned int domain_id = 0;
unsigned int sample_count = (std::numeric_limits<unsigned int>::max)();
rti::config::Verbosity verbosity(rti::config::Verbosity::EXCEPTION);
while (arg_processing < argc) {
if ((argc > arg_processing + 1)
&& (strcmp(argv[arg_processing], "-d") == 0
|| strcmp(argv[arg_processing], "--domain") == 0)) {
domain_id = atoi(argv[arg_processing + 1]);
arg_processing += 2;
} else if ((argc > arg_processing + 1)
&& (strcmp(argv[arg_processing], "-s") == 0
|| strcmp(argv[arg_processing], "--sample-count") == 0)) {
sample_count = atoi(argv[arg_processing + 1]);
arg_processing += 2;
} else if ((argc > arg_processing + 1)
&& (strcmp(argv[arg_processing], "-v") == 0
|| strcmp(argv[arg_processing], "--verbosity") == 0)) {
set_verbosity(verbosity, atoi(argv[arg_processing + 1]));
arg_processing += 2;
} else if (strcmp(argv[arg_processing], "-h") == 0
|| strcmp(argv[arg_processing], "--help") == 0) {
std::cout << "Example application." << std::endl;
show_usage = true;
parse_result = ParseReturn::exit;
break;
} else {
std::cout << "Bad parameter." << std::endl;
show_usage = true;
parse_result = ParseReturn::failure;
break;
}
}
if (show_usage) {
std::cout << "Usage:\n"\
" -d, --domain <int> Domain ID this application will\n" \
" subscribe in. \n"
" Default: 0\n"\
" -s, --sample_count <int> Number of samples to receive before\n"\
" cleanly shutting down. \n"
" Default: infinite\n"
" -v, --verbosity <int> How much debugging output to show.\n"\
" Range: 0-3 \n"
" Default: 1"
<< std::endl;
}
return ApplicationArguments(parse_result, domain_id, sample_count, verbosity);
}
} // namespace application
#endif // APPLICATION_HPP | hpp |
rticonnextdds-examples | data/projects/rticonnextdds-examples/connext_dds/partitions/c++11/partitions_subscriber.cxx | /*******************************************************************************
(c) 2005-2015 Copyright, Real-Time Innovations, Inc. All rights reserved.
RTI grants Licensee a license to use, modify, compile, and create derivative
works of the Software. Licensee has the right to distribute object form only
for use with RTI products. The Software is provided "as is", with no warranty
of any type, including any warranty for fitness for any purpose. RTI is under
no obligation to maintain or support the Software. RTI shall not be liable for
any incidental or consequential damages arising out of the use or inability to
use the software.
******************************************************************************/
#include <dds/sub/ddssub.hpp>
#include <dds/core/ddscore.hpp>
#include <rti/config/Logger.hpp> // for logging
#include "partitions.hpp"
#include "application.hpp" // for command line parsing and ctrl-c
int process_data(dds::sub::DataReader<partitions> reader)
{
int count = 0;
// Take all samples
dds::sub::LoanedSamples<partitions> samples = reader.take();
for (const auto &sample : samples) {
if (sample.info().valid()) {
count++;
// After partitions match, the instance is considered new
dds::sub::status::ViewState view_state =
sample.info().state().view_state();
if (view_state == dds::sub::status::ViewState::new_view()) {
std::cout << "Found new instance" << std::endl;
}
std::cout << sample.data() << std::endl;
}
}
return count;
}
void run_subscriber_application(
unsigned int domain_id,
unsigned int sample_count)
{
// Create a participant with default QoS.
dds::domain::DomainParticipant participant(domain_id);
// Retrieve the default Subscriber QoS, from USER_QOS_PROFILES.xml
dds::sub::qos::SubscriberQos subscriber_qos =
dds::core::QosProvider::Default().subscriber_qos();
dds::core::policy::Partition partition =
subscriber_qos.policy<dds::core::policy::Partition>();
std::vector<std::string> partition_names = partition.name();
// If you want to change the Subscriber QoS programmatically rather
// than using the XML file, you will need to comment out these lines.
// partition_names[0] = "ABC";
// partition_names[1] = "X*Z";
// partition.name(partition_names);
// subscriber_qos << partition;
std::cout << "Setting partition to "
<< "'" << partition_names[0] << "', "
<< "'" << partition_names[1] << "'..." << std::endl;
// Create a subscriber.
dds::sub::Subscriber subscriber(participant, subscriber_qos);
// Create a Topic -- and automatically register the type.
dds::topic::Topic<partitions> topic(participant, "Example partitions");
// Retrieve the default DataReader QoS, from USER_QOS_PROFILES.xml
dds::sub::qos::DataReaderQos reader_qos =
dds::core::QosProvider::Default().datareader_qos();
// If you want to change the Subscriber QoS programmatically rather
// than using the XML file, you will need to comment out these lines.
// reader_qos << Reliability::Reliable()
// << History::KeepAll()
// << Durability::TransientLocal();
// Create a DataReader.
dds::sub::DataReader<partitions> reader(subscriber, topic, reader_qos);
// WaitSet will be woken when the attached condition is triggered
dds::core::cond::WaitSet waitset;
// Create a ReadCondition for any data on this reader, and add to WaitSet
unsigned int samples_read = 0;
dds::sub::cond::ReadCondition read_condition(
reader,
dds::sub::status::DataState::new_data(),
[reader, &samples_read]() {
samples_read += process_data(reader);
});
waitset += read_condition;
// Main loop
while (!application::shutdown_requested && samples_read < sample_count) {
waitset.dispatch(dds::core::Duration(4));
}
}
int main(int argc, char *argv[])
{
using namespace application;
// Parse arguments and handle control-C
auto arguments = parse_arguments(argc, argv);
if (arguments.parse_result == ParseReturn::exit) {
return EXIT_SUCCESS;
} else if (arguments.parse_result == ParseReturn::failure) {
return EXIT_FAILURE;
}
setup_signal_handlers();
// Sets Connext verbosity to help debugging
rti::config::Logger::instance().verbosity(arguments.verbosity);
try {
run_subscriber_application(arguments.domain_id, arguments.sample_count);
} catch (const std::exception &ex) {
// This will catch DDS exceptions
std::cerr << "Exception in run_subscriber_application(): " << ex.what()
<< std::endl;
return EXIT_FAILURE;
}
// Releases the memory used by the participant factory. Optional at
// application exit
dds::domain::DomainParticipant::finalize_participant_factory();
return EXIT_SUCCESS;
}
| cxx |
rticonnextdds-examples | data/projects/rticonnextdds-examples/connext_dds/waitsets/c++/waitsets_publisher.cxx | /*******************************************************************************
(c) 2005-2014 Copyright, Real-Time Innovations, Inc. All rights reserved.
RTI grants Licensee a license to use, modify, compile, and create derivative
works of the Software. Licensee has the right to distribute object form only
for use with RTI products. The Software is provided "as is", with no warranty
of any type, including any warranty for fitness for any purpose. RTI is under
no obligation to maintain or support the Software. RTI shall not be liable for
any incidental or consequential damages arising out of the use or inability to
use the software.
******************************************************************************/
/* waitsets_publisher.cxx
A publication of data of type waitsets
This file is derived from code automatically generated by the rtiddsgen
command:
rtiddsgen -language C++ -example <arch> waitsets.idl
Example publication of type waitsets automatically generated by
'rtiddsgen'. To test them follow these steps:
(1) Compile this file and the example subscription.
(2) Start the subscription with the command
objs/<arch>/waitsets_subscriber <domain_id> <sample_count>
(3) Start the publication with the command
objs/<arch>/waitsets_publisher <domain_id> <sample_count>
(4) [Optional] Specify the list of discovery initial peers and
multicast receive addresses via an environment variable or a file
(in the current working directory) called NDDS_DISCOVERY_PEERS.
You can run any number of publishers and subscribers programs, and can
add and remove them dynamically from the domain.
Example:
To run the example application on domain <domain_id>:
On Unix:
objs/<arch>/waitsets_publisher <domain_id> o
objs/<arch>/waitsets_subscriber <domain_id>
On Windows:
objs\<arch>\waitsets_publisher <domain_id>
objs\<arch>\waitsets_subscriber <domain_id>
modification history
------------ -------
*/
#include <stdio.h>
#include <stdlib.h>
#ifdef RTI_VX653
#include <vThreadsData.h>
#endif
#include "ndds/ndds_cpp.h"
#include "waitsets.h"
#include "waitsetsSupport.h"
/* Delete all entities */
static int publisher_shutdown(DDSDomainParticipant *participant)
{
DDS_ReturnCode_t retcode;
int status = 0;
if (participant != NULL) {
retcode = participant->delete_contained_entities();
if (retcode != DDS_RETCODE_OK) {
printf("delete_contained_entities error %d\n", retcode);
status = -1;
}
retcode = DDSTheParticipantFactory->delete_participant(participant);
if (retcode != DDS_RETCODE_OK) {
printf("delete_participant error %d\n", retcode);
status = -1;
}
}
/* RTI Connext provides finalize_instance() method on
domain participant factory for people who want to release memory used
by the participant factory. Uncomment the following block of code for
clean destruction of the singleton. */
/*
retcode = DDSDomainParticipantFactory::finalize_instance();
if (retcode != DDS_RETCODE_OK) {
printf("finalize_instance error %d\n", retcode);
status = -1;
}
*/
return status;
}
extern "C" int publisher_main(int domainId, int sample_count)
{
DDSDomainParticipant *participant = NULL;
DDSPublisher *publisher = NULL;
DDSTopic *topic = NULL;
DDSDataWriter *writer = NULL;
waitsetsDataWriter *waitsets_writer = NULL;
waitsets *instance = NULL;
DDS_ReturnCode_t retcode;
DDS_InstanceHandle_t instance_handle = DDS_HANDLE_NIL;
const char *type_name = NULL;
int count = 0;
/* Send a new sample every second */
DDS_Duration_t send_period = { 1, 0 };
/* To customize participant QoS, use
the configuration file USER_QOS_PROFILES.xml */
participant = DDSTheParticipantFactory->create_participant(
domainId,
DDS_PARTICIPANT_QOS_DEFAULT,
NULL /* listener */,
DDS_STATUS_MASK_NONE);
if (participant == NULL) {
printf("create_participant error\n");
publisher_shutdown(participant);
return -1;
}
/* To customize publisher QoS, use
the configuration file USER_QOS_PROFILES.xml */
publisher = participant->create_publisher(
DDS_PUBLISHER_QOS_DEFAULT,
NULL /* listener */,
DDS_STATUS_MASK_NONE);
if (publisher == NULL) {
printf("create_publisher error\n");
publisher_shutdown(participant);
return -1;
}
/* Register type before creating topic */
type_name = waitsetsTypeSupport::get_type_name();
retcode = waitsetsTypeSupport::register_type(participant, type_name);
if (retcode != DDS_RETCODE_OK) {
printf("register_type error %d\n", retcode);
publisher_shutdown(participant);
return -1;
}
/* To customize topic QoS, use
the configuration file USER_QOS_PROFILES.xml */
topic = participant->create_topic(
"Example waitsets",
type_name,
DDS_TOPIC_QOS_DEFAULT,
NULL /* listener */,
DDS_STATUS_MASK_NONE);
if (topic == NULL) {
printf("create_topic error\n");
publisher_shutdown(participant);
return -1;
}
/* To customize data writer QoS, use
the configuration file USER_QOS_PROFILES.xml */
writer = publisher->create_datawriter(
topic,
DDS_DATAWRITER_QOS_DEFAULT,
NULL,
DDS_STATUS_MASK_NONE);
if (writer == NULL) {
printf("create_datawriter error\n");
publisher_shutdown(participant);
return -1;
}
/* If you want to change the DataWriter's QoS programmatically rather than
* using the XML file, you will need to add the following lines to your
* code and comment out the create_datawriter call above.
*
* In this case, we reduce the liveliness timeout period to trigger the
* StatusCondition DDS_LIVELINESS_CHANGED_STATUS */
/*
DDS_DataWriterQos datawriter_qos;
retcode = publisher->get_default_datawriter_qos(datawriter_qos);
if (retcode != DDS_RETCODE_OK) {
printf("get_default_datawriter_qos error\n");
return -1;
}
datawriter_qos.liveliness.lease_duration.sec = 1;
datawriter_qos.liveliness.lease_duration.nanosec = 0;
writer = publisher->create_datawriter(
topic, datawriter_qos, NULL,
DDS_STATUS_MASK_NONE);
if (writer == NULL) {
printf("create_datawriter error\n");
publisher_shutdown(participant);
return -1;
}
*/
waitsets_writer = waitsetsDataWriter::narrow(writer);
if (waitsets_writer == NULL) {
printf("DataWriter narrow error\n");
publisher_shutdown(participant);
return -1;
}
/* Create data sample for writing */
instance = waitsetsTypeSupport::create_data();
if (instance == NULL) {
printf("waitsetsTypeSupport::create_data error\n");
publisher_shutdown(participant);
return -1;
}
/* For a data type that has a key, if the same instance is going to be
written multiple times, initialize the key here
and register the keyed instance prior to writing */
/*
instance_handle = waitsets_writer->register_instance(*instance);
*/
/* Main loop */
for (count = 0; (sample_count == 0) || (count < sample_count); ++count) {
printf("Writing waitsets, count %d\n", count);
/* Modify the data to be sent here */
instance->x = count;
retcode = waitsets_writer->write(*instance, instance_handle);
if (retcode != DDS_RETCODE_OK) {
printf("write error %d\n", retcode);
}
NDDSUtility::sleep(send_period);
}
/*
retcode = waitsets_writer->unregister_instance(
*instance, instance_handle);
if (retcode != DDS_RETCODE_OK) {
printf("unregister instance error %d\n", retcode);
}
*/
/* Delete data sample */
retcode = waitsetsTypeSupport::delete_data(instance);
if (retcode != DDS_RETCODE_OK) {
printf("waitsetsTypeSupport::delete_data error %d\n", retcode);
}
/* Delete all entities */
return publisher_shutdown(participant);
}
#if defined(RTI_WINCE)
int wmain(int argc, wchar_t **argv)
{
int domainId = 0;
int sample_count = 0; /* infinite loop */
if (argc >= 2) {
domainId = _wtoi(argv[1]);
}
if (argc >= 3) {
sample_count = _wtoi(argv[2]);
}
/* Uncomment this to turn on additional logging
NDDSConfigLogger::get_instance()->
set_verbosity_by_category(NDDS_CONFIG_LOG_CATEGORY_API,
NDDS_CONFIG_LOG_VERBOSITY_STATUS_ALL);
*/
return publisher_main(domainId, sample_count);
}
#elif !(defined(RTI_VXWORKS) && !defined(__RTP__)) && !defined(RTI_PSOS)
int main(int argc, char *argv[])
{
int domainId = 0;
int sample_count = 0; /* infinite loop */
if (argc >= 2) {
domainId = atoi(argv[1]);
}
if (argc >= 3) {
sample_count = atoi(argv[2]);
}
/* Uncomment this to turn on additional logging
NDDSConfigLogger::get_instance()->
set_verbosity_by_category(NDDS_CONFIG_LOG_CATEGORY_API,
NDDS_CONFIG_LOG_VERBOSITY_STATUS_ALL);
*/
return publisher_main(domainId, sample_count);
}
#endif
#ifdef RTI_VX653
const unsigned char *__ctype = *(__ctypePtrGet());
extern "C" void usrAppInit()
{
#ifdef USER_APPL_INIT
USER_APPL_INIT; /* for backwards compatibility */
#endif
/* add application specific code here */
taskSpawn(
"pub",
RTI_OSAPI_THREAD_PRIORITY_NORMAL,
0x8,
0x150000,
(FUNCPTR) publisher_main,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0);
}
#endif
| cxx |
rticonnextdds-examples | data/projects/rticonnextdds-examples/connext_dds/waitsets/c++/waitsets_subscriber.cxx | /*******************************************************************************
(c) 2005-2014 Copyright, Real-Time Innovations, Inc. All rights reserved.
RTI grants Licensee a license to use, modify, compile, and create derivative
works of the Software. Licensee has the right to distribute object form only
for use with RTI products. The Software is provided "as is", with no warranty
of any type, including any warranty for fitness for any purpose. RTI is under
no obligation to maintain or support the Software. RTI shall not be liable for
any incidental or consequential damages arising out of the use or inability to
use the software.
******************************************************************************/
/* waitsets_subscriber.cxx
A subscription example
This file is derived from code automatically generated by the rtiddsgen
command:
rtiddsgen -language C++ -example <arch> waitsets.idl
Example subscription of type waitsets automatically generated by
'rtiddsgen'. To test them follow these steps:
(1) Compile this file and the example publication.
(2) Start the subscription with the command
objs/<arch>/waitsets_subscriber <domain_id> <sample_count>
(3) Start the publication with the command
objs/<arch>/waitsets_publisher <domain_id> <sample_count>
(4) [Optional] Specify the list of discovery initial peers and
multicast receive addresses via an environment variable or a file
(in the current working directory) called NDDS_DISCOVERY_PEERS.
You can run any number of publishers and subscribers programs, and can
add and remove them dynamically from the domain.
Example:
To run the example application on domain <domain_id>:
On Unix:
objs/<arch>/waitsets_publisher <domain_id>
objs/<arch>/waitsets_subscriber <domain_id>
On Windows:
objs\<arch>\waitsets_publisher <domain_id>
objs\<arch>\waitsets_subscriber <domain_id>
modification history
------------ -------
*/
#include <stdio.h>
#include <stdlib.h>
#ifdef RTI_VX653
#include <vThreadsData.h>
#endif
#include "ndds/ndds_cpp.h"
#include "waitsets.h"
#include "waitsetsSupport.h"
/* We don't need to use listeners as we are going to use Waitsets and Conditions
* so we have removed the auto generated code for listeners here */
/* Delete all entities */
static int subscriber_shutdown(DDSDomainParticipant *participant)
{
DDS_ReturnCode_t retcode;
int status = 0;
if (participant != NULL) {
retcode = participant->delete_contained_entities();
if (retcode != DDS_RETCODE_OK) {
printf("delete_contained_entities error %d\n", retcode);
status = -1;
}
retcode = DDSTheParticipantFactory->delete_participant(participant);
if (retcode != DDS_RETCODE_OK) {
printf("delete_participant error %d\n", retcode);
status = -1;
}
}
/* RTI Connext provides the finalize_instance() method on
domain participant factory for people who want to release memory used
by the participant factory. Uncomment the following block of code for
clean destruction of the singleton. */
/*
retcode = DDSDomainParticipantFactory::finalize_instance();
if (retcode != DDS_RETCODE_OK) {
printf("finalize_instance error %d\n", retcode);
status = -1;
}
*/
return status;
}
extern "C" int subscriber_main(int domainId, int sample_count)
{
DDSDomainParticipant *participant = NULL;
DDSSubscriber *subscriber = NULL;
DDSTopic *topic = NULL;
DDSDataReader *reader = NULL;
DDS_ReturnCode_t retcode;
const char *type_name = NULL;
int count = 0;
int status = 0;
struct DDS_Duration_t wait_timeout = { 1, 500000000 };
/* To customize the participant QoS, use
the configuration file USER_QOS_PROFILES.xml */
participant = DDSTheParticipantFactory->create_participant(
domainId,
DDS_PARTICIPANT_QOS_DEFAULT,
NULL /* listener */,
DDS_STATUS_MASK_NONE);
if (participant == NULL) {
printf("create_participant error\n");
subscriber_shutdown(participant);
return -1;
}
/* To customize the subscriber QoS, use
the configuration file USER_QOS_PROFILES.xml */
subscriber = participant->create_subscriber(
DDS_SUBSCRIBER_QOS_DEFAULT,
NULL /* listener */,
DDS_STATUS_MASK_NONE);
if (subscriber == NULL) {
printf("create_subscriber error\n");
subscriber_shutdown(participant);
return -1;
}
/* Register the type before creating the topic */
type_name = waitsetsTypeSupport::get_type_name();
retcode = waitsetsTypeSupport::register_type(participant, type_name);
if (retcode != DDS_RETCODE_OK) {
printf("register_type error %d\n", retcode);
subscriber_shutdown(participant);
return -1;
}
/* To customize the topic QoS, use
the configuration file USER_QOS_PROFILES.xml */
topic = participant->create_topic(
"Example waitsets",
type_name,
DDS_TOPIC_QOS_DEFAULT,
NULL /* listener */,
DDS_STATUS_MASK_NONE);
if (topic == NULL) {
printf("create_topic error\n");
subscriber_shutdown(participant);
return -1;
}
/* To customize the data reader QoS, use
the configuration file USER_QOS_PROFILES.xml */
reader = subscriber->create_datareader(
topic,
DDS_DATAREADER_QOS_DEFAULT,
NULL,
DDS_STATUS_MASK_NONE);
if (reader == NULL) {
printf("create_datareader error\n");
subscriber_shutdown(participant);
return -1;
}
/* If you want to change the DataReader's QoS programmatically rather than
* using the XML file, you will need to add the following lines to your
* code and comment out the create_datareader call above.
*
* In this case, we reduce the liveliness timeout period to trigger the
* StatusCondition DDS_LIVELINESS_CHANGED_STATUS
*/
/*
DDS_DataReaderQos datareader_qos;
retcode = subscriber->get_default_datareader_qos(datareader_qos);
if (retcode != DDS_RETCODE_OK) {
printf("get_default_datareader_qos error\n");
return -1;
}
datareader_qos.liveliness.lease_duration.sec = 2;
datareader_qos.liveliness.lease_duration.nanosec = 0;
reader = subscriber->create_datareader(
topic, datareader_qos, NULL,
DDS_STATUS_MASK_NONE);
if (reader == NULL) {
printf("create_datareader error\n");
subscriber_shutdown(participant);
return -1;
}
*/
/* Create read condition
* ---------------------
* Note that the Read Conditions are dependent on both incoming
* data as well as sample state. Thus, this method has more
* overhead than adding a DDS_DATA_AVAILABLE_STATUS StatusCondition.
* We show it here purely for reference
*/
DDSReadCondition *read_condition = reader->create_readcondition(
DDS_NOT_READ_SAMPLE_STATE,
DDS_ANY_VIEW_STATE,
DDS_ANY_INSTANCE_STATE);
if (read_condition == NULL) {
printf("create_readcondition error\n");
subscriber_shutdown(participant);
return -1;
}
/* Get status conditions
* ---------------------
* Each entity may have an attached Status Condition. To modify the
* statuses we need to get the reader's Status Conditions first.
*/
DDSStatusCondition *status_condition = reader->get_statuscondition();
if (status_condition == NULL) {
printf("get_statuscondition error\n");
subscriber_shutdown(participant);
return -1;
}
/* Set enabled statuses
* --------------------
* Now that we have the Status Condition, we are going to enable the
* statuses we are interested in: DDS_SUBSCRIPTION_MATCHED_STATUS and
* DDS_LIVELINESS_CHANGED_STATUS.
*/
retcode = status_condition->set_enabled_statuses(
DDS_SUBSCRIPTION_MATCHED_STATUS | DDS_LIVELINESS_CHANGED_STATUS);
if (retcode != DDS_RETCODE_OK) {
printf("set_enabled_statuses error\n");
subscriber_shutdown(participant);
return -1;
}
/* Create and attach conditions to the WaitSet
* -------------------------------------------
* Finally, we create the WaitSet and attach both the Read Conditions
* and the Status Condition to it.
*/
DDSWaitSet *waitset = new DDSWaitSet();
/* Attach Read Conditions */
retcode = waitset->attach_condition(read_condition);
if (retcode != DDS_RETCODE_OK) {
printf("attach_condition error\n");
subscriber_shutdown(participant);
return -1;
}
/* Attach Status Conditions */
retcode = waitset->attach_condition(status_condition);
if (retcode != DDS_RETCODE_OK) {
printf("attach_condition error\n");
subscriber_shutdown(participant);
return -1;
}
/* Narrow the reader into your specific data type */
waitsetsDataReader *waitsets_reader = waitsetsDataReader::narrow(reader);
if (waitsets_reader == NULL) {
printf("DataReader narrow error\n");
return -1;
}
/* Main loop */
for (count = 0; (sample_count == 0) || (count < sample_count); ++count) {
DDSConditionSeq active_conditions_seq;
/* wait() blocks execution of the thread until one or more attached
* Conditions become true, or until a user-specified timeout expires.
*/
retcode = waitset->wait(active_conditions_seq, wait_timeout);
/* We get to timeout if no conditions were triggered */
if (retcode == DDS_RETCODE_TIMEOUT) {
printf("Wait timed out!! No conditions were triggered.\n");
continue;
} else if (retcode != DDS_RETCODE_OK) {
printf("wait returned error: %d\n", retcode);
break;
}
/* Get the number of active conditions */
int active_conditions = active_conditions_seq.length();
printf("Got %d active conditions\n", active_conditions);
for (int i = 0; i < active_conditions; ++i) {
/* Now we compare the current condition with the Status
* Conditions and the Read Conditions previously defined. If
* they match, we print the condition that was triggered.*/
/* Compare with Status Conditions */
if (active_conditions_seq[i] == status_condition) {
/* Get the status changes so we can check which status
* condition triggered. */
DDS_StatusMask triggeredmask =
waitsets_reader->get_status_changes();
/* Liveliness changed */
if (triggeredmask & DDS_LIVELINESS_CHANGED_STATUS) {
DDS_LivelinessChangedStatus st;
waitsets_reader->get_liveliness_changed_status(st);
printf("Liveliness changed => Active writers = %d\n",
st.alive_count);
}
/* Subscription matched */
if (triggeredmask & DDS_SUBSCRIPTION_MATCHED_STATUS) {
DDS_SubscriptionMatchedStatus st;
waitsets_reader->get_subscription_matched_status(st);
printf("Subscription matched => Cumulative matches = %d\n",
st.total_count);
}
}
/* Compare with Read Conditions */
else if (active_conditions_seq[i] == read_condition) {
/* Current conditions match our conditions to read data, so
* we can read data just like we would do in any other
* example. */
waitsetsSeq data_seq;
DDS_SampleInfoSeq info_seq;
/* You may want to call take_w_condition() or
* read_w_condition() on the Data Reader. This way you will use
* the same status masks that were set on the Read Condition.
* This is just a suggestion, you can always use
* read() or take() like in any other example.
*/
retcode = DDS_RETCODE_OK;
while (retcode != DDS_RETCODE_NO_DATA) {
retcode = waitsets_reader->take_w_condition(
data_seq,
info_seq,
DDS_LENGTH_UNLIMITED,
read_condition);
for (int j = 0; j < data_seq.length(); ++j) {
if (!info_seq[j].valid_data) {
printf("Got metadata\n");
continue;
}
waitsetsTypeSupport::print_data(&data_seq[j]);
}
waitsets_reader->return_loan(data_seq, info_seq);
}
}
}
}
/* Delete all entities */
delete waitset;
status = subscriber_shutdown(participant);
return status;
}
#if defined(RTI_WINCE)
int wmain(int argc, wchar_t **argv)
{
int domainId = 0;
int sample_count = 0; /* infinite loop */
if (argc >= 2) {
domainId = _wtoi(argv[1]);
}
if (argc >= 3) {
sample_count = _wtoi(argv[2]);
}
/* Uncomment this to turn on additional logging
NDDSConfigLogger::get_instance()->
set_verbosity_by_category(NDDS_CONFIG_LOG_CATEGORY_API,
NDDS_CONFIG_LOG_VERBOSITY_STATUS_ALL);
*/
return subscriber_main(domainId, sample_count);
}
#elif !(defined(RTI_VXWORKS) && !defined(__RTP__)) && !defined(RTI_PSOS)
int main(int argc, char *argv[])
{
int domainId = 0;
int sample_count = 0; /* infinite loop */
if (argc >= 2) {
domainId = atoi(argv[1]);
}
if (argc >= 3) {
sample_count = atoi(argv[2]);
}
/* Uncomment this to turn on additional logging
NDDSConfigLogger::get_instance()->
set_verbosity_by_category(NDDS_CONFIG_LOG_CATEGORY_API,
NDDS_CONFIG_LOG_VERBOSITY_STATUS_ALL);
*/
return subscriber_main(domainId, sample_count);
}
#endif
#ifdef RTI_VX653
const unsigned char *__ctype = *(__ctypePtrGet());
extern "C" void usrAppInit()
{
#ifdef USER_APPL_INIT
USER_APPL_INIT; /* for backwards compatibility */
#endif
/* add application specific code here */
taskSpawn(
"sub",
RTI_OSAPI_THREAD_PRIORITY_NORMAL,
0x8,
0x150000,
(FUNCPTR) subscriber_main,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0);
}
#endif
| cxx |
rticonnextdds-examples | data/projects/rticonnextdds-examples/connext_dds/waitsets/c++98/waitsets_publisher.cxx | /*******************************************************************************
(c) 2005-2014 Copyright, Real-Time Innovations, Inc. All rights reserved.
RTI grants Licensee a license to use, modify, compile, and create derivative
works of the Software. Licensee has the right to distribute object form only
for use with RTI products. The Software is provided "as is", with no warranty
of any type, including any warranty for fitness for any purpose. RTI is under
no obligation to maintain or support the Software. RTI shall not be liable for
any incidental or consequential damages arising out of the use or inability to
use the software.
******************************************************************************/
#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include "waitsets.h"
#include "waitsetsSupport.h"
#include "ndds/ndds_cpp.h"
#include "application.h"
using namespace application;
static int shutdown_participant(
DDSDomainParticipant *participant,
const char *shutdown_message,
int status);
int run_publisher_application(unsigned int domain_id, unsigned int sample_count)
{
// Send a new sample every second
DDS_Duration_t send_period = { 1, 0 };
// Start communicating in a domain, usually one participant per application
DDSDomainParticipant *participant =
DDSTheParticipantFactory->create_participant(
domain_id,
DDS_PARTICIPANT_QOS_DEFAULT,
NULL /* listener */,
DDS_STATUS_MASK_NONE);
if (participant == NULL) {
return shutdown_participant(
participant,
"create_participant error",
EXIT_FAILURE);
}
// A Publisher allows an application to create one or more DataWriters
DDSPublisher *publisher = participant->create_publisher(
DDS_PUBLISHER_QOS_DEFAULT,
NULL /* listener */,
DDS_STATUS_MASK_NONE);
if (publisher == NULL) {
return shutdown_participant(
participant,
"create_publisher error",
EXIT_FAILURE);
}
// Register the datatype to use when creating the Topic
const char *type_name = waitsetsTypeSupport::get_type_name();
DDS_ReturnCode_t retcode =
waitsetsTypeSupport::register_type(participant, type_name);
if (retcode != DDS_RETCODE_OK) {
return shutdown_participant(
participant,
"register_type error",
EXIT_FAILURE);
}
// Create a Topic with a name and a datatype
DDSTopic *topic = participant->create_topic(
"Example waitsets",
type_name,
DDS_TOPIC_QOS_DEFAULT,
NULL /* listener */,
DDS_STATUS_MASK_NONE);
if (topic == NULL) {
return shutdown_participant(
participant,
"create_topic error",
EXIT_FAILURE);
}
// This DataWriter writes data on "Example waitsets" Topic
DDSDataWriter *untyped_writer = publisher->create_datawriter(
topic,
DDS_DATAWRITER_QOS_DEFAULT,
NULL,
DDS_STATUS_MASK_NONE);
if (untyped_writer == NULL) {
return shutdown_participant(
participant,
"create_datawriter error",
EXIT_FAILURE);
}
/* If you want to change the DataWriter's QoS programmatically rather than
* using the XML file, you will need to add the following lines to your
* code and comment out the create_datawriter call above.
*
* In this case, we reduce the liveliness timeout period to trigger the
* StatusCondition DDS_LIVELINESS_CHANGED_STATUS */
/*
DDS_DataWriterQos datawriter_qos;
retcode = publisher->get_default_datawriter_qos(datawriter_qos);
if (retcode != DDS_RETCODE_OK) {
return shutdown_participant(
participant,
"get_default_datawriter_qos error",
EXIT_FAILURE);
}
datawriter_qos.liveliness.lease_duration.sec = 1;
datawriter_qos.liveliness.lease_duration.nanosec = 0;
DDSDataWriter *untyped_writer = publisher->create_datawriter(
topic, datawriter_qos, NULL,
DDS_STATUS_MASK_NONE);
if (untyped_writer == NULL) {
return shutdown_participant(
participant,
"create_datawriter error",
EXIT_FAILURE);
}
*/
waitsetsDataWriter *typed_writer =
waitsetsDataWriter::narrow(untyped_writer);
if (typed_writer == NULL) {
return shutdown_participant(
participant,
"DataWriter narrow error",
EXIT_FAILURE);
}
// Create data sample for writing
waitsets *data = waitsetsTypeSupport::create_data();
if (data == NULL) {
return shutdown_participant(
participant,
"waitsetsTypeSupport::create_data error",
EXIT_FAILURE);
}
DDS_InstanceHandle_t instance_handle = DDS_HANDLE_NIL;
/* For a data type that has a key, if the same instance is going to be
written multiple times, initialize the key here
and register the keyed instance prior to writing */
/*
instance_handle = typed_writer->register_instance(*data);
*/
// Main loop, write data
for (unsigned int samples_written = 0;
!shutdown_requested && samples_written < sample_count;
++samples_written) {
std::cout << "Writing waitsets, count " << samples_written << std::endl;
// Modify the data to be sent here
data->x = samples_written;
retcode = typed_writer->write(*data, instance_handle);
if (retcode != DDS_RETCODE_OK) {
std::cerr << "write error " << retcode << std::endl;
}
NDDSUtility::sleep(send_period);
}
/*
retcode = typed_writer->unregister_instance(
*data, instance_handle);
if (retcode != DDS_RETCODE_OK) {
std::cerr << "unregister instance error " << retcode << std::endl;
}
*/
// Delete previously allocated data, including all contained elements
retcode = waitsetsTypeSupport::delete_data(data);
if (retcode != DDS_RETCODE_OK) {
std::cerr << "waitsetsTypeSupport::delete_data error " << retcode
<< std::endl;
}
// Delete all entities (DataWriter, Topic, Publisher, DomainParticipant)
return shutdown_participant(participant, "Shutting down", EXIT_SUCCESS);
}
// Delete all entities
static int shutdown_participant(
DDSDomainParticipant *participant,
const char *shutdown_message,
int status)
{
DDS_ReturnCode_t retcode;
std::cout << shutdown_message << std::endl;
if (participant != NULL) {
// Cleanup everything created by this Participant
retcode = participant->delete_contained_entities();
if (retcode != DDS_RETCODE_OK) {
std::cerr << "delete_contained_entities error " << retcode
<< std::endl;
status = EXIT_FAILURE;
}
retcode = DDSTheParticipantFactory->delete_participant(participant);
if (retcode != DDS_RETCODE_OK) {
std::cerr << "delete_participant error " << retcode << std::endl;
status = EXIT_FAILURE;
}
}
return status;
}
int main(int argc, char *argv[])
{
// Parse arguments and handle control-C
ApplicationArguments arguments;
parse_arguments(arguments, argc, argv);
if (arguments.parse_result == PARSE_RETURN_EXIT) {
return EXIT_SUCCESS;
} else if (arguments.parse_result == PARSE_RETURN_FAILURE) {
return EXIT_FAILURE;
}
setup_signal_handlers();
// Sets Connext verbosity to help debugging
NDDSConfigLogger::get_instance()->set_verbosity(arguments.verbosity);
int status = run_publisher_application(
arguments.domain_id,
arguments.sample_count);
// Releases the memory used by the participant factory. Optional at
// application exit
DDS_ReturnCode_t retcode = DDSDomainParticipantFactory::finalize_instance();
if (retcode != DDS_RETCODE_OK) {
std::cerr << "finalize_instance error " << retcode << std::endl;
status = EXIT_FAILURE;
}
return status;
}
| cxx |
rticonnextdds-examples | data/projects/rticonnextdds-examples/connext_dds/waitsets/c++98/waitsets_subscriber.cxx | /*******************************************************************************
(c) 2005-2014 Copyright, Real-Time Innovations, Inc. All rights reserved.
RTI grants Licensee a license to use, modify, compile, and create derivative
works of the Software. Licensee has the right to distribute object form only
for use with RTI products. The Software is provided "as is", with no warranty
of any type, including any warranty for fitness for any purpose. RTI is under
no obligation to maintain or support the Software. RTI shall not be liable for
any incidental or consequential damages arising out of the use or inability to
use the software.
******************************************************************************/
#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include "waitsets.h"
#include "waitsetsSupport.h"
#include "ndds/ndds_cpp.h"
#include "application.h"
/* We don't need to use listeners as we are going to use Waitsets and Conditions
* so we have removed the auto generated code for listeners here */
using namespace application;
static int shutdown_participant(
DDSDomainParticipant *participant,
const char *shutdown_message,
int status);
int run_subscriber_application(
unsigned int domain_id,
unsigned int sample_count)
{
struct DDS_Duration_t wait_timeout = { 1, 500000000 };
// Start communicating in a domain, usually one participant per application
DDSDomainParticipant *participant =
DDSTheParticipantFactory->create_participant(
domain_id,
DDS_PARTICIPANT_QOS_DEFAULT,
NULL /* listener */,
DDS_STATUS_MASK_NONE);
if (participant == NULL) {
return shutdown_participant(
participant,
"create_participant error",
EXIT_FAILURE);
}
// A Subscriber allows an application to create one or more DataReaders
DDSSubscriber *subscriber = participant->create_subscriber(
DDS_SUBSCRIBER_QOS_DEFAULT,
NULL /* listener */,
DDS_STATUS_MASK_NONE);
if (subscriber == NULL) {
return shutdown_participant(
participant,
"create_subscriber error",
EXIT_FAILURE);
}
// Register the datatype to use when creating the Topic
const char *type_name = waitsetsTypeSupport::get_type_name();
DDS_ReturnCode_t retcode =
waitsetsTypeSupport::register_type(participant, type_name);
if (retcode != DDS_RETCODE_OK) {
return shutdown_participant(
participant,
"register_type error",
EXIT_FAILURE);
}
// Create a Topic with a name and a datatype
DDSTopic *topic = participant->create_topic(
"Example waitsets",
type_name,
DDS_TOPIC_QOS_DEFAULT,
NULL /* listener */,
DDS_STATUS_MASK_NONE);
if (topic == NULL) {
return shutdown_participant(
participant,
"create_topic error",
EXIT_FAILURE);
}
// This DataReader reads data on "Example waitsets" Topic
DDSDataReader *untyped_reader = subscriber->create_datareader(
topic,
DDS_DATAREADER_QOS_DEFAULT,
NULL,
DDS_STATUS_MASK_NONE);
if (untyped_reader == NULL) {
return shutdown_participant(
participant,
"create_datareader error",
EXIT_FAILURE);
}
/* If you want to change the DataReader's QoS programmatically rather than
* using the XML file, you will need to add the following lines to your
* code and comment out the create_datareader call above.
*
* In this case, we reduce the liveliness timeout period to trigger the
* StatusCondition DDS_LIVELINESS_CHANGED_STATUS
*/
/*
DDS_DataReaderQos datareader_qos;
retcode = subscriber->get_default_datareader_qos(datareader_qos);
if (retcode != DDS_RETCODE_OK) {
return shutdown_participant(
participant,
"get_default_datareader_qos error",
EXIT_FAILURE);
}
datareader_qos.liveliness.lease_duration.sec = 2;
datareader_qos.liveliness.lease_duration.nanosec = 0;
DDSDataReader *untyped_reader = subscriber->create_datareader(
topic, datareader_qos, NULL,
DDS_STATUS_MASK_NONE);
if (untyped_reader == NULL) {
return shutdown_participant(
participant,
"create_datareader error",
EXIT_FAILURE);
}
*/
/* Create read condition
* ---------------------
* Note that the Read Conditions are dependent on both incoming
* data as well as sample state. Thus, this method has more
* overhead than adding a DDS_DATA_AVAILABLE_STATUS StatusCondition.
* We show it here purely for reference
*/
DDSReadCondition *read_condition = untyped_reader->create_readcondition(
DDS_NOT_READ_SAMPLE_STATE,
DDS_ANY_VIEW_STATE,
DDS_ANY_INSTANCE_STATE);
if (read_condition == NULL) {
return shutdown_participant(
participant,
"create_readcondition error",
EXIT_FAILURE);
}
/* Get status conditions
* ---------------------
* Each entity may have an attached Status Condition. To modify the
* statuses we need to get the reader's Status Conditions first.
*/
DDSStatusCondition *status_condition =
untyped_reader->get_statuscondition();
if (status_condition == NULL) {
return shutdown_participant(
participant,
"get_statuscondition error",
EXIT_FAILURE);
}
/* Set enabled statuses
* --------------------
* Now that we have the Status Condition, we are going to enable the
* statuses we are interested in: DDS_SUBSCRIPTION_MATCHED_STATUS and
* DDS_LIVELINESS_CHANGED_STATUS.
*/
retcode = status_condition->set_enabled_statuses(
DDS_SUBSCRIPTION_MATCHED_STATUS | DDS_LIVELINESS_CHANGED_STATUS);
if (retcode != DDS_RETCODE_OK) {
return shutdown_participant(
participant,
"set_enabled_statuses error",
EXIT_FAILURE);
}
/* Create and attach conditions to the WaitSet
* -------------------------------------------
* Finally, we create the WaitSet and attach both the Read Conditions
* and the Status Condition to it.
*/
DDSWaitSet *waitset = new DDSWaitSet();
// Attach Read Conditions
retcode = waitset->attach_condition(read_condition);
if (retcode != DDS_RETCODE_OK) {
return shutdown_participant(
participant,
"attach_condition error",
EXIT_FAILURE);
}
// Attach Status Conditions
retcode = waitset->attach_condition(status_condition);
if (retcode != DDS_RETCODE_OK) {
return shutdown_participant(
participant,
"attach_condition error",
EXIT_FAILURE);
}
// Narrow the reader into your specific data type
waitsetsDataReader *typed_reader =
waitsetsDataReader::narrow(untyped_reader);
if (typed_reader == NULL) {
return shutdown_participant(
participant,
"DataReader narrow error",
EXIT_FAILURE);
}
// Main loop. Wait for data to arrive, and process when it arrives
unsigned int samples_read = 0;
while (!shutdown_requested && samples_read < sample_count) {
DDSConditionSeq active_conditions_seq;
/* wait() blocks execution of the thread until one or more attached
* Conditions become true, or until a user-specified timeout expires.
*/
retcode = waitset->wait(active_conditions_seq, wait_timeout);
// We get to timeout if no conditions were triggered
if (retcode == DDS_RETCODE_TIMEOUT) {
std::cout << "Wait timed out!! No conditions were triggered.\n";
continue;
} else if (retcode != DDS_RETCODE_OK) {
std::cerr << "wait returned error: " << retcode << std::endl;
break;
}
// Get the number of active conditions
int active_conditions = active_conditions_seq.length();
std::cout << "Got " << active_conditions << " active conditions\n";
for (int i = 0; i < active_conditions; ++i) {
/* Now we compare the current condition with the Status
* Conditions and the Read Conditions previously defined. If
* they match, we print the condition that was triggered.*/
// Compare with Status Conditions
if (active_conditions_seq[i] == status_condition) {
/* Get the status changes so we can check which status
* condition triggered. */
DDS_StatusMask triggeredmask =
typed_reader->get_status_changes();
// Liveliness changed
if (triggeredmask & DDS_LIVELINESS_CHANGED_STATUS) {
DDS_LivelinessChangedStatus st;
typed_reader->get_liveliness_changed_status(st);
std::cout << "Liveliness changed => Active writers = "
<< st.alive_count << std::endl;
}
// Subscription matched
if (triggeredmask & DDS_SUBSCRIPTION_MATCHED_STATUS) {
DDS_SubscriptionMatchedStatus st;
typed_reader->get_subscription_matched_status(st);
std::cout << "Subscription matched => Cumulative matches = "
<< st.total_count << std::endl;
}
}
// Compare with Read Conditions
else if (active_conditions_seq[i] == read_condition) {
/* Current conditions match our conditions to read data, so
* we can read data just like we would do in any other
* example. */
waitsetsSeq data_seq;
DDS_SampleInfoSeq info_seq;
/* You may want to call take_w_condition() or
* read_w_condition() on the Data Reader. This way you will use
* the same status masks that were set on the Read Condition.
* This is just a suggestion, you can always use
* read() or take() like in any other example.
*/
retcode = DDS_RETCODE_OK;
while (retcode != DDS_RETCODE_NO_DATA) {
retcode = typed_reader->take_w_condition(
data_seq,
info_seq,
DDS_LENGTH_UNLIMITED,
read_condition);
for (int j = 0; j < data_seq.length(); ++j) {
if (!info_seq[j].valid_data) {
std::cout << "Got metadata\n";
continue;
}
samples_read++;
waitsetsTypeSupport::print_data(&data_seq[j]);
}
typed_reader->return_loan(data_seq, info_seq);
}
}
}
}
// Cleanup
return shutdown_participant(participant, "Shutting down", 0);
}
// Delete all entities
static int shutdown_participant(
DDSDomainParticipant *participant,
const char *shutdown_message,
int status)
{
DDS_ReturnCode_t retcode;
std::cout << shutdown_message << std::endl;
if (participant != NULL) {
// Cleanup everything created by this Participant
retcode = participant->delete_contained_entities();
if (retcode != DDS_RETCODE_OK) {
std::cerr << "delete_contained_entities error" << retcode
<< std::endl;
status = EXIT_FAILURE;
}
retcode = DDSTheParticipantFactory->delete_participant(participant);
if (retcode != DDS_RETCODE_OK) {
std::cerr << "delete_participant error" << retcode << std::endl;
status = EXIT_FAILURE;
}
}
return status;
}
int main(int argc, char *argv[])
{
// Parse arguments and handle control-C
ApplicationArguments arguments;
parse_arguments(arguments, argc, argv);
if (arguments.parse_result == PARSE_RETURN_EXIT) {
return EXIT_SUCCESS;
} else if (arguments.parse_result == PARSE_RETURN_FAILURE) {
return EXIT_FAILURE;
}
setup_signal_handlers();
// Sets Connext verbosity to help debugging
NDDSConfigLogger::get_instance()->set_verbosity(arguments.verbosity);
int status = run_subscriber_application(
arguments.domain_id,
arguments.sample_count);
// Releases the memory used by the participant factory. Optional at
// application exit
DDS_ReturnCode_t retcode = DDSDomainParticipantFactory::finalize_instance();
if (retcode != DDS_RETCODE_OK) {
std::cerr << "finalize_instance error" << retcode << std::endl;
status = EXIT_FAILURE;
}
return status;
}
| cxx |
rticonnextdds-examples | data/projects/rticonnextdds-examples/connext_dds/waitsets/c++98/application.h | /*
* (c) Copyright, Real-Time Innovations, 2020. All rights reserved.
* RTI grants Licensee a license to use, modify, compile, and create derivative
* works of the software solely for use with RTI Connext DDS. Licensee may
* redistribute copies of the software provided that all such copies are subject
* to this license. The software is provided "as is", with no warranty of any
* type, including any warranty for fitness for any purpose. RTI is under no
* obligation to maintain or support the software. RTI shall not be liable for
* any incidental or consequential damages arising out of the use or inability
* to use the software.
*/
#ifndef APPLICATION_H
#define APPLICATION_H
#include <iostream>
#include <csignal>
#include <climits>
namespace application {
// Catch control-C and tell application to shut down
bool shutdown_requested = false;
inline void stop_handler(int)
{
shutdown_requested = true;
std::cout << "preparing to shut down..." << std::endl;
}
inline void setup_signal_handlers()
{
signal(SIGINT, stop_handler);
signal(SIGTERM, stop_handler);
}
enum ParseReturn { PARSE_RETURN_OK, PARSE_RETURN_FAILURE, PARSE_RETURN_EXIT };
struct ApplicationArguments {
ParseReturn parse_result;
unsigned int domain_id;
unsigned int sample_count;
NDDS_Config_LogVerbosity verbosity;
};
inline void set_verbosity(ApplicationArguments &arguments, int verbosity)
{
switch (verbosity) {
case 0:
arguments.verbosity = NDDS_CONFIG_LOG_VERBOSITY_SILENT;
break;
case 1:
arguments.verbosity = NDDS_CONFIG_LOG_VERBOSITY_ERROR;
break;
case 2:
arguments.verbosity = NDDS_CONFIG_LOG_VERBOSITY_WARNING;
break;
case 3:
arguments.verbosity = NDDS_CONFIG_LOG_VERBOSITY_STATUS_ALL;
break;
default:
arguments.verbosity = NDDS_CONFIG_LOG_VERBOSITY_ERROR;
break;
}
}
// Parses application arguments for example. Returns whether to exit.
inline void parse_arguments(
ApplicationArguments &arguments,
int argc,
char *argv[])
{
int arg_processing = 1;
bool show_usage = false;
arguments.domain_id = 0;
arguments.sample_count = INT_MAX;
arguments.verbosity = NDDS_CONFIG_LOG_VERBOSITY_ERROR;
arguments.parse_result = PARSE_RETURN_OK;
while (arg_processing < argc) {
if ((argc > arg_processing + 1)
&& (strcmp(argv[arg_processing], "-d") == 0
|| strcmp(argv[arg_processing], "--domain") == 0)) {
arguments.domain_id = atoi(argv[arg_processing + 1]);
arg_processing += 2;
} else if (
(argc > arg_processing + 1)
&& (strcmp(argv[arg_processing], "-s") == 0
|| strcmp(argv[arg_processing], "--sample-count") == 0)) {
arguments.sample_count = atoi(argv[arg_processing + 1]);
arg_processing += 2;
} else if (
(argc > arg_processing + 1)
&& (strcmp(argv[arg_processing], "-v") == 0
|| strcmp(argv[arg_processing], "--verbosity") == 0)) {
set_verbosity(arguments, atoi(argv[arg_processing + 1]));
arg_processing += 2;
} else if (
strcmp(argv[arg_processing], "-h") == 0
|| strcmp(argv[arg_processing], "--help") == 0) {
std::cout << "Example application." << std::endl;
show_usage = true;
arguments.parse_result = PARSE_RETURN_EXIT;
break;
} else {
std::cout << "Bad parameter." << std::endl;
show_usage = true;
arguments.parse_result = PARSE_RETURN_FAILURE;
break;
}
}
if (show_usage) {
std::cout << "Usage:\n"
" -d, --domain <int> Domain ID this "
"application will\n"
" subscribe in. \n"
" Default: 0\n"
" -s, --sample_count <int> Number of samples to "
"receive before\n"
" cleanly shutting down. \n"
" Default: infinite\n"
" -v, --verbosity <int> How much debugging output "
"to show.\n"
" Range: 0-3 \n"
" Default: 1"
<< std::endl;
}
}
} // namespace application
#endif // APPLICATION_H
| h |
rticonnextdds-examples | data/projects/rticonnextdds-examples/connext_dds/waitsets/c/waitsets_subscriber.c | /*******************************************************************************
(c) 2005-2014 Copyright, Real-Time Innovations, Inc. All rights reserved.
RTI grants Licensee a license to use, modify, compile, and create derivative
works of the Software. Licensee has the right to distribute object form only
for use with RTI products. The Software is provided "as is", with no warranty
of any type, including any warranty for fitness for any purpose. RTI is under
no obligation to maintain or support the Software. RTI shall not be liable for
any incidental or consequential damages arising out of the use or inability to
use the software.
******************************************************************************/
/* waitsets_subscriber.c
A subscription example
This file is derived from code automatically generated by the rtiddsgen
command:
rtiddsgen -language C -example <arch> waitsets.idl
Example subscription of type waitsets automatically generated by
'rtiddsgen'. To test them, follow these steps:
(1) Compile this file and the example publication.
(2) Start the subscription with the command
objs/<arch>/waitsets_subscriber <domain_id> <sample_count>
(3) Start the publication with the command
objs/<arch>/waitsets_publisher <domain_id> <sample_count>
(4) [Optional] Specify the list of discovery initial peers and
multicast receive addresses via an environment variable or a file
(in the current working directory) called NDDS_DISCOVERY_PEERS.
You can run any number of publishers and subscribers programs, and can
add and remove them dynamically from the domain.
Example:
To run the example application on domain <domain_id>:
On UNIX systems:
objs/<arch>/waitsets_publisher <domain_id>
objs/<arch>/waitsets_subscriber <domain_id>
On Windows systems:
objs\<arch>\waitsets_publisher <domain_id>
objs\<arch>\waitsets_subscriber <domain_id>
modification history
------------ -------
*/
#include "ndds/ndds_c.h"
#include "waitsets.h"
#include "waitsetsSupport.h"
#include <stdio.h>
#include <stdlib.h>
/* We don't need to use listeners as we are going to use Waitsets and Conditions
* so we have removed the auto generated code for listeners here */
/* Delete all entities */
static int subscriber_shutdown(DDS_DomainParticipant *participant)
{
DDS_ReturnCode_t retcode;
int status = 0;
if (participant != NULL) {
retcode = DDS_DomainParticipant_delete_contained_entities(participant);
if (retcode != DDS_RETCODE_OK) {
printf("delete_contained_entities error %d\n", retcode);
status = -1;
}
retcode = DDS_DomainParticipantFactory_delete_participant(
DDS_TheParticipantFactory,
participant);
if (retcode != DDS_RETCODE_OK) {
printf("delete_participant error %d\n", retcode);
status = -1;
}
}
/* RTI Connext provides the finalize_instance() method on
domain participant factory for users who want to release memory used
by the participant factory. Uncomment the following block of code for
clean destruction of the singleton. */
/*
retcode = DDS_DomainParticipantFactory_finalize_instance();
if (retcode != DDS_RETCODE_OK) {
printf("finalize_instance error %d\n", retcode);
status = -1;
}
*/
return status;
}
static int subscriber_main(int domainId, int sample_count)
{
DDS_DomainParticipant *participant = NULL;
DDS_Subscriber *subscriber = NULL;
DDS_Topic *topic = NULL;
DDS_DataReader *reader = NULL;
DDS_ReturnCode_t retcode;
const char *type_name = NULL;
int count = 0;
DDS_ReadCondition *read_condition;
DDS_StatusCondition *status_condition;
DDS_WaitSet *waitset = NULL;
waitsetsDataReader *waitsets_reader = NULL;
struct DDS_Duration_t wait_timeout = { 1, 500000000 };
/* To change the DataReader's QoS programmatically you will need to
* declare and initialize datareader_qos here. */
/* struct DDS_DataReaderQos datareader_qos = DDS_DataReaderQos_INITIALIZER;
*/
struct waitsetsSeq data_seq = DDS_SEQUENCE_INITIALIZER;
struct DDS_SampleInfoSeq info_seq = DDS_SEQUENCE_INITIALIZER;
/* To customize participant QoS, use
the configuration file USER_QOS_PROFILES.xml */
participant = DDS_DomainParticipantFactory_create_participant(
DDS_TheParticipantFactory,
domainId,
&DDS_PARTICIPANT_QOS_DEFAULT,
NULL /* listener */,
DDS_STATUS_MASK_NONE);
if (participant == NULL) {
printf("create_participant error\n");
subscriber_shutdown(participant);
return -1;
}
/* To customize subscriber QoS, use
the configuration file USER_QOS_PROFILES.xml */
subscriber = DDS_DomainParticipant_create_subscriber(
participant,
&DDS_SUBSCRIBER_QOS_DEFAULT,
NULL /* listener */,
DDS_STATUS_MASK_NONE);
if (subscriber == NULL) {
printf("create_subscriber error\n");
subscriber_shutdown(participant);
return -1;
}
/* Register the type before creating the topic */
type_name = waitsetsTypeSupport_get_type_name();
retcode = waitsetsTypeSupport_register_type(participant, type_name);
if (retcode != DDS_RETCODE_OK) {
printf("register_type error %d\n", retcode);
subscriber_shutdown(participant);
return -1;
}
/* To customize topic QoS, use
the configuration file USER_QOS_PROFILES.xml */
topic = DDS_DomainParticipant_create_topic(
participant,
"Example waitsets",
type_name,
&DDS_TOPIC_QOS_DEFAULT,
NULL /* listener */,
DDS_STATUS_MASK_NONE);
if (topic == NULL) {
printf("create_topic error\n");
subscriber_shutdown(participant);
return -1;
}
/* To customize data reader QoS, use
the configuration file USER_QOS_PROFILES.xml */
reader = DDS_Subscriber_create_datareader(
subscriber,
DDS_Topic_as_topicdescription(topic),
&DDS_DATAREADER_QOS_DEFAULT,
NULL,
DDS_STATUS_MASK_NONE);
if (reader == NULL) {
printf("create_datareader error\n");
subscriber_shutdown(participant);
return -1;
}
/* If you want to change the DataReader's QoS programmatically rather than
* using the XML file, you will need to add the following lines to your
* code and comment out the create_datareader call above.
*
* In this case, we reduce the liveliness timeout period to trigger the
* StatusCondition DDS_LIVELINESS_CHANGED_STATUS
*/
/*
retcode = DDS_Subscriber_get_default_datareader_qos(subscriber,
&datareader_qos);
if (retcode != DDS_RETCODE_OK) {
printf("get_default_datareader_qos error\n");
return -1;
}
datareader_qos.liveliness.lease_duration.sec = 2;
datareader_qos.liveliness.lease_duration.nanosec = 0;
reader = DDS_Subscriber_create_datareader(
subscriber, DDS_Topic_as_topicdescription(topic),
&datareader_qos, NULL, DDS_STATUS_MASK_NONE);
if (reader == NULL) {
printf("create_datareader error\n");
subscriber_shutdown(participant);
return -1;
}
*/
/* Create read condition
* ---------------------
* Note that the Read Conditions are dependent on both incoming
* data as well as sample state. Thus, this method has more
* overhead than adding a DDS_DATA_AVAILABLE_STATUS StatusCondition.
* We show it here purely for reference
*/
read_condition = DDS_DataReader_create_readcondition(
reader,
DDS_NOT_READ_SAMPLE_STATE,
DDS_ANY_VIEW_STATE,
DDS_ANY_INSTANCE_STATE);
if (read_condition == NULL) {
printf("create_readcondition error\n");
subscriber_shutdown(participant);
return -1;
}
/* Get status conditions
* ---------------------
* Each entity may have an attached Status Condition. To modify the
* statuses we need to get the reader's Status Conditions first.
*/
status_condition = DDS_Entity_get_statuscondition((DDS_Entity *) reader);
if (status_condition == NULL) {
printf("get_statuscondition error\n");
subscriber_shutdown(participant);
return -1;
}
/* Set enabled statuses
* --------------------
* Now that we have the Status Condition, we are going to enable the
* statuses we are interested in: DDS_SUBSCRIPTION_MATCHED_STATUS and
* DDS_LIVELINESS_CHANGED_STATUS.
*/
retcode = DDS_StatusCondition_set_enabled_statuses(
status_condition,
DDS_SUBSCRIPTION_MATCHED_STATUS | DDS_LIVELINESS_CHANGED_STATUS);
if (retcode != DDS_RETCODE_OK) {
printf("set_enabled_statuses error\n");
subscriber_shutdown(participant);
return -1;
}
/* Create and attach conditions to the WaitSet
* -------------------------------------------
* Finally, we create the WaitSet and attach both the Read Conditions
* and the Status Condition to it.
*/
waitset = DDS_WaitSet_new();
if (waitset == NULL) {
printf("create waitset error\n");
subscriber_shutdown(participant);
return -1;
}
/* Attach Read Conditions */
retcode = DDS_WaitSet_attach_condition(
waitset,
(DDS_Condition *) read_condition);
if (retcode != DDS_RETCODE_OK) {
printf("attach_condition error\n");
subscriber_shutdown(participant);
return -1;
}
/* Attach Status Conditions */
retcode = DDS_WaitSet_attach_condition(
waitset,
(DDS_Condition *) status_condition);
if (retcode != DDS_RETCODE_OK) {
printf("attach_condition error\n");
subscriber_shutdown(participant);
return -1;
}
/* Narrow the reader into your specific data type */
waitsets_reader = waitsetsDataReader_narrow(reader);
if (waitsets_reader == NULL) {
printf("DataReader narrow error\n");
return -1;
}
/* Main loop */
for (count = 0; (sample_count == 0) || (count < sample_count); ++count) {
struct DDS_ConditionSeq active_conditions_seq =
DDS_SEQUENCE_INITIALIZER;
int i, j, active_conditions;
/* wait() blocks execution of the thread until one or more attached
* Conditions become true, or until a user-specified timeout expires.
*/
retcode = DDS_WaitSet_wait(
waitset, /* waitset */
&active_conditions_seq, /* active conditions sequence */
&wait_timeout); /* timeout */
/* We get to timeout if no conditions were triggered */
if (retcode == DDS_RETCODE_TIMEOUT) {
printf("Wait timed out!! No conditions were triggered.\n");
continue;
} else if (retcode != DDS_RETCODE_OK) {
printf("wait returned error: %d", retcode);
break;
}
/* Get the number of active conditions */
active_conditions = DDS_ConditionSeq_get_length(&active_conditions_seq);
printf("Got %d active conditions\n", active_conditions);
for (i = 0; i < active_conditions; ++i) {
/* Get the current condition and compare it with the Status
* Conditions and the Read Conditions previously defined. If
* they match, we print the condition that was triggered.*/
DDS_Condition *current_condition =
DDS_ConditionSeq_get(&active_conditions_seq, i);
/* Compare with Status Conditions */
if (current_condition == (DDS_Condition *) status_condition) {
DDS_StatusMask triggeredmask;
/* Get the status changes so we can check which status
* condition triggered. */
triggeredmask = DDS_Entity_get_status_changes(
(DDS_Entity *) waitsets_reader);
/* Liveliness changed */
if (triggeredmask & DDS_LIVELINESS_CHANGED_STATUS) {
struct DDS_LivelinessChangedStatus st;
DDS_DataReader_get_liveliness_changed_status(
(DDS_DataReader *) waitsets_reader,
&st);
printf("Liveliness changed => Active writers = %d\n",
st.alive_count);
}
/* Subscription matched */
if (triggeredmask & DDS_SUBSCRIPTION_MATCHED_STATUS) {
struct DDS_SubscriptionMatchedStatus st;
DDS_DataReader_get_subscription_matched_status(
(DDS_DataReader *) waitsets_reader,
&st);
printf("Subscription matched => Cumulative matches = %d\n",
st.total_count);
}
}
/* Compare with Read Conditions */
else if (current_condition == (DDS_Condition *) read_condition) {
printf("Read condition\n");
/* Current conditions match our conditions to read data, so
* we can read data just like we would do in any other
* example. We use data_seq and info_seq to this task
* defined at start.
*/
/* You may want to call take_w_condition() or
* read_w_condition() on the Data Reader. This way you will use
* the same status masks that were set on the Read Condition.
* This is just a suggestion, you can always use
* read() or take() like in any other example.
*/
retcode = DDS_RETCODE_OK;
while (retcode != DDS_RETCODE_NO_DATA) {
retcode = waitsetsDataReader_take_w_condition(
waitsets_reader,
&data_seq,
&info_seq,
DDS_LENGTH_UNLIMITED,
read_condition);
for (j = 0; j < waitsetsSeq_get_length(&data_seq); ++j) {
if (!DDS_SampleInfoSeq_get_reference(&info_seq, j)
->valid_data) {
printf("Got metadata\n");
continue;
}
waitsetsTypeSupport_print_data(
waitsetsSeq_get_reference(&data_seq, j));
}
waitsetsDataReader_return_loan(
waitsets_reader,
&data_seq,
&info_seq);
}
}
}
}
/* Delete all entities */
retcode = DDS_WaitSet_delete(waitset);
if (retcode != DDS_RETCODE_OK) {
printf("delete waitset error %d\n", retcode);
}
/* Cleanup and delete all entities */
return subscriber_shutdown(participant);
}
#if defined(RTI_WINCE)
int wmain(int argc, wchar_t **argv)
{
int domainId = 0;
int sample_count = 0; /* infinite loop */
if (argc >= 2) {
domainId = _wtoi(argv[1]);
}
if (argc >= 3) {
sample_count = _wtoi(argv[2]);
}
/* Uncomment this to turn on additional logging
NDDS_Config_Logger_set_verbosity_by_category(
NDDS_Config_Logger_get_instance(),
NDDS_CONFIG_LOG_CATEGORY_API,
NDDS_CONFIG_LOG_VERBOSITY_STATUS_ALL);
*/
return subscriber_main(domainId, sample_count);
}
#elif !(defined(RTI_VXWORKS) && !defined(__RTP__)) && !defined(RTI_PSOS)
int main(int argc, char *argv[])
{
int domainId = 0;
int sample_count = 0; /* infinite loop */
if (argc >= 2) {
domainId = atoi(argv[1]);
}
if (argc >= 3) {
sample_count = atoi(argv[2]);
}
/* Uncomment this to turn on additional logging
NDDS_Config_Logger_set_verbosity_by_category(
NDDS_Config_Logger_get_instance(),
NDDS_CONFIG_LOG_CATEGORY_API,
NDDS_CONFIG_LOG_VERBOSITY_STATUS_ALL);
*/
return subscriber_main(domainId, sample_count);
}
#endif
#ifdef RTI_VX653
const unsigned char *__ctype = NULL;
void usrAppInit()
{
#ifdef USER_APPL_INIT
USER_APPL_INIT; /* for backwards compatibility */
#endif
/* add application specific code here */
taskSpawn(
"sub",
RTI_OSAPI_THREAD_PRIORITY_NORMAL,
0x8,
0x150000,
(FUNCPTR) subscriber_main,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0);
}
#endif
| c |
rticonnextdds-examples | data/projects/rticonnextdds-examples/connext_dds/waitsets/c/waitsets_publisher.c | /*******************************************************************************
(c) 2005-2014 Copyright, Real-Time Innovations, Inc. All rights reserved.
RTI grants Licensee a license to use, modify, compile, and create derivative
works of the Software. Licensee has the right to distribute object form only
for use with RTI products. The Software is provided "as is", with no warranty
of any type, including any warranty for fitness for any purpose. RTI is under
no obligation to maintain or support the Software. RTI shall not be liable for
any incidental or consequential damages arising out of the use or inability to
use the software.
******************************************************************************/
/* waitsets_publisher.c
A publication of data of type waitsets
This file is derived from code automatically generated by the rtiddsgen
command:
rtiddsgen -language C -example <arch> waitsets.idl
Example publication of type waitsets automatically generated by
'rtiddsgen'. To test them follow these steps:
(1) Compile this file and the example subscription.
(2) Start the subscription with the command
objs/<arch>/waitsets_subscriber <domain_id> <sample_count>
(3) Start the publication with the command
objs/<arch>/waitsets_publisher <domain_id> <sample_count>
(4) [Optional] Specify the list of discovery initial peers and
multicast receive addresses via an environment variable or a file
(in the current working directory) called NDDS_DISCOVERY_PEERS.
You can run any number of publishers and subscribers programs, and can
add and remove them dynamically from the domain.
Example:
To run the example application on domain <domain_id>:
On Unix:
objs/<arch>/waitsets_publisher <domain_id>
objs/<arch>/waitsets_subscriber <domain_id>
On Windows:
objs\<arch>\waitsets_publisher <domain_id>
objs\<arch>\waitsets_subscriber <domain_id>
modification history
------------ -------
*/
#include "ndds/ndds_c.h"
#include "waitsets.h"
#include "waitsetsSupport.h"
#include <stdio.h>
#include <stdlib.h>
/* Delete all entities */
static int publisher_shutdown(DDS_DomainParticipant *participant)
{
DDS_ReturnCode_t retcode;
int status = 0;
if (participant != NULL) {
retcode = DDS_DomainParticipant_delete_contained_entities(participant);
if (retcode != DDS_RETCODE_OK) {
printf("delete_contained_entities error %d\n", retcode);
status = -1;
}
retcode = DDS_DomainParticipantFactory_delete_participant(
DDS_TheParticipantFactory,
participant);
if (retcode != DDS_RETCODE_OK) {
printf("delete_participant error %d\n", retcode);
status = -1;
}
}
/* RTI Connext provides finalize_instance() method on
domain participant factory for people who want to release memory used
by the participant factory. Uncomment the following block of code for
clean destruction of the singleton. */
/*
retcode = DDS_DomainParticipantFactory_finalize_instance();
if (retcode != DDS_RETCODE_OK) {
printf("finalize_instance error %d\n", retcode);
status = -1;
}
*/
return status;
}
static int publisher_main(int domainId, int sample_count)
{
DDS_DomainParticipant *participant = NULL;
DDS_Publisher *publisher = NULL;
DDS_Topic *topic = NULL;
DDS_DataWriter *writer = NULL;
waitsetsDataWriter *waitsets_writer = NULL;
waitsets *instance = NULL;
DDS_ReturnCode_t retcode;
DDS_InstanceHandle_t instance_handle = DDS_HANDLE_NIL;
const char *type_name = NULL;
int count = 0;
/* We publish a new sample every second */
struct DDS_Duration_t send_period = { 1, 0 };
/* To change the DataWriter's QoS programmatically you will need to
* declare and initialize datawriter_qos here. */
/* struct DDS_DataWriterQos datawriter_qos = DDS_DataWriterQos_INITIALIZER;
*/
/* To customize participant QoS, use
the configuration file USER_QOS_PROFILES.xml */
participant = DDS_DomainParticipantFactory_create_participant(
DDS_TheParticipantFactory,
domainId,
&DDS_PARTICIPANT_QOS_DEFAULT,
NULL /* listener */,
DDS_STATUS_MASK_NONE);
if (participant == NULL) {
printf("create_participant error\n");
publisher_shutdown(participant);
return -1;
}
/* To customize publisher QoS, use
the configuration file USER_QOS_PROFILES.xml */
publisher = DDS_DomainParticipant_create_publisher(
participant,
&DDS_PUBLISHER_QOS_DEFAULT,
NULL /* listener */,
DDS_STATUS_MASK_NONE);
if (publisher == NULL) {
printf("create_publisher error\n");
publisher_shutdown(participant);
return -1;
}
/* Register type before creating topic */
type_name = waitsetsTypeSupport_get_type_name();
retcode = waitsetsTypeSupport_register_type(participant, type_name);
if (retcode != DDS_RETCODE_OK) {
printf("register_type error %d\n", retcode);
publisher_shutdown(participant);
return -1;
}
/* To customize topic QoS, use
the configuration file USER_QOS_PROFILES.xml */
topic = DDS_DomainParticipant_create_topic(
participant,
"Example waitsets",
type_name,
&DDS_TOPIC_QOS_DEFAULT,
NULL /* listener */,
DDS_STATUS_MASK_NONE);
if (topic == NULL) {
printf("create_topic error\n");
publisher_shutdown(participant);
return -1;
}
/* To customize data writer QoS, use
the configuration file USER_QOS_PROFILES.xml */
writer = DDS_Publisher_create_datawriter(
publisher,
topic,
&DDS_DATAWRITER_QOS_DEFAULT,
NULL,
DDS_STATUS_MASK_NONE);
if (writer == NULL) {
printf("create_datawriter error\n");
publisher_shutdown(participant);
return -1;
}
/* If you want to change the DataWriter's QoS programmatically rather than
* using the XML file, you will need to add the following lines to your
* code and comment out the create_datawriter call above.
*
* In this case, we reduce the liveliness timeout period to trigger the
* StatusCondition DDS_LIVELINESS_CHANGED_STATUS */
/*
retcode = DDS_Publisher_get_default_datawriter_qos(publisher,
&datawriter_qos);
if (retcode != DDS_RETCODE_OK) {
printf("get_default_datawriter_qos error\n");
return -1;
}
datawriter_qos.liveliness.lease_duration.sec = 1;
datawriter_qos.liveliness.lease_duration.nanosec = 0;
writer = DDS_Publisher_create_datawriter(
publisher, topic,
&datawriter_qos, NULL, DDS_STATUS_MASK_NONE);
if (writer == NULL) {
printf("create_datawriter error\n");
publisher_shutdown(participant);
return -1;
}
*/
waitsets_writer = waitsetsDataWriter_narrow(writer);
if (waitsets_writer == NULL) {
printf("DataWriter narrow error\n");
publisher_shutdown(participant);
return -1;
}
/* Create data sample for writing */
instance = waitsetsTypeSupport_create_data_ex(DDS_BOOLEAN_TRUE);
if (instance == NULL) {
printf("waitsetsTypeSupport_create_data error\n");
publisher_shutdown(participant);
return -1;
}
/* For a data type that has a key, if the same instance is going to be
written multiple times, initialize the key here
and register the keyed instance prior to writing */
/*
instance_handle = waitsetsDataWriter_register_instance(
waitsets_writer, instance);
*/
/* Main loop */
for (count = 0; (sample_count == 0) || (count < sample_count); ++count) {
printf("Writing waitsets, count %d\n", count);
/* Modify the data to be written here */
instance->x = count;
/* Write data */
retcode = waitsetsDataWriter_write(
waitsets_writer,
instance,
&instance_handle);
if (retcode != DDS_RETCODE_OK) {
printf("write error %d\n", retcode);
}
NDDS_Utility_sleep(&send_period);
}
/*
retcode = waitsetsDataWriter_unregister_instance(
waitsets_writer, instance, &instance_handle);
if (retcode != DDS_RETCODE_OK) {
printf("unregister instance error %d\n", retcode);
}
*/
/* Delete data sample */
retcode = waitsetsTypeSupport_delete_data_ex(instance, DDS_BOOLEAN_TRUE);
if (retcode != DDS_RETCODE_OK) {
printf("waitsetsTypeSupport_delete_data error %d\n", retcode);
}
/* Cleanup and delete delete all entities */
return publisher_shutdown(participant);
}
#if defined(RTI_WINCE)
int wmain(int argc, wchar_t **argv)
{
int domainId = 0;
int sample_count = 0; /* infinite loop */
if (argc >= 2) {
domainId = _wtoi(argv[1]);
}
if (argc >= 3) {
sample_count = _wtoi(argv[2]);
}
/* Uncomment this to turn on additional logging
NDDS_Config_Logger_set_verbosity_by_category(
NDDS_Config_Logger_get_instance(),
NDDS_CONFIG_LOG_CATEGORY_API,
NDDS_CONFIG_LOG_VERBOSITY_STATUS_ALL);
*/
return publisher_main(domainId, sample_count);
}
#elif !(defined(RTI_VXWORKS) && !defined(__RTP__)) && !defined(RTI_PSOS)
int main(int argc, char *argv[])
{
int domainId = 0;
int sample_count = 0; /* infinite loop */
if (argc >= 2) {
domainId = atoi(argv[1]);
}
if (argc >= 3) {
sample_count = atoi(argv[2]);
}
/* Uncomment this to turn on additional logging
NDDS_Config_Logger_set_verbosity_by_category(
NDDS_Config_Logger_get_instance(),
NDDS_CONFIG_LOG_CATEGORY_API,
NDDS_CONFIG_LOG_VERBOSITY_STATUS_ALL);
*/
return publisher_main(domainId, sample_count);
}
#endif
#ifdef RTI_VX653
const unsigned char *__ctype = NULL;
void usrAppInit()
{
#ifdef USER_APPL_INIT
USER_APPL_INIT; /* for backwards compatibility */
#endif
/* add application specific code here */
taskSpawn(
"pub",
RTI_OSAPI_THREAD_PRIORITY_NORMAL,
0x8,
0x150000,
(FUNCPTR) publisher_main,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0);
}
#endif
| c |
rticonnextdds-examples | data/projects/rticonnextdds-examples/connext_dds/waitsets/c++03/waitsets_publisher.cxx | /*******************************************************************************
(c) 2005-2015 Copyright, Real-Time Innovations, Inc. All rights reserved.
RTI grants Licensee a license to use, modify, compile, and create derivative
works of the Software. Licensee has the right to distribute object form only
for use with RTI products. The Software is provided "as is", with no warranty
of any type, including any warranty for fitness for any purpose. RTI is under
no obligation to maintain or support the Software. RTI shall not be liable for
any incidental or consequential damages arising out of the use or inability to
use the software.
******************************************************************************/
#include <cstdlib>
#include <iostream>
#include "waitsets.hpp"
#include <dds/dds.hpp>
using namespace dds::core;
using namespace dds::core::policy;
using namespace dds::domain;
using namespace dds::topic;
using namespace dds::pub;
using namespace dds::pub::qos;
void publisher_main(int domain_id, int sample_count)
{
// Create a DomainParticipant with default QoS.
DomainParticipant participant(domain_id);
// Create a Topic -- and automatically register the type.
Topic<waitsets> topic(participant, "Example waitsets");
// Retrieve the default DataWriter QoS, from USER_QOS_PROFILES.xml
DataWriterQos writer_qos = QosProvider::Default().datawriter_qos();
// If you want to change the DataWriter QoS programmatically rather
// than using the XML file, you will need to uncomment these lines.
// writer_qos << Reliability::Reliable()
// << History::KeepAll()
// << Liveliness::Automatic().lease_duration(Duration(1));
// Create a DataWriter.
DataWriter<waitsets> writer(Publisher(participant), topic, writer_qos);
// Create a data sample for writing.
waitsets instance;
// Main loop.
for (int count = 0; (sample_count == 0) || (count < sample_count);
count++) {
std::cout << "Writing waitsets, count " << count << std::endl;
// Modify sample and send the sample.
instance.x(count);
writer.write(instance);
// Send a new sample every second.
rti::util::sleep(Duration(1));
}
}
int main(int argc, char *argv[])
{
int domain_id = 0;
int sample_count = 0; // Infinite loop
if (argc >= 2) {
domain_id = atoi(argv[1]);
}
if (argc >= 3) {
sample_count = atoi(argv[2]);
}
// To turn on additional logging, include <rti/config/Logger.hpp> and
// uncomment the following line:
// rti::config::Logger::instance().verbosity(rti::config::Verbosity::STATUS_ALL);
try {
publisher_main(domain_id, sample_count);
} catch (std::exception ex) {
std::cout << "Exception caught: " << ex.what() << std::endl;
return -1;
}
return 0;
}
| cxx |
rticonnextdds-examples | data/projects/rticonnextdds-examples/connext_dds/waitsets/c++03/waitsets_subscriber.cxx | /*******************************************************************************
(c) 2005-2015 Copyright, Real-Time Innovations, Inc. All rights reserved.
RTI grants Licensee a license to use, modify, compile, and create derivative
works of the Software. Licensee has the right to distribute object form only
for use with RTI products. The Software is provided "as is", with no warranty
of any type, including any warranty for fitness for any purpose. RTI is under
no obligation to maintain or support the Software. RTI shall not be liable for
any incidental or consequential damages arising out of the use or inability to
use the software.
******************************************************************************/
#include <cstdlib>
#include <iostream>
#include "waitsets.hpp"
#include <dds/dds.hpp>
using namespace dds::core;
using namespace dds::core::cond;
using namespace dds::core::policy;
using namespace dds::core::status;
using namespace dds::domain;
using namespace dds::topic;
using namespace dds::sub;
using namespace dds::sub::cond;
using namespace dds::sub::qos;
using namespace dds::sub::status;
void subscriber_main(int domain_id, int sample_count)
{
// Create a DomainParticipant with default QoS.
DomainParticipant participant(domain_id);
// Create a Topic -- and automatically register the type.
Topic<waitsets> topic(participant, "Example waitsets");
// Retrieve the default DataReader QoS, from USER_QOS_PROFILES.xml
DataReaderQos reader_qos = QosProvider::Default().datareader_qos();
// If you want to change the DataWriter QoS programmatically rather
// than using the XML file, you will need to uncomment these lines.
// reader_qos << Reliability::Reliable()
// << History::KeepAll()
// << Liveliness::Automatic().lease_duration(Duration(2));
// Create a DataReader.
DataReader<waitsets> reader(Subscriber(participant), topic, reader_qos);
// Create a Read Condition.
// Note that the Read Conditions are dependent on both incoming data as
// well as sample state.
ReadCondition read_cond(
reader,
DataState(
SampleState::not_read(),
ViewState::any(),
InstanceState::any()));
// Get status conditions.
// Each entity may have an attached Status Condition. To modify the
// statuses we need to get the reader's Status Conditions first.
StatusCondition status_condition(reader);
// Set enabled statuses.
// Now that we have the Status Condition, we are going to enable the
// statuses we are interested in:
status_condition.enabled_statuses(
StatusMask::subscription_matched()
| StatusMask::liveliness_changed());
// Create and attach conditions to the WaitSet
// Finally, we create the WaitSet and attach both the Read Conditions and
// the Status Condition to it. We can use the operator '+=' or the method
// 'attach_condition'.
WaitSet waitset;
waitset += read_cond;
waitset.attach_condition(status_condition);
// Main loop.
for (int count = 0; (sample_count == 0) || (count < sample_count);
++count) {
// 'wait()' blocks execution of the thread until one or more attached
// Conditions become true, or until a user-specified timeout expires.
WaitSet::ConditionSeq active_conditions =
waitset.wait(Duration::from_millisecs(1500));
if (active_conditions.size() == 0) {
std::cout << "Wait timed out!! No conditions were triggered."
<< std::endl;
continue;
}
std::cout << "Got " << active_conditions.size() << " active conditions"
<< std::endl;
for (std::vector<int>::size_type i = 0; i < active_conditions.size();
i++) {
// Now we compare the current condition with the Status Conditions
// and the Read Conditions previously defined. If they match, we
// print the condition that was triggered.
if (active_conditions[i] == status_condition) {
// Get the status changes so we can check witch status condition
// triggered.
StatusMask status_mask = reader.status_changes();
// Liveliness changed
if ((status_mask & StatusMask::liveliness_changed()).any()) {
LivelinessChangedStatus st =
reader.liveliness_changed_status();
std::cout << "Liveliness changed => Active writers = "
<< st.alive_count() << std::endl;
}
// Subscription matched
if ((status_mask & StatusMask::subscription_matched()).any()) {
SubscriptionMatchedStatus st =
reader.subscription_matched_status();
std::cout << "Subscription matched => Cumulative matches = "
<< st.total_count() << std::endl;
}
} else if (active_conditions[i] == read_cond) {
// Current conditions match our conditions to read data, so we
// can read data just like we would do in any other example.
LoanedSamples<waitsets> samples = reader.take();
for (LoanedSamples<waitsets>::iterator sampleIt =
samples.begin();
sampleIt != samples.end();
++sampleIt) {
if (!sampleIt->info().valid()) {
std::cout << "Got metadata" << std::endl;
} else {
std::cout << sampleIt->data() << std::endl;
}
}
}
}
}
}
int main(int argc, char *argv[])
{
int domain_id = 0;
int sample_count = 0; // infinite loop
if (argc >= 2) {
domain_id = atoi(argv[1]);
}
if (argc >= 3) {
sample_count = atoi(argv[2]);
}
// To turn on additional logging, include <rti/config/Logger.hpp> and
// uncomment the following line:
// rti::config::Logger::instance().verbosity(rti::config::Verbosity::STATUS_ALL);
try {
subscriber_main(domain_id, sample_count);
} catch (std::exception ex) {
std::cout << "Exception caught: " << ex.what() << std::endl;
return -1;
}
return 0;
}
| cxx |
rticonnextdds-examples | data/projects/rticonnextdds-examples/connext_dds/waitsets/c++11/application.hpp | /*
* (c) Copyright, Real-Time Innovations, 2020. All rights reserved.
* RTI grants Licensee a license to use, modify, compile, and create derivative
* works of the software solely for use with RTI Connext DDS. Licensee may
* redistribute copies of the software provided that all such copies are subject
* to this license. The software is provided "as is", with no warranty of any
* type, including any warranty for fitness for any purpose. RTI is under no
* obligation to maintain or support the software. RTI shall not be liable for
* any incidental or consequential damages arising out of the use or inability
* to use the software.
*/
#ifndef APPLICATION_HPP
#define APPLICATION_HPP
#include <iostream>
#include <csignal>
#include <dds/core/ddscore.hpp>
namespace application {
// Catch control-C and tell application to shut down
bool shutdown_requested = false;
inline void stop_handler(int)
{
shutdown_requested = true;
std::cout << "preparing to shut down..." << std::endl;
}
inline void setup_signal_handlers()
{
signal(SIGINT, stop_handler);
signal(SIGTERM, stop_handler);
}
enum class ParseReturn { ok, failure, exit };
struct ApplicationArguments {
ParseReturn parse_result;
unsigned int domain_id;
unsigned int sample_count;
rti::config::Verbosity verbosity;
ApplicationArguments(
ParseReturn parse_result_param,
unsigned int domain_id_param,
unsigned int sample_count_param,
rti::config::Verbosity verbosity_param)
: parse_result(parse_result_param),
domain_id(domain_id_param),
sample_count(sample_count_param),
verbosity(verbosity_param)
{
}
};
inline void set_verbosity(
rti::config::Verbosity &verbosity,
int verbosity_value)
{
switch (verbosity_value) {
case 0:
verbosity = rti::config::Verbosity::SILENT;
break;
case 1:
verbosity = rti::config::Verbosity::EXCEPTION;
break;
case 2:
verbosity = rti::config::Verbosity::WARNING;
break;
case 3:
verbosity = rti::config::Verbosity::STATUS_ALL;
break;
default:
verbosity = rti::config::Verbosity::EXCEPTION;
break;
}
}
// Parses application arguments for example.
inline ApplicationArguments parse_arguments(int argc, char *argv[])
{
int arg_processing = 1;
bool show_usage = false;
ParseReturn parse_result = ParseReturn::ok;
unsigned int domain_id = 0;
unsigned int sample_count = (std::numeric_limits<unsigned int>::max)();
rti::config::Verbosity verbosity(rti::config::Verbosity::EXCEPTION);
while (arg_processing < argc) {
if ((argc > arg_processing + 1)
&& (strcmp(argv[arg_processing], "-d") == 0
|| strcmp(argv[arg_processing], "--domain") == 0)) {
domain_id = atoi(argv[arg_processing + 1]);
arg_processing += 2;
} else if (
(argc > arg_processing + 1)
&& (strcmp(argv[arg_processing], "-s") == 0
|| strcmp(argv[arg_processing], "--sample-count") == 0)) {
sample_count = atoi(argv[arg_processing + 1]);
arg_processing += 2;
} else if (
(argc > arg_processing + 1)
&& (strcmp(argv[arg_processing], "-v") == 0
|| strcmp(argv[arg_processing], "--verbosity") == 0)) {
set_verbosity(verbosity, atoi(argv[arg_processing + 1]));
arg_processing += 2;
} else if (
strcmp(argv[arg_processing], "-h") == 0
|| strcmp(argv[arg_processing], "--help") == 0) {
std::cout << "Example application." << std::endl;
show_usage = true;
parse_result = ParseReturn::exit;
break;
} else {
std::cout << "Bad parameter." << std::endl;
show_usage = true;
parse_result = ParseReturn::failure;
break;
}
}
if (show_usage) {
std::cout << "Usage:\n"
" -d, --domain <int> Domain ID this "
"application will\n"
" subscribe in. \n"
" Default: 0\n"
" -s, --sample_count <int> Number of samples to "
"receive before\n"
" cleanly shutting down. \n"
" Default: infinite\n"
" -v, --verbosity <int> How much debugging output "
"to show.\n"
" Range: 0-3 \n"
" Default: 1"
<< std::endl;
}
return ApplicationArguments(
parse_result,
domain_id,
sample_count,
verbosity);
}
} // namespace application
#endif // APPLICATION_HPP | hpp |
rticonnextdds-examples | data/projects/rticonnextdds-examples/connext_dds/waitsets/c++11/waitsets_publisher.cxx | /*******************************************************************************
(c) 2005-2015 Copyright, Real-Time Innovations, Inc. All rights reserved.
RTI grants Licensee a license to use, modify, compile, and create derivative
works of the Software. Licensee has the right to distribute object form only
for use with RTI products. The Software is provided "as is", with no warranty
of any type, including any warranty for fitness for any purpose. RTI is under
no obligation to maintain or support the Software. RTI shall not be liable for
any incidental or consequential damages arising out of the use or inability to
use the software.
******************************************************************************/
#include <dds/pub/ddspub.hpp>
#include <rti/util/util.hpp> // for sleep()
#include <rti/config/Logger.hpp> // for logging
#include "application.hpp" // for command line parsing and ctrl-c
#include "waitsets.hpp"
void run_publisher_application(
unsigned int domain_id,
unsigned int sample_count)
{
// Create a DomainParticipant with default QoS.
dds::domain::DomainParticipant participant(domain_id);
// Create a Topic -- and automatically register the type.
dds::topic::Topic<waitsets> topic(participant, "Example waitsets");
// Retrieve the default DataWriter QoS, from USER_QOS_PROFILES.xml
dds::pub::qos::DataWriterQos writer_qos =
dds::core::QosProvider::Default().datawriter_qos();
// If you want to change the DataWriter QoS programmatically rather
// than using the XML file, you will need to uncomment these lines.
// writer_qos << Reliability::Reliable()
// << History::KeepAll()
// << Liveliness::Automatic().lease_duration(Duration(1));
// Create a Publisher
dds::pub::Publisher publiser(participant);
// Create a DataWriter.
dds::pub::DataWriter<waitsets> writer(publiser, topic, writer_qos);
// Create a data sample for writing.
waitsets instance;
// Main loop.
for (unsigned int samples_written = 0;
!application::shutdown_requested && samples_written < sample_count;
samples_written++) {
std::cout << "Writing waitsets, count " << samples_written << std::endl;
// Modify sample and send the sample.
instance.x(samples_written);
writer.write(instance);
// Send a new sample every second.
rti::util::sleep(dds::core::Duration(1));
}
}
int main(int argc, char *argv[])
{
using namespace application;
// Parse arguments and handle control-C
auto arguments = parse_arguments(argc, argv);
if (arguments.parse_result == ParseReturn::exit) {
return EXIT_SUCCESS;
} else if (arguments.parse_result == ParseReturn::failure) {
return EXIT_FAILURE;
}
setup_signal_handlers();
// Sets Connext verbosity to help debugging
rti::config::Logger::instance().verbosity(arguments.verbosity);
try {
run_publisher_application(arguments.domain_id, arguments.sample_count);
} catch (const std::exception &ex) {
// This will catch DDS exceptions
std::cerr << "Exception in run_publisher_application(): " << ex.what()
<< std::endl;
return EXIT_FAILURE;
}
// Releases the memory used by the participant factory. Optional at
// application exit
dds::domain::DomainParticipant::finalize_participant_factory();
return EXIT_SUCCESS;
}
| cxx |
rticonnextdds-examples | data/projects/rticonnextdds-examples/connext_dds/waitsets/c++11/waitsets_subscriber.cxx | /*******************************************************************************
(c) 2005-2015 Copyright, Real-Time Innovations, Inc. All rights reserved.
RTI grants Licensee a license to use, modify, compile, and create derivative
works of the Software. Licensee has the right to distribute object form only
for use with RTI products. The Software is provided "as is", with no warranty
of any type, including any warranty for fitness for any purpose. RTI is under
no obligation to maintain or support the Software. RTI shall not be liable for
any incidental or consequential damages arising out of the use or inability to
use the software.
******************************************************************************/
#include <dds/sub/ddssub.hpp>
#include <dds/core/ddscore.hpp>
#include <rti/config/Logger.hpp> // for logging
#include "waitsets.hpp"
#include "application.hpp" // for command line parsing and ctrl-c
void run_subscriber_application(
unsigned int domain_id,
unsigned int sample_count)
{
// Create a DomainParticipant with default QoS.
dds::domain::DomainParticipant participant(domain_id);
// Create a Topic -- and automatically register the type.
dds::topic::Topic<waitsets> topic(participant, "Example waitsets");
// Retrieve the default DataReader QoS, from USER_QOS_PROFILES.xml
dds::sub::qos::DataReaderQos reader_qos =
dds::core::QosProvider::Default().datareader_qos();
// If you want to change the DataWriter QoS programmatically rather
// than using the XML file, you will need to uncomment these lines.
// reader_qos << Reliability::Reliable()
// << History::KeepAll()
// << Liveliness::Automatic().lease_duration(Duration(2));
// Create a Subscriber
dds::sub::Subscriber subscriber(participant);
// Create a DataReader.
dds::sub::DataReader<waitsets> reader(subscriber, topic, reader_qos);
// Create a Read Condition.
// Note that the Read Conditions are dependent on both incoming data as
// well as sample state.
dds::sub::cond::ReadCondition read_cond(
reader,
dds::sub::status::DataState(
dds::sub::status::SampleState::not_read(),
dds::sub::status::ViewState::any(),
dds::sub::status::InstanceState::any()));
// Get status conditions.
// Each entity may have an attached Status Condition. To modify the
// statuses we need to get the reader's Status Conditions first.
dds::core::cond::StatusCondition status_condition(reader);
// Set enabled statuses.
// Now that we have the Status Condition, we are going to enable the
// statuses we are interested in:
status_condition.enabled_statuses(
dds::core::status::StatusMask::subscription_matched()
| dds::core::status::StatusMask::liveliness_changed());
// Create and attach conditions to the WaitSet
// Finally, we create the WaitSet and attach both the Read Conditions and
// the Status Condition to it. We can use the operator '+=' or the method
// 'attach_condition'.
dds::core::cond::WaitSet waitset;
waitset += read_cond;
waitset.attach_condition(status_condition);
int samples_read = 0;
// Main loop.
while (!application::shutdown_requested && samples_read < sample_count) {
// 'wait()' blocks execution of the thread until one or more attached
// Conditions become true, or until a user-specified timeout expires.
dds::core::cond::WaitSet::ConditionSeq active_conditions =
waitset.wait(dds::core::Duration::from_millisecs(1500));
if (active_conditions.size() == 0) {
std::cout << "Wait timed out!! No conditions were triggered."
<< std::endl;
continue;
}
std::cout << "Got " << active_conditions.size() << " active conditions"
<< std::endl;
for (std::vector<int>::size_type i = 0; i < active_conditions.size();
i++) {
// Now we compare the current condition with the Status Conditions
// and the Read Conditions previously defined. If they match, we
// print the condition that was triggered.
if (active_conditions[i] == status_condition) {
// Get the status changes so we can check witch status condition
// triggered.
dds::core::status::StatusMask status_mask =
reader.status_changes();
// Liveliness changed
if ((status_mask
& dds::core::status::StatusMask::liveliness_changed())
.any()) {
dds::core::status::LivelinessChangedStatus st =
reader.liveliness_changed_status();
std::cout << "Liveliness changed => Active writers = "
<< st.alive_count() << std::endl;
}
// Subscription matched
if ((status_mask
& dds::core::status::StatusMask::subscription_matched())
.any()) {
dds::core::status::SubscriptionMatchedStatus st =
reader.subscription_matched_status();
std::cout << "Subscription matched => Cumulative matches = "
<< st.total_count() << std::endl;
}
} else if (active_conditions[i] == read_cond) {
// Current conditions match our conditions to read data, so we
// can read data just like we would do in any other example.
dds::sub::LoanedSamples<waitsets> samples = reader.take();
for (const auto &sample : samples) {
if (!sample.info().valid()) {
std::cout << "Got metadata" << std::endl;
} else {
std::cout << sample.data() << std::endl;
samples_read++;
}
}
}
}
}
}
int main(int argc, char *argv[])
{
using namespace application;
// Parse arguments and handle control-C
auto arguments = parse_arguments(argc, argv);
if (arguments.parse_result == ParseReturn::exit) {
return EXIT_SUCCESS;
} else if (arguments.parse_result == ParseReturn::failure) {
return EXIT_FAILURE;
}
setup_signal_handlers();
// Sets Connext verbosity to help debugging
rti::config::Logger::instance().verbosity(arguments.verbosity);
try {
run_subscriber_application(arguments.domain_id, arguments.sample_count);
} catch (const std::exception &ex) {
// This will catch DDS exceptions
std::cerr << "Exception in run_subscriber_application(): " << ex.what()
<< std::endl;
return EXIT_FAILURE;
}
// Releases the memory used by the participant factory. Optional at
// application exit
dds::domain::DomainParticipant::finalize_participant_factory();
return EXIT_SUCCESS;
}
| cxx |
rticonnextdds-examples | data/projects/rticonnextdds-examples/connext_dds/using_sequences/c++/sequences_publisher.cxx | /*******************************************************************************
(c) 2005-2014 Copyright, Real-Time Innovations, Inc. All rights reserved.
RTI grants Licensee a license to use, modify, compile, and create derivative
works of the Software. Licensee has the right to distribute object form only
for use with RTI products. The Software is provided "as is", with no warranty
of any type, including any warranty for fitness for any purpose. RTI is under
no obligation to maintain or support the Software. RTI shall not be liable for
any incidental or consequential damages arising out of the use or inability to
use the software.
******************************************************************************/
/* sequences_publisher.cxx
A publication of data of type sequences
This file is derived from code automatically generated by the rtiddsgen
command:
rtiddsgen -language C++ -example <arch> sequences.idl
Example publication of type sequences automatically generated by
'rtiddsgen'. To test them follow these steps:
(1) Compile this file and the example subscription.
(2) Start the subscription with the command
objs/<arch>/sequences_subscriber <domain_id> <sample_count>
(3) Start the publication with the command
objs/<arch>/sequences_publisher <domain_id> <sample_count>
(4) [Optional] Specify the list of discovery initial peers and
multicast receive addresses via an environment variable or a file
(in the current working directory) called NDDS_DISCOVERY_PEERS.
You can run any number of publishers and subscribers programs, and can
add and remove them dynamically from the domain.
Example:
To run the example application on domain <domain_id>:
On Unix:
objs/<arch>/sequences_publisher <domain_id> o
objs/<arch>/sequences_subscriber <domain_id>
On Windows:
objs\<arch>\sequences_publisher <domain_id>
objs\<arch>\sequences_subscriber <domain_id>
modification history
------------ -------
*/
#include <stdio.h>
#include <stdlib.h>
#ifdef RTI_VX653
#include <vThreadsData.h>
#endif
#include "ndds/ndds_cpp.h"
#include "sequences.h"
#include "sequencesSupport.h"
/* Delete all entities */
static int publisher_shutdown(DDSDomainParticipant *participant)
{
DDS_ReturnCode_t retcode;
int status = 0;
if (participant != NULL) {
retcode = participant->delete_contained_entities();
if (retcode != DDS_RETCODE_OK) {
printf("delete_contained_entities error %d\n", retcode);
status = -1;
}
retcode = DDSTheParticipantFactory->delete_participant(participant);
if (retcode != DDS_RETCODE_OK) {
printf("delete_participant error %d\n", retcode);
status = -1;
}
}
/* RTI Connext provides finalize_instance() method on
domain participant factory for people who want to release memory used
by the participant factory. Uncomment the following block of code for
clean destruction of the singleton. */
/*
retcode = DDSDomainParticipantFactory::finalize_instance();
if (retcode != DDS_RETCODE_OK) {
printf("finalize_instance error %d\n", retcode);
status = -1;
}
*/
return status;
}
extern "C" int publisher_main(int domainId, int sample_count)
{
DDSDomainParticipant *participant = NULL;
DDSPublisher *publisher = NULL;
DDSTopic *topic = NULL;
DDSDataWriter *writer = NULL;
sequencesDataWriter *sequences_writer = NULL;
/* We define two instances to illustrate the different memory use of
* sequences: owner_instance and borrower_instance. */
sequences *owner_instance = NULL;
sequences *borrower_instance = NULL;
DDS_InstanceHandle_t owner_instance_handle = DDS_HANDLE_NIL;
DDS_InstanceHandle_t borrower_instance_handle = DDS_HANDLE_NIL;
DDS_ReturnCode_t retcode;
const char *type_name = NULL;
int count = 0;
/* Send a new sample every second */
DDS_Duration_t send_period = { 1, 0 };
/* To customize participant QoS, use
the configuration file USER_QOS_PROFILES.xml */
participant = DDSTheParticipantFactory->create_participant(
domainId,
DDS_PARTICIPANT_QOS_DEFAULT,
NULL /* listener */,
DDS_STATUS_MASK_NONE);
if (participant == NULL) {
printf("create_participant error\n");
publisher_shutdown(participant);
return -1;
}
/* To customize publisher QoS, use
the configuration file USER_QOS_PROFILES.xml */
publisher = participant->create_publisher(
DDS_PUBLISHER_QOS_DEFAULT,
NULL /* listener */,
DDS_STATUS_MASK_NONE);
if (publisher == NULL) {
printf("create_publisher error\n");
publisher_shutdown(participant);
return -1;
}
/* Register type before creating topic */
type_name = sequencesTypeSupport::get_type_name();
retcode = sequencesTypeSupport::register_type(participant, type_name);
if (retcode != DDS_RETCODE_OK) {
printf("register_type error %d\n", retcode);
publisher_shutdown(participant);
return -1;
}
/* To customize topic QoS, use
the configuration file USER_QOS_PROFILES.xml */
topic = participant->create_topic(
"Example sequences",
type_name,
DDS_TOPIC_QOS_DEFAULT,
NULL /* listener */,
DDS_STATUS_MASK_NONE);
if (topic == NULL) {
printf("create_topic error\n");
publisher_shutdown(participant);
return -1;
}
/* To customize data writer QoS, use
the configuration file USER_QOS_PROFILES.xml */
writer = publisher->create_datawriter(
topic,
DDS_DATAWRITER_QOS_DEFAULT,
NULL /* listener */,
DDS_STATUS_MASK_NONE);
if (writer == NULL) {
printf("create_datawriter error\n");
publisher_shutdown(participant);
return -1;
}
sequences_writer = sequencesDataWriter::narrow(writer);
if (sequences_writer == NULL) {
printf("DataWriter narrow error\n");
publisher_shutdown(participant);
return -1;
}
/* Here we define two instances: owner_instance and borrower_instance. */
/* owner_instance.data uses its own memory, as by default, a sequence
* you create owns its memory unless you explicitly loan memory of your
* own to it.
*/
owner_instance = sequencesTypeSupport::create_data();
if (owner_instance == NULL) {
printf("sequencesTypeSupport::create_data error\n");
publisher_shutdown(participant);
return -1;
}
/* borrower_instance.data "borrows" memory from a buffer of shorts,
* previously allocated, using DDS_ShortSeq_loan_contiguous(). */
borrower_instance = sequencesTypeSupport::create_data();
if (borrower_instance == NULL) {
printf("sequencesTypeSupport::create_data error\n");
publisher_shutdown(participant);
return -1;
}
/* If we want borrower_instance.data to loan a buffer of shorts, first we
* have to allocate the buffer. Here we allocate a buffer of
* MAX_SEQUENCE_LEN. */
short *short_buffer = new short[MAX_SEQUENCE_LEN];
/* Before calling loan_contiguous(), we need to set Seq.maximum to
* 0, i.e., the sequence won't have memory allocated to it. */
borrower_instance->data.maximum(0);
/* Now that the sequence doesn't have memory allocated to it, we can use
* loan_contiguous() to loan short_buffer to borrower_instance.
* We set the allocated number of elements to MAX_SEQUENCE_LEN, the size of
* the buffer and the maximum size of the sequence as we declared in the
* IDL. */
bool return_result = borrower_instance->data.loan_contiguous(
short_buffer, // Pointer to the sequence
0, // Initial Length
MAX_SEQUENCE_LEN // New maximum
);
if (return_result != DDS_BOOLEAN_TRUE) {
printf("loan_contiguous error\n");
publisher_shutdown(participant);
return -1;
}
/* Before starting to publish samples, set the instance id of each
* instance*/
strcpy(owner_instance->id, "owner_instance");
strcpy(borrower_instance->id, "borrower_instance");
/* To illustrate the use of the sequences, in the main loop we set a
* new sequence length every iteration to the sequences contained in
* both instances (instance->data). The sequence length value cycles between
* 0 and MAX_SEQUENCE_LEN. We assign a random number between 0 and 100 to
* each sequence's elements. */
for (count = 0; (sample_count == 0) || (count < sample_count); ++count) {
/* We set a different sequence_length for both instances every
* iteration. sequence_length is based on the value of count and
* its value cycles between the values of 1 and MAX_SEQUENCE_LEN. */
short sequence_length = (count % MAX_SEQUENCE_LEN) + 1;
printf("Writing sequences, count %d...\n", count);
owner_instance->count = count;
borrower_instance->count = count;
/* Here we set the new length of each sequence */
owner_instance->data.length(sequence_length);
borrower_instance->data.length(sequence_length);
/* Now that the sequences have a new length, we assign a
* random number between 0 and 100 to each element of
* owner_instance->data and borrower_instance->data. */
for (int i = 0; i < sequence_length; ++i) {
owner_instance->data[i] = (short) (rand() / (RAND_MAX / 100));
borrower_instance->data[i] = (short) (rand() / (RAND_MAX / 100));
}
/* Both sequences have the same length, so we only print the length
* of one of them. */
printf("Instances length = %d\n", owner_instance->data.length());
/* Write for each instance */
retcode =
sequences_writer->write(*owner_instance, owner_instance_handle);
if (retcode != DDS_RETCODE_OK) {
printf("write error %d\n", retcode);
}
retcode = sequences_writer->write(
*borrower_instance,
borrower_instance_handle);
if (retcode != DDS_RETCODE_OK) {
printf("write error %d\n", retcode);
}
NDDSUtility::sleep(send_period);
}
/* Once we are done with the sequence, we unloan and free the buffer. Make
* sure you don't call delete before unloan(); the next time you
* access the sequence, you will be accessing freed memory. */
return_result = borrower_instance->data.unloan();
if (return_result != DDS_BOOLEAN_TRUE) {
printf("unloan error \n");
}
delete[] short_buffer;
/* Delete data samples */
retcode = sequencesTypeSupport::delete_data(owner_instance);
if (retcode != DDS_RETCODE_OK) {
printf("sequencesTypeSupport::delete_data error %d\n", retcode);
}
retcode = sequencesTypeSupport::delete_data(borrower_instance);
if (retcode != DDS_RETCODE_OK) {
printf("sequencesTypeSupport::delete_data error %d\n", retcode);
}
/* Delete all entities */
return publisher_shutdown(participant);
}
#if defined(RTI_WINCE)
int wmain(int argc, wchar_t **argv)
{
int domainId = 0;
int sample_count = 0; /* infinite loop */
if (argc >= 2) {
domainId = _wtoi(argv[1]);
}
if (argc >= 3) {
sample_count = _wtoi(argv[2]);
}
/* Uncomment this to turn on additional logging
NDDSConfigLogger::get_instance()->
set_verbosity_by_category(NDDS_CONFIG_LOG_CATEGORY_API,
NDDS_CONFIG_LOG_VERBOSITY_STATUS_ALL);
*/
return publisher_main(domainId, sample_count);
}
#elif !(defined(RTI_VXWORKS) && !defined(__RTP__)) && !defined(RTI_PSOS)
int main(int argc, char *argv[])
{
int domainId = 0;
int sample_count = 0; /* infinite loop */
if (argc >= 2) {
domainId = atoi(argv[1]);
}
if (argc >= 3) {
sample_count = atoi(argv[2]);
}
/* Uncomment this to turn on additional logging
NDDSConfigLogger::get_instance()->
set_verbosity_by_category(NDDS_CONFIG_LOG_CATEGORY_API,
NDDS_CONFIG_LOG_VERBOSITY_STATUS_ALL);
*/
return publisher_main(domainId, sample_count);
}
#endif
#ifdef RTI_VX653
const unsigned char *__ctype = *(__ctypePtrGet());
extern "C" void usrAppInit()
{
#ifdef USER_APPL_INIT
USER_APPL_INIT; /* for backwards compatibility */
#endif
/* add application specific code here */
taskSpawn(
"pub",
RTI_OSAPI_THREAD_PRIORITY_NORMAL,
0x8,
0x150000,
(FUNCPTR) publisher_main,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0);
}
#endif
| cxx |
rticonnextdds-examples | data/projects/rticonnextdds-examples/connext_dds/using_sequences/c++/sequences_subscriber.cxx | /*******************************************************************************
(c) 2005-2014 Copyright, Real-Time Innovations, Inc. All rights reserved.
RTI grants Licensee a license to use, modify, compile, and create derivative
works of the Software. Licensee has the right to distribute object form only
for use with RTI products. The Software is provided "as is", with no warranty
of any type, including any warranty for fitness for any purpose. RTI is under
no obligation to maintain or support the Software. RTI shall not be liable for
any incidental or consequential damages arising out of the use or inability to
use the software.
******************************************************************************/
/* sequences_subscriber.cxx
A subscription example
This file is derived from code automatically generated by the rtiddsgen
command:
rtiddsgen -language C++ -example <arch> sequences.idl
Example subscription of type sequences automatically generated by
'rtiddsgen'. To test them follow these steps:
(1) Compile this file and the example publication.
(2) Start the subscription with the command
objs/<arch>/sequences_subscriber <domain_id> <sample_count>
(3) Start the publication with the command
objs/<arch>/sequences_publisher <domain_id> <sample_count>
(4) [Optional] Specify the list of discovery initial peers and
multicast receive addresses via an environment variable or a file
(in the current working directory) called NDDS_DISCOVERY_PEERS.
You can run any number of publishers and subscribers programs, and can
add and remove them dynamically from the domain.
Example:
To run the example application on domain <domain_id>:
On Unix:
objs/<arch>/sequences_publisher <domain_id>
objs/<arch>/sequences_subscriber <domain_id>
On Windows:
objs\<arch>\sequences_publisher <domain_id>
objs\<arch>\sequences_subscriber <domain_id>
modification history
------------ -------
*/
#include <stdio.h>
#include <stdlib.h>
#ifdef RTI_VX653
#include <vThreadsData.h>
#endif
#include "ndds/ndds_cpp.h"
#include "sequences.h"
#include "sequencesSupport.h"
class sequencesListener : public DDSDataReaderListener {
public:
virtual void on_requested_deadline_missed(
DDSDataReader * /*reader*/,
const DDS_RequestedDeadlineMissedStatus & /*status*/)
{
}
virtual void on_requested_incompatible_qos(
DDSDataReader * /*reader*/,
const DDS_RequestedIncompatibleQosStatus & /*status*/)
{
}
virtual void on_sample_rejected(
DDSDataReader * /*reader*/,
const DDS_SampleRejectedStatus & /*status*/)
{
}
virtual void on_liveliness_changed(
DDSDataReader * /*reader*/,
const DDS_LivelinessChangedStatus & /*status*/)
{
}
virtual void on_sample_lost(
DDSDataReader * /*reader*/,
const DDS_SampleLostStatus & /*status*/)
{
}
virtual void on_subscription_matched(
DDSDataReader * /*reader*/,
const DDS_SubscriptionMatchedStatus & /*status*/)
{
}
virtual void on_data_available(DDSDataReader *reader);
};
void sequencesListener::on_data_available(DDSDataReader *reader)
{
sequencesDataReader *sequences_reader = NULL;
sequencesSeq data_seq;
DDS_SampleInfoSeq info_seq;
DDS_ReturnCode_t retcode;
int i;
sequences_reader = sequencesDataReader::narrow(reader);
if (sequences_reader == NULL) {
printf("DataReader narrow error\n");
return;
}
retcode = sequences_reader->take(
data_seq,
info_seq,
DDS_LENGTH_UNLIMITED,
DDS_ANY_SAMPLE_STATE,
DDS_ANY_VIEW_STATE,
DDS_ANY_INSTANCE_STATE);
if (retcode == DDS_RETCODE_NO_DATA) {
return;
} else if (retcode != DDS_RETCODE_OK) {
printf("take error %d\n", retcode);
return;
}
for (i = 0; i < data_seq.length(); ++i) {
if (info_seq[i].valid_data) {
sequencesTypeSupport::print_data(&data_seq[i]);
}
}
retcode = sequences_reader->return_loan(data_seq, info_seq);
if (retcode != DDS_RETCODE_OK) {
printf("return loan error %d\n", retcode);
}
}
/* Delete all entities */
static int subscriber_shutdown(DDSDomainParticipant *participant)
{
DDS_ReturnCode_t retcode;
int status = 0;
if (participant != NULL) {
retcode = participant->delete_contained_entities();
if (retcode != DDS_RETCODE_OK) {
printf("delete_contained_entities error %d\n", retcode);
status = -1;
}
retcode = DDSTheParticipantFactory->delete_participant(participant);
if (retcode != DDS_RETCODE_OK) {
printf("delete_participant error %d\n", retcode);
status = -1;
}
}
/* RTI Connext provides the finalize_instance() method on
domain participant factory for people who want to release memory used
by the participant factory. Uncomment the following block of code for
clean destruction of the singleton. */
/*
retcode = DDSDomainParticipantFactory::finalize_instance();
if (retcode != DDS_RETCODE_OK) {
printf("finalize_instance error %d\n", retcode);
status = -1;
}
*/
return status;
}
extern "C" int subscriber_main(int domainId, int sample_count)
{
DDSDomainParticipant *participant = NULL;
DDSSubscriber *subscriber = NULL;
DDSTopic *topic = NULL;
sequencesListener *reader_listener = NULL;
DDSDataReader *reader = NULL;
DDS_ReturnCode_t retcode;
const char *type_name = NULL;
int count = 0;
DDS_Duration_t receive_period = { 4, 0 };
int status = 0;
/* To customize the participant QoS, use
the configuration file USER_QOS_PROFILES.xml */
participant = DDSTheParticipantFactory->create_participant(
domainId,
DDS_PARTICIPANT_QOS_DEFAULT,
NULL /* listener */,
DDS_STATUS_MASK_NONE);
if (participant == NULL) {
printf("create_participant error\n");
subscriber_shutdown(participant);
return -1;
}
/* To customize the subscriber QoS, use
the configuration file USER_QOS_PROFILES.xml */
subscriber = participant->create_subscriber(
DDS_SUBSCRIBER_QOS_DEFAULT,
NULL /* listener */,
DDS_STATUS_MASK_NONE);
if (subscriber == NULL) {
printf("create_subscriber error\n");
subscriber_shutdown(participant);
return -1;
}
/* Register the type before creating the topic */
type_name = sequencesTypeSupport::get_type_name();
retcode = sequencesTypeSupport::register_type(participant, type_name);
if (retcode != DDS_RETCODE_OK) {
printf("register_type error %d\n", retcode);
subscriber_shutdown(participant);
return -1;
}
/* To customize the topic QoS, use
the configuration file USER_QOS_PROFILES.xml */
topic = participant->create_topic(
"Example sequences",
type_name,
DDS_TOPIC_QOS_DEFAULT,
NULL /* listener */,
DDS_STATUS_MASK_NONE);
if (topic == NULL) {
printf("create_topic error\n");
subscriber_shutdown(participant);
return -1;
}
/* Create a data reader listener */
reader_listener = new sequencesListener();
/* To customize the data reader QoS, use
the configuration file USER_QOS_PROFILES.xml */
reader = subscriber->create_datareader(
topic,
DDS_DATAREADER_QOS_DEFAULT,
reader_listener,
DDS_STATUS_MASK_ALL);
if (reader == NULL) {
printf("create_datareader error\n");
subscriber_shutdown(participant);
delete reader_listener;
return -1;
}
/* Main loop */
for (count = 0; (sample_count == 0) || (count < sample_count); ++count) {
printf("sequences subscriber sleeping for %d sec...\n",
receive_period.sec);
NDDSUtility::sleep(receive_period);
}
/* Delete all entities */
status = subscriber_shutdown(participant);
delete reader_listener;
return status;
}
#if defined(RTI_WINCE)
int wmain(int argc, wchar_t **argv)
{
int domainId = 0;
int sample_count = 0; /* infinite loop */
if (argc >= 2) {
domainId = _wtoi(argv[1]);
}
if (argc >= 3) {
sample_count = _wtoi(argv[2]);
}
/* Uncomment this to turn on additional logging
NDDSConfigLogger::get_instance()->
set_verbosity_by_category(NDDS_CONFIG_LOG_CATEGORY_API,
NDDS_CONFIG_LOG_VERBOSITY_STATUS_ALL);
*/
return subscriber_main(domainId, sample_count);
}
#elif !(defined(RTI_VXWORKS) && !defined(__RTP__)) && !defined(RTI_PSOS)
int main(int argc, char *argv[])
{
int domainId = 0;
int sample_count = 0; /* infinite loop */
if (argc >= 2) {
domainId = atoi(argv[1]);
}
if (argc >= 3) {
sample_count = atoi(argv[2]);
}
/* Uncomment this to turn on additional logging
NDDSConfigLogger::get_instance()->
set_verbosity_by_category(NDDS_CONFIG_LOG_CATEGORY_API,
NDDS_CONFIG_LOG_VERBOSITY_STATUS_ALL);
*/
return subscriber_main(domainId, sample_count);
}
#endif
#ifdef RTI_VX653
const unsigned char *__ctype = *(__ctypePtrGet());
extern "C" void usrAppInit()
{
#ifdef USER_APPL_INIT
USER_APPL_INIT; /* for backwards compatibility */
#endif
/* add application specific code here */
taskSpawn(
"sub",
RTI_OSAPI_THREAD_PRIORITY_NORMAL,
0x8,
0x150000,
(FUNCPTR) subscriber_main,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0);
}
#endif
| cxx |
rticonnextdds-examples | data/projects/rticonnextdds-examples/connext_dds/using_sequences/c++98/sequences_publisher.cxx | /*******************************************************************************
(c) 2005-2014 Copyright, Real-Time Innovations, Inc. All rights reserved.
RTI grants Licensee a license to use, modify, compile, and create derivative
works of the Software. Licensee has the right to distribute object form only
for use with RTI products. The Software is provided "as is", with no warranty
of any type, including any warranty for fitness for any purpose. RTI is under
no obligation to maintain or support the Software. RTI shall not be liable for
any incidental or consequential damages arising out of the use or inability to
use the software.
******************************************************************************/
#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include "sequences.h"
#include "sequencesSupport.h"
#include "ndds/ndds_cpp.h"
#include "application.h"
using namespace application;
static int shutdown_participant(
DDSDomainParticipant *participant,
const char *shutdown_message,
int status);
int run_publisher_application(unsigned int domain_id, unsigned int sample_count)
{
/* Send a new sample every second */
DDS_Duration_t send_period = { 1, 0 };
// Start communicating in a domain, usually one participant per application
DDSDomainParticipant *participant =
DDSTheParticipantFactory->create_participant(
domain_id,
DDS_PARTICIPANT_QOS_DEFAULT,
NULL /* listener */,
DDS_STATUS_MASK_NONE);
if (participant == NULL) {
return shutdown_participant(
participant,
"create_participant error",
EXIT_FAILURE);
}
// A Publisher allows an application to create one or more DataWriters
DDSPublisher *publisher = participant->create_publisher(
DDS_PUBLISHER_QOS_DEFAULT,
NULL /* listener */,
DDS_STATUS_MASK_NONE);
if (publisher == NULL) {
return shutdown_participant(
participant,
"create_publisher error",
EXIT_FAILURE);
}
// Register the datatype to use when creating the Topic
const char *type_name = sequencesTypeSupport::get_type_name();
DDS_ReturnCode_t retcode =
sequencesTypeSupport::register_type(participant, type_name);
if (retcode != DDS_RETCODE_OK) {
return shutdown_participant(
participant,
"register_type error",
EXIT_FAILURE);
}
// Create a Topic with a name and a datatype
DDSTopic *topic = participant->create_topic(
"Example sequences",
type_name,
DDS_TOPIC_QOS_DEFAULT,
NULL /* listener */,
DDS_STATUS_MASK_NONE);
if (topic == NULL) {
return shutdown_participant(
participant,
"create_topic error",
EXIT_FAILURE);
}
// This DataWriter writes data on "Example sequences" Topic
DDSDataWriter *untyped_writer = publisher->create_datawriter(
topic,
DDS_DATAWRITER_QOS_DEFAULT,
NULL /* listener */,
DDS_STATUS_MASK_NONE);
if (untyped_writer == NULL) {
return shutdown_participant(
participant,
"create_datawriter error",
EXIT_FAILURE);
}
sequencesDataWriter *typed_writer =
sequencesDataWriter::narrow(untyped_writer);
if (typed_writer == NULL) {
return shutdown_participant(
participant,
"DataWriter narrow error",
EXIT_FAILURE);
}
/* Here we define two instances: owner_instance and borrower_instance. */
/* owner_instance.data uses its own memory, as by default, a sequence
* you create owns its memory unless you explicitly loan memory of your
* own to it.
*/
sequences *owner_instance = sequencesTypeSupport::create_data();
if (owner_instance == NULL) {
return shutdown_participant(
participant,
"sequencesTypeSupport::create_data error",
EXIT_FAILURE);
}
/* borrower_instance.data "borrows" memory from a buffer of shorts,
* previously allocated, using DDS_ShortSeq_loan_contiguous(). */
sequences *borrower_instance = sequencesTypeSupport::create_data();
if (borrower_instance == NULL) {
return shutdown_participant(
participant,
"sequencesTypeSupport::create_data error",
EXIT_FAILURE);
}
/* If we want borrower_instance.data to loan a buffer of shorts, first we
* have to allocate the buffer. Here we allocate a buffer of
* MAX_SEQUENCE_LEN. */
short *short_buffer = new short[MAX_SEQUENCE_LEN];
/* Before calling loan_contiguous(), we need to set Seq.maximum to
* 0, i.e., the sequence won't have memory allocated to it. */
borrower_instance->data.maximum(0);
/* Now that the sequence doesn't have memory allocated to it, we can use
* loan_contiguous() to loan short_buffer to borrower_instance.
* We set the allocated number of elements to MAX_SEQUENCE_LEN, the size of
* the buffer and the maximum size of the sequence as we declared in the
* IDL. */
bool return_result = borrower_instance->data.loan_contiguous(
short_buffer, // Pointer to the sequence
0, // Initial Length
MAX_SEQUENCE_LEN // New maximum
);
if (return_result != DDS_BOOLEAN_TRUE) {
return shutdown_participant(
participant,
"loan_contiguous error",
EXIT_FAILURE);
}
/* Before starting to publish samples, set the instance id of each
* instance*/
strcpy(owner_instance->id, "owner_instance");
strcpy(borrower_instance->id, "borrower_instance");
/* To illustrate the use of the sequences, in the main loop we set a
* new sequence length every iteration to the sequences contained in
* both instances (instance->data). The sequence length value cycles between
* 0 and MAX_SEQUENCE_LEN. We assign a random number between 0 and 100 to
* each sequence's elements. */
for (unsigned int samples_written = 0;
!shutdown_requested && samples_written < sample_count;
++samples_written) {
/* We set a different sequence_length for both instances every
* iteration. sequence_length is based on the value of count and
* its value cycles between the values of 1 and MAX_SEQUENCE_LEN. */
short sequence_length = (samples_written % MAX_SEQUENCE_LEN) + 1;
std::cout << "Writing sequences, count " << samples_written << "...\n";
owner_instance->count = samples_written;
borrower_instance->count = samples_written;
/* Here we set the new length of each sequence */
owner_instance->data.length(sequence_length);
borrower_instance->data.length(sequence_length);
/* Now that the sequences have a new length, we assign a
* random number between 0 and 100 to each element of
* owner_instance->data and borrower_instance->data. */
for (int i = 0; i < sequence_length; ++i) {
owner_instance->data[i] = (short) (rand() / (RAND_MAX / 100));
borrower_instance->data[i] = (short) (rand() / (RAND_MAX / 100));
}
/* Both sequences have the same length, so we only print the length
* of one of them. */
std::cout << "Instances length = " << owner_instance->data.length()
<< std::endl;
/* Write for each instance */
retcode = typed_writer->write(*owner_instance, DDS_HANDLE_NIL);
if (retcode != DDS_RETCODE_OK) {
std::cerr << "write error " << retcode << std::endl;
}
retcode = typed_writer->write(*borrower_instance, DDS_HANDLE_NIL);
if (retcode != DDS_RETCODE_OK) {
std::cerr << "write error " << retcode << std::endl;
}
NDDSUtility::sleep(send_period);
}
/* Once we are done with the sequence, we unloan and free the buffer. Make
* sure you don't call delete before unloan(); the next time you
* access the sequence, you will be accessing freed memory. */
return_result = borrower_instance->data.unloan();
if (return_result != DDS_BOOLEAN_TRUE) {
std::cerr << "unloan error \n";
}
delete[] short_buffer;
// Delete previously allocated sequences, including all contained elements
retcode = sequencesTypeSupport::delete_data(owner_instance);
if (retcode != DDS_RETCODE_OK) {
std::cerr << "sequencesTypeSupport::delete_data error " << retcode
<< std::endl;
}
retcode = sequencesTypeSupport::delete_data(borrower_instance);
if (retcode != DDS_RETCODE_OK) {
std::cerr << "sequencesTypeSupport::delete_data error " << retcode
<< std::endl;
}
// Delete all entities (DataWriter, Topic, Publisher, DomainParticipant)
return shutdown_participant(participant, "Shutting down", EXIT_SUCCESS);
}
// Delete all entities
static int shutdown_participant(
DDSDomainParticipant *participant,
const char *shutdown_message,
int status)
{
DDS_ReturnCode_t retcode;
std::cout << shutdown_message << std::endl;
if (participant != NULL) {
// Cleanup everything created by this Participant
retcode = participant->delete_contained_entities();
if (retcode != DDS_RETCODE_OK) {
std::cerr << "delete_contained_entities error " << retcode
<< std::endl;
status = EXIT_FAILURE;
}
retcode = DDSTheParticipantFactory->delete_participant(participant);
if (retcode != DDS_RETCODE_OK) {
std::cerr << "delete_participant error " << retcode << std::endl;
status = EXIT_FAILURE;
}
}
return status;
}
int main(int argc, char *argv[])
{
// Parse arguments and handle control-C
ApplicationArguments arguments;
parse_arguments(arguments, argc, argv);
if (arguments.parse_result == PARSE_RETURN_EXIT) {
return EXIT_SUCCESS;
} else if (arguments.parse_result == PARSE_RETURN_FAILURE) {
return EXIT_FAILURE;
}
setup_signal_handlers();
// Sets Connext verbosity to help debugging
NDDSConfigLogger::get_instance()->set_verbosity(arguments.verbosity);
int status = run_publisher_application(
arguments.domain_id,
arguments.sample_count);
// Releases the memory used by the participant factory. Optional at
// application exit
DDS_ReturnCode_t retcode = DDSDomainParticipantFactory::finalize_instance();
if (retcode != DDS_RETCODE_OK) {
std::cerr << "finalize_instance error " << retcode << std::endl;
status = EXIT_FAILURE;
}
return status;
}
| cxx |
rticonnextdds-examples | data/projects/rticonnextdds-examples/connext_dds/using_sequences/c++98/sequences_subscriber.cxx | /*******************************************************************************
(c) 2005-2014 Copyright, Real-Time Innovations, Inc. All rights reserved.
RTI grants Licensee a license to use, modify, compile, and create derivative
works of the Software. Licensee has the right to distribute object form only
for use with RTI products. The Software is provided "as is", with no warranty
of any type, including any warranty for fitness for any purpose. RTI is under
no obligation to maintain or support the Software. RTI shall not be liable for
any incidental or consequential damages arising out of the use or inability to
use the software.
******************************************************************************/
#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include "sequences.h"
#include "sequencesSupport.h"
#include "ndds/ndds_cpp.h"
#include "application.h"
using namespace application;
static int shutdown_participant(
DDSDomainParticipant *participant,
const char *shutdown_message,
int status);
unsigned int process_data(sequencesDataReader *typed_reader)
{
sequencesSeq data_seq;
DDS_SampleInfoSeq info_seq;
unsigned int samples_read = 0;
typed_reader->take(
data_seq,
info_seq,
DDS_LENGTH_UNLIMITED,
DDS_ANY_SAMPLE_STATE,
DDS_ANY_VIEW_STATE,
DDS_ANY_INSTANCE_STATE);
for (int i = 0; i < data_seq.length(); ++i) {
if (info_seq[i].valid_data) {
sequencesTypeSupport::print_data(&data_seq[i]);
samples_read++;
}
}
DDS_ReturnCode_t retcode = typed_reader->return_loan(data_seq, info_seq);
if (retcode != DDS_RETCODE_OK) {
std::cerr << "return loan error " << retcode << std::endl;
}
return samples_read;
}
int run_subscriber_application(
unsigned int domain_id,
unsigned int sample_count)
{
DDS_Duration_t wait_timeout = { 4, 0 };
// Start communicating in a domain, usually one participant per application
DDSDomainParticipant *participant =
DDSTheParticipantFactory->create_participant(
domain_id,
DDS_PARTICIPANT_QOS_DEFAULT,
NULL /* listener */,
DDS_STATUS_MASK_NONE);
if (participant == NULL) {
return shutdown_participant(
participant,
"create_participant error",
EXIT_FAILURE);
}
// A Subscriber allows an application to create one or more DataReaders
DDSSubscriber *subscriber = participant->create_subscriber(
DDS_SUBSCRIBER_QOS_DEFAULT,
NULL /* listener */,
DDS_STATUS_MASK_NONE);
if (subscriber == NULL) {
return shutdown_participant(
participant,
"create_subscriber error",
EXIT_FAILURE);
}
// Register the datatype to use when creating the Topic
const char *type_name = sequencesTypeSupport::get_type_name();
DDS_ReturnCode_t retcode =
sequencesTypeSupport::register_type(participant, type_name);
if (retcode != DDS_RETCODE_OK) {
return shutdown_participant(
participant,
"register_type error",
EXIT_FAILURE);
}
// Create a Topic with a name and a datatype
DDSTopic *topic = participant->create_topic(
"Example sequences",
type_name,
DDS_TOPIC_QOS_DEFAULT,
NULL /* listener */,
DDS_STATUS_MASK_NONE);
if (topic == NULL) {
return shutdown_participant(
participant,
"create_topic error",
EXIT_FAILURE);
}
// This DataReader reads data on "Example sequences" Topic
DDSDataReader *untyped_reader = subscriber->create_datareader(
topic,
DDS_DATAREADER_QOS_DEFAULT,
NULL,
DDS_STATUS_MASK_ALL);
if (untyped_reader == NULL) {
return shutdown_participant(
participant,
"create_datareader error",
EXIT_FAILURE);
}
// Narrow casts from a untyped DataReader to a reader of your type
sequencesDataReader *typed_reader =
sequencesDataReader::narrow(untyped_reader);
if (typed_reader == NULL) {
return shutdown_participant(
participant,
"DataReader narrow error",
EXIT_FAILURE);
}
// Create ReadCondition that triggers when unread data in reader's queue
DDSReadCondition *read_condition = typed_reader->create_readcondition(
DDS_NOT_READ_SAMPLE_STATE,
DDS_ANY_VIEW_STATE,
DDS_ANY_INSTANCE_STATE);
if (read_condition == NULL) {
return shutdown_participant(
participant,
"create_readcondition error",
EXIT_FAILURE);
}
// WaitSet will be woken when the attached condition is triggered
DDSWaitSet waitset;
retcode = waitset.attach_condition(read_condition);
if (retcode != DDS_RETCODE_OK) {
return shutdown_participant(
participant,
"attach_condition error",
EXIT_FAILURE);
}
// Main loop. Wait for data to arrive, and process when it arrives
unsigned int samples_read = 0;
while (!shutdown_requested && samples_read < sample_count) {
DDSConditionSeq active_conditions_seq;
// Wait for data and report if it does not arrive in 4 seconds
retcode = waitset.wait(active_conditions_seq, wait_timeout);
if (retcode == DDS_RETCODE_OK) {
// If the read condition is triggered, process data
samples_read += process_data(typed_reader);
} else {
if (retcode == DDS_RETCODE_TIMEOUT) {
std::cout << "No data after " << wait_timeout.sec << " seconds"
<< std::endl;
}
}
}
// Cleanup
return shutdown_participant(participant, "Shutting down", 0);
}
// Delete all entities
static int shutdown_participant(
DDSDomainParticipant *participant,
const char *shutdown_message,
int status)
{
DDS_ReturnCode_t retcode;
std::cout << shutdown_message << std::endl;
if (participant != NULL) {
// Cleanup everything created by this Participant
retcode = participant->delete_contained_entities();
if (retcode != DDS_RETCODE_OK) {
std::cerr << "delete_contained_entities error" << retcode
<< std::endl;
status = EXIT_FAILURE;
}
retcode = DDSTheParticipantFactory->delete_participant(participant);
if (retcode != DDS_RETCODE_OK) {
std::cerr << "delete_participant error" << retcode << std::endl;
status = EXIT_FAILURE;
}
}
return status;
}
int main(int argc, char *argv[])
{
// Parse arguments and handle control-C
ApplicationArguments arguments;
parse_arguments(arguments, argc, argv);
if (arguments.parse_result == PARSE_RETURN_EXIT) {
return EXIT_SUCCESS;
} else if (arguments.parse_result == PARSE_RETURN_FAILURE) {
return EXIT_FAILURE;
}
setup_signal_handlers();
// Sets Connext verbosity to help debugging
NDDSConfigLogger::get_instance()->set_verbosity(arguments.verbosity);
int status = run_subscriber_application(
arguments.domain_id,
arguments.sample_count);
// Releases the memory used by the participant factory. Optional at
// application exit
DDS_ReturnCode_t retcode = DDSDomainParticipantFactory::finalize_instance();
if (retcode != DDS_RETCODE_OK) {
std::cerr << "finalize_instance error" << retcode << std::endl;
status = EXIT_FAILURE;
}
return status;
}
| cxx |
rticonnextdds-examples | data/projects/rticonnextdds-examples/connext_dds/using_sequences/c++98/application.h | /*
* (c) Copyright, Real-Time Innovations, 2020. All rights reserved.
* RTI grants Licensee a license to use, modify, compile, and create derivative
* works of the software solely for use with RTI Connext DDS. Licensee may
* redistribute copies of the software provided that all such copies are subject
* to this license. The software is provided "as is", with no warranty of any
* type, including any warranty for fitness for any purpose. RTI is under no
* obligation to maintain or support the software. RTI shall not be liable for
* any incidental or consequential damages arising out of the use or inability
* to use the software.
*/
#ifndef APPLICATION_H
#define APPLICATION_H
#include <iostream>
#include <csignal>
#include <climits>
namespace application {
// Catch control-C and tell application to shut down
bool shutdown_requested = false;
inline void stop_handler(int)
{
shutdown_requested = true;
std::cout << "preparing to shut down..." << std::endl;
}
inline void setup_signal_handlers()
{
signal(SIGINT, stop_handler);
signal(SIGTERM, stop_handler);
}
enum ParseReturn { PARSE_RETURN_OK, PARSE_RETURN_FAILURE, PARSE_RETURN_EXIT };
struct ApplicationArguments {
ParseReturn parse_result;
unsigned int domain_id;
unsigned int sample_count;
NDDS_Config_LogVerbosity verbosity;
};
inline void set_verbosity(ApplicationArguments &arguments, int verbosity)
{
switch (verbosity) {
case 0:
arguments.verbosity = NDDS_CONFIG_LOG_VERBOSITY_SILENT;
break;
case 1:
arguments.verbosity = NDDS_CONFIG_LOG_VERBOSITY_ERROR;
break;
case 2:
arguments.verbosity = NDDS_CONFIG_LOG_VERBOSITY_WARNING;
break;
case 3:
arguments.verbosity = NDDS_CONFIG_LOG_VERBOSITY_STATUS_ALL;
break;
default:
arguments.verbosity = NDDS_CONFIG_LOG_VERBOSITY_ERROR;
break;
}
}
// Parses application arguments for example. Returns whether to exit.
inline void parse_arguments(
ApplicationArguments &arguments,
int argc,
char *argv[])
{
int arg_processing = 1;
bool show_usage = false;
arguments.domain_id = 0;
arguments.sample_count = INT_MAX;
arguments.verbosity = NDDS_CONFIG_LOG_VERBOSITY_ERROR;
arguments.parse_result = PARSE_RETURN_OK;
while (arg_processing < argc) {
if ((argc > arg_processing + 1)
&& (strcmp(argv[arg_processing], "-d") == 0
|| strcmp(argv[arg_processing], "--domain") == 0)) {
arguments.domain_id = atoi(argv[arg_processing + 1]);
arg_processing += 2;
} else if (
(argc > arg_processing + 1)
&& (strcmp(argv[arg_processing], "-s") == 0
|| strcmp(argv[arg_processing], "--sample-count") == 0)) {
arguments.sample_count = atoi(argv[arg_processing + 1]);
arg_processing += 2;
} else if (
(argc > arg_processing + 1)
&& (strcmp(argv[arg_processing], "-v") == 0
|| strcmp(argv[arg_processing], "--verbosity") == 0)) {
set_verbosity(arguments, atoi(argv[arg_processing + 1]));
arg_processing += 2;
} else if (
strcmp(argv[arg_processing], "-h") == 0
|| strcmp(argv[arg_processing], "--help") == 0) {
std::cout << "Example application." << std::endl;
show_usage = true;
arguments.parse_result = PARSE_RETURN_EXIT;
break;
} else {
std::cout << "Bad parameter." << std::endl;
show_usage = true;
arguments.parse_result = PARSE_RETURN_FAILURE;
break;
}
}
if (show_usage) {
std::cout << "Usage:\n"
" -d, --domain <int> Domain ID this "
"application will\n"
" subscribe in. \n"
" Default: 0\n"
" -s, --sample_count <int> Number of samples to "
"receive before\n"
" cleanly shutting down. \n"
" Default: infinite\n"
" -v, --verbosity <int> How much debugging output "
"to show.\n"
" Range: 0-3 \n"
" Default: 1"
<< std::endl;
}
}
} // namespace application
#endif // APPLICATION_H
| h |
rticonnextdds-examples | data/projects/rticonnextdds-examples/connext_dds/using_sequences/c/sequences_publisher.c | /*******************************************************************************
(c) 2005-2014 Copyright, Real-Time Innovations, Inc. All rights reserved.
RTI grants Licensee a license to use, modify, compile, and create derivative
works of the Software. Licensee has the right to distribute object form only
for use with RTI products. The Software is provided "as is", with no warranty
of any type, including any warranty for fitness for any purpose. RTI is under
no obligation to maintain or support the Software. RTI shall not be liable for
any incidental or consequential damages arising out of the use or inability to
use the software.
******************************************************************************/
/* sequences_publisher.c
A publication of data of type sequences
This file is derived from code automatically generated by the rtiddsgen
command:
rtiddsgen -language C -example <arch> sequences.idl
Example publication of type sequences automatically generated by
'rtiddsgen'. To test them follow these steps:
(1) Compile this file and the example subscription.
(2) Start the subscription with the command
objs/<arch>/sequences_subscriber <domain_id> <sample_count>
(3) Start the publication with the command
objs/<arch>/sequences_publisher <domain_id> <sample_count>
(4) [Optional] Specify the list of discovery initial peers and
multicast receive addresses via an environment variable or a file
(in the current working directory) called NDDS_DISCOVERY_PEERS.
You can run any number of publishers and subscribers programs, and can
add and remove them dynamically from the domain.
Example:
To run the example application on domain <domain_id>:
On Unix:
objs/<arch>/sequences_publisher <domain_id>
objs/<arch>/sequences_subscriber <domain_id>
On Windows:
objs\<arch>\sequences_publisher <domain_id>
objs\<arch>\sequences_subscriber <domain_id>
modification history
------------ -------
*/
#include "ndds/ndds_c.h"
#include "sequences.h"
#include "sequencesSupport.h"
#include <stdio.h>
#include <stdlib.h>
/* Delete all entities */
static int publisher_shutdown(DDS_DomainParticipant *participant)
{
DDS_ReturnCode_t retcode;
int status = 0;
if (participant != NULL) {
retcode = DDS_DomainParticipant_delete_contained_entities(participant);
if (retcode != DDS_RETCODE_OK) {
printf("delete_contained_entities error %d\n", retcode);
status = -1;
}
retcode = DDS_DomainParticipantFactory_delete_participant(
DDS_TheParticipantFactory,
participant);
if (retcode != DDS_RETCODE_OK) {
printf("delete_participant error %d\n", retcode);
status = -1;
}
}
/* RTI Connext provides finalize_instance() method on
domain participant factory for people who want to release memory used
by the participant factory. Uncomment the following block of code for
clean destruction of the singleton. */
/*
retcode = DDS_DomainParticipantFactory_finalize_instance();
if (retcode != DDS_RETCODE_OK) {
printf("finalize_instance error %d\n", retcode);
status = -1;
}
*/
return status;
}
static int publisher_main(int domainId, int sample_count)
{
DDS_DomainParticipant *participant = NULL;
DDS_Publisher *publisher = NULL;
DDS_Topic *topic = NULL;
DDS_DataWriter *writer = NULL;
sequencesDataWriter *sequences_writer = NULL;
/* We define two instances to illustrate the different memory use of
* sequences: owner_instance and borrower_instance. */
sequences *owner_instance = NULL;
sequences *borrower_instance = NULL;
DDS_InstanceHandle_t owner_instance_handle = DDS_HANDLE_NIL;
DDS_InstanceHandle_t borrower_instance_handle = DDS_HANDLE_NIL;
DDS_ReturnCode_t retcode;
const char *type_name = NULL;
int i, count = 0;
/* Send a new sample every second */
struct DDS_Duration_t send_period = { 1, 0 };
/* Buffer of shorts that borrower_instance loans */
short *short_buffer = NULL;
/* To customize participant QoS, use
the configuration file USER_QOS_PROFILES.xml */
participant = DDS_DomainParticipantFactory_create_participant(
DDS_TheParticipantFactory,
domainId,
&DDS_PARTICIPANT_QOS_DEFAULT,
NULL /* listener */,
DDS_STATUS_MASK_NONE);
if (participant == NULL) {
printf("create_participant error\n");
publisher_shutdown(participant);
return -1;
}
/* To customize publisher QoS, use
the configuration file USER_QOS_PROFILES.xml */
publisher = DDS_DomainParticipant_create_publisher(
participant,
&DDS_PUBLISHER_QOS_DEFAULT,
NULL /* listener */,
DDS_STATUS_MASK_NONE);
if (publisher == NULL) {
printf("create_publisher error\n");
publisher_shutdown(participant);
return -1;
}
/* Register type before creating topic */
type_name = sequencesTypeSupport_get_type_name();
retcode = sequencesTypeSupport_register_type(participant, type_name);
if (retcode != DDS_RETCODE_OK) {
printf("register_type error %d\n", retcode);
publisher_shutdown(participant);
return -1;
}
/* To customize topic QoS, use
the configuration file USER_QOS_PROFILES.xml */
topic = DDS_DomainParticipant_create_topic(
participant,
"Example sequences",
type_name,
&DDS_TOPIC_QOS_DEFAULT,
NULL /* listener */,
DDS_STATUS_MASK_NONE);
if (topic == NULL) {
printf("create_topic error\n");
publisher_shutdown(participant);
return -1;
}
/* To customize data writer QoS, use
the configuration file USER_QOS_PROFILES.xml */
writer = DDS_Publisher_create_datawriter(
publisher,
topic,
&DDS_DATAWRITER_QOS_DEFAULT,
NULL /* listener */,
DDS_STATUS_MASK_NONE);
if (writer == NULL) {
printf("create_datawriter error\n");
publisher_shutdown(participant);
return -1;
}
sequences_writer = sequencesDataWriter_narrow(writer);
if (sequences_writer == NULL) {
printf("DataWriter narrow error\n");
publisher_shutdown(participant);
return -1;
}
/* Here we define two instances: owner_instance and borrower_instance. */
/* owner_instance.data uses its own memory, as by default, a sequence
* you create owns its memory unless you explicitly loan memory of your
* own to it. */
owner_instance = sequencesTypeSupport_create_data_ex(DDS_BOOLEAN_TRUE);
if (owner_instance == NULL) {
printf("sequencesTypeSupport_create_data error\n");
publisher_shutdown(participant);
return -1;
}
/* borrower_instance.data "borrows" memory from a buffer of shorts,
* previously allocated, using DDS_ShortSeq_loan_contiguous(). */
borrower_instance = sequencesTypeSupport_create_data_ex(DDS_BOOLEAN_TRUE);
if (borrower_instance == NULL) {
printf("sequencesTypeSupport_create_data error\n");
publisher_shutdown(participant);
return -1;
}
/* If we want borrower_instance.data to loan a buffer of shorts, first we
* have to allocate the buffer. Here we allocate a buffer of
* MAX_SEQUENCE_LEN. */
short_buffer = (short *) malloc(MAX_SEQUENCE_LEN * sizeof(short));
if (short_buffer == NULL) {
printf("short_buffer malloc error\n");
publisher_shutdown(participant);
return -1;
}
/* Before calling DDS_ShortSeq_loan_contiguous(), we need to set
* DDS_ShortSeq_get_maximum() to 0, i.e., the sequence won't have
* memory allocated to it. */
DDS_ShortSeq_set_maximum(&borrower_instance->data, 0);
/* Now that the sequence doesn't have memory allocated to it, we can use
* DDS_ShortSeq_loan_contiguous() to loan short_buffer to borrower_instance.
* We set the allocated number of elements to MAX_SEQUENCE_LEN, the size of
* the buffer and the maximum size of the sequence as we declared in the
* IDL. */
DDS_ShortSeq_loan_contiguous(
&borrower_instance->data, /* Pointer to the sequence */
short_buffer, /* Buffer it loans */
0, /* Initial Length */
MAX_SEQUENCE_LEN /* New maximum */
);
/* Before starting to publish samples, set the instance id of each
* instance */
strcpy(owner_instance->id, "owner_instance");
strcpy(borrower_instance->id, "borrower_instance");
/* To illustrate the use of the sequences, in the main loop we set a
* new sequence length every iteration to the sequences contained in
* both instances (instance->data). The sequence length value cycles between
* 0 and MAX_SEQUENCE_LEN. We assign a random number between 0 and 100 to
* each sequence's elements. */
for (count = 0; (sample_count == 0) || (count < sample_count); ++count) {
/* We set a different sequence_length for both instances every
* iteration. sequence_length is based on the value of count and
* its value cycles between the values of 1 and MAX_SEQUENCE_LEN. */
short sequence_length = (count % MAX_SEQUENCE_LEN) + 1;
printf("Writing sequences, count %d...\n", count);
owner_instance->count = (short) count;
borrower_instance->count = (short) count;
/* Here we set the new length of each sequence */
DDS_ShortSeq_set_length(&owner_instance->data, sequence_length);
DDS_ShortSeq_set_length(&borrower_instance->data, sequence_length);
/* Now that the sequences have a new length, we assign a
* random number between 0 and 100 to each element of
* owner_instance->data and borrower_instance->data. */
for (i = 0; i < sequence_length; ++i) {
*DDS_ShortSeq_get_reference(&owner_instance->data, i) =
(short) (rand() / (RAND_MAX / 100));
*DDS_ShortSeq_get_reference(&borrower_instance->data, i) =
(short) (rand() / (RAND_MAX / 100));
}
/* Both sequences have the same length, so we only print the length
* of one of them. */
printf("Instances length = %d\n",
DDS_ShortSeq_get_length(&owner_instance->data));
/* Write for each instance */
retcode = sequencesDataWriter_write(
sequences_writer,
owner_instance,
&owner_instance_handle);
if (retcode != DDS_RETCODE_OK) {
printf("write error %d\n", retcode);
}
retcode = sequencesDataWriter_write(
sequences_writer,
borrower_instance,
&borrower_instance_handle);
if (retcode != DDS_RETCODE_OK) {
printf("write error %d\n", retcode);
}
NDDS_Utility_sleep(&send_period);
}
/* Once we are done with the sequence, we unloan and free the buffer. Make
* sure you don't call free before DDS_ShortSeq_unloan(); the next time you
* access the sequence, you will be accessing freed memory. */
if (!DDS_ShortSeq_unloan(&borrower_instance->data)) {
printf("Unloan error\n");
}
free(short_buffer);
/* Delete data samples */
retcode = sequencesTypeSupport_delete_data_ex(
owner_instance,
DDS_BOOLEAN_TRUE);
if (retcode != DDS_RETCODE_OK) {
printf("sequencesTypeSupport_delete_data error %d\n", retcode);
}
retcode = sequencesTypeSupport_delete_data_ex(
borrower_instance,
DDS_BOOLEAN_TRUE);
if (retcode != DDS_RETCODE_OK) {
printf("sequencesTypeSupport_delete_data error %d\n", retcode);
}
/* Cleanup and delete delete all entities */
return publisher_shutdown(participant);
}
#if defined(RTI_WINCE)
int wmain(int argc, wchar_t **argv)
{
int domainId = 0;
int sample_count = 0; /* infinite loop */
if (argc >= 2) {
domainId = _wtoi(argv[1]);
}
if (argc >= 3) {
sample_count = _wtoi(argv[2]);
}
/* Uncomment this to turn on additional logging
NDDS_Config_Logger_set_verbosity_by_category(
NDDS_Config_Logger_get_instance(),
NDDS_CONFIG_LOG_CATEGORY_API,
NDDS_CONFIG_LOG_VERBOSITY_STATUS_ALL);
*/
return publisher_main(domainId, sample_count);
}
#elif !(defined(RTI_VXWORKS) && !defined(__RTP__)) && !defined(RTI_PSOS)
int main(int argc, char *argv[])
{
int domainId = 0;
int sample_count = 0; /* infinite loop */
if (argc >= 2) {
domainId = atoi(argv[1]);
}
if (argc >= 3) {
sample_count = atoi(argv[2]);
}
/* Uncomment this to turn on additional logging
NDDS_Config_Logger_set_verbosity_by_category(
NDDS_Config_Logger_get_instance(),
NDDS_CONFIG_LOG_CATEGORY_API,
NDDS_CONFIG_LOG_VERBOSITY_STATUS_ALL);
*/
return publisher_main(domainId, sample_count);
}
#endif
#ifdef RTI_VX653
const unsigned char *__ctype = NULL;
void usrAppInit()
{
#ifdef USER_APPL_INIT
USER_APPL_INIT; /* for backwards compatibility */
#endif
/* add application specific code here */
taskSpawn(
"pub",
RTI_OSAPI_THREAD_PRIORITY_NORMAL,
0x8,
0x150000,
(FUNCPTR) publisher_main,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0);
}
#endif
| c |
rticonnextdds-examples | data/projects/rticonnextdds-examples/connext_dds/using_sequences/c/sequences_subscriber.c | /*******************************************************************************
(c) 2005-2014 Copyright, Real-Time Innovations, Inc. All rights reserved.
RTI grants Licensee a license to use, modify, compile, and create derivative
works of the Software. Licensee has the right to distribute object form only
for use with RTI products. The Software is provided "as is", with no warranty
of any type, including any warranty for fitness for any purpose. RTI is under
no obligation to maintain or support the Software. RTI shall not be liable for
any incidental or consequential damages arising out of the use or inability to
use the software.
******************************************************************************/
/* sequences_subscriber.c
A subscription example
This file is derived from code automatically generated by the rtiddsgen
command:
rtiddsgen -language C -example <arch> sequences.idl
Example subscription of type sequences automatically generated by
'rtiddsgen'. To test them, follow these steps:
(1) Compile this file and the example publication.
(2) Start the subscription with the command
objs/<arch>/sequences_subscriber <domain_id> <sample_count>
(3) Start the publication with the command
objs/<arch>/sequences_publisher <domain_id> <sample_count>
(4) [Optional] Specify the list of discovery initial peers and
multicast receive addresses via an environment variable or a file
(in the current working directory) called NDDS_DISCOVERY_PEERS.
You can run any number of publishers and subscribers programs, and can
add and remove them dynamically from the domain.
Example:
To run the example application on domain <domain_id>:
On UNIX systems:
objs/<arch>/sequences_publisher <domain_id>
objs/<arch>/sequences_subscriber <domain_id>
On Windows systems:
objs\<arch>\sequences_publisher <domain_id>
objs\<arch>\sequences_subscriber <domain_id>
modification history
------------ -------
*/
#include "ndds/ndds_c.h"
#include "sequences.h"
#include "sequencesSupport.h"
#include <stdio.h>
#include <stdlib.h>
void sequencesListener_on_requested_deadline_missed(
void *listener_data,
DDS_DataReader *reader,
const struct DDS_RequestedDeadlineMissedStatus *status)
{
}
void sequencesListener_on_requested_incompatible_qos(
void *listener_data,
DDS_DataReader *reader,
const struct DDS_RequestedIncompatibleQosStatus *status)
{
}
void sequencesListener_on_sample_rejected(
void *listener_data,
DDS_DataReader *reader,
const struct DDS_SampleRejectedStatus *status)
{
}
void sequencesListener_on_liveliness_changed(
void *listener_data,
DDS_DataReader *reader,
const struct DDS_LivelinessChangedStatus *status)
{
}
void sequencesListener_on_sample_lost(
void *listener_data,
DDS_DataReader *reader,
const struct DDS_SampleLostStatus *status)
{
}
void sequencesListener_on_subscription_matched(
void *listener_data,
DDS_DataReader *reader,
const struct DDS_SubscriptionMatchedStatus *status)
{
}
void sequencesListener_on_data_available(
void *listener_data,
DDS_DataReader *reader)
{
sequencesDataReader *sequences_reader = NULL;
struct sequencesSeq data_seq = DDS_SEQUENCE_INITIALIZER;
struct DDS_SampleInfoSeq info_seq = DDS_SEQUENCE_INITIALIZER;
DDS_ReturnCode_t retcode;
int i;
sequences_reader = sequencesDataReader_narrow(reader);
if (sequences_reader == NULL) {
printf("DataReader narrow error\n");
return;
}
retcode = sequencesDataReader_take(
sequences_reader,
&data_seq,
&info_seq,
DDS_LENGTH_UNLIMITED,
DDS_ANY_SAMPLE_STATE,
DDS_ANY_VIEW_STATE,
DDS_ANY_INSTANCE_STATE);
if (retcode == DDS_RETCODE_NO_DATA) {
return;
} else if (retcode != DDS_RETCODE_OK) {
printf("take error %d\n", retcode);
return;
}
for (i = 0; i < sequencesSeq_get_length(&data_seq); ++i) {
if (DDS_SampleInfoSeq_get_reference(&info_seq, i)->valid_data) {
sequencesTypeSupport_print_data(
sequencesSeq_get_reference(&data_seq, i));
}
}
retcode = sequencesDataReader_return_loan(
sequences_reader,
&data_seq,
&info_seq);
if (retcode != DDS_RETCODE_OK) {
printf("return loan error %d\n", retcode);
}
}
/* Delete all entities */
static int subscriber_shutdown(DDS_DomainParticipant *participant)
{
DDS_ReturnCode_t retcode;
int status = 0;
if (participant != NULL) {
retcode = DDS_DomainParticipant_delete_contained_entities(participant);
if (retcode != DDS_RETCODE_OK) {
printf("delete_contained_entities error %d\n", retcode);
status = -1;
}
retcode = DDS_DomainParticipantFactory_delete_participant(
DDS_TheParticipantFactory,
participant);
if (retcode != DDS_RETCODE_OK) {
printf("delete_participant error %d\n", retcode);
status = -1;
}
}
/* RTI Connext provides the finalize_instance() method on
domain participant factory for users who want to release memory used
by the participant factory. Uncomment the following block of code for
clean destruction of the singleton. */
/*
retcode = DDS_DomainParticipantFactory_finalize_instance();
if (retcode != DDS_RETCODE_OK) {
printf("finalize_instance error %d\n", retcode);
status = -1;
}
*/
return status;
}
static int subscriber_main(int domainId, int sample_count)
{
DDS_DomainParticipant *participant = NULL;
DDS_Subscriber *subscriber = NULL;
DDS_Topic *topic = NULL;
struct DDS_DataReaderListener reader_listener =
DDS_DataReaderListener_INITIALIZER;
DDS_DataReader *reader = NULL;
DDS_ReturnCode_t retcode;
const char *type_name = NULL;
int count = 0;
struct DDS_Duration_t poll_period = { 4, 0 };
/* To customize participant QoS, use
the configuration file USER_QOS_PROFILES.xml */
participant = DDS_DomainParticipantFactory_create_participant(
DDS_TheParticipantFactory,
domainId,
&DDS_PARTICIPANT_QOS_DEFAULT,
NULL /* listener */,
DDS_STATUS_MASK_NONE);
if (participant == NULL) {
printf("create_participant error\n");
subscriber_shutdown(participant);
return -1;
}
/* To customize subscriber QoS, use
the configuration file USER_QOS_PROFILES.xml */
subscriber = DDS_DomainParticipant_create_subscriber(
participant,
&DDS_SUBSCRIBER_QOS_DEFAULT,
NULL /* listener */,
DDS_STATUS_MASK_NONE);
if (subscriber == NULL) {
printf("create_subscriber error\n");
subscriber_shutdown(participant);
return -1;
}
/* Register the type before creating the topic */
type_name = sequencesTypeSupport_get_type_name();
retcode = sequencesTypeSupport_register_type(participant, type_name);
if (retcode != DDS_RETCODE_OK) {
printf("register_type error %d\n", retcode);
subscriber_shutdown(participant);
return -1;
}
/* To customize topic QoS, use
the configuration file USER_QOS_PROFILES.xml */
topic = DDS_DomainParticipant_create_topic(
participant,
"Example sequences",
type_name,
&DDS_TOPIC_QOS_DEFAULT,
NULL /* listener */,
DDS_STATUS_MASK_NONE);
if (topic == NULL) {
printf("create_topic error\n");
subscriber_shutdown(participant);
return -1;
}
/* Set up a data reader listener */
reader_listener.on_requested_deadline_missed =
sequencesListener_on_requested_deadline_missed;
reader_listener.on_requested_incompatible_qos =
sequencesListener_on_requested_incompatible_qos;
reader_listener.on_sample_rejected = sequencesListener_on_sample_rejected;
reader_listener.on_liveliness_changed =
sequencesListener_on_liveliness_changed;
reader_listener.on_sample_lost = sequencesListener_on_sample_lost;
reader_listener.on_subscription_matched =
sequencesListener_on_subscription_matched;
reader_listener.on_data_available = sequencesListener_on_data_available;
/* To customize data reader QoS, use
the configuration file USER_QOS_PROFILES.xml */
reader = DDS_Subscriber_create_datareader(
subscriber,
DDS_Topic_as_topicdescription(topic),
&DDS_DATAREADER_QOS_DEFAULT,
&reader_listener,
DDS_STATUS_MASK_ALL);
if (reader == NULL) {
printf("create_datareader error\n");
subscriber_shutdown(participant);
return -1;
}
/* Main loop */
for (count = 0; (sample_count == 0) || (count < sample_count); ++count) {
printf("sequences subscriber sleeping for %d sec...\n",
poll_period.sec);
NDDS_Utility_sleep(&poll_period);
}
/* Cleanup and delete all entities */
return subscriber_shutdown(participant);
}
#if defined(RTI_WINCE)
int wmain(int argc, wchar_t **argv)
{
int domainId = 0;
int sample_count = 0; /* infinite loop */
if (argc >= 2) {
domainId = _wtoi(argv[1]);
}
if (argc >= 3) {
sample_count = _wtoi(argv[2]);
}
/* Uncomment this to turn on additional logging
NDDS_Config_Logger_set_verbosity_by_category(
NDDS_Config_Logger_get_instance(),
NDDS_CONFIG_LOG_CATEGORY_API,
NDDS_CONFIG_LOG_VERBOSITY_STATUS_ALL);
*/
return subscriber_main(domainId, sample_count);
}
#elif !(defined(RTI_VXWORKS) && !defined(__RTP__)) && !defined(RTI_PSOS)
int main(int argc, char *argv[])
{
int domainId = 0;
int sample_count = 0; /* infinite loop */
if (argc >= 2) {
domainId = atoi(argv[1]);
}
if (argc >= 3) {
sample_count = atoi(argv[2]);
}
/* Uncomment this to turn on additional logging
NDDS_Config_Logger_set_verbosity_by_category(
NDDS_Config_Logger_get_instance(),
NDDS_CONFIG_LOG_CATEGORY_API,
NDDS_CONFIG_LOG_VERBOSITY_STATUS_ALL);
*/
return subscriber_main(domainId, sample_count);
}
#endif
#ifdef RTI_VX653
const unsigned char *__ctype = NULL;
void usrAppInit()
{
#ifdef USER_APPL_INIT
USER_APPL_INIT; /* for backwards compatibility */
#endif
/* add application specific code here */
taskSpawn(
"sub",
RTI_OSAPI_THREAD_PRIORITY_NORMAL,
0x8,
0x150000,
(FUNCPTR) subscriber_main,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0);
}
#endif
| c |
rticonnextdds-examples | data/projects/rticonnextdds-examples/connext_dds/required_subscription/c++/RequiredSubscriptions_publisher.cxx | /*
* (c) Copyright, Real-Time Innovations, 2021. All rights reserved.
* RTI grants Licensee a license to use, modify, compile, and create derivative
* works of the software solely for use with RTI Connext DDS. Licensee may
* redistribute copies of the software provided that all such copies are subject
* to this license. The software is provided "as is", with no warranty of any
* type, including any warranty for fitness for any purpose. RTI is under no
* obligation to maintain or support the software. RTI shall not be liable for
* any incidental or consequential damages arising out of the use or inability
* to use the software.
*/
#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include "RequiredSubscriptions.h"
#include "RequiredSubscriptionsSupport.h"
#include "ndds/ndds_cpp.h"
#include "application.h"
#include "dds_c/dds_c_infrastructure.h"
using namespace application;
static int shutdown_participant(
DDSDomainParticipant *participant,
const char *shutdown_message,
int status);
int run_publisher_application(unsigned int domain_id, unsigned int sample_count)
{
// Start communicating in a domain, usually one participant per application
DDSDomainParticipant *participant =
DDSTheParticipantFactory->create_participant(
domain_id,
DDS_PARTICIPANT_QOS_DEFAULT,
NULL,
DDS_STATUS_MASK_NONE);
if (participant == NULL) {
return shutdown_participant(
participant,
"create_participant error",
EXIT_FAILURE);
}
// A Publisher allows an application to create one or more DataWriters
DDSPublisher *publisher = participant->create_publisher(
DDS_PUBLISHER_QOS_DEFAULT,
NULL,
DDS_STATUS_MASK_NONE);
if (publisher == NULL) {
return shutdown_participant(
participant,
"create_publisher error",
EXIT_FAILURE);
}
// Register the datatype to use when creating the Topic
const char *type_name = RequiredSubscriptionsTypeSupport::get_type_name();
DDS_ReturnCode_t retcode = RequiredSubscriptionsTypeSupport::register_type(
participant,
type_name);
if (retcode != DDS_RETCODE_OK) {
return shutdown_participant(
participant,
"register_type error",
EXIT_FAILURE);
}
// Create a Topic with a name and a datatype
DDSTopic *topic = participant->create_topic(
"RequiredSubscriptionsTopic",
type_name,
DDS_TOPIC_QOS_DEFAULT,
NULL,
DDS_STATUS_MASK_NONE);
if (topic == NULL) {
return shutdown_participant(
participant,
"create_topic error",
EXIT_FAILURE);
}
// This DataWriter writes data on "RequiredSubscriptionsTopic" Topic
DDSDataWriter *untyped_writer = publisher->create_datawriter(
topic,
DDS_DATAWRITER_QOS_DEFAULT,
NULL,
DDS_STATUS_MASK_NONE);
if (untyped_writer == NULL) {
return shutdown_participant(
participant,
"create_datawriter error",
EXIT_FAILURE);
}
// Narrow casts from an untyped DataWriter to a writer of your type
RequiredSubscriptionsDataWriter *typed_writer =
RequiredSubscriptionsDataWriter::narrow(untyped_writer);
if (typed_writer == NULL) {
return shutdown_participant(
participant,
"DataWriter narrow error",
EXIT_FAILURE);
}
// Create data for writing, allocating all members
RequiredSubscriptions *data =
RequiredSubscriptionsTypeSupport::create_data();
if (data == NULL) {
return shutdown_participant(
participant,
"RequiredSubscriptionsTypeSupport::create_data error",
EXIT_FAILURE);
}
/* Write one sample and wait for acknowledgment from the
Required Subscribers */
std::cout << "Writing RequiredSubscriptions" << std::endl;
retcode = typed_writer->write(*data, DDS_HANDLE_NIL);
if (retcode != DDS_RETCODE_OK) {
return shutdown_participant(
participant,
"typed_writer->write error",
EXIT_FAILURE);
}
retcode = untyped_writer->wait_for_acknowledgments(DDS_DURATION_INFINITE);
if (retcode != DDS_RETCODE_OK) {
return shutdown_participant(
participant,
"untyped_writer->wait_for_acknowledgments error",
EXIT_FAILURE);
}
/* Delete previously allocated RequiredSubscriptions, including all
contained elements */
retcode = RequiredSubscriptionsTypeSupport::delete_data(data);
if (retcode != DDS_RETCODE_OK) {
std::cerr << "RequiredSubscriptionsTypeSupport::delete_data error "
<< retcode << std::endl;
// we don't exit with error status here because the sample has been sent
}
// Delete all entities (DataWriter, Topic, Publisher, DomainParticipant)
return shutdown_participant(participant, "Shutting down", EXIT_SUCCESS);
}
/* Delete all entities */
static int shutdown_participant(
DDSDomainParticipant *participant,
const char *shutdown_message,
int status)
{
DDS_ReturnCode_t retcode;
std::cout << shutdown_message << std::endl;
if (participant != NULL) {
// Cleanup everything created by this Participant
retcode = participant->delete_contained_entities();
if (retcode != DDS_RETCODE_OK) {
std::cerr << "delete_contained_entities error " << retcode
<< std::endl;
status = EXIT_FAILURE;
}
retcode = DDSTheParticipantFactory->delete_participant(participant);
if (retcode != DDS_RETCODE_OK) {
std::cerr << "delete_participant error " << retcode << std::endl;
status = EXIT_FAILURE;
}
}
return status;
}
int main(int argc, char *argv[])
{
// Parse arguments and handle control-C
ApplicationArguments arguments;
parse_arguments(arguments, argc, argv);
if (arguments.parse_result == PARSE_RETURN_EXIT) {
return EXIT_SUCCESS;
} else if (arguments.parse_result == PARSE_RETURN_FAILURE) {
return EXIT_FAILURE;
}
setup_signal_handlers();
// Sets Connext verbosity to help debugging
NDDSConfigLogger::get_instance()->set_verbosity(arguments.verbosity);
int status = run_publisher_application(
arguments.domain_id,
arguments.sample_count);
/* Releases the memory used by the participant factory. Optional at
application exit */
DDS_ReturnCode_t retcode = DDSDomainParticipantFactory::finalize_instance();
if (retcode != DDS_RETCODE_OK) {
std::cerr << "finalize_instance error " << retcode << std::endl;
status = EXIT_FAILURE;
}
return status;
}
| cxx |
rticonnextdds-examples | data/projects/rticonnextdds-examples/connext_dds/required_subscription/c++/RequiredSubscriptions_subscriber.cxx | /*
* (c) Copyright, Real-Time Innovations, 2021. All rights reserved.
* RTI grants Licensee a license to use, modify, compile, and create derivative
* works of the software solely for use with RTI Connext DDS. Licensee may
* redistribute copies of the software provided that all such copies are subject
* to this license. The software is provided "as is", with no warranty of any
* type, including any warranty for fitness for any purpose. RTI is under no
* obligation to maintain or support the software. RTI shall not be liable for
* any incidental or consequential damages arising out of the use or inability
* to use the software.
*/
#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include "RequiredSubscriptions.h"
#include "RequiredSubscriptionsSupport.h"
#include "ndds/ndds_cpp.h"
#include "application.h"
using namespace application;
static int shutdown_participant(
DDSDomainParticipant *participant,
const char *shutdown_message,
int status);
/* Process the data received by the DataReader passed as a parameter.
It returns the number of samples processed. */
unsigned int process_data(RequiredSubscriptionsDataReader *typed_reader)
{
// Sequence of received data
RequiredSubscriptionsSeq data_seq;
// Metadata associated with samples in data_seq
DDS_SampleInfoSeq info_seq;
unsigned int samples_read = 0;
// Take available data from DataReader's queue
typed_reader->take(
data_seq,
info_seq,
DDS_LENGTH_UNLIMITED,
DDS_ANY_SAMPLE_STATE,
DDS_ANY_VIEW_STATE,
DDS_ANY_INSTANCE_STATE);
// Iterate over all available data
for (int i = 0; i < data_seq.length(); ++i) {
// Check if a sample is an instance lifecycle event
if (info_seq[i].valid_data) {
// Print data
std::cout << "Received data" << std::endl;
RequiredSubscriptionsTypeSupport::print_data(&data_seq[i]);
samples_read++;
} else {
// This is an instance lifecycle event with no data payload.
std::cout << "Received instance state notification" << std::endl;
}
}
// Data loaned from Connext for performance. Return loan when done.
DDS_ReturnCode_t retcode = typed_reader->return_loan(data_seq, info_seq);
if (retcode != DDS_RETCODE_OK) {
std::cerr << "return loan error " << retcode << std::endl;
}
return samples_read;
}
int run_subscriber_application(
unsigned int domain_id,
unsigned int sample_count)
{
// Start communicating in a domain, usually one participant per application
DDSDomainParticipant *participant =
DDSTheParticipantFactory->create_participant(
domain_id,
DDS_PARTICIPANT_QOS_DEFAULT,
NULL,
DDS_STATUS_MASK_NONE);
if (participant == NULL) {
return shutdown_participant(
participant,
"create_participant error",
EXIT_FAILURE);
}
// A Subscriber allows an application to create one or more DataReaders
DDSSubscriber *subscriber = participant->create_subscriber(
DDS_SUBSCRIBER_QOS_DEFAULT,
NULL,
DDS_STATUS_MASK_NONE);
if (subscriber == NULL) {
return shutdown_participant(
participant,
"create_subscriber error",
EXIT_FAILURE);
}
// Register the datatype to use when creating the Topic
const char *type_name = RequiredSubscriptionsTypeSupport::get_type_name();
DDS_ReturnCode_t retcode = RequiredSubscriptionsTypeSupport::register_type(
participant,
type_name);
if (retcode != DDS_RETCODE_OK) {
return shutdown_participant(
participant,
"register_type error",
EXIT_FAILURE);
}
// Create a Topic with a name and a datatype
DDSTopic *topic = participant->create_topic(
"RequiredSubscriptionsTopic",
type_name,
DDS_TOPIC_QOS_DEFAULT,
NULL,
DDS_STATUS_MASK_NONE);
if (topic == NULL) {
return shutdown_participant(
participant,
"create_topic error",
EXIT_FAILURE);
}
// This DataReader reads data on "RequiredSubscriptionsTopic" Topic
DDSDataReader *untyped_reader = subscriber->create_datareader(
topic,
DDS_DATAREADER_QOS_DEFAULT,
NULL,
DDS_STATUS_MASK_NONE);
if (untyped_reader == NULL) {
return shutdown_participant(
participant,
"create_datareader error",
EXIT_FAILURE);
}
// Narrow casts from a untyped DataReader to a reader of your type
RequiredSubscriptionsDataReader *typed_reader =
RequiredSubscriptionsDataReader::narrow(untyped_reader);
if (typed_reader == NULL) {
return shutdown_participant(
participant,
"DataReader narrow error",
EXIT_FAILURE);
}
// Create ReadCondition that triggers when unread data in reader's queue
DDSReadCondition *read_condition = typed_reader->create_readcondition(
DDS_NOT_READ_SAMPLE_STATE,
DDS_ANY_VIEW_STATE,
DDS_ANY_INSTANCE_STATE);
if (read_condition == NULL) {
return shutdown_participant(
participant,
"create_readcondition error",
EXIT_FAILURE);
}
// WaitSet will be woken when the attached condition is triggered
DDSWaitSet waitset;
retcode = waitset.attach_condition(read_condition);
if (retcode != DDS_RETCODE_OK) {
return shutdown_participant(
participant,
"attach_condition error",
EXIT_FAILURE);
}
// Main loop. Wait for data to arrive, and process when it arrives
unsigned int samples_read = 0;
while (!shutdown_requested && samples_read < sample_count) {
DDSConditionSeq active_conditions_seq;
// Wait for data and report if it does not arrive in 1 second
DDS_Duration_t wait_timeout = { 1, 0 };
retcode = waitset.wait(active_conditions_seq, wait_timeout);
if (retcode == DDS_RETCODE_OK) {
// If the read condition is triggered, process data
samples_read += process_data(typed_reader);
} else {
if (retcode == DDS_RETCODE_TIMEOUT) {
std::cout << "No data after 1 second" << std::endl;
}
}
}
// Cleanup
return shutdown_participant(participant, "Shutting down", 0);
}
/* Delete all entities */
static int shutdown_participant(
DDSDomainParticipant *participant,
const char *shutdown_message,
int status)
{
DDS_ReturnCode_t retcode;
std::cout << shutdown_message << std::endl;
if (participant != NULL) {
// Cleanup everything created by this Participant
retcode = participant->delete_contained_entities();
if (retcode != DDS_RETCODE_OK) {
std::cerr << "delete_contained_entities error" << retcode
<< std::endl;
status = EXIT_FAILURE;
}
retcode = DDSTheParticipantFactory->delete_participant(participant);
if (retcode != DDS_RETCODE_OK) {
std::cerr << "delete_participant error" << retcode << std::endl;
status = EXIT_FAILURE;
}
}
return status;
}
int main(int argc, char *argv[])
{
// Parse arguments and handle control-C
ApplicationArguments arguments;
parse_arguments(arguments, argc, argv);
if (arguments.parse_result == PARSE_RETURN_EXIT) {
return EXIT_SUCCESS;
} else if (arguments.parse_result == PARSE_RETURN_FAILURE) {
return EXIT_FAILURE;
}
setup_signal_handlers();
// Sets Connext verbosity to help debugging
NDDSConfigLogger::get_instance()->set_verbosity(arguments.verbosity);
int status = run_subscriber_application(
arguments.domain_id,
arguments.sample_count);
/* Releases the memory used by the participant factory. Optional at
application exit */
DDS_ReturnCode_t retcode = DDSDomainParticipantFactory::finalize_instance();
if (retcode != DDS_RETCODE_OK) {
std::cerr << "finalize_instance error" << retcode << std::endl;
status = EXIT_FAILURE;
}
return status;
}
| cxx |
rticonnextdds-examples | data/projects/rticonnextdds-examples/connext_dds/required_subscription/c++/application.h | /*
* (c) Copyright, Real-Time Innovations, 2021. All rights reserved.
* RTI grants Licensee a license to use, modify, compile, and create derivative
* works of the software solely for use with RTI Connext DDS. Licensee may
* redistribute copies of the software provided that all such copies are subject
* to this license. The software is provided "as is", with no warranty of any
* type, including any warranty for fitness for any purpose. RTI is under no
* obligation to maintain or support the software. RTI shall not be liable for
* any incidental or consequential damages arising out of the use or inability
* to use the software.
*/
#ifndef APPLICATION_H
#define APPLICATION_H
#include <iostream>
#include <csignal>
#include <climits>
namespace application {
// Catch control-C and tell application to shut down
bool shutdown_requested = false;
inline void stop_handler(int)
{
shutdown_requested = true;
std::cout << "preparing to shut down..." << std::endl;
}
inline void setup_signal_handlers()
{
signal(SIGINT, stop_handler);
signal(SIGTERM, stop_handler);
}
enum ParseReturn { PARSE_RETURN_OK, PARSE_RETURN_FAILURE, PARSE_RETURN_EXIT };
struct ApplicationArguments {
ParseReturn parse_result;
unsigned int domain_id;
unsigned int sample_count;
NDDS_Config_LogVerbosity verbosity;
};
inline void set_verbosity(ApplicationArguments &arguments, int verbosity)
{
switch (verbosity) {
case 0:
arguments.verbosity = NDDS_CONFIG_LOG_VERBOSITY_SILENT;
break;
case 1:
arguments.verbosity = NDDS_CONFIG_LOG_VERBOSITY_ERROR;
break;
case 2:
arguments.verbosity = NDDS_CONFIG_LOG_VERBOSITY_WARNING;
break;
case 3:
arguments.verbosity = NDDS_CONFIG_LOG_VERBOSITY_STATUS_ALL;
break;
default:
arguments.verbosity = NDDS_CONFIG_LOG_VERBOSITY_ERROR;
break;
}
}
// Parses application arguments for example. Returns whether to exit.
inline void parse_arguments(
ApplicationArguments &arguments,
int argc,
char *argv[])
{
int arg_processing = 1;
bool show_usage = false;
arguments.domain_id = 0;
arguments.sample_count = INT_MAX;
arguments.verbosity = NDDS_CONFIG_LOG_VERBOSITY_ERROR;
arguments.parse_result = PARSE_RETURN_OK;
while (arg_processing < argc) {
if ((argc > arg_processing + 1)
&& (strcmp(argv[arg_processing], "-d") == 0
|| strcmp(argv[arg_processing], "--domain") == 0)) {
arguments.domain_id = atoi(argv[arg_processing + 1]);
arg_processing += 2;
} else if (
(argc > arg_processing + 1)
&& (strcmp(argv[arg_processing], "-s") == 0
|| strcmp(argv[arg_processing], "--sample-count") == 0)) {
arguments.sample_count = atoi(argv[arg_processing + 1]);
arg_processing += 2;
} else if (
(argc > arg_processing + 1)
&& (strcmp(argv[arg_processing], "-v") == 0
|| strcmp(argv[arg_processing], "--verbosity") == 0)) {
set_verbosity(arguments, atoi(argv[arg_processing + 1]));
arg_processing += 2;
} else if (
strcmp(argv[arg_processing], "-h") == 0
|| strcmp(argv[arg_processing], "--help") == 0) {
std::cout << "Example application." << std::endl;
show_usage = true;
arguments.parse_result = PARSE_RETURN_EXIT;
break;
} else {
std::cout << "Bad parameter." << std::endl;
show_usage = true;
arguments.parse_result = PARSE_RETURN_FAILURE;
break;
}
}
if (show_usage) {
std::cout << "Usage:\n"
" -d, --domain <int> Domain ID this "
"application will\n"
" subscribe in. \n"
" Default: 0\n"
" -s, --sample_count <int> Number of samples to "
"receive before\n"
" cleanly shutting down. \n"
" Default: infinite\n"
" -v, --verbosity <int> How much debugging output "
"to show.\n"
" Range: 0-3 \n"
" Default: 1"
<< std::endl;
}
}
} // namespace application
#endif // APPLICATION_H
| h |
rticonnextdds-examples | data/projects/rticonnextdds-examples/connext_dds/required_subscription/c++98/RequiredSubscriptions_publisher.cxx | /*
* (c) Copyright, Real-Time Innovations, 2021. All rights reserved.
* RTI grants Licensee a license to use, modify, compile, and create derivative
* works of the software solely for use with RTI Connext DDS. Licensee may
* redistribute copies of the software provided that all such copies are subject
* to this license. The software is provided "as is", with no warranty of any
* type, including any warranty for fitness for any purpose. RTI is under no
* obligation to maintain or support the software. RTI shall not be liable for
* any incidental or consequential damages arising out of the use or inability
* to use the software.
*/
#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include "RequiredSubscriptions.h"
#include "RequiredSubscriptionsSupport.h"
#include "ndds/ndds_cpp.h"
#include "application.h"
#include "dds_c/dds_c_infrastructure.h"
using namespace application;
static int shutdown_participant(
DDSDomainParticipant *participant,
const char *shutdown_message,
int status);
int run_publisher_application(unsigned int domain_id, unsigned int sample_count)
{
// Start communicating in a domain, usually one participant per application
DDSDomainParticipant *participant =
DDSTheParticipantFactory->create_participant(
domain_id,
DDS_PARTICIPANT_QOS_DEFAULT,
NULL,
DDS_STATUS_MASK_NONE);
if (participant == NULL) {
return shutdown_participant(
participant,
"create_participant error",
EXIT_FAILURE);
}
// A Publisher allows an application to create one or more DataWriters
DDSPublisher *publisher = participant->create_publisher(
DDS_PUBLISHER_QOS_DEFAULT,
NULL,
DDS_STATUS_MASK_NONE);
if (publisher == NULL) {
return shutdown_participant(
participant,
"create_publisher error",
EXIT_FAILURE);
}
// Register the datatype to use when creating the Topic
const char *type_name = RequiredSubscriptionsTypeSupport::get_type_name();
DDS_ReturnCode_t retcode = RequiredSubscriptionsTypeSupport::register_type(
participant,
type_name);
if (retcode != DDS_RETCODE_OK) {
return shutdown_participant(
participant,
"register_type error",
EXIT_FAILURE);
}
// Create a Topic with a name and a datatype
DDSTopic *topic = participant->create_topic(
"RequiredSubscriptionsTopic",
type_name,
DDS_TOPIC_QOS_DEFAULT,
NULL,
DDS_STATUS_MASK_NONE);
if (topic == NULL) {
return shutdown_participant(
participant,
"create_topic error",
EXIT_FAILURE);
}
// This DataWriter writes data on "RequiredSubscriptionsTopic" Topic
DDSDataWriter *untyped_writer = publisher->create_datawriter(
topic,
DDS_DATAWRITER_QOS_DEFAULT,
NULL,
DDS_STATUS_MASK_NONE);
if (untyped_writer == NULL) {
return shutdown_participant(
participant,
"create_datawriter error",
EXIT_FAILURE);
}
// Narrow casts from an untyped DataWriter to a writer of your type
RequiredSubscriptionsDataWriter *typed_writer =
RequiredSubscriptionsDataWriter::narrow(untyped_writer);
if (typed_writer == NULL) {
return shutdown_participant(
participant,
"DataWriter narrow error",
EXIT_FAILURE);
}
// Create data for writing, allocating all members
RequiredSubscriptions *data =
RequiredSubscriptionsTypeSupport::create_data();
if (data == NULL) {
return shutdown_participant(
participant,
"RequiredSubscriptionsTypeSupport::create_data error",
EXIT_FAILURE);
}
/* Write one sample and wait for acknowledgment from the
Required Subscribers */
std::cout << "Writing RequiredSubscriptions" << std::endl;
retcode = typed_writer->write(*data, DDS_HANDLE_NIL);
if (retcode != DDS_RETCODE_OK) {
return shutdown_participant(
participant,
"typed_writer->write error",
EXIT_FAILURE);
}
retcode = untyped_writer->wait_for_acknowledgments(DDS_DURATION_INFINITE);
if (retcode != DDS_RETCODE_OK) {
return shutdown_participant(
participant,
"untyped_writer->wait_for_acknowledgments error",
EXIT_FAILURE);
}
/* Delete previously allocated RequiredSubscriptions, including all
contained elements */
retcode = RequiredSubscriptionsTypeSupport::delete_data(data);
if (retcode != DDS_RETCODE_OK) {
std::cerr << "RequiredSubscriptionsTypeSupport::delete_data error "
<< retcode << std::endl;
// we don't exit with error status here because the sample has been sent
}
// Delete all entities (DataWriter, Topic, Publisher, DomainParticipant)
return shutdown_participant(participant, "Shutting down", EXIT_SUCCESS);
}
/* Delete all entities */
static int shutdown_participant(
DDSDomainParticipant *participant,
const char *shutdown_message,
int status)
{
DDS_ReturnCode_t retcode;
std::cout << shutdown_message << std::endl;
if (participant != NULL) {
// Cleanup everything created by this Participant
retcode = participant->delete_contained_entities();
if (retcode != DDS_RETCODE_OK) {
std::cerr << "delete_contained_entities error " << retcode
<< std::endl;
status = EXIT_FAILURE;
}
retcode = DDSTheParticipantFactory->delete_participant(participant);
if (retcode != DDS_RETCODE_OK) {
std::cerr << "delete_participant error " << retcode << std::endl;
status = EXIT_FAILURE;
}
}
return status;
}
int main(int argc, char *argv[])
{
// Parse arguments and handle control-C
ApplicationArguments arguments;
parse_arguments(arguments, argc, argv);
if (arguments.parse_result == PARSE_RETURN_EXIT) {
return EXIT_SUCCESS;
} else if (arguments.parse_result == PARSE_RETURN_FAILURE) {
return EXIT_FAILURE;
}
setup_signal_handlers();
// Sets Connext verbosity to help debugging
NDDSConfigLogger::get_instance()->set_verbosity(arguments.verbosity);
int status = run_publisher_application(
arguments.domain_id,
arguments.sample_count);
/* Releases the memory used by the participant factory. Optional at
application exit */
DDS_ReturnCode_t retcode = DDSDomainParticipantFactory::finalize_instance();
if (retcode != DDS_RETCODE_OK) {
std::cerr << "finalize_instance error " << retcode << std::endl;
status = EXIT_FAILURE;
}
return status;
}
| cxx |
rticonnextdds-examples | data/projects/rticonnextdds-examples/connext_dds/required_subscription/c++98/RequiredSubscriptions_subscriber.cxx | /*
* (c) Copyright, Real-Time Innovations, 2021. All rights reserved.
* RTI grants Licensee a license to use, modify, compile, and create derivative
* works of the software solely for use with RTI Connext DDS. Licensee may
* redistribute copies of the software provided that all such copies are subject
* to this license. The software is provided "as is", with no warranty of any
* type, including any warranty for fitness for any purpose. RTI is under no
* obligation to maintain or support the software. RTI shall not be liable for
* any incidental or consequential damages arising out of the use or inability
* to use the software.
*/
#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include "RequiredSubscriptions.h"
#include "RequiredSubscriptionsSupport.h"
#include "ndds/ndds_cpp.h"
#include "application.h"
using namespace application;
static int shutdown_participant(
DDSDomainParticipant *participant,
const char *shutdown_message,
int status);
/* Process the data received by the DataReader passed as a parameter.
It returns the number of samples processed. */
unsigned int process_data(RequiredSubscriptionsDataReader *typed_reader)
{
// Sequence of received data
RequiredSubscriptionsSeq data_seq;
// Metadata associated with samples in data_seq
DDS_SampleInfoSeq info_seq;
unsigned int samples_read = 0;
// Take available data from DataReader's queue
typed_reader->take(
data_seq,
info_seq,
DDS_LENGTH_UNLIMITED,
DDS_ANY_SAMPLE_STATE,
DDS_ANY_VIEW_STATE,
DDS_ANY_INSTANCE_STATE);
// Iterate over all available data
for (int i = 0; i < data_seq.length(); ++i) {
// Check if a sample is an instance lifecycle event
if (info_seq[i].valid_data) {
// Print data
std::cout << "Received data" << std::endl;
RequiredSubscriptionsTypeSupport::print_data(&data_seq[i]);
samples_read++;
} else {
// This is an instance lifecycle event with no data payload.
std::cout << "Received instance state notification" << std::endl;
}
}
// Data loaned from Connext for performance. Return loan when done.
DDS_ReturnCode_t retcode = typed_reader->return_loan(data_seq, info_seq);
if (retcode != DDS_RETCODE_OK) {
std::cerr << "return loan error " << retcode << std::endl;
}
return samples_read;
}
int run_subscriber_application(
unsigned int domain_id,
unsigned int sample_count)
{
// Start communicating in a domain, usually one participant per application
DDSDomainParticipant *participant =
DDSTheParticipantFactory->create_participant(
domain_id,
DDS_PARTICIPANT_QOS_DEFAULT,
NULL,
DDS_STATUS_MASK_NONE);
if (participant == NULL) {
return shutdown_participant(
participant,
"create_participant error",
EXIT_FAILURE);
}
// A Subscriber allows an application to create one or more DataReaders
DDSSubscriber *subscriber = participant->create_subscriber(
DDS_SUBSCRIBER_QOS_DEFAULT,
NULL,
DDS_STATUS_MASK_NONE);
if (subscriber == NULL) {
return shutdown_participant(
participant,
"create_subscriber error",
EXIT_FAILURE);
}
// Register the datatype to use when creating the Topic
const char *type_name = RequiredSubscriptionsTypeSupport::get_type_name();
DDS_ReturnCode_t retcode = RequiredSubscriptionsTypeSupport::register_type(
participant,
type_name);
if (retcode != DDS_RETCODE_OK) {
return shutdown_participant(
participant,
"register_type error",
EXIT_FAILURE);
}
// Create a Topic with a name and a datatype
DDSTopic *topic = participant->create_topic(
"RequiredSubscriptionsTopic",
type_name,
DDS_TOPIC_QOS_DEFAULT,
NULL,
DDS_STATUS_MASK_NONE);
if (topic == NULL) {
return shutdown_participant(
participant,
"create_topic error",
EXIT_FAILURE);
}
// This DataReader reads data on "RequiredSubscriptionsTopic" Topic
DDSDataReader *untyped_reader = subscriber->create_datareader(
topic,
DDS_DATAREADER_QOS_DEFAULT,
NULL,
DDS_STATUS_MASK_NONE);
if (untyped_reader == NULL) {
return shutdown_participant(
participant,
"create_datareader error",
EXIT_FAILURE);
}
// Narrow casts from a untyped DataReader to a reader of your type
RequiredSubscriptionsDataReader *typed_reader =
RequiredSubscriptionsDataReader::narrow(untyped_reader);
if (typed_reader == NULL) {
return shutdown_participant(
participant,
"DataReader narrow error",
EXIT_FAILURE);
}
// Create ReadCondition that triggers when unread data in reader's queue
DDSReadCondition *read_condition = typed_reader->create_readcondition(
DDS_NOT_READ_SAMPLE_STATE,
DDS_ANY_VIEW_STATE,
DDS_ANY_INSTANCE_STATE);
if (read_condition == NULL) {
return shutdown_participant(
participant,
"create_readcondition error",
EXIT_FAILURE);
}
// WaitSet will be woken when the attached condition is triggered
DDSWaitSet waitset;
retcode = waitset.attach_condition(read_condition);
if (retcode != DDS_RETCODE_OK) {
return shutdown_participant(
participant,
"attach_condition error",
EXIT_FAILURE);
}
// Main loop. Wait for data to arrive, and process when it arrives
unsigned int samples_read = 0;
while (!shutdown_requested && samples_read < sample_count) {
DDSConditionSeq active_conditions_seq;
// Wait for data and report if it does not arrive in 1 second
DDS_Duration_t wait_timeout = { 1, 0 };
retcode = waitset.wait(active_conditions_seq, wait_timeout);
if (retcode == DDS_RETCODE_OK) {
// If the read condition is triggered, process data
samples_read += process_data(typed_reader);
} else {
if (retcode == DDS_RETCODE_TIMEOUT) {
std::cout << "No data after 1 second" << std::endl;
}
}
}
// Cleanup
return shutdown_participant(participant, "Shutting down", 0);
}
/* Delete all entities */
static int shutdown_participant(
DDSDomainParticipant *participant,
const char *shutdown_message,
int status)
{
DDS_ReturnCode_t retcode;
std::cout << shutdown_message << std::endl;
if (participant != NULL) {
// Cleanup everything created by this Participant
retcode = participant->delete_contained_entities();
if (retcode != DDS_RETCODE_OK) {
std::cerr << "delete_contained_entities error" << retcode
<< std::endl;
status = EXIT_FAILURE;
}
retcode = DDSTheParticipantFactory->delete_participant(participant);
if (retcode != DDS_RETCODE_OK) {
std::cerr << "delete_participant error" << retcode << std::endl;
status = EXIT_FAILURE;
}
}
return status;
}
int main(int argc, char *argv[])
{
// Parse arguments and handle control-C
ApplicationArguments arguments;
parse_arguments(arguments, argc, argv);
if (arguments.parse_result == PARSE_RETURN_EXIT) {
return EXIT_SUCCESS;
} else if (arguments.parse_result == PARSE_RETURN_FAILURE) {
return EXIT_FAILURE;
}
setup_signal_handlers();
// Sets Connext verbosity to help debugging
NDDSConfigLogger::get_instance()->set_verbosity(arguments.verbosity);
int status = run_subscriber_application(
arguments.domain_id,
arguments.sample_count);
/* Releases the memory used by the participant factory. Optional at
application exit */
DDS_ReturnCode_t retcode = DDSDomainParticipantFactory::finalize_instance();
if (retcode != DDS_RETCODE_OK) {
std::cerr << "finalize_instance error" << retcode << std::endl;
status = EXIT_FAILURE;
}
return status;
}
| cxx |
rticonnextdds-examples | data/projects/rticonnextdds-examples/connext_dds/required_subscription/c++98/application.h | /*
* (c) Copyright, Real-Time Innovations, 2021. All rights reserved.
* RTI grants Licensee a license to use, modify, compile, and create derivative
* works of the software solely for use with RTI Connext DDS. Licensee may
* redistribute copies of the software provided that all such copies are subject
* to this license. The software is provided "as is", with no warranty of any
* type, including any warranty for fitness for any purpose. RTI is under no
* obligation to maintain or support the software. RTI shall not be liable for
* any incidental or consequential damages arising out of the use or inability
* to use the software.
*/
#ifndef APPLICATION_H
#define APPLICATION_H
#include <iostream>
#include <csignal>
#include <climits>
namespace application {
// Catch control-C and tell application to shut down
bool shutdown_requested = false;
inline void stop_handler(int)
{
shutdown_requested = true;
std::cout << "preparing to shut down..." << std::endl;
}
inline void setup_signal_handlers()
{
signal(SIGINT, stop_handler);
signal(SIGTERM, stop_handler);
}
enum ParseReturn { PARSE_RETURN_OK, PARSE_RETURN_FAILURE, PARSE_RETURN_EXIT };
struct ApplicationArguments {
ParseReturn parse_result;
unsigned int domain_id;
unsigned int sample_count;
NDDS_Config_LogVerbosity verbosity;
};
inline void set_verbosity(ApplicationArguments &arguments, int verbosity)
{
switch (verbosity) {
case 0:
arguments.verbosity = NDDS_CONFIG_LOG_VERBOSITY_SILENT;
break;
case 1:
arguments.verbosity = NDDS_CONFIG_LOG_VERBOSITY_ERROR;
break;
case 2:
arguments.verbosity = NDDS_CONFIG_LOG_VERBOSITY_WARNING;
break;
case 3:
arguments.verbosity = NDDS_CONFIG_LOG_VERBOSITY_STATUS_ALL;
break;
default:
arguments.verbosity = NDDS_CONFIG_LOG_VERBOSITY_ERROR;
break;
}
}
// Parses application arguments for example. Returns whether to exit.
inline void parse_arguments(
ApplicationArguments &arguments,
int argc,
char *argv[])
{
int arg_processing = 1;
bool show_usage = false;
arguments.domain_id = 0;
arguments.sample_count = INT_MAX;
arguments.verbosity = NDDS_CONFIG_LOG_VERBOSITY_ERROR;
arguments.parse_result = PARSE_RETURN_OK;
while (arg_processing < argc) {
if ((argc > arg_processing + 1)
&& (strcmp(argv[arg_processing], "-d") == 0
|| strcmp(argv[arg_processing], "--domain") == 0)) {
arguments.domain_id = atoi(argv[arg_processing + 1]);
arg_processing += 2;
} else if (
(argc > arg_processing + 1)
&& (strcmp(argv[arg_processing], "-s") == 0
|| strcmp(argv[arg_processing], "--sample-count") == 0)) {
arguments.sample_count = atoi(argv[arg_processing + 1]);
arg_processing += 2;
} else if (
(argc > arg_processing + 1)
&& (strcmp(argv[arg_processing], "-v") == 0
|| strcmp(argv[arg_processing], "--verbosity") == 0)) {
set_verbosity(arguments, atoi(argv[arg_processing + 1]));
arg_processing += 2;
} else if (
strcmp(argv[arg_processing], "-h") == 0
|| strcmp(argv[arg_processing], "--help") == 0) {
std::cout << "Example application." << std::endl;
show_usage = true;
arguments.parse_result = PARSE_RETURN_EXIT;
break;
} else {
std::cout << "Bad parameter." << std::endl;
show_usage = true;
arguments.parse_result = PARSE_RETURN_FAILURE;
break;
}
}
if (show_usage) {
std::cout << "Usage:\n"
" -d, --domain <int> Domain ID this "
"application will\n"
" subscribe in. \n"
" Default: 0\n"
" -s, --sample_count <int> Number of samples to "
"receive before\n"
" cleanly shutting down. \n"
" Default: infinite\n"
" -v, --verbosity <int> How much debugging output "
"to show.\n"
" Range: 0-3 \n"
" Default: 1"
<< std::endl;
}
}
} // namespace application
#endif // APPLICATION_H
| h |
rticonnextdds-examples | data/projects/rticonnextdds-examples/connext_dds/recursive_data_type/c++/RecursiveType_publisher.cxx |
/* RecursiveType_publisher.cxx
A publication of data of type Tree
This file is derived from code automatically generated by the rtiddsgen
command:
rtiddsgen -language C++ -example <arch> RecursiveType.idl
Example publication of type Tree automatically generated by
'rtiddsgen'. To test them follow these steps:
(1) Compile this file and the example subscription.
(2) Start the subscription with the command
objs/<arch>/RecursiveType_subscriber <domain_id> <sample_count>
(3) Start the publication with the command
objs/<arch>/RecursiveType_publisher <domain_id> <sample_count>
(4) [Optional] Specify the list of discovery initial peers and
multicast receive addresses via an environment variable or a file
(in the current working directory) called NDDS_DISCOVERY_PEERS.
You can run any number of publishers and subscribers programs, and can
add and remove them dynamically from the domain.
Example:
To run the example application on domain <domain_id>:
On Unix:
objs/<arch>/RecursiveType_publisher <domain_id> o
objs/<arch>/RecursiveType_subscriber <domain_id>
On Windows:
objs\<arch>\RecursiveType_publisher <domain_id>
objs\<arch>\RecursiveType_subscriber <domain_id>
*/
#include "RecursiveType.h"
#include "RecursiveTypeSupport.h"
#include "ndds/ndds_cpp.h"
#include <stdio.h>
#include <stdlib.h>
#include "ndds/ndds_namespace_cpp.h"
using namespace DDS;
/* Delete all entities */
static int publisher_shutdown(DomainParticipant *participant)
{
ReturnCode_t retcode;
int status = 0;
if (participant != NULL) {
retcode = participant->delete_contained_entities();
if (retcode != RETCODE_OK) {
printf("delete_contained_entities error %d\n", retcode);
status = -1;
}
retcode = TheParticipantFactory->delete_participant(participant);
if (retcode != RETCODE_OK) {
printf("delete_participant error %d\n", retcode);
status = -1;
}
}
/* RTI Connext provides finalize_instance() method on
domain participant factory for people who want to release memory used
by the participant factory. Uncomment the following block of code for
clean destruction of the singleton. */
/*
retcode = DomainParticipantFactory::finalize_instance();
if (retcode != RETCODE_OK) {
printf("finalize_instance error %d\n", retcode);
status = -1;
}
*/
return status;
}
void fill_tree(Tree *instance, int childcount, int depth, int value)
{
instance->node.data = value;
if (depth == 0) {
return;
}
if (instance->children == NULL) {
instance->children = new TreeSeq();
}
instance->children->ensure_length(childcount, childcount);
for (int i = 0; i < childcount; ++i) {
Tree &child = (*instance->children)[i];
fill_tree(&child, childcount, depth - 1, value);
}
}
extern "C" int publisher_main(int domainId, int sample_count)
{
DomainParticipant *participant = NULL;
Publisher *publisher = NULL;
Topic *topic = NULL;
DataWriter *writer = NULL;
TreeDataWriter *Tree_writer = NULL;
Tree *instance = NULL;
ReturnCode_t retcode;
InstanceHandle_t instance_handle = HANDLE_NIL;
const char *type_name = NULL;
int count = 0;
Duration_t send_period = { 4, 0 };
/* To customize participant QoS, use
the configuration file USER_QOS_PROFILES.xml */
participant = TheParticipantFactory->create_participant(
domainId,
PARTICIPANT_QOS_DEFAULT,
NULL /* listener */,
STATUS_MASK_NONE);
if (participant == NULL) {
printf("create_participant error\n");
publisher_shutdown(participant);
return -1;
}
/* To customize publisher QoS, use
the configuration file USER_QOS_PROFILES.xml */
publisher = participant->create_publisher(
PUBLISHER_QOS_DEFAULT,
NULL /* listener */,
STATUS_MASK_NONE);
if (publisher == NULL) {
printf("create_publisher error\n");
publisher_shutdown(participant);
return -1;
}
/* Register type before creating topic */
type_name = TreeTypeSupport::get_type_name();
retcode = TreeTypeSupport::register_type(participant, type_name);
if (retcode != RETCODE_OK) {
printf("register_type error %d\n", retcode);
publisher_shutdown(participant);
return -1;
}
/* To customize topic QoS, use
the configuration file USER_QOS_PROFILES.xml */
topic = participant->create_topic(
"Example Tree",
type_name,
TOPIC_QOS_DEFAULT,
NULL /* listener */,
STATUS_MASK_NONE);
if (topic == NULL) {
printf("create_topic error\n");
publisher_shutdown(participant);
return -1;
}
/* To customize data writer QoS, use
the configuration file USER_QOS_PROFILES.xml */
writer = publisher->create_datawriter(
topic,
DATAWRITER_QOS_DEFAULT,
NULL /* listener */,
STATUS_MASK_NONE);
if (writer == NULL) {
printf("create_datawriter error\n");
publisher_shutdown(participant);
return -1;
}
Tree_writer = TreeDataWriter::narrow(writer);
if (Tree_writer == NULL) {
printf("DataWriter narrow error\n");
publisher_shutdown(participant);
return -1;
}
/* Create data sample for writing */
instance = TreeTypeSupport::create_data();
if (instance == NULL) {
printf("TreeTypeSupport::create_data error\n");
publisher_shutdown(participant);
return -1;
}
/* For a data type that has a key, if the same instance is going to be
written multiple times, initialize the key here
and register the keyed instance prior to writing */
/*
instance_handle = Tree_writer->register_instance(*instance);
*/
/* Main loop */
for (count = 0; (sample_count == 0) || (count < sample_count); ++count) {
printf("Writing Tree, count %d\n", count);
/* Modify the data to be sent here */
fill_tree(instance, 1, count, count);
retcode = Tree_writer->write(*instance, instance_handle);
if (retcode != RETCODE_OK) {
printf("write error %d\n", retcode);
}
NDDSUtility::sleep(send_period);
}
/*
retcode = Tree_writer->unregister_instance(
*instance, instance_handle);
if (retcode != RETCODE_OK) {
printf("unregister instance error %d\n", retcode);
}
*/
/* Delete data sample */
retcode = TreeTypeSupport::delete_data(instance);
if (retcode != RETCODE_OK) {
printf("TreeTypeSupport::delete_data error %d\n", retcode);
}
/* Delete all entities */
return publisher_shutdown(participant);
}
int main(int argc, char *argv[])
{
int domainId = 0;
int sample_count = 0; /* infinite loop */
if (argc >= 2) {
domainId = atoi(argv[1]);
}
if (argc >= 3) {
sample_count = atoi(argv[2]);
}
/* Uncomment this to turn on additional logging
NDDSConfigLogger::get_instance()->
set_verbosity_by_category(NDDS_CONFIG_LOG_CATEGORY_API,
NDDS_CONFIG_LOG_VERBOSITY_STATUS_ALL);
*/
return publisher_main(domainId, sample_count);
}
| cxx |
rticonnextdds-examples | data/projects/rticonnextdds-examples/connext_dds/recursive_data_type/c++/RecursiveType_subscriber.cxx |
/* RecursiveType_subscriber.cxx
A subscription example
This file is derived from code automatically generated by the rtiddsgen
command:
rtiddsgen -language C++ -example <arch> RecursiveType.idl
Example subscription of type Tree automatically generated by
'rtiddsgen'. To test them follow these steps:
(1) Compile this file and the example publication.
(2) Start the subscription with the command
objs/<arch>/RecursiveType_subscriber <domain_id> <sample_count>
(3) Start the publication with the command
objs/<arch>/RecursiveType_publisher <domain_id> <sample_count>
(4) [Optional] Specify the list of discovery initial peers and
multicast receive addresses via an environment variable or a file
(in the current working directory) called NDDS_DISCOVERY_PEERS.
You can run any number of publishers and subscribers programs, and can
add and remove them dynamically from the domain.
Example:
To run the example application on domain <domain_id>:
On Unix:
objs/<arch>/RecursiveType_publisher <domain_id>
objs/<arch>/RecursiveType_subscriber <domain_id>
On Windows:
objs\<arch>\RecursiveType_publisher <domain_id>
objs\<arch>\RecursiveType_subscriber <domain_id>
*/
#include "RecursiveType.h"
#include "RecursiveTypeSupport.h"
#include "ndds/ndds_cpp.h"
#include <stdio.h>
#include <stdlib.h>
#include "ndds/ndds_namespace_cpp.h"
using namespace DDS;
class TreeListener : public DataReaderListener {
public:
virtual void on_requested_deadline_missed(
DataReader * /*reader*/,
const RequestedDeadlineMissedStatus & /*status*/)
{
}
virtual void on_requested_incompatible_qos(
DataReader * /*reader*/,
const RequestedIncompatibleQosStatus & /*status*/)
{
}
virtual void on_sample_rejected(
DataReader * /*reader*/,
const SampleRejectedStatus & /*status*/)
{
}
virtual void on_liveliness_changed(
DataReader * /*reader*/,
const LivelinessChangedStatus & /*status*/)
{
}
virtual void on_sample_lost(
DataReader * /*reader*/,
const SampleLostStatus & /*status*/)
{
}
virtual void on_subscription_matched(
DataReader * /*reader*/,
const SubscriptionMatchedStatus & /*status*/)
{
}
virtual void on_data_available(DataReader *reader);
};
void TreeListener::on_data_available(DataReader *reader)
{
TreeDataReader *Tree_reader = NULL;
TreeSeq data_seq;
SampleInfoSeq info_seq;
ReturnCode_t retcode;
int i;
Tree_reader = TreeDataReader::narrow(reader);
if (Tree_reader == NULL) {
printf("DataReader narrow error\n");
return;
}
retcode = Tree_reader->take(
data_seq,
info_seq,
LENGTH_UNLIMITED,
ANY_SAMPLE_STATE,
ANY_VIEW_STATE,
ANY_INSTANCE_STATE);
if (retcode == RETCODE_NO_DATA) {
return;
} else if (retcode != RETCODE_OK) {
printf("take error %d\n", retcode);
return;
}
for (i = 0; i < data_seq.length(); ++i) {
if (info_seq[i].valid_data) {
printf("Received data\n");
TreeTypeSupport::print_data(&data_seq[i]);
}
}
retcode = Tree_reader->return_loan(data_seq, info_seq);
if (retcode != RETCODE_OK) {
printf("return loan error %d\n", retcode);
}
}
/* Delete all entities */
static int subscriber_shutdown(DomainParticipant *participant)
{
ReturnCode_t retcode;
int status = 0;
if (participant != NULL) {
retcode = participant->delete_contained_entities();
if (retcode != RETCODE_OK) {
printf("delete_contained_entities error %d\n", retcode);
status = -1;
}
retcode = TheParticipantFactory->delete_participant(participant);
if (retcode != RETCODE_OK) {
printf("delete_participant error %d\n", retcode);
status = -1;
}
}
/* RTI Connext provides the finalize_instance() method on
domain participant factory for people who want to release memory used
by the participant factory. Uncomment the following block of code for
clean destruction of the singleton. */
/*
retcode = DomainParticipantFactory::finalize_instance();
if (retcode != RETCODE_OK) {
printf("finalize_instance error %d\n", retcode);
status = -1;
}
*/
return status;
}
extern "C" int subscriber_main(int domainId, int sample_count)
{
DomainParticipant *participant = NULL;
Subscriber *subscriber = NULL;
Topic *topic = NULL;
TreeListener *reader_listener = NULL;
DataReader *reader = NULL;
ReturnCode_t retcode;
const char *type_name = NULL;
int count = 0;
Duration_t receive_period = { 4, 0 };
int status = 0;
/* To customize the participant QoS, use
the configuration file USER_QOS_PROFILES.xml */
participant = TheParticipantFactory->create_participant(
domainId,
PARTICIPANT_QOS_DEFAULT,
NULL /* listener */,
STATUS_MASK_NONE);
if (participant == NULL) {
printf("create_participant error\n");
subscriber_shutdown(participant);
return -1;
}
/* To customize the subscriber QoS, use
the configuration file USER_QOS_PROFILES.xml */
subscriber = participant->create_subscriber(
SUBSCRIBER_QOS_DEFAULT,
NULL /* listener */,
STATUS_MASK_NONE);
if (subscriber == NULL) {
printf("create_subscriber error\n");
subscriber_shutdown(participant);
return -1;
}
/* Register the type before creating the topic */
type_name = TreeTypeSupport::get_type_name();
retcode = TreeTypeSupport::register_type(participant, type_name);
if (retcode != RETCODE_OK) {
printf("register_type error %d\n", retcode);
subscriber_shutdown(participant);
return -1;
}
/* To customize the topic QoS, use
the configuration file USER_QOS_PROFILES.xml */
topic = participant->create_topic(
"Example Tree",
type_name,
TOPIC_QOS_DEFAULT,
NULL /* listener */,
STATUS_MASK_NONE);
if (topic == NULL) {
printf("create_topic error\n");
subscriber_shutdown(participant);
return -1;
}
/* Create a data reader listener */
reader_listener = new TreeListener();
/* To customize the data reader QoS, use
the configuration file USER_QOS_PROFILES.xml */
reader = subscriber->create_datareader(
topic,
DATAREADER_QOS_DEFAULT,
reader_listener,
STATUS_MASK_ALL);
if (reader == NULL) {
printf("create_datareader error\n");
subscriber_shutdown(participant);
delete reader_listener;
return -1;
}
/* Main loop */
for (count = 0; (sample_count == 0) || (count < sample_count); ++count) {
printf("Tree subscriber sleeping for %d sec...\n", receive_period.sec);
NDDSUtility::sleep(receive_period);
}
/* Delete all entities */
status = subscriber_shutdown(participant);
delete reader_listener;
return status;
}
int main(int argc, char *argv[])
{
int domainId = 0;
int sample_count = 0; /* infinite loop */
if (argc >= 2) {
domainId = atoi(argv[1]);
}
if (argc >= 3) {
sample_count = atoi(argv[2]);
}
/* Uncomment this to turn on additional logging
NDDSConfigLogger::get_instance()->
set_verbosity_by_category(NDDS_CONFIG_LOG_CATEGORY_API,
NDDS_CONFIG_LOG_VERBOSITY_STATUS_ALL);
*/
return subscriber_main(domainId, sample_count);
}
| cxx |
rticonnextdds-examples | data/projects/rticonnextdds-examples/connext_dds/recursive_data_type/c/RecursiveType_publisher.c |
/* RecursiveType_publisher.c
A publication of data of type Tree
This file is derived from code automatically generated by the rtiddsgen
command:
rtiddsgen -language C -example <arch> RecursiveType.idl
Example publication of type Tree automatically generated by
'rtiddsgen'. To test them follow these steps:
(1) Compile this file and the example subscription.
(2) Start the subscription on the same domain used for RTI Data Distribution
Service with the command
objs/<arch>/RecursiveType_subscriber <domain_id> <sample_count>
(3) Start the publication on the same domain used for RTI Data Distribution
Service with the command
objs/<arch>/RecursiveType_publisher <domain_id> <sample_count>
(4) [Optional] Specify the list of discovery initial peers and
multicast receive addresses via an environment variable or a file
(in the current working directory) called NDDS_DISCOVERY_PEERS.
You can run any number of publishers and subscribers programs, and can
add and remove them dynamically from the domain.
Example:
To run the example application on domain <domain_id>:
On Unix:
objs/<arch>/RecursiveType_publisher <domain_id>
objs/<arch>/RecursiveType_subscriber <domain_id>
On Windows:
objs\<arch>\RecursiveType_publisher <domain_id>
objs\<arch>\RecursiveType_subscriber <domain_id>
*/
#include "RecursiveType.h"
#include "RecursiveTypeSupport.h"
#include "ndds/ndds_c.h"
#include <stdio.h>
#include <stdlib.h>
/* Delete all entities */
static int publisher_shutdown(DDS_DomainParticipant *participant)
{
DDS_ReturnCode_t retcode;
int status = 0;
if (participant != NULL) {
retcode = DDS_DomainParticipant_delete_contained_entities(participant);
if (retcode != DDS_RETCODE_OK) {
printf("delete_contained_entities error %d\n", retcode);
status = -1;
}
retcode = DDS_DomainParticipantFactory_delete_participant(
DDS_TheParticipantFactory,
participant);
if (retcode != DDS_RETCODE_OK) {
printf("delete_participant error %d\n", retcode);
status = -1;
}
}
/* RTI Data Distribution Service provides finalize_instance() method on
domain participant factory for people who want to release memory used
by the participant factory. Uncomment the following block of code for
clean destruction of the singleton. */
/*
retcode = DDS_DomainParticipantFactory_finalize_instance();
if (retcode != DDS_RETCODE_OK) {
printf("finalize_instance error %d\n", retcode);
status = -1;
}
*/
return status;
}
void fill_tree(Tree *instance, int childcount, int depth, int value)
{
int i = 0;
instance->node.data = value;
if (depth == 0) {
return;
}
if (instance->children == NULL) {
instance->children = (struct TreeSeq *) malloc(sizeof(struct TreeSeq));
TreeSeq_initialize(instance->children);
}
TreeSeq_ensure_length(instance->children, childcount, childcount);
for (i = 0; i < childcount; ++i) {
Tree *child = TreeSeq_get_reference(instance->children, i);
fill_tree(child, childcount, depth - 1, value);
}
}
static int publisher_main(int domainId, int sample_count)
{
DDS_DomainParticipant *participant = NULL;
DDS_Publisher *publisher = NULL;
DDS_Topic *topic = NULL;
DDS_DataWriter *writer = NULL;
TreeDataWriter *Tree_writer = NULL;
Tree *instance = NULL;
DDS_ReturnCode_t retcode;
DDS_InstanceHandle_t instance_handle = DDS_HANDLE_NIL;
const char *type_name = NULL;
int count = 0;
struct DDS_Duration_t send_period = { 4, 0 };
/* To customize participant QoS, use
the configuration file USER_QOS_PROFILES.xml */
participant = DDS_DomainParticipantFactory_create_participant(
DDS_TheParticipantFactory,
domainId,
&DDS_PARTICIPANT_QOS_DEFAULT,
NULL /* listener */,
DDS_STATUS_MASK_NONE);
if (participant == NULL) {
printf("create_participant error\n");
publisher_shutdown(participant);
return -1;
}
/* To customize publisher QoS, use
the configuration file USER_QOS_PROFILES.xml */
publisher = DDS_DomainParticipant_create_publisher(
participant,
&DDS_PUBLISHER_QOS_DEFAULT,
NULL /* listener */,
DDS_STATUS_MASK_NONE);
if (publisher == NULL) {
printf("create_publisher error\n");
publisher_shutdown(participant);
return -1;
}
/* Register type before creating topic */
type_name = TreeTypeSupport_get_type_name();
retcode = TreeTypeSupport_register_type(participant, type_name);
if (retcode != DDS_RETCODE_OK) {
printf("register_type error %d\n", retcode);
publisher_shutdown(participant);
return -1;
}
/* To customize topic QoS, use
the configuration file USER_QOS_PROFILES.xml */
topic = DDS_DomainParticipant_create_topic(
participant,
"Example Tree",
type_name,
&DDS_TOPIC_QOS_DEFAULT,
NULL /* listener */,
DDS_STATUS_MASK_NONE);
if (topic == NULL) {
printf("create_topic error\n");
publisher_shutdown(participant);
return -1;
}
/* To customize data writer QoS, use
the configuration file USER_QOS_PROFILES.xml */
writer = DDS_Publisher_create_datawriter(
publisher,
topic,
&DDS_DATAWRITER_QOS_DEFAULT,
NULL /* listener */,
DDS_STATUS_MASK_NONE);
if (writer == NULL) {
printf("create_datawriter error\n");
publisher_shutdown(participant);
return -1;
}
Tree_writer = TreeDataWriter_narrow(writer);
if (Tree_writer == NULL) {
printf("DataWriter narrow error\n");
publisher_shutdown(participant);
return -1;
}
/* Create data sample for writing */
instance = TreeTypeSupport_create_data_ex(DDS_BOOLEAN_TRUE);
if (instance == NULL) {
printf("TreeTypeSupport_create_data error\n");
publisher_shutdown(participant);
return -1;
}
/* For a data type that has a key, if the same instance is going to be
written multiple times, initialize the key here
and register the keyed instance prior to writing */
/*
instance_handle = TreeDataWriter_register_instance(
Tree_writer, instance);
*/
/* Main loop */
for (count = 0; (sample_count == 0) || (count < sample_count); ++count) {
printf("Writing Tree, count %d\n", count);
/* Modify the data to be written here */
fill_tree(instance, 1, count, count);
/* Write data */
retcode = TreeDataWriter_write(Tree_writer, instance, &instance_handle);
if (retcode != DDS_RETCODE_OK) {
printf("write error %d\n", retcode);
}
NDDS_Utility_sleep(&send_period);
}
/*
retcode = TreeDataWriter_unregister_instance(
Tree_writer, instance, &instance_handle);
if (retcode != DDS_RETCODE_OK) {
printf("unregister instance error %d\n", retcode);
}
*/
/* Delete data sample */
retcode = TreeTypeSupport_delete_data_ex(instance, DDS_BOOLEAN_TRUE);
if (retcode != DDS_RETCODE_OK) {
printf("TreeTypeSupport_delete_data error %d\n", retcode);
}
/* Cleanup and delete delete all entities */
return publisher_shutdown(participant);
}
int main(int argc, char *argv[])
{
int domainId = 0;
int sample_count = 0; /* infinite loop */
if (argc >= 2) {
domainId = atoi(argv[1]);
}
if (argc >= 3) {
sample_count = atoi(argv[2]);
}
/* Uncomment this to turn on additional logging
NDDS_Config_Logger_set_verbosity_by_category(
NDDS_Config_Logger_get_instance(),
NDDS_CONFIG_LOG_CATEGORY_API,
NDDS_CONFIG_LOG_VERBOSITY_STATUS_ALL);
*/
return publisher_main(domainId, sample_count);
}
| c |
rticonnextdds-examples | data/projects/rticonnextdds-examples/connext_dds/recursive_data_type/c/RecursiveType_subscriber.c |
/* RecursiveType_subscriber.c
A subscription example
This file is derived from code automatically generated by the rtiddsgen
command:
rtiddsgen -language C -example <arch> RecursiveType.idl
Example subscription of type Tree automatically generated by
'rtiddsgen'. To test them, follow these steps:
(1) Compile this file and the example publication.
(2) Start the subscription on the same domain used for RTI Data Distribution
Service with the command
objs/<arch>/RecursiveType_subscriber <domain_id> <sample_count>
(3) Start the publication on the same domain used for RTI Data Distribution
Service with the command
objs/<arch>/RecursiveType_publisher <domain_id> <sample_count>
(4) [Optional] Specify the list of discovery initial peers and
multicast receive addresses via an environment variable or a file
(in the current working directory) called NDDS_DISCOVERY_PEERS.
You can run any number of publishers and subscribers programs, and can
add and remove them dynamically from the domain.
Example:
To run the example application on domain <domain_id>:
On UNIX systems:
objs/<arch>/RecursiveType_publisher <domain_id>
objs/<arch>/RecursiveType_subscriber <domain_id>
On Windows systems:
objs\<arch>\RecursiveType_publisher <domain_id>
objs\<arch>\RecursiveType_subscriber <domain_id>
*/
#include "RecursiveType.h"
#include "RecursiveTypeSupport.h"
#include "ndds/ndds_c.h"
#include <stdio.h>
#include <stdlib.h>
void TreeListener_on_requested_deadline_missed(
void *listener_data,
DDS_DataReader *reader,
const struct DDS_RequestedDeadlineMissedStatus *status)
{
}
void TreeListener_on_requested_incompatible_qos(
void *listener_data,
DDS_DataReader *reader,
const struct DDS_RequestedIncompatibleQosStatus *status)
{
}
void TreeListener_on_sample_rejected(
void *listener_data,
DDS_DataReader *reader,
const struct DDS_SampleRejectedStatus *status)
{
}
void TreeListener_on_liveliness_changed(
void *listener_data,
DDS_DataReader *reader,
const struct DDS_LivelinessChangedStatus *status)
{
}
void TreeListener_on_sample_lost(
void *listener_data,
DDS_DataReader *reader,
const struct DDS_SampleLostStatus *status)
{
}
void TreeListener_on_subscription_matched(
void *listener_data,
DDS_DataReader *reader,
const struct DDS_SubscriptionMatchedStatus *status)
{
}
void TreeListener_on_data_available(void *listener_data, DDS_DataReader *reader)
{
TreeDataReader *Tree_reader = NULL;
struct TreeSeq data_seq = DDS_SEQUENCE_INITIALIZER;
struct DDS_SampleInfoSeq info_seq = DDS_SEQUENCE_INITIALIZER;
DDS_ReturnCode_t retcode;
int i;
Tree_reader = TreeDataReader_narrow(reader);
if (Tree_reader == NULL) {
printf("DataReader narrow error\n");
return;
}
retcode = TreeDataReader_take(
Tree_reader,
&data_seq,
&info_seq,
DDS_LENGTH_UNLIMITED,
DDS_ANY_SAMPLE_STATE,
DDS_ANY_VIEW_STATE,
DDS_ANY_INSTANCE_STATE);
if (retcode == DDS_RETCODE_NO_DATA) {
return;
} else if (retcode != DDS_RETCODE_OK) {
printf("take error %d\n", retcode);
return;
}
for (i = 0; i < TreeSeq_get_length(&data_seq); ++i) {
if (DDS_SampleInfoSeq_get_reference(&info_seq, i)->valid_data) {
printf("Received data\n");
TreeTypeSupport_print_data(TreeSeq_get_reference(&data_seq, i));
}
}
retcode = TreeDataReader_return_loan(Tree_reader, &data_seq, &info_seq);
if (retcode != DDS_RETCODE_OK) {
printf("return loan error %d\n", retcode);
}
}
/* Delete all entities */
static int subscriber_shutdown(DDS_DomainParticipant *participant)
{
DDS_ReturnCode_t retcode;
int status = 0;
if (participant != NULL) {
retcode = DDS_DomainParticipant_delete_contained_entities(participant);
if (retcode != DDS_RETCODE_OK) {
printf("delete_contained_entities error %d\n", retcode);
status = -1;
}
retcode = DDS_DomainParticipantFactory_delete_participant(
DDS_TheParticipantFactory,
participant);
if (retcode != DDS_RETCODE_OK) {
printf("delete_participant error %d\n", retcode);
status = -1;
}
}
/* RTI Data Distribution Service provides the finalize_instance() method on
domain participant factory for users who want to release memory used
by the participant factory. Uncomment the following block of code for
clean destruction of the singleton. */
/*
retcode = DDS_DomainParticipantFactory_finalize_instance();
if (retcode != DDS_RETCODE_OK) {
printf("finalize_instance error %d\n", retcode);
status = -1;
}
*/
return status;
}
static int subscriber_main(int domainId, int sample_count)
{
DDS_DomainParticipant *participant = NULL;
DDS_Subscriber *subscriber = NULL;
DDS_Topic *topic = NULL;
struct DDS_DataReaderListener reader_listener =
DDS_DataReaderListener_INITIALIZER;
DDS_DataReader *reader = NULL;
DDS_ReturnCode_t retcode;
const char *type_name = NULL;
int count = 0;
struct DDS_Duration_t poll_period = { 4, 0 };
/* To customize participant QoS, use
the configuration file USER_QOS_PROFILES.xml */
participant = DDS_DomainParticipantFactory_create_participant(
DDS_TheParticipantFactory,
domainId,
&DDS_PARTICIPANT_QOS_DEFAULT,
NULL /* listener */,
DDS_STATUS_MASK_NONE);
if (participant == NULL) {
printf("create_participant error\n");
subscriber_shutdown(participant);
return -1;
}
/* To customize subscriber QoS, use
the configuration file USER_QOS_PROFILES.xml */
subscriber = DDS_DomainParticipant_create_subscriber(
participant,
&DDS_SUBSCRIBER_QOS_DEFAULT,
NULL /* listener */,
DDS_STATUS_MASK_NONE);
if (subscriber == NULL) {
printf("create_subscriber error\n");
subscriber_shutdown(participant);
return -1;
}
/* Register the type before creating the topic */
type_name = TreeTypeSupport_get_type_name();
retcode = TreeTypeSupport_register_type(participant, type_name);
if (retcode != DDS_RETCODE_OK) {
printf("register_type error %d\n", retcode);
subscriber_shutdown(participant);
return -1;
}
/* To customize topic QoS, use
the configuration file USER_QOS_PROFILES.xml */
topic = DDS_DomainParticipant_create_topic(
participant,
"Example Tree",
type_name,
&DDS_TOPIC_QOS_DEFAULT,
NULL /* listener */,
DDS_STATUS_MASK_NONE);
if (topic == NULL) {
printf("create_topic error\n");
subscriber_shutdown(participant);
return -1;
}
/* Set up a data reader listener */
reader_listener.on_requested_deadline_missed =
TreeListener_on_requested_deadline_missed;
reader_listener.on_requested_incompatible_qos =
TreeListener_on_requested_incompatible_qos;
reader_listener.on_sample_rejected = TreeListener_on_sample_rejected;
reader_listener.on_liveliness_changed = TreeListener_on_liveliness_changed;
reader_listener.on_sample_lost = TreeListener_on_sample_lost;
reader_listener.on_subscription_matched =
TreeListener_on_subscription_matched;
reader_listener.on_data_available = TreeListener_on_data_available;
/* To customize data reader QoS, use
the configuration file USER_QOS_PROFILES.xml */
reader = DDS_Subscriber_create_datareader(
subscriber,
DDS_Topic_as_topicdescription(topic),
&DDS_DATAREADER_QOS_DEFAULT,
&reader_listener,
DDS_STATUS_MASK_ALL);
if (reader == NULL) {
printf("create_datareader error\n");
subscriber_shutdown(participant);
return -1;
}
/* Main loop */
for (count = 0; (sample_count == 0) || (count < sample_count); ++count) {
printf("Tree subscriber sleeping for %d sec...\n", poll_period.sec);
NDDS_Utility_sleep(&poll_period);
}
/* Cleanup and delete all entities */
return subscriber_shutdown(participant);
}
int main(int argc, char *argv[])
{
int domainId = 0;
int sample_count = 0; /* infinite loop */
if (argc >= 2) {
domainId = atoi(argv[1]);
}
if (argc >= 3) {
sample_count = atoi(argv[2]);
}
/* Uncomment this to turn on additional logging
NDDS_Config_Logger_set_verbosity_by_category(
NDDS_Config_Logger_get_instance(),
NDDS_CONFIG_LOG_CATEGORY_API,
NDDS_CONFIG_LOG_VERBOSITY_STATUS_ALL);
*/
return subscriber_main(domainId, sample_count);
}
| c |
rticonnextdds-examples | data/projects/rticonnextdds-examples/connext_dds/recursive_data_type/c++03/RecursiveType_publisher.cxx | /* RecursiveType_publisher.cxx
A publication of data of type Tree
This file is derived from code automatically generated by the rtiddsgen
command:
rtiddsgen -language C++03 -example <arch> RecursiveType.idl
Example publication of type Tree automatically generated by
'rtiddsgen'. To test them follow these steps:
(1) Compile this file and the example subscription.
(2) Start the subscription on the same domain used for RTI Data Distribution
Service with the command
objs/<arch>/RecursiveType_subscriber <domain_id> <sample_count>
(3) Start the publication on the same domain used for RTI Data Distribution
Service with the command
objs/<arch>/RecursiveType_publisher <domain_id> <sample_count>
(4) [Optional] Specify the list of discovery initial peers and
multicast receive addresses via an environment variable or a file
(in the current working directory) called NDDS_DISCOVERY_PEERS.
You can run any number of publishers and subscribers programs, and can
add and remove them dynamically from the domain.
Example:
To run the example application on domain <domain_id>:
On Unix:
objs/<arch>/RecursiveType_publisher <domain_id>
objs/<arch>/RecursiveType_subscriber <domain_id>
On Windows:
objs\<arch>\RecursiveType_publisher <domain_id>
objs\<arch>\RecursiveType_subscriber <domain_id>
*/
#include <iostream>
#include <dds/pub/ddspub.hpp>
#include <rti/util/util.hpp> // for sleep()
#include "RecursiveType.hpp"
void fill_tree(Tree &tree, int childcount, int depth, int value)
{
tree.node().data(value);
if (depth == 0) {
return;
}
if (!tree.children().is_set()) {
// Initialize Tree with empty vector of children. This
// call makes a copy of the (empty) vector
dds::core::vector<Tree> children;
tree.children(children);
}
// Resize the list of children to the desired length
tree.children().get().resize(childcount);
for (int i = 0; i < childcount; ++i) {
fill_tree(tree.children().get()[i], childcount, depth - 1, value);
}
}
void publisher_main(int domain_id, int sample_count)
{
// Create a DomainParticipant with default Qos
dds::domain::DomainParticipant participant(domain_id);
// Create a Topic -- and automatically register the type
dds::topic::Topic<Tree> topic(participant, "Example Tree");
// Create a DataWriter with default Qos (Publisher created in-line)
dds::pub::DataWriter<Tree> writer(dds::pub::Publisher(participant), topic);
Tree sample;
for (int count = 0; count < sample_count || sample_count == 0; count++) {
// Modify the data to be written here
fill_tree(sample, 1, count, count);
std::cout << "Writing Tree, count " << count << std::endl;
writer.write(sample);
rti::util::sleep(dds::core::Duration(4));
}
}
int main(int argc, char *argv[])
{
int domain_id = 0;
int sample_count = 0; // infinite loop
if (argc >= 2) {
domain_id = atoi(argv[1]);
}
if (argc >= 3) {
sample_count = atoi(argv[2]);
}
// To turn on additional logging, include <rti/config/Logger.hpp> and
// uncomment the following line:
// rti::config::Logger::instance().verbosity(rti::config::Verbosity::STATUS_ALL);
try {
publisher_main(domain_id, sample_count);
} catch (const std::exception &ex) {
// This will catch DDS exceptions
std::cerr << "Exception in publisher_main(): " << ex.what()
<< std::endl;
return -1;
}
// RTI Connext provides a finalize_participant_factory() method
// if you want to release memory used by the participant factory singleton.
// Uncomment the following line to release the singleton:
//
// dds::domain::DomainParticipant::finalize_participant_factory();
return 0;
}
| cxx |
rticonnextdds-examples | data/projects/rticonnextdds-examples/connext_dds/recursive_data_type/c++03/RecursiveType_subscriber.cxx | /* RecursiveType_subscriber.cxx
A subscription example
This file is derived from code automatically generated by the rtiddsgen
command:
rtiddsgen -language C++03 -example <arch> RecursiveType.idl
Example subscription of type Tree automatically generated by
'rtiddsgen'. To test them, follow these steps:
(1) Compile this file and the example publication.
(2) Start the subscription on the same domain used for RTI Data Distribution
Service with the command
objs/<arch>/RecursiveType_subscriber <domain_id> <sample_count>
(3) Start the publication on the same domain used for RTI Data Distribution
Service with the command
objs/<arch>/RecursiveType_publisher <domain_id> <sample_count>
(4) [Optional] Specify the list of discovery initial peers and
multicast receive addresses via an environment variable or a file
(in the current working directory) called NDDS_DISCOVERY_PEERS.
You can run any number of publishers and subscribers programs, and can
add and remove them dynamically from the domain.
Example:
To run the example application on domain <domain_id>:
On UNIX systems:
objs/<arch>/RecursiveType_publisher <domain_id>
objs/<arch>/RecursiveType_subscriber <domain_id>
On Windows systems:
objs\<arch>\RecursiveType_publisher <domain_id>
objs\<arch>\RecursiveType_subscriber <domain_id>
*/
#include <algorithm>
#include <iostream>
#include <dds/core/ddscore.hpp>
#include <dds/sub/ddssub.hpp>
// Or simply include <dds/dds.hpp>
#include "RecursiveType.hpp"
class TreeReaderListener : public dds::sub::NoOpDataReaderListener<Tree> {
public:
TreeReaderListener() : count_(0)
{
}
void on_data_available(dds::sub::DataReader<Tree> &reader)
{
// Take all samples
dds::sub::LoanedSamples<Tree> samples = reader.take();
for (dds::sub::LoanedSamples<Tree>::iterator sample_it =
samples.begin();
sample_it != samples.end();
sample_it++) {
if (sample_it->info().valid()) {
count_++;
std::cout << sample_it->data() << std::endl;
}
}
}
int count() const
{
return count_;
}
private:
int count_;
};
void subscriber_main(int domain_id, int sample_count)
{
// Create a DomainParticipant with default Qos
dds::domain::DomainParticipant participant(domain_id);
// Create a Topic -- and automatically register the type
dds::topic::Topic<Tree> topic(participant, "Example Tree");
// Create a DataReader with default Qos (Subscriber created in-line)
TreeReaderListener listener;
dds::sub::DataReader<Tree> reader(
dds::sub::Subscriber(participant),
topic,
dds::core::QosProvider::Default().datareader_qos(),
&listener,
dds::core::status::StatusMask::data_available());
while (listener.count() < sample_count || sample_count == 0) {
std::cout << "Tree subscriber sleeping for 4 sec..." << std::endl;
rti::util::sleep(dds::core::Duration(4));
}
// Unset the listener to allow the reader destruction
// (rti::core::ListenerBinder can do this automatically)
reader.listener(NULL, dds::core::status::StatusMask::none());
}
int main(int argc, char *argv[])
{
int domain_id = 0;
int sample_count = 0; // infinite loop
if (argc >= 2) {
domain_id = atoi(argv[1]);
}
if (argc >= 3) {
sample_count = atoi(argv[2]);
}
// To turn on additional logging, include <rti/config/Logger.hpp> and
// uncomment the following line:
// rti::config::Logger::instance().verbosity(rti::config::Verbosity::STATUS_ALL);
try {
subscriber_main(domain_id, sample_count);
} catch (const std::exception &ex) {
// This will catch DDS exceptions
std::cerr << "Exception in subscriber_main(): " << ex.what()
<< std::endl;
return -1;
}
// RTI Connext provides a finalize_participant_factory() method
// if you want to release memory used by the participant factory singleton.
// Uncomment the following line to release the singleton:
//
// dds::domain::DomainParticipant::finalize_participant_factory();
return 0;
}
| cxx |
rticonnextdds-examples | data/projects/rticonnextdds-examples/connext_dds/asyncwaitset/c++03/AwsExample_subscriber.cxx | /*******************************************************************************
(c) 2005-2015 Copyright, Real-Time Innovations, Inc. All rights reserved.
RTI grants Licensee a license to use, modify, compile, and create derivative
works of the Software. Licensee has the right to distribute object form only
for use with RTI products. The Software is provided "as is", with no warranty
of any type, including any warranty for fitness for any purpose. RTI is under
no obligation to maintain or support the Software. RTI shall not be liable for
any incidental or consequential damages arising out of the use or inability to
use the software.
******************************************************************************/
#include <iostream>
#include <dds/core/ddscore.hpp>
#include <dds/pub/ddspub.hpp>
#include <dds/sub/ddssub.hpp>
#include <rti/config/Logger.hpp>
#include <rti/core/cond/AsyncWaitSet.hpp>
#include <rti/util/util.hpp> // for sleep()
#include "AwsExample.hpp"
class AwsSubscriber {
public:
static const std::string TOPIC_NAME;
AwsSubscriber(
DDS_DomainId_t domain_id,
rti::core::cond::AsyncWaitSet async_waitset);
void process_received_samples();
int received_count();
~AwsSubscriber();
public:
// Entities to receive data
dds::sub::DataReader<AwsExample> receiver_;
// Reference to the AWS used for processing the events
rti::core::cond::AsyncWaitSet async_waitset_;
};
class DataAvailableHandler {
public:
/* Handles the reception of samples */
void operator()()
{
subscriber_.process_received_samples();
}
DataAvailableHandler(AwsSubscriber &subscriber) : subscriber_(subscriber)
{
}
private:
AwsSubscriber &subscriber_;
};
// AwsSubscriberPlayer implementation
const std::string AwsSubscriber::TOPIC_NAME = "AwsExample Example";
AwsSubscriber::AwsSubscriber(
DDS_DomainId_t domain_id,
rti::core::cond::AsyncWaitSet async_waitset)
: receiver_(dds::core::null), async_waitset_(async_waitset)
{
// Create a DomainParticipant with default Qos
dds::domain::DomainParticipant participant(domain_id);
// Create a Topic -- and automatically register the type
dds::topic::Topic<AwsExample> topic(participant, TOPIC_NAME);
// Create a DataReader with default Qos (Subscriber created in-line)
receiver_ = dds::sub::DataReader<AwsExample>(
dds::sub::Subscriber(participant),
topic);
// DataReader status condition: to process the reception of samples
dds::core::cond::StatusCondition reader_status_condition(receiver_);
reader_status_condition.enabled_statuses(
dds::core::status::StatusMask::data_available());
reader_status_condition->handler(DataAvailableHandler(*this));
async_waitset_.attach_condition(reader_status_condition);
}
void AwsSubscriber::process_received_samples()
{
// Take all samples This will reset the StatusCondition
dds::sub::LoanedSamples<AwsExample> samples = receiver_.take();
// Release status condition in case other threads can process outstanding
// samples
async_waitset_.unlock_condition(
dds::core::cond::StatusCondition(receiver_));
// Process sample
for (dds::sub::LoanedSamples<AwsExample>::iterator sample_it =
samples.begin();
sample_it != samples.end();
sample_it++) {
if (sample_it->info().valid()) {
std::cout << "Received sample:\n\t" << sample_it->data()
<< std::endl;
}
}
// Sleep a random amount of time between 1 and 10 secs. This is
// intended to cause the handling thread of the AWS to take a long
// time dispatching
rti::util::sleep(dds::core::Duration::from_secs(rand() % 10 + 1));
}
int AwsSubscriber::received_count()
{
return receiver_->datareader_protocol_status()
.received_sample_count()
.total();
}
AwsSubscriber::~AwsSubscriber()
{
async_waitset_.detach_condition(
dds::core::cond::StatusCondition(receiver_));
}
int main(int argc, char *argv[])
{
int domain_id = 0;
int thread_pool_size = 4;
int sample_count = 0; // infinite loop
const std::string USAGE(
"AwsSubscriber_subscriber [options]\n"
"Options:\n"
"\t-d, -domainId: Domain ID\n"
"\t-t, -threads: Number of threads used to process sample "
"reception\n"
"\t-s, -samples: Total number of received samples before "
"exiting\n");
srand(time(NULL));
for (int i = 0; i < argc; i++) {
if (strcmp(argv[i], "-d") == 0 || strcmp(argv[i], "-domainId") == 0) {
if (i == argc - 1) {
std::cerr << "missing domain ID parameter value " << std::endl;
return -1;
} else {
domain_id = atoi(argv[++i]);
}
} else if (
strcmp(argv[i], "-t") == 0
|| strcmp(argv[i], "-threads") == 0) {
if (i == argc - 1) {
std::cerr << "missing threads parameter value " << std::endl;
return -1;
} else {
thread_pool_size = atoi(argv[++i]);
}
} else if (
strcmp(argv[i], "-s") == 0
|| strcmp(argv[i], "-samples") == 0) {
if (i == argc - 1) {
std::cerr << "missing samples parameter value " << std::endl;
return -1;
} else {
sample_count = atoi(argv[++i]);
}
} else if (
strcmp(argv[i], "-h") == 0 || strcmp(argv[i], "-help") == 0) {
std::cout << USAGE << std::endl;
return 0;
}
}
// To turn on additional logging, include <rti/config/Logger.hpp> and
// uncomment the following line:
// rti::config::Logger::instance().verbosity(rti::config::Verbosity::STATUS_ALL);
try {
// An AsyncWaitSet (AWS) for multi-threaded events .
// The AWS will provide the infrastructure to receive samples using
// multiple threads.
rti::core::cond::AsyncWaitSet async_waitset(
rti::core::cond::AsyncWaitSetProperty().thread_pool_size(
thread_pool_size));
async_waitset.start();
AwsSubscriber subscriber(domain_id, async_waitset);
std::cout << "Wait for samples..." << std::endl;
while (subscriber.received_count() < sample_count
|| sample_count == 0) {
rti::util::sleep(dds::core::Duration(1));
}
} catch (const std::exception &ex) {
// This will catch DDS exceptions
std::cerr << "Exception in main(): " << ex.what() << std::endl;
return -1;
}
// RTI Connext provides a finalize_participant_factory() method
// if you want to release memory used by the participant factory singleton.
// Uncomment the following line to release the singleton:
//
// dds::domain::DomainParticipant::finalize_participant_factory();
return 0;
}
| cxx |
rticonnextdds-examples | data/projects/rticonnextdds-examples/connext_dds/asyncwaitset/c++03/AwsExample_publisher.cxx | /*******************************************************************************
(c) 2005-2015 Copyright, Real-Time Innovations, Inc. All rights reserved.
RTI grants Licensee a license to use, modify, compile, and create derivative
works of the Software. Licensee has the right to distribute object form only
for use with RTI products. The Software is provided "as is", with no warranty
of any type, including any warranty for fitness for any purpose. RTI is under
no obligation to maintain or support the Software. RTI shall not be liable for
any incidental or consequential damages arising out of the use or inability to
use the software.
******************************************************************************/
#include <iostream>
#include <dds/core/ddscore.hpp>
#include <dds/pub/ddspub.hpp>
#include <dds/sub/ddssub.hpp>
#include <rti/core/cond/AsyncWaitSet.hpp>
#include <rti/util/util.hpp> // for sleep()
#include "AwsExample.hpp"
class AwsPublisher {
public:
static const std::string TOPIC_NAME;
AwsPublisher(
DDS_DomainId_t domain_id,
int publisher_id,
rti::core::cond::AsyncWaitSet async_waitset);
void generate_send_event();
void send_sample();
~AwsPublisher();
private:
// A writer to send data
dds::pub::DataWriter<AwsExample> sender_;
// Sample buffer
AwsExample sample_;
// A GuardCondition to generate app-driven sends
dds::core::cond::GuardCondition send_condition_;
// Reference to the AWS used for writing the samples
rti::core::cond::AsyncWaitSet async_waitset_;
};
class SendRequestHandler {
public:
// Handles the send sample condition
void operator()(dds::core::cond::Condition condition)
{
// condition is the same than sendCondition_ so it is safe to
// perform the downcast. It is important to reset the condition trigger
// to avoid continuous wakeup and dispatch
dds::core::cond::GuardCondition guard_condition =
dds::core::polymorphic_cast<dds::core::cond::GuardCondition>(
condition);
guard_condition.trigger_value(false);
publisher_.send_sample();
}
SendRequestHandler(AwsPublisher &publisher) : publisher_(publisher)
{
}
private:
AwsPublisher &publisher_;
};
// AwsPublisher implementation
const std::string AwsPublisher::TOPIC_NAME = "AwsExample Example";
AwsPublisher::AwsPublisher(
DDS_DomainId_t domain_id,
int publisher_id,
rti::core::cond::AsyncWaitSet async_waitset)
: sender_(dds::core::null), async_waitset_(async_waitset)
{
// Create a DomainParticipant with default Qos
dds::domain::DomainParticipant participant(domain_id);
// Create a Topic -- and automatically register the type
dds::topic::Topic<AwsExample> topic(participant, TOPIC_NAME);
// Create a DataWriter with default Qos (Publisher created in-line)
sender_ = dds::pub::DataWriter<AwsExample>(
dds::pub::Publisher(participant),
topic);
// set sample key value:
sample_.key(publisher_id);
// Send condition: to generate application-driven events to send samples
send_condition_.handler(SendRequestHandler(*this));
async_waitset_.attach_condition(send_condition_);
}
void AwsPublisher::generate_send_event()
{
send_condition_.trigger_value(true);
}
void AwsPublisher::send_sample()
{
std::cout << "Send Sample: " << sample_.number() << std::endl;
sample_.number(sample_.number() + 1);
sender_.write(sample_);
}
AwsPublisher::~AwsPublisher()
{
async_waitset_.detach_condition(send_condition_);
}
int main(int argc, char *argv[])
{
int domain_id = 0;
int publisher_id = 0;
int sample_count = 0; // infinite loop
const std::string USAGE(
"Aws_publisher [options]\n"
"Options:\n"
"\t-d, -domainId: Domain ID\n"
"\t-p, -publisherId: Key value for the Aws samples\n"
"\t-s, -samples: Total number of published samples\n");
srand(time(NULL));
publisher_id = rand() % RAND_MAX;
for (int i = 0; i < argc; i++) {
if (strcmp(argv[i], "-d") == 0 || strcmp(argv[i], "-domainId") == 0) {
if (i == argc - 1) {
std::cerr << "missing domain ID parameter value " << std::endl;
return -1;
} else {
domain_id = atoi(argv[++i]);
}
} else if (
strcmp(argv[i], "-p") == 0
|| strcmp(argv[i], "-publisherId") == 0) {
if (i == argc - 1) {
std::cerr << "missing publisher ID parameter value "
<< std::endl;
return -1;
} else {
publisher_id = atoi(argv[++i]);
}
} else if (
strcmp(argv[i], "-s") == 0
|| strcmp(argv[i], "-samples") == 0) {
if (i == argc - 1) {
std::cerr << "missing samples parameter value " << std::endl;
return -1;
} else {
sample_count = atoi(argv[++i]);
}
} else if (
strcmp(argv[i], "-h") == 0 || strcmp(argv[i], "-help") == 0) {
std::cout << USAGE << std::endl;
return 0;
}
}
// To turn on additional logging, include <rti/config/Logger.hpp> and
// uncomment the following line:
// rti::config::Logger::instance().verbosity(rti::config::Verbosity::STATUS_ALL);
try {
// An AsyncWaitSet (AWS) to send samples in a separate thread
rti::core::cond::AsyncWaitSet async_waitset;
async_waitset.start();
AwsPublisher publisher(domain_id, publisher_id, async_waitset);
// Generate periodic send events
for (int count = 0; count < sample_count || sample_count == 0;
count++) {
publisher.generate_send_event();
rti::util::sleep(dds::core::Duration(1));
}
} catch (const std::exception &ex) {
// This will catch DDS exceptions
std::cerr << "Exception in publisher_main(): " << ex.what()
<< std::endl;
return -1;
}
// RTI Connext provides a finalize_participant_factory() method
// if you want to release memory used by the participant factory singleton.
// Uncomment the following line to release the singleton:
//
// dds::domain::DomainParticipant::finalize_participant_factory();
return 0;
}
| cxx |
rticonnextdds-examples | data/projects/rticonnextdds-examples/connext_dds/asyncwaitset/c++11/AwsExample_subscriber.cxx | /*******************************************************************************
(c) 2005-2015 Copyright, Real-Time Innovations, Inc. All rights reserved.
RTI grants Licensee a license to use, modify, compile, and create derivative
works of the Software. Licensee has the right to distribute object form only
for use with RTI products. The Software is provided "as is", with no warranty
of any type, including any warranty for fitness for any purpose. RTI is under
no obligation to maintain or support the Software. RTI shall not be liable for
any incidental or consequential damages arising out of the use or inability to
use the software.
******************************************************************************/
#include <iostream>
#include <dds/core/ddscore.hpp>
#include <dds/pub/ddspub.hpp>
#include <dds/sub/ddssub.hpp>
#include <rti/config/Logger.hpp>
#include <rti/core/cond/AsyncWaitSet.hpp>
#include <rti/util/util.hpp> // for sleep()
#include "AwsExample.hpp"
#include "application.hpp"
class AwsSubscriber {
public:
static const std::string TOPIC_NAME;
AwsSubscriber(
DDS_DomainId_t domain_id,
rti::core::cond::AsyncWaitSet async_waitset);
void process_received_samples();
int received_count();
~AwsSubscriber();
public:
// Entities to receive data
dds::sub::DataReader<AwsExample> receiver_;
// Reference to the AWS used for processing the events
rti::core::cond::AsyncWaitSet async_waitset_;
};
class DataAvailableHandler {
public:
/* Handles the reception of samples */
void operator()()
{
subscriber_.process_received_samples();
}
DataAvailableHandler(AwsSubscriber &subscriber) : subscriber_(subscriber)
{
}
private:
AwsSubscriber &subscriber_;
};
// AwsSubscriberPlayer implementation
const std::string AwsSubscriber::TOPIC_NAME = "AwsExample Example";
AwsSubscriber::AwsSubscriber(
DDS_DomainId_t domain_id,
rti::core::cond::AsyncWaitSet async_waitset)
: receiver_(dds::core::null), async_waitset_(async_waitset)
{
// Create a DomainParticipant with default Qos
dds::domain::DomainParticipant participant(domain_id);
// Create a Topic -- and automatically register the type
dds::topic::Topic<AwsExample> topic(participant, TOPIC_NAME);
// Create a DataReader with default Qos (Subscriber created in-line)
receiver_ = dds::sub::DataReader<AwsExample>(
dds::sub::Subscriber(participant),
topic);
// DataReader status condition: to process the reception of samples
dds::core::cond::StatusCondition reader_status_condition(receiver_);
reader_status_condition.enabled_statuses(
dds::core::status::StatusMask::data_available());
reader_status_condition->handler(DataAvailableHandler(*this));
async_waitset_.attach_condition(reader_status_condition);
}
void AwsSubscriber::process_received_samples()
{
// Take all samples This will reset the StatusCondition
dds::sub::LoanedSamples<AwsExample> samples = receiver_.take();
// Release status condition in case other threads can process outstanding
// samples
async_waitset_.unlock_condition(
dds::core::cond::StatusCondition(receiver_));
// Process sample
for (const auto &sample : samples) {
if (sample.info().valid()) {
std::cout << "Received sample:\n\t" << sample.data() << std::endl;
}
}
// Sleep a random amount of time between 1 and 10 secs. This is
// intended to cause the handling thread of the AWS to take a long
// time dispatching
rti::util::sleep(dds::core::Duration::from_secs(rand() % 10 + 1));
}
int AwsSubscriber::received_count()
{
return receiver_->datareader_protocol_status()
.received_sample_count()
.total();
}
AwsSubscriber::~AwsSubscriber()
{
async_waitset_.detach_condition(
dds::core::cond::StatusCondition(receiver_));
}
int main(int argc, char *argv[])
{
using namespace application;
srand(time(NULL));
// Parse arguments and handle control-C
auto arguments = parse_arguments(argc, argv, ApplicationKind::Subscriber);
if (arguments.parse_result == ParseReturn::exit) {
return EXIT_SUCCESS;
} else if (arguments.parse_result == ParseReturn::failure) {
return EXIT_FAILURE;
}
setup_signal_handlers();
// Sets Connext verbosity to help debugging
rti::config::Logger::instance().verbosity(arguments.verbosity);
try {
// An AsyncWaitSet (AWS) for multi-threaded events .
// The AWS will provide the infrastructure to receive samples using
// multiple threads.
rti::core::cond::AsyncWaitSet async_waitset(
rti::core::cond::AsyncWaitSetProperty().thread_pool_size(
arguments.thread_pool_size));
async_waitset.start();
AwsSubscriber subscriber(arguments.domain_id, async_waitset);
std::cout << "Wait for samples..." << std::endl;
while (!application::shutdown_requested
&& subscriber.received_count() < arguments.sample_count) {
rti::util::sleep(dds::core::Duration(1));
}
} catch (const std::exception &ex) {
// This will catch DDS exceptions
std::cerr << "Exception in main(): " << ex.what() << std::endl;
return -1;
}
// Releases the memory used by the participant factory. Optional at
// application exit
dds::domain::DomainParticipant::finalize_participant_factory();
return EXIT_SUCCESS;
}
| cxx |
rticonnextdds-examples | data/projects/rticonnextdds-examples/connext_dds/asyncwaitset/c++11/application.hpp | /*
* (c) Copyright, Real-Time Innovations, 2020. All rights reserved.
* RTI grants Licensee a license to use, modify, compile, and create derivative
* works of the software solely for use with RTI Connext DDS. Licensee may
* redistribute copies of the software provided that all such copies are subject
* to this license. The software is provided "as is", with no warranty of any
* type, including any warranty for fitness for any purpose. RTI is under no
* obligation to maintain or support the software. RTI shall not be liable for
* any incidental or consequential damages arising out of the use or inability
* to use the software.
*/
#ifndef APPLICATION_HPP
#define APPLICATION_HPP
#include <iostream>
#include <csignal>
#include <dds/core/ddscore.hpp>
namespace application {
// Catch control-C and tell application to shut down
bool shutdown_requested = false;
inline void stop_handler(int)
{
shutdown_requested = true;
std::cout << "preparing to shut down..." << std::endl;
}
inline void setup_signal_handlers()
{
signal(SIGINT, stop_handler);
signal(SIGTERM, stop_handler);
}
enum class ParseReturn { ok, failure, exit };
enum class ApplicationKind { Publisher, Subscriber };
struct ApplicationArguments {
ParseReturn parse_result;
unsigned int domain_id;
unsigned int sample_count;
rti::config::Verbosity verbosity;
unsigned int publisher_id;
unsigned int thread_pool_size;
ApplicationArguments(
ParseReturn parse_result_param,
unsigned int domain_id_param,
unsigned int sample_count_param,
rti::config::Verbosity verbosity_param,
unsigned int publisher_id_param,
unsigned int thread_pool_size_param)
: parse_result(parse_result_param),
domain_id(domain_id_param),
sample_count(sample_count_param),
verbosity(verbosity_param),
publisher_id(publisher_id_param),
thread_pool_size(thread_pool_size_param)
{
}
};
inline void set_verbosity(
rti::config::Verbosity &verbosity,
int verbosity_value)
{
switch (verbosity_value) {
case 0:
verbosity = rti::config::Verbosity::SILENT;
break;
case 1:
verbosity = rti::config::Verbosity::EXCEPTION;
break;
case 2:
verbosity = rti::config::Verbosity::WARNING;
break;
case 3:
verbosity = rti::config::Verbosity::STATUS_ALL;
break;
default:
verbosity = rti::config::Verbosity::EXCEPTION;
break;
}
}
// Parses application arguments for example.
inline ApplicationArguments parse_arguments(
int argc,
char *argv[],
ApplicationKind current_application)
{
srand(time(NULL));
int arg_processing = 1;
bool show_usage = false;
ParseReturn parse_result = ParseReturn::ok;
unsigned int domain_id = 0;
unsigned int sample_count = (std::numeric_limits<unsigned int>::max)();
rti::config::Verbosity verbosity(rti::config::Verbosity::EXCEPTION);
unsigned int publisher_id = rand() % RAND_MAX;
unsigned int thread_pool_size = 4;
while (arg_processing < argc) {
if ((argc > arg_processing + 1)
&& (strcmp(argv[arg_processing], "-d") == 0
|| strcmp(argv[arg_processing], "--domain") == 0)) {
domain_id = atoi(argv[arg_processing + 1]);
arg_processing += 2;
} else if (
(argc > arg_processing + 1)
&& (strcmp(argv[arg_processing], "-s") == 0
|| strcmp(argv[arg_processing], "--sample-count") == 0)) {
sample_count = atoi(argv[arg_processing + 1]);
arg_processing += 2;
} else if (
(argc > arg_processing + 1)
&& current_application == ApplicationKind::Publisher
&& (strcmp(argv[arg_processing], "-p") == 0
|| strcmp(argv[arg_processing], "--publisherId") == 0)) {
publisher_id = atoi(argv[arg_processing + 1]);
arg_processing += 2;
} else if (
(argc > arg_processing + 1)
&& current_application == ApplicationKind::Subscriber
&& (strcmp(argv[arg_processing], "-t") == 0
|| strcmp(argv[arg_processing], "--threads") == 0)) {
thread_pool_size = atoi(argv[arg_processing + 1]);
arg_processing += 2;
} else if (
(argc > arg_processing + 1)
&& (strcmp(argv[arg_processing], "-v") == 0
|| strcmp(argv[arg_processing], "--verbosity") == 0)) {
set_verbosity(verbosity, atoi(argv[arg_processing + 1]));
arg_processing += 2;
} else if (
strcmp(argv[arg_processing], "-h") == 0
|| strcmp(argv[arg_processing], "--help") == 0) {
std::cout << "Example application." << std::endl;
show_usage = true;
parse_result = ParseReturn::exit;
break;
} else {
std::cout << "Bad parameter." << std::endl;
show_usage = true;
parse_result = ParseReturn::failure;
break;
}
}
if (show_usage) {
std::cout << "Usage:\n"
" -d, --domain <int> Domain ID this "
"application will\n"
" subscribe in. \n"
" Default: 0\n"
" -s, --sample_count <int> Number of samples to "
"receive before\n"
" cleanly shutting down. \n"
" Default: infinite\n";
if (current_application == ApplicationKind::Publisher) {
std::cout << " -p, --publisherId <int> Key value for the Aws "
"samples.\n"
" Default: random\n";
} else {
std::cout << " -t, --threads <int> Number of threads "
"used to\n"
" process sample "
"reception.\n"
" Default: 4\n";
}
std::cout << " -v, --verbosity <int> How much debugging output "
"to show.\n"
" Range: 0-3 \n"
" Default: 1"
<< std::endl;
}
return ApplicationArguments(
parse_result,
domain_id,
sample_count,
verbosity,
publisher_id,
thread_pool_size);
}
} // namespace application
#endif // APPLICATION_HPP | hpp |
rticonnextdds-examples | data/projects/rticonnextdds-examples/connext_dds/asyncwaitset/c++11/AwsExample_publisher.cxx | /*******************************************************************************
(c) 2005-2015 Copyright, Real-Time Innovations, Inc. All rights reserved.
RTI grants Licensee a license to use, modify, compile, and create derivative
works of the Software. Licensee has the right to distribute object form only
for use with RTI products. The Software is provided "as is", with no warranty
of any type, including any warranty for fitness for any purpose. RTI is under
no obligation to maintain or support the Software. RTI shall not be liable for
any incidental or consequential damages arising out of the use or inability to
use the software.
******************************************************************************/
#include <iostream>
#include <dds/core/ddscore.hpp>
#include <dds/pub/ddspub.hpp>
#include <dds/sub/ddssub.hpp>
#include <rti/config/Logger.hpp>
#include <rti/core/cond/AsyncWaitSet.hpp>
#include <rti/util/util.hpp> // for sleep()
#include "AwsExample.hpp"
#include "application.hpp"
class AwsPublisher {
public:
static const std::string TOPIC_NAME;
AwsPublisher(
DDS_DomainId_t domain_id,
int publisher_id,
rti::core::cond::AsyncWaitSet async_waitset);
void generate_send_event();
void send_sample();
~AwsPublisher();
private:
// A writer to send data
dds::pub::DataWriter<AwsExample> sender_;
// Sample buffer
AwsExample sample_;
// A GuardCondition to generate app-driven sends
dds::core::cond::GuardCondition send_condition_;
// Reference to the AWS used for writing the samples
rti::core::cond::AsyncWaitSet async_waitset_;
};
class SendRequestHandler {
public:
// Handles the send sample condition
void operator()(dds::core::cond::Condition condition)
{
// condition is the same than sendCondition_ so it is safe to
// perform the downcast. It is important to reset the condition trigger
// to avoid continuous wakeup and dispatch
dds::core::cond::GuardCondition guard_condition =
dds::core::polymorphic_cast<dds::core::cond::GuardCondition>(
condition);
guard_condition.trigger_value(false);
publisher_.send_sample();
}
SendRequestHandler(AwsPublisher &publisher) : publisher_(publisher)
{
}
private:
AwsPublisher &publisher_;
};
// AwsPublisher implementation
const std::string AwsPublisher::TOPIC_NAME = "AwsExample Example";
AwsPublisher::AwsPublisher(
DDS_DomainId_t domain_id,
int publisher_id,
rti::core::cond::AsyncWaitSet async_waitset)
: sender_(dds::core::null), async_waitset_(async_waitset)
{
// Create a DomainParticipant with default Qos
dds::domain::DomainParticipant participant(domain_id);
// Create a Topic -- and automatically register the type
dds::topic::Topic<AwsExample> topic(participant, TOPIC_NAME);
// Create a DataWriter with default Qos (Publisher created in-line)
sender_ = dds::pub::DataWriter<AwsExample>(
dds::pub::Publisher(participant),
topic);
// set sample key value:
sample_.key(publisher_id);
// Send condition: to generate application-driven events to send samples
send_condition_.handler(SendRequestHandler(*this));
async_waitset_.attach_condition(send_condition_);
}
void AwsPublisher::generate_send_event()
{
send_condition_.trigger_value(true);
}
void AwsPublisher::send_sample()
{
std::cout << "Send Sample: " << sample_.number() << std::endl;
sample_.number(sample_.number() + 1);
sender_.write(sample_);
}
AwsPublisher::~AwsPublisher()
{
async_waitset_.detach_condition(send_condition_);
}
int main(int argc, char *argv[])
{
using namespace application;
// Parse arguments and handle control-C
auto arguments = parse_arguments(argc, argv, ApplicationKind::Publisher);
if (arguments.parse_result == ParseReturn::exit) {
return EXIT_SUCCESS;
} else if (arguments.parse_result == ParseReturn::failure) {
return EXIT_FAILURE;
}
setup_signal_handlers();
// Sets Connext verbosity to help debugging
rti::config::Logger::instance().verbosity(arguments.verbosity);
try {
// An AsyncWaitSet (AWS) to send samples in a separate thread
rti::core::cond::AsyncWaitSet async_waitset;
async_waitset.start();
AwsPublisher publisher(
arguments.domain_id,
arguments.publisher_id,
async_waitset);
// Generate periodic send events
for (unsigned int count = 0;
!application::shutdown_requested && count < arguments.sample_count;
count++) {
publisher.generate_send_event();
rti::util::sleep(dds::core::Duration(1));
}
} catch (const std::exception &ex) {
// This will catch DDS exceptions
std::cerr << "Exception in publisher_main(): " << ex.what()
<< std::endl;
return -1;
}
// Releases the memory used by the participant factory. Optional at
// application exit
dds::domain::DomainParticipant::finalize_participant_factory();
return EXIT_SUCCESS;
}
| cxx |
rticonnextdds-examples | data/projects/rticonnextdds-examples/lambda_content_filter/c++11/LambdaFilterExample_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 <random>
#include <dds/pub/ddspub.hpp>
#include <rti/util/util.hpp> // for sleep()
#include "LambdaFilterExample.hpp"
#include "LambdaFilter.hpp"
void publisher_main(int domain_id, int sample_count)
{
// Create a DomainParticipant with default Qos
dds::domain::DomainParticipant participant (domain_id);
// Register the same filter we use in the subscriber.
//
// This is *optional*, but recommended for better network usage. By
// registering the filter on this participant, we allow the DataWriter to
// filter the samples it writes before sending them.
//
// Note that the filter name and its definition need to be identical to the
// one in the subscribing application.
//
create_lambda_filter<Stock>(
"stock_cft",
participant,
[](const Stock& stock)
{
return stock.symbol() == "GOOG" || stock.symbol() == "IBM";
}
);
// Create a Topic -- and automatically register the type
dds::topic::Topic<Stock> topic (participant, "Example Stock");
// Create a DataWriter with default Qos (Publisher created in-line)
dds::pub::DataWriter<Stock> writer(dds::pub::Publisher(participant), topic);
Stock sample;
std::vector<std::string> symbols {"GOOG", "IBM", "RTI", "MSFT"};
std::random_device random_device;
std::uniform_int_distribution<int> distribution(0, symbols.size() - 1);
for (int count = 0; count < sample_count || sample_count == 0; count++) {
// Modify the data to be written here
sample.symbol(symbols[distribution(random_device)]);
sample.value(distribution(random_device) * 1.1);
// Print the sample we're writting
std::cout << "Writing " << sample << std::endl;
writer.write(sample);
// Print whether the sample was pushed on the network (to the DataReader)
// or not (for example, because it was locally filtered out)
auto pushed_samples =
writer->datawriter_protocol_status().pushed_sample_count().change();
std::cout << "Sample was "
<< (pushed_samples != 0 ? "pushed" : "not pushed")
<< 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() << "\n";
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/lambda_content_filter/c++11/LambdaFilter.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 <dds/topic/Filter.hpp>
#include <rti/topic/ContentFilter.hpp>
//
// A generic ContentFilter that works with a lambda function.
//
// Since this filter is fully defined at compile time, it doesn't expect
// any expression or parameters.
//
template <typename T>
class LambdaFilter : public rti::topic::ContentFilter<T> {
public:
// The expected function signature: takes a sample of type T and decides
// whether it passes the filter (return true) or not (return false).
typedef std::function<bool(const T&)> LambdaType;
// Creates a LambdaFilter with the given filter function
LambdaFilter(LambdaType f) : filter_(f) {}
rti::topic::no_compile_data_t& compile(
const std::string& expression,
const dds::core::StringSeq& parameters,
const dds::core::optional<dds::core::xtypes::DynamicType>& type_code,
const std::string& type_class_name,
rti::topic::no_compile_data_t* old_compile_data) override
{
// Nothing to compile, the lambda function does everything!
return rti::topic::no_compile_data;
}
bool evaluate(
rti::topic::no_compile_data_t& compile_data,
const T& sample,
const rti::topic::FilterSampleInfo& meta_data) override
{
// Run the function
return filter_(sample);
}
void finalize(rti::topic::no_compile_data_t& compile_data) override
{
// Nothing to finalize
}
private:
LambdaType filter_; // The function used to filter
};
// Creates and register in the participant with the given name
// a new custom filter based on a lambda function.
//
// The filter can be used to create ContentFilteredTopics, QueryConditions or
// to enable DataWriters to perform writer-side
// filtering for DataReaders using a filter with the same name.
//
// @param name The name used to register the filter on the participant. This name
// is also used to allow a DataWriter to filter samples before sending them to
// a DataReader that uses a ContentFilteredTopic with the same filter. If the
// names are equal, the DataWriter will use his filter, so the lambda function
// should also be the same.
//
// @param participant The participant where to register the filter so its
// DataWriters and DataReaders can use it.
//
// @param lambda_func The function that decides if a sample of type T
// passes the filter or not. The function must have a single argument of type
// const T& and return a bool.
//
// @return A Filter object that can be used to create a ContentFilteredTopic,
// or a QueryCondition.
//
template <typename T>
dds::topic::Filter create_lambda_filter(
const std::string& name,
dds::domain::DomainParticipant participant,
typename LambdaFilter<T>::LambdaType lambda_func)
{
participant->register_contentfilter(
rti::topic::CustomFilter<LambdaFilter<T> >(
new LambdaFilter<T>(lambda_func)),
name);
dds::topic::Filter filter(""); // no expression
filter->name(name);
return filter;
}
// Uses the Filter that create_lambda_filter() returns to create
// a ContentFilteredTopic for the given Topic.
template <typename T>
dds::topic::ContentFilteredTopic<T> create_lambda_cft(
const std::string& name,
dds::topic::Topic<T>& topic,
typename LambdaFilter<T>::LambdaType lambda_func)
{
return dds::topic::ContentFilteredTopic<T>(
topic,
name,
create_lambda_filter<T>(name, topic.participant(), lambda_func));
}
| hpp |
rticonnextdds-examples | data/projects/rticonnextdds-examples/lambda_content_filter/c++11/LambdaFilterExample_subscriber.cxx | /*******************************************************************************
(c) 2005-2015 Copyright, Real-Time Innovations, Inc. All rights reserved.
RTI grants Licensee a license to use, modify, compile, and create derivative
works of the Software. Licensee has the right to distribute object form only
for use with RTI products. The Software is provided "as is", with no warranty
of any type, including any warranty for fitness for any purpose. RTI is under
no obligation to maintain or support the Software. RTI shall not be liable for
any incidental or consequential damages arising out of the use or inability to
use the software.
******************************************************************************/
#include <algorithm>
#include <iostream>
#include <dds/sub/ddssub.hpp>
#include <dds/core/ddscore.hpp>
// Or simply include <dds/dds.hpp>
#include "LambdaFilterExample.hpp"
#include "LambdaFilter.hpp"
void subscriber_main(int domain_id, int sample_count)
{
dds::domain::DomainParticipant participant(domain_id);
dds::topic::Topic<Stock> topic(participant, "Example Stock");
// Create a ContentFilteredTopic that only selects those Stocks whose
// symbol is GOOG or IBM.
auto lambda_cft = create_lambda_cft<Stock>(
"stock_cft",
topic,
[](const Stock& stock)
{
return stock.symbol() == "GOOG" || stock.symbol() == "IBM";
}
);
dds::sub::DataReader<Stock> reader(
dds::sub::Subscriber(participant), lambda_cft);
// 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<Stock> 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 << "Stock subscriber sleeping for 4 sec...\n";
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() << "\n";
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/content_filtered_topic_string_filter/c++/cft_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.
******************************************************************************/
/* cft_publisher.cxx
A publication of data of type cft
This file is derived from code automatically generated by the rtiddsgen
command:
rtiddsgen -language C++ -example <arch> cft.idl
Example publication of type cft 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>/cft_subscriber <domain_id> <sample_count>
(3) Start the publication with the command
objs/<arch>/cft_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>/cft_publisher <domain_id> o
objs/<arch>/cft_subscriber <domain_id>
On Windows:
objs\<arch>\cft_publisher <domain_id>
objs\<arch>\cft_subscriber <domain_id>
modification history
------------ -------
*/
#include <stdio.h>
#include <stdlib.h>
#ifdef RTI_VX653
#include <vThreadsData.h>
#endif
#include "cft.h"
#include "cftSupport.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;
cftDataWriter * cft_writer = NULL;
cft *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};
char* even_string = DDS_String_dup("EVEN");
char* odd_string = DDS_String_dup("ODD");
/* 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 = cftTypeSupport::get_type_name();
retcode = cftTypeSupport::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 cft",
type_name, DDS_TOPIC_QOS_DEFAULT, NULL /* listener */,
DDS_STATUS_MASK_NONE);
if (topic == NULL) {
printf("create_topic error\n");
publisher_shutdown(participant);
return -1;
}
/* To customize data writer QoS, use
the configuration file USER_QOS_PROFILES.xml */
writer = publisher->create_datawriter(
topic, DDS_DATAWRITER_QOS_DEFAULT, NULL /* listener */,
DDS_STATUS_MASK_NONE);
if (writer == NULL) {
printf("create_datawriter error\n");
publisher_shutdown(participant);
return -1;
}
/* If you want to set the reliability and history QoS settings
* programmatically rather than using the XML, you will need to add
* the following lines to your code and comment out the create_datawriter
* call above.
*/
/*
DDS_DataWriterQos datawriter_qos;
retcode = publisher->get_default_datawriter_qos(datawriter_qos);
if (retcode != DDS_RETCODE_OK) {
printf("get_default_datawriter_qos error\n");
return -1;
}
datawriter_qos.reliability.kind = DDS_RELIABLE_RELIABILITY_QOS;
datawriter_qos.durability.kind = DDS_TRANSIENT_LOCAL_DURABILITY_QOS;
datawriter_qos.history.kind = DDS_KEEP_LAST_HISTORY_QOS;
datawriter_qos.history.depth = 20;
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;
}
*/
cft_writer = cftDataWriter::narrow(writer);
if (cft_writer == NULL) {
printf("DataWriter narrow error\n");
publisher_shutdown(participant);
return -1;
}
/* Create data sample for writing */
instance = cftTypeSupport::create_data();
if (instance == NULL) {
printf("cftTypeSupport::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 = cft_writer->register_instance(*instance);
*/
/* Main loop */
for (count=0; (sample_count == 0) || (count < sample_count); ++count) {
printf("Writing cft, count %d\n", count);
/* Modify the data to be sent here */
if(count%2 == 1){
instance->name = odd_string;
} else {
instance->name = even_string;
}
instance->count = count;
retcode = cft_writer->write(*instance, instance_handle);
if (retcode != DDS_RETCODE_OK) {
printf("write error %d\n", retcode);
}
NDDSUtility::sleep(send_period);
}
/*
retcode = cft_writer->unregister_instance(
*instance, instance_handle);
if (retcode != DDS_RETCODE_OK) {
printf("unregister instance error %d\n", retcode);
}
*/
/* Delete data sample */
retcode = cftTypeSupport::delete_data(instance);
if (retcode != DDS_RETCODE_OK) {
printf("cftTypeSupport::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/content_filtered_topic_string_filter/c++/cft_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.
******************************************************************************/
/* cft_subscriber.cxx
A subscription example
This file is derived from code automatically generated by the rtiddsgen
command:
rtiddsgen -language C++ -example <arch> cft.idl
Example subscription of type cft 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>/cft_subscriber <domain_id> <sample_count>
(3) Start the publication with the command
objs/<arch>/cft_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>/cft_publisher <domain_id>
objs/<arch>/cft_subscriber <domain_id>
On Windows:
objs\<arch>\cft_publisher <domain_id>
objs\<arch>\cft_subscriber <domain_id>
modification history
------------ -------
*/
#include <stdio.h>
#include <stdlib.h>
#ifdef RTI_VX653
#include <vThreadsData.h>
#endif
#include "cft.h"
#include "cftSupport.h"
#include "ndds/ndds_cpp.h"
class cftListener : 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 cftListener::on_data_available(DDSDataReader* reader)
{
cftDataReader *cft_reader = NULL;
cftSeq data_seq;
DDS_SampleInfoSeq info_seq;
DDS_ReturnCode_t retcode;
int i;
cft_reader = cftDataReader::narrow(reader);
if (cft_reader == NULL) {
printf("DataReader narrow error\n");
return;
}
retcode = cft_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) {
cftTypeSupport::print_data(&data_seq[i]);
}
}
retcode = cft_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, int sel_cft)
{
DDSDomainParticipant *participant = NULL;
DDSSubscriber *subscriber = NULL;
DDSTopic *topic = NULL;
cftListener *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;
DDSContentFilteredTopic *cft = NULL;
/* For this filter we only allow 1 parameter*/
DDS_StringSeq parameters(1);
const char* param_list[] = {"SOME_STRING"};
/* 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 = cftTypeSupport::get_type_name();
retcode = cftTypeSupport::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 cft",
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;
}
parameters.from_array(param_list, 1);
if (sel_cft) {
/* create_contentfilteredtopic_with_filter */
cft = participant->create_contentfilteredtopic_with_filter(
"ContentFilteredTopic", topic, "name MATCH %0", parameters,
DDS_STRINGMATCHFILTER_NAME);
if (cft == NULL) {
printf("create_contentfilteredtopic error\n");
subscriber_shutdown(participant);
return -1;
}
}
/* Create a data reader listener */
reader_listener = new cftListener();
/* Here we create the reader either using a Content Filtered Topic or
* a normal topic */
if (sel_cft) {
printf("Using ContentFiltered Topic\n");
reader = subscriber->create_datareader(
cft, DDS_DATAREADER_QOS_DEFAULT, reader_listener,
DDS_STATUS_MASK_ALL);
} else {
printf("Using Normal Topic\n");
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 set the reliability and history 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 calls 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.reliability.kind = DDS_RELIABLE_RELIABILITY_QOS;
datareader_qos.durability.kind = DDS_TRANSIENT_LOCAL_DURABILITY_QOS;
datareader_qos.history.kind = DDS_KEEP_LAST_HISTORY_QOS;
datareader_qos.history.depth = 20;
if (sel_cft) {
printf("Using ContentFiltered Topic\n");
reader = subscriber->create_datareader(
cft, datareader_qos, reader_listener,
DDS_STATUS_MASK_ALL);
} else {
printf("Using Normal Topic\n");
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;
}
*/
/* Change the filter */
if (sel_cft) {
printf(">>> Now setting a new filter: name MATCH \"EVEN\"\n");
retcode = cft->append_to_expression_parameter(0,"EVEN");
if (retcode != DDS_RETCODE_OK) {
printf("append_to_expression_parameter error\n");
subscriber_shutdown(participant);
return -1;
}
}
/* Main loop */
for (count=0; (sample_count == 0) || (count < sample_count); ++count) {
NDDSUtility::sleep(receive_period);
if (sel_cft == 0) {
continue;
}
if (count == 10) {
printf("\n===========================\n");
printf("Changing filter parameters\n");
printf("Append 'ODD' filter\n");
printf("===========================\n");
retcode = cft->append_to_expression_parameter(0,"ODD");
if (retcode != DDS_RETCODE_OK) {
printf("append_to_expression_parameter error\n");
subscriber_shutdown(participant);
return -1;
}
} else if (count == 20) {
printf("\n===========================\n");
printf("Changing filter parameters\n");
printf("Removing 'EVEN' filter \n");
printf("===========================\n");
retcode = cft->remove_from_expression_parameter(0,"EVEN");
if (retcode != DDS_RETCODE_OK) {
printf("append_to_expression_parameter error\n");
subscriber_shutdown(participant);
return -1;
}
}
}
/* 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 */
int sel_cft = 1;
if (argc >= 2) {
domainId = atoi(argv[1]);
}
if (argc >= 3) {
sample_count = atoi(argv[2]);
}
if (argc >= 4) {
sel_cft = atoi(argv[3]);
}
/* 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, sel_cft);
}
#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/content_filtered_topic_string_filter/c/cft_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.
******************************************************************************/
/* cft_publisher.c
A publication of data of type cft
This file is derived from code automatically generated by the rtiddsgen
command:
rtiddsgen -language C -example <arch> cft.idl
Example publication of type cft 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>/cft_subscriber <domain_id> <sample_count>
(3) Start the publication with the command
objs/<arch>/cft_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>/cft_publisher <domain_id>
objs/<arch>/cft_subscriber <domain_id>
On Windows:
objs\<arch>\cft_publisher <domain_id>
objs\<arch>\cft_subscriber <domain_id>
modification history
------------ -------
*/
#include <stdio.h>
#include <stdlib.h>
#include "ndds/ndds_c.h"
#include "cft.h"
#include "cftSupport.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;
cftDataWriter *cft_writer = NULL;
cft *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};
char* even_string = DDS_String_dup("EVEN");
char* odd_string = DDS_String_dup("ODD");
/* We need this structure in case we want to change the datawriter_qos
* programmatically.*/
struct DDS_DataWriterQos datawriter_qos = DDS_DataWriterQos_INITIALIZER;
/* To customize participant QoS, use
the configuration file USER_QOS_PROFILES.xml */
participant = DDS_DomainParticipantFactory_create_participant(
DDS_TheParticipantFactory, domainId, &DDS_PARTICIPANT_QOS_DEFAULT,
NULL /* listener */, DDS_STATUS_MASK_NONE);
if (participant == NULL) {
printf("create_participant error\n");
publisher_shutdown(participant);
return -1;
}
/* To customize publisher QoS, use
the configuration file USER_QOS_PROFILES.xml */
publisher = DDS_DomainParticipant_create_publisher(
participant, &DDS_PUBLISHER_QOS_DEFAULT, NULL /* listener */,
DDS_STATUS_MASK_NONE);
if (publisher == NULL) {
printf("create_publisher error\n");
publisher_shutdown(participant);
return -1;
}
/* Register type before creating topic */
type_name = cftTypeSupport_get_type_name();
retcode = cftTypeSupport_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 cft",
type_name, &DDS_TOPIC_QOS_DEFAULT, NULL /* listener */,
DDS_STATUS_MASK_NONE);
if (topic == NULL) {
printf("create_topic error\n");
publisher_shutdown(participant);
return -1;
}
/* To customize data writer QoS, use
the configuration file USER_QOS_PROFILES.xml */
writer = DDS_Publisher_create_datawriter(
publisher, topic,
&DDS_DATAWRITER_QOS_DEFAULT, NULL /* listener */, DDS_STATUS_MASK_NONE);
if (writer == NULL) {
printf("create_datawriter error\n");
publisher_shutdown(participant);
return -1;
}
/* If you want to set the reliability and history QoS settings
* programmatically rather than using the XML, you will need to add
* the following lines to your code and comment out the create_datawriter
* call above.
*/
/*
retcode = DDS_Publisher_get_default_datawriter_qos(publisher,
&datawriter_qos);
if (retcode != DDS_RETCODE_OK) {
printf("get_default_datawriter_qos error\n");
return -1;
}
datawriter_qos.reliability.kind = DDS_RELIABLE_RELIABILITY_QOS;
datawriter_qos.durability.kind = DDS_TRANSIENT_LOCAL_DURABILITY_QOS;
datawriter_qos.history.kind = DDS_KEEP_LAST_HISTORY_QOS;
datawriter_qos.history.depth = 20;
writer = DDS_Publisher_create_datawriter(
publisher, topic,
&datawriter_qos, NULL, DDS_STATUS_MASK_NONE);
if (writer == NULL) {
printf("create_datawriter error\n");
publisher_shutdown(participant);
return -1;
}
*/
cft_writer = cftDataWriter_narrow(writer);
if (cft_writer == NULL) {
printf("DataWriter narrow error\n");
publisher_shutdown(participant);
return -1;
}
/* Create data sample for writing */
instance = cftTypeSupport_create_data_ex(DDS_BOOLEAN_TRUE);
if (instance == NULL) {
printf("cftTypeSupport_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 = cftDataWriter_register_instance(
cft_writer, instance);
*/
/* Main loop */
for (count=0; (sample_count == 0) || (count < sample_count); ++count) {
printf("Writing cft, count %d\n", count);
/* Modify the data to be written here */
if(count%2 == 1){
instance->name = odd_string;
} else {
instance->name = even_string;
}
instance->count = count;
/* Write data */
retcode = cftDataWriter_write(
cft_writer, instance, &instance_handle);
if (retcode != DDS_RETCODE_OK) {
printf("write error %d\n", retcode);
}
NDDS_Utility_sleep(&send_period);
}
/*
retcode = cftDataWriter_unregister_instance(
cft_writer, instance, &instance_handle);
if (retcode != DDS_RETCODE_OK) {
printf("unregister instance error %d\n", retcode);
}
*/
/* Delete data sample */
retcode = cftTypeSupport_delete_data_ex(instance, DDS_BOOLEAN_TRUE);
if (retcode != DDS_RETCODE_OK) {
printf("cftTypeSupport_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/content_filtered_topic_string_filter/c/cft_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.
******************************************************************************/
/* cft_subscriber.c
A subscription example
This file is derived from code automatically generated by the rtiddsgen
command:
rtiddsgen -language C -example <arch> cft.idl
Example subscription of type cft 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>/cft_subscriber <domain_id> <sample_count>
(3) Start the publication with the command
objs/<arch>/cft_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>/cft_publisher <domain_id>
objs/<arch>/cft_subscriber <domain_id>
On Windows systems:
objs\<arch>\cft_publisher <domain_id>
objs\<arch>\cft_subscriber <domain_id>
modification history
------------ -------
*/
#include <stdio.h>
#include <stdlib.h>
#include "ndds/ndds_c.h"
#include "cft.h"
#include "cftSupport.h"
void cftListener_on_requested_deadline_missed(
void* listener_data,
DDS_DataReader* reader,
const struct DDS_RequestedDeadlineMissedStatus *status)
{
}
void cftListener_on_requested_incompatible_qos(
void* listener_data,
DDS_DataReader* reader,
const struct DDS_RequestedIncompatibleQosStatus *status)
{
}
void cftListener_on_sample_rejected(
void* listener_data,
DDS_DataReader* reader,
const struct DDS_SampleRejectedStatus *status)
{
}
void cftListener_on_liveliness_changed(
void* listener_data,
DDS_DataReader* reader,
const struct DDS_LivelinessChangedStatus *status)
{
}
void cftListener_on_sample_lost(
void* listener_data,
DDS_DataReader* reader,
const struct DDS_SampleLostStatus *status)
{
}
void cftListener_on_subscription_matched(
void* listener_data,
DDS_DataReader* reader,
const struct DDS_SubscriptionMatchedStatus *status)
{
}
void cftListener_on_data_available(
void* listener_data,
DDS_DataReader* reader)
{
cftDataReader *cft_reader = NULL;
struct cftSeq data_seq = DDS_SEQUENCE_INITIALIZER;
struct DDS_SampleInfoSeq info_seq = DDS_SEQUENCE_INITIALIZER;
DDS_ReturnCode_t retcode;
int i;
cft_reader = cftDataReader_narrow(reader);
if (cft_reader == NULL) {
printf("DataReader narrow error\n");
return;
}
retcode = cftDataReader_take(
cft_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 < cftSeq_get_length(&data_seq); ++i) {
if (DDS_SampleInfoSeq_get_reference(&info_seq, i)->valid_data) {
cftTypeSupport_print_data(
cftSeq_get_reference(&data_seq, i));
}
}
retcode = cftDataReader_return_loan(
cft_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, int sel_cft)
{
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};
DDS_ContentFilteredTopic *cft = NULL;
/* If you want to modify datareader_qos programatically you
* will need to use the following structure. */
struct DDS_DataReaderQos datareader_qos = DDS_DataReaderQos_INITIALIZER;
/* For this filter we only allow 1 parameter*/
struct DDS_StringSeq parameters;
const char* param_list[] = {"SOME_STRING"};
/* To customize participant QoS, use
the configuration file USER_QOS_PROFILES.xml */
participant = DDS_DomainParticipantFactory_create_participant(
DDS_TheParticipantFactory, domainId, &DDS_PARTICIPANT_QOS_DEFAULT,
NULL /* listener */, DDS_STATUS_MASK_NONE);
if (participant == NULL) {
printf("create_participant error\n");
subscriber_shutdown(participant);
return -1;
}
/* To customize subscriber QoS, use
the configuration file USER_QOS_PROFILES.xml */
subscriber = DDS_DomainParticipant_create_subscriber(
participant, &DDS_SUBSCRIBER_QOS_DEFAULT, NULL /* listener */,
DDS_STATUS_MASK_NONE);
if (subscriber == NULL) {
printf("create_subscriber error\n");
subscriber_shutdown(participant);
return -1;
}
/* Register the type before creating the topic */
type_name = cftTypeSupport_get_type_name();
retcode = cftTypeSupport_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 cft",
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;
}
DDS_StringSeq_initialize(¶meters);
DDS_StringSeq_set_maximum(¶meters, 1);
/* Here we set the default filter using the param_list */
DDS_StringSeq_from_array(¶meters, param_list, 1);
if (sel_cft) {
/* create_contentfilteredtopic_with_filter */
cft = DDS_DomainParticipant_create_contentfilteredtopic_with_filter(
participant,"ContentFilteredTopic", topic, "name MATCH %0",
¶meters, DDS_STRINGMATCHFILTER_NAME);
if (cft == NULL) {
printf("create_contentfilteredtopic error\n");
subscriber_shutdown(participant);
return -1;
}
}
/* Set up a data reader listener */
reader_listener.on_requested_deadline_missed =
cftListener_on_requested_deadline_missed;
reader_listener.on_requested_incompatible_qos =
cftListener_on_requested_incompatible_qos;
reader_listener.on_sample_rejected =
cftListener_on_sample_rejected;
reader_listener.on_liveliness_changed =
cftListener_on_liveliness_changed;
reader_listener.on_sample_lost =
cftListener_on_sample_lost;
reader_listener.on_subscription_matched =
cftListener_on_subscription_matched;
reader_listener.on_data_available =
cftListener_on_data_available;
/* To customize data reader QoS, use
the configuration file USER_QOS_PROFILES.xml */
if (sel_cft) {
printf("Using ContentFiltered Topic\n");
reader = DDS_Subscriber_create_datareader(
subscriber, DDS_ContentFilteredTopic_as_topicdescription(cft),
&DDS_DATAREADER_QOS_DEFAULT, &reader_listener, DDS_STATUS_MASK_ALL);
} else {
printf("Using Normal Topic\n");
reader = DDS_Subscriber_create_datareader(
subscriber, DDS_Topic_as_topicdescription(topic),
&DDS_DATAREADER_QOS_DEFAULT, &reader_listener, DDS_STATUS_MASK_ALL);
}
if (reader == NULL) {
printf("create_datareader error\n");
subscriber_shutdown(participant);
return -1;
}
/* If you want to set the reliability and history 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
* calls 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.reliability.kind = DDS_RELIABLE_RELIABILITY_QOS;
datareader_qos.durability.kind = DDS_TRANSIENT_LOCAL_DURABILITY_QOS;
datareader_qos.history.kind = DDS_KEEP_LAST_HISTORY_QOS;
datareader_qos.history.depth = 20;
if (sel_cft) {
printf("Using ContentFiltered Topic\n");
reader = DDS_Subscriber_create_datareader(
subscriber, DDS_ContentFilteredTopic_as_topicdescription(cft),
&datareader_qos, &reader_listener, DDS_STATUS_MASK_ALL);
} else {
printf("Using Normal Topic\n");
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;
}
*/
/* Change the filter */
if (sel_cft) {
printf(">>> Now setting a new filter: name MATCH \"EVEN\"\n");
retcode = DDS_ContentFilteredTopic_append_to_expression_parameter(
cft, 0,"EVEN");
if (retcode != DDS_RETCODE_OK) {
printf("append_to_expression_parameter error\n");
subscriber_shutdown(participant);
return -1;
}
}
/* Main loop */
for (count=0; (sample_count == 0) || (count < sample_count); ++count) {
NDDS_Utility_sleep(&poll_period);
if (sel_cft == 0) {
continue;
}
if (count == 10) {
printf("\n===========================\n");
printf("Changing filter parameters\n");
printf("Append 'ODD' filter\n");
printf("===========================\n");
retcode = DDS_ContentFilteredTopic_append_to_expression_parameter(
cft, 0,"ODD");
if (retcode != DDS_RETCODE_OK) {
printf("append_to_expression_parameter error\n");
subscriber_shutdown(participant);
return -1;
}
} else if (count == 20) {
printf("\n===========================\n");
printf("Changing filter parameters\n");
printf("Removing 'EVEN' filter \n");
printf("===========================\n");
retcode = DDS_ContentFilteredTopic_remove_from_expression_parameter(
cft, 0,"EVEN");
if (retcode != DDS_RETCODE_OK) {
printf("append_to_expression_parameter error\n");
subscriber_shutdown(participant);
return -1;
}
}
}
/* 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 */
int sel_cft = 1;
if (argc >= 2) {
domainId = atoi(argv[1]);
}
if (argc >= 3) {
sample_count = atoi(argv[2]);
}
if (argc >= 4) {
sel_cft = atoi(argv[3]);
}
/* 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, sel_cft);
}
#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/content_filtered_topic_string_filter/c++03/cft_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 "cft.hpp"
using namespace dds::core;
using namespace dds::core::policy;
using namespace dds::domain;
using namespace dds::topic;
using namespace dds::pub;
using namespace dds::pub::qos;
void publisher_main(int domain_id, int sample_count)
{
// Create a DomainParticipant with default Qos
DomainParticipant participant (domain_id);
// Create a Topic -- and automatically register the type
Topic<cft> topic (participant, "Example cft");
// 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()
// << Durability::TransientLocal()
// << History::KeepLast(20);
// Create a DataWriter with default Qos (Publisher created in-line)
DataWriter<cft> writer(Publisher(participant), topic, writer_qos);
cft sample;
for (int count = 0; count < sample_count || sample_count == 0; count++) {
std::cout << "Writing cft, count " << count << std::endl;
// Modify sample data
sample.count(count);
if (count % 2 == 1) {
sample.name("ODD");
} else {
sample.name("EVEN");
}
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/content_filtered_topic_string_filter/c++03/cft_subscriber.cxx | /*******************************************************************************
(c) 2005-2015 Copyright, Real-Time Innovations, Inc. All rights reserved.
RTI grants Licensee a license to use, modify, compile, and create derivative
works of the Software. Licensee has the right to distribute object form only
for use with RTI products. The Software is provided "as is", with no warranty
of any type, including any warranty for fitness for any purpose. RTI is under
no obligation to maintain or support the Software. RTI shall not be liable for
any incidental or consequential damages arising out of the use or inability to
use the software.
******************************************************************************/
#include <cstdlib>
#include <algorithm>
#include <iostream>
#include <dds/dds.hpp>
#include <rti/core/ListenerBinder.hpp>
#include "cft.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 rti::core;
class cftReaderListener : public NoOpDataReaderListener<cft> {
public:
void on_data_available(dds::sub::DataReader<cft>& reader)
{
// Take all samples
LoanedSamples<cft> samples = reader.take();
for (LoanedSamples<cft>::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 is_cft)
{
// Create a DomainParticipant with default Qos
DomainParticipant participant(domain_id);
// Create a Topic -- and automatically register the type
Topic<cft> topic(participant, "Example cft");
// Define the default parameter of the filter.
std::vector<std::string> parameters(1);
parameters[0] = "SOME_STRING";
// Retrieve the default DataReader QoS, from USER_QOS_PROFILES.xml
DataReaderQos reader_qos = QosProvider::Default().datareader_qos();
// If you want to change the DataReader's QoS programmatically rather than
// using the XML file, uncomment the following lines.
// reader_qos << Reliability::Reliable()
// << Durability::TransientLocal()
// << History::KeepLast(20);
// Create the ContentFilteredTopic and DataReader.
ContentFilteredTopic<cft> cft_topic = dds::core::null;
DataReader<cft> reader = dds::core::null;
if (is_cft) {
std::cout << "Using ContentFiltered Topic" << std::endl;
Filter filter("name MATCH %0", parameters);
// If there is no filter name, the regular SQL filter will be used.
filter->name(rti::topic::stringmatch_filter_name());
cft_topic = ContentFilteredTopic<cft>(
topic,
"ContentFilteredTopic",
filter);
reader = DataReader<cft>(Subscriber(participant), cft_topic,reader_qos);
} else {
std::cout << "Using Normal Topic" << std::endl;
reader = DataReader<cft>(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.
ListenerBinder< DataReader<cft> > scoped_listener =
bind_and_manage_listener(
reader,
new cftReaderListener,
StatusMask::data_available());
// Change the filter
if (is_cft) {
std::cout << "Now setting a new filter: 'name MATCH \"EVEN\"'"
<< std::endl;
cft_topic->append_to_expression_parameter(0, "EVEN");
}
// Main loop
for (int count = 0; (sample_count == 0) || (count < sample_count); count++){
rti::util::sleep(dds::core::Duration(1));
if (!is_cft) {
continue;
}
if (count == 10) {
std::cout << std::endl << "===========================" << std::endl
<< "Changing filter parameters" << std::endl
<< "Append 'ODD' filter" << std::endl
<< "===========================" << std::endl;
cft_topic->append_to_expression_parameter(0, "ODD");
} else if (count == 20) {
std::cout << std::endl << "===========================" << std::endl
<< "Changing filter parameters" << std::endl
<< "Removing 'EVEN' filter" << std::endl
<< "===========================" << std::endl;
cft_topic->remove_from_expression_parameter(0, "EVEN");
}
}
}
int main(int argc, char *argv[])
{
int domain_id = 0;
int sample_count = 0; // Infinite loop
bool is_cft = true;
if (argc >= 2) {
domain_id = atoi(argv[1]);
}
if (argc >= 3) {
sample_count = atoi(argv[2]);
}
if (argc >= 4) {
is_cft = (argv[3][0] == '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, is_cft);
} 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/batching/c++/batch_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.
******************************************************************************/
/* batch_data_subscriber.cxx
A subscription example
This file is derived from code automatically generated by the rtiddsgen
command:
rtiddsgen -language C++ -example <arch> batch_data.idl
Example subscription of type batch_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>/batch_data_subscriber <domain_id> <sample_count>
(3) Start the publication with the command
objs/<arch>/batch_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>/batch_data_publisher <domain_id>
objs/<arch>/batch_data_subscriber <domain_id>
On Windows:
objs\<arch>\batch_data_publisher <domain_id>
objs\<arch>\batch_data_subscriber <domain_id>
*/
#include <stdio.h>
#include <stdlib.h>
#ifdef RTI_VX653
#include <vThreadsData.h>
#endif
#include "batch_data.h"
#include "batch_dataSupport.h"
#include "ndds/ndds_cpp.h"
class batch_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 batch_dataListener::on_data_available(DDSDataReader* reader)
{
batch_dataDataReader *batch_data_reader = NULL;
batch_dataSeq data_seq;
DDS_SampleInfoSeq info_seq;
DDS_ReturnCode_t retcode;
int i;
batch_data_reader = batch_dataDataReader::narrow(reader);
if (batch_data_reader == NULL) {
printf("DataReader narrow error\n");
return;
}
retcode = batch_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) {
batch_dataTypeSupport::print_data(&data_seq[i]);
}
}
retcode = batch_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,
int turbo_mode_on) {
DDSDomainParticipant *participant = NULL;
DDSSubscriber *subscriber = NULL;
DDSTopic *topic = NULL;
batch_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;
const char *profile_name = NULL;
const char *library_name = DDS_String_dup("batching_Library");
/* We pick the profile name if the turbo_mode is selected or not.
* If Turbo_mode is not selected, the batching profile will be used.
*/
if (turbo_mode_on) {
profile_name = DDS_String_dup("turbo_mode_profile");
printf("Turbo Mode enable\n");
} else {
profile_name = DDS_String_dup("batch_profile");
printf("Manual batching enable\n");
}
/* To customize the participant QoS, use
the configuration file USER_QOS_PROFILES.xml */
participant = DDSTheParticipantFactory->create_participant_with_profile(
domainId, library_name, profile_name,
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_with_profile(
library_name, profile_name, 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 = batch_dataTypeSupport::get_type_name();
retcode = batch_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 batch_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;
}
/* Create a data reader listener */
reader_listener = new batch_dataListener();
/* To customize the data reader QoS, use
the configuration file USER_QOS_PROFILES.xml */
reader = subscriber->create_datareader_with_profile(
topic, library_name, profile_name, 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("batch_data 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 */
int turbo_mode_on = 0;
if (argc >= 2) {
domainId = _wtoi(argv[1]);
}
if (argc >= 3) {
turbo_mode_on = _wtoi(argv[2]);
}
if (argc >= 4) {
sample_count = _wtoi(argv[3]);
}
/* 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 */
int turbo_mode_on = 0;
if (argc >= 2) {
domainId = atoi(argv[1]);
}
if (argc >= 3) {
turbo_mode_on = atoi(argv[2]);
}
if (argc >= 4) {
sample_count = atoi(argv[3]);
}
/* 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, turbo_mode_on);
}
#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/batching/c++/batch_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.
******************************************************************************/
/* batch_data_publisher.cxx
A publication of data of type batch_data
This file is derived from code automatically generated by the rtiddsgen
command:
rtiddsgen -language C++ -example <arch> batch_data.idl
Example publication of type batch_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>/batch_data_subscriber <domain_id> <sample_count>
(3) Start the publication with the command
objs/<arch>/batch_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>/batch_data_publisher <domain_id>
objs/<arch>/batch_data_subscriber <domain_id>
On Windows:
objs\<arch>\batch_data_publisher <domain_id>
objs\<arch>\batch_data_subscriber <domain_id>
*/
#include <stdio.h>
#include <stdlib.h>
#ifdef RTI_VX653
#include <vThreadsData.h>
#endif
#include "batch_data.h"
#include "batch_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, int turbo_mode_on)
{
DDSDomainParticipant *participant = NULL;
DDSPublisher *publisher = NULL;
DDSTopic *topic = NULL;
DDSDataWriter *writer = NULL;
batch_dataDataWriter * batch_data_writer = NULL;
batch_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 = {1,0};
const char *profile_name = NULL;
const char *library_name = DDS_String_dup("batching_Library");
/* We pick the profile name if the turbo_mode is selected or not.
* If Turbo_mode is not selected, the batching profile will be used.
*/
if (turbo_mode_on) {
profile_name = DDS_String_dup("turbo_mode_profile");
/* In turbo_mode, we do not want to wait to send samples */
send_period.sec = 0;
printf("Turbo Mode enable\n");
} else {
profile_name = DDS_String_dup("batch_profile");
printf("Manual batching enable\n");
}
/* To customize participant QoS, use
the configuration file USER_QOS_PROFILES.xml */
participant = DDSTheParticipantFactory->create_participant_with_profile(
domainId, library_name, profile_name,
NULL /* listener */, DDS_STATUS_MASK_NONE);
if (participant == NULL) {
printf("create_participant error\n");
publisher_shutdown(participant);
return -1;
}
/* To customize publisher QoS, use
the configuration file USER_QOS_PROFILES.xml */
publisher = participant->create_publisher_with_profile(
library_name, profile_name, 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 = batch_dataTypeSupport::get_type_name();
retcode = batch_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 batch_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;
}
/* To customize data writer QoS, use
the configuration file USER_QOS_PROFILES.xml */
writer = publisher->create_datawriter_with_profile(
topic, library_name, profile_name, NULL /* listener */,
DDS_STATUS_MASK_NONE);
if (writer == NULL) {
printf("create_datawriter error\n");
publisher_shutdown(participant);
return -1;
}
batch_data_writer = batch_dataDataWriter::narrow(writer);
if (batch_data_writer == NULL) {
printf("DataWriter narrow error\n");
publisher_shutdown(participant);
return -1;
}
/* Create data sample for writing */
instance = batch_dataTypeSupport::create_data();
if (instance == NULL) {
printf("batch_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 = batch_data_writer->register_instance(*instance);
*/
/* Main loop */
for (count=0; (sample_count == 0) || (count < sample_count); ++count) {
printf("Writing batch_data, count %d\n", count);
/* Modify the data to be sent here */
instance->x = count;
retcode = batch_data_writer->write(*instance, instance_handle);
if (retcode != DDS_RETCODE_OK) {
printf("write error %d\n", retcode);
}
NDDSUtility::sleep(send_period);
}
/*
retcode = batch_data_writer->unregister_instance(
*instance, instance_handle);
if (retcode != DDS_RETCODE_OK) {
printf("unregister instance error %d\n", retcode);
}
*/
/* Delete data sample */
retcode = batch_dataTypeSupport::delete_data(instance);
if (retcode != DDS_RETCODE_OK) {
printf("batch_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 */
int turbo_mode_on = 0;
if (argc >= 2) {
domainId = _wtoi(argv[1]);
}
if (argc >= 3) {
turbo_mode_on = _wtoi(argv[2]);
}
if (argc >= 4) {
sample_count = _wtoi(argv[3]);
}
/* 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, turbo_mode_on);
}
#elif !(defined(RTI_VXWORKS) && !defined(__RTP__)) && !defined(RTI_PSOS)
int main(int argc, char *argv[])
{
int domainId = 0;
int sample_count = 0; /* infinite loop */
int turbo_mode_on = 0;
if (argc >= 2) {
domainId = atoi(argv[1]);
}
if (argc >= 3) {
turbo_mode_on = atoi(argv[2]);
}
if (argc >= 4) {
sample_count = atoi(argv[3]);
}
/* 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, turbo_mode_on);
}
#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/batching/c/batch_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.
******************************************************************************/
/* batch_data_subscriber.c
A subscription example
This file is derived from code automatically generated by the rtiddsgen
command:
rtiddsgen -language C -example <arch> batch_data.idl
Example subscription of type batch_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>/batch_data_subscriber <domain_id> <sample_count>
(3) Start the publication with the command
objs/<arch>/batch_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>/batch_data_publisher <domain_id>
objs/<arch>/batch_data_subscriber <domain_id>
On Windows systems:
objs\<arch>\batch_data_publisher <domain_id>
objs\<arch>\batch_data_subscriber <domain_id>
modification history
------------ -------
*/
#include <stdio.h>
#include <stdlib.h>
#include "ndds/ndds_c.h"
#include "batch_data.h"
#include "batch_dataSupport.h"
void batch_dataListener_on_requested_deadline_missed(
void* listener_data,
DDS_DataReader* reader,
const struct DDS_RequestedDeadlineMissedStatus *status)
{
}
void batch_dataListener_on_requested_incompatible_qos(
void* listener_data,
DDS_DataReader* reader,
const struct DDS_RequestedIncompatibleQosStatus *status)
{
}
void batch_dataListener_on_sample_rejected(
void* listener_data,
DDS_DataReader* reader,
const struct DDS_SampleRejectedStatus *status)
{
}
void batch_dataListener_on_liveliness_changed(
void* listener_data,
DDS_DataReader* reader,
const struct DDS_LivelinessChangedStatus *status)
{
}
void batch_dataListener_on_sample_lost(
void* listener_data,
DDS_DataReader* reader,
const struct DDS_SampleLostStatus *status)
{
}
void batch_dataListener_on_subscription_matched(
void* listener_data,
DDS_DataReader* reader,
const struct DDS_SubscriptionMatchedStatus *status)
{
}
void batch_dataListener_on_data_available(
void* listener_data,
DDS_DataReader* reader)
{
batch_dataDataReader *batch_data_reader = NULL;
struct batch_dataSeq data_seq = DDS_SEQUENCE_INITIALIZER;
struct DDS_SampleInfoSeq info_seq = DDS_SEQUENCE_INITIALIZER;
DDS_ReturnCode_t retcode;
int i;
batch_data_reader = batch_dataDataReader_narrow(reader);
if (batch_data_reader == NULL) {
printf("DataReader narrow error\n");
return;
}
retcode = batch_dataDataReader_take(
batch_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 < batch_dataSeq_get_length(&data_seq); ++i) {
if (DDS_SampleInfoSeq_get_reference(&info_seq, i)->valid_data) {
batch_dataTypeSupport_print_data(
batch_dataSeq_get_reference(&data_seq, i));
}
}
retcode = batch_dataDataReader_return_loan(
batch_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,
int turbo_mode_on) {
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};
const char *profile_name = NULL;
const char *library_name = DDS_String_dup("batching_Library");
/* We pick the profile name if the turbo_mode is selected or not.
* If Turbo_mode is not selected, the batching profile will be used.
*/
if (turbo_mode_on) {
profile_name = DDS_String_dup("turbo_mode_profile");
printf("Turbo Mode enable\n");
} else {
profile_name = DDS_String_dup("batch_profile");
printf("Manual batching enable\n");
}
/* To customize participant QoS, use
the configuration file USER_QOS_PROFILES.xml */
participant = DDS_DomainParticipantFactory_create_participant_with_profile(
DDS_TheParticipantFactory, domainId, library_name, profile_name,
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_with_profile(
participant, library_name, profile_name, 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 = batch_dataTypeSupport_get_type_name();
retcode = batch_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 batch_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;
}
/* Set up a data reader listener */
reader_listener.on_requested_deadline_missed =
batch_dataListener_on_requested_deadline_missed;
reader_listener.on_requested_incompatible_qos =
batch_dataListener_on_requested_incompatible_qos;
reader_listener.on_sample_rejected =
batch_dataListener_on_sample_rejected;
reader_listener.on_liveliness_changed =
batch_dataListener_on_liveliness_changed;
reader_listener.on_sample_lost =
batch_dataListener_on_sample_lost;
reader_listener.on_subscription_matched =
batch_dataListener_on_subscription_matched;
reader_listener.on_data_available =
batch_dataListener_on_data_available;
/* To customize data reader QoS, use
the configuration file USER_QOS_PROFILES.xml */
reader = DDS_Subscriber_create_datareader_with_profile(
subscriber, DDS_Topic_as_topicdescription(topic),
library_name, profile_name, &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("batch_data 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 */
int turbo_mode_on = 0;
if (argc >= 2) {
domainId = _wtoi(argv[1]);
}
if (argc >= 3) {
turbo_mode_on = _wtoi(argv[2]);
}
if (argc >= 4) {
sample_count = _wtoi(argv[3]);
}
/* 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, turbo_mode_on);
}
#elif !(defined(RTI_VXWORKS) && !defined(__RTP__)) && !defined(RTI_PSOS)
int main(int argc, char *argv[])
{
int domainId = 0;
int sample_count = 0; /* infinite loop */
int turbo_mode_on = 0;
if (argc >= 2) {
domainId = atoi(argv[1]);
}
if (argc >= 3) {
turbo_mode_on = atoi(argv[2]);
}
if (argc >= 4) {
sample_count = atoi(argv[3]);
}
/* 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, turbo_mode_on);
}
#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/batching/c/batch_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.
******************************************************************************/
/* batch_data_publisher.c
A publication of data of type batch_data
This file is derived from code automatically generated by the rtiddsgen
command:
rtiddsgen -language C -example <arch> batch_data.idl
Example publication of type batch_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>/batch_data_subscriber <domain_id> <sample_count>
(3) Start the publication with the command
objs/<arch>/batch_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>/batch_data_publisher <domain_id>
objs/<arch>/batch_data_subscriber <domain_id>
On Windows:
objs\<arch>\batch_data_publisher <domain_id>
objs\<arch>\batch_data_subscriber <domain_id>
modification history
------------ -------
*/
#include <stdio.h>
#include <stdlib.h>
#include "ndds/ndds_c.h"
#include "batch_data.h"
#include "batch_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, int turbo_mode_on)
{
DDS_DomainParticipant *participant = NULL;
DDS_Publisher *publisher = NULL;
DDS_Topic *topic = NULL;
DDS_DataWriter *writer = NULL;
batch_dataDataWriter *batch_data_writer = NULL;
batch_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_Duration_t send_period = {1,0};
const char *profile_name = NULL;
const char *library_name = DDS_String_dup("batching_Library");
/* We pick the profile name if the turbo_mode is selected or not.
* If Turbo_mode is not selected, the batching profile will be used.
*/
if (turbo_mode_on) {
profile_name = DDS_String_dup("turbo_mode_profile");
/* In turbo_mode, we do not want to wait to send samples */
send_period.sec = 0;
printf("Turbo Mode enable\n");
} else {
profile_name = DDS_String_dup("batch_profile");
printf("Manual batching enable\n");
}
/* To customize participant QoS, use
the configuration file USER_QOS_PROFILES.xml */
participant = DDS_DomainParticipantFactory_create_participant_with_profile(
DDS_TheParticipantFactory, domainId, library_name, profile_name,
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_with_profile(
participant, library_name, profile_name, 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 = batch_dataTypeSupport_get_type_name();
retcode = batch_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 batch_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;
}
/* To customize data writer QoS, use
the configuration file USER_QOS_PROFILES.xml */
writer = DDS_Publisher_create_datawriter_with_profile(
publisher, topic,
library_name, profile_name, NULL /* listener */, DDS_STATUS_MASK_NONE);
if (writer == NULL) {
printf("create_datawriter error\n");
publisher_shutdown(participant);
return -1;
}
batch_data_writer = batch_dataDataWriter_narrow(writer);
if (batch_data_writer == NULL) {
printf("DataWriter narrow error\n");
publisher_shutdown(participant);
return -1;
}
/* Create data sample for writing */
instance = batch_dataTypeSupport_create_data_ex(DDS_BOOLEAN_TRUE);
if (instance == NULL) {
printf("batch_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 = batch_dataDataWriter_register_instance(
batch_data_writer, instance);
*/
/* Main loop */
for (count=0; (sample_count == 0) || (count < sample_count); ++count) {
printf("Writing batch_data, count %d\n", count);
/* Modify the data to be written here */
instance->x = count;
/* Write data */
retcode = batch_dataDataWriter_write(
batch_data_writer, instance, &instance_handle);
if (retcode != DDS_RETCODE_OK) {
printf("write error %d\n", retcode);
}
NDDS_Utility_sleep(&send_period);
}
/*
retcode = batch_dataDataWriter_unregister_instance(
batch_data_writer, instance, &instance_handle);
if (retcode != DDS_RETCODE_OK) {
printf("unregister instance error %d\n", retcode);
}
*/
/* Delete data sample */
retcode = batch_dataTypeSupport_delete_data_ex(instance, DDS_BOOLEAN_TRUE);
if (retcode != DDS_RETCODE_OK) {
printf("batch_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 */
int turbo_mode_on = 0;
if (argc >= 2) {
domainId = _wtoi(argv[1]);
}
if (argc >= 3) {
turbo_mode_on = _wtoi(argv[2]);
}
if (argc >= 4) {
sample_count = _wtoi(argv[3]);
}
/* 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, turbo_mode_on);
}
#elif !(defined(RTI_VXWORKS) && !defined(__RTP__)) && !defined(RTI_PSOS)
int main(int argc, char *argv[])
{
int domainId = 0;
int sample_count = 0; /* infinite loop */
int turbo_mode_on = 0;
if (argc >= 2) {
domainId = atoi(argv[1]);
}
if (argc >= 3) {
turbo_mode_on = atoi(argv[2]);
}
if (argc >= 4) {
sample_count = atoi(argv[3]);
}
/* 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, turbo_mode_on);
}
#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/batching/c++03/batch_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 <string>
#include "batch_data.hpp"
#include <dds/dds.hpp>
#include <rti/core/ListenerBinder.hpp>
using namespace dds::core;
using namespace dds::core::policy;
using namespace dds::core::status;
using namespace dds::domain;
using namespace dds::topic;
using namespace dds::sub;
using namespace dds::sub::qos;
class BatchDataReaderListener : public NoOpDataReaderListener<batch_data> {
public:
void on_data_available(DataReader<batch_data>& reader)
{
// Take all samples
LoanedSamples<batch_data> samples = reader.take();
for (LoanedSamples<batch_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, bool turbo_mode_on)
{
// We pick the profile name if the turbo_mode is selected or not.
// If turbo_mode is not selected, the batching profile will be used.
std::string profile_name = "batching_Library::";
if (turbo_mode_on) {
std::cout << "Turbo Mode enable" << std::endl;
profile_name.append("turbo_mode_profile");
} else {
std::cout << "Manual batching enable" << std::endl;
profile_name.append("batch_profile");
}
// To customize entities QoS use the file USER_QOS_PROFILES.xml
DomainParticipant participant (
domain_id,
QosProvider::Default().participant_qos(profile_name));
Topic<batch_data> topic (participant, "Example batch_data");
Subscriber subscriber (
participant,
QosProvider::Default().subscriber_qos(profile_name));
DataReader<batch_data> reader(
subscriber,
topic,
QosProvider::Default().datareader_qos(profile_name));
// Set the listener using a RAII so it's exception-safe
rti::core::ListenerBinder< DataReader<batch_data> > scoped_listener =
rti::core::bind_and_manage_listener(
reader,
new BatchDataReaderListener,
StatusMask::data_available());
// Main loop
for (int count = 0; count < sample_count || sample_count == 0; ++count) {
std::cout << "batch_data subscriber sleeping for 4 sec...\n";
rti::util::sleep(Duration(4));
}
}
int main(int argc, char *argv[])
{
int domain_id = 0;
int sample_count = 0; // Infinite loop
bool turbo_mode_on = false;
if (argc >= 2) {
domain_id = atoi(argv[1]);
}
if (argc >= 3) {
turbo_mode_on = (argv[2][0] == '1');
}
if (argc >= 4) {
sample_count = atoi(argv[3]);
}
// 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, turbo_mode_on);
} catch (const std::exception& ex) {
// This will catch DDS exceptions
std::cerr << "Exception in subscriber_main(): " << ex.what() << "\n";
return -1;
}
// RTI Connext provides a finalize_participant_factory() method
// if you want to release memory used by the participant factory singleton.
// dds::domain::DomainParticipant::finalize_participant_factory();
return 0;
}
| cxx |
rticonnextdds-examples | data/projects/rticonnextdds-examples/batching/c++03/batch_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 <string>
#include "batch_data.hpp"
#include <dds/dds.hpp>
using namespace dds::core;
using namespace dds::domain;
using namespace dds::domain::qos;
using namespace dds::topic;
using namespace dds::pub;
void publisher_main(int domain_id, int sample_count, bool turbo_mode_on)
{
// Seconds to wait between samples published.
Duration send_period (1);
// We pick the profile name if the turbo_mode is selected or not.
// If turbo_mode is not selected, the batching profile will be used.
std::string profile_name = "batching_Library::";
if (turbo_mode_on) {
std::cout << "Turbo Mode enable" << std::endl;
profile_name.append("turbo_mode_profile");
// If turbo_mode, we do not want to wait to send samples.
send_period.sec(0);
} else {
std::cout << "Manual batching enable" << std::endl;
profile_name.append("batch_profile");
}
// To customize entities QoS use the file USER_QOS_PROFILES.xml
DomainParticipant participant (
domain_id,
QosProvider::Default().participant_qos(profile_name));
Topic<batch_data> topic (participant, "Example batch_data");
Publisher publisher (
participant,
QosProvider::Default().publisher_qos(profile_name));
DataWriter<batch_data> writer (
publisher,
topic,
QosProvider::Default().datawriter_qos(profile_name));
// Create data sample for writing.
batch_data sample;
// 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.
InstanceHandle instance_handle = InstanceHandle::nil();
//instance_handle = writer.register_instance(sample);
for (int count = 0; count < sample_count || sample_count == 0; count++) {
// Modify the data to be written here
sample.x(count);
std::cout << "Writing batch_data, count " << count << std::endl;
writer.write(sample);
rti::util::sleep(send_period);
}
//writer.unregister_instance(sample);
}
int main(int argc, char *argv[])
{
int domain_id = 0;
int sample_count = 0; // infinite loop
bool turbo_mode_on = false;
if (argc >= 2) {
domain_id = atoi(argv[1]);
}
if (argc >= 3) {
turbo_mode_on = (argv[2][0] == '1');
}
if (argc >= 4) {
sample_count = atoi(argv[3]);
}
// 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, turbo_mode_on);
} 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/ordered_presentation_group/c++/ordered_group_publisher.cxx | /*******************************************************************************
(c) 2005-2014 Copyright, Real-Time Innovations, Inc. All rights reserved.
RTI grants Licensee a license to use, modify, compile, and create derivative
works of the Software. Licensee has the right to distribute object form only
for use with RTI products. The Software is provided "as is", with no warranty
of any type, including any warranty for fitness for any purpose. RTI is under
no obligation to maintain or support the Software. RTI shall not be liable for
any incidental or consequential damages arising out of the use or inability to
use the software.
******************************************************************************/
/* ordered_group_publisher.cxx
A publication of data of type ordered_group
This file is derived from code automatically generated by the rtiddsgen
command:
rtiddsgen -language C++ -example <arch> ordered_group.idl
Example publication of type ordered_group automatically generated by
'rtiddsgen'. To test them follow these steps:
(1) Compile this file and the example subscription.
(2) Start the subscription with the command
objs/<arch>/ordered_group_subscriber <domain_id> <sample_count>
(3) Start the publication with the command
objs/<arch>/ordered_group_publisher <domain_id> <sample_count>
(4) [Optional] Specify the list of discovery initial peers and
multicast receive addresses via an environment variable or a file
(in the current working directory) called NDDS_DISCOVERY_PEERS.
You can run any number of publishers and subscribers programs, and can
add and remove them dynamically from the domain.
Example:
To run the example application on domain <domain_id>:
On Unix:
objs/<arch>/ordered_group_publisher <domain_id> o
objs/<arch>/ordered_group_subscriber <domain_id>
On Windows:
objs\<arch>\ordered_group_publisher <domain_id>
objs\<arch>\ordered_group_subscriber <domain_id>
modification history
------------ -------
*/
#include <stdio.h>
#include <stdlib.h>
#ifdef RTI_VX653
#include <vThreadsData.h>
#endif
#include "ordered_group.h"
#include "ordered_groupSupport.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;
/* Declaration of Topics */
DDSTopic *topic1 = NULL;
DDSTopic *topic2 = NULL;
DDSTopic *topic3 = NULL;
/* Declaration of DataWriters */
DDSDataWriter *writer1 = NULL;
DDSDataWriter *writer2 = NULL;
DDSDataWriter *writer3 = NULL;
ordered_groupDataWriter * ordered_group_writer1 = NULL;
ordered_groupDataWriter * ordered_group_writer2 = NULL;
ordered_groupDataWriter * ordered_group_writer3 = NULL;
/* Declaration of instances */
ordered_group *instance1 = NULL;
ordered_group *instance2 = NULL;
ordered_group *instance3 = 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 DATA TYPES. In this example, only one data type */
/* Register type before creating topic */
type_name = ordered_groupTypeSupport::get_type_name();
retcode = ordered_groupTypeSupport::register_type(
participant, type_name);
if (retcode != DDS_RETCODE_OK) {
printf("register_type error %d\n", retcode);
publisher_shutdown(participant);
return -1;
}
/* TOPICS */
/* To customize topic QoS, use
the configuration file USER_QOS_PROFILES.xml */
topic1 = participant->create_topic(
"Topic1",
type_name, DDS_TOPIC_QOS_DEFAULT, NULL /* listener */,
DDS_STATUS_MASK_NONE);
if (topic1 == NULL) {
printf("create_topic error\n");
publisher_shutdown(participant);
return -1;
}
topic2 = participant->create_topic(
"Topic2",
type_name, DDS_TOPIC_QOS_DEFAULT, NULL /* listener */,
DDS_STATUS_MASK_NONE);
if (topic2 == NULL) {
printf("create_topic error\n");
publisher_shutdown(participant);
return -1;
}
topic3 = participant->create_topic(
"Topic3",
type_name, DDS_TOPIC_QOS_DEFAULT, NULL /* listener */,
DDS_STATUS_MASK_NONE);
if (topic3 == NULL) {
printf("create_topic error\n");
publisher_shutdown(participant);
return -1;
}
/* DATAWRITERS */
/* To customize data writer QoS, use
the configuration file USER_QOS_PROFILES.xml */
writer1 = publisher->create_datawriter(
topic1, DDS_DATAWRITER_QOS_DEFAULT, NULL /* listener */,
DDS_STATUS_MASK_NONE);
if (writer1 == NULL) {
printf("create_datawriter error\n");
publisher_shutdown(participant);
return -1;
}
ordered_group_writer1 = ordered_groupDataWriter::narrow(writer1);
if (ordered_group_writer1 == NULL) {
printf("DataWriter narrow error\n");
publisher_shutdown(participant);
return -1;
}
writer2 = publisher->create_datawriter(
topic2, DDS_DATAWRITER_QOS_DEFAULT, NULL /* listener */,
DDS_STATUS_MASK_NONE);
if (writer2 == NULL) {
printf("create_datawriter error\n");
publisher_shutdown(participant);
return -1;
}
ordered_group_writer2 = ordered_groupDataWriter::narrow(writer2);
if (ordered_group_writer2 == NULL) {
printf("DataWriter narrow error\n");
publisher_shutdown(participant);
return -1;
}
writer3 = publisher->create_datawriter(
topic3, DDS_DATAWRITER_QOS_DEFAULT, NULL /* listener */,
DDS_STATUS_MASK_NONE);
if (writer3 == NULL) {
printf("create_datawriter error\n");
publisher_shutdown(participant);
return -1;
}
ordered_group_writer3 = ordered_groupDataWriter::narrow(writer3);
if (ordered_group_writer3 == NULL) {
printf("DataWriter narrow error\n");
publisher_shutdown(participant);
return -1;
}
/* INSTANCES */
/* Create data sample for writing */
instance1 = ordered_groupTypeSupport::create_data();
if (instance1 == NULL) {
printf("ordered_groupTypeSupport::create_data error\n");
publisher_shutdown(participant);
return -1;
}
instance2 = ordered_groupTypeSupport::create_data();
if (instance2 == NULL) {
printf("ordered_groupTypeSupport::create_data error\n");
publisher_shutdown(participant);
return -1;
}
instance3 = ordered_groupTypeSupport::create_data();
if (instance3 == NULL) {
printf("ordered_groupTypeSupport::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 = ordered_group_writer->register_instance(*instance);
*/
/* Main loop */
for (count=0; (sample_count == 0) || (count < sample_count); ++count) {
printf("Writing ordered_group, count %d\n", count);
/* Modify the data to be sent and Write data */
instance1->message =
"First sample, Topic 1 sent by DataWriter number 1";
retcode = ordered_group_writer1->write(*instance1, instance_handle);
if (retcode != DDS_RETCODE_OK) {
printf("write error %d\n", retcode);
}
instance1->message =
"Second sample, Topic 1 sent by DataWriter number 1";
retcode = ordered_group_writer1->write(*instance1, instance_handle);
if (retcode != DDS_RETCODE_OK) {
printf("write error %d\n", retcode);
}
instance2->message =
"First sample, Topic 2 sent by DataWriter number 2";
retcode = ordered_group_writer2->write(*instance2, instance_handle);
if (retcode != DDS_RETCODE_OK) {
printf("write error %d\n", retcode);
}
instance2->message =
"Second sample, Topic 2 sent by DataWriter number 2";
retcode = ordered_group_writer2->write(*instance2, instance_handle);
if (retcode != DDS_RETCODE_OK) {
printf("write error %d\n", retcode);
}
instance3->message =
"First sample, Topic 3 sent by DataWriter number 3";
retcode = ordered_group_writer3->write(*instance3, instance_handle);
if (retcode != DDS_RETCODE_OK) {
printf("write error %d\n", retcode);
}
instance3->message =
"Second sample, Topic 3 sent by DataWriter number 3";
retcode = ordered_group_writer3->write(*instance3, instance_handle);
if (retcode != DDS_RETCODE_OK) {
printf("write error %d\n", retcode);
}
NDDSUtility::sleep(send_period);
}
/*
retcode = ordered_group_writer->unregister_instance(
*instance, instance_handle);
if (retcode != DDS_RETCODE_OK) {
printf("unregister instance error %d\n", retcode);
}
*/
/* Delete data sample */
retcode = ordered_groupTypeSupport::delete_data(instance1);
if (retcode != DDS_RETCODE_OK) {
printf("ordered_groupTypeSupport::delete_data error %d\n", retcode);
}
/* Delete data sample */
retcode = ordered_groupTypeSupport::delete_data(instance2);
if (retcode != DDS_RETCODE_OK) {
printf("ordered_groupTypeSupport::delete_data error %d\n", retcode);
}
/* Delete data sample */
retcode = ordered_groupTypeSupport::delete_data(instance3);
if (retcode != DDS_RETCODE_OK) {
printf("ordered_groupTypeSupport::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/ordered_presentation_group/c++/ordered_group_subscriber.cxx | /*******************************************************************************
(c) 2005-2014 Copyright, Real-Time Innovations, Inc. All rights reserved.
RTI grants Licensee a license to use, modify, compile, and create derivative
works of the Software. Licensee has the right to distribute object form only
for use with RTI products. The Software is provided "as is", with no warranty
of any type, including any warranty for fitness for any purpose. RTI is under
no obligation to maintain or support the Software. RTI shall not be liable for
any incidental or consequential damages arising out of the use or inability to
use the software.
******************************************************************************/
/* ordered_group_subscriber.cxx
A subscription example
This file is derived from code automatically generated by the rtiddsgen
command:
rtiddsgen -language C++ -example <arch> ordered_group.idl
Example subscription of type ordered_group automatically generated by
'rtiddsgen'. To test them follow these steps:
(1) Compile this file and the example publication.
(2) Start the subscription with the command
objs/<arch>/ordered_group_subscriber <domain_id> <sample_count>
(3) Start the publication with the command
objs/<arch>/ordered_group_publisher <domain_id> <sample_count>
(4) [Optional] Specify the list of discovery initial peers and
multicast receive addresses via an environment variable or a file
(in the current working directory) called NDDS_DISCOVERY_PEERS.
You can run any number of publishers and subscribers programs, and can
add and remove them dynamically from the domain.
Example:
To run the example application on domain <domain_id>:
On Unix:
objs/<arch>/ordered_group_publisher <domain_id>
objs/<arch>/ordered_group_subscriber <domain_id>
On Windows:
objs\<arch>\ordered_group_publisher <domain_id>
objs\<arch>\ordered_group_subscriber <domain_id>
modification history
------------ -------
*/
#include <stdio.h>
#include <stdlib.h>
#ifdef RTI_VX653
#include <vThreadsData.h>
#endif
#include "ordered_group.h"
#include "ordered_groupSupport.h"
#include "ndds/ndds_cpp.h"
////////////////////////////////////////////////////////////////////////
class ordered_groupSubscriberListener : public DDSSubscriberListener {
public:
virtual void on_data_on_readers(DDSSubscriber* subscriber);
};
void ordered_groupSubscriberListener::on_data_on_readers(
DDSSubscriber* subscriber)
{
DDSDataReaderSeq MyDataReaders;
DDS_ReturnCode_t retcode;
int i;
/* IMPORTANT for GROUP access scope: Invoking begin_access() */
subscriber->begin_access();
/* Obtain DataReaders. We obtain a sequence of DataReaders that specifies
the order in which each sample should be read */
retcode = subscriber->get_datareaders(MyDataReaders,DDS_ANY_SAMPLE_STATE,
DDS_ANY_VIEW_STATE,DDS_ANY_INSTANCE_STATE);
if (retcode != DDS_RETCODE_OK) {
printf("ERROR error %d\n", retcode);
/* IMPORTANT. Remember to invoke end_access() before a return call.
Also reset DataReaders sequence */
MyDataReaders.ensure_length(0,0);
subscriber->end_access();
return;
}
/* Read the samples received, following the DataReaders sequence */
for(i=0; i<MyDataReaders.length(); i++){
ordered_groupDataReader *ordered_group_reader = NULL;
ordered_group data;
DDS_SampleInfo info;
ordered_group_initialize(&data);
ordered_group_reader =
ordered_groupDataReader::narrow(MyDataReaders.get_at(i));
if (ordered_group_reader == NULL) {
printf("DataReader narrow error\n");
/* IMPORTANT. Remember to invoke end_access() before a return call.
Also reset DataReaders sequence */
MyDataReaders.ensure_length(0,0);
subscriber->end_access();
return;
}
/* IMPORTANT. Use take_next_sample(). We need to take only
* one sample each time, as we want to follow the sequence of
* DataReaders. This way the samples will be returned in the
* order in which they were modified */
retcode = ordered_group_reader->take_next_sample(data, info);
/* In case there is no data in current DataReader,
check next in the sequence */
if (retcode == DDS_RETCODE_NO_DATA) {
continue;
} else if (retcode != DDS_RETCODE_OK) {
printf("take error %d\n", retcode);
continue;
}
/* Print data sample */
if (info.valid_data) {
ordered_groupTypeSupport::print_data(&data);
}
}
/* Reset DataReaders sequence */
MyDataReaders.ensure_length(0,0);
/* IMPORTANT for GROUP access scope: Invoking end_access() */
subscriber->end_access();
}
/////////////////////////////////////////////////////////////////////////
/* 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 *topic1 = NULL;
DDSTopic *topic2 = NULL;
DDSTopic *topic3 = NULL;
ordered_groupSubscriberListener *subscriber_listener = NULL;
DDSDataReader *reader1 = NULL;
DDSDataReader *reader2 = NULL;
DDSDataReader *reader3 = 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;
}
/* Create Subscriber listener and establish on_data_on_readers callback */
subscriber_listener = new ordered_groupSubscriberListener();
/* To customize the subscriber QoS, use
the configuration file USER_QOS_PROFILES.xml */
subscriber = participant->create_subscriber(
DDS_SUBSCRIBER_QOS_DEFAULT, subscriber_listener,
DDS_DATA_ON_READERS_STATUS);
if (subscriber == NULL) {
printf("create_subscriber error\n");
subscriber_shutdown(participant);
delete subscriber_listener;
return -1;
}
/* Register the type before creating the topic */
type_name = ordered_groupTypeSupport::get_type_name();
retcode = ordered_groupTypeSupport::register_type(
participant, type_name);
if (retcode != DDS_RETCODE_OK) {
printf("register_type error %d\n", retcode);
subscriber_shutdown(participant);
return -1;
}
/* TOPICS */
/* To customize the topic QoS, use
the configuration file USER_QOS_PROFILES.xml */
topic1 = participant->create_topic(
"Topic1",
type_name, DDS_TOPIC_QOS_DEFAULT, NULL /* listener */,
DDS_STATUS_MASK_NONE);
if (topic1 == NULL) {
printf("create_topic error\n");
subscriber_shutdown(participant);
return -1;
}
topic2 = participant->create_topic(
"Topic2",
type_name, DDS_TOPIC_QOS_DEFAULT, NULL /* listener */,
DDS_STATUS_MASK_NONE);
if (topic2 == NULL) {
printf("create_topic error\n");
subscriber_shutdown(participant);
return -1;
}
topic3 = participant->create_topic(
"Topic3",
type_name, DDS_TOPIC_QOS_DEFAULT, NULL /* listener */,
DDS_STATUS_MASK_NONE);
if (topic3 == NULL) {
printf("create_topic error\n");
subscriber_shutdown(participant);
return -1;
}
/* DATAREADERS */
/* To customize the data reader QoS, use
the configuration file USER_QOS_PROFILES.xml */
reader1 = subscriber->create_datareader(
topic1, DDS_DATAREADER_QOS_DEFAULT, NULL,
DDS_STATUS_MASK_NONE);
if (reader1 == NULL) {
printf("create_datareader error\n");
subscriber_shutdown(participant);
return -1;
}
reader2 = subscriber->create_datareader(
topic2, DDS_DATAREADER_QOS_DEFAULT, NULL,
DDS_STATUS_MASK_NONE);
if (reader2 == NULL) {
printf("create_datareader error\n");
subscriber_shutdown(participant);
return -1;
}
reader3 = subscriber->create_datareader(
topic3, DDS_DATAREADER_QOS_DEFAULT, NULL,
DDS_STATUS_MASK_NONE);
if (reader3 == NULL) {
printf("create_datareader error\n");
subscriber_shutdown(participant);
return -1;
}
/* Main loop */
for (count=0; (sample_count == 0) || (count < sample_count); ++count) {
printf("ordered_group subscriber sleeping for %d sec...\n",
receive_period.sec);
NDDSUtility::sleep(receive_period);
}
/* Delete all entities */
status = subscriber_shutdown(participant);
delete subscriber_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/ordered_presentation_group/c/ordered_group_publisher.c | /*******************************************************************************
(c) 2005-2014 Copyright, Real-Time Innovations, Inc. All rights reserved.
RTI grants Licensee a license to use, modify, compile, and create derivative
works of the Software. Licensee has the right to distribute object form only
for use with RTI products. The Software is provided "as is", with no warranty
of any type, including any warranty for fitness for any purpose. RTI is under
no obligation to maintain or support the Software. RTI shall not be liable for
any incidental or consequential damages arising out of the use or inability to
use the software.
******************************************************************************/
/* ordered_group_publisher.c
A publication of data of type ordered_group
This file is derived from code automatically generated by the rtiddsgen
command:
rtiddsgen -language C -example <arch> ordered_group.idl
Example publication of type ordered_group automatically generated by
'rtiddsgen'. To test them follow these steps:
(1) Compile this file and the example subscription.
(2) Start the subscription with the command
objs/<arch>/ordered_group_subscriber <domain_id> <sample_count>
(3) Start the publication with the command
objs/<arch>/ordered_group_publisher <domain_id> <sample_count>
(4) [Optional] Specify the list of discovery initial peers and
multicast receive addresses via an environment variable or a file
(in the current working directory) called NDDS_DISCOVERY_PEERS.
You can run any number of publishers and subscribers programs, and can
add and remove them dynamically from the domain.
Example:
To run the example application on domain <domain_id>:
On Unix:
objs/<arch>/ordered_group_publisher <domain_id>
objs/<arch>/ordered_group_subscriber <domain_id>
On Windows:
objs\<arch>\ordered_group_publisher <domain_id>
objs\<arch>\ordered_group_subscriber <domain_id>
modification history
------------ -------
*/
#include <stdio.h>
#include <stdlib.h>
#include "ndds/ndds_c.h"
#include "ordered_group.h"
#include "ordered_groupSupport.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;
/* Declaration of Topics */
DDS_Topic *topic1 = NULL;
DDS_Topic *topic2 = NULL;
DDS_Topic *topic3 = NULL;
/* Declaration of DataWriters */
DDS_DataWriter *writer1 = NULL;
DDS_DataWriter *writer2 = NULL;
DDS_DataWriter *writer3 = NULL;
ordered_groupDataWriter * ordered_group_writer1 = NULL;
ordered_groupDataWriter * ordered_group_writer2 = NULL;
ordered_groupDataWriter * ordered_group_writer3 = NULL;
/* Declaration of instances */
ordered_group *instance1 = NULL;
ordered_group *instance2 = NULL;
ordered_group *instance3 = NULL;
DDS_ReturnCode_t retcode;
DDS_InstanceHandle_t instance_handle = DDS_HANDLE_NIL;
const char *type_name = NULL;
int count = 0;
struct DDS_Duration_t send_period = {1,0};
/* To customize participant QoS, use
the configuration file USER_QOS_PROFILES.xml */
participant = DDS_DomainParticipantFactory_create_participant(
DDS_TheParticipantFactory, domainId, &DDS_PARTICIPANT_QOS_DEFAULT,
NULL /* listener */, DDS_STATUS_MASK_NONE);
if (participant == NULL) {
printf("create_participant error\n");
publisher_shutdown(participant);
return -1;
}
/* To customize publisher QoS, use
the configuration file USER_QOS_PROFILES.xml */
publisher = DDS_DomainParticipant_create_publisher(
participant, &DDS_PUBLISHER_QOS_DEFAULT, NULL /* listener */,
DDS_STATUS_MASK_NONE);
if (publisher == NULL) {
printf("create_publisher error\n");
publisher_shutdown(participant);
return -1;
}
/* Register DATA TYPES. In this example, only one data type */
/* Register type before creating topic */
type_name = ordered_groupTypeSupport_get_type_name();
retcode = ordered_groupTypeSupport_register_type(
participant, type_name);
if (retcode != DDS_RETCODE_OK) {
printf("register_type error %d\n", retcode);
publisher_shutdown(participant);
return -1;
}
/* TOPICS */
/* To customize topic QoS, use
the configuration file USER_QOS_PROFILES.xml */
topic1 = DDS_DomainParticipant_create_topic(
participant, "Topic1",
type_name, &DDS_TOPIC_QOS_DEFAULT, NULL /* listener */,
DDS_STATUS_MASK_NONE);
if (topic1 == NULL) {
printf("create_topic error\n");
publisher_shutdown(participant);
return -1;
}
topic2 = DDS_DomainParticipant_create_topic(
participant, "Topic2",
type_name, &DDS_TOPIC_QOS_DEFAULT, NULL /* listener */,
DDS_STATUS_MASK_NONE);
if (topic2 == NULL) {
printf("create_topic error\n");
publisher_shutdown(participant);
return -1;
}
topic3 = DDS_DomainParticipant_create_topic(
participant, "Topic3",
type_name, &DDS_TOPIC_QOS_DEFAULT, NULL /* listener */,
DDS_STATUS_MASK_NONE);
if (topic3 == NULL) {
printf("create_topic error\n");
publisher_shutdown(participant);
return -1;
}
/* DATAWRITERS */
/* To customize data writer QoS, use
the configuration file USER_QOS_PROFILES.xml */
writer1 = DDS_Publisher_create_datawriter(
publisher, topic1,
&DDS_DATAWRITER_QOS_DEFAULT, NULL /* listener */,
DDS_STATUS_MASK_NONE);
if (writer1 == NULL) {
printf("create_datawriter error\n");
publisher_shutdown(participant);
return -1;
}
ordered_group_writer1 = ordered_groupDataWriter_narrow(writer1);
if (ordered_group_writer1 == NULL) {
printf("DataWriter narrow error\n");
publisher_shutdown(participant);
return -1;
}
writer2 = DDS_Publisher_create_datawriter(
publisher, topic2,
&DDS_DATAWRITER_QOS_DEFAULT, NULL /* listener */,
DDS_STATUS_MASK_NONE);
if (writer2 == NULL) {
printf("create_datawriter error\n");
publisher_shutdown(participant);
return -1;
}
ordered_group_writer2 = ordered_groupDataWriter_narrow(writer2);
if (ordered_group_writer2 == NULL) {
printf("DataWriter narrow error\n");
publisher_shutdown(participant);
return -1;
}
writer3 = DDS_Publisher_create_datawriter(
publisher, topic3,
&DDS_DATAWRITER_QOS_DEFAULT, NULL /* listener */,
DDS_STATUS_MASK_NONE);
if (writer3 == NULL) {
printf("create_datawriter error\n");
publisher_shutdown(participant);
return -1;
}
ordered_group_writer3 = ordered_groupDataWriter_narrow(writer3);
if (ordered_group_writer3 == NULL) {
printf("DataWriter narrow error\n");
publisher_shutdown(participant);
return -1;
}
/* INSTANCES */
/* Create data sample for writing */
instance1 = ordered_groupTypeSupport_create_data_ex(DDS_BOOLEAN_TRUE);
if (instance1 == NULL) {
printf("ordered_groupTypeSupport_create_data error\n");
publisher_shutdown(participant);
return -1;
}
instance2 = ordered_groupTypeSupport_create_data_ex(DDS_BOOLEAN_TRUE);
if (instance2 == NULL) {
printf("ordered_groupTypeSupport_create_data error\n");
publisher_shutdown(participant);
return -1;
}
instance3 = ordered_groupTypeSupport_create_data_ex(DDS_BOOLEAN_TRUE);
if (instance3 == NULL) {
printf("ordered_groupTypeSupport_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 = ordered_groupDataWriter_register_instance(
ordered_group_writer, instance);
*/
/* Main loop */
for (count=0; (sample_count == 0) || (count < sample_count); ++count) {
printf("Writing ordered_group, count %d\n", count);
/* Modify the data to be sent and Write data */
instance1->message =
"First sample, Topic 1 sent by DataWriter number 1";
retcode = ordered_groupDataWriter_write(
ordered_group_writer1, instance1, &instance_handle);
if (retcode != DDS_RETCODE_OK) {
printf("write error %d\n", retcode);
}
instance1->message =
"Second sample, Topic 1 sent by DataWriter number 1";
retcode = ordered_groupDataWriter_write(
ordered_group_writer1, instance1, &instance_handle);
if (retcode != DDS_RETCODE_OK) {
printf("write error %d\n", retcode);
}
instance2->message =
"First sample, Topic 2 sent by DataWriter number 2";
retcode = ordered_groupDataWriter_write(
ordered_group_writer2, instance2, &instance_handle);
if (retcode != DDS_RETCODE_OK) {
printf("write error %d\n", retcode);
}
instance2->message =
"Second sample, Topic 2 sent by DataWriter number 2";
retcode = ordered_groupDataWriter_write(
ordered_group_writer2, instance2, &instance_handle);
if (retcode != DDS_RETCODE_OK) {
printf("write error %d\n", retcode);
}
instance3->message =
"First sample, Topic 3 sent by DataWriter number 3";
retcode = ordered_groupDataWriter_write(
ordered_group_writer3, instance3, &instance_handle);
if (retcode != DDS_RETCODE_OK) {
printf("write error %d\n", retcode);
}
instance3->message =
"Second sample, Topic 3 sent by DataWriter number 3";
retcode = ordered_groupDataWriter_write(
ordered_group_writer3, instance3, &instance_handle);
if (retcode != DDS_RETCODE_OK) {
printf("write error %d\n", retcode);
}
NDDS_Utility_sleep(&send_period);
}
/*
retcode = ordered_groupDataWriter_unregister_instance(
ordered_group_writer, instance, &instance_handle);
if (retcode != DDS_RETCODE_OK) {
printf("unregister instance error %d\n", retcode);
}
*/
/* Delete data sample */
retcode = ordered_groupTypeSupport_delete_data_ex(instance1,
DDS_BOOLEAN_TRUE);
if (retcode != DDS_RETCODE_OK) {
printf("ordered_groupTypeSupport_delete_data error %d\n", retcode);
}
/* Delete data sample */
retcode = ordered_groupTypeSupport_delete_data_ex(instance2,
DDS_BOOLEAN_TRUE);
if (retcode != DDS_RETCODE_OK) {
printf("ordered_groupTypeSupport_delete_data error %d\n", retcode);
}
/* Delete data sample */
retcode = ordered_groupTypeSupport_delete_data_ex(instance3,
DDS_BOOLEAN_TRUE);
if (retcode != DDS_RETCODE_OK) {
printf("ordered_groupTypeSupport_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/ordered_presentation_group/c/ordered_group_subscriber.c | /*******************************************************************************
(c) 2005-2014 Copyright, Real-Time Innovations, Inc. All rights reserved.
RTI grants Licensee a license to use, modify, compile, and create derivative
works of the Software. Licensee has the right to distribute object form only
for use with RTI products. The Software is provided "as is", with no warranty
of any type, including any warranty for fitness for any purpose. RTI is under
no obligation to maintain or support the Software. RTI shall not be liable for
any incidental or consequential damages arising out of the use or inability to
use the software.
******************************************************************************/
/* ordered_group_subscriber.c
A subscription example
This file is derived from code automatically generated by the rtiddsgen
command:
rtiddsgen -language C -example <arch> ordered_group.idl
Example subscription of type ordered_group automatically generated by
'rtiddsgen'. To test them, follow these steps:
(1) Compile this file and the example publication.
(2) Start the subscription with the command
objs/<arch>/ordered_group_subscriber <domain_id> <sample_count>
(3) Start the publication with the command
objs/<arch>/ordered_group_publisher <domain_id> <sample_count>
(4) [Optional] Specify the list of discovery initial peers and
multicast receive addresses via an environment variable or a file
(in the current working directory) called NDDS_DISCOVERY_PEERS.
You can run any number of publishers and subscribers programs, and can
add and remove them dynamically from the domain.
Example:
To run the example application on domain <domain_id>:
On UNIX systems:
objs/<arch>/ordered_group_publisher <domain_id>
objs/<arch>/ordered_group_subscriber <domain_id>
On Windows systems:
objs\<arch>\ordered_group_publisher <domain_id>
objs\<arch>\ordered_group_subscriber <domain_id>
modification history
------------ -------
*/
#include <stdio.h>
#include <stdlib.h>
#include "ndds/ndds_c.h"
#include "ordered_group.h"
#include "ordered_groupSupport.h"
void ordered_groupListener_on_data_on_readers(
void *listener_data, DDS_Subscriber* subscriber)
{
struct DDS_DataReaderSeq MyDataReaders;
DDS_ReturnCode_t retcode;
int i;
/* IMPORTANT for GROUP access scope: Invoking
* DDS_Subscriber_begin_access() */
DDS_Subscriber_begin_access(subscriber);
/* Obtain DataReaders. We obtain a sequence of DataReaders that
* specifies the order in which each sample should be read */
retcode = DDS_Subscriber_get_datareaders(subscriber,
&MyDataReaders,
DDS_ANY_SAMPLE_STATE,
DDS_ANY_VIEW_STATE,
DDS_ANY_INSTANCE_STATE);
if (retcode != DDS_RETCODE_OK) {
printf("ERROR error %d\n", retcode);
/* IMPORTANT. Remember to invoke DDS_Subscriber_end_access() before a
* return call. Also reset DataReaders sequence */
DDS_DataReaderSeq_ensure_length(&MyDataReaders,0,0);
DDS_Subscriber_end_access(subscriber);
return;
}
/* Read the samples received, following the DataReaders sequence */
for (i = 0; i < DDS_DataReaderSeq_get_length(&MyDataReaders); i++) {
ordered_groupDataReader *ordered_group_reader = NULL;
struct ordered_group data;
struct DDS_SampleInfo info;
ordered_group_initialize(&data);
ordered_group_reader =
ordered_groupDataReader_narrow(
DDS_DataReaderSeq_get(&MyDataReaders,i));
if (ordered_group_reader == NULL) {
printf("DataReader narrow error\n");
/* IMPORTANT. Remember to invoke DDS_Subscriber_end_access() before
* a return call. Also reset DataReaders sequence */
DDS_DataReaderSeq_ensure_length(&MyDataReaders,0,0);
DDS_Subscriber_end_access(subscriber);
return;
}
/* IMPORTANT. Use take_next_sample(). We need to take only
one sample each time, as we want to follow the sequence of
DataReaders. This way the samples will be returned in the
order in which they were modified */
retcode = ordered_groupDataReader_take_next_sample(ordered_group_reader,
&data,
&info);
/* In case there is no data in current DataReader,
check next in the sequence */
if (retcode == DDS_RETCODE_NO_DATA) {
continue;
} else if (retcode != DDS_RETCODE_OK) {
printf("take error %d\n", retcode);
continue;
}
/* Print data sample */
if (info.valid_data) {
ordered_groupTypeSupport_print_data(&data);
}
}
/* Reset DataReaders sequence */
DDS_DataReaderSeq_ensure_length(&MyDataReaders,0,0);
/* IMPORTANT for GROUP access scope: Invoking DDS_Subscriber_end_access() */
DDS_Subscriber_end_access(subscriber);
}
/* 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 *topic1 = NULL;
DDS_Topic *topic2 = NULL;
DDS_Topic *topic3 = NULL;
struct DDS_SubscriberListener subscriber_listener =
DDS_SubscriberListener_INITIALIZER;
DDS_DataReader *reader1 = NULL;
DDS_DataReader *reader2 = NULL;
DDS_DataReader *reader3 = 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;
}
/* Set up Subscriber listener and establish on_data_on_readers callback */
/* Set up a data reader listener */
subscriber_listener.on_data_on_readers =
ordered_groupListener_on_data_on_readers;
/* To customize subscriber QoS, use
the configuration file USER_QOS_PROFILES.xml */
subscriber = DDS_DomainParticipant_create_subscriber(
participant, &DDS_SUBSCRIBER_QOS_DEFAULT,
&subscriber_listener /* listener */, DDS_DATA_ON_READERS_STATUS);
if (subscriber == NULL) {
printf("create_subscriber error\n");
subscriber_shutdown(participant);
return -1;
}
/* Register the type before creating the topic */
type_name = ordered_groupTypeSupport_get_type_name();
retcode = ordered_groupTypeSupport_register_type(participant, type_name);
if (retcode != DDS_RETCODE_OK) {
printf("register_type error %d\n", retcode);
subscriber_shutdown(participant);
return -1;
}
/* TOPICS */
/* To customize topic QoS, use
the configuration file USER_QOS_PROFILES.xml */
topic1 = DDS_DomainParticipant_create_topic(
participant, "Topic1",
type_name, &DDS_TOPIC_QOS_DEFAULT, NULL /* listener */,
DDS_STATUS_MASK_NONE);
if (topic1 == NULL) {
printf("create_topic error\n");
subscriber_shutdown(participant);
return -1;
}
topic2 = DDS_DomainParticipant_create_topic(
participant, "Topic2",
type_name, &DDS_TOPIC_QOS_DEFAULT, NULL /* listener */,
DDS_STATUS_MASK_NONE);
if (topic2 == NULL) {
printf("create_topic error\n");
subscriber_shutdown(participant);
return -1;
}
topic3 = DDS_DomainParticipant_create_topic(
participant, "Topic3",
type_name, &DDS_TOPIC_QOS_DEFAULT, NULL /* listener */,
DDS_STATUS_MASK_NONE);
if (topic3 == NULL) {
printf("create_topic error\n");
subscriber_shutdown(participant);
return -1;
}
/* DATAREADERS */
/* To customize data reader QoS, use
the configuration file USER_QOS_PROFILES.xml */
reader1 = DDS_Subscriber_create_datareader(
subscriber, DDS_Topic_as_topicdescription(topic1),
&DDS_DATAREADER_QOS_DEFAULT, NULL, DDS_STATUS_MASK_NONE);
if (reader1 == NULL) {
printf("create_datareader error\n");
subscriber_shutdown(participant);
return -1;
}
reader2 = DDS_Subscriber_create_datareader(
subscriber, DDS_Topic_as_topicdescription(topic2),
&DDS_DATAREADER_QOS_DEFAULT, NULL, DDS_STATUS_MASK_NONE);
if (reader2 == NULL) {
printf("create_datareader error\n");
subscriber_shutdown(participant);
return -1;
}
reader3 = DDS_Subscriber_create_datareader(
subscriber, DDS_Topic_as_topicdescription(topic3),
&DDS_DATAREADER_QOS_DEFAULT, NULL, DDS_STATUS_MASK_NONE);
if (reader3 == NULL) {
printf("create_datareader error\n");
subscriber_shutdown(participant);
return -1;
}
/* Main loop */
for (count=0; (sample_count == 0) || (count < sample_count); ++count) {
printf("ordered_group 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/ordered_presentation_group/c++03/ordered_group_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 "ordered_group.hpp"
using namespace dds::core;
using namespace dds::core::policy;
using namespace dds::domain;
using namespace dds::pub;
using namespace dds::pub::qos;
using namespace dds::topic;
void publisher_main(int domain_id, int sample_count)
{
// Create a DomainParticipant with default Qos
DomainParticipant participant(domain_id);
// Retrieve the default Publisher QoS, from USER_QOS_PROFILES.xml
PublisherQos publisher_qos = QosProvider::Default().publisher_qos();
// If you want to change the Publisher's QoS programmatically rather than
// using the XML file, uncomment the following line.
// publisher_qos << Presentation::GroupAccessScope(false, true);
// Create a single Publisher for all DataWriters.
Publisher publisher(participant, publisher_qos);
// Create three Topic, once for each DataWriter.
Topic<ordered_group> topic1(participant, "Topic1");
Topic<ordered_group> topic2(participant, "Topic2");
Topic<ordered_group> topic3(participant, "Topic3");
// Create three DataWriter. Since the QoS policy is set to 'GROUP',
// and the three writers belong to the same Publisher, the instance change
// will be available for the Subscriber in the same order.
DataWriter<ordered_group> writer1(publisher, topic1);
DataWriter<ordered_group> writer2(publisher, topic2);
DataWriter<ordered_group> writer3(publisher, topic3);
// Create one instance for each DataWriter.
ordered_group instance1;
ordered_group instance2;
ordered_group instance3;
for (int count = 0; count < sample_count || sample_count == 0; count++) {
std::cout << "Writing ordered_group, count " << count << std::endl;
// Modify twice the first instance and send with the first writer.
instance1.message("First sample, Topic 1 sent by DataWriter number 1");
writer1.write(instance1);
instance1.message("Second sample, Topic 1 sent by DataWriter number 1");
writer1.write(instance1);
// Modify twice the second instance and send with the second writer.
instance2.message("First sample, Topic 2 sent by DataWriter number 2");
writer2.write(instance2);
instance2.message("Second sample, Topic 2 sent by DataWriter number 2");
writer2.write(instance2);
// Modify twice the third instance and send with the third writer.
instance3.message("First sample, Topic 3 sent by DataWriter number 3");
writer3.write(instance3);
instance3.message("Second sample, Topic 3 sent by DataWriter number 3");
writer3.write(instance3);
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/ordered_presentation_group/c++03/ordered_group_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 "ordered_group.hpp"
using namespace dds::core;
using namespace dds::core::policy;
using namespace rti::core;
using namespace dds::core::status;
using namespace dds::domain;
using namespace dds::sub;
using namespace dds::sub::qos;
using namespace rti::sub;
using namespace dds::topic;
class ordered_groupSubscriberListener: public NoOpSubscriberListener{
public:
void on_data_on_readers(Subscriber& subscriber)
{
// Create a coherent group access.
CoherentAccess coherent_access(subscriber);
// Get the sequence of DataReaders that specifies the order
// in wich each sample should be read.
std::vector<AnyDataReader> readers;
int num_readers = find(subscriber,
dds::sub::status::DataState::new_data(),
std::back_inserter(readers));
std::cout << num_readers << std::endl;
for (int i = 0; i < num_readers; i++) {
DataReader<ordered_group> reader =
readers[i].get<ordered_group>();
// We need to take only one sample each time, as we want to follow
// the sequence of DataReaders. This way the samples will be
// returned in the order in which they were modified.
LoanedSamples<ordered_group> sample =
reader.select().max_samples(1).take();
if (sample.length() > 0 && sample[0].info().valid()) {
std::cout << sample[0].data() << std::endl;
}
}
// The destructor will ends the coherent group access
}
};
void subscriber_main(int domain_id, int sample_count)
{
// Create a DomainParticipant 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's QoS programmatically rather than
// using the XML file, uncomment the following line.
// subscriber_qos << Presentation::GroupAccessScope(false, true);
// Create a Subscriber.
Subscriber subscriber(participant, subscriber_qos);
// Associate a listener to the subscriber using ListenerBinder, a RAII that
// will take care of setting it to NULL on destruction.
ListenerBinder<Subscriber> subscriber_listener =
rti::core::bind_and_manage_listener(
subscriber,
new ordered_groupSubscriberListener,
dds::core::status::StatusMask::data_on_readers());
// Create three Topic, once for each DataReader.
Topic<ordered_group> topic1(participant, "Topic1");
Topic<ordered_group> topic2(participant, "Topic2");
Topic<ordered_group> topic3(participant, "Topic3");
// Create one DataReader for each Topic.
DataReader<ordered_group> reader1(subscriber, topic1);
DataReader<ordered_group> reader2(subscriber, topic2);
DataReader<ordered_group> reader3(subscriber, topic3);
for (int count = 0; (sample_count == 0) || (count < sample_count); ++count){
std::cout << "ordered_group subscriber sleeping for 1 sec..."
<< std::endl;
rti::util::sleep(Duration(1));
}
}
int main(int argc, char *argv[])
{
int domain_id = 0;
int sample_count = 0; // Infinite loop
if (argc >= 2) {
domain_id = atoi(argv[1]);
}
if (argc >= 3) {
sample_count = atoi(argv[2]);
}
// To turn on additional logging, include <rti/config/Logger.hpp> and
// uncomment the following line:
// rti::config::Logger::instance().verbosity(rti::config::Verbosity::STATUS_ALL);
try {
subscriber_main(domain_id, sample_count);
} catch (const std::exception& ex) {
// This will catch DDS exceptions
std::cerr << "Exception in subscriber_main: " << ex.what() << std::endl;
return -1;
}
return 0;
}
| cxx |
rticonnextdds-examples | data/projects/rticonnextdds-examples/dynamic_data_using_publisher_subscriber/c++/Shapes_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.
******************************************************************************/
/* Shapes_subscriber.cxx
A subscription of data type ShapeType using DynamicData
This file is derived from code automatically generated by the rtiddsgen
command:
rtiddsgen -language C++ -example <arch> Shapes.idl
If you are not using and IDL to generate the TypeCode,
you will need to create it manually. Follow other DynamicData
examples (such as NestedStruct one) to learn how to do it.
Example:
To run the example application on domain <domain_id>:
On Unix:
objs/<arch>/Shapes_publisher <domain_id> <sample #>
objs/<arch>/Shapes_subscriber <domain_id> <sample #>
On Windows:
objs\<arch>\Shapes_publisher <domain_id> <sample #>
objs\<arch>\Shapes_subscriber <domain_id> <sample #>
modification history
------------ -------
*/
#include <stdio.h>
#include <stdlib.h>
#ifdef RTI_VX653
#include <vThreadsData.h>
#endif
#include "Shapes.h"
#include "ndds/ndds_cpp.h"
#define EXAMPLE_TYPE_NAME "ShapesType"
class ShapeTypeListener: 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 ShapeTypeListener::on_data_available(DDSDataReader* reader) {
/* We need to create a DynamicDataReader to receive the DynamicData
* and a DynamicDataSeq to store there the available DynamicData received
*/
DDSDynamicDataReader *DynamicData_reader = NULL;
DDS_DynamicDataSeq data_seq;
DDS_SampleInfoSeq info_seq;
DDS_ReturnCode_t retcode;
int i;
/* To use DynamicData, we need to assign the generic DataReader to
* a DynamicDataReader, using DDS_DynamicDataReader_narrow.
* The following narrow fuction should never fail, as it performs
* only a safe cast.
*/
DynamicData_reader = DDSDynamicDataReader::narrow(reader);
if (DynamicData_reader == NULL) {
printf("DataReader narrow error\n");
return;
}
retcode = DynamicData_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) {
data_seq[i].print(stdout, 1);
}
}
retcode = DynamicData_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,
DDSDynamicDataTypeSupport *type_support) {
DDS_ReturnCode_t retcode;
int status = 0;
if (participant != NULL) {
if (type_support != NULL) {
delete type_support;
type_support = 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;
ShapeTypeListener *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;
/* Dynamic Data parameters that we will need */
struct DDS_TypeCode *type_code = NULL;
struct DDS_DynamicDataTypeProperty_t props;
DDSDynamicDataTypeSupport *type_support = NULL;
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, type_support);
return -1;
}
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, type_support);
return -1;
}
/* Create DynamicData using TypeCode from Shapes.cxx
* If you are NOT using a type generated with rtiddsgen, you
* need to create this TypeCode from scratch.
*/
type_code = ShapeType_get_typecode();
if (type_code == NULL) {
printf("get_typecode error\n");
subscriber_shutdown(participant, type_support);
return -1;
}
/* Create the Dynamic data type support object */
type_support = new DDSDynamicDataTypeSupport(type_code, props);
if (type_support == NULL) {
fprintf(stderr, "create type_support error\n");
subscriber_shutdown(participant, type_support);
return -1;
}
/* Register the type before creating the topic */
type_name = EXAMPLE_TYPE_NAME;
retcode = type_support->register_type(participant, type_name);
if (retcode != DDS_RETCODE_OK) {
printf("register_type error %d\n", retcode);
subscriber_shutdown(participant, type_support);
return -1;
}
/* Make sure both publisher and subscriber share the same topic name.
* In the Shapes example: we are subscribing to a Square, wich is the
* topic name. If you want to publish other shapes (Triangle or Circle),
* you just need to update the topic name.
*/
topic = participant->create_topic("Square", type_name,
DDS_TOPIC_QOS_DEFAULT, NULL /* listener */, DDS_STATUS_MASK_NONE);
if (topic == NULL) {
printf("create_topic error\n");
subscriber_shutdown(participant, type_support);
return -1;
}
/* Create a data reader listener */
reader_listener = new ShapeTypeListener();
/* First, we create a generic DataReader for our topic */
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, type_support);
delete reader_listener;
return -1;
}
/* Main loop */
for (count = 0; (sample_count == 0) || (count < sample_count); ++count) {
printf("ShapeType subscriber sleeping for %d sec...\n",
receive_period.sec);
NDDSUtility::sleep(receive_period);
}
/* Delete all entities */
status = subscriber_shutdown(participant, type_support);
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/dynamic_data_using_publisher_subscriber/c++/Shapes_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.
******************************************************************************/
/* Shapes_publisher.cxx
A publication of data of type ShapeType using DynamicData
This file is derived from code automatically generated by the rtiddsgen
command:
rtiddsgen -language C++ -example <arch> Shapes.idl
If you are not using an IDL to generate the TypeCode,
you will need to create it manually. Follow other DynamicData
examples (such as NestedStruct one) to learn how to do it.
Example:
To run the example application on domain <domain_id>:
On Unix:
objs/<arch>/Shapes_publisher <domain_id> <sample #>
objs/<arch>/Shapes_subscriber <domain_id> <sample #>
On Windows:
objs\<arch>\Shapes_publisher <domain_id> <sample #>
objs\<arch>\Shapes_subscriber <domain_id> <sample #>
modification history
------------ -------
*/
#include <cstdio>
#include <cstdlib>
#ifdef RTI_VX653
#include <vThreadsData.h>
#endif
#include "Shapes.h"
#include "ndds/ndds_cpp.h"
#define EXAMPLE_TYPE_NAME "ShapesType"
/* Delete all entities */
static int publisher_shutdown(DDSDomainParticipant *participant,
DDSDynamicDataTypeSupport *type_support) {
DDS_ReturnCode_t retcode;
int status = 0;
if (participant != NULL) {
if (type_support != NULL) {
delete type_support;
type_support = 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) {
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 }; /* 100 ms */
/*** Shape direction variables ***/
int direction = 1; /* 1 means left to right and -1, right to left */
int x_position = 50; /* 50 is the initial position */
/*** DDS ENTITIES ***/
DDSDomainParticipant *participant = NULL;
DDSPublisher *publisher = NULL;
DDSTopic *topic = NULL;
DDSDataWriter *writer = NULL;
/*** Dynamic Data parameters that we will need ***/
struct DDS_TypeCode *type_code = NULL;
DDS_DynamicData *data = NULL;
DDS_Boolean data_is_initialized = DDS_BOOLEAN_FALSE;
DDSDynamicDataWriter *DynamicData_writer = NULL;
struct DDS_DynamicDataTypeProperty_t props;
DDSDynamicDataTypeSupport *type_support = NULL;
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, type_support);
return -1;
}
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, type_support);
return -1;
}
/* Create DynamicData using TypeCode from Shapes.cxx
* If you are NOT using a type generated with rtiddsgen, you
* need to create this TypeCode from scratch.
*/
type_code = ShapeType_get_typecode();
if (type_code == NULL) {
printf("get_typecode error\n");
publisher_shutdown(participant, type_support);
return -1;
}
/* Create the Dynamic data type support object */
type_support = new DDSDynamicDataTypeSupport(type_code, props);
if (type_support == NULL) {
printf("constructor DynamicDataTypeSupport error\n");
publisher_shutdown(participant, type_support);
return -1;
}
/* Register type before creating topic */
type_name = EXAMPLE_TYPE_NAME;
retcode = type_support->register_type(participant, EXAMPLE_TYPE_NAME);
if (retcode != DDS_RETCODE_OK) {
printf("register_type error\n");
publisher_shutdown(participant, type_support);
return -1;
}
/* Make sure both publisher and subscriber share the same topic
* name.
* In the Shapes example: we are publishing a Square, which is the
* topic name. If you want to publish other shapes (Triangle or
* Circle), you just need to update the topic name. */
topic = participant->create_topic("Square", type_name,
DDS_TOPIC_QOS_DEFAULT, NULL /* listener */, DDS_STATUS_MASK_NONE);
if (topic == NULL) {
printf("create_topic error\n");
publisher_shutdown(participant, type_support);
return -1;
}
/* First, we create a generic DataWriter for our topic */
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, type_support);
return -1;
}
/* Then, to use DynamicData, we need to assign the generic
* DataWriter to a DynamicDataWriter, using
* DDS_DynamicDataWriter_narrow.
* The following narrow function should never fail, as it performs
* only a safe cast.
*/
DynamicData_writer = DDSDynamicDataWriter::narrow(writer);
if (DynamicData_writer == NULL) {
printf("DynamicData_writer narrow error\n");
publisher_shutdown(participant, type_support);
return -1;
}
/* Create an instance of the sparse data we are about to send */
data = type_support->create_data();
if (data == NULL) {
printf("create_data error\n");
publisher_shutdown(participant, type_support);
return -1;
}
/* Initialize the DynamicData object */
data->set_string("color", DDS_DYNAMIC_DATA_MEMBER_ID_UNSPECIFIED, "BLUE");
data->set_long("x", DDS_DYNAMIC_DATA_MEMBER_ID_UNSPECIFIED, 100);
data->set_long("y", DDS_DYNAMIC_DATA_MEMBER_ID_UNSPECIFIED, 100);
data->set_long("shapesize", DDS_DYNAMIC_DATA_MEMBER_ID_UNSPECIFIED, 30);
/* Main loop */
for (count = 0; (sample_count == 0) || (count < sample_count); ++count) {
printf("Sending shapesize %d\n", 30 + (count % 20));
printf("Sending x position %d\n", x_position);
/* Modify the shapesize from 30 to 50 */
retcode = data->set_long("shapesize",
DDS_DYNAMIC_DATA_MEMBER_ID_UNSPECIFIED, 30 + (count % 20));
if (retcode != DDS_RETCODE_OK) {
fprintf(stderr, "! Unable to set shapesize\n");
publisher_shutdown(participant, type_support);
return -1;
}
/* Modify the position */
retcode = data->set_long("x", DDS_DYNAMIC_DATA_MEMBER_ID_UNSPECIFIED,
x_position);
if (retcode != DDS_RETCODE_OK) {
fprintf(stderr, "! Unable to set x\n");
publisher_shutdown(participant, type_support);
return -1;
}
/* The x_position will be modified adding or substracting
* 2 to the previous x_position depending on the direction.
*/
x_position += (direction * 2);
/* The x_position will stay between 50 and 150 pixels.
* When the position is greater than 150 'direction' will be negative
* (moving to the left) and when it is lower than 50 'direction' will
* be possitive (moving to the right).
*/
if (x_position >= 150) {
direction = -1;
}
if (x_position <= 50) {
direction = 1;
}
/* Write data */
retcode = DynamicData_writer->write(*data, instance_handle);
if (retcode != DDS_RETCODE_OK) {
printf("write error %d\n", retcode);
publisher_shutdown(participant, type_support);
}
NDDSUtility::sleep(send_period);
}
/* Delete data sample */
retcode = type_support->delete_data(data);
if (retcode != DDS_RETCODE_OK) {
printf("ShapeTypeTypeSupport::delete_data error %d\n", retcode);
}
/* Delete all entities */
return publisher_shutdown(participant, type_support);
}
#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/dynamic_data_using_publisher_subscriber/c/Shapes_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.
******************************************************************************/
/* Shapes_subscriber.c
A subscription of data of type ShapeType using DynamicData
This file is derived from code automatically generated by the rtiddsgen
command:
rtiddsgen -language C -example <arch> Shapes.idl
If you are not using and IDL to generate the TypeCode,
you will need to create it manually. Follow other DynamicData
examples (such as NestedStruct one) to learn how to do it.
Example:
To run the example application on domain <domain_id>:
On UNIX systems:
objs/<arch>/Shapes_publisher <domain_id> <sample #>
objs/<arch>/Shapes_subscriber <domain_id> <sample #>
On Windows systems:
objs\<arch>\Shapes_publisher <domain_id> <sample #>
objs\<arch>\Shapes_subscriber <domain_id> <sample #>
*/
#include <stdio.h>
#include <stdlib.h>
#include "ndds/ndds_c.h"
#include "Shapes.h"
#define EXAMPLE_TYPE_NAME "ShapesType"
void ShapeTypeListener_on_requested_deadline_missed(void* listener_data,
DDS_DataReader* reader,
const struct DDS_RequestedDeadlineMissedStatus *status) {
}
void ShapeTypeListener_on_requested_incompatible_qos(void* listener_data,
DDS_DataReader* reader,
const struct DDS_RequestedIncompatibleQosStatus *status) {
}
void ShapeTypeListener_on_sample_rejected(void* listener_data,
DDS_DataReader* reader, const struct DDS_SampleRejectedStatus *status) {
}
void ShapeTypeListener_on_liveliness_changed(void* listener_data,
DDS_DataReader* reader,
const struct DDS_LivelinessChangedStatus *status) {
}
void ShapeTypeListener_on_sample_lost(void* listener_data,
DDS_DataReader* reader, const struct DDS_SampleLostStatus *status) {
}
void ShapeTypeListener_on_subscription_matched(void* listener_data,
DDS_DataReader* reader,
const struct DDS_SubscriptionMatchedStatus *status) {
}
void ShapeTypeListener_on_data_available(void* listener_data,
DDS_DataReader* reader) {
/* We need to create a DynamicDataReader to receive the DynamicData
* and a DynamicDataSeq to store there the available DynamicData received
*/
DDS_DynamicDataReader *DynamicData_reader = NULL;
struct DDS_DynamicDataSeq data_seq = DDS_SEQUENCE_INITIALIZER;
struct DDS_SampleInfoSeq info_seq = DDS_SEQUENCE_INITIALIZER;
DDS_ReturnCode_t retcode;
int i;
/* To use DynamicData, we need to assign the generic DataReader to
* a DynamicDataReader, using DDS_DynamicDataReader_narrow.
* The following narrow fuction should never fail, as it performs
* only a safe cast.
*/
DynamicData_reader = DDS_DynamicDataReader_narrow(reader);
if (DynamicData_reader == NULL) {
printf("DataReader narrow error\n");
return;
}
retcode = DDS_DynamicDataReader_take(DynamicData_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 < DDS_DynamicDataSeq_get_length(&data_seq); ++i) {
if (DDS_SampleInfoSeq_get_reference(&info_seq, i)->valid_data) {
DDS_DynamicData_print(
DDS_DynamicDataSeq_get_reference(&data_seq, i),
stdout, 1);
}
}
retcode = DDS_DynamicDataReader_return_loan(DynamicData_reader, &data_seq,
&info_seq);
if (retcode != DDS_RETCODE_OK) {
printf("return loan error %d\n", retcode);
}
DDS_DynamicDataSeq_finalize(&data_seq);
DDS_SampleInfoSeq_finalize(&info_seq);
}
/* Delete all entities */
static int subscriber_shutdown(DDS_DomainParticipant *participant,
struct DDS_DynamicDataTypeSupport *typeSupport) {
DDS_ReturnCode_t retcode;
int status = 0;
if (participant != NULL) {
if (typeSupport != NULL) {
DDS_DynamicDataTypeSupport_delete(typeSupport);
}
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 };
/* Dynamic Data parameters that we will need */
struct DDS_TypeCode *type_code = NULL;
struct DDS_DynamicDataTypeProperty_t props =
DDS_DynamicDataTypeProperty_t_INITIALIZER;
struct DDS_DynamicDataTypeSupport *type_support = NULL;
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, type_support);
return -1;
}
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, type_support);
return -1;
}
/* Create DynamicData using TypeCode from Shapes.c
* If you are NOT using a type generated with rtiddsgen, you
* need to create this TypeCode from scratch.
*/
type_code = ShapeType_get_typecode();
if (type_code == NULL) {
printf("get_typecode error\n");
subscriber_shutdown(participant, type_support);
return -1;
}
/* Create the Dynamic data type support object */
type_support = DDS_DynamicDataTypeSupport_new(type_code, &props);
if (type_support == NULL) {
fprintf(stderr, "! Unable to create dynamic data type support\n");
subscriber_shutdown(participant, type_support);
return -1;
}
/* Register the type before creating the topic */
type_name = EXAMPLE_TYPE_NAME;
retcode = DDS_DynamicDataTypeSupport_register_type(type_support,
participant, type_name);
if (retcode != DDS_RETCODE_OK) {
printf("register_type error %d\n", retcode);
subscriber_shutdown(participant, type_support);
return -1;
}
/* Make sure both publisher and subscriber share the same topic name.
* In the Shapes example: we are subscribing to a Square, wich is the
* topic name. If you want to publish other shapes (Triangle or Circle),
* you just need to update the topic name.
*/
topic = DDS_DomainParticipant_create_topic(participant, "Square", type_name,
&DDS_TOPIC_QOS_DEFAULT, NULL /* listener */, DDS_STATUS_MASK_NONE);
if (topic == NULL) {
printf("create_topic error\n");
subscriber_shutdown(participant, type_support);
return -1;
}
/* Set up a data reader listener */
reader_listener.on_requested_deadline_missed =
ShapeTypeListener_on_requested_deadline_missed;
reader_listener.on_requested_incompatible_qos =
ShapeTypeListener_on_requested_incompatible_qos;
reader_listener.on_sample_rejected = ShapeTypeListener_on_sample_rejected;
reader_listener.on_liveliness_changed =
ShapeTypeListener_on_liveliness_changed;
reader_listener.on_sample_lost = ShapeTypeListener_on_sample_lost;
reader_listener.on_subscription_matched =
ShapeTypeListener_on_subscription_matched;
reader_listener.on_data_available = ShapeTypeListener_on_data_available;
/* First, we create a generic DataReader for our topic */
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, type_support);
return -1;
}
/* Main loop */
for (count = 0; (sample_count == 0) || (count < sample_count); ++count) {
printf("ShapeType subscriber sleeping for %d sec...\n",
poll_period.sec);
NDDS_Utility_sleep(&poll_period);
}
/* Cleanup and delete all entities */
return subscriber_shutdown(participant, type_support);
}
#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/dynamic_data_using_publisher_subscriber/c/Shapes_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.
******************************************************************************/
/* Shapes_publisher.c
A publication of data of type ShapeType using DynamicData
This file is derived from code automatically generated by the rtiddsgen
command:
rtiddsgen -language C -example <arch> Shapes.idl
If you are not using an IDL to generate the TypeCode,
you will need to create it manually. Follow other DynamicData
examples (such as NestedStruct one) to learn how to do it.
Example:
To run the example application on domain <domain_id>:
On Unix:
objs/<arch>/Shapes_publisher <domain_id> <sample #>
objs/<arch>/Shapes_subscriber <domain_id> <sample #>
On Windows:
objs\<arch>\Shapes_publisher <domain_id> <sample #>
objs\<arch>\Shapes_subscriber <domain_id> <sample #>
*/
#include <stdio.h>
#include <stdlib.h>
#include "ndds/ndds_c.h"
#include "Shapes.h"
#define EXAMPLE_TYPE_NAME "ShapesType"
/* Delete all created entities */
static int publisher_shutdown(DDS_DomainParticipant *participant,
struct DDS_DynamicDataTypeSupport * type_support,
DDS_Boolean data_is_initialized, struct DDS_DynamicData *data) {
DDS_ReturnCode_t retcode;
int status = 0;
if (participant != NULL) {
if (data_is_initialized) {
DDS_DynamicData_finalize(data);
}
if (type_support != NULL) {
DDS_DynamicDataTypeSupport_delete(type_support);
}
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_ReturnCode_t retcode;
DDS_InstanceHandle_t instance_handle = DDS_HANDLE_NIL;
const char *type_name = NULL;
int count = 0;
struct DDS_Duration_t send_period = { 0, 100000000 }; /* 100 ms */
/*** Shape direction variables ***/
int direction = 1; /* 1 means left to right and -1, right to left */
int x_position = 50; /* 50 is the initial position */
/*** DDS ENTITIES ***/
DDS_DomainParticipant *participant = NULL;
DDS_Publisher *publisher = NULL;
DDS_Topic *topic = NULL;
DDS_DataWriter *writer = NULL;
/*** Dynamic Data parameters that we will need ***/
struct DDS_TypeCode *type_code = NULL;
struct DDS_DynamicData data;
DDS_Boolean data_is_initialized = DDS_BOOLEAN_FALSE;
DDS_DynamicDataWriter *DynamicData_writer = NULL;
struct DDS_DynamicDataTypeProperty_t props =
DDS_DynamicDataTypeProperty_t_INITIALIZER;
struct DDS_DynamicDataTypeSupport *type_support = NULL;
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, type_support, data_is_initialized,
&data);
return -1;
}
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, type_support, data_is_initialized,
&data);
return -1;
}
/* Create DynamicData using TypeCode from Shapes.c
* If you are NOT using a type generated with rtiddsgen, you
* need to create this TypeCode from scratch.
*/
type_code = ShapeType_get_typecode();
if (type_code == NULL) {
printf("get_typecode error\n");
publisher_shutdown(participant, type_support, data_is_initialized,
&data);
return -1;
}
/* Create the Dynamic Data TypeSupport object */
type_support = DDS_DynamicDataTypeSupport_new(type_code, &props);
if (type_support == NULL) {
fprintf(stderr, "! Unable to create dynamic data type support\n");
publisher_shutdown(participant, type_support, data_is_initialized,
&data);
return -1;
}
/* Register the type before creating the topic. */
type_name = EXAMPLE_TYPE_NAME;
retcode = DDS_DynamicDataTypeSupport_register_type(type_support,
participant, type_name);
if (retcode != DDS_RETCODE_OK) {
publisher_shutdown(participant, type_support, data_is_initialized,
&data);
return -1;
}
/* Make sure both publisher and subscriber share the same topic
* name.
* In the Shapes example: we are publishing a Square, which is the
* topic name. If you want to publish other shapes (Triangle or
* Circle), you just need to update the topic name. */
topic = DDS_DomainParticipant_create_topic(participant, "Square", type_name,
&DDS_TOPIC_QOS_DEFAULT, NULL /* listener */, DDS_STATUS_MASK_NONE);
if (topic == NULL) {
printf("create_topic error\n");
publisher_shutdown(participant, type_support, data_is_initialized,
&data);
return -1;
}
/* First, we create a generic DataWriter for our topic */
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, type_support, data_is_initialized,
&data);
return -1;
}
/* Then, to use DynamicData, we need to assign the generic
* DataWriter to a DynamicDataWriter, using
* DDS_DynamicDataWriter_narrow.
* The following narrow function should never fail, as it performs
* only a safe cast.
*/
DynamicData_writer = DDS_DynamicDataWriter_narrow(writer);
if (DynamicData_writer == NULL) {
fprintf(stderr, "! Unable to narrow data writer into "
"DDS_StringDataWriter\n");
publisher_shutdown(participant, type_support, data_is_initialized,
&data);
return -1;
}
/* Create an instance of the sparse data we are about to send */
data_is_initialized = DDS_DynamicData_initialize(&data, type_code,
&DDS_DYNAMIC_DATA_PROPERTY_DEFAULT);
if (!data_is_initialized) {
printf("DynamicData_initialize error\n");
publisher_shutdown(participant, type_support, data_is_initialized,
&data);
return -1;
}
/* Initialize the DynamicData object */
DDS_DynamicData_set_string(&data, "color",
DDS_DYNAMIC_DATA_MEMBER_ID_UNSPECIFIED, "BLUE");
DDS_DynamicData_set_long(&data, "x", DDS_DYNAMIC_DATA_MEMBER_ID_UNSPECIFIED,
0);
DDS_DynamicData_set_long(&data, "y", DDS_DYNAMIC_DATA_MEMBER_ID_UNSPECIFIED,
100);
DDS_DynamicData_set_long(&data, "shapesize",
DDS_DYNAMIC_DATA_MEMBER_ID_UNSPECIFIED, 30);
/* Main loop */
for (count = 0; (sample_count == 0) || (count < sample_count); ++count) {
printf("Sending shapesize %d\n", 30 + (count % 20));
printf("Sending x position %d\n", x_position);
/* Modify the shapesize from 30 to 50 */
retcode = DDS_DynamicData_set_long(&data, "shapesize",
DDS_DYNAMIC_DATA_MEMBER_ID_UNSPECIFIED, 30 + (count % 20));
if (retcode != DDS_RETCODE_OK) {
fprintf(stderr, "! Unable to set shapesize long\n");
publisher_shutdown(participant, type_support, data_is_initialized,
&data);
return -1;
}
/* Modify the position x from 50 to 150 */
retcode = DDS_DynamicData_set_long(&data, "x",
DDS_DYNAMIC_DATA_MEMBER_ID_UNSPECIFIED, x_position);
if (retcode != DDS_RETCODE_OK) {
fprintf(stderr, "! Unable to set x\n");
publisher_shutdown(participant, type_support, data_is_initialized,
&data);
return -1;
}
/* The x_position will be modified adding or substracting
* 2 to the previous x_position depending on the direction.
*/
x_position += (direction * 2);
/* The x_position will stay between 50 and 150 pixels.
* When the position is greater than 150 'direction' will be negative
* (moving to the left) and when it is lower than 50 'direction' will
* be possitive (moving to the right).
*/
if (x_position >= 150) {
direction = -1;
}
if (x_position <= 50) {
direction = 1;
}
/* Write data */
retcode = DDS_DynamicDataWriter_write(DynamicData_writer, &data,
&instance_handle);
if (retcode != DDS_RETCODE_OK) {
printf("write error %d\n", retcode);
publisher_shutdown(participant, type_support, data_is_initialized,
&data);
}
NDDS_Utility_sleep(&send_period);
}
/* Cleanup and delete delete all entities */
return publisher_shutdown(participant, type_support, data_is_initialized,
&data);
}
#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/dynamic_data_using_publisher_subscriber/c++11/Shapes_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/xtypes/DynamicDataTuples.hpp>
#include "Shapes.hpp"
using namespace dds::core;
using namespace dds::core::cond;
using namespace dds::core::xtypes;
using namespace dds::domain;
using namespace dds::topic;
using namespace dds::sub;
using namespace dds::sub::cond;
using namespace dds::sub::status;
void print_shape_data(const DynamicData& data)
{
// First method: using C++ tuples (C++11 only).
auto shape_tuple_data = rti::core::xtypes::get_tuple<
std::string, int32_t, int32_t, int32_t>(data);
std::cout << "\t color: " << std::get<0>(shape_tuple_data) << std::endl
<< "\t x: " << std::get<1>(shape_tuple_data) << std::endl
<< "\t y: " << std::get<2>(shape_tuple_data) << std::endl
<< "\t shapesize: " << std::get<3>(shape_tuple_data) << std::endl;
// Second method: using DynamicData getters.
std::cout << "\t color: " << data.value<std::string>("color") << std::endl
<< "\t x: " << data.value<int32_t>("x") << std::endl
<< "\t y: " << data.value<int32_t>("y") << std::endl
<< "\t shapesize: " << data.value<int32_t>("shapesize")
<< std::endl;
// Third method: automatic with the '<<' operator overload.
std::cout << data << std::endl;
}
void subscriber_main(int domain_id, int sample_count)
{
// Create the participant.
DomainParticipant participant(domain_id);
// Create DynamicData using the type defined in the IDL file.
const StructType& shape_type = rti::topic::dynamic_type<ShapeType>::get();
// If you want to create the type from code instead of using an IDL
// file with rtiddsgen, comment out the previous declaration and
// uncomment the following code.
// StructType shape_type("ShapeType");
// shape_type.add_member(Member("color", StringType(128)).key(true));
// shape_type.add_member(Member("x", primitive_type<int32_t>()));
// shape_type.add_member(Member("y", primitive_type<int32_t>()));
// shape_type.add_member(Member("shapesize", primitive_type<int32_t>()));
// Create a Topic -- and automatically register the type.
// Make sure both publisher and subscriber share the same topic name.
// In the Shapes example: we are subscribing to a Square, wich is the
// topic name. If you want to publish other shapes (Triangle or Circle),
// you just need to update the topic name.
Topic<DynamicData> topic(participant, "Square", shape_type);
// Create a DataReader (Subscriber created in-line).
DataReader<DynamicData> reader(Subscriber(participant), topic);
// Create a ReadCondition for any data on this reader and associate
// a handler.
int count = 0;
ReadCondition read_condition(
reader,
DataState::any(),
[&reader, &count]()
{
// Take all samples
LoanedSamples<DynamicData> samples = reader.take();
for (auto sample : samples){
if (sample.info().valid()){
count++;
// Print sample with different methods.
print_shape_data(sample.data());
}
}
}
);
// Create a WaitSet and attach the ReadCondition
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 << "ShapeType subscriber sleeping for 1 sec..." << std::endl;
waitset.dispatch(dds::core::Duration(1)); // Wait up to 1s 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;
}
return 0;
}
| cxx |
rticonnextdds-examples | data/projects/rticonnextdds-examples/dynamic_data_using_publisher_subscriber/c++11/Shapes_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 <rti/core/xtypes/DynamicDataTuples.hpp>
#include "Shapes.hpp"
using namespace dds::core;
using namespace dds::core::xtypes;
using namespace dds::domain;
using namespace dds::topic;
using namespace dds::pub;
void publisher_main(int domain_id, int sample_count)
{
// Create the participant.
DomainParticipant participant(domain_id);
// Create DynamicData using the type defined in the IDL file.
const StructType& shape_type = rti::topic::dynamic_type<ShapeType>::get();
// If you want to create the type from code instead of using an IDL
// file with rtiddsgen, comment out the previous declaration and
// uncomment the following code.
// StructType shape_type("ShapeType");
// shape_type.add_member(Member("color", StringType(128)).key(true));
// shape_type.add_member(Member("x", primitive_type<int32_t>()));
// shape_type.add_member(Member("y", primitive_type<int32_t>()));
// shape_type.add_member(Member("shapesize", primitive_type<int32_t>()));
// Create a Topic -- and automatically register the type.
// Make sure both publisher and subscriber share the same topic
// name. In the Shapes example: we are publishing a Square, which is the
// topic name. If you want to publish other shapes (Triangle or
// Circle), you just need to update the topic name.
Topic<DynamicData> topic(participant, "Square", shape_type);
// Create a DataReader (Subscriber created in-line).
DataWriter<DynamicData> writer(Publisher(participant), topic);
// Create an instance of DynamicData.
DynamicData shape_data(shape_type);
// Initialize the data values.
int direction = 1;
int x_position = 50;
int shape_size = 30;
// Set data with C++ tuples (C++11 only).
rti::core::xtypes::set_tuple(
shape_data,
std::make_tuple(std::string("BLUE"), x_position, 100, shape_size));
// Standard method with setters (C++03 compatible).
// shape_data.value<std::string>("color", "BLUE");
// shape_data.value("x", x_position);
// shape_data.value("y", 100);
// shape_data.value("shapesize", shape_size);
// Main loop
for (int count = 0; (sample_count == 0) || (count < sample_count); ++count){
// Modify and set the shape size from 30 to 50.
shape_size = 30 + (count % 20);
shape_data.value("shapesize", shape_size);
// Set the position X.
shape_data.value("x", x_position);
// Publish data.
std::cout << "Sending [shapesize=" << shape_size
<< ", x=" << x_position << "]" << std::endl;
writer.write(shape_data);
// Update the position X.
// It will be modified adding or substraction 2 to the previous value
// depending on the direction. The value will be between 50 and 150.
// When it reachs one border, the direction is inverted.
x_position += (direction * 2);
if (x_position >= 150) {
direction = -1;
} else if (x_position <= 50) {
direction = 1;
}
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 (std::exception ex) {
std::cout << "Exception caught: " << ex.what() << std::endl;
return -1;
}
return 0;
}
| cxx |
rticonnextdds-examples | data/projects/rticonnextdds-examples/persistence_service/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/persistence_service/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/persistence_service/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 "hello_world.h"
#include "hello_worldSupport.h"
#include "ndds/ndds_c.h"
#include <stdio.h>
#include <stdlib.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 |
rticonnextdds-examples | data/projects/rticonnextdds-examples/persistence_service/persistent_storage/c/hello_world_subscriber.c | /*******************************************************************************
(c) 2005-2014 Copyright, Real-Time Innovations, Inc. All rights reserved.
RTI grants Licensee a license to use, modify, compile, and create derivative
works of the Software. Licensee has the right to distribute object form only
for use with RTI products. The Software is provided "as is", with no warranty
of any type, including any warranty for fitness for any purpose. RTI is under
no obligation to maintain or support the Software. RTI shall not be liable for
any incidental or consequential damages arising out of the use or inability to
use the software.
******************************************************************************/
/* hello_world_subscriber.c
A subscription example
This file is derived from code automatically generated by the rtiddsgen
command:
rtiddsgen -language C -example <arch> hello_world.idl
Example subscription of type hello_world automatically generated by
'rtiddsgen'. To test them, follow these steps:
(1) Compile this file and the example publication.
(2) Start the subscription with the command
objs/<arch>/hello_world_subscriber <domain_id> <sample_count>
(3) Start the publication with the command
objs/<arch>/hello_world_publisher <domain_id> <sample_count>
(4) [Optional] Specify the list of discovery initial peers and
multicast receive addresses via an environment variable or a file
(in the current working directory) called NDDS_DISCOVERY_PEERS.
You can run any number of publishers and subscribers programs, and can
add and remove them dynamically from the domain.
Example:
To run the example application on domain <domain_id>:
On UNIX systems:
objs/<arch>/hello_world_publisher <domain_id>
objs/<arch>/hello_world_subscriber <domain_id>
On Windows systems:
objs\<arch>\hello_world_publisher <domain_id>
objs\<arch>\hello_world_subscriber <domain_id>
*/
#include "hello_world.h"
#include "hello_worldSupport.h"
#include "ndds/ndds_c.h"
#include <stdio.h>
#include <stdlib.h>
/******************************************************************************
Macros to read input parameters
******************************************************************************/
#define READ_INTEGER_PARAM(parameter, outValue) \
if (!strcmp(argv[i], parameter)) { \
if (i + 1 >= argc) { \
printf("%s", syntax); \
return 1; \
} \
i++; \
outValue = atoi(argv[i]); \
i++; \
continue; \
}
#define READ_STRING_PARAM(parameter, outValue) \
if (!strcmp(argv[i], parameter)) { \
if (i + 1 >= argc) { \
printf("%s", syntax); \
return 1; \
} \
i++; \
outValue = argv[i]; \
i++; \
continue; \
}
void hello_worldListener_on_requested_deadline_missed(
void *listener_data,
DDS_DataReader *reader,
const struct DDS_RequestedDeadlineMissedStatus *status)
{
}
void hello_worldListener_on_requested_incompatible_qos(
void *listener_data,
DDS_DataReader *reader,
const struct DDS_RequestedIncompatibleQosStatus *status)
{
}
void hello_worldListener_on_sample_rejected(
void *listener_data,
DDS_DataReader *reader,
const struct DDS_SampleRejectedStatus *status)
{
}
void hello_worldListener_on_liveliness_changed(
void *listener_data,
DDS_DataReader *reader,
const struct DDS_LivelinessChangedStatus *status)
{
}
void hello_worldListener_on_sample_lost(
void *listener_data,
DDS_DataReader *reader,
const struct DDS_SampleLostStatus *status)
{
}
void hello_worldListener_on_subscription_matched(
void *listener_data,
DDS_DataReader *reader,
const struct DDS_SubscriptionMatchedStatus *status)
{
}
void hello_worldListener_on_data_available(
void *listener_data,
DDS_DataReader *reader)
{
hello_worldDataReader *hello_world_reader = NULL;
struct hello_worldSeq data_seq = DDS_SEQUENCE_INITIALIZER;
struct DDS_SampleInfoSeq info_seq = DDS_SEQUENCE_INITIALIZER;
DDS_ReturnCode_t retcode;
int i;
hello_world_reader = hello_worldDataReader_narrow(reader);
if (hello_world_reader == NULL) {
printf("DataReader narrow error\n");
return;
}
retcode = hello_worldDataReader_take(
hello_world_reader,
&data_seq,
&info_seq,
DDS_LENGTH_UNLIMITED,
DDS_ANY_SAMPLE_STATE,
DDS_ANY_VIEW_STATE,
DDS_ANY_INSTANCE_STATE);
if (retcode == DDS_RETCODE_NO_DATA) {
return;
} else if (retcode != DDS_RETCODE_OK) {
printf("take error %d\n", retcode);
return;
}
for (i = 0; i < hello_worldSeq_get_length(&data_seq); ++i) {
if (DDS_SampleInfoSeq_get_reference(&info_seq, i)->valid_data) {
hello_worldTypeSupport_print_data(
hello_worldSeq_get_reference(&data_seq, i));
}
}
retcode = hello_worldDataReader_return_loan(
hello_world_reader,
&data_seq,
&info_seq);
if (retcode != DDS_RETCODE_OK) {
printf("return loan error %d\n", retcode);
}
}
/* Delete all entities */
static int subscriber_shutdown(DDS_DomainParticipant *participant)
{
DDS_ReturnCode_t retcode;
int status = 0;
if (participant != NULL) {
retcode = DDS_DomainParticipant_delete_contained_entities(participant);
if (retcode != DDS_RETCODE_OK) {
printf("delete_contained_entities error %d\n", retcode);
status = -1;
}
retcode = DDS_DomainParticipantFactory_delete_participant(
DDS_TheParticipantFactory,
participant);
if (retcode != DDS_RETCODE_OK) {
printf("delete_participant error %d\n", retcode);
status = -1;
}
}
/* RTI Connext provides the finalize_instance() method on
domain participant factory for users who want to release memory used
by the participant factory. Uncomment the following block of code for
clean destruction of the singleton. */
/*
retcode = DDS_DomainParticipantFactory_finalize_instance();
if (retcode != DDS_RETCODE_OK) {
printf("finalize_instance error %d\n", retcode);
status = -1;
}
*/
return status;
}
static int subscriber_main(int domain_id, int sample_count, int drs)
{
DDS_DomainParticipant *participant = NULL;
DDS_Subscriber *subscriber = NULL;
DDS_Topic *topic = NULL;
struct DDS_DataReaderListener reader_listener =
DDS_DataReaderListener_INITIALIZER;
struct DDS_DataReaderQos reader_qos = DDS_DataReaderQos_INITIALIZER;
DDS_DataReader *reader = NULL;
DDS_ReturnCode_t retcode;
const char *type_name = NULL;
int count = 0;
struct DDS_Duration_t poll_period = { 4, 0 };
/* To customize participant QoS, use
the configuration file USER_QOS_PROFILES.xml */
participant = DDS_DomainParticipantFactory_create_participant(
DDS_TheParticipantFactory,
domain_id,
&DDS_PARTICIPANT_QOS_DEFAULT,
NULL /* listener */,
DDS_STATUS_MASK_NONE);
if (participant == NULL) {
printf("create_participant error\n");
subscriber_shutdown(participant);
return -1;
}
/* To customize subscriber QoS, use
the configuration file USER_QOS_PROFILES.xml */
subscriber = DDS_DomainParticipant_create_subscriber(
participant,
&DDS_SUBSCRIBER_QOS_DEFAULT,
NULL /* listener */,
DDS_STATUS_MASK_NONE);
if (subscriber == NULL) {
printf("create_subscriber error\n");
subscriber_shutdown(participant);
return -1;
}
/* Register the type before creating the topic */
type_name = hello_worldTypeSupport_get_type_name();
retcode = hello_worldTypeSupport_register_type(participant, type_name);
if (retcode != DDS_RETCODE_OK) {
printf("register_type error %d\n", retcode);
subscriber_shutdown(participant);
return -1;
}
/* To customize topic QoS, use
the configuration file USER_QOS_PROFILES.xml */
topic = DDS_DomainParticipant_create_topic(
participant,
"Example hello_world",
type_name,
&DDS_TOPIC_QOS_DEFAULT,
NULL /* listener */,
DDS_STATUS_MASK_NONE);
if (topic == NULL) {
printf("create_topic error\n");
subscriber_shutdown(participant);
return -1;
}
/* Set up a data reader listener */
reader_listener.on_requested_deadline_missed =
hello_worldListener_on_requested_deadline_missed;
reader_listener.on_requested_incompatible_qos =
hello_worldListener_on_requested_incompatible_qos;
reader_listener.on_sample_rejected = hello_worldListener_on_sample_rejected;
reader_listener.on_liveliness_changed =
hello_worldListener_on_liveliness_changed;
reader_listener.on_sample_lost = hello_worldListener_on_sample_lost;
reader_listener.on_subscription_matched =
hello_worldListener_on_subscription_matched;
reader_listener.on_data_available = hello_worldListener_on_data_available;
/* If you use Durable Reader State, you need to set up several properties.
* In this example, we have modified them using a QoS XML profile. See
* further details in USER_QOS_PROFILES.xml.
*/
if (drs == 1) {
reader = DDS_Subscriber_create_datareader_with_profile(
subscriber,
DDS_Topic_as_topicdescription(topic),
"persistence_example_Library",
"durable_reader_state_Profile",
&reader_listener,
DDS_STATUS_MASK_ALL);
if (reader == NULL) {
printf("create_datareader error\n");
subscriber_shutdown(participant);
return -1;
}
} else {
reader = DDS_Subscriber_create_datareader_with_profile(
subscriber,
DDS_Topic_as_topicdescription(topic),
"persistence_example_Library",
"persistence_service_Profile",
&reader_listener,
DDS_STATUS_MASK_ALL);
if (reader == NULL) {
printf("create_datareader error\n");
subscriber_shutdown(participant);
return -1;
}
}
/* Main loop */
for (count = 0; (sample_count == 0) || (count < sample_count); ++count) {
printf("hello_world subscriber sleeping for %d sec...\n",
poll_period.sec);
NDDS_Utility_sleep(&poll_period);
}
/* Cleanup and delete all entities */
return subscriber_shutdown(participant);
}
int main(int argc, char *argv[])
{
int domain_id = 0;
int drs = 0;
int i;
char syntax[1024];
int sample_count = 0; /* infinite loop */
sprintf(syntax,
"%s [options] \n\
-domain_id <domain ID> (default: 0)\n\
-sample_count <sample_count> (default: infinite => 0) \n\
-drs <1|0> Enable/Disable durable reader state (default: 0)\n",
argv[0]);
for (i = 1; i < argc;) {
READ_INTEGER_PARAM("-sample_count", sample_count);
READ_INTEGER_PARAM("-domain_id", domain_id);
READ_INTEGER_PARAM("-drs", drs);
printf("%s", syntax);
return 0;
}
/* Uncomment this to turn on additional logging
NDDS_Config_Logger_set_verbosity_by_category(
NDDS_Config_Logger_get_instance(),
NDDS_CONFIG_LOG_CATEGORY_API,
NDDS_CONFIG_LOG_VERBOSITY_STATUS_ALL);
*/
return subscriber_main(domain_id, sample_count, drs);
}
#ifdef RTI_VX653
const unsigned char *__ctype = NULL;
void usrAppInit()
{
#ifdef USER_APPL_INIT
USER_APPL_INIT; /* for backwards compatibility */
#endif
/* add application specific code here */
taskSpawn(
"sub",
RTI_OSAPI_THREAD_PRIORITY_NORMAL,
0x8,
0x150000,
(FUNCPTR) subscriber_main,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0);
}
#endif
| c |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.