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/logging_config/c/logging_publisher.c | /*
* (c) Copyright, Real-Time Innovations, 2021. All rights reserved.
* RTI grants Licensee a license to use, modify, compile, and create derivative
* works of the software solely for use with RTI Connext DDS. Licensee may
* redistribute copies of the software provided that all such copies are subject
* to this license. The software is provided "as is", with no warranty of any
* type, including any warranty for fitness for any purpose. RTI is under no
* obligation to maintain or support the software. RTI shall not be liable for
* any incidental or consequential damages arising out of the use or inability
* to use the software.
*/
/* logging_publisher.c
A publication of data of type logging
This file is derived from code automatically generated by the rtiddsgen
command:
rtiddsgen -language C -example <arch> logging.idl
Example publication of type logging automatically generated by
'rtiddsgen'. To test it, follow these steps:
(1) Compile this file and the example subscription.
(2) Start the subscription on the same domain used for RTI Connext
(3) Start the publication on the same domain used for RTI Connext
(4) [Optional] Specify the list of discovery initial peers and
multicast receive addresses via an environment variable or a file
(in the current working directory) called NDDS_DISCOVERY_PEERS.
You can run any number of publisher and subscriber programs, and can
add and remove them dynamically from the domain.
*/
#include <stdio.h>
#include <stdlib.h>
#include "ndds/ndds_c.h"
#include "logging.h"
#include "loggingSupport.h"
/* Delete all entities */
static int publisher_shutdown(
DDS_DomainParticipant *participant)
{
DDS_ReturnCode_t retcode;
int status = 0;
if (participant != NULL) {
retcode = DDS_DomainParticipant_delete_contained_entities(participant);
if (retcode != DDS_RETCODE_OK) {
fprintf(stderr, "delete_contained_entities error %d\n", retcode);
status = -1;
}
retcode = DDS_DomainParticipantFactory_delete_participant(
DDS_TheParticipantFactory, participant);
if (retcode != DDS_RETCODE_OK) {
fprintf(stderr, "delete_participant error %d\n", retcode);
status = -1;
}
}
/* RTI Data Distribution Service provides finalize_instance() method on
domain participant factory for people who want to release memory used
by the participant factory. Uncomment the following block of code for
clean destruction of the singleton. */
/*
retcode = DDS_DomainParticipantFactory_finalize_instance();
if (retcode != DDS_RETCODE_OK) {
fprintf(stderr, "finalize_instance error %d\n", retcode);
status = -1;
}
*/
return status;
}
int publisher_main(int domainId, int sample_count)
{
DDS_DomainParticipant *participant = NULL;
DDS_Publisher *publisher = NULL;
DDS_Topic *topic = NULL;
DDS_DataWriter *writer = NULL;
loggingDataWriter *logging_writer = NULL;
logging *instance = NULL;
DDS_ReturnCode_t retcode;
DDS_InstanceHandle_t instance_handle = DDS_HANDLE_NIL;
const char *type_name = NULL;
int count = 0;
struct DDS_Time_t sourceTimestamp = {0, 0};
/* To customize participant QoS, use
the configuration file USER_QOS_PROFILES.xml */
participant = DDS_DomainParticipantFactory_create_participant(
DDS_TheParticipantFactory, domainId, &DDS_PARTICIPANT_QOS_DEFAULT,
NULL /* listener */, DDS_STATUS_MASK_NONE);
if (participant == NULL) {
fprintf(stderr, "create_participant error\n");
publisher_shutdown(participant);
return -1;
}
/*
* Start - modifying the generated example to showcase the usage of
* the Logging API.
*/
/*
* Set NDDS_CONFIG_LOG_VERBOSITY_WARNING NDDS_Config_LogVerbosity.
* Set NDDS_CONFIG_LOG_PRINT_FORMAT_MAXIMAL NDDS_Config_LogPrintFormat
* for NDDS_CONFIG_LOG_LEVEL_WARNING.
*/
NDDS_Config_Logger_set_verbosity(
NDDS_Config_Logger_get_instance(),
NDDS_CONFIG_LOG_VERBOSITY_WARNING);
if (!NDDS_Config_Logger_set_print_format_by_log_level(
NDDS_Config_Logger_get_instance(),
NDDS_CONFIG_LOG_PRINT_FORMAT_MAXIMAL,
NDDS_CONFIG_LOG_LEVEL_WARNING)) {
fprintf(stderr, "NDDS_Config_Logger_set_print_format_by_log_level error\n");
publisher_shutdown(participant);
return -1;
}
/* To customize publisher QoS, use
the configuration file USER_QOS_PROFILES.xml */
publisher = DDS_DomainParticipant_create_publisher(
participant, &DDS_PUBLISHER_QOS_DEFAULT, NULL /* listener */,
DDS_STATUS_MASK_NONE);
if (publisher == NULL) {
fprintf(stderr, "create_publisher error\n");
publisher_shutdown(participant);
return -1;
}
/* Register type before creating topic */
type_name = loggingTypeSupport_get_type_name();
retcode = loggingTypeSupport_register_type(
participant, type_name);
if (retcode != DDS_RETCODE_OK) {
fprintf(stderr, "register_type error %d\n", retcode);
publisher_shutdown(participant);
return -1;
}
/* To customize topic QoS, use
the configuration file USER_QOS_PROFILES.xml */
topic = DDS_DomainParticipant_create_topic(
participant, "Example logging",
type_name, &DDS_TOPIC_QOS_DEFAULT, NULL /* listener */,
DDS_STATUS_MASK_NONE);
if (topic == NULL) {
fprintf(stderr, "create_topic error\n");
publisher_shutdown(participant);
return -1;
}
/* To customize data writer QoS, use
the configuration file USER_QOS_PROFILES.xml */
writer = DDS_Publisher_create_datawriter(
publisher, topic,
&DDS_DATAWRITER_QOS_DEFAULT, NULL /* listener */, DDS_STATUS_MASK_NONE);
if (writer == NULL) {
fprintf(stderr, "create_datawriter error\n");
publisher_shutdown(participant);
return -1;
}
logging_writer = loggingDataWriter_narrow(writer);
if (logging_writer == NULL) {
fprintf(stderr, "DataWriter narrow error\n");
publisher_shutdown(participant);
return -1;
}
/* Create data sample for writing */
instance = loggingTypeSupport_create_data_ex(DDS_BOOLEAN_TRUE);
if (instance == NULL) {
fprintf(stderr, "loggingTypeSupport_create_data error\n");
publisher_shutdown(participant);
return -1;
}
/* Write data */
retcode = loggingDataWriter_write(
logging_writer, instance, &instance_handle);
if (retcode != DDS_RETCODE_OK) {
fprintf(stderr, "write error %d\n", retcode);
}
/*
* Force a warning by writing a sample where the source time stamp is older
* than that of a previously sent sample. When using
* DDS_BY_SOURCE_TIMESTAMP_DESTINATIONORDER_QOS: If source timestamp is
* older than in previous write a warnings message will be logged.
*/
retcode = loggingDataWriter_write_w_timestamp(
logging_writer, instance, &instance_handle, &sourceTimestamp);
if (retcode != DDS_RETCODE_BAD_PARAMETER) {
fprintf(stderr, "write error %d\n", retcode);
}
/*
* End - modifying the generated example to showcase the usage of
* the Logging API.
*/
/* Delete data sample */
retcode = loggingTypeSupport_delete_data_ex(instance, DDS_BOOLEAN_TRUE);
if (retcode != DDS_RETCODE_OK) {
fprintf(stderr, "loggingTypeSupport_delete_data error %d\n", retcode);
}
/* Cleanup and delete delete all entities */
return publisher_shutdown(participant);
}
int main(int argc, char *argv[])
{
int domain_id = 0;
int sample_count = 0; /* infinite loop */
if (argc >= 2) {
domain_id = atoi(argv[1]);
}
if (argc >= 3) {
sample_count = atoi(argv[2]);
}
return publisher_main(domain_id, sample_count);
}
| c |
rticonnextdds-examples | data/projects/rticonnextdds-examples/connext_dds/logging_config/c++11/application.hpp | /*
* (c) Copyright, Real-Time Innovations, 2021. All rights reserved.
* RTI grants Licensee a license to use, modify, compile, and create derivative
* works of the software solely for use with RTI Connext DDS. Licensee may
* redistribute copies of the software provided that all such copies are subject
* to this license. The software is provided "as is", with no warranty of any
* type, including any warranty for fitness for any purpose. RTI is under no
* obligation to maintain or support the software. RTI shall not be liable for
* any incidental or consequential damages arising out of the use or inability
* to use the software.
*/
#ifndef APPLICATION_HPP
#define APPLICATION_HPP
#include <iostream>
#include <csignal>
#include <dds/core/ddscore.hpp>
namespace application {
// Catch control-C and tell application to shut down
bool shutdown_requested = false;
inline void stop_handler(int)
{
shutdown_requested = true;
std::cout << "preparing to shut down..." << std::endl;
}
inline void setup_signal_handlers()
{
signal(SIGINT, stop_handler);
signal(SIGTERM, stop_handler);
}
enum class ParseReturn {
ok,
failure,
exit
};
struct ApplicationArguments {
ParseReturn parse_result;
unsigned int domain_id;
unsigned int sample_count;
rti::config::Verbosity verbosity;
ApplicationArguments(
ParseReturn parse_result_param,
unsigned int domain_id_param,
unsigned int sample_count_param,
rti::config::Verbosity verbosity_param)
: parse_result(parse_result_param),
domain_id(domain_id_param),
sample_count(sample_count_param),
verbosity(verbosity_param) {}
};
// Parses application arguments for example.
inline ApplicationArguments parse_arguments(int argc, char *argv[])
{
int arg_processing = 1;
bool show_usage = false;
ParseReturn parse_result = ParseReturn::ok;
unsigned int domain_id = 0;
unsigned int sample_count = (std::numeric_limits<unsigned int>::max)();
rti::config::Verbosity verbosity(rti::config::Verbosity::EXCEPTION);
while (arg_processing < argc) {
if ((argc > arg_processing + 1)
&& (strcmp(argv[arg_processing], "-d") == 0
|| strcmp(argv[arg_processing], "--domain") == 0)) {
domain_id = atoi(argv[arg_processing + 1]);
arg_processing += 2;
} else if ((argc > arg_processing + 1)
&& (strcmp(argv[arg_processing], "-s") == 0
|| strcmp(argv[arg_processing], "--sample-count") == 0)) {
sample_count = atoi(argv[arg_processing + 1]);
arg_processing += 2;
} else if ((argc > arg_processing + 1)
&& (strcmp(argv[arg_processing], "-v") == 0
|| strcmp(argv[arg_processing], "--verbosity") == 0)) {
verbosity =
static_cast<rti::config::Verbosity::inner_enum>(
atoi(argv[arg_processing + 1]));
arg_processing += 2;
} else if (strcmp(argv[arg_processing], "-h") == 0
|| strcmp(argv[arg_processing], "--help") == 0) {
std::cout << "Example application." << std::endl;
show_usage = true;
parse_result = ParseReturn::exit;
break;
} else {
std::cout << "Bad parameter." << std::endl;
show_usage = true;
parse_result = ParseReturn::failure;
break;
}
}
if (show_usage) {
std::cout << "Usage:\n"\
" -d, --domain <int> Domain ID this application will\n" \
" subscribe in. \n"
" Default: 0\n"\
" -s, --sample_count <int> Number of samples to receive before\n"\
" cleanly shutting down. \n"
" Default: infinite\n"
" -v, --verbosity <int> How much debugging output to show.\n"\
" Range: 0-5 \n"
" Default: 0"
<< std::endl;
}
return ApplicationArguments(parse_result, domain_id, sample_count, verbosity);
}
} // namespace application
#endif // APPLICATION_HPP | hpp |
rticonnextdds-examples | data/projects/rticonnextdds-examples/connext_dds/logging_config/c++11/logging_publisher.cxx | /*
* (c) Copyright, Real-Time Innovations, 2021. All rights reserved.
* RTI grants Licensee a license to use, modify, compile, and create derivative
* works of the software solely for use with RTI Connext DDS. Licensee may
* redistribute copies of the software provided that all such copies are subject
* to this license. The software is provided "as is", with no warranty of any
* type, including any warranty for fitness for any purpose. RTI is under no
* obligation to maintain or support the software. RTI shall not be liable for
* any incidental or consequential damages arising out of the use or inability
* to use the software.
*/
#include <iostream>
#include <dds/pub/ddspub.hpp>
#include <rti/util/util.hpp> // for sleep()
#include <rti/config/Logger.hpp> // for logging
// alternatively, to include all the standard APIs:
// <dds/dds.hpp>
// or to include both the standard APIs and extensions:
// <rti/rti.hpp>
//
// For more information about the headers and namespaces, see:
// https://community.rti.com/static/documentation/connext-dds/6.1.0/doc/api/connext_dds/api_cpp2/group__DDSNamespaceModule.html
// For information on how to use extensions, see:
// https://community.rti.com/static/documentation/connext-dds/6.1.0/doc/api/connext_dds/api_cpp2/group__DDSCpp2Conventions.html
#include "application.hpp" // for command line parsing and ctrl-c
#include "logging.hpp"
void run_publisher_application(unsigned int domain_id, unsigned int sample_count)
{
// DDS objects behave like shared pointers or value types
// (see https://community.rti.com/static/documentation/connext-dds/6.1.0/doc/api/connext_dds/api_cpp2/group__DDSCpp2Conventions.html)
// Start communicating in a domain, usually one participant per application
dds::domain::DomainParticipant participant(domain_id);
// Create a Topic with a name and a datatype
dds::topic::Topic<logging> topic(participant, "Example logging");
// Create a Publisher
dds::pub::Publisher publisher(participant);
/*
* Start - modifying the generated example to showcase the usage of
* the Logging API.
*/
/*
* Set NDDS_CONFIG_LOG_VERBOSITY_WARNING NDDS_Config_LogVerbosity.
* Set NDDS_CONFIG_LOG_PRINT_FORMAT_MAXIMAL NDDS_Config_LogPrintFormat
* for NDDS_CONFIG_LOG_LEVEL_WARNING.
*/
rti::config::Logger::instance().verbosity(rti::config::Verbosity::WARNING);
rti::config::Logger::instance().print_format_by_log_level(
rti::config::PrintFormat::MAXIMAL,
rti::config::LogLevel::WARNING);
// Create a DataWriter with default QoS
dds::pub::DataWriter<logging> writer(publisher, topic);
logging data;
writer.write(data);
/*
* Force a warning by writing a sample where the source time stamp is older
* than that of a previously sent sample. When using
* DDS_BY_SOURCE_TIMESTAMP_DESTINATIONORDER_QOS: If source timestamp is
* older than in previous write a warnings message will be logged.
*/
writer.write(data, dds::core::null_type(), dds::core::Time(0));
}
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/custom_transport/c/FileTransport.c | /*******************************************************************************
(c) 2005-2014 Copyright, Real-Time Innovations, Inc. All rights reserved.
RTI grants Licensee a license to use, modify, compile, and create derivative
works of the Software. Licensee has the right to distribute object form only
for use with RTI products. The Software is provided "as is", with no warranty
of any type, including any warranty for fitness for any purpose. RTI is under
no obligation to maintain or support the Software. RTI shall not be liable for
any incidental or consequential damages arising out of the use or inability to
use the software.
******************************************************************************/
/* $Id: Intra.c,v 1.20 2008/10/22 19:16:46 jim Exp $
(c) Copyright, Real-Time Innovations, $Date: 2008/10/22 19:16:46 $.
All rights reserved.
No duplications, whole or partial, manual or electronic, may be made
without express written permission. Any such copies, or
revisions thereof, must display this notice unaltered.
This code contains trade secrets of Real-Time Innovations, Inc.
modification history
------------ -------
18apr2013,gpc Written
=========================================================================*/
#include "signal.h"
#include "sys/errno.h"
#include "sys/stat.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "ndds/ndds_c.h"
#include "ndds/osapi/osapi_process.h"
#include "FileTransport.h"
/* =====================================================================
* FILE Transport-Plugin
*
* See:
* http://community.rti.com/rti-doc/500/RTI_Transport_Plugin_5.0.0/doc/html/index.html
*
* for general documentation on the RTI Connext DDS Transport Plugin API
*
* Overview:
* --------
*
* The FileTransport Plugin is intended as an example of how to use the
* the transport plugin API. The emphasis is on simplicity and
* understandability. There has been no effort to make this a "real"
* transport with any reasonable performance. Rather the goal was to use
* simple APIs for communications that would not distract from the APIs
* required to interface with the Connext DDS Core.
*
* The transport is limited to communicate between computers that have
* access to a common file-system.
*
* The transport was implemented for Unix systems (Linux, MacOSX) in that
* it uses some Unix system calls to do things like lock files and read/write
* bytes to the file. It should be possible to port to other operating systems
* as long as they offer similar functionality.
*
* Design:
* ------
*
* The FileTransport uses simple files for communication. Each address/port
* combination maps to a separate file placed in an agreed location in the
* file-system. To send to an address/port the transport opens the file and
* appends to the end. To receive, the transport opens the file and reads
* whatever was written beyond the position previously read.
*
* The access to the files is serialized using file locking. So that multiple
* applications can send "simultaneously" to the same address/port and the
* bytes sent are serialized in the corresponding file. The receiver also
* used file-locking to ensure it does not read from a file that is being
* concurrently updated.
*
* The "receive" operation on the TransportPlugin is required to block until
* data is available. To keep things simple the FileTransport implements
* this by polling the file to see if there were changes and if not
* sleeping 1 second before checking again. This is obviously not efficient
* but it keep the code simple which is the main goal.
*
* The transport can be configured via properties. These properties control
* the location in the file-system where the files are placed, the network
* address of the transport, and the tracing verbosity.
*
* A single participant can instantiate more then one FileTransports, each
* should be given a different name and network address.
*
* Configuration
* -------------
*
* The simplest way to load and configure the transport is do it using the
* DomainParticipantQos and moreover specify the DomainParticipantQos using
* the XML file USER_QOS_PROFILES.xml that is automatically loaded by the
* application.
*
* You can find the USER_QOS_PROFILES.xml used with this example in the
* same directoryRoot where this source file is.
*
* Properties:
* ----------
*
* In this properties the string "myPlugin" represents an arbitrary name that
* is given in order to name a particular instantiation of the transport plugin
* such that it can be distinguished from other instantiations. The choice of
* name is arbitrary as long as the same name is used consistenty in all the
* properties that configure a particular transport instance.
*
* Property: Meaning:
* ds.transport.load_plugins Property common to all transport
* plugins used to indicate there is a new plugin to load and give it a name (in
* this example we assume the name chosen is "myPlugin" )
*
* dds.transport.FILE.myPlugin.library Defines the name of the library
* that contains the plugin
* implementation for the plugin named in the load_plugins property
*
* dds.transport.FILE.myPlugin.create_function Defines the name of the
* entry-function in the library defined by the previous property. This function
* must conform to the signature:
*
* NDDS_Transport_Plugin*
* TransportPluginCreateFunctionName( NDDS_Transport_Address_t
* *default_network_address_out, const struct DDS_PropertyQosPolicy
* *property_in);
*
* dds.transport.FILE.myPlugin.address The network address given to the
* instance of the transport plugin. Each FILE plugin instance can have a single
* network address. This is also propagated via discovery and must be used in
* the NDDS_DISCOVERY_PEERS environment variable. By default: "1.1.1.1"
*
* dds.transport.FILE.myPlugin.dirname The 'home' directoryRoot under
* which the files used to hold the received messages are written By default:
* "/tmp/dds/<address>"
*
* ===================================================================== */
#define NDDS_Transport_FILE_DIRROOT "/tmp/dds"
#define NDDS_Transport_FILE_DIRBASE NDDS_Transport_FILE_DIRROOT "/FileTransport"
/* Max length of the signature message is placed as the first message to
* mark/identify how the file was created
*/
#define NDDS_Transport_FILE_SIGNATURE_MAX_LEN (256)
/* The NDDS_Transport_RecvResource represents the state needed to receive
* information to a given address/port. It is intended to be defined
* by each transport plugin implementation. In the case of UDP the
* NDDS_Transport_RecvResource would wrap a receive socket bound to
* that port.
*
* NDDS_Transport_RecvResource_FILE is created by the operation
* NDDS_Transport_FILE_create_recvresource_rrEA()
*/
struct NDDS_Transport_RecvResource_FILE {
/* The file associated with the resource. It is kept open in read mode */
FILE *_file;
/* The port number associated with the resource */
int _portNum;
int _fileDescriptor;
int _receiveMessageCount;
};
/* The NDDS_Transport_SendResource represents the state needed to send
* information to a given address/port. It is intended to be defined
* by each transport plugin implementation. In the case of UDP the
* NDDS_Transport_SendResource would wrap a send socket.
*
* NDDS_Transport_SendResource_FILE is created by the operation
* NDDS_Transport_FILE_create_sendresource_rrEA()
*/
struct NDDS_Transport_SendResource_FILE {
/* The destination port number */
int _portNum;
/* The destination address */
NDDS_Transport_Address_t _address;
/* The file name associated with the resource */
char _fileName[NDDS_TRANSPORT_FILE_MAX_FILEPATH_LEN];
int _sendMessageCount;
};
/* The NDDS_Transport_Plugin structure is intended to be implemented in
* a different way by each transport plugin implementation.
*
* NDDS_Transport_Pugin_FILE represents the state of the transport as it
* it instantiated. It contains any necessary resources that would
* be required to create send and receive resources.
*
* NDDS_Transport_Pugin_FILE must extend the NDDS_Transport_Plugin structure
* by including it as its fist member with the conventional name "_parent"
*
*/
struct NDDS_Transport_FILE {
NDDS_Transport_Plugin parent; /* must be first entry! */
struct NDDS_Transport_FILE_Property_t _property;
char *_buffer;
};
/* ================================================================= */
/* Debugging utilities */
/* ================================================================= */
/* ----------------------------------------------------------------- */
/* Test whether the transport us enabled logging at level 1 */
#define NDDS_Transport_Log1Enabled(self) (self->_property.trace_level >= 1)
#define NDDS_Transport_Log2Enabled(self) (self->_property.trace_level >= 2)
/* ----------------------------------------------------------------- */
/* Conditionally Log a message id the transport us enabled logging at level 1 */
#define NDDS_Transport_Log0printf printf
#define NDDS_Transport_Log1print(self, message) \
if (NDDS_Transport_Log1Enabled(self)) \
printf("%s: %s\n", METHOD_NAME, message);
#define NDDS_Transport_Log2print(self, message) \
if (NDDS_Transport_Log2Enabled(self)) \
printf("%s: %s\n", METHOD_NAME, message);
/* ----------------------------------------------------------------- */
/* Utility function to print NDDS_Transport_Address_t and NDDS_Transport_Port_t
*/
static void NDDS_Transport_FILE_print_address(
const NDDS_Transport_Address_t *address_in,
const NDDS_Transport_Port_t port_in,
int verbosity)
{
if (address_in == NULL) {
return;
}
unsigned const char *addressBytes = address_in->network_ordered_value;
if (port_in != -1) {
NDDS_Transport_Log0printf("port= %d, ", port_in);
}
NDDS_Transport_Log0printf(
"address= %d.%d.%d.%d",
addressBytes[12],
addressBytes[13],
addressBytes[14],
addressBytes[15]);
if (verbosity >= 2) {
char ifaddr[256];
NDDS_Transport_Address_to_string(address_in, ifaddr, 256);
NDDS_Transport_Log0printf(" (%s)\n", ifaddr);
} else {
NDDS_Transport_Log0printf("\n");
}
}
/* ----------------------------------------------------------------- */
/* Member function to retrieve the directoryRoot where to put the files used
* to write the data sent by the transport.
*/
const char *NDDS_Transport_FILE_getdirname(const struct NDDS_Transport_FILE *me)
{
return me->_property.directoryRoot;
}
/* ----------------------------------------------------------------- */
/* Utility function to construct the filename that will be read by
* the transport when receiving on a port.
*/
void NDDS_Transport_FILE_getfilename_for_port(
const struct NDDS_Transport_FILE *me,
char *fname_out,
int fname_out_len,
const NDDS_Transport_Port_t port_in)
{
const char *METHOD_NAME = "NDDS_Transport_FILE_getfilename_for_port";
if (strlen(NDDS_Transport_FILE_getdirname(me)) + 16 >= fname_out_len) {
NDDS_Transport_Log0printf(
"%s: %s\n",
METHOD_NAME,
"fname_out is not big enough for filename");
}
sprintf(fname_out,
"%s/%s/%d",
NDDS_Transport_FILE_getdirname(me),
me->_property.address,
port_in);
}
/* ----------------------------------------------------------------- */
/* Utility function to construct the filename that will be read by
* the transport when receiving on a port.
*/
void NDDS_Transport_FILE_getfilename_for_address_and_port(
const struct NDDS_Transport_FILE *me,
char *fname_out,
int fname_out_len,
const NDDS_Transport_Address_t *address_in,
const NDDS_Transport_Port_t port_in)
{
const char *METHOD_NAME = "NDDS_Transport_FILE_getfilename_for_port";
unsigned const char *addrBytes = address_in->network_ordered_value;
if (strlen(NDDS_Transport_FILE_getdirname(me)) + 6 >= fname_out_len) {
NDDS_Transport_Log0printf(
"%s: %s\n",
METHOD_NAME,
"fname_out is not big enough for filename");
}
sprintf(fname_out,
"%s/%d.%d.%d.%d/%d",
NDDS_Transport_FILE_getdirname(me),
addrBytes[12],
addrBytes[13],
addrBytes[14],
addrBytes[15],
port_in);
}
/* ----------------------------------------------------------------- */
/* Utility function to create the directoryRoot that will contain the
* files used by the transport to send/receive date
*/
RTIBool NDDS_Transport_FILE_ensure_directory_exists(const char *path)
{
const char *METHOD_NAME = "NDDS_Transport_FILE_ensure_directory_exists";
mode_t mode = S_IRWXU | S_IRWXG | S_IRWXO;
RTIBool returnValue = RTI_TRUE;
// Set the mask for file creation to allow full configuration of permissions
mode_t oldmask = umask(~mode);
if (mkdir(path, mode) == -1) {
if (errno != EEXIST) {
NDDS_Transport_Log0printf(
"%s: failed to create directory \"%s\" errno= %d (%s)\n",
METHOD_NAME,
path,
errno,
strerror(errno));
returnValue = RTI_FALSE; // fail
}
}
/* restore mask */
umask(oldmask);
return returnValue;
}
RTIBool NDDS_Transport_FILE_ensure_receive_directory_exists(
struct NDDS_Transport_FILE *me)
{
char directoryPath[NDDS_TRANSPORT_FILE_MAX_FILEPATH_LEN];
char *ptrToBegin, *ptrToEnd;
sprintf(directoryPath,
"%s/%s",
NDDS_Transport_FILE_getdirname(me),
me->_property.address);
ptrToBegin = directoryPath;
while ((ptrToEnd = strchr(ptrToBegin + 1, '/')) != NULL) {
*ptrToEnd = '\0';
if (!NDDS_Transport_FILE_ensure_directory_exists(directoryPath)) {
return RTI_FALSE;
}
*ptrToEnd = '/';
ptrToBegin = ptrToEnd;
}
/* One last one in case directoryPath does not end in '/' */
if (!NDDS_Transport_FILE_ensure_directory_exists(directoryPath)) {
return RTI_FALSE;
}
return RTI_TRUE;
}
/* ----------------------------------------------------------------- */
/* When sending a message, the transport writes the corresponding
* bytes to a file. But it puts a 10-Byte header before to frame the message.
*
* This is not strictly required as it would be sufficient to rely
* on the fact the the messages are RTPS messages and have a well-known
* structure. However adding this simplifies the visual inspection
* of the file and makes the transport implementation independent of
* of the fact that it will be used to send only RTPS messages
*
* The 10-byte header introduced around each message is:
* "\nFILE"<lengthOfMessage>"\n" where <lengthOfMessage> is the length of
* the message wrapped by the header expressed as a 4-byte integer in the
* native endianess of the computer that writes the file.
*/
const char *NDDS_Transport_FILE_writeMessageHeaderPREFIX = "\nFILE";
const char *NDDS_Transport_FILE_writeMessageHeaderSUFFIX = "\n";
/* ----------------------------------------------------------------- */
/* Returns the length of the message header (10 Bytes in our case)
*/
static RTI_INT32 NDDS_Transport_FILE_messageHeaderLength()
{
return (strlen(NDDS_Transport_FILE_writeMessageHeaderPREFIX) + 4 /* length
of
message
*/
+ strlen(NDDS_Transport_FILE_writeMessageHeaderSUFFIX));
}
/* ----------------------------------------------------------------- */
/* Write the (10-Byte) message header to the file
*/
static void NDDS_Transport_FILE_writeMessageHeader(FILE *file, int messageLen)
{
fwrite(NDDS_Transport_FILE_writeMessageHeaderPREFIX,
1,
strlen(NDDS_Transport_FILE_writeMessageHeaderPREFIX),
file);
fwrite(&messageLen, 4, 1, file);
fwrite(NDDS_Transport_FILE_writeMessageHeaderSUFFIX,
1,
strlen(NDDS_Transport_FILE_writeMessageHeaderSUFFIX),
file);
}
/* ----------------------------------------------------------------- */
/* Utility function to read the next message header from the file and
* return the number of bytes of the message that follow the message header.
*
* There are 3 possible return values:
* 0 ==> indicates there is no data in the file beyond the last byte read
* this is normal. Should not be considered an error
*
* -1 ==> indicates an error occurred. For example bytes were read but
* not enough for a complete header or the header signature is wrong
*
* Positive Int ==> indicates success and the return is the size of the
* message that appears in the file right after the header.
*
* The function verifies that the file position is pointing to a valid
* transport message header. If that is not the case the function returns -1 and
* leaves the file position unaltered.
*
* If the file position is pointing is pointing to a message header then the
* function returns the number of bytes belonging to the message
* that follow the message header and leaves the file seek position to
* the next byte after the message header
*/
static RTI_INT32 NDDS_Transport_FILE_readMessageHeader(FILE *file)
{
const char *METHOD_NAME = "NDDS_Transport_FILE_readMessageHeader";
char headerBuffer[256];
char *messageSizePtr;
int filePos;
RTI_INT32 headerLength = NDDS_Transport_FILE_messageHeaderLength();
RTI_INT32 bytesRead;
if (sizeof(headerBuffer) < headerLength) {
NDDS_Transport_Log0printf(
"%s: header buffer of size %d is too small. It needs to be at "
"least %d bytes\n",
METHOD_NAME,
(int) sizeof(headerBuffer),
headerLength);
return -1;
}
filePos = ftell(file);
if (filePos == -1) {
NDDS_Transport_Log0printf(
"%s: failed to get file position\n",
METHOD_NAME);
return -1;
}
bytesRead = fread(headerBuffer, 1, headerLength, file);
if (bytesRead == 0) {
/* This may be and EOF or an error. We need to distinguish between the
* two. */
if (feof(file)) {
/* End of file was reached. It just indicates there is no new data
*/
/* Important: Clear the EOF "error" otherwise subsequent reads will
* fail */
clearerr(file);
return 0;
} else {
/* This is a real error */
NDDS_Transport_Log0printf(
"%s: failed, errno= %d (%s)\n",
METHOD_NAME,
errno,
strerror(errno));
return -1;
}
}
if (bytesRead != headerLength) {
NDDS_Transport_Log0printf(
"%s: at file position= %d failed to read %d bytes of header. "
"Got only %d\n",
METHOD_NAME,
(int) filePos,
headerLength,
bytesRead);
fseek(file, filePos, SEEK_SET);
return -1;
}
if (strncmp(NDDS_Transport_FILE_writeMessageHeaderPREFIX,
headerBuffer,
strlen(NDDS_Transport_FILE_writeMessageHeaderPREFIX))
!= 0) {
NDDS_Transport_Log0printf(
"%s: the message does not contain the transport header "
"position = %d\n",
METHOD_NAME,
(int) filePos);
fseek(file, filePos, SEEK_SET);
return -1;
}
messageSizePtr = ((char *) headerBuffer)
+ strlen(NDDS_Transport_FILE_writeMessageHeaderPREFIX);
return *(RTI_INT32 *) messageSizePtr;
}
/* ----------------------------------------------------------------- */
/*
* This function reads the next message from the file.
* The FILE position must be pointing to a transport message header.
* If this is not the case the function will return -1 and leave
* the file position unaltered
*
* On input:
* outBuffer - points to an allocated buffer to receive the message body
* outBufferLen - contains the size in bytes of outBuffer.
*
* On output:
* outBuffer - is filled with the message body on success and left
* unchanged on failure
*
* Return Value: Indicates weather there was an error and if not
* the numbers of bytes copied into the output buffer:
* -1 ==> Indicates an error occurred. For example the caller passed
* outBuffer==NULL
*
* 0 ==> Indicates no data was copied. This can be either a normal
* return or an error:
* - If *neededBufferSize is also set to zero it indicates
* there was no data to read. This is normal
* - If *neededBufferSize is not set to zero it indicates that
* the provided buffer was too small.
*
* Positive Int ==> Indicates a message was read successfully.
* The returned value is the number of bytes in teh message
* which are the ones copied to outBuffer.
* Arguments:
* The function verifies that the next message
* in the file fits in the provided outBuffer
* - If it fits the function :
* a) copies the message body into outBuffer
* (skipping the transport header)
* b) fills the output parameter neededBufferSize with the
* number of bytes copied into outBuffer
* c) moves the file position to point to the transport header
* of the next message
* d) returns the number of bytes copied into outBuffer
* (which differs from the ones read from the file by size
* of the message header)
*
* - If it does not fit, the function:
* a) leaves outBuffer unchanged
* b) fills the output parameter neededBufferSize with the
* number of bytes that would be required to receive the message
* c) leaves the file position unchanged
* d) returns 0.
*
* - The situation where there is no message in the file can be detected
* because the will return 0 with a *neededBufferSize==0
*/
static int NDDS_Transport_FILE_readNextMessage(
struct NDDS_Transport_FILE *me,
FILE *file,
int portNum,
char *outBuffer,
int outBufferSize,
int *messageSize)
{
const char *METHOD_NAME = "NDDS_Transport_FILE_readNextMessage";
int filePos;
RTI_INT32 messageLenght;
RTI_INT32 bytesRead;
*messageSize = 0;
if (outBuffer == NULL) {
NDDS_Transport_Log0printf(
"%s (port %d): error specified outBuffer is NULL\n",
METHOD_NAME,
portNum);
return -1;
}
filePos = ftell(file);
if (filePos == -1) {
NDDS_Transport_Log0printf(
"%s (port %d): failed to get file position errno=%d (%s)\n",
METHOD_NAME,
portNum,
errno,
strerror(errno));
return -1;
}
messageLenght = NDDS_Transport_FILE_readMessageHeader(file);
/* Check for errors */
if (messageLenght == -1) {
NDDS_Transport_Log0printf(
"%s (port %d): failed to read transport message header\n",
METHOD_NAME,
portNum);
return -1;
}
/* Check for no data */
if (messageLenght == 0) {
if (NDDS_Transport_Log2Enabled(me)) {
printf("%s (port %d): no data found\n", METHOD_NAME, portNum);
}
return 0;
}
/* Check message fits in output buffer */
if (outBufferSize < messageLenght) {
/* It does not fit. This is an error. Print it and revert file position
*/
fseek(file, filePos, SEEK_SET);
*messageSize = messageLenght;
NDDS_Transport_Log0printf(
"%s (port %d): buffer of size %d is too small for message. It "
"needs at least %d\n",
METHOD_NAME,
portNum,
outBufferSize,
messageLenght);
return -1;
}
/* All is good, Read the message */
bytesRead = fread(outBuffer, 1, messageLenght, file);
if (bytesRead != messageLenght) {
/* There was an error. Leave the file position unchanged */
fseek(file, filePos, SEEK_SET);
NDDS_Transport_Log0printf(
"%s (port %d): position= %d, read only %d bytes, expected %d "
"bytes\n",
METHOD_NAME,
portNum,
(int) ftell(file),
bytesRead,
messageLenght);
return -1;
}
/* Success */
*messageSize = messageLenght;
return messageLenght;
}
/* ----------------------------------------------------------------- */
/* Utility function to check whether the process that created
* the receive resource associated with the file is still running
*
* The first message in the file contains the process id of the
* process that created the file as a result of the call to
* NDDS_Transport_FILE_open_file_for_port() which is called from
* NDDS_Transport_FILE_create_recvresource_rrEA.
*
* This function parses that message to locate the process Id
* and then checks if the process is still running
*/
RTIBool NDDS_Transport_FILE_check_file_in_active_use(
struct NDDS_Transport_FILE *me,
FILE *file,
int portNum)
{
RTI_INT32 readResult;
char signatureBuffer[NDDS_Transport_FILE_SIGNATURE_MAX_LEN];
int messageSize;
const char *processIdStr;
char *processIdEndStr;
int processId;
int killReturn;
/* By default we return true indicating file is active. This is safest */
RTIBool result = RTI_TRUE;
const char *METHOD_NAME = "NDDS_Transport_FILE_check_file_in_active_use";
/* First get the position so we can restore it prior to return */
int filePos = ftell(file);
if (filePos == -1) {
NDDS_Transport_Log0printf(
"%s (port %d): file=%p, failed to get file position errno=%d "
"(%s)\n",
METHOD_NAME,
portNum,
file,
errno,
strerror(errno));
return -1;
}
if (fseek(file, 0, SEEK_SET) != 0) {
NDDS_Transport_Log0printf(
"%s (port %d): failed to set file position to begining "
"errno=%d (%s)\n",
METHOD_NAME,
portNum,
errno,
strerror(errno));
return -1;
}
readResult = NDDS_Transport_FILE_readNextMessage(
me,
file,
portNum,
signatureBuffer,
NDDS_Transport_FILE_SIGNATURE_MAX_LEN,
&messageSize);
/* Since the file exists, it must have at least the first message.
* if it does not then there is some error.
*/
if (readResult <= 0) {
NDDS_Transport_Log0printf(
"%s: failed to read first message in file\n",
METHOD_NAME);
goto restoreFilePosAndReturn;
}
/* Parse the first message to find the processId*/
processIdStr = strstr(signatureBuffer, "processId=\"");
if (processIdStr == NULL) {
NDDS_Transport_Log0printf(
"%s: failed to find \"processId\" in fist message\n",
METHOD_NAME);
NDDS_Transport_Log0printf(
"..... first message was: %s\n",
signatureBuffer);
goto restoreFilePosAndReturn;
}
/* get the PID */
processIdStr += strlen("processId=\"");
processId = strtoul(processIdStr, &processIdEndStr, 10);
if (*processIdEndStr != '"') {
NDDS_Transport_Log0printf(
"%s: Value of \"processId\" was not followed by \"\n",
METHOD_NAME);
NDDS_Transport_Log0printf(
"..... first message was: %s\n",
signatureBuffer);
goto restoreFilePosAndReturn;
}
/* Send signal "0" to the process. Which is not really sending a signal but
* it can be used to test if the process exists. If the process does not
* exist kill sets errno to ESRCH.
*/
if (kill(processId, 0) != 0) {
result = (errno != ESRCH);
}
if (NDDS_Transport_Log1Enabled(me)) {
printf("%s: file=%p (port %d) owned by process %d. Process is %s\n",
METHOD_NAME,
file,
portNum,
processId,
result ? "ALIVE" : "NOT ALIVE");
}
restoreFilePosAndReturn:
fseek(file, 0, SEEK_SET);
return result;
}
/* ----------------------------------------------------------------- */
/*
* Each port maps to a filename. We check if the file already exists
* if it exists we fail. If it does not exist we create it and succeed.
*/
struct NDDS_Transport_RecvResource_FILE *NDDS_Transport_FILE_open_file_for_port(
struct NDDS_Transport_FILE *me,
const NDDS_Transport_Port_t port_in)
{
const char *METHOD_NAME = "NDDS_Transport_FILE_open_file_for_port";
char fileName[256];
char tinfo[NDDS_Transport_FILE_SIGNATURE_MAX_LEN];
FILE *file;
struct NDDS_Transport_RecvResource_FILE *recvResourceStruct;
int tInfoBytes;
NDDS_Transport_FILE_getfilename_for_port(me, fileName, 256, port_in);
file = fopen(fileName, "r");
/* file != NULL indicates the file already exists */
if (file != NULL) {
if (NDDS_Transport_Log1Enabled(me)) {
printf("%s: file '%s' already exists\n", METHOD_NAME, fileName);
}
/* Check if the owing PID is still alive. If not then cleanup the
* content and reuse it.
*/
if (NDDS_Transport_FILE_check_file_in_active_use(me, file, port_in)) {
if (NDDS_Transport_Log1Enabled(me)) {
printf("%s: file '%s' actively being used\n",
METHOD_NAME,
fileName);
}
fclose(file);
return NULL;
}
/* Else. File exists and not in active. Reuse it */
if (NDDS_Transport_Log1Enabled(me)) {
printf("%s: file '%s' not actively being used. Reclaiming it.\n",
METHOD_NAME,
fileName);
}
fclose(file);
}
/* Either the file did not exist or else the owning process is no longer
* active either way we open the file (wiping any contents if the file
* existed) and initialize the to be used by this process
* */
file = fopen(fileName, "wb+");
if (file == NULL) {
/* Failed to create a file that did not exist. This should not happen */
NDDS_Transport_Log0printf(
"%s: Error failed to create file '%s' errno= %d (%s)\n",
METHOD_NAME,
fileName,
errno,
strerror(errno));
return NULL;
}
/* We successfully opened the file. Write a HEADER to mark the file and the
* owner */
sprintf(tinfo,
"transportClass=\"%d\";transportName=\"%s\";address=\"%s\";portNum="
"\"%d\";"
"fileName=\"%s\";processId=\"%llu\"",
NDDS_TRANSPORT_CLASSID_FILE,
NDDS_TRANSPORT_FILE_CLASS_NAME,
me->_property.address,
port_in,
fileName,
RTIOsapiProcess_getId());
tInfoBytes = strlen(tinfo);
NDDS_Transport_FILE_writeMessageHeader(file, tInfoBytes);
/* Write the initial message containing file details */
fprintf(file, "%s", tinfo);
/* In principle we could reopen file as read-only because from not on we
* will only fread() from it. However we cannot because we use use lockf()
* to lock the file and serialize reads and writes to it. And in some
* platforms lockf() requires the process have write access to the file
*/
/* Rewind to the beginning of the file */
fseek(file, 0, SEEK_SET);
/* Create the receive resource */
recvResourceStruct = (struct NDDS_Transport_RecvResource_FILE *) calloc(
1,
sizeof(*recvResourceStruct));
recvResourceStruct->_portNum = port_in;
recvResourceStruct->_file = file;
recvResourceStruct->_fileDescriptor = fileno(file);
if (NDDS_Transport_Log1Enabled(me)) {
printf("%s (port %d): initialized file=%p, descriptor=%d, fileName: "
"\"%s\"\n",
METHOD_NAME,
port_in,
recvResourceStruct->_file,
recvResourceStruct->_fileDescriptor,
fileName);
}
return recvResourceStruct;
}
/* ----------------------------------------------------------------- */
/*i \ingroup NDDS_Transport_FILE
@brief Validate properties
*/
RTI_INT32 NDDS_Transport_FILE_Property_verify(
const struct NDDS_Transport_FILE_Property_t *property)
{
RTI_INT32 ok = 1;
const char *const METHOD_NAME = "NDDS_Transport_FILE_Property_verify";
if (property == NULL) {
NDDS_Transport_Log0printf("%s: Error, NULL property\n", METHOD_NAME);
return 0;
}
ok = NDDS_Transport_Property_verify(&property->parent);
if (property->parent.classid != NDDS_TRANSPORT_CLASSID_FILE) {
NDDS_Transport_Log0printf(
"%s: %s\n",
METHOD_NAME,
"classid is incorrect");
ok = 0;
}
if (property->parent.address_bit_count
!= NDDS_TRANSPORT_FILE_ADDRESS_BIT_COUNT) {
NDDS_Transport_Log0printf(
"%s: %s\n",
METHOD_NAME,
"address_bit_count is incorrect");
ok = 0;
}
if (property->received_message_count_max < 1) {
NDDS_Transport_Log0printf(
"%s: %s\n",
METHOD_NAME,
"received_message_count_max < 1");
ok = 0;
}
if (property->receive_buffer_size < property->parent.message_size_max) {
NDDS_Transport_Log0printf(
"%s: %s\n",
METHOD_NAME,
"receive_buffer_size < message_size_max");
ok = 0;
}
return ok;
}
/* ----------------------------------------------------------------- */
/*i \ingroup NDDS_Transport_FILE
@brief Send a message over the transport-plugin.
*/
static RTI_INT32 NDDS_Transport_FILE_send(
NDDS_Transport_Plugin *self,
const NDDS_Transport_SendResource_t *sendresource_in,
const NDDS_Transport_Address_t *dest_address_in,
const NDDS_Transport_Port_t dest_port_in,
RTI_INT32 transport_priority_in,
const NDDS_Transport_Buffer_t buffer_in[],
RTI_INT32 buffer_count_in,
void *reserved)
{
const char *METHOD_NAME = "NDDS_Transport_FILE_send";
struct NDDS_Transport_FILE *me = (struct NDDS_Transport_FILE *) self;
struct NDDS_Transport_SendResource_FILE *sendResourceStruct =
(struct NDDS_Transport_SendResource_FILE *) *sendresource_in;
int i = 0, bytesToSend = 0;
RTI_INT32 returnValue = 0; /* Indicates error */
/* Verify pre-conditions */
if (me == NULL || buffer_in == NULL || buffer_count_in <= 0
|| (*sendresource_in == NULL) || dest_address_in == NULL) {
NDDS_Transport_Log0printf(
"%s: RTIOsapiSemaphore_give error\n",
METHOD_NAME);
return returnValue;
}
REDABufferArray_getSize(&bytesToSend, buffer_in, buffer_count_in);
if (NDDS_Transport_Log2Enabled(me)) {
printf("%s: sending %d bytes using resource %p to destination:\n",
METHOD_NAME,
bytesToSend,
sendResourceStruct);
NDDS_Transport_FILE_print_address(
dest_address_in,
dest_port_in,
me->_property.trace_level);
}
/* First check the file exists */
FILE *file = fopen(sendResourceStruct->_fileName, "rb+");
if (file == NULL) {
/* This is normal. Indicates that there is no receiver at a particular
* address/port it may indicate that discovery is sending to a port that
* is not there, or that the application that was receiving data is no
* longer there
*/
if (NDDS_Transport_Log2Enabled(me)) {
printf("%s: file \"%s\" does not exist\n",
METHOD_NAME,
sendResourceStruct->_fileName);
}
return returnValue;
}
/* Now we know the file exists, reopen for writing */
file = freopen(NULL, "ab", file);
if (file == NULL) {
NDDS_Transport_Log0printf(
"%s: error opening file for write filename= \"%s\" errno= %d "
"(%s)\n",
METHOD_NAME,
sendResourceStruct->_fileName,
errno,
strerror(errno));
goto doneClose;
}
/**** After this point we have to return via "goto doneClose" to ensure we
* close the file ****/
/* Lock the file to make sure there is only one application writing to it */
int fd = fileno(file);
if (fd == -1) {
NDDS_Transport_Log0printf(
"%s: error in fileno. filename= \"%s\" errno= %d (%s)\n",
METHOD_NAME,
sendResourceStruct->_fileName,
errno,
strerror(errno));
}
/* This blocks until file can be locked. Use F_TLOCK to just test */
if (lockf(fd, F_LOCK, 0) == -1) { /* zero offset indicates lock whole file
*/
NDDS_Transport_Log0printf(
"%s: error locking filename= \"%s\" fd= %d, errno= %d (%s)\n",
METHOD_NAME,
sendResourceStruct->_fileName,
fd,
errno,
strerror(errno));
goto doneClose;
}
/* File successfully locked. */
/**** After this point we have to return via "goto doneUnlock" to ensure we
* release the lock ****/
/* Write a TransportMessageHeader that frames the packet to send (This is
* similar intent to the UDP/IP header that the UDP transport puts around
* each message
* '\n' 'F' 'I' 'F' '0' <messageSize> '\n'
*/
NDDS_Transport_FILE_writeMessageHeader(file, bytesToSend);
/* Write bytes to the end of the file */
for (i = 0; i < buffer_count_in; ++i) { /* write data from each iovec */
if (fwrite(buffer_in[i].pointer, 1, buffer_in[i].length, file)
!= buffer_in[i].length) {
NDDS_Transport_Log0printf(
"%s: error writing to file filename= \"%s\" errno= %d "
"(%s)\n",
METHOD_NAME,
sendResourceStruct->_fileName,
errno,
strerror(errno));
goto doneUnlock;
}
}
++sendResourceStruct->_sendMessageCount;
if (NDDS_Transport_Log2Enabled(me)) {
printf("%s: sent message count=%d of %d bytes to destination: ",
METHOD_NAME,
sendResourceStruct->_sendMessageCount,
bytesToSend);
NDDS_Transport_FILE_print_address(
dest_address_in,
dest_port_in,
me->_property.trace_level);
}
returnValue = 1; /* Indicates success */
doneUnlock:
if (lockf(fd, F_ULOCK, 0) == -1) { /* zero offset indicates lock whole file
*/
NDDS_Transport_Log0printf(
"%s: error unlocking filename= \"%s\" errno= %d (%s)\n",
METHOD_NAME,
sendResourceStruct->_fileName,
errno,
strerror(errno));
}
doneClose:
fclose(file);
return returnValue;
}
/* ----------------------------------------------------------------- */
/*i \ingroup NDDS_Transport_FILE
@brief Called to receive messages from a ReceiveResource.
According to the API this function should block until there is data
to return. To keep thisn simple in this example rather than block
the function polls the file each 1 second until it gets new data.
*/
static RTI_INT32 NDDS_Transport_FILE_receive_rEA(
NDDS_Transport_Plugin *self,
NDDS_Transport_Message_t *message_out,
const NDDS_Transport_Buffer_t *buffer_in,
const NDDS_Transport_RecvResource_t *recvresource_in,
void *reserved)
{
struct NDDS_Transport_FILE *me = (struct NDDS_Transport_FILE *) self;
const char *METHOD_NAME = "NDDS_Transport_FILE_receive_rEA";
struct NDDS_Transport_RecvResource_FILE *receiveResourceStruct =
(struct NDDS_Transport_RecvResource_FILE *) *recvresource_in;
int bytesNeededToRead = 0;
int bytesCopiedToBuffer = 0;
RTI_INT32 returnErrorValue = 0; /* Indicates an error return */
RTI_INT32 returnSuccessValue = 1; /* Indicates a successful return */
/* Verify pre-conditions */
if (me == NULL || message_out == NULL || receiveResourceStruct == NULL
|| buffer_in == NULL) {
NDDS_Transport_Log0printf("%s: precondition error\n", METHOD_NAME);
return returnErrorValue;
}
if (NDDS_Transport_Log2Enabled(me)) {
printf("%s (port %d): file= %p, position= %d. Receive buffer can hold "
"%d bytes\n",
METHOD_NAME,
receiveResourceStruct->_portNum,
receiveResourceStruct->_file,
(int) ftell(receiveResourceStruct->_file),
buffer_in->length);
}
while (bytesCopiedToBuffer == 0) {
if (NDDS_Transport_Log2Enabled(me)) {
printf("%s (port %d): Waiting for message (received so far %d), "
"file= %p, position= %d...\n",
METHOD_NAME,
receiveResourceStruct->_portNum,
receiveResourceStruct->_receiveMessageCount,
receiveResourceStruct->_file,
(int) ftell(receiveResourceStruct->_file));
}
/* BEGIN of FILE LOCK ------------->>> */
/* This blocks until file can be locked. Use F_TLOCK to just test */
if (lockf(receiveResourceStruct->_fileDescriptor, F_LOCK, 0)
== -1) { /* zero offset indicates lock whole file */
NDDS_Transport_Log0printf(
"%s (port %d): error locking file fd= %d, errno= %d (%s)\n",
METHOD_NAME,
receiveResourceStruct->_portNum,
receiveResourceStruct->_fileDescriptor,
errno,
strerror(errno));
return returnErrorValue;
}
bytesCopiedToBuffer = NDDS_Transport_FILE_readNextMessage(
me,
receiveResourceStruct->_file,
receiveResourceStruct->_portNum,
buffer_in->pointer,
buffer_in->length,
&bytesNeededToRead);
if (lockf(receiveResourceStruct->_fileDescriptor, F_ULOCK, 0)
== -1) { /* zero offset indicates lock whole file */
NDDS_Transport_Log0printf(
"%s (port %d): error unlocking file errno= %d (%s)\n",
METHOD_NAME,
receiveResourceStruct->_portNum,
errno,
strerror(errno));
}
/* END of FILE LOCK -------------<<< */
if (NDDS_Transport_Log2Enabled(me)) {
printf("%s (port %d): NDDS_Transport_FILE_readNextMessage returned "
"%d, bytesNeeded= %d\n",
METHOD_NAME,
receiveResourceStruct->_portNum,
bytesCopiedToBuffer,
bytesNeededToRead);
}
/* Check for errors */
if (bytesCopiedToBuffer == -1) {
NDDS_Transport_Log0printf(
"%s (%d): unknown error\n",
METHOD_NAME,
receiveResourceStruct->_portNum);
return returnErrorValue;
}
/* Check if there was something copied to buffer */
if (bytesCopiedToBuffer == 0) {
if (bytesNeededToRead == 0) {
/* There was no data. Sleep a bit and try again */
sleep(1);
continue;
} else {
/* Indicates buffer was not big enough to copy message */
NDDS_Transport_Log0printf(
"%s (port %d): buffer of size %d is too small, it "
"needs %d\n",
METHOD_NAME,
receiveResourceStruct->_portNum,
buffer_in->length,
bytesNeededToRead);
return returnErrorValue;
}
}
}
/* If we exit the loop here it is because we copied a message
* to the buffer_in->pointer
*/
message_out->buffer.pointer = buffer_in->pointer;
message_out->buffer.length = bytesCopiedToBuffer;
/* The loaned_buffer_param is only needed if the transport is zero-copy and
* wants to loan a buffer to the middleware. In that case it should save in
* loaned_buffer_param any information needed to retuer that loan when the
* middleware calls return_loaned_buffer_rEA().
* The FileTransport does not loan buffers so we can leave this unset or
* put some arbitrary value
*/
message_out->loaned_buffer_param = (void *) -1;
++receiveResourceStruct->_receiveMessageCount;
if (NDDS_Transport_Log2Enabled(me)) {
printf("%s (port %d): received message count=%d of %d bytes\n",
METHOD_NAME,
receiveResourceStruct->_portNum,
receiveResourceStruct->_receiveMessageCount,
bytesCopiedToBuffer);
}
return returnSuccessValue;
}
/* ----------------------------------------------------------------- */
/*i \ingroup NDDS_Transport_FILE
@brief Returns a loaned buffer.
*/
static void NDDS_Transport_FILE_return_loaned_buffer_rEA(
NDDS_Transport_Plugin *self,
const NDDS_Transport_RecvResource_t *recvresource_in,
NDDS_Transport_Message_t *message_in,
void *reserved)
{
/* This transport does not loan buffers on the receive_rEA() call
* so there is really nothing to do here
*/
message_in->loaned_buffer_param = NULL;
}
/* ----------------------------------------------------------------- */
/*i \ingroup NDDS_Transport_FILE
@brief Unblocks a receive thread.
*/
static RTI_INT32 NDDS_Transport_FILE_unblock_receive_rrEA(
NDDS_Transport_Plugin *self,
const NDDS_Transport_RecvResource_t *recvresource_in,
void *reserved)
{
const char *METHOD_NAME = "NDDS_Transport_FILE_unblock_receive_rrEA";
struct NDDS_Transport_RecvResource_FILE *recvRes =
(struct NDDS_Transport_RecvResource_FILE *) *recvresource_in;
RTI_INT32 ok = 0;
if (self == NULL || NDDS_Transport_Plugin_is_polled(self)) {
NDDS_Transport_Log0printf(
"%s: cannot unblock polled transport\n",
METHOD_NAME);
goto done;
}
NDDS_Transport_FILE_writeMessageHeader(recvRes->_file, 0);
ok = 1;
done:
return ok;
}
/* ----------------------------------------------------------------- */
/*i \ingroup NDDS_Transport_FILE
@brief Creates a ReceiveResource for a given port with a given
transport_priority.
Doesn't support multicast.
*/
static RTI_INT32 NDDS_Transport_FILE_create_recvresource_rrEA(
NDDS_Transport_Plugin *self,
NDDS_Transport_RecvResource_t *recvresource_out,
NDDS_Transport_Port_t *dest_port_inout,
const NDDS_Transport_Address_t *multicast_address_in,
RTI_INT32 reserved)
{
const char *METHOD_NAME = "NDDS_Transport_FILE_create_recvresource_rrEA";
struct NDDS_Transport_FILE *me = (struct NDDS_Transport_FILE *) self;
if (*dest_port_inout == NDDS_TRANSPORT_PORT_INVALID) {
char str[256];
sprintf(str, "invalid port specified: %d", *dest_port_inout);
NDDS_Transport_Log1print(me, str);
return 0;
}
/* FileTransport does not support multicast. Fail if a multicast address is
* specified
*/
if (multicast_address_in != NULL) {
NDDS_Transport_Log1print(me, "transport does not support multicast. ");
if (NDDS_Transport_Log2Enabled(me)) {
NDDS_Transport_FILE_print_address(
multicast_address_in,
*dest_port_inout,
me->_property.trace_level);
}
return 0;
}
/* Each port maps to a filename. We check if the file already exists
* if it exists we fail. If it does not exist we create it and succeed.
*/
*recvresource_out =
NDDS_Transport_FILE_open_file_for_port(me, *dest_port_inout);
if (*recvresource_out == NULL) {
NDDS_Transport_Log0printf(
"%s: failed to create receive resource for address= \"%s\", "
"port= %d\n",
METHOD_NAME,
me->_property.address,
*dest_port_inout);
return 0;
}
/* Success */
if (NDDS_Transport_Log1Enabled(me)) {
printf("%s: created receive resource for address= \"%s\", port= %d\n",
METHOD_NAME,
me->_property.address,
*dest_port_inout);
}
return 1;
}
/* ----------------------------------------------------------------- */
/*i \ingroup NDDS_Transport_FILE
@brief Try to share a ReceiveResource for receiving messages on a
port.
Doesn't support multicast.
Each port maps to a different file so only suceed if the same port
is specified.
*/
static RTI_INT32 NDDS_Transport_FILE_share_recvresource_rrEA(
NDDS_Transport_Plugin *self,
const NDDS_Transport_RecvResource_t *recvresource_in,
const NDDS_Transport_Port_t recv_port_in,
const NDDS_Transport_Address_t *multicast_address_in,
RTI_INT32 reserved)
{
const char *METHOD_NAME = "NDDS_Transport_FILE_share_recvresource_rrEA";
const struct NDDS_Transport_FILE *me = (struct NDDS_Transport_FILE *) self;
struct NDDS_Transport_RecvResource_FILE *recvRes =
(struct NDDS_Transport_RecvResource_FILE *) *recvresource_in;
/* Transport does nor support multicast */
if (multicast_address_in != NULL) {
return 0;
}
/* This transport can only use a NDDS_Transport_RecvResource_t for a single
* port so this function can only return TRUE if the requested port matches
* the one in the NDDS_Transport_RecvResource_t
*/
if (recvRes->_portNum != recv_port_in) {
if (NDDS_Transport_Log1Enabled(me)) {
printf("%s: resource at port '%d' not reused for port %d\n",
METHOD_NAME,
recvRes->_portNum,
recv_port_in);
}
return 0;
}
/* It is exactly the same port and we only have one address per transport
* so you can reuse
*/
if (NDDS_Transport_Log1Enabled(me)) {
printf("%s: resource at port '%d' reused for port '%d'\n",
METHOD_NAME,
recvRes->_portNum,
recv_port_in);
}
return 1;
}
/* ----------------------------------------------------------------- */
/*i \ingroup NDDS_Transport_FILE
@brief Unshares a recvresource.
*/
static RTI_INT32 NDDS_Transport_FILE_unshare_recvresource_rrEA(
NDDS_Transport_Plugin *self,
const NDDS_Transport_RecvResource_t *recvresource_in,
const NDDS_Transport_Port_t dest_port_in,
const NDDS_Transport_Address_t *multicast_address_in,
RTI_INT32 reserved)
{
const char *METHOD_NAME = "NDDS_Transport_FILE_unshare_recvresource_rrEA";
const struct NDDS_Transport_FILE *me = (struct NDDS_Transport_FILE *) self;
NDDS_Transport_Log1print(me, "");
/* If we had done something special to share a resource on a prior call
* to NDDS_Transport_FILE_share_recvresource_rrEA() we would undo that
* here. Since we did not this function is a NOOP
*/
return 1;
}
/* ----------------------------------------------------------------- */
/*i \ingroup NDDS_Transport_FILE
@brief Creates a SendResource for the given destination address
and port.
*/
static RTI_INT32 NDDS_Transport_FILE_create_sendresource_srEA(
NDDS_Transport_Plugin *self,
NDDS_Transport_SendResource_t *sendresource_out,
const NDDS_Transport_Address_t *dest_address_in,
const NDDS_Transport_Port_t dest_port_in,
RTI_INT32 transport_priority_in)
{
const char *METHOD_NAME = "NDDS_Transport_FILE_create_sendresource_srEA";
const struct NDDS_Transport_FILE *me = (struct NDDS_Transport_FILE *) self;
struct NDDS_Transport_SendResource_FILE *sendResourceStruct;
*sendresource_out = NULL;
/* Check if dest_address_in is null */
if (dest_address_in == NULL) {
printf("WARNING: The destination address cannot be NULL.");
return 0;
}
/* multicast not supported */
if (NDDS_Transport_Address_is_multicast(dest_address_in)) {
if (NDDS_Transport_Log1Enabled(me)) {
printf("%s: specified address is multicast and transport does not "
"support multicast: ",
METHOD_NAME);
NDDS_Transport_FILE_print_address(
dest_address_in,
dest_port_in,
me->_property.trace_level);
}
return 0;
}
sendResourceStruct = (struct NDDS_Transport_SendResource_FILE *) calloc(
1,
sizeof(*sendResourceStruct));
NDDS_Transport_Address_copy(&sendResourceStruct->_address, dest_address_in);
sendResourceStruct->_portNum = dest_port_in;
NDDS_Transport_FILE_getfilename_for_address_and_port(
me,
sendResourceStruct->_fileName,
NDDS_TRANSPORT_FILE_MAX_FILEPATH_LEN,
dest_address_in,
dest_port_in);
if (NDDS_Transport_Log1Enabled(me)) {
printf("%s: Send resource %p (file =\"%s\") created for ",
METHOD_NAME,
sendResourceStruct,
sendResourceStruct->_fileName);
NDDS_Transport_FILE_print_address(dest_address_in, dest_port_in, 2);
}
*sendresource_out = sendResourceStruct;
return 1;
}
/* ----------------------------------------------------------------- */
/*i \ingroup NDDS_Transport_FILE
@brief Try to share a SendResource for sending messages to a
destination.
*/
static RTI_INT32 NDDS_Transport_FILE_share_sendresource_srEA(
NDDS_Transport_Plugin *self,
const NDDS_Transport_SendResource_t *sendresource_in,
const NDDS_Transport_Address_t *dest_address_in,
const NDDS_Transport_Port_t dest_port_in,
RTI_INT32 transport_priority_in)
{
const char *METHOD_NAME = "NDDS_Transport_FILE_share_sendresource_srEA";
const struct NDDS_Transport_FILE *me = (struct NDDS_Transport_FILE *) self;
struct NDDS_Transport_SendResource_FILE *sendResourceStruct =
(struct NDDS_Transport_SendResource_FILE *) *sendresource_in;
/* Check if dest_address_in is null */
if (dest_address_in == NULL) {
printf("WARNING: The destination address cannot be NULL.");
return 0;
}
/* multicast not supported */
if (NDDS_Transport_Address_is_multicast(dest_address_in)) {
return 0;
}
/* This transport can only share a NDDS_Transport_SendResource_t if the
* destination address and port number match
*/
if ((sendResourceStruct->_portNum != dest_port_in)
|| (!NDDS_Transport_Address_is_equal(
&sendResourceStruct->_address,
dest_address_in))) {
if (NDDS_Transport_Log2Enabled(me)) {
printf("%s: Send resource (%p) not reused for:\n",
METHOD_NAME,
sendResourceStruct);
NDDS_Transport_FILE_print_address(
dest_address_in,
dest_port_in,
me->_property.trace_level);
}
return 0;
}
if (NDDS_Transport_Log1Enabled(me)) {
printf("%s: Send resource (%p) reused for \n",
METHOD_NAME,
sendResourceStruct);
NDDS_Transport_FILE_print_address(
dest_address_in,
dest_port_in,
me->_property.trace_level);
}
/* OK. Reuse */
return 1;
}
/* ----------------------------------------------------------------- */
/*i \ingroup NDDS_Transport_FILE
@brief Unshares a sendresource.
*/
static RTI_INT32 NDDS_Transport_FILE_unshare_sendresource_srEA(
NDDS_Transport_Plugin *self,
const NDDS_Transport_SendResource_t *sendresource_in,
const NDDS_Transport_Address_t *dest_address_in,
const NDDS_Transport_Port_t dest_port_in,
RTI_INT32 transport_priority_in)
{
const char *METHOD_NAME = "NDDS_Transport_FILE_unshare_sendresource_srEA";
const struct NDDS_Transport_FILE *me = (struct NDDS_Transport_FILE *) self;
/* If we had done something special to share a resource on a prior call
* to NDDS_Transport_FILE_share_sendresource_srEA() we would undo that
* here. Since we did not this function is a NOOP
*/
if (NDDS_Transport_Log1Enabled(me)) {
struct NDDS_Transport_SendResource_FILE *sendResourceStruct =
(struct NDDS_Transport_SendResource_FILE *) *sendresource_in;
printf("%s: Send resource (%p) unshared for: \n",
METHOD_NAME,
sendResourceStruct);
NDDS_Transport_FILE_print_address(
dest_address_in,
dest_port_in,
me->_property.trace_level);
}
/* no op */
return 1;
}
/* ----------------------------------------------------------------- */
/*i \ingroup NDDS_Transport_FILE
@brief Destroys send or receive resource.
*/
static void NDDS_Transport_FILE_destroy_sendresource_srEA(
NDDS_Transport_Plugin *self,
const NDDS_Transport_SendResource_t *resource_in)
{
const char *METHOD_NAME = "NDDS_Transport_FILE_destroy_sendresource_srEA";
const struct NDDS_Transport_FILE *me = (struct NDDS_Transport_FILE *) self;
struct NDDS_Transport_SendResource_FILE *sendResourceStruct =
(struct NDDS_Transport_SendResource_FILE *) resource_in;
if (NDDS_Transport_Log1Enabled(me)) {
printf("%s: Send resource (%p) for port %d destroyed: ",
METHOD_NAME,
sendResourceStruct,
sendResourceStruct->_portNum);
NDDS_Transport_FILE_print_address(
&sendResourceStruct->_address,
sendResourceStruct->_portNum,
me->_property.trace_level);
}
free(sendResourceStruct);
}
/* ----------------------------------------------------------------- */
/*i \ingroup NDDS_Transport_FILE
@brief Destroys send or receive resource.
*/
static void NDDS_Transport_FILE_destroy_recvresource_rrEA(
NDDS_Transport_Plugin *self,
const NDDS_Transport_RecvResource_t *resource_in)
{
const char *METHOD_NAME = "NDDS_Transport_FILE_destroy_recvresource_rrEA";
const struct NDDS_Transport_FILE *me = (struct NDDS_Transport_FILE *) self;
struct NDDS_Transport_RecvResource_FILE *recvResourceStruct =
(struct NDDS_Transport_RecvResource_FILE *) resource_in;
if (NDDS_Transport_Log1Enabled(me)) {
printf("%s: Receive resource (%p) for port %d destroyed\n",
METHOD_NAME,
recvResourceStruct,
recvResourceStruct->_portNum);
}
fclose(recvResourceStruct->_file);
free(recvResourceStruct);
}
/* ----------------------------------------------------------------- */
/*i \ingroup NDDS_Transport_FILE
@brief Returns the string class name of the transport.
*/
const char *NDDS_Transport_FILE_get_class_name_cEA(NDDS_Transport_Plugin *self)
{
const char *METHOD_NAME = "NDDS_Transport_FILE_get_class_name_cEA";
const struct NDDS_Transport_FILE *me = (struct NDDS_Transport_FILE *) self;
NDDS_Transport_Log1print(me, NDDS_TRANSPORT_FILE_CLASS_NAME);
return NDDS_TRANSPORT_FILE_CLASS_NAME;
}
/* ----------------------------------------------------------------- */
/*i \ingroup NDDS_Transport_FILE
@brief Converts a Transport-Plugin-specific address string to an
IPv6 address.
*/
RTI_INT32 NDDS_Transport_FILE_string_to_address_cEA(
NDDS_Transport_Plugin *self,
NDDS_Transport_Address_t *address_out,
const char *address_in)
{
const char *METHOD_NAME = "NDDS_Transport_FILE_string_to_address_cEA";
struct NDDS_Transport_FILE *me = (struct NDDS_Transport_FILE *) self;
NDDS_Transport_Log1print(me, "");
if (address_out == NULL || address_in == NULL) {
printf("%s: precondition error\n", METHOD_NAME);
return 0;
}
if (NDDS_Transport_Log1Enabled(me)) {
printf("%s: Conversion of addresses not supported. Requested \"%s\"\n",
METHOD_NAME,
address_in);
/* NDDS_Transport_FILE_print_address(address_out, -1, 2); */
}
/* Does not support string to IPv6 address conversion */
return 0;
}
/* ----------------------------------------------------------------- */
/*i \ingroup NDDS_Transport_FILE
@brief Returns a list of network interfaces represented by this
transport-plugin instance.
The FILE NIF is represented by the address of this transport plugin
instance.
The FileTransport IPv6 address address is made globally unique
by concatenating:
(
4-bytes: <network address configured by end user>
4 bytes: <RTPS Host Id>, // or IPv4 address
4-bytes: Process Id // Note: could also be <RTPS App Id>
4-bytes: <plugin_address truncated to 4 bytes>
)
So the FILE address uses only the last 12 bytes (96 bits) of the
IPv6 address space.
*/
RTI_INT32 NDDS_Transport_FILE_get_receive_interfaces_cEA(
NDDS_Transport_Plugin *self,
RTI_INT32 *found_more_than_provided_for_out,
RTI_INT32 *interface_reported_count_out,
NDDS_Transport_Interface_t interface_array_inout[],
RTI_INT32 interface_array_size_in)
{
const char *METHOD_NAME = "NDDS_Transport_FILE_get_receive_interfaces_cEA";
struct NDDS_Transport_FILE *me = (struct NDDS_Transport_FILE *) self;
if (self == NULL || interface_array_size_in < 0
|| interface_array_inout == NULL
|| found_more_than_provided_for_out == NULL
|| interface_reported_count_out == NULL) {
NDDS_Transport_Log0printf("%s: precondition error\n", METHOD_NAME);
return 0;
}
if (interface_array_size_in < 1) {
*found_more_than_provided_for_out = 1;
goto success;
}
*found_more_than_provided_for_out = 0;
/* --- output the interface --- */
*interface_reported_count_out = 1;
interface_array_inout[0].transport_classid = NDDS_TRANSPORT_CLASSID_FILE;
/* Zero bytes */
memset(&interface_array_inout[0].address.network_ordered_value,
0,
NDDS_TRANSPORT_ADDRESS_LENGTH);
/* Set the meaningful bytes of the address */
{
struct in_addr ipAddr;
inet_aton(me->_property.address, &ipAddr);
memcpy(interface_array_inout[0].address.network_ordered_value + 12,
&ipAddr,
4);
}
success:
if (NDDS_Transport_Log1Enabled(me)) {
int i;
printf("%s: num receive interfaces: %d\n",
METHOD_NAME,
*interface_reported_count_out);
for (i = 0; i < *interface_reported_count_out; ++i) {
char ifaddr[256];
NDDS_Transport_Address_to_string(
&interface_array_inout[i].address,
ifaddr,
256);
printf(" interface[%d] = \"%s\" (%s)\n",
i,
me->_property.address,
ifaddr);
}
}
return 1;
}
/* ----------------------------------------------------------------- */
/*i \ingroup NDDS_Transport_FILE
@brief Register a callback to be notified of the changes in the
availability of interfaces supported by the plugin.
Doesn't do anything with a listener.
*/
static RTI_INT32 NDDS_Transport_FILE_register_listener_cEA(
NDDS_Transport_Plugin *self,
NDDS_Transport_Listener *listener)
{
const char *METHOD_NAME = "NDDS_Transport_FILE_register_listener_cEA";
if (self == NULL) {
printf("%s: NULL transport\n", METHOD_NAME);
return 0;
}
/* Transport is static */
return 1;
}
/* ---------------------------------------------------------------------- */
/*i \ingroup NDDS_Transport_FILE
@brief (Destructor) Called to destroy the Transport-Plugin.
@pre No RecvResources or SendResources exist for this transport
@post Transport has been deleted. It should not be used after this call.
Deletes the memory allocated when NDDS_Transport_FILE_new()
was called. Does not take care of deleting any RecvResources or
SendResources associated with the transport. It is the
responsibility NDDS to delete all SendResources and RecvResources
associated with the transport prior to deleting the transport
itself.
*/
static void NDDS_Transport_FILE_delete_cEA(
NDDS_Transport_Plugin *self,
void *reserved)
{
const char *METHOD_NAME = "NDDS_Transport_FILE_delete_cEA";
struct NDDS_Transport_FILE *me = (struct NDDS_Transport_FILE *) self;
if (me == NULL) {
printf("%s: NULL transport\n", METHOD_NAME);
return;
}
if (me->_buffer != NULL) {
free(me->_buffer);
}
if (NDDS_Transport_Log1Enabled(me)) {
printf("%s: Transport (%p) for address %s destroyed\n",
METHOD_NAME,
me,
me->_property.address);
}
free(me);
}
/* ---------------------------------------------------------------------- */
/*i \ingroup NDDS_Transport_FILE
@brief (Constructor) Create a intra-transport-plugin instance.
*/
NDDS_Transport_Plugin *NDDS_Transport_FILE_newPlugin(
const struct NDDS_Transport_FILE_Property_t *property_in)
{
const char *METHOD_NAME = "NDDS_Transport_FILE_newI";
struct NDDS_Transport_FILE *me = NULL;
const struct NDDS_Transport_FILE_Property_t defaultProp =
NDDS_TRANSPORT_FILE_PROPERTY_DEFAULT;
int bufferSize = 0;
int pid = 0;
/* allocate instance */
me = (struct NDDS_Transport_FILE *) calloc(1, sizeof(*me));
if (me == NULL) {
printf("%s: malloc(%d) failed\n", METHOD_NAME, (int) sizeof(*me));
goto failed;
}
/* Set the property */
if (property_in == NULL) {
me->_property = defaultProp;
} else {
me->_property = *property_in;
}
me->parent.property = (struct NDDS_Transport_Property_t *) &me->_property;
if (!NDDS_Transport_FILE_Property_verify(&me->_property)) {
printf("%s: %s\n", METHOD_NAME, "Invalid transport properties.");
goto failed;
}
pid = RTIOsapiProcess_getId();
{
char str[256];
sprintf(str,
"pid: %d bound to address: \"%s\"",
pid,
me->_property.address);
NDDS_Transport_Log1print(me, str);
}
/* Ensure existence of directoryRoot that will contain the files associated
* with receive resource */
if (!NDDS_Transport_FILE_ensure_receive_directory_exists(me)) {
goto failed;
}
/* create receive buffer */
bufferSize = me->_property.receive_buffer_size
+ NDDS_Transport_FILE_messageHeaderLength();
/* The extra 8 is to compensate for the worst case alignments that are
* required when serializing to the buffer */
me->_buffer = (char *) calloc(1, bufferSize + 8);
if (me->_buffer == NULL) {
printf("%s: RTIOsapiHeap_allocateBuffer semaphore error\n",
METHOD_NAME);
goto failed;
}
me->parent.send = NDDS_Transport_FILE_send;
me->parent.receive_rEA = NDDS_Transport_FILE_receive_rEA;
me->parent.return_loaned_buffer_rEA =
NDDS_Transport_FILE_return_loaned_buffer_rEA;
me->parent.unblock_receive_rrEA = NDDS_Transport_FILE_unblock_receive_rrEA;
me->parent.create_recvresource_rrEA =
NDDS_Transport_FILE_create_recvresource_rrEA;
me->parent.destroy_recvresource_rrEA =
NDDS_Transport_FILE_destroy_recvresource_rrEA;
me->parent.share_recvresource_rrEA =
NDDS_Transport_FILE_share_recvresource_rrEA;
me->parent.unshare_recvresource_rrEA =
NDDS_Transport_FILE_unshare_recvresource_rrEA;
me->parent.create_sendresource_srEA =
NDDS_Transport_FILE_create_sendresource_srEA;
me->parent.destroy_sendresource_srEA =
NDDS_Transport_FILE_destroy_sendresource_srEA;
me->parent.share_sendresource_srEA =
NDDS_Transport_FILE_share_sendresource_srEA;
me->parent.unshare_sendresource_srEA =
NDDS_Transport_FILE_unshare_sendresource_srEA;
me->parent.get_class_name_cEA = NDDS_Transport_FILE_get_class_name_cEA;
me->parent.string_to_address_cEA =
NDDS_Transport_FILE_string_to_address_cEA;
me->parent.get_receive_interfaces_cEA =
NDDS_Transport_FILE_get_receive_interfaces_cEA;
me->parent.register_listener_cEA =
NDDS_Transport_FILE_register_listener_cEA;
me->parent.delete_cEA = NDDS_Transport_FILE_delete_cEA;
return (NDDS_Transport_Plugin *) me;
failed:
NDDS_Transport_FILE_delete_cEA((NDDS_Transport_Plugin *) me, NULL);
return NULL;
}
NDDS_Transport_Plugin *NDDS_Transport_FILE_create(
NDDS_Transport_Address_t *default_network_address_out,
const struct DDS_PropertyQosPolicy *property_in)
{
struct NDDS_Transport_FILE_Property_t fifoProperty =
NDDS_TRANSPORT_FILE_PROPERTY_DEFAULT;
const struct DDS_Property_t *p;
p = DDS_PropertyQosPolicyHelper_lookup_property(
(struct DDS_PropertyQosPolicy *) property_in,
"address");
if (p != NULL) {
strncpy(fifoProperty.address,
p->value,
NDDS_TRANSPORT_FILE_MAX_ADDR_LEN - 1);
fifoProperty.address[NDDS_TRANSPORT_FILE_MAX_ADDR_LEN - 1] = '\0';
} else {
char defaultAddress[] = NDDS_TRANSPORT_FILE_ADDRESS_DEFAULT;
strcpy(fifoProperty.address, defaultAddress);
}
p = DDS_PropertyQosPolicyHelper_lookup_property(
(struct DDS_PropertyQosPolicy *) property_in,
"trace_level");
if (p != NULL) {
fifoProperty.trace_level = strtoul(p->value, NULL, 10);
} else {
fifoProperty.trace_level = 0;
}
p = DDS_PropertyQosPolicyHelper_lookup_property(
(struct DDS_PropertyQosPolicy *) property_in,
"directory");
if (p != NULL) {
strncpy(fifoProperty.directoryRoot,
p->value,
NDDS_TRANSPORT_FILE_MAX_FILEPATH_LEN - 1);
fifoProperty.directoryRoot[NDDS_TRANSPORT_FILE_MAX_FILEPATH_LEN - 1] =
'\0';
} else {
char defaultDirectoryRoot[] =
NDDS_TRANSPORT_FILE_DIRECTORY_ROOT_DEFAULT;
strcpy(fifoProperty.directoryRoot, defaultDirectoryRoot);
}
NDDS_Transport_Plugin *plugin =
NDDS_Transport_FILE_newPlugin(&fifoProperty);
return plugin;
}
/* end of $Id: FILE.c,v 1.20 2008/10/22 19:16:46 jim Exp $ */
| c |
rticonnextdds-examples | data/projects/rticonnextdds-examples/connext_dds/custom_transport/c/FileTransport.h | /*******************************************************************************
(c) 2005-2014 Copyright, Real-Time Innovations, Inc. All rights reserved.
RTI grants Licensee a license to use, modify, compile, and create derivative
works of the Software. Licensee has the right to distribute object form only
for use with RTI products. The Software is provided "as is", with no warranty
of any type, including any warranty for fitness for any purpose. RTI is under
no obligation to maintain or support the Software. RTI shall not be liable for
any incidental or consequential damages arising out of the use or inability to
use the software.
******************************************************************************/
#include "transport/transport_interface.h"
/* ================================================================= */
/* Intra Process Transport-Plugin */
/* ================================================================= */
#define NDDS_TRANSPORT_CLASSID_FILE (20)
#define NDDS_TRANSPORT_FILE_CLASS_NAME "FileTransport"
/* Indicates the number of bits that are significant to the FIFO
transport. In other words the size of the FileTransport addresses.
We make the FileTrasport use 4-byte addresses like IPv4.
This means that we leave the remaining 96 bits configurable for
a "network" address
*/
#define NDDS_TRANSPORT_FILE_ADDRESS_BIT_COUNT (32)
#define NDDS_TRANSPORT_FILE_PROPERTIES_BITMAP_DEFAULT \
(NDDS_TRANSPORT_PROPERTY_BIT_BUFFER_ALWAYS_LOANED)
#define NDDS_TRANSPORT_FILE_GATHER_SEND_BUFFER_COUNT_MAX_DEFAULT (1024)
#define NDDS_TRANSPORT_FILE_MESSAGE_SIZE_MAX_DEFAULT (9216)
#define NDDS_TRANSPORT_FILE_RECEIVED_MESSAGE_COUNT_MAX_DEFAULT (10)
#define NDDS_TRANSPORT_FILE_TRACE_LEVEL_DEFAULT (1)
#define NDDS_TRANSPORT_FILE_RECEIVE_BUFFER_SIZE_DEFAULT \
(NDDS_TRANSPORT_FILE_RECEIVED_MESSAGE_COUNT_MAX_DEFAULT \
* NDDS_TRANSPORT_FILE_MESSAGE_SIZE_MAX_DEFAULT)
#define NDDS_TRANSPORT_FILE_MAX_ADDR_LEN (32)
#define NDDS_TRANSPORT_FILE_ADDRESS_DEFAULT \
{ \
'1', '.', '1', '.', '1', '.', '1', '\0' \
}
#define NDDS_TRANSPORT_FILE_DIRECTORY_ROOT_DEFAULT \
{ \
'/', 't', 'm', 'p', '/', 'd', 'd', 's', '/', 'F', 'i', 'l', 'e', 'T', \
'r', 'a', 'n', 's', 'p', 'o', 'r', 't', '\0' \
}
#define NDDS_TRANSPORT_FILE_MAX_FILEPATH_LEN (128)
struct NDDS_Transport_FILE_Property_t {
/*e @brief Generic properties of all Transport Plugins.
*/
struct NDDS_Transport_Property_t parent;
RTI_INT32 received_message_count_max;
RTI_INT32 receive_buffer_size;
RTI_INT32 trace_level;
char address[NDDS_TRANSPORT_FILE_MAX_ADDR_LEN];
char directoryRoot[NDDS_TRANSPORT_FILE_MAX_FILEPATH_LEN];
};
#define NDDS_TRANSPORT_FILE_PROPERTY_DEFAULT \
{ \
{ \
NDDS_TRANSPORT_CLASSID_FILE, \
NDDS_TRANSPORT_FILE_ADDRESS_BIT_COUNT, \
NDDS_TRANSPORT_FILE_PROPERTIES_BITMAP_DEFAULT, \
NDDS_TRANSPORT_FILE_GATHER_SEND_BUFFER_COUNT_MAX_DEFAULT, \
NDDS_TRANSPORT_FILE_MESSAGE_SIZE_MAX_DEFAULT, \
NULL, \
0, /* allow_interfaces_list */ \
NULL, \
0, /* deny_interfaces_list */ \
NULL, \
0, /* allow_multicast_interfaces_list */ \
NULL, \
0, /* deny_multicast_interfaces_list */ \
}, \
NDDS_TRANSPORT_FILE_RECEIVED_MESSAGE_COUNT_MAX_DEFAULT, \
NDDS_TRANSPORT_FILE_RECEIVE_BUFFER_SIZE_DEFAULT, \
NDDS_TRANSPORT_FILE_TRACE_LEVEL_DEFAULT, \
NDDS_TRANSPORT_FILE_ADDRESS_DEFAULT, \
NDDS_TRANSPORT_FILE_DIRECTORY_ROOT_DEFAULT \
}
NDDS_Transport_Plugin *NDDS_Transport_FILE_newPlugin(
const struct NDDS_Transport_FILE_Property_t *property_in);
struct DDS_PropertyQosPolicy;
NDDS_Transport_Plugin *NDDS_Transport_FILE_create(
NDDS_Transport_Address_t *default_network_address_out,
const struct DDS_PropertyQosPolicy *property_in);
| h |
rticonnextdds-examples | data/projects/rticonnextdds-examples/connext_dds/xml_application_env/c++11/xml_application_env.cpp | /*******************************************************************************
(c) 2020 Copyright, Real-Time Innovations, Inc. All rights reserved.
RTI grants Licensee a license to use, modify, compile, and create derivative
works of the Software. Licensee has the right to distribute object form only
for use with RTI products. The Software is provided "as is", with no warranty
of any type, including any warranty for fitness for any purpose. RTI is under
no obligation to maintain or support 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 <csignal>
#include <dds/dds.hpp>
#include <rti/util/util.hpp> // for sleep()
const std::string QOS_URL = "file://application.xml";
const std::string PARTICIPANT_NAME = "domain_participant_library::participant";
const std::string WRITER_NAME = "publisher::writer";
const std::string READER_NAME = "subscriber::reader";
const std::string KVP_TYPE_NAME = "KeyValuePair";
// 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);
}
class MyDataReaderListener : public dds::sub::NoOpDataReaderListener<
dds::core::xtypes::DynamicData> {
virtual void on_data_available(
dds::sub::DataReader<dds::core::xtypes::DynamicData> &reader)
{
dds::sub::LoanedSamples<dds::core::xtypes::DynamicData> samples =
reader.take();
for (const auto &sample : samples) {
// If the reference we get is valid data, it means we have actual
// data available, otherwise we received metadata.
if (sample.info().valid()) {
std::cout << sample.data() << std::endl;
} else {
std::cout << " Received metadata" << std::endl;
}
}
}
};
// Writes environment variables to a DDS topic. Each environment variable is
// written as a key/value pair to the DDS bus.
//
// writer - a DataWriter for DnyamicData
// kvpType - a key value pair DynamicType
// env - the environment array
void publish_env(
int id,
dds::pub::DataWriter<dds::core::xtypes::DynamicData> &writer,
const dds::core::xtypes::DynamicType &kvpType,
char *env[])
{
// Create one sample from the specified type and populate the id field.
// This sample will be used repeatedly in the loop below.
dds::core::xtypes::DynamicData sample(kvpType);
sample.value<int64_t>("id", id);
// Loop over the env pointer, extract the key and value from the enviroment
// variable, set the values in the sample, and write with the writer.
char buf[4096];
while (*env) {
try {
strncpy(buf, *env, 4095);
buf[4095] = '\0'; // prevent buffer overflow
char *key = strtok(buf, "=");
char *value = strtok(NULL, "=");
sample.value<std::string>("key", key);
sample.value<std::string>("value", value);
env++;
// Now we can write out the populated sample.
writer.write(sample);
} catch (std::exception ex) {
std::cout << "Exception caught publishing sample: " << ex.what()
<< std::endl;
}
}
}
int main(int argc, char *argv[], char *envp[])
{
setup_signal_handlers();
// Create the QosPovider from the specified xml file.
// The application.xml filename is used in this example instead of the
// default.
dds::core::QosProvider qos_provider(QOS_URL);
// Create the participant as defined in the xml file. This instantiats the
// participant registeres the types, and creates the child publisher,
// subscriber, reader and writer.
dds::domain::DomainParticipant participant =
qos_provider->create_participant_from_config(PARTICIPANT_NAME);
// Lookup the specific KeyValuePair type as defined in the xml file.
// This will be needed to create samples of the correct type when
// publishing.
const dds::core::xtypes::DynamicType &myType =
qos_provider->type(KVP_TYPE_NAME);
// Find the DataWriter defined in the xml by using the participant and the
// publisher::writer pair as the datawriter name.
dds::pub::DataWriter<dds::core::xtypes::DynamicData> writer =
rti::pub::find_datawriter_by_name<
dds::pub::DataWriter<dds::core::xtypes::DynamicData>>(
participant,
WRITER_NAME);
// Find the DataReader defined in the xml by using the participant and the
// subscriber::reader pair as the datareader name.
dds::sub::DataReader<dds::core::xtypes::DynamicData> reader =
rti::sub::find_datareader_by_name<
dds::sub::DataReader<dds::core::xtypes::DynamicData>>(
participant,
READER_NAME);
// Create a shared pointer for MyDataReaderListener
auto my_listener = std::make_shared<MyDataReaderListener>();
// Associate the listener to the data reader.
reader.set_listener(my_listener);
// Ignore our own publications so they do not trigger our data listener.
dds::domain::ignore(participant, participant.instance_handle());
// Application id to uniquely identify data from a particular application
int id = std::rand();
// Publish the environment vairables to the topic configured in the
// xml writer.
while (!shutdown_requested) {
std::cout << "Publishing Environment" << std::endl;
publish_env(id, writer, myType, envp);
rti::util::sleep(dds::core::Duration(2));
}
return 0;
}
| cpp |
rticonnextdds-examples | data/projects/rticonnextdds-examples/connext_dds/flat_data_api/c++98/CameraImage_publisher.cxx | /*
* (c) 2019 Copyright, Real-Time Innovations, Inc. All rights reserved.
*
* RTI grants Licensee a license to use, modify, compile, and create derivative
* works of the Software. Licensee has the right to distribute object form
* only for use with RTI products. The Software is provided "as is", with no
* warranty of any type, including any warranty for fitness for any purpose.
* RTI is under no obligation to maintain or support the Software. RTI shall
* not be liable for any incidental or consequential damages arising out of the
* use or inability to use the software.
*/
#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include "CameraImage.h"
#include "CameraImageSupport.h"
#include "ndds/ndds_cpp.h"
#include "application.h"
using namespace application;
const int PIXEL_COUNT = 10;
static int shutdown_participant(
DDSDomainParticipant *participant,
const char *shutdown_message,
int status);
// Simplest way to create the data sample
bool build_data_sample(CameraImageBuilder &builder, int seed)
{
// The Traditional C++ API doesn't use exceptions, so errors must be checked
// after each operation.
//
// Depending on the function, the error can be checked via the return value
// when they return a boolean, an Offset (is_null()), or a Builder
// (is_valid()). A Builder also provides check_failure() when the error
// can't be notified with the return value.
if (!builder.add_format(RGB)) {
return false;
}
if (seed % 3 == 0) {
// All fields in a mutable FlatData type are in effect optional. For
// illustration purposes, we will omit the resolution field in some
// samples
ResolutionOffset resolution_offset = builder.add_resolution();
if (resolution_offset.is_null()) {
return false;
}
if (!resolution_offset.height(100)) {
return false;
}
if (!resolution_offset.width(200)) {
return false;
}
}
rti::flat::StringBuilder string_builder = builder.build_source();
if (string_builder.check_failure()) {
return false;
}
string_builder.set_string("CAM-1");
if (string_builder.check_failure()) {
return false;
}
string_builder.finish();
if (string_builder.check_failure()) {
return false;
}
// Method 1 - Build the pixel sequence element by element
rti::flat::FinalSequenceBuilder<PixelOffset> pixels_builder =
builder.build_pixels();
if (!pixels_builder.is_valid()) {
return false;
}
for (int i = 0; i < PIXEL_COUNT; i++) {
PixelOffset pixel = pixels_builder.add_next();
if (pixel.is_null()) {
return false;
}
if (!pixel.red((seed + i) % 100)) {
return false;
}
if (!pixel.green((seed + i + 1) % 100)) {
return false;
}
if (!pixel.blue((seed + i + 2) % 100)) {
return false;
}
}
rti::flat::SequenceOffset<PixelOffset> pixels = pixels_builder.finish();
if (pixels.is_null()) {
return false;
}
return true;
}
//
// Note:
// build_data_sample_fast disabled due to known issue.
// Contact [email protected] for a fix.
//
#if 0
// Creates the same data sample using a faster method
// to populate the pixel sequence
bool build_data_sample_fast(CameraImageBuilder& builder, int seed)
{
// The initialization of these members doesn't change
rti::flat::StringBuilder string_builder = builder.build_source();
if (string_builder.check_failure()) {
return false;
}
string_builder.set_string("CAM-1");
if (string_builder.check_failure()) {
return false;
}
string_builder.finish();
if (string_builder.check_failure()) {
return false;
}
if (!builder.add_format(RGB)) {
return false;
}
ResolutionOffset resolution_offset = builder.add_resolution();
if (resolution_offset.is_null()) {
return false;
}
if (!resolution_offset.height(100)) {
return false;
}
if (!resolution_offset.width(200)) {
return false;
}
// Populate the pixel sequence accessing the byte buffer directly, instead
// of iterating through each element Offset
// 1) Use the builder to add all the elements at once. This operation is
// cheap (it just advances the underlying buffer without initializing anything)
rti::flat::FinalSequenceBuilder<PixelOffset> pixels_builder =
builder.build_pixels();
if (!pixels_builder.is_valid()) {
return false;
}
pixels_builder.add_n(PIXEL_COUNT);
if (pixels_builder.check_failure()) {
return false;
}
rti::flat::SequenceOffset<PixelOffset> pixels = pixels_builder.finish();
if (pixels.is_null()) {
return false;
}
// 2) Use plain_cast to access the buffer as an array of regular C++ Pixels
// (pixel_array's type is PixelPlainHelper*)
PixelPlainHelper *pixel_array = rti::flat::plain_cast(pixels);
if (pixel_array == NULL) {
return false;
}
for (int i = 0; i < PIXEL_COUNT; i++) {
PixelPlainHelper& pixel = pixel_array[i];
pixel.red = (seed + i) % 100;
pixel.green = (seed + i + 1) % 100;
pixel.blue = (seed + i + 2) % 100;
}
return true;
}
#else // See Note in #if above
bool build_data_sample_fast(CameraImageBuilder &builder, int seed)
{
return build_data_sample(builder, seed);
}
#endif
int run_publisher_application(unsigned int domain_id, unsigned int sample_count)
{
DDS_Duration_t send_period = { 4, 0 };
// Start communicating in a domain, usually one participant per application
DDSDomainParticipant *participant =
DDSTheParticipantFactory->create_participant(
domain_id,
DDS_PARTICIPANT_QOS_DEFAULT,
NULL /* 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 = CameraImageTypeSupport::get_type_name();
DDS_ReturnCode_t retcode =
CameraImageTypeSupport::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 CameraImage",
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 StringLine" Topic
DDSDataWriter *untyped_writer = publisher->create_datawriter(
topic,
DDS_DATAWRITER_QOS_DEFAULT,
NULL /* listener */,
DDS_STATUS_MASK_NONE);
if (untyped_writer == NULL) {
return shutdown_participant(
participant,
"create_datawriter error",
EXIT_FAILURE);
}
// Narrow casts from an untyped DataWriter to a writer of your type
CameraImageDataWriter *typed_writer =
CameraImageDataWriter::narrow(untyped_writer);
if (typed_writer == NULL) {
return shutdown_participant(
participant,
"DataWriter narrow error",
EXIT_FAILURE);
}
// Main loop, write data
for (unsigned int samples_written = 0;
!shutdown_requested && samples_written < sample_count;
++samples_written) {
CameraImageBuilder builder =
rti::flat::build_data<CameraImage>(typed_writer);
if (builder.check_failure()) {
return shutdown_participant(
participant,
"builder creation error",
EXIT_FAILURE);
}
// Build the CameraImage data sample using the builder
bool build_result = false;
if (samples_written % 2 == 0) {
build_result =
build_data_sample(builder, samples_written); // method
// 1
} else {
build_result =
build_data_sample_fast(builder, samples_written); // method
// 2
}
if (!build_result) {
return shutdown_participant(
participant,
"error building the sample",
EXIT_FAILURE);
}
// Create the sample
CameraImage *data = builder.finish_sample();
if (data == NULL) {
return shutdown_participant(
participant,
"finish_sample() error",
EXIT_FAILURE);
}
std::cout << "Writing CameraImage, count " << samples_written
<< std::endl;
retcode = typed_writer->write(*data, DDS_HANDLE_NIL);
if (retcode != DDS_RETCODE_OK) {
std::cerr << "write error " << retcode << std::endl;
}
NDDSUtility::sleep(send_period);
}
// Delete all entities (DataWriter, Topic, Publisher, DomainParticipant)
return shutdown_participant(participant, "Shutting down", EXIT_SUCCESS);
}
// Delete all entities
static int shutdown_participant(
DDSDomainParticipant *participant,
const char *shutdown_message,
int status)
{
DDS_ReturnCode_t retcode;
std::cout << shutdown_message << std::endl;
if (participant != NULL) {
// Cleanup everything created by this Participant
retcode = participant->delete_contained_entities();
if (retcode != DDS_RETCODE_OK) {
std::cerr << "delete_contained_entities error " << retcode
<< std::endl;
status = EXIT_FAILURE;
}
retcode = DDSTheParticipantFactory->delete_participant(participant);
if (retcode != DDS_RETCODE_OK) {
std::cerr << "delete_participant error " << retcode << std::endl;
status = EXIT_FAILURE;
}
}
return status;
}
int main(int argc, char *argv[])
{
// Parse arguments and handle control-C
ApplicationArguments arguments;
parse_arguments(arguments, argc, argv);
if (arguments.parse_result == PARSE_RETURN_EXIT) {
return EXIT_SUCCESS;
} else if (arguments.parse_result == PARSE_RETURN_FAILURE) {
return EXIT_FAILURE;
}
setup_signal_handlers();
// Sets Connext verbosity to help debugging
NDDSConfigLogger::get_instance()->set_verbosity(arguments.verbosity);
int status = run_publisher_application(
arguments.domain_id,
arguments.sample_count);
// Releases the memory used by the participant factory. Optional at
// application exit
DDS_ReturnCode_t retcode = DDSDomainParticipantFactory::finalize_instance();
if (retcode != DDS_RETCODE_OK) {
std::cerr << "finalize_instance error " << retcode << std::endl;
status = EXIT_FAILURE;
}
return status;
}
| cxx |
rticonnextdds-examples | data/projects/rticonnextdds-examples/connext_dds/flat_data_api/c++98/CameraImage_subscriber.cxx |
/*
* (c) 2019 Copyright, Real-Time Innovations, Inc. All rights reserved.
*
* RTI grants Licensee a license to use, modify, compile, and create derivative
* works of the Software. Licensee has the right to distribute object form
* only for use with RTI products. The Software is provided "as is", with no
* warranty of any type, including any warranty for fitness for any purpose.
* RTI is under no obligation to maintain or support the Software. RTI shall
* not be liable for any incidental or consequential damages arising out of the
* use or inability to use the software.
*/
#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include "CameraImage.h"
#include "CameraImageSupport.h"
#include "ndds/ndds_cpp.h"
#include "application.h"
using namespace application;
static int shutdown_participant(
DDSDomainParticipant *participant,
const char *shutdown_message,
int status);
// Shows how to access a flat data sample (this is the simplest code, for
// a more efficient implementation, see print_average_pixel_fast).
bool print_average_pixel_simple(const CameraImage &sample)
{
CameraImageConstOffset camera = sample.root();
if (camera.is_null()) {
return false;
}
rti::flat::SequenceOffset<PixelConstOffset> pixels = camera.pixels();
if (pixels.is_null()) {
return false;
}
unsigned int pixel_count = pixels.element_count();
unsigned int red_sum = 0, green_sum = 0, blue_sum = 0;
for (rti::flat::SequenceOffset<PixelConstOffset>::iterator pixels_it =
pixels.begin();
pixels_it != pixels.end();
++pixels_it) {
PixelConstOffset pixel = *pixels_it;
if (pixel.is_null()) {
return false;
}
red_sum += pixel.red();
green_sum += pixel.green();
blue_sum += pixel.blue();
}
std::cout << "Avg. pixel: (" << red_sum / pixel_count << ", "
<< green_sum / pixel_count << ", " << blue_sum / pixel_count
<< ")";
return true;
}
// Shows how to access a flat data sample in a more efficient way
bool print_average_pixel_fast(const CameraImage &sample)
{
CameraImageConstOffset camera = sample.root();
if (camera.is_null()) {
return false;
}
rti::flat::SequenceOffset<PixelConstOffset> pixels = camera.pixels();
if (pixels.is_null()) {
return false;
}
unsigned int pixel_count = pixels.element_count();
if (pixel_count == 0) {
std::cout << "WARNING: the pixels count is 0" << std::endl;
return false;
}
PixelPlainHelper *pixel_array = rti::flat::plain_cast(pixels);
if (pixel_array == NULL) {
return false;
}
unsigned int red_sum = 0, green_sum = 0, blue_sum = 0;
for (unsigned int i = 0; i < pixel_count; i++) {
const PixelPlainHelper &pixel = pixel_array[i];
red_sum += pixel.red;
green_sum += pixel.green;
blue_sum += pixel.blue;
}
std::cout << "Avg. pixel: (" << red_sum / pixel_count << ", "
<< green_sum / pixel_count << ", " << blue_sum / pixel_count
<< ")";
return true;
}
unsigned int process_data(CameraImageDataReader *typed_reader)
{
CameraImageSeq 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) {
CameraImageOffset root = data_seq[i].root();
if (root.is_null()) {
std::cerr << "error taking sample root\n";
continue;
}
// Print the source name
rti::flat::StringOffset source = root.source();
if (!source.is_null()) {
std::cout << root.source().get_string() << ": ";
} else {
std::cout << "(Unknown source): ";
}
// Print the field resolution (if it was published)
ResolutionOffset resolution = root.resolution();
if (!resolution.is_null()) {
std::cout << "(Resolution: " << resolution.height() << " x "
<< resolution.width() << ") ";
}
// print_average_pixel_simple(data_seq[i]); // Method 1
print_average_pixel_fast(data_seq[i]); // Method 2
std::cout << std::endl;
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 = CameraImageTypeSupport::get_type_name();
DDS_ReturnCode_t retcode =
CameraImageTypeSupport::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 CameraImage",
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 CameraImage" 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
CameraImageDataReader *typed_reader =
CameraImageDataReader::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;
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/flat_data_api/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/flat_data_api/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/flat_data_api/c++11/CameraImage_publisher.cxx | /*
* (c) 2019 Copyright, Real-Time Innovations, Inc. All rights reserved.
*
* RTI grants Licensee a license to use, modify, compile, and create derivative
* works of the Software. Licensee has the right to distribute object form
* only for use with RTI products. The Software is provided "as is", with no
* warranty of any type, including any warranty for fitness for any purpose.
* RTI is under no obligation to maintain or support the Software. RTI shall
* not be liable for any incidental or consequential damages arising out of the
* use or inability to use the software.
*/
#include <iostream>
#include <dds/pub/ddspub.hpp>
#include <rti/config/Logger.hpp>
#include <rti/util/util.hpp> // for sleep()
#include "CameraImage.hpp"
#include "application.hpp"
const int PIXEL_COUNT = 10;
// Simplest way to create the data sample
void build_data_sample(CameraImageBuilder &builder, int seed)
{
builder.add_format(Format::RGB);
if (seed % 3 == 0) {
// All fields in a mutable FlatData type are in effect optional. For
// illustration purposes, we will omit the resolution field in some
// samples
auto resolution_offset = builder.add_resolution();
resolution_offset.height(100);
resolution_offset.width(200);
}
auto string_builder = builder.build_source();
string_builder.set_string("CAM-1");
string_builder.finish();
// Method 1 - Build the pixel sequence element by element
auto pixels_builder = builder.build_pixels();
for (int i = 0; i < PIXEL_COUNT; i++) {
auto pixel = pixels_builder.add_next();
pixel.red((seed + i) % 100);
pixel.green((seed + i + 1) % 100);
pixel.blue((seed + i + 2) % 100);
}
pixels_builder.finish();
}
// Creates the same data sample using a faster method
// to populate the pixel sequence
void build_data_sample_fast(CameraImageBuilder &builder, int seed)
{
// The initialization of these members doesn't change
builder.build_source().set_string("CAM-1");
builder.add_format(Format::RGB);
auto resolution_offset = builder.add_resolution();
resolution_offset.height(100);
resolution_offset.width(200);
// Populate the pixel sequence accessing the byte buffer directly, instead
// of iterating through each element Offset
// 1) Use the builder to add all the elements at once. This operation is
// cheap (it just advances the underlying buffer without initializing
// anything)
auto pixels_builder = builder.build_pixels();
pixels_builder.add_n(PIXEL_COUNT);
auto pixels = pixels_builder.finish();
// 2) Use plain_cast to access the buffer as an array of regular C++ Pixels
// (pixel_array's type is PixelPlainHelper*)
auto pixel_array = rti::flat::plain_cast(pixels);
for (int i = 0; i < PIXEL_COUNT; i++) {
auto &pixel = pixel_array[i];
pixel.red((seed + i) % 100);
pixel.green((seed + i + 1) % 100);
pixel.blue((seed + i + 2) % 100);
}
}
void 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<CameraImage> topic(participant, "Example CameraImage");
// Create a DataWriter with default Qos (Publisher created in-line)
dds::pub::DataWriter<CameraImage> writer(
dds::pub::Publisher(participant),
topic);
for (unsigned int samples_written = 0;
!application::shutdown_requested && samples_written < sample_count;
samples_written++) {
CameraImageBuilder builder = rti::flat::build_data(writer);
// Build the CameraImage data sample using the builder
if (samples_written % 2 == 0) {
build_data_sample(builder, samples_written); // method 1
} else {
build_data_sample_fast(builder, samples_written); // method 2
}
// Create the sample
CameraImage *sample = builder.finish_sample();
std::cout << "Writing CameraImage, count " << samples_written
<< std::endl;
writer.write(*sample);
rti::util::sleep(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_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/flat_data_api/c++11/CameraImage_subscriber.cxx | /*
* (c) 2019 Copyright, Real-Time Innovations, Inc. All rights reserved.
*
* RTI grants Licensee a license to use, modify, compile, and create derivative
* works of the Software. Licensee has the right to distribute object form
* only for use with RTI products. The Software is provided "as is", with no
* warranty of any type, including any warranty for fitness for any purpose.
* RTI is under no obligation to maintain or support the Software. RTI shall
* not be liable for any incidental or consequential damages arising out of the
* use or inability to use the software.
*/
#include <algorithm>
#include <iostream>
#include <dds/core/ddscore.hpp>
#include <dds/sub/ddssub.hpp>
#include <rti/config/Logger.hpp> // for logging
#include "CameraImage.hpp"
#include "application.hpp"
// Shows how to access a flat data sample (this is the simplest code, for
// a more efficient implementation, see print_average_pixel_fast).
void print_average_pixel_simple(const CameraImage &sample)
{
auto pixels = sample.root().pixels();
auto pixel_count = pixels.element_count();
unsigned int red_sum = 0, green_sum = 0, blue_sum = 0;
for (auto &&pixel : pixels) {
red_sum += pixel.red();
green_sum += pixel.green();
blue_sum += pixel.blue();
}
std::cout << "Avg. pixel: (" << red_sum / pixel_count << ", "
<< green_sum / pixel_count << ", " << blue_sum / pixel_count
<< ")";
}
// Shows how to access a flat data sample in a more efficient way
void print_average_pixel_fast(const CameraImage &sample)
{
auto pixels = sample.root().pixels();
auto pixel_count = pixels.element_count();
if (pixel_count == 0) {
return;
}
auto pixel_array = rti::flat::plain_cast(pixels);
unsigned int red_sum = 0, green_sum = 0, blue_sum = 0;
for (unsigned int i = 0; i < pixel_count; i++) {
const auto &pixel = pixel_array[i];
red_sum += pixel.red();
green_sum += pixel.green();
blue_sum += pixel.blue();
}
std::cout << "Avg. pixel: (" << red_sum / pixel_count << ", "
<< green_sum / pixel_count << ", " << blue_sum / pixel_count
<< ")";
}
int process_data(dds::sub::DataReader<CameraImage> &reader)
{
// Take all samples
int count = 0;
auto samples = rti::sub::valid_data(reader.take());
for (const auto &sample : samples) {
count++;
auto root = sample.data().root();
// Print the source name. We assume the publisher always sets this
// field; if not, root.source().is_null() is true, and get_string() will
// throw an exception
std::cout << root.source().get_string() << ": ";
// Print the field resolution. In this case we assume the publisher may
// decide not to send this field
auto resolution = root.resolution();
if (!resolution.is_null()) {
std::cout << "(Resolution: " << resolution.height() << " x "
<< resolution.width() << ") ";
}
// print_average_pixel_simple(sample.data()); // Method 1
print_average_pixel_fast(sample.data()); // Method 2
std::cout << std::endl;
}
return count;
}
void run_subscriber_application(
unsigned int domain_id,
unsigned int sample_count)
{
// Create a DomainParticipant with default Qos
dds::domain::DomainParticipant participant(domain_id);
// Create a Topic -- and automatically register the type
dds::topic::Topic<CameraImage> topic(participant, "Example CameraImage");
// Create a DataReader with default Qos (Subscriber created in-line)
dds::sub::DataReader<CameraImage> reader(
dds::sub::Subscriber(participant),
topic);
// Create a ReadCondition for any data on this reader and associate a
// handler
int count = 0;
dds::sub::cond::ReadCondition read_condition(
reader,
dds::sub::status::DataState::any(),
[&reader, &count](/* dds::core::cond::Condition condition */) {
count += process_data(reader);
});
// Create a WaitSet and attach the ReadCondition
dds::core::cond::WaitSet waitset;
waitset += read_condition;
while (!application::shutdown_requested && count < sample_count) {
// Dispatch will call the handlers associated to the WaitSet conditions
// when they activate
std::cout << "CameraImage subscriber sleeping for 4 sec..."
<< std::endl;
waitset.dispatch(dds::core::Duration(4)); // Wait up to 4s each time
}
}
int main(int argc, char *argv[])
{
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/network_capture/01_shared_memory_and_udp/c++/network_capture_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.
*/
/*
* A simple HelloWorld using network capture to save DomainParticipant traffic.
*
* This example is a simple hello world running network capture for both a
* publisher participant (network_capture_publisher.cxx).and a subscriber
* participant (network_capture_subscriber.cxx). It shows the basic flow when
* working with network capture:
* - Enabling before anything else.
* - Start capturing traffic (for one or all participants).
* - Pause/resume capturing traffic (for one or all participants).
* - Stop capturing trafffic (for one or all participants).
* - Disable after everything else.
*/
#include <stdio.h>
#include <stdlib.h>
#include "ndds/ndds_cpp.h"
#include "network_capture.h"
#include "network_captureSupport.h"
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) {
fprintf(stderr, "delete_contained_entities error %d\n", retcode);
status = -1;
}
retcode = DDSTheParticipantFactory->delete_participant(participant);
if (retcode != DDS_RETCODE_OK) {
fprintf(stderr, "delete_participant error %d\n", retcode);
status = -1;
}
}
retcode = DDSDomainParticipantFactory::finalize_instance();
if (retcode != DDS_RETCODE_OK) {
fprintf(stderr, "finalize_instance error %d\n", retcode);
status = -1;
}
/*
* Disable network capture.
*
* This must be:
* - The last network capture function that is called.
*/
if (!NDDSUtilityNetworkCapture::disable()) {
fprintf(stderr, "Error disabling network capture\n");
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;
NetworkCaptureDataWriter *NetworkCapture_writer = NULL;
NetworkCapture *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 };
/*
* Enable network capture.
*
* This must be called before:
* - Any other network capture function is called.
* - Creating the participants for which we want to capture traffic.
*/
if (!NDDSUtilityNetworkCapture::enable()) {
fprintf(stderr, "Error enabling network capture\n");
return -1;
}
participant = DDSTheParticipantFactory->create_participant(
domainId,
DDS_PARTICIPANT_QOS_DEFAULT,
NULL, /* listener */
DDS_STATUS_MASK_NONE);
if (participant == NULL) {
fprintf(stderr, "create_participant error\n");
publisher_shutdown(participant);
return -1;
}
/*
* Start capturing traffic for all participants.
*
* All participants: those already created and those yet to be created.
* Default parameters: all transports and some other sane defaults.
*
* A capture file will be created for each participant. The capture file
* will start with the prefix "publisher" and continue with a suffix
* dependent on the participant's GUID.
*/
if (!NDDSUtilityNetworkCapture::start("publisher")) {
fprintf(stderr, "Error starting network capture\n");
return -1;
}
/* The example continues as the usual Connext DDS HelloWorld. */
publisher = participant->create_publisher(
DDS_PUBLISHER_QOS_DEFAULT,
NULL, /* listener */
DDS_STATUS_MASK_NONE);
if (publisher == NULL) {
fprintf(stderr, "create_publisher error\n");
publisher_shutdown(participant);
return -1;
}
type_name = NetworkCaptureTypeSupport::get_type_name();
retcode = NetworkCaptureTypeSupport::register_type(participant, type_name);
if (retcode != DDS_RETCODE_OK) {
fprintf(stderr, "register_type error %d\n", retcode);
publisher_shutdown(participant);
return -1;
}
topic = participant->create_topic(
"Network capture shared memory example",
type_name,
DDS_TOPIC_QOS_DEFAULT,
NULL, /* listener */
DDS_STATUS_MASK_NONE);
if (topic == NULL) {
fprintf(stderr, "create_topic error\n");
publisher_shutdown(participant);
return -1;
}
writer = publisher->create_datawriter(
topic,
DDS_DATAWRITER_QOS_DEFAULT,
NULL, /* listener */
DDS_STATUS_MASK_NONE);
if (writer == NULL) {
fprintf(stderr, "create_datawriter error\n");
publisher_shutdown(participant);
return -1;
}
NetworkCapture_writer = NetworkCaptureDataWriter::narrow(writer);
if (NetworkCapture_writer == NULL) {
fprintf(stderr, "DataWriter narrow error\n");
publisher_shutdown(participant);
return -1;
}
instance = NetworkCaptureTypeSupport::create_data();
if (instance == NULL) {
fprintf(stderr, "NetworkCaptureTypeSupport::create_data error\n");
publisher_shutdown(participant);
return -1;
}
for (count = 0; (sample_count == 0) || (count < sample_count); ++count) {
printf("Writing NetworkCapture, count %d\n", count);
RTIOsapiUtility_snprintf(instance->msg, 128, "Hello World (%d)", count);
/*
* Here we are going to pause capturing for some samples.
* The resulting pcap file will not contain them.
*/
if (count == 4 && !NDDSUtilityNetworkCapture::pause()) {
fprintf(stderr, "Error pausing network capture\n");
publisher_shutdown(participant);
return -1;
} else if (count == 6 && !NDDSUtilityNetworkCapture::resume()) {
fprintf(stderr, "Error resuming network capture\n");
publisher_shutdown(participant);
return -1;
}
retcode = NetworkCapture_writer->write(*instance, instance_handle);
if (retcode != DDS_RETCODE_OK) {
fprintf(stderr, "write error %d\n", retcode);
}
NDDSUtility::sleep(send_period);
}
retcode = NetworkCapture_writer->unregister_instance(
*instance,
instance_handle);
if (retcode != DDS_RETCODE_OK) {
fprintf(stderr, "unregister instance error %d\n", retcode);
}
retcode = NetworkCaptureTypeSupport::delete_data(instance);
if (retcode != DDS_RETCODE_OK) {
fprintf(stderr,
"NetworkCaptureTypeSupport::delete_data error %d\n",
retcode);
}
/*
* Before deleting the participants that are capturing, we must stop
* network capture for them.
*/
if (!NDDSUtilityNetworkCapture::stop()) {
fprintf(stderr, "Error stopping network capture\n");
publisher_shutdown(participant);
return -1;
}
return publisher_shutdown(participant);
}
int main(int argc, char *argv[])
{
int domain_id = 0;
int sample_count = 0; /* infinite loop */
if (argc >= 2) {
domain_id = atoi(argv[1]);
}
if (argc >= 3) {
sample_count = atoi(argv[2]);
}
return publisher_main(domain_id, sample_count);
}
| cxx |
rticonnextdds-examples | data/projects/rticonnextdds-examples/connext_dds/network_capture/01_shared_memory_and_udp/c++/network_capture_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.
*/
/*
* A simple NetworkCapture using network capture to save DomainParticipant
* traffic.
*
* This example is a simple hello world running network capture for both a
* publisher participant (network_capture_publisher.cxx).and a subscriber
* participant (network_capture_subscriber.cxx). It shows the basic flow when
* working with network capture:
* - Enabling before anything else.
* - Start capturing traffic (for one or all participants).
* - Pause/resume capturing traffic (for one or all participants).
* - Stop capturing trafffic (for one or all participants).
* - Disable after everything else.
*/
#include <stdio.h>
#include <stdlib.h>
#include "ndds/ndds_cpp.h"
#include "network_capture.h"
#include "network_captureSupport.h"
class NetworkCaptureListener : 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 NetworkCaptureListener::on_data_available(DDSDataReader *reader)
{
NetworkCaptureDataReader *NetworkCapture_reader = NULL;
NetworkCaptureSeq data_seq;
DDS_SampleInfoSeq info_seq;
DDS_ReturnCode_t retcode;
int i;
NetworkCapture_reader = NetworkCaptureDataReader::narrow(reader);
if (NetworkCapture_reader == NULL) {
fprintf(stderr, "DataReader narrow error\n");
return;
}
retcode = NetworkCapture_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) {
fprintf(stderr, "take error %d\n", retcode);
return;
}
for (i = 0; i < data_seq.length(); ++i) {
if (info_seq[i].valid_data) {
printf("Received data\n");
NetworkCaptureTypeSupport::print_data(&data_seq[i]);
}
}
retcode = NetworkCapture_reader->return_loan(data_seq, info_seq);
if (retcode != DDS_RETCODE_OK) {
fprintf(stderr, "return loan error %d\n", retcode);
}
}
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) {
fprintf(stderr, "delete_contained_entities error %d\n", retcode);
status = -1;
}
retcode = DDSTheParticipantFactory->delete_participant(participant);
if (retcode != DDS_RETCODE_OK) {
fprintf(stderr, "delete_participant error %d\n", retcode);
status = -1;
}
}
retcode = DDSDomainParticipantFactory::finalize_instance();
if (retcode != DDS_RETCODE_OK) {
fprintf(stderr, "finalize_instance error %d\n", retcode);
status = -1;
}
if (!NDDSUtilityNetworkCapture::disable()) {
fprintf(stderr, "Error disabling network capture\n");
status = -1;
}
return status;
}
extern "C" int subscriber_main(int domainId, int sample_count)
{
DDSDomainParticipant *participant = NULL;
DDSSubscriber *subscriber = NULL;
DDSTopic *topic = NULL;
NetworkCaptureListener *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;
DDS_Boolean success = DDS_BOOLEAN_FALSE;
/*
* Enable network capture.
*
* This must be called before:
* - Any other network capture function is called.
* - Creating the participants for which we want to capture traffic.
*/
success = NDDSUtilityNetworkCapture::enable();
if (!success) {
fprintf(stderr, "Error enabling network capture\n");
return -1;
}
/*
* Start capturing traffic for all participants.
*
* All participants: those already created and those yet to be created.
* Default parameters: all transports and some other sane defaults.
*
* A capture file will be created for each participant. The capture file
* will start with the prefix "subscriber" and continue with a suffix
* dependent on the participant's GUID.
*/
success = NDDSUtilityNetworkCapture::start("subscriber");
if (!success) {
fprintf(stderr, "Error starting network capture\n");
return -1;
}
participant = DDSTheParticipantFactory->create_participant(
domainId,
DDS_PARTICIPANT_QOS_DEFAULT,
NULL, /* listener */
DDS_STATUS_MASK_NONE);
if (participant == NULL) {
fprintf(stderr, "create_participant error\n");
subscriber_shutdown(participant);
return -1;
}
subscriber = participant->create_subscriber(
DDS_SUBSCRIBER_QOS_DEFAULT,
NULL, /* listener */
DDS_STATUS_MASK_NONE);
if (subscriber == NULL) {
fprintf(stderr, "create_subscriber error\n");
subscriber_shutdown(participant);
return -1;
}
type_name = NetworkCaptureTypeSupport::get_type_name();
retcode = NetworkCaptureTypeSupport::register_type(participant, type_name);
if (retcode != DDS_RETCODE_OK) {
fprintf(stderr, "register_type error %d\n", retcode);
subscriber_shutdown(participant);
return -1;
}
topic = participant->create_topic(
"Network capture shared memory example",
type_name,
DDS_TOPIC_QOS_DEFAULT,
NULL, /* listener */
DDS_STATUS_MASK_NONE);
if (topic == NULL) {
fprintf(stderr, "create_topic error\n");
subscriber_shutdown(participant);
return -1;
}
reader_listener = new NetworkCaptureListener();
reader = subscriber->create_datareader(
topic,
DDS_DATAREADER_QOS_DEFAULT,
reader_listener,
DDS_STATUS_MASK_ALL);
if (reader == NULL) {
fprintf(stderr, "create_datareader error\n");
subscriber_shutdown(participant);
delete reader_listener;
return -1;
}
for (count = 0; (sample_count == 0) || (count < sample_count); ++count) {
printf("NetworkCapture subscriber sleeping for %d sec...\n",
receive_period.sec);
NDDSUtility::sleep(receive_period);
}
/*
* But before deleting the participants that are capturing, we must stop
* network capture for them.
*/
success = NDDSUtilityNetworkCapture::stop();
if (!success) {
fprintf(stderr, "Error stopping network capture\n");
subscriber_shutdown(participant);
return -1;
}
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 */
if (argc >= 2) {
domain_id = atoi(argv[1]);
}
if (argc >= 3) {
sample_count = atoi(argv[2]);
}
return subscriber_main(domain_id, sample_count);
}
| cxx |
rticonnextdds-examples | data/projects/rticonnextdds-examples/connext_dds/network_capture/01_shared_memory_and_udp/c++98/network_capture_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.
*/
/*
* A simple HelloWorld using network capture to save DomainParticipant traffic.
*
* This example is a simple hello world running network capture for both a
* publisher participant (network_capture_publisher.cxx).and a subscriber
* participant (network_capture_subscriber.cxx). It shows the basic flow when
* working with network capture:
* - Enabling before anything else.
* - Start capturing traffic (for one or all participants).
* - Pause/resume capturing traffic (for one or all participants).
* - Stop capturing trafffic (for one or all participants).
* - Disable after everything else.
*/
#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include "ndds/ndds_cpp.h"
#include "network_capture.h"
#include "network_captureSupport.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 };
DDS_InstanceHandle_t instance_handle = DDS_HANDLE_NIL;
/*
* Enable network capture.
*
* This must be called before:
* - Any other network capture function is called.
* - Creating the participants for which we want to capture traffic.
*/
if (!NDDSUtilityNetworkCapture::enable()) {
std::cerr << "Error enabling network capture\n";
return -1;
}
// 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 capturing traffic for all participants.
*
* All participants: those already created and those yet to be created.
* Default parameters: all transports and some other sane defaults.
*
* A capture file will be created for each participant. The capture file
* will start with the prefix "publisher" and continue with a suffix
* dependent on the participant's GUID.
*/
if (!NDDSUtilityNetworkCapture::start("publisher")) {
std::cerr << "Error starting network capture\n";
return 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 = NetworkCaptureTypeSupport::get_type_name();
DDS_ReturnCode_t retcode =
NetworkCaptureTypeSupport::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(
"Network capture shared memory example",
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 prueba" Topic
DDSDataWriter *untyped_writer = publisher->create_datawriter(
topic,
DDS_DATAWRITER_QOS_DEFAULT,
NULL, /* listener */
DDS_STATUS_MASK_NONE);
if (untyped_writer == NULL) {
return shutdown_participant(
participant,
"create_datawriter error",
EXIT_FAILURE);
}
// Narrow casts from an untyped DataWriter to a writer of your type
NetworkCaptureDataWriter *typed_writer =
NetworkCaptureDataWriter::narrow(untyped_writer);
if (typed_writer == NULL) {
return shutdown_participant(
participant,
"DataWriter narrow error",
EXIT_FAILURE);
}
// Create data for writing, allocating all members
NetworkCapture *data = NetworkCaptureTypeSupport::create_data();
if (data == NULL) {
return shutdown_participant(
participant,
"NetworkCaptureTypeSupport::create_data error",
EXIT_FAILURE);
}
// Main loop, write data
for (unsigned int samples_written = 0;
!shutdown_requested && samples_written < sample_count;
++samples_written) {
std::cout << "Writing NetworkCapture, count " << samples_written
<< std::endl;
RTIOsapiUtility_snprintf(
data->msg,
128,
"Hello World (%d)",
samples_written);
/*
* Here we are going to pause capturing for some samples.
* The resulting pcap file will not contain them.
*/
if (samples_written == 4 && !NDDSUtilityNetworkCapture::pause()) {
return shutdown_participant(
participant,
"Error pausing network capture",
EXIT_FAILURE);
} else if (
samples_written == 6 && !NDDSUtilityNetworkCapture::resume()) {
return shutdown_participant(
participant,
"Error resuming network capture",
EXIT_FAILURE);
}
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;
}
retcode = NetworkCaptureTypeSupport::delete_data(data);
if (retcode != DDS_RETCODE_OK) {
std::cerr << "NetworkCaptureTypeSupport::delete_data error " << retcode
<< std::endl;
}
/*
* Before deleting the participants that are capturing, we must stop
* network capture for them.
*/
if (!NDDSUtilityNetworkCapture::stop()) {
return shutdown_participant(
participant,
"Error stopping network capture",
EXIT_FAILURE);
}
// 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/network_capture/01_shared_memory_and_udp/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/network_capture/01_shared_memory_and_udp/c++98/network_capture_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.
*/
/*
* A simple NetworkCapture using network capture to save DomainParticipant
* traffic.
*
* This example is a simple hello world running network capture for both a
* publisher participant (network_capture_publisher.cxx).and a subscriber
* participant (network_capture_subscriber.cxx). It shows the basic flow when
* working with network capture:
* - Enabling before anything else.
* - Start capturing traffic (for one or all participants).
* - Pause/resume capturing traffic (for one or all participants).
* - Stop capturing trafffic (for one or all participants).
* - Disable after everything else.
*/
#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include "ndds/ndds_cpp.h"
#include "network_capture.h"
#include "network_captureSupport.h"
#include "application.h"
using namespace application;
static int shutdown_participant(
DDSDomainParticipant *participant,
const char *shutdown_message,
int status);
unsigned int process_data(NetworkCaptureDataReader *typed_reader)
{
NetworkCaptureSeq 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) {
std::cout << "Received data\n";
NetworkCaptureTypeSupport::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;
}
}
int run_subscriber_application(
unsigned int domain_id,
unsigned int sample_count)
{
DDS_Duration_t wait_timeout = { 1, 0 };
DDS_Boolean success = DDS_BOOLEAN_FALSE;
/*
* Enable network capture.
*
* This must be called before:
* - Any other network capture function is called.
* - Creating the participants for which we want to capture traffic.
*/
success = NDDSUtilityNetworkCapture::enable();
if (!success) {
std::cerr << "Error enabling network capture\n";
return EXIT_FAILURE;
}
/*
* Start capturing traffic for all participants.
*
* All participants: those already created and those yet to be created.
* Default parameters: all transports and some other sane defaults.
*
* A capture file will be created for each participant. The capture file
* will start with the prefix "subscriber" and continue with a suffix
* dependent on the participant's GUID.
*/
success = NDDSUtilityNetworkCapture::start("subscriber");
if (!success) {
std::cerr << "Error starting network capture\n";
return EXIT_FAILURE;
}
// 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 = NetworkCaptureTypeSupport::get_type_name();
DDS_ReturnCode_t retcode =
NetworkCaptureTypeSupport::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(
"Network capture shared memory example",
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 prueba" 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
NetworkCaptureDataReader *typed_reader =
NetworkCaptureDataReader::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
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 << " second"
<< std::endl;
}
}
}
/*
* But before deleting the participants that are capturing, we must stop
* network capture for them.
*/
success = NDDSUtilityNetworkCapture::stop();
if (!success) {
return shutdown_participant(
participant,
"Error stopping network capture",
EXIT_FAILURE);
}
// 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/network_capture/01_shared_memory_and_udp/c/network_capture_publisher.c | /*
* (c) Copyright, Real-Time Innovations, 2021. All rights reserved.
* RTI grants Licensee a license to use, modify, compile, and create derivative
* works of the software solely for use with RTI Connext DDS. Licensee may
* redistribute copies of the software provided that all such copies are subject
* to this license. The software is provided "as is", with no warranty of any
* type, including any warranty for fitness for any purpose. RTI is under no
* obligation to maintain or support the software. RTI shall not be liable for
* any incidental or consequential damages arising out of the use or inability
* to use the software.
*/
/*
* A simple HelloWorld using network capture to save DomainParticipant traffic.
*
* This example is a simple hello world running network capture for both a
* publisher participant (network_capture_publisher.c).and a subscriber
* participant (network_capture_subscriber.c). It shows the basic flow when
* working with network capture:
* - Enabling before anything else.
* - Start capturing traffic (for one or all participants).
* - Pause/resume capturing traffic (for one or all participants).
* - Stop capturing trafffic (for one or all participants).
* - Disable after everything else.
*/
#include "ndds/ndds_c.h"
#include "network_capture.h"
#include "network_captureSupport.h"
#include <stdio.h>
#include <stdlib.h>
static int publisher_shutdown(DDS_DomainParticipant *participant)
{
DDS_ReturnCode_t retcode;
int status = 0;
if (participant != NULL) {
retcode = DDS_DomainParticipant_delete_contained_entities(participant);
if (retcode != DDS_RETCODE_OK) {
fprintf(stderr, "delete_contained_entities error %d\n", retcode);
status = -1;
}
retcode = DDS_DomainParticipantFactory_delete_participant(
DDS_TheParticipantFactory,
participant);
if (retcode != DDS_RETCODE_OK) {
fprintf(stderr, "delete_participant error %d\n", retcode);
status = -1;
}
}
retcode = DDS_DomainParticipantFactory_finalize_instance();
if (retcode != DDS_RETCODE_OK) {
fprintf(stderr, "finalize_instance error %d\n", retcode);
status = -1;
}
/*
* Disable network capture.
*
* This must be:
* - The last network capture function that is called.
*/
if (!NDDS_Utility_disable_network_capture()) {
fprintf(stderr, "Error disabling network capture\n");
status = -1;
}
return status;
}
int publisher_main(int domainId, int sample_count)
{
DDS_DomainParticipant *participant = NULL;
DDS_Publisher *publisher = NULL;
DDS_Topic *topic = NULL;
DDS_DataWriter *writer = NULL;
NetworkCaptureDataWriter *NetworkCapture_writer = NULL;
NetworkCapture *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 }; /* 1 s */
/*
* Enable network capture.
*
* This must be called before:
* - Any other network capture function is called.
* - Creating the participants for which we want to capture traffic.
*/
if (!NDDS_Utility_enable_network_capture()) {
fprintf(stderr, "Error enabling network capture\n");
return -1;
}
/*
* Start capturing traffic for all participants.
*
* All participants: those already created and those yet to be created.
* Default parameters: all transports and some other sane defaults.
*
* A capture file will be created for each participant. The capture file
* will start with the prefix "publisher" and continue with a suffix
* dependent on the participant's GUID.
*/
if (!NDDS_Utility_start_network_capture("publisher")) {
fprintf(stderr,
"Error starting network capture for all participants\n");
return -1;
}
/*
* The example continues as the usual Connext DDS HelloWorld.
* Create entities, start communication, etc.
*/
participant = DDS_DomainParticipantFactory_create_participant(
DDS_TheParticipantFactory,
domainId,
&DDS_PARTICIPANT_QOS_DEFAULT,
NULL, /* listener */
DDS_STATUS_MASK_NONE);
if (participant == NULL) {
fprintf(stderr, "create_participant error\n");
publisher_shutdown(participant);
return -1;
}
publisher = DDS_DomainParticipant_create_publisher(
participant,
&DDS_PUBLISHER_QOS_DEFAULT,
NULL, /* listener */
DDS_STATUS_MASK_NONE);
if (publisher == NULL) {
fprintf(stderr, "create_publisher error\n");
publisher_shutdown(participant);
return -1;
}
type_name = NetworkCaptureTypeSupport_get_type_name();
retcode = NetworkCaptureTypeSupport_register_type(participant, type_name);
if (retcode != DDS_RETCODE_OK) {
fprintf(stderr, "register_type error %d\n", retcode);
publisher_shutdown(participant);
return -1;
}
topic = DDS_DomainParticipant_create_topic(
participant,
"Network capture shared memory example",
type_name,
&DDS_TOPIC_QOS_DEFAULT,
NULL, /* listener */
DDS_STATUS_MASK_NONE);
if (topic == NULL) {
fprintf(stderr, "create_topic error\n");
publisher_shutdown(participant);
return -1;
}
writer = DDS_Publisher_create_datawriter(
publisher,
topic,
&DDS_DATAWRITER_QOS_DEFAULT,
NULL, /* listener */
DDS_STATUS_MASK_NONE);
if (writer == NULL) {
fprintf(stderr, "create_datawriter error\n");
publisher_shutdown(participant);
return -1;
}
NetworkCapture_writer = NetworkCaptureDataWriter_narrow(writer);
if (NetworkCapture_writer == NULL) {
fprintf(stderr, "DataWriter narrow error\n");
publisher_shutdown(participant);
return -1;
}
instance = NetworkCaptureTypeSupport_create_data_ex(DDS_BOOLEAN_TRUE);
if (instance == NULL) {
fprintf(stderr, "NetworkCaptureTypeSupport_create_data error\n");
publisher_shutdown(participant);
return -1;
}
for (count = 0; (sample_count == 0) || (count < sample_count); ++count) {
printf("Writing NetworkCapture, count %d\n", count);
RTIOsapiUtility_snprintf(instance->msg, 128, "Hello World (%d)", count);
/*
* Here we are going to pause capturing for some samples.
* The resulting pcap file will not contain them.
*/
if (count == 4 && !NDDS_Utility_pause_network_capture()) {
fprintf(stderr, "Error pausing network capture\n");
} else if (count == 6 && !NDDS_Utility_resume_network_capture()) {
fprintf(stderr, "Error resuming network capture\n");
}
retcode = NetworkCaptureDataWriter_write(
NetworkCapture_writer,
instance,
&instance_handle);
if (retcode != DDS_RETCODE_OK) {
fprintf(stderr, "write error %d\n", retcode);
}
NDDS_Utility_sleep(&send_period);
}
retcode = NetworkCaptureTypeSupport_delete_data_ex(
instance,
DDS_BOOLEAN_TRUE);
if (retcode != DDS_RETCODE_OK) {
fprintf(stderr,
"NetworkCaptureTypeSupport_delete_data error %d\n",
retcode);
}
/*
* Before deleting the participants that are capturing, we must stop
* network capture for them.
*/
if (!NDDS_Utility_stop_network_capture()) {
fprintf(stderr,
"Error stopping network capture for all participants\n");
}
return publisher_shutdown(participant);
}
int main(int argc, char *argv[])
{
int domain_id = 0;
int sample_count = 0; /* infinite loop */
if (argc >= 2) {
domain_id = atoi(argv[1]);
}
if (argc >= 3) {
sample_count = atoi(argv[2]);
}
return publisher_main(domain_id, sample_count);
}
| c |
rticonnextdds-examples | data/projects/rticonnextdds-examples/connext_dds/network_capture/01_shared_memory_and_udp/c/network_capture_subscriber.c | /*
* (c) Copyright, Real-Time Innovations, 2021. All rights reserved.
* RTI grants Licensee a license to use, modify, compile, and create derivative
* works of the software solely for use with RTI Connext DDS. Licensee may
* redistribute copies of the software provided that all such copies are subject
* to this license. The software is provided "as is", with no warranty of any
* type, including any warranty for fitness for any purpose. RTI is under no
* obligation to maintain or support the software. RTI shall not be liable for
* any incidental or consequential damages arising out of the use or inability
* to use the software.
*/
/*
* A simple HelloWorld using network capture to save DomainParticipant traffic.
*
* This example is a simple hello world running network capture for both a
* publisher participant (network_capture_publisher.c).and a subscriber
* participant (network_capture_subscriber.c). It shows the basic flow when
* working with network capture:
* - Enabling before anything else.
* - Start capturing traffic (for one or all participants).
* - Pause/resume capturing traffic (for one or all participants).
* - Stop capturing trafffic (for one or all participants).
* - Disable after everything else.
*/
#include "ndds/ndds_c.h"
#include "network_capture.h"
#include "network_captureSupport.h"
#include <stdio.h>
#include <stdlib.h>
void NetworkCaptureListener_on_requested_deadline_missed(
void *listener_data,
DDS_DataReader *reader,
const struct DDS_RequestedDeadlineMissedStatus *status)
{
}
void NetworkCaptureListener_on_requested_incompatible_qos(
void *listener_data,
DDS_DataReader *reader,
const struct DDS_RequestedIncompatibleQosStatus *status)
{
}
void NetworkCaptureListener_on_sample_rejected(
void *listener_data,
DDS_DataReader *reader,
const struct DDS_SampleRejectedStatus *status)
{
}
void NetworkCaptureListener_on_liveliness_changed(
void *listener_data,
DDS_DataReader *reader,
const struct DDS_LivelinessChangedStatus *status)
{
}
void NetworkCaptureListener_on_sample_lost(
void *listener_data,
DDS_DataReader *reader,
const struct DDS_SampleLostStatus *status)
{
}
void NetworkCaptureListener_on_subscription_matched(
void *listener_data,
DDS_DataReader *reader,
const struct DDS_SubscriptionMatchedStatus *status)
{
}
void NetworkCaptureListener_on_data_available(
void *listener_data,
DDS_DataReader *reader)
{
NetworkCaptureDataReader *NetworkCapture_reader = NULL;
struct NetworkCaptureSeq data_seq = DDS_SEQUENCE_INITIALIZER;
struct DDS_SampleInfoSeq info_seq = DDS_SEQUENCE_INITIALIZER;
DDS_ReturnCode_t retcode;
int i;
NetworkCapture_reader = NetworkCaptureDataReader_narrow(reader);
if (NetworkCapture_reader == NULL) {
fprintf(stderr, "DataReader narrow error\n");
return;
}
retcode = NetworkCaptureDataReader_take(
NetworkCapture_reader,
&data_seq,
&info_seq,
DDS_LENGTH_UNLIMITED,
DDS_ANY_SAMPLE_STATE,
DDS_ANY_VIEW_STATE,
DDS_ANY_INSTANCE_STATE);
if (retcode == DDS_RETCODE_NO_DATA) {
return;
} else if (retcode != DDS_RETCODE_OK) {
fprintf(stderr, "take error %d\n", retcode);
return;
}
for (i = 0; i < NetworkCaptureSeq_get_length(&data_seq); ++i) {
if (DDS_SampleInfoSeq_get_reference(&info_seq, i)->valid_data) {
printf("Received data\n");
NetworkCaptureTypeSupport_print_data(
NetworkCaptureSeq_get_reference(&data_seq, i));
}
}
retcode = NetworkCaptureDataReader_return_loan(
NetworkCapture_reader,
&data_seq,
&info_seq);
if (retcode != DDS_RETCODE_OK) {
fprintf(stderr, "return loan error %d\n", retcode);
}
}
static int subscriber_shutdown(DDS_DomainParticipant *participant)
{
DDS_ReturnCode_t retcode;
int status = 0;
if (participant != NULL) {
retcode = DDS_DomainParticipant_delete_contained_entities(participant);
if (retcode != DDS_RETCODE_OK) {
fprintf(stderr, "delete_contained_entities error %d\n", retcode);
status = -1;
}
retcode = DDS_DomainParticipantFactory_delete_participant(
DDS_TheParticipantFactory,
participant);
if (retcode != DDS_RETCODE_OK) {
fprintf(stderr, "delete_participant error %d\n", retcode);
status = -1;
}
}
/*
* Disable network capture.
*
* This must be:
* - The last network capture function that is called.
*/
if (!NDDS_Utility_disable_network_capture()) {
fprintf(stderr, "Error disabling network capture\n");
status = -1;
}
return status;
}
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 }; /* 1 s */
/*
* Enable network capture
*
* This must be called before:
* - Any other network capture function is called.
* - Creating the participants for which we want to capture traffic.
*/
if (!NDDS_Utility_enable_network_capture()) {
fprintf(stderr, "Error enabling network capture\n");
return -1;
}
/*
* Start capturing traffic for all participants.
*
* All participants: those already created and those yet to be created.
* Default parameters: all transports and some other sane defaults.
*
* A capture file will be created for each participant. The capture file
* will start with the prefix "subscriber" and continue with a suffix
* dependent on the participant's GUID.
*/
if (!NDDS_Utility_start_network_capture("subscriber")) {
fprintf(stderr,
"Error starting network capture for all participants\n");
return -1;
}
/*
* The example continues as the usual Connext DDS HelloWorld.
* Create entities, start communication, etc.
*/
participant = DDS_DomainParticipantFactory_create_participant(
DDS_TheParticipantFactory,
domainId,
&DDS_PARTICIPANT_QOS_DEFAULT,
NULL, /* listener */
DDS_STATUS_MASK_NONE);
if (participant == NULL) {
fprintf(stderr, "create_participant error\n");
subscriber_shutdown(participant);
return -1;
}
subscriber = DDS_DomainParticipant_create_subscriber(
participant,
&DDS_SUBSCRIBER_QOS_DEFAULT,
NULL, /* listener */
DDS_STATUS_MASK_NONE);
if (subscriber == NULL) {
fprintf(stderr, "create_subscriber error\n");
subscriber_shutdown(participant);
return -1;
}
type_name = NetworkCaptureTypeSupport_get_type_name();
retcode = NetworkCaptureTypeSupport_register_type(participant, type_name);
if (retcode != DDS_RETCODE_OK) {
fprintf(stderr, "register_type error %d\n", retcode);
subscriber_shutdown(participant);
return -1;
}
topic = DDS_DomainParticipant_create_topic(
participant,
"Network capture shared memory example",
type_name,
&DDS_TOPIC_QOS_DEFAULT,
NULL, /* listener */
DDS_STATUS_MASK_NONE);
if (topic == NULL) {
fprintf(stderr, "create_topic error\n");
subscriber_shutdown(participant);
return -1;
}
reader_listener.on_requested_deadline_missed =
NetworkCaptureListener_on_requested_deadline_missed;
reader_listener.on_requested_incompatible_qos =
NetworkCaptureListener_on_requested_incompatible_qos;
reader_listener.on_sample_rejected =
NetworkCaptureListener_on_sample_rejected;
reader_listener.on_liveliness_changed =
NetworkCaptureListener_on_liveliness_changed;
reader_listener.on_sample_lost = NetworkCaptureListener_on_sample_lost;
reader_listener.on_subscription_matched =
NetworkCaptureListener_on_subscription_matched;
reader_listener.on_data_available =
NetworkCaptureListener_on_data_available;
reader = DDS_Subscriber_create_datareader(
subscriber,
DDS_Topic_as_topicdescription(topic),
&DDS_DATAREADER_QOS_DEFAULT,
&reader_listener,
DDS_STATUS_MASK_ALL);
if (reader == NULL) {
fprintf(stderr, "create_datareader error\n");
subscriber_shutdown(participant);
return -1;
}
for (count = 0; (sample_count == 0) || (count < sample_count); ++count) {
printf("NetworkCapture subscriber sleeping for %d sec...\n",
poll_period.sec);
NDDS_Utility_sleep(&poll_period);
}
/*
* But before deleting the participants that are capturing, we must stop
* network capture for them.
*/
if (!NDDS_Utility_stop_network_capture()) {
fprintf(stderr,
"Error stopping network capture for all participants\n");
}
return subscriber_shutdown(participant);
}
int main(int argc, char *argv[])
{
int domain_id = 0;
int sample_count = 0; /* infinite loop */
if (argc >= 2) {
domain_id = atoi(argv[1]);
}
if (argc >= 3) {
sample_count = atoi(argv[2]);
}
return subscriber_main(domain_id, sample_count);
}
| c |
rticonnextdds-examples | data/projects/rticonnextdds-examples/connext_dds/network_capture/01_shared_memory_and_udp/c++11/application.hpp | /*
* (c) Copyright, Real-Time Innovations, 2021. All rights reserved.
* RTI grants Licensee a license to use, modify, compile, and create derivative
* works of the software solely for use with RTI Connext DDS. Licensee may
* redistribute copies of the software provided that all such copies are subject
* to this license. The software is provided "as is", with no warranty of any
* type, including any warranty for fitness for any purpose. RTI is under no
* obligation to maintain or support the software. RTI shall not be liable for
* any incidental or consequential damages arising out of the use or inability
* to use the software.
*/
#ifndef APPLICATION_HPP
#define APPLICATION_HPP
#include <iostream>
#include <csignal>
#include <dds/core/ddscore.hpp>
#include <rti/config/Logger.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/network_capture/01_shared_memory_and_udp/c++11/network_capture_publisher.cxx | /*
* (c) Copyright, Real-Time Innovations, 2021. All rights reserved.
* RTI grants Licensee a license to use, modify, compile, and create derivative
* works of the software solely for use with RTI Connext DDS. Licensee may
* redistribute copies of the software provided that all such copies are subject
* to this license. The software is provided "as is", with no warranty of any
* type, including any warranty for fitness for any purpose. RTI is under no
* obligation to maintain or support the software. RTI shall not be liable for
* any incidental or consequential damages arising out of the use or inability
* to use the software.
*/
#include <iostream>
#include <dds/pub/ddspub.hpp>
#include <rti/util/util.hpp> // for sleep()
#include <rti/config/Logger.hpp> // for logging
#include "application.hpp" // for command line parsing and ctrl-c
#include "network_capture.hpp"
void run_publisher_application(
unsigned int domain_id,
unsigned int sample_count)
{
// Start capturing traffic for all participants.
//
// All participants: those already created and those yet to be created.
// Default parameters: all transports and some other sane defaults.
//
// A capture file will be created for each participant. The capture file
// will start with the prefix "publisher" and continue with a suffix
// dependent on the participant's GUID.
if (!rti::util::network_capture::start("publisher")) {
std::cerr << "Error starting network capture" << std::endl;
}
// The example continues as the usual Connext DDS HelloWorld.
// Create entities, start communication, etc.
dds::domain::DomainParticipant participant(domain_id);
dds::topic::Topic<NetworkCapture> topic(
participant,
"Network capture shared memory example");
dds::pub::Publisher publisher(participant);
dds::pub::DataWriter<NetworkCapture> writer(publisher, topic);
NetworkCapture data;
for (unsigned int samples_written = 0;
!application::shutdown_requested && samples_written < sample_count;
samples_written++) {
data.msg("Hello World " + std::to_string(samples_written));
std::cout << "Writing NetworkCapture, count " << samples_written
<< std::endl;
// Here we are going to pause capturing for some samples.
// The resulting pcap file will not contain them.
if (samples_written == 4 && !rti::util::network_capture::pause()) {
std::cerr << "Error pausing network capture" << std::endl;
} else if (
samples_written == 6 && !rti::util::network_capture::resume()) {
std::cerr << "Error resuming network capture" << std::endl;
}
// Send once every second
writer.write(data);
rti::util::sleep(dds::core::Duration(1));
}
// Before deleting the participants that are capturing, we must stop
// network capture for them.
if (!rti::util::network_capture::stop()) {
std::cerr << "Error stopping network capture" << std::endl;
}
}
int main(int argc, char *argv[])
{
using namespace application;
// Parse arguments and handle control-C
// Set Connext verbosity to help debugging
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();
rti::config::Logger::instance().verbosity(arguments.verbosity);
// Enable network capture.
//
// This must be called before:
// - Any other network capture function is called.
// - Creating the participants for which we want to capture traffic.
if (!rti::util::network_capture::enable()) {
std::cerr << "Error enabling network capture" << std::endl;
}
try {
run_publisher_application(arguments.domain_id, arguments.sample_count);
} catch (const std::exception &ex) {
std::cerr << "Exception in run_publisher_application(): " << ex.what()
<< std::endl;
return EXIT_FAILURE;
}
dds::domain::DomainParticipant::finalize_participant_factory();
// Disable network capture.
//
// This must be:
// - The last network capture function that is called.
if (!rti::util::network_capture::disable()) {
std::cerr << "Error disabling network capture" << std::endl;
}
return EXIT_SUCCESS;
}
| cxx |
rticonnextdds-examples | data/projects/rticonnextdds-examples/connext_dds/network_capture/01_shared_memory_and_udp/c++11/network_capture_subscriber.cxx | /*
* (c) Copyright, Real-Time Innovations, 2021. All rights reserved.
* RTI grants Licensee a license to use, modify, compile, and create derivative
* works of the software solely for use with RTI Connext DDS. Licensee may
* redistribute copies of the software provided that all such copies are subject
* to this license. The software is provided "as is", with no warranty of any
* type, including any warranty for fitness for any purpose. RTI is under no
* obligation to maintain or support the software. RTI shall not be liable for
* any incidental or consequential damages arising out of the use or inability
* to use the software.
*/
#include <algorithm>
#include <iostream>
#include <dds/sub/ddssub.hpp>
#include <dds/core/ddscore.hpp>
#include <rti/util/util.hpp>
#include <rti/config/Logger.hpp> // for logging
#include "network_capture.hpp"
#include "application.hpp" // for command line parsing and ctrl-c
int process_data(dds::sub::DataReader<NetworkCapture> reader)
{
int count = 0;
dds::sub::LoanedSamples<NetworkCapture> samples = reader.take();
for (const auto &sample : samples) {
if (sample.info().valid()) {
count++;
std::cout << sample.data() << std::endl;
} else {
std::cout << "Instance state changed to "
<< sample.info().state().instance_state() << std::endl;
}
}
return count;
}
void run_subscriber_application(
unsigned int domain_id,
unsigned int sample_count)
{
// Start capturing traffic for all participants.
//
// All participants: those already created and those yet to be created.
// Default parameters: all transports and some other sane defaults.
//
// A capture file will be created for each participant. The capture file
// will start with the prefix "publisher" and continue with a suffix
// dependent on the participant's GUID.
if (!rti::util::network_capture::start("subscriber")) {
std::cerr << "Error starting network capture" << std::endl;
}
// The example continues as the usual Connext DDS HelloWorld.
// Create entities, start communication, etc.
dds::domain::DomainParticipant participant(domain_id);
dds::topic::Topic<NetworkCapture> topic(
participant,
"Network capture shared memory example");
dds::sub::Subscriber subscriber(participant);
dds::sub::DataReader<NetworkCapture> reader(subscriber, topic);
dds::core::cond::WaitSet waitset;
unsigned int samples_read = 0;
dds::sub::cond::ReadCondition read_condition(
reader,
dds::sub::status::DataState::any(),
[reader, &samples_read]() {
samples_read += process_data(reader);
});
waitset += read_condition;
while (!application::shutdown_requested
&& samples_read < (sample_count - 1)) {
std::cout << "NetworkCapture subscriber sleeping up to 1 sec..."
<< std::endl;
waitset.dispatch(dds::core::Duration(1));
}
// Before deleting the participants that are capturing, we must stop
// network capture for them.
if (!rti::util::network_capture::stop()) {
std::cerr << "Error stopping network capture" << std::endl;
}
}
int main(int argc, char *argv[])
{
using namespace application;
// Parse arguments and handle control-C
// Set Connext verbosity to help debugging
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();
rti::config::Logger::instance().verbosity(arguments.verbosity);
// Enable network capture.
//
// This must be called before:
// - Any other network capture function is called.
// - Creating the participants for which we want to capture traffic.
if (!rti::util::network_capture::enable()) {
std::cerr << "Error enabling network capture" << std::endl;
}
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;
}
dds::domain::DomainParticipant::finalize_participant_factory();
// Disable network capture.
//
// This must be:
// - The last network capture function that is called.
if (!rti::util::network_capture::disable()) {
std::cerr << "Error disabling network capture" << std::endl;
}
return EXIT_SUCCESS;
}
| cxx |
rticonnextdds-examples | data/projects/rticonnextdds-examples/connext_dds/network_capture/02_tcp/c/network_capture_publisher.c | /*
* (c) Copyright, Real-Time Innovations, 2021. All rights reserved.
* RTI grants Licensee a license to use, modify, compile, and create derivative
* works of the software solely for use with RTI Connext DDS. Licensee may
* redistribute copies of the software provided that all such copies are subject
* to this license. The software is provided "as is", with no warranty of any
* type, including any warranty for fitness for any purpose. RTI is under no
* obligation to maintain or support the software. RTI shall not be liable for
* any incidental or consequential damages arising out of the use or inability
* to use the software.
*/
/*
* A simple HelloWorld using network capture to save DomainParticipant traffic.
*
* This example is a simple hello world running network capture for both a
* publisher participant (network_capture_publisher.c).and a subscriber
* participant (network_capture_subscriber.c). It shows the basic flow when
* working with network capture:
* - Enabling before anything else.
* - Start capturing traffic (for one or all participants).
* - Pause/resume capturing traffic (for one or all participants).
* - Stop capturing trafffic (for one or all participants).
* - Disable after everything else.
*/
#include "ndds/ndds_c.h"
#include "network_capture.h"
#include "network_captureSupport.h"
#include <stdio.h>
#include <stdlib.h>
static int publisher_shutdown(DDS_DomainParticipant *participant)
{
DDS_ReturnCode_t retcode;
int status = 0;
if (participant != NULL) {
retcode = DDS_DomainParticipant_delete_contained_entities(participant);
if (retcode != DDS_RETCODE_OK) {
fprintf(stderr, "delete_contained_entities error %d\n", retcode);
status = -1;
}
retcode = DDS_DomainParticipantFactory_delete_participant(
DDS_TheParticipantFactory,
participant);
if (retcode != DDS_RETCODE_OK) {
fprintf(stderr, "delete_participant error %d\n", retcode);
status = -1;
}
}
retcode = DDS_DomainParticipantFactory_finalize_instance();
if (retcode != DDS_RETCODE_OK) {
fprintf(stderr, "finalize_instance error %d\n", retcode);
status = -1;
}
/*
* Disable network capture.
*
* This must be:
* - The last network capture function that is called.
*/
if (!NDDS_Utility_disable_network_capture()) {
fprintf(stderr, "Error disabling network capture\n");
status = -1;
}
return status;
}
int publisher_main(int domainId, int sample_count, const char *profile)
{
DDS_DomainParticipant *participant = NULL;
DDS_Publisher *publisher = NULL;
DDS_Topic *topic = NULL;
DDS_DataWriter *writer = NULL;
NetworkCaptureDataWriter *NetworkCapture_writer = NULL;
NetworkCapture *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 }; /* 1 s */
/*
* Enable network capture.
*
* This must be called before:
* - Any other network capture function is called.
* - Creating the participants for which we want to capture traffic.
*/
if (!NDDS_Utility_enable_network_capture()) {
fprintf(stderr, "Error enabling network capture\n");
return -1;
}
/*
* Start capturing traffic for all participants.
*
* All participants: those already created and those yet to be created.
* Default parameters: all transports and some other sane defaults.
*
* A capture file will be created for each participant. The capture file
* will start with the prefix "publisher" and continue with a suffix
* dependent on the participant's GUID.
*/
if (!NDDS_Utility_start_network_capture("publisher")) {
fprintf(stderr,
"Error starting network capture for all participants\n");
return -1;
}
/*
* The example continues as the usual Connext DDS HelloWorld.
* Create entities, start communication, etc.
*/
participant = DDS_DomainParticipantFactory_create_participant_with_profile(
DDS_TheParticipantFactory,
domainId,
"network_capture_Library",
profile,
NULL, /* listener */
DDS_STATUS_MASK_NONE);
if (participant == NULL) {
fprintf(stderr, "create_participant error\n");
publisher_shutdown(participant);
return -1;
}
publisher = DDS_DomainParticipant_create_publisher(
participant,
&DDS_PUBLISHER_QOS_DEFAULT,
NULL, /* listener */
DDS_STATUS_MASK_NONE);
if (publisher == NULL) {
fprintf(stderr, "create_publisher error\n");
publisher_shutdown(participant);
return -1;
}
type_name = NetworkCaptureTypeSupport_get_type_name();
retcode = NetworkCaptureTypeSupport_register_type(participant, type_name);
if (retcode != DDS_RETCODE_OK) {
fprintf(stderr, "register_type error %d\n", retcode);
publisher_shutdown(participant);
return -1;
}
topic = DDS_DomainParticipant_create_topic(
participant,
"Example NetworkCapture using TCP",
type_name,
&DDS_TOPIC_QOS_DEFAULT,
NULL, /* listener */
DDS_STATUS_MASK_NONE);
if (topic == NULL) {
fprintf(stderr, "create_topic error\n");
publisher_shutdown(participant);
return -1;
}
writer = DDS_Publisher_create_datawriter(
publisher,
topic,
&DDS_DATAWRITER_QOS_DEFAULT,
NULL, /* listener */
DDS_STATUS_MASK_NONE);
if (writer == NULL) {
fprintf(stderr, "create_datawriter error\n");
publisher_shutdown(participant);
return -1;
}
NetworkCapture_writer = NetworkCaptureDataWriter_narrow(writer);
if (NetworkCapture_writer == NULL) {
fprintf(stderr, "DataWriter narrow error\n");
publisher_shutdown(participant);
return -1;
}
instance = NetworkCaptureTypeSupport_create_data_ex(DDS_BOOLEAN_TRUE);
if (instance == NULL) {
fprintf(stderr, "NetworkCaptureTypeSupport_create_data error\n");
publisher_shutdown(participant);
return -1;
}
for (count = 0; (sample_count == 0) || (count < sample_count); ++count) {
printf("Writing NetworkCapture, count %d\n", count);
RTIOsapiUtility_snprintf(instance->msg, 128, "Hello World (%d)", count);
/*
* Here we are going to pause capturing for some samples.
* The resulting pcap file will not contain them.
*/
if (count == 4) {
if (!NDDS_Utility_pause_network_capture()) {
fprintf(stderr, "Error pausing network capture\n");
}
} else if (count == 6) {
if (!NDDS_Utility_resume_network_capture()) {
fprintf(stderr, "Error resuming network capture\n");
}
}
retcode = NetworkCaptureDataWriter_write(
NetworkCapture_writer,
instance,
&instance_handle);
if (retcode != DDS_RETCODE_OK) {
fprintf(stderr, "write error %d\n", retcode);
}
NDDS_Utility_sleep(&send_period);
}
retcode = NetworkCaptureTypeSupport_delete_data_ex(
instance,
DDS_BOOLEAN_TRUE);
if (retcode != DDS_RETCODE_OK) {
fprintf(stderr,
"NetworkCaptureTypeSupport_delete_data error %d\n",
retcode);
}
/*
* Before deleting the participants that are capturing, we must stop
* network capture for them.
*/
if (!NDDS_Utility_stop_network_capture()) {
fprintf(stderr,
"Error stopping network capture for all participants\n");
}
return publisher_shutdown(participant);
}
int main(int argc, char *argv[])
{
int domain_id = 0;
int sample_count = 0; /* infinite loop */
const char *profile = "LANpublisher";
if (argc >= 2) {
domain_id = atoi(argv[1]);
}
if (argc >= 3) {
sample_count = atoi(argv[2]);
}
if (argc >= 4) {
if (strcmp(argv[3], "lan") == 0) {
profile = "LANpublisher";
} else if (strcmp(argv[3], "wanSym") == 0) {
profile = "WANsymPublisher";
} else if (strcmp(argv[3], "wanAsym") == 0) {
profile = "WANasymPublisher";
} else if (strcmp(argv[3], "tls") == 0) {
profile = "TLSpublisher";
} else {
fprintf(stderr,
"Mode must be one of: {lan, wanSym, wanAsym, tls}\n");
}
}
return publisher_main(domain_id, sample_count, profile);
}
| c |
rticonnextdds-examples | data/projects/rticonnextdds-examples/connext_dds/network_capture/02_tcp/c/network_capture_subscriber.c | /*
* (c) Copyright, Real-Time Innovations, 2021. All rights reserved.
* RTI grants Licensee a license to use, modify, compile, and create derivative
* works of the software solely for use with RTI Connext DDS. Licensee may
* redistribute copies of the software provided that all such copies are subject
* to this license. The software is provided "as is", with no warranty of any
* type, including any warranty for fitness for any purpose. RTI is under no
* obligation to maintain or support the software. RTI shall not be liable for
* any incidental or consequential damages arising out of the use or inability
* to use the software.
*/
/*
* A simple HelloWorld using network capture to save DomainParticipant traffic.
*
* This example is a simple hello world running network capture for both a
* publisher participant (network_capture_publisher.c).and a subscriber
* participant (network_capture_subscriber.c). It shows the basic flow when
* working with network capture:
* - Enabling before anything else.
* - Start capturing traffic (for one or all participants).
* - Pause/resume capturing traffic (for one or all participants).
* - Stop capturing trafffic (for one or all participants).
* - Disable after everything else.
*/
#include "ndds/ndds_c.h"
#include "network_capture.h"
#include "network_captureSupport.h"
#include <stdio.h>
#include <stdlib.h>
void NetworkCaptureListener_on_requested_deadline_missed(
void *listener_data,
DDS_DataReader *reader,
const struct DDS_RequestedDeadlineMissedStatus *status)
{
}
void NetworkCaptureListener_on_requested_incompatible_qos(
void *listener_data,
DDS_DataReader *reader,
const struct DDS_RequestedIncompatibleQosStatus *status)
{
}
void NetworkCaptureListener_on_sample_rejected(
void *listener_data,
DDS_DataReader *reader,
const struct DDS_SampleRejectedStatus *status)
{
}
void NetworkCaptureListener_on_liveliness_changed(
void *listener_data,
DDS_DataReader *reader,
const struct DDS_LivelinessChangedStatus *status)
{
}
void NetworkCaptureListener_on_sample_lost(
void *listener_data,
DDS_DataReader *reader,
const struct DDS_SampleLostStatus *status)
{
}
void NetworkCaptureListener_on_subscription_matched(
void *listener_data,
DDS_DataReader *reader,
const struct DDS_SubscriptionMatchedStatus *status)
{
}
void NetworkCaptureListener_on_data_available(
void *listener_data,
DDS_DataReader *reader)
{
NetworkCaptureDataReader *NetworkCapture_reader = NULL;
struct NetworkCaptureSeq data_seq = DDS_SEQUENCE_INITIALIZER;
struct DDS_SampleInfoSeq info_seq = DDS_SEQUENCE_INITIALIZER;
DDS_ReturnCode_t retcode;
int i;
NetworkCapture_reader = NetworkCaptureDataReader_narrow(reader);
if (NetworkCapture_reader == NULL) {
fprintf(stderr, "DataReader narrow error\n");
return;
}
retcode = NetworkCaptureDataReader_take(
NetworkCapture_reader,
&data_seq,
&info_seq,
DDS_LENGTH_UNLIMITED,
DDS_ANY_SAMPLE_STATE,
DDS_ANY_VIEW_STATE,
DDS_ANY_INSTANCE_STATE);
if (retcode == DDS_RETCODE_NO_DATA) {
return;
} else if (retcode != DDS_RETCODE_OK) {
fprintf(stderr, "take error %d\n", retcode);
return;
}
for (i = 0; i < NetworkCaptureSeq_get_length(&data_seq); ++i) {
if (DDS_SampleInfoSeq_get_reference(&info_seq, i)->valid_data) {
printf("Received data\n");
NetworkCaptureTypeSupport_print_data(
NetworkCaptureSeq_get_reference(&data_seq, i));
}
}
retcode = NetworkCaptureDataReader_return_loan(
NetworkCapture_reader,
&data_seq,
&info_seq);
if (retcode != DDS_RETCODE_OK) {
fprintf(stderr, "return loan error %d\n", retcode);
}
}
static int subscriber_shutdown(DDS_DomainParticipant *participant)
{
DDS_ReturnCode_t retcode;
int status = 0;
if (participant != NULL) {
retcode = DDS_DomainParticipant_delete_contained_entities(participant);
if (retcode != DDS_RETCODE_OK) {
fprintf(stderr, "delete_contained_entities error %d\n", retcode);
status = -1;
}
retcode = DDS_DomainParticipantFactory_delete_participant(
DDS_TheParticipantFactory,
participant);
if (retcode != DDS_RETCODE_OK) {
fprintf(stderr, "delete_participant error %d\n", retcode);
status = -1;
}
}
/*
* Disable network capture.
*
* This must be:
* - The last network capture function that is called.
*/
if (!NDDS_Utility_disable_network_capture()) {
fprintf(stderr, "Error disabling network capture\n");
status = -1;
}
return status;
}
int subscriber_main(int domainId, int sample_count, const char *profile)
{
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 }; /* 1 s */
/*
* Enable network capture
*
* This must be called before:
* - Any other network capture function is called.
* - Creating the participants for which we want to capture traffic.
*/
if (!NDDS_Utility_enable_network_capture()) {
fprintf(stderr, "Error enabling network capture\n");
return -1;
}
/*
* Start capturing traffic for all participants.
*
* All participants: those already created and those yet to be created.
* Default parameters: all transports and some other sane defaults.
*
* A capture file will be created for each participant. The capture file
* will start with the prefix "subscriber" and continue with a suffix
* dependent on the participant's GUID.
*/
if (!NDDS_Utility_start_network_capture("subscriber")) {
fprintf(stderr,
"Error starting network capture for all participants\n");
return -1;
}
/*
* The example continues as the usual Connext DDS HelloWorld.
* Create entities, start communication, etc.
*/
participant = DDS_DomainParticipantFactory_create_participant_with_profile(
DDS_TheParticipantFactory,
domainId,
"network_capture_Library",
profile,
NULL, /* listener */
DDS_STATUS_MASK_NONE);
if (participant == NULL) {
fprintf(stderr, "create_participant error\n");
subscriber_shutdown(participant);
return -1;
}
subscriber = DDS_DomainParticipant_create_subscriber(
participant,
&DDS_SUBSCRIBER_QOS_DEFAULT,
NULL, /* listener */
DDS_STATUS_MASK_NONE);
if (subscriber == NULL) {
fprintf(stderr, "create_subscriber error\n");
subscriber_shutdown(participant);
return -1;
}
type_name = NetworkCaptureTypeSupport_get_type_name();
retcode = NetworkCaptureTypeSupport_register_type(participant, type_name);
if (retcode != DDS_RETCODE_OK) {
fprintf(stderr, "register_type error %d\n", retcode);
subscriber_shutdown(participant);
return -1;
}
topic = DDS_DomainParticipant_create_topic(
participant,
"Example NetworkCapture using TCP",
type_name,
&DDS_TOPIC_QOS_DEFAULT,
NULL, /* listener */
DDS_STATUS_MASK_NONE);
if (topic == NULL) {
fprintf(stderr, "create_topic error\n");
subscriber_shutdown(participant);
return -1;
}
reader_listener.on_requested_deadline_missed =
NetworkCaptureListener_on_requested_deadline_missed;
reader_listener.on_requested_incompatible_qos =
NetworkCaptureListener_on_requested_incompatible_qos;
reader_listener.on_sample_rejected =
NetworkCaptureListener_on_sample_rejected;
reader_listener.on_liveliness_changed =
NetworkCaptureListener_on_liveliness_changed;
reader_listener.on_sample_lost = NetworkCaptureListener_on_sample_lost;
reader_listener.on_subscription_matched =
NetworkCaptureListener_on_subscription_matched;
reader_listener.on_data_available =
NetworkCaptureListener_on_data_available;
reader = DDS_Subscriber_create_datareader(
subscriber,
DDS_Topic_as_topicdescription(topic),
&DDS_DATAREADER_QOS_DEFAULT,
&reader_listener,
DDS_STATUS_MASK_ALL);
if (reader == NULL) {
fprintf(stderr, "create_datareader error\n");
subscriber_shutdown(participant);
return -1;
}
for (count = 0; (sample_count == 0) || (count < sample_count); ++count) {
printf("NetworkCapture subscriber sleeping for %d sec...\n",
poll_period.sec);
NDDS_Utility_sleep(&poll_period);
}
/*
* But before deleting the participants that are capturing, we must stop
* network capture for them.
*/
if (!NDDS_Utility_stop_network_capture()) {
fprintf(stderr,
"Error stopping network capture for all participants\n");
}
return subscriber_shutdown(participant);
}
int main(int argc, char *argv[])
{
int domain_id = 0;
int sample_count = 0; /* infinite loop */
const char *profile = "LANsubscriber";
if (argc >= 2) {
domain_id = atoi(argv[1]);
}
if (argc >= 3) {
sample_count = atoi(argv[2]);
}
if (argc >= 4) {
if (strcmp(argv[3], "lan") == 0) {
profile = "LANsubscriber";
} else if (strcmp(argv[3], "wanSym") == 0) {
profile = "WANsymSubscriber";
} else if (strcmp(argv[3], "wanAsym") == 0) {
profile = "WANasymSubscriber";
} else if (strcmp(argv[3], "tls") == 0) {
profile = "TLSsubscriber";
} else {
fprintf(stderr,
"Mode must be one of: {lan, wanSym, wanAsym, tls}\n");
}
}
return subscriber_main(domain_id, sample_count, profile);
}
| c |
rticonnextdds-examples | data/projects/rticonnextdds-examples/connext_dds/network_capture/04_advanced_api/c/network_capture_publisher.c | /*
* (c) Copyright, Real-Time Innovations, 2021. All rights reserved.
* RTI grants Licensee a license to use, modify, compile, and create derivative
* works of the software solely for use with RTI Connext DDS. Licensee may
* redistribute copies of the software provided that all such copies are subject
* to this license. The software is provided "as is", with no warranty of any
* type, including any warranty for fitness for any purpose. RTI is under no
* obligation to maintain or support the software. RTI shall not be liable for
* any incidental or consequential damages arising out of the use or inability
* to use the software.
*/
/*
* A simple secure HelloWorld using network capture to save DomainParticipant
* traffic from several participants.
*
* It shows how, if we have several participants, we can control from which
* we want to capture traffic and when.
*/
#include "ndds/ndds_c.h"
#include "network_capture.h"
#include "network_captureSupport.h"
#include <stdio.h>
#include <stdlib.h>
#ifdef RTI_STATIC
#include "security/security_default.h"
#endif
static int publisher_shutdown(
DDS_DomainParticipant *participant,
DDS_Boolean last_participant)
{
DDS_ReturnCode_t retcode;
int status = 0;
if (participant != NULL) {
retcode = DDS_DomainParticipant_delete_contained_entities(participant);
if (retcode != DDS_RETCODE_OK) {
fprintf(stderr, "delete_contained_entities error %d\n", retcode);
status = -1;
}
retcode = DDS_DomainParticipantFactory_delete_participant(
DDS_TheParticipantFactory,
participant);
if (retcode != DDS_RETCODE_OK) {
fprintf(stderr, "delete_participant error %d\n", retcode);
status = -1;
}
}
if (last_participant) {
retcode = DDS_DomainParticipantFactory_finalize_instance();
if (retcode != DDS_RETCODE_OK) {
fprintf(stderr, "finalize_instance error %d\n", retcode);
status = -1;
}
/*
* Disable network capture.
*
* This must be:
* - The last network capture function that is called.
*/
if (!NDDS_Utility_disable_network_capture()) {
fprintf(stderr, "Error disabling network capture\n");
status = -1;
}
}
return status;
}
static int publisher_main(int domainId, int sample_count)
{
DDS_DomainParticipant *participant = NULL;
DDS_DomainParticipant *participant2 = NULL;
DDS_Publisher *publisher = NULL;
DDS_Publisher *publisher2 = NULL;
DDS_Topic *topic = NULL;
DDS_Topic *topic2 = NULL;
DDS_DataWriter *writer = NULL;
DDS_DataWriter *writer2 = NULL;
NetworkCaptureDataWriter *NetworkCapture_writer = NULL;
NetworkCaptureDataWriter *NetworkCapture_writer2 = NULL;
NetworkCapture *instance = NULL;
DDS_ReturnCode_t retcode;
DDS_InstanceHandle_t instance_handle = DDS_HANDLE_NIL;
const char *type_name = NULL;
const char *type_name2 = NULL;
int count = 0;
struct DDS_Duration_t send_period = { 0, 10000000 }; /* 10 ms */
DDS_Boolean success = DDS_BOOLEAN_FALSE;
NDDS_Utility_NetworkCaptureParams_t params =
NDDS_UTILITY_NETWORK_CAPTURE_PARAMETERS_DEFAULT;
/*
* Enable network capture.
*
* This must be called before:
* - Any other network capture function is called.
* - Creating the participants for which we want to capture traffic.
*/
if (!NDDS_Utility_enable_network_capture()) {
fprintf(stderr, "Error enabling network capture\n");
return -1;
}
#ifdef RTI_STATIC
struct DDS_DomainParticipantQos participant_qos =
DDS_DomainParticipantQos_INITIALIZER;
retcode = DDS_DomainParticipantFactory_get_participant_qos_from_profile(
DDS_TheParticipantFactory,
&participant_qos,
"network_capture_Library",
"network_capture_ProfileB");
if (retcode != DDS_RETCODE_OK) {
fprintf(stderr, "Unable to get participant qos from profile\n");
return -1;
}
retcode = DDS_PropertyQosPolicyHelper_assert_pointer_property(
&participant_qos.property,
RTI_SECURITY_BUILTIN_PLUGIN_PROPERTY_NAME ".create_function_ptr",
RTI_Security_PluginSuite_create);
if (retcode != DDS_RETCODE_OK) {
fprintf(stderr, "Unable to assert create_function_ptr property\n");
return -1;
}
participant = DDS_DomainParticipantFactory_create_participant(
DDS_TheParticipantFactory,
domainId,
&participant_qos,
NULL,
DDS_STATUS_MASK_NONE);
participant2 = DDS_DomainParticipantFactory_create_participant(
DDS_TheParticipantFactory,
domainId,
&participant_qos,
NULL,
DDS_STATUS_MASK_NONE);
DDS_DomainParticipantQos_finalize(&participant_qos);
#else
participant = DDS_DomainParticipantFactory_create_participant_with_profile(
DDS_TheParticipantFactory,
domainId,
"network_capture_Library",
"network_capture_ProfileB",
NULL,
DDS_STATUS_MASK_NONE);
participant2 = DDS_DomainParticipantFactory_create_participant_with_profile(
DDS_TheParticipantFactory,
domainId,
"network_capture_Library",
"network_capture_ProfileB",
NULL,
DDS_STATUS_MASK_NONE);
#endif
if (participant == NULL || participant2 == NULL) {
fprintf(stderr, "create_participant error\n");
publisher_shutdown(participant, DDS_BOOLEAN_FALSE);
publisher_shutdown(participant2, DDS_BOOLEAN_TRUE);
return -1;
}
publisher = DDS_DomainParticipant_create_publisher(
participant,
&DDS_PUBLISHER_QOS_DEFAULT,
NULL, /* listener */
DDS_STATUS_MASK_NONE);
if (publisher == NULL) {
fprintf(stderr, "create_publisher error\n");
publisher_shutdown(participant, DDS_BOOLEAN_FALSE);
publisher_shutdown(participant2, DDS_BOOLEAN_TRUE);
return -1;
}
publisher2 = DDS_DomainParticipant_create_publisher(
participant2,
&DDS_PUBLISHER_QOS_DEFAULT,
NULL, /* listener */
DDS_STATUS_MASK_NONE);
if (publisher2 == NULL) {
fprintf(stderr, "create_publisher error\n");
publisher_shutdown(participant, DDS_BOOLEAN_FALSE);
publisher_shutdown(participant2, DDS_BOOLEAN_TRUE);
return -1;
}
type_name = NetworkCaptureTypeSupport_get_type_name();
retcode = NetworkCaptureTypeSupport_register_type(participant, type_name);
if (retcode != DDS_RETCODE_OK) {
fprintf(stderr, "register_type error %d\n", retcode);
publisher_shutdown(participant, DDS_BOOLEAN_FALSE);
publisher_shutdown(participant2, DDS_BOOLEAN_TRUE);
return -1;
}
type_name2 = NetworkCaptureTypeSupport_get_type_name();
retcode = NetworkCaptureTypeSupport_register_type(participant2, type_name2);
if (retcode != DDS_RETCODE_OK) {
fprintf(stderr, "register_type error %d\n", retcode);
publisher_shutdown(participant, DDS_BOOLEAN_FALSE);
publisher_shutdown(participant2, DDS_BOOLEAN_TRUE);
return -1;
}
topic = DDS_DomainParticipant_create_topic(
participant,
"NetworkCapture [1st Participant]",
type_name,
&DDS_TOPIC_QOS_DEFAULT,
NULL, /* listener */
DDS_STATUS_MASK_NONE);
if (topic == NULL) {
fprintf(stderr, "create_topic error\n");
publisher_shutdown(participant, DDS_BOOLEAN_FALSE);
publisher_shutdown(participant2, DDS_BOOLEAN_TRUE);
return -1;
}
topic2 = DDS_DomainParticipant_create_topic(
participant2,
"NetworkCapture [2nd Participant]",
type_name2,
&DDS_TOPIC_QOS_DEFAULT,
NULL, /* listener */
DDS_STATUS_MASK_NONE);
if (topic2 == NULL) {
fprintf(stderr, "create_topic error\n");
publisher_shutdown(participant, DDS_BOOLEAN_FALSE);
publisher_shutdown(participant2, DDS_BOOLEAN_TRUE);
return -1;
}
writer = DDS_Publisher_create_datawriter(
publisher,
topic,
&DDS_DATAWRITER_QOS_DEFAULT,
NULL, /* listener */
DDS_STATUS_MASK_NONE);
if (writer == NULL) {
fprintf(stderr, "create_datawriter error\n");
publisher_shutdown(participant, DDS_BOOLEAN_FALSE);
publisher_shutdown(participant2, DDS_BOOLEAN_TRUE);
return -1;
}
NetworkCapture_writer = NetworkCaptureDataWriter_narrow(writer);
if (NetworkCapture_writer == NULL) {
fprintf(stderr, "DataWriter narrow error\n");
publisher_shutdown(participant, DDS_BOOLEAN_FALSE);
publisher_shutdown(participant2, DDS_BOOLEAN_TRUE);
return -1;
}
writer2 = DDS_Publisher_create_datawriter(
publisher2,
topic2,
&DDS_DATAWRITER_QOS_DEFAULT,
NULL, /* listener */
DDS_STATUS_MASK_NONE);
if (writer2 == NULL) {
fprintf(stderr, "create_datawriter error\n");
publisher_shutdown(participant, DDS_BOOLEAN_FALSE);
publisher_shutdown(participant2, DDS_BOOLEAN_TRUE);
return -1;
}
NetworkCapture_writer2 = NetworkCaptureDataWriter_narrow(writer2);
if (NetworkCapture_writer2 == NULL) {
fprintf(stderr, "DataWriter narrow error\n");
publisher_shutdown(participant, DDS_BOOLEAN_FALSE);
publisher_shutdown(participant2, DDS_BOOLEAN_TRUE);
return -1;
}
instance = NetworkCaptureTypeSupport_create_data_ex(DDS_BOOLEAN_TRUE);
if (instance == NULL) {
fprintf(stderr, "NetworkCaptureTypeSupport_create_data error\n");
publisher_shutdown(participant, DDS_BOOLEAN_FALSE);
publisher_shutdown(participant2, DDS_BOOLEAN_TRUE);
return -1;
}
/*
* Start capturing for all participants and then stop capturing for the
* first one. Similar to capture only for the second participant.
* The exception is that an empty capture file will be generated for the
* first participant, because we started capturing for it.
*/
params.parse_encrypted_content = DDS_BOOLEAN_TRUE;
params.dropped_content = NDDS_UTILITY_NETWORK_CAPTURE_CONTENT_MASK_ALL;
if (!NDDS_Utility_start_network_capture_w_params("publisher", ¶ms)) {
fprintf(stderr, "Error starting network capture\n");
}
if (!NDDS_Utility_stop_network_capture_for_participant(participant)) {
fprintf(stderr, "Error stopping network capture for 1st participant\n");
}
for (count = 0; (sample_count == 0) || (count < sample_count); ++count) {
printf("Writing NetworkCapture Secure, count %d\n", count);
RTIOsapiUtility_snprintf(
instance->msg,
128,
"Hello World Secure (%d)",
count);
retcode = NetworkCaptureDataWriter_write(
NetworkCapture_writer,
instance,
&instance_handle);
if (retcode != DDS_RETCODE_OK) {
fprintf(stderr, "write error %d\n", retcode);
}
retcode = NetworkCaptureDataWriter_write(
NetworkCapture_writer2,
instance,
&instance_handle);
if (retcode != DDS_RETCODE_OK) {
fprintf(stderr, "write error %d\n", retcode);
}
NDDS_Utility_sleep(&send_period);
}
retcode = NetworkCaptureTypeSupport_delete_data_ex(
instance,
DDS_BOOLEAN_TRUE);
if (retcode != DDS_RETCODE_OK) {
fprintf(stderr,
"NetworkCaptureTypeSupport_delete_data error %d\n",
retcode);
}
/* After a global start, use a global stop. This stops the 2nd participant
*/
success = NDDS_Utility_stop_network_capture();
if (!success) {
fprintf(stderr, "Error stopping network capture\n");
}
/* Finalize the parameters to free allocated memory */
NDDS_Utility_NetworkCaptureParams_t_finalize(¶ms);
return publisher_shutdown(participant, DDS_BOOLEAN_FALSE)
&& publisher_shutdown(participant2, DDS_BOOLEAN_TRUE);
}
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]);
}
return publisher_main(domainId, sample_count);
}
| c |
rticonnextdds-examples | data/projects/rticonnextdds-examples/connext_dds/network_capture/04_advanced_api/c/network_capture_subscriber.c | /*
* (c) Copyright, Real-Time Innovations, 2021. All rights reserved.
* RTI grants Licensee a license to use, modify, compile, and create derivative
* works of the software solely for use with RTI Connext DDS. Licensee may
* redistribute copies of the software provided that all such copies are subject
* to this license. The software is provided "as is", with no warranty of any
* type, including any warranty for fitness for any purpose. RTI is under no
* obligation to maintain or support the software. RTI shall not be liable for
* any incidental or consequential damages arising out of the use or inability
* to use the software.
*/
/*
* A simple secure Hello World using network capture to save DomainParticipant
* traffic from several participants.
*
* It shows how, if we have several participants, we can control from which
* we want to capture traffic and when.
*/
#include "ndds/ndds_c.h"
#include "network_capture.h"
#include "network_captureSupport.h"
#include <stdio.h>
#include <stdlib.h>
#ifdef RTI_STATIC
#include "security/security_default.h"
#endif
void NetworkCaptureListener_on_requested_deadline_missed(
void *listener_data,
DDS_DataReader *reader,
const struct DDS_RequestedDeadlineMissedStatus *status)
{
}
void NetworkCaptureListener_on_requested_incompatible_qos(
void *listener_data,
DDS_DataReader *reader,
const struct DDS_RequestedIncompatibleQosStatus *status)
{
}
void NetworkCaptureListener_on_sample_rejected(
void *listener_data,
DDS_DataReader *reader,
const struct DDS_SampleRejectedStatus *status)
{
}
void NetworkCaptureListener_on_liveliness_changed(
void *listener_data,
DDS_DataReader *reader,
const struct DDS_LivelinessChangedStatus *status)
{
}
void NetworkCaptureListener_on_sample_lost(
void *listener_data,
DDS_DataReader *reader,
const struct DDS_SampleLostStatus *status)
{
}
void NetworkCaptureListener_on_subscription_matched(
void *listener_data,
DDS_DataReader *reader,
const struct DDS_SubscriptionMatchedStatus *status)
{
}
void NetworkCaptureListener_on_data_available(
void *listener_data,
DDS_DataReader *reader)
{
NetworkCaptureDataReader *NetworkCapture_reader = NULL;
struct NetworkCaptureSeq data_seq = DDS_SEQUENCE_INITIALIZER;
struct DDS_SampleInfoSeq info_seq = DDS_SEQUENCE_INITIALIZER;
DDS_ReturnCode_t retcode;
int i;
NetworkCapture_reader = NetworkCaptureDataReader_narrow(reader);
if (NetworkCapture_reader == NULL) {
fprintf(stderr, "DataReader narrow error\n");
return;
}
retcode = NetworkCaptureDataReader_take(
NetworkCapture_reader,
&data_seq,
&info_seq,
DDS_LENGTH_UNLIMITED,
DDS_ANY_SAMPLE_STATE,
DDS_ANY_VIEW_STATE,
DDS_ANY_INSTANCE_STATE);
if (retcode == DDS_RETCODE_NO_DATA) {
return;
} else if (retcode != DDS_RETCODE_OK) {
fprintf(stderr, "take error %d\n", retcode);
return;
}
for (i = 0; i < NetworkCaptureSeq_get_length(&data_seq); ++i) {
if (DDS_SampleInfoSeq_get_reference(&info_seq, i)->valid_data) {
printf("Received data:\n");
NetworkCaptureTypeSupport_print_data(
NetworkCaptureSeq_get_reference(&data_seq, i));
}
}
retcode = NetworkCaptureDataReader_return_loan(
NetworkCapture_reader,
&data_seq,
&info_seq);
if (retcode != DDS_RETCODE_OK) {
fprintf(stderr, "return loan error %d\n", retcode);
}
}
static int subscriber_shutdown(
DDS_DomainParticipant *participant,
DDS_Boolean last_participant)
{
DDS_ReturnCode_t retcode;
int status = 0;
if (participant != NULL) {
retcode = DDS_DomainParticipant_delete_contained_entities(participant);
if (retcode != DDS_RETCODE_OK) {
fprintf(stderr, "delete_contained_entities error %d\n", retcode);
status = -1;
}
retcode = DDS_DomainParticipantFactory_delete_participant(
DDS_TheParticipantFactory,
participant);
if (retcode != DDS_RETCODE_OK) {
fprintf(stderr, "delete_participant error %d\n", retcode);
status = -1;
}
}
if (last_participant) {
retcode = DDS_DomainParticipantFactory_finalize_instance();
if (retcode != DDS_RETCODE_OK) {
fprintf(stderr, "finalize_instance error %d\n", retcode);
status = -1;
}
/*
* Disable network capture.
*
* This must be:
* - The last network capture function that is called.
*/
if (!NDDS_Utility_disable_network_capture()) {
fprintf(stderr, "Error disabling network capture\n");
status = -1;
}
}
return status;
}
static int subscriber_main(int domainId, int sample_count)
{
DDS_DomainParticipant *participant = NULL;
DDS_DomainParticipant *participant2 = NULL;
DDS_Subscriber *subscriber = NULL;
DDS_Subscriber *subscriber2 = NULL;
DDS_Subscriber *subscriber3 = NULL;
DDS_Topic *topic = NULL;
DDS_Topic *topic2 = NULL;
struct DDS_DataReaderListener reader_listener =
DDS_DataReaderListener_INITIALIZER;
DDS_DataReader *reader = NULL;
DDS_DataReader *reader2 = NULL;
DDS_DataReader *reader3 = NULL;
DDS_ReturnCode_t retcode;
const char *type_name = NULL;
const char *type_name2 = NULL;
int count = 0;
struct DDS_Duration_t poll_period = { 0, 10000000 }; /* 10 ms */
DDS_Boolean success = DDS_BOOLEAN_FALSE;
NDDS_Utility_NetworkCaptureParams_t params =
NDDS_UTILITY_NETWORK_CAPTURE_PARAMETERS_DEFAULT;
/*
* Enable network capture.
*
* This must be called before:
* - Any other network capture function is called.
* - Creating the participants for which we want to capture traffic.
*/
if (!NDDS_Utility_enable_network_capture()) {
fprintf(stderr, "Error enabling network capture\n");
return -1;
}
/*
* Configuration of the capture for the second participant.
* - Parse encrypted content.
* - Only capture shared memory transport.
*/
params.parse_encrypted_content = DDS_BOOLEAN_TRUE;
DDS_StringSeq_ensure_length(¶ms.transports, 1, 128);
*DDS_StringSeq_get_reference(¶ms.transports, 0) =
DDS_String_dup("shmem");
/*
* Or you could add also udpv4 by using instead:
* DDS_StringSeq_ensure_length(¶ms.transports, 2, 128);
* *DDS_StringSeq_get_reference(¶ms.transports, 0) =
* DDS_String_dup("shmem");
* *DDS_StringSeq_get_reference(¶ms.transports, 1) =
* DDS_String_dup("udpv4");
*/
/*
* The example continues as the usual Connext DDS secure Hello World.
* Create entities, start communication, etc.
*
* The peculiarity here is that we are creating two participants, each one
* with its own subscriber (participant2 has two) and joining to a different
* topic.
*/
#ifdef RTI_STATIC
struct DDS_DomainParticipantQos participant_qos =
DDS_DomainParticipantQos_INITIALIZER;
retcode = DDS_DomainParticipantFactory_get_participant_qos_from_profile(
DDS_TheParticipantFactory,
&participant_qos,
"network_capture_Library",
"network_capture_ProfileA");
if (retcode != DDS_RETCODE_OK) {
fprintf(stderr, "Unable to get default participant qos\n");
return -1;
}
retcode = DDS_PropertyQosPolicyHelper_assert_pointer_property(
&participant_qos.property,
RTI_SECURITY_BUILTIN_PLUGIN_PROPERTY_NAME ".create_function_ptr",
RTI_Security_PluginSuite_create);
if (retcode != DDS_RETCODE_OK) {
fprintf(stderr, "Unable to assert create_function_ptr property\n");
return -1;
}
participant = DDS_DomainParticipantFactory_create_participant(
DDS_TheParticipantFactory,
domainId,
&participant_qos,
NULL,
DDS_STATUS_MASK_NONE);
participant2 = DDS_DomainParticipantFactory_create_participant(
DDS_TheParticipantFactory,
domainId,
&participant_qos,
NULL,
DDS_STATUS_MASK_NONE);
DDS_DomainParticipantQos_finalize(&participant_qos);
#else
participant = DDS_DomainParticipantFactory_create_participant_with_profile(
DDS_TheParticipantFactory,
domainId,
"network_capture_Library",
"network_capture_ProfileA",
NULL,
DDS_STATUS_MASK_NONE);
participant2 = DDS_DomainParticipantFactory_create_participant_with_profile(
DDS_TheParticipantFactory,
domainId,
"network_capture_Library",
"network_capture_ProfileA",
NULL,
DDS_STATUS_MASK_NONE);
#endif
if (participant == NULL || participant2 == NULL) {
fprintf(stderr, "create_participant error\n");
subscriber_shutdown(participant, DDS_BOOLEAN_FALSE);
subscriber_shutdown(participant2, DDS_BOOLEAN_TRUE);
return -1;
}
subscriber = DDS_DomainParticipant_create_subscriber(
participant,
&DDS_SUBSCRIBER_QOS_DEFAULT,
NULL, /* listener */
DDS_STATUS_MASK_NONE);
if (subscriber == NULL) {
fprintf(stderr, "create_subscriber error\n");
subscriber_shutdown(participant, DDS_BOOLEAN_FALSE);
subscriber_shutdown(participant2, DDS_BOOLEAN_TRUE);
return -1;
}
subscriber2 = DDS_DomainParticipant_create_subscriber(
participant2,
&DDS_SUBSCRIBER_QOS_DEFAULT,
NULL, /* listener */
DDS_STATUS_MASK_NONE);
if (subscriber2 == NULL) {
fprintf(stderr, "create_subscriber error\n");
subscriber_shutdown(participant, DDS_BOOLEAN_FALSE);
subscriber_shutdown(participant2, DDS_BOOLEAN_TRUE);
return -1;
}
subscriber3 = DDS_DomainParticipant_create_subscriber(
participant2,
&DDS_SUBSCRIBER_QOS_DEFAULT,
NULL, /* listener */
DDS_STATUS_MASK_NONE);
if (subscriber3 == NULL) {
fprintf(stderr, "create_subscriber error\n");
subscriber_shutdown(participant, DDS_BOOLEAN_FALSE);
subscriber_shutdown(participant2, DDS_BOOLEAN_TRUE);
return -1;
}
type_name = NetworkCaptureTypeSupport_get_type_name();
retcode = NetworkCaptureTypeSupport_register_type(participant, type_name);
if (retcode != DDS_RETCODE_OK) {
fprintf(stderr, "register_type error %d\n", retcode);
subscriber_shutdown(participant, DDS_BOOLEAN_FALSE);
subscriber_shutdown(participant2, DDS_BOOLEAN_TRUE);
return -1;
}
type_name2 = NetworkCaptureTypeSupport_get_type_name();
retcode = NetworkCaptureTypeSupport_register_type(participant2, type_name2);
if (retcode != DDS_RETCODE_OK) {
fprintf(stderr, "register_type error %d\n", retcode);
subscriber_shutdown(participant, DDS_BOOLEAN_FALSE);
subscriber_shutdown(participant2, DDS_BOOLEAN_TRUE);
return -1;
}
topic = DDS_DomainParticipant_create_topic(
participant,
"NetworkCapture [1st Participant]",
type_name,
&DDS_TOPIC_QOS_DEFAULT,
NULL, /* listener */
DDS_STATUS_MASK_NONE);
if (topic == NULL) {
fprintf(stderr, "create_topic error\n");
subscriber_shutdown(participant, DDS_BOOLEAN_FALSE);
subscriber_shutdown(participant2, DDS_BOOLEAN_TRUE);
return -1;
}
topic2 = DDS_DomainParticipant_create_topic(
participant2,
"NetworkCapture [2nd Participant]",
type_name2,
&DDS_TOPIC_QOS_DEFAULT,
NULL, /* listener */
DDS_STATUS_MASK_NONE);
if (topic2 == NULL) {
fprintf(stderr, "create_topic error\n");
subscriber_shutdown(participant, DDS_BOOLEAN_FALSE);
subscriber_shutdown(participant2, DDS_BOOLEAN_TRUE);
return -1;
}
/*
* Start capturing traffic.
* Default parameters for first participant and configured ones for the
* second participant.
*/
success = NDDS_Utility_start_network_capture_for_participant(
participant,
"subscriberParticipant1");
if (!success) {
fprintf(stderr, "Error starting network capture for 1st participant\n");
}
success = NDDS_Utility_start_network_capture_w_params_for_participant(
participant2,
"subscriberParticipant2",
¶ms);
if (!success) {
fprintf(stderr, "Error starting network monitor for 2nd participant\n");
}
reader_listener.on_requested_deadline_missed =
NetworkCaptureListener_on_requested_deadline_missed;
reader_listener.on_requested_incompatible_qos =
NetworkCaptureListener_on_requested_incompatible_qos;
reader_listener.on_sample_rejected =
NetworkCaptureListener_on_sample_rejected;
reader_listener.on_liveliness_changed =
NetworkCaptureListener_on_liveliness_changed;
reader_listener.on_sample_lost = NetworkCaptureListener_on_sample_lost;
reader_listener.on_subscription_matched =
NetworkCaptureListener_on_subscription_matched;
reader_listener.on_data_available =
NetworkCaptureListener_on_data_available;
reader = DDS_Subscriber_create_datareader(
subscriber,
DDS_Topic_as_topicdescription(topic),
&DDS_DATAREADER_QOS_DEFAULT,
&reader_listener,
DDS_STATUS_MASK_ALL);
if (reader == NULL) {
fprintf(stderr, "create_datareader error\n");
subscriber_shutdown(participant, DDS_BOOLEAN_FALSE);
subscriber_shutdown(participant2, DDS_BOOLEAN_TRUE);
return -1;
}
reader2 = DDS_Subscriber_create_datareader(
subscriber2,
DDS_Topic_as_topicdescription(topic2),
&DDS_DATAREADER_QOS_DEFAULT,
&reader_listener,
DDS_STATUS_MASK_ALL);
if (reader2 == NULL) {
fprintf(stderr, "create_datareader error\n");
subscriber_shutdown(participant, DDS_BOOLEAN_FALSE);
subscriber_shutdown(participant2, DDS_BOOLEAN_TRUE);
return -1;
}
reader3 = DDS_Subscriber_create_datareader(
subscriber3,
DDS_Topic_as_topicdescription(topic2),
&DDS_DATAREADER_QOS_DEFAULT,
&reader_listener,
DDS_STATUS_MASK_ALL);
if (reader3 == NULL) {
fprintf(stderr, "create_datareader error\n");
subscriber_shutdown(participant, DDS_BOOLEAN_FALSE);
subscriber_shutdown(participant2, DDS_BOOLEAN_TRUE);
return -1;
}
for (count = 0; (sample_count == 0) || (count < sample_count); ++count) {
printf("NetworkCapture subscriber sleeping for %d sec...\n",
poll_period.sec);
/*
* Here we are going to pause capturing for the second participant
* The resulting pcap file will not contain them.
*
* Note: the count here is independent of the count in the publisher, so
* the numbers will not exactly match.
*/
if (count == 4
&& !NDDS_Utility_pause_network_capture_for_participant(
participant2)) {
fprintf(stderr, "Error pausing network capture\n");
} else if (count == 6 && !NDDS_Utility_resume_network_capture()) {
/*
* This will resume network capture for the second participant
* (the first is already running).
*/
fprintf(stderr, "Error resuming network capture\n");
}
NDDS_Utility_sleep(&poll_period);
}
/*
* Before deleting the participants that are capturing, we must stop
* network capture for them.
*/
if (!NDDS_Utility_stop_network_capture_for_participant(participant)) {
fprintf(stderr, "Error stopping network capture for 1st participant\n");
}
if (!NDDS_Utility_stop_network_capture) {
/* First participant is already stopped, so this stops only second */
fprintf(stderr, "Error stopping network capture\n");
}
/* Finalize the parameters to free allocated memory */
NDDS_Utility_NetworkCaptureParams_t_finalize(¶ms);
return subscriber_shutdown(participant, DDS_BOOLEAN_FALSE)
&& subscriber_shutdown(participant2, DDS_BOOLEAN_TRUE);
}
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]);
}
return subscriber_main(domainId, sample_count);
}
| c |
rticonnextdds-examples | data/projects/rticonnextdds-examples/connext_dds/network_capture/03_security/c/network_capture_publisher.c | /*
* (c) Copyright, Real-Time Innovations, 2021. All rights reserved.
* RTI grants Licensee a license to use, modify, compile, and create derivative
* works of the software solely for use with RTI Connext DDS. Licensee may
* redistribute copies of the software provided that all such copies are subject
* to this license. The software is provided "as is", with no warranty of any
* type, including any warranty for fitness for any purpose. RTI is under no
* obligation to maintain or support the software. RTI shall not be liable for
* any incidental or consequential damages arising out of the use or inability
* to use the software.
*/
/*
* A simple secure HelloWorld using network capture to save DomainParticipant
* traffic.
*
* This example is a simple secure hello world running network capture for both
* a publisher participant (network_capture_publisher.c).and a subscriber
* participant (network_capture_subscriber.c). It shows the basic flow when
* working with network capture:
* - Enabling before anything else.
* - Start capturing traffic (for one or all participants).
* - Pause/resume capturing traffic (for one or all participants).
* - Stop capturing trafffic (for one or all participants).
* - Disable after everything else.
* It also initializes some configuration parameters before starting to capture
* and finalizes when they are no longer in use.
*/
#include "ndds/ndds_c.h"
#include "network_capture.h"
#include "network_captureSupport.h"
#include <stdio.h>
#include <stdlib.h>
#ifdef RTI_STATIC
#include "security/security_default.h"
#endif
static int publisher_shutdown(DDS_DomainParticipant *participant)
{
DDS_ReturnCode_t retcode;
int status = 0;
if (participant != NULL) {
retcode = DDS_DomainParticipant_delete_contained_entities(participant);
if (retcode != DDS_RETCODE_OK) {
fprintf(stderr, "delete_contained_entities error %d\n", retcode);
status = -1;
}
retcode = DDS_DomainParticipantFactory_delete_participant(
DDS_TheParticipantFactory,
participant);
if (retcode != DDS_RETCODE_OK) {
fprintf(stderr, "delete_participant error %d\n", retcode);
status = -1;
}
}
retcode = DDS_DomainParticipantFactory_finalize_instance();
if (retcode != DDS_RETCODE_OK) {
fprintf(stderr, "finalize_instance error %d\n", retcode);
status = -1;
}
/*
* Disable network capture.
*
* This must be:
* - The last network capture function that is called.
*/
if (!NDDS_Utility_disable_network_capture()) {
fprintf(stderr, "Error disabling network capture\n");
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;
NetworkCaptureDataWriter *NetworkCapture_writer = NULL;
NetworkCapture *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 }; /* 1 s */
NDDS_Utility_NetworkCaptureParams_t params =
NDDS_UTILITY_NETWORK_CAPTURE_PARAMETERS_DEFAULT;
/*
* Enable network capture.
*
* This must be called before:
* - Any other network capture function is called.
* - Creating the participants for which we want to capture traffic.
*/
if (!NDDS_Utility_enable_network_capture()) {
fprintf(stderr, "Error enabling network capture\n");
return -1;
}
/*
* Configuration of the capture.
* - Only capture input traffic.
* - Defaults: e.g. Do not parse encrypted content (i.e., show traffic
* with protection, as in wire).
*/
params.traffic = NDDS_UTILITY_NETWORK_CAPTURE_TRAFFIC_IN;
if (!NDDS_Utility_start_network_capture_w_params("publisher", ¶ms)) {
fprintf(stderr,
"Error enabling network monitor for all participants\n");
}
/*
* The example continues as the usual Connext DDS secure HelloWorld.
* Create entities, start communication, etc.
*/
#ifdef RTI_STATIC
struct DDS_DomainParticipantQos participant_qos =
DDS_DomainParticipantQos_INITIALIZER;
retcode = DDS_DomainParticipantFactory_get_participant_qos_from_profile(
DDS_TheParticipantFactory,
&participant_qos,
"network_capture_Library",
"network_capture_ProfileB");
if (retcode != DDS_RETCODE_OK) {
fprintf(stderr, "Unable to get participant qos from profile\n");
return -1;
}
retcode = DDS_PropertyQosPolicyHelper_assert_pointer_property(
&participant_qos.property,
RTI_SECURITY_BUILTIN_PLUGIN_PROPERTY_NAME ".create_function_ptr",
RTI_Security_PluginSuite_create);
if (retcode != DDS_RETCODE_OK) {
fprintf(stderr, "Unable to assert create_function_ptr property\n");
return -1;
}
participant = DDS_DomainParticipantFactory_create_participant(
DDS_TheParticipantFactory,
domainId,
&participant_qos,
NULL,
DDS_STATUS_MASK_NONE);
DDS_DomainParticipantQos_finalize(&participant_qos);
#else
participant = DDS_DomainParticipantFactory_create_participant_with_profile(
DDS_TheParticipantFactory,
domainId,
"network_capture_Library",
"network_capture_ProfileB",
NULL,
DDS_STATUS_MASK_NONE);
#endif
if (participant == NULL) {
fprintf(stderr, "create_participant error\n");
publisher_shutdown(participant);
return -1;
}
publisher = DDS_DomainParticipant_create_publisher(
participant,
&DDS_PUBLISHER_QOS_DEFAULT,
NULL, /* listener */
DDS_STATUS_MASK_NONE);
if (publisher == NULL) {
fprintf(stderr, "create_publisher error\n");
publisher_shutdown(participant);
return -1;
}
type_name = NetworkCaptureTypeSupport_get_type_name();
retcode = NetworkCaptureTypeSupport_register_type(participant, type_name);
if (retcode != DDS_RETCODE_OK) {
fprintf(stderr, "register_type error %d\n", retcode);
publisher_shutdown(participant);
return -1;
}
topic = DDS_DomainParticipant_create_topic(
participant,
"Example NetworkCapture using security",
type_name,
&DDS_TOPIC_QOS_DEFAULT,
NULL, /* listener */
DDS_STATUS_MASK_NONE);
if (topic == NULL) {
fprintf(stderr, "create_topic error\n");
publisher_shutdown(participant);
return -1;
}
writer = DDS_Publisher_create_datawriter(
publisher,
topic,
&DDS_DATAWRITER_QOS_DEFAULT,
NULL, /* listener */
DDS_STATUS_MASK_NONE);
if (writer == NULL) {
fprintf(stderr, "create_datawriter error\n");
publisher_shutdown(participant);
return -1;
}
NetworkCapture_writer = NetworkCaptureDataWriter_narrow(writer);
if (NetworkCapture_writer == NULL) {
fprintf(stderr, "DataWriter narrow error\n");
publisher_shutdown(participant);
return -1;
}
instance = NetworkCaptureTypeSupport_create_data_ex(DDS_BOOLEAN_TRUE);
if (instance == NULL) {
fprintf(stderr, "NetworkCaptureTypeSupport_create_data error\n");
publisher_shutdown(participant);
return -1;
}
for (count = 0; (sample_count == 0) || (count < sample_count); ++count) {
printf("Writing NetworkCapture Secure, count %d\n", count);
RTIOsapiUtility_snprintf(
instance->msg,
128,
"Hello World Secure (%d)",
count);
retcode = NetworkCaptureDataWriter_write(
NetworkCapture_writer,
instance,
&instance_handle);
if (retcode != DDS_RETCODE_OK) {
fprintf(stderr, "write error %d\n", retcode);
}
NDDS_Utility_sleep(&send_period);
}
retcode = NetworkCaptureTypeSupport_delete_data_ex(
instance,
DDS_BOOLEAN_TRUE);
if (retcode != DDS_RETCODE_OK) {
fprintf(stderr,
"NetworkCaptureTypeSupport_delete_data error %d\n",
retcode);
}
/*
* Before deleting the participants that are capturing, we must stop
* network capture for them.
*/
if (!NDDS_Utility_stop_network_capture()) {
fprintf(stderr,
"Error stopping network capture for all participants\n");
}
/* Finalize the parameters to free allocated memory */
NDDS_Utility_NetworkCaptureParams_t_finalize(¶ms);
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]);
}
return publisher_main(domainId, sample_count);
}
| c |
rticonnextdds-examples | data/projects/rticonnextdds-examples/connext_dds/network_capture/03_security/c/network_capture_subscriber.c | /*
* (c) Copyright, Real-Time Innovations, 2021. All rights reserved.
* RTI grants Licensee a license to use, modify, compile, and create derivative
* works of the software solely for use with RTI Connext DDS. Licensee may
* redistribute copies of the software provided that all such copies are subject
* to this license. The software is provided "as is", with no warranty of any
* type, including any warranty for fitness for any purpose. RTI is under no
* obligation to maintain or support the software. RTI shall not be liable for
* any incidental or consequential damages arising out of the use or inability
* to use the software.
*/
/*
* A simple secure HelloWorld using network capture to save DomainParticipant
* traffic.
*
* This example is a simple secure hello world running network capture for both
* a publisher participant (network_capture_publisher.c).and a subscriber
* participant (network_capture_subscriber.c). It shows the basic flow when
* working with network capture:
* - Enabling before anything else.
* - Start capturing traffic (for one or all participants).
* - Pause/resume capturing traffic (for one or all participants).
* - Stop capturing trafffic (for one or all participants).
* - Disable after everything else.
* It also initializes some configuration parameters before starting to capture
* and finalizes when they are no longer in use.
*/
#include "ndds/ndds_c.h"
#include "network_capture.h"
#include "network_captureSupport.h"
#include <stdio.h>
#include <stdlib.h>
#ifdef RTI_STATIC
#include "security/security_default.h"
#endif
void NetworkCaptureListener_on_requested_deadline_missed(
void *listener_data,
DDS_DataReader *reader,
const struct DDS_RequestedDeadlineMissedStatus *status)
{
}
void NetworkCaptureListener_on_requested_incompatible_qos(
void *listener_data,
DDS_DataReader *reader,
const struct DDS_RequestedIncompatibleQosStatus *status)
{
}
void NetworkCaptureListener_on_sample_rejected(
void *listener_data,
DDS_DataReader *reader,
const struct DDS_SampleRejectedStatus *status)
{
}
void NetworkCaptureListener_on_liveliness_changed(
void *listener_data,
DDS_DataReader *reader,
const struct DDS_LivelinessChangedStatus *status)
{
}
void NetworkCaptureListener_on_sample_lost(
void *listener_data,
DDS_DataReader *reader,
const struct DDS_SampleLostStatus *status)
{
}
void NetworkCaptureListener_on_subscription_matched(
void *listener_data,
DDS_DataReader *reader,
const struct DDS_SubscriptionMatchedStatus *status)
{
}
void NetworkCaptureListener_on_data_available(
void *listener_data,
DDS_DataReader *reader)
{
NetworkCaptureDataReader *NetworkCapture_reader = NULL;
struct NetworkCaptureSeq data_seq = DDS_SEQUENCE_INITIALIZER;
struct DDS_SampleInfoSeq info_seq = DDS_SEQUENCE_INITIALIZER;
DDS_ReturnCode_t retcode;
int i;
NetworkCapture_reader = NetworkCaptureDataReader_narrow(reader);
if (NetworkCapture_reader == NULL) {
fprintf(stderr, "DataReader narrow error\n");
return;
}
retcode = NetworkCaptureDataReader_take(
NetworkCapture_reader,
&data_seq,
&info_seq,
DDS_LENGTH_UNLIMITED,
DDS_ANY_SAMPLE_STATE,
DDS_ANY_VIEW_STATE,
DDS_ANY_INSTANCE_STATE);
if (retcode == DDS_RETCODE_NO_DATA) {
return;
} else if (retcode != DDS_RETCODE_OK) {
fprintf(stderr, "take error %d\n", retcode);
return;
}
for (i = 0; i < NetworkCaptureSeq_get_length(&data_seq); ++i) {
if (DDS_SampleInfoSeq_get_reference(&info_seq, i)->valid_data) {
printf("Received data:\n");
NetworkCaptureTypeSupport_print_data(
NetworkCaptureSeq_get_reference(&data_seq, i));
}
}
retcode = NetworkCaptureDataReader_return_loan(
NetworkCapture_reader,
&data_seq,
&info_seq);
if (retcode != DDS_RETCODE_OK) {
fprintf(stderr, "return loan error %d\n", retcode);
}
}
static int subscriber_shutdown(DDS_DomainParticipant *participant)
{
DDS_ReturnCode_t retcode;
int status = 0;
if (participant != NULL) {
retcode = DDS_DomainParticipant_delete_contained_entities(participant);
if (retcode != DDS_RETCODE_OK) {
fprintf(stderr, "delete_contained_entities error %d\n", retcode);
status = -1;
}
retcode = DDS_DomainParticipantFactory_delete_participant(
DDS_TheParticipantFactory,
participant);
if (retcode != DDS_RETCODE_OK) {
fprintf(stderr, "delete_participant error %d\n", retcode);
status = -1;
}
}
retcode = DDS_DomainParticipantFactory_finalize_instance();
if (retcode != DDS_RETCODE_OK) {
fprintf(stderr, "finalize_instance error %d\n", retcode);
status = -1;
}
/*
* Disable network capture.
*
* This must be:
* - The last network capture function that is called.
*/
if (!NDDS_Utility_disable_network_capture()) {
fprintf(stderr, "Error disabling network capture\n");
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 }; /* 1 s */
NDDS_Utility_NetworkCaptureParams_t params =
NDDS_UTILITY_NETWORK_CAPTURE_PARAMETERS_DEFAULT;
/*
* Enable network capture.
*
* This must be called before:
* - Any other network capture function is called.
* - Creating the participants for which we want to capture traffic.
*/
if (!NDDS_Utility_enable_network_capture()) {
fprintf(stderr, "Error enabling network capture\n");
return -1;
}
/*
* Configuration of the capture.
* - Parse encrypted content.
* - Remove all user data (serialized and encrypted) from the capture.
* - Defaults: e.g., capture input and output traffic.
*/
params.parse_encrypted_content = DDS_BOOLEAN_TRUE;
params.dropped_content =
NDDS_UTILITY_NETWORK_CAPTURE_CONTENT_ENCRYPTED_DATA;
if (!NDDS_Utility_start_network_capture_w_params("subscriber", ¶ms)) {
fprintf(stderr,
"Error enabling network monitor for all participants\n");
}
/*
* The example continues as the usual Connext DDS secure HelloWorld.
* Create entities, start communication, etc.
*/
#ifdef RTI_STATIC
struct DDS_DomainParticipantQos participant_qos =
DDS_DomainParticipantQos_INITIALIZER;
retcode = DDS_DomainParticipantFactory_get_participant_qos_from_profile(
DDS_TheParticipantFactory,
&participant_qos,
"network_capture_Library",
"network_capture_ProfileA");
if (retcode != DDS_RETCODE_OK) {
fprintf(stderr, "Unable to get default participant qos\n");
return -1;
}
retcode = DDS_PropertyQosPolicyHelper_assert_pointer_property(
&participant_qos.property,
RTI_SECURITY_BUILTIN_PLUGIN_PROPERTY_NAME ".create_function_ptr",
RTI_Security_PluginSuite_create);
if (retcode != DDS_RETCODE_OK) {
fprintf(stderr, "Unable to assert create_function_ptr property\n");
return -1;
}
participant = DDS_DomainParticipantFactory_create_participant(
DDS_TheParticipantFactory,
domainId,
&participant_qos,
NULL,
DDS_STATUS_MASK_NONE);
DDS_DomainParticipantQos_finalize(&participant_qos);
#else
participant = DDS_DomainParticipantFactory_create_participant_with_profile(
DDS_TheParticipantFactory,
domainId,
"network_capture_Library",
"network_capture_ProfileA",
NULL,
DDS_STATUS_MASK_NONE);
#endif
if (participant == NULL) {
fprintf(stderr, "create_participant error\n");
subscriber_shutdown(participant);
return -1;
}
subscriber = DDS_DomainParticipant_create_subscriber(
participant,
&DDS_SUBSCRIBER_QOS_DEFAULT,
NULL, /* listener */
DDS_STATUS_MASK_NONE);
if (subscriber == NULL) {
fprintf(stderr, "create_subscriber error\n");
subscriber_shutdown(participant);
return -1;
}
type_name = NetworkCaptureTypeSupport_get_type_name();
retcode = NetworkCaptureTypeSupport_register_type(participant, type_name);
if (retcode != DDS_RETCODE_OK) {
fprintf(stderr, "register_type error %d\n", retcode);
subscriber_shutdown(participant);
return -1;
}
topic = DDS_DomainParticipant_create_topic(
participant,
"Example NetworkCapture using security",
type_name,
&DDS_TOPIC_QOS_DEFAULT,
NULL, /* listener */
DDS_STATUS_MASK_NONE);
if (topic == NULL) {
fprintf(stderr, "create_topic error\n");
subscriber_shutdown(participant);
return -1;
}
reader_listener.on_requested_deadline_missed =
NetworkCaptureListener_on_requested_deadline_missed;
reader_listener.on_requested_incompatible_qos =
NetworkCaptureListener_on_requested_incompatible_qos;
reader_listener.on_sample_rejected =
NetworkCaptureListener_on_sample_rejected;
reader_listener.on_liveliness_changed =
NetworkCaptureListener_on_liveliness_changed;
reader_listener.on_sample_lost = NetworkCaptureListener_on_sample_lost;
reader_listener.on_subscription_matched =
NetworkCaptureListener_on_subscription_matched;
reader_listener.on_data_available =
NetworkCaptureListener_on_data_available;
reader = DDS_Subscriber_create_datareader(
subscriber,
DDS_Topic_as_topicdescription(topic),
&DDS_DATAREADER_QOS_DEFAULT,
&reader_listener,
DDS_STATUS_MASK_ALL);
if (reader == NULL) {
fprintf(stderr, "create_datareader error\n");
subscriber_shutdown(participant);
return -1;
}
for (count = 0; (sample_count == 0) || (count < sample_count); ++count) {
printf("NetworkCapture subscriber sleeping for %d sec...\n",
poll_period.sec);
NDDS_Utility_sleep(&poll_period);
}
/*
* Before deleting the participants that are capturing, we must stop
* network capture for them.
*/
if (!NDDS_Utility_stop_network_capture()) {
fprintf(stderr,
"Error stopping network capture for all participants\n");
}
/* Finalize the parameters to free allocated memory */
NDDS_Utility_NetworkCaptureParams_t_finalize(¶ms);
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]);
}
return subscriber_main(domainId, sample_count);
}
| c |
rticonnextdds-examples | data/projects/rticonnextdds-examples/connext_dds/coherent_presentation/c++/coherent_subscriber.cxx | /*******************************************************************************
(c) 2005-2014 Copyright, Real-Time Innovations, Inc. All rights reserved.
RTI grants Licensee a license to use, modify, compile, and create derivative
works of the Software. Licensee has the right to distribute object form only
for use with RTI products. The Software is provided "as is", with no warranty
of any type, including any warranty for fitness for any purpose. RTI is under
no obligation to maintain or support the Software. RTI shall not be liable for
any incidental or consequential damages arising out of the use or inability to
use the software.
******************************************************************************/
/* coherent_subscriber.cxx
A subscription example
This file is derived from code automatically generated by the rtiddsgen
command:
rtiddsgen -language C++ -example <arch> coherent.idl
Example subscription of type coherent automatically generated by
'rtiddsgen'. To test them follow these steps:
(1) Compile this file and the example publication.
(2) Start the subscription with the command
objs/<arch>/coherent_subscriber <domain_id> <sample_count>
(3) Start the publication with the command
objs/<arch>/coherent_publisher <domain_id> <sample_count>
(4) [Optional] Specify the list of discovery initial peers and
multicast receive addresses via an environment variable or a file
(in the current working directory) called NDDS_DISCOVERY_PEERS.
You can run any number of publishers and subscribers programs, and can
add and remove them dynamically from the domain.
Example:
To run the example application on domain <domain_id>:
On Unix:
objs/<arch>/coherent_publisher <domain_id>
objs/<arch>/coherent_subscriber <domain_id>
On Windows:
objs\<arch>\coherent_publisher <domain_id>
objs\<arch>\coherent_subscriber <domain_id>
modification history
------------ -------
*/
#include <stdio.h>
#include <stdlib.h>
#ifdef RTI_VX653
#include <vThreadsData.h>
#endif
#include "coherent.h"
#include "coherentSupport.h"
#include "ndds/ndds_cpp.h"
/* Start changes for coherent_presentation */
static const unsigned int STATENVALS = 6;
int statevals[STATENVALS] = { 0 };
void print_state()
{
char c = 'a';
unsigned int i = 0;
for (i = 0; i < STATENVALS; ++i) {
printf(" %c = %d;", c++, statevals[i]);
}
}
void set_state(char c, int value)
{
unsigned int idx = c - 'a';
if (idx < 0 || idx >= STATENVALS) {
printf("error: invalid field '%c'\n", c);
return;
}
statevals[idx] = value;
}
/* End changes for coherent_presentation */
class coherentListener : public DDSDataReaderListener {
public:
virtual void on_requested_deadline_missed(
DDSDataReader * /*reader*/,
const DDS_RequestedDeadlineMissedStatus & /*status*/)
{
}
virtual void on_requested_incompatible_qos(
DDSDataReader * /*reader*/,
const DDS_RequestedIncompatibleQosStatus & /*status*/)
{
}
virtual void on_sample_rejected(
DDSDataReader * /*reader*/,
const DDS_SampleRejectedStatus & /*status*/)
{
}
virtual void on_liveliness_changed(
DDSDataReader * /*reader*/,
const DDS_LivelinessChangedStatus & /*status*/)
{
}
virtual void on_sample_lost(
DDSDataReader * /*reader*/,
const DDS_SampleLostStatus & /*status*/)
{
}
virtual void on_subscription_matched(
DDSDataReader * /*reader*/,
const DDS_SubscriptionMatchedStatus & /*status*/)
{
}
virtual void on_data_available(DDSDataReader *reader);
};
void coherentListener::on_data_available(DDSDataReader *reader)
{
coherentDataReader *coherent_reader = NULL;
coherentSeq data_seq;
DDS_SampleInfoSeq info_seq;
DDS_ReturnCode_t retcode;
int i;
int len = 0;
coherent_reader = coherentDataReader::narrow(reader);
if (coherent_reader == NULL) {
printf("DataReader narrow error\n");
return;
}
retcode = coherent_reader->take(
data_seq,
info_seq,
DDS_LENGTH_UNLIMITED,
DDS_ANY_SAMPLE_STATE,
DDS_ANY_VIEW_STATE,
DDS_ANY_INSTANCE_STATE);
if (retcode == DDS_RETCODE_NO_DATA) {
return;
} else if (retcode != DDS_RETCODE_OK) {
printf("take error %d\n", retcode);
return;
}
/* Start changes for coherent_presentation */
/* Firstly process all samples */
for (i = 0; i < data_seq.length(); ++i) {
if (info_seq[i].valid_data) {
len++;
set_state(data_seq[i].field, data_seq[i].value);
}
}
/* Then, we print the results */
if (len > 0) {
printf("Received %d updates\n", len);
print_state();
printf("\n");
}
/* End changes for coherent_presentation */
retcode = coherent_reader->return_loan(data_seq, info_seq);
if (retcode != DDS_RETCODE_OK) {
printf("return loan error %d\n", retcode);
}
}
/* Delete all entities */
static int subscriber_shutdown(DDSDomainParticipant *participant)
{
DDS_ReturnCode_t retcode;
int status = 0;
if (participant != NULL) {
retcode = participant->delete_contained_entities();
if (retcode != DDS_RETCODE_OK) {
printf("delete_contained_entities error %d\n", retcode);
status = -1;
}
retcode = DDSTheParticipantFactory->delete_participant(participant);
if (retcode != DDS_RETCODE_OK) {
printf("delete_participant error %d\n", retcode);
status = -1;
}
}
/* RTI Connext provides the finalize_instance() method on
domain participant factory for people who want to release memory used
by the participant factory. Uncomment the following block of code for
clean destruction of the singleton. */
/*
retcode = DDSDomainParticipantFactory::finalize_instance();
if (retcode != DDS_RETCODE_OK) {
printf("finalize_instance error %d\n", retcode);
status = -1;
}
*/
return status;
}
extern "C" int subscriber_main(int domainId, int sample_count)
{
DDSDomainParticipant *participant = NULL;
DDSSubscriber *subscriber = NULL;
DDSTopic *topic = NULL;
coherentListener *reader_listener = NULL;
DDSDataReader *reader = NULL;
DDS_ReturnCode_t retcode;
const char *type_name = NULL;
int count = 0;
DDS_Duration_t receive_period = { 4, 0 };
int status = 0;
DDS_SubscriberQos subscriber_qos;
DDS_DataReaderQos datareader_qos;
/* To customize the participant QoS, use
the configuration file USER_QOS_PROFILES.xml */
participant = DDSTheParticipantFactory->create_participant(
domainId,
DDS_PARTICIPANT_QOS_DEFAULT,
NULL /* listener */,
DDS_STATUS_MASK_NONE);
if (participant == NULL) {
printf("create_participant error\n");
subscriber_shutdown(participant);
return -1;
}
/* To customize the subscriber QoS, use
the configuration file USER_QOS_PROFILES.xml */
subscriber = participant->create_subscriber(
DDS_SUBSCRIBER_QOS_DEFAULT,
NULL /* listener */,
DDS_STATUS_MASK_NONE);
if (subscriber == NULL) {
printf("create_subscriber error\n");
subscriber_shutdown(participant);
return -1;
}
/* If you want to change the DataWriter's QoS programmatically rather than
* using the XML file, you will need to add the following lines to your
* code and comment out the create_subscriber call above.
*/
/* Start changes for coherent_presentation */
/* retcode = participant->get_default_subscriber_qos(subscriber_qos);
if (retcode != DDS_RETCODE_OK) {
printf("get_default_subscriber_qos error\n");
return -1;
}
subscriber_qos.presentation.access_scope = DDS_TOPIC_PRESENTATION_QOS;
subscriber_qos.presentation.coherent_access = DDS_BOOLEAN_TRUE;
subscriber = participant->create_subscriber(subscriber_qos, NULL,
DDS_STATUS_MASK_NONE);
if (subscriber == NULL) {
printf("create_subscriber error\n");
subscriber_shutdown(participant);
return -1;
}
*/
/* End changes for coherent_presentation */
/* Register the type before creating the topic */
type_name = coherentTypeSupport::get_type_name();
retcode = coherentTypeSupport::register_type(participant, type_name);
if (retcode != DDS_RETCODE_OK) {
printf("register_type error %d\n", retcode);
subscriber_shutdown(participant);
return -1;
}
/* To customize the topic QoS, use
the configuration file USER_QOS_PROFILES.xml */
topic = participant->create_topic(
"Example coherent",
type_name,
DDS_TOPIC_QOS_DEFAULT,
NULL /* listener */,
DDS_STATUS_MASK_NONE);
if (topic == NULL) {
printf("create_topic error\n");
subscriber_shutdown(participant);
return -1;
}
/* Create a data reader listener */
reader_listener = new coherentListener();
/* To customize the data reader QoS, use
the configuration file USER_QOS_PROFILES.xml */
reader = subscriber->create_datareader(
topic,
DDS_DATAREADER_QOS_DEFAULT,
reader_listener,
DDS_STATUS_MASK_ALL);
if (reader == NULL) {
printf("create_datareader error\n");
subscriber_shutdown(participant);
delete reader_listener;
return -1;
}
/* If you want to change the DataWriter's QoS programmatically rather than
* using the XML file, you will need to add the following lines to your
* code and comment out the create_datareader call above.
*/
/* retcode = subscriber->get_default_datareader_qos(datareader_qos);
if (retcode != DDS_RETCODE_OK) {
printf("get_default_datareader_qos error\n");
return -1;
}
datareader_qos.reliability.kind = DDS_RELIABLE_RELIABILITY_QOS;
datareader_qos.history.depth = 10;
reader = subscriber->create_datareader(topic, datareader_qos,
reader_listener, DDS_STATUS_MASK_ALL);
if (reader == NULL) {
printf("create_datareader error\n");
subscriber_shutdown(participant);
delete reader_listener;
return -1;
}
*/ /* End changes for coherent_presentation */
/* Main loop */
for (count = 0; (sample_count == 0) || (count < sample_count); ++count) {
NDDSUtility::sleep(receive_period);
}
/* Delete all entities */
status = subscriber_shutdown(participant);
delete reader_listener;
return status;
}
#if defined(RTI_WINCE)
int wmain(int argc, wchar_t **argv)
{
int domainId = 0;
int sample_count = 0; /* infinite loop */
if (argc >= 2) {
domainId = _wtoi(argv[1]);
}
if (argc >= 3) {
sample_count = _wtoi(argv[2]);
}
/* Uncomment this to turn on additional logging
NDDSConfigLogger::get_instance()->
set_verbosity_by_category(NDDS_CONFIG_LOG_CATEGORY_API,
NDDS_CONFIG_LOG_VERBOSITY_STATUS_ALL);
*/
return subscriber_main(domainId, sample_count);
}
#elif !(defined(RTI_VXWORKS) && !defined(__RTP__)) && !defined(RTI_PSOS)
int main(int argc, char *argv[])
{
int domainId = 0;
int sample_count = 0; /* infinite loop */
if (argc >= 2) {
domainId = atoi(argv[1]);
}
if (argc >= 3) {
sample_count = atoi(argv[2]);
}
/* Uncomment this to turn on additional logging
NDDSConfigLogger::get_instance()->
set_verbosity_by_category(NDDS_CONFIG_LOG_CATEGORY_API,
NDDS_CONFIG_LOG_VERBOSITY_STATUS_ALL);
*/
return subscriber_main(domainId, sample_count);
}
#endif
#ifdef RTI_VX653
const unsigned char *__ctype = *(__ctypePtrGet());
extern "C" void usrAppInit()
{
#ifdef USER_APPL_INIT
USER_APPL_INIT; /* for backwards compatibility */
#endif
/* add application specific code here */
taskSpawn(
"sub",
RTI_OSAPI_THREAD_PRIORITY_NORMAL,
0x8,
0x150000,
(FUNCPTR) subscriber_main,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0);
}
#endif
| cxx |
rticonnextdds-examples | data/projects/rticonnextdds-examples/connext_dds/coherent_presentation/c++/coherent_publisher.cxx | /*******************************************************************************
(c) 2005-2014 Copyright, Real-Time Innovations, Inc. All rights reserved.
RTI grants Licensee a license to use, modify, compile, and create derivative
works of the Software. Licensee has the right to distribute object form only
for use with RTI products. The Software is provided "as is", with no warranty
of any type, including any warranty for fitness for any purpose. RTI is under
no obligation to maintain or support the Software. RTI shall not be liable for
any incidental or consequential damages arising out of the use or inability to
use the software.
******************************************************************************/
/* coherent_publisher.cxx
A publication of data of type coherent
This file is derived from code automatically generated by the rtiddsgen
command:
rtiddsgen -language C++ -example <arch> coherent.idl
Example publication of type coherent automatically generated by
'rtiddsgen'. To test them follow these steps:
(1) Compile this file and the example subscription.
(2) Start the subscription with the command
objs/<arch>/coherent_subscriber <domain_id> <sample_count>
(3) Start the publication with the command
objs/<arch>/coherent_publisher <domain_id> <sample_count>
(4) [Optional] Specify the list of discovery initial peers and
multicast receive addresses via an environment variable or a file
(in the current working directory) called NDDS_DISCOVERY_PEERS.
You can run any number of publishers and subscribers programs, and can
add and remove them dynamically from the domain.
Example:
To run the example application on domain <domain_id>:
On Unix:
objs/<arch>/coherent_publisher <domain_id> o
objs/<arch>/coherent_subscriber <domain_id>
On Windows:
objs\<arch>\coherent_publisher <domain_id>
objs\<arch>\coherent_subscriber <domain_id>
modification history
------------ -------
* Change presentation scope in publisher QoS
* Use reliable communication (currently required for coherency QoS)
* Surround coherent changes with calls to {begin, end}_coherent_changes
* All QoS are in the xml file
*/
#include <stdio.h>
#include <stdlib.h>
#ifdef RTI_VX653
#include <vThreadsData.h>
#endif
#include "coherent.h"
#include "coherentSupport.h"
#include "ndds/ndds_cpp.h"
/* Delete all entities */
static int publisher_shutdown(DDSDomainParticipant *participant)
{
DDS_ReturnCode_t retcode;
int status = 0;
if (participant != NULL) {
retcode = participant->delete_contained_entities();
if (retcode != DDS_RETCODE_OK) {
printf("delete_contained_entities error %d\n", retcode);
status = -1;
}
retcode = DDSTheParticipantFactory->delete_participant(participant);
if (retcode != DDS_RETCODE_OK) {
printf("delete_participant error %d\n", retcode);
status = -1;
}
}
/* RTI Connext provides finalize_instance() method on
domain participant factory for people who want to release memory used
by the participant factory. Uncomment the following block of code for
clean destruction of the singleton. */
/*
retcode = DDSDomainParticipantFactory::finalize_instance();
if (retcode != DDS_RETCODE_OK) {
printf("finalize_instance error %d\n", retcode);
status = -1;
}
*/
return status;
}
extern "C" int publisher_main(int domainId, int sample_count)
{
DDSDomainParticipant *participant = NULL;
DDSPublisher *publisher = NULL;
DDSTopic *topic = NULL;
DDSDataWriter *writer = NULL;
coherentDataWriter *coherent_writer = NULL;
coherent *instance = NULL;
DDS_ReturnCode_t retcode;
DDS_InstanceHandle_t instance_handle = DDS_HANDLE_NIL;
const char *type_name = NULL;
int count = 0;
DDS_Duration_t send_period = { 1, 0 };
DDS_PublisherQos publisher_qos;
DDS_DataWriterQos datawriter_qos;
int mod = 0;
/* To customize participant QoS, use
the configuration file USER_QOS_PROFILES.xml */
participant = DDSTheParticipantFactory->create_participant(
domainId,
DDS_PARTICIPANT_QOS_DEFAULT,
NULL /* listener */,
DDS_STATUS_MASK_NONE);
if (participant == NULL) {
printf("create_participant error\n");
publisher_shutdown(participant);
return -1;
}
/* To customize publisher QoS, use
the configuration file USER_QOS_PROFILES.xml */
publisher = participant->create_publisher(
DDS_PUBLISHER_QOS_DEFAULT,
NULL /* listener */,
DDS_STATUS_MASK_NONE);
if (publisher == NULL) {
printf("create_publisher error\n");
publisher_shutdown(participant);
return -1;
}
/* If you want to change the DataWriter's QoS programmatically rather than
* using the XML file, you will need to add the following lines to your
* code and comment out the create_publisher call above.
*/
/* Start changes for coherent_presentation */
/* Get default publisher QoS to customize */
/* retcode = participant->get_default_publisher_qos(publisher_qos);
if (retcode != DDS_RETCODE_OK) {
printf("get_default_publisher_qos error\n");
return -1;
}
*/ /* Topic access scope means that writes from a particular datawriter to
* multiple instances will be viewed coherently.
*/
/* publisher_qos.presentation.access_scope = DDS_TOPIC_PRESENTATION_QOS;
publisher_qos.presentation.coherent_access = DDS_BOOLEAN_TRUE;
publisher = participant->create_publisher(publisher_qos, NULL,
DDS_STATUS_MASK_NONE);
if (publisher == NULL) {
printf("create_participant error\n");
publisher_shutdown(participant);
return -1;
}
*/ /* End changes for coherent_presentation */
/* Register type before creating topic */
type_name = coherentTypeSupport::get_type_name();
retcode = coherentTypeSupport::register_type(participant, type_name);
if (retcode != DDS_RETCODE_OK) {
printf("register_type error %d\n", retcode);
publisher_shutdown(participant);
return -1;
}
/* To customize topic QoS, use
the configuration file USER_QOS_PROFILES.xml */
topic = participant->create_topic(
"Example coherent",
type_name,
DDS_TOPIC_QOS_DEFAULT,
NULL /* listener */,
DDS_STATUS_MASK_NONE);
if (topic == NULL) {
printf("create_topic error\n");
publisher_shutdown(participant);
return -1;
}
/* To customize data writer QoS, use
the configuration file USER_QOS_PROFILES.xml */
writer = publisher->create_datawriter(
topic,
DDS_DATAWRITER_QOS_DEFAULT,
NULL /* listener */,
DDS_STATUS_MASK_NONE);
if (writer == NULL) {
printf("create_datawriter error\n");
publisher_shutdown(participant);
return -1;
}
/* If you want to change the DataWriter's QoS programmatically rather than
* using the XML file, you will need to add the following lines to your
* code and comment out the create_datawriter call above.
*/
/* Start changes for coheren_presentation */
/* retcode = publisher->get_default_datawriter_qos(datawriter_qos);
if (retcode != DDS_RETCODE_OK) {
printf("get_default_datawriter_qos error\n");
return -1;
}
datawriter_qos.reliability.kind = DDS_RELIABLE_RELIABILITY_QOS;
datawriter_qos.history.depth = 10;
datawriter_qos.protocol.rtps_reliable_writer.heartbeats_per_max_samples
= 0;
writer = publisher->create_datawriter(topic, datawriter_qos, NULL,
DDS_STATUS_MASK_NONE);
if (writer == NULL) {
printf("create_datawriter error\n");
publisher_shutdown(participant);
return -1;
}
*/ /* End changes for coherent_presentation */
coherent_writer = coherentDataWriter::narrow(writer);
if (coherent_writer == NULL) {
printf("DataWriter narrow error\n");
publisher_shutdown(participant);
return -1;
}
/* Create data sample for writing */
instance = coherentTypeSupport::create_data();
if (instance == NULL) {
printf("coherentTypeSupport::create_data error\n");
publisher_shutdown(participant);
return -1;
}
/* For a data type that has a key, if the same instance is going to be
written multiple times, initialize the key here
and register the keyed instance prior to writing */
instance->id = 0;
instance_handle = coherent_writer->register_instance(*instance);
publisher->begin_coherent_changes();
printf("Begin Coherent Changes\n");
/* Main loop */
for (count = 0; (sample_count == 0) || (count < sample_count); ++count) {
NDDSUtility::sleep(send_period);
mod = count % 7;
if (mod == 6) {
publisher->begin_coherent_changes();
printf("Begin Coherent Changes\n");
continue;
}
/* Choose a random value for each field */
instance->field = 'a' + mod;
instance->value = (int) (rand() / (RAND_MAX / 10.0));
printf(" Updating instance, %c->%d\n",
instance->field,
instance->value);
retcode = coherent_writer->write(*instance, instance_handle);
if (retcode != DDS_RETCODE_OK) {
printf("write error %d\n", retcode);
}
if (mod == 5) {
publisher->end_coherent_changes();
printf("End Coherent Changes\n\n");
}
}
retcode = coherent_writer->unregister_instance(*instance, instance_handle);
if (retcode != DDS_RETCODE_OK) {
printf("unregister instance error %d\n", retcode);
}
/* Delete data sample */
retcode = coherentTypeSupport::delete_data(instance);
if (retcode != DDS_RETCODE_OK) {
printf("coherentTypeSupport::delete_data error %d\n", retcode);
}
/* Delete all entities */
return publisher_shutdown(participant);
}
#if defined(RTI_WINCE)
int wmain(int argc, wchar_t **argv)
{
int domainId = 0;
int sample_count = 0; /* infinite loop */
if (argc >= 2) {
domainId = _wtoi(argv[1]);
}
if (argc >= 3) {
sample_count = _wtoi(argv[2]);
}
/* Uncomment this to turn on additional logging
NDDSConfigLogger::get_instance()->
set_verbosity_by_category(NDDS_CONFIG_LOG_CATEGORY_API,
NDDS_CONFIG_LOG_VERBOSITY_STATUS_ALL);
*/
return publisher_main(domainId, sample_count);
}
#elif !(defined(RTI_VXWORKS) && !defined(__RTP__)) && !defined(RTI_PSOS)
int main(int argc, char *argv[])
{
int domainId = 0;
int sample_count = 0; /* infinite loop */
if (argc >= 2) {
domainId = atoi(argv[1]);
}
if (argc >= 3) {
sample_count = atoi(argv[2]);
}
/* Uncomment this to turn on additional logging
NDDSConfigLogger::get_instance()->
set_verbosity_by_category(NDDS_CONFIG_LOG_CATEGORY_API,
NDDS_CONFIG_LOG_VERBOSITY_STATUS_ALL);
*/
return publisher_main(domainId, sample_count);
}
#endif
#ifdef RTI_VX653
const unsigned char *__ctype = *(__ctypePtrGet());
extern "C" void usrAppInit()
{
#ifdef USER_APPL_INIT
USER_APPL_INIT; /* for backwards compatibility */
#endif
/* add application specific code here */
taskSpawn(
"pub",
RTI_OSAPI_THREAD_PRIORITY_NORMAL,
0x8,
0x150000,
(FUNCPTR) publisher_main,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0);
}
#endif
| cxx |
rticonnextdds-examples | data/projects/rticonnextdds-examples/connext_dds/coherent_presentation/c++98/coherent_subscriber.cxx | /*******************************************************************************
(c) 2005-2014 Copyright, Real-Time Innovations, Inc. All rights reserved.
RTI grants Licensee a license to use, modify, compile, and create derivative
works of the Software. Licensee has the right to distribute object form only
for use with RTI products. The Software is provided "as is", with no warranty
of any type, including any warranty for fitness for any purpose. RTI is under
no obligation to maintain or support the Software. RTI shall not be liable for
any incidental or consequential damages arising out of the use or inability to
use the software.
******************************************************************************/
#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include "coherent.h"
#include "coherentSupport.h"
#include "ndds/ndds_cpp.h"
#include "application.h"
using namespace application;
static int shutdown_participant(
DDSDomainParticipant *participant,
const char *shutdown_message,
int status);
// Start changes for coherent_presentation
static const unsigned int STATENVALS = 6;
int statevals[STATENVALS] = { 0 };
void print_state()
{
char c = 'a';
for (int i = 0; i < STATENVALS; ++i) {
std::cout << " " << c++ << " = " << statevals[i] << ";";
}
}
void set_state(char c, int value)
{
unsigned int idx = c - 'a';
if (idx < 0 || idx >= STATENVALS) {
std::cerr << "error: invalid field " << c << std::endl;
return;
}
statevals[idx] = value;
}
// End changes for coherent_presentation
unsigned int process_data(coherentDataReader *typed_reader)
{
coherentSeq 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);
/* Start changes for coherent_presentation */
/* Firstly process all samples */
for (int i = 0; i < data_seq.length(); ++i) {
if (info_seq[i].valid_data) {
set_state(data_seq[i].field, data_seq[i].value);
samples_read++;
}
}
/* Then, we print the results */
if (samples_read > 0) {
std::cout << "Received " << samples_read << " updates\n";
print_state();
std::cout << std::endl;
}
/* End changes for coherent_presentation */
// 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)
{
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);
}
/* If you want to change the DataWriter's QoS programmatically rather than
* using the XML file, you will need to add the following lines to your
* code and comment out the create_subscriber call above.
*/
/* Start changes for coherent_presentation */
/*
DDS_ReturnCode_t retcode = participant->
get_default_subscriber_qos(subscriber_qos);
if (retcode != DDS_RETCODE_OK) {
std::cerr << "get_default_subscriber_qos error\n";
return EXIT_FAILURE;
}
subscriber_qos.presentation.access_scope = DDS_TOPIC_PRESENTATION_QOS;
subscriber_qos.presentation.coherent_access = DDS_BOOLEAN_TRUE;
DDSSubscriber *subscriber = participant
->create_subscriber(subscriber_qos, NULL, DDS_STATUS_MASK_NONE);
if (subscriber == NULL) {
return shutdown_participant(
participant,
"create_subscriber error",
EXIT_FAILURE);
}
*/
/* End changes for coherent_presentation */
// Register the datatype to use when creating the Topic
const char *type_name = coherentTypeSupport::get_type_name();
DDS_ReturnCode_t retcode =
coherentTypeSupport::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 coherent",
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 coherent" 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);
}
/* If you want to change the DataWriter's QoS programmatically rather than
* using the XML file, you will need to add the following lines to your
* code and comment out the create_datareader call above.
*/
/* retcode = subscriber->get_default_datareader_qos(datareader_qos);
if (retcode != DDS_RETCODE_OK) {
std::cerr << "get_default_datareader_qos error\n";
return EXIT_FAILURE;
}
datareader_qos.reliability.kind = DDS_RELIABLE_RELIABILITY_QOS;
datareader_qos.history.depth = 10;
DDSDataReader *untyped_reader = subscriber->create_datareader(
topic,
datareader_qos,
reader_listener,
DDS_STATUS_MASK_ALL);
if (untyped_reader == NULL) {
return shutdown_participant(
participant,
"create_datareader error",
EXIT_FAILURE);
}
*/ /* End changes for coherent_presentation */
// Narrow casts from a untyped DataReader to a reader of your type
coherentDataReader *typed_reader =
coherentDataReader::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/coherent_presentation/c++98/coherent_publisher.cxx | /*******************************************************************************
(c) 2005-2014 Copyright, Real-Time Innovations, Inc. All rights reserved.
RTI grants Licensee a license to use, modify, compile, and create derivative
works of the Software. Licensee has the right to distribute object form only
for use with RTI products. The Software is provided "as is", with no warranty
of any type, including any warranty for fitness for any purpose. RTI is under
no obligation to maintain or support the Software. RTI shall not be liable for
any incidental or consequential damages arising out of the use or inability to
use the software.
******************************************************************************/
#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include "coherent.h"
#include "coherentSupport.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 };
int mod;
// 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);
}
/* If you want to change the DataWriter's QoS programmatically rather than
* using the XML file, you will need to add the following lines to your
* code and comment out the create_publisher call above.
*/
/* Start changes for coherent_presentation */
/* Get default publisher QoS to customize */
/* DDS_ReturnCode_t retcode = participant
->get_default_publisher_qos(publisher_qos);
if (retcode != DDS_RETCODE_OK) {
std::cerr << "get_default_publisher_qos error\n");
return EXIT_FAILURE;
}
*/ /* Topic access scope means that writes from a particular datawriter to
* multiple instances will be viewed coherently.
*/
/* publisher_qos.presentation.access_scope = DDS_TOPIC_PRESENTATION_QOS;
publisher_qos.presentation.coherent_access = DDS_BOOLEAN_TRUE;
DDSPublisher * = participant->create_publisher(
publisher_qos,
NULL,
DDS_STATUS_MASK_NONE);
if (publisher == NULL) {
return shutdown_participant(
participant,
"create_publisher error",
EXIT_FAILURE);
}
*/ /* End changes for coherent_presentation */
// Register the datatype to use when creating the Topic
const char *type_name = coherentTypeSupport::get_type_name();
DDS_ReturnCode_t retcode =
coherentTypeSupport::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 coherent",
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 async" Topic
DDSDataWriter *untyped_writer = publisher->create_datawriter(
topic,
DDS_DATAWRITER_QOS_DEFAULT,
NULL /* listener */,
DDS_STATUS_MASK_NONE);
if (untyped_writer == NULL) {
return shutdown_participant(
participant,
"create_datawriter error",
EXIT_FAILURE);
}
/* If you want to change the DataWriter's QoS programmatically rather than
* using the XML file, you will need to add the following lines to your
* code and comment out the create_datawriter call above.
*/
/* Start changes for coheren_presentation */
/* retcode = publisher->get_default_datawriter_qos(datawriter_qos);
if (retcode != DDS_RETCODE_OK) {
std::cerr << "get_default_datawriter_qos error\n";
return EXIT_FAILURE;
}
datawriter_qos.reliability.kind = DDS_RELIABLE_RELIABILITY_QOS;
datawriter_qos.history.depth = 10;
datawriter_qos.protocol.rtps_reliable_writer.heartbeats_per_max_samples
= 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);
}
*/ /* End changes for coherent_presentation */
coherentDataWriter *typed_writer =
coherentDataWriter::narrow(untyped_writer);
if (typed_writer == NULL) {
return shutdown_participant(
participant,
"DataWriter narrow error",
EXIT_FAILURE);
}
/* Create data sample for writing */
coherent *data = coherentTypeSupport::create_data();
if (data == NULL) {
return shutdown_participant(
participant,
"asyncTypeSupport::create_data error",
EXIT_FAILURE);
}
/* 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 */
data->id = 0;
DDS_InstanceHandle_t instance_handle =
typed_writer->register_instance(*data);
publisher->begin_coherent_changes();
std::cout << "Begin Coherent Changes\n";
/* Main loop */
for (unsigned int samples_written = 0;
!shutdown_requested && samples_written < sample_count;
++samples_written) {
NDDSUtility::sleep(send_period);
mod = samples_written % 7;
if (mod == 6) {
publisher->begin_coherent_changes();
std::cout << "Begin Coherent Changes\n";
continue;
}
// Choose a random value for each field
data->field = 'a' + mod;
data->value = (int) (rand() / (RAND_MAX / 10.0));
std::cout << " Updating instance, " << data->field << "->"
<< data->value << std::endl;
retcode = typed_writer->write(*data, instance_handle);
if (retcode != DDS_RETCODE_OK) {
std::cerr << "write error " << retcode << std::endl;
}
if (mod == 5) {
publisher->end_coherent_changes();
std::cout << "End Coherent Changes\n\n";
}
}
// Delete previously allocated async, including all contained elements
retcode = typed_writer->unregister_instance(*data, instance_handle);
if (retcode != DDS_RETCODE_OK) {
std::cerr << "unregister instance error " << retcode << std::endl;
}
/* Delete data sample */
retcode = coherentTypeSupport::delete_data(data);
if (retcode != DDS_RETCODE_OK) {
std::cerr << "coherentTypeSupport::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/coherent_presentation/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/coherent_presentation/c/coherent_subscriber.c | /*******************************************************************************
(c) 2005-2014 Copyright, Real-Time Innovations, Inc. All rights reserved.
RTI grants Licensee a license to use, modify, compile, and create derivative
works of the Software. Licensee has the right to distribute object form only
for use with RTI products. The Software is provided "as is", with no warranty
of any type, including any warranty for fitness for any purpose. RTI is under
no obligation to maintain or support the Software. RTI shall not be liable for
any incidental or consequential damages arising out of the use or inability to
use the software.
******************************************************************************/
/* coherent_subscriber.c
A subscription example
This file is derived from code automatically generated by the rtiddsgen
command:
rtiddsgen -language C -example <arch> coherent.idl
Example subscription of type coherent automatically generated by
'rtiddsgen'. To test them, follow these steps:
(1) Compile this file and the example publication.
(2) Start the subscription with the command
objs/<arch>/coherent_subscriber <domain_id> <sample_count>
(3) Start the publication with the command
objs/<arch>/coherent_publisher <domain_id> <sample_count>
(4) [Optional] Specify the list of discovery initial peers and
multicast receive addresses via an environment variable or a file
(in the current working directory) called NDDS_DISCOVERY_PEERS.
You can run any number of publishers and subscribers programs, and can
add and remove them dynamically from the domain.
Example:
To run the example application on domain <domain_id>:
On UNIX systems:
objs/<arch>/coherent_publisher <domain_id>
objs/<arch>/coherent_subscriber <domain_id>
On Windows systems:
objs\<arch>\coherent_publisher <domain_id>
objs\<arch>\coherent_subscriber <domain_id>
modification history
------------ -------
* Modify listener callback to update Object State
* Change presentation scope in subscriber QoS
* Use reliable communication (currently required for coherency QoS)
* All QoS are in the xml file
*/
#include "coherent.h"
#include "coherentSupport.h"
#include "ndds/ndds_c.h"
#include <stdio.h>
#include <stdlib.h>
/* Start changes for coherent_presentation */
#define STATENVALS 6
int statevals[STATENVALS] = { 0 };
void print_state()
{
unsigned int i;
char c = 'a';
for (i = 0; i < STATENVALS; ++i) {
printf(" %c = %d;", c++, statevals[i]);
}
}
void set_state(char c, int value)
{
unsigned int idx = c - 'a';
if (idx < 0 || idx >= STATENVALS) {
printf("error: invalid field '%c'\n", c);
return;
}
statevals[idx] = value;
}
/* End changes for coherent_presentation */
void coherentListener_on_requested_deadline_missed(
void *listener_data,
DDS_DataReader *reader,
const struct DDS_RequestedDeadlineMissedStatus *status)
{
}
void coherentListener_on_requested_incompatible_qos(
void *listener_data,
DDS_DataReader *reader,
const struct DDS_RequestedIncompatibleQosStatus *status)
{
}
void coherentListener_on_sample_rejected(
void *listener_data,
DDS_DataReader *reader,
const struct DDS_SampleRejectedStatus *status)
{
}
void coherentListener_on_liveliness_changed(
void *listener_data,
DDS_DataReader *reader,
const struct DDS_LivelinessChangedStatus *status)
{
}
void coherentListener_on_sample_lost(
void *listener_data,
DDS_DataReader *reader,
const struct DDS_SampleLostStatus *status)
{
}
void coherentListener_on_subscription_matched(
void *listener_data,
DDS_DataReader *reader,
const struct DDS_SubscriptionMatchedStatus *status)
{
}
void coherentListener_on_data_available(
void *listener_data,
DDS_DataReader *reader)
{
coherentDataReader *coherent_reader = NULL;
struct coherentSeq data_seq = DDS_SEQUENCE_INITIALIZER;
struct DDS_SampleInfoSeq info_seq = DDS_SEQUENCE_INITIALIZER;
DDS_ReturnCode_t retcode;
int i;
int len = 0;
coherent *data;
coherent_reader = coherentDataReader_narrow(reader);
if (coherent_reader == NULL) {
printf("DataReader narrow error\n");
return;
}
retcode = coherentDataReader_take(
coherent_reader,
&data_seq,
&info_seq,
DDS_LENGTH_UNLIMITED,
DDS_ANY_SAMPLE_STATE,
DDS_ANY_VIEW_STATE,
DDS_ANY_INSTANCE_STATE);
if (retcode == DDS_RETCODE_NO_DATA) {
return;
} else if (retcode != DDS_RETCODE_OK) {
printf("take error %d\n", retcode);
return;
}
/* Start changes for coherent_presentation */
/* Firstly, we process all samples */
len = 0;
for (i = 0; i < DDS_SampleInfoSeq_get_length(&info_seq); ++i) {
if (DDS_SampleInfoSeq_get_reference(&info_seq, i)->valid_data) {
data = coherentSeq_get_reference(&data_seq, i);
len++;
set_state(data->field, data->value);
}
}
/* Then, we print the results */
if (len > 0) {
printf("Received %d updates\n", len);
print_state();
printf("\n");
}
/* End changes for coherent_presentation */
retcode = coherentDataReader_return_loan(
coherent_reader,
&data_seq,
&info_seq);
if (retcode != DDS_RETCODE_OK) {
printf("return loan error %d\n", retcode);
}
}
/* Delete all entities */
static int subscriber_shutdown(
DDS_DomainParticipant *participant,
struct DDS_SubscriberQos *subscriber_qos,
struct DDS_DataReaderQos *datareader_qos)
{
DDS_ReturnCode_t retcode;
int status = 0;
if (participant != NULL) {
retcode = DDS_DomainParticipant_delete_contained_entities(participant);
if (retcode != DDS_RETCODE_OK) {
printf("delete_contained_entities error %d\n", retcode);
status = -1;
}
retcode = DDS_DomainParticipantFactory_delete_participant(
DDS_TheParticipantFactory,
participant);
if (retcode != DDS_RETCODE_OK) {
printf("delete_participant error %d\n", retcode);
status = -1;
}
}
retcode = DDS_SubscriberQos_finalize(subscriber_qos);
if (retcode != DDS_RETCODE_OK) {
printf("DDS_SubscriberQos_finalize error %d\n", retcode);
status = -1;
}
retcode = DDS_DataReaderQos_finalize(datareader_qos);
if (retcode != DDS_RETCODE_OK) {
printf("DDS_DataReaderQos_finalize error %d\n", retcode);
status = -1;
}
/* RTI Connext provides the finalize_instance() method on
domain participant factory for users who want to release memory used
by the participant factory. Uncomment the following block of code for
clean destruction of the singleton. */
/*
retcode = DDS_DomainParticipantFactory_finalize_instance();
if (retcode != DDS_RETCODE_OK) {
printf("finalize_instance error %d\n", retcode);
status = -1;
}
*/
return status;
}
static int subscriber_main(int domainId, int sample_count)
{
DDS_DomainParticipant *participant = NULL;
DDS_Subscriber *subscriber = NULL;
DDS_Topic *topic = NULL;
struct DDS_DataReaderListener reader_listener =
DDS_DataReaderListener_INITIALIZER;
DDS_DataReader *reader = NULL;
DDS_ReturnCode_t retcode;
const char *type_name = NULL;
int count = 0;
struct DDS_Duration_t poll_period = { 4, 0 };
struct DDS_SubscriberQos subscriber_qos = DDS_SubscriberQos_INITIALIZER;
struct DDS_DataReaderQos datareader_qos = DDS_DataReaderQos_INITIALIZER;
/* To customize participant QoS, use
the configuration file USER_QOS_PROFILES.xml */
participant = DDS_DomainParticipantFactory_create_participant(
DDS_TheParticipantFactory,
domainId,
&DDS_PARTICIPANT_QOS_DEFAULT,
NULL /* listener */,
DDS_STATUS_MASK_NONE);
if (participant == NULL) {
printf("create_participant error\n");
subscriber_shutdown(participant, &subscriber_qos, &datareader_qos);
return -1;
}
/* To customize subscriber QoS, use
the configuration file USER_QOS_PROFILES.xml */
subscriber = DDS_DomainParticipant_create_subscriber(
participant,
&DDS_SUBSCRIBER_QOS_DEFAULT,
NULL /* listener */,
DDS_STATUS_MASK_NONE);
if (subscriber == NULL) {
printf("create_subscriber error\n");
subscriber_shutdown(participant, &subscriber_qos, &datareader_qos);
return -1;
}
/* If you want to change the DataWriter's QoS programmatically rather than
* using the XML file, you will need to add the following lines to your
* code and comment out the create_subscriber call above.
*/
/* Start changes for coherent_presentation */
/* Get default subscriber QoS to customize */
/* retcode =
DDS_DomainParticipant_get_default_subscriber_qos(participant,
&subscriber_qos);
if (retcode != DDS_RETCODE_OK) {
printf("get_default_subscriber_qos error\n");
return -1;
}
subscriber_qos.presentation.access_scope = DDS_TOPIC_PRESENTATION_QOS;
subscriber_qos.presentation.coherent_access = DDS_BOOLEAN_TRUE;
subscriber = DDS_DomainParticipant_create_subscriber(participant,
&subscriber_qos, NULL, DDS_STATUS_MASK_NONE);
if (subscriber == NULL) {
printf("create_subscriber error\n");
subscriber_shutdown(participant, &subscriber_qos, &datareader_qos);
return -1;
}
*/ /* End changes for coherent_presentation */
/* Register the type before creating the topic */
type_name = coherentTypeSupport_get_type_name();
retcode = coherentTypeSupport_register_type(participant, type_name);
if (retcode != DDS_RETCODE_OK) {
printf("register_type error %d\n", retcode);
subscriber_shutdown(participant, &subscriber_qos, &datareader_qos);
return -1;
}
/* To customize topic QoS, use
the configuration file USER_QOS_PROFILES.xml */
topic = DDS_DomainParticipant_create_topic(
participant,
"Example coherent",
type_name,
&DDS_TOPIC_QOS_DEFAULT,
NULL /* listener */,
DDS_STATUS_MASK_NONE);
if (topic == NULL) {
printf("create_topic error\n");
subscriber_shutdown(participant, &subscriber_qos, &datareader_qos);
return -1;
}
/* Set up a data reader listener */
reader_listener.on_requested_deadline_missed =
coherentListener_on_requested_deadline_missed;
reader_listener.on_requested_incompatible_qos =
coherentListener_on_requested_incompatible_qos;
reader_listener.on_sample_rejected = coherentListener_on_sample_rejected;
reader_listener.on_liveliness_changed =
coherentListener_on_liveliness_changed;
reader_listener.on_sample_lost = coherentListener_on_sample_lost;
reader_listener.on_subscription_matched =
coherentListener_on_subscription_matched;
reader_listener.on_data_available = coherentListener_on_data_available;
/* To customize data reader QoS, use
the configuration file USER_QOS_PROFILES.xml */
reader = DDS_Subscriber_create_datareader(
subscriber,
DDS_Topic_as_topicdescription(topic),
&DDS_DATAREADER_QOS_DEFAULT,
&reader_listener,
DDS_STATUS_MASK_ALL);
if (reader == NULL) {
printf("create_datareader error\n");
subscriber_shutdown(participant, &subscriber_qos, &datareader_qos);
return -1;
}
/* If you want to change the DataWriter's QoS programmatically rather than
* using the XML file, you will need to add the following lines to your
* code and comment out the create_datareader call above.
*/
/* Start changes for coherent_presentation */
/* Get default datareader QoS to customize */
/* retcode = DDS_Subscriber_get_default_datareader_qos(subscriber,
&datareader_qos);
if (retcode != DDS_RETCODE_OK) {
printf("get_default_datareader_qos error\n");
return -1;
}
datareader_qos.reliability.kind = DDS_RELIABLE_RELIABILITY_QOS;
datareader_qos.history.depth = 10;
reader = DDS_Subscriber_create_datareader(subscriber,
DDS_Topic_as_topicdescription(topic), &datareader_qos,
&reader_listener, DDS_STATUS_MASK_ALL);
if (reader == NULL) {
printf("create_datareader error\n");
subscriber_shutdown(participant, &subscriber_qos, &datareader_qos);
return -1;
}
*/ /* End changes for coherent_presentation */
/* Main loop */
for (count = 0; (sample_count == 0) || (count < sample_count); ++count) {
NDDS_Utility_sleep(&poll_period);
}
/* Cleanup and delete all entities */
return subscriber_shutdown(participant, &subscriber_qos, &datareader_qos);
}
#if defined(RTI_WINCE)
int wmain(int argc, wchar_t **argv)
{
int domainId = 0;
int sample_count = 0; /* infinite loop */
if (argc >= 2) {
domainId = _wtoi(argv[1]);
}
if (argc >= 3) {
sample_count = _wtoi(argv[2]);
}
/* Uncomment this to turn on additional logging
NDDS_Config_Logger_set_verbosity_by_category(
NDDS_Config_Logger_get_instance(),
NDDS_CONFIG_LOG_CATEGORY_API,
NDDS_CONFIG_LOG_VERBOSITY_STATUS_ALL);
*/
return subscriber_main(domainId, sample_count);
}
#elif !(defined(RTI_VXWORKS) && !defined(__RTP__)) && !defined(RTI_PSOS)
int main(int argc, char *argv[])
{
int domainId = 0;
int sample_count = 0; /* infinite loop */
if (argc >= 2) {
domainId = atoi(argv[1]);
}
if (argc >= 3) {
sample_count = atoi(argv[2]);
}
/* Uncomment this to turn on additional logging
NDDS_Config_Logger_set_verbosity_by_category(
NDDS_Config_Logger_get_instance(),
NDDS_CONFIG_LOG_CATEGORY_API,
NDDS_CONFIG_LOG_VERBOSITY_STATUS_ALL);
*/
return subscriber_main(domainId, sample_count);
}
#endif
#ifdef RTI_VX653
const unsigned char *__ctype = NULL;
void usrAppInit()
{
#ifdef USER_APPL_INIT
USER_APPL_INIT; /* for backwards compatibility */
#endif
/* add application specific code here */
taskSpawn(
"sub",
RTI_OSAPI_THREAD_PRIORITY_NORMAL,
0x8,
0x150000,
(FUNCPTR) subscriber_main,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0);
}
#endif
| c |
rticonnextdds-examples | data/projects/rticonnextdds-examples/connext_dds/coherent_presentation/c/coherent_publisher.c | /*******************************************************************************
(c) 2005-2014 Copyright, Real-Time Innovations, Inc. All rights reserved.
RTI grants Licensee a license to use, modify, compile, and create derivative
works of the Software. Licensee has the right to distribute object form only
for use with RTI products. The Software is provided "as is", with no warranty
of any type, including any warranty for fitness for any purpose. RTI is under
no obligation to maintain or support the Software. RTI shall not be liable for
any incidental or consequential damages arising out of the use or inability to
use the software.
******************************************************************************/
/* coherent_publisher.c
A publication of data of type coherent
This file is derived from code automatically generated by the rtiddsgen
command:
rtiddsgen -language C -example <arch> coherent.idl
Example publication of type coherent automatically generated by
'rtiddsgen'. To test them follow these steps:
(1) Compile this file and the example subscription.
(2) Start the subscription with the command
objs/<arch>/coherent_subscriber <domain_id> <sample_count>
(3) Start the publication with the command
objs/<arch>/coherent_publisher <domain_id> <sample_count>
(4) [Optional] Specify the list of discovery initial peers and
multicast receive addresses via an environment variable or a file
(in the current working directory) called NDDS_DISCOVERY_PEERS.
You can run any number of publishers and subscribers programs, and can
add and remove them dynamically from the domain.
Example:
To run the example application on domain <domain_id>:
On Unix:
objs/<arch>/coherent_publisher <domain_id>
objs/<arch>/coherent_subscriber <domain_id>
On Windows:
objs\<arch>\coherent_publisher <domain_id>
objs\<arch>\coherent_subscriber <domain_id>
modification history
------------ -------
* Change presentation scope in publisher QoS
* Use reliable communication (currently required for coherency QoS)
* Surround coherent changes with calls to {begin, end}_coherent_changes
* All QoS are in the xml file
*/
#include "coherent.h"
#include "coherentSupport.h"
#include "ndds/ndds_c.h"
#include <stdio.h>
#include <stdlib.h>
/* Delete all entities */
static int publisher_shutdown(
DDS_DomainParticipant *participant,
struct DDS_PublisherQos *publisher_qos,
struct DDS_DataWriterQos *datawriter_qos)
{
DDS_ReturnCode_t retcode;
int status = 0;
if (participant != NULL) {
retcode = DDS_DomainParticipant_delete_contained_entities(participant);
if (retcode != DDS_RETCODE_OK) {
printf("delete_contained_entities error %d\n", retcode);
status = -1;
}
retcode = DDS_DomainParticipantFactory_delete_participant(
DDS_TheParticipantFactory,
participant);
if (retcode != DDS_RETCODE_OK) {
printf("delete_participant error %d\n", retcode);
status = -1;
}
}
retcode = DDS_PublisherQos_finalize(publisher_qos);
if (retcode != DDS_RETCODE_OK) {
printf("PublisherQos_finalize error %d\n", retcode);
status = -1;
}
retcode = DDS_DataWriterQos_finalize(datawriter_qos);
if (retcode != DDS_RETCODE_OK) {
printf("DataWriterQos_finalize error %d\n", retcode);
status = -1;
}
/* RTI Connext provides finalize_instance() method on
domain participant factory for people who want to release memory used
by the participant factory. Uncomment the following block of code for
clean destruction of the singleton. */
/*
retcode = DDS_DomainParticipantFactory_finalize_instance();
if (retcode != DDS_RETCODE_OK) {
printf("finalize_instance error %d\n", retcode);
status = -1;
}
*/
return status;
}
static int publisher_main(int domainId, int sample_count)
{
DDS_DomainParticipant *participant = NULL;
DDS_Publisher *publisher = NULL;
DDS_Topic *topic = NULL;
DDS_DataWriter *writer = NULL;
coherentDataWriter *coherent_writer = NULL;
coherent *instance = NULL;
DDS_ReturnCode_t retcode;
DDS_InstanceHandle_t instance_handle = DDS_HANDLE_NIL;
const char *type_name = NULL;
int count = 0;
struct DDS_Duration_t send_period = { 1, 0 };
struct DDS_PublisherQos publisher_qos = DDS_PublisherQos_INITIALIZER;
struct DDS_DataWriterQos datawriter_qos = DDS_DataWriterQos_INITIALIZER;
int mod = 0;
/* To customize participant QoS, use
the configuration file USER_QOS_PROFILES.xml */
participant = DDS_DomainParticipantFactory_create_participant(
DDS_TheParticipantFactory,
domainId,
&DDS_PARTICIPANT_QOS_DEFAULT,
NULL /* listener */,
DDS_STATUS_MASK_NONE);
if (participant == NULL) {
printf("create_participant error\n");
publisher_shutdown(participant, &publisher_qos, &datawriter_qos);
return -1;
}
/* To customize publisher QoS, use
the configuration file USER_QOS_PROFILES.xml */
publisher = DDS_DomainParticipant_create_publisher(
participant,
&DDS_PUBLISHER_QOS_DEFAULT,
NULL /* listener */,
DDS_STATUS_MASK_NONE);
if (publisher == NULL) {
printf("create_publisher error\n");
publisher_shutdown(participant, &publisher_qos, &datawriter_qos);
return -1;
}
/* If you want to change the DataWriter's QoS programmatically rather than
* using the XML file, you will need to add the following lines to your
* code and comment out the create_publisher call above.
*/
/* Start changes for coherent_presentation */
/* Get default publisher QoS to customize */
/* retcode = DDS_DomainParticipant_get_default_publisher_qos(participant,
&publisher_qos);
if (retcode != DDS_RETCODE_OK) {
printf("get_default_publisher_qos error\n");
return -1;
}
*/ /* Topic access scope means that writes from a particular datawriter to
* multiple instances will be viewed coherently.
*/
/* publisher_qos.presentation.access_scope = DDS_TOPIC_PRESENTATION_QOS;
publisher_qos.presentation.coherent_access = DDS_BOOLEAN_TRUE;
*/ /* To customize publisher QoS, use
the configuration file USER_QOS_PROFILES.xml */
/* publisher = DDS_DomainParticipant_create_publisher(participant,
&publisher_qos, NULL, DDS_STATUS_MASK_NONE);
if (publisher == NULL) {
printf("create_publisher error\n");
publisher_shutdown(participant, &publisher_qos, &datawriter_qos);
return -1;
}
*/ /* End changes for coherent_presentation */
/* Register type before creating topic */
type_name = coherentTypeSupport_get_type_name();
retcode = coherentTypeSupport_register_type(participant, type_name);
if (retcode != DDS_RETCODE_OK) {
printf("register_type error %d\n", retcode);
publisher_shutdown(participant, &publisher_qos, &datawriter_qos);
return -1;
}
/* To customize topic QoS, use
the configuration file USER_QOS_PROFILES.xml */
topic = DDS_DomainParticipant_create_topic(
participant,
"Example coherent",
type_name,
&DDS_TOPIC_QOS_DEFAULT,
NULL /* listener */,
DDS_STATUS_MASK_NONE);
if (topic == NULL) {
printf("create_topic error\n");
publisher_shutdown(participant, &publisher_qos, &datawriter_qos);
return -1;
}
writer = DDS_Publisher_create_datawriter(
publisher,
topic,
&DDS_DATAWRITER_QOS_DEFAULT,
NULL /* listener */,
DDS_STATUS_MASK_NONE);
if (writer == NULL) {
printf("create_datawriter error\n");
publisher_shutdown(participant, &publisher_qos, &datawriter_qos);
return -1;
}
/* If you want to change the DataWriter's QoS programmatically rather than
* using the XML file, you will need to add the following lines to your
* code and comment out the create_datawriter call above.
*/
/* Start changes for coherent_presentation */
/* Get default datawriter QoS to customize */
/* retcode = DDS_Publisher_get_default_datawriter_qos(publisher,
&datawriter_qos);
if (retcode != DDS_RETCODE_OK) {
printf("get_default_datawriter_qos error\n");
return -1;
}
datawriter_qos.reliability.kind = DDS_RELIABLE_RELIABILITY_QOS;
datawriter_qos.history.kind = DDS_KEEP_ALL_HISTORY_QOS;
datawriter_qos.protocol.rtps_reliable_writer.heartbeats_per_max_samples
= 0;
*/ /* To customize data writer QoS, use
the configuration file USER_QOS_PROFILES.xml */
/* writer = DDS_Publisher_create_datawriter(publisher, topic,
&datawriter_qos, NULL, DDS_STATUS_MASK_NONE);
if (writer == NULL) {
printf("create_datawriter error\n");
publisher_shutdown(participant, &publisher_qos, &datawriter_qos);
return -1;
}
*/ /* End changes for coherent_presentation */
coherent_writer = coherentDataWriter_narrow(writer);
if (coherent_writer == NULL) {
printf("DataWriter narrow error\n");
publisher_shutdown(participant, &publisher_qos, &datawriter_qos);
return -1;
}
/* Create data sample for writing */
instance = coherentTypeSupport_create_data_ex(DDS_BOOLEAN_TRUE);
if (instance == NULL) {
printf("coherentTypeSupport_create_data error\n");
publisher_shutdown(participant, &publisher_qos, &datawriter_qos);
return -1;
}
/* Start changes for coherent_presentation */
/* For a data type that has a key, if the same instance is going to be
written multiple times, initialize the key here
and register the keyed instance prior to writing */
instance->id = 0;
instance_handle =
coherentDataWriter_register_instance(coherent_writer, instance);
DDS_Publisher_begin_coherent_changes(publisher);
printf("Begin Coherent Changes\n");
/* Main loop */
for (count = 0; (sample_count == 0) || (count < sample_count); ++count) {
NDDS_Utility_sleep(&send_period);
mod = count % 7;
if (mod == 6) {
DDS_Publisher_begin_coherent_changes(publisher);
printf("Begin Coherent Changes\n");
continue;
}
/* Choose a random value for each field */
instance->field = 'a' + mod;
instance->value = (int) (rand() / (RAND_MAX / 10.0));
printf(" Updating instance, %c->%d\n",
instance->field,
instance->value);
/* Write data */
retcode = coherentDataWriter_write(
coherent_writer,
instance,
&instance_handle);
if (retcode != DDS_RETCODE_OK) {
printf("write error %d\n", retcode);
}
/* Begin a new change group after sending 6 samples */
if (mod == 5) {
DDS_Publisher_end_coherent_changes(publisher);
printf("End Coherent Changes\n\n");
}
}
retcode = coherentDataWriter_unregister_instance(
coherent_writer,
instance,
&instance_handle);
if (retcode != DDS_RETCODE_OK) {
printf("unregister instance error %d\n", retcode);
}
/* Delete data sample */
retcode = coherentTypeSupport_delete_data_ex(instance, DDS_BOOLEAN_TRUE);
if (retcode != DDS_RETCODE_OK) {
printf("coherentTypeSupport_delete_data error %d\n", retcode);
}
/* End changes for coherent_presentation */
/* Cleanup and delete delete all entities */
return publisher_shutdown(participant, &publisher_qos, &datawriter_qos);
}
#if defined(RTI_WINCE)
int wmain(int argc, wchar_t **argv)
{
int domainId = 0;
int sample_count = 0; /* infinite loop */
if (argc >= 2) {
domainId = _wtoi(argv[1]);
}
if (argc >= 3) {
sample_count = _wtoi(argv[2]);
}
/* Uncomment this to turn on additional logging
NDDS_Config_Logger_set_verbosity_by_category(
NDDS_Config_Logger_get_instance(),
NDDS_CONFIG_LOG_CATEGORY_API,
NDDS_CONFIG_LOG_VERBOSITY_STATUS_ALL);
*/
return publisher_main(domainId, sample_count);
}
#elif !(defined(RTI_VXWORKS) && !defined(__RTP__)) && !defined(RTI_PSOS)
int main(int argc, char *argv[])
{
int domainId = 0;
int sample_count = 0; /* infinite loop */
if (argc >= 2) {
domainId = atoi(argv[1]);
}
if (argc >= 3) {
sample_count = atoi(argv[2]);
}
/* Uncomment this to turn on additional logging
NDDS_Config_Logger_set_verbosity_by_category(
NDDS_Config_Logger_get_instance(),
NDDS_CONFIG_LOG_CATEGORY_API,
NDDS_CONFIG_LOG_VERBOSITY_STATUS_ALL);
*/
return publisher_main(domainId, sample_count);
}
#endif
#ifdef RTI_VX653
const unsigned char *__ctype = NULL;
void usrAppInit()
{
#ifdef USER_APPL_INIT
USER_APPL_INIT; /* for backwards compatibility */
#endif
/* add application specific code here */
taskSpawn(
"pub",
RTI_OSAPI_THREAD_PRIORITY_NORMAL,
0x8,
0x150000,
(FUNCPTR) publisher_main,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0);
}
#endif
| c |
rticonnextdds-examples | data/projects/rticonnextdds-examples/connext_dds/coherent_presentation/c++03/coherent_subscriber.cxx | /*******************************************************************************
(c) 2005-2015 Copyright, Real-Time Innovations, Inc. All rights reserved.
RTI grants Licensee a license to use, modify, compile, and create derivative
works of the Software. Licensee has the right to distribute object form only
for use with RTI products. The Software is provided "as is", with no warranty
of any type, including any warranty for fitness for any purpose. RTI is under
no obligation to maintain or support the Software. RTI shall not be liable for
any incidental or consequential damages arising out of the use or inability to
use the software.
******************************************************************************/
#include <cstdlib>
#include <iostream>
#include "coherent.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;
using namespace rti::sub;
// Transform a DDS sample into a pair value for a dictionary.
std::pair<char, int> sample2map(const coherent &data)
{
return std::make_pair(data.field(), data.value());
}
class CoherentListener : public NoOpDataReaderListener<coherent> {
public:
void on_data_available(DataReader<coherent> &reader)
{
// Take all samples
LoanedSamples<coherent> samples = reader.take();
// Process samples and add to a dictionary
std::map<char, int> values;
std::transform(
rti::sub::valid_samples(samples.begin()),
rti::sub::valid_samples(samples.end()),
std::inserter(values, values.begin()),
sample2map);
std::cout << std::endl;
// Print result
std::cout << "Received updates:" << std::endl;
typedef std::map<char, int>::const_iterator MapIterator;
for (MapIterator iter = values.begin(); iter != values.end(); iter++) {
std::cout << " " << iter->first << " = " << iter->second << ";";
}
std::cout << std::endl;
}
};
void subscriber_main(int domain_id, int sample_count)
{
// Create a participant with default QoS.
DomainParticipant participant(domain_id);
// Retrieve the default Subscriber QoS, from USER_QOS_PROFILES.xml
SubscriberQos subscriber_qos = QosProvider::Default().subscriber_qos();
// If you want to change the Subscriber QoS programmatically rather
// than using the XML file, you will need to comment out these lines.
// subscriber_qos << Presentation::TopicAccessScope(true, false);
// Create a subscriber.
Subscriber subscriber(participant, subscriber_qos);
// Create a Topic -- and automatically register the type.
Topic<coherent> topic(participant, "Example coherent");
// Retrieve the default DataReader QoS, from USER_QOS_PROFILES.xml
DataReaderQos reader_qos = QosProvider::Default().datareader_qos();
// If you want to change the Subscriber QoS programmatically rather
// than using the XML file, you will need to comment out these lines.
// reader_qos << Reliability::Reliable()
// << History::KeepLast(10);
// Create a DataReader.
DataReader<coherent> reader(subscriber, topic, reader_qos);
// Create a DataReader listener using ListenerBinder, a RAII utility that
// will take care of reseting it from the reader and deleting it.
ListenerBinder<DataReader<coherent> > scoped_listener =
bind_and_manage_listener(
reader,
new CoherentListener,
StatusMask::data_available());
// Main loop
for (int count = 0; (sample_count == 0) || (count < sample_count);
count++) {
rti::util::sleep(Duration(1));
}
}
int main(int argc, char *argv[])
{
int domain_id = 0;
int sample_count = 0; // Infinite loop
if (argc >= 2) {
domain_id = atoi(argv[1]);
}
if (argc >= 3) {
sample_count = atoi(argv[2]);
}
// To turn on additional logging, include <rti/config/Logger.hpp> and
// uncomment the following line:
// rti::config::Logger::instance().verbosity(rti::config::Verbosity::STATUS_ALL);
try {
subscriber_main(domain_id, sample_count);
} catch (std::exception ex) {
std::cout << "Exception caught: " << ex.what() << std::endl;
return -1;
}
return 0;
}
| cxx |
rticonnextdds-examples | data/projects/rticonnextdds-examples/connext_dds/coherent_presentation/c++03/coherent_publisher.cxx | /*******************************************************************************
(c) 2005-2015 Copyright, Real-Time Innovations, Inc. All rights reserved.
RTI grants Licensee a license to use, modify, compile, and create derivative
works of the Software. Licensee has the right to distribute object form only
for use with RTI products. The Software is provided "as is", with no warranty
of any type, including any warranty for fitness for any purpose. RTI is under
no obligation to maintain or support the Software. RTI shall not be liable for
any incidental or consequential damages arising out of the use or inability to
use the software.
******************************************************************************/
#include <cstdlib>
#include <iostream>
#include "coherent.hpp"
#include <dds/dds.hpp>
using namespace dds::core;
using namespace dds::core::policy;
using namespace rti::core::policy;
using namespace dds::domain;
using namespace dds::topic;
using namespace dds::pub;
using namespace dds::pub::qos;
void publisher_main(int domain_id, int sample_count)
{
// Create a DomainParticipant with default Qos
DomainParticipant participant(domain_id);
// Create a Topic -- and automatically register the type
Topic<coherent> topic(participant, "Example coherent");
// Retrieve the Publisher QoS, from USER_QOS_PROFILES.xml.
PublisherQos publisher_qos = QosProvider::Default().publisher_qos();
// If you want to change the Publisher's QoS programmatically rather
// than using the XML file, you will need to uncomment the following lines.
// publisher_qos << Presentation::TopicAccessScope(true, false);
Publisher publisher(participant, publisher_qos);
// Retrieve the DataWriter QoS, from USER_QOS_PROFILES.xml.
DataWriterQos writer_qos = QosProvider::Default().datawriter_qos();
// If you want to change the DataWriter's QoS programmatically rather
// than using the XML file, you will need to uncomment the following lines.
// writer_qos << Reliability::Reliable()
// << History::KeepLast(10)
// << DataWriterProtocol().rtps_reliable_writer(
// RtpsReliableWriterProtocol().heartbeats_per_max_samples(0));
// Create a DataWriter with default Qos
DataWriter<coherent> writer(publisher, topic, writer_qos);
coherent sample;
sample.id(0);
InstanceHandle handle = writer.register_instance(sample);
int num_samples = 7;
for (int count = 0; count < sample_count || sample_count == 0;) {
CoherentSet coherent_set(publisher);
std::cout << "Begin Coherent Changes" << std::endl;
for (int i = 0; i < num_samples; i++, count++) {
rti::util::sleep(Duration(1));
sample.field('a' + i);
sample.value((int) (rand() / (RAND_MAX / 10.0)));
std::cout << "\tUpdating instance, " << sample.field() << "->"
<< sample.value() << std::endl;
writer.write(sample, handle);
}
// `coherent_set.end()` will be called by the destructor.
std::cout << "End Coherent Changes" << std::endl << std::endl;
}
writer.unregister_instance(handle);
}
int main(int argc, char *argv[])
{
int domain_id = 0;
int sample_count = 0; // Infinite loop
if (argc >= 2) {
domain_id = atoi(argv[1]);
}
if (argc >= 3) {
sample_count = atoi(argv[2]);
}
// To turn on additional logging, include <rti/config/Logger.hpp> and
// uncomment the following line:
// rti::config::Logger::instance().verbosity(rti::config::Verbosity::STATUS_ALL);
try {
publisher_main(domain_id, sample_count);
} catch (const std::exception &ex) {
// This will catch DDS exceptions
std::cerr << "Exception in publisher_main(): " << ex.what()
<< std::endl;
return -1;
}
return 0;
}
| cxx |
rticonnextdds-examples | data/projects/rticonnextdds-examples/connext_dds/coherent_presentation/c++11/application.hpp | /*
* (c) Copyright, Real-Time Innovations, 2020. All rights reserved.
* RTI grants Licensee a license to use, modify, compile, and create derivative
* works of the software solely for use with RTI Connext DDS. Licensee may
* redistribute copies of the software provided that all such copies are subject
* to this license. The software is provided "as is", with no warranty of any
* type, including any warranty for fitness for any purpose. RTI is under no
* obligation to maintain or support the software. RTI shall not be liable for
* any incidental or consequential damages arising out of the use or inability
* to use the software.
*/
#ifndef APPLICATION_HPP
#define APPLICATION_HPP
#include <iostream>
#include <csignal>
#include <dds/core/ddscore.hpp>
namespace application {
// Catch control-C and tell application to shut down
bool shutdown_requested = false;
inline void stop_handler(int)
{
shutdown_requested = true;
std::cout << "preparing to shut down..." << std::endl;
}
inline void setup_signal_handlers()
{
signal(SIGINT, stop_handler);
signal(SIGTERM, stop_handler);
}
enum class ParseReturn { ok, failure, exit };
struct ApplicationArguments {
ParseReturn parse_result;
unsigned int domain_id;
unsigned int 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/coherent_presentation/c++11/coherent_subscriber.cxx | /*******************************************************************************
(c) 2005-2015 Copyright, Real-Time Innovations, Inc. All rights reserved.
RTI grants Licensee a license to use, modify, compile, and create derivative
works of the Software. Licensee has the right to distribute object form only
for use with RTI products. The Software is provided "as is", with no warranty
of any type, including any warranty for fitness for any purpose. RTI is under
no obligation to maintain or support the Software. RTI shall not be liable for
any incidental or consequential damages arising out of the use or inability to
use the software.
******************************************************************************/
#include <dds/sub/ddssub.hpp>
#include <dds/core/ddscore.hpp>
#include <rti/config/Logger.hpp> // for logging
#include "coherent.hpp"
#include "application.hpp" // for command line parsing and ctrl-c
int process_data(dds::sub::DataReader<coherent> reader)
{
int count = 0;
// Take all samples
dds::sub::LoanedSamples<coherent> samples = reader.take();
// Process samples and add to a dictionary
std::map<char, int> values;
std::transform(
rti::sub::valid_samples(samples.begin()),
rti::sub::valid_samples(samples.end()),
std::inserter(values, values.begin()),
[](const coherent &data) {
return std::make_pair(data.field(), data.value());
});
std::cout << std::endl;
// Print result
std::cout << "Received updates:" << std::endl;
for (const auto &value : values) {
count++;
std::cout << " " << value.first << " = " << value.second << ";";
}
std::cout << 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();
// If you want to change the Subscriber QoS programmatically rather
// than using the XML file, you will need to comment out these lines.
// subscriber_qos << Presentation::TopicAccessScope(true, false);
// Create a subscriber.
dds::sub::Subscriber subscriber(participant, subscriber_qos);
// Create a Topic -- and automatically register the type.
dds::topic::Topic<coherent> topic(participant, "Example coherent");
// 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::KeepLast(10);
// Create a DataReader.
dds::sub::DataReader<coherent> 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::any(),
[reader, &samples_read]() {
samples_read += process_data(reader);
});
waitset += read_condition;
// Main loop
while (!application::shutdown_requested && samples_read < sample_count) {
std::cout << "async subscriber sleeping up to 1 sec..." << std::endl;
// Wait for data and report if it does not arrive in 1 second
waitset.dispatch(dds::core::Duration(1));
}
}
int main(int argc, char *argv[])
{
using namespace application;
// Parse arguments and handle control-C
auto arguments = parse_arguments(argc, argv);
if (arguments.parse_result == ParseReturn::exit) {
return EXIT_SUCCESS;
} else if (arguments.parse_result == ParseReturn::failure) {
return EXIT_FAILURE;
}
setup_signal_handlers();
// Sets Connext verbosity to help debugging
rti::config::Logger::instance().verbosity(arguments.verbosity);
try {
run_subscriber_application(arguments.domain_id, arguments.sample_count);
} catch (const std::exception &ex) {
// This will catch DDS exceptions
std::cerr << "Exception in run_subscriber_application(): " << ex.what()
<< std::endl;
return EXIT_FAILURE;
}
// Releases the memory used by the participant factory. Optional at
// application exit
dds::domain::DomainParticipant::finalize_participant_factory();
return EXIT_SUCCESS;
}
| cxx |
rticonnextdds-examples | data/projects/rticonnextdds-examples/connext_dds/coherent_presentation/c++11/coherent_publisher.cxx | /*******************************************************************************
(c) 2005-2015 Copyright, Real-Time Innovations, Inc. All rights reserved.
RTI grants Licensee a license to use, modify, compile, and create derivative
works of the Software. Licensee has the right to distribute object form only
for use with RTI products. The Software is provided "as is", with no warranty
of any type, including any warranty for fitness for any purpose. RTI is under
no obligation to maintain or support the Software. RTI shall not be liable for
any incidental or consequential damages arising out of the use or inability to
use the software.
******************************************************************************/
#include <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 "coherent.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<coherent> topic(participant, "Example coherent");
// Retrieve the Publisher QoS, from USER_QOS_PROFILES.xml.
dds::pub::qos::PublisherQos publisher_qos =
dds::core::QosProvider::Default().publisher_qos();
// If you want to change the Publisher's QoS programmatically rather
// than using the XML file, you will need to uncomment the following lines.
// publisher_qos << Presentation::TopicAccessScope(true, false);
dds::pub::Publisher publisher(participant, publisher_qos);
// Retrieve the DataWriter QoS, from USER_QOS_PROFILES.xml.
dds::pub::qos::DataWriterQos writer_qos =
dds::core::QosProvider::Default().datawriter_qos();
// If you want to change the DataWriter's QoS programmatically rather
// than using the XML file, you will need to uncomment the following lines.
// writer_qos << Reliability::Reliable()
// << History::KeepLast(10)
// << DataWriterProtocol().rtps_reliable_writer(
// RtpsReliableWriterProtocol().heartbeats_per_max_samples(0));
// Create a DataWriter with default Qos
dds::pub::DataWriter<coherent> writer(publisher, topic, writer_qos);
coherent sample;
sample.id(0);
dds::core::InstanceHandle handle = writer.register_instance(sample);
int num_samples = 7;
for (unsigned int count = 0;
!application::shutdown_requested && count < sample_count;) {
dds::pub::CoherentSet coherent_set(publisher);
std::cout << "Begin Coherent Changes" << std::endl;
for (int i = 0; i < num_samples; i++, count++) {
rti::util::sleep(dds::core::Duration(1));
sample.field('a' + i);
sample.value((int) (rand() / (RAND_MAX / 10.0)));
std::cout << "\tUpdating instance, " << sample.field() << "->"
<< sample.value() << std::endl;
writer.write(sample, handle);
}
// `coherent_set.end()` will be called by the destructor.
std::cout << "End Coherent Changes" << std::endl << std::endl;
}
writer.unregister_instance(handle);
}
int main(int argc, char *argv[])
{
using namespace application;
// Parse arguments and handle control-C
auto arguments = parse_arguments(argc, argv);
if (arguments.parse_result == ParseReturn::exit) {
return EXIT_SUCCESS;
} else if (arguments.parse_result == ParseReturn::failure) {
return EXIT_FAILURE;
}
setup_signal_handlers();
// Sets Connext verbosity to help debugging
rti::config::Logger::instance().verbosity(arguments.verbosity);
try {
run_publisher_application(arguments.domain_id, arguments.sample_count);
} catch (const std::exception &ex) {
// This will catch DDS exceptions
std::cerr << "Exception in run_publisher_application(): " << ex.what()
<< std::endl;
return EXIT_FAILURE;
}
// Releases the memory used by the participant factory. Optional at
// application exit
dds::domain::DomainParticipant::finalize_participant_factory();
return EXIT_SUCCESS;
}
| cxx |
rticonnextdds-examples | data/projects/rticonnextdds-examples/connext_dds/keyed_data_advanced/c++/keys_publisher.cxx | /*******************************************************************************
(c) 2005-2014 Copyright, Real-Time Innovations, Inc. All rights reserved.
RTI grants Licensee a license to use, modify, compile, and create derivative
works of the Software. Licensee has the right to distribute object form only
for use with RTI products. The Software is provided "as is", with no warranty
of any type, including any warranty for fitness for any purpose. RTI is under
no obligation to maintain or support the Software. RTI shall not be liable for
any incidental or consequential damages arising out of the use or inability to
use the software.
******************************************************************************/
/* keys_publisher.cxx
A publication of data of type keys
This file is derived from code automatically generated by the rtiddsgen
command:
rtiddsgen -language C++ -example <arch> keys.idl
Example publication of type keys automatically generated by
'rtiddsgen'. To test them follow these steps:
(1) Compile this file and the example subscription.
(2) Start the subscription with the command
objs/<arch>/keys_subscriber <domain_id> <sample_count>
(3) Start the publication with the command
objs/<arch>/keys_publisher <domain_id> <sample_count>
(4) [Optional] Specify the list of discovery initial peers and
multicast receive addresses via an environment variable or a file
(in the current working directory) called NDDS_DISCOVERY_PEERS.
You can run any number of publishers and subscribers programs, and can
add and remove them dynamically from the domain.
Example:
To run the example application on domain <domain_id>:
On Unix:
objs/<arch>/keys_publisher <domain_id> o
objs/<arch>/keys_subscriber <domain_id>
On Windows:
objs\<arch>\keys_publisher <domain_id>
objs\<arch>\keys_subscriber <domain_id>
modification history
------------ -------
*/
#include <stdio.h>
#include <stdlib.h>
#ifdef RTI_VX653
#include <vThreadsData.h>
#endif
#include "keys.h"
#include "keysSupport.h"
#include "ndds/ndds_cpp.h"
/* Delete all entities */
static int publisher_shutdown(DDSDomainParticipant *participant)
{
DDS_ReturnCode_t retcode;
int status = 0;
if (participant != NULL) {
retcode = participant->delete_contained_entities();
if (retcode != DDS_RETCODE_OK) {
printf("delete_contained_entities error %d\n", retcode);
status = -1;
}
retcode = DDSTheParticipantFactory->delete_participant(participant);
if (retcode != DDS_RETCODE_OK) {
printf("delete_participant error %d\n", retcode);
status = -1;
}
}
/* RTI Connext provides finalize_instance() method on
domain participant factory for people who want to release memory used
by the participant factory. Uncomment the following block of code for
clean destruction of the singleton. */
/*
retcode = DDSDomainParticipantFactory::finalize_instance();
if (retcode != DDS_RETCODE_OK) {
printf("finalize_instance error %d\n", retcode);
status = -1;
}
*/
return status;
}
extern "C" int publisher_main(int domainId, int sample_count)
{
DDSDomainParticipant *participant = NULL;
DDSPublisher *publisher = NULL;
DDSTopic *topic = NULL;
DDSDataWriter *writer = NULL;
keysDataWriter *keys_writer = NULL;
DDSDataWriter *writer2 = NULL;
keysDataWriter *keys_writer2 = NULL;
/* Creates three instances */
keys *instance[3] = { NULL, NULL, NULL };
/* Creates three handles for managing the registrations */
DDS_InstanceHandle_t handle[3] = { DDS_HANDLE_NIL,
DDS_HANDLE_NIL,
DDS_HANDLE_NIL };
/* We only will send data over the instances marked as active */
int active[3] = { 1, 0, 0 };
DDS_ReturnCode_t retcode;
const char *type_name = NULL;
int count = 0;
DDS_Duration_t send_period = { 1, 0 };
/* To customize participant QoS, use
the configuration file USER_QOS_PROFILES.xml */
participant = DDSTheParticipantFactory->create_participant(
domainId,
DDS_PARTICIPANT_QOS_DEFAULT,
NULL /* listener */,
DDS_STATUS_MASK_NONE);
if (participant == NULL) {
printf("create_participant error\n");
publisher_shutdown(participant);
return -1;
}
/* To customize publisher QoS, use
the configuration file USER_QOS_PROFILES.xml */
publisher = participant->create_publisher(
DDS_PUBLISHER_QOS_DEFAULT,
NULL /* listener */,
DDS_STATUS_MASK_NONE);
if (publisher == NULL) {
printf("create_publisher error\n");
publisher_shutdown(participant);
return -1;
}
/* Register type before creating topic */
type_name = keysTypeSupport::get_type_name();
retcode = keysTypeSupport::register_type(participant, type_name);
if (retcode != DDS_RETCODE_OK) {
printf("register_type error %d\n", retcode);
publisher_shutdown(participant);
return -1;
}
/* To customize topic QoS, use
the configuration file USER_QOS_PROFILES.xml */
topic = participant->create_topic(
"Example keys",
type_name,
DDS_TOPIC_QOS_DEFAULT,
NULL /* listener */,
DDS_STATUS_MASK_NONE);
if (topic == NULL) {
printf("create_topic error\n");
publisher_shutdown(participant);
return -1;
}
/* We are going to load different QoS profiles for the two DWs */
DDS_DataWriterQos datawriter_qos;
/* To customize data writer QoS, use
the configuration file USER_QOS_PROFILES.xml */
writer = publisher->create_datawriter(
topic,
DDS_DATAWRITER_QOS_DEFAULT,
NULL /* listener */,
DDS_STATUS_MASK_NONE);
retcode = DDSTheParticipantFactory->get_datawriter_qos_from_profile(
datawriter_qos,
"keys_Library",
"keys_Profile_dw2");
if (retcode != DDS_RETCODE_OK) {
printf("get_datawriter_qos_from_profile error\n");
return -1;
}
/* If you want to set the writer_data_lifecycle QoS settings
* programmatically rather than using the XML, you will need to add
* the following lines to your code and comment out the create_datawriter
* and get_datawriter_qos_from_profile calls above.
*/
/*
retcode = publisher->get_default_datawriter_qos(datawriter_qos);
if (retcode != DDS_RETCODE_OK) {
printf("get_default_datawriter_qos error\n");
return -1;
}
datawriter_qos.writer_data_lifecycle.autodispose_unregistered_instances =
DDS_BOOLEAN_FALSE; datawriter_qos.ownership.kind =
DDS_EXCLUSIVE_OWNERSHIP_QOS; datawriter_qos.ownership_strength.value = 10;
writer = publisher->create_datawriter(
topic, datawriter_qos, NULL,
DDS_STATUS_MASK_NONE);
datawriter_qos.ownership_strength.value = 5;
*/
writer2 = publisher->create_datawriter(
topic,
datawriter_qos,
NULL,
DDS_STATUS_MASK_NONE);
if (writer == NULL) {
printf("create_datawriter1 error\n");
publisher_shutdown(participant);
return -1;
}
if (writer2 == NULL) {
printf("create_datawriter2 error\n");
publisher_shutdown(participant);
return -1;
}
keys_writer = keysDataWriter::narrow(writer);
if (keys_writer == NULL) {
printf("DataWriter narrow error\n");
publisher_shutdown(participant);
return -1;
}
keys_writer2 = keysDataWriter::narrow(writer2);
if (keys_writer2 == NULL) {
printf("DataWriter narrow error\n");
publisher_shutdown(participant);
return -1;
}
/* Create data samples for writing */
instance[0] = keysTypeSupport::create_data();
instance[1] = keysTypeSupport::create_data();
instance[2] = keysTypeSupport::create_data();
if (instance[0] == NULL || instance[1] == NULL || instance[2] == NULL) {
printf("keysTypeSupport::create_data error\n");
publisher_shutdown(participant);
return -1;
}
/* RTI Connext could examine the key fields each time it needs to determine
* which data-instance is being modified.
* However, for performance and semantic reasons, it is better
* for your application to declare all the data-instances it intends to
* modify prior to actually writing any samples. This is known as
* registration.
*/
/* In order to register the instances, we must set their associated keys
* first */
instance[0]->code = 0;
instance[1]->code = 1;
instance[2]->code = 2;
/* The keys must have been set before making this call */
printf("----DW1 registering instance %d\n", instance[0]->code);
handle[0] = keys_writer->register_instance(*instance[0]);
/* Modify the data to be sent here */
instance[0]->x = 1;
instance[1]->x = 1;
instance[2]->x = 1;
/* Make variables for the instance for the second datawriter to use.
Note that it actually refers to the same logical instance, but
because we're running both datawriters in the same thread, we
to create separate variables so they don't clobber each other.
*/
keys *instance_dw2 = NULL;
instance_dw2 = keysTypeSupport::create_data();
if (instance_dw2 == NULL) {
printf("keysTypeSupport::create_data error\n");
publisher_shutdown(participant);
return -1;
}
/* instance_dw2 and instance[1] have the same key, and thus
will write to the same instance (ins1).
*/
instance_dw2->code = instance[1]->code;
instance_dw2->x = 2;
DDS_InstanceHandle_t handle_dw2 =
keys_writer2->register_instance(*instance_dw2);
int active_dw2 = 1;
/* Main loop */
for (count = 0; (sample_count == 0) || (count < sample_count); ++count) {
NDDSUtility::sleep(send_period);
/* Modify the data to be sent here */
instance[0]->y = count;
instance[1]->y = count + 1000;
instance[2]->y = count + 2000;
instance_dw2->y = -count - 1000;
/* We control two datawriters via a state machine here rather than
introducing separate threads.
*/
/* Control first DataWriter */
switch (count) {
case 4: { /* Start sending the second (ins1) and third instances (ins2)
*/
printf("----DW1 registering instance %d\n", instance[1]->code);
printf("----DW1 registering instance %d\n", instance[2]->code);
handle[1] = keys_writer->register_instance(*instance[1]);
handle[2] = keys_writer->register_instance(*instance[2]);
active[1] = 1;
active[2] = 1;
} break;
case 8: { /* Dispose the second instance (ins1) */
printf("----DW1 disposing instance %d\n", instance[1]->code);
retcode = keys_writer->dispose(*instance[1], handle[1]);
if (retcode != DDS_RETCODE_OK) {
printf("dispose instance error %d\n", retcode);
return -1;
}
active[1] = 0;
} break;
case 10: { /* Unregister the second instance (ins1) */
printf("----DW1 unregistering instance %d\n", instance[1]->code);
retcode = keys_writer->unregister_instance(*instance[1], handle[1]);
if (retcode != DDS_RETCODE_OK) {
printf("unregister instance error %d\n", retcode);
return -1;
}
active[1] = 0;
} break;
case 12: { /* Unregister the third instance (ins2) */
printf("----DW1 unregistering instance %d\n", instance[2]->code);
retcode = keys_writer->unregister_instance(*instance[2], handle[2]);
if (retcode != DDS_RETCODE_OK) {
printf("unregister instance error %d\n", retcode);
return -1;
}
active[2] = 0;
/* Re-register the second instance (ins1) */
printf("----DW1 re-registering instance %d\n", instance[1]->code);
handle[1] = keys_writer->register_instance(*instance[1]);
active[1] = 1;
} break;
case 16: { /* Re-register the third instance (ins2) */
printf("----DW1 re-registering instance %d\n", instance[2]->code);
handle[2] = keys_writer->register_instance(*instance[2]);
active[2] = 1;
} break;
}
for (int i = 0; i < 3; ++i) {
if (active[i]) {
printf("DW1 write; code: %d, x: %d, y: %d\n",
instance[i]->code,
instance[i]->x,
instance[i]->y);
retcode = keys_writer->write(*instance[i], handle[i]);
if (retcode != DDS_RETCODE_OK) {
printf("write error %d\n", retcode);
return -1;
}
}
}
/* Control second datawriter */
switch (count) {
case 16: { /* Dispose the instance (ins1).
Since it has lower ownership strength, this does nothing */
printf("----DW2 disposing instance %d\n", instance_dw2->code);
retcode = keys_writer2->dispose(*instance_dw2, handle_dw2);
if (retcode != DDS_RETCODE_OK) {
printf("DW2 dispose instance error %d\n", retcode);
}
active_dw2 = 0;
} break;
}
if (active_dw2) {
printf("DW2 write; code: %d, x: %d, y: %d\n",
instance_dw2->code,
instance_dw2->x,
instance_dw2->y);
retcode = keys_writer2->write(*instance_dw2, handle_dw2);
if (retcode != DDS_RETCODE_OK) {
printf("write error %d\n", retcode);
return -1;
}
}
}
/* Delete data samples */
for (int i = 0; i < 3; ++i) {
retcode = keysTypeSupport::delete_data(instance[i]);
if (retcode != DDS_RETCODE_OK) {
printf("keysTypeSupport::delete_data error %d\n", retcode);
}
}
/* Delete all entities */
return publisher_shutdown(participant);
}
#if defined(RTI_WINCE)
int wmain(int argc, wchar_t **argv)
{
int domainId = 0;
int sample_count = 0; /* infinite loop */
if (argc >= 2) {
domainId = _wtoi(argv[1]);
}
if (argc >= 3) {
sample_count = _wtoi(argv[2]);
}
/* Uncomment this to turn on additional logging
NDDSConfigLogger::get_instance()->
set_verbosity_by_category(NDDS_CONFIG_LOG_CATEGORY_API,
NDDS_CONFIG_LOG_VERBOSITY_STATUS_ALL);
*/
return publisher_main(domainId, sample_count);
}
#elif !(defined(RTI_VXWORKS) && !defined(__RTP__)) && !defined(RTI_PSOS)
int main(int argc, char *argv[])
{
int domainId = 0;
int sample_count = 0; /* infinite loop */
if (argc >= 2) {
domainId = atoi(argv[1]);
}
if (argc >= 3) {
sample_count = atoi(argv[2]);
}
/* Uncomment this to turn on additional logging
NDDSConfigLogger::get_instance()->
set_verbosity_by_category(NDDS_CONFIG_LOG_CATEGORY_API,
NDDS_CONFIG_LOG_VERBOSITY_STATUS_ALL);
*/
return publisher_main(domainId, sample_count);
}
#endif
#ifdef RTI_VX653
const unsigned char *__ctype = *(__ctypePtrGet());
extern "C" void usrAppInit()
{
#ifdef USER_APPL_INIT
USER_APPL_INIT; /* for backwards compatibility */
#endif
/* add application specific code here */
taskSpawn(
"pub",
RTI_OSAPI_THREAD_PRIORITY_NORMAL,
0x8,
0x150000,
(FUNCPTR) publisher_main,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0);
}
#endif
| cxx |
rticonnextdds-examples | data/projects/rticonnextdds-examples/connext_dds/keyed_data_advanced/c++/keys_subscriber.cxx | /*******************************************************************************
(c) 2005-2014 Copyright, Real-Time Innovations, Inc. All rights reserved.
RTI grants Licensee a license to use, modify, compile, and create derivative
works of the Software. Licensee has the right to distribute object form only
for use with RTI products. The Software is provided "as is", with no warranty
of any type, including any warranty for fitness for any purpose. RTI is under
no obligation to maintain or support the Software. RTI shall not be liable for
any incidental or consequential damages arising out of the use or inability to
use the software.
******************************************************************************/
/* keys_subscriber.cxx
A subscription example
This file is derived from code automatically generated by the rtiddsgen
command:
rtiddsgen -language C++ -example <arch> keys.idl
Example subscription of type keys automatically generated by
'rtiddsgen'. To test them follow these steps:
(1) Compile this file and the example publication.
(2) Start the subscription with the command
objs/<arch>/keys_subscriber <domain_id> <sample_count>
(3) Start the publication with the command
objs/<arch>/keys_publisher <domain_id> <sample_count>
(4) [Optional] Specify the list of discovery initial peers and
multicast receive addresses via an environment variable or a file
(in the current working directory) called NDDS_DISCOVERY_PEERS.
You can run any number of publishers and subscribers programs, and can
add and remove them dynamically from the domain.
Example:
To run the example application on domain <domain_id>:
On Unix:
objs/<arch>/keys_publisher <domain_id>
objs/<arch>/keys_subscriber <domain_id>
On Windows:
objs\<arch>\keys_publisher <domain_id>
objs\<arch>\keys_subscriber <domain_id>
modification history
------------ -------
*/
#include <stdio.h>
#include <stdlib.h>
#ifdef RTI_VX653
#include <vThreadsData.h>
#endif
#include "keys.h"
#include "keysSupport.h"
#include "ndds/ndds_cpp.h"
class keysListener : public DDSDataReaderListener {
public:
virtual void on_requested_deadline_missed(
DDSDataReader * /*reader*/,
const DDS_RequestedDeadlineMissedStatus & /*status*/)
{
}
virtual void on_requested_incompatible_qos(
DDSDataReader * /*reader*/,
const DDS_RequestedIncompatibleQosStatus & /*status*/)
{
}
virtual void on_sample_rejected(
DDSDataReader * /*reader*/,
const DDS_SampleRejectedStatus & /*status*/)
{
}
virtual void on_liveliness_changed(
DDSDataReader * /*reader*/,
const DDS_LivelinessChangedStatus & /*status*/)
{
}
virtual void on_sample_lost(
DDSDataReader * /*reader*/,
const DDS_SampleLostStatus & /*status*/)
{
}
virtual void on_subscription_matched(
DDSDataReader * /*reader*/,
const DDS_SubscriptionMatchedStatus & /*status*/)
{
}
virtual void on_data_available(DDSDataReader *reader);
/**** Start changes for Advanced_Keys ****/
/* These are not called by DDS. on_data_available() calls
the appropriate function when it gets updates about
an instances' status
*/
virtual void new_instance_found(
keysDataReader *keys_reader,
const DDS_SampleInfo *info,
const keys *msg);
virtual void instance_lost_writers(
keysDataReader *keys_reader,
const DDS_SampleInfo *info,
const keys *msg);
virtual void instance_disposed(
keysDataReader *keys_reader,
const DDS_SampleInfo *info,
const keys *msg);
/* Called to handle relevant data samples */
virtual void handle_data(
keysDataReader *keys_reader,
const DDS_SampleInfo *info,
const keys *msg);
/* Called to determine if a key is relevant to this application */
virtual bool key_is_relevant(const keys *msg);
/* Initialize instance states */
keysListener()
{
for (int i = 0; i < 3; ++i)
states[i] = inactive;
}
protected:
/* Track instance state */
enum Instance_State { inactive, active, no_writers, disposed };
Instance_State states[3];
/**** End changes for Advanced_Keys ****/
};
/**** Start changes for Advanced_Keys ****/
void keysListener::on_data_available(DDSDataReader *reader)
{
keysDataReader *keys_reader = NULL;
keysSeq data_seq;
DDS_SampleInfoSeq info_seq;
DDS_ReturnCode_t retcode;
int i;
keys_reader = keysDataReader::narrow(reader);
if (keys_reader == NULL) {
printf("DataReader narrow error\n");
return;
}
while (true) {
/* Given DDS_HANDLE_NIL as a parameter, take_next_instance returns
a sequence containing samples from only the next (in a well-determined
but unspecified order) un-taken instance.
*/
retcode = keys_reader->take_next_instance(
data_seq,
info_seq,
DDS_LENGTH_UNLIMITED,
DDS_HANDLE_NIL,
DDS_ANY_SAMPLE_STATE,
DDS_ANY_VIEW_STATE,
DDS_ANY_INSTANCE_STATE);
if (retcode == DDS_RETCODE_NO_DATA) {
break;
} else if (retcode != DDS_RETCODE_OK) {
printf("read error %d\n", retcode);
break;
}
/* We process all the obtained samples for a particular instance */
for (i = 0; i < data_seq.length(); ++i) {
/* We first check if the sample includes valid data */
if (info_seq[i].valid_data) {
if (info_seq[i].view_state == DDS_NEW_VIEW_STATE) {
new_instance_found(keys_reader, &info_seq[i], &data_seq[i]);
}
/* We check if the obtained samples are associated to one
of the instances of interest.
Since take_next_instance gives sequences of the same instance,
we only need to test this for the first sample obtained.
*/
if (i == 0 && !key_is_relevant(&data_seq[i])) {
break;
}
handle_data(keys_reader, &info_seq[i], &data_seq[i]);
} else {
/* Since there is not valid data, it may include metadata */
keys dummy;
retcode = keys_reader->get_key_value(
dummy,
info_seq[i].instance_handle);
if (retcode != DDS_RETCODE_OK) {
printf("get_key_value error %d\n", retcode);
continue;
}
/* Here we print a message and change the instance state
if the instance state is ALIVE_NO_WRITERS or ALIVE_DISPOSED
*/
if (info_seq[i].instance_state
== DDS_NOT_ALIVE_NO_WRITERS_INSTANCE_STATE) {
instance_lost_writers(keys_reader, &info_seq[i], &dummy);
} else if (
info_seq[i].instance_state
== DDS_NOT_ALIVE_DISPOSED_INSTANCE_STATE) {
instance_disposed(keys_reader, &info_seq[i], &dummy);
}
}
}
/* Prepare sequences for next take_next_instance */
retcode = keys_reader->return_loan(data_seq, info_seq);
if (retcode != DDS_RETCODE_OK) {
printf("return loan error %d\n", retcode);
}
data_seq.maximum(0);
info_seq.maximum(0);
}
}
void keysListener::new_instance_found(
keysDataReader *keys_reader,
const DDS_SampleInfo *info,
const keys *msg)
{
/* There are three cases here:
1.) truly new instance
2.) instance lost all writers, but now we're getting data again
3.) instance was disposed, but a new one has been created
We distinguish these cases by examining generation counts, BUT
note that if the instance resources have been reclaimed, the
generation counts may be reset to 0.
Instances are eligible for resource cleanup if there are no
active writers and all samples have been taken. To reliably
determine which case a 'new' instance falls into, the application
must store state information on a per-instance basis.
Note that this example assumes that state changes only occur via
explicit register_instance(), unregister_instance() and dispose()
calls from the datawriter. In reality, these changes could also
occur due to lost liveliness or missed deadlines, so those
listeners would also need to update the instance state.
*/
switch (states[msg->code]) {
case inactive:
printf("New instance found; code = %d\n", msg->code);
break;
case active:
/* An active instance should never be interpreted as new */
printf("Error, 'new' already-active instance found; code = %d\n",
msg->code);
break;
case no_writers:
printf("Found writer for instance; code = %d\n", msg->code);
break;
case disposed:
printf("Found reborn instance; code = %d\n", msg->code);
break;
}
states[msg->code] = active;
}
void keysListener::instance_lost_writers(
keysDataReader *keys_reader,
const DDS_SampleInfo *info,
const keys *msg)
{
printf("Instance has no writers; code = %d\n", msg->code);
states[msg->code] = no_writers;
}
void keysListener::instance_disposed(
keysDataReader *keys_reader,
const DDS_SampleInfo *info,
const keys *msg)
{
printf("Instance disposed; code = %d\n", msg->code);
states[msg->code] = disposed;
}
/* Called to handle relevant data samples */
void keysListener::handle_data(
keysDataReader *keys_reader,
const DDS_SampleInfo *info,
const keys *msg)
{
printf("code: %d, x: %d, y: %d\n", msg->code, msg->x, msg->y);
}
bool keysListener::key_is_relevant(const keys *msg)
{
/* For this example we just care about codes > 0,
which are the ones related to instances ins1 and ins2 .*/
return (msg->code > 0);
}
/**** End changes for Advanced_Keys ****/
/* Delete all entities */
static int subscriber_shutdown(DDSDomainParticipant *participant)
{
DDS_ReturnCode_t retcode;
int status = 0;
if (participant != NULL) {
retcode = participant->delete_contained_entities();
if (retcode != DDS_RETCODE_OK) {
printf("delete_contained_entities error %d\n", retcode);
status = -1;
}
retcode = DDSTheParticipantFactory->delete_participant(participant);
if (retcode != DDS_RETCODE_OK) {
printf("delete_participant error %d\n", retcode);
status = -1;
}
}
/* RTI Connext provides the finalize_instance() method on
domain participant factory for people who want to release memory used
by the participant factory. Uncomment the following block of code for
clean destruction of the singleton. */
/*
retcode = DDSDomainParticipantFactory::finalize_instance();
if (retcode != DDS_RETCODE_OK) {
printf("finalize_instance error %d\n", retcode);
status = -1;
}
*/
return status;
}
extern "C" int subscriber_main(int domainId, int sample_count)
{
DDSDomainParticipant *participant = NULL;
DDSSubscriber *subscriber = NULL;
DDSTopic *topic = NULL;
keysListener *reader_listener = NULL;
DDSDataReader *reader = NULL;
DDS_ReturnCode_t retcode;
const char *type_name = NULL;
int count = 0;
DDS_Duration_t receive_period = { 1, 0 };
int status = 0;
/* To customize the participant QoS, use
the configuration file USER_QOS_PROFILES.xml */
participant = DDSTheParticipantFactory->create_participant(
domainId,
DDS_PARTICIPANT_QOS_DEFAULT,
NULL /* listener */,
DDS_STATUS_MASK_NONE);
if (participant == NULL) {
printf("create_participant error\n");
subscriber_shutdown(participant);
return -1;
}
/* To customize the subscriber QoS, use
the configuration file USER_QOS_PROFILES.xml */
subscriber = participant->create_subscriber(
DDS_SUBSCRIBER_QOS_DEFAULT,
NULL /* listener */,
DDS_STATUS_MASK_NONE);
if (subscriber == NULL) {
printf("create_subscriber error\n");
subscriber_shutdown(participant);
return -1;
}
/* Register the type before creating the topic */
type_name = keysTypeSupport::get_type_name();
retcode = keysTypeSupport::register_type(participant, type_name);
if (retcode != DDS_RETCODE_OK) {
printf("register_type error %d\n", retcode);
subscriber_shutdown(participant);
return -1;
}
/* To customize the topic QoS, use
the configuration file USER_QOS_PROFILES.xml */
topic = participant->create_topic(
"Example keys",
type_name,
DDS_TOPIC_QOS_DEFAULT,
NULL /* listener */,
DDS_STATUS_MASK_NONE);
if (topic == NULL) {
printf("create_topic error\n");
subscriber_shutdown(participant);
return -1;
}
/* Create a data reader listener */
reader_listener = new keysListener();
/* To customize the data reader QoS, use
the configuration file USER_QOS_PROFILES.xml */
reader = subscriber->create_datareader(
topic,
DDS_DATAREADER_QOS_DEFAULT,
reader_listener,
DDS_STATUS_MASK_ALL);
/* If you want to set the writer_data_lifecycle QoS settings
* programmatically rather than using the XML, you will need to add
* the following lines to your code and comment out the create_datareader
* call above.
*/
/*
DDS_DataReaderQos datareader_qos;
retcode = subscriber->get_default_datareader_qos(datareader_qos);
if (retcode != DDS_RETCODE_OK) {
printf("get_default_datareader_qos error\n");
return -1;
}
datareader_qos.ownership.kind = DDS_EXCLUSIVE_OWNERSHIP_QOS;
reader = subscriber->create_datareader(
topic, datareader_qos, reader_listener,
DDS_STATUS_MASK_ALL);
*/
if (reader == NULL) {
printf("create_datareader error\n");
subscriber_shutdown(participant);
delete reader_listener;
return -1;
}
/* Main loop */
for (count = 0; (sample_count == 0) || (count < sample_count); ++count) {
// printf("keys subscriber sleeping for %d sec...\n",
// receive_period.sec);
NDDSUtility::sleep(receive_period);
}
/* Delete all entities */
status = subscriber_shutdown(participant);
delete reader_listener;
return status;
}
#if defined(RTI_WINCE)
int wmain(int argc, wchar_t **argv)
{
int domainId = 0;
int sample_count = 0; /* infinite loop */
if (argc >= 2) {
domainId = _wtoi(argv[1]);
}
if (argc >= 3) {
sample_count = _wtoi(argv[2]);
}
/* Uncomment this to turn on additional logging
NDDSConfigLogger::get_instance()->
set_verbosity_by_category(NDDS_CONFIG_LOG_CATEGORY_API,
NDDS_CONFIG_LOG_VERBOSITY_STATUS_ALL);
*/
return subscriber_main(domainId, sample_count);
}
#elif !(defined(RTI_VXWORKS) && !defined(__RTP__)) && !defined(RTI_PSOS)
int main(int argc, char *argv[])
{
int domainId = 0;
int sample_count = 0; /* infinite loop */
if (argc >= 2) {
domainId = atoi(argv[1]);
}
if (argc >= 3) {
sample_count = atoi(argv[2]);
}
/* Uncomment this to turn on additional logging
NDDSConfigLogger::get_instance()->
set_verbosity_by_category(NDDS_CONFIG_LOG_CATEGORY_API,
NDDS_CONFIG_LOG_VERBOSITY_STATUS_ALL);
*/
return subscriber_main(domainId, sample_count);
}
#endif
#ifdef RTI_VX653
const unsigned char *__ctype = *(__ctypePtrGet());
extern "C" void usrAppInit()
{
#ifdef USER_APPL_INIT
USER_APPL_INIT; /* for backwards compatibility */
#endif
/* add application specific code here */
taskSpawn(
"sub",
RTI_OSAPI_THREAD_PRIORITY_NORMAL,
0x8,
0x150000,
(FUNCPTR) subscriber_main,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0);
}
#endif
| cxx |
rticonnextdds-examples | data/projects/rticonnextdds-examples/connext_dds/keyed_data_advanced/c++98/keys_publisher.cxx | /*******************************************************************************
(c) 2005-2014 Copyright, Real-Time Innovations, Inc. All rights reserved.
RTI grants Licensee a license to use, modify, compile, and create derivative
works of the Software. Licensee has the right to distribute object form only
for use with RTI products. The Software is provided "as is", with no warranty
of any type, including any warranty for fitness for any purpose. RTI is under
no obligation to maintain or support the Software. RTI shall not be liable for
any incidental or consequential damages arising out of the use or inability to
use the software.
******************************************************************************/
#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include "keys.h"
#include "keysSupport.h"
#include "ndds/ndds_cpp.h"
#include "application.h"
using namespace application;
static int shutdown_participant(
DDSDomainParticipant *participant,
const char *shutdown_message,
int status);
int run_publisher_application(unsigned int domain_id, unsigned int sample_count)
{
// Creates three instances
keys *data[3] = { NULL, NULL, NULL };
// Creates three handles for managing the registrations
DDS_InstanceHandle_t handle[3] = { DDS_HANDLE_NIL,
DDS_HANDLE_NIL,
DDS_HANDLE_NIL };
// We only will send data over the instances marked as active
bool active[3] = { true, false, false };
DDS_Duration_t send_period = { 1, 0 };
// Start communicating in a domain, usually one participant per application
DDSDomainParticipant *participant =
DDSTheParticipantFactory->create_participant(
domain_id,
DDS_PARTICIPANT_QOS_DEFAULT,
NULL /* listener */,
DDS_STATUS_MASK_NONE);
if (participant == NULL) {
return shutdown_participant(
participant,
"create_participant error",
EXIT_FAILURE);
}
// A Publisher allows an application to create one or more DataWriters
DDSPublisher *publisher = participant->create_publisher(
DDS_PUBLISHER_QOS_DEFAULT,
NULL /* listener */,
DDS_STATUS_MASK_NONE);
if (publisher == NULL) {
return shutdown_participant(
participant,
"create_publisher error",
EXIT_FAILURE);
}
// Register the datatype to use when creating the Topic
const char *type_name = keysTypeSupport::get_type_name();
DDS_ReturnCode_t retcode =
keysTypeSupport::register_type(participant, type_name);
if (retcode != DDS_RETCODE_OK) {
return shutdown_participant(
participant,
"register_type error",
EXIT_FAILURE);
}
// Create a Topic with a name and a datatype
DDSTopic *topic = participant->create_topic(
"Example keys",
type_name,
DDS_TOPIC_QOS_DEFAULT,
NULL /* listener */,
DDS_STATUS_MASK_NONE);
if (topic == NULL) {
return shutdown_participant(
participant,
"create_topic error",
EXIT_FAILURE);
}
// We are going to load different QoS profiles for the two DWs
DDS_DataWriterQos datawriter_qos;
// This DataWriter writes data on "Example keys" Topic
DDSDataWriter *untyped_writer = publisher->create_datawriter(
topic,
DDS_DATAWRITER_QOS_DEFAULT,
NULL /* listener */,
DDS_STATUS_MASK_NONE);
retcode = DDSTheParticipantFactory->get_datawriter_qos_from_profile(
datawriter_qos,
"keys_Library",
"keys_Profile_dw2");
if (retcode != DDS_RETCODE_OK) {
return shutdown_participant(
participant,
"get_datawriter_qos_from_profile error",
EXIT_FAILURE);
}
/* If you want to set the writer_data_lifecycle QoS settings
* programmatically rather than using the XML, you will need to add
* the following lines to your code and comment out the create_datawriter
* and get_datawriter_qos_from_profile calls above.
*/
/*
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.writer_data_lifecycle.autodispose_unregistered_instances =
DDS_BOOLEAN_FALSE; datawriter_qos.ownership.kind =
DDS_EXCLUSIVE_OWNERSHIP_QOS; datawriter_qos.ownership_strength.value = 10;
DDSDataWriter *untyped_writer1 = publisher->create_datawriter(
topic, datawriter_qos, NULL,
DDS_STATUS_MASK_NONE);
datawriter_qos.ownership_strength.value = 5;
*/
// This DataWriter writes data on "Example keys" Topic
DDSDataWriter *untyped_writer2 = publisher->create_datawriter(
topic,
datawriter_qos,
NULL,
DDS_STATUS_MASK_NONE);
if (untyped_writer == NULL) {
return shutdown_participant(
participant,
"create_datawriter1 error",
EXIT_FAILURE);
}
if (untyped_writer2 == NULL) {
return shutdown_participant(
participant,
"create_datawriter2 error",
EXIT_FAILURE);
}
// Narrow casts from an untyped DataWriter to a writer of your type
keysDataWriter *typed_writer = keysDataWriter::narrow(untyped_writer);
if (typed_writer == NULL) {
return shutdown_participant(
participant,
"DataWriter narrow error",
EXIT_FAILURE);
}
keysDataWriter *typed_writer2 = keysDataWriter::narrow(untyped_writer2);
if (typed_writer2 == NULL) {
return shutdown_participant(
participant,
"DataWriter narrow error",
EXIT_FAILURE);
}
/* Create data samples for writing */
data[0] = keysTypeSupport::create_data();
data[1] = keysTypeSupport::create_data();
data[2] = keysTypeSupport::create_data();
if (data[0] == NULL || data[1] == NULL || data[2] == NULL) {
return shutdown_participant(
participant,
"keysTypeSupport::create_data error",
EXIT_FAILURE);
}
/* RTI Connext could examine the key fields each time it needs to determine
* which data-instance is being modified.
* However, for performance and semantic reasons, it is better
* for your application to declare all the data-instances it intends to
* modify prior to actually writing any samples. This is known as
* registration.
*/
/* In order to register the instances, we must set their associated keys
* first */
data[0]->code = 0;
data[1]->code = 1;
data[2]->code = 2;
/* The keys must have been set before making this call */
std::cout << "----DW1 registering instance " << data[0]->code << std::endl;
handle[0] = typed_writer->register_instance(*data[0]);
/* Modify the data to be sent here */
data[0]->x = 1;
data[1]->x = 1;
data[2]->x = 1;
/* Make variables for the instance for the second datawriter to use.
Note that it actually refers to the same logical instance, but
because we're running both datawriters in the same thread, we
to create separate variables so they don't clobber each other.
*/
keys *instance_dw2 = NULL;
instance_dw2 = keysTypeSupport::create_data();
if (instance_dw2 == NULL) {
return shutdown_participant(
participant,
"keysTypeSupport::create_data error",
EXIT_FAILURE);
}
/* instance_dw2 and instance[1] have the same key, and thus
will write to the same instance (ins1).
*/
instance_dw2->code = data[1]->code;
instance_dw2->x = 2;
DDS_InstanceHandle_t handle_dw2 =
typed_writer2->register_instance(*instance_dw2);
bool active_dw2 = true;
// Main loop, write data
for (unsigned int samples_written = 0;
!shutdown_requested && samples_written < sample_count;
++samples_written) {
NDDSUtility::sleep(send_period);
// Modify the data to be sent here
data[0]->y = samples_written;
data[1]->y = samples_written + 1000;
data[2]->y = samples_written + 2000;
instance_dw2->y = -samples_written - 1000;
/* We control two datawriters via a state machine here rather than
introducing separate threads.
*/
// Control first DataWriter
switch (samples_written) {
case 4: {
// Start sending the second (ins1) and third instances (ins2)
std::cout << "----DW1 registering instance " << data[1]->code
<< std::endl;
std::cout << "----DW1 registering instance " << data[2]->code
<< std::endl;
handle[1] = typed_writer->register_instance(*data[1]);
handle[2] = typed_writer->register_instance(*data[2]);
active[1] = true;
active[2] = true;
} break;
case 8: { /* Dispose the second instance (ins1) */
std::cout << "----DW1 disposing instance " << data[1]->code
<< std::endl;
retcode = typed_writer->dispose(*data[1], handle[1]);
if (retcode != DDS_RETCODE_OK) {
std::cerr << "dispose instance error" << retcode << std::endl;
return EXIT_FAILURE;
}
active[1] = false;
} break;
case 10: {
// Unregister the second instance (ins1)
std::cout << "----DW1 unregistering instance " << data[1]->code
<< std::endl;
retcode = typed_writer->unregister_instance(*data[1], handle[1]);
if (retcode != DDS_RETCODE_OK) {
std::cerr << "unregister instance error " << retcode
<< std::endl;
return EXIT_FAILURE;
}
active[1] = false;
} break;
case 12: {
// Unregister the third instance (ins2)
std::cout << "----DW1 unregistering instance " << data[2]->code
<< std::endl;
retcode = typed_writer->unregister_instance(*data[2], handle[2]);
if (retcode != DDS_RETCODE_OK) {
std::cerr << "unregister instance error " << retcode
<< std::endl;
return EXIT_FAILURE;
}
active[2] = false;
// Re-register the second instance (ins1)
std::cout << "----DW1 re-registering instance " << data[1]->code
<< std::endl;
handle[1] = typed_writer->register_instance(*data[1]);
active[1] = true;
} break;
case 16: {
// Re-register the third instance (ins2)
std::cout << "----DW1 re-registering instance " << data[2]->code
<< std::endl;
handle[2] = typed_writer->register_instance(*data[2]);
active[2] = true;
} break;
}
for (int i = 0; i < 3; ++i) {
if (active[i]) {
std::cout << "DW1 write; code: " << data[i]->code
<< ", x: " << data[i]->x << ", y: " << data[i]->y
<< std::endl;
retcode = typed_writer->write(*data[i], handle[i]);
if (retcode != DDS_RETCODE_OK) {
std::cerr << "write error " << retcode << std::endl;
return EXIT_FAILURE;
}
}
}
// Control second datawriter
switch (samples_written) {
case 16: { /* Dispose the instance (ins1).
Since it has lower ownership strength, this does nothing */
std::cout << "----DW2 disposing instance " << instance_dw2->code
<< std::endl;
retcode = typed_writer2->dispose(*instance_dw2, handle_dw2);
if (retcode != DDS_RETCODE_OK) {
std::cerr << "DW2 dispose instance error " << retcode
<< std::endl;
}
active_dw2 = false;
} break;
}
if (active_dw2) {
std::cout << "DW2 write; code: " << instance_dw2->code
<< ", x: " << instance_dw2->x
<< ", y: " << instance_dw2->y << std::endl;
retcode = typed_writer2->write(*instance_dw2, handle_dw2);
if (retcode != DDS_RETCODE_OK) {
std::cerr << "write error " << retcode << std::endl;
return EXIT_FAILURE;
}
}
}
// Delete data samples
for (int i = 0; i < 3; ++i) {
retcode = keysTypeSupport::delete_data(data[i]);
if (retcode != DDS_RETCODE_OK) {
std::cerr << "keysTypeSupport::delete_data error " << retcode
<< std::endl;
}
}
// Delete all entities (DataWriter, Topic, Publisher, DomainParticipant)
return shutdown_participant(participant, "Shutting down", EXIT_SUCCESS);
}
// Delete all entities
static int shutdown_participant(
DDSDomainParticipant *participant,
const char *shutdown_message,
int status)
{
DDS_ReturnCode_t retcode;
std::cout << shutdown_message << std::endl;
if (participant != NULL) {
// Cleanup everything created by this Participant
retcode = participant->delete_contained_entities();
if (retcode != DDS_RETCODE_OK) {
std::cerr << "delete_contained_entities error " << retcode
<< std::endl;
status = EXIT_FAILURE;
}
retcode = DDSTheParticipantFactory->delete_participant(participant);
if (retcode != DDS_RETCODE_OK) {
std::cerr << "delete_participant error " << retcode << std::endl;
status = EXIT_FAILURE;
}
}
return status;
}
int main(int argc, char *argv[])
{
// Parse arguments and handle control-C
ApplicationArguments arguments;
parse_arguments(arguments, argc, argv);
if (arguments.parse_result == PARSE_RETURN_EXIT) {
return EXIT_SUCCESS;
} else if (arguments.parse_result == PARSE_RETURN_FAILURE) {
return EXIT_FAILURE;
}
setup_signal_handlers();
// Sets Connext verbosity to help debugging
NDDSConfigLogger::get_instance()->set_verbosity(arguments.verbosity);
int status = run_publisher_application(
arguments.domain_id,
arguments.sample_count);
// Releases the memory used by the participant factory. Optional at
// application exit
DDS_ReturnCode_t retcode = DDSDomainParticipantFactory::finalize_instance();
if (retcode != DDS_RETCODE_OK) {
std::cerr << "finalize_instance error " << retcode << std::endl;
status = EXIT_FAILURE;
}
return status;
}
| cxx |
rticonnextdds-examples | data/projects/rticonnextdds-examples/connext_dds/keyed_data_advanced/c++98/keys_subscriber.cxx | /*******************************************************************************
(c) 2005-2014 Copyright, Real-Time Innovations, Inc. All rights reserved.
RTI grants Licensee a license to use, modify, compile, and create derivative
works of the Software. Licensee has the right to distribute object form only
for use with RTI products. The Software is provided "as is", with no warranty
of any type, including any warranty for fitness for any purpose. RTI is under
no obligation to maintain or support the Software. RTI shall not be liable for
any incidental or consequential damages arising out of the use or inability to
use the software.
******************************************************************************/
#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include "keys.h"
#include "keysSupport.h"
#include "ndds/ndds_cpp.h"
#include "application.h"
using namespace application;
static int shutdown_participant(
DDSDomainParticipant *participant,
const char *shutdown_message,
int status);
enum Instance_State { inactive, active, no_writers, disposed };
void new_instance_found(
Instance_State *states,
const DDS_SampleInfo *info,
const keys *msg)
{
/* There are three cases here:
1.) truly new instance
2.) instance lost all writers, but now we're getting data again
3.) instance was disposed, but a new one has been created
We distinguish these cases by examining generation counts, BUT
note that if the instance resources have been reclaimed, the
generation counts may be reset to 0.
Instances are eligible for resource cleanup if there are no
active writers and all samples have been taken. To reliably
determine which case a 'new' instance falls into, the application
must store state information on a per-instance basis.
Note that this example assumes that state changes only occur via
explicit register_instance(), unregister_instance() and dispose()
calls from the datawriter. In reality, these changes could also
occur due to lost liveliness or missed deadlines, so those
listeners would also need to update the instance state.
*/
switch (states[msg->code]) {
case inactive:
std::cout << "New instance found; code = " << msg->code << std::endl;
break;
case active:
// An active instance should never be interpreted as new
std::cout << "Error, 'new' already-active instance found; code = "
<< msg->code << std::endl;
break;
case no_writers:
std::cout << "Found writer for instance; code = " << msg->code
<< std::endl;
break;
case disposed:
std::cout << "Found reborn instance; code = " << msg->code << std::endl;
break;
}
states[msg->code] = active;
}
void instance_lost_writers(
Instance_State *states,
const DDS_SampleInfo *info,
const keys *msg)
{
std::cout << "Instance has no writers; code = " << msg->code << std::endl;
states[msg->code] = no_writers;
}
void instance_disposed(
Instance_State *states,
const DDS_SampleInfo *info,
const keys *msg)
{
std::cout << "Instance disposed; code = " << msg->code << std::endl;
states[msg->code] = disposed;
}
/* Called to handle relevant data samples */
void handle_data(const DDS_SampleInfo *info, const keys *msg)
{
std::cout << "code: " << msg->code << ", x: " << msg->x << ", y: " << msg->y
<< std::endl;
}
bool key_is_relevant(const keys *msg)
{
/* For this example we just care about codes > 0,
which are the ones related to instances ins1 and ins2 .*/
return (msg->code > 0);
}
unsigned int process_data(keysDataReader *typed_reader, Instance_State *states)
{
keysSeq data_seq;
DDS_SampleInfoSeq info_seq;
unsigned int samples_read = 0;
DDS_ReturnCode_t retcode;
while (true) {
/* Given DDS_HANDLE_NIL as a parameter, take_next_instance returns
a sequence containing samples from only the next (in a well-determined
but unspecified order) un-taken instance.
*/
retcode = typed_reader->take_next_instance(
data_seq,
info_seq,
DDS_LENGTH_UNLIMITED,
DDS_HANDLE_NIL,
DDS_ANY_SAMPLE_STATE,
DDS_ANY_VIEW_STATE,
DDS_ANY_INSTANCE_STATE);
if (retcode == DDS_RETCODE_NO_DATA) {
break;
} else if (retcode != DDS_RETCODE_OK) {
std::cerr << "read error " << retcode << std::endl;
break;
}
/* We process all the obtained samples for a particular instance */
for (int i = 0; i < data_seq.length(); ++i) {
/* We first check if the sample includes valid data */
if (info_seq[i].valid_data) {
if (info_seq[i].view_state == DDS_NEW_VIEW_STATE) {
new_instance_found(states, &info_seq[i], &data_seq[i]);
}
/* We check if the obtained samples are associated to one
of the instances of interest.
Since take_next_instance gives sequences of the same instance,
we only need to test this for the first sample obtained.
*/
if (i == 0 && !key_is_relevant(&data_seq[i])) {
break;
}
handle_data(&info_seq[i], &data_seq[i]);
samples_read++;
} else {
/* Since there is not valid data, it may include metadata */
keys dummy;
retcode = typed_reader->get_key_value(
dummy,
info_seq[i].instance_handle);
if (retcode != DDS_RETCODE_OK) {
std::cerr << "get_key_value error " << retcode << std::endl;
continue;
}
/* Here we print a message and change the instance state
if the instance state is ALIVE_NO_WRITERS or ALIVE_DISPOSED
*/
if (info_seq[i].instance_state
== DDS_NOT_ALIVE_NO_WRITERS_INSTANCE_STATE) {
instance_lost_writers(states, &info_seq[i], &dummy);
} else if (
info_seq[i].instance_state
== DDS_NOT_ALIVE_DISPOSED_INSTANCE_STATE) {
instance_disposed(states, &info_seq[i], &dummy);
}
}
}
/* Prepare sequences for next take_next_instance */
retcode = typed_reader->return_loan(data_seq, info_seq);
if (retcode != DDS_RETCODE_OK) {
std::cerr << "return loan error " << retcode << std::endl;
}
data_seq.maximum(0);
info_seq.maximum(0);
}
return samples_read;
}
int run_subscriber_application(
unsigned int domain_id,
unsigned int sample_count)
{
DDS_Duration_t wait_timeout = { 1, 0 };
Instance_State states[3] = { inactive, inactive, inactive };
// Start communicating in a domain, usually one participant per application
DDSDomainParticipant *participant =
DDSTheParticipantFactory->create_participant(
domain_id,
DDS_PARTICIPANT_QOS_DEFAULT,
NULL /* listener */,
DDS_STATUS_MASK_NONE);
if (participant == NULL) {
return shutdown_participant(
participant,
"create_participant error",
EXIT_FAILURE);
}
// A Subscriber allows an application to create one or more DataReaders
DDSSubscriber *subscriber = participant->create_subscriber(
DDS_SUBSCRIBER_QOS_DEFAULT,
NULL /* listener */,
DDS_STATUS_MASK_NONE);
if (subscriber == NULL) {
return shutdown_participant(
participant,
"create_subscriber error",
EXIT_FAILURE);
}
// Register the datatype to use when creating the Topic
const char *type_name = keysTypeSupport::get_type_name();
DDS_ReturnCode_t retcode =
keysTypeSupport::register_type(participant, type_name);
if (retcode != DDS_RETCODE_OK) {
return shutdown_participant(
participant,
"register_type error",
EXIT_FAILURE);
}
// Create a Topic with a name and a datatype
DDSTopic *topic = participant->create_topic(
"Example keys",
type_name,
DDS_TOPIC_QOS_DEFAULT,
NULL /* listener */,
DDS_STATUS_MASK_NONE);
if (topic == NULL) {
return shutdown_participant(
participant,
"create_topic error",
EXIT_FAILURE);
}
// This DataReader reads data on "Example keys" Topic
DDSDataReader *untyped_reader = subscriber->create_datareader(
topic,
DDS_DATAREADER_QOS_DEFAULT,
NULL,
DDS_STATUS_MASK_ALL);
/* If you want to set the writer_data_lifecycle QoS settings
* programmatically rather than using the XML, you will need to add
* the following lines to your code and comment out the create_datareader
* call above.
*/
/*
DDS_DataReaderQos datareader_qos;
retcode = subscriber->get_default_datareader_qos(datareader_qos);
if (retcode != DDS_RETCODE_OK) {
std::cerr << "get_default_datareader_qos error\n";
return EXIT_FAILURE;
}
datareader_qos.ownership.kind = DDS_EXCLUSIVE_OWNERSHIP_QOS;
DDSDataReader *untyped_reader = subscriber->create_datareader(
topic, datareader_qos, reader_listener,
DDS_STATUS_MASK_ALL);
*/
if (untyped_reader == NULL) {
return shutdown_participant(
participant,
"create_datareader error",
EXIT_FAILURE);
}
// Narrow casts from a untyped DataReader to a reader of your type
keysDataReader *typed_reader = keysDataReader::narrow(untyped_reader);
if (typed_reader == NULL) {
return shutdown_participant(
participant,
"DataReader narrow error",
EXIT_FAILURE);
}
// Create ReadCondition that triggers when unread data in reader's queue
DDSReadCondition *read_condition = typed_reader->create_readcondition(
DDS_NOT_READ_SAMPLE_STATE,
DDS_ANY_VIEW_STATE,
DDS_ANY_INSTANCE_STATE);
if (read_condition == NULL) {
return shutdown_participant(
participant,
"create_readcondition error",
EXIT_FAILURE);
}
// WaitSet will be woken when the attached condition is triggered
DDSWaitSet waitset;
retcode = waitset.attach_condition(read_condition);
if (retcode != DDS_RETCODE_OK) {
return shutdown_participant(
participant,
"attach_condition error",
EXIT_FAILURE);
}
// Main loop. Wait for data to arrive, and process when it arrives
unsigned int samples_read = 0;
while (!shutdown_requested && samples_read < sample_count) {
DDSConditionSeq active_conditions_seq;
// Wait for data
retcode = waitset.wait(active_conditions_seq, wait_timeout);
if (retcode == DDS_RETCODE_OK) {
// If the read condition is triggered, process data
samples_read += process_data(typed_reader, states);
}
}
// Cleanup
return shutdown_participant(participant, "Shutting down", 0);
}
// Delete all entities
static int shutdown_participant(
DDSDomainParticipant *participant,
const char *shutdown_message,
int status)
{
DDS_ReturnCode_t retcode;
std::cout << shutdown_message << std::endl;
if (participant != NULL) {
// Cleanup everything created by this Participant
retcode = participant->delete_contained_entities();
if (retcode != DDS_RETCODE_OK) {
std::cerr << "delete_contained_entities error" << retcode
<< std::endl;
status = EXIT_FAILURE;
}
retcode = DDSTheParticipantFactory->delete_participant(participant);
if (retcode != DDS_RETCODE_OK) {
std::cerr << "delete_participant error" << retcode << std::endl;
status = EXIT_FAILURE;
}
}
return status;
}
int main(int argc, char *argv[])
{
// Parse arguments and handle control-C
ApplicationArguments arguments;
parse_arguments(arguments, argc, argv);
if (arguments.parse_result == PARSE_RETURN_EXIT) {
return EXIT_SUCCESS;
} else if (arguments.parse_result == PARSE_RETURN_FAILURE) {
return EXIT_FAILURE;
}
setup_signal_handlers();
// Sets Connext verbosity to help debugging
NDDSConfigLogger::get_instance()->set_verbosity(arguments.verbosity);
int status = run_subscriber_application(
arguments.domain_id,
arguments.sample_count);
// Releases the memory used by the participant factory. Optional at
// application exit
DDS_ReturnCode_t retcode = DDSDomainParticipantFactory::finalize_instance();
if (retcode != DDS_RETCODE_OK) {
std::cerr << "finalize_instance error" << retcode << std::endl;
status = EXIT_FAILURE;
}
return status;
}
| cxx |
rticonnextdds-examples | data/projects/rticonnextdds-examples/connext_dds/keyed_data_advanced/c++98/application.h | /*
* (c) Copyright, Real-Time Innovations, 2020. All rights reserved.
* RTI grants Licensee a license to use, modify, compile, and create derivative
* works of the software solely for use with RTI Connext DDS. Licensee may
* redistribute copies of the software provided that all such copies are subject
* to this license. The software is provided "as is", with no warranty of any
* type, including any warranty for fitness for any purpose. RTI is under no
* obligation to maintain or support the software. RTI shall not be liable for
* any incidental or consequential damages arising out of the use or inability
* to use the software.
*/
#ifndef APPLICATION_H
#define APPLICATION_H
#include <iostream>
#include <csignal>
#include <climits>
namespace application {
// Catch control-C and tell application to shut down
bool shutdown_requested = false;
inline void stop_handler(int)
{
shutdown_requested = true;
std::cout << "preparing to shut down..." << std::endl;
}
inline void setup_signal_handlers()
{
signal(SIGINT, stop_handler);
signal(SIGTERM, stop_handler);
}
enum ParseReturn { PARSE_RETURN_OK, PARSE_RETURN_FAILURE, PARSE_RETURN_EXIT };
struct ApplicationArguments {
ParseReturn parse_result;
unsigned int domain_id;
unsigned int sample_count;
NDDS_Config_LogVerbosity verbosity;
};
inline void set_verbosity(ApplicationArguments &arguments, int verbosity)
{
switch (verbosity) {
case 0:
arguments.verbosity = NDDS_CONFIG_LOG_VERBOSITY_SILENT;
break;
case 1:
arguments.verbosity = NDDS_CONFIG_LOG_VERBOSITY_ERROR;
break;
case 2:
arguments.verbosity = NDDS_CONFIG_LOG_VERBOSITY_WARNING;
break;
case 3:
arguments.verbosity = NDDS_CONFIG_LOG_VERBOSITY_STATUS_ALL;
break;
default:
arguments.verbosity = NDDS_CONFIG_LOG_VERBOSITY_ERROR;
break;
}
}
// Parses application arguments for example. Returns whether to exit.
inline void parse_arguments(
ApplicationArguments &arguments,
int argc,
char *argv[])
{
int arg_processing = 1;
bool show_usage = false;
arguments.domain_id = 0;
arguments.sample_count = INT_MAX;
arguments.verbosity = NDDS_CONFIG_LOG_VERBOSITY_ERROR;
arguments.parse_result = PARSE_RETURN_OK;
while (arg_processing < argc) {
if ((argc > arg_processing + 1)
&& (strcmp(argv[arg_processing], "-d") == 0
|| strcmp(argv[arg_processing], "--domain") == 0)) {
arguments.domain_id = atoi(argv[arg_processing + 1]);
arg_processing += 2;
} else if (
(argc > arg_processing + 1)
&& (strcmp(argv[arg_processing], "-s") == 0
|| strcmp(argv[arg_processing], "--sample-count") == 0)) {
arguments.sample_count = atoi(argv[arg_processing + 1]);
arg_processing += 2;
} else if (
(argc > arg_processing + 1)
&& (strcmp(argv[arg_processing], "-v") == 0
|| strcmp(argv[arg_processing], "--verbosity") == 0)) {
set_verbosity(arguments, atoi(argv[arg_processing + 1]));
arg_processing += 2;
} else if (
strcmp(argv[arg_processing], "-h") == 0
|| strcmp(argv[arg_processing], "--help") == 0) {
std::cout << "Example application." << std::endl;
show_usage = true;
arguments.parse_result = PARSE_RETURN_EXIT;
break;
} else {
std::cout << "Bad parameter." << std::endl;
show_usage = true;
arguments.parse_result = PARSE_RETURN_FAILURE;
break;
}
}
if (show_usage) {
std::cout << "Usage:\n"
" -d, --domain <int> Domain ID this "
"application will\n"
" subscribe in. \n"
" Default: 0\n"
" -s, --sample_count <int> Number of samples to "
"receive before\n"
" cleanly shutting down. \n"
" Default: infinite\n"
" -v, --verbosity <int> How much debugging output "
"to show.\n"
" Range: 0-3 \n"
" Default: 1"
<< std::endl;
}
}
} // namespace application
#endif // APPLICATION_H
| h |
rticonnextdds-examples | data/projects/rticonnextdds-examples/connext_dds/keyed_data_advanced/c/keys_publisher.c | /*******************************************************************************
(c) 2005-2014 Copyright, Real-Time Innovations, Inc. All rights reserved.
RTI grants Licensee a license to use, modify, compile, and create derivative
works of the Software. Licensee has the right to distribute object form only
for use with RTI products. The Software is provided "as is", with no warranty
of any type, including any warranty for fitness for any purpose. RTI is under
no obligation to maintain or support the Software. RTI shall not be liable for
any incidental or consequential damages arising out of the use or inability to
use the software.
******************************************************************************/
/* keys_publisher.c
A publication of data of type keys
This file is derived from code automatically generated by the rtiddsgen
command:
rtiddsgen -language C -example <arch> keys.idl
Example publication of type keys automatically generated by
'rtiddsgen'. To test them follow these steps:
(1) Compile this file and the example subscription.
(2) Start the subscription with the command
objs/<arch>/keys_subscriber <domain_id> <sample_count>
(3) Start the publication with the command
objs/<arch>/keys_publisher <domain_id> <sample_count>
(4) [Optional] Specify the list of discovery initial peers and
multicast receive addresses via an environment variable or a file
(in the current working directory) called NDDS_DISCOVERY_PEERS.
You can run any number of publishers and subscribers programs, and can
add and remove them dynamically from the domain.
Example:
To run the example application on domain <domain_id>:
On Unix:
objs/<arch>/keys_publisher <domain_id>
objs/<arch>/keys_subscriber <domain_id>
On Windows:
objs\<arch>\keys_publisher <domain_id>
objs\<arch>\keys_subscriber <domain_id>
modification history
------------ -------
*/
#include "keys.h"
#include "keysSupport.h"
#include "ndds/ndds_c.h"
#include <stdio.h>
#include <stdlib.h>
/* Delete all entities */
static int publisher_shutdown(DDS_DomainParticipant *participant)
{
DDS_ReturnCode_t retcode;
int status = 0;
if (participant != NULL) {
retcode = DDS_DomainParticipant_delete_contained_entities(participant);
if (retcode != DDS_RETCODE_OK) {
printf("delete_contained_entities error %d\n", retcode);
status = -1;
}
retcode = DDS_DomainParticipantFactory_delete_participant(
DDS_TheParticipantFactory,
participant);
if (retcode != DDS_RETCODE_OK) {
printf("delete_participant error %d\n", retcode);
status = -1;
}
}
/* RTI Connext provides finalize_instance() method on
domain participant factory for people who want to release memory used
by the participant factory. Uncomment the following block of code for
clean destruction of the singleton. */
/*
retcode = DDS_DomainParticipantFactory_finalize_instance();
if (retcode != DDS_RETCODE_OK) {
printf("finalize_instance error %d\n", retcode);
status = -1;
}
*/
return status;
}
static int publisher_main(int domainId, int sample_count)
{
DDS_DomainParticipant *participant = NULL;
DDS_Publisher *publisher = NULL;
DDS_Topic *topic = NULL;
DDS_DataWriter *writer = NULL;
DDS_DataWriter *writer2 = NULL;
keysDataWriter *keys_writer = NULL;
keysDataWriter *keys_writer2 = NULL;
DDS_ReturnCode_t retcode;
/* Creates three instances */
keys *instance[3] = { NULL, NULL, NULL };
/* Creates three handles for managing the registrations */
DDS_InstanceHandle_t handle[3];
/* Make variables for the instance for the second datawriter to use.
Note that it actually refers to the same logical instance, but
because we're running both datawriters in the same thread, we
to create separate variables so they don't clobber each other.
*/
keys *instance_dw2 = NULL;
DDS_InstanceHandle_t handle_dw2 = DDS_HANDLE_NIL;
/* We only will send data over the instances marked as active */
int active[3] = { 1, 0, 0 };
int active_dw2 = 1;
/* We are going to load different QoS profiles for the two DWs */
struct DDS_DataWriterQos datawriter_qos = DDS_DataWriterQos_INITIALIZER;
const char *type_name = NULL;
int count = 0;
struct DDS_Duration_t send_period = { 1, 0 };
int i = 0;
/* To customize participant QoS, use
the configuration file USER_QOS_PROFILES.xml */
participant = DDS_DomainParticipantFactory_create_participant(
DDS_TheParticipantFactory,
domainId,
&DDS_PARTICIPANT_QOS_DEFAULT,
NULL /* listener */,
DDS_STATUS_MASK_NONE);
if (participant == NULL) {
printf("create_participant error\n");
publisher_shutdown(participant);
return -1;
}
/* To customize publisher QoS, use
the configuration file USER_QOS_PROFILES.xml */
publisher = DDS_DomainParticipant_create_publisher(
participant,
&DDS_PUBLISHER_QOS_DEFAULT,
NULL /* listener */,
DDS_STATUS_MASK_NONE);
if (publisher == NULL) {
printf("create_publisher error\n");
publisher_shutdown(participant);
return -1;
}
/* Register type before creating topic */
type_name = keysTypeSupport_get_type_name();
retcode = keysTypeSupport_register_type(participant, type_name);
if (retcode != DDS_RETCODE_OK) {
printf("register_type error %d\n", retcode);
publisher_shutdown(participant);
return -1;
}
/* To customize topic QoS, use
the configuration file USER_QOS_PROFILES.xml */
topic = DDS_DomainParticipant_create_topic(
participant,
"Example keys",
type_name,
&DDS_TOPIC_QOS_DEFAULT,
NULL /* listener */,
DDS_STATUS_MASK_NONE);
if (topic == NULL) {
printf("create_topic error\n");
publisher_shutdown(participant);
return -1;
}
/* To customize data writer QoS, use
the configuration file USER_QOS_PROFILES.xml */
writer = DDS_Publisher_create_datawriter(
publisher,
topic,
&DDS_DATAWRITER_QOS_DEFAULT,
NULL /* listener */,
DDS_STATUS_MASK_NONE);
retcode = DDS_DomainParticipantFactory_get_datawriter_qos_from_profile(
DDS_TheParticipantFactory,
&datawriter_qos,
"keys_Library",
"keys_Profile_dw2");
if (retcode != DDS_RETCODE_OK) {
printf("get_datawriter_qos_from_profile error\n");
return -1;
}
/* If you want to set the writer_data_lifecycle QoS settings
* programmatically rather than using the XML, you will need to add
* the following lines to your code and comment out the create_datawriter
* and get_datawriter_qos_from_profile calls above.
*/
/*
retcode = DDS_Publisher_get_default_datawriter_qos(publisher,
&datawriter_qos); if (retcode != DDS_RETCODE_OK) {
printf("get_default_datawriter_qos error\n");
return -1;
}
datawriter_qos.writer_data_lifecycle.autodispose_unregistered_instances =
DDS_BOOLEAN_FALSE;
datawriter_qos.ownership.kind = DDS_EXCLUSIVE_OWNERSHIP_QOS;
datawriter_qos.ownership_strength.value = 10;
writer = DDS_Publisher_create_datawriter(
publisher, topic,
&datawriter_qos, NULL, DDS_STATUS_MASK_NONE);
datawriter_qos.ownership_strength.value = 5;
*/
writer2 = DDS_Publisher_create_datawriter(
publisher,
topic,
&datawriter_qos,
NULL,
DDS_STATUS_MASK_NONE);
if (writer == NULL) {
printf("create_datawriter1 error\n");
publisher_shutdown(participant);
return -1;
}
if (writer2 == NULL) {
printf("create_datawriter2 error\n");
publisher_shutdown(participant);
return -1;
}
keys_writer = keysDataWriter_narrow(writer);
if (keys_writer == NULL) {
printf("DataWriter narrow error\n");
publisher_shutdown(participant);
return -1;
}
keys_writer2 = keysDataWriter_narrow(writer2);
if (keys_writer2 == NULL) {
printf("DataWriter narrow error\n");
publisher_shutdown(participant);
return -1;
}
/* Create data sample for writing */
instance[0] = keysTypeSupport_create_data_ex(DDS_BOOLEAN_TRUE);
instance[1] = keysTypeSupport_create_data_ex(DDS_BOOLEAN_TRUE);
instance[2] = keysTypeSupport_create_data_ex(DDS_BOOLEAN_TRUE);
if (instance[0] == NULL || instance[1] == NULL || instance[2] == NULL) {
printf("keysTypeSupport_create_data error\n");
publisher_shutdown(participant);
return -1;
}
/* RTI Connext could examine the key fields each time it needs to determine
* which data-instance is being modified.
* However, for performance and semantic reasons, it is better
* for your application to declare all the data-instances it intends to
* modify prior to actually writing any samples. This is known as
* registration.
*/
/* In order to register the instances, we must set their associated keys
* first */
instance[0]->code = 0;
instance[1]->code = 1;
instance[2]->code = 2;
handle[0] = DDS_HANDLE_NIL;
handle[1] = DDS_HANDLE_NIL;
handle[2] = DDS_HANDLE_NIL;
/* The keys must have been set before making this call */
printf("Registering instance %d\n", instance[0]->code);
handle[0] = keysDataWriter_register_instance(keys_writer, instance[0]);
/* Modify the data to be sent here */
instance[0]->x = 1;
instance[1]->x = 1;
instance[2]->x = 1;
/* Make variables for the instance for the second datawriter to use.
Note that it actually refers to the same logical instance, but
because we're running both datawriters in the same thread, we
to create separate variables so they don't clobber each other.
*/
instance_dw2 = keysTypeSupport_create_data_ex(DDS_BOOLEAN_TRUE);
if (instance_dw2 == NULL) {
printf("keysTypeSupport_create_data error\n");
publisher_shutdown(participant);
return -1;
}
/* instance_dw2 and instance[1] have the same key, and thus
will write to the same instance (ins1).
*/
instance_dw2->code = instance[1]->code;
instance_dw2->x = 2;
handle_dw2 = keysDataWriter_register_instance(keys_writer2, instance_dw2);
/* Main loop */
for (count = 0; (sample_count == 0) || (count < sample_count); ++count) {
NDDS_Utility_sleep(&send_period);
/* Modify the data to be sent here */
instance[0]->y = count;
instance[1]->y = count + 1000;
instance[2]->y = count + 2000;
instance_dw2->y = -count - 1000;
/* We control two datawriters via a state machine here rather than
introducing separate threads.
*/
/* Control first DataWriter */
switch (count) {
case 4: { /* Start sending the second (ins1) and third instances (ins2)
*/
printf("----DW1 registering instance %d\n", instance[1]->code);
printf("----DW1 registering instance %d\n", instance[2]->code);
handle[1] =
keysDataWriter_register_instance(keys_writer, instance[1]);
handle[2] =
keysDataWriter_register_instance(keys_writer, instance[2]);
active[1] = 1;
active[2] = 1;
} break;
case 8: { /* Dispose the second instance (ins1) */
printf("----DW1 disposing instance %d\n", instance[1]->code);
retcode = keysDataWriter_dispose(
keys_writer,
instance[1],
&handle[1]);
if (retcode != DDS_RETCODE_OK) {
printf("dispose instance error %d\n", retcode);
return -1;
}
active[1] = 0;
} break;
case 10: { /* Unregister the second instance (ins1) */
printf("----DW1 unregistering instance %d\n", instance[1]->code);
retcode = keysDataWriter_unregister_instance(
keys_writer,
instance[1],
&handle[1]);
if (retcode != DDS_RETCODE_OK) {
printf("unregister instance error %d\n", retcode);
return -1;
}
active[1] = 0;
} break;
case 12: { /* Unregister the third instance (ins2) */
printf("----DW1 unregistering instance %d\n", instance[2]->code);
retcode = keysDataWriter_unregister_instance(
keys_writer,
instance[2],
&handle[2]);
if (retcode != DDS_RETCODE_OK) {
printf("dispose instance error %d\n", retcode);
return -1;
}
active[2] = 0;
/* Re-register the second instance (ins1) */
printf("----DW1 re-registering instance %d\n", instance[1]->code);
handle[1] =
keysDataWriter_register_instance(keys_writer, instance[1]);
active[1] = 1;
} break;
case 16: { /* Re-register the third instance (ins2) */
printf("----DW1 re-registering instance %d\n", instance[2]->code);
handle[2] =
keysDataWriter_register_instance(keys_writer, instance[2]);
active[2] = 1;
} break;
}
for (i = 0; i < 3; ++i) {
if (active[i]) {
printf("DW1 write; code: %d, x: %d, y: %d\n",
instance[i]->code,
instance[i]->x,
instance[i]->y);
retcode = keysDataWriter_write(
keys_writer,
instance[i],
&handle[i]);
if (retcode != DDS_RETCODE_OK) {
printf("write error %d\n", retcode);
return -1;
}
}
}
/* Control second datawriter */
switch (count) {
case 16: { /* Dispose the instance (ins1).
Since it has lower ownership strength, this does nothing */
printf("----DW2 disposing instance %d\n", instance_dw2->code);
retcode = keysDataWriter_dispose(
keys_writer2,
instance_dw2,
&handle_dw2);
if (retcode != DDS_RETCODE_OK) {
printf("DW2 dispose instance error %d\n", retcode);
}
active_dw2 = 0;
} break;
}
if (active_dw2) {
printf("DW2 write; code: %d, x: %d, y: %d\n",
instance_dw2->code,
instance_dw2->x,
instance_dw2->y);
retcode = keysDataWriter_write(
keys_writer2,
instance_dw2,
&handle_dw2);
if (retcode != DDS_RETCODE_OK) {
printf("write error %d\n", retcode);
return -1;
}
}
}
/* Delete data samples */
for (i = 0; i < 3; ++i) {
retcode = keysTypeSupport_delete_data(instance[i]);
if (retcode != DDS_RETCODE_OK) {
printf("keysTypeSupport::delete_data error %d\n", retcode);
}
}
retcode = keysTypeSupport_delete_data(instance_dw2);
if (retcode != DDS_RETCODE_OK) {
printf("keysTypeSupport::delete_data error %d\n", retcode);
}
/* Cleanup and delete delete all entities */
return publisher_shutdown(participant);
}
#if defined(RTI_WINCE)
int wmain(int argc, wchar_t **argv)
{
int domainId = 0;
int sample_count = 0; /* infinite loop */
if (argc >= 2) {
domainId = _wtoi(argv[1]);
}
if (argc >= 3) {
sample_count = _wtoi(argv[2]);
}
/* Uncomment this to turn on additional logging
NDDS_Config_Logger_set_verbosity_by_category(
NDDS_Config_Logger_get_instance(),
NDDS_CONFIG_LOG_CATEGORY_API,
NDDS_CONFIG_LOG_VERBOSITY_STATUS_ALL);
*/
return publisher_main(domainId, sample_count);
}
#elif !(defined(RTI_VXWORKS) && !defined(__RTP__)) && !defined(RTI_PSOS)
int main(int argc, char *argv[])
{
int domainId = 0;
int sample_count = 0; /* infinite loop */
if (argc >= 2) {
domainId = atoi(argv[1]);
}
if (argc >= 3) {
sample_count = atoi(argv[2]);
}
/* Uncomment this to turn on additional logging
NDDS_Config_Logger_set_verbosity_by_category(
NDDS_Config_Logger_get_instance(),
NDDS_CONFIG_LOG_CATEGORY_API,
NDDS_CONFIG_LOG_VERBOSITY_STATUS_ALL);
*/
return publisher_main(domainId, sample_count);
}
#endif
#ifdef RTI_VX653
const unsigned char *__ctype = NULL;
void usrAppInit()
{
#ifdef USER_APPL_INIT
USER_APPL_INIT; /* for backwards compatibility */
#endif
/* add application specific code here */
taskSpawn(
"pub",
RTI_OSAPI_THREAD_PRIORITY_NORMAL,
0x8,
0x150000,
(FUNCPTR) publisher_main,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0);
}
#endif
| c |
rticonnextdds-examples | data/projects/rticonnextdds-examples/connext_dds/keyed_data_advanced/c/keys_subscriber.c | /*******************************************************************************
(c) 2005-2014 Copyright, Real-Time Innovations, Inc. All rights reserved.
RTI grants Licensee a license to use, modify, compile, and create derivative
works of the Software. Licensee has the right to distribute object form only
for use with RTI products. The Software is provided "as is", with no warranty
of any type, including any warranty for fitness for any purpose. RTI is under
no obligation to maintain or support the Software. RTI shall not be liable for
any incidental or consequential damages arising out of the use or inability to
use the software.
******************************************************************************/
/* keys_subscriber.c
A subscription example
This file is derived from code automatically generated by the rtiddsgen
command:
rtiddsgen -language C -example <arch> keys.idl
Example subscription of type keys automatically generated by
'rtiddsgen'. To test them, follow these steps:
(1) Compile this file and the example publication.
(2) Start the subscription with the command
objs/<arch>/keys_subscriber <domain_id> <sample_count>
(3) Start the publication with the command
objs/<arch>/keys_publisher <domain_id> <sample_count>
(4) [Optional] Specify the list of discovery initial peers and
multicast receive addresses via an environment variable or a file
(in the current working directory) called NDDS_DISCOVERY_PEERS.
You can run any number of publishers and subscribers programs, and can
add and remove them dynamically from the domain.
Example:
To run the example application on domain <domain_id>:
On UNIX systems:
objs/<arch>/keys_publisher <domain_id>
objs/<arch>/keys_subscriber <domain_id>
On Windows systems:
objs\<arch>\keys_publisher <domain_id>
objs\<arch>\keys_subscriber <domain_id>
modification history
------------ -------
*/
#include "keys.h"
#include "keysSupport.h"
#include "ndds/ndds_c.h"
#include <stdio.h>
#include <stdlib.h>
void keysListener_on_requested_deadline_missed(
void *listener_data,
DDS_DataReader *reader,
const struct DDS_RequestedDeadlineMissedStatus *status)
{
}
void keysListener_on_requested_incompatible_qos(
void *listener_data,
DDS_DataReader *reader,
const struct DDS_RequestedIncompatibleQosStatus *status)
{
}
void keysListener_on_sample_rejected(
void *listener_data,
DDS_DataReader *reader,
const struct DDS_SampleRejectedStatus *status)
{
}
void keysListener_on_liveliness_changed(
void *listener_data,
DDS_DataReader *reader,
const struct DDS_LivelinessChangedStatus *status)
{
}
void keysListener_on_sample_lost(
void *listener_data,
DDS_DataReader *reader,
const struct DDS_SampleLostStatus *status)
{
}
void keysListener_on_subscription_matched(
void *listener_data,
DDS_DataReader *reader,
const struct DDS_SubscriptionMatchedStatus *status)
{
}
/**** Start changes for Advanced_Keys ****/
/* Track instance state */
#define INSTANCE_STATE_INACTIVE 0
#define INSTANCE_STATE_ACTIVE 1
#define INSTANCE_STATE_NO_WRITERS 2
#define INSTANCE_STATE_DISPOSED 3
int states[3] = { INSTANCE_STATE_INACTIVE,
INSTANCE_STATE_INACTIVE,
INSTANCE_STATE_INACTIVE };
/* These are not called by DDS. on_data_available() calls
the appropriate function when it gets updates about
an instances' status
*/
void keysListener_new_instance_found(
keysDataReader *keys_reader,
const struct DDS_SampleInfo *info,
const struct keys *msg);
void keysListener_instance_lost_writers(
keysDataReader *keys_reader,
const struct DDS_SampleInfo *info,
const struct keys *msg);
void keysListener_instance_disposed(
keysDataReader *keys_reader,
const struct DDS_SampleInfo *info,
const struct keys *msg);
/* Called to handle relevant data samples */
void keysListener_handle_data(
keysDataReader *keys_reader,
const struct DDS_SampleInfo *info,
const struct keys *msg);
/* Called to determine if a key is relevant to this application */
int keysListener_key_is_relevant(const struct keys *msg);
void keysListener_on_data_available(void *listener_data, DDS_DataReader *reader)
{
keysDataReader *keys_reader = NULL;
struct keysSeq data_seq = DDS_SEQUENCE_INITIALIZER;
struct DDS_SampleInfoSeq info_seq = DDS_SEQUENCE_INITIALIZER;
DDS_ReturnCode_t retcode;
int i;
keys_reader = keysDataReader_narrow(reader);
if (keys_reader == NULL) {
printf("DataReader narrow error\n");
return;
}
while (1) {
/* Given DDS_HANDLE_NIL as a parameter, take_next_instance returns
a sequence containing samples from only the next (in a well-determined
but unspecified order) un-taken instance.
*/
retcode = keysDataReader_take_next_instance(
keys_reader,
&data_seq,
&info_seq,
DDS_LENGTH_UNLIMITED,
&DDS_HANDLE_NIL,
DDS_ANY_SAMPLE_STATE,
DDS_ANY_VIEW_STATE,
DDS_ANY_INSTANCE_STATE);
if (retcode == DDS_RETCODE_NO_DATA) {
break;
} else if (retcode != DDS_RETCODE_OK) {
printf("read error %d\n", retcode);
break;
}
/* We process all the obtained samples for a particular instance */
for (i = 0; i < keysSeq_get_length(&data_seq); ++i) {
struct DDS_SampleInfo *info = NULL;
struct keys *data = NULL;
info = DDS_SampleInfoSeq_get_reference(&info_seq, i);
data = keysSeq_get_reference(&data_seq, i);
/* We first check if the sample includes valid data */
if (info->valid_data) {
if (info->view_state == DDS_NEW_VIEW_STATE) {
keysListener_new_instance_found(keys_reader, info, data);
}
/* We check if the obtained samples are associated to one
of the instances of interest.
Since take_next_instance gives sequences of the same instance,
we only need to test this for the first sample obtained.
*/
if (i == 0 && !keysListener_key_is_relevant(data)) {
break;
}
keysListener_handle_data(keys_reader, info, data);
} else {
/* Since there is not valid data, it may include metadata */
keys dummy;
retcode = keysDataReader_get_key_value(
keys_reader,
&dummy,
&info->instance_handle);
if (retcode != DDS_RETCODE_OK) {
printf("get_key_value error %d\n", retcode);
continue;
}
/* Here we print a message and change the instance state
if the instance state is ALIVE_NO_WRITERS or ALIVE_DISPOSED */
if (info->instance_state
== DDS_NOT_ALIVE_NO_WRITERS_INSTANCE_STATE) {
keysListener_instance_lost_writers(
keys_reader,
info,
&dummy);
} else if (
info->instance_state
== DDS_NOT_ALIVE_DISPOSED_INSTANCE_STATE) {
keysListener_instance_disposed(keys_reader, info, &dummy);
}
}
}
/* Prepare sequences for next take_next_instance */
retcode = keysDataReader_return_loan(keys_reader, &data_seq, &info_seq);
if (retcode != DDS_RETCODE_OK) {
printf("return loan error %d\n", retcode);
}
keysSeq_set_maximum(&data_seq, 0);
DDS_SampleInfoSeq_set_maximum(&info_seq, 0);
}
}
void keysListener_new_instance_found(
keysDataReader *keys_reader,
const struct DDS_SampleInfo *info,
const struct keys *msg)
{
/* There are really three cases here:
1.) truly new instance
2.) instance lost all writers, but now we're getting data again
3.) instance was disposed, but a new one has been created
We distinguish these cases by examining generation counts, BUT
note that if the instance resources have been reclaimed, the
generation counts may be reset to 0.
Instances are eligible for resource cleanup if there are no
active writers and all samples have been taken. To reliably
determine which case a 'new' instance falls into, the application
must store state information on a per-instance basis.
Note that this example assumes that state changes only occur via
explicit register_instance(), unregister_instance() and dispose()
calls from the datawriter. In reality, these changes could also
occur due to lost liveliness or missed deadlines, so those
listeners would also need to update the instance state.
*/
switch (states[msg->code]) {
case INSTANCE_STATE_INACTIVE:
printf("New instance found; code = %d\n", msg->code);
break;
case INSTANCE_STATE_ACTIVE:
/* An active instance should never be interpreted as new */
printf("Error, 'new' already-active instance found; code = %d\n",
msg->code);
break;
case INSTANCE_STATE_NO_WRITERS:
printf("Found writer for instance; code = %d\n", msg->code);
break;
case INSTANCE_STATE_DISPOSED:
printf("Found reborn instance; code = %d\n", msg->code);
break;
}
states[msg->code] = INSTANCE_STATE_ACTIVE;
}
void keysListener_instance_lost_writers(
keysDataReader *keys_reader,
const struct DDS_SampleInfo *info,
const struct keys *msg)
{
printf("Instance has no writers; code = %d\n", msg->code);
states[msg->code] = INSTANCE_STATE_NO_WRITERS;
}
void keysListener_instance_disposed(
keysDataReader *keys_reader,
const struct DDS_SampleInfo *info,
const struct keys *msg)
{
printf("Instance disposed; code = %d\n", msg->code);
states[msg->code] = INSTANCE_STATE_DISPOSED;
}
/* Called to handle relevant data samples */
void keysListener_handle_data(
keysDataReader *keys_reader,
const struct DDS_SampleInfo *info,
const struct keys *msg)
{
printf("code: %d, x: %d, y: %d\n", msg->code, msg->x, msg->y);
}
int keysListener_key_is_relevant(const struct keys *msg)
{
/* For this example we just care about codes > 0,
which are the ones related to instances ins1 and ins2 .*/
return (msg->code > 0) ? 1 : 0;
}
/**** End changes for Advanced_Keys ****/
/* Delete all entities */
static int subscriber_shutdown(DDS_DomainParticipant *participant)
{
DDS_ReturnCode_t retcode;
int status = 0;
if (participant != NULL) {
retcode = DDS_DomainParticipant_delete_contained_entities(participant);
if (retcode != DDS_RETCODE_OK) {
printf("delete_contained_entities error %d\n", retcode);
status = -1;
}
retcode = DDS_DomainParticipantFactory_delete_participant(
DDS_TheParticipantFactory,
participant);
if (retcode != DDS_RETCODE_OK) {
printf("delete_participant error %d\n", retcode);
status = -1;
}
}
/* RTI Connext provides the finalize_instance() method on
domain participant factory for users who want to release memory used
by the participant factory. Uncomment the following block of code for
clean destruction of the singleton. */
/*
retcode = DDS_DomainParticipantFactory_finalize_instance();
if (retcode != DDS_RETCODE_OK) {
printf("finalize_instance error %d\n", retcode);
status = -1;
}
*/
return status;
}
static int subscriber_main(int domainId, int sample_count)
{
DDS_DomainParticipant *participant = NULL;
DDS_Subscriber *subscriber = NULL;
DDS_Topic *topic = NULL;
struct DDS_DataReaderListener reader_listener =
DDS_DataReaderListener_INITIALIZER;
DDS_DataReader *reader = NULL;
DDS_ReturnCode_t retcode;
const char *type_name = NULL;
int count = 0;
struct DDS_Duration_t poll_period = { 1, 0 };
/* If you want to set the DataReader QoS settings
* programmatically rather than using the XML, you will need to add
* the following line to your code
*/
/*struct DDS_DataReaderQos datareader_qos = DDS_DataReaderQos_INITIALIZER;*/
/* To customize participant QoS, use
the configuration file USER_QOS_PROFILES.xml */
participant = DDS_DomainParticipantFactory_create_participant(
DDS_TheParticipantFactory,
domainId,
&DDS_PARTICIPANT_QOS_DEFAULT,
NULL /* listener */,
DDS_STATUS_MASK_NONE);
if (participant == NULL) {
printf("create_participant error\n");
subscriber_shutdown(participant);
return -1;
}
/* To customize subscriber QoS, use
the configuration file USER_QOS_PROFILES.xml */
subscriber = DDS_DomainParticipant_create_subscriber(
participant,
&DDS_SUBSCRIBER_QOS_DEFAULT,
NULL /* listener */,
DDS_STATUS_MASK_NONE);
if (subscriber == NULL) {
printf("create_subscriber error\n");
subscriber_shutdown(participant);
return -1;
}
/* Register the type before creating the topic */
type_name = keysTypeSupport_get_type_name();
retcode = keysTypeSupport_register_type(participant, type_name);
if (retcode != DDS_RETCODE_OK) {
printf("register_type error %d\n", retcode);
subscriber_shutdown(participant);
return -1;
}
/* To customize topic QoS, use
the configuration file USER_QOS_PROFILES.xml */
topic = DDS_DomainParticipant_create_topic(
participant,
"Example keys",
type_name,
&DDS_TOPIC_QOS_DEFAULT,
NULL /* listener */,
DDS_STATUS_MASK_NONE);
if (topic == NULL) {
printf("create_topic error\n");
subscriber_shutdown(participant);
return -1;
}
/* Set up a data reader listener */
reader_listener.on_requested_deadline_missed =
keysListener_on_requested_deadline_missed;
reader_listener.on_requested_incompatible_qos =
keysListener_on_requested_incompatible_qos;
reader_listener.on_sample_rejected = keysListener_on_sample_rejected;
reader_listener.on_liveliness_changed = keysListener_on_liveliness_changed;
reader_listener.on_sample_lost = keysListener_on_sample_lost;
reader_listener.on_subscription_matched =
keysListener_on_subscription_matched;
reader_listener.on_data_available = keysListener_on_data_available;
/* To customize data reader QoS, use
the configuration file USER_QOS_PROFILES.xml */
reader = DDS_Subscriber_create_datareader(
subscriber,
DDS_Topic_as_topicdescription(topic),
&DDS_DATAREADER_QOS_DEFAULT,
&reader_listener,
DDS_STATUS_MASK_ALL);
/* If you want to set the writer_data_lifecycle QoS settings
* programmatically rather than using the XML, you will need to add
* the following lines to your code and comment out the create_datareader
* call above.
*/
/*
retcode = DDS_Subscriber_get_default_datareader_qos(subscriber,
&datareader_qos); if (retcode != DDS_RETCODE_OK) {
printf("get_default_datareader_qos error\n");
return -1;
}
datareader_qos.ownership.kind = DDS_EXCLUSIVE_OWNERSHIP_QOS;
reader = DDS_Subscriber_create_datareader(
subscriber, DDS_Topic_as_topicdescription(topic),
&datareader_qos, &reader_listener, DDS_STATUS_MASK_ALL);
*/
if (reader == NULL) {
printf("create_datareader error\n");
subscriber_shutdown(participant);
return -1;
}
/* Main loop */
for (count = 0; (sample_count == 0) || (count < sample_count); ++count) {
// printf("keys subscriber sleeping for %d sec...\n",poll_period.sec);
NDDS_Utility_sleep(&poll_period);
}
/* Cleanup and delete all entities */
return subscriber_shutdown(participant);
}
#if defined(RTI_WINCE)
int wmain(int argc, wchar_t **argv)
{
int domainId = 0;
int sample_count = 0; /* infinite loop */
if (argc >= 2) {
domainId = _wtoi(argv[1]);
}
if (argc >= 3) {
sample_count = _wtoi(argv[2]);
}
/* Uncomment this to turn on additional logging
NDDS_Config_Logger_set_verbosity_by_category(
NDDS_Config_Logger_get_instance(),
NDDS_CONFIG_LOG_CATEGORY_API,
NDDS_CONFIG_LOG_VERBOSITY_STATUS_ALL);
*/
return subscriber_main(domainId, sample_count);
}
#elif !(defined(RTI_VXWORKS) && !defined(__RTP__)) && !defined(RTI_PSOS)
int main(int argc, char *argv[])
{
int domainId = 0;
int sample_count = 0; /* infinite loop */
if (argc >= 2) {
domainId = atoi(argv[1]);
}
if (argc >= 3) {
sample_count = atoi(argv[2]);
}
/* Uncomment this to turn on additional logging
NDDS_Config_Logger_set_verbosity_by_category(
NDDS_Config_Logger_get_instance(),
NDDS_CONFIG_LOG_CATEGORY_API,
NDDS_CONFIG_LOG_VERBOSITY_STATUS_ALL);
*/
return subscriber_main(domainId, sample_count);
}
#endif
#ifdef RTI_VX653
const unsigned char *__ctype = NULL;
void usrAppInit()
{
#ifdef USER_APPL_INIT
USER_APPL_INIT; /* for backwards compatibility */
#endif
/* add application specific code here */
taskSpawn(
"sub",
RTI_OSAPI_THREAD_PRIORITY_NORMAL,
0x8,
0x150000,
(FUNCPTR) subscriber_main,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0);
}
#endif
| c |
rticonnextdds-examples | data/projects/rticonnextdds-examples/connext_dds/keyed_data_advanced/c++03/keys_publisher.cxx | /*******************************************************************************
(c) 2005-2015 Copyright, Real-Time Innovations, Inc. All rights reserved.
RTI grants Licensee a license to use, modify, compile, and create derivative
works of the Software. Licensee has the right to distribute object form only
for use with RTI products. The Software is provided "as is", with no warranty
of any type, including any warranty for fitness for any purpose. RTI is under
no obligation to maintain or support the Software. RTI shall not be liable for
any incidental or consequential damages arising out of the use or inability to
use the software.
******************************************************************************/
#include <cstdlib>
#include <iostream>
#include "keys.hpp"
#include <dds/dds.hpp>
using namespace dds::core;
using namespace dds::core::policy;
using namespace rti::core::policy;
using namespace dds::domain;
using namespace dds::topic;
using namespace dds::pub;
using namespace dds::pub::qos;
void publisher_main(int domain_id, int sample_count)
{
// Create a DomainParticipant with default Qos
DomainParticipant participant(domain_id);
// Create a Topic -- and automatically register the type
Topic<keys> topic(participant, "Example keys");
// Create a publisher for both DataWriters.
Publisher publisher(participant);
// Retrieve the default DataWriter QoS profile from USER_QOS_PROFILES.xml
// for the first writer.
DataWriterQos writer1_qos = QosProvider::Default().datawriter_qos();
// If you want to change the DataWriter's QoS programmatically rather than
// using the XML file, uncomment the following lines.
// writer1_qos <<
// WriterDataLifecycle::ManuallyDisposeUnregisteredInstances()
// << Ownership::Exclusive()
// << OwnershipStrength(10)
// << Reliability::Reliable(Duration(60))
// << History::KeepAll()
// << DataWriterProtocol().rtps_reliable_writer(
// RtpsReliableWriterProtocol()
// .min_send_window_size(50)
// .max_send_window_size(50));
// Create a DataWriter with default Qos.
DataWriter<keys> writer1(publisher, topic, writer1_qos);
// Retrieve the keys_Profile_dw2 QoS profile from USER_QOS_PROFILES.xml
// for the second writer.
DataWriterQos writer2_qos = QosProvider::Default().datawriter_qos(
"keys_Library::keys_Profile_dw2");
// If you want to change the DataWriter's QoS programmatically rather than
// using the XML file, uncomment the following lines.
// writer2_qos <<
// WriterDataLifecycle::ManuallyDisposeUnregisteredInstances()
// << Ownership::Exclusive()
// << OwnershipStrength(5);
DataWriter<keys> writer2(publisher, topic, writer2_qos);
std::vector<keys> samples1;
std::vector<InstanceHandle> instance_handles1;
std::vector<bool> samples1_active;
// RTI Connext could examine the key fields each time it needs to determine
// which data-instance is being modified. However, for performance and
// semantic reasons, it is better for your application to declare all the
// data-instances it intends to modify prior to actually writing any
// samples. This is known as registration.
int num_samples = 3;
for (int i = 0; i < num_samples; i++) {
// In order to register the instances, we must set their associated
// keys first.
keys k;
k.code(i);
// Initially, we register only the first sample.
if (i == 0) {
// The keys must have been set before making this call.
std::cout << "----DW1 registering instance " << k.code()
<< std::endl;
instance_handles1.push_back(writer1.register_instance(k));
samples1_active.push_back(true);
} else {
instance_handles1.push_back(InstanceHandle::nil());
samples1_active.push_back(false);
}
// Finally, we modify the data to be sent.
k.x(1);
samples1.push_back(k);
}
keys sample2(samples1[1].code(), 2, 0);
std::cout << "----DW2 registering instance " << sample2.code() << std::endl;
InstanceHandle instance_handle2 = writer2.register_instance(sample2);
bool sample2_active = true;
for (int count = 0; count < sample_count || sample_count == 0; count++) {
rti::util::sleep(Duration(2));
// Control first DataWriter.
if (count == 4) {
// Start sending the second and third instances.
std::cout << "----DW1 registering instance " << samples1[1].code()
<< std::endl
<< "----DW1 registering instance " << samples1[2].code()
<< std::endl;
instance_handles1[1] = writer1.register_instance(samples1[1]);
instance_handles1[2] = writer1.register_instance(samples1[2]);
samples1_active[1] = true;
samples1_active[2] = true;
} else if (count == 8) {
// Dispose the second instance.
std::cout << "----DW1 disposing instance " << samples1[1].code()
<< std::endl;
writer1.dispose_instance(instance_handles1[1]);
samples1_active[1] = false;
} else if (count == 10) {
// Unregister the second instance.
std::cout << "----DW1 unregistering instance " << samples1[1].code()
<< std::endl;
writer1.unregister_instance(instance_handles1[1]);
samples1_active[1] = false;
} else if (count == 12) {
// Unregister the third instance.
std::cout << "----DW1 unregistering instance " << samples1[2].code()
<< std::endl;
writer1.unregister_instance(instance_handles1[2]);
samples1_active[2] = false;
std::cout << "----DW1 re-registering instance "
<< samples1[1].code() << std::endl;
instance_handles1[1] = writer1.register_instance(samples1[1]);
samples1_active[1] = true;
} else if (count == 16) {
std::cout << "----DW1 re-registering instance "
<< samples1[2].code() << std::endl;
instance_handles1[2] = writer1.register_instance(samples1[2]);
samples1_active[2] = true;
}
// Send samples for writer 1
for (int i = 0; i < num_samples; i++) {
if (samples1_active[i]) {
samples1[i].y(count + i * 1000);
std::cout << "DW1 write; code: " << samples1[i].code()
<< ", x: " << samples1[i].x()
<< ", y: " << samples1[i].y() << std::endl;
writer1.write(samples1[i], instance_handles1[i]);
}
}
// Control second DataWriter
if (count == 16) {
// Dispose the instance.
// Since it has lower ownership strength, this does nothing.
std::cout << "----DW2 disposing instance " << sample2.code()
<< std::endl;
writer2.dispose_instance(instance_handle2);
sample2_active = false;
}
// Send sample for writer 2
sample2.y(-count - 1000);
if (sample2_active) {
std::cout << "DW2 write; code: " << sample2.code()
<< ", x: " << sample2.x() << ", y: " << sample2.y()
<< std::endl;
writer2.write(sample2, instance_handle2);
}
}
}
int main(int argc, char *argv[])
{
int domain_id = 0;
int sample_count = 0; // Infinite loop
if (argc >= 2) {
domain_id = atoi(argv[1]);
}
if (argc >= 3) {
sample_count = atoi(argv[2]);
}
// To turn on additional logging, include <rti/config/Logger.hpp> and
// uncomment the following line:
// rti::config::Logger::instance().verbosity(rti::config::Verbosity::STATUS_ALL);
try {
publisher_main(domain_id, sample_count);
} catch (const std::exception &ex) {
// This will catch DDS exceptions
std::cerr << "Exception in publisher_main: " << ex.what() << std::endl;
return -1;
}
return 0;
}
| cxx |
rticonnextdds-examples | data/projects/rticonnextdds-examples/connext_dds/keyed_data_advanced/c++03/keys_subscriber.cxx | /*******************************************************************************
(c) 2005-2015 Copyright, Real-Time Innovations, Inc. All rights reserved.
RTI grants Licensee a license to use, modify, compile, and create derivative
works of the Software. Licensee has the right to distribute object form only
for use with RTI products. The Software is provided "as is", with no warranty
of any type, including any warranty for fitness for any purpose. RTI is under
no obligation to maintain or support the Software. RTI shall not be liable for
any incidental or consequential damages arising out of the use or inability to
use the software.
******************************************************************************/
#include "keys.hpp"
#include <dds/dds.hpp>
#include <iostream>
#include <rti/core/ListenerBinder.hpp>
using namespace dds::core;
using namespace dds::core::policy;
using namespace dds::domain;
using namespace dds::topic;
using namespace dds::sub;
using namespace rti::sub;
using namespace dds::sub::cond;
using namespace dds::sub::qos;
using namespace dds::sub::status;
class KeysReaderListener : public NoOpDataReaderListener<keys> {
public:
void on_data_available(DataReader<keys> &reader)
{
// To read the first instance the handle must be InstanceHandle::nil()
InstanceHandle previous_handle = InstanceHandle::nil();
LoanedSamples<keys> samples;
do {
samples = reader.select().next_instance(previous_handle).take();
// Update the previous handle to read the next instance.
if (samples.length() > 0) {
previous_handle = samples[0].info().instance_handle();
}
for (LoanedSamples<keys>::iterator sampleIt = samples.begin();
sampleIt != samples.end();
++sampleIt) {
const SampleInfo &info = sampleIt->info();
if (info.valid()) {
if (info.state().view_state() == ViewState::new_view()) {
new_instance_found(sampleIt->data());
}
handle_data(sampleIt->data());
} else {
// Since there is not valid data, it may include metadata.
keys key_sample;
reader.key_value(key_sample, info.instance_handle());
// Here we print a message and change the instance state
// if the instance state is
InstanceState inst_state = info.state().instance_state();
if (inst_state == InstanceState::not_alive_no_writers()) {
instance_lost_writers(key_sample);
} else if (
inst_state == InstanceState::not_alive_disposed()) {
instance_disposed(key_sample);
}
}
}
} while (samples.length() > 0);
}
void new_instance_found(const keys &msg)
{
// There are three cases here:
// 1.) truly new instance.
// 2.) instance lost all writers, but now we're getting data again.
// 3.) instance was disposed, but a new one has been created.
//
// We distinguish these cases by examining generation counts, BUT
// note that if the instance resources have been reclaimed, the
// generation counts may be reset to 0.
//
// Instances are eligible for resource cleanup if there are no
// active writers and all samples have been taken. To reliably
// determine which case a 'new' instance falls into, the application
// must store state information on a per-instance basis.
//
// Note that this example assumes that state changes only occur via
// explicit register_instance(), unregister_instance() and dispose()
// calls from the DataWriter. In reality, these changes could also
// occur due to lost liveliness or missed deadlines, so those
// listeners would also need to update the instance state.
int code = msg.code();
// If we don't have any information about it, it's a new instance.
if (sampleState.count(code) == 0) {
std::cout << "New instance found; code = " << code << std::endl;
} else if (sampleState[code] == InstanceState::alive()) {
std::cout << "Error, 'new' already-active instance found; code = "
<< code << std::endl;
} else if (sampleState[code] == InstanceState::not_alive_no_writers()) {
std::cout << "Found writer for instance; code = " << code
<< std::endl;
} else if (sampleState[code] == InstanceState::not_alive_disposed()) {
std::cout << "Found reborn instance; code = " << code << std::endl;
}
sampleState[code] = InstanceState::alive();
}
void instance_lost_writers(const keys &msg)
{
std::cout << "Instance has no writers; code = " << msg.code()
<< std::endl;
sampleState[msg.code()] = InstanceState::not_alive_no_writers();
}
void instance_disposed(const keys &msg)
{
std::cout << "Instance disposed; code = " << msg.code() << std::endl;
sampleState[msg.code()] = InstanceState::not_alive_disposed();
}
void handle_data(const keys &msg)
{
std::cout << "code: " << msg.code() << ", x: " << msg.x()
<< ", y: " << msg.y() << std::endl;
}
private:
std::map<int, InstanceState> sampleState;
};
void subscriber_main(int domain_id, int sample_count)
{
// Create a DomainParticipant with default Qos
DomainParticipant participant(domain_id);
// Create a Topic -- and automatically register the type
Topic<keys> topic(participant, "Example keys");
// Retrieve the default DataWriter QoS, from USER_QOS_PROFILES.xml
DataReaderQos reader_qos = QosProvider::Default().datareader_qos();
// If you want to change the DataReader's QoS programmatically rather than
// using the XML file, uncomment the following lines.
// reader_qos << Ownership::Exclusive();
// Create a DataReader with default Qos (Subscriber created in-line)
DataReader<keys> reader(Subscriber(participant), topic, reader_qos);
// Associate a listener using ListenerBinder, a RAII that will take care of
// setting it to NULL on destruction.
rti::core::ListenerBinder<DataReader<keys> > reader_listener =
rti::core::bind_and_manage_listener(
reader,
new KeysReaderListener,
dds::core::status::StatusMask::all());
// Main loop.
for (int count = 0; (sample_count == 0) || (count < sample_count);
count++) {
rti::util::sleep(Duration(2));
}
}
int main(int argc, char *argv[])
{
int domain_id = 0;
int sample_count = 0; // Infinite loop
if (argc >= 2) {
domain_id = atoi(argv[1]);
}
if (argc >= 3) {
sample_count = atoi(argv[2]);
}
// To turn on additional logging, include <rti/config/Logger.hpp> and
// uncomment the following line:
// rti::config::Logger::instance().verbosity(rti::config::Verbosity::STATUS_ALL);
try {
subscriber_main(domain_id, sample_count);
} catch (const std::exception &ex) {
// This will catch DDS exceptions
std::cerr << "Exception in subscriber_main: " << ex.what() << std::endl;
return -1;
}
return 0;
}
| cxx |
rticonnextdds-examples | data/projects/rticonnextdds-examples/connext_dds/keyed_data_advanced/c++11/application.hpp | /*
* (c) Copyright, Real-Time Innovations, 2020. All rights reserved.
* RTI grants Licensee a license to use, modify, compile, and create derivative
* works of the software solely for use with RTI Connext DDS. Licensee may
* redistribute copies of the software provided that all such copies are subject
* to this license. The software is provided "as is", with no warranty of any
* type, including any warranty for fitness for any purpose. RTI is under no
* obligation to maintain or support the software. RTI shall not be liable for
* any incidental or consequential damages arising out of the use or inability
* to use the software.
*/
#ifndef APPLICATION_HPP
#define APPLICATION_HPP
#include <iostream>
#include <csignal>
#include <dds/core/ddscore.hpp>
namespace application {
// Catch control-C and tell application to shut down
bool shutdown_requested = false;
inline void stop_handler(int)
{
shutdown_requested = true;
std::cout << "preparing to shut down..." << std::endl;
}
inline void setup_signal_handlers()
{
signal(SIGINT, stop_handler);
signal(SIGTERM, stop_handler);
}
enum class ParseReturn { ok, failure, exit };
struct ApplicationArguments {
ParseReturn parse_result;
unsigned int domain_id;
unsigned int sample_count;
rti::config::Verbosity verbosity;
ApplicationArguments(
ParseReturn parse_result_param,
unsigned int domain_id_param,
unsigned int sample_count_param,
rti::config::Verbosity verbosity_param)
: parse_result(parse_result_param),
domain_id(domain_id_param),
sample_count(sample_count_param),
verbosity(verbosity_param)
{
}
};
inline void set_verbosity(
rti::config::Verbosity &verbosity,
int verbosity_value)
{
switch (verbosity_value) {
case 0:
verbosity = rti::config::Verbosity::SILENT;
break;
case 1:
verbosity = rti::config::Verbosity::EXCEPTION;
break;
case 2:
verbosity = rti::config::Verbosity::WARNING;
break;
case 3:
verbosity = rti::config::Verbosity::STATUS_ALL;
break;
default:
verbosity = rti::config::Verbosity::EXCEPTION;
break;
}
}
// Parses application arguments for example.
inline ApplicationArguments parse_arguments(int argc, char *argv[])
{
int arg_processing = 1;
bool show_usage = false;
ParseReturn parse_result = ParseReturn::ok;
unsigned int domain_id = 0;
unsigned int sample_count = (std::numeric_limits<unsigned int>::max)();
rti::config::Verbosity verbosity(rti::config::Verbosity::EXCEPTION);
while (arg_processing < argc) {
if ((argc > arg_processing + 1)
&& (strcmp(argv[arg_processing], "-d") == 0
|| strcmp(argv[arg_processing], "--domain") == 0)) {
domain_id = atoi(argv[arg_processing + 1]);
arg_processing += 2;
} else if (
(argc > arg_processing + 1)
&& (strcmp(argv[arg_processing], "-s") == 0
|| strcmp(argv[arg_processing], "--sample-count") == 0)) {
sample_count = atoi(argv[arg_processing + 1]);
arg_processing += 2;
} else if (
(argc > arg_processing + 1)
&& (strcmp(argv[arg_processing], "-v") == 0
|| strcmp(argv[arg_processing], "--verbosity") == 0)) {
set_verbosity(verbosity, atoi(argv[arg_processing + 1]));
arg_processing += 2;
} else if (
strcmp(argv[arg_processing], "-h") == 0
|| strcmp(argv[arg_processing], "--help") == 0) {
std::cout << "Example application." << std::endl;
show_usage = true;
parse_result = ParseReturn::exit;
break;
} else {
std::cout << "Bad parameter." << std::endl;
show_usage = true;
parse_result = ParseReturn::failure;
break;
}
}
if (show_usage) {
std::cout << "Usage:\n"
" -d, --domain <int> Domain ID this "
"application will\n"
" subscribe in. \n"
" Default: 0\n"
" -s, --sample_count <int> Number of samples to "
"receive before\n"
" cleanly shutting down. \n"
" Default: infinite\n"
" -v, --verbosity <int> How much debugging output "
"to show.\n"
" Range: 0-3 \n"
" Default: 1"
<< std::endl;
}
return ApplicationArguments(
parse_result,
domain_id,
sample_count,
verbosity);
}
} // namespace application
#endif // APPLICATION_HPP | hpp |
rticonnextdds-examples | data/projects/rticonnextdds-examples/connext_dds/keyed_data_advanced/c++11/keys_publisher.cxx | /*******************************************************************************
(c) 2005-2015 Copyright, Real-Time Innovations, Inc. All rights reserved.
RTI grants Licensee a license to use, modify, compile, and create derivative
works of the Software. Licensee has the right to distribute object form only
for use with RTI products. The Software is provided "as is", with no warranty
of any type, including any warranty for fitness for any purpose. RTI is under
no obligation to maintain or support the Software. RTI shall not be liable for
any incidental or consequential damages arising out of the use or inability to
use the software.
******************************************************************************/
#include <dds/pub/ddspub.hpp>
#include <rti/util/util.hpp> // for sleep()
#include <rti/config/Logger.hpp> // for logging
#include "application.hpp" // for command line parsing and ctrl-c
#include "keys.hpp"
void run_publisher_application(
unsigned int domain_id,
unsigned int sample_count)
{
// Create a DomainParticipant with default Qos
dds::domain::DomainParticipant participant(domain_id);
// Create a Topic -- and automatically register the type
dds::topic::Topic<keys> topic(participant, "Example keys");
// Create a publisher for both DataWriters.
dds::pub::Publisher publisher(participant);
// Retrieve the default DataWriter QoS profile from USER_QOS_PROFILES.xml
// for the first writer.
dds::pub::qos::DataWriterQos writer1_qos =
dds::core::QosProvider::Default().datawriter_qos();
// If you want to change the DataWriter's QoS programmatically rather than
// using the XML file, uncomment the following lines.
// writer1_qos <<
// WriterDataLifecycle::ManuallyDisposeUnregisteredInstances()
// << Ownership::Exclusive()
// << OwnershipStrength(10)
// << Reliability::Reliable(Duration(60))
// << History::KeepAll()
// << DataWriterProtocol().rtps_reliable_writer(
// RtpsReliableWriterProtocol()
// .min_send_window_size(50)
// .max_send_window_size(50));
// Create a DataWriter with default Qos.
dds::pub::DataWriter<keys> writer1(publisher, topic, writer1_qos);
// Retrieve the keys_Profile_dw2 QoS profile from USER_QOS_PROFILES.xml
// for the second writer.
dds::pub::qos::DataWriterQos writer2_qos =
dds::core::QosProvider::Default().datawriter_qos(
"keys_Library::keys_Profile_dw2");
// If you want to change the DataWriter's QoS programmatically rather than
// using the XML file, uncomment the following lines.
// writer2_qos <<
// WriterDataLifecycle::ManuallyDisposeUnregisteredInstances()
// << Ownership::Exclusive()
// << OwnershipStrength(5);
dds::pub::DataWriter<keys> writer2(publisher, topic, writer2_qos);
std::vector<keys> samples1;
std::vector<dds::core::InstanceHandle> instance_handles1;
std::vector<bool> samples1_active;
// RTI Connext could examine the key fields each time it needs to determine
// which data-instance is being modified. However, for performance and
// semantic reasons, it is better for your application to declare all the
// data-instances it intends to modify prior to actually writing any
// samples. This is known as registration.
int num_samples = 3;
for (int i = 0; i < num_samples; i++) {
// In order to register the instances, we must set their associated
// keys first.
keys k;
k.code(i);
// Initially, we register only the first sample.
if (i == 0) {
// The keys must have been set before making this call.
std::cout << "----DW1 registering instance " << k.code()
<< std::endl;
instance_handles1.push_back(writer1.register_instance(k));
samples1_active.push_back(true);
} else {
instance_handles1.push_back(dds::core::InstanceHandle::nil());
samples1_active.push_back(false);
}
// Finally, we modify the data to be sent.
k.x(1);
samples1.push_back(k);
}
keys sample2(samples1[1].code(), 2, 0);
std::cout << "----DW2 registering instance " << sample2.code() << std::endl;
dds::core::InstanceHandle instance_handle2 =
writer2.register_instance(sample2);
bool sample2_active = true;
for (unsigned int samples_written = 0;
!application::shutdown_requested && samples_written < sample_count;
samples_written++) {
rti::util::sleep(dds::core::Duration(2));
// Control first DataWriter.
if (samples_written == 4) {
// Start sending the second and third instances.
std::cout << "----DW1 registering instance " << samples1[1].code()
<< std::endl
<< "----DW1 registering instance " << samples1[2].code()
<< std::endl;
instance_handles1[1] = writer1.register_instance(samples1[1]);
instance_handles1[2] = writer1.register_instance(samples1[2]);
samples1_active[1] = true;
samples1_active[2] = true;
} else if (samples_written == 8) {
// Dispose the second instance.
std::cout << "----DW1 disposing instance " << samples1[1].code()
<< std::endl;
writer1.dispose_instance(instance_handles1[1]);
samples1_active[1] = false;
} else if (samples_written == 10) {
// Unregister the second instance.
std::cout << "----DW1 unregistering instance " << samples1[1].code()
<< std::endl;
writer1.unregister_instance(instance_handles1[1]);
samples1_active[1] = false;
} else if (samples_written == 12) {
// Unregister the third instance.
std::cout << "----DW1 unregistering instance " << samples1[2].code()
<< std::endl;
writer1.unregister_instance(instance_handles1[2]);
samples1_active[2] = false;
std::cout << "----DW1 re-registering instance "
<< samples1[1].code() << std::endl;
instance_handles1[1] = writer1.register_instance(samples1[1]);
samples1_active[1] = true;
} else if (samples_written == 16) {
std::cout << "----DW1 re-registering instance "
<< samples1[2].code() << std::endl;
instance_handles1[2] = writer1.register_instance(samples1[2]);
samples1_active[2] = true;
}
// Send samples for writer 1
for (int i = 0; i < num_samples; i++) {
if (samples1_active[i]) {
samples1[i].y(samples_written + i * 1000);
std::cout << "DW1 write; code: " << samples1[i].code()
<< ", x: " << samples1[i].x()
<< ", y: " << samples1[i].y() << std::endl;
writer1.write(samples1[i], instance_handles1[i]);
}
}
// Control second DataWriter
if (samples_written == 16) {
// Dispose the instance.
// Since it has lower ownership strength, this does nothing.
std::cout << "----DW2 disposing instance " << sample2.code()
<< std::endl;
writer2.dispose_instance(instance_handle2);
sample2_active = false;
}
// Send sample for writer 2
sample2.y(-samples_written - 1000);
if (sample2_active) {
std::cout << "DW2 write; code: " << sample2.code()
<< ", x: " << sample2.x() << ", y: " << sample2.y()
<< std::endl;
writer2.write(sample2, instance_handle2);
}
}
}
int main(int argc, char *argv[])
{
using namespace application;
// Parse arguments and handle control-C
auto arguments = parse_arguments(argc, argv);
if (arguments.parse_result == ParseReturn::exit) {
return EXIT_SUCCESS;
} else if (arguments.parse_result == ParseReturn::failure) {
return EXIT_FAILURE;
}
setup_signal_handlers();
// Sets Connext verbosity to help debugging
rti::config::Logger::instance().verbosity(arguments.verbosity);
try {
run_publisher_application(arguments.domain_id, arguments.sample_count);
} catch (const std::exception &ex) {
// This will catch DDS exceptions
std::cerr << "Exception in run_publisher_application(): " << ex.what()
<< std::endl;
return EXIT_FAILURE;
}
// Releases the memory used by the participant factory. Optional at
// application exit
dds::domain::DomainParticipant::finalize_participant_factory();
return EXIT_SUCCESS;
}
| cxx |
rticonnextdds-examples | data/projects/rticonnextdds-examples/connext_dds/keyed_data_advanced/c++11/keys_subscriber.cxx | /*******************************************************************************
(c) 2005-2015 Copyright, Real-Time Innovations, Inc. All rights reserved.
RTI grants Licensee a license to use, modify, compile, and create derivative
works of the Software. Licensee has the right to distribute object form only
for use with RTI products. The Software is provided "as is", with no warranty
of any type, including any warranty for fitness for any purpose. RTI is under
no obligation to maintain or support the Software. RTI shall not be liable for
any incidental or consequential damages arising out of the use or inability to
use the software.
******************************************************************************/
#include <dds/sub/ddssub.hpp>
#include <dds/core/ddscore.hpp>
#include <rti/config/Logger.hpp> // for logging
#include "keys.hpp"
#include "application.hpp" // for command line parsing and ctrl-c
void new_instance_found(
const keys &msg,
std::map<int, dds::sub::status::InstanceState> &sampleState)
{
// There are three cases here:
// 1.) truly new instance.
// 2.) instance lost all writers, but now we're getting data again.
// 3.) instance was disposed, but a new one has been created.
//
// We distinguish these cases by examining generation counts, BUT
// note that if the instance resources have been reclaimed, the
// generation counts may be reset to 0.
//
// Instances are eligible for resource cleanup if there are no
// active writers and all samples have been taken. To reliably
// determine which case a 'new' instance falls into, the application
// must store state information on a per-instance basis.
//
// Note that this example assumes that state changes only occur via
// explicit register_instance(), unregister_instance() and dispose()
// calls from the DataWriter. In reality, these changes could also
// occur due to lost liveliness or missed deadlines, so those
// listeners would also need to update the instance state.
int code = msg.code();
// If we don't have any information about it, it's a new instance.
if (sampleState.count(code) == 0) {
std::cout << "New instance found; code = " << code << std::endl;
} else if (sampleState[code] == dds::sub::status::InstanceState::alive()) {
std::cout << "Error, 'new' already-active instance found; code = "
<< code << std::endl;
} else if (
sampleState[code]
== dds::sub::status::InstanceState::not_alive_no_writers()) {
std::cout << "Found writer for instance; code = " << code << std::endl;
} else if (
sampleState[code]
== dds::sub::status::InstanceState::not_alive_disposed()) {
std::cout << "Found reborn instance; code = " << code << std::endl;
}
sampleState[code] = dds::sub::status::InstanceState::alive();
}
void instance_lost_writers(
const keys &msg,
std::map<int, dds::sub::status::InstanceState> &sampleState)
{
std::cout << "Instance has no writers; code = " << msg.code() << std::endl;
sampleState[msg.code()] =
dds::sub::status::InstanceState::not_alive_no_writers();
}
void instance_disposed(
const keys &msg,
std::map<int, dds::sub::status::InstanceState> &sampleState)
{
std::cout << "Instance disposed; code = " << msg.code() << std::endl;
sampleState[msg.code()] =
dds::sub::status::InstanceState::not_alive_disposed();
}
void handle_data(const keys &msg)
{
std::cout << "code: " << msg.code() << ", x: " << msg.x()
<< ", y: " << msg.y() << std::endl;
}
int process_data(dds::sub::DataReader<keys> reader)
{
int count = 0;
// To read the first instance the handle must be InstanceHandle::nil()
dds::core::InstanceHandle previous_handle =
dds::core::InstanceHandle::nil();
std::map<int, dds::sub::status::InstanceState> sampleState;
dds::sub::LoanedSamples<keys> samples;
do {
samples = reader.select().next_instance(previous_handle).take();
// Update the previous handle to read the next instance.
if (samples.length() > 0) {
previous_handle = samples[0].info().instance_handle();
}
for (const auto &sample : samples) {
const dds::sub::SampleInfo &info = sample.info();
if (info.valid()) {
if (info.state().view_state()
== dds::sub::status::ViewState::new_view()) {
new_instance_found(sample.data(), sampleState);
}
handle_data(sample.data());
} else {
// Since there is not valid data, it may include metadata.
keys key_sample;
reader.key_value(key_sample, info.instance_handle());
// Here we print a message and change the instance state
// if the instance state is
dds::sub::status::InstanceState inst_state =
info.state().instance_state();
if (inst_state
== dds::sub::status::InstanceState::
not_alive_no_writers()) {
instance_lost_writers(key_sample, sampleState);
} else if (
inst_state
== dds::sub::status::InstanceState::
not_alive_disposed()) {
instance_disposed(key_sample, sampleState);
}
}
count++;
}
} while (samples.length() > 0);
return count;
}
void run_subscriber_application(
unsigned int domain_id,
unsigned int sample_count)
{
// Create a DomainParticipant with default Qos
dds::domain::DomainParticipant participant(domain_id);
// Create a Topic -- and automatically register the type
dds::topic::Topic<keys> topic(participant, "Example keys");
// Retrieve the default DataWriter QoS, from USER_QOS_PROFILES.xml
dds::sub::qos::DataReaderQos reader_qos =
dds::core::QosProvider::Default().datareader_qos();
// If you want to change the DataReader's QoS programmatically rather than
// using the XML file, uncomment the following lines.
// reader_qos << Ownership::Exclusive();
// Create a subscriber with default QoS
dds::sub::Subscriber subscriber(participant);
// Create a DataReader with default Qos
dds::sub::DataReader<keys> 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::any(),
[reader, &samples_read]() {
samples_read += process_data(reader);
});
waitset += read_condition;
// Main loop.
while (!application::shutdown_requested && samples_read < sample_count) {
waitset.dispatch(dds::core::Duration(2));
}
}
int main(int argc, char *argv[])
{
using namespace application;
// Parse arguments and handle control-C
auto arguments = parse_arguments(argc, argv);
if (arguments.parse_result == ParseReturn::exit) {
return EXIT_SUCCESS;
} else if (arguments.parse_result == ParseReturn::failure) {
return EXIT_FAILURE;
}
setup_signal_handlers();
// Sets Connext verbosity to help debugging
rti::config::Logger::instance().verbosity(arguments.verbosity);
try {
run_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/property_qos/c++/numbers_common.h | /*******************************************************************************
(c) 2005-2014 Copyright, Real-Time Innovations, Inc. All rights reserved.
RTI grants Licensee a license to use, modify, compile, and create derivative
works of the Software. Licensee has the right to distribute object form only
for use with RTI products. The Software is provided "as is", with no warranty
of any type, including any warranty for fitness for any purpose. RTI is under
no obligation to maintain or support the Software. RTI shall not be liable for
any incidental or consequential damages arising out of the use or inability to
use the software.
******************************************************************************/
#ifndef NUMBERS_COMMON_H
#define NUMBERS_COMMON_H
/* numbers_common.h
*
* This file contains few macros that are used to configure the transport
* in the following files:
* - numbers_publisher.c++
* - numbers_subscriber.c++
*/
/* Comment the following macro to allow compilation on RTI DDS older than 4.2 */
#define USE_NDDS42_API
/* The new value of the transport socket size */
#define NEW_SOCKET_BUFFER_SIZE (65507)
#define NEW_SOCKET_BUFFER_SIZE_STRING ("65507")
/* Creates the domain participant, modifying the transport qos properties
* to increase the send and receive socket buffer size to 64k.
* Returns zero if success, non-zero in case of error.
*/
extern DDSDomainParticipant *numbers_common_create_participant(int domainId);
/* Reads the transport QoS and verify that are correctly set
* Returns zero if success, non-zero in case of error.
*/
extern int numbers_common_verify_qos(DDSDomainParticipant *part);
#endif | h |
rticonnextdds-examples | data/projects/rticonnextdds-examples/connext_dds/property_qos/c++/numbers_common.cxx | /*******************************************************************************
(c) 2005-2014 Copyright, Real-Time Innovations, Inc. All rights reserved.
RTI grants Licensee a license to use, modify, compile, and create derivative
works of the Software. Licensee has the right to distribute object form only
for use with RTI products. The Software is provided "as is", with no warranty
of any type, including any warranty for fitness for any purpose. RTI is under
no obligation to maintain or support the Software. RTI shall not be liable for
any incidental or consequential damages arising out of the use or inability to
use the software.
******************************************************************************/
/* numbers_common.c
*
* This file contains the body of the numbers_common_create_participant
* function.
*/
#include "ndds/ndds_cpp.h"
#include "numbers.h"
#include "numbersSupport.h"
#include <stdio.h>
#include <stdlib.h>
#include "numbers_common.h"
#ifdef USE_NDDS42_API
/************************************************************************
* The following code modifies the transport QoS using the
* PropertyQoS, introduced in RTI DDS 4.2.
************************************************************************/
DDSDomainParticipant *numbers_common_create_participant(int domainId)
{
struct DDS_DomainParticipantQos domainparticipant_qos =
DDS_PARTICIPANT_QOS_DEFAULT;
DDS_ReturnCode_t retcode;
DDSDomainParticipant *part = NULL;
/* To customize participant QoS, use
DDS_DomainParticipantFactory_get_default_participant_qos() */
retcode = DDSTheParticipantFactory->get_default_participant_qos(
domainparticipant_qos);
if (retcode != DDS_RETCODE_OK) {
puts("Error, impossible get default participant qos");
return NULL;
}
/* Set the send socket buffer size */
retcode = DDSPropertyQosPolicyHelper::add_property(
domainparticipant_qos.property,
"dds.transport.UDPv4.builtin.send_socket_buffer_size",
NEW_SOCKET_BUFFER_SIZE_STRING,
DDS_BOOLEAN_FALSE);
if (retcode != DDS_RETCODE_OK) {
printf("Error, impossible add property");
return NULL;
}
/* Set the receive socket buffer size */
retcode = DDSPropertyQosPolicyHelper::add_property(
domainparticipant_qos.property,
"dds.transport.UDPv4.builtin.recv_socket_buffer_size",
NEW_SOCKET_BUFFER_SIZE_STRING,
DDS_BOOLEAN_FALSE);
if (retcode != DDS_RETCODE_OK) {
printf("Error, impossible add property");
return NULL;
}
/* Create the participant */
part = DDSTheParticipantFactory->create_participant(
domainId,
domainparticipant_qos,
NULL /* listener */,
DDS_STATUS_MASK_NONE);
if (part == NULL) {
puts("create_participant error");
return NULL;
}
return part;
}
#else
/************************************************************************
* This is the "classic" method for changing the transport QoS.
*
* It shows how to change QoS without using the
* PropertyQoS, which was added in 4.2.
* This method is still available in 4.2 and later.
*
* To modify the transport QoS using this classic method:
* - turn off auto-enable using the DomainParticipantFactory QoS
* - create the DomainParticipant (disabled)
* - get the transport QoS
* - modify the transport QoS
* - set the new transport QoS
* - enable the DomainParticipant
*
************************************************************************/
DDSDomainParticipant *numbers_common_create_participant(int domainId)
{
struct NDDS_Transport_UDPv4_Property_t transport_UDPv4_property =
NDDS_TRANSPORT_UDPV4_PROPERTY_DEFAULT;
struct DDS_DomainParticipantFactoryQos factory_qos =
DDS_DomainParticipantFactoryQos_INITIALIZER;
DDS_ReturnCode_t retcode;
DDSDomainParticipant *part = NULL;
/* Get the current DomainParticipantFactory QoS */
retcode = DDSTheParticipantFactory->get_qos(factory_qos);
if (retcode != DDS_RETCODE_OK) {
puts("Error, impossible get domain participant factory qos");
return NULL;
}
/* Turn off auto-enabling of entities */
factory_qos.entity_factory.autoenable_created_entities = DDS_BOOLEAN_FALSE;
/* Set the DomainParticipantFactory QoS */
retcode = DDSTheParticipantFactory->set_qos(factory_qos);
if (retcode != DDS_RETCODE_OK) {
puts("Error, impossible set domain participant factory qos");
return NULL;
}
/* Create the DomainParticipant */
part = DDSTheParticipantFactory->create_participant(
domainId,
DDS_PARTICIPANT_QOS_DEFAULT,
NULL /* listener */,
DDS_STATUS_MASK_NONE);
if (part == NULL) {
printf("create_participant error\n");
return NULL;
}
/* Get current transport QoS */
retcode = NDDSTransportSupport::get_builtin_transport_property(
part,
DDS_TRANSPORTBUILTIN_UDPv4,
(struct NDDS_Transport_Property_t &) transport_UDPv4_property);
if (part == NULL) {
printf("NDDS_Transport_Support_get_builtin_transport_property error\n");
return NULL;
}
/* Modify the transport QoS */
transport_UDPv4_property.send_socket_buffer_size = NEW_SOCKET_BUFFER_SIZE;
transport_UDPv4_property.recv_socket_buffer_size = NEW_SOCKET_BUFFER_SIZE;
/* Set the transport QoS */
retcode = NDDSTransportSupport::set_builtin_transport_property(
part,
DDS_TRANSPORTBUILTIN_UDPv4,
(struct NDDS_Transport_Property_t &) transport_UDPv4_property);
if (retcode != DDS_RETCODE_OK) {
printf("NDDS_Transport_Support_set_builtin_transport_property error\n");
return NULL;
}
/* Enable the DomainParticipant */
// retcode = DDS_Entity_enable(DDS_DomainParticipant_as_entity(part));
retcode = part->enable();
if (retcode != DDS_RETCODE_OK) {
printf("DDS_Entity_enable error\n");
return NULL;
}
return part;
}
#endif
/************************************************************************
* The following code read back the transport QoS (accessing it through
* the DDS transport QoS) and verify that are the same as the one set
* before.
************************************************************************/
int numbers_common_verify_qos(DDSDomainParticipant *part)
{
struct NDDS_Transport_UDPv4_Property_t transport_UDPv4_property =
NDDS_TRANSPORT_UDPV4_PROPERTY_DEFAULT;
DDS_ReturnCode_t retcode;
retcode = NDDSTransportSupport::get_builtin_transport_property(
part,
DDS_TRANSPORTBUILTIN_UDPv4,
reinterpret_cast<NDDS_Transport_Property_t &>(
transport_UDPv4_property));
if (retcode != DDS_RETCODE_OK) {
puts("Error, impossible to get builtin transport property");
return -1;
} else {
if (transport_UDPv4_property.send_socket_buffer_size
!= NEW_SOCKET_BUFFER_SIZE) {
puts("Error, send_socket_buffer_size...not modified");
return -1;
} else {
puts("Ok, send_socket_buffer_size....modified");
}
if (transport_UDPv4_property.recv_socket_buffer_size
!= NEW_SOCKET_BUFFER_SIZE) {
puts("Error, recv_socket_buffer_size...not modified");
return -1;
} else {
puts("Ok, recv_socket_buffer_size....modified");
}
}
printf("New UDPv4 send socket buffer size is: %d \n",
transport_UDPv4_property.send_socket_buffer_size);
printf("New UDPv4 receive socket buffer size is: %d \n",
transport_UDPv4_property.recv_socket_buffer_size);
return 0;
}
| cxx |
rticonnextdds-examples | data/projects/rticonnextdds-examples/connext_dds/property_qos/c++/numbers_subscriber.cxx | /*******************************************************************************
(c) 2005-2014 Copyright, Real-Time Innovations, Inc. All rights reserved.
RTI grants Licensee a license to use, modify, compile, and create derivative
works of the Software. Licensee has the right to distribute object form only
for use with RTI products. The Software is provided "as is", with no warranty
of any type, including any warranty for fitness for any purpose. RTI is under
no obligation to maintain or support the Software. RTI shall not be liable for
any incidental or consequential damages arising out of the use or inability to
use the software.
******************************************************************************/
/* numbers_subscriber.cxx
A subscription example
This file is derived from code automatically generated by the rtiddsgen
command:
rtiddsgen -language C++ -example <arch> numbers.idl
Example subscription of type numbers automatically generated by
'rtiddsgen'. To test them follow these steps:
(1) Compile this file and the example publication.
(2) Start the subscription on the same domain used for RTI Data Distribution
Service with the command
objs/<arch>/numbers_subscriber <domain_id> <sample_count>
(3) Start the publication on the same domain used for RTI Data Distribution
with the command
objs/<arch>/numbers_publisher <domain_id> <sample_count>
(4) [Optional] Specify the list of discovery initial peers and
multicast receive addresses via an environment variable or a file
(in the current working directory) called NDDS_DISCOVERY_PEERS.
You can run any number of publishers and subscribers programs, and can
add and remove them dynamically from the domain.
Example:
To run the example application on domain <domain_id>:
On Unix:
objs/<arch>/numbers_publisher <domain_id>
objs/<arch>/numbers_subscriber <domain_id>
On Windows:
objs\<arch>\numbers_publisher <domain_id>
objs\<arch>\numbers_subscriber <domain_id>
modification history
------------ -------
*/
#include "ndds/ndds_cpp.h"
#include "numbers.h"
#include "numbersSupport.h"
#include <stdio.h>
#include <stdlib.h>
#include "numbers_common.cxx"
class numbersListener : public DDSDataReaderListener {
public:
virtual void on_requested_deadline_missed(
DDSDataReader * /*reader*/,
const DDS_RequestedDeadlineMissedStatus & /*status*/)
{
}
virtual void on_requested_incompatible_qos(
DDSDataReader * /*reader*/,
const DDS_RequestedIncompatibleQosStatus & /*status*/)
{
}
virtual void on_sample_rejected(
DDSDataReader * /*reader*/,
const DDS_SampleRejectedStatus & /*status*/)
{
}
virtual void on_liveliness_changed(
DDSDataReader * /*reader*/,
const DDS_LivelinessChangedStatus & /*status*/)
{
}
virtual void on_sample_lost(
DDSDataReader * /*reader*/,
const DDS_SampleLostStatus & /*status*/)
{
}
virtual void on_subscription_matched(
DDSDataReader * /*reader*/,
const DDS_SubscriptionMatchedStatus & /*status*/)
{
}
virtual void on_data_available(DDSDataReader *reader);
};
void numbersListener::on_data_available(DDSDataReader *reader)
{
numbersDataReader *numbers_reader = NULL;
numbersSeq data_seq;
DDS_SampleInfoSeq info_seq;
DDS_ReturnCode_t retcode;
int i;
numbers_reader = numbersDataReader::narrow(reader);
if (numbers_reader == NULL) {
printf("DataReader narrow error\n");
return;
}
retcode = numbers_reader->take(
data_seq,
info_seq,
DDS_LENGTH_UNLIMITED,
DDS_ANY_SAMPLE_STATE,
DDS_ANY_VIEW_STATE,
DDS_ANY_INSTANCE_STATE);
if (retcode == DDS_RETCODE_NO_DATA) {
return;
} else if (retcode != DDS_RETCODE_OK) {
printf("take error %d\n", retcode);
return;
}
for (i = 0; i < data_seq.length(); ++i) {
if (info_seq[i].valid_data) {
numbersTypeSupport::print_data(&data_seq[i]);
}
}
retcode = numbers_reader->return_loan(data_seq, info_seq);
if (retcode != DDS_RETCODE_OK) {
printf("return loan error %d\n", retcode);
}
}
/* Delete all entities */
static int subscriber_shutdown(DDSDomainParticipant *participant)
{
DDS_ReturnCode_t retcode;
int status = 0;
if (participant != NULL) {
retcode = participant->delete_contained_entities();
if (retcode != DDS_RETCODE_OK) {
printf("delete_contained_entities error %d\n", retcode);
status = -1;
}
retcode = DDSTheParticipantFactory->delete_participant(participant);
if (retcode != DDS_RETCODE_OK) {
printf("delete_participant error %d\n", retcode);
status = -1;
}
}
/* RTI Data Distribution Service provides finalize_instance() method on
domain participant factory and finalize() method on type support for
people who want to release memory used by the participant factory and
type support singletons. Uncomment the following block of code for
clean destruction of the singletons. */
/*
numbersTypeSupport::finalize();
retcode = DDSDomainParticipantFactory::finalize_instance();
if (retcode != DDS_RETCODE_OK) {
printf("finalize_instance error %d\n", retcode);
status = -1;
}
*/
return status;
}
extern "C" int subscriber_main(int domainId, int sample_count)
{
DDSDomainParticipant *participant = NULL;
DDSSubscriber *subscriber = NULL;
DDSTopic *topic = NULL;
numbersListener *reader_listener = NULL;
DDSDataReader *reader = NULL;
DDS_ReturnCode_t retcode;
const char *type_name = NULL;
int count = 0;
struct DDS_Duration_t receive_period = { 4, 0 };
int status = 0;
participant = DDSTheParticipantFactory->create_participant(
domainId,
DDS_PARTICIPANT_QOS_DEFAULT,
NULL /* listener */,
DDS_STATUS_MASK_NONE);
if (participant == NULL) {
printf("create_participant error\n");
subscriber_shutdown(participant);
return -1;
}
/* If you want to change the DomainParticipant's QoS programmatically
* rather than using the XML file, you will need to add the following lines
* to your code and comment out the create_participant call above.
*
* In this case, we set the transport settings in the XML by default, but
* in the numbers_common_create_participant call, we set up the transport
* properties either using the Properties QoS or with the transport
* property objects.
*/
/*
participant = numbers_common_create_participant(domainId);
if (participant == NULL) {
subscriber_shutdown(participant);
return -1;
}*/
if (numbers_common_verify_qos(participant) != 0) {
subscriber_shutdown(participant);
return -1;
}
/* To customize subscriber QoS, use
participant->get_default_subscriber_qos() */
subscriber = participant->create_subscriber(
DDS_SUBSCRIBER_QOS_DEFAULT,
NULL /* listener */,
DDS_STATUS_MASK_NONE);
if (subscriber == NULL) {
printf("create_subscriber error\n");
subscriber_shutdown(participant);
return -1;
}
/* Register type before creating topic */
type_name = numbersTypeSupport::get_type_name();
retcode = numbersTypeSupport::register_type(participant, type_name);
if (retcode != DDS_RETCODE_OK) {
printf("register_type error %d\n", retcode);
subscriber_shutdown(participant);
return -1;
}
/* To customize topic QoS, use
participant->get_default_topic_qos() */
topic = participant->create_topic(
"Example numbers",
type_name,
DDS_TOPIC_QOS_DEFAULT,
NULL /* listener */,
DDS_STATUS_MASK_NONE);
if (topic == NULL) {
printf("create_topic error\n");
subscriber_shutdown(participant);
return -1;
}
/* Create data reader listener */
reader_listener = new numbersListener();
if (reader_listener == NULL) {
printf("listener instantiation error\n");
subscriber_shutdown(participant);
return -1;
}
/* To customize data reader QoS, use
subscriber->get_default_datareader_qos() */
reader = subscriber->create_datareader(
topic,
DDS_DATAREADER_QOS_DEFAULT,
reader_listener,
DDS_STATUS_MASK_ALL);
if (reader == NULL) {
printf("create_datareader error\n");
subscriber_shutdown(participant);
delete reader_listener;
return -1;
}
/* Main loop */
for (count = 0; (sample_count == 0) || (count < sample_count); ++count) {
printf("numbers subscriber sleeping for %d sec...\n",
receive_period.sec);
NDDSUtility::sleep(receive_period);
}
/* Delete all entities */
status = subscriber_shutdown(participant);
delete reader_listener;
return status;
}
#if defined(RTI_WINCE)
int wmain(int argc, wchar_t **argv)
{
int domainId = 0;
int sample_count = 0; /* infinite loop */
if (argc >= 2) {
domainId = _wtoi(argv[1]);
}
if (argc >= 3) {
sample_count = _wtoi(argv[2]);
}
/* Uncomment this to turn on additional logging
NDDSConfigLogger::get_instance()->
set_verbosity_by_category(NDDS_CONFIG_LOG_CATEGORY_API,
NDDS_CONFIG_LOG_VERBOSITY_STATUS_ALL);
*/
return subscriber_main(domainId, sample_count);
}
#elif !(defined(RTI_VXWORKS) && !defined(__RTP__)) && !defined(RTI_PSOS)
int main(int argc, char *argv[])
{
int domainId = 0;
int sample_count = 0; /* infinite loop */
if (argc >= 2) {
domainId = atoi(argv[1]);
}
if (argc >= 3) {
sample_count = atoi(argv[2]);
}
/* Uncomment this to turn on additional logging
NDDSConfigLogger::get_instance()->
set_verbosity_by_category(NDDS_CONFIG_LOG_CATEGORY_API,
NDDS_CONFIG_LOG_VERBOSITY_STATUS_ALL);
*/
return subscriber_main(domainId, sample_count);
}
#endif
| cxx |
rticonnextdds-examples | data/projects/rticonnextdds-examples/connext_dds/property_qos/c++/numbers_publisher.cxx | /*******************************************************************************
(c) 2005-2014 Copyright, Real-Time Innovations, Inc. All rights reserved.
RTI grants Licensee a license to use, modify, compile, and create derivative
works of the Software. Licensee has the right to distribute object form only
for use with RTI products. The Software is provided "as is", with no warranty
of any type, including any warranty for fitness for any purpose. RTI is under
no obligation to maintain or support the Software. RTI shall not be liable for
any incidental or consequential damages arising out of the use or inability to
use the software.
******************************************************************************/
/* numbers_publisher.cxx
A publication of data of type numbers
This file is derived from code automatically generated by the rtiddsgen
command:
rtiddsgen -language C++ -example <arch> numbers.idl
Example publication of type numbers automatically generated by
'rtiddsgen'. To test them follow these steps:
(1) Compile this file and the example subscription.
(2) Start the subscription on the same domain used for RTI Data Distribution
with the command
objs/<arch>/numbers_subscriber <domain_id> <sample_count>
(3) Start the publication on the same domain used for RTI Data Distribution
with the command
objs/<arch>/numbers_publisher <domain_id> <sample_count>
(4) [Optional] Specify the list of discovery initial peers and
multicast receive addresses via an environment variable or a file
(in the current working directory) called NDDS_DISCOVERY_PEERS.
You can run any number of publishers and subscribers programs, and can
add and remove them dynamically from the domain.
Example:
To run the example application on domain <domain_id>:
On Unix:
objs/<arch>/numbers_publisher <domain_id> o
objs/<arch>/numbers_subscriber <domain_id>
On Windows:
objs\<arch>\numbers_publisher <domain_id>
objs\<arch>\numbers_subscriber <domain_id>
modification history
------------ -------
*/
#include "ndds/ndds_cpp.h"
#include "numbers.h"
#include "numbersSupport.h"
#include <stdio.h>
#include <stdlib.h>
#include "numbers_common.cxx"
/* Delete all entities */
static int publisher_shutdown(DDSDomainParticipant *participant)
{
DDS_ReturnCode_t retcode;
int status = 0;
if (participant != NULL) {
retcode = participant->delete_contained_entities();
if (retcode != DDS_RETCODE_OK) {
printf("delete_contained_entities error %d\n", retcode);
status = -1;
}
retcode = DDSTheParticipantFactory->delete_participant(participant);
if (retcode != DDS_RETCODE_OK) {
printf("delete_participant error %d\n", retcode);
status = -1;
}
}
/* RTI Data Distribution Service provides finalize_instance() method on
domain participant factory and finalize() method on type support for
people who want to release memory used by the participant factory and
type support singletons. Uncomment the following block of code for
clean destruction of the singletons. */
/*
numbersTypeSupport::finalize();
retcode = DDSDomainParticipantFactory::finalize_instance();
if (retcode != DDS_RETCODE_OK) {
printf("finalize_instance error %d\n", retcode);
status = -1;
}
*/
return status;
}
extern "C" int publisher_main(int domainId, int sample_count)
{
DDSDomainParticipant *participant = NULL;
DDSPublisher *publisher = NULL;
DDSTopic *topic = NULL;
DDSDataWriter *writer = NULL;
numbersDataWriter *numbers_writer = NULL;
numbers *instance = NULL;
DDS_ReturnCode_t retcode;
DDS_InstanceHandle_t instance_handle = DDS_HANDLE_NIL;
const char *type_name = NULL;
int count = 0;
struct DDS_Duration_t send_period = { 4, 0 };
participant = DDSTheParticipantFactory->create_participant(
domainId,
DDS_PARTICIPANT_QOS_DEFAULT,
NULL /* listener */,
DDS_STATUS_MASK_NONE);
if (participant == NULL) {
printf("create_participant error\n");
publisher_shutdown(participant);
return -1;
}
/* If you want to change the DomainParticipant's QoS programmatically
* rather than using the XML file, you will need to add the following lines
* to your code and comment out the create_participant call above.
*
* In this case, we set the transport settings in the XML by default, but
* in the numbers_common_create_participant call, we set up the transport
* properties either using the Properties QoS or with the transport
* property objects.
*/
/*
participant = numbers_common_create_participant(domainId);
if (participant == NULL) {
publisher_shutdown(participant);
return -1;
}
*/
if (numbers_common_verify_qos(participant) != 0) {
publisher_shutdown(participant);
return -1;
}
/* To customize publisher QoS, use
participant->get_default_publisher_qos() */
publisher = participant->create_publisher(
DDS_PUBLISHER_QOS_DEFAULT,
NULL /* listener */,
DDS_STATUS_MASK_NONE);
if (publisher == NULL) {
printf("create_publisher error\n");
publisher_shutdown(participant);
return -1;
}
/* Register type before creating topic */
type_name = numbersTypeSupport::get_type_name();
retcode = numbersTypeSupport::register_type(participant, type_name);
if (retcode != DDS_RETCODE_OK) {
printf("register_type error %d\n", retcode);
publisher_shutdown(participant);
return -1;
}
/* To customize topic QoS, use
participant->get_default_topic_qos() */
topic = participant->create_topic(
"Example numbers",
type_name,
DDS_TOPIC_QOS_DEFAULT,
NULL /* listener */,
DDS_STATUS_MASK_NONE);
if (topic == NULL) {
printf("create_topic error\n");
publisher_shutdown(participant);
return -1;
}
/* To customize data writer QoS, use
publisher->get_default_datawriter_qos() */
writer = publisher->create_datawriter(
topic,
DDS_DATAWRITER_QOS_DEFAULT,
NULL /* listener */,
DDS_STATUS_MASK_NONE);
if (writer == NULL) {
printf("create_datawriter error\n");
publisher_shutdown(participant);
return -1;
}
numbers_writer = numbersDataWriter::narrow(writer);
if (numbers_writer == NULL) {
printf("DataWriter narrow error\n");
publisher_shutdown(participant);
return -1;
}
/* Create data sample for writing */
instance = numbersTypeSupport::create_data();
if (instance == NULL) {
printf("numbersTypeSupport::create_data error\n");
publisher_shutdown(participant);
return -1;
}
/* For data type that has key, if the same instance is going to be
written multiple times, initialize the key here
and register the keyed instance prior to writing */
/*
instance_handle = numbers_writer->register_instance(*instance);
*/
instance->number = 1000;
instance->halfNumber = (float) (instance->number) / 2;
/* Main loop */
for (count = 0; (sample_count == 0) || (count < sample_count); ++count) {
printf("Writing numbers, count %d\n", count);
/* Modify the data to be sent here */
retcode = numbers_writer->write(*instance, instance_handle);
if (retcode != DDS_RETCODE_OK) {
printf("write error %d\n", retcode);
}
instance->number = (DDS_Long) instance->halfNumber;
instance->halfNumber = (float) (instance->number) / 2;
NDDSUtility::sleep(send_period);
}
/*
retcode = numbers_writer->unregister_instance(
*instance, instance_handle);
if (retcode != DDS_RETCODE_OK) {
printf("unregister instance error %d\n", retcode);
}
*/
/* Delete data sample */
retcode = numbersTypeSupport::delete_data(instance);
if (retcode != DDS_RETCODE_OK) {
printf("numbersTypeSupport::delete_data error %d\n", retcode);
}
/* Delete all entities */
return publisher_shutdown(participant);
}
#if defined(RTI_WINCE)
int wmain(int argc, wchar_t **argv)
{
int domainId = 0;
int sample_count = 0; /* infinite loop */
if (argc >= 2) {
domainId = _wtoi(argv[1]);
}
if (argc >= 3) {
sample_count = _wtoi(argv[2]);
}
/* Uncomment this to turn on additional logging
NDDSConfigLogger::get_instance()->
set_verbosity_by_category(NDDS_CONFIG_LOG_CATEGORY_API,
NDDS_CONFIG_LOG_VERBOSITY_STATUS_ALL);
*/
return publisher_main(domainId, sample_count);
}
#elif !(defined(RTI_VXWORKS) && !defined(__RTP__)) && !defined(RTI_PSOS)
int main(int argc, char *argv[])
{
int domainId = 0;
int sample_count = 0; /* infinite loop */
if (argc >= 2) {
domainId = atoi(argv[1]);
}
if (argc >= 3) {
sample_count = atoi(argv[2]);
}
/* Uncomment this to turn on additional logging
NDDSConfigLogger::get_instance()->
set_verbosity_by_category(NDDS_CONFIG_LOG_CATEGORY_API,
NDDS_CONFIG_LOG_VERBOSITY_STATUS_ALL);
*/
return publisher_main(domainId, sample_count);
}
#endif
| cxx |
rticonnextdds-examples | data/projects/rticonnextdds-examples/connext_dds/property_qos/c++98/numbers_common.h | /*******************************************************************************
(c) 2005-2014 Copyright, Real-Time Innovations, Inc. All rights reserved.
RTI grants Licensee a license to use, modify, compile, and create derivative
works of the Software. Licensee has the right to distribute object form only
for use with RTI products. The Software is provided "as is", with no warranty
of any type, including any warranty for fitness for any purpose. RTI is under
no obligation to maintain or support the Software. RTI shall not be liable for
any incidental or consequential damages arising out of the use or inability to
use the software.
******************************************************************************/
#ifndef NUMBERS_COMMON_H
#define NUMBERS_COMMON_H
#include "ndds/ndds_cpp.h"
#include "numbers.h"
#include "numbersSupport.h"
#include <stdio.h>
#include <stdlib.h>
/* numbers_common.h
*
* This file contains few macros that are used to configure the transport
* in the following files:
* - numbers_publisher.c++
* - numbers_subscriber.c++
*/
/* The new value of the transport socket size */
#define NEW_SOCKET_BUFFER_SIZE (65507)
#define NEW_SOCKET_BUFFER_SIZE_STRING ("65507")
/* Creates the domain participant, modifying the transport qos properties
* to increase the send and receive socket buffer size to 64k.
* Returns zero if success, non-zero in case of error.
*/
inline DDSDomainParticipant *numbers_common_create_participant(int domain_id)
{
struct DDS_DomainParticipantQos domainparticipant_qos =
DDS_PARTICIPANT_QOS_DEFAULT;
DDS_ReturnCode_t retcode;
DDSDomainParticipant *part = NULL;
/* To customize participant QoS, use
DDS_DomainParticipantFactory_get_default_participant_qos() */
retcode = DDSTheParticipantFactory->get_default_participant_qos(
domainparticipant_qos);
if (retcode != DDS_RETCODE_OK) {
std::cerr << "Error, impossible get default participant qos\n";
return NULL;
}
/* Set the send socket buffer size */
retcode = DDSPropertyQosPolicyHelper::add_property(
domainparticipant_qos.property,
"dds.transport.UDPv4.builtin.send_socket_buffer_size",
NEW_SOCKET_BUFFER_SIZE_STRING,
DDS_BOOLEAN_FALSE);
if (retcode != DDS_RETCODE_OK) {
std::cerr << "Error, impossible add property\n";
return NULL;
}
/* Set the receive socket buffer size */
retcode = DDSPropertyQosPolicyHelper::add_property(
domainparticipant_qos.property,
"dds.transport.UDPv4.builtin.recv_socket_buffer_size",
NEW_SOCKET_BUFFER_SIZE_STRING,
DDS_BOOLEAN_FALSE);
if (retcode != DDS_RETCODE_OK) {
std::cerr << "Error, impossible add property\n";
return NULL;
}
/* Create the participant */
part = DDSTheParticipantFactory->create_participant(
domain_id,
domainparticipant_qos,
NULL /* listener */,
DDS_STATUS_MASK_NONE);
if (part == NULL) {
std::cerr << "create_participant error\n";
return NULL;
}
return part;
}
/* Reads the transport QoS and verify that are correctly set
* Returns zero if success, non-zero in case of error.
*/
inline int numbers_common_verify_qos(DDSDomainParticipant *part)
{
struct NDDS_Transport_UDPv4_Property_t transport_UDPv4_property =
NDDS_TRANSPORT_UDPV4_PROPERTY_DEFAULT;
DDS_ReturnCode_t retcode;
retcode = NDDSTransportSupport::get_builtin_transport_property(
part,
DDS_TRANSPORTBUILTIN_UDPv4,
reinterpret_cast<NDDS_Transport_Property_t &>(
transport_UDPv4_property));
if (retcode != DDS_RETCODE_OK) {
std::cerr << "Error, impossible to get builtin transport property\n";
return -1;
} else {
if (transport_UDPv4_property.send_socket_buffer_size
!= NEW_SOCKET_BUFFER_SIZE) {
std::cerr << "Error, send_socket_buffer_size...not modified\n";
return -1;
} else {
std::cout << "Ok, send_socket_buffer_size....modified\n";
}
if (transport_UDPv4_property.recv_socket_buffer_size
!= NEW_SOCKET_BUFFER_SIZE) {
std::cerr << "Error, recv_socket_buffer_size...not modified\n";
return -1;
} else {
std::cout << "Ok, recv_socket_buffer_size....modified\n";
}
}
std::cout << "New UDPv4 send socket buffer size is: "
<< transport_UDPv4_property.send_socket_buffer_size << std::endl;
std::cout << "New UDPv4 receive socket buffer size is: "
<< transport_UDPv4_property.recv_socket_buffer_size << std::endl;
return 0;
}
#endif
| h |
rticonnextdds-examples | data/projects/rticonnextdds-examples/connext_dds/property_qos/c++98/numbers_subscriber.cxx | /*******************************************************************************
(c) 2005-2014 Copyright, Real-Time Innovations, Inc. All rights reserved.
RTI grants Licensee a license to use, modify, compile, and create derivative
works of the Software. Licensee has the right to distribute object form only
for use with RTI products. The Software is provided "as is", with no warranty
of any type, including any warranty for fitness for any purpose. RTI is under
no obligation to maintain or support the Software. RTI shall not be liable for
any incidental or consequential damages arising out of the use or inability to
use the software.
******************************************************************************/
#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include "numbers.h"
#include "numbersSupport.h"
#include "ndds/ndds_cpp.h"
#include "application.h"
#include "numbers_common.h"
using namespace application;
static int shutdown_participant(
DDSDomainParticipant *participant,
const char *shutdown_message,
int status);
unsigned int process_data(numbersDataReader *typed_reader)
{
numbersSeq 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) {
numbersTypeSupport::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)
{
struct 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);
}
/* If you want to change the DomainParticipant's QoS programmatically
* rather than using the XML file, you will need to add the following lines
* to your code and comment out the create_participant call above.
*
* In this case, we set the transport settings in the XML by default, but
* in the numbers_common_create_participant call, we set up the transport
* properties either using the Properties QoS or with the transport
* property objects.
*/
if (numbers_common_verify_qos(participant) != 0) {
return shutdown_participant(
participant,
"numbers_common_verify_qos 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 = numbersTypeSupport::get_type_name();
DDS_ReturnCode_t retcode =
numbersTypeSupport::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 numbers",
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 prueba" 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
numbersDataReader *typed_reader = numbersDataReader::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;
std::cout << "numbers subscriber sleeping for " << wait_timeout.sec
<< " sec...\n";
// 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);
}
}
// 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/property_qos/c++98/numbers_publisher.cxx | /*******************************************************************************
(c) 2005-2014 Copyright, Real-Time Innovations, Inc. All rights reserved.
RTI grants Licensee a license to use, modify, compile, and create derivative
works of the Software. Licensee has the right to distribute object form only
for use with RTI products. The Software is provided "as is", with no warranty
of any type, including any warranty for fitness for any purpose. RTI is under
no obligation to maintain or support the Software. RTI shall not be liable for
any incidental or consequential damages arising out of the use or inability to
use the software.
******************************************************************************/
#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include "numbers.h"
#include "numbersSupport.h"
#include "ndds/ndds_cpp.h"
#include "application.h"
#include "numbers_common.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)
{
struct DDS_Duration_t send_period = { 4, 0 };
// Start communicating in a domain, usually one participant per application
DDSDomainParticipant *participant =
DDSTheParticipantFactory->create_participant(
domain_id,
DDS_PARTICIPANT_QOS_DEFAULT,
NULL /* listener */,
DDS_STATUS_MASK_NONE);
if (participant == NULL) {
return shutdown_participant(
participant,
"create_participant error",
EXIT_FAILURE);
}
/* If you want to change the DomainParticipant's QoS programmatically
* rather than using the XML file, you will need to add the following lines
* to your code and comment out the create_participant call above.
*
* In this case, we set the transport settings in the XML by default, but
* in the numbers_common_create_participant call, we set up the transport
* properties either using the Properties QoS or with the transport
* property objects.
*/
if (numbers_common_verify_qos(participant) != 0) {
return shutdown_participant(
participant,
"numbers_common_verify_qos 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 = numbersTypeSupport::get_type_name();
DDS_ReturnCode_t retcode =
numbersTypeSupport::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 numbers",
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 numbers" Topic
DDSDataWriter *untyped_writer = publisher->create_datawriter(
topic,
DDS_DATAWRITER_QOS_DEFAULT,
NULL /* listener */,
DDS_STATUS_MASK_NONE);
if (untyped_writer == NULL) {
return shutdown_participant(
participant,
"create_datawriter error",
EXIT_FAILURE);
}
// Narrow casts from an untyped DataWriter to a writer of your type
numbersDataWriter *typed_writer = numbersDataWriter::narrow(untyped_writer);
if (typed_writer == NULL) {
return shutdown_participant(
participant,
"DataWriter narrow error",
EXIT_FAILURE);
}
// Create data for writing, allocating all members
numbers *data = numbersTypeSupport::create_data();
if (data == NULL) {
return shutdown_participant(
participant,
"numbersTypeSupport::create_data error",
EXIT_FAILURE);
}
DDS_InstanceHandle_t instance_handle = DDS_HANDLE_NIL;
/* For data type that has key, if the same instance is going to be
written multiple times, initialize the key here
and register the keyed instance prior to writing */
/*
instance_handle = typed_writer->register_instance(*data);
*/
data->number = 1000;
data->halfNumber = (float) (data->number) / 2;
// Main loop, write data
for (unsigned int samples_written = 0;
!shutdown_requested && samples_written < sample_count;
++samples_written) {
std::cout << "Writing numbers, count " << samples_written << std::endl;
/* Modify the data to be sent here */
retcode = typed_writer->write(*data, instance_handle);
if (retcode != DDS_RETCODE_OK) {
std::cerr << "write error " << retcode << std::endl;
}
data->number = (DDS_Long) data->halfNumber;
data->halfNumber = (float) (data->number) / 2;
NDDSUtility::sleep(send_period);
}
/*
retcode = typed_writer->unregister_instance(
*data, instance_handle);
if (retcode != DDS_RETCODE_OK) {
std::cerr << "unregister instance error " << retcode << std::endl;
}
*/
/* Delete data sample */
retcode = numbersTypeSupport::delete_data(data);
if (retcode != DDS_RETCODE_OK) {
std::cerr << "numbersTypeSupport::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/property_qos/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/property_qos/c/numbers_publisher.c | /*******************************************************************************
(c) 2005-2014 Copyright, Real-Time Innovations, Inc. All rights reserved.
RTI grants Licensee a license to use, modify, compile, and create derivative
works of the Software. Licensee has the right to distribute object form only
for use with RTI products. The Software is provided "as is", with no warranty
of any type, including any warranty for fitness for any purpose. RTI is under
no obligation to maintain or support the Software. RTI shall not be liable for
any incidental or consequential damages arising out of the use or inability to
use the software.
******************************************************************************/
/* numbers_publisher.c
A publication of data of type numbers
This file is derived from code automatically generated by the rtiddsgen
command:
rtiddsgen -language C -example <arch> numbers.idl
Example publication of type numbers automatically generated by
'rtiddsgen'. To test them follow these steps:
(1) Compile this file and the example subscription.
(2) Start the subscription on the same domain used for RTI Data Distribution
Service with the command
objs/<arch>/numbers_subscriber <domain_id> <sample_count>
(3) Start the publication on the same domain used for RTI Data Distribution
Service with the command
objs/<arch>/numbers_publisher <domain_id> <sample_count>
(4) [Optional] Specify the list of discovery initial peers and
multicast receive addresses via an environment variable or a file
(in the current working directory) called NDDS_DISCOVERY_PEERS.
You can run any number of publishers and subscribers programs, and can
add and remove them dynamically from the domain.
Example:
To run the example application on domain <domain_id>:
On Unix:
objs/<arch>/numbers_publisher <domain_id>
objs/<arch>/numbers_subscriber <domain_id>
On Windows:
objs\<arch>\numbers_publisher <domain_id>
objs\<arch>\numbers_subscriber <domain_id>
modification history
------------ -------
*/
#include "ndds/ndds_c.h"
#include "numbers.h"
#include "numbersSupport.h"
#include <stdio.h>
#include <stdlib.h>
#include "numbers_common.c"
/* Delete all entities */
static int publisher_shutdown(DDS_DomainParticipant *participant)
{
DDS_ReturnCode_t retcode;
int status = 0;
if (participant != NULL) {
retcode = DDS_DomainParticipant_delete_contained_entities(participant);
if (retcode != DDS_RETCODE_OK) {
printf("delete_contained_entities error %d\n", retcode);
status = -1;
}
retcode = DDS_DomainParticipantFactory_delete_participant(
DDS_TheParticipantFactory,
participant);
if (retcode != DDS_RETCODE_OK) {
printf("delete_participant error %d\n", retcode);
status = -1;
}
}
/* RTI Data Distribution Service provides finalize_instance() method on
domain participant factory and finalize() method on type support for
people who want to release memory used by the participant factory and
type support singletons. Uncomment the following block of code for
clean destruction of the singletons. */
/*
numbersTypeSupport_finalize();
retcode = DDS_DomainParticipantFactory_finalize_instance();
if (retcode != DDS_RETCODE_OK) {
printf("finalize_instance error %d\n", retcode);
status = -1;
}
*/
return status;
}
static int publisher_main(int domainId, int sample_count)
{
DDS_DomainParticipant *participant = NULL;
DDS_Publisher *publisher = NULL;
DDS_Topic *topic = NULL;
DDS_DataWriter *writer = NULL;
numbersDataWriter *numbers_writer = NULL;
numbers *instance = NULL;
DDS_ReturnCode_t retcode;
DDS_InstanceHandle_t instance_handle = DDS_HANDLE_NIL;
const char *type_name = NULL;
int count = 0;
struct DDS_Duration_t send_period = { 4, 0 };
/* To customize participant QoS, use
the configuration file USER_QOS_PROFILES.xml */
participant = DDS_DomainParticipantFactory_create_participant(
DDS_TheParticipantFactory,
domainId,
&DDS_PARTICIPANT_QOS_DEFAULT,
NULL /* listener */,
DDS_STATUS_MASK_NONE);
if (participant == NULL) {
printf("create_participant error\n");
publisher_shutdown(participant);
return -1;
}
/* If you want to change the DomainParticipant's QoS programmatically
* rather than using the XML file, you will need to add the following lines
* to your code and comment out the create_participant call above.
*
* In this case, we set the transport settings in the XML by default, but
* in the numbers_common_create_participant call, we set up the transport
* properties either using the Properties QoS or with the transport
* property objects.
*/
/*participant = numbers_common_create_participant(domainId);
if (participant == NULL) {
publisher_shutdown(participant);
return -1;
}*/
if (numbers_common_verify_qos(participant) != 0) {
publisher_shutdown(participant);
return -1;
}
/* To customize publisher QoS, use
DDS_DomainParticipant_get_default_publisher_qos() */
publisher = DDS_DomainParticipant_create_publisher(
participant,
&DDS_PUBLISHER_QOS_DEFAULT,
NULL /* listener */,
DDS_STATUS_MASK_NONE);
if (publisher == NULL) {
printf("create_publisher error\n");
publisher_shutdown(participant);
return -1;
}
/* Register type before creating topic */
type_name = numbersTypeSupport_get_type_name();
retcode = numbersTypeSupport_register_type(participant, type_name);
if (retcode != DDS_RETCODE_OK) {
printf("register_type error %d\n", retcode);
publisher_shutdown(participant);
return -1;
}
/* To customize topic QoS, use
DDS_DomainParticipant_get_default_topic_qos() */
topic = DDS_DomainParticipant_create_topic(
participant,
"Example numbers",
type_name,
&DDS_TOPIC_QOS_DEFAULT,
NULL /* listener */,
DDS_STATUS_MASK_NONE);
if (topic == NULL) {
printf("create_topic error\n");
publisher_shutdown(participant);
return -1;
}
/* To customize data writer QoS, use
DDS_Publisher_get_default_datawriter_qos() */
writer = DDS_Publisher_create_datawriter(
publisher,
topic,
&DDS_DATAWRITER_QOS_DEFAULT,
NULL /* listener */,
DDS_STATUS_MASK_NONE);
if (writer == NULL) {
printf("create_datawriter error\n");
publisher_shutdown(participant);
return -1;
}
numbers_writer = numbersDataWriter_narrow(writer);
if (numbers_writer == NULL) {
printf("DataWriter narrow error\n");
publisher_shutdown(participant);
return -1;
}
/* Create data sample for writing */
instance = numbersTypeSupport_create_data_ex(DDS_BOOLEAN_TRUE);
if (instance == NULL) {
printf("numbersTypeSupport_create_data error\n");
publisher_shutdown(participant);
return -1;
}
/* For data type that has key, if the same instance is going to be
written multiple times, initialize the key here
and register the keyed instance prior to writing */
/*
instance_handle = numbersDataWriter_register_instance(
numbers_writer, instance);
*/
instance->number = 1000;
instance->halfNumber = (float) (instance->number) / 2;
/* Main loop */
for (count = 0; (sample_count == 0) || (count < sample_count); ++count) {
printf("Writing numbers, count %d\n", count);
/* Modify the data to be written here */
/* Write data */
retcode = numbersDataWriter_write(
numbers_writer,
instance,
&instance_handle);
if (retcode != DDS_RETCODE_OK) {
printf("write error %d\n", retcode);
}
instance->number = instance->halfNumber;
instance->halfNumber = (float) (instance->number) / 2;
NDDS_Utility_sleep(&send_period);
}
/*
retcode = numbersDataWriter_unregister_instance(
numbers_writer, instance, &instance_handle);
if (retcode != DDS_RETCODE_OK) {
printf("unregister instance error %d\n", retcode);
}
*/
/* Delete data sample */
retcode = numbersTypeSupport_delete_data_ex(instance, DDS_BOOLEAN_TRUE);
if (retcode != DDS_RETCODE_OK) {
printf("numbersTypeSupport_delete_data error %d\n", retcode);
}
/* Cleanup and delete delete all entities */
return publisher_shutdown(participant);
}
#if defined(RTI_WINCE)
int wmain(int argc, wchar_t **argv)
{
int domainId = 0;
int sample_count = 0; /* infinite loop */
if (argc >= 2) {
domainId = _wtoi(argv[1]);
}
if (argc >= 3) {
sample_count = _wtoi(argv[2]);
}
/* Uncomment this to turn on additional logging
NDDS_Config_Logger_set_verbosity_by_category(
NDDS_Config_Logger_get_instance(),
NDDS_CONFIG_LOG_CATEGORY_API,
NDDS_CONFIG_LOG_VERBOSITY_STATUS_ALL);
*/
return publisher_main(domainId, sample_count);
}
#elif !(defined(RTI_VXWORKS) && !defined(__RTP__)) && !defined(RTI_PSOS)
int main(int argc, char *argv[])
{
int domainId = 0;
int sample_count = 0; /* infinite loop */
if (argc >= 2) {
domainId = atoi(argv[1]);
}
if (argc >= 3) {
sample_count = atoi(argv[2]);
}
/* Uncomment this to turn on additional logging
NDDS_Config_Logger_set_verbosity_by_category(
NDDS_Config_Logger_get_instance(),
NDDS_CONFIG_LOG_CATEGORY_API,
NDDS_CONFIG_LOG_VERBOSITY_STATUS_ALL);
*/
return publisher_main(domainId, sample_count);
}
#endif
| c |
rticonnextdds-examples | data/projects/rticonnextdds-examples/connext_dds/property_qos/c/numbers_common.h | /*******************************************************************************
(c) 2005-2014 Copyright, Real-Time Innovations, Inc. All rights reserved.
RTI grants Licensee a license to use, modify, compile, and create derivative
works of the Software. Licensee has the right to distribute object form only
for use with RTI products. The Software is provided "as is", with no warranty
of any type, including any warranty for fitness for any purpose. RTI is under
no obligation to maintain or support the Software. RTI shall not be liable for
any incidental or consequential damages arising out of the use or inability to
use the software.
******************************************************************************/
/* numbers_common.h
*
* This file contains few macros that are used to configure the transport
* in the following files:
* - numbers_publisher.c
* - numbers_subscriber.c
*/
/* Comment the following macro to allow compilation on RTI DDS older than 4.2 */
//#define USE_NDDS42_API
/* The new value of the transport socket size */
#define NEW_SOCKET_BUFFER_SIZE (65507)
#define NEW_SOCKET_BUFFER_SIZE_STRING ("65507")
/* Creates the domain participant, modifying the transport qos properties
* to increase the send and receive socket buffer size to 64k.
* Returns zero if success, non-zero in case of error.
*/
extern DDS_DomainParticipant *numbers_common_create_participant(int domainId);
/* Reads the transport QoS and verify that are correctly set
* Returns zero if success, non-zero in case of error.
*/
extern int numbers_common_verify_qos(DDS_DomainParticipant *part);
| h |
rticonnextdds-examples | data/projects/rticonnextdds-examples/connext_dds/property_qos/c/numbers_common.c | /*******************************************************************************
(c) 2005-2014 Copyright, Real-Time Innovations, Inc. All rights reserved.
RTI grants Licensee a license to use, modify, compile, and create derivative
works of the Software. Licensee has the right to distribute object form only
for use with RTI products. The Software is provided "as is", with no warranty
of any type, including any warranty for fitness for any purpose. RTI is under
no obligation to maintain or support the Software. RTI shall not be liable for
any incidental or consequential damages arising out of the use or inability to
use the software.
******************************************************************************/
/* numbers_common.c
*
* This file contains the body of the numbers_common_create_participant
* function.
*/
#include "ndds/ndds_c.h"
#include "numbers.h"
#include "numbersSupport.h"
#include <stdio.h>
#include <stdlib.h>
#include "numbers_common.h"
#ifdef USE_NDDS42_API
/************************************************************************
* The following code modifies the transport QoS using the
* PropertyQoS, introduced in RTI DDS 4.2.
************************************************************************/
DDS_DomainParticipant *numbers_common_create_participant(int domainId)
{
struct NDDS_Transport_UDPv4_Property_t transport_UDPv4_property =
NDDS_TRANSPORT_UDPV4_PROPERTY_DEFAULT;
struct DDS_DomainParticipantQos domainparticipant_qos =
DDS_DomainParticipantQos_INITIALIZER;
struct DDS_PropertySeq *propertySeq = NULL;
struct DDS_Property_t *propertyElement = NULL;
DDS_ReturnCode_t retcode;
DDS_DomainParticipant *part = NULL;
/* To customize participant QoS, use
DDS_DomainParticipantFactory_get_default_participant_qos() */
retcode = DDS_DomainParticipantFactory_get_default_participant_qos(
DDS_TheParticipantFactory,
&domainparticipant_qos);
if (retcode != DDS_RETCODE_OK) {
puts("Error, impossible get default participant qos");
return NULL;
}
propertySeq = &domainparticipant_qos.property.value;
DDS_PropertySeq_ensure_length(propertySeq, 2, 2);
/* Set the send socket buffer size */
propertyElement = DDS_PropertySeq_get_reference(propertySeq, 0);
propertyElement->name = DDS_String_dup(
"dds.transport.UDPv4.builtin.send_socket_buffer_size");
propertyElement->value = DDS_String_dup(NEW_SOCKET_BUFFER_SIZE_STRING);
propertyElement->propagate = DDS_BOOLEAN_FALSE;
/* Set the send socket buffer size */
propertyElement = DDS_PropertySeq_get_reference(propertySeq, 1);
propertyElement->name = DDS_String_dup(
"dds.transport.UDPv4.builtin.recv_socket_buffer_size");
propertyElement->value = DDS_String_dup(NEW_SOCKET_BUFFER_SIZE_STRING);
propertyElement->propagate = DDS_BOOLEAN_FALSE;
/* Create the participant */
part = DDS_DomainParticipantFactory_create_participant(
DDS_TheParticipantFactory,
domainId,
&domainparticipant_qos,
NULL /* listener */,
DDS_STATUS_MASK_NONE);
if (part == NULL) {
puts("create_participant error");
return NULL;
}
return part;
}
#else
/************************************************************************
* This is the "classic" method for changing the transport QoS.
*
* It shows how to change QoS without using the
* PropertyQoS, which was added in 4.2.
* This method is still available in 4.2 and later.
*
* To modify the transport QoS using this classic method:
* - turn off auto-enable using the DomainParticipantFactory QoS
* - create the DomainParticipant (disabled)
* - get the transport QoS
* - modify the transport QoS
* - set the new transport QoS
* - enable the DomainParticipant
*
************************************************************************/
DDS_DomainParticipant *numbers_common_create_participant(int domainId)
{
struct NDDS_Transport_UDPv4_Property_t transport_UDPv4_property =
NDDS_TRANSPORT_UDPV4_PROPERTY_DEFAULT;
struct DDS_DomainParticipantFactoryQos factory_qos =
DDS_DomainParticipantFactoryQos_INITIALIZER;
DDS_ReturnCode_t retcode;
DDS_DomainParticipant *part = NULL;
/* Get the DomainParticipantFactory QoS */
retcode = DDS_DomainParticipantFactory_get_qos(
DDS_TheParticipantFactory,
&factory_qos);
if (retcode != DDS_RETCODE_OK) {
puts("Error, impossible get domain participant factory qos");
return NULL;
}
/* Turn off auto-enabling of entities */
factory_qos.entity_factory.autoenable_created_entities = DDS_BOOLEAN_FALSE;
/* Set the DomainParticipantFactory QoS */
retcode = DDS_DomainParticipantFactory_set_qos(
DDS_TheParticipantFactory,
&factory_qos);
if (retcode != DDS_RETCODE_OK) {
puts("Error, impossible set domain participant factory qos");
return NULL;
}
/* Create the DomainParticipant */
part = DDS_DomainParticipantFactory_create_participant(
DDS_TheParticipantFactory,
domainId,
&DDS_PARTICIPANT_QOS_DEFAULT,
NULL /* listener */,
DDS_STATUS_MASK_NONE);
if (part == NULL) {
printf("create_participant error\n");
return NULL;
}
/* Get current transport QoS */
retcode = NDDS_Transport_Support_get_builtin_transport_property(
part,
DDS_TRANSPORTBUILTIN_UDPv4,
(struct NDDS_Transport_Property_t *) &transport_UDPv4_property);
if (retcode != DDS_RETCODE_OK || part == NULL) {
printf("NDDS_Transport_Support_get_builtin_transport_property error\n");
return NULL;
}
/* Modify the transport QoS */
transport_UDPv4_property.send_socket_buffer_size = NEW_SOCKET_BUFFER_SIZE;
transport_UDPv4_property.recv_socket_buffer_size = NEW_SOCKET_BUFFER_SIZE;
/* Set the transport QoS */
retcode = NDDS_Transport_Support_set_builtin_transport_property(
part,
DDS_TRANSPORTBUILTIN_UDPv4,
(struct NDDS_Transport_Property_t *) &transport_UDPv4_property);
if (retcode != DDS_RETCODE_OK) {
printf("NDDS_Transport_Support_set_builtin_transport_property error\n");
return NULL;
}
/* Enable the DomainParticipant */
retcode = DDS_Entity_enable(DDS_DomainParticipant_as_entity(part));
if (retcode != DDS_RETCODE_OK) {
printf("DDS_Entity_enable error\n");
return NULL;
}
return part;
}
#endif
/************************************************************************
* The following code read back the transport QoS (accessing it through
* the DDS transport QoS) and verify that are the same as the one set
* before.
************************************************************************/
int numbers_common_verify_qos(DDS_DomainParticipant *part)
{
struct NDDS_Transport_UDPv4_Property_t transport_UDPv4_property =
NDDS_TRANSPORT_UDPV4_PROPERTY_DEFAULT;
DDS_ReturnCode_t retcode;
retcode = NDDS_Transport_Support_get_builtin_transport_property(
part,
DDS_TRANSPORTBUILTIN_UDPv4,
(struct NDDS_Transport_Property_t *) &transport_UDPv4_property);
if (retcode != DDS_RETCODE_OK) {
puts("Error, impossible to get builtin transport property");
return -1;
} else {
if (transport_UDPv4_property.send_socket_buffer_size
!= NEW_SOCKET_BUFFER_SIZE) {
puts("Error, send_socket_buffer_size...not modified");
return -1;
} else {
puts("Ok, send_socket_buffer_size....modified");
}
if (transport_UDPv4_property.recv_socket_buffer_size
!= NEW_SOCKET_BUFFER_SIZE) {
puts("Error, recv_socket_buffer_size...not modified");
return -1;
} else {
puts("Ok, recv_socket_buffer_size....modified");
}
}
printf("New UDPv4 send socket buffer size is: %d \n",
transport_UDPv4_property.send_socket_buffer_size);
printf("New UDPv4 receive socket buffer size is: %d \n",
transport_UDPv4_property.recv_socket_buffer_size);
return 0;
}
| c |
rticonnextdds-examples | data/projects/rticonnextdds-examples/connext_dds/property_qos/c/numbers_subscriber.c | /*******************************************************************************
(c) 2005-2014 Copyright, Real-Time Innovations, Inc. All rights reserved.
RTI grants Licensee a license to use, modify, compile, and create derivative
works of the Software. Licensee has the right to distribute object form only
for use with RTI products. The Software is provided "as is", with no warranty
of any type, including any warranty for fitness for any purpose. RTI is under
no obligation to maintain or support the Software. RTI shall not be liable for
any incidental or consequential damages arising out of the use or inability to
use the software.
******************************************************************************/
/* numbers_subscriber.c
A subscription example
This file is derived from code automatically generated by the rtiddsgen
command:
rtiddsgen -language C -example <arch> numbers.idl
Example subscription of type numbers automatically generated by
'rtiddsgen'. To test them follow these steps:
(1) Compile this file and the example publication.
(2) Start the subscription on the same domain used for RTI Data Distribution
Service with the command
objs/<arch>/numbers_subscriber <domain_id> <sample_count>
(3) Start the publication on the same domain used for RTI Data Distribution
Service with the command
objs/<arch>/numbers_publisher <domain_id> <sample_count>
(4) [Optional] Specify the list of discovery initial peers and
multicast receive addresses via an environment variable or a file
(in the current working directory) called NDDS_DISCOVERY_PEERS.
You can run any number of publishers and subscribers programs, and can
add and remove them dynamically from the domain.
Example:
To run the example application on domain <domain_id>:
On Unix:
objs/<arch>/numbers_publisher <domain_id>
objs/<arch>/numbers_subscriber <domain_id>
On Windows:
objs\<arch>\numbers_publisher <domain_id>
objs\<arch>\numbers_subscriber <domain_id>
modification history
------------ -------
*/
#include "ndds/ndds_c.h"
#include "numbers.h"
#include "numbersSupport.h"
#include <stdio.h>
#include <stdlib.h>
#include "numbers_common.c"
void numbersListener_on_requested_deadline_missed(
void *listener_data,
DDS_DataReader *reader,
const struct DDS_RequestedDeadlineMissedStatus *status)
{
}
void numbersListener_on_requested_incompatible_qos(
void *listener_data,
DDS_DataReader *reader,
const struct DDS_RequestedIncompatibleQosStatus *status)
{
}
void numbersListener_on_sample_rejected(
void *listener_data,
DDS_DataReader *reader,
const struct DDS_SampleRejectedStatus *status)
{
}
void numbersListener_on_liveliness_changed(
void *listener_data,
DDS_DataReader *reader,
const struct DDS_LivelinessChangedStatus *status)
{
}
void numbersListener_on_sample_lost(
void *listener_data,
DDS_DataReader *reader,
const struct DDS_SampleLostStatus *status)
{
}
void numbersListener_on_subscription_matched(
void *listener_data,
DDS_DataReader *reader,
const struct DDS_SubscriptionMatchedStatus *status)
{
}
void numbersListener_on_data_available(
void *listener_data,
DDS_DataReader *reader)
{
numbersDataReader *numbers_reader = NULL;
struct numbersSeq data_seq = DDS_SEQUENCE_INITIALIZER;
struct DDS_SampleInfoSeq info_seq = DDS_SEQUENCE_INITIALIZER;
DDS_ReturnCode_t retcode;
int i;
numbers_reader = numbersDataReader_narrow(reader);
if (numbers_reader == NULL) {
printf("DataReader narrow error\n");
return;
}
retcode = numbersDataReader_take(
numbers_reader,
&data_seq,
&info_seq,
DDS_LENGTH_UNLIMITED,
DDS_ANY_SAMPLE_STATE,
DDS_ANY_VIEW_STATE,
DDS_ANY_INSTANCE_STATE);
if (retcode == DDS_RETCODE_NO_DATA) {
return;
} else if (retcode != DDS_RETCODE_OK) {
printf("take error %d\n", retcode);
return;
}
for (i = 0; i < numbersSeq_get_length(&data_seq); ++i) {
if (DDS_SampleInfoSeq_get_reference(&info_seq, i)->valid_data) {
numbersTypeSupport_print_data(
numbersSeq_get_reference(&data_seq, i));
}
}
retcode =
numbersDataReader_return_loan(numbers_reader, &data_seq, &info_seq);
if (retcode != DDS_RETCODE_OK) {
printf("return loan error %d\n", retcode);
}
}
/* Delete all entities */
static int subscriber_shutdown(DDS_DomainParticipant *participant)
{
DDS_ReturnCode_t retcode;
int status = 0;
if (participant != NULL) {
retcode = DDS_DomainParticipant_delete_contained_entities(participant);
if (retcode != DDS_RETCODE_OK) {
printf("delete_contained_entities error %d\n", retcode);
status = -1;
}
retcode = DDS_DomainParticipantFactory_delete_participant(
DDS_TheParticipantFactory,
participant);
if (retcode != DDS_RETCODE_OK) {
printf("delete_participant error %d\n", retcode);
status = -1;
}
}
/* RTI Data Distribution Service provides finalize_instance() method on
domain participant factory and finalize() method on type support for
people who want to release memory used by the participant factory and
type support singletons. Uncomment the following block of code for
clean destruction of the singletons. */
/*
numbersTypeSupport_finalize();
retcode = DDS_DomainParticipantFactory_finalize_instance();
if (retcode != DDS_RETCODE_OK) {
printf("finalize_instance error %d\n", retcode);
status = -1;
}
*/
return status;
}
static int subscriber_main(int domainId, int sample_count)
{
DDS_DomainParticipant *participant = NULL;
DDS_Subscriber *subscriber = NULL;
DDS_Topic *topic = NULL;
struct DDS_DataReaderListener reader_listener =
DDS_DataReaderListener_INITIALIZER;
DDS_DataReader *reader = NULL;
DDS_ReturnCode_t retcode;
const char *type_name = NULL;
int count = 0;
struct DDS_Duration_t poll_period = { 4, 0 };
/* To customize participant QoS, use
the configuration file USER_QOS_PROFILES.xml */
participant = DDS_DomainParticipantFactory_create_participant(
DDS_TheParticipantFactory,
domainId,
&DDS_PARTICIPANT_QOS_DEFAULT,
NULL /* listener */,
DDS_STATUS_MASK_NONE);
if (participant == NULL) {
printf("create_participant error\n");
subscriber_shutdown(participant);
return -1;
}
/* If you want to change the DomainParticipant's QoS programmatically
* rather than using the XML file, you will need to add the following lines
* to your code and comment out the create_participant call above.
*
* In this case, we set the transport settings in the XML by default, but
* in the numbers_common_create_participant call, we set up the transport
* properties either using the Properties QoS or with the transport
* property objects.
*/
/*participant = numbers_common_create_participant(domainId);
if (participant == NULL) {
subscriber_shutdown(participant);
return -1; }
*/
if (numbers_common_verify_qos(participant) != 0) {
subscriber_shutdown(participant);
return -1;
}
/* To customize subscriber QoS, use
DDS_DomainParticipant_get_default_subscriber_qos() */
subscriber = DDS_DomainParticipant_create_subscriber(
participant,
&DDS_SUBSCRIBER_QOS_DEFAULT,
NULL /* listener */,
DDS_STATUS_MASK_NONE);
if (subscriber == NULL) {
printf("create_subscriber error\n");
subscriber_shutdown(participant);
return -1;
}
/* Register type before creating topic */
type_name = numbersTypeSupport_get_type_name();
retcode = numbersTypeSupport_register_type(participant, type_name);
if (retcode != DDS_RETCODE_OK) {
printf("register_type error %d\n", retcode);
subscriber_shutdown(participant);
return -1;
}
/* To customize topic QoS, use
DDS_DomainParticipant_get_default_topic_qos() */
topic = DDS_DomainParticipant_create_topic(
participant,
"Example numbers",
type_name,
&DDS_TOPIC_QOS_DEFAULT,
NULL /* listener */,
DDS_STATUS_MASK_NONE);
if (topic == NULL) {
printf("create_topic error\n");
subscriber_shutdown(participant);
return -1;
}
/* Setup data reader listener */
reader_listener.on_requested_deadline_missed =
numbersListener_on_requested_deadline_missed;
reader_listener.on_requested_incompatible_qos =
numbersListener_on_requested_incompatible_qos;
reader_listener.on_sample_rejected = numbersListener_on_sample_rejected;
reader_listener.on_liveliness_changed =
numbersListener_on_liveliness_changed;
reader_listener.on_sample_lost = numbersListener_on_sample_lost;
reader_listener.on_subscription_matched =
numbersListener_on_subscription_matched;
reader_listener.on_data_available = numbersListener_on_data_available;
/* To customize data reader QoS, use
DDS_Subscriber_get_default_datareader_qos() */
reader = DDS_Subscriber_create_datareader(
subscriber,
DDS_Topic_as_topicdescription(topic),
&DDS_DATAREADER_QOS_DEFAULT,
&reader_listener,
DDS_STATUS_MASK_ALL);
if (reader == NULL) {
printf("create_datareader error\n");
subscriber_shutdown(participant);
return -1;
}
/* Main loop */
for (count = 0; (sample_count == 0) || (count < sample_count); ++count) {
printf("numbers subscriber sleeping for %d sec...\n", poll_period.sec);
NDDS_Utility_sleep(&poll_period);
}
/* Cleanup and delete delete all entities */
return subscriber_shutdown(participant);
}
#if defined(RTI_WINCE)
int wmain(int argc, wchar_t **argv)
{
int domainId = 0;
int sample_count = 0; /* infinite loop */
if (argc >= 2) {
domainId = _wtoi(argv[1]);
}
if (argc >= 3) {
sample_count = _wtoi(argv[2]);
}
/* Uncomment this to turn on additional logging
NDDS_Config_Logger_set_verbosity_by_category(
NDDS_Config_Logger_get_instance(),
NDDS_CONFIG_LOG_CATEGORY_API,
NDDS_CONFIG_LOG_VERBOSITY_STATUS_ALL);
*/
return subscriber_main(domainId, sample_count);
}
#elif !(defined(RTI_VXWORKS) && !defined(__RTP__)) && !defined(RTI_PSOS)
int main(int argc, char *argv[])
{
int domainId = 0;
int sample_count = 0; /* infinite loop */
if (argc >= 2) {
domainId = atoi(argv[1]);
}
if (argc >= 3) {
sample_count = atoi(argv[2]);
}
/* Uncomment this to turn on additional logging
NDDS_Config_Logger_set_verbosity_by_category(
NDDS_Config_Logger_get_instance(),
NDDS_CONFIG_LOG_CATEGORY_API,
NDDS_CONFIG_LOG_VERBOSITY_STATUS_ALL);
*/
return subscriber_main(domainId, sample_count);
}
#endif
| c |
rticonnextdds-examples | data/projects/rticonnextdds-examples/connext_dds/builtin_qos_profiles/c++/profiles_subscriber.cxx | /*******************************************************************************
(c) 2005-2014 Copyright, Real-Time Innovations, Inc. All rights reserved.
RTI grants Licensee a license to use, modify, compile, and create derivative
works of the Software. Licensee has the right to distribute object form only
for use with RTI products. The Software is provided "as is", with no warranty
of any type, including any warranty for fitness for any purpose. RTI is under
no obligation to maintain or support the Software. RTI shall not be liable for
any incidental or consequential damages arising out of the use or inability to
use the software.
******************************************************************************/
/* profiles_subscriber.cxx
A subscription example
This file is derived from code automatically generated by the rtiddsgen
command:
rtiddsgen -language C++ -example <arch> profiles.idl
Example subscription of type profiles automatically generated by
'rtiddsgen'. To test them follow these steps:
(1) Compile this file and the example publication.
(2) Start the subscription with the command
objs/<arch>/profiles_subscriber <domain_id> <sample_count>
(3) Start the publication with the command
objs/<arch>/profiles_publisher <domain_id> <sample_count>
(4) [Optional] Specify the list of discovery initial peers and
multicast receive addresses via an environment variable or a file
(in the current working directory) called NDDS_DISCOVERY_PEERS.
You can run any number of publishers and subscribers programs, and can
add and remove them dynamically from the domain.
!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
!!! NOTE: This example will only work when dynamically linking. !!!
In Visual Studio, change the target to "Debug DLL" or "Release DLL"
to build.
!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
Example:
To run the example application on domain <domain_id>:
On Unix:
objs/<arch>/profiles_publisher <domain_id>
objs/<arch>/profiles_subscriber <domain_id>
On Windows:
objs\<arch>\profiles_publisher <domain_id>
objs\<arch>\profiles_subscriber <domain_id>
modification history
------------ -------
*/
#include <stdio.h>
#include <stdlib.h>
#ifdef RTI_VX653
#include <vThreadsData.h>
#endif
#include "ndds/ndds_cpp.h"
#include "profiles.h"
#include "profilesSupport.h"
class profilesListener : public DDSDataReaderListener {
public:
virtual void on_requested_deadline_missed(
DDSDataReader * /*reader*/,
const DDS_RequestedDeadlineMissedStatus & /*status*/)
{
}
virtual void on_requested_incompatible_qos(
DDSDataReader * /*reader*/,
const DDS_RequestedIncompatibleQosStatus & /*status*/)
{
printf("Discovered writer wit incompatible QoS\n");
}
virtual void on_sample_rejected(
DDSDataReader * /*reader*/,
const DDS_SampleRejectedStatus & /*status*/)
{
}
virtual void on_liveliness_changed(
DDSDataReader * /*reader*/,
const DDS_LivelinessChangedStatus & /*status*/)
{
}
virtual void on_sample_lost(
DDSDataReader * /*reader*/,
const DDS_SampleLostStatus & /*status*/)
{
}
virtual void on_subscription_matched(
DDSDataReader * /*reader*/,
const DDS_SubscriptionMatchedStatus & /*status*/)
{
}
virtual void on_data_available(DDSDataReader *reader);
};
void profilesListener::on_data_available(DDSDataReader *reader)
{
profilesDataReader *profiles_reader = NULL;
profilesSeq data_seq;
DDS_SampleInfoSeq info_seq;
DDS_ReturnCode_t retcode;
int i;
profiles_reader = profilesDataReader::narrow(reader);
if (profiles_reader == NULL) {
printf("DataReader narrow error\n");
return;
}
retcode = profiles_reader->take(
data_seq,
info_seq,
DDS_LENGTH_UNLIMITED,
DDS_ANY_SAMPLE_STATE,
DDS_ANY_VIEW_STATE,
DDS_ANY_INSTANCE_STATE);
if (retcode == DDS_RETCODE_NO_DATA) {
return;
} else if (retcode != DDS_RETCODE_OK) {
printf("take error %d\n", retcode);
return;
}
for (i = 0; i < data_seq.length(); ++i) {
if (info_seq[i].valid_data) {
profilesTypeSupport::print_data(&data_seq[i]);
}
}
retcode = profiles_reader->return_loan(data_seq, info_seq);
if (retcode != DDS_RETCODE_OK) {
printf("return loan error %d\n", retcode);
}
}
/* Delete all entities */
static int subscriber_shutdown(DDSDomainParticipant *participant)
{
DDS_ReturnCode_t retcode;
int status = 0;
if (participant != NULL) {
retcode = participant->delete_contained_entities();
if (retcode != DDS_RETCODE_OK) {
printf("delete_contained_entities error %d\n", retcode);
status = -1;
}
retcode = DDSTheParticipantFactory->delete_participant(participant);
if (retcode != DDS_RETCODE_OK) {
printf("delete_participant error %d\n", retcode);
status = -1;
}
}
/* RTI Connext provides the finalize_instance() method on
domain participant factory for people who want to release memory used
by the participant factory. Uncomment the following block of code for
clean destruction of the singleton. */
/*
retcode = DDSDomainParticipantFactory::finalize_instance();
if (retcode != DDS_RETCODE_OK) {
printf("finalize_instance error %d\n", retcode);
status = -1;
}
*/
return status;
}
extern "C" int subscriber_main(int domainId, int sample_count)
{
DDSDomainParticipant *participant = NULL;
DDSSubscriber *subscriber = NULL;
DDSTopic *topic = NULL;
profilesListener *reader_listener = NULL;
DDSDataReader *reader = NULL;
DDS_ReturnCode_t retcode;
const char *type_name = NULL;
int count = 0;
DDS_Duration_t receive_period = { 4, 0 };
int status = 0;
/*
* This example uses a built-in QoS profile to enable monitoring on the
* DomainParticipant. The code below loads the XML QoS from the
* USER_QOS_PROFILES.xml file, which is inheriting from the
* "BuiltinQoSLib::Generic.Monitoring.Common" profile to enable monitoring.
*
* !!!! NOTE: This example will only work when dynamically linking !!!
* In Visual Studio, change the target to "Debug DLL" or "Release DLL"
* to build.
*/
participant = DDSTheParticipantFactory->create_participant(
domainId,
DDS_PARTICIPANT_QOS_DEFAULT,
NULL /* listener */,
DDS_STATUS_MASK_NONE);
/* If you want to change the DomainParticipant's QoS programatically rather
* than using the XML file, you will need to add the following lines to
* your code and comment out the create_participant call above.
*
* This example uses a built-in QoS profile to enable
* monitoring on the DomainParticipant.*/
/* participant = DDSTheParticipantFactory->create_participant_with_profile(
domainId, "BuiltinQosLib", "Generic.Monitoring.Common",
NULL /* listener * /, DDS_STATUS_MASK_NONE);
*/
if (participant == NULL) {
printf("create_participant error\n");
subscriber_shutdown(participant);
return -1;
}
/* To customize the subscriber QoS, use
the configuration file USER_QOS_PROFILES.xml */
subscriber = participant->create_subscriber(
DDS_SUBSCRIBER_QOS_DEFAULT,
NULL /* listener */,
DDS_STATUS_MASK_NONE);
if (subscriber == NULL) {
printf("create_subscriber error\n");
subscriber_shutdown(participant);
return -1;
}
/* Register the type before creating the topic */
type_name = profilesTypeSupport::get_type_name();
retcode = profilesTypeSupport::register_type(participant, type_name);
if (retcode != DDS_RETCODE_OK) {
printf("register_type error %d\n", retcode);
subscriber_shutdown(participant);
return -1;
}
/* To customize the topic QoS, use
the configuration file USER_QOS_PROFILES.xml */
topic = participant->create_topic(
"Example profiles",
type_name,
DDS_TOPIC_QOS_DEFAULT,
NULL /* listener */,
DDS_STATUS_MASK_NONE);
if (topic == NULL) {
printf("create_topic error\n");
subscriber_shutdown(participant);
return -1;
}
/* Create a data reader listener */
reader_listener = new profilesListener();
/* To customize the data reader QoS, use
the configuration file USER_QOS_PROFILES.xml */
reader = subscriber->create_datareader(
topic,
DDS_DATAREADER_QOS_DEFAULT,
reader_listener,
DDS_STATUS_MASK_ALL);
/* If you want to change the DataReader's QoS programatically rather
* than using the XML file, you will need to add the following lines to
* your code and comment out the create_datareader call above.
*
* This example uses a built-in QoS profile to enable reliable streaming
* data.*/
/* reader = subscriber->create_datareader_with_profile(
topic, DDS_BUILTIN_QOS_LIB_EXP,
DDS_PROFILE_PATTERN_RELIABLE_STREAMING, reader_listener,
DDS_STATUS_MASK_ALL);
*/
if (reader == NULL) {
printf("create_datareader error\n");
subscriber_shutdown(participant);
delete reader_listener;
return -1;
}
/* Main loop */
for (count = 0; (sample_count == 0) || (count < sample_count); ++count) {
printf("profiles subscriber sleeping for %d sec...\n",
receive_period.sec);
NDDSUtility::sleep(receive_period);
}
/* Delete all entities */
status = subscriber_shutdown(participant);
delete reader_listener;
return status;
}
#if defined(RTI_WINCE)
int wmain(int argc, wchar_t **argv)
{
int domainId = 0;
int sample_count = 0; /* infinite loop */
if (argc >= 2) {
domainId = _wtoi(argv[1]);
}
if (argc >= 3) {
sample_count = _wtoi(argv[2]);
}
/* Uncomment this to turn on additional logging
NDDSConfigLogger::get_instance()->
set_verbosity_by_category(NDDS_CONFIG_LOG_CATEGORY_API,
NDDS_CONFIG_LOG_VERBOSITY_STATUS_ALL);
*/
return subscriber_main(domainId, sample_count);
}
#elif !(defined(RTI_VXWORKS) && !defined(__RTP__)) && !defined(RTI_PSOS)
int main(int argc, char *argv[])
{
int domainId = 0;
int sample_count = 0; /* infinite loop */
if (argc >= 2) {
domainId = atoi(argv[1]);
}
if (argc >= 3) {
sample_count = atoi(argv[2]);
}
/* Uncomment this to turn on additional logging
NDDSConfigLogger::get_instance()->
set_verbosity_by_category(NDDS_CONFIG_LOG_CATEGORY_API,
NDDS_CONFIG_LOG_VERBOSITY_STATUS_ALL);
*/
return subscriber_main(domainId, sample_count);
}
#endif
#ifdef RTI_VX653
const unsigned char *__ctype = *(__ctypePtrGet());
extern "C" void usrAppInit()
{
#ifdef USER_APPL_INIT
USER_APPL_INIT; /* for backwards compatibility */
#endif
/* add application specific code here */
taskSpawn(
"sub",
RTI_OSAPI_THREAD_PRIORITY_NORMAL,
0x8,
0x150000,
(FUNCPTR) subscriber_main,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0);
}
#endif
| cxx |
rticonnextdds-examples | data/projects/rticonnextdds-examples/connext_dds/builtin_qos_profiles/c++/profiles_publisher.cxx | /*******************************************************************************
(c) 2005-2014 Copyright, Real-Time Innovations, Inc. All rights reserved.
RTI grants Licensee a license to use, modify, compile, and create derivative
works of the Software. Licensee has the right to distribute object form only
for use with RTI products. The Software is provided "as is", with no warranty
of any type, including any warranty for fitness for any purpose. RTI is under
no obligation to maintain or support the Software. RTI shall not be liable for
any incidental or consequential damages arising out of the use or inability to
use the software.
******************************************************************************/
/* profiles_publisher.cxx
A publication of data of type profiles
This file is derived from code automatically generated by the rtiddsgen
command:
rtiddsgen -language C++ -example <arch> profiles.idl
Example publication of type profiles automatically generated by
'rtiddsgen'. To test them follow these steps:
(1) Compile this file and the example subscription.
(2) Start the subscription with the command
objs/<arch>/profiles_subscriber <domain_id> <sample_count>
(3) Start the publication with the command
objs/<arch>/profiles_publisher <domain_id> <sample_count>
(4) [Optional] Specify the list of discovery initial peers and
multicast receive addresses via an environment variable or a file
(in the current working directory) called NDDS_DISCOVERY_PEERS.
You can run any number of publishers and subscribers programs, and can
add and remove them dynamically from the domain.
!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
!!! NOTE: This example will only work when dynamically linking. !!!
In Visual Studio, change the target to "Debug DLL" or "Release DLL"
to build.
!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
Example:
To run the example application on domain <domain_id>:
On Unix:
objs/<arch>/profiles_publisher <domain_id> o
objs/<arch>/profiles_subscriber <domain_id>
On Windows:
objs\<arch>\profiles_publisher <domain_id>
objs\<arch>\profiles_subscriber <domain_id>
modification history
------------ -------
*/
#include <stdio.h>
#include <stdlib.h>
#ifdef RTI_VX653
#include <vThreadsData.h>
#endif
#include "ndds/ndds_cpp.h"
#include "profiles.h"
#include "profilesSupport.h"
/* Delete all entities */
static int publisher_shutdown(DDSDomainParticipant *participant)
{
DDS_ReturnCode_t retcode;
int status = 0;
if (participant != NULL) {
retcode = participant->delete_contained_entities();
if (retcode != DDS_RETCODE_OK) {
printf("delete_contained_entities error %d\n", retcode);
status = -1;
}
retcode = DDSTheParticipantFactory->delete_participant(participant);
if (retcode != DDS_RETCODE_OK) {
printf("delete_participant error %d\n", retcode);
status = -1;
}
}
/* RTI Connext provides finalize_instance() method on
domain participant factory for people who want to release memory used
by the participant factory. Uncomment the following block of code for
clean destruction of the singleton. */
/*
retcode = DDSDomainParticipantFactory::finalize_instance();
if (retcode != DDS_RETCODE_OK) {
printf("finalize_instance error %d\n", retcode);
status = -1;
}
*/
return status;
}
extern "C" int publisher_main(int domainId, int sample_count)
{
DDSDomainParticipant *participant = NULL;
DDSPublisher *publisher = NULL;
DDSTopic *topic = NULL;
DDSDataWriter *writer = NULL;
profilesDataWriter *profiles_writer = NULL;
profiles *instance = NULL;
DDS_ReturnCode_t retcode;
DDS_InstanceHandle_t instance_handle = DDS_HANDLE_NIL;
const char *type_name = NULL;
int count = 0;
DDS_Duration_t send_period = { 4, 0 };
/*
* This example uses a built-in QoS profile to enable monitoring on the
* DomainParticipant. The code below loads the XML QoS from the
* USER_QOS_PROFILES.xml file, which is inheriting from the
* "BuiltinQoSLib::Generic.Monitoring.Common" profile to enable monitoring.
*
* !!!! NOTE: This example will only work when dynamically linking !!!
* In Visual Studio, change the target to "Debug DLL" or "Release DLL"
* to build.
*/
participant = DDSTheParticipantFactory->create_participant(
domainId,
DDS_PARTICIPANT_QOS_DEFAULT,
NULL /* listener */,
DDS_STATUS_MASK_NONE);
/* If you want to change the DomainParticipant's QoS programatically rather
* than using the XML file, you will need to add the following lines to
* your code and comment out the create_participant call above.
*
* This example uses a built-in QoS profile to enable
* monitoring on the DomainParticipant.*/
/* participant = DDSTheParticipantFactory->create_participant_with_profile(
domainId, "BuiltinQosLib", "Generic.Monitoring.Common",
NULL /* listener * /, DDS_STATUS_MASK_NONE);
*/
if (participant == NULL) {
printf("create_participant error\n");
publisher_shutdown(participant);
return -1;
}
/* To customize publisher QoS, use
the configuration file USER_QOS_PROFILES.xml */
publisher = participant->create_publisher(
DDS_PUBLISHER_QOS_DEFAULT,
NULL /* listener */,
DDS_STATUS_MASK_NONE);
if (publisher == NULL) {
printf("create_publisher error\n");
publisher_shutdown(participant);
return -1;
}
/* Register type before creating topic */
type_name = profilesTypeSupport::get_type_name();
retcode = profilesTypeSupport::register_type(participant, type_name);
if (retcode != DDS_RETCODE_OK) {
printf("register_type error %d\n", retcode);
publisher_shutdown(participant);
return -1;
}
/* To customize topic QoS, use
the configuration file USER_QOS_PROFILES.xml */
topic = participant->create_topic(
"Example profiles",
type_name,
DDS_TOPIC_QOS_DEFAULT,
NULL /* listener */,
DDS_STATUS_MASK_NONE);
if (topic == NULL) {
printf("create_topic error\n");
publisher_shutdown(participant);
return -1;
}
/* To customize data writer QoS, use
the configuration file USER_QOS_PROFILES.xml */
writer = publisher->create_datawriter(
topic,
DDS_DATAWRITER_QOS_DEFAULT,
NULL /* listener */,
DDS_STATUS_MASK_NONE);
/* If you want to change the DataWriter's QoS programatically rather
* than using the XML file, you will need to add the following lines to
* your code and comment out the create_datawriter call above.
*
* This example uses a built-in QoS profile to tune QoS for
* reliable streaming data.*/
/* To customize data writer QoS, use
the configuration file USER_QOS_PROFILES.xml */
/* writer = publisher->create_datawriter_with_profile(
topic, DDS_BUILTIN_QOS_LIB_EXP,
DDS_PROFILE_PATTERN_RELIABLE_STREAMING, NULL /* listener * /,
DDS_STATUS_MASK_NONE);
*/
if (writer == NULL) {
printf("create_datawriter error\n");
publisher_shutdown(participant);
return -1;
}
profiles_writer = profilesDataWriter::narrow(writer);
if (profiles_writer == NULL) {
printf("DataWriter narrow error\n");
publisher_shutdown(participant);
return -1;
}
/* Create data sample for writing */
instance = profilesTypeSupport::create_data();
if (instance == NULL) {
printf("profilesTypeSupport::create_data error\n");
publisher_shutdown(participant);
return -1;
}
/* For a data type that has a key, if the same instance is going to be
written multiple times, initialize the key here
and register the keyed instance prior to writing */
/*
instance_handle = profiles_writer->register_instance(*instance);
*/
/* Main loop */
for (count = 0; (sample_count == 0) || (count < sample_count); ++count) {
printf("Writing profiles, count %d\n", count);
/* Modify the data to be sent here */
retcode = profiles_writer->write(*instance, instance_handle);
if (retcode != DDS_RETCODE_OK) {
printf("write error %d\n", retcode);
}
NDDSUtility::sleep(send_period);
}
/*
retcode = profiles_writer->unregister_instance(
*instance, instance_handle);
if (retcode != DDS_RETCODE_OK) {
printf("unregister instance error %d\n", retcode);
}
*/
/* Delete data sample */
retcode = profilesTypeSupport::delete_data(instance);
if (retcode != DDS_RETCODE_OK) {
printf("profilesTypeSupport::delete_data error %d\n", retcode);
}
/* Delete all entities */
return publisher_shutdown(participant);
}
#if defined(RTI_WINCE)
int wmain(int argc, wchar_t **argv)
{
int domainId = 0;
int sample_count = 0; /* infinite loop */
if (argc >= 2) {
domainId = _wtoi(argv[1]);
}
if (argc >= 3) {
sample_count = _wtoi(argv[2]);
}
/* Uncomment this to turn on additional logging
NDDSConfigLogger::get_instance()->
set_verbosity_by_category(NDDS_CONFIG_LOG_CATEGORY_API,
NDDS_CONFIG_LOG_VERBOSITY_STATUS_ALL);
*/
return publisher_main(domainId, sample_count);
}
#elif !(defined(RTI_VXWORKS) && !defined(__RTP__)) && !defined(RTI_PSOS)
int main(int argc, char *argv[])
{
int domainId = 0;
int sample_count = 0; /* infinite loop */
if (argc >= 2) {
domainId = atoi(argv[1]);
}
if (argc >= 3) {
sample_count = atoi(argv[2]);
}
/* Uncomment this to turn on additional logging
NDDSConfigLogger::get_instance()->
set_verbosity_by_category(NDDS_CONFIG_LOG_CATEGORY_API,
NDDS_CONFIG_LOG_VERBOSITY_STATUS_ALL);
*/
return publisher_main(domainId, sample_count);
}
#endif
#ifdef RTI_VX653
const unsigned char *__ctype = *(__ctypePtrGet());
extern "C" void usrAppInit()
{
#ifdef USER_APPL_INIT
USER_APPL_INIT; /* for backwards compatibility */
#endif
/* add application specific code here */
taskSpawn(
"pub",
RTI_OSAPI_THREAD_PRIORITY_NORMAL,
0x8,
0x150000,
(FUNCPTR) publisher_main,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0);
}
#endif
| cxx |
rticonnextdds-examples | data/projects/rticonnextdds-examples/connext_dds/builtin_qos_profiles/c++98/profiles_subscriber.cxx | /*******************************************************************************
(c) 2005-2014 Copyright, Real-Time Innovations, Inc. All rights reserved.
RTI grants Licensee a license to use, modify, compile, and create derivative
works of the Software. Licensee has the right to distribute object form only
for use with RTI products. The Software is provided "as is", with no warranty
of any type, including any warranty for fitness for any purpose. RTI is under
no obligation to maintain or support the Software. RTI shall not be liable for
any incidental or consequential damages arising out of the use or inability to
use the software.
******************************************************************************/
#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include "profiles.h"
#include "profilesSupport.h"
#include "ndds/ndds_cpp.h"
#include "application.h"
using namespace application;
static int shutdown_participant(
DDSDomainParticipant *participant,
const char *shutdown_message,
int status);
unsigned int process_data(profilesDataReader *typed_reader)
{
profilesSeq 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) {
samples_read++;
profilesTypeSupport::print_data(&data_seq[i]);
}
}
// 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)
{
DDS_Duration_t wait_timeout = { 4, 0 };
/*
* This example uses a built-in QoS profile to enable monitoring on the
* DomainParticipant. The code below loads the XML QoS from the
* USER_QOS_PROFILES.xml file, which is inheriting from the
* "BuiltinQoSLib::Generic.Monitoring.Common" profile to enable monitoring.
*
* !!!! NOTE: This example will only work when dynamically linking !!!
* In Visual Studio, change the target to "Debug DLL" or "Release DLL"
* to build.
*/
DDSDomainParticipant *participant =
DDSTheParticipantFactory->create_participant(
domain_id,
DDS_PARTICIPANT_QOS_DEFAULT,
NULL /* listener */,
DDS_STATUS_MASK_NONE);
/* If you want to change the DomainParticipant's QoS programatically rather
* than using the XML file, you will need to add the following lines to
* your code and comment out the create_participant call above.
*
* This example uses a built-in QoS profile to enable
* monitoring on the DomainParticipant.*/
/* DDSDomainParticipant *participant = DDSTheParticipantFactory->
create_participant_with_profile(
domainId,
"BuiltinQosLib",
"Generic.Monitoring.Common",
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 = profilesTypeSupport::get_type_name();
DDS_ReturnCode_t retcode =
profilesTypeSupport::register_type(participant, type_name);
if (retcode != DDS_RETCODE_OK) {
return shutdown_participant(
participant,
"register_type error",
EXIT_FAILURE);
}
// Create a Topic with a name and a datatype
DDSTopic *topic = participant->create_topic(
"Example profiles",
type_name,
DDS_TOPIC_QOS_DEFAULT,
NULL /* listener */,
DDS_STATUS_MASK_NONE);
if (topic == NULL) {
return shutdown_participant(
participant,
"create_topic error",
EXIT_FAILURE);
}
// This DataReader reads data on "Example async" Topic
DDSDataReader *untyped_reader = subscriber->create_datareader(
topic,
DDS_DATAREADER_QOS_DEFAULT,
NULL,
DDS_STATUS_MASK_ALL);
/* If you want to change the DataReader's QoS programatically rather
* than using the XML file, you will need to add the following lines to
* your code and comment out the create_datareader call above.
*
* This example uses a built-in QoS profile to enable reliable streaming
* data.*/
/* DDSDataReader *untyped_reader =
subscriber->create_datareader_with_profile( topic,
DDS_BUILTIN_QOS_LIB_EXP, DDS_PROFILE_PATTERN_RELIABLE_STREAMING,
reader_listener, 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
profilesDataReader *typed_reader =
profilesDataReader::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;
std::cout << "profiles subscriber sleeping for " << wait_timeout.sec
<< " sec...\n";
// 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/builtin_qos_profiles/c++98/profiles_publisher.cxx | /*******************************************************************************
(c) 2005-2014 Copyright, Real-Time Innovations, Inc. All rights reserved.
RTI grants Licensee a license to use, modify, compile, and create derivative
works of the Software. Licensee has the right to distribute object form only
for use with RTI products. The Software is provided "as is", with no warranty
of any type, including any warranty for fitness for any purpose. RTI is under
no obligation to maintain or support the Software. RTI shall not be liable for
any incidental or consequential damages arising out of the use or inability to
use the software.
******************************************************************************/
#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include "profiles.h"
#include "profilesSupport.h"
#include "ndds/ndds_cpp.h"
#include "application.h"
using namespace application;
static int shutdown_participant(
DDSDomainParticipant *participant,
const char *shutdown_message,
int status);
int run_publisher_application(unsigned int domain_id, unsigned int sample_count)
{
DDS_Duration_t send_period = { 4, 0 };
/*
* This example uses a built-in QoS profile to enable monitoring on the
* DomainParticipant. The code below loads the XML QoS from the
* USER_QOS_PROFILES.xml file, which is inheriting from the
* "BuiltinQoSLib::Generic.Monitoring.Common" profile to enable monitoring.
*
* !!!! NOTE: This example will only work when dynamically linking !!!
* In Visual Studio, change the target to "Debug DLL" or "Release DLL"
* to build.
*/
DDSDomainParticipant *participant =
DDSTheParticipantFactory->create_participant(
domain_id,
DDS_PARTICIPANT_QOS_DEFAULT,
NULL /* listener */,
DDS_STATUS_MASK_NONE);
/* If you want to change the DomainParticipant's QoS programatically rather
* than using the XML file, you will need to add the following lines to
* your code and comment out the create_participant call above.
*
* This example uses a built-in QoS profile to enable
* monitoring on the DomainParticipant.*/
/* DDSDomainParticipant *participant = DDSTheParticipantFactory
->create_participant_with_profile(
domainId, "BuiltinQosLib", "Generic.Monitoring.Common",
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 = profilesTypeSupport::get_type_name();
DDS_ReturnCode_t retcode =
profilesTypeSupport::register_type(participant, type_name);
if (retcode != DDS_RETCODE_OK) {
return shutdown_participant(
participant,
"register_type error",
EXIT_FAILURE);
}
// Create a Topic with a name and a datatype
DDSTopic *topic = participant->create_topic(
"Example profiles",
type_name,
DDS_TOPIC_QOS_DEFAULT,
NULL /* listener */,
DDS_STATUS_MASK_NONE);
if (topic == NULL) {
return shutdown_participant(
participant,
"create_topic error",
EXIT_FAILURE);
}
// This DataWriter writes data on "Example profiles" Topic
DDSDataWriter *untyped_writer = publisher->create_datawriter(
topic,
DDS_DATAWRITER_QOS_DEFAULT,
NULL /* listener */,
DDS_STATUS_MASK_NONE);
/* If you want to change the DataWriter's QoS programatically rather
* than using the XML file, you will need to add the following lines to
* your code and comment out the create_datawriter call above.
*
* This example uses a built-in QoS profile to tune QoS for
* reliable streaming data.*/
/* To customize data writer QoS, use
the configuration file USER_QOS_PROFILES.xml */
/* DDSDataWriter *untyped_writer = publisher
->create_datawriter_with_profile(
topic,
DDS_BUILTIN_QOS_LIB_EXP,
DDS_PROFILE_PATTERN_RELIABLE_STREAMING,
NULL /* listener * /,
DDS_STATUS_MASK_NONE);
*/
if (untyped_writer == NULL) {
return shutdown_participant(
participant,
"create_datawriter error",
EXIT_FAILURE);
}
profilesDataWriter *typed_writer =
profilesDataWriter::narrow(untyped_writer);
if (untyped_writer == NULL) {
return shutdown_participant(
participant,
"create_datawriter error",
EXIT_FAILURE);
}
// Create data for writing, allocating all members
profiles *data = profilesTypeSupport::create_data();
if (data == NULL) {
return shutdown_participant(
participant,
"profilesTypeSupport::create_data error",
EXIT_FAILURE);
}
data->msg = DDS_String_dup("Hello World!");
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 = profiles_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 profiles, count " << samples_written << std::endl;
// Modify the data to be written here
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 profiles, including all contained elements
retcode = profilesTypeSupport::delete_data(data);
if (retcode != DDS_RETCODE_OK) {
std::cerr << "profilesTypeSupport::delete_data error " << retcode
<< std::endl;
}
// Delete all entities (DataWriter, Topic, Publisher, DomainParticipant)
return shutdown_participant(participant, "Shutting down", EXIT_SUCCESS);
}
// Delete all entities
static int shutdown_participant(
DDSDomainParticipant *participant,
const char *shutdown_message,
int status)
{
DDS_ReturnCode_t retcode;
std::cout << shutdown_message << std::endl;
if (participant != NULL) {
// Cleanup everything created by this Participant
retcode = participant->delete_contained_entities();
if (retcode != DDS_RETCODE_OK) {
std::cerr << "delete_contained_entities error " << retcode
<< std::endl;
status = EXIT_FAILURE;
}
retcode = DDSTheParticipantFactory->delete_participant(participant);
if (retcode != DDS_RETCODE_OK) {
std::cerr << "delete_participant error " << retcode << std::endl;
status = EXIT_FAILURE;
}
}
return status;
}
int main(int argc, char *argv[])
{
// Parse arguments and handle control-C
ApplicationArguments arguments;
parse_arguments(arguments, argc, argv);
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/builtin_qos_profiles/c++98/application.h | /*
* (c) Copyright, Real-Time Innovations, 2020. All rights reserved.
* RTI grants Licensee a license to use, modify, compile, and create derivative
* works of the software solely for use with RTI Connext DDS. Licensee may
* redistribute copies of the software provided that all such copies are subject
* to this license. The software is provided "as is", with no warranty of any
* type, including any warranty for fitness for any purpose. RTI is under no
* obligation to maintain or support the software. RTI shall not be liable for
* any incidental or consequential damages arising out of the use or inability
* to use the software.
*/
#ifndef APPLICATION_H
#define APPLICATION_H
#include <iostream>
#include <csignal>
#include <climits>
namespace application {
// Catch control-C and tell application to shut down
bool shutdown_requested = false;
inline void stop_handler(int)
{
shutdown_requested = true;
std::cout << "preparing to shut down..." << std::endl;
}
inline void setup_signal_handlers()
{
signal(SIGINT, stop_handler);
signal(SIGTERM, stop_handler);
}
enum ParseReturn { PARSE_RETURN_OK, PARSE_RETURN_FAILURE, PARSE_RETURN_EXIT };
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/builtin_qos_profiles/c/profiles_publisher.c | /*******************************************************************************
(c) 2005-2014 Copyright, Real-Time Innovations, Inc. All rights reserved.
RTI grants Licensee a license to use, modify, compile, and create derivative
works of the Software. Licensee has the right to distribute object form only
for use with RTI products. The Software is provided "as is", with no warranty
of any type, including any warranty for fitness for any purpose. RTI is under
no obligation to maintain or support the Software. RTI shall not be liable for
any incidental or consequential damages arising out of the use or inability to
use the software.
******************************************************************************/
/* profiles_publisher.c
A publication of data of type profiles
This file is derived from code automatically generated by the rtiddsgen
command:
rtiddsgen -language C -example <arch> profiles.idl
Example publication of type profiles automatically generated by
'rtiddsgen'. To test them follow these steps:
(1) Compile this file and the example subscription.
(2) Start the subscription with the command
objs/<arch>/profiles_subscriber <domain_id> <sample_count>
(3) Start the publication with the command
objs/<arch>/profiles_publisher <domain_id> <sample_count>
(4) [Optional] Specify the list of discovery initial peers and
multicast receive addresses via an environment variable or a file
(in the current working directory) called NDDS_DISCOVERY_PEERS.
You can run any number of publishers and subscribers programs, and can
add and remove them dynamically from the domain.
!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
!!! NOTE: This example will only work when dynamically linking. !!!
In Visual Studio, change the target to "Debug DLL" or "Release DLL"
to build.
!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
Example:
To run the example application on domain <domain_id>:
On Unix:
objs/<arch>/profiles_publisher <domain_id>
objs/<arch>/profiles_subscriber <domain_id>
On Windows:
objs\<arch>\profiles_publisher <domain_id>
objs\<arch>\profiles_subscriber <domain_id>
modification history
------------ -------
*/
#include "ndds/ndds_c.h"
#include "profiles.h"
#include "profilesSupport.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;
profilesDataWriter *profiles_writer = NULL;
profiles *instance = NULL;
DDS_ReturnCode_t retcode;
DDS_InstanceHandle_t instance_handle = DDS_HANDLE_NIL;
const char *type_name = NULL;
int count = 0;
struct DDS_Duration_t send_period = { 4, 0 };
/*
* This example uses a built-in QoS profile to enable monitoring on the
* DomainParticipant. The code below loads the XML QoS from the
* USER_QOS_PROFILES.xml file, which is inheriting from the
* "BuiltinQoSLib::Generic.Monitoring.Common" profile to enable monitoring.
*
* !!!! NOTE: This example will only work when dynamically linking !!!
* In Visual Studio, change the target to "Debug DLL" or "Release DLL"
* to build.
*/
/* To customize participant QoS, use
the configuration file USER_QOS_PROFILES.xml */
participant = DDS_DomainParticipantFactory_create_participant(
DDS_TheParticipantFactory,
domainId,
&DDS_PARTICIPANT_QOS_DEFAULT,
NULL /* listener */,
DDS_STATUS_MASK_NONE);
/* If you want to change the DomainParticipant's QoS programatically rather
* than using the XML file, you will need to add the following lines to
* your code and comment out the create_participant call above.
*
* This example uses a built-in QoS profile to enable
* monitoring on the DomainParticipant.*/
/*participant =
DDS_DomainParticipantFactory_create_participant_with_profile(
DDS_TheParticipantFactory, domainId,
DDS_BUILTIN_QOS_LIB, DDS_PROFILE_GENERIC_MONITORING_COMMON,
NULL /* listener * /, DDS_STATUS_MASK_NONE);
*/
if (participant == NULL) {
printf("create_participant error\n");
publisher_shutdown(participant);
return -1;
}
/* To customize publisher QoS, use
the configuration file USER_QOS_PROFILES.xml */
publisher = DDS_DomainParticipant_create_publisher(
participant,
&DDS_PUBLISHER_QOS_DEFAULT,
NULL /* listener */,
DDS_STATUS_MASK_NONE);
if (publisher == NULL) {
printf("create_publisher error\n");
publisher_shutdown(participant);
return -1;
}
/* Register type before creating topic */
type_name = profilesTypeSupport_get_type_name();
retcode = profilesTypeSupport_register_type(participant, type_name);
if (retcode != DDS_RETCODE_OK) {
printf("register_type error %d\n", retcode);
publisher_shutdown(participant);
return -1;
}
/* To customize topic QoS, use
the configuration file USER_QOS_PROFILES.xml */
topic = DDS_DomainParticipant_create_topic(
participant,
"Example profiles",
type_name,
&DDS_TOPIC_QOS_DEFAULT,
NULL /* listener */,
DDS_STATUS_MASK_NONE);
if (topic == NULL) {
printf("create_topic error\n");
publisher_shutdown(participant);
return -1;
}
/* To customize data writer QoS, use
the configuration file USER_QOS_PROFILES.xml */
writer = DDS_Publisher_create_datawriter(
publisher,
topic,
&DDS_DATAWRITER_QOS_DEFAULT,
NULL /* listener */,
DDS_STATUS_MASK_NONE);
/* If you want to change the DataWriter's QoS programatically rather
* than using the XML file, you will need to add the following lines to
* your code and comment out the create_datawriter call above.
*
* This example uses a built-in QoS profile to tune the QoS for
* reliable streaming data. */
/*writer = DDS_Publisher_create_datawriter_with_profile(
publisher,
topic, DDS_BUILTIN_QOS_LIB_EXP,
DDS_PROFILE_PATTERN_RELIABLE_STREAMING, NULL /* listener * /,
DDS_STATUS_MASK_NONE);*/
if (writer == NULL) {
printf("create_datawriter error\n");
publisher_shutdown(participant);
return -1;
}
profiles_writer = profilesDataWriter_narrow(writer);
if (profiles_writer == NULL) {
printf("DataWriter narrow error\n");
publisher_shutdown(participant);
return -1;
}
/* Create data sample for writing */
instance = profilesTypeSupport_create_data_ex(DDS_BOOLEAN_TRUE);
if (instance == NULL) {
printf("profilesTypeSupport_create_data error\n");
publisher_shutdown(participant);
return -1;
}
/* For a data type that has a key, if the same instance is going to be
written multiple times, initialize the key here
and register the keyed instance prior to writing */
/*
instance_handle = profilesDataWriter_register_instance(
profiles_writer, instance);
*/
/* Main loop */
for (count = 0; (sample_count == 0) || (count < sample_count); ++count) {
printf("Writing profiles, count %d\n", count);
/* Modify the data to be written here */
/* Write data */
retcode = profilesDataWriter_write(
profiles_writer,
instance,
&instance_handle);
if (retcode != DDS_RETCODE_OK) {
printf("write error %d\n", retcode);
}
NDDS_Utility_sleep(&send_period);
}
/*
retcode = profilesDataWriter_unregister_instance(
profiles_writer, instance, &instance_handle);
if (retcode != DDS_RETCODE_OK) {
printf("unregister instance error %d\n", retcode);
}
*/
/* Delete data sample */
retcode = profilesTypeSupport_delete_data_ex(instance, DDS_BOOLEAN_TRUE);
if (retcode != DDS_RETCODE_OK) {
printf("profilesTypeSupport_delete_data error %d\n", retcode);
}
/* Cleanup and delete delete all entities */
return publisher_shutdown(participant);
}
#if defined(RTI_WINCE)
int wmain(int argc, wchar_t **argv)
{
int domainId = 0;
int sample_count = 0; /* infinite loop */
if (argc >= 2) {
domainId = _wtoi(argv[1]);
}
if (argc >= 3) {
sample_count = _wtoi(argv[2]);
}
/* Uncomment this to turn on additional logging
NDDS_Config_Logger_set_verbosity_by_category(
NDDS_Config_Logger_get_instance(),
NDDS_CONFIG_LOG_CATEGORY_API,
NDDS_CONFIG_LOG_VERBOSITY_STATUS_ALL);
*/
return publisher_main(domainId, sample_count);
}
#elif !(defined(RTI_VXWORKS) && !defined(__RTP__)) && !defined(RTI_PSOS)
int main(int argc, char *argv[])
{
int domainId = 0;
int sample_count = 0; /* infinite loop */
if (argc >= 2) {
domainId = atoi(argv[1]);
}
if (argc >= 3) {
sample_count = atoi(argv[2]);
}
/* Uncomment this to turn on additional logging
NDDS_Config_Logger_set_verbosity_by_category(
NDDS_Config_Logger_get_instance(),
NDDS_CONFIG_LOG_CATEGORY_API,
NDDS_CONFIG_LOG_VERBOSITY_STATUS_ALL);
*/
return publisher_main(domainId, sample_count);
}
#endif
#ifdef RTI_VX653
const unsigned char *__ctype = NULL;
void usrAppInit()
{
#ifdef USER_APPL_INIT
USER_APPL_INIT; /* for backwards compatibility */
#endif
/* add application specific code here */
taskSpawn(
"pub",
RTI_OSAPI_THREAD_PRIORITY_NORMAL,
0x8,
0x150000,
(FUNCPTR) publisher_main,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0);
}
#endif
| c |
rticonnextdds-examples | data/projects/rticonnextdds-examples/connext_dds/builtin_qos_profiles/c/profiles_subscriber.c | /*******************************************************************************
(c) 2005-2014 Copyright, Real-Time Innovations, Inc. All rights reserved.
RTI grants Licensee a license to use, modify, compile, and create derivative
works of the Software. Licensee has the right to distribute object form only
for use with RTI products. The Software is provided "as is", with no warranty
of any type, including any warranty for fitness for any purpose. RTI is under
no obligation to maintain or support the Software. RTI shall not be liable for
any incidental or consequential damages arising out of the use or inability to
use the software.
******************************************************************************/
/* profiles_subscriber.c
A subscription example
This file is derived from code automatically generated by the rtiddsgen
command:
rtiddsgen -language C -example <arch> profiles.idl
Example subscription of type profiles automatically generated by
'rtiddsgen'. To test them, follow these steps:
(1) Compile this file and the example publication.
(2) Start the subscription with the command
objs/<arch>/profiles_subscriber <domain_id> <sample_count>
(3) Start the publication with the command
objs/<arch>/profiles_publisher <domain_id> <sample_count>
(4) [Optional] Specify the list of discovery initial peers and
multicast receive addresses via an environment variable or a file
(in the current working directory) called NDDS_DISCOVERY_PEERS.
You can run any number of publishers and subscribers programs, and can
add and remove them dynamically from the domain.
!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
!!! NOTE: This example will only work when dynamically linking. !!!
In Visual Studio, change the target to "Debug DLL" or "Release DLL"
to build.
!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
Example:
To run the example application on domain <domain_id>:
On UNIX systems:
objs/<arch>/profiles_publisher <domain_id>
objs/<arch>/profiles_subscriber <domain_id>
On Windows systems:
objs\<arch>\profiles_publisher <domain_id>
objs\<arch>\profiles_subscriber <domain_id>
modification history
------------ -------
*/
#include "ndds/ndds_c.h"
#include "profiles.h"
#include "profilesSupport.h"
#include <stdio.h>
#include <stdlib.h>
void profilesListener_on_requested_deadline_missed(
void *listener_data,
DDS_DataReader *reader,
const struct DDS_RequestedDeadlineMissedStatus *status)
{
}
void profilesListener_on_requested_incompatible_qos(
void *listener_data,
DDS_DataReader *reader,
const struct DDS_RequestedIncompatibleQosStatus *status)
{
}
void profilesListener_on_sample_rejected(
void *listener_data,
DDS_DataReader *reader,
const struct DDS_SampleRejectedStatus *status)
{
}
void profilesListener_on_liveliness_changed(
void *listener_data,
DDS_DataReader *reader,
const struct DDS_LivelinessChangedStatus *status)
{
}
void profilesListener_on_sample_lost(
void *listener_data,
DDS_DataReader *reader,
const struct DDS_SampleLostStatus *status)
{
}
void profilesListener_on_subscription_matched(
void *listener_data,
DDS_DataReader *reader,
const struct DDS_SubscriptionMatchedStatus *status)
{
}
void profilesListener_on_data_available(
void *listener_data,
DDS_DataReader *reader)
{
profilesDataReader *profiles_reader = NULL;
struct profilesSeq data_seq = DDS_SEQUENCE_INITIALIZER;
struct DDS_SampleInfoSeq info_seq = DDS_SEQUENCE_INITIALIZER;
DDS_ReturnCode_t retcode;
int i;
profiles_reader = profilesDataReader_narrow(reader);
if (profiles_reader == NULL) {
printf("DataReader narrow error\n");
return;
}
retcode = profilesDataReader_take(
profiles_reader,
&data_seq,
&info_seq,
DDS_LENGTH_UNLIMITED,
DDS_ANY_SAMPLE_STATE,
DDS_ANY_VIEW_STATE,
DDS_ANY_INSTANCE_STATE);
if (retcode == DDS_RETCODE_NO_DATA) {
return;
} else if (retcode != DDS_RETCODE_OK) {
printf("take error %d\n", retcode);
return;
}
for (i = 0; i < profilesSeq_get_length(&data_seq); ++i) {
if (DDS_SampleInfoSeq_get_reference(&info_seq, i)->valid_data) {
profilesTypeSupport_print_data(
profilesSeq_get_reference(&data_seq, i));
}
}
retcode = profilesDataReader_return_loan(
profiles_reader,
&data_seq,
&info_seq);
if (retcode != DDS_RETCODE_OK) {
printf("return loan error %d\n", retcode);
}
}
/* Delete all entities */
static int subscriber_shutdown(DDS_DomainParticipant *participant)
{
DDS_ReturnCode_t retcode;
int status = 0;
if (participant != NULL) {
retcode = DDS_DomainParticipant_delete_contained_entities(participant);
if (retcode != DDS_RETCODE_OK) {
printf("delete_contained_entities error %d\n", retcode);
status = -1;
}
retcode = DDS_DomainParticipantFactory_delete_participant(
DDS_TheParticipantFactory,
participant);
if (retcode != DDS_RETCODE_OK) {
printf("delete_participant error %d\n", retcode);
status = -1;
}
}
/* RTI Connext provides the finalize_instance() method on
domain participant factory for users who want to release memory used
by the participant factory. Uncomment the following block of code for
clean destruction of the singleton. */
/*
retcode = DDS_DomainParticipantFactory_finalize_instance();
if (retcode != DDS_RETCODE_OK) {
printf("finalize_instance error %d\n", retcode);
status = -1;
}
*/
return status;
}
static int subscriber_main(int domainId, int sample_count)
{
DDS_DomainParticipant *participant = NULL;
DDS_Subscriber *subscriber = NULL;
DDS_Topic *topic = NULL;
struct DDS_DataReaderListener reader_listener =
DDS_DataReaderListener_INITIALIZER;
DDS_DataReader *reader = NULL;
DDS_ReturnCode_t retcode;
const char *type_name = NULL;
int count = 0;
struct DDS_Duration_t poll_period = { 4, 0 };
/*
* This example uses a built-in QoS profile to enable monitoring on the
* DomainParticipant. The code below loads the XML QoS from the
* USER_QOS_PROFILES.xml file, which is inheriting from the
* "BuiltinQoSLib::Generic.Monitoring.Common" profile to enable monitoring.
*
* !!!! NOTE: This example will only work when dynamically linking !!!
* In Visual Studio, change the target to "Debug DLL" or "Release DLL"
* to build.
*/
/* To customize participant QoS, use
the configuration file USER_QOS_PROFILES.xml */
participant = DDS_DomainParticipantFactory_create_participant(
DDS_TheParticipantFactory,
domainId,
&DDS_PARTICIPANT_QOS_DEFAULT,
NULL /* listener */,
DDS_STATUS_MASK_NONE);
/* If you want to change the DomainParticipant's QoS programatically rather
* than using the XML file, you will need to add the following lines to
* your code and comment out the create_participant call above.
*
* This example uses a built-in QoS profile to enable
* monitoring on the DomainParticipant.*/
/*participant =
DDS_DomainParticipantFactory_create_participant_with_profile(
DDS_TheParticipantFactory, domainId,
DDS_BUILTIN_QOS_LIB, DDS_PROFILE_GENERIC_MONITORING_COMMON,
NULL /* listener * /, DDS_STATUS_MASK_NONE);
*/
if (participant == NULL) {
printf("create_participant error\n");
subscriber_shutdown(participant);
return -1;
}
/* To customize subscriber QoS, use
the configuration file USER_QOS_PROFILES.xml */
subscriber = DDS_DomainParticipant_create_subscriber(
participant,
&DDS_SUBSCRIBER_QOS_DEFAULT,
NULL /* listener */,
DDS_STATUS_MASK_NONE);
if (subscriber == NULL) {
printf("create_subscriber error\n");
subscriber_shutdown(participant);
return -1;
}
/* Register the type before creating the topic */
type_name = profilesTypeSupport_get_type_name();
retcode = profilesTypeSupport_register_type(participant, type_name);
if (retcode != DDS_RETCODE_OK) {
printf("register_type error %d\n", retcode);
subscriber_shutdown(participant);
return -1;
}
/* To customize topic QoS, use
the configuration file USER_QOS_PROFILES.xml */
topic = DDS_DomainParticipant_create_topic(
participant,
"Example profiles",
type_name,
&DDS_TOPIC_QOS_DEFAULT,
NULL /* listener */,
DDS_STATUS_MASK_NONE);
if (topic == NULL) {
printf("create_topic error\n");
subscriber_shutdown(participant);
return -1;
}
/* Set up a data reader listener */
reader_listener.on_requested_deadline_missed =
profilesListener_on_requested_deadline_missed;
reader_listener.on_requested_incompatible_qos =
profilesListener_on_requested_incompatible_qos;
reader_listener.on_sample_rejected = profilesListener_on_sample_rejected;
reader_listener.on_liveliness_changed =
profilesListener_on_liveliness_changed;
reader_listener.on_sample_lost = profilesListener_on_sample_lost;
reader_listener.on_subscription_matched =
profilesListener_on_subscription_matched;
reader_listener.on_data_available = profilesListener_on_data_available;
/* To customize data reader QoS, use
the configuration file USER_QOS_PROFILES.xml */
reader = DDS_Subscriber_create_datareader(
subscriber,
DDS_Topic_as_topicdescription(topic),
&DDS_DATAREADER_QOS_DEFAULT,
&reader_listener,
DDS_STATUS_MASK_ALL);
/* If you want to change the DataReader's QoS programatically rather
* than using the XML file, you will need to add the following lines to
* your code and comment out the create_datareader call above.
*
* This example uses a built-in QoS profile to tune the QoS for
* reliable streaming data. */
/*reader = DDS_Subscriber_create_datareader_with_profile(
subscriber, DDS_Topic_as_topicdescription(topic),
DDS_BUILTIN_QOS_LIB_EXP, DDS_PROFILE_PATTERN_RELIABLE_STREAMING,
&reader_listener, DDS_STATUS_MASK_ALL);
*/
if (reader == NULL) {
printf("create_datareader error\n");
subscriber_shutdown(participant);
return -1;
}
/* Main loop */
for (count = 0; (sample_count == 0) || (count < sample_count); ++count) {
printf("profiles subscriber sleeping for %d sec...\n", poll_period.sec);
NDDS_Utility_sleep(&poll_period);
}
/* Cleanup and delete all entities */
return subscriber_shutdown(participant);
}
#if defined(RTI_WINCE)
int wmain(int argc, wchar_t **argv)
{
int domainId = 0;
int sample_count = 0; /* infinite loop */
if (argc >= 2) {
domainId = _wtoi(argv[1]);
}
if (argc >= 3) {
sample_count = _wtoi(argv[2]);
}
/* Uncomment this to turn on additional logging
NDDS_Config_Logger_set_verbosity_by_category(
NDDS_Config_Logger_get_instance(),
NDDS_CONFIG_LOG_CATEGORY_API,
NDDS_CONFIG_LOG_VERBOSITY_STATUS_ALL);
*/
return subscriber_main(domainId, sample_count);
}
#elif !(defined(RTI_VXWORKS) && !defined(__RTP__)) && !defined(RTI_PSOS)
int main(int argc, char *argv[])
{
int domainId = 0;
int sample_count = 0; /* infinite loop */
if (argc >= 2) {
domainId = atoi(argv[1]);
}
if (argc >= 3) {
sample_count = atoi(argv[2]);
}
/* Uncomment this to turn on additional logging
NDDS_Config_Logger_set_verbosity_by_category(
NDDS_Config_Logger_get_instance(),
NDDS_CONFIG_LOG_CATEGORY_API,
NDDS_CONFIG_LOG_VERBOSITY_STATUS_ALL);
*/
return subscriber_main(domainId, sample_count);
}
#endif
#ifdef RTI_VX653
const unsigned char *__ctype = NULL;
void usrAppInit()
{
#ifdef USER_APPL_INIT
USER_APPL_INIT; /* for backwards compatibility */
#endif
/* add application specific code here */
taskSpawn(
"sub",
RTI_OSAPI_THREAD_PRIORITY_NORMAL,
0x8,
0x150000,
(FUNCPTR) subscriber_main,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0);
}
#endif
| c |
rticonnextdds-examples | data/projects/rticonnextdds-examples/connext_dds/builtin_qos_profiles/c++03/profiles_subscriber.cxx | /*******************************************************************************
(c) 2005-2015 Copyright, Real-Time Innovations, Inc. All rights reserved.
RTI grants Licensee a license to use, modify, compile, and create derivative
works of the Software. Licensee has the right to distribute object form only
for use with RTI products. The Software is provided "as is", with no warranty
of any type, including any warranty for fitness for any purpose. RTI is under
no obligation to maintain or support the Software. RTI shall not be liable for
any incidental or consequential damages arising out of the use or inability to
use the software.
******************************************************************************/
#include <iostream>
#include "profiles.hpp"
#include <dds/dds.hpp>
#include <rti/core/ListenerBinder.hpp>
using namespace dds::core;
using namespace dds::core::status;
using namespace dds::domain;
using namespace dds::domain::qos;
using namespace dds::topic;
using namespace dds::sub;
using namespace dds::sub::qos;
class ProfilesListener : public NoOpDataReaderListener<HelloWorld> {
public:
void on_data_available(DataReader<HelloWorld> &reader)
{
// Take all samples
LoanedSamples<HelloWorld> samples = reader.take();
for (LoanedSamples<HelloWorld>::iterator sample_it = samples.begin();
sample_it != samples.end();
sample_it++) {
if (sample_it->info().valid()) {
std::cout << sample_it->data() << std::endl;
}
}
}
};
void subscriber_main(int domain_id, int sample_count)
{
// Retrieve the Participant QoS from USER_QOS_PROFILES.xml
DomainParticipantQos participant_qos =
QosProvider::Default().participant_qos();
// This example uses a built-in QoS profile to enable monitoring on the
// DomainParticipant. This profile is specified in USER_QOS_PROFILES.xml.
// To enable it programmatically uncomment these lines.
// participant_qos = QosProvider::Default().participant_qos(
// "BuiltinQosLib::Generic.Monitoring.Common");
// Create a DomainParticipant.
DomainParticipant participant(domain_id, participant_qos);
// Create a Topic -- and automatically register the type.
Topic<HelloWorld> topic(participant, "Example profiles");
// Retrieve the DataReader QoS from USER_QOS_PROFILES.xml
DataReaderQos reader_qos = QosProvider::Default().datareader_qos();
// This example uses a built-in QoS profile to tune QoS for reliable
// streaming data. To enable it programmatically uncomment these lines.
// reader_qos = QosProvider::Default().datareader_qos(
// "BuiltinQosLibExp::Pattern.ReliableStreaming");
// Create a DataReader.
DataReader<HelloWorld> reader(Subscriber(participant), topic, reader_qos);
// Create a DataReader listener using ListenerBinder, a RAII utility that
// will take care of reseting it from the reader and deleting it.
rti::core::ListenerBinder<DataReader<HelloWorld> > scoped_listener =
rti::core::bind_and_manage_listener(
reader,
new ProfilesListener,
StatusMask::data_available());
// Main loop
for (int count = 0; (sample_count == 0) || (count < sample_count);
++count) {
std::cout << "profiles subscriber sleeping for 4 sec..." << std::endl;
rti::util::sleep(Duration(4));
}
}
int main(int argc, char *argv[])
{
int domain_id = 0;
int sample_count = 0; // Infinite loop
if (argc >= 2) {
domain_id = atoi(argv[1]);
}
if (argc >= 3) {
sample_count = atoi(argv[2]);
}
// To turn on additional logging, include <rti/config/Logger.hpp> and
// uncomment the following line:
// rti::config::Logger::instance().verbosity(rti::config::Verbosity::STATUS_ALL);
try {
subscriber_main(domain_id, sample_count);
} catch (const std::exception &ex) {
// This will catch DDS exceptions
std::cerr << "Exception in subscriber_main(): " << ex.what()
<< std::endl;
return -1;
}
return 0;
}
| cxx |
rticonnextdds-examples | data/projects/rticonnextdds-examples/connext_dds/builtin_qos_profiles/c++03/profiles_publisher.cxx | /*******************************************************************************
(c) 2005-2015 Copyright, Real-Time Innovations, Inc. All rights reserved.
RTI grants Licensee a license to use, modify, compile, and create derivative
works of the Software. Licensee has the right to distribute object form only
for use with RTI products. The Software is provided "as is", with no warranty
of any type, including any warranty for fitness for any purpose. RTI is under
no obligation to maintain or support the Software. RTI shall not be liable for
any incidental or consequential damages arising out of the use or inability to
use the software.
******************************************************************************/
#include "profiles.hpp"
#include <dds/dds.hpp>
#include <iostream>
using namespace dds::core;
using namespace dds::domain;
using namespace dds::domain::qos;
using namespace dds::topic;
using namespace dds::pub;
using namespace dds::pub::qos;
void publisher_main(int domain_id, int sample_count)
{
// Retrieve the Participant QoS from USER_QOS_PROFILES.xml
DomainParticipantQos participant_qos =
QosProvider::Default().participant_qos();
// This example uses a built-in QoS profile to enable monitoring on the
// DomainParticipant. This profile is specified in USER_QOS_PROFILES.xml.
// To enable it programmatically uncomment these lines.
// participant_qos = QosProvider::Default().participant_qos(
// "BuiltinQosLib::Generic.Monitoring.Common");
// Create a DomainParticipant.
DomainParticipant participant(domain_id, participant_qos);
// Create a Topic -- and automatically register the type.
Topic<HelloWorld> topic(participant, "Example profiles");
// Retrieve the DataWriter QoS from USER_QOS_PROFILES.xml
DataWriterQos writer_qos = QosProvider::Default().datawriter_qos();
// This example uses a built-in QoS profile to tune QoS for reliable
// streaming data. To enable it programmatically uncomment these lines.
// writer_qos = QosProvider::Default().datawriter_qos(
// "BuiltinQosLibExp::Pattern.ReliableStreaming");
// Create a Datawriter.
DataWriter<HelloWorld> writer(Publisher(participant), topic, writer_qos);
// Create a data sample for writing.
HelloWorld instance;
// Main loop
for (int count = 0; (sample_count == 0) || (count < sample_count);
++count) {
std::cout << "Writing profiles, count " << count << std::endl;
instance.msg("Hello World!");
writer.write(instance);
rti::util::sleep(Duration(4));
}
}
int main(int argc, char *argv[])
{
int domain_id = 0;
int sample_count = 0; // Infinite loop
if (argc >= 2) {
domain_id = atoi(argv[1]);
}
if (argc >= 3) {
sample_count = atoi(argv[2]);
}
// To turn on additional logging, include <rti/config/Logger.hpp> and
// uncomment the following line:
// rti::config::Logger::instance().verbosity(rti::config::Verbosity::STATUS_ALL);
try {
publisher_main(domain_id, sample_count);
} catch (std::exception ex) {
std::cout << "Exception caught: " << ex.what() << std::endl;
return -1;
}
return 0;
}
| cxx |
rticonnextdds-examples | data/projects/rticonnextdds-examples/connext_dds/builtin_qos_profiles/c++11/application.hpp | /*
* (c) Copyright, Real-Time Innovations, 2020. All rights reserved.
* RTI grants Licensee a license to use, modify, compile, and create derivative
* works of the software solely for use with RTI Connext DDS. Licensee may
* redistribute copies of the software provided that all such copies are subject
* to this license. The software is provided "as is", with no warranty of any
* type, including any warranty for fitness for any purpose. RTI is under no
* obligation to maintain or support the software. RTI shall not be liable for
* any incidental or consequential damages arising out of the use or inability
* to use the software.
*/
#ifndef APPLICATION_HPP
#define APPLICATION_HPP
#include <iostream>
#include <csignal>
#include <dds/core/ddscore.hpp>
namespace application {
// Catch control-C and tell application to shut down
bool shutdown_requested = false;
inline void stop_handler(int)
{
shutdown_requested = true;
std::cout << "preparing to shut down..." << std::endl;
}
inline void setup_signal_handlers()
{
signal(SIGINT, stop_handler);
signal(SIGTERM, stop_handler);
}
enum class ParseReturn { ok, failure, exit };
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/builtin_qos_profiles/c++11/profiles_subscriber.cxx | /*******************************************************************************
(c) 2005-2015 Copyright, Real-Time Innovations, Inc. All rights reserved.
RTI grants Licensee a license to use, modify, compile, and create derivative
works of the Software. Licensee has the right to distribute object form only
for use with RTI products. The Software is provided "as is", with no warranty
of any type, including any warranty for fitness for any purpose. RTI is under
no obligation to maintain or support the Software. RTI shall not be liable for
any incidental or consequential damages arising out of the use or inability to
use the software.
******************************************************************************/
#include <iostream>
#include <dds/sub/ddssub.hpp>
#include <dds/core/ddscore.hpp>
#include <rti/config/Logger.hpp> // for logging
#include "profiles.hpp"
#include "application.hpp" // for command line parsing and ctrl-c
int process_data(dds::sub::DataReader<HelloWorld> reader)
{
// Take all samples
int count = 0;
dds::sub::LoanedSamples<HelloWorld> samples = reader.take();
for (const auto &sample : samples) {
if (sample.info().valid()) {
count++;
std::cout << sample.data() << std::endl;
} else {
std::cout << "Instance state changed to "
<< sample.info().state().instance_state() << std::endl;
}
}
return count;
}
void run_subscriber_application(int domain_id, int sample_count)
{
// Retrieve the Participant QoS from USER_QOS_PROFILES.xml
dds::domain::qos::DomainParticipantQos participant_qos =
dds::core::QosProvider::Default().participant_qos();
// This example uses a built-in QoS profile to enable monitoring on the
// DomainParticipant. This profile is specified in USER_QOS_PROFILES.xml.
// To enable it programmatically uncomment these lines.
// participant_qos = QosProvider::Default().participant_qos(
// "BuiltinQosLib::Generic.Monitoring.Common");
// Create a DomainParticipant.
dds::domain::DomainParticipant participant(domain_id, participant_qos);
// Create a Topic -- and automatically register the type.
dds::topic::Topic<HelloWorld> topic(participant, "Example profiles");
// Retrieve the DataReader QoS from USER_QOS_PROFILES.xml
dds::sub::qos::DataReaderQos reader_qos =
dds::core::QosProvider::Default().datareader_qos();
// This example uses a built-in QoS profile to tune QoS for reliable
// streaming data. To enable it programmatically uncomment these lines.
// reader_qos = QosProvider::Default().datareader_qos(
// "BuiltinQosLibExp::Pattern.ReliableStreaming");
// Create a Subscriber and DataReader with a Qos
dds::sub::Subscriber subscriber(participant);
dds::sub::DataReader<HelloWorld> 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::any(),
[reader, &samples_read]() {
samples_read += process_data(reader);
});
waitset += read_condition;
// Main loop
while (!application::shutdown_requested && samples_read < sample_count) {
std::cout << "profiles subscriber sleeping up to 4 sec..." << std::endl;
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/builtin_qos_profiles/c++11/profiles_publisher.cxx | /*******************************************************************************
(c) 2005-2015 Copyright, Real-Time Innovations, Inc. All rights reserved.
RTI grants Licensee a license to use, modify, compile, and create derivative
works of the Software. Licensee has the right to distribute object form only
for use with RTI products. The Software is provided "as is", with no warranty
of any type, including any warranty for fitness for any purpose. RTI is under
no obligation to maintain or support the Software. RTI shall not be liable for
any incidental or consequential damages arising out of the use or inability to
use the software.
******************************************************************************/
#include <iostream>
#include <dds/pub/ddspub.hpp>
#include <rti/util/util.hpp> // for sleep()
#include <rti/config/Logger.hpp> // for logging
#include "application.hpp" // for command line parsing and ctrl-c
#include "profiles.hpp"
void run_publisher_application(int domain_id, int sample_count)
{
// Retrieve the Participant QoS from USER_QOS_PROFILES.xml
dds::domain::qos::DomainParticipantQos participant_qos =
dds::core::QosProvider::Default().participant_qos();
// This example uses a built-in QoS profile to enable monitoring on the
// DomainParticipant. This profile is specified in USER_QOS_PROFILES.xml.
// To enable it programmatically uncomment these lines.
// participant_qos = QosProvider::Default().participant_qos(
// "BuiltinQosLib::Generic.Monitoring.Common");
// Create a DomainParticipant.
dds::domain::DomainParticipant participant(domain_id, participant_qos);
// Create a Topic -- and automatically register the type.
dds::topic::Topic<HelloWorld> topic(participant, "Example profiles");
// Retrieve the DataWriter QoS from USER_QOS_PROFILES.xml
dds::pub::qos::DataWriterQos writer_qos =
dds::core::QosProvider::Default().datawriter_qos();
// This example uses a built-in QoS profile to tune QoS for reliable
// streaming data. To enable it programmatically uncomment these lines.
// writer_qos = QosProvider::Default().datawriter_qos(
// "BuiltinQosLibExp::Pattern.ReliableStreaming");
// Create a Publisher
dds::pub::Publisher publisher(participant);
// Create a Datawriter.
dds::pub::DataWriter<HelloWorld> writer(publisher, topic, writer_qos);
// Create a data sample for writing.
HelloWorld instance;
for (unsigned int samples_written = 0;
!application::shutdown_requested && samples_written < sample_count;
samples_written++) {
// Modify the data to be written here
instance.msg("Hello World!");
std::cout << "Writing HelloWord, count " << samples_written
<< std::endl;
writer.write(instance);
// Send once every second
rti::util::sleep(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_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/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/connext_dds/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/connext_dds/persistent_storage/c/hello_world_publisher.c | /*******************************************************************************
(c) 2005-2014 Copyright, Real-Time Innovations, Inc. All rights reserved.
RTI grants Licensee a license to use, modify, compile, and create derivative
works of the Software. Licensee has the right to distribute object form only
for use with RTI products. The Software is provided "as is", with no warranty
of any type, including any warranty for fitness for any purpose. RTI is under
no obligation to maintain or support the Software. RTI shall not be liable for
any incidental or consequential damages arising out of the use or inability to
use the software.
******************************************************************************/
/* hello_world_publisher.c
A publication of data of type hello_world
This file is derived from code automatically generated by the rtiddsgen
command:
rtiddsgen -language C -example <arch> hello_world.idl
Example publication of type hello_world automatically generated by
'rtiddsgen'. To test them follow these steps:
(1) Compile this file and the example subscription.
(2) Start the subscription with the command
objs/<arch>/hello_world_subscriber <domain_id> <sample_count>
(3) Start the publication with the command
objs/<arch>/hello_world_publisher <domain_id> <sample_count>
(4) [Optional] Specify the list of discovery initial peers and
multicast receive addresses via an environment variable or a file
(in the current working directory) called NDDS_DISCOVERY_PEERS.
You can run any number of publishers and subscribers programs, and can
add and remove them dynamically from the domain.
Example:
To run the example application on domain <domain_id>:
On Unix:
objs/<arch>/hello_world_publisher <domain_id>
objs/<arch>/hello_world_subscriber <domain_id>
On Windows:
objs\<arch>\hello_world_publisher <domain_id>
objs\<arch>\hello_world_subscriber <domain_id>
*/
#include <stdio.h>
#include <stdlib.h>
#include "ndds/ndds_c.h"
#include "hello_world.h"
#include "hello_worldSupport.h"
/******************************************************************************
Macros to read input parameters
******************************************************************************/
#define READ_INTEGER_PARAM(parameter,outValue)\
if (!strcmp(argv[i],parameter)) {\
if (i+1 >= argc) {\
printf("%s",syntax);\
return 1;\
}\
i++;\
outValue = atoi(argv[i]);\
i++;\
continue;\
}
#define READ_STRING_PARAM(parameter,outValue)\
if (!strcmp(argv[i],parameter)) {\
if (i+1 >= argc) {\
printf("%s",syntax);\
return 1;\
}\
i++;\
outValue=rgv[i];\
i++;\
continue;\
}
/* Delete all entities */
static int publisher_shutdown(DDS_DomainParticipant *participant) {
DDS_ReturnCode_t retcode;
int status = 0;
if (participant != NULL) {
retcode = DDS_DomainParticipant_delete_contained_entities(participant);
if (retcode != DDS_RETCODE_OK) {
printf("delete_contained_entities error %d\n", retcode);
status = -1;
}
retcode = DDS_DomainParticipantFactory_delete_participant(
DDS_TheParticipantFactory, participant);
if (retcode != DDS_RETCODE_OK) {
printf("delete_participant error %d\n", retcode);
status = -1;
}
}
/* RTI Connext provides finalize_instance() method on
domain participant factory for people who want to release memory used
by the participant factory. Uncomment the following block of code for
clean destruction of the singleton. */
/*
retcode = DDS_DomainParticipantFactory_finalize_instance();
if (retcode != DDS_RETCODE_OK) {
printf("finalize_instance error %d\n", retcode);
status = -1;
}
*/
return status;
}
static int publisher_main(int domain_id, int sample_count, int initial_count,
int dwh, int sleep) {
DDS_DomainParticipant *participant = NULL;
DDS_Publisher *publisher = NULL;
DDS_Topic *topic = NULL;
DDS_DataWriter *writer = NULL;
struct DDS_DataWriterQos writer_qos = DDS_DataWriterQos_INITIALIZER;
hello_worldDataWriter *hello_world_writer = NULL;
hello_world *instance = NULL;
DDS_ReturnCode_t retcode;
DDS_InstanceHandle_t instance_handle = DDS_HANDLE_NIL;
const char *type_name = NULL;
int count = 0;
struct DDS_Duration_t send_period = { 1, 0 };
struct DDS_Duration_t one_sec = { 1, 0 };
/* To customize participant QoS, use the configuration file
* USER_QOS_PROFILES.xml */
participant = DDS_DomainParticipantFactory_create_participant(
DDS_TheParticipantFactory, domain_id, &DDS_PARTICIPANT_QOS_DEFAULT,
NULL /* listener */, DDS_STATUS_MASK_NONE);
if (participant == NULL) {
printf("create_participant error\n");
publisher_shutdown(participant);
return -1;
}
/* To customize publisher QoS, use the configuration file
* USER_QOS_PROFILES.xml */
publisher = DDS_DomainParticipant_create_publisher(participant,
&DDS_PUBLISHER_QOS_DEFAULT, NULL /* listener */,
DDS_STATUS_MASK_NONE);
if (publisher == NULL) {
printf("create_publisher error\n");
publisher_shutdown(participant);
return -1;
}
/* Register type before creating topic */
type_name = hello_worldTypeSupport_get_type_name();
retcode = hello_worldTypeSupport_register_type(participant, type_name);
if (retcode != DDS_RETCODE_OK) {
printf("register_type error %d\n", retcode);
publisher_shutdown(participant);
return -1;
}
/* To customize topic QoS, use
the configuration file USER_QOS_PROFILES.xml */
topic = DDS_DomainParticipant_create_topic(participant,
"Example hello_world", type_name, &DDS_TOPIC_QOS_DEFAULT,
NULL /* listener */, DDS_STATUS_MASK_NONE);
if (topic == NULL) {
printf("create_topic error\n");
publisher_shutdown(participant);
return -1;
}
/* If you use Durable Writer History, you need to set
* several properties. These properties are set in the USER_QOS_PROFILE.xml
* file, "durable_writer_history_Profile" profile. See that file for further
* details.
*/
if (dwh == 1) {
writer = DDS_Publisher_create_datawriter_with_profile(publisher, topic,
"persistence_example_Library", "durable_writer_history_Profile",
NULL /* listener */, DDS_STATUS_MASK_NONE);
if (writer == NULL) {
printf("create_datawriter error\n");
publisher_shutdown(participant);
return -1;
}
} else {
writer = DDS_Publisher_create_datawriter_with_profile(publisher, topic,
"persistence_example_Library", "persistence_service_Profile",
NULL /* listener */, DDS_STATUS_MASK_NONE);
if (writer == NULL) {
printf("create_datawriter error\n");
publisher_shutdown(participant);
return -1;
}
}
hello_world_writer = hello_worldDataWriter_narrow(writer);
if (hello_world_writer == NULL) {
printf("DataWriter narrow error\n");
publisher_shutdown(participant);
return -1;
}
/* Create data sample for writing */
instance = hello_worldTypeSupport_create_data_ex(DDS_BOOLEAN_TRUE);
if (instance == NULL) {
printf("hello_worldTypeSupport_create_data error\n");
publisher_shutdown(participant);
return -1;
}
/* For a data type that has a key, if the same instance is going to be
written multiple times, initialize the key here
and register the keyed instance prior to writing */
/*
instance_handle = hello_worldDataWriter_register_instance(
hello_world_writer, instance);
*/
/* Main loop */
for (count = 0; (sample_count == 0) || (count < sample_count); ++count) {
printf("Writing hello_world, count %d\n", initial_count);
/* Modify the data to be written here */
instance->data = initial_count;
initial_count++;
/* Write data */
retcode = hello_worldDataWriter_write(hello_world_writer, instance,
&instance_handle);
if (retcode != DDS_RETCODE_OK) {
printf("write error %d\n", retcode);
}
NDDS_Utility_sleep(&send_period);
}
while (sleep != 0) {
NDDS_Utility_sleep(&one_sec);
sleep--;
}
/*
retcode = hello_worldDataWriter_unregister_instance(
hello_world_writer, instance, &instance_handle);
if (retcode != DDS_RETCODE_OK) {
printf("unregister instance error %d\n", retcode);
}
*/
/* Delete data sample */
retcode = hello_worldTypeSupport_delete_data_ex(instance, DDS_BOOLEAN_TRUE);
if (retcode != DDS_RETCODE_OK) {
printf("hello_worldTypeSupport_delete_data error %d\n", retcode);
}
/* Cleanup and delete delete all entities */
return publisher_shutdown(participant);
}
int main(int argc, char *argv[]) {
int domain_id = 0;
int sample_count = 0; /* infinite loop */
int initial_value = 0;
int dwh = 0;
int sleep = 0;
char syntax[1024];
int i;
sprintf(syntax,
"%s [options] \n\
-domain_id <domain ID> (default: 0)\n\
-sample_count <number of published samples> (default: infinite)\n\
-initial_value <first sample value> (default: 0)\n\
-sleep <sleep time in seconds before finishing> (default: 0)\n\
-dwh <1|0> Enable/Disable durable writer history (default: 0)\n",
argv[0]);
for (i = 1; i < argc;) {
READ_INTEGER_PARAM("-sleep", sleep);
READ_INTEGER_PARAM("-domain_id", domain_id);
READ_INTEGER_PARAM("-sample_count", sample_count);
READ_INTEGER_PARAM("-initial_value", initial_value);
READ_INTEGER_PARAM("-dwh", dwh);
printf("%s", syntax);
return 0;
}
/* Uncomment this to turn on additional logging
NDDS_Config_Logger_set_verbosity_by_category(
NDDS_Config_Logger_get_instance(),
NDDS_CONFIG_LOG_CATEGORY_API,
NDDS_CONFIG_LOG_VERBOSITY_STATUS_ALL);
*/
return publisher_main(domain_id, sample_count, initial_value, dwh, sleep);
}
#ifdef RTI_VX653
const unsigned char* __ctype = NULL;
void usrAppInit ()
{
#ifdef USER_APPL_INIT
USER_APPL_INIT; /* for backwards compatibility */
#endif
/* add application specific code here */
taskSpawn("pub", RTI_OSAPI_THREAD_PRIORITY_NORMAL, 0x8, 0x150000,
(FUNCPTR)publisher_main, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
}
#endif
| c |
rticonnextdds-examples | data/projects/rticonnextdds-examples/connext_dds/persistent_storage/c/hello_world_subscriber.c | /*******************************************************************************
(c) 2005-2014 Copyright, Real-Time Innovations, Inc. All rights reserved.
RTI grants Licensee a license to use, modify, compile, and create derivative
works of the Software. Licensee has the right to distribute object form only
for use with RTI products. The Software is provided "as is", with no warranty
of any type, including any warranty for fitness for any purpose. RTI is under
no obligation to maintain or support the Software. RTI shall not be liable for
any incidental or consequential damages arising out of the use or inability to
use the software.
******************************************************************************/
/* hello_world_subscriber.c
A subscription example
This file is derived from code automatically generated by the rtiddsgen
command:
rtiddsgen -language C -example <arch> hello_world.idl
Example subscription of type hello_world automatically generated by
'rtiddsgen'. To test them, follow these steps:
(1) Compile this file and the example publication.
(2) Start the subscription with the command
objs/<arch>/hello_world_subscriber <domain_id> <sample_count>
(3) Start the publication with the command
objs/<arch>/hello_world_publisher <domain_id> <sample_count>
(4) [Optional] Specify the list of discovery initial peers and
multicast receive addresses via an environment variable or a file
(in the current working directory) called NDDS_DISCOVERY_PEERS.
You can run any number of publishers and subscribers programs, and can
add and remove them dynamically from the domain.
Example:
To run the example application on domain <domain_id>:
On UNIX systems:
objs/<arch>/hello_world_publisher <domain_id>
objs/<arch>/hello_world_subscriber <domain_id>
On Windows systems:
objs\<arch>\hello_world_publisher <domain_id>
objs\<arch>\hello_world_subscriber <domain_id>
*/
#include <stdio.h>
#include <stdlib.h>
#include "ndds/ndds_c.h"
#include "hello_world.h"
#include "hello_worldSupport.h"
/******************************************************************************
Macros to read input parameters
******************************************************************************/
#define READ_INTEGER_PARAM(parameter,outValue)\
if (!strcmp(argv[i],parameter)) {\
if (i+1 >= argc) {\
printf("%s",syntax);\
return 1;\
}\
i++;\
outValue = atoi(argv[i]);\
i++;\
continue;\
}
#define READ_STRING_PARAM(parameter,outValue)\
if (!strcmp(argv[i],parameter)) {\
if (i+1 >= argc) {\
printf("%s",syntax);\
return 1;\
}\
i++;\
outValue=argv[i];\
i++;\
continue;\
}
void hello_worldListener_on_requested_deadline_missed(void* listener_data,
DDS_DataReader* reader,
const struct DDS_RequestedDeadlineMissedStatus *status) {
}
void hello_worldListener_on_requested_incompatible_qos(void* listener_data,
DDS_DataReader* reader,
const struct DDS_RequestedIncompatibleQosStatus *status) {
}
void hello_worldListener_on_sample_rejected(void* listener_data,
DDS_DataReader* reader, const struct DDS_SampleRejectedStatus *status) {
}
void hello_worldListener_on_liveliness_changed(void* listener_data,
DDS_DataReader* reader,
const struct DDS_LivelinessChangedStatus *status) {
}
void hello_worldListener_on_sample_lost(void* listener_data,
DDS_DataReader* reader, const struct DDS_SampleLostStatus *status) {
}
void hello_worldListener_on_subscription_matched(void* listener_data,
DDS_DataReader* reader,
const struct DDS_SubscriptionMatchedStatus *status) {
}
void hello_worldListener_on_data_available(void* listener_data,
DDS_DataReader* reader) {
hello_worldDataReader *hello_world_reader = NULL;
struct hello_worldSeq data_seq = DDS_SEQUENCE_INITIALIZER;
struct DDS_SampleInfoSeq info_seq = DDS_SEQUENCE_INITIALIZER;
DDS_ReturnCode_t retcode;
int i;
hello_world_reader = hello_worldDataReader_narrow(reader);
if (hello_world_reader == NULL) {
printf("DataReader narrow error\n");
return;
}
retcode = hello_worldDataReader_take(hello_world_reader, &data_seq,
&info_seq, DDS_LENGTH_UNLIMITED, DDS_ANY_SAMPLE_STATE,
DDS_ANY_VIEW_STATE, DDS_ANY_INSTANCE_STATE);
if (retcode == DDS_RETCODE_NO_DATA) {
return;
} else if (retcode != DDS_RETCODE_OK) {
printf("take error %d\n", retcode);
return;
}
for (i = 0; i < hello_worldSeq_get_length(&data_seq); ++i) {
if (DDS_SampleInfoSeq_get_reference(&info_seq, i)->valid_data) {
hello_worldTypeSupport_print_data(
hello_worldSeq_get_reference(&data_seq, i));
}
}
retcode = hello_worldDataReader_return_loan(hello_world_reader, &data_seq,
&info_seq);
if (retcode != DDS_RETCODE_OK) {
printf("return loan error %d\n", retcode);
}
}
/* Delete all entities */
static int subscriber_shutdown(DDS_DomainParticipant *participant) {
DDS_ReturnCode_t retcode;
int status = 0;
if (participant != NULL) {
retcode = DDS_DomainParticipant_delete_contained_entities(participant);
if (retcode != DDS_RETCODE_OK) {
printf("delete_contained_entities error %d\n", retcode);
status = -1;
}
retcode = DDS_DomainParticipantFactory_delete_participant(
DDS_TheParticipantFactory, participant);
if (retcode != DDS_RETCODE_OK) {
printf("delete_participant error %d\n", retcode);
status = -1;
}
}
/* RTI Connext provides the finalize_instance() method on
domain participant factory for users who want to release memory used
by the participant factory. Uncomment the following block of code for
clean destruction of the singleton. */
/*
retcode = DDS_DomainParticipantFactory_finalize_instance();
if (retcode != DDS_RETCODE_OK) {
printf("finalize_instance error %d\n", retcode);
status = -1;
}
*/
return status;
}
static int subscriber_main(int domain_id, int sample_count, int drs) {
DDS_DomainParticipant *participant = NULL;
DDS_Subscriber *subscriber = NULL;
DDS_Topic *topic = NULL;
struct DDS_DataReaderListener reader_listener =
DDS_DataReaderListener_INITIALIZER;
struct DDS_DataReaderQos reader_qos = DDS_DataReaderQos_INITIALIZER;
DDS_DataReader *reader = NULL;
DDS_ReturnCode_t retcode;
const char *type_name = NULL;
int count = 0;
struct DDS_Duration_t poll_period = { 4, 0 };
/* To customize participant QoS, use
the configuration file USER_QOS_PROFILES.xml */
participant = DDS_DomainParticipantFactory_create_participant(
DDS_TheParticipantFactory, domain_id, &DDS_PARTICIPANT_QOS_DEFAULT,
NULL /* listener */, DDS_STATUS_MASK_NONE);
if (participant == NULL) {
printf("create_participant error\n");
subscriber_shutdown(participant);
return -1;
}
/* To customize subscriber QoS, use
the configuration file USER_QOS_PROFILES.xml */
subscriber = DDS_DomainParticipant_create_subscriber(participant,
&DDS_SUBSCRIBER_QOS_DEFAULT, NULL /* listener */,
DDS_STATUS_MASK_NONE);
if (subscriber == NULL) {
printf("create_subscriber error\n");
subscriber_shutdown(participant);
return -1;
}
/* Register the type before creating the topic */
type_name = hello_worldTypeSupport_get_type_name();
retcode = hello_worldTypeSupport_register_type(participant, type_name);
if (retcode != DDS_RETCODE_OK) {
printf("register_type error %d\n", retcode);
subscriber_shutdown(participant);
return -1;
}
/* To customize topic QoS, use
the configuration file USER_QOS_PROFILES.xml */
topic = DDS_DomainParticipant_create_topic(participant,
"Example hello_world", type_name, &DDS_TOPIC_QOS_DEFAULT,
NULL /* listener */, DDS_STATUS_MASK_NONE);
if (topic == NULL) {
printf("create_topic error\n");
subscriber_shutdown(participant);
return -1;
}
/* Set up a data reader listener */
reader_listener.on_requested_deadline_missed =
hello_worldListener_on_requested_deadline_missed;
reader_listener.on_requested_incompatible_qos =
hello_worldListener_on_requested_incompatible_qos;
reader_listener.on_sample_rejected = hello_worldListener_on_sample_rejected;
reader_listener.on_liveliness_changed =
hello_worldListener_on_liveliness_changed;
reader_listener.on_sample_lost = hello_worldListener_on_sample_lost;
reader_listener.on_subscription_matched =
hello_worldListener_on_subscription_matched;
reader_listener.on_data_available = hello_worldListener_on_data_available;
/* If you use Durable Reader State, you need to set up several properties.
* In this example, we have modified them using a QoS XML profile. See
* further details in USER_QOS_PROFILES.xml.
*/
if (drs == 1) {
reader = DDS_Subscriber_create_datareader_with_profile(subscriber,
DDS_Topic_as_topicdescription(topic),
"persistence_example_Library", "durable_reader_state_Profile",
&reader_listener, DDS_STATUS_MASK_ALL);
if (reader == NULL) {
printf("create_datareader error\n");
subscriber_shutdown(participant);
return -1;
}
} else {
reader = DDS_Subscriber_create_datareader_with_profile(subscriber,
DDS_Topic_as_topicdescription(topic),
"persistence_example_Library", "persistence_service_Profile",
&reader_listener, DDS_STATUS_MASK_ALL);
if (reader == NULL) {
printf("create_datareader error\n");
subscriber_shutdown(participant);
return -1;
}
}
/* Main loop */
for (count = 0; (sample_count == 0) || (count < sample_count); ++count) {
printf("hello_world subscriber sleeping for %d sec...\n",
poll_period.sec);
NDDS_Utility_sleep(&poll_period);
}
/* Cleanup and delete all entities */
return subscriber_shutdown(participant);
}
int main(int argc, char *argv[]) {
int domain_id = 0;
int drs = 0;
int i;
char syntax[1024];
int sample_count = 0; /* infinite loop */
sprintf(syntax,
"%s [options] \n\
-domain_id <domain ID> (default: 0)\n\
-sample_count <sample_count> (default: infinite => 0) \n\
-drs <1|0> Enable/Disable durable reader state (default: 0)\n",
argv[0]);
for (i = 1; i < argc;) {
READ_INTEGER_PARAM("-sample_count", sample_count);
READ_INTEGER_PARAM("-domain_id", domain_id);
READ_INTEGER_PARAM("-drs", drs);
printf("%s", syntax);
return 0;
}
/* Uncomment this to turn on additional logging
NDDS_Config_Logger_set_verbosity_by_category(
NDDS_Config_Logger_get_instance(),
NDDS_CONFIG_LOG_CATEGORY_API,
NDDS_CONFIG_LOG_VERBOSITY_STATUS_ALL);
*/
return subscriber_main(domain_id, sample_count, drs);
}
#ifdef RTI_VX653
const unsigned char* __ctype = NULL;
void usrAppInit ()
{
#ifdef USER_APPL_INIT
USER_APPL_INIT; /* for backwards compatibility */
#endif
/* add application specific code here */
taskSpawn("sub", RTI_OSAPI_THREAD_PRIORITY_NORMAL, 0x8, 0x150000,
(FUNCPTR)subscriber_main, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
}
#endif
| c |
rticonnextdds-examples | data/projects/rticonnextdds-examples/connext_dds/persistent_storage/c++03/hello_world_subscriber.cxx | /*******************************************************************************
(c) 2005-2015 Copyright, Real-Time Innovations, Inc. All rights reserved.
RTI grants Licensee a license to use, modify, compile, and create derivative
works of the Software. Licensee has the right to distribute object form only
for use with RTI products. The Software is provided "as is", with no warranty
of any type, including any warranty for fitness for any purpose. RTI is under
no obligation to maintain or support the Software. RTI shall not be liable for
any incidental or consequential damages arising out of the use or inability to
use the software.
******************************************************************************/
#include <cstdlib>
#include <algorithm>
#include <iostream>
#include <dds/dds.hpp>
#include <rti/core/ListenerBinder.hpp>
#include "hello_world.hpp"
using namespace dds::core;
using namespace dds::core::status;
using namespace dds::domain;
using namespace dds::topic;
using namespace dds::sub;
using namespace dds::sub::qos;
class hello_worldReaderListener : public NoOpDataReaderListener<hello_world> {
public:
void on_data_available(DataReader<hello_world>& reader)
{
// Take all samples
LoanedSamples<hello_world> samples = reader.take();
for (LoanedSamples<hello_world>::iterator sample_it = samples.begin();
sample_it != samples.end();
sample_it++) {
if (sample_it->info().valid()){
std::cout << sample_it->data() << std::endl;
}
}
}
};
void subscriber_main(int domain_id, int sample_count, bool drs)
{
// Create a DomainParticipant with default Qos
DomainParticipant participant(domain_id);
// Create a Topic -- and automatically register the type
Topic<hello_world> topic(participant, "Example hello_world");
// If you use Durable Reader State, you need to set up several properties.
// In this example, we have modified them using a QoS XML profile. See
// further details in USER_QOS_PROFILES.xml.
std::string qos_libname = "persistence_example_Library";
DataReaderQos reader_qos = drs ?
QosProvider::Default().datareader_qos(
qos_libname + "::durable_reader_state_Profile") :
QosProvider::Default().datareader_qos(
qos_libname + "::persistence_service_Profile");
// Create a DataReader (Subscriber created in-line)
DataReader<hello_world> reader(Subscriber(participant), topic, reader_qos);
// Create a data reader listener using ListenerBinder, a RAII that
// will take care of setting it to NULL on destruction.
rti::core::ListenerBinder< DataReader<hello_world> > scoped_listener =
rti::core::bind_and_manage_listener(
reader,
new hello_worldReaderListener,
StatusMask::data_available());
for (int count = 0; sample_count == 0 || count < sample_count; ++count) {
std::cout << "hello_world subscriber sleeping for 4 sec..."
<< std::endl;
rti::util::sleep(Duration(4));
}
}
int main(int argc, char *argv[])
{
int domain_id = 0;
int sample_count = 0; // Infinite loop
bool drs = false;
for (int i = 1; i < argc; ) {
const std::string& param = argv[i++];
if (param == "-domain_id" && i < argc) {
domain_id = atoi(argv[i++]);
} else if (param == "-sample_count" && i < argc) {
sample_count = atoi(argv[i++]);
} else if (param == "-drs" && i < argc) {
drs = (atoi(argv[i++]) == 1);
} else {
std::cout << argv[0] << " [options]" << std::endl
<< "\t-domain_id <domain ID> (default: 0)" << std::endl
<< "\t-sample_count <number of published samples> "
<< "(default: 0 (infinite))" << std::endl
<< "\t-drs <1|0> Enable/Disable durable reader state "
<< "(default: 0)" << std::endl;
return -1;
}
}
// To turn on additional logging, include <rti/config/Logger.hpp> and
// uncomment the following line:
// rti::config::Logger::instance().verbosity(rti::config::Verbosity::STATUS_ALL);
try {
subscriber_main(domain_id, sample_count, drs);
} catch (const std::exception& ex) {
// This will catch DDS exceptions
std::cerr << "Exception in publisher_main: " << ex.what() << std::endl;
return -1;
}
return 0;
}
| cxx |
rticonnextdds-examples | data/projects/rticonnextdds-examples/connext_dds/persistent_storage/c++03/hello_world_publisher.cxx | /*******************************************************************************
(c) 2005-2015 Copyright, Real-Time Innovations, Inc. All rights reserved.
RTI grants Licensee a license to use, modify, compile, and create derivative
works of the Software. Licensee has the right to distribute object form only
for use with RTI products. The Software is provided "as is", with no warranty
of any type, including any warranty for fitness for any purpose. RTI is under
no obligation to maintain or support the Software. RTI shall not be liable for
any incidental or consequential damages arising out of the use or inability to
use the software.
******************************************************************************/
#include <cstdlib>
#include <iostream>
#include <dds/dds.hpp>
#include "hello_world.hpp"
using namespace dds::core;
using namespace dds::domain;
using namespace dds::topic;
using namespace dds::pub;
using namespace dds::pub::qos;
void publisher_main(int domain_id, int sample_count, int initial_value,
bool use_durable_writer_history, int sleep)
{
// Create a DomainParticipant with default Qos
DomainParticipant participant(domain_id);
// Create a Topic -- and automatically register the type
Topic<hello_world> topic(participant, "Example hello_world");
// If you use Durable Writer History, you need to set several properties.
// These properties are set in the USER_QOS_PROFILE.xml file,
// "durable_writer_history_Profile" profile. See that file for further
// details.
std::string qos_libname = "persistence_example_Library";
DataWriterQos writer_qos = use_durable_writer_history ?
QosProvider::Default().datawriter_qos(
qos_libname + "::durable_writer_history_Profile") :
QosProvider::Default().datawriter_qos(
qos_libname + "::persistence_service_Profile");
// Create a DataWriter (Publisher created in-line)
DataWriter<hello_world> writer(Publisher(participant), topic, writer_qos);
hello_world sample;
for (int count = 0; count < sample_count || sample_count == 0; count++) {
std::cout << "Writing hello_world, count " << count << std::endl;
sample.data(initial_value++);
writer.write(sample);
rti::util::sleep(Duration(1));
}
while (sleep != 0) {
rti::util::sleep(Duration(1));
sleep--;
}
}
int main(int argc, char *argv[])
{
int domain_id = 0;
int sample_count = 0; // Infinite loop
int initial_value = 0;
bool use_durable_writer_history = false;
int sleep = 0;
for (int i = 1; i < argc; ) {
const std::string& param = argv[i++];
if (param == "-sleep" && i < argc) {
sleep = atoi(argv[i++]);
} else if (param == "-domain_id" && i < argc) {
domain_id = atoi(argv[i++]);
} else if (param == "-sample_count" && i < argc) {
sample_count = atoi(argv[i++]);
} else if (param == "-initial_value" && i < argc) {
initial_value = atoi(argv[i++]);
} else if (param == "-dwh" && i < argc) {
use_durable_writer_history = (atoi(argv[i++]) == 1);
} else {
std::cout << argv[0] << " [options]" << std::endl
<< "\t-domain_id <domain ID> (default: 0)" << std::endl
<< "\t-sample_count <number of published samples> "
<< "(default: 0 (infinite))" << std::endl
<< "\t-initial_value <first sample value> (default: 0)"
<< std::endl
<< "\t-sleep <sleep time in seconds before finishing> "
<< "(default: 0)" << std::endl
<< "\t-dwh <1|0> Enable/Disable durable writer history "
<< "(default: 0)" << std::endl;
return -1;
}
}
// To turn on additional logging, include <rti/config/Logger.hpp> and
// uncomment the following line:
// rti::config::Logger::instance().verbosity(rti::config::Verbosity::STATUS_ALL);
try {
publisher_main(domain_id, sample_count, initial_value,
use_durable_writer_history, sleep);
} catch (const std::exception& ex) {
// This will catch DDS exceptions
std::cerr << "Exception in publisher_main: " << ex.what() << std::endl;
return -1;
}
return 0;
}
| cxx |
rticonnextdds-examples | data/projects/rticonnextdds-examples/connext_dds/time_based_filter/c++/tbf_subscriber.cxx | /*******************************************************************************
(c) 2005-2014 Copyright, Real-Time Innovations, Inc. All rights reserved.
RTI grants Licensee a license to use, modify, compile, and create derivative
works of the Software. Licensee has the right to distribute object form only
for use with RTI products. The Software is provided "as is", with no warranty
of any type, including any warranty for fitness for any purpose. RTI is under
no obligation to maintain or support the Software. RTI shall not be liable for
any incidental or consequential damages arising out of the use or inability to
use the software.
******************************************************************************/
/* tbf_subscriber.cxx
A subscription example
This file is derived from code automatically generated by the rtiddsgen
command:
rtiddsgen -language C++ -example <arch> tbf.idl
Example subscription of type tbf automatically generated by
'rtiddsgen'. To test them follow these steps:
(1) Compile this file and the example publication.
(2) Start the subscription with the command
objs/<arch>/tbf_subscriber <domain_id> <sample_count>
(3) Start the publication with the command
objs/<arch>/tbf_publisher <domain_id> <sample_count>
(4) [Optional] Specify the list of discovery initial peers and
multicast receive addresses via an environment variable or a file
(in the current working directory) called NDDS_DISCOVERY_PEERS.
You can run any number of publishers and subscribers programs, and can
add and remove them dynamically from the domain.
Example:
To run the example application on domain <domain_id>:
On Unix:
objs/<arch>/tbf_publisher <domain_id>
objs/<arch>/tbf_subscriber <domain_id>
On Windows:
objs\<arch>\tbf_publisher <domain_id>
objs\<arch>\tbf_subscriber <domain_id>
modification history
------------ -------
*/
#include <stdio.h>
#include <stdlib.h>
#ifdef RTI_VX653
#include <vThreadsData.h>
#endif
#include "ndds/ndds_cpp.h"
#include "tbf.h"
#include "tbfSupport.h"
#define NANOSECOND 1000000000.0
class tbfListener : public DDSDataReaderListener {
public:
virtual void on_requested_deadline_missed(
DDSDataReader * /*reader*/,
const DDS_RequestedDeadlineMissedStatus & /*status*/)
{
}
virtual void on_requested_incompatible_qos(
DDSDataReader * /*reader*/,
const DDS_RequestedIncompatibleQosStatus & /*status*/)
{
}
virtual void on_sample_rejected(
DDSDataReader * /*reader*/,
const DDS_SampleRejectedStatus & /*status*/)
{
}
virtual void on_liveliness_changed(
DDSDataReader * /*reader*/,
const DDS_LivelinessChangedStatus & /*status*/)
{
}
virtual void on_sample_lost(
DDSDataReader * /*reader*/,
const DDS_SampleLostStatus & /*status*/)
{
}
virtual void on_subscription_matched(
DDSDataReader * /*reader*/,
const DDS_SubscriptionMatchedStatus & /*status*/)
{
}
virtual void on_data_available(DDSDataReader *reader);
};
void tbfListener::on_data_available(DDSDataReader *reader)
{
tbfDataReader *tbf_reader = NULL;
tbfSeq data_seq;
DDS_SampleInfoSeq info_seq;
DDS_ReturnCode_t retcode;
int i;
tbf_reader = tbfDataReader::narrow(reader);
if (tbf_reader == NULL) {
printf("DataReader narrow error\n");
return;
}
retcode = tbf_reader->take(
data_seq,
info_seq,
DDS_LENGTH_UNLIMITED,
DDS_ANY_SAMPLE_STATE,
DDS_ANY_VIEW_STATE,
DDS_ANY_INSTANCE_STATE);
if (retcode == DDS_RETCODE_NO_DATA) {
return;
} else if (retcode != DDS_RETCODE_OK) {
printf("take error %d\n", retcode);
return;
}
for (i = 0; i < data_seq.length(); ++i) {
if (info_seq[i].valid_data) {
/* Here we get source timestamp of the sample using the sample info.
*
* info_seq[i].source_timestamp returns DDS_Time_t
* ({seconds,nanoseconds}). We convert nanoseconds to seconds to get
* the decimal part of the timestamp.
*/
double source_timestamp = info_seq[i].source_timestamp.sec
+ info_seq[i].source_timestamp.nanosec / NANOSECOND;
printf("%f\t%d\t\t%d\n",
source_timestamp,
data_seq[i].code,
data_seq[i].x);
}
}
retcode = tbf_reader->return_loan(data_seq, info_seq);
if (retcode != DDS_RETCODE_OK) {
printf("return loan error %d\n", retcode);
}
}
/* Delete all entities */
static int subscriber_shutdown(DDSDomainParticipant *participant)
{
DDS_ReturnCode_t retcode;
int status = 0;
if (participant != NULL) {
retcode = participant->delete_contained_entities();
if (retcode != DDS_RETCODE_OK) {
printf("delete_contained_entities error %d\n", retcode);
status = -1;
}
retcode = DDSTheParticipantFactory->delete_participant(participant);
if (retcode != DDS_RETCODE_OK) {
printf("delete_participant error %d\n", retcode);
status = -1;
}
}
/* RTI Connext provides the finalize_instance() method on
domain participant factory for people who want to release memory used
by the participant factory. Uncomment the following block of code for
clean destruction of the singleton. */
/*
retcode = DDSDomainParticipantFactory::finalize_instance();
if (retcode != DDS_RETCODE_OK) {
printf("finalize_instance error %d\n", retcode);
status = -1;
}
*/
return status;
}
extern "C" int subscriber_main(int domainId, int sample_count)
{
DDSDomainParticipant *participant = NULL;
DDSSubscriber *subscriber = NULL;
DDSTopic *topic = NULL;
tbfListener *reader_listener = NULL;
DDSDataReader *reader = NULL;
DDS_ReturnCode_t retcode;
const char *type_name = NULL;
int count = 0;
DDS_Duration_t receive_period = { 4, 0 };
int status = 0;
/* To customize the participant QoS, use
the configuration file USER_QOS_PROFILES.xml */
participant = DDSTheParticipantFactory->create_participant(
domainId,
DDS_PARTICIPANT_QOS_DEFAULT,
NULL /* listener */,
DDS_STATUS_MASK_NONE);
if (participant == NULL) {
printf("create_participant error\n");
subscriber_shutdown(participant);
return -1;
}
/* To customize the subscriber QoS, use
the configuration file USER_QOS_PROFILES.xml */
subscriber = participant->create_subscriber(
DDS_SUBSCRIBER_QOS_DEFAULT,
NULL /* listener */,
DDS_STATUS_MASK_NONE);
if (subscriber == NULL) {
printf("create_subscriber error\n");
subscriber_shutdown(participant);
return -1;
}
/* Register the type before creating the topic */
type_name = tbfTypeSupport::get_type_name();
retcode = tbfTypeSupport::register_type(participant, type_name);
if (retcode != DDS_RETCODE_OK) {
printf("register_type error %d\n", retcode);
subscriber_shutdown(participant);
return -1;
}
/* To customize the topic QoS, use
the configuration file USER_QOS_PROFILES.xml */
topic = participant->create_topic(
"Example tbf",
type_name,
DDS_TOPIC_QOS_DEFAULT,
NULL /* listener */,
DDS_STATUS_MASK_NONE);
if (topic == NULL) {
printf("create_topic error\n");
subscriber_shutdown(participant);
return -1;
}
/* Create a data reader listener */
reader_listener = new tbfListener();
/* To customize the data reader QoS, use
the configuration file USER_QOS_PROFILES.xml */
reader = subscriber->create_datareader(
topic,
DDS_DATAREADER_QOS_DEFAULT,
reader_listener,
DDS_STATUS_MASK_ALL);
if (reader == NULL) {
printf("create_datareader error\n");
subscriber_shutdown(participant);
delete reader_listener;
return -1;
}
/* If you want to change the time-based filter programmatically (e.g., to
* 2 seconds) rather than using the XML file, you will need to add the
* following lines to your code and comment out the create_datareader
* call above. */
/*DDS_DataReaderQos datareader_qos;
retcode = subscriber->get_default_datareader_qos(datareader_qos);
if (retcode != DDS_RETCODE_OK) {
printf("get_default_datareader_qos error\n");
return -1;
}
DDS_Duration_t minsep = {2, 0}; // 2 sec
datareader_qos.time_based_filter.minimum_separation = minsep;
reader = subscriber->create_datareader(
topic, datareader_qos, reader_listener,
DDS_STATUS_MASK_ALL);
if (reader == NULL) {
printf("create_datareader error\n");
subscriber_shutdown(participant);
delete reader_listener;
return -1;
}*/
/* Results table header: (1) source timestamp of the sample received;
* (2) instance id (instance.code value); and (3) value of x (instance.x).
*/
printf("================================================\n");
printf("Source Timestamp\tInstance\tX\n");
printf("================================================\n");
/* Main loop */
for (count = 0; (sample_count == 0) || (count < sample_count); ++count) {
/*printf("tbf subscriber sleeping for %d sec...\n",
receive_period.sec);*/
NDDSUtility::sleep(receive_period);
}
/* Delete all entities */
status = subscriber_shutdown(participant);
delete reader_listener;
return status;
}
#if defined(RTI_WINCE)
int wmain(int argc, wchar_t **argv)
{
int domainId = 0;
int sample_count = 0; /* infinite loop */
if (argc >= 2) {
domainId = _wtoi(argv[1]);
}
if (argc >= 3) {
sample_count = _wtoi(argv[2]);
}
/* Uncomment this to turn on additional logging
NDDSConfigLogger::get_instance()->
set_verbosity_by_category(NDDS_CONFIG_LOG_CATEGORY_API,
NDDS_CONFIG_LOG_VERBOSITY_STATUS_ALL);
*/
return subscriber_main(domainId, sample_count);
}
#elif !(defined(RTI_VXWORKS) && !defined(__RTP__)) && !defined(RTI_PSOS)
int main(int argc, char *argv[])
{
int domainId = 0;
int sample_count = 0; /* infinite loop */
if (argc >= 2) {
domainId = atoi(argv[1]);
}
if (argc >= 3) {
sample_count = atoi(argv[2]);
}
/* Uncomment this to turn on additional logging
NDDSConfigLogger::get_instance()->
set_verbosity_by_category(NDDS_CONFIG_LOG_CATEGORY_API,
NDDS_CONFIG_LOG_VERBOSITY_STATUS_ALL);
*/
return subscriber_main(domainId, sample_count);
}
#endif
#ifdef RTI_VX653
const unsigned char *__ctype = *(__ctypePtrGet());
extern "C" void usrAppInit()
{
#ifdef USER_APPL_INIT
USER_APPL_INIT; /* for backwards compatibility */
#endif
/* add application specific code here */
taskSpawn(
"sub",
RTI_OSAPI_THREAD_PRIORITY_NORMAL,
0x8,
0x150000,
(FUNCPTR) subscriber_main,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0);
}
#endif
| cxx |
rticonnextdds-examples | data/projects/rticonnextdds-examples/connext_dds/time_based_filter/c++/tbf_publisher.cxx | /*******************************************************************************
(c) 2005-2014 Copyright, Real-Time Innovations, Inc. All rights reserved.
RTI grants Licensee a license to use, modify, compile, and create derivative
works of the Software. Licensee has the right to distribute object form only
for use with RTI products. The Software is provided "as is", with no warranty
of any type, including any warranty for fitness for any purpose. RTI is under
no obligation to maintain or support the Software. RTI shall not be liable for
any incidental or consequential damages arising out of the use or inability to
use the software.
******************************************************************************/
/* tbf_publisher.cxx
A publication of data of type tbf
This file is derived from code automatically generated by the rtiddsgen
command:
rtiddsgen -language C++ -example <arch> tbf.idl
Example publication of type tbf automatically generated by
'rtiddsgen'. To test them follow these steps:
(1) Compile this file and the example subscription.
(2) Start the subscription with the command
objs/<arch>/tbf_subscriber <domain_id> <sample_count>
(3) Start the publication with the command
objs/<arch>/tbf_publisher <domain_id> <sample_count>
(4) [Optional] Specify the list of discovery initial peers and
multicast receive addresses via an environment variable or a file
(in the current working directory) called NDDS_DISCOVERY_PEERS.
You can run any number of publishers and subscribers programs, and can
add and remove them dynamically from the domain.
Example:
To run the example application on domain <domain_id>:
On Unix:
objs/<arch>/tbf_publisher <domain_id> o
objs/<arch>/tbf_subscriber <domain_id>
On Windows:
objs\<arch>\tbf_publisher <domain_id>
objs\<arch>\tbf_subscriber <domain_id>
modification history
------------ -------
*/
#include <stdio.h>
#include <stdlib.h>
#ifdef RTI_VX653
#include <vThreadsData.h>
#endif
#include "ndds/ndds_cpp.h"
#include "tbf.h"
#include "tbfSupport.h"
/* Delete all entities */
static int publisher_shutdown(DDSDomainParticipant *participant)
{
DDS_ReturnCode_t retcode;
int status = 0;
if (participant != NULL) {
retcode = participant->delete_contained_entities();
if (retcode != DDS_RETCODE_OK) {
printf("delete_contained_entities error %d\n", retcode);
status = -1;
}
retcode = DDSTheParticipantFactory->delete_participant(participant);
if (retcode != DDS_RETCODE_OK) {
printf("delete_participant error %d\n", retcode);
status = -1;
}
}
/* RTI Connext provides finalize_instance() method on
domain participant factory for people who want to release memory used
by the participant factory. Uncomment the following block of code for
clean destruction of the singleton. */
/*
retcode = DDSDomainParticipantFactory::finalize_instance();
if (retcode != DDS_RETCODE_OK) {
printf("finalize_instance error %d\n", retcode);
status = -1;
}
*/
return status;
}
extern "C" int publisher_main(int domainId, int sample_count)
{
DDSDomainParticipant *participant = NULL;
DDSPublisher *publisher = NULL;
DDSTopic *topic = NULL;
DDSDataWriter *writer = NULL;
tbfDataWriter *tbf_writer = NULL;
tbf *instance = NULL;
DDS_ReturnCode_t retcode;
DDS_InstanceHandle_t instance_handle = DDS_HANDLE_NIL;
const char *type_name = NULL;
int count = 0;
/* send_period sleep of 0.25 second, i.e., the loop where we write
* new samples will sleep for 0.25 second every iteration.*/
DDS_Duration_t send_period = { 0, 250000000 };
/* To customize participant QoS, use
the configuration file USER_QOS_PROFILES.xml */
participant = DDSTheParticipantFactory->create_participant(
domainId,
DDS_PARTICIPANT_QOS_DEFAULT,
NULL /* listener */,
DDS_STATUS_MASK_NONE);
if (participant == NULL) {
printf("create_participant error\n");
publisher_shutdown(participant);
return -1;
}
/* To customize publisher QoS, use
the configuration file USER_QOS_PROFILES.xml */
publisher = participant->create_publisher(
DDS_PUBLISHER_QOS_DEFAULT,
NULL /* listener */,
DDS_STATUS_MASK_NONE);
if (publisher == NULL) {
printf("create_publisher error\n");
publisher_shutdown(participant);
return -1;
}
/* Register type before creating topic */
type_name = tbfTypeSupport::get_type_name();
retcode = tbfTypeSupport::register_type(participant, type_name);
if (retcode != DDS_RETCODE_OK) {
printf("register_type error %d\n", retcode);
publisher_shutdown(participant);
return -1;
}
/* To customize topic QoS, use
the configuration file USER_QOS_PROFILES.xml */
topic = participant->create_topic(
"Example tbf",
type_name,
DDS_TOPIC_QOS_DEFAULT,
NULL /* listener */,
DDS_STATUS_MASK_NONE);
if (topic == NULL) {
printf("create_topic error\n");
publisher_shutdown(participant);
return -1;
}
/* To customize data writer QoS, use
the configuration file USER_QOS_PROFILES.xml */
writer = publisher->create_datawriter(
topic,
DDS_DATAWRITER_QOS_DEFAULT,
NULL /* listener */,
DDS_STATUS_MASK_NONE);
if (writer == NULL) {
printf("create_datawriter error\n");
publisher_shutdown(participant);
return -1;
}
tbf_writer = tbfDataWriter::narrow(writer);
if (tbf_writer == NULL) {
printf("DataWriter narrow error\n");
publisher_shutdown(participant);
return -1;
}
/* Create data sample for writing */
instance = tbfTypeSupport::create_data();
if (instance == NULL) {
printf("tbfTypeSupport::create_data error\n");
publisher_shutdown(participant);
return -1;
}
/* For a data type that has a key, if the same instance is going to be
written multiple times, initialize the key here
and register the keyed instance prior to writing */
/*
instance_handle = tbf_writer->register_instance(*instance);
*/
/* Main loop */
for (count = 0; (sample_count == 0) || (count < sample_count); ++count) {
printf("\nWriting tbf, count %d\n", count);
printf("=======================\n");
/* Modify the data to be sent here */
/* Update instance 1 (code = 1) every 0.5 seconds */
if ((count + 1) % 2 == 0) {
printf("Publishing instance 1\n");
instance->code = 1;
instance->x = count;
retcode = tbf_writer->write(*instance, instance_handle);
if (retcode != DDS_RETCODE_OK) {
printf("write error %d\n", retcode);
}
}
/* Update instance 0 (code = 0) every 0.25 seconds */
printf("Publishing instance 0\n");
instance->code = 0;
instance->x = count;
retcode = tbf_writer->write(*instance, instance_handle);
if (retcode != DDS_RETCODE_OK) {
printf("write error %d\n", retcode);
}
NDDSUtility::sleep(send_period);
}
/*
retcode = tbf_writer->unregister_instance(
*instance, instance_handle);
if (retcode != DDS_RETCODE_OK) {
printf("unregister instance error %d\n", retcode);
}
*/
/* Delete data sample */
retcode = tbfTypeSupport::delete_data(instance);
if (retcode != DDS_RETCODE_OK) {
printf("tbfTypeSupport::delete_data error %d\n", retcode);
}
/* Delete all entities */
return publisher_shutdown(participant);
}
#if defined(RTI_WINCE)
int wmain(int argc, wchar_t **argv)
{
int domainId = 0;
int sample_count = 0; /* infinite loop */
if (argc >= 2) {
domainId = _wtoi(argv[1]);
}
if (argc >= 3) {
sample_count = _wtoi(argv[2]);
}
/* Uncomment this to turn on additional logging
NDDSConfigLogger::get_instance()->
set_verbosity_by_category(NDDS_CONFIG_LOG_CATEGORY_API,
NDDS_CONFIG_LOG_VERBOSITY_STATUS_ALL);
*/
return publisher_main(domainId, sample_count);
}
#elif !(defined(RTI_VXWORKS) && !defined(__RTP__)) && !defined(RTI_PSOS)
int main(int argc, char *argv[])
{
int domainId = 0;
int sample_count = 0; /* infinite loop */
if (argc >= 2) {
domainId = atoi(argv[1]);
}
if (argc >= 3) {
sample_count = atoi(argv[2]);
}
/* Uncomment this to turn on additional logging
NDDSConfigLogger::get_instance()->
set_verbosity_by_category(NDDS_CONFIG_LOG_CATEGORY_API,
NDDS_CONFIG_LOG_VERBOSITY_STATUS_ALL);
*/
return publisher_main(domainId, sample_count);
}
#endif
#ifdef RTI_VX653
const unsigned char *__ctype = *(__ctypePtrGet());
extern "C" void usrAppInit()
{
#ifdef USER_APPL_INIT
USER_APPL_INIT; /* for backwards compatibility */
#endif
/* add application specific code here */
taskSpawn(
"pub",
RTI_OSAPI_THREAD_PRIORITY_NORMAL,
0x8,
0x150000,
(FUNCPTR) publisher_main,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0);
}
#endif
| cxx |
rticonnextdds-examples | data/projects/rticonnextdds-examples/connext_dds/time_based_filter/c++98/tbf_subscriber.cxx | /*******************************************************************************
(c) 2005-2014 Copyright, Real-Time Innovations, Inc. All rights reserved.
RTI grants Licensee a license to use, modify, compile, and create derivative
works of the Software. Licensee has the right to distribute object form only
for use with RTI products. The Software is provided "as is", with no warranty
of any type, including any warranty for fitness for any purpose. RTI is under
no obligation to maintain or support the Software. RTI shall not be liable for
any incidental or consequential damages arising out of the use or inability to
use the software.
******************************************************************************/
#include <iostream>
#include <iomanip>
#include <stdio.h>
#include <stdlib.h>
#include "tbf.h"
#include "tbfSupport.h"
#include "ndds/ndds_cpp.h"
#include "application.h"
#define NANOSECOND 1000000000.0
using namespace application;
static int shutdown_participant(
DDSDomainParticipant *participant,
const char *shutdown_message,
int status);
unsigned int process_data(tbfDataReader *typed_reader)
{
tbfSeq 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);
std::cout << std::fixed << std::setprecision(6);
for (int i = 0; i < data_seq.length(); ++i) {
if (info_seq[i].valid_data) {
/* Here we get source timestamp of the sample using the sample info.
*
* info_seq[i].source_timestamp returns DDS_Time_t
* ({seconds,nanoseconds}). We convert nanoseconds to seconds to get
* the decimal part of the timestamp.
*/
double source_timestamp = info_seq[i].source_timestamp.sec
+ info_seq[i].source_timestamp.nanosec / NANOSECOND;
std::cout << source_timestamp << "\t" << data_seq[i].code << "\t\t"
<< data_seq[i].x << std::endl;
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 receive_period = { 4, 0 };
// Start communicating in a domain, usually one participant per application
DDSDomainParticipant *participant =
DDSTheParticipantFactory->create_participant(
domain_id,
DDS_PARTICIPANT_QOS_DEFAULT,
NULL /* 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 = tbfTypeSupport::get_type_name();
DDS_ReturnCode_t retcode =
tbfTypeSupport::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 tbf",
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 tbf" 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);
}
/* If you want to change the time-based filter programmatically (e.g., to
* 2 seconds) rather than using the XML file, you will need to add the
* following lines to your code and comment out the create_datareader
* call above. */
/*DDS_DataReaderQos datareader_qos;
retcode = subscriber->get_default_datareader_qos(datareader_qos);
if (retcode != DDS_RETCODE_OK) {
return shutdown_participant(
participant,
"get_default_datareader_qos error",
EXIT_FAILURE);
}
DDS_Duration_t minsep = {2, 0}; // 2 sec
datareader_qos.time_based_filter.minimum_separation = minsep;
DDSDataReader *untyped_reader = subscriber->create_datareader(
topic, datareader_qos, reader_listener,
DDS_STATUS_MASK_ALL);
if (untyped_reader == NULL) {
return shutdown_participant(
participant,
"create_datareader error",
EXIT_FAILURE);
}*/
/* Results table header: (1) source timestamp of the sample received;
* (2) instance id (instance.code value); and (3) value of x (instance.x).
*/
// Narrow casts from a untyped DataReader to a reader of your type
tbfDataReader *typed_reader = tbfDataReader::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);
}
std::cout << "================================================\n";
std::cout << "Source Timestamp\tInstance\tX\n";
std::cout << "================================================\n";
// 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, receive_period);
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/time_based_filter/c++98/tbf_publisher.cxx | /*******************************************************************************
(c) 2005-2014 Copyright, Real-Time Innovations, Inc. All rights reserved.
RTI grants Licensee a license to use, modify, compile, and create derivative
works of the Software. Licensee has the right to distribute object form only
for use with RTI products. The Software is provided "as is", with no warranty
of any type, including any warranty for fitness for any purpose. RTI is under
no obligation to maintain or support the Software. RTI shall not be liable for
any incidental or consequential damages arising out of the use or inability to
use the software.
******************************************************************************/
#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include "tbf.h"
#include "tbfSupport.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_period sleep of 0.25 second, i.e., the loop where we write
* new samples will sleep for 0.25 second every iteration.*/
DDS_Duration_t send_period = { 0, 250000000 };
// 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 = tbfTypeSupport::get_type_name();
DDS_ReturnCode_t retcode =
tbfTypeSupport::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 tbf",
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 tbf" 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);
}
tbfDataWriter *typed_writer = tbfDataWriter::narrow(untyped_writer);
if (typed_writer == NULL) {
return shutdown_participant(
participant,
"DataWriter narrow error",
EXIT_FAILURE);
}
// Create data for writing, allocating all members
tbf *data = tbfTypeSupport::create_data();
if (data == NULL) {
return shutdown_participant(
participant,
"tbfTypeSupport::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 << "\nWriting tbf, count " << samples_written << std::endl;
std::cout << "=======================\n";
// Modify the data to be sent here
// Update instance 1 (code = 1) every 0.5 seconds
if ((samples_written + 1) % 2 == 0) {
std::cout << "Publishing instance 1\n";
data->code = 1;
data->x = samples_written;
retcode = typed_writer->write(*data, instance_handle);
if (retcode != DDS_RETCODE_OK) {
std::cerr << "write error " << retcode << std::endl;
}
}
// Update instance 0 (code = 0) every 0.25 seconds
std::cout << "Publishing instance 0\n";
data->code = 0;
data->x = samples_written;
retcode = typed_writer->write(*data, DDS_HANDLE_NIL);
if (retcode != DDS_RETCODE_OK) {
std::cerr << "write error " << retcode << std::endl;
}
NDDSUtility::sleep(send_period);
}
/*
retcode = typed_writer->unregister_instance(
*data, instance_handle);
if (retcode != DDS_RETCODE_OK) {
std::cerr << "unregister instance error " << retcode << std::endl;
}
*/
// Delete data sample
retcode = tbfTypeSupport::delete_data(data);
if (retcode != DDS_RETCODE_OK) {
std::cerr << "tbfTypeSupport::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/time_based_filter/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/time_based_filter/c/tbf_subscriber.c | /*******************************************************************************
(c) 2005-2014 Copyright, Real-Time Innovations, Inc. All rights reserved.
RTI grants Licensee a license to use, modify, compile, and create derivative
works of the Software. Licensee has the right to distribute object form only
for use with RTI products. The Software is provided "as is", with no warranty
of any type, including any warranty for fitness for any purpose. RTI is under
no obligation to maintain or support the Software. RTI shall not be liable for
any incidental or consequential damages arising out of the use or inability to
use the software.
******************************************************************************/
/* tbf_subscriber.c
A subscription example
This file is derived from code automatically generated by the rtiddsgen
command:
rtiddsgen -language C -example <arch> tbf.idl
Example subscription of type tbf automatically generated by
'rtiddsgen'. To test them, follow these steps:
(1) Compile this file and the example publication.
(2) Start the subscription with the command
objs/<arch>/tbf_subscriber <domain_id> <sample_count>
(3) Start the publication with the command
objs/<arch>/tbf_publisher <domain_id> <sample_count>
(4) [Optional] Specify the list of discovery initial peers and
multicast receive addresses via an environment variable or a file
(in the current working directory) called NDDS_DISCOVERY_PEERS.
You can run any number of publishers and subscribers programs, and can
add and remove them dynamically from the domain.
Example:
To run the example application on domain <domain_id>:
On UNIX systems:
objs/<arch>/tbf_publisher <domain_id>
objs/<arch>/tbf_subscriber <domain_id>
On Windows systems:
objs\<arch>\tbf_publisher <domain_id>
objs\<arch>\tbf_subscriber <domain_id>
modification history
------------ -------
*/
#include "ndds/ndds_c.h"
#include "tbf.h"
#include "tbfSupport.h"
#include <stdio.h>
#include <stdlib.h>
#define NANOSECOND 1000000000.0
void tbfListener_on_requested_deadline_missed(
void *listener_data,
DDS_DataReader *reader,
const struct DDS_RequestedDeadlineMissedStatus *status)
{
}
void tbfListener_on_requested_incompatible_qos(
void *listener_data,
DDS_DataReader *reader,
const struct DDS_RequestedIncompatibleQosStatus *status)
{
}
void tbfListener_on_sample_rejected(
void *listener_data,
DDS_DataReader *reader,
const struct DDS_SampleRejectedStatus *status)
{
}
void tbfListener_on_liveliness_changed(
void *listener_data,
DDS_DataReader *reader,
const struct DDS_LivelinessChangedStatus *status)
{
}
void tbfListener_on_sample_lost(
void *listener_data,
DDS_DataReader *reader,
const struct DDS_SampleLostStatus *status)
{
}
void tbfListener_on_subscription_matched(
void *listener_data,
DDS_DataReader *reader,
const struct DDS_SubscriptionMatchedStatus *status)
{
}
void tbfListener_on_data_available(void *listener_data, DDS_DataReader *reader)
{
tbfDataReader *tbf_reader = NULL;
struct tbfSeq data_seq = DDS_SEQUENCE_INITIALIZER;
struct DDS_SampleInfoSeq info_seq = DDS_SEQUENCE_INITIALIZER;
DDS_ReturnCode_t retcode;
int i;
double source_timestamp;
tbf *data;
struct DDS_SampleInfo *sample_info;
tbf_reader = tbfDataReader_narrow(reader);
if (tbf_reader == NULL) {
printf("DataReader narrow error\n");
return;
}
retcode = tbfDataReader_take(
tbf_reader,
&data_seq,
&info_seq,
DDS_LENGTH_UNLIMITED,
DDS_ANY_SAMPLE_STATE,
DDS_ANY_VIEW_STATE,
DDS_ANY_INSTANCE_STATE);
if (retcode == DDS_RETCODE_NO_DATA) {
return;
} else if (retcode != DDS_RETCODE_OK) {
printf("take error %d\n", retcode);
return;
}
for (i = 0; i < tbfSeq_get_length(&data_seq); ++i) {
sample_info = DDS_SampleInfoSeq_get_reference(&info_seq, i);
if (sample_info->valid_data) {
data = tbfSeq_get_reference(&data_seq, i);
/* Here we get source timestamp of the sample using the sample info.
*
* info_seq[i].source_timestamp returns DDS_Time_t
* ({seconds,nanoseconds}). We convert nanoseconds to seconds to get
* the decimal part of the timestamp.
*/
source_timestamp = sample_info->source_timestamp.sec
+ sample_info->source_timestamp.nanosec / NANOSECOND;
printf("%f\t%d\t\t%d\n", source_timestamp, data->code, data->x);
}
}
retcode = tbfDataReader_return_loan(tbf_reader, &data_seq, &info_seq);
if (retcode != DDS_RETCODE_OK) {
printf("return loan error %d\n", retcode);
}
}
/* Delete all entities */
static int subscriber_shutdown(DDS_DomainParticipant *participant)
{
DDS_ReturnCode_t retcode;
int status = 0;
if (participant != NULL) {
retcode = DDS_DomainParticipant_delete_contained_entities(participant);
if (retcode != DDS_RETCODE_OK) {
printf("delete_contained_entities error %d\n", retcode);
status = -1;
}
retcode = DDS_DomainParticipantFactory_delete_participant(
DDS_TheParticipantFactory,
participant);
if (retcode != DDS_RETCODE_OK) {
printf("delete_participant error %d\n", retcode);
status = -1;
}
}
/* RTI Connext provides the finalize_instance() method on
domain participant factory for users who want to release memory used
by the participant factory. Uncomment the following block of code for
clean destruction of the singleton. */
/*
retcode = DDS_DomainParticipantFactory_finalize_instance();
if (retcode != DDS_RETCODE_OK) {
printf("finalize_instance error %d\n", retcode);
status = -1;
}
*/
return status;
}
static int subscriber_main(int domainId, int sample_count)
{
DDS_DomainParticipant *participant = NULL;
DDS_Subscriber *subscriber = NULL;
DDS_Topic *topic = NULL;
struct DDS_DataReaderListener reader_listener =
DDS_DataReaderListener_INITIALIZER;
DDS_DataReader *reader = NULL;
DDS_ReturnCode_t retcode;
const char *type_name = NULL;
int count = 0;
struct DDS_Duration_t poll_period = { 4, 0 };
/* To change the time-based filter programmatically you will need to declare
* the DataReaderQoS */
/* struct DDS_DataReaderQos datareader_qos = DDS_DataReaderQos_INITIALIZER;
*/
/* To customize participant QoS, use
the configuration file USER_QOS_PROFILES.xml */
participant = DDS_DomainParticipantFactory_create_participant(
DDS_TheParticipantFactory,
domainId,
&DDS_PARTICIPANT_QOS_DEFAULT,
NULL /* listener */,
DDS_STATUS_MASK_NONE);
if (participant == NULL) {
printf("create_participant error\n");
subscriber_shutdown(participant);
return -1;
}
/* To customize subscriber QoS, use
the configuration file USER_QOS_PROFILES.xml */
subscriber = DDS_DomainParticipant_create_subscriber(
participant,
&DDS_SUBSCRIBER_QOS_DEFAULT,
NULL /* listener */,
DDS_STATUS_MASK_NONE);
if (subscriber == NULL) {
printf("create_subscriber error\n");
subscriber_shutdown(participant);
return -1;
}
/* Register the type before creating the topic */
type_name = tbfTypeSupport_get_type_name();
retcode = tbfTypeSupport_register_type(participant, type_name);
if (retcode != DDS_RETCODE_OK) {
printf("register_type error %d\n", retcode);
subscriber_shutdown(participant);
return -1;
}
/* To customize topic QoS, use
the configuration file USER_QOS_PROFILES.xml */
topic = DDS_DomainParticipant_create_topic(
participant,
"Example tbf",
type_name,
&DDS_TOPIC_QOS_DEFAULT,
NULL /* listener */,
DDS_STATUS_MASK_NONE);
if (topic == NULL) {
printf("create_topic error\n");
subscriber_shutdown(participant);
return -1;
}
/* Set up a data reader listener */
reader_listener.on_requested_deadline_missed =
tbfListener_on_requested_deadline_missed;
reader_listener.on_requested_incompatible_qos =
tbfListener_on_requested_incompatible_qos;
reader_listener.on_sample_rejected = tbfListener_on_sample_rejected;
reader_listener.on_liveliness_changed = tbfListener_on_liveliness_changed;
reader_listener.on_sample_lost = tbfListener_on_sample_lost;
reader_listener.on_subscription_matched =
tbfListener_on_subscription_matched;
reader_listener.on_data_available = tbfListener_on_data_available;
/* To customize data reader QoS, use
the configuration file USER_QOS_PROFILES.xml */
reader = DDS_Subscriber_create_datareader(
subscriber,
DDS_Topic_as_topicdescription(topic),
&DDS_DATAREADER_QOS_DEFAULT,
&reader_listener,
DDS_STATUS_MASK_ALL);
if (reader == NULL) {
printf("create_datareader error\n");
subscriber_shutdown(participant);
return -1;
}
/* If you want to change the time-based filter programmatically (e.g., to
* 2 seconds) rather than using the XML file, you will need to add the
* following lines to your code and comment out the create_datareader
* call above. */
/*datareader_qos.time_based_filter.minimum_separation.sec = 2;
datareader_qos.time_based_filter.minimum_separation.nanosec = 0;
reader = DDS_Subscriber_create_datareader(
subscriber, DDS_Topic_as_topicdescription(topic),
&datareader_qos, &reader_listener, DDS_STATUS_MASK_ALL);
if (reader == NULL) {
printf("create_datareader error\n");
subscriber_shutdown(participant);
return -1;
}*/
/* Results table header: (1) source timestamp of the sample received;
* (2) instance id (instance.code value); and (3) value of x (instance.x).
*/
printf("================================================\n");
printf("Source Timestamp\tInstance\tX\n");
printf("================================================\n");
/* Main loop */
for (count = 0; (sample_count == 0) || (count < sample_count); ++count) {
/*printf("tbf subscriber sleeping for %d sec...\n",
poll_period.sec);*/
NDDS_Utility_sleep(&poll_period);
}
/* Cleanup and delete all entities */
return subscriber_shutdown(participant);
}
#if defined(RTI_WINCE)
int wmain(int argc, wchar_t **argv)
{
int domainId = 0;
int sample_count = 0; /* infinite loop */
if (argc >= 2) {
domainId = _wtoi(argv[1]);
}
if (argc >= 3) {
sample_count = _wtoi(argv[2]);
}
/* Uncomment this to turn on additional logging
NDDS_Config_Logger_set_verbosity_by_category(
NDDS_Config_Logger_get_instance(),
NDDS_CONFIG_LOG_CATEGORY_API,
NDDS_CONFIG_LOG_VERBOSITY_STATUS_ALL);
*/
return subscriber_main(domainId, sample_count);
}
#elif !(defined(RTI_VXWORKS) && !defined(__RTP__)) && !defined(RTI_PSOS)
int main(int argc, char *argv[])
{
int domainId = 0;
int sample_count = 0; /* infinite loop */
if (argc >= 2) {
domainId = atoi(argv[1]);
}
if (argc >= 3) {
sample_count = atoi(argv[2]);
}
/* Uncomment this to turn on additional logging
NDDS_Config_Logger_set_verbosity_by_category(
NDDS_Config_Logger_get_instance(),
NDDS_CONFIG_LOG_CATEGORY_API,
NDDS_CONFIG_LOG_VERBOSITY_STATUS_ALL);
*/
return subscriber_main(domainId, sample_count);
}
#endif
#ifdef RTI_VX653
const unsigned char *__ctype = NULL;
void usrAppInit()
{
#ifdef USER_APPL_INIT
USER_APPL_INIT; /* for backwards compatibility */
#endif
/* add application specific code here */
taskSpawn(
"sub",
RTI_OSAPI_THREAD_PRIORITY_NORMAL,
0x8,
0x150000,
(FUNCPTR) subscriber_main,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0);
}
#endif
| c |
rticonnextdds-examples | data/projects/rticonnextdds-examples/connext_dds/time_based_filter/c/tbf_publisher.c | /*******************************************************************************
(c) 2005-2014 Copyright, Real-Time Innovations, Inc. All rights reserved.
RTI grants Licensee a license to use, modify, compile, and create derivative
works of the Software. Licensee has the right to distribute object form only
for use with RTI products. The Software is provided "as is", with no warranty
of any type, including any warranty for fitness for any purpose. RTI is under
no obligation to maintain or support the Software. RTI shall not be liable for
any incidental or consequential damages arising out of the use or inability to
use the software.
******************************************************************************/
/* tbf_publisher.c
A publication of data of type tbf
This file is derived from code automatically generated by the rtiddsgen
command:
rtiddsgen -language C -example <arch> tbf.idl
Example publication of type tbf automatically generated by
'rtiddsgen'. To test them follow these steps:
(1) Compile this file and the example subscription.
(2) Start the subscription with the command
objs/<arch>/tbf_subscriber <domain_id> <sample_count>
(3) Start the publication with the command
objs/<arch>/tbf_publisher <domain_id> <sample_count>
(4) [Optional] Specify the list of discovery initial peers and
multicast receive addresses via an environment variable or a file
(in the current working directory) called NDDS_DISCOVERY_PEERS.
You can run any number of publishers and subscribers programs, and can
add and remove them dynamically from the domain.
Example:
To run the example application on domain <domain_id>:
On Unix:
objs/<arch>/tbf_publisher <domain_id>
objs/<arch>/tbf_subscriber <domain_id>
On Windows:
objs\<arch>\tbf_publisher <domain_id>
objs\<arch>\tbf_subscriber <domain_id>
modification history
------------ -------
*/
#include "ndds/ndds_c.h"
#include "tbf.h"
#include "tbfSupport.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;
tbfDataWriter *tbf_writer = NULL;
tbf *instance = NULL;
DDS_ReturnCode_t retcode;
DDS_InstanceHandle_t instance_handle = DDS_HANDLE_NIL;
const char *type_name = NULL;
int count = 0;
/* send_period sleep of 0.25 seconds, i.e., the loop where we write
* new samples will sleep for 0.25 seconds every iteration.*/
struct DDS_Duration_t send_period = { 0, 250000000 };
/* To customize participant QoS, use
the configuration file USER_QOS_PROFILES.xml */
participant = DDS_DomainParticipantFactory_create_participant(
DDS_TheParticipantFactory,
domainId,
&DDS_PARTICIPANT_QOS_DEFAULT,
NULL /* listener */,
DDS_STATUS_MASK_NONE);
if (participant == NULL) {
printf("create_participant error\n");
publisher_shutdown(participant);
return -1;
}
/* To customize publisher QoS, use
the configuration file USER_QOS_PROFILES.xml */
publisher = DDS_DomainParticipant_create_publisher(
participant,
&DDS_PUBLISHER_QOS_DEFAULT,
NULL /* listener */,
DDS_STATUS_MASK_NONE);
if (publisher == NULL) {
printf("create_publisher error\n");
publisher_shutdown(participant);
return -1;
}
/* Register type before creating topic */
type_name = tbfTypeSupport_get_type_name();
retcode = tbfTypeSupport_register_type(participant, type_name);
if (retcode != DDS_RETCODE_OK) {
printf("register_type error %d\n", retcode);
publisher_shutdown(participant);
return -1;
}
/* To customize topic QoS, use
the configuration file USER_QOS_PROFILES.xml */
topic = DDS_DomainParticipant_create_topic(
participant,
"Example tbf",
type_name,
&DDS_TOPIC_QOS_DEFAULT,
NULL /* listener */,
DDS_STATUS_MASK_NONE);
if (topic == NULL) {
printf("create_topic error\n");
publisher_shutdown(participant);
return -1;
}
/* To customize data writer QoS, use
the configuration file USER_QOS_PROFILES.xml */
writer = DDS_Publisher_create_datawriter(
publisher,
topic,
&DDS_DATAWRITER_QOS_DEFAULT,
NULL /* listener */,
DDS_STATUS_MASK_NONE);
if (writer == NULL) {
printf("create_datawriter error\n");
publisher_shutdown(participant);
return -1;
}
tbf_writer = tbfDataWriter_narrow(writer);
if (tbf_writer == NULL) {
printf("DataWriter narrow error\n");
publisher_shutdown(participant);
return -1;
}
/* Create data sample for writing */
instance = tbfTypeSupport_create_data_ex(DDS_BOOLEAN_TRUE);
if (instance == NULL) {
printf("tbfTypeSupport_create_data error\n");
publisher_shutdown(participant);
return -1;
}
/* For a data type that has a key, if the same instance is going to be
written multiple times, initialize the key here
and register the keyed instance prior to writing */
/*
instance_handle = tbfDataWriter_register_instance(
tbf_writer, instance);
*/
/* Main loop */
for (count = 0; (sample_count == 0) || (count < sample_count); ++count) {
printf("\nWriting tbf, count %d\n", count);
printf("=======================\n");
/* Modify the data to be written here */
/* Update instance 1 (code = 1) every 0.50 seconds */
if ((count + 1) % 2 == 0) {
printf("Publishing instance 1\n");
instance->code = 1;
instance->x = count;
retcode =
tbfDataWriter_write(tbf_writer, instance, &instance_handle);
if (retcode != DDS_RETCODE_OK) {
printf("write error %d\n", retcode);
}
}
/* Update instance 0 (code = 0) every 0.25 seconds */
printf("Publishing instance 0\n");
instance->code = 0;
instance->x = count;
retcode = tbfDataWriter_write(tbf_writer, instance, &instance_handle);
if (retcode != DDS_RETCODE_OK) {
printf("write error %d\n", retcode);
}
NDDS_Utility_sleep(&send_period);
}
/*
retcode = tbfDataWriter_unregister_instance(
tbf_writer, instance, &instance_handle);
if (retcode != DDS_RETCODE_OK) {
printf("unregister instance error %d\n", retcode);
}
*/
/* Delete data sample */
retcode = tbfTypeSupport_delete_data_ex(instance, DDS_BOOLEAN_TRUE);
if (retcode != DDS_RETCODE_OK) {
printf("tbfTypeSupport_delete_data error %d\n", retcode);
}
/* Cleanup and delete delete all entities */
return publisher_shutdown(participant);
}
#if defined(RTI_WINCE)
int wmain(int argc, wchar_t **argv)
{
int domainId = 0;
int sample_count = 0; /* infinite loop */
if (argc >= 2) {
domainId = _wtoi(argv[1]);
}
if (argc >= 3) {
sample_count = _wtoi(argv[2]);
}
/* Uncomment this to turn on additional logging
NDDS_Config_Logger_set_verbosity_by_category(
NDDS_Config_Logger_get_instance(),
NDDS_CONFIG_LOG_CATEGORY_API,
NDDS_CONFIG_LOG_VERBOSITY_STATUS_ALL);
*/
return publisher_main(domainId, sample_count);
}
#elif !(defined(RTI_VXWORKS) && !defined(__RTP__)) && !defined(RTI_PSOS)
int main(int argc, char *argv[])
{
int domainId = 0;
int sample_count = 0; /* infinite loop */
if (argc >= 2) {
domainId = atoi(argv[1]);
}
if (argc >= 3) {
sample_count = atoi(argv[2]);
}
/* Uncomment this to turn on additional logging
NDDS_Config_Logger_set_verbosity_by_category(
NDDS_Config_Logger_get_instance(),
NDDS_CONFIG_LOG_CATEGORY_API,
NDDS_CONFIG_LOG_VERBOSITY_STATUS_ALL);
*/
return publisher_main(domainId, sample_count);
}
#endif
#ifdef RTI_VX653
const unsigned char *__ctype = NULL;
void usrAppInit()
{
#ifdef USER_APPL_INIT
USER_APPL_INIT; /* for backwards compatibility */
#endif
/* add application specific code here */
taskSpawn(
"pub",
RTI_OSAPI_THREAD_PRIORITY_NORMAL,
0x8,
0x150000,
(FUNCPTR) publisher_main,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0);
}
#endif
| c |
rticonnextdds-examples | data/projects/rticonnextdds-examples/connext_dds/time_based_filter/c++03/tbf_subscriber.cxx | /*******************************************************************************
(c) 2005-2015 Copyright, Real-Time Innovations, Inc. All rights reserved.
RTI grants Licensee a license to use, modify, compile, and create derivative
works of the Software. Licensee has the right to distribute object form only
for use with RTI products. The Software is provided "as is", with no warranty
of any type, including any warranty for fitness for any purpose. RTI is under
no obligation to maintain or support the Software. RTI shall not be liable for
any incidental or consequential damages arising out of the use or inability to
use the software.
******************************************************************************/
#include <cstdlib>
#include <iostream>
#include "tbf.hpp"
#include <dds/dds.hpp>
#include <rti/core/ListenerBinder.hpp>
using namespace dds::core;
using namespace dds::core::policy;
using namespace rti::core;
using namespace dds::domain;
using namespace dds::topic;
using namespace dds::sub;
using namespace dds::sub::qos;
class tbfReaderListener : public NoOpDataReaderListener<tbf> {
public:
void on_data_available(dds::sub::DataReader<tbf> &reader)
{
// Take all samples
LoanedSamples<tbf> samples = reader.take();
for (LoanedSamples<tbf>::iterator sample_it = samples.begin();
sample_it != samples.end();
sample_it++) {
if (sample_it->info().valid()) {
// Here we get source timestamp of the sample using the sample
// info. 'info.source_timestamp()' returns dds::core::Time.
double source_timestamp =
sample_it->info().source_timestamp().to_secs();
const tbf &data = sample_it->data();
std::cout << source_timestamp << "\t" << data.code() << "\t\t"
<< data.x() << std::endl;
}
}
}
};
void subscriber_main(int domain_id, int sample_count)
{
// Create a DomainParticipant with default Qos
DomainParticipant participant(domain_id);
// Create a Topic -- and automatically register the type
Topic<tbf> topic(participant, "Example tbf");
// Retrieve the default DataReader QoS, from USER_QOS_PROFILES.xml
DataReaderQos reader_qos = QosProvider::Default().datareader_qos();
// If you want to change the DataReader's QoS programmatically rather
// than using the XML file, you will need uncomment this line.
// reader_qos << TimeBasedFilter(Duration::from_secs(2));
// Create a DataReader with default Qos (Subscriber created in-line)
DataReader<tbf> reader(Subscriber(participant), topic, reader_qos);
// Associate a listener to the DataReader using ListenerBinder, a RAII that
// will take care of setting it to NULL on destruction.
ListenerBinder<DataReader<tbf> > reader_listener =
rti::core::bind_and_manage_listener(
reader,
new tbfReaderListener,
dds::core::status::StatusMask::all());
std::cout << "================================================" << std::endl
<< "Source Timestamp\tInstance\tX" << std::endl
<< "================================================" << std::endl
<< std::fixed;
for (int count = 0; (sample_count == 0) || (count < sample_count);
++count) {
rti::util::sleep(Duration(1));
}
}
int main(int argc, char *argv[])
{
int domain_id = 0;
int sample_count = 0; // Infinite loop
if (argc >= 2) {
domain_id = atoi(argv[1]);
}
if (argc >= 3) {
sample_count = atoi(argv[2]);
}
// To turn on additional logging, include <rti/config/Logger.hpp> and
// uncomment the following line:
// rti::config::Logger::instance().verbosity(rti::config::Verbosity::STATUS_ALL);
try {
subscriber_main(domain_id, sample_count);
} catch (const std::exception &ex) {
// This will catch DDS exceptions
std::cerr << "Exception in subscriber_main: " << ex.what() << std::endl;
return -1;
}
return 0;
}
| cxx |
rticonnextdds-examples | data/projects/rticonnextdds-examples/connext_dds/time_based_filter/c++03/tbf_publisher.cxx | /*******************************************************************************
(c) 2005-2015 Copyright, Real-Time Innovations, Inc. All rights reserved.
RTI grants Licensee a license to use, modify, compile, and create derivative
works of the Software. Licensee has the right to distribute object form only
for use with RTI products. The Software is provided "as is", with no warranty
of any type, including any warranty for fitness for any purpose. RTI is under
no obligation to maintain or support the Software. RTI shall not be liable for
any incidental or consequential damages arising out of the use or inability to
use the software.
******************************************************************************/
#include <cstdlib>
#include <iostream>
#include "tbf.hpp"
#include <dds/dds.hpp>
using namespace dds::core;
using namespace dds::domain;
using namespace dds::topic;
using namespace dds::pub;
void publisher_main(int domain_id, int sample_count)
{
// Create a DomainParticipant with default Qos
DomainParticipant participant(domain_id);
// Create a Topic -- and automatically register the type
Topic<tbf> topic(participant, "Example tbf");
// Create a DataWriter with default Qos (Publisher created in-line)
DataWriter<tbf> writer(Publisher(participant), topic);
// Create a sample to write
tbf sample;
for (int count = 0; count < sample_count || sample_count == 0; count++) {
std::cout << "Writing tbf, count " << count << std::endl;
// Update instance1 (code = 1) every 0.5 seconds => when count is even.
if ((count + 1) % 2 == 0) {
std::cout << "Publishing instance 1" << std::endl;
sample.code(1);
sample.x(count);
writer.write(sample);
}
// Update instance 0 (code = 0) every 0.25 seconds.
std::cout << "Publishing instance 0" << std::endl;
sample.code(0);
sample.x(count);
writer.write(sample);
// The loop to write new samples will sleep for 0.25 second.
rti::util::sleep(Duration::from_millisecs(250));
}
}
int main(int argc, char *argv[])
{
int domain_id = 0;
int sample_count = 0; // Infinite loop
if (argc >= 2) {
domain_id = atoi(argv[1]);
}
if (argc >= 3) {
sample_count = atoi(argv[2]);
}
// To turn on additional logging, include <rti/config/Logger.hpp> and
// uncomment the following line:
// rti::config::Logger::instance().verbosity(rti::config::Verbosity::STATUS_ALL);
try {
publisher_main(domain_id, sample_count);
} catch (const std::exception &ex) {
// This will catch DDS exceptions
std::cerr << "Exception in publisher_main: " << ex.what() << std::endl;
return -1;
}
return 0;
}
| cxx |
rticonnextdds-examples | data/projects/rticonnextdds-examples/connext_dds/time_based_filter/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/time_based_filter/c++11/tbf_subscriber.cxx | /*******************************************************************************
(c) 2005-2015 Copyright, Real-Time Innovations, Inc. All rights reserved.
RTI grants Licensee a license to use, modify, compile, and create derivative
works of the Software. Licensee has the right to distribute object form only
for use with RTI products. The Software is provided "as is", with no warranty
of any type, including any warranty for fitness for any purpose. RTI is under
no obligation to maintain or support the Software. RTI shall not be liable for
any incidental or consequential damages arising out of the use or inability to
use the software.
******************************************************************************/
#include <dds/sub/ddssub.hpp>
#include <dds/core/ddscore.hpp>
#include <rti/config/Logger.hpp> // for logging
#include "tbf.hpp"
#include "application.hpp" // for command line parsing and ctrl-c
int process_data(dds::sub::DataReader<tbf> reader)
{
int count = 0;
// Take all samples
dds::sub::LoanedSamples<tbf> samples = reader.take();
for (const auto &sample : samples) {
if (sample.info().valid()) {
count++;
// Here we get source timestamp of the sample using the sample
// info. 'info.source_timestamp()' returns dds::core::Time.
double source_timestamp =
sample.info().source_timestamp().to_secs();
const tbf &data = sample.data();
std::cout << source_timestamp << "\t" << data.code() << "\t\t"
<< data.x() << std::endl;
}
}
return count;
}
void run_subscriber_application(
unsigned int domain_id,
unsigned int sample_count)
{
// Create a DomainParticipant with default Qos
dds::domain::DomainParticipant participant(domain_id);
// Create a Topic -- and automatically register the type
dds::topic::Topic<tbf> topic(participant, "Example tbf");
// 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 DataReader's QoS programmatically rather
// than using the XML file, you will need uncomment this line.
// reader_qos << TimeBasedFilter(Duration::from_secs(2));
// Create a Subscriber with default QoS
dds::sub::Subscriber subscriber(participant);
// Create a DataReader with default Qos
dds::sub::DataReader<tbf> 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::any(),
[reader, &samples_read]() {
samples_read += process_data(reader);
});
waitset += read_condition;
std::cout << "================================================" << std::endl
<< "Source Timestamp\tInstance\tX" << std::endl
<< "================================================" << std::endl
<< std::fixed;
while (!application::shutdown_requested && samples_read < sample_count) {
waitset.dispatch(dds::core::Duration(1));
}
}
int main(int argc, char *argv[])
{
using namespace application;
// Parse arguments and handle control-C
auto arguments = parse_arguments(argc, argv);
if (arguments.parse_result == ParseReturn::exit) {
return EXIT_SUCCESS;
} else if (arguments.parse_result == ParseReturn::failure) {
return EXIT_FAILURE;
}
setup_signal_handlers();
// Sets Connext verbosity to help debugging
rti::config::Logger::instance().verbosity(arguments.verbosity);
try {
run_subscriber_application(arguments.domain_id, arguments.sample_count);
} catch (const std::exception &ex) {
// This will catch DDS exceptions
std::cerr << "Exception in run_subscriber_application(): " << ex.what()
<< std::endl;
return EXIT_FAILURE;
}
// Releases the memory used by the participant factory. Optional at
// application exit
dds::domain::DomainParticipant::finalize_participant_factory();
return EXIT_SUCCESS;
}
| cxx |
rticonnextdds-examples | data/projects/rticonnextdds-examples/connext_dds/time_based_filter/c++11/tbf_publisher.cxx | /*******************************************************************************
(c) 2005-2015 Copyright, Real-Time Innovations, Inc. All rights reserved.
RTI grants Licensee a license to use, modify, compile, and create derivative
works of the Software. Licensee has the right to distribute object form only
for use with RTI products. The Software is provided "as is", with no warranty
of any type, including any warranty for fitness for any purpose. RTI is under
no obligation to maintain or support the Software. RTI shall not be liable for
any incidental or consequential damages arising out of the use or inability to
use the software.
******************************************************************************/
#include <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 "tbf.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<tbf> topic(participant, "Example tbf");
// Create a Publisher with default QoS
dds::pub::Publisher publisher(participant);
// Create a DataWriter with default Qos
dds::pub::DataWriter<tbf> writer(publisher, topic);
// Create a sample to write
tbf sample;
for (unsigned int samples_written = 0;
!application::shutdown_requested && samples_written < sample_count;
samples_written++) {
std::cout << "Writing tbf, count " << samples_written << std::endl;
// Update instance1 (code = 1) every 0.5 seconds => when count is even.
if ((samples_written + 1) % 2 == 0) {
std::cout << "Publishing instance 1" << std::endl;
sample.code(1);
sample.x(samples_written);
writer.write(sample);
}
// Update instance 0 (code = 0) every 0.25 seconds.
std::cout << "Publishing instance 0" << std::endl;
sample.code(0);
sample.x(samples_written);
writer.write(sample);
// The loop to write new samples will sleep for 0.25 second.
rti::util::sleep(dds::core::Duration::from_millisecs(250));
}
}
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/ordered_presentation/c++/ordered_subscriber.cxx | /*******************************************************************************
(c) 2005-2014 Copyright, Real-Time Innovations, Inc. All rights reserved.
RTI grants Licensee a license to use, modify, compile, and create derivative
works of the Software. Licensee has the right to distribute object form only
for use with RTI products. The Software is provided "as is", with no warranty
of any type, including any warranty for fitness for any purpose. RTI is under
no obligation to maintain or support the Software. RTI shall not be liable for
any incidental or consequential damages arising out of the use or inability to
use the software.
******************************************************************************/
/* ordered_subscriber.cxx
A subscription example
This file is derived from code automatically generated by the rtiddsgen
command:
rtiddsgen -language C++ -example <arch> ordered.idl
Example subscription of type ordered automatically generated by
'rtiddsgen'. To test them follow these steps:
(1) Compile this file and the example publication.
(2) Start the subscription with the command
objs/<arch>/ordered_subscriber <domain_id> <sample_count>
(3) Start the publication with the command
objs/<arch>/ordered_publisher <domain_id> <sample_count>
(4) [Optional] Specify the list of discovery initial peers and
multicast receive addresses via an environment variable or a file
(in the current working directory) called NDDS_DISCOVERY_PEERS.
You can run any number of publishers and subscribers programs, and can
add and remove them dynamically from the domain.
Example:
To run the example application on domain <domain_id>:
On Unix:
objs/<arch>/ordered_publisher <domain_id>
objs/<arch>/ordered_subscriber <domain_id>
On Windows:
objs\<arch>\ordered_publisher <domain_id>
objs\<arch>\ordered_subscriber <domain_id>
modification history
------------ -------
*/
#include <stdio.h>
#include <stdlib.h>
#ifdef RTI_VX653
#include <vThreadsData.h>
#endif
#include "ndds/ndds_cpp.h"
#include "ordered.h"
#include "orderedSupport.h"
#define MAX_SUBSCRIBERS 2
/* Start changes for Ordered_Presentation */
/* No listener is needed; we poll readers in this function */
void poll_data(orderedDataReader *ordered_reader[], int numreaders)
{
DDS_ReturnCode_t retcode = DDS_RETCODE_OK;
for (int r = 0; r < numreaders; ++r) {
DDS_SampleInfoSeq info_seq;
orderedSeq data_seq;
retcode = ordered_reader[r]->take(
data_seq,
info_seq,
DDS_LENGTH_UNLIMITED,
DDS_ANY_SAMPLE_STATE,
DDS_ANY_VIEW_STATE,
DDS_ANY_INSTANCE_STATE);
if (retcode == DDS_RETCODE_NO_DATA) {
/* Not an error */
continue;
} else if (retcode != DDS_RETCODE_OK) {
/* Is an error */
printf("take error: %d\n", retcode);
return;
}
for (int i = 0; i < data_seq.length(); ++i) {
if (!info_seq[i].valid_data)
continue;
/* Make things a bit easier to read. */
int ident = r;
while (ident--) {
printf("\t");
}
printf("Reader %d: Instance%d->value = %d\n",
r,
data_seq[i].id,
data_seq[i].value);
}
retcode = ordered_reader[r]->return_loan(data_seq, info_seq);
if (retcode != DDS_RETCODE_OK) {
printf("return loan error %d\n", retcode);
}
}
}
/* Delete all entities */
static int subscriber_shutdown(DDSDomainParticipant *participant)
{
DDS_ReturnCode_t retcode;
int status = 0;
if (participant != NULL) {
retcode = participant->delete_contained_entities();
if (retcode != DDS_RETCODE_OK) {
printf("delete_contained_entities error %d\n", retcode);
status = -1;
}
retcode = DDSTheParticipantFactory->delete_participant(participant);
if (retcode != DDS_RETCODE_OK) {
printf("delete_participant error %d\n", retcode);
status = -1;
}
}
/* RTI Connext provides the finalize_instance() method on
domain participant factory for people who want to release memory used
by the participant factory. Uncomment the following block of code for
clean destruction of the singleton. */
/*
retcode = DDSDomainParticipantFactory::finalize_instance();
if (retcode != DDS_RETCODE_OK) {
printf("finalize_instance error %d\n", retcode);
status = -1;
}
*/
return status;
}
extern "C" int subscriber_main(int domainId, int sample_count)
{
DDSDomainParticipant *participant = NULL;
DDSSubscriber *subscriber[2] = { 0 };
DDSTopic *topic = NULL;
DDSDataReader *reader[2] = { 0 };
DDS_ReturnCode_t retcode;
const char *type_name = NULL;
int count = 0;
DDS_Duration_t receive_period = { 4, 0 };
int status = 0;
int i = 0;
char *profile_name[] = { (char *) "ordered_Profile_subscriber_instance",
(char *) "ordered_Profile_subscriber_topic" };
/* To customize the participant QoS, use
the configuration file USER_QOS_PROFILES.xml */
participant = DDSTheParticipantFactory->create_participant(
domainId,
DDS_PARTICIPANT_QOS_DEFAULT,
NULL /* listener */,
DDS_STATUS_MASK_NONE);
if (participant == NULL) {
printf("create_participant error\n");
subscriber_shutdown(participant);
return -1;
}
/* Register the type before creating the topic */
type_name = orderedTypeSupport::get_type_name();
retcode = orderedTypeSupport::register_type(participant, type_name);
if (retcode != DDS_RETCODE_OK) {
printf("register_type error %d\n", retcode);
subscriber_shutdown(participant);
return -1;
}
/* To customize the topic QoS, use
the configuration file USER_QOS_PROFILES.xml */
topic = participant->create_topic(
"Example ordered",
type_name,
DDS_TOPIC_QOS_DEFAULT,
NULL /* listener */,
DDS_STATUS_MASK_NONE);
if (topic == NULL) {
printf("create_topic error\n");
subscriber_shutdown(participant);
return -1;
}
/* Start changes for ordered_presentation */
/* Create two subscribers to illustrate different presentation QoS
* This is a publisher/subscriber level QoS, so we have to
* do it here instead of just making two datareaders
*/
orderedDataReader *ordered_reader[2] = { 0 };
/* Subscriber[0], reader[0] and ordered_reader[0] is getting
* the profile "ordered_Profile_subscriber_instance"
*/
/* Subscriber[1], reader[1] and ordered_reader[1] is getting
* the profile "ordered_Profile_subscriber_topic"
*/
for (i = 0; i < MAX_SUBSCRIBERS; ++i) {
printf("Subscriber %d using %s\n", i, profile_name[i]);
subscriber[i] = participant->create_subscriber_with_profile(
"ordered_Library",
profile_name[i],
NULL,
DDS_STATUS_MASK_NONE);
if (subscriber[i] == NULL) {
printf("create_subscriber%d error\n", i);
subscriber_shutdown(participant);
return -1;
}
reader[i] = subscriber[i]->create_datareader_with_profile(
topic,
"ordered_Library",
profile_name[i],
NULL,
DDS_STATUS_MASK_ALL);
if (reader[i] == NULL) {
printf("create_datareader%d error\n", i);
subscriber_shutdown(participant);
return -1;
}
ordered_reader[i] = orderedDataReader::narrow(reader[i]);
if (ordered_reader[i] == NULL) {
printf("DataReader%d narrow error\n", i);
return -1;
}
}
/* If you want to change the Publisher's QoS programmatically rather than
* using the XML file, you will need to add the following lines to your
* code and comment out the above 'for' loop.
*/
/* for (int i = 0; i < MAX_SUBSCRIBERS; ++i) {
*/ /* Get default subscriber QoS to customize */
/* DDS_SubscriberQos subscriber_qos;
retcode = participant->get_default_subscriber_qos(subscriber_qos);
if (retcode != DDS_RETCODE_OK) {
printf("get_default_subscriber_qos error\n");
return -1;
}
*/ /* Set this for both subscribers */
/* subscriber_qos.presentation.ordered_access = DDS_BOOLEAN_TRUE;
if (i == 0) {
printf("Subscriber 0 using Instance access scope\n");
subscriber_qos.presentation.access_scope =
DDS_INSTANCE_PRESENTATION_QOS;
} else {
printf("Subscriber 1 using Topic access scope\n");
subscriber_qos.presentation.access_scope =
DDS_TOPIC_PRESENTATION_QOS;
}
*/ /* To create subscriber with default QoS, use
* DDS_SUBSCRIBER_QOS_DEFAULT instead of subscriber_qos */
/* subscriber[i] = participant->create_subscriber(subscriber_qos,
NULL, DDS_STATUS_MASK_NONE); if (subscriber[i] == NULL) {
printf("create_subscriber error\n");
subscriber_shutdown(participant);
return -1;
}
*/ /* No listener needed, but we do need to increase history depth */
/* Get default datareader QoS to customize */
/* DDS_DataReaderQos datareader_qos;
retcode = subscriber[i]->get_default_datareader_qos(datareader_qos);
if (retcode != DDS_RETCODE_OK) {
printf("get_default_datareader_qos error\n");
return -1;
}
datareader_qos.history.depth = 10;
*/ /* To create datareader with default QoS,
* use DDS_DATAREADER_QOS_DEFAULT instead of datareader_qos */
/* reader[i] = subscriber[i]->create_datareader(topic,
datareader_qos, NULL, DDS_STATUS_MASK_ALL); if (reader[i] == NULL) {
printf("create_datareader error\n");
subscriber_shutdown(participant);
return -1;
}
ordered_reader[i] = orderedDataReader::narrow(reader[i]);
if (ordered_reader[i] == NULL) {
printf("DataReader narrow error\n");
return -1;
}
}
*/
/* Poll for data every 4 seconds */
/* Main loop */
for (count = 0; (sample_count == 0) || (count < sample_count); ++count) {
printf("ordered subscriber sleeping for %d sec...\n",
receive_period.sec);
NDDSUtility::sleep(receive_period);
poll_data(ordered_reader, MAX_SUBSCRIBERS);
}
/* 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/ordered_presentation/c++/ordered_publisher.cxx | /*******************************************************************************
(c) 2005-2014 Copyright, Real-Time Innovations, Inc. All rights reserved.
RTI grants Licensee a license to use, modify, compile, and create derivative
works of the Software. Licensee has the right to distribute object form only
for use with RTI products. The Software is provided "as is", with no warranty
of any type, including any warranty for fitness for any purpose. RTI is under
no obligation to maintain or support the Software. RTI shall not be liable for
any incidental or consequential damages arising out of the use or inability to
use the software.
******************************************************************************/
/* ordered_publisher.cxx
A publication of data of type ordered
This file is derived from code automatically generated by the rtiddsgen
command:
rtiddsgen -language C++ -example <arch> ordered.idl
Example publication of type ordered automatically generated by
'rtiddsgen'. To test them follow these steps:
(1) Compile this file and the example subscription.
(2) Start the subscription with the command
objs/<arch>/ordered_subscriber <domain_id> <sample_count>
(3) Start the publication with the command
objs/<arch>/ordered_publisher <domain_id> <sample_count>
(4) [Optional] Specify the list of discovery initial peers and
multicast receive addresses via an environment variable or a file
(in the current working directory) called NDDS_DISCOVERY_PEERS.
You can run any number of publishers and subscribers programs, and can
add and remove them dynamically from the domain.
Example:
To run the example application on domain <domain_id>:
On Unix:
objs/<arch>/ordered_publisher <domain_id> o
objs/<arch>/ordered_subscriber <domain_id>
On Windows:
objs\<arch>\ordered_publisher <domain_id>
objs\<arch>\ordered_subscriber <domain_id>
modification history
------------ -------
*/
#include <stdio.h>
#include <stdlib.h>
#ifdef RTI_VX653
#include <vThreadsData.h>
#endif
#include "ndds/ndds_cpp.h"
#include "ordered.h"
#include "orderedSupport.h"
/* Delete all entities */
static int publisher_shutdown(DDSDomainParticipant *participant)
{
DDS_ReturnCode_t retcode;
int status = 0;
if (participant != NULL) {
retcode = participant->delete_contained_entities();
if (retcode != DDS_RETCODE_OK) {
printf("delete_contained_entities error %d\n", retcode);
status = -1;
}
retcode = DDSTheParticipantFactory->delete_participant(participant);
if (retcode != DDS_RETCODE_OK) {
printf("delete_participant error %d\n", retcode);
status = -1;
}
}
/* RTI Connext provides finalize_instance() method on
domain participant factory for people who want to release memory used
by the participant factory. Uncomment the following block of code for
clean destruction of the singleton. */
/*
retcode = DDSDomainParticipantFactory::finalize_instance();
if (retcode != DDS_RETCODE_OK) {
printf("finalize_instance error %d\n", retcode);
status = -1;
}
*/
return status;
}
extern "C" int publisher_main(int domainId, int sample_count)
{
DDSDomainParticipant *participant = NULL;
DDSPublisher *publisher = NULL;
DDSTopic *topic = NULL;
DDSDataWriter *writer = NULL;
orderedDataWriter *ordered_writer = NULL;
DDS_ReturnCode_t retcode;
const char *type_name = NULL;
int count = 0;
DDS_Duration_t send_period = { 1, 0 };
/* To customize participant QoS, use
the configuration file USER_QOS_PROFILES.xml */
participant = DDSTheParticipantFactory->create_participant(
domainId,
DDS_PARTICIPANT_QOS_DEFAULT,
NULL /* listener */,
DDS_STATUS_MASK_NONE);
if (participant == NULL) {
printf("create_participant error\n");
publisher_shutdown(participant);
return -1;
}
/* To customize publisher QoS, use
the configuration file USER_QOS_PROFILES.xml */
publisher = participant->create_publisher_with_profile(
"ordered_Library",
"ordered_Profile_subscriber_instance",
NULL /* listener */,
DDS_STATUS_MASK_NONE);
if (publisher == NULL) {
printf("create_publisher error\n");
publisher_shutdown(participant);
return -1;
}
/* If you want to change the Publisher's QoS programmatically rather than
* using the XML file, you will need to add the following lines to your
* code and comment out the create_publisher call above.
*
* In this case, we set the presentation publish mode ordered in the topic.
*/
/* Get default publisher QoS to customize */
/* DDS_PublisherQos publisher_qos;
retcode = participant->get_default_publisher_qos(publisher_qos);
if (retcode != DDS_RETCODE_OK) {
printf("get_default_publisher_qos error\n");
return -1;
}
publisher_qos.presentation.access_scope = DDS_TOPIC_PRESENTATION_QOS;
publisher_qos.presentation.ordered_access = DDS_BOOLEAN_TRUE;
*/ /* To create publisher with default QoS, use DDS_PUBLISHER_QOS_DEFAULT
instead of publisher_qos */
/* publisher = participant->create_publisher(publisher_qos, NULL,
DDS_STATUS_MASK_NONE);
if (publisher == NULL) {
printf("create_participant error\n");
publisher_shutdown(participant);
return -1;
}
*/
/* Register type before creating topic */
type_name = orderedTypeSupport::get_type_name();
retcode = orderedTypeSupport::register_type(participant, type_name);
if (retcode != DDS_RETCODE_OK) {
printf("register_type error %d\n", retcode);
publisher_shutdown(participant);
return -1;
}
/* To customize topic QoS, use
the configuration file USER_QOS_PROFILES.xml */
topic = participant->create_topic(
"Example ordered",
type_name,
DDS_TOPIC_QOS_DEFAULT,
NULL /* listener */,
DDS_STATUS_MASK_NONE);
if (topic == NULL) {
printf("create_topic error\n");
publisher_shutdown(participant);
return -1;
}
/* To customize data writer QoS, use
the configuration file USER_QOS_PROFILES.xml */
writer = publisher->create_datawriter(
topic,
DDS_DATAWRITER_QOS_DEFAULT,
NULL /* listener */,
DDS_STATUS_MASK_NONE);
if (writer == NULL) {
printf("create_datawriter error\n");
publisher_shutdown(participant);
return -1;
}
ordered_writer = orderedDataWriter::narrow(writer);
if (ordered_writer == NULL) {
printf("DataWriter narrow error\n");
publisher_shutdown(participant);
return -1;
}
/* Start changes for Ordered_Presentation */
/* Create two instances*/
ordered *instance0 = NULL;
ordered *instance1 = NULL;
DDS_InstanceHandle_t handle0 = DDS_HANDLE_NIL;
DDS_InstanceHandle_t handle1 = DDS_HANDLE_NIL;
/* Create data sample for writing */
instance0 = orderedTypeSupport::create_data();
if (instance0 == NULL) {
printf("orderedTypeSupport::create_data0 error\n");
publisher_shutdown(participant);
return -1;
}
instance1 = orderedTypeSupport::create_data();
if (instance1 == NULL) {
printf("orderedTypeSupport::create_data1 error\n");
publisher_shutdown(participant);
return -1;
}
/* For a data type that has a key, if the same instance is going to be
written multiple times, initialize the key here
and register the keyed instance prior to writing */
instance0->id = 0;
instance1->id = 1;
handle0 = ordered_writer->register_instance(*instance0);
handle1 = ordered_writer->register_instance(*instance1);
/* Main loop */
for (count = 0; (sample_count == 0) || (count < sample_count); ++count) {
instance0->value = count;
instance1->value = count;
printf("writing instance0, value->%d\n", instance0->value);
retcode = ordered_writer->write(*instance0, handle0);
if (retcode != DDS_RETCODE_OK) {
printf("write error %d\n", retcode);
}
printf("writing instance1, value->%d\n", instance1->value);
retcode = ordered_writer->write(*instance1, handle1);
if (retcode != DDS_RETCODE_OK) {
printf("write error %d\n", retcode);
}
NDDSUtility::sleep(send_period);
}
retcode = ordered_writer->unregister_instance(*instance0, handle0);
if (retcode != DDS_RETCODE_OK) {
printf("unregister instance0 error %d\n", retcode);
}
retcode = ordered_writer->unregister_instance(*instance1, handle1);
if (retcode != DDS_RETCODE_OK) {
printf("unregister instance1 error %d\n", retcode);
}
/* Delete data sample */
retcode = orderedTypeSupport::delete_data(instance0);
if (retcode != DDS_RETCODE_OK) {
printf("orderedTypeSupport::delete_data0 error %d\n", retcode);
}
retcode = orderedTypeSupport::delete_data(instance1);
if (retcode != DDS_RETCODE_OK) {
printf("orderedTypeSupport::delete_data1 error %d\n", retcode);
}
/* Delete all entities */
return publisher_shutdown(participant);
}
#if defined(RTI_WINCE)
int wmain(int argc, wchar_t **argv)
{
int domainId = 0;
int sample_count = 0; /* infinite loop */
if (argc >= 2) {
domainId = _wtoi(argv[1]);
}
if (argc >= 3) {
sample_count = _wtoi(argv[2]);
}
/* Uncomment this to turn on additional logging
NDDSConfigLogger::get_instance()->
set_verbosity_by_category(NDDS_CONFIG_LOG_CATEGORY_API,
NDDS_CONFIG_LOG_VERBOSITY_STATUS_ALL);
*/
return publisher_main(domainId, sample_count);
}
#elif !(defined(RTI_VXWORKS) && !defined(__RTP__)) && !defined(RTI_PSOS)
int main(int argc, char *argv[])
{
int domainId = 0;
int sample_count = 0; /* infinite loop */
if (argc >= 2) {
domainId = atoi(argv[1]);
}
if (argc >= 3) {
sample_count = atoi(argv[2]);
}
/* Uncomment this to turn on additional logging
NDDSConfigLogger::get_instance()->
set_verbosity_by_category(NDDS_CONFIG_LOG_CATEGORY_API,
NDDS_CONFIG_LOG_VERBOSITY_STATUS_ALL);
*/
return publisher_main(domainId, sample_count);
}
#endif
#ifdef RTI_VX653
const unsigned char *__ctype = *(__ctypePtrGet());
extern "C" void usrAppInit()
{
#ifdef USER_APPL_INIT
USER_APPL_INIT; /* for backwards compatibility */
#endif
/* add application specific code here */
taskSpawn(
"pub",
RTI_OSAPI_THREAD_PRIORITY_NORMAL,
0x8,
0x150000,
(FUNCPTR) publisher_main,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0);
}
#endif
| cxx |
rticonnextdds-examples | data/projects/rticonnextdds-examples/connext_dds/ordered_presentation/c++98/ordered_subscriber.cxx | /*******************************************************************************
(c) 2005-2014 Copyright, Real-Time Innovations, Inc. All rights reserved.
RTI grants Licensee a license to use, modify, compile, and create derivative
works of the Software. Licensee has the right to distribute object form only
for use with RTI products. The Software is provided "as is", with no warranty
of any type, including any warranty for fitness for any purpose. RTI is under
no obligation to maintain or support the Software. RTI shall not be liable for
any incidental or consequential damages arising out of the use or inability to
use the software.
******************************************************************************/
#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include "ordered.h"
#include "orderedSupport.h"
#include "ndds/ndds_cpp.h"
#include "application.h"
#define MAX_SUBSCRIBERS 2
using namespace application;
static int shutdown_participant(
DDSDomainParticipant *participant,
const char *shutdown_message,
int status);
/* Start changes for Ordered_Presentation */
/* No listener is needed; we poll readers in this function */
unsigned int poll_data(orderedDataReader *typed_reader[], int numreaders)
{
DDS_ReturnCode_t retcode = DDS_RETCODE_OK;
unsigned int samples_read = 0;
for (int r = 0; r < numreaders; ++r) {
DDS_SampleInfoSeq info_seq;
orderedSeq data_seq;
DDS_ReturnCode_t retcode = typed_reader[r]->take(
data_seq,
info_seq,
DDS_LENGTH_UNLIMITED,
DDS_ANY_SAMPLE_STATE,
DDS_ANY_VIEW_STATE,
DDS_ANY_INSTANCE_STATE);
if (retcode == DDS_RETCODE_NO_DATA) {
// Not an error
continue;
} else if (retcode != DDS_RETCODE_OK) {
// Is an error
std::cerr << "take error: " << retcode << std::endl;
return 0;
}
for (int i = 0; i < data_seq.length(); ++i) {
if (!info_seq[i].valid_data)
continue;
// Make things a bit easier to read.
samples_read++;
int ident = r;
while (ident--) {
std::cout << "\t";
}
std::cout << "Reader " << r << ": Instance" << data_seq[i].id
<< "->value = " << data_seq[i].value << std::endl;
}
retcode = typed_reader[r]->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)
{
DDSSubscriber *subscriber[2] = { 0 };
DDSDataReader *untyped_reader[2] = { 0 };
DDS_Duration_t receive_period = { 4, 0 };
char *profile_name[] = { (char *) "ordered_Profile_subscriber_instance",
(char *) "ordered_Profile_subscriber_topic" };
// 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);
}
// Register the datatype to use when creating the Topic
const char *type_name = orderedTypeSupport::get_type_name();
DDS_ReturnCode_t retcode =
orderedTypeSupport::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 ordered",
type_name,
DDS_TOPIC_QOS_DEFAULT,
NULL /* listener */,
DDS_STATUS_MASK_NONE);
if (topic == NULL) {
return shutdown_participant(
participant,
"create_topic error",
EXIT_FAILURE);
}
/* Start changes for ordered_presentation */
/* Create two subscribers to illustrate different presentation QoS
* This is a publisher/subscriber level QoS, so we have to
* do it here instead of just making two datareaders
*/
orderedDataReader *typed_reader[2] = { 0 };
/* Subscriber[0], reader[0] and ordered_reader[0] is getting
* the profile "ordered_Profile_subscriber_instance"
*/
/* Subscriber[1], reader[1] and ordered_reader[1] is getting
* the profile "ordered_Profile_subscriber_topic"
*/
for (int i = 0; i < MAX_SUBSCRIBERS; ++i) {
std::cout << "Subscriber " << i << " using " << profile_name[i]
<< std::endl;
subscriber[i] = participant->create_subscriber_with_profile(
"ordered_Library",
profile_name[i],
NULL,
DDS_STATUS_MASK_NONE);
if (subscriber[i] == NULL) {
return shutdown_participant(
participant,
"create_subscriber error",
EXIT_FAILURE);
}
untyped_reader[i] = subscriber[i]->create_datareader_with_profile(
topic,
"ordered_Library",
profile_name[i],
NULL,
DDS_STATUS_MASK_ALL);
if (untyped_reader[i] == NULL) {
return shutdown_participant(
participant,
"create_datareader error",
EXIT_FAILURE);
}
typed_reader[i] = orderedDataReader::narrow(untyped_reader[i]);
if (typed_reader[i] == NULL) {
return shutdown_participant(
participant,
"DataReader narrow error",
EXIT_FAILURE);
}
}
/* If you want to change the Publisher's QoS programmatically rather than
* using the XML file, you will need to add the following lines to your
* code and comment out the above 'for' loop.
*/
/* for (int i = 0; i < MAX_SUBSCRIBERS; ++i) {
*/ /* Get default subscriber QoS to customize */
/* DDS_SubscriberQos subscriber_qos;
retcode = participant->get_default_subscriber_qos(subscriber_qos);
if (retcode != DDS_RETCODE_OK) {
std::cerr << "get_default_subscriber_qos error\n";
return EXIT_FAILURE;
}
*/ /* Set this for both subscribers */
/* subscriber_qos.presentation.ordered_access = DDS_BOOLEAN_TRUE;
if (i == 0) {
std::cout << "Subscriber 0 using Instance access scope\n";
subscriber_qos.presentation.access_scope =
DDS_INSTANCE_PRESENTATION_QOS;
} else {
std::cout << "Subscriber 1 using Topic access scope\n";
subscriber_qos.presentation.access_scope =
DDS_TOPIC_PRESENTATION_QOS;
}
*/ /* To create subscriber with default QoS, use
* DDS_SUBSCRIBER_QOS_DEFAULT instead of subscriber_qos */
/* subscriber[i] = participant->create_subscriber(subscriber_qos,
NULL, DDS_STATUS_MASK_NONE); if (subscriber[i] == NULL) {
return shutdown_participant(
participant,
"create_subscriber error",
EXIT_FAILURE);
}
*/ /* No listener needed, but we do need to increase history depth */
/* Get default datareader QoS to customize */
/* DDS_DataReaderQos datareader_qos;
retcode = subscriber[i]->get_default_datareader_qos(datareader_qos);
if (retcode != DDS_RETCODE_OK) {
std::cerr << "get_default_datareader_qos error\n";
return EXIT_FAILURE;
}
datareader_qos.history.depth = 10;
*/ /* To create datareader with default QoS,
* use DDS_DATAREADER_QOS_DEFAULT instead of datareader_qos */
/* untyped_reader[i] = subscriber[i]->create_datareader(topic,
datareader_qos, NULL, DDS_STATUS_MASK_ALL); if (untyped_reader[i] ==
NULL) { return shutdown_participant( participant, "create_datareader
error", EXIT_FAILURE);
}
typed_reader[i] = orderedDataReader::narrow(untyped_reader[i]);
if (typed_reader[i] == NULL) {
return shutdown_participant(
participant,
"DataReader narrow error",
EXIT_FAILURE);
}
}
*/
/* Poll for data every 4 seconds */
// Main loop. Wait for data to arrive, and process when it arrives
unsigned int samples_read = 0;
while (!shutdown_requested && samples_read < sample_count) {
std::cout << "ordered subscriber sleeping for " << receive_period.sec
<< " sec...\n";
NDDSUtility::sleep(receive_period);
samples_read += poll_data(typed_reader, MAX_SUBSCRIBERS);
}
// 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/ordered_presentation/c++98/ordered_publisher.cxx | /*******************************************************************************
(c) 2005-2014 Copyright, Real-Time Innovations, Inc. All rights reserved.
RTI grants Licensee a license to use, modify, compile, and create derivative
works of the Software. Licensee has the right to distribute object form only
for use with RTI products. The Software is provided "as is", with no warranty
of any type, including any warranty for fitness for any purpose. RTI is under
no obligation to maintain or support the Software. RTI shall not be liable for
any incidental or consequential damages arising out of the use or inability to
use the software.
******************************************************************************/
#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include "ordered.h"
#include "orderedSupport.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);
}
// A Publisher allows an application to create one or more DataWriters
DDSPublisher *publisher = participant->create_publisher_with_profile(
"ordered_Library",
"ordered_Profile_subscriber_instance",
NULL /* listener */,
DDS_STATUS_MASK_NONE);
if (publisher == NULL) {
return shutdown_participant(
participant,
"create_publisher error",
EXIT_FAILURE);
}
/* If you want to change the Publisher's QoS programmatically rather than
* using the XML file, you will need to add the following lines to your
* code and comment out the create_publisher call above.
*
* In this case, we set the presentation publish mode ordered in the topic.
*/
/* Get default publisher QoS to customize */
/* DDS_PublisherQos publisher_qos;
retcode = participant->get_default_publisher_qos(publisher_qos);
if (retcode != DDS_RETCODE_OK) {
std::cerr << "get_default_publisher_qos error\n";
return EXIT_FAILURE;
}
publisher_qos.presentation.access_scope = DDS_TOPIC_PRESENTATION_QOS;
publisher_qos.presentation.ordered_access = DDS_BOOLEAN_TRUE;
*/ /* To create publisher with default QoS, use DDS_PUBLISHER_QOS_DEFAULT
instead of publisher_qos */
/* DDSPublisher *publisher = participant->create_publisher(
publisher_qos,
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 = orderedTypeSupport::get_type_name();
DDS_ReturnCode_t retcode =
orderedTypeSupport::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 ordered",
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 ordered" Topic
DDSDataWriter *untyped_writer = publisher->create_datawriter(
topic,
DDS_DATAWRITER_QOS_DEFAULT,
NULL /* listener */,
DDS_STATUS_MASK_NONE);
if (untyped_writer == NULL) {
return shutdown_participant(
participant,
"create_datawriter error",
EXIT_FAILURE);
}
// Narrow casts from an untyped DataWriter to a writer of your type
orderedDataWriter *typed_writer = orderedDataWriter::narrow(untyped_writer);
if (typed_writer == NULL) {
return shutdown_participant(
participant,
"DataWriter narrow error",
EXIT_FAILURE);
}
/* Start changes for Ordered_Presentation */
/* Create two instances*/
ordered *instance0 = NULL;
ordered *instance1 = NULL;
DDS_InstanceHandle_t handle0 = DDS_HANDLE_NIL;
DDS_InstanceHandle_t handle1 = DDS_HANDLE_NIL;
/* Create data sample for writing */
instance0 = orderedTypeSupport::create_data();
if (instance0 == NULL) {
return shutdown_participant(
participant,
"orderedTypeSupport::create_data0 error",
EXIT_FAILURE);
}
instance1 = orderedTypeSupport::create_data();
if (instance1 == NULL) {
return shutdown_participant(
participant,
"orderedTypeSupport::create_data1 error",
EXIT_FAILURE);
}
/* For a data type that has a key, if the same instance is going to be
written multiple times, initialize the key here
and register the keyed instance prior to writing */
instance0->id = 0;
instance1->id = 1;
handle0 = typed_writer->register_instance(*instance0);
handle1 = typed_writer->register_instance(*instance1);
// Main loop, write data
for (unsigned int samples_written = 0;
!shutdown_requested && samples_written < sample_count;
++samples_written) {
instance0->value = samples_written;
instance1->value = samples_written;
std::cout << "writing instance0, value->" << instance0->value
<< std::endl;
retcode = typed_writer->write(*instance0, handle0);
if (retcode != DDS_RETCODE_OK) {
std::cerr << "write error " << retcode << std::endl;
}
std::cout << "writing instance1, value->" << instance1->value
<< std::endl;
retcode = typed_writer->write(*instance1, handle1);
if (retcode != DDS_RETCODE_OK) {
std::cerr << "write error " << retcode << std::endl;
}
NDDSUtility::sleep(send_period);
}
retcode = typed_writer->unregister_instance(*instance0, handle0);
if (retcode != DDS_RETCODE_OK) {
std::cerr << "unregister instance0 error " << retcode << std::endl;
}
retcode = typed_writer->unregister_instance(*instance1, handle1);
if (retcode != DDS_RETCODE_OK) {
std::cerr << "unregister instance1 error " << retcode << std::endl;
}
/* Delete data sample */
retcode = orderedTypeSupport::delete_data(instance0);
if (retcode != DDS_RETCODE_OK) {
std::cerr << "orderedTypeSupport::delete_data0 error " << retcode
<< std::endl;
}
retcode = orderedTypeSupport::delete_data(instance1);
if (retcode != DDS_RETCODE_OK) {
std::cerr << "orderedTypeSupport::delete_data1 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/ordered_presentation/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/ordered_presentation/c/ordered_subscriber.c | /*******************************************************************************
(c) 2005-2014 Copyright, Real-Time Innovations, Inc. All rights reserved.
RTI grants Licensee a license to use, modify, compile, and create derivative
works of the Software. Licensee has the right to distribute object form only
for use with RTI products. The Software is provided "as is", with no warranty
of any type, including any warranty for fitness for any purpose. RTI is under
no obligation to maintain or support the Software. RTI shall not be liable for
any incidental or consequential damages arising out of the use or inability to
use the software.
******************************************************************************/
/* ordered_subscriber.c
A subscription example
This file is derived from code automatically generated by the rtiddsgen
command:
rtiddsgen -language C -example <arch> ordered.idl
Example subscription of type ordered automatically generated by
'rtiddsgen'. To test them, follow these steps:
(1) Compile this file and the example publication.
(2) Start the subscription with the command
objs/<arch>/ordered_subscriber <domain_id> <sample_count>
(3) Start the publication with the command
objs/<arch>/ordered_publisher <domain_id> <sample_count>
(4) [Optional] Specify the list of discovery initial peers and
multicast receive addresses via an environment variable or a file
(in the current working directory) called NDDS_DISCOVERY_PEERS.
You can run any number of publishers and subscribers programs, and can
add and remove them dynamically from the domain.
Example:
To run the example application on domain <domain_id>:
On UNIX systems:
objs/<arch>/ordered_publisher <domain_id>
objs/<arch>/ordered_subscriber <domain_id>
On Windows systems:
objs\<arch>\ordered_publisher <domain_id>
objs\<arch>\ordered_subscriber <domain_id>
modification history
------------ -------
*/
#include "ndds/ndds_c.h"
#include "ordered.h"
#include "orderedSupport.h"
#include <stdio.h>
#include <stdlib.h>
#define MAX_SUBSCRIBERS 2
/* Start changes for Ordered_Presentation */
/* No listener is needed; we poll readers in this function*/
void poll_data(orderedDataReader *ordered_reader[], int numreaders)
{
DDS_ReturnCode_t retcode = DDS_RETCODE_OK;
int r, i, ident;
for (r = 0; r < numreaders; ++r) {
struct DDS_SampleInfoSeq info_seq;
struct orderedSeq data_seq = DDS_SEQUENCE_INITIALIZER;
retcode = orderedDataReader_take(
ordered_reader[r],
&data_seq,
&info_seq,
DDS_LENGTH_UNLIMITED,
DDS_ANY_SAMPLE_STATE,
DDS_ANY_VIEW_STATE,
DDS_ANY_INSTANCE_STATE);
if (retcode == DDS_RETCODE_NO_DATA) {
/* Not an error */
continue;
} else if (retcode != DDS_RETCODE_OK) {
/* Is an error */
printf("take error: %d\n", retcode);
return;
}
for (i = 0; i < orderedSeq_get_length(&data_seq); ++i) {
ordered *data;
if (DDS_SampleInfoSeq_get_reference(&info_seq, i)->valid_data) {
data = orderedSeq_get_reference(&data_seq, i);
/* Make things a bit easier to read. */
ident = r;
while (ident--) {
printf("\t");
}
printf("Reader %d: Instance%d->value = %d\n",
r,
data->id,
data->value);
}
}
retcode = orderedDataReader_return_loan(
ordered_reader[r],
&data_seq,
&info_seq);
if (retcode != DDS_RETCODE_OK) {
printf("return loan error %d\n", retcode);
}
}
}
/* End changes for Ordered_Presentation */
/* Delete all entities */
static int subscriber_shutdown(
DDS_DomainParticipant *participant,
struct DDS_SubscriberQos *subscriber_qos,
struct DDS_DataReaderQos *datareader_qos)
{
DDS_ReturnCode_t retcode;
int status = 0;
if (participant != NULL) {
retcode = DDS_DomainParticipant_delete_contained_entities(participant);
if (retcode != DDS_RETCODE_OK) {
printf("delete_contained_entities error %d\n", retcode);
status = -1;
}
retcode = DDS_DomainParticipantFactory_delete_participant(
DDS_TheParticipantFactory,
participant);
if (retcode != DDS_RETCODE_OK) {
printf("delete_participant error %d\n", retcode);
status = -1;
}
retcode = DDS_DataReaderQos_finalize(datareader_qos);
if (retcode != DDS_RETCODE_OK) {
printf("DataReaderQos_finalize error %d\n", retcode);
status = -1;
}
retcode = DDS_SubscriberQos_finalize(subscriber_qos);
if (retcode != DDS_RETCODE_OK) {
printf("SubscriberQos_finalize error %d\n", retcode);
status = -1;
}
}
/* RTI Connext provides the finalize_instance() method on
domain participant factory for users who want to release memory used
by the participant factory. Uncomment the following block of code for
clean destruction of the singleton. */
/*
retcode = DDS_DomainParticipantFactory_finalize_instance();
if (retcode != DDS_RETCODE_OK) {
printf("finalize_instance error %d\n", retcode);
status = -1;
}
*/
return status;
}
static int subscriber_main(int domainId, int sample_count)
{
DDS_DomainParticipant *participant = NULL;
DDS_Subscriber *subscriber[MAX_SUBSCRIBERS] = { 0 };
DDS_Topic *topic = NULL;
DDS_DataReader *reader[MAX_SUBSCRIBERS] = { 0 };
DDS_ReturnCode_t retcode;
const char *type_name = NULL;
int count = 0;
struct DDS_Duration_t poll_period = { 4, 0 };
orderedDataReader *ordered_reader[MAX_SUBSCRIBERS] = { 0 };
int i;
struct DDS_SubscriberQos subscriber_qos = DDS_SubscriberQos_INITIALIZER;
struct DDS_DataReaderQos datareader_qos = DDS_DataReaderQos_INITIALIZER;
char *profile_name[] = { "ordered_Profile_subscriber_instance",
"ordered_Profile_subscriber_topic" };
/* To customize participant QoS, use
the configuration file USER_QOS_PROFILES.xml */
participant = DDS_DomainParticipantFactory_create_participant(
DDS_TheParticipantFactory,
domainId,
&DDS_PARTICIPANT_QOS_DEFAULT,
NULL /* listener */,
DDS_STATUS_MASK_NONE);
if (participant == NULL) {
printf("create_participant error\n");
subscriber_shutdown(participant, &subscriber_qos, &datareader_qos);
return -1;
}
/* Register the type before creating the topic */
type_name = orderedTypeSupport_get_type_name();
retcode = orderedTypeSupport_register_type(participant, type_name);
if (retcode != DDS_RETCODE_OK) {
printf("register_type error %d\n", retcode);
subscriber_shutdown(participant, &subscriber_qos, &datareader_qos);
return -1;
}
/* To customize topic QoS, use
the configuration file USER_QOS_PROFILES.xml */
topic = DDS_DomainParticipant_create_topic(
participant,
"Example ordered",
type_name,
&DDS_TOPIC_QOS_DEFAULT,
NULL /* listener */,
DDS_STATUS_MASK_NONE);
if (topic == NULL) {
printf("create_topic error\n");
subscriber_shutdown(participant, &subscriber_qos, &datareader_qos);
return -1;
}
/* Start changes for ordered_presentation */
/* Create two subscriber to illustrate different presentation QoS
* This is a publisher/subscriber level QoS, so we have to do it
* here instead of just making two datareaders
*/
/* Subscriber[0], reader[0] and ordered_reader[0] is getting
* the profile "ordered_Profile_subscriber_instance"
*/
for (i = 0; i < MAX_SUBSCRIBERS; ++i) {
/* Subscriber[1], reader[1] and ordered_reader[1] is getting
* the profile "ordered_Profile_subscriber_topic"
*/
printf("Subscriber %d using %s\n", i, profile_name[i]);
subscriber[i] = DDS_DomainParticipant_create_subscriber_with_profile(
participant,
"ordered_Library",
profile_name[i],
NULL /* Listener */,
DDS_STATUS_MASK_NONE);
if (subscriber[i] == NULL) {
printf("create_subscriber%d error\n", i);
subscriber_shutdown(participant, &subscriber_qos, &datareader_qos);
return -1;
}
reader[i] = DDS_Subscriber_create_datareader_with_profile(
subscriber[i],
DDS_Topic_as_topicdescription(topic),
"ordered_Library",
profile_name[i],
NULL,
DDS_STATUS_MASK_NONE);
if (reader[i] == NULL) {
printf("create_datareader%d error\n", i);
subscriber_shutdown(participant, &subscriber_qos, &datareader_qos);
return -1;
}
ordered_reader[i] = orderedDataReader_narrow(reader[i]);
if (ordered_reader[i] == NULL) {
printf("DataReader%d narrow error\n", i);
return -1;
}
}
/* If you want to change the Publisher's QoS programmatically rather than
* using the XML file, you will need to add the following lines to your
* code and comment out the above 'for' loop.
*/
/*
for (i = 0; i < MAX_SUBSCRIBERS; ++i) {
*/ /* Get default subscriber QoS to customize */
/* retcode =
DDS_DomainParticipant_get_default_subscriber_qos(participant,
&subscriber_qos);
if (retcode != DDS_RETCODE_OK) {
printf("get_default_subscriber_qos error\n");
return -1;
}
*/ /* Set ordered_access = TRUE for both subscribers */
/* subscriber_qos.presentation.ordered_access = DDS_BOOLEAN_TRUE;
*/ /* We are assuming there are only 2 subscribers. Otherwise you
* will need to modify the following conditions.
*/
/* if (i == 0) {
printf("Subscriber 0 using Instance access scope\n");
subscriber_qos.presentation.access_scope =
DDS_INSTANCE_PRESENTATION_QOS;
} else {
printf("Subscriber 1 using Topic access scope\n");
subscriber_qos.presentation.access_scope =
DDS_TOPIC_PRESENTATION_QOS;
}
*/ /* To create subscriber with default QoS, use DDS_SUBSCRIBER_QOS_DEFAULT
instead of subscriber_qos */
/* subscriber[i] = DDS_DomainParticipant_create_subscriber(participant,
&subscriber_qos, NULL, DDS_STATUS_MASK_NONE);
if (subscriber == NULL) {
printf("create_subscriber error\n");
subscriber_shutdown(participant, &subscriber_qos,
&datareader_qos); return -1;
}
*/ /* No listener needed, but we do need to increase history depth */
/* Get default datareader QoS to customize */
/* retcode = DDS_Subscriber_get_default_datareader_qos(subscriber[i],
&datareader_qos);
if (retcode != DDS_RETCODE_OK) {
printf("get_default_datareader_qos error\n");
return -1;
}
datareader_qos.history.depth = 10;
*/ /* To create datareader with default QoS, use DDS_DATAREADER_QOS_DEFAULT
instead of datareader_qos */
/* reader[i] = DDS_Subscriber_create_datareader(subscriber[i],
DDS_Topic_as_topicdescription(topic), &datareader_qos, NULL,
DDS_STATUS_MASK_NONE);
if (reader == NULL) {
printf("create_datareader error\n");
subscriber_shutdown(participant, &subscriber_qos,
&datareader_qos); return -1;
}
ordered_reader[i] = orderedDataReader_narrow(reader[i]);
if (ordered_reader[i] == NULL) {
printf("DataReader narrow error\n");
return -1;
}
}
*/
/* Main loop */
for (count = 0; (sample_count == 0) || (count < sample_count); ++count) {
printf("ordered subscriber sleeping for %d sec...\n", poll_period.sec);
NDDS_Utility_sleep(&poll_period);
poll_data(ordered_reader, MAX_SUBSCRIBERS);
}
/* Cleanup and delete all entities */
return subscriber_shutdown(participant, &subscriber_qos, &datareader_qos);
}
#if defined(RTI_WINCE)
int wmain(int argc, wchar_t **argv)
{
int domainId = 0;
int sample_count = 0; /* infinite loop */
if (argc >= 2) {
domainId = _wtoi(argv[1]);
}
if (argc >= 3) {
sample_count = _wtoi(argv[2]);
}
/* Uncomment this to turn on additional logging
NDDS_Config_Logger_set_verbosity_by_category(
NDDS_Config_Logger_get_instance(),
NDDS_CONFIG_LOG_CATEGORY_API,
NDDS_CONFIG_LOG_VERBOSITY_STATUS_ALL);
*/
return subscriber_main(domainId, sample_count);
}
#elif !(defined(RTI_VXWORKS) && !defined(__RTP__)) && !defined(RTI_PSOS)
int main(int argc, char *argv[])
{
int domainId = 0;
int sample_count = 0; /* infinite loop */
if (argc >= 2) {
domainId = atoi(argv[1]);
}
if (argc >= 3) {
sample_count = atoi(argv[2]);
}
/* Uncomment this to turn on additional logging
NDDS_Config_Logger_set_verbosity_by_category(
NDDS_Config_Logger_get_instance(),
NDDS_CONFIG_LOG_CATEGORY_API,
NDDS_CONFIG_LOG_VERBOSITY_STATUS_ALL);
*/
return subscriber_main(domainId, sample_count);
}
#endif
#ifdef RTI_VX653
const unsigned char *__ctype = NULL;
void usrAppInit()
{
#ifdef USER_APPL_INIT
USER_APPL_INIT; /* for backwards compatibility */
#endif
/* add application specific code here */
taskSpawn(
"sub",
RTI_OSAPI_THREAD_PRIORITY_NORMAL,
0x8,
0x150000,
(FUNCPTR) subscriber_main,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0);
}
#endif
| c |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.