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/using_typecodes/c++11/msg_publisher.cxx
/******************************************************************************* (c) 2005-2015 Copyright, Real-Time Innovations, Inc. All rights reserved. RTI grants Licensee a license to use, modify, compile, and create derivative works of the Software. Licensee has the right to distribute object form only for use with RTI products. The Software is provided "as is", with no warranty of any type, including any warranty for fitness for any purpose. RTI is under no obligation to maintain or support the Software. RTI shall not be liable for any incidental or consequential damages arising out of the use or inability to use the software. ******************************************************************************/ #include <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 "msg.hpp" void run_publisher_application( unsigned int domain_id, unsigned int sample_count) { // Retrieve the Participant QoS, from USER_QOS_PROFILES.xml dds::domain::qos::DomainParticipantQos participant_qos = dds::core::QosProvider::Default()->participant_qos(); // If you want to change the Participant's QoS programmatically rather than // using the XML file, uncomment the following lines. // participant_qos << DomainParticipantResourceLimits(). // type_code_max_serialized_length(3070); // Create a DomainParticipant. dds::domain::DomainParticipant participant(domain_id, participant_qos); // Create a Topic -- and automatically register the type dds::topic::Topic<msg> topic(participant, "Example msg"); // Create a Publisher with default QoS dds::pub::Publisher publisher(participant); // Create a DataWriter with default Qos dds::pub::DataWriter<msg> writer(publisher, topic); msg sample; for (unsigned int samples_written = 0; !application::shutdown_requested && samples_written < sample_count; samples_written++) { // Update sample and send it. std::cout << "Writing msg, count " << samples_written << std::endl; sample.count(samples_written); 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/using_typecodes/c++11/msg_subscriber.cxx
/******************************************************************************* (c) 2005-2015 Copyright, Real-Time Innovations, Inc. All rights reserved. RTI grants Licensee a license to use, modify, compile, and create derivative works of the Software. Licensee has the right to distribute object form only for use with RTI products. The Software is provided "as is", with no warranty of any type, including any warranty for fitness for any purpose. RTI is under no obligation to maintain or support the Software. RTI shall not be liable for any incidental or consequential damages arising out of the use or inability to use the software. ******************************************************************************/ #include <dds/sub/ddssub.hpp> #include <dds/core/ddscore.hpp> #include <rti/config/Logger.hpp> // for logging #include "msg.hpp" #include "application.hpp" // for command line parsing and ctrl-c int process_data( dds::sub::DataReader<dds::topic::PublicationBuiltinTopicData> reader) { int count = 0; // Take all samples dds::sub::LoanedSamples<dds::topic::PublicationBuiltinTopicData> samples = reader.take(); for (const auto &sample : samples) { if (sample.info().valid()) { const dds::topic::PublicationBuiltinTopicData &data = sample.data(); const dds::topic::BuiltinTopicKey &partKey = data.participant_key(); const dds::topic::BuiltinTopicKey &key = sample.data().key(); std::cout << std::hex << std::setw(8) << std::setfill('0'); std::cout << "-----" << std::endl << "Found topic \"" << data.topic_name() << "\"" << std::endl << "participant: " << partKey.value()[0] << partKey.value()[1] << partKey.value()[2] << std::endl << "datawriter: " << key.value()[0] << key.value()[1] << key.value()[2] << std::endl << "type:" << std::endl; if (!data->type().is_set()) { std::cout << "No type received, perhaps increase " << "type_code_max_serialized_length?" << std::endl; } else { // Using the type propagated we print the data type // with print_idl() rti::core::xtypes::print_idl(data->type().get(), 2); } count++; } } return count; } void run_subscriber_application( unsigned int domain_id, unsigned int sample_count) { // Retrieve the Participant QoS, from USER_QOS_PROFILES.xml dds::domain::qos::DomainParticipantQos participant_qos = dds::core::QosProvider::Default()->participant_qos(); // If you want to change the Participant's QoS programmatically rather than // using the XML file, uncomment the following lines. // participant_qos << DomainParticipantResourceLimits(). // type_code_max_serialized_length(3070); // Create a DomainParticipant. dds::domain::DomainParticipant participant(domain_id, participant_qos); // First get the builtin subscriber. dds::sub::Subscriber builtin_subscriber = dds::sub::builtin_subscriber(participant); // Then get builtin subscriber's DataReader for DataWriters. dds::sub::DataReader<dds::topic::PublicationBuiltinTopicData> publication_reader = rti::sub::find_datareader_by_topic_name< dds::sub::DataReader< dds::topic::PublicationBuiltinTopicData>>( builtin_subscriber, dds::topic::publication_topic_name()); // 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( publication_reader, dds::sub::status::DataState::any(), [publication_reader, &samples_read]() { samples_read += process_data(publication_reader); }); waitset += read_condition; 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/printing_qos/c++/printing_subscriber.cxx
/* * (c) Copyright, Real-Time Innovations, 2021. All rights reserved. * RTI grants Licensee a license to use, modify, compile, and create derivative * works of the software solely for use with RTI Connext DDS. Licensee may * redistribute copies of the software provided that all such copies are subject * to this license. The software is provided "as is", with no warranty of any * type, including any warranty for fitness for any purpose. RTI is under no * obligation to maintain or support the software. RTI shall not be liable for * any incidental or consequential damages arising out of the use or inability * to use the software. */ #include <iostream> #include <stdio.h> #include <stdlib.h> #include "printing.h" #include "printingSupport.h" #include "ndds/ndds_cpp.h" #include "application.h" using namespace application; static int shutdown_participant( DDSDomainParticipant *participant, const char *shutdown_message, int status); // Process data. Returns number of samples processed. unsigned int process_data(printingDataReader *typed_reader) { printingSeq data_seq; // Sequence of received data DDS_SampleInfoSeq info_seq; // Metadata associated with samples in data_seq unsigned int samples_read = 0; // Take available data from DataReader's queue typed_reader->take( data_seq, info_seq, DDS_LENGTH_UNLIMITED, DDS_ANY_SAMPLE_STATE, DDS_ANY_VIEW_STATE, DDS_ANY_INSTANCE_STATE); // Iterate over all available data for (int i = 0; i < data_seq.length(); ++i) { // Check if a sample is an instance lifecycle event if (info_seq[i].valid_data) { // Print data std::cout << "Received data" << std::endl; printingTypeSupport::print_data(&data_seq[i]); samples_read++; } else { // This is an instance lifecycle event with no data payload. std::cout << "Received instance state notification" << std::endl; } } // Data loaned from Connext for performance. Return loan when done. DDS_ReturnCode_t retcode = typed_reader->return_loan(data_seq, info_seq); if (retcode != DDS_RETCODE_OK) { std::cerr << "return loan error " << retcode << std::endl; } return samples_read; } int run_subscriber_application(unsigned int domain_id, unsigned int sample_count) { // Start communicating in a domain, usually one participant per application DDSDomainParticipant *participant = DDSTheParticipantFactory->create_participant( domain_id, DDS_PARTICIPANT_QOS_DEFAULT, NULL, // listener DDS_STATUS_MASK_NONE); if (participant == NULL) { return shutdown_participant(participant, "create_participant error", EXIT_FAILURE); } DDS_DomainParticipantQos participant_qos; DDS_ReturnCode_t retcode = participant->get_qos(participant_qos); if (retcode != DDS_RETCODE_OK){ return shutdown_participant(participant, "get_qos error", EXIT_FAILURE); } char *str = NULL; DDS_UnsignedLong strSize = 0; DDS_QosPrintFormat printFormat = DDS_QosPrintFormat_INITIALIZER; /* * First, we pass NULL for the str argument. This will cause the API to update * the strSize argument to contain the required size of the str buffer. * We then allocate a buffer of that size and obtain the QoS string. * The DDS_DomainParticipantQos_to_string_w_params API prints all the QoS values for * the DomainParticipantQos object. */ participant_qos.to_string(str, strSize, DDS_QOS_PRINT_ALL, printFormat); str = DDS_String_alloc(strSize); if (str == NULL) { return shutdown_participant(participant, "String allocation error", EXIT_FAILURE); } participant_qos.to_string(str, strSize, DDS_QOS_PRINT_ALL, printFormat); std::cout << str << std::endl; DDS_String_free(str); str = NULL; // 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); } DDS_SubscriberQos subscriber_qos; retcode = subscriber->get_qos(subscriber_qos); if (retcode != DDS_RETCODE_OK){ return shutdown_participant(participant, "get_qos error", EXIT_FAILURE); } /* * First, we pass NULL for the str argument. This will cause the API to update * the strSize argument to contain the required size of the str buffer. * We then allocate a buffer of that size and obtain the QoS string. * The DDS_SubscriberQos_to_string_w_params API prints all the QoS values for * the SubscriberQos object. */ subscriber_qos.to_string(str, strSize, printFormat); str = DDS_String_alloc(strSize); if (str == NULL) { return shutdown_participant(participant, "String allocation error", EXIT_FAILURE); } subscriber_qos.to_string(str, strSize, printFormat); std::cout << str << std::endl; DDS_String_free(str); str = NULL; // Register the datatype to use when creating the Topic const char *type_name = printingTypeSupport::get_type_name(); retcode = printingTypeSupport::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 printing", 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 printing" Topic DDSDataReader *untyped_reader = subscriber->create_datareader( topic, DDS_DATAREADER_QOS_DEFAULT, NULL, DDS_STATUS_MASK_NONE); if (untyped_reader == NULL) { return shutdown_participant(participant, "create_datareader error", EXIT_FAILURE); } DDS_DataReaderQos reader_qos; retcode = untyped_reader->get_qos(reader_qos); if (retcode != DDS_RETCODE_OK){ return shutdown_participant(participant, "get_qos error", EXIT_FAILURE); } reader_qos.print(); // Narrow casts from a untyped DataReader to a reader of your type printingDataReader *typed_reader = printingDataReader::narrow(untyped_reader); if (typed_reader == NULL) { return shutdown_participant(participant, "DataReader narrow error", EXIT_FAILURE); } // Create ReadCondition that triggers when unread data in reader's queue DDSReadCondition *read_condition = typed_reader->create_readcondition( DDS_NOT_READ_SAMPLE_STATE, DDS_ANY_VIEW_STATE, DDS_ANY_INSTANCE_STATE); if (read_condition == NULL) { return shutdown_participant(participant, "create_readcondition error", EXIT_FAILURE); } // WaitSet will be woken when the attached condition is triggered DDSWaitSet waitset; retcode = waitset.attach_condition(read_condition); if (retcode != DDS_RETCODE_OK) { return shutdown_participant(participant, "attach_condition error", EXIT_FAILURE); } // Main loop. Wait for data to arrive, and process when it arrives unsigned int samples_read = 0; while (!shutdown_requested && samples_read < sample_count) { DDSConditionSeq active_conditions_seq; // Wait for data and report if it does not arrive in 1 second DDS_Duration_t wait_timeout = { 1, 0 }; retcode = waitset.wait(active_conditions_seq, wait_timeout); if (retcode == DDS_RETCODE_OK) { // If the read condition is triggered, process data samples_read += process_data(typed_reader); } else { if (retcode == DDS_RETCODE_TIMEOUT) { std::cout << "No data after 1 second" << std::endl; } } } // Cleanup return shutdown_participant(participant, "Shutting down", 0); } // Delete all entities static int shutdown_participant( DDSDomainParticipant *participant, const char *shutdown_message, int status) { DDS_ReturnCode_t retcode; std::cout << shutdown_message << std::endl; if (participant != NULL) { // Cleanup everything created by this Participant retcode = participant->delete_contained_entities(); if (retcode != DDS_RETCODE_OK) { std::cerr << "delete_contained_entities error" << retcode << std::endl; status = EXIT_FAILURE; } retcode = DDSTheParticipantFactory->delete_participant(participant); if (retcode != DDS_RETCODE_OK) { std::cerr << "delete_participant error" << retcode << std::endl; status = EXIT_FAILURE; } } return status; } int main(int argc, char *argv[]) { // Parse arguments and handle control-C ApplicationArguments arguments; parse_arguments(arguments, argc, argv); if (arguments.parse_result == PARSE_RETURN_EXIT) { return EXIT_SUCCESS; } else if (arguments.parse_result == PARSE_RETURN_FAILURE) { return EXIT_FAILURE; } setup_signal_handlers(); // Sets Connext verbosity to help debugging NDDSConfigLogger::get_instance()->set_verbosity(arguments.verbosity); int status = run_subscriber_application(arguments.domain_id, arguments.sample_count); // Releases the memory used by the participant factory. Optional at // application exit DDS_ReturnCode_t retcode = DDSDomainParticipantFactory::finalize_instance(); if (retcode != DDS_RETCODE_OK) { std::cerr << "finalize_instance error" << retcode << std::endl; status = EXIT_FAILURE; } return status; }
cxx
rticonnextdds-examples
data/projects/rticonnextdds-examples/connext_dds/printing_qos/c++/printing_publisher.cxx
/* * (c) Copyright, Real-Time Innovations, 2021. All rights reserved. * RTI grants Licensee a license to use, modify, compile, and create derivative * works of the software solely for use with RTI Connext DDS. Licensee may * redistribute copies of the software provided that all such copies are subject * to this license. The software is provided "as is", with no warranty of any * type, including any warranty for fitness for any purpose. RTI is under no * obligation to maintain or support the software. RTI shall not be liable for * any incidental or consequential damages arising out of the use or inability * to use the software. */ #include <iostream> #include <stdio.h> #include <stdlib.h> #include "printing.h" #include "printingSupport.h" #include "ndds/ndds_cpp.h" #include "application.h" using namespace application; static int shutdown_participant( DDSDomainParticipant *participant, const char *shutdown_message, int status); int run_publisher_application(unsigned int domain_id, unsigned int sample_count) { // Start communicating in a domain, usually one participant per application DDSDomainParticipant *participant = DDSTheParticipantFactory->create_participant( domain_id, DDS_PARTICIPANT_QOS_DEFAULT, NULL, // listener DDS_STATUS_MASK_NONE); if (participant == NULL) { return shutdown_participant(participant, "create_participant error", EXIT_FAILURE); } // A Publisher allows an application to create one or more DataWriters DDSPublisher *publisher = participant->create_publisher( DDS_PUBLISHER_QOS_DEFAULT, NULL, // listener DDS_STATUS_MASK_NONE); if (publisher == NULL) { return shutdown_participant(participant, "create_publisher error", EXIT_FAILURE); } DDS_PublisherQos publisher_qos; DDS_ReturnCode_t retcode = publisher->get_qos(publisher_qos); if (retcode != DDS_RETCODE_OK){ return shutdown_participant(participant, "get_qos error", EXIT_FAILURE); } char *str = NULL; DDS_UnsignedLong strSize = 0; DDS_QosPrintFormat printFormat = DDS_QosPrintFormat_INITIALIZER; /* * First, we pass NULL for the str argument. This will cause the API to update * the strSize argument to contain the required size of the str buffer. * We then allocate a buffer of that size and obtain the QoS string. * The DDS_PublisherQos_to_string_w_params API prints all the QoS values for * the PublisherQos object. */ publisher_qos.to_string(str, strSize, DDS_QOS_PRINT_ALL, printFormat); str = DDS_String_alloc(strSize); if (str == NULL) { return shutdown_participant(participant, "String allocation error", EXIT_FAILURE); } publisher_qos.to_string(str, strSize, DDS_QOS_PRINT_ALL, printFormat); std::cout << str << std::endl; DDS_String_free(str); str = NULL; // Register the datatype to use when creating the Topic const char *type_name = printingTypeSupport::get_type_name(); retcode = printingTypeSupport::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 printing", type_name, DDS_TOPIC_QOS_DEFAULT, NULL, // listener DDS_STATUS_MASK_NONE); if (topic == NULL) { return shutdown_participant(participant, "create_topic error", EXIT_FAILURE); } DDS_TopicQos topic_qos; retcode = topic->get_qos(topic_qos); if (retcode != DDS_RETCODE_OK){ return shutdown_participant(participant, "get_qos error", EXIT_FAILURE); } /* * First, we pass NULL for the str argument. This will cause the API to update * the strSize argument to contain the required size of the str buffer. * We then allocate a buffer of that size and obtain the QoS string. * The DDS_TopicQos_to_string_w_params API prints all the QoS values for * the TopicQos object. */ topic_qos.to_string(str, strSize, printFormat); str = DDS_String_alloc(strSize); if (str == NULL) { return shutdown_participant(participant, "String allocation error", EXIT_FAILURE); } topic_qos.to_string(str, strSize, printFormat); std::cout << str << std::endl; DDS_String_free(str); str = NULL; // This DataWriter writes data on "Example printing" 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); } DDS_DataWriterQos writer_qos; retcode = untyped_writer->get_qos(writer_qos); if (retcode != DDS_RETCODE_OK){ return shutdown_participant(participant, "get_qos error", EXIT_FAILURE); } writer_qos.print(); // Narrow casts from an untyped DataWriter to a writer of your type printingDataWriter *typed_writer = printingDataWriter::narrow(untyped_writer); if (typed_writer == NULL) { return shutdown_participant(participant, "DataWriter narrow error", EXIT_FAILURE); } // Create data for writing, allocating all members printing *data = printingTypeSupport::create_data(); if (data == NULL) { return shutdown_participant( participant, "printingTypeSupport::create_data error", EXIT_FAILURE); } // Main loop, write data for (unsigned int samples_written = 0; !shutdown_requested && samples_written < sample_count; ++samples_written) { // Modify the data to be written here data->x = static_cast<DDS_Short>(samples_written); std::cout << "Writing printing, count " << samples_written << std::endl; retcode = typed_writer->write(*data, DDS_HANDLE_NIL); if (retcode != DDS_RETCODE_OK) { std::cerr << "write error " << retcode << std::endl; } // Send once every second DDS_Duration_t send_period = { 1, 0 }; NDDSUtility::sleep(send_period); } // Delete previously allocated printing, including all contained elements retcode = printingTypeSupport::delete_data(data); if (retcode != DDS_RETCODE_OK) { std::cerr << "printingTypeSupport::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/printing_qos/c++/application.h
/* * (c) Copyright, Real-Time Innovations, 2021. All rights reserved. * RTI grants Licensee a license to use, modify, compile, and create derivative * works of the software solely for use with RTI Connext DDS. Licensee may * redistribute copies of the software provided that all such copies are subject * to this license. The software is provided "as is", with no warranty of any * type, including any warranty for fitness for any purpose. RTI is under no * obligation to maintain or support the software. RTI shall not be liable for * any incidental or consequential damages arising out of the use or inability * to use the software. */ #ifndef APPLICATION_H #define APPLICATION_H #include <iostream> #include <csignal> #include <climits> namespace application { // Catch control-C and tell application to shut down bool shutdown_requested = false; inline void stop_handler(int) { shutdown_requested = true; std::cout << "preparing to shut down..." << std::endl; } inline void setup_signal_handlers() { signal(SIGINT, stop_handler); signal(SIGTERM, stop_handler); } enum ParseReturn { PARSE_RETURN_OK, PARSE_RETURN_FAILURE, PARSE_RETURN_EXIT }; struct ApplicationArguments { ParseReturn parse_result; unsigned int domain_id; unsigned int sample_count; NDDS_Config_LogVerbosity verbosity; }; // Parses application arguments for example. Returns whether to exit. inline void parse_arguments( ApplicationArguments& arguments, int argc, char *argv[]) { int arg_processing = 1; bool show_usage = false; arguments.domain_id = 0; arguments.sample_count = INT_MAX; arguments.verbosity = NDDS_CONFIG_LOG_VERBOSITY_ERROR; arguments.parse_result = PARSE_RETURN_OK; while (arg_processing < argc) { if ((argc > arg_processing + 1) && (strcmp(argv[arg_processing], "-d") == 0 || strcmp(argv[arg_processing], "--domain") == 0)) { arguments.domain_id = atoi(argv[arg_processing + 1]); arg_processing += 2; } else if ((argc > arg_processing + 1) && (strcmp(argv[arg_processing], "-s") == 0 || strcmp(argv[arg_processing], "--sample-count") == 0)) { arguments.sample_count = atoi(argv[arg_processing + 1]); arg_processing += 2; } else if ((argc > arg_processing + 1) && (strcmp(argv[arg_processing], "-v") == 0 || strcmp(argv[arg_processing], "--verbosity") == 0)) { arguments.verbosity = (NDDS_Config_LogVerbosity) atoi(argv[arg_processing + 1]); arg_processing += 2; } else if (strcmp(argv[arg_processing], "-h") == 0 || strcmp(argv[arg_processing], "--help") == 0) { std::cout << "Example application." << std::endl; show_usage = true; arguments.parse_result = PARSE_RETURN_EXIT; break; } else { std::cout << "Bad parameter." << std::endl; show_usage = true; arguments.parse_result = PARSE_RETURN_FAILURE; break; } } if (show_usage) { std::cout << "Usage:\n"\ " -d, --domain <int> Domain ID this application will\n" \ " subscribe in. \n" " Default: 0\n"\ " -s, --sample_count <int> Number of samples to receive before\n"\ " cleanly shutting down. \n" " Default: infinite\n" " -v, --verbosity <int> How much debugging output to show.\n"\ " Range: 0-5 \n" " Default: 0" << std::endl; } } } // namespace application #endif // APPLICATION_H
h
rticonnextdds-examples
data/projects/rticonnextdds-examples/connext_dds/printing_qos/c++98/printing_subscriber.cxx
/* * (c) Copyright, Real-Time Innovations, 2021. All rights reserved. * RTI grants Licensee a license to use, modify, compile, and create derivative * works of the software solely for use with RTI Connext DDS. Licensee may * redistribute copies of the software provided that all such copies are subject * to this license. The software is provided "as is", with no warranty of any * type, including any warranty for fitness for any purpose. RTI is under no * obligation to maintain or support the software. RTI shall not be liable for * any incidental or consequential damages arising out of the use or inability * to use the software. */ #include <iostream> #include <stdio.h> #include <stdlib.h> #include "printing.h" #include "printingSupport.h" #include "ndds/ndds_cpp.h" #include "application.h" using namespace application; static int shutdown_participant( DDSDomainParticipant *participant, const char *shutdown_message, int status); // Process data. Returns number of samples processed. unsigned int process_data(printingDataReader *typed_reader) { printingSeq data_seq; // Sequence of received data DDS_SampleInfoSeq info_seq; // Metadata associated with samples in data_seq unsigned int samples_read = 0; // Take available data from DataReader's queue typed_reader->take( data_seq, info_seq, DDS_LENGTH_UNLIMITED, DDS_ANY_SAMPLE_STATE, DDS_ANY_VIEW_STATE, DDS_ANY_INSTANCE_STATE); // Iterate over all available data for (int i = 0; i < data_seq.length(); ++i) { // Check if a sample is an instance lifecycle event if (info_seq[i].valid_data) { // Print data std::cout << "Received data" << std::endl; printingTypeSupport::print_data(&data_seq[i]); samples_read++; } else { // This is an instance lifecycle event with no data payload. std::cout << "Received instance state notification" << std::endl; } } // Data loaned from Connext for performance. Return loan when done. DDS_ReturnCode_t retcode = typed_reader->return_loan(data_seq, info_seq); if (retcode != DDS_RETCODE_OK) { std::cerr << "return loan error " << retcode << std::endl; } return samples_read; } int run_subscriber_application( unsigned int domain_id, unsigned int sample_count) { // Start communicating in a domain, usually one participant per application DDSDomainParticipant *participant = DDSTheParticipantFactory->create_participant( domain_id, DDS_PARTICIPANT_QOS_DEFAULT, NULL, // listener DDS_STATUS_MASK_NONE); if (participant == NULL) { return shutdown_participant( participant, "create_participant error", EXIT_FAILURE); } DDS_DomainParticipantQos participant_qos; DDS_ReturnCode_t retcode = participant->get_qos(participant_qos); if (retcode != DDS_RETCODE_OK) { return shutdown_participant(participant, "get_qos error", EXIT_FAILURE); } char *str = NULL; DDS_UnsignedLong strSize = 0; DDS_QosPrintFormat printFormat = DDS_QosPrintFormat_INITIALIZER; /* * First, we pass NULL for the str argument. This will cause the API to * update the strSize argument to contain the required size of the str * buffer. We then allocate a buffer of that size and obtain the QoS string. * The DDS_DomainParticipantQos_to_string_w_params API prints all the QoS * values for the DomainParticipantQos object. */ participant_qos.to_string(str, strSize, DDS_QOS_PRINT_ALL, printFormat); str = DDS_String_alloc(strSize); if (str == NULL) { return shutdown_participant( participant, "String allocation error", EXIT_FAILURE); } participant_qos.to_string(str, strSize, DDS_QOS_PRINT_ALL, printFormat); std::cout << str << std::endl; DDS_String_free(str); str = NULL; // 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); } DDS_SubscriberQos subscriber_qos; retcode = subscriber->get_qos(subscriber_qos); if (retcode != DDS_RETCODE_OK) { return shutdown_participant(participant, "get_qos error", EXIT_FAILURE); } /* * First, we pass NULL for the str argument. This will cause the API to * update the strSize argument to contain the required size of the str * buffer. We then allocate a buffer of that size and obtain the QoS string. * The DDS_SubscriberQos_to_string_w_params API prints all the QoS values * for the SubscriberQos object. */ subscriber_qos.to_string(str, strSize, printFormat); str = DDS_String_alloc(strSize); if (str == NULL) { return shutdown_participant( participant, "String allocation error", EXIT_FAILURE); } subscriber_qos.to_string(str, strSize, printFormat); std::cout << str << std::endl; DDS_String_free(str); str = NULL; // Register the datatype to use when creating the Topic const char *type_name = printingTypeSupport::get_type_name(); retcode = printingTypeSupport::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 printing", 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 printing" Topic DDSDataReader *untyped_reader = subscriber->create_datareader( topic, DDS_DATAREADER_QOS_DEFAULT, NULL, DDS_STATUS_MASK_NONE); if (untyped_reader == NULL) { return shutdown_participant( participant, "create_datareader error", EXIT_FAILURE); } DDS_DataReaderQos reader_qos; retcode = untyped_reader->get_qos(reader_qos); if (retcode != DDS_RETCODE_OK) { return shutdown_participant(participant, "get_qos error", EXIT_FAILURE); } reader_qos.print(); // Narrow casts from a untyped DataReader to a reader of your type printingDataReader *typed_reader = printingDataReader::narrow(untyped_reader); if (typed_reader == NULL) { return shutdown_participant( participant, "DataReader narrow error", EXIT_FAILURE); } // Create ReadCondition that triggers when unread data in reader's queue DDSReadCondition *read_condition = typed_reader->create_readcondition( DDS_NOT_READ_SAMPLE_STATE, DDS_ANY_VIEW_STATE, DDS_ANY_INSTANCE_STATE); if (read_condition == NULL) { return shutdown_participant( participant, "create_readcondition error", EXIT_FAILURE); } // WaitSet will be woken when the attached condition is triggered DDSWaitSet waitset; retcode = waitset.attach_condition(read_condition); if (retcode != DDS_RETCODE_OK) { return shutdown_participant( participant, "attach_condition error", EXIT_FAILURE); } // Main loop. Wait for data to arrive, and process when it arrives unsigned int samples_read = 0; while (!shutdown_requested && samples_read < sample_count) { DDSConditionSeq active_conditions_seq; // Wait for data and report if it does not arrive in 1 second DDS_Duration_t wait_timeout = { 1, 0 }; retcode = waitset.wait(active_conditions_seq, wait_timeout); if (retcode == DDS_RETCODE_OK) { // If the read condition is triggered, process data samples_read += process_data(typed_reader); } else { if (retcode == DDS_RETCODE_TIMEOUT) { std::cout << "No data after 1 second" << std::endl; } } } // Cleanup return shutdown_participant(participant, "Shutting down", 0); } // Delete all entities static int shutdown_participant( DDSDomainParticipant *participant, const char *shutdown_message, int status) { DDS_ReturnCode_t retcode; std::cout << shutdown_message << std::endl; if (participant != NULL) { // Cleanup everything created by this Participant retcode = participant->delete_contained_entities(); if (retcode != DDS_RETCODE_OK) { std::cerr << "delete_contained_entities error" << retcode << std::endl; status = EXIT_FAILURE; } retcode = DDSTheParticipantFactory->delete_participant(participant); if (retcode != DDS_RETCODE_OK) { std::cerr << "delete_participant error" << retcode << std::endl; status = EXIT_FAILURE; } } return status; } int main(int argc, char *argv[]) { // Parse arguments and handle control-C ApplicationArguments arguments; parse_arguments(arguments, argc, argv); if (arguments.parse_result == PARSE_RETURN_EXIT) { return EXIT_SUCCESS; } else if (arguments.parse_result == PARSE_RETURN_FAILURE) { return EXIT_FAILURE; } setup_signal_handlers(); // Sets Connext verbosity to help debugging NDDSConfigLogger::get_instance()->set_verbosity(arguments.verbosity); int status = run_subscriber_application( arguments.domain_id, arguments.sample_count); // Releases the memory used by the participant factory. Optional at // application exit DDS_ReturnCode_t retcode = DDSDomainParticipantFactory::finalize_instance(); if (retcode != DDS_RETCODE_OK) { std::cerr << "finalize_instance error" << retcode << std::endl; status = EXIT_FAILURE; } return status; }
cxx
rticonnextdds-examples
data/projects/rticonnextdds-examples/connext_dds/printing_qos/c++98/printing_publisher.cxx
/* * (c) Copyright, Real-Time Innovations, 2021. All rights reserved. * RTI grants Licensee a license to use, modify, compile, and create derivative * works of the software solely for use with RTI Connext DDS. Licensee may * redistribute copies of the software provided that all such copies are subject * to this license. The software is provided "as is", with no warranty of any * type, including any warranty for fitness for any purpose. RTI is under no * obligation to maintain or support the software. RTI shall not be liable for * any incidental or consequential damages arising out of the use or inability * to use the software. */ #include <iostream> #include <stdio.h> #include <stdlib.h> #include "printing.h" #include "printingSupport.h" #include "ndds/ndds_cpp.h" #include "application.h" using namespace application; static int shutdown_participant( DDSDomainParticipant *participant, const char *shutdown_message, int status); int run_publisher_application(unsigned int domain_id, unsigned int sample_count) { // Start communicating in a domain, usually one participant per application DDSDomainParticipant *participant = DDSTheParticipantFactory->create_participant( domain_id, DDS_PARTICIPANT_QOS_DEFAULT, NULL, // listener DDS_STATUS_MASK_NONE); if (participant == NULL) { return shutdown_participant( participant, "create_participant error", EXIT_FAILURE); } // A Publisher allows an application to create one or more DataWriters DDSPublisher *publisher = participant->create_publisher( DDS_PUBLISHER_QOS_DEFAULT, NULL, // listener DDS_STATUS_MASK_NONE); if (publisher == NULL) { return shutdown_participant( participant, "create_publisher error", EXIT_FAILURE); } DDS_PublisherQos publisher_qos; DDS_ReturnCode_t retcode = publisher->get_qos(publisher_qos); if (retcode != DDS_RETCODE_OK) { return shutdown_participant(participant, "get_qos error", EXIT_FAILURE); } char *str = NULL; DDS_UnsignedLong strSize = 0; DDS_QosPrintFormat printFormat = DDS_QosPrintFormat_INITIALIZER; /* * First, we pass NULL for the str argument. This will cause the API to * update the strSize argument to contain the required size of the str * buffer. We then allocate a buffer of that size and obtain the QoS string. * The DDS_PublisherQos_to_string_w_params API prints all the QoS values for * the PublisherQos object. */ publisher_qos.to_string(str, strSize, DDS_QOS_PRINT_ALL, printFormat); str = DDS_String_alloc(strSize); if (str == NULL) { return shutdown_participant( participant, "String allocation error", EXIT_FAILURE); } publisher_qos.to_string(str, strSize, DDS_QOS_PRINT_ALL, printFormat); std::cout << str << std::endl; DDS_String_free(str); str = NULL; // Register the datatype to use when creating the Topic const char *type_name = printingTypeSupport::get_type_name(); retcode = printingTypeSupport::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 printing", type_name, DDS_TOPIC_QOS_DEFAULT, NULL, // listener DDS_STATUS_MASK_NONE); if (topic == NULL) { return shutdown_participant( participant, "create_topic error", EXIT_FAILURE); } DDS_TopicQos topic_qos; retcode = topic->get_qos(topic_qos); if (retcode != DDS_RETCODE_OK) { return shutdown_participant(participant, "get_qos error", EXIT_FAILURE); } /* * First, we pass NULL for the str argument. This will cause the API to * update the strSize argument to contain the required size of the str * buffer. We then allocate a buffer of that size and obtain the QoS string. * The DDS_TopicQos_to_string_w_params API prints all the QoS values for * the TopicQos object. */ topic_qos.to_string(str, strSize, printFormat); str = DDS_String_alloc(strSize); if (str == NULL) { return shutdown_participant( participant, "String allocation error", EXIT_FAILURE); } topic_qos.to_string(str, strSize, printFormat); std::cout << str << std::endl; DDS_String_free(str); str = NULL; // This DataWriter writes data on "Example printing" 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); } DDS_DataWriterQos writer_qos; retcode = untyped_writer->get_qos(writer_qos); if (retcode != DDS_RETCODE_OK) { return shutdown_participant(participant, "get_qos error", EXIT_FAILURE); } writer_qos.print(); // Narrow casts from an untyped DataWriter to a writer of your type printingDataWriter *typed_writer = printingDataWriter::narrow(untyped_writer); if (typed_writer == NULL) { return shutdown_participant( participant, "DataWriter narrow error", EXIT_FAILURE); } // Create data for writing, allocating all members printing *data = printingTypeSupport::create_data(); if (data == NULL) { return shutdown_participant( participant, "printingTypeSupport::create_data error", EXIT_FAILURE); } // Main loop, write data for (unsigned int samples_written = 0; !shutdown_requested && samples_written < sample_count; ++samples_written) { // Modify the data to be written here data->x = static_cast<DDS_Short>(samples_written); std::cout << "Writing printing, count " << samples_written << std::endl; retcode = typed_writer->write(*data, DDS_HANDLE_NIL); if (retcode != DDS_RETCODE_OK) { std::cerr << "write error " << retcode << std::endl; } // Send once every second DDS_Duration_t send_period = { 1, 0 }; NDDSUtility::sleep(send_period); } // Delete previously allocated printing, including all contained elements retcode = printingTypeSupport::delete_data(data); if (retcode != DDS_RETCODE_OK) { std::cerr << "printingTypeSupport::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/printing_qos/c++98/application.h
/* * (c) Copyright, Real-Time Innovations, 2021. All rights reserved. * RTI grants Licensee a license to use, modify, compile, and create derivative * works of the software solely for use with RTI Connext DDS. Licensee may * redistribute copies of the software provided that all such copies are subject * to this license. The software is provided "as is", with no warranty of any * type, including any warranty for fitness for any purpose. RTI is under no * obligation to maintain or support the software. RTI shall not be liable for * any incidental or consequential damages arising out of the use or inability * to use the software. */ #ifndef APPLICATION_H #define APPLICATION_H #include <iostream> #include <csignal> #include <climits> namespace application { // Catch control-C and tell application to shut down bool shutdown_requested = false; inline void stop_handler(int) { shutdown_requested = true; std::cout << "preparing to shut down..." << std::endl; } inline void setup_signal_handlers() { signal(SIGINT, stop_handler); signal(SIGTERM, stop_handler); } enum ParseReturn { PARSE_RETURN_OK, PARSE_RETURN_FAILURE, PARSE_RETURN_EXIT }; struct ApplicationArguments { ParseReturn parse_result; unsigned int domain_id; unsigned int sample_count; NDDS_Config_LogVerbosity verbosity; }; // Parses application arguments for example. Returns whether to exit. inline void parse_arguments( ApplicationArguments &arguments, int argc, char *argv[]) { int arg_processing = 1; bool show_usage = false; arguments.domain_id = 0; arguments.sample_count = INT_MAX; arguments.verbosity = NDDS_CONFIG_LOG_VERBOSITY_ERROR; arguments.parse_result = PARSE_RETURN_OK; while (arg_processing < argc) { if ((argc > arg_processing + 1) && (strcmp(argv[arg_processing], "-d") == 0 || strcmp(argv[arg_processing], "--domain") == 0)) { arguments.domain_id = atoi(argv[arg_processing + 1]); arg_processing += 2; } else if ( (argc > arg_processing + 1) && (strcmp(argv[arg_processing], "-s") == 0 || strcmp(argv[arg_processing], "--sample-count") == 0)) { arguments.sample_count = atoi(argv[arg_processing + 1]); arg_processing += 2; } else if ( (argc > arg_processing + 1) && (strcmp(argv[arg_processing], "-v") == 0 || strcmp(argv[arg_processing], "--verbosity") == 0)) { arguments.verbosity = (NDDS_Config_LogVerbosity) atoi(argv[arg_processing + 1]); arg_processing += 2; } else if ( strcmp(argv[arg_processing], "-h") == 0 || strcmp(argv[arg_processing], "--help") == 0) { std::cout << "Example application." << std::endl; show_usage = true; arguments.parse_result = PARSE_RETURN_EXIT; break; } else { std::cout << "Bad parameter." << std::endl; show_usage = true; arguments.parse_result = PARSE_RETURN_FAILURE; break; } } if (show_usage) { std::cout << "Usage:\n" " -d, --domain <int> Domain ID this " "application will\n" " subscribe in. \n" " Default: 0\n" " -s, --sample_count <int> Number of samples to " "receive before\n" " cleanly shutting down. \n" " Default: infinite\n" " -v, --verbosity <int> How much debugging output " "to show.\n" " Range: 0-5 \n" " Default: 0" << std::endl; } } } // namespace application #endif // APPLICATION_H
h
rticonnextdds-examples
data/projects/rticonnextdds-examples/connext_dds/printing_qos/c/printing_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. */ /* printing_publisher.c A publication of data of type printing This file is derived from code automatically generated by the rtiddsgen command: rtiddsgen -language C -example <arch> printing.idl Example publication of type printing 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 "printing.h" #include "printingSupport.h" /* Delete all entities */ static int publisher_shutdown( DDS_DomainParticipant *participant, struct DDS_TopicQos *topic_qos, struct DDS_PublisherQos *publisher_qos, struct DDS_DataWriterQos *writer_qos) { 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_TopicQos_finalize(topic_qos); if (retcode != DDS_RETCODE_OK) { fprintf(stderr, "finalize Topic qos error %d\n", retcode); status = -1; } retcode = DDS_PublisherQos_finalize(publisher_qos); if (retcode != DDS_RETCODE_OK) { fprintf(stderr, "finalize Publisher qos error %d\n", retcode); status = -1; } retcode = DDS_DataWriterQos_finalize(writer_qos); if (retcode != DDS_RETCODE_OK) { fprintf(stderr, "finalize Writer qos 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; printingDataWriter *printing_writer = NULL; printing *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}; struct DDS_TopicQos topic_qos = DDS_TopicQos_INITIALIZER; struct DDS_PublisherQos publisher_qos = DDS_PublisherQos_INITIALIZER; struct DDS_DataWriterQos writer_qos = DDS_DataWriterQos_INITIALIZER; char *str = NULL; DDS_UnsignedLong strSize = 0; struct DDS_QosPrintFormat printFormat = DDS_QosPrintFormat_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) { fprintf(stderr, "create_participant error\n"); publisher_shutdown(participant, &topic_qos, &publisher_qos, &writer_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) { fprintf(stderr, "create_publisher error\n"); publisher_shutdown(participant, &topic_qos, &publisher_qos, &writer_qos); return -1; } /* Test DDS_PublisherQos_to_string_w_params */ retcode = DDS_Publisher_get_qos(publisher, &publisher_qos); if (retcode != DDS_RETCODE_OK) { fprintf(stderr, "get publisher qos"); publisher_shutdown(participant, &topic_qos, &publisher_qos, &writer_qos); return -1; } /* * First, we pass NULL for the str argument. This will cause the API to update * the strSize argument to contain the required size of the str buffer. * We then allocate a buffer of that size and obtain the QoS string. * The DDS_PublisherQos_to_string_w_params API prints all the QoS values for * the PublisherQos object. */ retcode = DDS_PublisherQos_to_string_w_params( &publisher_qos, str, &strSize, DDS_PUBLISHER_QOS_PRINT_ALL, &printFormat); if (retcode != DDS_RETCODE_OK) { fprintf(stderr, "publisher qos to string"); publisher_shutdown(participant, &topic_qos, &publisher_qos, &writer_qos); return -1; } str = DDS_String_alloc(strSize); if (str == NULL) { fprintf(stderr, "String allocation"); publisher_shutdown(participant, &topic_qos, &publisher_qos, &writer_qos); return -1; } retcode = DDS_PublisherQos_to_string_w_params( &publisher_qos, str, &strSize, DDS_PUBLISHER_QOS_PRINT_ALL, &printFormat); if (retcode != DDS_RETCODE_OK) { fprintf(stderr, "publisher qos to string"); publisher_shutdown(participant, &topic_qos, &publisher_qos, &writer_qos); DDS_String_free(str); return -1; } printf("%s", str); DDS_String_free(str); str = NULL; /* Register type before creating topic */ type_name = printingTypeSupport_get_type_name(); retcode = printingTypeSupport_register_type( participant, type_name); if (retcode != DDS_RETCODE_OK) { fprintf(stderr, "register_type error %d\n", retcode); publisher_shutdown(participant, &topic_qos, &publisher_qos, &writer_qos); return -1; } /* To customize topic QoS, use the configuration file USER_QOS_PROFILES.xml */ topic = DDS_DomainParticipant_create_topic( participant, "Example printing", type_name, &DDS_TOPIC_QOS_DEFAULT, NULL /* listener */, DDS_STATUS_MASK_NONE); if (topic == NULL) { fprintf(stderr, "create_topic error\n"); publisher_shutdown(participant, &topic_qos, &publisher_qos, &writer_qos); return -1; } /* Test DDS_TopicQos_to_string */ retcode = DDS_Topic_get_qos(topic, &topic_qos); if (retcode != DDS_RETCODE_OK) { fprintf(stderr, "get topic qos"); publisher_shutdown(participant, &topic_qos, &publisher_qos, &writer_qos); return -1; } /* * First, we pass NULL for the str argument. This will cause the API to update * the strSize argument to contain the required size of the str buffer. * We then allocate a buffer of that size and obtain the QoS string. * The DDS_TopicQos_to_string API only prints differences with respect to * the document default values for the TopicQos object. */ retcode = DDS_TopicQos_to_string(&topic_qos, str, &strSize); if (retcode != DDS_RETCODE_OK) { fprintf(stderr, "topic qos to string"); publisher_shutdown(participant, &topic_qos, &publisher_qos, &writer_qos); return -1; } str = DDS_String_alloc(strSize); if (str == NULL) { fprintf(stderr, "String allocation"); publisher_shutdown(participant, &topic_qos, &publisher_qos, &writer_qos); return -1; } retcode = DDS_TopicQos_to_string(&topic_qos, str, &strSize); if (retcode != DDS_RETCODE_OK) { fprintf(stderr, "topic qos to string"); publisher_shutdown(participant, &topic_qos, &publisher_qos, &writer_qos); DDS_String_free(str); return -1; } printf("%s", str); DDS_String_free(str); str = NULL; /* 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, &topic_qos, &publisher_qos, &writer_qos); return -1; } /* Test DDS_DataWriterQos_print */ retcode = DDS_DataWriter_get_qos(writer, &writer_qos); if (retcode != DDS_RETCODE_OK) { fprintf(stderr, "get writer qos"); publisher_shutdown(participant, &topic_qos, &publisher_qos, &writer_qos); return -1; } retcode = DDS_DataWriterQos_print(&writer_qos); if (retcode != DDS_RETCODE_OK) { fprintf(stderr, "print writer qos"); publisher_shutdown(participant, &topic_qos, &publisher_qos, &writer_qos); return -1; } printing_writer = printingDataWriter_narrow(writer); if (printing_writer == NULL) { fprintf(stderr, "DataWriter narrow error\n"); publisher_shutdown(participant, &topic_qos, &publisher_qos, &writer_qos); return -1; } /* Create data sample for writing */ instance = printingTypeSupport_create_data_ex(DDS_BOOLEAN_TRUE); if (instance == NULL) { fprintf(stderr, "printingTypeSupport_create_data error\n"); publisher_shutdown(participant, &topic_qos, &publisher_qos, &writer_qos); return -1; } /* For a data type that has a key, if the same instance is going to be written multiple times, initialize the key here and register the keyed instance prior to writing */ /* instance_handle = printingDataWriter_register_instance( printing_writer, instance); */ /* Main loop */ for (count=0; (sample_count == 0) || (count < sample_count); ++count) { printf("Writing printing, count %d\n", count); /* Modify the data to be written here */ /* Write data */ retcode = printingDataWriter_write( printing_writer, instance, &instance_handle); if (retcode != DDS_RETCODE_OK) { fprintf(stderr, "write error %d\n", retcode); } NDDS_Utility_sleep(&send_period); } /* retcode = printingDataWriter_unregister_instance( printing_writer, instance, &instance_handle); if (retcode != DDS_RETCODE_OK) { fprintf(stderr, "unregister instance error %d\n", retcode); } */ /* Delete data sample */ retcode = printingTypeSupport_delete_data_ex(instance, DDS_BOOLEAN_TRUE); if (retcode != DDS_RETCODE_OK) { fprintf(stderr, "printingTypeSupport_delete_data error %d\n", retcode); } /* Cleanup and delete delete all entities */ return publisher_shutdown(participant, &topic_qos, &publisher_qos, &writer_qos); } int main(int argc, char *argv[]) { int domain_id = 0; int sample_count = 0; /* infinite loop */ if (argc >= 2) { domain_id = atoi(argv[1]); } if (argc >= 3) { sample_count = atoi(argv[2]); } /* Uncomment this to turn on additional printing NDDS_Config_Logger_set_verbosity_by_category( NDDS_Config_Logger_get_instance(), NDDS_CONFIG_LOG_CATEGORY_API, NDDS_CONFIG_LOG_VERBOSITY_STATUS_ALL); */ return publisher_main(domain_id, sample_count); }
c
rticonnextdds-examples
data/projects/rticonnextdds-examples/connext_dds/printing_qos/c/printing_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. */ /* printing_subscriber.c A subscription example This file is derived from code automatically generated by the rtiddsgen command: rtiddsgen -language C -example <arch> printing.idl Example subscription of type printing automatically generated by 'rtiddsgen'. To test it, follow these steps: (1) Compile this file and the example publication. (2) Start the subscription on the same domain used for RTI Connext (3) Start the publication on the same domain used for RTI Connext (4) [Optional] Specify the list of discovery initial peers and multicast receive addresses via an environment variable or a file (in the current working directory) called NDDS_DISCOVERY_PEERS. You can run any number of publisher and subscriber programs, and can add and remove them dynamically from the domain. */ #include <stdio.h> #include <stdlib.h> #include "ndds/ndds_c.h" #include "printing.h" #include "printingSupport.h" void printingListener_on_requested_deadline_missed( void* listener_data, DDS_DataReader* reader, const struct DDS_RequestedDeadlineMissedStatus *status) { } void printingListener_on_requested_incompatible_qos( void* listener_data, DDS_DataReader* reader, const struct DDS_RequestedIncompatibleQosStatus *status) { } void printingListener_on_sample_rejected( void* listener_data, DDS_DataReader* reader, const struct DDS_SampleRejectedStatus *status) { } void printingListener_on_liveliness_changed( void* listener_data, DDS_DataReader* reader, const struct DDS_LivelinessChangedStatus *status) { } void printingListener_on_sample_lost( void* listener_data, DDS_DataReader* reader, const struct DDS_SampleLostStatus *status) { } void printingListener_on_subscription_matched( void* listener_data, DDS_DataReader* reader, const struct DDS_SubscriptionMatchedStatus *status) { } void printingListener_on_data_available( void* listener_data, DDS_DataReader* reader) { printingDataReader *printing_reader = NULL; struct printingSeq data_seq = DDS_SEQUENCE_INITIALIZER; struct DDS_SampleInfoSeq info_seq = DDS_SEQUENCE_INITIALIZER; DDS_ReturnCode_t retcode; int i; printing_reader = printingDataReader_narrow(reader); if (printing_reader == NULL) { fprintf(stderr, "DataReader narrow error\n"); return; } retcode = printingDataReader_take( printing_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 < printingSeq_get_length(&data_seq); ++i) { if (DDS_SampleInfoSeq_get_reference(&info_seq, i)->valid_data) { printf("Received data\n"); printingTypeSupport_print_data( printingSeq_get_reference(&data_seq, i)); } } retcode = printingDataReader_return_loan( printing_reader, &data_seq, &info_seq); if (retcode != DDS_RETCODE_OK) { fprintf(stderr, "return loan error %d\n", retcode); } } /* Delete all entities */ static int subscriber_shutdown( DDS_DomainParticipant *participant, struct DDS_DomainParticipantQos *participant_qos, struct DDS_SubscriberQos *subscriber_qos, struct DDS_DataReaderQos *reader_qos) { 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_DomainParticipantQos_finalize(participant_qos); if (retcode != DDS_RETCODE_OK) { fprintf(stderr, "finalize Participant qos error %d\n", retcode); status = -1; } retcode = DDS_SubscriberQos_finalize(subscriber_qos); if (retcode != DDS_RETCODE_OK) { fprintf(stderr, "finalize Subscriber qos error %d\n", retcode); status = -1; } retcode = DDS_DataReaderQos_finalize(reader_qos); if (retcode != DDS_RETCODE_OK) { fprintf(stderr, "finalize Reader qos error %d\n", retcode); status = -1; } /* RTI Data Distribution Service provides the finalize_instance() method on domain participant factory for users who want to release memory used by the participant factory. Uncomment the following block of code for clean destruction of the singleton. */ /* retcode = DDS_DomainParticipantFactory_finalize_instance(); if (retcode != DDS_RETCODE_OK) { fprintf(stderr, "finalize_instance error %d\n", retcode); status = -1; } */ return status; } 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_DomainParticipantQos participant_qos = DDS_DomainParticipantQos_INITIALIZER; struct DDS_SubscriberQos subscriber_qos = DDS_SubscriberQos_INITIALIZER; struct DDS_DataReaderQos reader_qos = DDS_DataReaderQos_INITIALIZER; char *str = NULL; DDS_UnsignedLong strSize = 0; struct DDS_QosPrintFormat printFormat = DDS_QosPrintFormat_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) { fprintf(stderr, "create_participant error\n"); subscriber_shutdown( participant, &participant_qos, &subscriber_qos, &reader_qos); return -1; } /* Test DDS_DomainParticipantQos_to_string */ retcode = DDS_DomainParticipant_get_qos(participant, &participant_qos); if (retcode != DDS_RETCODE_OK) { fprintf(stderr, "get participant qos"); subscriber_shutdown( participant, &participant_qos, &subscriber_qos, &reader_qos); return -1; } /* * First, we pass NULL for the str argument. This will cause the API to update * the strSize argument to contain the required size of the str buffer. * We then allocate a buffer of that size and obtain the QoS string. * The DDS_DomainParticipantQos_to_string API only prints differences with * respect to the document default values for the DomainParticipantQos object. */ retcode = DDS_DomainParticipantQos_to_string( &participant_qos, str, &strSize); if (retcode != DDS_RETCODE_OK) { fprintf(stderr, "participant qos to string"); subscriber_shutdown( participant, &participant_qos, &subscriber_qos, &reader_qos); return -1; } str = DDS_String_alloc(strSize); if (str == NULL) { fprintf(stderr, "String allocation"); subscriber_shutdown( participant, &participant_qos, &subscriber_qos, &reader_qos); return -1; } retcode = DDS_DomainParticipantQos_to_string( &participant_qos, str, &strSize); if (retcode != DDS_RETCODE_OK) { fprintf(stderr, "participant qos to string"); subscriber_shutdown( participant, &participant_qos, &subscriber_qos, &reader_qos); DDS_String_free(str); return -1; } printf("%s", str); DDS_String_free(str); str = NULL; /* To customize subscriber QoS, use the configuration file USER_QOS_PROFILES.xml */ subscriber = DDS_DomainParticipant_create_subscriber( participant, &DDS_SUBSCRIBER_QOS_DEFAULT, NULL /* listener */, DDS_STATUS_MASK_NONE); if (subscriber == NULL) { fprintf(stderr, "create_subscriber error\n"); subscriber_shutdown( participant, &participant_qos, &subscriber_qos, &reader_qos); return -1; } /* Test DDS_SubscriberQos_to_string_w_params */ retcode = DDS_Subscriber_get_qos(subscriber, &subscriber_qos); if (retcode != DDS_RETCODE_OK) { fprintf(stderr, "get subscriber qos"); subscriber_shutdown( participant, &participant_qos, &subscriber_qos, &reader_qos); return -1; } /* * First, we pass NULL for the str argument. This will cause the API to update * the strSize argument to contain the required size of the str buffer. * We then allocate a buffer of that size and obtain the QoS string. * The DDS_SubscriberQos_to_string_w_params API prints all the QoS values for * the SubscriberQos object. */ retcode = DDS_SubscriberQos_to_string_w_params( &subscriber_qos, str, &strSize, DDS_SUBSCRIBER_QOS_PRINT_ALL, &printFormat); if (retcode != DDS_RETCODE_OK) { fprintf(stderr, "subscriber qos to string"); subscriber_shutdown( participant, &participant_qos, &subscriber_qos, &reader_qos); return -1; } str = DDS_String_alloc(strSize); if (str == NULL) { fprintf(stderr, "String allocation"); subscriber_shutdown( participant, &participant_qos, &subscriber_qos, &reader_qos); return -1; } retcode = DDS_SubscriberQos_to_string_w_params( &subscriber_qos, str, &strSize, DDS_SUBSCRIBER_QOS_PRINT_ALL, &printFormat); if (retcode != DDS_RETCODE_OK) { fprintf(stderr, "subscriber qos to string"); subscriber_shutdown( participant, &participant_qos, &subscriber_qos, &reader_qos); DDS_String_free(str); return -1; } printf("%s", str); DDS_String_free(str); str = NULL; /* Register the type before creating the topic */ type_name = printingTypeSupport_get_type_name(); retcode = printingTypeSupport_register_type(participant, type_name); if (retcode != DDS_RETCODE_OK) { fprintf(stderr, "register_type error %d\n", retcode); subscriber_shutdown( participant, &participant_qos, &subscriber_qos, &reader_qos); return -1; } /* To customize topic QoS, use the configuration file USER_QOS_PROFILES.xml */ topic = DDS_DomainParticipant_create_topic( participant, "Example printing", type_name, &DDS_TOPIC_QOS_DEFAULT, NULL /* listener */, DDS_STATUS_MASK_NONE); if (topic == NULL) { fprintf(stderr, "create_topic error\n"); subscriber_shutdown( participant, &participant_qos, &subscriber_qos, &reader_qos); return -1; } /* Set up a data reader listener */ reader_listener.on_requested_deadline_missed = printingListener_on_requested_deadline_missed; reader_listener.on_requested_incompatible_qos = printingListener_on_requested_incompatible_qos; reader_listener.on_sample_rejected = printingListener_on_sample_rejected; reader_listener.on_liveliness_changed = printingListener_on_liveliness_changed; reader_listener.on_sample_lost = printingListener_on_sample_lost; reader_listener.on_subscription_matched = printingListener_on_subscription_matched; reader_listener.on_data_available = printingListener_on_data_available; /* To customize data reader QoS, use the configuration file USER_QOS_PROFILES.xml */ reader = DDS_Subscriber_create_datareader( subscriber, DDS_Topic_as_topicdescription(topic), &DDS_DATAREADER_QOS_DEFAULT, &reader_listener, DDS_STATUS_MASK_ALL); if (reader == NULL) { fprintf(stderr, "create_datareader error\n"); subscriber_shutdown( participant, &participant_qos, &subscriber_qos, &reader_qos); return -1; } /* Test DDS_DataReaderQos_print */ retcode = DDS_DataReader_get_qos(reader, &reader_qos); if (retcode != DDS_RETCODE_OK) { fprintf(stderr, "get reader qos"); subscriber_shutdown( participant, &participant_qos, &subscriber_qos, &reader_qos); return -1; } retcode = DDS_DataReaderQos_print(&reader_qos); if (retcode != DDS_RETCODE_OK) { fprintf(stderr, "print reader qos"); subscriber_shutdown( participant, &participant_qos, &subscriber_qos, &reader_qos); return -1; } /* Main loop */ for (count=0; (sample_count == 0) || (count < sample_count); ++count) { printf("printing subscriber sleeping for %d sec...\n", poll_period.sec); NDDS_Utility_sleep(&poll_period); } /* Cleanup and delete all entities */ return subscriber_shutdown( participant, &participant_qos, &subscriber_qos, &reader_qos); } int main(int argc, char *argv[]) { int domain_id = 0; int sample_count = 0; /* infinite loop */ if (argc >= 2) { domain_id = atoi(argv[1]); } if (argc >= 3) { sample_count = atoi(argv[2]); } /* Uncomment this to turn on additional printing NDDS_Config_Logger_set_verbosity_by_category( NDDS_Config_Logger_get_instance(), NDDS_CONFIG_LOG_CATEGORY_API, NDDS_CONFIG_LOG_VERBOSITY_STATUS_ALL); */ return subscriber_main(domain_id, sample_count); }
c
rticonnextdds-examples
data/projects/rticonnextdds-examples/connext_dds/printing_qos/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/printing_qos/c++11/printing_subscriber.cxx
/* * (c) Copyright, Real-Time Innovations, 2021. All rights reserved. * RTI grants Licensee a license to use, modify, compile, and create derivative * works of the software solely for use with RTI Connext DDS. Licensee may * redistribute copies of the software provided that all such copies are subject * to this license. The software is provided "as is", with no warranty of any * type, including any warranty for fitness for any purpose. RTI is under no * obligation to maintain or support the software. RTI shall not be liable for * any incidental or consequential damages arising out of the use or inability * to use the software. */ #include <algorithm> #include <iostream> #include <dds/sub/ddssub.hpp> #include <dds/core/ddscore.hpp> #include <rti/config/Logger.hpp> // for logging // alternatively, to include all the standard APIs: // <dds/dds.hpp> // or to include both the standard APIs and extensions: // <rti/rti.hpp> // // For more information about the headers and namespaces, see: // https://community.rti.com/static/documentation/connext-dds/6.1.0/doc/api/connext_dds/api_cpp2/group__DDSNamespaceModule.html // For information on how to use extensions, see: // https://community.rti.com/static/documentation/connext-dds/6.1.0/doc/api/connext_dds/api_cpp2/group__DDSCpp2Conventions.html #include "printing.hpp" #include "application.hpp" // for command line parsing and ctrl-c int process_data(dds::sub::DataReader<printing> reader) { // Take all samples int count = 0; dds::sub::LoanedSamples<printing> samples = reader.take(); for (const auto& sample : samples) { if (sample.info().valid()) { count++; std::cout << sample.data() << std::endl; } else { std::cout << "Instance state changed to " << sample.info().state().instance_state() << std::endl; } } return count; } // The LoanedSamples destructor returns the loan void run_subscriber_application(unsigned int domain_id, unsigned int sample_count) { // DDS objects behave like shared pointers or value types // (see https://community.rti.com/static/documentation/connext-dds/6.1.0/doc/api/connext_dds/api_cpp2/group__DDSCpp2Conventions.html) // Start communicating in a domain, usually one participant per application dds::domain::DomainParticipant participant(domain_id); rti::core::QosPrintFormat format; dds::domain::qos::DomainParticipantQos participant_qos = participant.qos(); std::cout << to_string(participant_qos, rti::core::qos_print_all, format) << std::endl; // Create a Topic with a name and a datatype dds::topic::Topic<printing> topic(participant, "Example printing"); // Create a Subscriber and DataReader with default Qos dds::sub::Subscriber subscriber(participant); dds::sub::qos::SubscriberQos subscriber_qos = subscriber.qos(); std::cout << to_string(subscriber_qos, format) << std::endl; dds::sub::DataReader<printing> reader(subscriber, topic); dds::sub::qos::DataReaderQos reader_qos = reader.qos(); std::cout << to_string(reader_qos, format) << std::endl; // 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; while (!application::shutdown_requested && samples_read < sample_count) { std::cout << "printing 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/printing_qos/c++11/printing_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 "printing.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<printing> topic(participant, "Example printing"); dds::topic::qos::TopicQos topic_qos = topic.qos(); std::string str; rti::core::QosPrintFormat format; std::cout << to_string(topic_qos, format) << std::endl; // Create a Publisher dds::pub::Publisher publisher(participant); dds::pub::qos::PublisherQos publisher_qos = publisher.qos(); std::cout << to_string(publisher_qos, rti::core::qos_print_all, format) << std::endl; // Create a DataWriter with default QoS dds::pub::DataWriter<printing> writer(publisher, topic); dds::pub::qos::DataWriterQos writer_qos = writer.qos(); std::cout << to_string(writer_qos) << std::endl; printing data; for (unsigned int samples_written = 0; !application::shutdown_requested && samples_written < sample_count; samples_written++) { // Modify the data to be written here data.x(static_cast<int16_t>(samples_written)); std::cout << "Writing printing, count " << samples_written << std::endl; writer.write(data); // Send once every second rti::util::sleep(dds::core::Duration(1)); } } int main(int argc, char *argv[]) { using namespace application; // Parse arguments and handle control-C auto arguments = parse_arguments(argc, argv); if (arguments.parse_result == ParseReturn::exit) { return EXIT_SUCCESS; } else if (arguments.parse_result == ParseReturn::failure) { return EXIT_FAILURE; } setup_signal_handlers(); // Sets Connext verbosity to help debugging rti::config::Logger::instance().verbosity(arguments.verbosity); try { run_publisher_application(arguments.domain_id, arguments.sample_count); } catch (const std::exception& ex) { // This will catch DDS exceptions std::cerr << "Exception in run_publisher_application(): " << ex.what() << std::endl; return EXIT_FAILURE; } // Releases the memory used by the participant factory. Optional at // application exit dds::domain::DomainParticipant::finalize_participant_factory(); return EXIT_SUCCESS; }
cxx
rticonnextdds-examples
data/projects/rticonnextdds-examples/connext_dds/builtin_topics/c++/msg_publisher.cxx
/******************************************************************************* (c) 2005-2014 Copyright, Real-Time Innovations, Inc. All rights reserved. RTI grants Licensee a license to use, modify, compile, and create derivative works of the Software. Licensee has the right to distribute object form only for use with RTI products. The Software is provided "as is", with no warranty of any type, including any warranty for fitness for any purpose. RTI is under no obligation to maintain or support the Software. RTI shall not be liable for any incidental or consequential damages arising out of the use or inability to use the software. ******************************************************************************/ /* msg_publisher.cxx A publication of data of type msg This file is derived from code automatically generated by the rtiddsgen command: rtiddsgen -language C++ -example <arch> msg.idl Example publication of type msg automatically generated by 'rtiddsgen'. To test them follow these steps: (1) Compile this file and the example subscription. (2) Start the subscription on the same domain used for RTI Data Distribution with the command objs/<arch>/msg_subscriber <domain_id> <sample_count> (3) Start the publication on the same domain used for RTI Data Distribution with the command objs/<arch>/msg_publisher <domain_id> <sample_count> (4) [Optional] Specify the list of discovery initial peers and multicast receive addresses via an environment variable or a file (in the current working directory) called NDDS_DISCOVERY_PEERS. You can run any number of publishers and subscribers programs, and can add and remove them dynamically from the domain. Example: To run the example application on domain <domain_id>: On Unix: objs/<arch>/msg_publisher <domain_id> objs/<arch>/msg_subscriber <domain_id> On Windows: objs\<arch>\msg_publisher <domain_id> objs\<arch>\msg_subscriber <domain_id> modification history ------------ ------- * Add code to store keys of authorized participants * Define listeners for builtin topics, which get called when we find a new participant or reader. * Create disabled participant to ensure our listeners are installed before anything is processed * Install listeners * Uncommented the code that authorized a subscriber that belonged to an authorized participant * Changed ih to be an array of 6 ints instead of 4. An instance handle is the size of 6 ints. */ #include "msg.h" #include "msgSupport.h" #include "ndds/ndds_cpp.h" #include <stdio.h> #include <stdlib.h> #include <string.h> /* Authorization string. */ const char *auth = "password"; /* The builtin subscriber sets participant_qos.user_data and so we set up listeners for the builtin DataReaders to access these fields. */ class BuiltinParticipantListener : public DDSDataReaderListener { public: virtual void on_data_available(DDSDataReader *reader); }; /* This gets called when a participant has been discovered */ void BuiltinParticipantListener::on_data_available(DDSDataReader *reader) { DDSParticipantBuiltinTopicDataDataReader *builtin_reader = (DDSParticipantBuiltinTopicDataDataReader *) reader; DDS_ParticipantBuiltinTopicDataSeq data_seq; DDS_SampleInfoSeq info_seq; DDS_ReturnCode_t retcode; const char *participant_data; /* We only process newly seen participants */ retcode = builtin_reader->take( data_seq, info_seq, DDS_LENGTH_UNLIMITED, DDS_ANY_SAMPLE_STATE, DDS_NEW_VIEW_STATE, DDS_ANY_INSTANCE_STATE); /* This happens when we get announcements from participants we * already know about */ if (retcode == DDS_RETCODE_NO_DATA) return; if (retcode != DDS_RETCODE_OK) { printf("***Error: failed to access data from the built-in reader\n"); return; } for (int i = 0; i < data_seq.length(); ++i) { if (!info_seq[i].valid_data) continue; participant_data = "nil"; bool is_auth = false; /* see if there is any participant_data */ if (data_seq[i].user_data.value.length() != 0) { /* This sequence is guaranteed to be contiguous */ participant_data = (char *) &data_seq[i].user_data.value[0]; is_auth = (strcmp(participant_data, auth) == 0); } printf("Built-in Reader: found participant \n"); printf("\tkey->'%08x %08x %08x'\n\tuser_data->'%s'\n", data_seq[i].key.value[0], data_seq[i].key.value[1], data_seq[i].key.value[2], participant_data); int ih[6]; memcpy(ih, &info_seq[i].instance_handle, sizeof(info_seq[i].instance_handle)); printf("instance_handle: %08x%08x %08x%08x %08x%08x \n", ih[0], ih[1], ih[2], ih[3], ih[4], ih[5]); if (!is_auth) { printf("Bad authorization, ignoring participant\n"); DDSDomainParticipant *participant = reader->get_subscriber()->get_participant(); retcode = participant->ignore_participant( info_seq[i].instance_handle); if (retcode != DDS_RETCODE_OK) { printf("error ignoring participant: %d\n", retcode); return; } } } builtin_reader->return_loan(data_seq, info_seq); } class BuiltinSubscriberListener : public DDSDataReaderListener { public: virtual void on_data_available(DDSDataReader *reader); }; /* This gets called when a new subscriber has been discovered */ void BuiltinSubscriberListener::on_data_available(DDSDataReader *reader) { DDSSubscriptionBuiltinTopicDataDataReader *builtin_reader = (DDSSubscriptionBuiltinTopicDataDataReader *) reader; DDS_SubscriptionBuiltinTopicDataSeq data_seq; DDS_SampleInfoSeq info_seq; DDS_ReturnCode_t retcode; /* We only process newly seen subscribers */ retcode = builtin_reader->take( data_seq, info_seq, DDS_LENGTH_UNLIMITED, DDS_ANY_SAMPLE_STATE, DDS_NEW_VIEW_STATE, DDS_ANY_INSTANCE_STATE); if (retcode == DDS_RETCODE_NO_DATA) return; if (retcode != DDS_RETCODE_OK) { printf("***Error: failed to access data from the built-in reader\n"); return; } for (int i = 0; i < data_seq.length(); ++i) { if (!info_seq[i].valid_data) continue; printf("Built-in Reader: found subscriber \n"); printf("\tparticipant_key->'%08x %08x %08x'\n", data_seq[i].participant_key.value[0], data_seq[i].participant_key.value[1], data_seq[i].participant_key.value[2]); printf("\tkey->'%08x %08x %08x'\n", data_seq[i].key.value[0], data_seq[i].key.value[1], data_seq[i].key.value[2]); int ih[6]; memcpy(ih, &info_seq[i].instance_handle, sizeof(info_seq[i].instance_handle)); printf("instance_handle: %08x%08x %08x%08x %08x%08x \n", ih[0], ih[1], ih[2], ih[3], ih[4], ih[5]); } builtin_reader->return_loan(data_seq, info_seq); } /* End changes for Builtin_Topics */ /* Delete all entities */ static int publisher_shutdown(DDSDomainParticipant *participant) { DDS_ReturnCode_t retcode; int status = 0; if (participant != NULL) { retcode = participant->delete_contained_entities(); if (retcode != DDS_RETCODE_OK) { printf("delete_contained_entities error %d\n", retcode); status = -1; } retcode = DDSTheParticipantFactory->delete_participant(participant); if (retcode != DDS_RETCODE_OK) { printf("delete_participant error %d\n", retcode); status = -1; } } /* RTI Data Distribution Service provides finalize_instance() method for people who want to release memory used by the participant factory singleton. Uncomment the following block of code for clean destruction of the participant factory singleton. */ /* retcode = DDSDomainParticipantFactory::finalize_instance(); if (retcode != DDS_RETCODE_OK) { printf("finalize_instance error %d\n", retcode); status = -1; } */ return status; } extern "C" int publisher_main(int domainId, int sample_count) { DDSDomainParticipant *participant = NULL; DDSPublisher *publisher = NULL; DDSTopic *topic = NULL; DDSDataWriter *writer = NULL; msgDataWriter *msg_writer = NULL; msg *instance = NULL; DDS_ReturnCode_t retcode; DDS_InstanceHandle_t instance_handle = DDS_HANDLE_NIL; const char *type_name = NULL; int count = 0; DDS_Duration_t send_period = { 1, 0 }; /* By default, the participant is enabled upon construction. * At that time our listeners for the builtin topics have not * been installed, so we disable the participant until we * set up the listeners. This is done by default in the * USER_QOS_PROFILES.xml * file. If you want to do it programmatically, just uncomment * the following code. */ /* DDS_DomainParticipantFactoryQos factory_qos; retcode = DDSTheParticipantFactory->get_qos(factory_qos); if (retcode != DDS_RETCODE_OK) { printf("Cannot get factory Qos for domain participant\n"); return -1; } factory_qos.entity_factory.autoenable_created_entities = DDS_BOOLEAN_FALSE; switch(DDSTheParticipantFactory->set_qos(factory_qos)) { case DDS_RETCODE_OK: break; case DDS_RETCODE_IMMUTABLE_POLICY: { printf("Cannot set factory Qos due to IMMUTABLE_POLICY "); printf("for domain participant\n"); return -1; break; } case DDS_RETCODE_INCONSISTENT_POLICY: { printf("Cannot set factory Qos due to INCONSISTENT_POLICY for "); printf("domain participant\n"); return -1; break; } default: { printf("Cannot set factory Qos for unknown reason for "); printf("domain participant\n"); return -1; break; } } */ DDS_DomainParticipantQos participant_qos; retcode = DDSTheParticipantFactory->get_default_participant_qos( participant_qos); if (retcode != DDS_RETCODE_OK) { printf("get_default_participant_qos error\n"); return -1; } /* If you want to change the Participant's QoS programmatically rather * than using the XML file, you will need to uncomment the following line. */ /* participant_qos.resource_limits.participant_user_data_max_length = 1024; */ /* To customize participant QoS, use the configuration file USER_QOS_PROFILES.xml */ participant = DDSTheParticipantFactory->create_participant( domainId, participant_qos, NULL /* listener */, DDS_STATUS_MASK_NONE); if (participant == NULL) { printf("create_participant error\n"); publisher_shutdown(participant); return -1; } /* Start changes for Builtin_Topics */ /* Installing listeners for the builtin topics requires several steps */ /* First get the builtin subscriber */ DDSSubscriber *builtin_subscriber = participant->get_builtin_subscriber(); if (builtin_subscriber == NULL) { printf("***Error: failed to create builtin subscriber\n"); return 0; } /* Then get builtin subscriber's datareader for participants The type name is a bit hairy, but can be read right to left: DDSParticipantBuiltinTopicDataDataReader is a DataReader for BuiltinTopicData concerning a discovered Participant */ DDSParticipantBuiltinTopicDataDataReader *builtin_participant_datareader = (DDSParticipantBuiltinTopicDataDataReader *) builtin_subscriber ->lookup_datareader(DDS_PARTICIPANT_TOPIC_NAME); if (builtin_participant_datareader == NULL) { printf("***Error: failed to create builtin participant data reader\n"); return 0; } /* Install our listener */ BuiltinParticipantListener *builtin_participant_listener = new BuiltinParticipantListener(); builtin_participant_datareader->set_listener( builtin_participant_listener, DDS_DATA_AVAILABLE_STATUS); /* Get builtin subscriber's datareader for subscribers */ DDSSubscriptionBuiltinTopicDataDataReader *builtin_subscription_datareader = (DDSSubscriptionBuiltinTopicDataDataReader *) builtin_subscriber ->lookup_datareader(DDS_SUBSCRIPTION_TOPIC_NAME); if (builtin_subscription_datareader == NULL) { printf("***Error: failed to create builtin subscription data reader\n"); return 0; } /* Install our listener */ BuiltinSubscriberListener *builtin_subscriber_listener = new BuiltinSubscriberListener(); builtin_subscription_datareader->set_listener( builtin_subscriber_listener, DDS_DATA_AVAILABLE_STATUS); /* Done! All the listeners are installed, so we can enable the * participant now. */ if (participant->enable() != DDS_RETCODE_OK) { printf("***Error: Failed to Enable Participant\n"); return 0; } /* End changes for Builtin_Topics */ /* 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 the type before creating the topic */ type_name = msgTypeSupport::get_type_name(); retcode = msgTypeSupport::register_type(participant, type_name); if (retcode != DDS_RETCODE_OK) { printf("register_type error %d\n", retcode); publisher_shutdown(participant); return -1; } /* To customize topic QoS, use the configuration file USER_QOS_PROFILES.xml */ topic = participant->create_topic( "Example msg", type_name, DDS_TOPIC_QOS_DEFAULT, NULL /* listener */, DDS_STATUS_MASK_NONE); if (topic == NULL) { printf("create_topic error\n"); publisher_shutdown(participant); return -1; } /* To customize data writer QoS, use the configuration file USER_QOS_PROFILES.xml */ writer = publisher->create_datawriter( topic, DDS_DATAWRITER_QOS_DEFAULT, NULL /* listener */, DDS_STATUS_MASK_NONE); if (writer == NULL) { printf("create_datawriter error\n"); publisher_shutdown(participant); return -1; } msg_writer = msgDataWriter::narrow(writer); if (msg_writer == NULL) { printf("DataWriter narrow error\n"); publisher_shutdown(participant); return -1; } /* Create data sample for writing */ instance = msgTypeSupport::create_data(); if (instance == NULL) { printf("msgTypeSupport::create_data error\n"); publisher_shutdown(participant); return -1; } /* For 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 = msg_writer->register_instance(*instance); */ /* Main loop */ for (count = 0; (sample_count == 0) || (count < sample_count); ++count) { NDDSUtility::sleep(send_period); printf("Writing msg, count %d\n", count); /* Modify the data to be sent here */ instance->x = count; retcode = msg_writer->write(*instance, instance_handle); if (retcode != DDS_RETCODE_OK) { printf("write error %d\n", retcode); } } /* retcode = msg_writer->unregister_instance( *instance, instance_handle); if (retcode != DDS_RETCODE_OK) { printf("unregister instance error %d\n", retcode); } */ /* Delete data sample */ retcode = msgTypeSupport::delete_data(instance); if (retcode != DDS_RETCODE_OK) { printf("msgTypeSupport::delete_data error %d\n", retcode); } /* Delete all entities */ return publisher_shutdown(participant); } int main(int argc, char *argv[]) { int domain_id = 0; int sample_count = 0; /* infinite loop */ if (argc >= 2) { domain_id = atoi(argv[1]); } if (argc >= 3) { sample_count = atoi(argv[2]); } /* Uncomment this to turn on additional logging 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); }
cxx
rticonnextdds-examples
data/projects/rticonnextdds-examples/connext_dds/builtin_topics/c++/msg_subscriber.cxx
/******************************************************************************* (c) 2005-2014 Copyright, Real-Time Innovations, Inc. All rights reserved. RTI grants Licensee a license to use, modify, compile, and create derivative works of the Software. Licensee has the right to distribute object form only for use with RTI products. The Software is provided "as is", with no warranty of any type, including any warranty for fitness for any purpose. RTI is under no obligation to maintain or support the Software. RTI shall not be liable for any incidental or consequential damages arising out of the use or inability to use the software. ******************************************************************************/ /* msg_subscriber.cxx A subscription example This file is derived from code automatically generated by the rtiddsgen command: rtiddsgen -language C++ -example <arch> msg.idl Example subscription of type msg automatically generated by 'rtiddsgen'. To test them follow these steps: (1) Compile this file and the example publication. (2) Start the subscription on the same domain used for RTI Data Distribution Service with the command objs/<arch>/msg_subscriber <domain_id> <sample_count> (3) Start the publication on the same domain used for RTI Data Distribution with the command objs/<arch>/msg_publisher <domain_id> <sample_count> (4) [Optional] Specify the list of discovery initial peers and multicast receive addresses via an environment variable or a file (in the current working directory) called NDDS_DISCOVERY_PEERS. You can run any number of publishers and subscribers programs, and can add and remove them dynamically from the domain. Example: To run the example application on domain <domain_id>: On Unix: objs/<arch>/msg_publisher <domain_id> objs/<arch>/msg_subscriber <domain_id> On Windows: objs\<arch>\msg_publisher <domain_id> objs\<arch>\msg_subscriber <domain_id> modification history ------------ ------- * Set user_data QoS fields in participant and datareader with strings given on command line * Updated for 4.1 to 4.2: participant_index changed to participant_id * Refactor and remove unused variables and classes * Fix not including null char in participant user_data password. */ #include "msg.h" #include "msgSupport.h" #include "ndds/ndds_cpp.h" #include <stdio.h> #include <stdlib.h> class msgListener : 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 msgListener::on_data_available(DDSDataReader *reader) { msgDataReader *msg_reader = NULL; msgSeq data_seq; DDS_SampleInfoSeq info_seq; DDS_ReturnCode_t retcode; int i; msg_reader = msgDataReader::narrow(reader); if (msg_reader == NULL) { printf("DataReader narrow error\n"); return; } retcode = msg_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) { msgTypeSupport::print_data(&data_seq[i]); } } retcode = msg_reader->return_loan(data_seq, info_seq); if (retcode != DDS_RETCODE_OK) { printf("return loan error %d\n", retcode); } } /* Delete all entities */ static int subscriber_shutdown(DDSDomainParticipant *participant) { DDS_ReturnCode_t retcode; int status = 0; if (participant != NULL) { retcode = participant->delete_contained_entities(); if (retcode != DDS_RETCODE_OK) { printf("delete_contained_entities error %d\n", retcode); status = -1; } retcode = DDSTheParticipantFactory->delete_participant(participant); if (retcode != DDS_RETCODE_OK) { printf("delete_participant error %d\n", retcode); status = -1; } } /* RTI Data Distribution Service provides finalize_instance() method for people who want to release memory used by the participant factory singleton. Uncomment the following block of code for clean destruction of the participant factory singleton. */ /* retcode = DDSDomainParticipantFactory::finalize_instance(); if (retcode != DDS_RETCODE_OK) { printf("finalize_instance error %d\n", retcode); status = -1; } */ return status; } extern "C" int subscriber_main( int domain_id, int sample_count, const char *participant_auth) { DDSDomainParticipant *participant = NULL; DDSSubscriber *subscriber = NULL; DDSTopic *topic = NULL; msgListener *reader_listener = NULL; DDSDataReader *reader = NULL; DDS_ReturnCode_t retcode; const char *type_name = NULL; int count = 0; DDS_Duration_t receive_period = { 1, 0 }; int status = 0; /* Start changes for Builtin_Topics */ /* Set user_data qos field for participant */ /* Get default participant QoS to customize */ DDS_DomainParticipantQos participant_qos; retcode = DDSTheParticipantFactory->get_default_participant_qos( participant_qos); if (retcode != DDS_RETCODE_OK) { printf("get_default_participant_qos error\n"); return -1; } /* The maximum length for USER_DATA QoS field is set by default to 256 bytes. To increase it programmatically uncomment the following line of code. */ /* participant_qos.resource_limits.participant_user_data_max_length = 1024; */ /* user_data is opaque to DDS, so we include trailing \0 for string */ int len = strlen(participant_auth) + 1; int max = participant_qos.resource_limits.participant_user_data_max_length; if (len > max) { printf("error, participant user_data exceeds resource limits\n"); } else { /* DDS_Octet is defined to be 8 bits. If chars are not 8 bits * on your system, this will not work. */ participant_qos.user_data.value.from_array( reinterpret_cast<const DDS_Octet *>(participant_auth), len); } /* To create participant with default QoS, use DDS_PARTICIPANT_QOS_DEFAULT instead of participant_qos */ participant = DDSTheParticipantFactory->create_participant( domain_id, participant_qos, NULL /* listener */, DDS_STATUS_MASK_NONE); if (participant == NULL) { printf("create_participant error\n"); subscriber_shutdown(participant); return -1; } /* The participant is disabled by default. We enable it now */ if (participant->enable() != DDS_RETCODE_OK) { printf("***Error: Failed to Enable Participant\n"); return 0; } /* 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 = msgTypeSupport::get_type_name(); retcode = msgTypeSupport::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 = participant->create_topic( "Example msg", type_name, DDS_TOPIC_QOS_DEFAULT, NULL /* listener */, DDS_STATUS_MASK_NONE); if (topic == NULL) { printf("create_topic error\n"); subscriber_shutdown(participant); return -1; } /* Create a data reader listener */ reader_listener = new msgListener(); /* To customize data reader QoS, use the configuration file USER_QOS_PROFILES.xml */ reader = subscriber->create_datareader( topic, DDS_DATAREADER_QOS_DEFAULT, reader_listener, DDS_STATUS_MASK_ALL); if (reader == NULL) { printf("create_datareader error\n"); subscriber_shutdown(participant); delete reader_listener; return -1; } /* Main loop */ for (count = 0; (sample_count == 0) || (count < sample_count); ++count) { NDDSUtility::sleep(receive_period); } /* Delete all entities */ status = subscriber_shutdown(participant); delete reader_listener; return status; } int main(int argc, char *argv[]) { int domain_id = 0; int sample_count = 0; /* infinite loop */ const char *participant_auth = "password"; if (argc >= 2) { domain_id = atoi(argv[1]); } if (argc >= 3) { sample_count = atoi(argv[2]); } if (argc >= 4) { participant_auth = argv[3]; } /* Uncomment this to turn on additional logging NDDSConfigLogger::get_instance()-> set_verbosity_by_category(NDDS_CONFIG_LOG_CATEGORY_API, NDDS_CONFIG_LOG_VERBOSITY_STATUS_ALL); */ return subscriber_main(domain_id, sample_count, participant_auth); }
cxx
rticonnextdds-examples
data/projects/rticonnextdds-examples/connext_dds/builtin_topics/c++98/msg_publisher.cxx
/******************************************************************************* (c) 2005-2014 Copyright, Real-Time Innovations, Inc. All rights reserved. RTI grants Licensee a license to use, modify, compile, and create derivative works of the Software. Licensee has the right to distribute object form only for use with RTI products. The Software is provided "as is", with no warranty of any type, including any warranty for fitness for any purpose. RTI is under no obligation to maintain or support the Software. RTI shall not be liable for any incidental or consequential damages arising out of the use or inability to use the software. ******************************************************************************/ #include <iostream> #include <iomanip> #include <stdio.h> #include <stdlib.h> #include "msg.h" #include "msgSupport.h" #include "ndds/ndds_cpp.h" #include "application.h" using namespace application; /* Authorization string. */ const char *auth = "password"; static int shutdown_participant( DDSDomainParticipant *participant, const char *shutdown_message, int status); /* The builtin subscriber sets participant_qos.user_data and so we set up listeners for the builtin DataReaders to access these fields. */ class BuiltinParticipantListener : public DDSDataReaderListener { public: virtual void on_data_available(DDSDataReader *reader); }; /* This gets called when a participant has been discovered */ void BuiltinParticipantListener::on_data_available(DDSDataReader *reader) { DDSParticipantBuiltinTopicDataDataReader *builtin_reader = (DDSParticipantBuiltinTopicDataDataReader *) reader; DDS_ParticipantBuiltinTopicDataSeq data_seq; DDS_SampleInfoSeq info_seq; DDS_ReturnCode_t retcode; const char *participant_data; // We only process newly seen participants retcode = builtin_reader->take( data_seq, info_seq, DDS_LENGTH_UNLIMITED, DDS_ANY_SAMPLE_STATE, DDS_NEW_VIEW_STATE, DDS_ANY_INSTANCE_STATE); /* This happens when we get announcements from participants we * already know about */ if (retcode == DDS_RETCODE_NO_DATA) return; if (retcode != DDS_RETCODE_OK) { std::cerr << "Error: failed to access data from the built-in reader\n"; return; } for (int i = 0; i < data_seq.length(); ++i) { if (!info_seq[i].valid_data) continue; participant_data = "nil"; bool is_auth = false; // see if there is any participant_data if (data_seq[i].user_data.value.length() != 0) { // This sequence is guaranteed to be contiguous participant_data = (char *) &data_seq[i].user_data.value[0]; is_auth = (strcmp(participant_data, auth) == 0); } std::ios::fmtflags default_format(std::cout.flags()); std::cout << std::hex << std::setw(8) << std::setfill('0'); std::cout << "Built-in Reader: found participant \n"; std::cout << "\tkey->'" << data_seq[i].key.value[0] << " " << data_seq[i].key.value[1] << " " << data_seq[i].key.value[2] << "'\n"; std::cout << "\tuser_data->'" << participant_data << "'\n"; int ih[6]; memcpy(ih, &info_seq[i].instance_handle, sizeof(info_seq[i].instance_handle)); std::cout << "instance_handle: " << ih[0] << ih[1] << " " << ih[2] << ih[3] << " " << ih[4] << ih[5] << std::endl; std::cout.flags(default_format); if (!is_auth) { std::cout << "Bad authorization, ignoring participant\n"; DDSDomainParticipant *participant = reader->get_subscriber()->get_participant(); retcode = participant->ignore_participant( info_seq[i].instance_handle); if (retcode != DDS_RETCODE_OK) { std::cout << "error ignoring participant: " << retcode << std::endl; return; } } } builtin_reader->return_loan(data_seq, info_seq); } class BuiltinSubscriberListener : public DDSDataReaderListener { public: virtual void on_data_available(DDSDataReader *reader); }; // This gets called when a new subscriber has been discovered void BuiltinSubscriberListener::on_data_available(DDSDataReader *reader) { DDSSubscriptionBuiltinTopicDataDataReader *builtin_reader = (DDSSubscriptionBuiltinTopicDataDataReader *) reader; DDS_SubscriptionBuiltinTopicDataSeq data_seq; DDS_SampleInfoSeq info_seq; DDS_ReturnCode_t retcode; // We only process newly seen subscribers retcode = builtin_reader->take( data_seq, info_seq, DDS_LENGTH_UNLIMITED, DDS_ANY_SAMPLE_STATE, DDS_NEW_VIEW_STATE, DDS_ANY_INSTANCE_STATE); if (retcode == DDS_RETCODE_NO_DATA) return; if (retcode != DDS_RETCODE_OK) { std::cerr << "Error: failed to access data from the built-in reader\n"; return; } for (int i = 0; i < data_seq.length(); ++i) { if (!info_seq[i].valid_data) continue; std::ios::fmtflags default_format(std::cout.flags()); std::cout << std::hex << std::setw(8) << std::setfill('0'); std::cout << "Built-in Reader: found subscriber \n"; std::cout << "\tparticipant_key->'" << data_seq[i].participant_key.value[0] << " " << data_seq[i].participant_key.value[1] << " " << data_seq[i].participant_key.value[2] << "'\n"; std::cout << "\tkey->'" << data_seq[i].key.value[0] << " " << data_seq[i].key.value[1] << " " << data_seq[i].key.value[2] << "'\n"; int ih[6]; memcpy(ih, &info_seq[i].instance_handle, sizeof(info_seq[i].instance_handle)); std::cout << "instance_handle: " << ih[0] << ih[1] << " " << ih[2] << ih[3] << " " << ih[4] << ih[5] << std::endl; std::cout.flags(default_format); } builtin_reader->return_loan(data_seq, info_seq); } int run_publisher_application(unsigned int domain_id, unsigned int sample_count) { DDS_Duration_t send_period = { 1, 0 }; /* By default, the participant is enabled upon construction. * At that time our listeners for the builtin topics have not * been installed, so we disable the participant until we * set up the listeners. This is done by default in the * USER_QOS_PROFILES.xml * file. If you want to do it programmatically, just uncomment * the following code. */ /* DDS_DomainParticipantFactoryQos factory_qos; DDS_ReturnCode_t retcode = DDSTheParticipantFactory->get_qos(factory_qos); if (retcode != DDS_RETCODE_OK) { return shutdown_participant(participant, "create_participant error", EXIT_FAILURE); } factory_qos.entity_factory.autoenable_created_entities = DDS_BOOLEAN_FALSE; switch(DDSTheParticipantFactory->set_qos(factory_qos)) { case DDS_RETCODE_OK: break; case DDS_RETCODE_IMMUTABLE_POLICY: { std::cerr << "Cannot set factory Qos due to IMMUTABLE_POLICY "; std::cerr << "for domain participant\n"; return EXIT_FAILURE; break; } case DDS_RETCODE_INCONSISTENT_POLICY: { std::cerr << "Cannot set factory Qos due to INCONSISTENT_POLICY for "; std::cerr << "domain participant\n"; return EXIT_FAILURE; break; } default: { std::cerr << "Cannot set factory Qos for unknown reason for "; std::cerr <<"domain participant\n"; return EXIT_FAILURE; break; } } */ DDS_DomainParticipantQos participant_qos; DDS_ReturnCode_t retcode = DDSTheParticipantFactory->get_default_participant_qos( participant_qos); if (retcode != DDS_RETCODE_OK) { std::cerr << "get_default_participant_qos error" << std::endl; return EXIT_FAILURE; } /* If you want to change the Participant's QoS programmatically rather * than using the XML file, you will need to uncomment the following line. */ /* participant_qos.resource_limits.participant_user_data_max_length = 1024; */ // Start communicating in a domain, usually one participant per application DDSDomainParticipant *participant = DDSTheParticipantFactory->create_participant( domain_id, participant_qos, NULL /* listener */, DDS_STATUS_MASK_NONE); if (participant == NULL) { return shutdown_participant( participant, "create_participant error", EXIT_FAILURE); } /* Start changes for Builtin_Topics * Installing listeners for the builtin topics requires several steps */ // A Subscriber allows an application to create one or more DataReaders DDSSubscriber *builtin_subscriber = participant->get_builtin_subscriber(); if (builtin_subscriber == NULL) { return shutdown_participant( participant, "failed to create builtin subscriber", EXIT_FAILURE); } /* Then get builtin subscriber's datareader for participants The type name is a bit hairy, but can be read right to left: DDSParticipantBuiltinTopicDataDataReader is a DataReader for BuiltinTopicData concerning a discovered Participant */ DDSParticipantBuiltinTopicDataDataReader *builtin_participant_datareader = (DDSParticipantBuiltinTopicDataDataReader *) builtin_subscriber ->lookup_datareader(DDS_PARTICIPANT_TOPIC_NAME); if (builtin_participant_datareader == NULL) { return shutdown_participant( participant, "failed to create builtin participant data reader", EXIT_FAILURE); } // Install our listener BuiltinParticipantListener *builtin_participant_listener = new BuiltinParticipantListener(); builtin_participant_datareader->set_listener( builtin_participant_listener, DDS_DATA_AVAILABLE_STATUS); // Get builtin subscriber's datareader for subscribers DDSSubscriptionBuiltinTopicDataDataReader *builtin_subscription_datareader = (DDSSubscriptionBuiltinTopicDataDataReader *) builtin_subscriber ->lookup_datareader(DDS_SUBSCRIPTION_TOPIC_NAME); if (builtin_subscription_datareader == NULL) { return shutdown_participant( participant, "failed to create builtin subscription data reader", EXIT_FAILURE); } // Install our listener BuiltinSubscriberListener *builtin_subscriber_listener = new BuiltinSubscriberListener(); builtin_subscription_datareader->set_listener( builtin_subscriber_listener, DDS_DATA_AVAILABLE_STATUS); /* Done! All the listeners are installed, so we can enable the * participant now. */ if (participant->enable() != DDS_RETCODE_OK) { return shutdown_participant( participant, "failed to Enable Participant", EXIT_FAILURE); } // End changes for Builtin_Topics // A Publisher allows an application to create one or more DataWriters DDSPublisher *publisher = participant->create_publisher( DDS_PUBLISHER_QOS_DEFAULT, NULL /* listener */, DDS_STATUS_MASK_NONE); if (publisher == NULL) { return shutdown_participant( participant, "create_publisher error", EXIT_FAILURE); } // Register the datatype to use when creating the Topic const char *type_name = msgTypeSupport::get_type_name(); retcode = msgTypeSupport::register_type(participant, type_name); if (retcode != DDS_RETCODE_OK) { return shutdown_participant( participant, "register_type error", EXIT_FAILURE); } // Create a Topic with a name and a datatype DDSTopic *topic = participant->create_topic( "Example msg", type_name, DDS_TOPIC_QOS_DEFAULT, NULL /* listener */, DDS_STATUS_MASK_NONE); if (topic == NULL) { return shutdown_participant( participant, "create_topic error", EXIT_FAILURE); } DDSDataWriter *untyped_writer = publisher->create_datawriter( topic, DDS_DATAWRITER_QOS_DEFAULT, NULL /* listener */, DDS_STATUS_MASK_NONE); if (untyped_writer == NULL) { return shutdown_participant( participant, "create_datawriter error", EXIT_FAILURE); } msgDataWriter *typed_writer = msgDataWriter::narrow(untyped_writer); if (typed_writer == NULL) { return shutdown_participant( participant, "DataWriter narrow error", EXIT_FAILURE); } // Create data sample for writing msg *data = msgTypeSupport::create_data(); if (data == NULL) { return shutdown_participant( participant, "msgTypeSupport::create_data error", EXIT_FAILURE); } DDS_InstanceHandle_t instance_handle = DDS_HANDLE_NIL; /* For 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); */ // Main loop, write data for (unsigned int samples_written = 0; !shutdown_requested && samples_written < sample_count; ++samples_written) { NDDSUtility::sleep(send_period); std::cout << "Writing msg, count " << samples_written << std::endl; // Modify the data to be sent here data->x = samples_written; retcode = typed_writer->write(*data, instance_handle); if (retcode != DDS_RETCODE_OK) { printf("write error %d\n", retcode); } } /* retcode = typed_writer->unregister_instance( *data, instance_handle); if (retcode != DDS_RETCODE_OK) { std::cerr << "unregister instance error " << retcode << std::endl; } */ // Delete previously allocated async, including all contained elements retcode = msgTypeSupport::delete_data(data); if (retcode != DDS_RETCODE_OK) { std::cerr << "msgTypeSupport::delete_data error " << retcode << std::endl; } // Delete all entities (DataWriter, Topic, Publisher, DomainParticipant) return shutdown_participant(participant, "Shutting down", EXIT_SUCCESS); } // Delete all entities static int shutdown_participant( DDSDomainParticipant *participant, const char *shutdown_message, int status) { DDS_ReturnCode_t retcode; std::cout << shutdown_message << std::endl; if (participant != NULL) { // Cleanup everything created by this Participant retcode = participant->delete_contained_entities(); if (retcode != DDS_RETCODE_OK) { std::cerr << "delete_contained_entities error " << retcode << std::endl; status = EXIT_FAILURE; } retcode = DDSTheParticipantFactory->delete_participant(participant); if (retcode != DDS_RETCODE_OK) { std::cerr << "delete_participant error " << retcode << std::endl; status = EXIT_FAILURE; } } return status; } int main(int argc, char *argv[]) { // Parse arguments and handle control-C ApplicationArguments arguments; parse_arguments(arguments, argc, argv, publisher); if (arguments.parse_result == PARSE_RETURN_EXIT) { return EXIT_SUCCESS; } else if (arguments.parse_result == PARSE_RETURN_FAILURE) { return EXIT_FAILURE; } setup_signal_handlers(); // Sets Connext verbosity to help debugging NDDSConfigLogger::get_instance()->set_verbosity(arguments.verbosity); int status = run_publisher_application( arguments.domain_id, arguments.sample_count); // Releases the memory used by the participant factory. Optional at // application exit DDS_ReturnCode_t retcode = DDSDomainParticipantFactory::finalize_instance(); if (retcode != DDS_RETCODE_OK) { std::cerr << "finalize_instance error " << retcode << std::endl; status = EXIT_FAILURE; } return status; }
cxx
rticonnextdds-examples
data/projects/rticonnextdds-examples/connext_dds/builtin_topics/c++98/msg_subscriber.cxx
/******************************************************************************* (c) 2005-2014 Copyright, Real-Time Innovations, Inc. All rights reserved. RTI grants Licensee a license to use, modify, compile, and create derivative works of the Software. Licensee has the right to distribute object form only for use with RTI products. The Software is provided "as is", with no warranty of any type, including any warranty for fitness for any purpose. RTI is under no obligation to maintain or support the Software. RTI shall not be liable for any incidental or consequential damages arising out of the use or inability to use the software. ******************************************************************************/ #include <iostream> #include <stdio.h> #include <stdlib.h> #include "msg.h" #include "msgSupport.h" #include "ndds/ndds_cpp.h" #include "application.h" using namespace application; static int shutdown_participant( DDSDomainParticipant *participant, const char *shutdown_message, int status); unsigned int process_data(msgDataReader *typed_reader) { msgSeq 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) { msgTypeSupport::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, const char *participant_auth) { DDS_Duration_t wait_timeout = { 1, 0 }; /* Start changes for Builtin_Topics */ /* Set user_data qos field for participant */ // Get default participant QoS to customize DDS_DomainParticipantQos participant_qos; DDS_ReturnCode_t retcode = DDSTheParticipantFactory->get_default_participant_qos( participant_qos); if (retcode != DDS_RETCODE_OK) { std::cerr << "get_default_participant_qos error\n"; return EXIT_FAILURE; } /* The maximum length for USER_DATA QoS field is set by default to 256 bytes. To increase it programmatically uncomment the following line of code. */ /* participant_qos.resource_limits.participant_user_data_max_length = 1024; */ /* user_data is opaque to DDS, so we include trailing \0 for string */ int len = strlen(participant_auth) + 1; int max = participant_qos.resource_limits.participant_user_data_max_length; if (len > max) { std::cerr << "error, participant user_data exceeds resource limits\n"; } else { /* DDS_Octet is defined to be 8 bits. If chars are not 8 bits * on your system, this will not work. */ participant_qos.user_data.value.from_array( reinterpret_cast<const DDS_Octet *>(participant_auth), len); } // Start communicating in a domain, usually one participant per application DDSDomainParticipant *participant = DDSTheParticipantFactory->create_participant( domain_id, participant_qos, NULL /* listener */, DDS_STATUS_MASK_NONE); if (participant == NULL) { return shutdown_participant( participant, "create_participant error", EXIT_FAILURE); } // The participant is disabled by default. We enable it now if (participant->enable() != DDS_RETCODE_OK) { return shutdown_participant( participant, "Failed to Enable Participant", 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 = msgTypeSupport::get_type_name(); retcode = msgTypeSupport::register_type(participant, type_name); if (retcode != DDS_RETCODE_OK) { return shutdown_participant( participant, "register_type error", EXIT_FAILURE); } // Create a Topic with a name and a datatype DDSTopic *topic = participant->create_topic( "Example msg", type_name, DDS_TOPIC_QOS_DEFAULT, NULL /* listener */, DDS_STATUS_MASK_NONE); if (topic == NULL) { return shutdown_participant( participant, "create_topic error", EXIT_FAILURE); } // This DataReader reads data on "Example msg" 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 msgDataReader *typed_reader = msgDataReader::narrow(untyped_reader); if (typed_reader == NULL) { return shutdown_participant( participant, "DataReader narrow error", EXIT_FAILURE); } // Create ReadCondition that triggers when unread data in reader's queue DDSReadCondition *read_condition = typed_reader->create_readcondition( DDS_NOT_READ_SAMPLE_STATE, DDS_ANY_VIEW_STATE, DDS_ANY_INSTANCE_STATE); if (read_condition == NULL) { return shutdown_participant( participant, "create_readcondition error", EXIT_FAILURE); } // WaitSet will be woken when the attached condition is triggered DDSWaitSet waitset; retcode = waitset.attach_condition(read_condition); if (retcode != DDS_RETCODE_OK) { return shutdown_participant( participant, "attach_condition error", EXIT_FAILURE); } // Main loop. Wait for data to arrive, and process when it arrives unsigned int samples_read = 0; while (!shutdown_requested && samples_read < sample_count) { DDSConditionSeq active_conditions_seq; // Wait for data and report if it does not arrive in 1 second 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, subscriber); if (arguments.parse_result == PARSE_RETURN_EXIT) { return EXIT_SUCCESS; } else if (arguments.parse_result == PARSE_RETURN_FAILURE) { return EXIT_FAILURE; } setup_signal_handlers(); // Sets Connext verbosity to help debugging NDDSConfigLogger::get_instance()->set_verbosity(arguments.verbosity); int status = run_subscriber_application( arguments.domain_id, arguments.sample_count, arguments.participant_auth); // 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_topics/c++98/application.h
/* * (c) Copyright, Real-Time Innovations, 2021. All rights reserved. * RTI grants Licensee a license to use, modify, compile, and create derivative * works of the software solely for use with RTI Connext DDS. Licensee may * redistribute copies of the software provided that all such copies are subject * to this license. The software is provided "as is", with no warranty of any * type, including any warranty for fitness for any purpose. RTI is under no * obligation to maintain or support the software. RTI shall not be liable for * any incidental or consequential damages arising out of the use or inability * to use the software. */ #ifndef APPLICATION_H #define APPLICATION_H #include <iostream> #include <csignal> #include <climits> namespace application { // Catch control-C and tell application to shut down bool shutdown_requested = false; inline void stop_handler(int) { shutdown_requested = true; std::cout << "preparing to shut down..." << std::endl; } inline void setup_signal_handlers() { signal(SIGINT, stop_handler); signal(SIGTERM, stop_handler); } enum ParseReturn { PARSE_RETURN_OK, PARSE_RETURN_FAILURE, PARSE_RETURN_EXIT }; enum ApplicationKind { publisher, subscriber }; struct ApplicationArguments { ParseReturn parse_result; unsigned int domain_id; unsigned int sample_count; NDDS_Config_LogVerbosity verbosity; char *participant_auth; char *reader_auth; }; inline void set_verbosity(ApplicationArguments &arguments, int verbosity) { switch (verbosity) { case 0: arguments.verbosity = NDDS_CONFIG_LOG_VERBOSITY_SILENT; break; case 1: arguments.verbosity = NDDS_CONFIG_LOG_VERBOSITY_ERROR; break; case 2: arguments.verbosity = NDDS_CONFIG_LOG_VERBOSITY_WARNING; break; case 3: arguments.verbosity = NDDS_CONFIG_LOG_VERBOSITY_STATUS_ALL; break; default: arguments.verbosity = NDDS_CONFIG_LOG_VERBOSITY_ERROR; break; } } // Parses application arguments for example. Returns whether to exit. inline void parse_arguments( ApplicationArguments &arguments, int argc, char *argv[], ApplicationKind current_application) { int arg_processing = 1; bool show_usage = false; arguments.domain_id = 0; arguments.sample_count = INT_MAX; arguments.verbosity = NDDS_CONFIG_LOG_VERBOSITY_ERROR; arguments.parse_result = PARSE_RETURN_OK; arguments.participant_auth = DDS_String_dup("password"); arguments.reader_auth = DDS_String_dup("Reader_Auth"); 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) && current_application == subscriber && (strcmp(argv[arg_processing], "-pa") == 0 || strcmp(argv[arg_processing], "--pauth") == 0)) { arguments.participant_auth = argv[arg_processing + 1]; arg_processing += 2; } else if ( (argc > arg_processing + 1) && current_application == subscriber && (strcmp(argv[arg_processing], "-ra") == 0 || strcmp(argv[arg_processing], "--rauth") == 0)) { arguments.reader_auth = 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; if (current_application == subscriber) { std::cout << " -pa, --pauth <string> The participant " "authorization string. \n" " Default: \"password\"\n" " -ra, --rauth <string> The reader " "authorization string. \n" " Default: \"Reader_Auth\"" << std::endl; } } } } // namespace application #endif // APPLICATION_H
h
rticonnextdds-examples
data/projects/rticonnextdds-examples/connext_dds/builtin_topics/c/msg_publisher.c
/******************************************************************************* (c) 2005-2014 Copyright, Real-Time Innovations, Inc. All rights reserved. RTI grants Licensee a license to use, modify, compile, and create derivative works of the Software. Licensee has the right to distribute object form only for use with RTI products. The Software is provided "as is", with no warranty of any type, including any warranty for fitness for any purpose. RTI is under no obligation to maintain or support the Software. RTI shall not be liable for any incidental or consequential damages arising out of the use or inability to use the software. ******************************************************************************/ /* msg_publisher.c A publication of data of type msg This file is derived from code automatically generated by the rtiddsgen command: rtiddsgen -language C -example <arch> msg.idl Example publication of type msg automatically generated by 'rtiddsgen'. To test them follow these steps: (1) Compile this file and the example subscription. (2) Start the subscription on the same domain used for RTI Data Distribution Service with the command objs/<arch>/msg_subscriber <domain_id> <sample_count> (3) Start the publication on the same domain used for RTI Data Distribution Service with the command objs/<arch>/msg_publisher <domain_id> <sample_count> (4) [Optional] Specify the list of discovery initial peers and multicast receive addresses via an environment variable or a file (in the current working directory) called NDDS_DISCOVERY_PEERS. You can run any number of publishers and subscribers programs, and can add and remove them dynamically from the domain. Example: To run the example application on domain <domain_id>: On Unix: objs/<arch>/msg_publisher <domain_id> objs/<arch>/msg_subscriber <domain_id> On Windows: objs\<arch>\msg_publisher <domain_id> objs\<arch>\msg_subscriber <domain_id> modification history ------------ ------- * Add code to store keys of authorized participants * Define listeners for builtin topics, which get called when we find a new participant or reader. * Create disabled participant to ensure our listeners are installed before anything is processed * Install listeners * Do not ignore subscriber since it is a bad security practice. * Print key and instance_handle info. */ #include "msg.h" #include "msgSupport.h" #include "ndds/ndds_c.h" #include <stdio.h> #include <stdlib.h> /* Authorization string. */ const char *auth = "password"; /* * The builtin subscriber sets participant_qos.user_data and * so we set up listeners for the builtin * DataReaders to access these fields. */ /* This gets called when a participant has been discovered */ void BuiltinParticipantListener_on_data_available( void *listener_data, DDS_DataReader *reader) { DDS_ParticipantBuiltinTopicDataDataReader *builtin_reader = NULL; struct DDS_ParticipantBuiltinTopicDataSeq data_seq = DDS_SEQUENCE_INITIALIZER; struct DDS_SampleInfoSeq info_seq = DDS_SEQUENCE_INITIALIZER; DDS_ReturnCode_t retcode; int i; int len; int ih[6]; builtin_reader = DDS_ParticipantBuiltinTopicDataDataReader_narrow(reader); /* We only process newly seen participants */ retcode = DDS_ParticipantBuiltinTopicDataDataReader_take( builtin_reader, &data_seq, &info_seq, DDS_LENGTH_UNLIMITED, DDS_ANY_SAMPLE_STATE, DDS_NEW_VIEW_STATE, DDS_ANY_INSTANCE_STATE); /* * This happens when we get announcements from participants we * already know about */ if (retcode == DDS_RETCODE_NO_DATA) return; if (retcode != DDS_RETCODE_OK) { printf("***Error: failed to access data from the built-in reader\n"); return; } len = DDS_ParticipantBuiltinTopicDataSeq_get_length(&data_seq); for (i = 0; i < len; ++i) { struct DDS_SampleInfo *info = NULL; struct DDS_ParticipantBuiltinTopicData *data = NULL; char *participant_data = "nil"; int is_auth = 0; info = DDS_SampleInfoSeq_get_reference(&info_seq, i); data = DDS_ParticipantBuiltinTopicDataSeq_get_reference(&data_seq, i); if (!info->valid_data) continue; /* see if there is any participant_data */ if (DDS_OctetSeq_get_length(&data->user_data.value) != 0) { /* This sequence is guaranteed to be contiguous */ participant_data = (char *) (DDS_OctetSeq_get_reference( &data->user_data.value, 0)); is_auth = (strcmp(participant_data, auth) == 0); } printf("Built-in Reader: found participant \n"); printf("\tkey->'%08x%08x%08x'\n\tuser_data->'%s'\n", data->key.value[0], data->key.value[1], data->key.value[2], participant_data); memcpy(ih, &info->instance_handle, sizeof(info->instance_handle)); printf("instance_handle: %08x%08x %08x%08x %08x%08x \n", ih[0], ih[1], ih[2], ih[3], ih[4], ih[5]); /* Ignore unauthorized subscribers */ if (!is_auth) { /* Get the associated participant... */ DDS_DomainParticipant *participant = NULL; DDS_Subscriber *subscriber = NULL; subscriber = DDS_DataReader_get_subscriber(reader); participant = DDS_Subscriber_get_participant(subscriber); printf("Bad authorization, ignoring participant\n"); /* Ignore the remote reader */ DDS_DomainParticipant_ignore_participant( participant, &info->instance_handle); } } retcode = DDS_ParticipantBuiltinTopicDataDataReader_return_loan( builtin_reader, &data_seq, &info_seq); if (retcode != DDS_RETCODE_OK) { printf("return loan error %d\n", retcode); } } /* This gets called when a new subscriber has been discovered */ void BuiltinSubscriberListener_on_data_available( void *listener_data, DDS_DataReader *reader) { DDS_SubscriptionBuiltinTopicDataDataReader *builtin_reader = NULL; struct DDS_SubscriptionBuiltinTopicDataSeq data_seq = DDS_SEQUENCE_INITIALIZER; struct DDS_SampleInfoSeq info_seq = DDS_SEQUENCE_INITIALIZER; DDS_ReturnCode_t retcode; int i; int len; int ih[6]; builtin_reader = DDS_SubscriptionBuiltinTopicDataDataReader_narrow(reader); /* We only process newly seen subscribers */ retcode = DDS_SubscriptionBuiltinTopicDataDataReader_take( builtin_reader, &data_seq, &info_seq, DDS_LENGTH_UNLIMITED, DDS_ANY_SAMPLE_STATE, DDS_NEW_VIEW_STATE, DDS_ANY_INSTANCE_STATE); if (retcode == DDS_RETCODE_NO_DATA) return; if (retcode != DDS_RETCODE_OK) { printf("***Error: failed to access data from the built-in reader\n"); return; } len = DDS_SubscriptionBuiltinTopicDataSeq_get_length(&data_seq); for (i = 0; i < len; ++i) { struct DDS_SampleInfo *info = NULL; struct DDS_SubscriptionBuiltinTopicData *data = NULL; info = DDS_SampleInfoSeq_get_reference(&info_seq, i); data = DDS_SubscriptionBuiltinTopicDataSeq_get_reference(&data_seq, i); if (!info->valid_data) continue; printf("Built-in Reader: found subscriber \n"); printf("\tparticipant_key->'%08x%08x%08x'\n", data->participant_key.value[0], data->participant_key.value[1], data->participant_key.value[2]); printf("\tkey->'%08x %08x %08x'\n", data->key.value[0], data->key.value[1], data->key.value[2]); memcpy(ih, &info->instance_handle, sizeof(info->instance_handle)); printf("instance_handle: %08x%08x %08x%08x %08x%08x \n", ih[0], ih[1], ih[2], ih[3], ih[4], ih[5]); } retcode = DDS_SubscriptionBuiltinTopicDataDataReader_return_loan( builtin_reader, &data_seq, &info_seq); if (retcode != DDS_RETCODE_OK) { printf("return loan error %d\n", retcode); } } /* 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 forpeople who want to release memory used by the participant factory. Uncomment the following block of code for clean destruction of the singleton. */ /* retcode = DDS_DomainParticipantFactory_finalize_instance(); if (retcode != DDS_RETCODE_OK) { printf("finalize_instance error %d\n", retcode); status = -1; } */ return status; } static int publisher_main(int domain_id, int sample_count) { DDS_DomainParticipant *participant = NULL; DDS_Publisher *publisher = NULL; DDS_Topic *topic = NULL; DDS_DataWriter *writer = NULL; msgDataWriter *msg_writer = NULL; msg *instance = NULL; DDS_ReturnCode_t retcode; DDS_InstanceHandle_t instance_handle = DDS_HANDLE_NIL; const char *type_name = NULL; int count = 0; struct DDS_Duration_t send_period = { 1, 0 }; DDS_DataReader *builtin_participant_datareader = NULL; struct DDS_DataReaderListener builtin_participant_listener = DDS_DataReaderListener_INITIALIZER; DDS_DataReader *builtin_subscriber_datareader = NULL; struct DDS_DataReaderListener builtin_subscriber_listener = DDS_DataReaderListener_INITIALIZER; DDS_Subscriber *builtin_subscriber = NULL; /* struct DDS_DomainParticipantFactoryQos factory_qos = DDS_DomainParticipantFactoryQos_INITIALIZER; struct DDS_DomainParticipantQos participant_qos = DDS_DomainParticipantQos_INITIALIZER; */ /* It is recommended to install built-in topic listeners on disabled * entities (EntityFactoryQoS). For this reason it is necessary to set * the autoenable_created_entities setting to false. To do this * programmatically, just uncomment the following code */ /* retcode = DDS_DomainParticipantFactory_get_qos(DDS_TheParticipantFactory, &factory_qos); if (retcode != DDS_RETCODE_OK) { printf("Cannot get factory Qos for domain participant\n"); return -1; } factory_qos.entity_factory.autoenable_created_entities = DDS_BOOLEAN_FALSE; switch(DDS_DomainParticipantFactory_set_qos(DDS_TheParticipantFactory, &factory_qos)) { case DDS_RETCODE_OK: break; case DDS_RETCODE_IMMUTABLE_POLICY: { printf("Cannot set factory Qos due to IMMUTABLE_POLICY"); printf(" for domain participant\n"); return -1; break; } case DDS_RETCODE_INCONSISTENT_POLICY: { printf("Cannot set factory Qos due to INCONSISTENT_POLICY "); printf("for domain participant\n"); return -1; break; } default: { printf("Cannot set factory Qos for unknown reason for domain "); printf("participant\n"); return -1; break; } } DDS_DomainParticipantFactoryQos_finalize(&factory_qos); */ /* The maximum length for USER_DATA QoS field is set by default to 256 bytes. To increase it programmatically uncomment the following lines of code and replace DDS_PARTICIPANT_QOS_DEFAULT with participant_qos in the constructor call. */ /* retcode = DDS_DomainParticipantFactory_get_default_participant_qos( DDS_TheParticipantFactory, &participant_qos); if (retcode != DDS_RETCODE_OK) { printf("get_default_participant_qos error\n"); return -1; } participant_qos.resource_limits.participant_user_data_max_length = 1024; */ /* 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; } /* Start changes for Builtin_Topics Installing listeners for the builtin topics requires several steps: */ /* * First, get the builtin subscriber */ builtin_subscriber = DDS_DomainParticipant_get_builtin_subscriber(participant); if (builtin_subscriber == NULL) { printf("***Error: failed to create builtin subscriber\n"); return -1; } /* * Then get builtin subscriber's datareader for participants */ builtin_participant_datareader = DDS_Subscriber_lookup_datareader( builtin_subscriber, DDS_PARTICIPANT_TOPIC_NAME); if (builtin_participant_datareader == NULL) { printf("***Error: failed to create builtin participant data reader\n"); return -1; } /* * Install our listener in the builtin datareader */ builtin_participant_listener.on_data_available = BuiltinParticipantListener_on_data_available; retcode = DDS_DataReader_set_listener( builtin_participant_datareader, &builtin_participant_listener, DDS_DATA_AVAILABLE_STATUS); if (retcode != DDS_RETCODE_OK) { printf("set_listener failed %d\n", retcode); return -1; } /* Now we repeat the same procedure for builtin subscription topics. */ /* * Get builtin subscriber's datareader for subscribers */ builtin_subscriber_datareader = DDS_Subscriber_lookup_datareader( builtin_subscriber, DDS_SUBSCRIPTION_TOPIC_NAME); if (builtin_subscriber_datareader == NULL) { printf("***Error: failed to create builtin subscription data reader\n"); return -1; } /* Install our listener */ builtin_subscriber_listener.on_data_available = BuiltinSubscriberListener_on_data_available; retcode = DDS_DataReader_set_listener( builtin_subscriber_datareader, &builtin_subscriber_listener, DDS_DATA_AVAILABLE_STATUS); if (retcode != DDS_RETCODE_OK) { printf("set_listener failed %d\n", retcode); return -1; } if (DDS_Entity_enable((DDS_Entity *) participant) != DDS_RETCODE_OK) { printf("***Error: Failed to Enable Participant\n"); return -1; } /* To customize publisher QoS, use the configuration file USER_QOS_PROFILES.xml */ publisher = DDS_DomainParticipant_create_publisher( participant, &DDS_PUBLISHER_QOS_DEFAULT, NULL /* listener */, DDS_STATUS_MASK_NONE); if (publisher == NULL) { printf("create_publisher error\n"); publisher_shutdown(participant); return -1; } /* Register type before creating topic */ type_name = msgTypeSupport_get_type_name(); retcode = msgTypeSupport_register_type(participant, type_name); if (retcode != DDS_RETCODE_OK) { printf("register_type error %d\n", retcode); publisher_shutdown(participant); return -1; } /* To customize topic QoS, use the configuration file USER_QOS_PROFILES.xml */ topic = DDS_DomainParticipant_create_topic( participant, "Example msg", type_name, &DDS_TOPIC_QOS_DEFAULT, NULL /* listener */, DDS_STATUS_MASK_NONE); if (topic == NULL) { printf("create_topic error\n"); publisher_shutdown(participant); return -1; } /* To customize data writer QoS, use 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; } msg_writer = msgDataWriter_narrow(writer); if (msg_writer == NULL) { printf("DataWriter narrow error\n"); publisher_shutdown(participant); return -1; } /* Create data sample for writing */ instance = msgTypeSupport_create_data_ex(DDS_BOOLEAN_TRUE); if (instance == NULL) { printf("msgTypeSupport_create_data error\n"); publisher_shutdown(participant); return -1; } /* For a data type that has a key, if the same instance is going to be written multiple times, initialize the key here and register the keyed instance prior to writing */ /* instance_handle = msgDataWriter_register_instance( msg_writer, instance); */ /* Main loop */ for (count = 0; (sample_count == 0) || (count < sample_count); ++count) { printf("Writing msg, count %d\n", count); /* Modify the data to be written here */ instance->x = count; /* Write data */ retcode = msgDataWriter_write(msg_writer, instance, &instance_handle); if (retcode != DDS_RETCODE_OK) { printf("write error %d\n", retcode); } NDDS_Utility_sleep(&send_period); } /* retcode = msgDataWriter_unregister_instance( msg_writer, instance, &instance_handle); if (retcode != DDS_RETCODE_OK) { printf("unregister instance error %d\n", retcode); } */ /* Delete data sample */ retcode = msgTypeSupport_delete_data_ex(instance, DDS_BOOLEAN_TRUE); if (retcode != DDS_RETCODE_OK) { printf("msgTypeSupport_delete_data error %d\n", retcode); } /* Cleanup and delete delete all entities */ return publisher_shutdown(participant); } int main(int argc, char *argv[]) { int domain_id = 0; int sample_count = 0; /* infinite loop */ if (argc >= 2) { domain_id = atoi(argv[1]); } if (argc >= 3) { sample_count = atoi(argv[2]); } /* Uncomment this to turn on additional logging NDDS_Config_Logger_set_verbosity_by_category( NDDS_Config_Logger_get_instance(), NDDS_CONFIG_LOG_CATEGORY_API, NDDS_CONFIG_LOG_VERBOSITY_STATUS_ALL); */ return publisher_main(domain_id, sample_count); }
c
rticonnextdds-examples
data/projects/rticonnextdds-examples/connext_dds/builtin_topics/c/msg_subscriber.c
/******************************************************************************* * (c) 2005-2014 Copyright, Real-Time Innovations, Inc. All rights reserved. * RTI grants Licensee a license to use, modify, compile, and create derivative * works of the Software. Licensee has the right to distribute object form * only for use with RTI products. The Software is provided "as is", with no * warranty of any type, including any warranty for fitness for any purpose. * RTI is under no obligation to maintain or support the Software. RTI shall * not be liable for any incidental or consequential damages arising out of the * use or inability to use the software. * ******************************************************************************/ /* msg_subscriber.c A subscription example This file is derived from code automatically generated by the rtiddsgen command: rtiddsgen -language C -example <arch> msg.idl Example subscription of type msg automatically generated by 'rtiddsgen'. To test them follow these steps: (1) Compile this file and the example publication. (2) Start the subscription on the same domain used for RTI Data Distribution Service with the command objs/<arch>/msg_subscriber <domain_id> <sample_count> (3) Start the publication on the same domain used for RTI Data Distribution Service with the command objs/<arch>/msg_publisher <domain_id> <sample_count> (4) [Optional] Specify the list of discovery initial peers and multicast receive addresses via an environment variable or a file (in the current working directory) called NDDS_DISCOVERY_PEERS. You can run any number of publishers and subscribers programs, and can add and remove them dynamically from the domain. Example: To run the example application on domain <domain_id>: On Unix: objs/<arch>/msg_publisher <domain_id> objs/<arch>/msg_subscriber <domain_id> On Windows: objs\<arch>\msg_publisher <domain_id> objs\<arch>\msg_subscriber <domain_id> modification history ------------ ------- * Set user_data QoS fields in participant and datareader with strings given on command line * Do not ignore data readers since it is a bad security practice. * Fix null char in participant user_data field. */ #include "msg.h" #include "msgSupport.h" #include "ndds/ndds_c.h" #include <stdio.h> #include <stdlib.h> void msgListener_on_requested_deadline_missed( void *listener_data, DDS_DataReader *reader, const struct DDS_RequestedDeadlineMissedStatus *status) { } void msgListener_on_requested_incompatible_qos( void *listener_data, DDS_DataReader *reader, const struct DDS_RequestedIncompatibleQosStatus *status) { } void msgListener_on_sample_rejected( void *listener_data, DDS_DataReader *reader, const struct DDS_SampleRejectedStatus *status) { } void msgListener_on_liveliness_changed( void *listener_data, DDS_DataReader *reader, const struct DDS_LivelinessChangedStatus *status) { } void msgListener_on_sample_lost( void *listener_data, DDS_DataReader *reader, const struct DDS_SampleLostStatus *status) { } void msgListener_on_subscription_matched( void *listener_data, DDS_DataReader *reader, const struct DDS_SubscriptionMatchedStatus *status) { } void msgListener_on_data_available(void *listener_data, DDS_DataReader *reader) { msgDataReader *msg_reader = NULL; struct msgSeq data_seq = DDS_SEQUENCE_INITIALIZER; struct DDS_SampleInfoSeq info_seq = DDS_SEQUENCE_INITIALIZER; DDS_ReturnCode_t retcode; int i; msg_reader = msgDataReader_narrow(reader); if (msg_reader == NULL) { printf("DataReader narrow error\n"); return; } retcode = msgDataReader_take( msg_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 < msgSeq_get_length(&data_seq); ++i) { if (DDS_SampleInfoSeq_get_reference(&info_seq, i)->valid_data) { msgTypeSupport_print_data(msgSeq_get_reference(&data_seq, i)); } } retcode = msgDataReader_return_loan(msg_reader, &data_seq, &info_seq); if (retcode != DDS_RETCODE_OK) { printf("return loan error %d\n", retcode); } } /* Delete all entities */ static int subscriber_shutdown(DDS_DomainParticipant *participant) { DDS_ReturnCode_t retcode; int status = 0; if (participant != NULL) { retcode = DDS_DomainParticipant_delete_contained_entities(participant); if (retcode != DDS_RETCODE_OK) { printf("delete_contained_entities error %d\n", retcode); status = -1; } retcode = DDS_DomainParticipantFactory_delete_participant( DDS_TheParticipantFactory, participant); if (retcode != DDS_RETCODE_OK) { printf("delete_participant error %d\n", retcode); status = -1; } } /* RTI Data Distribution Service provides the finalize_instance() method on domain participant factory for users who want to release memory used by the participant factory. Uncomment the following block of code for clean destruction of the singleton. */ /* retcode = DDS_DomainParticipantFactory_finalize_instance(); if (retcode != DDS_RETCODE_OK) { printf("finalize_instance error %d\n", retcode); status = -1; } */ return status; } static int subscriber_main(int domain_id, int sample_count, char *participant_auth) { DDS_DomainParticipant *participant = NULL; DDS_Subscriber *subscriber = NULL; DDS_Topic *topic = NULL; struct DDS_DataReaderListener reader_listener = DDS_DataReaderListener_INITIALIZER; DDS_DataReader *reader = NULL; DDS_ReturnCode_t retcode; const char *type_name = NULL; int count = 0; struct DDS_Duration_t poll_period = { 1, 0 }; struct DDS_DomainParticipantQos participant_qos = DDS_DomainParticipantQos_INITIALIZER; int len, max; retcode = DDS_DomainParticipantFactory_get_default_participant_qos( DDS_TheParticipantFactory, &participant_qos); if (retcode != DDS_RETCODE_OK) { printf("get_default_participant_qos error\n"); return -1; } /* The maximum length for USER_DATA QoS field is set by default to 256 bytes. To increase it programmatically uncomment the following line of code. */ /* participant_qos.resource_limits.participant_user_data_max_length = 1024; */ /* We include the subscriber credentials into de USER_DATA QoS. */ len = strlen(participant_auth) + 1; max = participant_qos.resource_limits.participant_user_data_max_length; if (len > max) { printf("error, participant user_data exceeds resource limits\n"); } else { /* * DDS_Octet is defined to be 8 bits. If chars are not 8 bits * on your system, this will not work. */ DDS_OctetSeq_from_array( &participant_qos.user_data.value, (DDS_Octet *) (participant_auth), len); } /* To customize participant QoS, use the configuration file USER_QOS_PROFILES.xml */ participant = DDS_DomainParticipantFactory_create_participant( DDS_TheParticipantFactory, domain_id, &participant_qos, NULL /* listener */, DDS_STATUS_MASK_NONE); if (participant == NULL) { printf("create_participant error\n"); subscriber_shutdown(participant); return -1; } /* Done! All the listeners are installed, so we can enable the * participant now. */ if (DDS_Entity_enable((DDS_Entity *) participant) != DDS_RETCODE_OK) { printf("***Error: Failed to Enable Participant\n"); 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 = msgTypeSupport_get_type_name(); retcode = msgTypeSupport_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 msg", 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 = msgListener_on_requested_deadline_missed; reader_listener.on_requested_incompatible_qos = msgListener_on_requested_incompatible_qos; reader_listener.on_sample_rejected = msgListener_on_sample_rejected; reader_listener.on_liveliness_changed = msgListener_on_liveliness_changed; reader_listener.on_sample_lost = msgListener_on_sample_lost; reader_listener.on_subscription_matched = msgListener_on_subscription_matched; reader_listener.on_data_available = msgListener_on_data_available; /* To customize data reader QoS, use the configuration file USER_QOS_PROFILES.xml */ reader = DDS_Subscriber_create_datareader( subscriber, DDS_Topic_as_topicdescription(topic), &DDS_DATAREADER_QOS_DEFAULT, &reader_listener, DDS_STATUS_MASK_ALL); if (reader == NULL) { printf("create_datareader error\n"); subscriber_shutdown(participant); return -1; } /* Main loop */ for (count = 0; (sample_count == 0) || (count < sample_count); ++count) { /* printf("msg 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 sample_count = 0; /* infinite loop */ /* * Changes for Builtin_Topics * Get arguments for auth strings and pass to subscriber_main() */ char *participant_auth = "password"; if (argc >= 2) { domain_id = atoi(argv[1]); } if (argc >= 3) { sample_count = atoi(argv[2]); } if (argc >= 4) { participant_auth = argv[3]; } /* Uncomment this to turn on additional logging NDDS_Config_Logger_set_verbosity_by_category( NDDS_Config_Logger_get_instance(), NDDS_CONFIG_LOG_CATEGORY_API, NDDS_CONFIG_LOG_VERBOSITY_STATUS_ALL); */ subscriber_main(domain_id, sample_count, participant_auth); return 0; }
c
rticonnextdds-examples
data/projects/rticonnextdds-examples/connext_dds/builtin_topics/c++03/msg_publisher.cxx
/******************************************************************************* (c) 2005-2015 Copyright, Real-Time Innovations, Inc. All rights reserved. RTI grants Licensee a license to use, modify, compile, and create derivative works of the Software. Licensee has the right to distribute object form only for use with RTI products. The Software is provided "as is", with no warranty of any type, including any warranty for fitness for any purpose. RTI is under no obligation to maintain or support the Software. RTI shall not be liable for any incidental or consequential damages arising out of the use or inability to use the software. ******************************************************************************/ #include <algorithm> #include <iomanip> #include <iostream> #include <list> #include <string> #include "msg.hpp" #include <dds/dds.hpp> #include <rti/core/ListenerBinder.hpp> using namespace dds::core; using namespace dds::core::policy; using namespace rti::core::policy; using namespace dds::domain; using namespace dds::domain::qos; using namespace dds::topic; using namespace dds::sub; using namespace dds::pub; // Authorization string const std::string expected_password = "password"; // The builtin subscriber sets participant_qos.user_data, so we set up listeners // for the builtin DataReaders to access these fields. class BuiltinParticipantListener : public NoOpDataReaderListener<ParticipantBuiltinTopicData> { public: // This gets called when a participant has been discovered void on_data_available(DataReader<ParticipantBuiltinTopicData> &reader) { // We only process newly seen participants LoanedSamples<ParticipantBuiltinTopicData> samples = reader.select() .state(dds::sub::status::DataState::new_instance()) .take(); for (LoanedSamples<ParticipantBuiltinTopicData>::iterator sampleIt = samples.begin(); sampleIt != samples.end(); ++sampleIt) { if (!sampleIt->info().valid()) { continue; } const ByteSeq &user_data = sampleIt->data().user_data().value(); std::string user_auth(user_data.begin(), user_data.end()); std::ios::fmtflags default_format(std::cout.flags()); std::cout << std::hex << std::setw(8) << std::setfill('0'); const BuiltinTopicKey &key = sampleIt->data().key(); std::cout << "Built-in Reader: found participant" << std::endl << "\tkey->'" << key.value()[0] << " " << key.value()[1] << " " << key.value()[2] << "'" << std::endl << "\tuser_data->'" << user_auth << "'" << std::endl << "\tinstance_handle: " << sampleIt->info().instance_handle() << std::endl; std::cout.flags(default_format); // Check if the password match. Otherwise, ignore the participant. if (user_auth != expected_password) { std::cout << "Bad authorization, ignoring participant" << std::endl; // Get the associated participant... DomainParticipant participant = reader.subscriber().participant(); // Ignore the remote participant dds::domain::ignore( participant, sampleIt->info().instance_handle()); } } } }; class BuiltinSubscriberListener : public NoOpDataReaderListener<SubscriptionBuiltinTopicData> { public: // This gets called when a subscriber has been discovered void on_data_available(DataReader<SubscriptionBuiltinTopicData> &reader) { // We only process newly seen subscribers LoanedSamples<SubscriptionBuiltinTopicData> samples = reader.select() .state(dds::sub::status::DataState::new_instance()) .take(); for (LoanedSamples<SubscriptionBuiltinTopicData>::iterator sampleIt = samples.begin(); sampleIt != samples.end(); ++sampleIt) { if (!sampleIt->info().valid()) { continue; } std::ios::fmtflags default_format(std::cout.flags()); std::cout << std::hex << std::setw(8) << std::setfill('0'); const BuiltinTopicKey &partKey = sampleIt->data().participant_key(); const BuiltinTopicKey &key = sampleIt->data().key(); std::cout << "Built-in Reader: found subscriber" << std::endl << "\tparticipant_key->'" << partKey.value()[0] << " " << partKey.value()[1] << " " << partKey.value()[2] << "'" << std::endl << "\tkey->'" << key.value()[0] << " " << key.value()[1] << " " << key.value()[2] << "'" << std::endl << "\tinstance_handle: " << sampleIt->info().instance_handle() << std::endl; std::cout.flags(default_format); } } }; void publisher_main(int domain_id, int sample_count) { // By default, the participant is enabled upon construction. // At that time our listeners for the builtin topics have not // been installed, so we disable the participant until we // set up the listeners. This is done by default in the // USER_QOS_PROFILES.xml file. If you want to do it programmatically, // just uncomment the following code. // DomainParticipantFactoryQos factoryQos = // DomainParticipant::participant_factory_qos(); // factoryQos << EntityFactory::ManuallyEnable(); // DomainParticipant::participant_factory_qos(factoryQos); // If you want to change the Participant's QoS programmatically rather than // using the XML file, you will need to comment out these lines and pass // the variable participant_qos as second argument in the constructor call. // DomainParticipantQos participant_qos = QosProvider::Default() // .participant_qos(); // DomainParticipantResourceLimits resource_limits_qos; // resource_limits_qos.participant_user_data_max_length(1024); // participant_qos << resource_limits_qos; // Create a DomainParticipant with default Qos. DomainParticipant participant(domain_id); // Installing listeners for the builtin topics requires several steps // First get the builtin subscriber. Subscriber builtin_subscriber = dds::sub::builtin_subscriber(participant); // Then get builtin subscriber's datareader for participants. std::vector<DataReader<ParticipantBuiltinTopicData> > participant_reader; find<DataReader<ParticipantBuiltinTopicData> >( builtin_subscriber, dds::topic::participant_topic_name(), std::back_inserter(participant_reader)); // Install our listener using ListenerBinder, a RAII that will take care // of setting it to NULL and deleting it. rti::core::ListenerBinder<DataReader<ParticipantBuiltinTopicData> > participant_listener = rti::core::bind_and_manage_listener( participant_reader[0], new BuiltinParticipantListener, dds::core::status::StatusMask::data_available()); // Get builtin subscriber's datareader for subscribers. std::vector<DataReader<SubscriptionBuiltinTopicData> > subscription_reader; find<DataReader<SubscriptionBuiltinTopicData> >( builtin_subscriber, dds::topic::subscription_topic_name(), std::back_inserter(subscription_reader)); // Install our listener using ListenerBinder. rti::core::ListenerBinder<DataReader<SubscriptionBuiltinTopicData> > subscriber_listener = rti::core::bind_and_manage_listener( subscription_reader[0], new BuiltinSubscriberListener, dds::core::status::StatusMask::data_available()); // Done! All the listeners are installed, so we can enable the // participant now. participant.enable(); // Create a Topic -- and automatically register the type. Topic<msg> topic(participant, "Example msg"); // Create a DataWriter DataWriter<msg> writer(Publisher(participant), topic); // Create data sample for writing msg instance; // 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 InstanceHandle instance_handle = InstanceHandle::nil(); // instance_handle = writer.register_instance(instance); // Main loop for (short count = 0; (sample_count == 0) || (count < sample_count); ++count) { rti::util::sleep(Duration(1)); std::cout << "Writing msg, count " << count << std::endl; // Modify the data to be sent here instance.x(count); writer.write(instance, instance_handle); } // writer.unregister_instance(instance); } 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_topics/c++03/msg_subscriber.cxx
/******************************************************************************* (c) 2005-2015 Copyright, Real-Time Innovations, Inc. All rights reserved. RTI grants Licensee a license to use, modify, compile, and create derivative works of the Software. Licensee has the right to distribute object form only for use with RTI products. The Software is provided "as is", with no warranty of any type, including any warranty for fitness for any purpose. RTI is under no obligation to maintain or support the Software. RTI shall not be liable for any incidental or consequential damages arising out of the use or inability to use the software. ******************************************************************************/ #include <iostream> #include <string> #include "msg.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 rti::core::policy; using namespace dds::domain; using namespace dds::domain::qos; using namespace dds::topic; using namespace dds::sub; using namespace dds::sub::qos; class MsgListener : public NoOpDataReaderListener<msg> { public: void on_data_available(DataReader<msg> &reader) { LoanedSamples<msg> samples = reader.take(); for (LoanedSamples<msg>::iterator sampleIt = samples.begin(); sampleIt != samples.end(); ++sampleIt) { if (sampleIt->info().valid()) { std::cout << sampleIt->data() << std::endl; } } } }; void subscriber_main( int domain_id, int sample_count, std::string participant_auth) { // Retrieve the default participant QoS, from USER_QOS_PROFILES.xml DomainParticipantQos participant_qos = QosProvider::Default().participant_qos(); DomainParticipantResourceLimits resource_limits_qos = participant_qos.policy<DomainParticipantResourceLimits>(); // If you want to change the Participant's QoS programmatically rather // than using the XML file, you will need to comment out these lines. // resource_limits_qos.participant_user_data_max_length(1024); // participant_qos << resource_limits_qos; unsigned int max_participant_user_data = resource_limits_qos.participant_user_data_max_length(); if (participant_auth.size() > max_participant_user_data) { std::cout << "error, participant user_data exceeds resource limits" << std::endl; } else { participant_qos << UserData( ByteSeq(participant_auth.begin(), participant_auth.end())); } // Create a DomainParticipant. DomainParticipant participant(domain_id, participant_qos); // Participant is disabled by default in USER_QOS_PROFILES. We enable it now participant.enable(); // Create a Topic -- and automatically register the type. Topic<msg> topic(participant, "Example msg"); // Create a DataReader DataReader<msg> reader(Subscriber(participant), topic); // Create a data reader listener using ListenerBinder, a RAII utility that // will take care of reseting it from the reader and deleting it. ListenerBinder<DataReader<msg> > scoped_listener = bind_and_manage_listener( reader, new MsgListener, dds::core::status::StatusMask::data_available()); // Main loop for (int count = 0; (sample_count == 0) || (count < sample_count); ++count) { // Each "sample_count" is one second. rti::util::sleep(Duration(1)); } } int main(int argc, char *argv[]) { int domain_id = 0; int sample_count = 0; // Infinite loop // Changes for Builtin_Topics // Get arguments for auth strings and pass to subscriber_main() std::string participant_auth = "password"; if (argc >= 2) { domain_id = atoi(argv[1]); } if (argc >= 3) { sample_count = atoi(argv[2]); } if (argc >= 4) { participant_auth = argv[3]; } // To turn on additional logging, include <rti/config/Logger.hpp> and // uncomment the following line: // rti::config::Logger::instance().verbosity(rti::config::Verbosity::STATUS_ALL); try { subscriber_main(domain_id, sample_count, participant_auth); } 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_topics/c++11/application.hpp
/* * (c) Copyright, Real-Time Innovations, 2020. All rights reserved. * RTI grants Licensee a license to use, modify, compile, and create derivative * works of the software solely for use with RTI Connext DDS. Licensee may * redistribute copies of the software provided that all such copies are subject * to this license. The software is provided "as is", with no warranty of any * type, including any warranty for fitness for any purpose. RTI is under no * obligation to maintain or support the software. RTI shall not be liable for * any incidental or consequential damages arising out of the use or inability * to use the software. */ #ifndef APPLICATION_HPP #define APPLICATION_HPP #include <iostream> #include <csignal> #include <dds/core/ddscore.hpp> namespace application { // Catch control-C and tell application to shut down bool shutdown_requested = false; inline void stop_handler(int) { shutdown_requested = true; std::cout << "preparing to shut down..." << std::endl; } inline void setup_signal_handlers() { signal(SIGINT, stop_handler); signal(SIGTERM, stop_handler); } enum class ParseReturn { ok, failure, exit }; enum class ApplicationKind { publisher, subscriber }; struct ApplicationArguments { ParseReturn parse_result; unsigned int domain_id; unsigned int sample_count; rti::config::Verbosity verbosity; std::string participant_password; std::string reader_password; ApplicationArguments( ParseReturn parse_result_param, unsigned int domain_id_param, unsigned int sample_count_param, rti::config::Verbosity verbosity_param, std::string participant_password_param, std::string reader_password_param) : parse_result(parse_result_param), domain_id(domain_id_param), sample_count(sample_count_param), verbosity(verbosity_param), participant_password(participant_password_param), reader_password(reader_password_param) { } }; inline void set_verbosity( rti::config::Verbosity &verbosity, int verbosity_value) { switch (verbosity_value) { case 0: verbosity = rti::config::Verbosity::SILENT; break; case 1: verbosity = rti::config::Verbosity::EXCEPTION; break; case 2: verbosity = rti::config::Verbosity::WARNING; break; case 3: verbosity = rti::config::Verbosity::STATUS_ALL; break; default: verbosity = rti::config::Verbosity::EXCEPTION; break; } } // Parses application arguments for example. inline ApplicationArguments parse_arguments( int argc, char *argv[], ApplicationKind current_application) { 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); std::string participant_password = "password"; std::string reader_password = "Reader_Auth"; while (arg_processing < argc) { if ((argc > arg_processing + 1) && (strcmp(argv[arg_processing], "-d") == 0 || strcmp(argv[arg_processing], "--domain") == 0)) { domain_id = atoi(argv[arg_processing + 1]); arg_processing += 2; } else if ( (argc > arg_processing + 1) && (strcmp(argv[arg_processing], "-s") == 0 || strcmp(argv[arg_processing], "--sample-count") == 0)) { sample_count = atoi(argv[arg_processing + 1]); arg_processing += 2; } else if ( (argc > arg_processing + 1) && current_application == ApplicationKind::subscriber && (strcmp(argv[arg_processing], "-pa") == 0 || strcmp(argv[arg_processing], "--pauth") == 0)) { participant_password = argv[arg_processing + 1]; arg_processing += 2; } else if ( (argc > arg_processing + 1) && current_application == ApplicationKind::subscriber && (strcmp(argv[arg_processing], "-ra") == 0 || strcmp(argv[arg_processing], "--rauth") == 0)) { reader_password = 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\n"; if (current_application == ApplicationKind::subscriber) std::cout << " -pa, --pauth <string> The participant " "authorization string. \n" " Default: \"password\"\n" " -ra, --rauth <string> The reader " "authorization string. \n" " Default: \"Reader_Auth\"" << std::endl; } return ApplicationArguments( parse_result, domain_id, sample_count, verbosity, participant_password, reader_password); } } // namespace application #endif // APPLICATION_HPP
hpp
rticonnextdds-examples
data/projects/rticonnextdds-examples/connext_dds/builtin_topics/c++11/msg_publisher.cxx
/******************************************************************************* (c) 2005-2015 Copyright, Real-Time Innovations, Inc. All rights reserved. RTI grants Licensee a license to use, modify, compile, and create derivative works of the Software. Licensee has the right to distribute object form only for use with RTI products. The Software is provided "as is", with no warranty of any type, including any warranty for fitness for any purpose. RTI is under no obligation to maintain or support the Software. RTI shall not be liable for any incidental or consequential damages arising out of the use or inability to use the software. ******************************************************************************/ #include <algorithm> #include <iomanip> #include <iostream> #include <list> #include <string> #include <dds/domain/discovery.hpp> #include <dds/sub/ddssub.hpp> #include <dds/pub/ddspub.hpp> #include <rti/util/util.hpp> // for sleep() #include <rti/config/Logger.hpp> // for logging #include "msg.hpp" #include "application.hpp" // Authorization string const std::string expected_password = "password"; // The builtin subscriber sets participant_qos.user_data, so we set up listeners // for the builtin DataReaders to access these fields. class BuiltinParticipantListener : public dds::sub::NoOpDataReaderListener< dds::topic::ParticipantBuiltinTopicData> { public: // This gets called when a participant has been discovered void on_data_available( dds::sub::DataReader<dds::topic::ParticipantBuiltinTopicData> &reader) { // We only process newly seen participants dds::sub::LoanedSamples<dds::topic::ParticipantBuiltinTopicData> samples = reader.select() .state(dds::sub::status::DataState:: new_instance()) .take(); for (const auto &sample : samples) { if (!sample.info().valid()) { continue; } const dds::core::ByteSeq &user_data = sample.data().user_data().value(); std::string user_auth(user_data.begin(), user_data.end()); std::ios::fmtflags default_format(std::cout.flags()); std::cout << std::hex << std::setw(8) << std::setfill('0'); const dds::topic::BuiltinTopicKey &key = sample.data().key(); std::cout << "Built-in Reader: found participant" << std::endl << "\tkey->'" << key.value()[0] << " " << key.value()[1] << " " << key.value()[2] << "'" << std::endl << "\tuser_data->'" << user_auth << "'" << std::endl << "\tinstance_handle: " << sample.info().instance_handle() << std::endl; std::cout.flags(default_format); // Check if the password match. Otherwise, ignore the participant. if (user_auth != expected_password) { std::cout << "Bad authorization, ignoring participant" << std::endl; // Get the associated participant... dds::domain::DomainParticipant participant = reader.subscriber().participant(); // Ignore the remote participant dds::domain::ignore( participant, sample->info().instance_handle()); } } } }; class BuiltinSubscriberListener : public dds::sub::NoOpDataReaderListener< dds::topic::SubscriptionBuiltinTopicData> { public: // This gets called when a subscriber has been discovered void on_data_available( dds::sub::DataReader<dds::topic::SubscriptionBuiltinTopicData> &reader) { // We only process newly seen subscribers dds::sub::LoanedSamples<dds::topic::SubscriptionBuiltinTopicData> samples = reader.select() .state(dds::sub::status::DataState:: new_instance()) .take(); for (const auto &sample : samples) { if (!sample.info().valid()) { continue; } std::ios::fmtflags default_format(std::cout.flags()); std::cout << std::hex << std::setw(8) << std::setfill('0'); const dds::topic::BuiltinTopicKey &partKey = sample.data().participant_key(); const dds::topic::BuiltinTopicKey &key = sample.data().key(); std::cout << "Built-in Reader: found subscriber" << std::endl << "\tparticipant_key->'" << partKey.value()[0] << " " << partKey.value()[1] << " " << partKey.value()[2] << "'" << std::endl << "\tkey->'" << key.value()[0] << " " << key.value()[1] << " " << key.value()[2] << "'" << std::endl << "\tinstance_handle: " << sample.info().instance_handle() << std::endl; std::cout.flags(default_format); } } }; void run_publisher_application( unsigned int domain_id, unsigned int sample_count) { // By default, the participant is enabled upon construction. // At that time our listeners for the builtin topics have not // been installed, so we disable the participant until we // set up the listeners. This is done by default in the // USER_QOS_PROFILES.xml file. If you want to do it programmatically, // just uncomment the following code. // DomainParticipantFactoryQos factoryQos = // DomainParticipant::participant_factory_qos(); // factoryQos << EntityFactory::ManuallyEnable(); // DomainParticipant::participant_factory_qos(factoryQos); // If you want to change the Participant's QoS programmatically rather than // using the XML file, you will need to comment out these lines and pass // the variable participant_qos as second argument in the constructor call. // DomainParticipantQos participant_qos = QosProvider::Default() // .participant_qos(); // DomainParticipantResourceLimits resource_limits_qos; // resource_limits_qos.participant_user_data_max_length(1024); // participant_qos << resource_limits_qos; // Create a DomainParticipant with default Qos. dds::domain::DomainParticipant participant(domain_id); // Installing listeners for the builtin topics requires several steps // First get the builtin subscriber. dds::sub::Subscriber builtin_subscriber = dds::sub::builtin_subscriber(participant); // Create shared pointer to BuiltinParticipantListener class auto participant_listener = std::make_shared<BuiltinParticipantListener>(); // Then get builtin subscriber's datareader for participants. std::vector<dds::sub::DataReader<dds::topic::ParticipantBuiltinTopicData>> participant_reader; dds::sub::find< dds::sub::DataReader<dds::topic::ParticipantBuiltinTopicData>>( builtin_subscriber, dds::topic::participant_topic_name(), std::back_inserter(participant_reader)); participant_reader[0].set_listener(participant_listener); auto subscriber_listener = std::make_shared<BuiltinSubscriberListener>(); // Get builtin subscriber's datareader for subscribers. std::vector<dds::sub::DataReader<dds::topic::SubscriptionBuiltinTopicData>> subscription_reader; dds::sub::find< dds::sub::DataReader<dds::topic::SubscriptionBuiltinTopicData>>( builtin_subscriber, dds::topic::subscription_topic_name(), std::back_inserter(subscription_reader)); // Install our listener using the shared pointer. subscription_reader[0].set_listener(subscriber_listener); // Done! All the listeners are installed, so we can enable the // participant now. participant.enable(); // Create a Topic -- and automatically register the type. dds::topic::Topic<msg> topic(participant, "Example msg"); // Create a publisher dds::pub::Publisher publisher(participant); // Create a DataWriter dds::pub::DataWriter<msg> writer(publisher, topic); // Create data sample for writing msg instance; // 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 dds::core::InstanceHandle instance_handle = dds::core::InstanceHandle::nil(); // instance_handle = writer.register_instance(instance); // Main loop for (unsigned int samples_written = 0; !application::shutdown_requested && samples_written < sample_count; samples_written++) { std::cout << "Writing msg, count " << samples_written << std::endl; // Send count as data instance.x(samples_written); // Send it, if using instance_handle: // writer.write(instance, instance_handle); writer.write(instance); // Send once every second rti::util::sleep(dds::core::Duration(1)); } // writer.unregister_instance(instance); } int main(int argc, char *argv[]) { using namespace application; // Parse arguments and handle control-C auto arguments = parse_arguments(argc, argv, ApplicationKind::publisher); if (arguments.parse_result == ParseReturn::exit) { return EXIT_SUCCESS; } else if (arguments.parse_result == ParseReturn::failure) { return EXIT_FAILURE; } setup_signal_handlers(); // Sets Connext verbosity to help debugging rti::config::Logger::instance().verbosity(arguments.verbosity); try { run_publisher_application(arguments.domain_id, arguments.sample_count); } catch (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/builtin_topics/c++11/msg_subscriber.cxx
/******************************************************************************* (c) 2005-2015 Copyright, Real-Time Innovations, Inc. All rights reserved. RTI grants Licensee a license to use, modify, compile, and create derivative works of the Software. Licensee has the right to distribute object form only for use with RTI products. The Software is provided "as is", with no warranty of any type, including any warranty for fitness for any purpose. RTI is under no obligation to maintain or support the Software. RTI shall not be liable for any incidental or consequential damages arising out of the use or inability to use the software. ******************************************************************************/ #include <dds/sub/ddssub.hpp> #include <dds/core/ddscore.hpp> #include <rti/config/Logger.hpp> // for logging #include "msg.hpp" #include "application.hpp" int process_data(dds::sub::DataReader<msg> reader) { int count = 0; dds::sub::LoanedSamples<msg> samples = reader.take(); for (const auto &sample : samples) { if (sample.info().valid()) { count++; std::cout << sample.data() << std::endl; } } return count; } // The LoanedSamples destructor returns the loan void run_subscriber_application( unsigned int domain_id, unsigned int sample_count, std::string participant_auth) { // Retrieve the default participant QoS, from USER_QOS_PROFILES.xml dds::domain::qos::DomainParticipantQos participant_qos = dds::core::QosProvider::Default().participant_qos(); auto resource_limits_qos = participant_qos.policy< rti::core::policy::DomainParticipantResourceLimits>(); // If you want to change the Participant's QoS programmatically rather // than using the XML file, you will need to comment out these lines. // resource_limits_qos.participant_user_data_max_length(1024); // participant_qos << resource_limits_qos; unsigned int max_participant_user_data = resource_limits_qos.participant_user_data_max_length(); if (participant_auth.size() > max_participant_user_data) { std::cout << "error, participant user_data exceeds resource limits" << std::endl; } else { participant_qos << dds::core::policy::UserData(dds::core::ByteSeq( participant_auth.begin(), participant_auth.end())); } // Create a DomainParticipant. dds::domain::DomainParticipant participant(domain_id, participant_qos); // Participant is disabled by default in USER_QOS_PROFILES. We enable it now participant.enable(); // Create a Topic -- and automatically register the type. dds::topic::Topic<msg> topic(participant, "Example msg"); // Create a DataReader with default QoS // Create a Subscriber and DataReader with default Qos dds::sub::Subscriber subscriber(participant); dds::sub::DataReader<msg> reader(subscriber, topic); // WaitSet will be woken when the attached condition is triggered dds::core::cond::WaitSet waitset; // Create a ReadCondition for any data on this reader, and add to WaitSet unsigned int samples_read = 0; dds::sub::cond::ReadCondition read_condition( reader, dds::sub::status::DataState::any(), [reader, &samples_read]() { samples_read += process_data(reader); }); waitset += read_condition; // Main loop while (!application::shutdown_requested && samples_read < sample_count) { std::cout << "builtin_topics subscriber sleeping for 1 sec...\n"; // 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, ApplicationKind::subscriber); if (arguments.parse_result == ParseReturn::exit) { return EXIT_SUCCESS; } else if (arguments.parse_result == ParseReturn::failure) { return EXIT_FAILURE; } setup_signal_handlers(); // Sets Connext verbosity to help debugging rti::config::Logger::instance().verbosity(arguments.verbosity); try { run_subscriber_application( arguments.domain_id, arguments.sample_count, arguments.participant_password); } 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/content_filtered_topic/c++/cft_publisher.cxx
/******************************************************************************* (c) 2005-2014 Copyright, Real-Time Innovations, Inc. All rights reserved. RTI grants Licensee a license to use, modify, compile, and create derivative works of the Software. Licensee has the right to distribute object form only for use with RTI products. The Software is provided "as is", with no warranty of any type, including any warranty for fitness for any purpose. RTI is under no obligation to maintain or support the Software. RTI shall not be liable for any incidental or consequential damages arising out of the use or inability to use the software. ******************************************************************************/ /* cft_publisher.cxx A publication of data of type cft This file is derived from code automatically generated by the rtiddsgen command: rtiddsgen -language C++ -example <arch> cft.idl Example publication of type cft automatically generated by 'rtiddsgen'. To test them follow these steps: (1) Compile this file and the example subscription. (2) Start the subscription with the command objs/<arch>/cft_subscriber <domain_id> <sample_count> (3) Start the publication with the command objs/<arch>/cft_publisher <domain_id> <sample_count> (4) [Optional] Specify the list of discovery initial peers and multicast receive addresses via an environment variable or a file (in the current working directory) called NDDS_DISCOVERY_PEERS. You can run any number of publishers and subscribers programs, and can add and remove them dynamically from the domain. Example: To run the example application on domain <domain_id>: On Unix: objs/<arch>/cft_publisher <domain_id> o objs/<arch>/cft_subscriber <domain_id> On Windows: objs\<arch>\cft_publisher <domain_id> objs\<arch>\cft_subscriber <domain_id> modification history ------------ ------- */ #include <stdio.h> #include <stdlib.h> #ifdef RTI_VX653 #include <vThreadsData.h> #endif #include "cft.h" #include "cftSupport.h" #include "ndds/ndds_cpp.h" /* Delete all entities */ static int publisher_shutdown(DDSDomainParticipant *participant) { DDS_ReturnCode_t retcode; int status = 0; if (participant != NULL) { retcode = participant->delete_contained_entities(); if (retcode != DDS_RETCODE_OK) { printf("delete_contained_entities error %d\n", retcode); status = -1; } retcode = DDSTheParticipantFactory->delete_participant(participant); if (retcode != DDS_RETCODE_OK) { printf("delete_participant error %d\n", retcode); status = -1; } } /* RTI Connext provides finalize_instance() method on domain participant factory for people who want to release memory used by the participant factory. Uncomment the following block of code for clean destruction of the singleton. */ /* retcode = DDSDomainParticipantFactory::finalize_instance(); if (retcode != DDS_RETCODE_OK) { printf("finalize_instance error %d\n", retcode); status = -1; } */ return status; } extern "C" int publisher_main(int domainId, int sample_count) { DDSDomainParticipant *participant = NULL; DDSPublisher *publisher = NULL; DDSTopic *topic = NULL; DDSDataWriter *writer = NULL; cftDataWriter *cft_writer = NULL; cft *instance = NULL; DDS_ReturnCode_t retcode; DDS_InstanceHandle_t instance_handle = DDS_HANDLE_NIL; const char *type_name = NULL; int count = 0; /* Send a new sample every second */ DDS_Duration_t send_period = { 1, 0 }; /* To customize participant QoS, use the configuration file USER_QOS_PROFILES.xml */ participant = DDSTheParticipantFactory->create_participant( domainId, DDS_PARTICIPANT_QOS_DEFAULT, NULL /* listener */, DDS_STATUS_MASK_NONE); if (participant == NULL) { printf("create_participant error\n"); publisher_shutdown(participant); return -1; } /* To customize publisher QoS, use the configuration file USER_QOS_PROFILES.xml */ publisher = participant->create_publisher( DDS_PUBLISHER_QOS_DEFAULT, NULL /* listener */, DDS_STATUS_MASK_NONE); if (publisher == NULL) { printf("create_publisher error\n"); publisher_shutdown(participant); return -1; } /* Register type before creating topic */ type_name = cftTypeSupport::get_type_name(); retcode = cftTypeSupport::register_type(participant, type_name); if (retcode != DDS_RETCODE_OK) { printf("register_type error %d\n", retcode); publisher_shutdown(participant); return -1; } /* To customize topic QoS, use the configuration file USER_QOS_PROFILES.xml */ topic = participant->create_topic( "Example cft", type_name, DDS_TOPIC_QOS_DEFAULT, NULL /* listener */, DDS_STATUS_MASK_NONE); if (topic == NULL) { printf("create_topic error\n"); publisher_shutdown(participant); return -1; } /* To customize data writer QoS, use the configuration file USER_QOS_PROFILES.xml */ writer = publisher->create_datawriter( topic, DDS_DATAWRITER_QOS_DEFAULT, NULL, DDS_STATUS_MASK_NONE); if (writer == NULL) { printf("create_datawriter error\n"); publisher_shutdown(participant); return -1; } /* If you want to set the reliability and history QoS settings * programmatically rather than using the XML, you will need to add * the following lines to your code and comment out the create_datawriter * call above. */ /* DDS_DataWriterQos datawriter_qos; retcode = publisher->get_default_datawriter_qos(datawriter_qos); if (retcode != DDS_RETCODE_OK) { printf("get_default_datawriter_qos error\n"); return -1; } datawriter_qos.reliability.kind = DDS_RELIABLE_RELIABILITY_QOS; datawriter_qos.durability.kind = DDS_TRANSIENT_LOCAL_DURABILITY_QOS; datawriter_qos.history.kind = DDS_KEEP_LAST_HISTORY_QOS; datawriter_qos.history.depth = 20; writer = publisher->create_datawriter( topic, datawriter_qos, NULL, DDS_STATUS_MASK_NONE); if (writer == NULL) { printf("create_datawriter error\n"); publisher_shutdown(participant); return -1; } */ cft_writer = cftDataWriter::narrow(writer); if (cft_writer == NULL) { printf("DataWriter narrow error\n"); publisher_shutdown(participant); return -1; } /* Create data sample for writing */ instance = cftTypeSupport::create_data(); if (instance == NULL) { printf("cftTypeSupport::create_data error\n"); publisher_shutdown(participant); return -1; } /* For a data type that has a key, if the same instance is going to be written multiple times, initialize the key here and register the keyed instance prior to writing */ /* instance_handle = cft_writer->register_instance(*instance); */ /* Main loop */ for (count = 0; (sample_count == 0) || (count < sample_count); ++count) { /* Modify the data to be sent here */ /* Our purpose is to increment x every time we send a sample and to * reset the x counter to 0 every time we send 10 samples (x=0,1,..,9). * Using the value of count, we can get set x to the appropriate value * applying % 10 operation to it. */ instance->count = count; instance->x = count % 10; printf("Writing cft, count %d\tx=%d\n", instance->count, instance->x); retcode = cft_writer->write(*instance, instance_handle); if (retcode != DDS_RETCODE_OK) { printf("write error %d\n", retcode); } NDDSUtility::sleep(send_period); } /* retcode = cft_writer->unregister_instance( *instance, instance_handle); if (retcode != DDS_RETCODE_OK) { printf("unregister instance error %d\n", retcode); } */ /* Delete data sample */ retcode = cftTypeSupport::delete_data(instance); if (retcode != DDS_RETCODE_OK) { printf("cftTypeSupport::delete_data error %d\n", retcode); } /* Delete all entities */ return publisher_shutdown(participant); } #if defined(RTI_WINCE) int wmain(int argc, wchar_t **argv) { int domainId = 0; int sample_count = 0; /* infinite loop */ if (argc >= 2) { domainId = _wtoi(argv[1]); } if (argc >= 3) { sample_count = _wtoi(argv[2]); } /* Uncomment this to turn on additional logging NDDSConfigLogger::get_instance()-> set_verbosity_by_category(NDDS_CONFIG_LOG_CATEGORY_API, NDDS_CONFIG_LOG_VERBOSITY_STATUS_ALL); */ return publisher_main(domainId, sample_count); } #elif !(defined(RTI_VXWORKS) && !defined(__RTP__)) && !defined(RTI_PSOS) int main(int argc, char *argv[]) { int domainId = 0; int sample_count = 0; /* infinite loop */ if (argc >= 2) { domainId = atoi(argv[1]); } if (argc >= 3) { sample_count = atoi(argv[2]); } /* Uncomment this to turn on additional logging NDDSConfigLogger::get_instance()-> set_verbosity_by_category(NDDS_CONFIG_LOG_CATEGORY_API, NDDS_CONFIG_LOG_VERBOSITY_STATUS_ALL); */ return publisher_main(domainId, sample_count); } #endif #ifdef RTI_VX653 const unsigned char *__ctype = *(__ctypePtrGet()); extern "C" void usrAppInit() { #ifdef USER_APPL_INIT USER_APPL_INIT; /* for backwards compatibility */ #endif /* add application specific code here */ taskSpawn( "pub", RTI_OSAPI_THREAD_PRIORITY_NORMAL, 0x8, 0x150000, (FUNCPTR) publisher_main, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0); } #endif
cxx
rticonnextdds-examples
data/projects/rticonnextdds-examples/connext_dds/content_filtered_topic/c++/cft_subscriber.cxx
/******************************************************************************* (c) 2005-2014 Copyright, Real-Time Innovations, Inc. All rights reserved. RTI grants Licensee a license to use, modify, compile, and create derivative works of the Software. Licensee has the right to distribute object form only for use with RTI products. The Software is provided "as is", with no warranty of any type, including any warranty for fitness for any purpose. RTI is under no obligation to maintain or support the Software. RTI shall not be liable for any incidental or consequential damages arising out of the use or inability to use the software. ******************************************************************************/ /* cft_subscriber.cxx A subscription example This file is derived from code automatically generated by the rtiddsgen command: rtiddsgen -language C++ -example <arch> cft.idl Example subscription of type cft automatically generated by 'rtiddsgen'. To test them follow these steps: (1) Compile this file and the example publication. (2) Start the subscription with the command objs/<arch>/cft_subscriber <domain_id> <sample_count> (3) Start the publication with the command objs/<arch>/cft_publisher <domain_id> <sample_count> (4) [Optional] Specify the list of discovery initial peers and multicast receive addresses via an environment variable or a file (in the current working directory) called NDDS_DISCOVERY_PEERS. You can run any number of publishers and subscribers programs, and can add and remove them dynamically from the domain. Example: To run the example application on domain <domain_id>: On Unix: objs/<arch>/cft_publisher <domain_id> objs/<arch>/cft_subscriber <domain_id> On Windows: objs\<arch>\cft_publisher <domain_id> objs\<arch>\cft_subscriber <domain_id> modification history ------------ ------- */ #include <stdio.h> #include <stdlib.h> #ifdef RTI_VX653 #include <vThreadsData.h> #endif #include "cft.h" #include "cftSupport.h" #include "ndds/ndds_cpp.h" class cftListener : public DDSDataReaderListener { public: virtual void on_requested_deadline_missed( DDSDataReader * /*reader*/, const DDS_RequestedDeadlineMissedStatus & /*status*/) { } virtual void on_requested_incompatible_qos( DDSDataReader * /*reader*/, const DDS_RequestedIncompatibleQosStatus & /*status*/) { } virtual void on_sample_rejected( DDSDataReader * /*reader*/, const DDS_SampleRejectedStatus & /*status*/) { } virtual void on_liveliness_changed( DDSDataReader * /*reader*/, const DDS_LivelinessChangedStatus & /*status*/) { } virtual void on_sample_lost( DDSDataReader * /*reader*/, const DDS_SampleLostStatus & /*status*/) { } virtual void on_subscription_matched( DDSDataReader * /*reader*/, const DDS_SubscriptionMatchedStatus & /*status*/) { } virtual void on_data_available(DDSDataReader *reader); }; void cftListener::on_data_available(DDSDataReader *reader) { cftDataReader *cft_reader = NULL; cftSeq data_seq; DDS_SampleInfoSeq info_seq; DDS_ReturnCode_t retcode; int i; cft_reader = cftDataReader::narrow(reader); if (cft_reader == NULL) { printf("DataReader narrow error\n"); return; } retcode = cft_reader->take( data_seq, info_seq, DDS_LENGTH_UNLIMITED, DDS_ANY_SAMPLE_STATE, DDS_ANY_VIEW_STATE, DDS_ANY_INSTANCE_STATE); if (retcode == DDS_RETCODE_NO_DATA) { return; } else if (retcode != DDS_RETCODE_OK) { printf("take error %d\n", retcode); return; } for (i = 0; i < data_seq.length(); ++i) { if (info_seq[i].valid_data) { cftTypeSupport::print_data(&data_seq[i]); } } retcode = cft_reader->return_loan(data_seq, info_seq); if (retcode != DDS_RETCODE_OK) { printf("return loan error %d\n", retcode); } } /* Delete all entities */ static int subscriber_shutdown(DDSDomainParticipant *participant) { DDS_ReturnCode_t retcode; int status = 0; if (participant != NULL) { retcode = participant->delete_contained_entities(); if (retcode != DDS_RETCODE_OK) { printf("delete_contained_entities error %d\n", retcode); status = -1; } retcode = DDSTheParticipantFactory->delete_participant(participant); if (retcode != DDS_RETCODE_OK) { printf("delete_participant error %d\n", retcode); status = -1; } } /* RTI Connext provides the finalize_instance() method on domain participant factory for people who want to release memory used by the participant factory. Uncomment the following block of code for clean destruction of the singleton. */ /* retcode = DDSDomainParticipantFactory::finalize_instance(); if (retcode != DDS_RETCODE_OK) { printf("finalize_instance error %d\n", retcode); status = -1; } */ return status; } extern "C" int subscriber_main(int domainId, int sample_count, int sel_cft) { DDSDomainParticipant *participant = NULL; DDSSubscriber *subscriber = NULL; DDSTopic *topic = NULL; cftListener *reader_listener = NULL; DDSDataReader *reader = NULL; DDS_ReturnCode_t retcode; const char *type_name = NULL; int count = 0; DDS_Duration_t receive_period = { 1, 0 }; int status = 0; /* To customize the participant QoS, use the configuration file USER_QOS_PROFILES.xml */ participant = DDSTheParticipantFactory->create_participant( domainId, DDS_PARTICIPANT_QOS_DEFAULT, NULL /* listener */, DDS_STATUS_MASK_NONE); if (participant == NULL) { printf("create_participant error\n"); subscriber_shutdown(participant); return -1; } /* To customize the subscriber QoS, use the configuration file USER_QOS_PROFILES.xml */ subscriber = participant->create_subscriber( DDS_SUBSCRIBER_QOS_DEFAULT, NULL /* listener */, DDS_STATUS_MASK_NONE); if (subscriber == NULL) { printf("create_subscriber error\n"); subscriber_shutdown(participant); return -1; } /* Register the type before creating the topic */ type_name = cftTypeSupport::get_type_name(); retcode = cftTypeSupport::register_type(participant, type_name); if (retcode != DDS_RETCODE_OK) { printf("register_type error %d\n", retcode); subscriber_shutdown(participant); return -1; } /* To customize the topic QoS, use the configuration file USER_QOS_PROFILES.xml */ topic = participant->create_topic( "Example cft", type_name, DDS_TOPIC_QOS_DEFAULT, NULL /* listener */, DDS_STATUS_MASK_NONE); if (topic == NULL) { printf("create_topic error\n"); subscriber_shutdown(participant); return -1; } /* Sequence of parameters for the content filter expression */ DDS_StringSeq parameters(2); /* The default parameter list that we will include in the * sequence of parameters will be "1","4" (i.e., 1 <= x <= 4). */ const char *param_list[] = { "1", "4" }; parameters.from_array(param_list, 2); /* Create the content filtered topic in case sel_cft * is true. * The Content Filter Expresion has two parameters: * - %0 -- x must be greater or equal than %0. * - %1 -- x must be less or equal than %1. */ DDSContentFilteredTopic *cft = NULL; if (sel_cft) { cft = participant->create_contentfilteredtopic( "ContentFilteredTopic", topic, "(x >= %0 and x <= %1)", parameters); if (cft == NULL) { printf("create_contentfilteredtopic error\n"); subscriber_shutdown(participant); return -1; } } /* Create a data reader listener */ reader_listener = new cftListener(); /* Here we create the reader either using a Content Filtered Topic or * a normal topic */ if (sel_cft) { printf("Using ContentFiltered Topic\n"); reader = subscriber->create_datareader( cft, DDS_DATAREADER_QOS_DEFAULT, reader_listener, DDS_STATUS_MASK_ALL); } else { printf("Using Normal Topic\n"); reader = subscriber->create_datareader( topic, DDS_DATAREADER_QOS_DEFAULT, reader_listener, DDS_STATUS_MASK_ALL); } if (reader == NULL) { printf("create_datareader error\n"); subscriber_shutdown(participant); delete reader_listener; return -1; } /* If you want to set the reliability and history QoS settings * programmatically rather than using the XML, you will need to add * the following lines to your code and comment out the create_datareader * calls above. */ /* DDS_DataReaderQos datareader_qos; retcode = subscriber->get_default_datareader_qos(datareader_qos); if (retcode != DDS_RETCODE_OK) { printf("get_default_datareader_qos error\n"); return -1; } datareader_qos.reliability.kind = DDS_RELIABLE_RELIABILITY_QOS; datareader_qos.durability.kind = DDS_TRANSIENT_LOCAL_DURABILITY_QOS; datareader_qos.history.kind = DDS_KEEP_LAST_HISTORY_QOS; datareader_qos.history.depth = 20; if (sel_cft) { printf("Using ContentFiltered Topic\n"); reader = subscriber->create_datareader( cft, datareader_qos, reader_listener, DDS_STATUS_MASK_ALL); } else { printf("Using Normal Topic\n"); reader = subscriber->create_datareader( topic, datareader_qos, reader_listener, DDS_STATUS_MASK_ALL); } if (reader == NULL) { printf("create_datareader error\n"); subscriber_shutdown(participant); delete reader_listener; return -1; } */ if (sel_cft) { printf("\n==========================\n"); printf("Using CFT\nFilter: 1 <= x <= 4\n"); printf("===========================\n"); } /* Main loop */ for (count = 0; (sample_count == 0) || (count < sample_count); ++count) { /* Receive period of 1 second. */ NDDSUtility::sleep(receive_period); /* If we are not using CFT, we do not need to change the filter * parameters */ if (sel_cft == 0) { continue; } if (count == 10) { printf("\n==========================\n"); printf("Changing filter parameters\n"); printf("Filter: 5 <= x <= 9\n"); printf("===========================\n"); DDS_String_free(parameters[0]); DDS_String_free(parameters[1]); parameters[0] = DDS_String_dup("5"); parameters[1] = DDS_String_dup("9"); retcode = cft->set_expression_parameters(parameters); if (retcode != DDS_RETCODE_OK) { printf("set_expression_parameters error\n"); subscriber_shutdown(participant); return -1; } } else if (count == 20) { printf("\n==========================\n"); printf("Changing filter parameters\n"); printf("Filter: 3 <= x <= 9\n"); printf("===========================\n"); DDS_StringSeq oldParameters; cft->get_expression_parameters(oldParameters); DDS_String_free(oldParameters[0]); oldParameters[0] = DDS_String_dup("3"); retcode = cft->set_expression_parameters(oldParameters); if (retcode != DDS_RETCODE_OK) { printf("set_expression_parameters error\n"); subscriber_shutdown(participant); return -1; } } } /* Delete all entities */ status = subscriber_shutdown(participant); delete reader_listener; return status; } #if defined(RTI_WINCE) int wmain(int argc, wchar_t **argv) { int domainId = 0; int sample_count = 0; /* infinite loop */ if (argc >= 2) { domainId = _wtoi(argv[1]); } if (argc >= 3) { sample_count = _wtoi(argv[2]); } /* Uncomment this to turn on additional logging NDDSConfigLogger::get_instance()-> set_verbosity_by_category(NDDS_CONFIG_LOG_CATEGORY_API, NDDS_CONFIG_LOG_VERBOSITY_STATUS_ALL); */ return subscriber_main(domainId, sample_count); } #elif !(defined(RTI_VXWORKS) && !defined(__RTP__)) && !defined(RTI_PSOS) int main(int argc, char *argv[]) { int domainId = 0; int sample_count = 0; /* infinite loop */ int sel_cft = 1; /* Use content filtered topic? */ if (argc >= 2) { domainId = atoi(argv[1]); } if (argc >= 3) { sample_count = atoi(argv[2]); } if (argc >= 4) { sel_cft = atoi(argv[3]); } /* Uncomment this to turn on additional logging NDDSConfigLogger::get_instance()-> set_verbosity_by_category(NDDS_CONFIG_LOG_CATEGORY_API, NDDS_CONFIG_LOG_VERBOSITY_STATUS_ALL); */ return subscriber_main(domainId, sample_count, sel_cft); } #endif #ifdef RTI_VX653 const unsigned char *__ctype = *(__ctypePtrGet()); extern "C" void usrAppInit() { #ifdef USER_APPL_INIT USER_APPL_INIT; /* for backwards compatibility */ #endif /* add application specific code here */ taskSpawn( "sub", RTI_OSAPI_THREAD_PRIORITY_NORMAL, 0x8, 0x150000, (FUNCPTR) subscriber_main, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0); } #endif
cxx
rticonnextdds-examples
data/projects/rticonnextdds-examples/connext_dds/content_filtered_topic/c++98/cft_publisher.cxx
/******************************************************************************* (c) 2005-2014 Copyright, Real-Time Innovations, Inc. All rights reserved. RTI grants Licensee a license to use, modify, compile, and create derivative works of the Software. Licensee has the right to distribute object form only for use with RTI products. The Software is provided "as is", with no warranty of any type, including any warranty for fitness for any purpose. RTI is under no obligation to maintain or support the Software. RTI shall not be liable for any incidental or consequential damages arising out of the use or inability to use the software. ******************************************************************************/ #include <iostream> #include <stdio.h> #include <stdlib.h> #include "cft.h" #include "cftSupport.h" #include "ndds/ndds_cpp.h" #include "application.h" using namespace application; static int shutdown_participant( DDSDomainParticipant *participant, const char *shutdown_message, int status); int run_publisher_application(unsigned int domain_id, unsigned int sample_count) { // Send a new sample every second DDS_Duration_t send_period = { 1, 0 }; // Start communicating in a domain, usually one participant per application DDSDomainParticipant *participant = DDSTheParticipantFactory->create_participant( domain_id, DDS_PARTICIPANT_QOS_DEFAULT, NULL /* listener */, DDS_STATUS_MASK_NONE); if (participant == NULL) { return shutdown_participant( participant, "create_participant error", EXIT_FAILURE); } // A Publisher allows an application to create one or more DataWriters DDSPublisher *publisher = participant->create_publisher( DDS_PUBLISHER_QOS_DEFAULT, NULL /* listener */, DDS_STATUS_MASK_NONE); if (publisher == NULL) { return shutdown_participant( participant, "create_publisher error", EXIT_FAILURE); } // Register the datatype to use when creating the Topic const char *type_name = cftTypeSupport::get_type_name(); DDS_ReturnCode_t retcode = cftTypeSupport::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 cft", 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 cft" Topic DDSDataWriter *untyped_writer = publisher->create_datawriter( topic, DDS_DATAWRITER_QOS_DEFAULT, NULL, DDS_STATUS_MASK_NONE); if (untyped_writer == NULL) { return shutdown_participant( participant, "create_datawriter error", EXIT_FAILURE); } /* If you want to set the reliability and history QoS settings * programmatically rather than using the XML, you will need to add * the following lines to your code and comment out the create_datawriter * call above. */ /* DDS_DataWriterQos datawriter_qos; retcode = publisher->get_default_datawriter_qos(datawriter_qos); if (retcode != DDS_RETCODE_OK) { std::cerr << "get_default_datawriter_qos error\n"; return EXIT_FAILURE; } datawriter_qos.reliability.kind = DDS_RELIABLE_RELIABILITY_QOS; datawriter_qos.durability.kind = DDS_TRANSIENT_LOCAL_DURABILITY_QOS; datawriter_qos.history.kind = DDS_KEEP_LAST_HISTORY_QOS; datawriter_qos.history.depth = 20; DDSDataWriter *untyped_writer = publisher->create_datawriter( topic, datawriter_qos, NULL, DDS_STATUS_MASK_NONE); if (untyped_writer == NULL) { return shutdown_participant( participant, "create_datawriter error", EXIT_FAILURE); } */ // Narrow casts from an untyped DataWriter to a writer of your type cftDataWriter *typed_writer = cftDataWriter::narrow(untyped_writer); if (typed_writer == NULL) { return shutdown_participant( participant, "DataWriter narrow error", EXIT_FAILURE); } /* Create data sample for writing */ cft *data = cftTypeSupport::create_data(); if (data == NULL) { return shutdown_participant( participant, "cftTypeSupport::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(*instance); */ // Main loop, write data for (unsigned int samples_written = 0; !shutdown_requested && samples_written < sample_count; ++samples_written) { /* Modify the data to be sent here */ /* Our purpose is to increment x every time we send a sample and to * reset the x counter to 0 every time we send 10 samples (x=0,1,..,9). * Using the value of count, we can get set x to the appropriate value * applying % 10 operation to it. */ data->count = samples_written; data->x = samples_written % 10; std::cout << "Writing cft, count " << data->count << "\tx=" << data->x << std::endl; 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 cft, including all contained elements retcode = cftTypeSupport::delete_data(data); if (retcode != DDS_RETCODE_OK) { std::cerr << "cftTypeSupport::delete_data error " << retcode << std::endl; } // Delete all entities (DataWriter, Topic, Publisher, DomainParticipant) return shutdown_participant(participant, "Shutting down", EXIT_SUCCESS); } // Delete all entities static int shutdown_participant( DDSDomainParticipant *participant, const char *shutdown_message, int status) { DDS_ReturnCode_t retcode; std::cout << shutdown_message << std::endl; if (participant != NULL) { // Cleanup everything created by this Participant retcode = participant->delete_contained_entities(); if (retcode != DDS_RETCODE_OK) { std::cerr << "delete_contained_entities error " << retcode << std::endl; status = EXIT_FAILURE; } retcode = DDSTheParticipantFactory->delete_participant(participant); if (retcode != DDS_RETCODE_OK) { std::cerr << "delete_participant error " << retcode << std::endl; status = EXIT_FAILURE; } } return status; } int main(int argc, char *argv[]) { // Parse arguments and handle control-C ApplicationArguments arguments; parse_arguments(arguments, argc, argv, publisher); if (arguments.parse_result == PARSE_RETURN_EXIT) { return EXIT_SUCCESS; } else if (arguments.parse_result == PARSE_RETURN_FAILURE) { return EXIT_FAILURE; } setup_signal_handlers(); // Sets Connext verbosity to help debugging NDDSConfigLogger::get_instance()->set_verbosity(arguments.verbosity); int status = run_publisher_application( arguments.domain_id, arguments.sample_count); // Releases the memory used by the participant factory. Optional at // application exit DDS_ReturnCode_t retcode = DDSDomainParticipantFactory::finalize_instance(); if (retcode != DDS_RETCODE_OK) { std::cerr << "finalize_instance error " << retcode << std::endl; status = EXIT_FAILURE; } return status; }
cxx
rticonnextdds-examples
data/projects/rticonnextdds-examples/connext_dds/content_filtered_topic/c++98/application.h
/* * (c) Copyright, Real-Time Innovations, 2020. All rights reserved. * RTI grants Licensee a license to use, modify, compile, and create derivative * works of the software solely for use with RTI Connext DDS. Licensee may * redistribute copies of the software provided that all such copies are subject * to this license. The software is provided "as is", with no warranty of any * type, including any warranty for fitness for any purpose. RTI is under no * obligation to maintain or support the software. RTI shall not be liable for * any incidental or consequential damages arising out of the use or inability * to use the software. */ #ifndef APPLICATION_H #define APPLICATION_H #include <iostream> #include <csignal> #include <climits> namespace application { // Catch control-C and tell application to shut down bool shutdown_requested = false; inline void stop_handler(int) { shutdown_requested = true; std::cout << "preparing to shut down..." << std::endl; } inline void setup_signal_handlers() { signal(SIGINT, stop_handler); signal(SIGTERM, stop_handler); } enum ParseReturn { PARSE_RETURN_OK, PARSE_RETURN_FAILURE, PARSE_RETURN_EXIT }; enum ApplicationKind { publisher, subscriber }; struct ApplicationArguments { ParseReturn parse_result; unsigned int domain_id; unsigned int sample_count; NDDS_Config_LogVerbosity verbosity; bool normal_topic; }; inline void set_verbosity(ApplicationArguments &arguments, int verbosity) { switch (verbosity) { case 0: arguments.verbosity = NDDS_CONFIG_LOG_VERBOSITY_SILENT; break; case 1: arguments.verbosity = NDDS_CONFIG_LOG_VERBOSITY_ERROR; break; case 2: arguments.verbosity = NDDS_CONFIG_LOG_VERBOSITY_WARNING; break; case 3: arguments.verbosity = NDDS_CONFIG_LOG_VERBOSITY_STATUS_ALL; break; default: arguments.verbosity = NDDS_CONFIG_LOG_VERBOSITY_ERROR; break; } } // Parses application arguments for example. Returns whether to exit. inline void parse_arguments( ApplicationArguments &arguments, int argc, char *argv[], ApplicationKind current_application) { int arg_processing = 1; bool show_usage = false; arguments.domain_id = 0; arguments.sample_count = INT_MAX; arguments.verbosity = NDDS_CONFIG_LOG_VERBOSITY_ERROR; arguments.parse_result = PARSE_RETURN_OK; arguments.normal_topic = false; 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 ( current_application == subscriber && strcmp(argv[arg_processing], "--normal-topic") == 0) { arguments.normal_topic = true; arg_processing += 1; } 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" << std::endl; if (current_application == subscriber) { std::cout << " --normal-topic If this option is " "given, the subscriber\n" " will use a normal topic " "instead of a\n" " Content Filtered Topic." << std::endl; } std::cout << " -v, --verbosity <int> How much debugging output " "to show.\n" " Range: 0-3 \n" " Default: 1" << std::endl; } } } // namespace application #endif // APPLICATION_H
h
rticonnextdds-examples
data/projects/rticonnextdds-examples/connext_dds/content_filtered_topic/c++98/cft_subscriber.cxx
/******************************************************************************* (c) 2005-2014 Copyright, Real-Time Innovations, Inc. All rights reserved. RTI grants Licensee a license to use, modify, compile, and create derivative works of the Software. Licensee has the right to distribute object form only for use with RTI products. The Software is provided "as is", with no warranty of any type, including any warranty for fitness for any purpose. RTI is under no obligation to maintain or support the Software. RTI shall not be liable for any incidental or consequential damages arising out of the use or inability to use the software. ******************************************************************************/ #include <iostream> #include <stdio.h> #include <stdlib.h> #include "cft.h" #include "cftSupport.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(cftDataReader *typed_reader) { cftSeq 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) { cftTypeSupport::print_data(&data_seq[i]); samples_read++; } } // 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, bool normal_topic) { DDS_Duration_t wait_timeout = { 1, 0 }; // Start communicating in a domain, usually one participant per application DDSDomainParticipant *participant = DDSTheParticipantFactory->create_participant( domain_id, DDS_PARTICIPANT_QOS_DEFAULT, NULL /* listener */, DDS_STATUS_MASK_NONE); if (participant == NULL) { return shutdown_participant( participant, "create_participant error", EXIT_FAILURE); } // A Subscriber allows an application to create one or more DataReaders DDSSubscriber *subscriber = participant->create_subscriber( DDS_SUBSCRIBER_QOS_DEFAULT, NULL /* listener */, DDS_STATUS_MASK_NONE); if (subscriber == NULL) { return shutdown_participant( participant, "create_subscriber error", EXIT_FAILURE); } // Register the datatype to use when creating the Topic const char *type_name = cftTypeSupport::get_type_name(); DDS_ReturnCode_t retcode = cftTypeSupport::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 cft", type_name, DDS_TOPIC_QOS_DEFAULT, NULL /* listener */, DDS_STATUS_MASK_NONE); if (topic == NULL) { return shutdown_participant( participant, "create_topic error", EXIT_FAILURE); } // Sequence of parameters for the content filter expression DDS_StringSeq parameters(2); /* The default parameter list that we will include in the * sequence of parameters will be "1","4" (i.e., 1 <= x <= 4). */ const char *param_list[] = { "1", "4" }; parameters.from_array(param_list, 2); /* Create the content filtered topic in case sel_cft * is true. * The Content Filter Expresion has two parameters: * - %0 -- x must be greater or equal than %0. * - %1 -- x must be less or equal than %1. */ DDSContentFilteredTopic *cft = NULL; if (!normal_topic) { cft = participant->create_contentfilteredtopic( "ContentFilteredTopic", topic, "(x >= %0 and x <= %1)", parameters); if (cft == NULL) { return shutdown_participant( participant, "create_contentfilteredtopic error", EXIT_FAILURE); } } /* Here we create the reader either using a Content Filtered Topic or * a normal topic */ DDSDataReader *untyped_reader = NULL; if (!normal_topic) { std::cout << "Using ContentFiltered Topic\n"; untyped_reader = subscriber->create_datareader( cft, DDS_DATAREADER_QOS_DEFAULT, NULL, DDS_STATUS_MASK_ALL); } else { std::cout << "Using Normal Topic\n"; 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 set the reliability and history QoS settings * programmatically rather than using the XML, you will need to add * the following lines to your code and comment out the create_datareader * calls above. */ /* DDS_DataReaderQos datareader_qos; retcode = subscriber->get_default_datareader_qos(datareader_qos); if (retcode != DDS_RETCODE_OK) { return shutdown_participant( participant, "get_default_datareader_qos error", EXIT_FAILURE); } datareader_qos.reliability.kind = DDS_RELIABLE_RELIABILITY_QOS; datareader_qos.durability.kind = DDS_TRANSIENT_LOCAL_DURABILITY_QOS; datareader_qos.history.kind = DDS_KEEP_LAST_HISTORY_QOS; datareader_qos.history.depth = 20; if (!normal_topic) { std::cout << "Using ContentFiltered Topic\n"; untyped_reader = subscriber->create_datareader( cft, datareader_qos, NULL, DDS_STATUS_MASK_ALL); } else { std::cout << "Using Normal Topic\n"; untyped_reader = subscriber->create_datareader( topic, datareader_qos, NULL, DDS_STATUS_MASK_ALL); } if (untyped_reader == NULL) { return shutdown_participant( participant, "create_datareader error", EXIT_FAILURE); } */ cftDataReader *typed_reader = cftDataReader::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); } if (!normal_topic) { std::cout << "\n==========================\n"; std::cout << "Using CFT\nFilter: 1 <= x <= 4\n"; std::cout << "===========================\n"; } bool changed_filter1 = false; bool changed_filter2 = false; // 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 we are not using CFT, we do not need to change the filter * parameters */ if (retcode == DDS_RETCODE_OK) { // If the read condition is triggered, process data samples_read += process_data(typed_reader); } if (normal_topic) { continue; } if (samples_read == 10 && !changed_filter1) { std::cout << "\n==========================\n"; std::cout << "Changing filter parameters\n"; std::cout << "Filter: 5 <= x <= 9\n"; std::cout << "===========================\n"; DDS_String_free(parameters[0]); DDS_String_free(parameters[1]); parameters[0] = DDS_String_dup("5"); parameters[1] = DDS_String_dup("9"); retcode = cft->set_expression_parameters(parameters); if (retcode != DDS_RETCODE_OK) { return shutdown_participant( participant, "set_expression_parameters error", EXIT_FAILURE); } changed_filter1 = true; } else if (samples_read == 20 && !changed_filter2) { std::cout << "\n==========================\n"; std::cout << "Changing filter parameters\n"; std::cout << "Filter: 3 <= x <= 9\n"; std::cout << "===========================\n"; DDS_StringSeq oldParameters; cft->get_expression_parameters(oldParameters); DDS_String_free(oldParameters[0]); oldParameters[0] = DDS_String_dup("3"); retcode = cft->set_expression_parameters(oldParameters); if (retcode != DDS_RETCODE_OK) { return shutdown_participant( participant, "set_expression_parameters error", EXIT_FAILURE); } changed_filter2 = true; } } // Cleanup return shutdown_participant(participant, "Shutting down", 0); } // Delete all entities static int shutdown_participant( DDSDomainParticipant *participant, const char *shutdown_message, int status) { DDS_ReturnCode_t retcode; std::cout << shutdown_message << std::endl; if (participant != NULL) { // Cleanup everything created by this Participant retcode = participant->delete_contained_entities(); if (retcode != DDS_RETCODE_OK) { std::cerr << "delete_contained_entities error" << retcode << std::endl; status = EXIT_FAILURE; } retcode = DDSTheParticipantFactory->delete_participant(participant); if (retcode != DDS_RETCODE_OK) { std::cerr << "delete_participant error" << retcode << std::endl; status = EXIT_FAILURE; } } return status; } int main(int argc, char *argv[]) { // Parse arguments and handle control-C ApplicationArguments arguments; parse_arguments(arguments, argc, argv, subscriber); if (arguments.parse_result == PARSE_RETURN_EXIT) { return EXIT_SUCCESS; } else if (arguments.parse_result == PARSE_RETURN_FAILURE) { return EXIT_FAILURE; } setup_signal_handlers(); // Sets Connext verbosity to help debugging NDDSConfigLogger::get_instance()->set_verbosity(arguments.verbosity); int status = run_subscriber_application( arguments.domain_id, arguments.sample_count, arguments.normal_topic); // 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/content_filtered_topic/c/cft_publisher.c
/******************************************************************************* (c) 2005-2014 Copyright, Real-Time Innovations, Inc. All rights reserved. RTI grants Licensee a license to use, modify, compile, and create derivative works of the Software. Licensee has the right to distribute object form only for use with RTI products. The Software is provided "as is", with no warranty of any type, including any warranty for fitness for any purpose. RTI is under no obligation to maintain or support the Software. RTI shall not be liable for any incidental or consequential damages arising out of the use or inability to use the software. ******************************************************************************/ /* cft_publisher.c A publication of data of type cft This file is derived from code automatically generated by the rtiddsgen command: rtiddsgen -language C -example <arch> cft.idl Example publication of type cft automatically generated by 'rtiddsgen'. To test them follow these steps: (1) Compile this file and the example subscription. (2) Start the subscription with the command objs/<arch>/cft_subscriber <domain_id> <sample_count> (3) Start the publication with the command objs/<arch>/cft_publisher <domain_id> <sample_count> (4) [Optional] Specify the list of discovery initial peers and multicast receive addresses via an environment variable or a file (in the current working directory) called NDDS_DISCOVERY_PEERS. You can run any number of publishers and subscribers programs, and can add and remove them dynamically from the domain. Example: To run the example application on domain <domain_id>: On Unix: objs/<arch>/cft_publisher <domain_id> objs/<arch>/cft_subscriber <domain_id> On Windows: objs\<arch>\cft_publisher <domain_id> objs\<arch>\cft_subscriber <domain_id> modification history ------------ ------- */ #include "cft.h" #include "cftSupport.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; cftDataWriter *cft_writer = NULL; cft *instance = NULL; DDS_ReturnCode_t retcode; DDS_InstanceHandle_t instance_handle = DDS_HANDLE_NIL; const char *type_name = NULL; int count = 0; /* Send a new sample every second */ struct DDS_Duration_t send_period = { 1, 0 }; /* We need this structure in case we want to change the datawriter_qos * programmatically.*/ /* struct DDS_DataWriterQos datawriter_qos = DDS_DataWriterQos_INITIALIZER; */ /* To customize participant QoS, use the configuration file USER_QOS_PROFILES.xml */ participant = DDS_DomainParticipantFactory_create_participant( DDS_TheParticipantFactory, domainId, &DDS_PARTICIPANT_QOS_DEFAULT, NULL /* listener */, DDS_STATUS_MASK_NONE); if (participant == NULL) { printf("create_participant error\n"); publisher_shutdown(participant); return -1; } /* To customize publisher QoS, use the configuration file USER_QOS_PROFILES.xml */ publisher = DDS_DomainParticipant_create_publisher( participant, &DDS_PUBLISHER_QOS_DEFAULT, NULL /* listener */, DDS_STATUS_MASK_NONE); if (publisher == NULL) { printf("create_publisher error\n"); publisher_shutdown(participant); return -1; } /* Register type before creating topic */ type_name = cftTypeSupport_get_type_name(); retcode = cftTypeSupport_register_type(participant, type_name); if (retcode != DDS_RETCODE_OK) { printf("register_type error %d\n", retcode); publisher_shutdown(participant); return -1; } /* To customize topic QoS, use the configuration file USER_QOS_PROFILES.xml */ topic = DDS_DomainParticipant_create_topic( participant, "Example cft", type_name, &DDS_TOPIC_QOS_DEFAULT, NULL /* listener */, DDS_STATUS_MASK_NONE); if (topic == NULL) { printf("create_topic error\n"); publisher_shutdown(participant); return -1; } /* To customize data writer QoS, use the configuration file USER_QOS_PROFILES.xml */ writer = DDS_Publisher_create_datawriter( publisher, topic, &DDS_DATAWRITER_QOS_DEFAULT, NULL, DDS_STATUS_MASK_NONE); if (writer == NULL) { printf("create_datawriter error\n"); publisher_shutdown(participant); return -1; } /* If you want to set the reliability and history QoS settings * programmatically rather than using the XML, you will need to add * the following lines to your code and comment out the create_datawriter * call above. */ /* retcode = DDS_Publisher_get_default_datawriter_qos(publisher, &datawriter_qos); if (retcode != DDS_RETCODE_OK) { printf("get_default_datawriter_qos error\n"); return -1; } datawriter_qos.reliability.kind = DDS_RELIABLE_RELIABILITY_QOS; datawriter_qos.durability.kind = DDS_TRANSIENT_LOCAL_DURABILITY_QOS; datawriter_qos.history.kind = DDS_KEEP_LAST_HISTORY_QOS; datawriter_qos.history.depth = 20; writer = DDS_Publisher_create_datawriter( publisher, topic, &datawriter_qos, NULL, DDS_STATUS_MASK_NONE); if (writer == NULL) { printf("create_datawriter error\n"); publisher_shutdown(participant); return -1; } */ cft_writer = cftDataWriter_narrow(writer); if (cft_writer == NULL) { printf("DataWriter narrow error\n"); publisher_shutdown(participant); return -1; } /* Create data sample for writing */ instance = cftTypeSupport_create_data_ex(DDS_BOOLEAN_TRUE); if (instance == NULL) { printf("cftTypeSupport_create_data error\n"); publisher_shutdown(participant); return -1; } /* For a data type that has a key, if the same instance is going to be written multiple times, initialize the key here and register the keyed instance prior to writing */ /* instance_handle = cftDataWriter_register_instance( cft_writer, instance); */ /* Main loop */ for (count = 0; (sample_count == 0) || (count < sample_count); ++count) { /* Modify the data to be written here */ /* Our purpose is to increment x every time we send a sample and to * reset the x counter to 0 every time we send 10 samples (x=0,1,..,9). * Using the value of count, we can get set x to the appropriate value * applying % 10 operation to it. */ instance->count = count; instance->x = count % 10; printf("Writing cft, count %d\tx=%d\n", instance->count, instance->x); /* Write data */ retcode = cftDataWriter_write(cft_writer, instance, &instance_handle); if (retcode != DDS_RETCODE_OK) { printf("write error %d\n", retcode); } NDDS_Utility_sleep(&send_period); } /* retcode = cftDataWriter_unregister_instance( cft_writer, instance, &instance_handle); if (retcode != DDS_RETCODE_OK) { printf("unregister instance error %d\n", retcode); } */ /* Delete data sample */ retcode = cftTypeSupport_delete_data_ex(instance, DDS_BOOLEAN_TRUE); if (retcode != DDS_RETCODE_OK) { printf("cftTypeSupport_delete_data error %d\n", retcode); } /* Cleanup and delete delete all entities */ return publisher_shutdown(participant); } #if defined(RTI_WINCE) int wmain(int argc, wchar_t **argv) { int domainId = 0; int sample_count = 0; /* infinite loop */ if (argc >= 2) { domainId = _wtoi(argv[1]); } if (argc >= 3) { sample_count = _wtoi(argv[2]); } /* Uncomment this to turn on additional logging NDDS_Config_Logger_set_verbosity_by_category( NDDS_Config_Logger_get_instance(), NDDS_CONFIG_LOG_CATEGORY_API, NDDS_CONFIG_LOG_VERBOSITY_STATUS_ALL); */ return publisher_main(domainId, sample_count); } #elif !(defined(RTI_VXWORKS) && !defined(__RTP__)) && !defined(RTI_PSOS) int main(int argc, char *argv[]) { int domainId = 0; int sample_count = 0; /* infinite loop */ if (argc >= 2) { domainId = atoi(argv[1]); } if (argc >= 3) { sample_count = atoi(argv[2]); } /* Uncomment this to turn on additional logging NDDS_Config_Logger_set_verbosity_by_category( NDDS_Config_Logger_get_instance(), NDDS_CONFIG_LOG_CATEGORY_API, NDDS_CONFIG_LOG_VERBOSITY_STATUS_ALL); */ return publisher_main(domainId, sample_count); } #endif #ifdef RTI_VX653 const unsigned char *__ctype = NULL; void usrAppInit() { #ifdef USER_APPL_INIT USER_APPL_INIT; /* for backwards compatibility */ #endif /* add application specific code here */ taskSpawn( "pub", RTI_OSAPI_THREAD_PRIORITY_NORMAL, 0x8, 0x150000, (FUNCPTR) publisher_main, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0); } #endif
c
rticonnextdds-examples
data/projects/rticonnextdds-examples/connext_dds/content_filtered_topic/c/cft_subscriber.c
/******************************************************************************* (c) 2005-2014 Copyright, Real-Time Innovations, Inc. All rights reserved. RTI grants Licensee a license to use, modify, compile, and create derivative works of the Software. Licensee has the right to distribute object form only for use with RTI products. The Software is provided "as is", with no warranty of any type, including any warranty for fitness for any purpose. RTI is under no obligation to maintain or support the Software. RTI shall not be liable for any incidental or consequential damages arising out of the use or inability to use the software. ******************************************************************************/ /* cft_subscriber.c A subscription example This file is derived from code automatically generated by the rtiddsgen command: rtiddsgen -language C -example <arch> cft.idl Example subscription of type cft automatically generated by 'rtiddsgen'. To test them, follow these steps: (1) Compile this file and the example publication. (2) Start the subscription with the command objs/<arch>/cft_subscriber <domain_id> <sample_count> (3) Start the publication with the command objs/<arch>/cft_publisher <domain_id> <sample_count> (4) [Optional] Specify the list of discovery initial peers and multicast receive addresses via an environment variable or a file (in the current working directory) called NDDS_DISCOVERY_PEERS. You can run any number of publishers and subscribers programs, and can add and remove them dynamically from the domain. Example: To run the example application on domain <domain_id>: On UNIX systems: objs/<arch>/cft_publisher <domain_id> objs/<arch>/cft_subscriber <domain_id> On Windows systems: objs\<arch>\cft_publisher <domain_id> objs\<arch>\cft_subscriber <domain_id> modification history ------------ ------- */ #include "cft.h" #include "cftSupport.h" #include "ndds/ndds_c.h" #include <stdio.h> #include <stdlib.h> void cftListener_on_requested_deadline_missed( void *listener_data, DDS_DataReader *reader, const struct DDS_RequestedDeadlineMissedStatus *status) { } void cftListener_on_requested_incompatible_qos( void *listener_data, DDS_DataReader *reader, const struct DDS_RequestedIncompatibleQosStatus *status) { } void cftListener_on_sample_rejected( void *listener_data, DDS_DataReader *reader, const struct DDS_SampleRejectedStatus *status) { } void cftListener_on_liveliness_changed( void *listener_data, DDS_DataReader *reader, const struct DDS_LivelinessChangedStatus *status) { } void cftListener_on_sample_lost( void *listener_data, DDS_DataReader *reader, const struct DDS_SampleLostStatus *status) { } void cftListener_on_subscription_matched( void *listener_data, DDS_DataReader *reader, const struct DDS_SubscriptionMatchedStatus *status) { } void cftListener_on_data_available(void *listener_data, DDS_DataReader *reader) { cftDataReader *cft_reader = NULL; struct cftSeq data_seq = DDS_SEQUENCE_INITIALIZER; struct DDS_SampleInfoSeq info_seq = DDS_SEQUENCE_INITIALIZER; DDS_ReturnCode_t retcode; int i; cft_reader = cftDataReader_narrow(reader); if (cft_reader == NULL) { printf("DataReader narrow error\n"); return; } retcode = cftDataReader_take( cft_reader, &data_seq, &info_seq, DDS_LENGTH_UNLIMITED, DDS_ANY_SAMPLE_STATE, DDS_ANY_VIEW_STATE, DDS_ANY_INSTANCE_STATE); if (retcode == DDS_RETCODE_NO_DATA) { return; } else if (retcode != DDS_RETCODE_OK) { printf("take error %d\n", retcode); return; } for (i = 0; i < cftSeq_get_length(&data_seq); ++i) { if (DDS_SampleInfoSeq_get_reference(&info_seq, i)->valid_data) { cftTypeSupport_print_data(cftSeq_get_reference(&data_seq, i)); } } retcode = cftDataReader_return_loan(cft_reader, &data_seq, &info_seq); if (retcode != DDS_RETCODE_OK) { printf("return loan error %d\n", retcode); } } /* Delete all entities */ static int subscriber_shutdown(DDS_DomainParticipant *participant) { DDS_ReturnCode_t retcode; int status = 0; if (participant != NULL) { retcode = DDS_DomainParticipant_delete_contained_entities(participant); if (retcode != DDS_RETCODE_OK) { printf("delete_contained_entities error %d\n", retcode); status = -1; } retcode = DDS_DomainParticipantFactory_delete_participant( DDS_TheParticipantFactory, participant); if (retcode != DDS_RETCODE_OK) { printf("delete_participant error %d\n", retcode); status = -1; } } /* RTI Connext provides the finalize_instance() method on domain participant factory for users who want to release memory used by the participant factory. Uncomment the following block of code for clean destruction of the singleton. */ /* retcode = DDS_DomainParticipantFactory_finalize_instance(); if (retcode != DDS_RETCODE_OK) { printf("finalize_instance error %d\n", retcode); status = -1; } */ return status; } /* The subscribrer_main function gets an extra parameter called * sel_cft that specifies whether to apply content filtering * or not. */ static int subscriber_main(int domainId, int sample_count, int sel_cft) { DDS_DomainParticipant *participant = NULL; DDS_Subscriber *subscriber = NULL; DDS_Topic *topic = NULL; struct DDS_DataReaderListener reader_listener = DDS_DataReaderListener_INITIALIZER; DDS_DataReader *reader = NULL; DDS_ReturnCode_t retcode; const char *type_name = NULL; int count = 0; struct DDS_Duration_t poll_period = { 1, 0 }; /* If you want to modify datareader_qos programatically you * will need to use the following structure. */ /* struct DDS_DataReaderQos datareader_qos = DDS_DataReaderQos_INITIALIZER; */ /* Sequence of parameters for the content filter expression */ struct DDS_StringSeq parameters; /* The default parameter list that we will include in the * sequence of parameters will be "1","4" (i.e., 1 <= x <= 4). */ const char *param_list[] = { "1", "4" }; /* Content Filtered Topic */ DDS_ContentFilteredTopic *cft = NULL; /* To customize participant QoS, use the configuration file USER_QOS_PROFILES.xml */ participant = DDS_DomainParticipantFactory_create_participant( DDS_TheParticipantFactory, domainId, &DDS_PARTICIPANT_QOS_DEFAULT, NULL /* listener */, DDS_STATUS_MASK_NONE); if (participant == NULL) { printf("create_participant error\n"); subscriber_shutdown(participant); return -1; } /* To customize subscriber QoS, use the configuration file USER_QOS_PROFILES.xml */ subscriber = DDS_DomainParticipant_create_subscriber( participant, &DDS_SUBSCRIBER_QOS_DEFAULT, NULL /* listener */, DDS_STATUS_MASK_NONE); if (subscriber == NULL) { printf("create_subscriber error\n"); subscriber_shutdown(participant); return -1; } /* Register the type before creating the topic */ type_name = cftTypeSupport_get_type_name(); retcode = cftTypeSupport_register_type(participant, type_name); if (retcode != DDS_RETCODE_OK) { printf("register_type error %d\n", retcode); subscriber_shutdown(participant); return -1; } /* To customize topic QoS, use the configuration file USER_QOS_PROFILES.xml */ topic = DDS_DomainParticipant_create_topic( participant, "Example cft", type_name, &DDS_TOPIC_QOS_DEFAULT, NULL /* listener */, DDS_STATUS_MASK_NONE); if (topic == NULL) { printf("create_topic error\n"); subscriber_shutdown(participant); return -1; } /* Create the content filtered topic in case sel_cft * is true. * The Content Filter Expresion has two parameters: * - %0 -- x must be greater or equal than %0. * - %1 -- x must be less or equal than %1. */ DDS_StringSeq_initialize(&parameters); DDS_StringSeq_set_maximum(&parameters, 2); /* Here we set the default filter to 1 <= x <= 4 */ DDS_StringSeq_from_array(&parameters, param_list, 2); if (sel_cft) { cft = DDS_DomainParticipant_create_contentfilteredtopic( participant, "ContentFilteredTopic", topic, "(x >= %0 and x <= %1)", &parameters); if (cft == NULL) { printf("create_contentfilteredtopic error\n"); subscriber_shutdown(participant); return -1; } } /* Set up a data reader listener */ reader_listener.on_requested_deadline_missed = cftListener_on_requested_deadline_missed; reader_listener.on_requested_incompatible_qos = cftListener_on_requested_incompatible_qos; reader_listener.on_sample_rejected = cftListener_on_sample_rejected; reader_listener.on_liveliness_changed = cftListener_on_liveliness_changed; reader_listener.on_sample_lost = cftListener_on_sample_lost; reader_listener.on_subscription_matched = cftListener_on_subscription_matched; reader_listener.on_data_available = cftListener_on_data_available; /* To customize data reader QoS, use the configuration file USER_QOS_PROFILES.xml */ if (sel_cft) { printf("Using ContentFiltered Topic\n"); reader = DDS_Subscriber_create_datareader( subscriber, DDS_ContentFilteredTopic_as_topicdescription(cft), &DDS_DATAREADER_QOS_DEFAULT, &reader_listener, DDS_STATUS_MASK_ALL); } else { printf("Using Normal Topic\n"); reader = DDS_Subscriber_create_datareader( subscriber, DDS_Topic_as_topicdescription(topic), &DDS_DATAREADER_QOS_DEFAULT, &reader_listener, DDS_STATUS_MASK_ALL); } if (reader == NULL) { printf("create_datareader error\n"); subscriber_shutdown(participant); return -1; } /* If you want to set the reliability and history QoS settings * programmatically rather than using the XML, you will need to add * the following lines to your code and comment out the create_datareader * calls above. */ /* retcode = DDS_Subscriber_get_default_datareader_qos(subscriber, &datareader_qos); if (retcode != DDS_RETCODE_OK) { printf("get_default_datareader_qos error\n"); return -1; } datareader_qos.reliability.kind = DDS_RELIABLE_RELIABILITY_QOS; datareader_qos.durability.kind = DDS_TRANSIENT_LOCAL_DURABILITY_QOS; datareader_qos.history.kind = DDS_KEEP_LAST_HISTORY_QOS; datareader_qos.history.depth = 20; if (sel_cft) { printf("Using ContentFiltered Topic\n"); reader = DDS_Subscriber_create_datareader( subscriber, DDS_ContentFilteredTopic_as_topicdescription(cft), &datareader_qos, &reader_listener, DDS_STATUS_MASK_ALL); } else { printf("Using Normal Topic\n"); reader = DDS_Subscriber_create_datareader( subscriber, DDS_Topic_as_topicdescription(topic), &datareader_qos, &reader_listener, DDS_STATUS_MASK_ALL); } if (reader == NULL) { printf("create_datareader error\n"); subscriber_shutdown(participant); return -1; } */ if (sel_cft) { printf("\n==========================\n"); printf("Using CFT\nFilter: 1 <= x <= 4\n"); printf("===========================\n"); } /* Main loop */ for (count = 0; (sample_count == 0) || (count < sample_count); ++count) { /* Pool period of 1 second. */ NDDS_Utility_sleep(&poll_period); /* If we are not using CFT, we do not need to change the filter * parameters */ if (sel_cft == 0) { continue; } if (count == 10) { printf("\n==========================\n"); printf("Changing filter parameters\n"); printf("Filter: 5 <= x <= 9\n"); printf("===========================\n"); DDS_String_free(DDS_StringSeq_get(&parameters, 0)); DDS_String_free(DDS_StringSeq_get(&parameters, 1)); *DDS_StringSeq_get_reference(&parameters, 0) = DDS_String_dup("5"); *DDS_StringSeq_get_reference(&parameters, 1) = DDS_String_dup("9"); retcode = DDS_ContentFilteredTopic_set_expression_parameters( cft, &parameters); if (retcode != DDS_RETCODE_OK) { printf("set_expression_parameters error\n"); subscriber_shutdown(participant); return -1; } } else if (count == 20) { struct DDS_StringSeq oldParameters; printf("\n==========================\n"); printf("Changing filter parameters\n"); printf("Filter: 3 <= x <= 9\n"); printf("===========================\n"); DDS_ContentFilteredTopic_get_expression_parameters( cft, &oldParameters); DDS_String_free(DDS_StringSeq_get(&oldParameters, 0)); *DDS_StringSeq_get_reference(&oldParameters, 0) = DDS_String_dup("3"); retcode = DDS_ContentFilteredTopic_set_expression_parameters( cft, &oldParameters); if (retcode != DDS_RETCODE_OK) { printf("set_expression_parameters error\n"); subscriber_shutdown(participant); return -1; } } } /* Cleanup and delete all entities */ return subscriber_shutdown(participant); } #if defined(RTI_WINCE) int wmain(int argc, wchar_t **argv) { int domainId = 0; int sample_count = 0; /* infinite loop */ if (argc >= 2) { domainId = _wtoi(argv[1]); } if (argc >= 3) { sample_count = _wtoi(argv[2]); } /* Uncomment this to turn on additional logging NDDS_Config_Logger_set_verbosity_by_category( NDDS_Config_Logger_get_instance(), NDDS_CONFIG_LOG_CATEGORY_API, NDDS_CONFIG_LOG_VERBOSITY_STATUS_ALL); */ return subscriber_main(domainId, sample_count); } #elif !(defined(RTI_VXWORKS) && !defined(__RTP__)) && !defined(RTI_PSOS) int main(int argc, char *argv[]) { int domainId = 0; int sample_count = 0; /* infinite loop */ int sel_cft = 1; /* Use content filtered topic? */ if (argc >= 2) { domainId = atoi(argv[1]); } if (argc >= 3) { sample_count = atoi(argv[2]); } if (argc >= 4) { sel_cft = atoi(argv[3]); } /* Uncomment this to turn on additional logging NDDS_Config_Logger_set_verbosity_by_category( NDDS_Config_Logger_get_instance(), NDDS_CONFIG_LOG_CATEGORY_API, NDDS_CONFIG_LOG_VERBOSITY_STATUS_ALL); */ return subscriber_main(domainId, sample_count, sel_cft); } #endif #ifdef RTI_VX653 const unsigned char *__ctype = NULL; void usrAppInit() { #ifdef USER_APPL_INIT USER_APPL_INIT; /* for backwards compatibility */ #endif /* add application specific code here */ taskSpawn( "sub", RTI_OSAPI_THREAD_PRIORITY_NORMAL, 0x8, 0x150000, (FUNCPTR) subscriber_main, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0); } #endif
c
rticonnextdds-examples
data/projects/rticonnextdds-examples/connext_dds/content_filtered_topic/c++03/cft_publisher.cxx
/******************************************************************************* (c) 2005-2015 Copyright, Real-Time Innovations, Inc. All rights reserved. RTI grants Licensee a license to use, modify, compile, and create derivative works of the Software. Licensee has the right to distribute object form only for use with RTI products. The Software is provided "as is", with no warranty of any type, including any warranty for fitness for any purpose. RTI is under no obligation to maintain or support the Software. RTI shall not be liable for any incidental or consequential damages arising out of the use or inability to use the software. ******************************************************************************/ #include "cft.hpp" #include <dds/dds.hpp> using namespace dds::core; using namespace dds::core::policy; using namespace dds::domain; using namespace dds::topic; using namespace dds::pub; using namespace dds::pub::qos; void publisher_main(int domain_id, int sample_count) { // To customize any of the entities QoS, use // the configuration file USER_QOS_PROFILES.xml DomainParticipant participant(domain_id); Topic<cft> topic(participant, "Example cft"); DataWriterQos writer_qos = QosProvider::Default().datawriter_qos(); // If you want to set the reliability and history QoS settings // programmatically rather than using the XML, you will need to comment out // the following lines of code. // writer_qos << Reliability::Reliable() // << Durability::TransientLocal() // << History::KeepLast(20); DataWriter<cft> writer(Publisher(participant), topic, writer_qos); // Create data sample for writing cft instance; // For a data type that has a key, if the same instance is going to be // written multiple times, initialize the key here // and register the keyed instance prior to writing. InstanceHandle instance_handle = InstanceHandle::nil(); // instance_handle = writer.register_instance(instance); // Main loop for (int count = 0; (sample_count == 0) || (count < sample_count); ++count) { // Modify the data to be sent here // Our purpose is to increment x every time we send a sample and to // reset the x counter to 0 every time we send 10 samples (x=0,1,..,9). // Using the value of count, we can get set x to the appropriate value // applying % 10 operation to it. instance.count(count); instance.x(count % 10); std::cout << "Writing cft, count " << instance.count() << "\t" << "x=" << instance.x() << std::endl; writer.write(instance, instance_handle); // Send a new sample every second rti::util::sleep(Duration(1)); } // writer.unregister_instance(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/content_filtered_topic/c++03/cft_subscriber.cxx
/******************************************************************************* (c) 2005-2015 Copyright, Real-Time Innovations, Inc. All rights reserved. RTI grants Licensee a license to use, modify, compile, and create derivative works of the Software. Licensee has the right to distribute object form only for use with RTI products. The Software is provided "as is", with no warranty of any type, including any warranty for fitness for any purpose. RTI is under no obligation to maintain or support the Software. RTI shall not be liable for any incidental or consequential damages arising out of the use or inability to use the software. ******************************************************************************/ #include "cft.hpp" #include <dds/dds.hpp> #include <rti/core/ListenerBinder.hpp> using namespace dds::core; using namespace dds::core::status; using namespace dds::core::policy; using namespace dds::domain; using namespace dds::topic; using namespace dds::sub; using namespace dds::sub::qos; class CftListener : public NoOpDataReaderListener<cft> { public: void on_data_available(DataReader<cft> &reader) { // Take the available data LoanedSamples<cft> samples = reader.take(); // Print samples by copying to std::cout for (LoanedSamples<cft>::iterator sampleIt = samples.begin(); sampleIt != samples.end(); ++sampleIt) { if (sampleIt->info().valid()) { std::cout << sampleIt->data() << std::endl; } } } }; void subscriber_main(int domain_id, int sample_count, bool is_cft) { // To customize any of the entities QoS, use // the configuration file USER_QOS_PROFILES.xml DomainParticipant participant(domain_id); Topic<cft> topic(participant, "Example cft"); // Sequence of parameters for the content filter expression std::vector<std::string> parameters(2); // The default parameter list that we will include in the // sequence of parameters will be "1", "4" (i.e., 1 <= x <= 4). parameters[0] = "1"; parameters[1] = "4"; if (is_cft) { std::cout << std::endl << "==========================" << std::endl << "Using CFT" << std::endl << "Filter: 1 <= x <= 4" << std::endl << "==========================" << std::endl; } DataReaderQos reader_qos = QosProvider::Default().datareader_qos(); // If you want to set the reliability and history QoS settings // programmatically rather than using the XML, you will need to comment out // the following lines of code. // reader_qos << Reliability::Reliable() // << Durability::TransientLocal() // << History::KeepLast(20); // Create the content filtered topic in the case sel_cft is true // The Content Filter Expresion has two parameters: // - %0 -- x must be greater or equal than %0. // - %1 -- x must be less or equal than %1. ContentFilteredTopic<cft> cft_topic = dds::core::null; DataReader<cft> reader = dds::core::null; if (is_cft) { std::cout << "Using ContentFiltered Topic" << std::endl; cft_topic = ContentFilteredTopic<cft>( topic, "ContentFilteredTopic", Filter("x >= %0 AND x <= %1", parameters)); reader = DataReader<cft>(Subscriber(participant), cft_topic, reader_qos); } else { std::cout << "Using Normal Topic" << std::endl; reader = DataReader<cft>(Subscriber(participant), topic, reader_qos); } // Create a data reader listener using ListenerBinder, a RAII that // will take care of setting it to NULL on destruction. rti::core::ListenerBinder<DataReader<cft> > scoped_listener = rti::core::bind_and_manage_listener( reader, new CftListener, StatusMask::data_available()); // Main loop for (int count = 0; (sample_count == 0) || (count < sample_count); ++count) { // Receive period of 1 second. rti::util::sleep(Duration(1)); // If we are not using CFT, we do not need to change the filter // parameters if (!is_cft) { continue; } if (count == 10) { std::cout << std::endl << "==========================" << std::endl << "Changing filter parameters" << std::endl << "Filter: 5 <= x <= 9" << std::endl << "==========================" << std::endl; parameters[0] = "5"; parameters[1] = "9"; cft_topic.filter_parameters(parameters.begin(), parameters.end()); } else if (count == 20) { std::cout << std::endl << "==========================" << std::endl << "Changing filter parameters" << std::endl << "Filter: 3 <= x <= 9" << std::endl << "==========================" << std::endl; parameters[0] = "3"; cft_topic.filter_parameters(parameters.begin(), parameters.end()); } } } int main(int argc, char *argv[]) { int domain_id = 0; int sample_count = 0; // Infinite loop bool is_cft = true; // Use content filtered topic? if (argc >= 2) { domain_id = atoi(argv[1]); } if (argc >= 3) { sample_count = atoi(argv[2]); } if (argc >= 4) { is_cft = (argv[3][0] == '1'); } // To turn on additional logging, include <rti/config/Logger.hpp> and // uncomment the following line: // rti::config::Logger::instance().verbosity(rti::config::Verbosity::STATUS_ALL); try { subscriber_main(domain_id, sample_count, is_cft); } catch (const std::exception &ex) { // This will catch DDS exceptions std::cerr << "Exception in subscriber_main(): " << ex.what() << std::endl; return -1; } return 0; }
cxx
rticonnextdds-examples
data/projects/rticonnextdds-examples/connext_dds/content_filtered_topic/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; bool use_cft; ApplicationArguments( ParseReturn parse_result_param, unsigned int domain_id_param, unsigned int sample_count_param, rti::config::Verbosity verbosity_param, bool use_cft_param) : parse_result(parse_result_param), domain_id(domain_id_param), sample_count(sample_count_param), verbosity(verbosity_param), use_cft(use_cft_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); bool use_cft = true; while (arg_processing < argc) { if ((argc > arg_processing + 1) && (strcmp(argv[arg_processing], "-d") == 0 || strcmp(argv[arg_processing], "--domain") == 0)) { domain_id = atoi(argv[arg_processing + 1]); arg_processing += 2; } else if ( (argc > arg_processing + 1) && (strcmp(argv[arg_processing], "-s") == 0 || strcmp(argv[arg_processing], "--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 if (strcmp(argv[arg_processing], "--normal-topic") == 0) { use_cft = false; arg_processing += 1; } 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\n" " --normal-topic (subscriber only) If this " "argument\n" " is given, it will use a " "normal\n" " Topic instead of a Content " "Filtered\n" " Topic." << std::endl; } return ApplicationArguments( parse_result, domain_id, sample_count, verbosity, use_cft); } } // namespace application #endif // APPLICATION_HPP
hpp
rticonnextdds-examples
data/projects/rticonnextdds-examples/connext_dds/content_filtered_topic/c++11/cft_publisher.cxx
/******************************************************************************* (c) 2005-2015 Copyright, Real-Time Innovations, Inc. All rights reserved. RTI grants Licensee a license to use, modify, compile, and create derivative works of the Software. Licensee has the right to distribute object form only for use with RTI products. The Software is provided "as is", with no warranty of any type, including any warranty for fitness for any purpose. RTI is under no obligation to maintain or support the Software. RTI shall not be liable for any incidental or consequential damages arising out of the use or inability to use the software. ******************************************************************************/ #include <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 "cft.hpp" void run_publisher_application( unsigned int domain_id, unsigned int sample_count) { // To customize any of the entities QoS, use // the configuration file USER_QOS_PROFILES.xml dds::domain::DomainParticipant participant(domain_id); dds::topic::Topic<cft> topic(participant, "Example cft"); dds::pub::qos::DataWriterQos writer_qos = dds::core::QosProvider::Default().datawriter_qos(); // If you want to set the reliability and history QoS settings // programmatically rather than using the XML, you will need to comment out // the following lines of code. // writer_qos << Reliability::Reliable() // << Durability::TransientLocal() // << History::KeepLast(20); dds::pub::Publisher publisher(participant); dds::pub::DataWriter<cft> writer(publisher, topic, writer_qos); // Create data sample for writing cft instance; // 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. dds::core::InstanceHandle instance_handle = dds::core::InstanceHandle::nil(); // instance_handle = writer.register_instance(instance); // Main loop for (unsigned int samples_written = 0; !application::shutdown_requested && samples_written < sample_count; samples_written++) { // Modify the data to be sent here // Our purpose is to increment x every time we send a sample and to // reset the x counter to 0 every time we send 10 samples (x=0,1,..,9). // Using the value of count, we can get set x to the appropriate value // applying % 10 operation to it. instance.count(samples_written); instance.x(samples_written % 10); std::cout << "Writing cft, count " << instance.count() << "\t" << "x=" << instance.x() << std::endl; writer.write(instance, instance_handle); // Send a new sample every second rti::util::sleep(dds::core::Duration(1)); } // writer.unregister_instance(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/content_filtered_topic/c++11/cft_subscriber.cxx
/******************************************************************************* (c) 2005-2015 Copyright, Real-Time Innovations, Inc. All rights reserved. RTI grants Licensee a license to use, modify, compile, and create derivative works of the Software. Licensee has the right to distribute object form only for use with RTI products. The Software is provided "as is", with no warranty of any type, including any warranty for fitness for any purpose. RTI is under no obligation to maintain or support the Software. RTI shall not be liable for any incidental or consequential damages arising out of the use or inability to use the software. ******************************************************************************/ #include <dds/sub/ddssub.hpp> #include <dds/core/ddscore.hpp> #include <rti/config/Logger.hpp> // for logging #include "cft.hpp" #include "application.hpp" // for command line parsing and ctrl-c int process_data(dds::sub::DataReader<cft> reader) { int count = 0; // Take the available data dds::sub::LoanedSamples<cft> samples = reader.take(); for (const auto &sample : samples) { if (sample.info().valid()) { count++; std::cout << sample.data() << std::endl; } } return count; } void run_subscriber_application( unsigned int domain_id, unsigned int sample_count, bool is_cft) { // To customize any of the entities QoS, use // the configuration file USER_QOS_PROFILES.xml dds::domain::DomainParticipant participant(domain_id); dds::topic::Topic<cft> topic(participant, "Example cft"); if (is_cft) { std::cout << std::endl << "==========================" << std::endl << "Using CFT" << std::endl << "Filter: 1 <= x <= 4" << std::endl << "==========================" << std::endl; } dds::sub::qos::DataReaderQos reader_qos = dds::core::QosProvider::Default().datareader_qos(); // If you want to set the reliability and history QoS settings // programmatically rather than using the XML, you will need to comment out // the following lines of code. // reader_qos << Reliability::Reliable() // << Durability::TransientLocal() // << History::KeepLast(20); // Create the content filtered topic in the case sel_cft is true // The Content Filter Expresion has two parameters: // - %0 -- x must be greater or equal than %0. // - %1 -- x must be less or equal than %1. dds::topic::ContentFilteredTopic<cft> cft_topic = dds::core::null; dds::sub::DataReader<cft> reader = dds::core::null; dds::sub::Subscriber subscriber(participant); if (is_cft) { std::cout << "Using ContentFiltered Topic" << std::endl; cft_topic = dds::topic::ContentFilteredTopic<cft>( topic, "ContentFilteredTopic", dds::topic::Filter("x >= %0 AND x <= %1", { "1", "4" })); reader = dds::sub::DataReader<cft>(subscriber, cft_topic, reader_qos); } else { std::cout << "Using Normal Topic" << std::endl; reader = dds::sub::DataReader<cft>(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; bool filter_changed1 = false; bool filter_changed2 = false; // Main loop while (!application::shutdown_requested && samples_read < sample_count) { // Wait for data and report if it does not arrive in 1 second waitset.dispatch(dds::core::Duration(1)); // If we are not using CFT, we do not need to change the filter // parameters if (!is_cft) { continue; } if (samples_read == 10 && !filter_changed1) { std::cout << std::endl << "==========================" << std::endl << "Changing filter parameters" << std::endl << "Filter: 5 <= x <= 9" << std::endl << "==========================" << std::endl; std::vector<std::string> parameters { "5", "9" }; cft_topic.filter_parameters(parameters.begin(), parameters.end()); filter_changed1 = true; } else if (samples_read == 20 && !filter_changed2) { std::cout << std::endl << "==========================" << std::endl << "Changing filter parameters" << std::endl << "Filter: 3 <= x <= 9" << std::endl << "==========================" << std::endl; std::vector<std::string> parameters { "3", "9" }; cft_topic.filter_parameters(parameters.begin(), parameters.end()); filter_changed2 = true; } } } 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, arguments.use_cft); } 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/high_priority_first_flow_controller/c++/hpf_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 <stdio.h> #include <stdlib.h> #include "hpf.h" #include "hpfSupport.h" #include "ndds/ndds_cpp.h" class hpfListener : 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 hpfListener::on_data_available(DDSDataReader *reader) { hpfDataReader *hpf_reader = NULL; hpfSeq data_seq; DDS_SampleInfoSeq info_seq; DDS_ReturnCode_t retcode; int i; hpf_reader = hpfDataReader::narrow(reader); if (hpf_reader == NULL) { fprintf(stderr, "DataReader narrow error\n"); return; } retcode = hpf_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"); hpfTypeSupport::print_data(&data_seq[i]); } } retcode = hpf_reader->return_loan(data_seq, info_seq); if (retcode != DDS_RETCODE_OK) { fprintf(stderr, "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) { 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; } } /* 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) { fprintf(stderr, "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; hpfListener *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) { fprintf(stderr, "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) { fprintf(stderr, "create_subscriber error\n"); subscriber_shutdown(participant); return -1; } /* Register the type before creating the topic */ type_name = hpfTypeSupport::get_type_name(); retcode = hpfTypeSupport::register_type(participant, type_name); if (retcode != DDS_RETCODE_OK) { fprintf(stderr, "register_type error %d\n", retcode); subscriber_shutdown(participant); return -1; } /* To customize the topic QoS, use the configuration file USER_QOS_PROFILES.xml */ topic = participant->create_topic( "Example hpf", 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; } /* Create a data reader listener */ reader_listener = new hpfListener(); /* 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) { fprintf(stderr, "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("hpf 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 */ if (argc >= 2) { domain_id = 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(domain_id, sample_count); }
cxx
rticonnextdds-examples
data/projects/rticonnextdds-examples/connext_dds/high_priority_first_flow_controller/c++/hpf_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. ******************************************************************************/ /* hpf_publisher.cxx A publication of data of type hpf This file is derived from code automatically generated by the rtiddsgen command: rtiddsgen -language C++ -example <arch> hpf.idl Example publication of type hpf 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>/hpf_subscriber <domain_id> <sample_count> (3) Start the publication with the command objs/<arch>/hpf_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>/hpf_publisher <domain_id> o objs/<arch>/hpf_subscriber <domain_id> On Windows: objs\<arch>\hpf_publisher <domain_id> objs\<arch>\hpf_subscriber <domain_id> modification history ------------ ------- */ #include <stdio.h> #include <stdlib.h> #ifdef RTI_VX653 #include <vThreadsData.h> #endif #include "hpf.h" #include "hpfSupport.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; hpfDataWriter *hpf_writer = NULL; hpf *instance = NULL; DDS_ReturnCode_t retcode; DDS_InstanceHandle_t instance_handle = DDS_HANDLE_NIL; const char *type_name = NULL; int count = 0; DDS_Duration_t send_period = { 4, 0 }; /* To customize participant QoS, use the configuration file USER_QOS_PROFILES.xml */ participant = DDSTheParticipantFactory->create_participant( domainId, DDS_PARTICIPANT_QOS_DEFAULT, NULL /* listener */, DDS_STATUS_MASK_NONE); if (participant == NULL) { printf("create_participant error\n"); publisher_shutdown(participant); return -1; } /* 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 = hpfTypeSupport::get_type_name(); retcode = hpfTypeSupport::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 hpf", 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; } hpf_writer = hpfDataWriter::narrow(writer); if (hpf_writer == NULL) { printf("DataWriter narrow error\n"); publisher_shutdown(participant); return -1; } /* Create data sample for writing */ instance = hpfTypeSupport::create_data(); if (instance == NULL) { printf("hpfTypeSupport::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 = hpf_writer->register_instance(*instance); */ instance->payload.ensure_length( HPF_MAX_PAYLOAD_SIZE, HPF_MAX_PAYLOAD_SIZE); //<<HPF>> /* Main loop */ for (count = 0; (sample_count == 0) || (count < sample_count); ++count) { printf("Writing hpf, count %d\n", count); /* Modify the data to be sent here */ retcode = hpf_writer->write(*instance, instance_handle); if (retcode != DDS_RETCODE_OK) { printf("write error %d\n", retcode); } NDDSUtility::sleep(send_period); } /* retcode = hpf_writer->unregister_instance( *instance, instance_handle); if (retcode != DDS_RETCODE_OK) { printf("unregister instance error %d\n", retcode); } */ /* Delete data sample */ retcode = hpfTypeSupport::delete_data(instance); if (retcode != DDS_RETCODE_OK) { printf("hpfTypeSupport::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/high_priority_first_flow_controller/c++98/hpf_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 "hpf.h" #include "hpfSupport.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(hpfDataReader *typed_reader) { hpfSeq 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"; hpfTypeSupport::print_data(&data_seq[i]); samples_read++; } } DDS_ReturnCode_t retcode = typed_reader->return_loan(data_seq, info_seq); if (retcode != DDS_RETCODE_OK) { std::cerr << "return loan error " << retcode << std::endl; } return samples_read; } int run_subscriber_application( unsigned int domain_id, unsigned int sample_count) { DDS_Duration_t wait_timeout = { 4, 0 }; // Start communicating in a domain, usually one participant per application DDSDomainParticipant *participant = DDSTheParticipantFactory->create_participant( domain_id, DDS_PARTICIPANT_QOS_DEFAULT, NULL /* listener */, DDS_STATUS_MASK_NONE); if (participant == NULL) { return shutdown_participant( participant, "create_participant error", EXIT_FAILURE); } // A Subscriber allows an application to create one or more DataReaders DDSSubscriber *subscriber = participant->create_subscriber( DDS_SUBSCRIBER_QOS_DEFAULT, NULL /* listener */, DDS_STATUS_MASK_NONE); if (subscriber == NULL) { return shutdown_participant( participant, "create_subscriber error", EXIT_FAILURE); } // Register the datatype to use when creating the Topic const char *type_name = hpfTypeSupport::get_type_name(); DDS_ReturnCode_t retcode = hpfTypeSupport::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 hpf", 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 hpf" 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 hpfDataReader *typed_reader = hpfDataReader::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); } else if (retcode == DDS_RETCODE_TIMEOUT) { std::cout << "No data after " << wait_timeout.sec << " seconds" << std::endl; } } // Cleanup 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_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/high_priority_first_flow_controller/c++98/hpf_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 "hpf.h" #include "hpfSupport.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 }; // 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 = hpfTypeSupport::get_type_name(); DDS_ReturnCode_t retcode = hpfTypeSupport::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 hpf", 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 hpf" 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 hpfDataWriter *typed_writer = hpfDataWriter::narrow(untyped_writer); if (untyped_writer == NULL) { return shutdown_participant( participant, "DataWriter narrow error", EXIT_FAILURE); } // Create data for writing, allocating all members hpf *data = hpfTypeSupport::create_data(); if (data == NULL) { return shutdown_participant( participant, "hpfTypeSupport::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); */ data->payload.ensure_length( HPF_MAX_PAYLOAD_SIZE, HPF_MAX_PAYLOAD_SIZE); //<<HPF>> // Main loop, write data for (unsigned int samples_written = 0; !shutdown_requested && samples_written < sample_count; ++samples_written) { std::cout << "Writing hpf " << samples_written << std::endl; /* Modify the data to be sent here */ retcode = typed_writer->write(*data, instance_handle); if (retcode != DDS_RETCODE_OK) { std::cout << "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 hpf, including all contained elements retcode = hpfTypeSupport::delete_data(data); if (retcode != DDS_RETCODE_OK) { std::cout << "hpfTypeSupport::delete_data error " << retcode << std::endl; } // Cleanup 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/high_priority_first_flow_controller/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/lambda_content_filter/c++11/LambdaFilterExample_publisher.cxx
/******************************************************************************* (c) 2005-2015 Copyright, Real-Time Innovations, Inc. All rights reserved. RTI grants Licensee a license to use, modify, compile, and create derivative works of the Software. Licensee has the right to distribute object form only for use with RTI products. The Software is provided "as is", with no warranty of any type, including any warranty for fitness for any purpose. RTI is under no obligation to maintain or support the Software. RTI shall not be liable for any incidental or consequential damages arising out of the use or inability to use the software. ******************************************************************************/ #include <iostream> #include <random> #include <dds/pub/ddspub.hpp> #include <rti/util/util.hpp> // for sleep() #include <rti/config/Logger.hpp> // for logging #include "LambdaFilterExample.hpp" #include "LambdaFilter.hpp" #include "application.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); // Register the same filter we use in the subscriber. // // This is *optional*, but recommended for better network usage. By // registering the filter on this participant, we allow the DataWriter to // filter the samples it writes before sending them. // // Note that the filter name and its definition need to be identical to the // one in the subscribing application. // create_lambda_filter<Stock>( "stock_cft", participant, [](const Stock &stock) { return stock.symbol() == "GOOG" || stock.symbol() == "IBM"; }); // Create a Topic -- and automatically register the type dds::topic::Topic<Stock> topic(participant, "Example Stock"); // Create a DataWriter with default Qos (Publisher created in-line) dds::pub::DataWriter<Stock> writer(dds::pub::Publisher(participant), topic); Stock sample; std::vector<std::string> symbols { "GOOG", "IBM", "RTI", "MSFT" }; std::random_device random_device; std::uniform_int_distribution<int> distribution(0, symbols.size() - 1); for (unsigned int samples_written = 0; !application::shutdown_requested && samples_written < sample_count; samples_written++) { // Modify the data to be written here sample.symbol(symbols[distribution(random_device)]); sample.value(distribution(random_device) * 1.1); // Print the sample we're writting std::cout << "Writing " << sample << std::endl; writer.write(sample); // Print whether the sample was pushed on the network (to the // DataReader) or not (for example, because it was locally filtered out) auto pushed_samples = writer->datawriter_protocol_status() .pushed_sample_count() .change(); std::cout << "Sample was " << (pushed_samples != 0 ? "pushed" : "not pushed") << std::endl; rti::util::sleep(dds::core::Duration(4)); } } int main(int argc, char *argv[]) { 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/lambda_content_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/lambda_content_filter/c++11/LambdaFilter.hpp
/******************************************************************************* (c) 2005-2015 Copyright, Real-Time Innovations, Inc. All rights reserved. RTI grants Licensee a license to use, modify, compile, and create derivative works of the Software. Licensee has the right to distribute object form only for use with RTI products. The Software is provided "as is", with no warranty of any type, including any warranty for fitness for any purpose. RTI is under no obligation to maintain or support the Software. RTI shall not be liable for any incidental or consequential damages arising out of the use or inability to use the software. ******************************************************************************/ #include <dds/topic/Filter.hpp> #include <rti/topic/ContentFilter.hpp> // // A generic ContentFilter that works with a lambda function. // // Since this filter is fully defined at compile time, it doesn't expect // any expression or parameters. // template <typename T> class LambdaFilter : public rti::topic::ContentFilter<T> { public: // The expected function signature: takes a sample of type T and decides // whether it passes the filter (return true) or not (return false). typedef std::function<bool(const T &)> LambdaType; // Creates a LambdaFilter with the given filter function LambdaFilter(LambdaType f) : filter_(f) { } rti::topic::no_compile_data_t & compile(const std::string &expression, const dds::core::StringSeq &parameters, const dds::core::optional<dds::core::xtypes::DynamicType> &type_code, const std::string &type_class_name, rti::topic::no_compile_data_t *old_compile_data) override { // Nothing to compile, the lambda function does everything! return rti::topic::no_compile_data; } bool evaluate( rti::topic::no_compile_data_t &compile_data, const T &sample, const rti::topic::FilterSampleInfo &meta_data) override { // Run the function return filter_(sample); } void finalize(rti::topic::no_compile_data_t &compile_data) override { // Nothing to finalize } private: LambdaType filter_; // The function used to filter }; // Creates and register in the participant with the given name // a new custom filter based on a lambda function. // // The filter can be used to create ContentFilteredTopics, QueryConditions or // to enable DataWriters to perform writer-side // filtering for DataReaders using a filter with the same name. // // @param name The name used to register the filter on the participant. This // name is also used to allow a DataWriter to filter samples before sending them // to a DataReader that uses a ContentFilteredTopic with the same filter. If the // names are equal, the DataWriter will use his filter, so the lambda function // should also be the same. // // @param participant The participant where to register the filter so its // DataWriters and DataReaders can use it. // // @param lambda_func The function that decides if a sample of type T // passes the filter or not. The function must have a single argument of type // const T& and return a bool. // // @return A Filter object that can be used to create a ContentFilteredTopic, // or a QueryCondition. // template <typename T> dds::topic::Filter create_lambda_filter( const std::string &name, dds::domain::DomainParticipant participant, typename LambdaFilter<T>::LambdaType lambda_func) { participant->register_contentfilter( rti::topic::CustomFilter<LambdaFilter<T>>( new LambdaFilter<T>(lambda_func)), name); dds::topic::Filter filter(""); // no expression filter->name(name); return filter; } // Uses the Filter that create_lambda_filter() returns to create // a ContentFilteredTopic for the given Topic. template <typename T> dds::topic::ContentFilteredTopic<T> create_lambda_cft( const std::string &name, dds::topic::Topic<T> &topic, typename LambdaFilter<T>::LambdaType lambda_func) { return dds::topic::ContentFilteredTopic<T>( topic, name, create_lambda_filter<T>(name, topic.participant(), lambda_func)); }
hpp
rticonnextdds-examples
data/projects/rticonnextdds-examples/connext_dds/lambda_content_filter/c++11/LambdaFilterExample_subscriber.cxx
/******************************************************************************* (c) 2005-2015 Copyright, Real-Time Innovations, Inc. All rights reserved. RTI grants Licensee a license to use, modify, compile, and create derivative works of the Software. Licensee has the right to distribute object form only for use with RTI products. The Software is provided "as is", with no warranty of any type, including any warranty for fitness for any purpose. RTI is under no obligation to maintain or support the Software. RTI shall not be liable for any incidental or consequential damages arising out of the use or inability to use the software. ******************************************************************************/ #include <algorithm> #include <iostream> #include <dds/core/ddscore.hpp> #include <dds/sub/ddssub.hpp> // Or simply include <dds/dds.hpp> #include <rti/config/Logger.hpp> // for logging #include "LambdaFilterExample.hpp" #include "LambdaFilter.hpp" #include "application.hpp" // for command line parsing and ctrl-c void run_subscriber_application( unsigned int domain_id, unsigned int sample_count) { dds::domain::DomainParticipant participant(domain_id); dds::topic::Topic<Stock> topic(participant, "Example Stock"); // Create a ContentFilteredTopic that only selects those Stocks whose // symbol is GOOG or IBM. auto lambda_cft = create_lambda_cft<Stock>( "stock_cft", topic, [](const Stock &stock) { return stock.symbol() == "GOOG" || stock.symbol() == "IBM"; }); dds::sub::DataReader<Stock> reader( dds::sub::Subscriber(participant), lambda_cft); // Create a ReadCondition for any data on this reader and associate a // handler int count = 0; dds::sub::cond::ReadCondition read_condition( reader, dds::sub::status::DataState::any(), [&reader, &count]() { // Take all samples dds::sub::LoanedSamples<Stock> samples = reader.take(); for (auto sample : samples) { if (sample.info().valid()) { count++; std::cout << sample.data() << std::endl; } } } // The LoanedSamples destructor returns the loan ); // Create a WaitSet and attach the ReadCondition dds::core::cond::WaitSet waitset; waitset += read_condition; while (!application::shutdown_requested && count < sample_count) { // Dispatch will call the handlers associated to the WaitSet conditions // when they activate std::cout << "Stock subscriber sleeping for 4 sec...\n"; waitset.dispatch(dds::core::Duration(4)); // Wait up to 4s each time } } int main(int argc, char *argv[]) { 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/detect_samples_dropped/c++/DroppedSamplesExample_subscriber.cxx
/* * (c) Copyright, Real-Time Innovations, 2021. All rights reserved. * RTI grants Licensee a license to use, modify, compile, and create derivative * works of the software solely for use with RTI Connext DDS. Licensee may * redistribute copies of the software provided that all such copies are subject * to this license. The software is provided "as is", with no warranty of any * type, including any warranty for fitness for any purpose. RTI is under no * obligation to maintain or support the software. RTI shall not be liable for * any incidental or consequential damages arising out of the use or inability * to use the software. */ #include <iostream> #include <stdio.h> #include <stdlib.h> #include "DroppedSamplesExample.h" #include "DroppedSamplesExampleSupport.h" #include "ndds/ndds_cpp.h" #include "application.h" using namespace application; static int shutdown_participant( DDSDomainParticipant *participant, const char *shutdown_message, int status); // Process data. Returns number of samples processed. unsigned int process_data(DroppedSamplesExampleDataReader *typed_reader) { DroppedSamplesExampleSeq data_seq; // Sequence of received data DDS_SampleInfoSeq info_seq; // Metadata associated with samples in data_seq unsigned int samples_read = 0; // Take available data from DataReader's queue typed_reader->take( data_seq, info_seq, DDS_LENGTH_UNLIMITED, DDS_ANY_SAMPLE_STATE, DDS_ANY_VIEW_STATE, DDS_ANY_INSTANCE_STATE); // Iterate over all available data for (int i = 0; i < data_seq.length(); ++i) { // Check if a sample is an instance lifecycle event if (info_seq[i].valid_data) { // Print data std::cout << "Received data" << std::endl; DroppedSamplesExampleTypeSupport::print_data(&data_seq[i]); samples_read++; } else { // This is an instance lifecycle event with no data payload. std::cout << "Received instance state notification" << std::endl; } } // Data loaned from Connext for performance. Return loan when done. DDS_ReturnCode_t retcode = typed_reader->return_loan(data_seq, info_seq); if (retcode != DDS_RETCODE_OK) { std::cerr << "return loan error " << retcode << std::endl; } return samples_read; } int run_subscriber_application( unsigned int domain_id, unsigned int sample_count) { // Start communicating in a domain, usually one participant per application DDSDomainParticipant *participant = DDSTheParticipantFactory->create_participant( domain_id, DDS_PARTICIPANT_QOS_DEFAULT, NULL, // listener DDS_STATUS_MASK_NONE); if (participant == NULL) { return shutdown_participant( participant, "create_participant error", EXIT_FAILURE); } // A Subscriber allows an application to create one or more DataReaders DDSSubscriber *subscriber = participant->create_subscriber( DDS_SUBSCRIBER_QOS_DEFAULT, NULL, // listener DDS_STATUS_MASK_NONE); if (subscriber == NULL) { return shutdown_participant( participant, "create_subscriber error", EXIT_FAILURE); } // Register the datatype to use when creating the Topic const char *type_name = DroppedSamplesExampleTypeSupport::get_type_name(); DDS_ReturnCode_t retcode = DroppedSamplesExampleTypeSupport::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 DroppedSamplesExample", type_name, DDS_TOPIC_QOS_DEFAULT, NULL, // listener DDS_STATUS_MASK_NONE); if (topic == NULL) { return shutdown_participant( participant, "create_topic error", EXIT_FAILURE); } DDS_StringSeq parameters(0); parameters.length(0); DDSContentFilteredTopic *cft = participant->create_contentfilteredtopic( "Example DroppedSamplesExample CFT", topic, "x < 4", parameters); if (cft == NULL) { return shutdown_participant( participant, "create_contentfilteredtopic error", EXIT_FAILURE); } DDS_DataReaderQos reader_qos; retcode = subscriber->get_default_datareader_qos(reader_qos); if (retcode != DDS_RETCODE_OK) { return shutdown_participant( participant, "get_default_datareader_qos error", EXIT_FAILURE); } reader_qos.ownership.kind = DDS_EXCLUSIVE_OWNERSHIP_QOS; // This DataReader reads data on "Example DroppedSamplesExample" Topic DDSDataReader *untyped_reader = subscriber->create_datareader( cft, reader_qos, NULL, DDS_STATUS_MASK_NONE); if (untyped_reader == NULL) { return shutdown_participant( participant, "create_datareader error", EXIT_FAILURE); } // Narrow casts from a untyped DataReader to a reader of your type DroppedSamplesExampleDataReader *typed_reader = DroppedSamplesExampleDataReader::narrow(untyped_reader); if (typed_reader == NULL) { return shutdown_participant( participant, "DataReader narrow error", EXIT_FAILURE); } // Create ReadCondition that triggers when unread data in reader's queue DDSReadCondition *read_condition = typed_reader->create_readcondition( DDS_NOT_READ_SAMPLE_STATE, DDS_ANY_VIEW_STATE, DDS_ANY_INSTANCE_STATE); if (read_condition == NULL) { return shutdown_participant( participant, "create_readcondition error", EXIT_FAILURE); } // WaitSet will be woken when the attached condition is triggered DDSWaitSet waitset; retcode = waitset.attach_condition(read_condition); if (retcode != DDS_RETCODE_OK) { return shutdown_participant( participant, "attach_condition error", EXIT_FAILURE); } // Main loop. Wait for data to arrive, and process when it arrives unsigned int samples_read = 0; DDS_DataReaderCacheStatus status; while (!shutdown_requested && samples_read < sample_count) { DDSConditionSeq active_conditions_seq; DDS_Duration_t wait_timeout = { 1, 0 }; retcode = waitset.wait(active_conditions_seq, wait_timeout); if (retcode == DDS_RETCODE_OK) { // If the read condition is triggered, process data samples_read += process_data(typed_reader); } else { if (retcode == DDS_RETCODE_TIMEOUT) { std::cout << "No data after 1 second" << std::endl; } } untyped_reader->get_datareader_cache_status(status); std::cout << "Samples dropped:" << "\n\t ownership_dropped_sample_count " << status.ownership_dropped_sample_count << "\n\t content_filter_dropped_sample_count " << status.content_filter_dropped_sample_count << 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/detect_samples_dropped/c++/DroppedSamplesExample_publisher.cxx
/* * (c) Copyright, Real-Time Innovations, 2021. All rights reserved. * RTI grants Licensee a license to use, modify, compile, and create derivative * works of the software solely for use with RTI Connext DDS. Licensee may * redistribute copies of the software provided that all such copies are subject * to this license. The software is provided "as is", with no warranty of any * type, including any warranty for fitness for any purpose. RTI is under no * obligation to maintain or support the software. RTI shall not be liable for * any incidental or consequential damages arising out of the use or inability * to use the software. */ #include <iostream> #include <stdio.h> #include <stdlib.h> #include "DroppedSamplesExample.h" #include "DroppedSamplesExampleSupport.h" #include "ndds/ndds_cpp.h" #include "application.h" using namespace application; static int shutdown_participant( DDSDomainParticipant *participant, const char *shutdown_message, int status); int run_publisher_application(unsigned int domain_id, unsigned int sample_count) { // Start communicating in a domain, usually one participant per application DDSDomainParticipant *participant = DDSTheParticipantFactory->create_participant( domain_id, DDS_PARTICIPANT_QOS_DEFAULT, NULL, // listener DDS_STATUS_MASK_NONE); if (participant == NULL) { return shutdown_participant( participant, "create_participant error", EXIT_FAILURE); } // A Publisher allows an application to create one or more DataWriters DDSPublisher *publisher = participant->create_publisher( DDS_PUBLISHER_QOS_DEFAULT, NULL, // listener DDS_STATUS_MASK_NONE); if (publisher == NULL) { return shutdown_participant( participant, "create_publisher error", EXIT_FAILURE); } // Register the datatype to use when creating the Topic const char *type_name = DroppedSamplesExampleTypeSupport::get_type_name(); DDS_ReturnCode_t retcode = DroppedSamplesExampleTypeSupport::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 DroppedSamplesExample", 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 detecting samples DroppedSamplesExampleped DDS_DataWriterQos writer_qos; retcode = publisher->get_default_datawriter_qos(writer_qos); if (retcode != DDS_RETCODE_OK) { return shutdown_participant( participant, "get_default_datawriter_qos error", EXIT_FAILURE); } /* Use batching in order to evaluate the CFT in the reader side */ writer_qos.batch.enable = DDS_BOOLEAN_TRUE; writer_qos.batch.max_samples = 1; writer_qos.ownership.kind = DDS_EXCLUSIVE_OWNERSHIP_QOS; writer_qos.ownership_strength.value = 1; // This DataWriter writes data on "Example DroppedSamplesExample" Topic DDSDataWriter *untyped_writer1 = publisher->create_datawriter( topic, writer_qos, NULL, // listener DDS_STATUS_MASK_NONE); if (untyped_writer1 == NULL) { return shutdown_participant( participant, "create_datawriter error", EXIT_FAILURE); } // Narrow casts from an untyped DataWriter to a writer of your type DroppedSamplesExampleDataWriter *typed_writer1 = DroppedSamplesExampleDataWriter::narrow(untyped_writer1); if (typed_writer1 == NULL) { return shutdown_participant( participant, "DataWriter narrow error", EXIT_FAILURE); } writer_qos.ownership_strength.value = 2; // This DataWriter writes data on "Example DroppedSamplesExample" Topic DDSDataWriter *untyped_writer2 = publisher->create_datawriter( topic, writer_qos, NULL, // listener DDS_STATUS_MASK_NONE); if (untyped_writer2 == NULL) { return shutdown_participant( participant, "create_datawriter error", EXIT_FAILURE); } // Narrow casts from an untyped DataWriter to a writer of your type DroppedSamplesExampleDataWriter *typed_writer2 = DroppedSamplesExampleDataWriter::narrow(untyped_writer2); if (typed_writer2 == NULL) { return shutdown_participant( participant, "DataWriter narrow error", EXIT_FAILURE); } // Create data for writing, allocating all members DroppedSamplesExample *data = DroppedSamplesExampleTypeSupport::create_data(); if (data == NULL) { return shutdown_participant( participant, "DroppedSamplesExampleTypeSupport::create_data error", EXIT_FAILURE); } // Main loop, write data for (unsigned int samples_written = 0; !shutdown_requested && samples_written < sample_count; ++samples_written) { // Modify the data to be written here data->x = static_cast<DDS_Short>(samples_written); std::cout << "Writing DroppedSamplesExample, count " << samples_written << std::endl; retcode = typed_writer1->write(*data, DDS_HANDLE_NIL); if (retcode != DDS_RETCODE_OK) { std::cerr << "write error " << retcode << std::endl; } retcode = typed_writer2->write(*data, DDS_HANDLE_NIL); if (retcode != DDS_RETCODE_OK) { std::cerr << "write error " << retcode << std::endl; } // Send once every second DDS_Duration_t send_period = { 1, 0 }; NDDSUtility::sleep(send_period); } // End changes for detecting samples DroppedSamplesExampleped // Delete previously allocated DroppedSamplesExample, including all // contained elements retcode = DroppedSamplesExampleTypeSupport::delete_data(data); if (retcode != DDS_RETCODE_OK) { std::cerr << "DroppedSamplesExampleTypeSupport::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/detect_samples_dropped/c++/application.h
/* * (c) Copyright, Real-Time Innovations, 2021. All rights reserved. * RTI grants Licensee a license to use, modify, compile, and create derivative * works of the software solely for use with RTI Connext DDS. Licensee may * redistribute copies of the software provided that all such copies are subject * to this license. The software is provided "as is", with no warranty of any * type, including any warranty for fitness for any purpose. RTI is under no * obligation to maintain or support the software. RTI shall not be liable for * any incidental or consequential damages arising out of the use or inability * to use the software. */ #ifndef APPLICATION_H #define APPLICATION_H #include <iostream> #include <csignal> #include <climits> namespace application { // Catch control-C and tell application to shut down bool shutdown_requested = false; inline void stop_handler(int) { shutdown_requested = true; std::cout << "preparing to shut down..." << std::endl; } inline void setup_signal_handlers() { signal(SIGINT, stop_handler); signal(SIGTERM, stop_handler); } enum ParseReturn { PARSE_RETURN_OK, PARSE_RETURN_FAILURE, PARSE_RETURN_EXIT }; struct ApplicationArguments { ParseReturn parse_result; unsigned int domain_id; unsigned int sample_count; NDDS_Config_LogVerbosity verbosity; }; // Parses application arguments for example. Returns whether to exit. inline void parse_arguments( ApplicationArguments& arguments, int argc, char *argv[]) { int arg_processing = 1; bool show_usage = false; arguments.domain_id = 0; arguments.sample_count = INT_MAX; arguments.verbosity = NDDS_CONFIG_LOG_VERBOSITY_ERROR; arguments.parse_result = PARSE_RETURN_OK; while (arg_processing < argc) { if ((argc > arg_processing + 1) && (strcmp(argv[arg_processing], "-d") == 0 || strcmp(argv[arg_processing], "--domain") == 0)) { arguments.domain_id = atoi(argv[arg_processing + 1]); arg_processing += 2; } else if ((argc > arg_processing + 1) && (strcmp(argv[arg_processing], "-s") == 0 || strcmp(argv[arg_processing], "--sample-count") == 0)) { arguments.sample_count = atoi(argv[arg_processing + 1]); arg_processing += 2; } else if ((argc > arg_processing + 1) && (strcmp(argv[arg_processing], "-v") == 0 || strcmp(argv[arg_processing], "--verbosity") == 0)) { arguments.verbosity = (NDDS_Config_LogVerbosity) atoi(argv[arg_processing + 1]); arg_processing += 2; } else if (strcmp(argv[arg_processing], "-h") == 0 || strcmp(argv[arg_processing], "--help") == 0) { std::cout << "Example application." << std::endl; show_usage = true; arguments.parse_result = PARSE_RETURN_EXIT; break; } else { std::cout << "Bad parameter." << std::endl; show_usage = true; arguments.parse_result = PARSE_RETURN_FAILURE; break; } } if (show_usage) { std::cout << "Usage:\n"\ " -d, --domain <int> Domain ID this application will\n" \ " subscribe in. \n" " Default: 0\n"\ " -s, --sample_count <int> Number of samples to receive before\n"\ " cleanly shutting down. \n" " Default: infinite\n" " -v, --verbosity <int> How much debugging output to show.\n"\ " Range: 0-5 \n" " Default: 0" << std::endl; } } } // namespace application #endif // APPLICATION_H
h
rticonnextdds-examples
data/projects/rticonnextdds-examples/connext_dds/detect_samples_dropped/c++98/DroppedSamplesExample_subscriber.cxx
/* * (c) Copyright, Real-Time Innovations, 2021. All rights reserved. * RTI grants Licensee a license to use, modify, compile, and create derivative * works of the software solely for use with RTI Connext DDS. Licensee may * redistribute copies of the software provided that all such copies are subject * to this license. The software is provided "as is", with no warranty of any * type, including any warranty for fitness for any purpose. RTI is under no * obligation to maintain or support the software. RTI shall not be liable for * any incidental or consequential damages arising out of the use or inability * to use the software. */ #include <iostream> #include <stdio.h> #include <stdlib.h> #include "DroppedSamplesExample.h" #include "DroppedSamplesExampleSupport.h" #include "ndds/ndds_cpp.h" #include "application.h" using namespace application; static int shutdown_participant( DDSDomainParticipant *participant, const char *shutdown_message, int status); // Process data. Returns number of samples processed. unsigned int process_data(DroppedSamplesExampleDataReader *typed_reader) { DroppedSamplesExampleSeq data_seq; // Sequence of received data DDS_SampleInfoSeq info_seq; // Metadata associated with samples in data_seq unsigned int samples_read = 0; // Take available data from DataReader's queue typed_reader->take( data_seq, info_seq, DDS_LENGTH_UNLIMITED, DDS_ANY_SAMPLE_STATE, DDS_ANY_VIEW_STATE, DDS_ANY_INSTANCE_STATE); // Iterate over all available data for (int i = 0; i < data_seq.length(); ++i) { // Check if a sample is an instance lifecycle event if (info_seq[i].valid_data) { // Print data std::cout << "Received data" << std::endl; DroppedSamplesExampleTypeSupport::print_data(&data_seq[i]); samples_read++; } else { // This is an instance lifecycle event with no data payload. std::cout << "Received instance state notification" << std::endl; } } // Data loaned from Connext for performance. Return loan when done. DDS_ReturnCode_t retcode = typed_reader->return_loan(data_seq, info_seq); if (retcode != DDS_RETCODE_OK) { std::cerr << "return loan error " << retcode << std::endl; } return samples_read; } int run_subscriber_application( unsigned int domain_id, unsigned int sample_count) { // Start communicating in a domain, usually one participant per application DDSDomainParticipant *participant = DDSTheParticipantFactory->create_participant( domain_id, DDS_PARTICIPANT_QOS_DEFAULT, NULL, // listener DDS_STATUS_MASK_NONE); if (participant == NULL) { return shutdown_participant( participant, "create_participant error", EXIT_FAILURE); } // A Subscriber allows an application to create one or more DataReaders DDSSubscriber *subscriber = participant->create_subscriber( DDS_SUBSCRIBER_QOS_DEFAULT, NULL, // listener DDS_STATUS_MASK_NONE); if (subscriber == NULL) { return shutdown_participant( participant, "create_subscriber error", EXIT_FAILURE); } // Register the datatype to use when creating the Topic const char *type_name = DroppedSamplesExampleTypeSupport::get_type_name(); DDS_ReturnCode_t retcode = DroppedSamplesExampleTypeSupport::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 DroppedSamplesExample", type_name, DDS_TOPIC_QOS_DEFAULT, NULL, // listener DDS_STATUS_MASK_NONE); if (topic == NULL) { return shutdown_participant( participant, "create_topic error", EXIT_FAILURE); } DDS_StringSeq parameters(0); parameters.length(0); DDSContentFilteredTopic *cft = participant->create_contentfilteredtopic( "Example DroppedSamplesExample CFT", topic, "x < 4", parameters); if (cft == NULL) { return shutdown_participant( participant, "create_contentfilteredtopic error", EXIT_FAILURE); } DDS_DataReaderQos reader_qos; retcode = subscriber->get_default_datareader_qos(reader_qos); if (retcode != DDS_RETCODE_OK) { return shutdown_participant( participant, "get_default_datareader_qos error", EXIT_FAILURE); } reader_qos.ownership.kind = DDS_EXCLUSIVE_OWNERSHIP_QOS; // This DataReader reads data on "Example DroppedSamplesExample" Topic DDSDataReader *untyped_reader = subscriber->create_datareader( cft, reader_qos, NULL, DDS_STATUS_MASK_NONE); if (untyped_reader == NULL) { return shutdown_participant( participant, "create_datareader error", EXIT_FAILURE); } // Narrow casts from a untyped DataReader to a reader of your type DroppedSamplesExampleDataReader *typed_reader = DroppedSamplesExampleDataReader::narrow(untyped_reader); if (typed_reader == NULL) { return shutdown_participant( participant, "DataReader narrow error", EXIT_FAILURE); } // Create ReadCondition that triggers when unread data in reader's queue DDSReadCondition *read_condition = typed_reader->create_readcondition( DDS_NOT_READ_SAMPLE_STATE, DDS_ANY_VIEW_STATE, DDS_ANY_INSTANCE_STATE); if (read_condition == NULL) { return shutdown_participant( participant, "create_readcondition error", EXIT_FAILURE); } // WaitSet will be woken when the attached condition is triggered DDSWaitSet waitset; retcode = waitset.attach_condition(read_condition); if (retcode != DDS_RETCODE_OK) { return shutdown_participant( participant, "attach_condition error", EXIT_FAILURE); } // Main loop. Wait for data to arrive, and process when it arrives unsigned int samples_read = 0; DDS_DataReaderCacheStatus status; while (!shutdown_requested && samples_read < sample_count) { DDSConditionSeq active_conditions_seq; DDS_Duration_t wait_timeout = { 1, 0 }; retcode = waitset.wait(active_conditions_seq, wait_timeout); if (retcode == DDS_RETCODE_OK) { // If the read condition is triggered, process data samples_read += process_data(typed_reader); } else { if (retcode == DDS_RETCODE_TIMEOUT) { std::cout << "No data after 1 second" << std::endl; } } untyped_reader->get_datareader_cache_status(status); std::cout << "Samples dropped:" << "\n\t ownership_dropped_sample_count " << status.ownership_dropped_sample_count << "\n\t content_filter_dropped_sample_count " << status.content_filter_dropped_sample_count << 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/detect_samples_dropped/c++98/DroppedSamplesExample_publisher.cxx
/* * (c) Copyright, Real-Time Innovations, 2021. All rights reserved. * RTI grants Licensee a license to use, modify, compile, and create derivative * works of the software solely for use with RTI Connext DDS. Licensee may * redistribute copies of the software provided that all such copies are subject * to this license. The software is provided "as is", with no warranty of any * type, including any warranty for fitness for any purpose. RTI is under no * obligation to maintain or support the software. RTI shall not be liable for * any incidental or consequential damages arising out of the use or inability * to use the software. */ #include <iostream> #include <stdio.h> #include <stdlib.h> #include "DroppedSamplesExample.h" #include "DroppedSamplesExampleSupport.h" #include "ndds/ndds_cpp.h" #include "application.h" using namespace application; static int shutdown_participant( DDSDomainParticipant *participant, const char *shutdown_message, int status); int run_publisher_application(unsigned int domain_id, unsigned int sample_count) { // Start communicating in a domain, usually one participant per application DDSDomainParticipant *participant = DDSTheParticipantFactory->create_participant( domain_id, DDS_PARTICIPANT_QOS_DEFAULT, NULL, // listener DDS_STATUS_MASK_NONE); if (participant == NULL) { return shutdown_participant( participant, "create_participant error", EXIT_FAILURE); } // A Publisher allows an application to create one or more DataWriters DDSPublisher *publisher = participant->create_publisher( DDS_PUBLISHER_QOS_DEFAULT, NULL, // listener DDS_STATUS_MASK_NONE); if (publisher == NULL) { return shutdown_participant( participant, "create_publisher error", EXIT_FAILURE); } // Register the datatype to use when creating the Topic const char *type_name = DroppedSamplesExampleTypeSupport::get_type_name(); DDS_ReturnCode_t retcode = DroppedSamplesExampleTypeSupport::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 DroppedSamplesExample", 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 detecting samples DroppedSamplesExampleped DDS_DataWriterQos writer_qos; retcode = publisher->get_default_datawriter_qos(writer_qos); if (retcode != DDS_RETCODE_OK) { return shutdown_participant( participant, "get_default_datawriter_qos error", EXIT_FAILURE); } /* Use batching in order to evaluate the CFT in the reader side */ writer_qos.batch.enable = DDS_BOOLEAN_TRUE; writer_qos.batch.max_samples = 1; writer_qos.ownership.kind = DDS_EXCLUSIVE_OWNERSHIP_QOS; writer_qos.ownership_strength.value = 1; // This DataWriter writes data on "Example DroppedSamplesExample" Topic DDSDataWriter *untyped_writer1 = publisher->create_datawriter( topic, writer_qos, NULL, // listener DDS_STATUS_MASK_NONE); if (untyped_writer1 == NULL) { return shutdown_participant( participant, "create_datawriter error", EXIT_FAILURE); } // Narrow casts from an untyped DataWriter to a writer of your type DroppedSamplesExampleDataWriter *typed_writer1 = DroppedSamplesExampleDataWriter::narrow(untyped_writer1); if (typed_writer1 == NULL) { return shutdown_participant( participant, "DataWriter narrow error", EXIT_FAILURE); } writer_qos.ownership_strength.value = 2; // This DataWriter writes data on "Example DroppedSamplesExample" Topic DDSDataWriter *untyped_writer2 = publisher->create_datawriter( topic, writer_qos, NULL, // listener DDS_STATUS_MASK_NONE); if (untyped_writer2 == NULL) { return shutdown_participant( participant, "create_datawriter error", EXIT_FAILURE); } // Narrow casts from an untyped DataWriter to a writer of your type DroppedSamplesExampleDataWriter *typed_writer2 = DroppedSamplesExampleDataWriter::narrow(untyped_writer2); if (typed_writer2 == NULL) { return shutdown_participant( participant, "DataWriter narrow error", EXIT_FAILURE); } // Create data for writing, allocating all members DroppedSamplesExample *data = DroppedSamplesExampleTypeSupport::create_data(); if (data == NULL) { return shutdown_participant( participant, "DroppedSamplesExampleTypeSupport::create_data error", EXIT_FAILURE); } // Main loop, write data for (unsigned int samples_written = 0; !shutdown_requested && samples_written < sample_count; ++samples_written) { // Modify the data to be written here data->x = static_cast<DDS_Short>(samples_written); std::cout << "Writing DroppedSamplesExample, count " << samples_written << std::endl; retcode = typed_writer1->write(*data, DDS_HANDLE_NIL); if (retcode != DDS_RETCODE_OK) { std::cerr << "write error " << retcode << std::endl; } retcode = typed_writer2->write(*data, DDS_HANDLE_NIL); if (retcode != DDS_RETCODE_OK) { std::cerr << "write error " << retcode << std::endl; } // Send once every second DDS_Duration_t send_period = { 1, 0 }; NDDSUtility::sleep(send_period); } // End changes for detecting samples DroppedSamplesExampleped // Delete previously allocated DroppedSamplesExample, including all // contained elements retcode = DroppedSamplesExampleTypeSupport::delete_data(data); if (retcode != DDS_RETCODE_OK) { std::cerr << "DroppedSamplesExampleTypeSupport::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/detect_samples_dropped/c++98/application.h
/* * (c) Copyright, Real-Time Innovations, 2021. All rights reserved. * RTI grants Licensee a license to use, modify, compile, and create derivative * works of the software solely for use with RTI Connext DDS. Licensee may * redistribute copies of the software provided that all such copies are subject * to this license. The software is provided "as is", with no warranty of any * type, including any warranty for fitness for any purpose. RTI is under no * obligation to maintain or support the software. RTI shall not be liable for * any incidental or consequential damages arising out of the use or inability * to use the software. */ #ifndef APPLICATION_H #define APPLICATION_H #include <iostream> #include <csignal> #include <climits> namespace application { // Catch control-C and tell application to shut down bool shutdown_requested = false; inline void stop_handler(int) { shutdown_requested = true; std::cout << "preparing to shut down..." << std::endl; } inline void setup_signal_handlers() { signal(SIGINT, stop_handler); signal(SIGTERM, stop_handler); } enum ParseReturn { PARSE_RETURN_OK, PARSE_RETURN_FAILURE, PARSE_RETURN_EXIT }; struct ApplicationArguments { ParseReturn parse_result; unsigned int domain_id; unsigned int sample_count; NDDS_Config_LogVerbosity verbosity; }; // Parses application arguments for example. Returns whether to exit. inline void parse_arguments( ApplicationArguments &arguments, int argc, char *argv[]) { int arg_processing = 1; bool show_usage = false; arguments.domain_id = 0; arguments.sample_count = INT_MAX; arguments.verbosity = NDDS_CONFIG_LOG_VERBOSITY_ERROR; arguments.parse_result = PARSE_RETURN_OK; while (arg_processing < argc) { if ((argc > arg_processing + 1) && (strcmp(argv[arg_processing], "-d") == 0 || strcmp(argv[arg_processing], "--domain") == 0)) { arguments.domain_id = atoi(argv[arg_processing + 1]); arg_processing += 2; } else if ( (argc > arg_processing + 1) && (strcmp(argv[arg_processing], "-s") == 0 || strcmp(argv[arg_processing], "--sample-count") == 0)) { arguments.sample_count = atoi(argv[arg_processing + 1]); arg_processing += 2; } else if ( (argc > arg_processing + 1) && (strcmp(argv[arg_processing], "-v") == 0 || strcmp(argv[arg_processing], "--verbosity") == 0)) { arguments.verbosity = (NDDS_Config_LogVerbosity) atoi(argv[arg_processing + 1]); arg_processing += 2; } else if ( strcmp(argv[arg_processing], "-h") == 0 || strcmp(argv[arg_processing], "--help") == 0) { std::cout << "Example application." << std::endl; show_usage = true; arguments.parse_result = PARSE_RETURN_EXIT; break; } else { std::cout << "Bad parameter." << std::endl; show_usage = true; arguments.parse_result = PARSE_RETURN_FAILURE; break; } } if (show_usage) { std::cout << "Usage:\n" " -d, --domain <int> Domain ID this " "application will\n" " subscribe in. \n" " Default: 0\n" " -s, --sample_count <int> Number of samples to " "receive before\n" " cleanly shutting down. \n" " Default: infinite\n" " -v, --verbosity <int> How much debugging output " "to show.\n" " Range: 0-5 \n" " Default: 0" << std::endl; } } } // namespace application #endif // APPLICATION_H
h
rticonnextdds-examples
data/projects/rticonnextdds-examples/connext_dds/detect_samples_dropped/c/DroppedSamplesExample_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. */ /* DroppedSamplesExample_subscriber.c A subscription example This file is derived from code automatically generated by the rtiddsgen command: rtiddsgen -language C -example <arch> DroppedSamplesExample.idl Example subscription of type DroppedSamplesExample automatically generated by 'rtiddsgen'. To test it, follow these steps: (1) Compile this file and the example publication. (2) Start the subscription on the same domain used for RTI Connext (3) Start the publication on the same domain used for RTI Connext (4) [Optional] Specify the list of discovery initial peers and multicast receive addresses via an environment variable or a file (in the current working directory) called NDDS_DISCOVERY_PEERS. You can run any number of publisher and subscriber programs, and can add and remove them dynamically from the domain. */ #include <stdio.h> #include <stdlib.h> #include "ndds/ndds_c.h" #include "DroppedSamplesExample.h" #include "DroppedSamplesExampleSupport.h" void DroppedSamplesExampleListener_on_requested_deadline_missed( void *listener_data, DDS_DataReader *reader, const struct DDS_RequestedDeadlineMissedStatus *status) { } void DroppedSamplesExampleListener_on_requested_incompatible_qos( void *listener_data, DDS_DataReader *reader, const struct DDS_RequestedIncompatibleQosStatus *status) { } void DroppedSamplesExampleListener_on_sample_rejected( void *listener_data, DDS_DataReader *reader, const struct DDS_SampleRejectedStatus *status) { } void DroppedSamplesExampleListener_on_liveliness_changed( void *listener_data, DDS_DataReader *reader, const struct DDS_LivelinessChangedStatus *status) { } void DroppedSamplesExampleListener_on_sample_lost( void *listener_data, DDS_DataReader *reader, const struct DDS_SampleLostStatus *status) { } void DroppedSamplesExampleListener_on_subscription_matched( void *listener_data, DDS_DataReader *reader, const struct DDS_SubscriptionMatchedStatus *status) { } void DroppedSamplesExampleListener_on_data_available( void *listener_data, DDS_DataReader *reader) { DroppedSamplesExampleDataReader *DroppedSamplesExample_reader = NULL; struct DroppedSamplesExampleSeq data_seq = DDS_SEQUENCE_INITIALIZER; struct DDS_SampleInfoSeq info_seq = DDS_SEQUENCE_INITIALIZER; DDS_ReturnCode_t retcode; int i; DroppedSamplesExample_reader = DroppedSamplesExampleDataReader_narrow(reader); if (DroppedSamplesExample_reader == NULL) { fprintf(stderr, "DataReader narrow error\n"); return; } retcode = DroppedSamplesExampleDataReader_take( DroppedSamplesExample_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 < DroppedSamplesExampleSeq_get_length(&data_seq); ++i) { if (DDS_SampleInfoSeq_get_reference(&info_seq, i)->valid_data) { printf("Received data\n"); DroppedSamplesExampleTypeSupport_print_data( DroppedSamplesExampleSeq_get_reference(&data_seq, i)); } } retcode = DroppedSamplesExampleDataReader_return_loan( DroppedSamplesExample_reader, &data_seq, &info_seq); if (retcode != DDS_RETCODE_OK) { fprintf(stderr, "return loan error %d\n", retcode); } } /* Delete all entities */ static int subscriber_shutdown( DDS_DomainParticipant *participant, struct DDS_DataReaderQos *reader_qos) { 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_DataReaderQos_finalize(reader_qos); if (retcode != DDS_RETCODE_OK) { fprintf(stderr, "finalize Reader qos error %d\n", retcode); status = -1; } /* RTI Data Distribution Service provides the finalize_instance() method on domain participant factory for users who want to release memory used by the participant factory. Uncomment the following block of code for clean destruction of the singleton. */ retcode = DDS_DomainParticipantFactory_finalize_instance(); if (retcode != DDS_RETCODE_OK) { fprintf(stderr, "finalize_instance error %d\n", retcode); status = -1; } return status; } int subscriber_main(int domainId, int sample_count) { DDS_DomainParticipant *participant = NULL; DDS_Subscriber *subscriber = NULL; DDS_Topic *topic = NULL; DDS_ContentFilteredTopic *cft_topic = NULL; struct DDS_StringSeq parameters = DDS_SEQUENCE_INITIALIZER; 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 }; struct DDS_DataReaderCacheStatus cache_status = DDS_DataReaderCacheStatus_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) { fprintf(stderr, "create_participant error\n"); subscriber_shutdown(participant, &reader_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) { fprintf(stderr, "create_subscriber error\n"); subscriber_shutdown(participant, &reader_qos); return -1; } /* Register the type before creating the topic */ type_name = DroppedSamplesExampleTypeSupport_get_type_name(); retcode = DroppedSamplesExampleTypeSupport_register_type( participant, type_name); if (retcode != DDS_RETCODE_OK) { fprintf(stderr, "register_type error %d\n", retcode); subscriber_shutdown(participant, &reader_qos); return -1; } /* To customize topic QoS, use the configuration file USER_QOS_PROFILES.xml */ topic = DDS_DomainParticipant_create_topic( participant, "Example DroppedSamplesExample", type_name, &DDS_TOPIC_QOS_DEFAULT, NULL /* listener */, DDS_STATUS_MASK_NONE); if (topic == NULL) { fprintf(stderr, "create_topic error\n"); subscriber_shutdown(participant, &reader_qos); return -1; } cft_topic = DDS_DomainParticipant_create_contentfilteredtopic( participant, "Example DroppedSamplesExample CFT", topic, "x < 4", &parameters); if (cft_topic == NULL) { fprintf(stderr, "create_contentfilteredtopic error\n"); subscriber_shutdown(participant, &reader_qos); return -1; } /* Set up a data reader listener */ reader_listener.on_requested_deadline_missed = DroppedSamplesExampleListener_on_requested_deadline_missed; reader_listener.on_requested_incompatible_qos = DroppedSamplesExampleListener_on_requested_incompatible_qos; reader_listener.on_sample_rejected = DroppedSamplesExampleListener_on_sample_rejected; reader_listener.on_liveliness_changed = DroppedSamplesExampleListener_on_liveliness_changed; reader_listener.on_sample_lost = DroppedSamplesExampleListener_on_sample_lost; reader_listener.on_subscription_matched = DroppedSamplesExampleListener_on_subscription_matched; reader_listener.on_data_available = DroppedSamplesExampleListener_on_data_available; /* Set reader qos */ retcode = DDS_Subscriber_get_default_datareader_qos(subscriber, &reader_qos); if (retcode != DDS_RETCODE_OK) { fprintf(stderr, "get_default_datareader_qos error\n"); subscriber_shutdown(participant, &reader_qos); return -1; } reader_qos.ownership.kind = DDS_EXCLUSIVE_OWNERSHIP_QOS; /* To customize data reader QoS, use the configuration file USER_QOS_PROFILES.xml */ reader = DDS_Subscriber_create_datareader( subscriber, DDS_Topic_as_topicdescription(cft_topic), &reader_qos, &reader_listener, DDS_STATUS_MASK_ALL); if (reader == NULL) { fprintf(stderr, "create_datareader error\n"); subscriber_shutdown(participant, &reader_qos); return -1; } /* Main loop */ for (count = 0; (sample_count == 0) || (count < sample_count); ++count) { printf("subscriber sleeping for %d sec...\n", poll_period.sec); NDDS_Utility_sleep(&poll_period); retcode = DDS_DataReader_get_datareader_cache_status( reader, &cache_status); if (retcode != DDS_RETCODE_OK) { fprintf(stderr, "get_datareader_cache_status error\n"); subscriber_shutdown(participant, &reader_qos); return -1; } printf("Samples dropped:\n" "\t ownership_dropped_sample_count %lld\n" "\t content_filter_dropped_sample_count %lld\n", cache_status.ownership_dropped_sample_count, cache_status.content_filter_dropped_sample_count); } /* Cleanup and delete all entities */ return subscriber_shutdown(participant, &reader_qos); } int main(int argc, char *argv[]) { int domain_id = 0; int sample_count = 0; /* infinite loop */ if (argc >= 2) { domain_id = atoi(argv[1]); } if (argc >= 3) { sample_count = atoi(argv[2]); } /* Uncomment this to turn on additional logging NDDS_Config_Logger_set_verbosity_by_category( NDDS_Config_Logger_get_instance(), NDDS_CONFIG_LOG_CATEGORY_API, NDDS_CONFIG_LOG_VERBOSITY_STATUS_ALL); */ return subscriber_main(domain_id, sample_count); }
c
rticonnextdds-examples
data/projects/rticonnextdds-examples/connext_dds/detect_samples_dropped/c/DroppedSamplesExample_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. */ /* DroppedSamplesExample_publisher.c A publication of data of type DroppedSamplesExample This file is derived from code automatically generated by the rtiddsgen command: rtiddsgen -language C -example <arch> DroppedSamplesExample.idl Example publication of type DroppedSamplesExample 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 "DroppedSamplesExample.h" #include "DroppedSamplesExampleSupport.h" /* Delete all entities */ static int publisher_shutdown( DDS_DomainParticipant *participant, struct DDS_DataWriterQos *writer_qos) { 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_DataWriterQos_finalize(writer_qos); if (retcode != DDS_RETCODE_OK) { fprintf(stderr, "finalize Writer qos 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 *writer1 = NULL, *writer2 = NULL; struct DDS_DataWriterQos writer_qos = DDS_DataWriterQos_INITIALIZER; DroppedSamplesExampleDataWriter *DroppedSamplesExample_writer1 = NULL, *DroppedSamplesExample_writer2 = NULL; DroppedSamplesExample *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) { fprintf(stderr, "create_participant error\n"); publisher_shutdown(participant, &writer_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) { fprintf(stderr, "create_publisher error\n"); publisher_shutdown(participant, &writer_qos); return -1; } /* Register type before creating topic */ type_name = DroppedSamplesExampleTypeSupport_get_type_name(); retcode = DroppedSamplesExampleTypeSupport_register_type( participant, type_name); if (retcode != DDS_RETCODE_OK) { fprintf(stderr, "register_type error %d\n", retcode); publisher_shutdown(participant, &writer_qos); return -1; } /* To customize topic QoS, use the configuration file USER_QOS_PROFILES.xml */ topic = DDS_DomainParticipant_create_topic( participant, "Example DroppedSamplesExample", type_name, &DDS_TOPIC_QOS_DEFAULT, NULL /* listener */, DDS_STATUS_MASK_NONE); if (topic == NULL) { fprintf(stderr, "create_topic error\n"); publisher_shutdown(participant, &writer_qos); return -1; } /* Set writer qos */ retcode = DDS_Publisher_get_default_datawriter_qos(publisher, &writer_qos); if (retcode != DDS_RETCODE_OK) { fprintf(stderr, "get_default_datawriter_qos error\n"); publisher_shutdown(participant, &writer_qos); return -1; } /* Use batching in order to evaluate the CFT in the reader side */ writer_qos.batch.enable = DDS_BOOLEAN_TRUE; writer_qos.batch.max_samples = 1; writer_qos.ownership.kind = DDS_EXCLUSIVE_OWNERSHIP_QOS; writer_qos.ownership_strength.value = 1; /* To customize data writer QoS, use the configuration file USER_QOS_PROFILES.xml */ writer1 = DDS_Publisher_create_datawriter( publisher, topic, &writer_qos, NULL /* listener */, DDS_STATUS_MASK_NONE); if (writer1 == NULL) { fprintf(stderr, "create_datawriter error\n"); publisher_shutdown(participant, &writer_qos); return -1; } DroppedSamplesExample_writer1 = DroppedSamplesExampleDataWriter_narrow(writer1); if (DroppedSamplesExample_writer1 == NULL) { fprintf(stderr, "DataWriter narrow error\n"); publisher_shutdown(participant, &writer_qos); return -1; } writer_qos.ownership_strength.value = 2; /* To customize data writer QoS, use the configuration file USER_QOS_PROFILES.xml */ writer2 = DDS_Publisher_create_datawriter( publisher, topic, &writer_qos, NULL /* listener */, DDS_STATUS_MASK_NONE); if (writer2 == NULL) { fprintf(stderr, "create_datawriter error\n"); publisher_shutdown(participant, &writer_qos); return -1; } DroppedSamplesExample_writer2 = DroppedSamplesExampleDataWriter_narrow(writer2); if (DroppedSamplesExample_writer2 == NULL) { fprintf(stderr, "DataWriter narrow error\n"); publisher_shutdown(participant, &writer_qos); return -1; } /* Create data sample for writing */ instance = DroppedSamplesExampleTypeSupport_create_data_ex(DDS_BOOLEAN_TRUE); if (instance == NULL) { fprintf(stderr, "DroppedSamplesExampleTypeSupport_create_data error\n"); publisher_shutdown(participant, &writer_qos); return -1; } /* For a data type that has a key, if the same instance is going to be written multiple times, initialize the key here and register the keyed instance prior to writing */ /* instance_handle = DroppedSamplesExampleDataWriter_register_instance( DroppedSamplesExample_writer, instance); */ /* Main loop */ for (count = 0; (sample_count == 0) || (count < sample_count); ++count) { printf("Writing DroppedSamplesExample, count %d\n", count); /* Modify the data to be written here */ instance->x = count; /* Write data */ retcode = DroppedSamplesExampleDataWriter_write( DroppedSamplesExample_writer1, instance, &instance_handle); if (retcode != DDS_RETCODE_OK) { fprintf(stderr, "write error %d\n", retcode); } /* Write data */ retcode = DroppedSamplesExampleDataWriter_write( DroppedSamplesExample_writer2, instance, &instance_handle); if (retcode != DDS_RETCODE_OK) { fprintf(stderr, "write error %d\n", retcode); } NDDS_Utility_sleep(&send_period); } /* retcode = DroppedSamplesExampleDataWriter_unregister_instance( DroppedSamplesExample_writer, instance, &instance_handle); if (retcode != DDS_RETCODE_OK) { fprintf(stderr, "unregister instance error %d\n", retcode); } */ /* Delete data sample */ retcode = DroppedSamplesExampleTypeSupport_delete_data_ex( instance, DDS_BOOLEAN_TRUE); if (retcode != DDS_RETCODE_OK) { fprintf(stderr, "DroppedSamplesExampleTypeSupport_delete_data error %d\n", retcode); } /* Cleanup and delete delete all entities */ return publisher_shutdown(participant, &writer_qos); } int main(int argc, char *argv[]) { int domain_id = 0; int sample_count = 0; /* infinite loop */ if (argc >= 2) { domain_id = atoi(argv[1]); } if (argc >= 3) { sample_count = atoi(argv[2]); } /* Uncomment this to turn on additional logging NDDS_Config_Logger_set_verbosity_by_category( NDDS_Config_Logger_get_instance(), NDDS_CONFIG_LOG_CATEGORY_API, NDDS_CONFIG_LOG_VERBOSITY_STATUS_ALL); */ return publisher_main(domain_id, sample_count); }
c
rticonnextdds-examples
data/projects/rticonnextdds-examples/connext_dds/detect_samples_dropped/c++11/DroppedSamplesExample_subscriber.cxx
/* * (c) Copyright, Real-Time Innovations, 2021. All rights reserved. * RTI grants Licensee a license to use, modify, compile, and create derivative * works of the software solely for use with RTI Connext DDS. Licensee may * redistribute copies of the software provided that all such copies are subject * to this license. The software is provided "as is", with no warranty of any * type, including any warranty for fitness for any purpose. RTI is under no * obligation to maintain or support the software. RTI shall not be liable for * any incidental or consequential damages arising out of the use or inability * to use the software. */ #include <algorithm> #include <iostream> #include <dds/sub/ddssub.hpp> #include <dds/core/ddscore.hpp> #include <rti/config/Logger.hpp> // for logging // alternatively, to include all the standard APIs: // <dds/dds.hpp> // or to include both the standard APIs and extensions: // <rti/rti.hpp> // // For more information about the headers and namespaces, see: // https://community.rti.com/static/documentation/connext-dds/6.1.0/doc/api/connext_dds/api_cpp2/group__DDSNamespaceModule.html // For information on how to use extensions, see: // https://community.rti.com/static/documentation/connext-dds/6.1.0/doc/api/connext_dds/api_cpp2/group__DDSCpp2Conventions.html #include "DroppedSamplesExample.hpp" #include "application.hpp" // for command line parsing and ctrl-c int process_data(dds::sub::DataReader<DroppedSamplesExample> reader) { // Take all samples int count = 0; dds::sub::LoanedSamples<DroppedSamplesExample> samples = reader.take(); for (const auto &sample : samples) { if (sample.info().valid()) { count++; std::cout << sample.data() << std::endl; } else { std::cout << "Instance state changed to " << sample.info().state().instance_state() << std::endl; } } return count; } // The LoanedSamples destructor returns the loan void run_subscriber_application( unsigned int domain_id, unsigned int sample_count) { // DDS objects behave like shared pointers or value types // (see // https://community.rti.com/static/documentation/connext-dds/6.1.0/doc/api/connext_dds/api_cpp2/group__DDSCpp2Conventions.html) // Start communicating in a domain, usually one participant per application dds::domain::DomainParticipant participant(domain_id); // Create a Topic with a name and a datatype dds::topic::Topic<DroppedSamplesExample> topic( participant, "Example DroppedSamplesExample"); dds::topic::ContentFilteredTopic<DroppedSamplesExample> cft( topic, "Example DroppedSamplesExample CFT", dds::topic::Filter("x < 4")); // Create a Subscriber and DataReader with default Qos dds::sub::Subscriber subscriber(participant); dds::sub::qos::DataReaderQos reader_qos = subscriber.default_datareader_qos(); reader_qos << dds::core::policy::Ownership::Exclusive(); dds::sub::DataReader<DroppedSamplesExample> reader( subscriber, cft, 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; rti::core::status::DataReaderCacheStatus status; while (!application::shutdown_requested && samples_read < sample_count) { std::cout << "DroppedSamplesExample subscriber sleeping up to 1 sec..." << std::endl; waitset.dispatch(dds::core::Duration(1)); status = reader.extensions().datareader_cache_status(); std::cout << "Samples dropped:" << "\n\t ownership_dropped_sample_count " << status.ownership_dropped_sample_count() << "\n\t content_filter_dropped_sample_count " << status.content_filter_dropped_sample_count() << std::endl; } } int main(int argc, char *argv[]) { using namespace application; // Parse arguments and handle control-C auto arguments = parse_arguments(argc, argv); if (arguments.parse_result == ParseReturn::exit) { return EXIT_SUCCESS; } else if (arguments.parse_result == ParseReturn::failure) { return EXIT_FAILURE; } setup_signal_handlers(); // Sets Connext verbosity to help debugging rti::config::Logger::instance().verbosity(arguments.verbosity); try { run_subscriber_application(arguments.domain_id, arguments.sample_count); } catch (const std::exception &ex) { // This will catch DDS exceptions std::cerr << "Exception in run_subscriber_application(): " << ex.what() << std::endl; return EXIT_FAILURE; } // Releases the memory used by the participant factory. Optional at // application exit dds::domain::DomainParticipant::finalize_participant_factory(); return EXIT_SUCCESS; }
cxx
rticonnextdds-examples
data/projects/rticonnextdds-examples/connext_dds/detect_samples_dropped/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/detect_samples_dropped/c++11/DroppedSamplesExample_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 "DroppedSamplesExample.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<DroppedSamplesExample> topic( participant, "Example DroppedSamplesExample"); // Create a Publisher dds::pub::Publisher publisher(participant); dds::pub::qos::DataWriterQos writer_qos = publisher.default_datawriter_qos(); // Use batching in order to evaluate the CFT in the reader side writer_qos << rti::core::policy::Batch().enable(true).max_samples(1) << dds::core::policy::Ownership::Exclusive() << dds::core::policy::OwnershipStrength(1); // Create a DataWriter with default QoS dds::pub::DataWriter<DroppedSamplesExample> writer1( publisher, topic, writer_qos); writer_qos << dds::core::policy::OwnershipStrength(2); dds::pub::DataWriter<DroppedSamplesExample> writer2( publisher, topic, writer_qos); DroppedSamplesExample data; for (unsigned int samples_written = 0; !application::shutdown_requested && samples_written < sample_count; samples_written++) { // Modify the data to be written here data.x(static_cast<int16_t>(samples_written)); std::cout << "Writing DroppedSamplesExample, count " << samples_written << std::endl; writer1.write(data); writer2.write(data); // Send once every second rti::util::sleep(dds::core::Duration(1)); } } int main(int argc, char *argv[]) { using namespace application; // Parse arguments and handle control-C auto arguments = parse_arguments(argc, argv); if (arguments.parse_result == ParseReturn::exit) { return EXIT_SUCCESS; } else if (arguments.parse_result == ParseReturn::failure) { return EXIT_FAILURE; } setup_signal_handlers(); // Sets Connext verbosity to help debugging rti::config::Logger::instance().verbosity(arguments.verbosity); try { run_publisher_application(arguments.domain_id, arguments.sample_count); } catch (const std::exception &ex) { // This will catch DDS exceptions std::cerr << "Exception in run_publisher_application(): " << ex.what() << std::endl; return EXIT_FAILURE; } // Releases the memory used by the participant factory. Optional at // application exit dds::domain::DomainParticipant::finalize_participant_factory(); return EXIT_SUCCESS; }
cxx
rticonnextdds-examples
data/projects/rticonnextdds-examples/connext_dds/content_filtered_topic_string_filter/c++/cft_publisher.cxx
/******************************************************************************* (c) 2005-2014 Copyright, Real-Time Innovations, Inc. All rights reserved. RTI grants Licensee a license to use, modify, compile, and create derivative works of the Software. Licensee has the right to distribute object form only for use with RTI products. The Software is provided "as is", with no warranty of any type, including any warranty for fitness for any purpose. RTI is under no obligation to maintain or support the Software. RTI shall not be liable for any incidental or consequential damages arising out of the use or inability to use the software. ******************************************************************************/ /* cft_publisher.cxx A publication of data of type cft This file is derived from code automatically generated by the rtiddsgen command: rtiddsgen -language C++ -example <arch> cft.idl Example publication of type cft automatically generated by 'rtiddsgen'. To test them follow these steps: (1) Compile this file and the example subscription. (2) Start the subscription with the command objs/<arch>/cft_subscriber <domain_id> <sample_count> (3) Start the publication with the command objs/<arch>/cft_publisher <domain_id> <sample_count> (4) [Optional] Specify the list of discovery initial peers and multicast receive addresses via an environment variable or a file (in the current working directory) called NDDS_DISCOVERY_PEERS. You can run any number of publishers and subscribers programs, and can add and remove them dynamically from the domain. Example: To run the example application on domain <domain_id>: On Unix: objs/<arch>/cft_publisher <domain_id> o objs/<arch>/cft_subscriber <domain_id> On Windows: objs\<arch>\cft_publisher <domain_id> objs\<arch>\cft_subscriber <domain_id> modification history ------------ ------- */ #include <stdio.h> #include <stdlib.h> #ifdef RTI_VX653 #include <vThreadsData.h> #endif #include "cft.h" #include "cftSupport.h" #include "ndds/ndds_cpp.h" /* Delete all entities */ static int publisher_shutdown(DDSDomainParticipant *participant) { DDS_ReturnCode_t retcode; int status = 0; if (participant != NULL) { retcode = participant->delete_contained_entities(); if (retcode != DDS_RETCODE_OK) { printf("delete_contained_entities error %d\n", retcode); status = -1; } retcode = DDSTheParticipantFactory->delete_participant(participant); if (retcode != DDS_RETCODE_OK) { printf("delete_participant error %d\n", retcode); status = -1; } } /* RTI Connext provides finalize_instance() method on domain participant factory for people who want to release memory used by the participant factory. Uncomment the following block of code for clean destruction of the singleton. */ /* retcode = DDSDomainParticipantFactory::finalize_instance(); if (retcode != DDS_RETCODE_OK) { printf("finalize_instance error %d\n", retcode); status = -1; } */ return status; } extern "C" int publisher_main(int domainId, int sample_count) { DDSDomainParticipant *participant = NULL; DDSPublisher *publisher = NULL; DDSTopic *topic = NULL; DDSDataWriter *writer = NULL; cftDataWriter *cft_writer = NULL; cft *instance = NULL; DDS_ReturnCode_t retcode; DDS_InstanceHandle_t instance_handle = DDS_HANDLE_NIL; const char *type_name = NULL; int count = 0; DDS_Duration_t send_period = { 1, 0 }; char *even_string = DDS_String_dup("EVEN"); char *odd_string = DDS_String_dup("ODD"); /* To customize participant QoS, use the configuration file USER_QOS_PROFILES.xml */ participant = DDSTheParticipantFactory->create_participant( domainId, DDS_PARTICIPANT_QOS_DEFAULT, NULL /* listener */, DDS_STATUS_MASK_NONE); if (participant == NULL) { printf("create_participant error\n"); publisher_shutdown(participant); return -1; } /* To customize publisher QoS, use the configuration file USER_QOS_PROFILES.xml */ publisher = participant->create_publisher( DDS_PUBLISHER_QOS_DEFAULT, NULL /* listener */, DDS_STATUS_MASK_NONE); if (publisher == NULL) { printf("create_publisher error\n"); publisher_shutdown(participant); return -1; } /* Register type before creating topic */ type_name = cftTypeSupport::get_type_name(); retcode = cftTypeSupport::register_type(participant, type_name); if (retcode != DDS_RETCODE_OK) { printf("register_type error %d\n", retcode); publisher_shutdown(participant); return -1; } /* To customize topic QoS, use the configuration file USER_QOS_PROFILES.xml */ topic = participant->create_topic( "Example cft", type_name, DDS_TOPIC_QOS_DEFAULT, NULL /* listener */, DDS_STATUS_MASK_NONE); if (topic == NULL) { printf("create_topic error\n"); publisher_shutdown(participant); return -1; } /* To customize data writer QoS, use the configuration file USER_QOS_PROFILES.xml */ writer = publisher->create_datawriter( topic, DDS_DATAWRITER_QOS_DEFAULT, NULL /* listener */, DDS_STATUS_MASK_NONE); if (writer == NULL) { printf("create_datawriter error\n"); publisher_shutdown(participant); return -1; } /* If you want to set the reliability and history QoS settings * programmatically rather than using the XML, you will need to add * the following lines to your code and comment out the create_datawriter * call above. */ /* DDS_DataWriterQos datawriter_qos; retcode = publisher->get_default_datawriter_qos(datawriter_qos); if (retcode != DDS_RETCODE_OK) { printf("get_default_datawriter_qos error\n"); return -1; } datawriter_qos.reliability.kind = DDS_RELIABLE_RELIABILITY_QOS; datawriter_qos.durability.kind = DDS_TRANSIENT_LOCAL_DURABILITY_QOS; datawriter_qos.history.kind = DDS_KEEP_LAST_HISTORY_QOS; datawriter_qos.history.depth = 20; writer = publisher->create_datawriter( topic, datawriter_qos, NULL, DDS_STATUS_MASK_NONE); if (writer == NULL) { printf("create_datawriter error\n"); publisher_shutdown(participant); return -1; } */ cft_writer = cftDataWriter::narrow(writer); if (cft_writer == NULL) { printf("DataWriter narrow error\n"); publisher_shutdown(participant); return -1; } /* Create data sample for writing */ instance = cftTypeSupport::create_data(); if (instance == NULL) { printf("cftTypeSupport::create_data error\n"); publisher_shutdown(participant); return -1; } /* For a data type that has a key, if the same instance is going to be written multiple times, initialize the key here and register the keyed instance prior to writing */ /* instance_handle = cft_writer->register_instance(*instance); */ /* Main loop */ for (count = 0; (sample_count == 0) || (count < sample_count); ++count) { printf("Writing cft, count %d\n", count); /* Modify the data to be sent here */ if (count % 2 == 1) { instance->name = odd_string; } else { instance->name = even_string; } instance->count = count; retcode = cft_writer->write(*instance, instance_handle); if (retcode != DDS_RETCODE_OK) { printf("write error %d\n", retcode); } NDDSUtility::sleep(send_period); } /* retcode = cft_writer->unregister_instance( *instance, instance_handle); if (retcode != DDS_RETCODE_OK) { printf("unregister instance error %d\n", retcode); } */ /* Delete data sample */ retcode = cftTypeSupport::delete_data(instance); if (retcode != DDS_RETCODE_OK) { printf("cftTypeSupport::delete_data error %d\n", retcode); } /* Delete all entities */ return publisher_shutdown(participant); } #if defined(RTI_WINCE) int wmain(int argc, wchar_t **argv) { int domainId = 0; int sample_count = 0; /* infinite loop */ if (argc >= 2) { domainId = _wtoi(argv[1]); } if (argc >= 3) { sample_count = _wtoi(argv[2]); } /* Uncomment this to turn on additional logging NDDSConfigLogger::get_instance()-> set_verbosity_by_category(NDDS_CONFIG_LOG_CATEGORY_API, NDDS_CONFIG_LOG_VERBOSITY_STATUS_ALL); */ return publisher_main(domainId, sample_count); } #elif !(defined(RTI_VXWORKS) && !defined(__RTP__)) && !defined(RTI_PSOS) int main(int argc, char *argv[]) { int domainId = 0; int sample_count = 0; /* infinite loop */ if (argc >= 2) { domainId = atoi(argv[1]); } if (argc >= 3) { sample_count = atoi(argv[2]); } /* Uncomment this to turn on additional logging NDDSConfigLogger::get_instance()-> set_verbosity_by_category(NDDS_CONFIG_LOG_CATEGORY_API, NDDS_CONFIG_LOG_VERBOSITY_STATUS_ALL); */ return publisher_main(domainId, sample_count); } #endif #ifdef RTI_VX653 const unsigned char *__ctype = *(__ctypePtrGet()); extern "C" void usrAppInit() { #ifdef USER_APPL_INIT USER_APPL_INIT; /* for backwards compatibility */ #endif /* add application specific code here */ taskSpawn( "pub", RTI_OSAPI_THREAD_PRIORITY_NORMAL, 0x8, 0x150000, (FUNCPTR) publisher_main, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0); } #endif
cxx
rticonnextdds-examples
data/projects/rticonnextdds-examples/connext_dds/content_filtered_topic_string_filter/c++/cft_subscriber.cxx
/******************************************************************************* (c) 2005-2014 Copyright, Real-Time Innovations, Inc. All rights reserved. RTI grants Licensee a license to use, modify, compile, and create derivative works of the Software. Licensee has the right to distribute object form only for use with RTI products. The Software is provided "as is", with no warranty of any type, including any warranty for fitness for any purpose. RTI is under no obligation to maintain or support the Software. RTI shall not be liable for any incidental or consequential damages arising out of the use or inability to use the software. ******************************************************************************/ /* cft_subscriber.cxx A subscription example This file is derived from code automatically generated by the rtiddsgen command: rtiddsgen -language C++ -example <arch> cft.idl Example subscription of type cft automatically generated by 'rtiddsgen'. To test them follow these steps: (1) Compile this file and the example publication. (2) Start the subscription with the command objs/<arch>/cft_subscriber <domain_id> <sample_count> (3) Start the publication with the command objs/<arch>/cft_publisher <domain_id> <sample_count> (4) [Optional] Specify the list of discovery initial peers and multicast receive addresses via an environment variable or a file (in the current working directory) called NDDS_DISCOVERY_PEERS. You can run any number of publishers and subscribers programs, and can add and remove them dynamically from the domain. Example: To run the example application on domain <domain_id>: On Unix: objs/<arch>/cft_publisher <domain_id> objs/<arch>/cft_subscriber <domain_id> On Windows: objs\<arch>\cft_publisher <domain_id> objs\<arch>\cft_subscriber <domain_id> modification history ------------ ------- */ #include <stdio.h> #include <stdlib.h> #ifdef RTI_VX653 #include <vThreadsData.h> #endif #include "cft.h" #include "cftSupport.h" #include "ndds/ndds_cpp.h" class cftListener : public DDSDataReaderListener { public: virtual void on_requested_deadline_missed( DDSDataReader * /*reader*/, const DDS_RequestedDeadlineMissedStatus & /*status*/) { } virtual void on_requested_incompatible_qos( DDSDataReader * /*reader*/, const DDS_RequestedIncompatibleQosStatus & /*status*/) { } virtual void on_sample_rejected( DDSDataReader * /*reader*/, const DDS_SampleRejectedStatus & /*status*/) { } virtual void on_liveliness_changed( DDSDataReader * /*reader*/, const DDS_LivelinessChangedStatus & /*status*/) { } virtual void on_sample_lost( DDSDataReader * /*reader*/, const DDS_SampleLostStatus & /*status*/) { } virtual void on_subscription_matched( DDSDataReader * /*reader*/, const DDS_SubscriptionMatchedStatus & /*status*/) { } virtual void on_data_available(DDSDataReader *reader); }; void cftListener::on_data_available(DDSDataReader *reader) { cftDataReader *cft_reader = NULL; cftSeq data_seq; DDS_SampleInfoSeq info_seq; DDS_ReturnCode_t retcode; int i; cft_reader = cftDataReader::narrow(reader); if (cft_reader == NULL) { printf("DataReader narrow error\n"); return; } retcode = cft_reader->take( data_seq, info_seq, DDS_LENGTH_UNLIMITED, DDS_ANY_SAMPLE_STATE, DDS_ANY_VIEW_STATE, DDS_ANY_INSTANCE_STATE); if (retcode == DDS_RETCODE_NO_DATA) { return; } else if (retcode != DDS_RETCODE_OK) { printf("take error %d\n", retcode); return; } for (i = 0; i < data_seq.length(); ++i) { if (info_seq[i].valid_data) { cftTypeSupport::print_data(&data_seq[i]); } } retcode = cft_reader->return_loan(data_seq, info_seq); if (retcode != DDS_RETCODE_OK) { printf("return loan error %d\n", retcode); } } /* Delete all entities */ static int subscriber_shutdown(DDSDomainParticipant *participant) { DDS_ReturnCode_t retcode; int status = 0; if (participant != NULL) { retcode = participant->delete_contained_entities(); if (retcode != DDS_RETCODE_OK) { printf("delete_contained_entities error %d\n", retcode); status = -1; } retcode = DDSTheParticipantFactory->delete_participant(participant); if (retcode != DDS_RETCODE_OK) { printf("delete_participant error %d\n", retcode); status = -1; } } /* RTI Connext provides the finalize_instance() method on domain participant factory for people who want to release memory used by the participant factory. Uncomment the following block of code for clean destruction of the singleton. */ /* retcode = DDSDomainParticipantFactory::finalize_instance(); if (retcode != DDS_RETCODE_OK) { printf("finalize_instance error %d\n", retcode); status = -1; } */ return status; } extern "C" int subscriber_main(int domainId, int sample_count, int sel_cft) { DDSDomainParticipant *participant = NULL; DDSSubscriber *subscriber = NULL; DDSTopic *topic = NULL; cftListener *reader_listener = NULL; DDSDataReader *reader = NULL; DDS_ReturnCode_t retcode; const char *type_name = NULL; int count = 0; DDS_Duration_t receive_period = { 1, 0 }; int status = 0; DDSContentFilteredTopic *cft = NULL; /* For this filter we only allow 1 parameter*/ DDS_StringSeq parameters(1); const char *param_list[] = { "SOME_STRING" }; /* To customize the participant QoS, use the configuration file USER_QOS_PROFILES.xml */ participant = DDSTheParticipantFactory->create_participant( domainId, DDS_PARTICIPANT_QOS_DEFAULT, NULL /* listener */, DDS_STATUS_MASK_NONE); if (participant == NULL) { printf("create_participant error\n"); subscriber_shutdown(participant); return -1; } /* To customize the subscriber QoS, use the configuration file USER_QOS_PROFILES.xml */ subscriber = participant->create_subscriber( DDS_SUBSCRIBER_QOS_DEFAULT, NULL /* listener */, DDS_STATUS_MASK_NONE); if (subscriber == NULL) { printf("create_subscriber error\n"); subscriber_shutdown(participant); return -1; } /* Register the type before creating the topic */ type_name = cftTypeSupport::get_type_name(); retcode = cftTypeSupport::register_type(participant, type_name); if (retcode != DDS_RETCODE_OK) { printf("register_type error %d\n", retcode); subscriber_shutdown(participant); return -1; } /* To customize the topic QoS, use the configuration file USER_QOS_PROFILES.xml */ topic = participant->create_topic( "Example cft", type_name, DDS_TOPIC_QOS_DEFAULT, NULL /* listener */, DDS_STATUS_MASK_NONE); if (topic == NULL) { printf("create_topic error\n"); subscriber_shutdown(participant); return -1; } parameters.from_array(param_list, 1); if (sel_cft) { /* create_contentfilteredtopic_with_filter */ cft = participant->create_contentfilteredtopic_with_filter( "ContentFilteredTopic", topic, "name MATCH %0", parameters, DDS_STRINGMATCHFILTER_NAME); if (cft == NULL) { printf("create_contentfilteredtopic error\n"); subscriber_shutdown(participant); return -1; } } /* Create a data reader listener */ reader_listener = new cftListener(); /* Here we create the reader either using a Content Filtered Topic or * a normal topic */ if (sel_cft) { printf("Using ContentFiltered Topic\n"); reader = subscriber->create_datareader( cft, DDS_DATAREADER_QOS_DEFAULT, reader_listener, DDS_STATUS_MASK_ALL); } else { printf("Using Normal Topic\n"); reader = subscriber->create_datareader( topic, DDS_DATAREADER_QOS_DEFAULT, reader_listener, DDS_STATUS_MASK_ALL); } if (reader == NULL) { printf("create_datareader error\n"); subscriber_shutdown(participant); delete reader_listener; return -1; } /* If you want to set the reliability and history QoS settings * programmatically rather than using the XML, you will need to add * the following lines to your code and comment out the * create_datareader calls above. */ /* DDS_DataReaderQos datareader_qos; retcode = subscriber->get_default_datareader_qos(datareader_qos); if (retcode != DDS_RETCODE_OK) { printf("get_default_datareader_qos error\n"); return -1; } datareader_qos.reliability.kind = DDS_RELIABLE_RELIABILITY_QOS; datareader_qos.durability.kind = DDS_TRANSIENT_LOCAL_DURABILITY_QOS; datareader_qos.history.kind = DDS_KEEP_LAST_HISTORY_QOS; datareader_qos.history.depth = 20; if (sel_cft) { printf("Using ContentFiltered Topic\n"); reader = subscriber->create_datareader( cft, datareader_qos, reader_listener, DDS_STATUS_MASK_ALL); } else { printf("Using Normal Topic\n"); reader = subscriber->create_datareader( topic, datareader_qos, reader_listener, DDS_STATUS_MASK_ALL); } if (reader == NULL) { printf("create_datareader error\n"); subscriber_shutdown(participant); delete reader_listener; return -1; } */ /* Change the filter */ if (sel_cft) { printf(">>> Now setting a new filter: name MATCH \"EVEN\"\n"); retcode = cft->append_to_expression_parameter(0, "EVEN"); if (retcode != DDS_RETCODE_OK) { printf("append_to_expression_parameter error\n"); subscriber_shutdown(participant); return -1; } } /* Main loop */ for (count = 0; (sample_count == 0) || (count < sample_count); ++count) { NDDSUtility::sleep(receive_period); if (sel_cft == 0) { continue; } if (count == 10) { printf("\n===========================\n"); printf("Changing filter parameters\n"); printf("Append 'ODD' filter\n"); printf("===========================\n"); retcode = cft->append_to_expression_parameter(0, "ODD"); if (retcode != DDS_RETCODE_OK) { printf("append_to_expression_parameter error\n"); subscriber_shutdown(participant); return -1; } } else if (count == 20) { printf("\n===========================\n"); printf("Changing filter parameters\n"); printf("Removing 'EVEN' filter \n"); printf("===========================\n"); retcode = cft->remove_from_expression_parameter(0, "EVEN"); if (retcode != DDS_RETCODE_OK) { printf("append_to_expression_parameter error\n"); subscriber_shutdown(participant); return -1; } } } /* Delete all entities */ status = subscriber_shutdown(participant); delete reader_listener; return status; } #if defined(RTI_WINCE) int wmain(int argc, wchar_t **argv) { int domainId = 0; int sample_count = 0; /* infinite loop */ if (argc >= 2) { domainId = _wtoi(argv[1]); } if (argc >= 3) { sample_count = _wtoi(argv[2]); } /* Uncomment this to turn on additional logging NDDSConfigLogger::get_instance()-> set_verbosity_by_category(NDDS_CONFIG_LOG_CATEGORY_API, NDDS_CONFIG_LOG_VERBOSITY_STATUS_ALL); */ return subscriber_main(domainId, sample_count); } #elif !(defined(RTI_VXWORKS) && !defined(__RTP__)) && !defined(RTI_PSOS) int main(int argc, char *argv[]) { int domainId = 0; int sample_count = 0; /* infinite loop */ int sel_cft = 1; if (argc >= 2) { domainId = atoi(argv[1]); } if (argc >= 3) { sample_count = atoi(argv[2]); } if (argc >= 4) { sel_cft = atoi(argv[3]); } /* Uncomment this to turn on additional logging NDDSConfigLogger::get_instance()-> set_verbosity_by_category(NDDS_CONFIG_LOG_CATEGORY_API, NDDS_CONFIG_LOG_VERBOSITY_STATUS_ALL); */ return subscriber_main(domainId, sample_count, sel_cft); } #endif #ifdef RTI_VX653 const unsigned char *__ctype = *(__ctypePtrGet()); extern "C" void usrAppInit() { #ifdef USER_APPL_INIT USER_APPL_INIT; /* for backwards compatibility */ #endif /* add application specific code here */ taskSpawn( "sub", RTI_OSAPI_THREAD_PRIORITY_NORMAL, 0x8, 0x150000, (FUNCPTR) subscriber_main, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0); } #endif
cxx
rticonnextdds-examples
data/projects/rticonnextdds-examples/connext_dds/content_filtered_topic_string_filter/c++98/cft_publisher.cxx
/******************************************************************************* (c) 2005-2014 Copyright, Real-Time Innovations, Inc. All rights reserved. RTI grants Licensee a license to use, modify, compile, and create derivative works of the Software. Licensee has the right to distribute object form only for use with RTI products. The Software is provided "as is", with no warranty of any type, including any warranty for fitness for any purpose. RTI is under no obligation to maintain or support the Software. RTI shall not be liable for any incidental or consequential damages arising out of the use or inability to use the software. ******************************************************************************/ #include <iostream> #include <stdio.h> #include <stdlib.h> #include "cft.h" #include "cftSupport.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 }; char *even_string = DDS_String_dup("EVEN"); char *odd_string = DDS_String_dup("ODD"); // 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 = cftTypeSupport::get_type_name(); DDS_ReturnCode_t retcode = cftTypeSupport::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 cft", 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 cft" Topic DDSDataWriter *untyped_writer = publisher->create_datawriter( topic, DDS_DATAWRITER_QOS_DEFAULT, NULL /* listener */, DDS_STATUS_MASK_NONE); if (untyped_writer == NULL) { return shutdown_participant( participant, "create_datawriter error", EXIT_FAILURE); } /* If you want to set the reliability and history QoS settings * programmatically rather than using the XML, you will need to add * the following lines to your code and comment out the create_datawriter * call above. */ /* DDS_DataWriterQos datawriter_qos; retcode = publisher->get_default_datawriter_qos(datawriter_qos); if (retcode != DDS_RETCODE_OK) { return shutdown_participant( participant, "get_default_datawriter_qos error", EXIT_FAILURE); } datawriter_qos.reliability.kind = DDS_RELIABLE_RELIABILITY_QOS; datawriter_qos.durability.kind = DDS_TRANSIENT_LOCAL_DURABILITY_QOS; datawriter_qos.history.kind = DDS_KEEP_LAST_HISTORY_QOS; datawriter_qos.history.depth = 20; DDSDataWriter *untyped_writer = publisher->create_datawriter( topic, datawriter_qos, NULL, DDS_STATUS_MASK_NONE); if (untyped_writer == NULL) { return shutdown_participant( participant, "create_datawriter error", EXIT_FAILURE); } */ // Narrow casts from an untyped DataWriter to a writer of your type cftDataWriter *typed_writer = cftDataWriter::narrow(untyped_writer); if (typed_writer == NULL) { return shutdown_participant( participant, "DataWriter narrow error", EXIT_FAILURE); } // Create data for writing, allocating all members cft *data = cftTypeSupport::create_data(); if (data == NULL) { return shutdown_participant( participant, "cftTypeSupport::create_data error", EXIT_FAILURE); } DDS_InstanceHandle_t instance_handle = DDS_HANDLE_NIL; /* For a data type that has a key, if the same instance is going to be written multiple times, initialize the key here and register the keyed instance prior to writing */ /* instance_handle = typed_writer->register_instance(*data); */ // Main loop, write data for (unsigned int samples_written = 0; !shutdown_requested && samples_written < sample_count; ++samples_written) { std::cout << "Writing cft, count " << samples_written << std::endl; // Modify the data to be sent here if (samples_written % 2 == 1) { data->name = odd_string; } else { data->name = even_string; } data->count = samples_written; retcode = typed_writer->write(*data, instance_handle); if (retcode != DDS_RETCODE_OK) { std::cerr << "write error " << retcode << std::endl; } NDDSUtility::sleep(send_period); } /* retcode = typed_writer->unregister_instance( *data, instance_handle); if (retcode != DDS_RETCODE_OK) { std::cerr << "unregister instance error " << retcode << std::endl; } */ // Delete previously allocated cft, including all contained elements retcode = cftTypeSupport::delete_data(data); if (retcode != DDS_RETCODE_OK) { std::cerr << "cftTypeSupport::delete_data error " << retcode << std::endl; } // Delete all entities (DataWriter, Topic, Publisher, DomainParticipant) return shutdown_participant(participant, "Shutting down", EXIT_SUCCESS); } // Delete all entities static int shutdown_participant( DDSDomainParticipant *participant, const char *shutdown_message, int status) { DDS_ReturnCode_t retcode; std::cout << shutdown_message << std::endl; if (participant != NULL) { // Cleanup everything created by this Participant retcode = participant->delete_contained_entities(); if (retcode != DDS_RETCODE_OK) { std::cerr << "delete_contained_entities error " << retcode << std::endl; status = EXIT_FAILURE; } retcode = DDSTheParticipantFactory->delete_participant(participant); if (retcode != DDS_RETCODE_OK) { std::cerr << "delete_participant error " << retcode << std::endl; status = EXIT_FAILURE; } } return status; } int main(int argc, char *argv[]) { // Parse arguments and handle control-C ApplicationArguments arguments; parse_arguments(arguments, argc, argv, publisher); if (arguments.parse_result == PARSE_RETURN_EXIT) { return EXIT_SUCCESS; } else if (arguments.parse_result == PARSE_RETURN_FAILURE) { return EXIT_FAILURE; } setup_signal_handlers(); // Sets Connext verbosity to help debugging NDDSConfigLogger::get_instance()->set_verbosity(arguments.verbosity); int status = run_publisher_application( arguments.domain_id, arguments.sample_count); // Releases the memory used by the participant factory. Optional at // application exit DDS_ReturnCode_t retcode = DDSDomainParticipantFactory::finalize_instance(); if (retcode != DDS_RETCODE_OK) { std::cerr << "finalize_instance error " << retcode << std::endl; status = EXIT_FAILURE; } return status; }
cxx
rticonnextdds-examples
data/projects/rticonnextdds-examples/connext_dds/content_filtered_topic_string_filter/c++98/application.h
/* * (c) Copyright, Real-Time Innovations, 2021. All rights reserved. * RTI grants Licensee a license to use, modify, compile, and create derivative * works of the software solely for use with RTI Connext DDS. Licensee may * redistribute copies of the software provided that all such copies are subject * to this license. The software is provided "as is", with no warranty of any * type, including any warranty for fitness for any purpose. RTI is under no * obligation to maintain or support the software. RTI shall not be liable for * any incidental or consequential damages arising out of the use or inability * to use the software. */ #ifndef APPLICATION_H #define APPLICATION_H #include <iostream> #include <csignal> #include <climits> namespace application { // Catch control-C and tell application to shut down bool shutdown_requested = false; inline void stop_handler(int) { shutdown_requested = true; std::cout << "preparing to shut down..." << std::endl; } inline void setup_signal_handlers() { signal(SIGINT, stop_handler); signal(SIGTERM, stop_handler); } enum ParseReturn { PARSE_RETURN_OK, PARSE_RETURN_FAILURE, PARSE_RETURN_EXIT }; enum ApplicationKind { publisher, subscriber }; struct ApplicationArguments { ParseReturn parse_result; unsigned int domain_id; unsigned int sample_count; NDDS_Config_LogVerbosity verbosity; bool normal_topic; }; inline void set_verbosity(ApplicationArguments &arguments, int verbosity) { switch (verbosity) { case 0: arguments.verbosity = NDDS_CONFIG_LOG_VERBOSITY_SILENT; break; case 1: arguments.verbosity = NDDS_CONFIG_LOG_VERBOSITY_ERROR; break; case 2: arguments.verbosity = NDDS_CONFIG_LOG_VERBOSITY_WARNING; break; case 3: arguments.verbosity = NDDS_CONFIG_LOG_VERBOSITY_STATUS_ALL; break; default: arguments.verbosity = NDDS_CONFIG_LOG_VERBOSITY_ERROR; break; } } // Parses application arguments for example. Returns whether to exit. inline void parse_arguments( ApplicationArguments &arguments, int argc, char *argv[], ApplicationKind current_application) { int arg_processing = 1; bool show_usage = false; arguments.domain_id = 0; arguments.sample_count = INT_MAX; arguments.verbosity = NDDS_CONFIG_LOG_VERBOSITY_ERROR; arguments.parse_result = PARSE_RETURN_OK; arguments.normal_topic = false; 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 ( current_application == subscriber && strcmp(argv[arg_processing], "--normal-topic") == 0) { arguments.normal_topic = true; arg_processing += 1; } 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" << std::endl; if (current_application == subscriber) { std::cout << " --normal-topic If this option is " "given, the subscriber\n" " will use a normal topic " "instead of a\n" " Content Filtered Topic." << std::endl; } std::cout << " -v, --verbosity <int> How much debugging output " "to show.\n" " Range: 0-3 \n" " Default: 1" << std::endl; } } } // namespace application #endif // APPLICATION_H
h
rticonnextdds-examples
data/projects/rticonnextdds-examples/connext_dds/content_filtered_topic_string_filter/c++98/cft_subscriber.cxx
/******************************************************************************* (c) 2005-2014 Copyright, Real-Time Innovations, Inc. All rights reserved. RTI grants Licensee a license to use, modify, compile, and create derivative works of the Software. Licensee has the right to distribute object form only for use with RTI products. The Software is provided "as is", with no warranty of any type, including any warranty for fitness for any purpose. RTI is under no obligation to maintain or support the Software. RTI shall not be liable for any incidental or consequential damages arising out of the use or inability to use the software. ******************************************************************************/ #include <iostream> #include <stdio.h> #include <stdlib.h> #include "cft.h" #include "cftSupport.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(cftDataReader *typed_reader) { cftSeq 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) { cftTypeSupport::print_data(&data_seq[i]); samples_read++; } } // 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, bool normal_topic) { DDS_Duration_t wait_timeout = { 1, 0 }; /* For this filter we only allow 1 parameter*/ DDS_StringSeq parameters(1); const char *param_list[] = { "SOME_STRING" }; // 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 = cftTypeSupport::get_type_name(); DDS_ReturnCode_t retcode = cftTypeSupport::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 cft", type_name, DDS_TOPIC_QOS_DEFAULT, NULL /* listener */, DDS_STATUS_MASK_NONE); if (topic == NULL) { return shutdown_participant( participant, "create_topic error", EXIT_FAILURE); } parameters.from_array(param_list, 1); DDSContentFilteredTopic *cft = NULL; if (!normal_topic) { /* create_contentfilteredtopic_with_filter */ cft = participant->create_contentfilteredtopic_with_filter( "ContentFilteredTopic", topic, "name MATCH %0", parameters, DDS_STRINGMATCHFILTER_NAME); if (cft == NULL) { return shutdown_participant( participant, "create_contentfilteredtopic error", EXIT_FAILURE); } } /* Here we create the reader either using a Content Filtered Topic or * a normal topic */ DDSDataReader *untyped_reader = NULL; if (!normal_topic) { std::cout << "Using ContentFiltered Topic\n"; untyped_reader = subscriber->create_datareader( cft, DDS_DATAREADER_QOS_DEFAULT, NULL, DDS_STATUS_MASK_ALL); } else { std::cout << "Using Normal Topic\n"; 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 set the reliability and history QoS settings * programmatically rather than using the XML, you will need to add * the following lines to your code and comment out the * create_datareader calls above. */ /* DDS_DataReaderQos datareader_qos; retcode = subscriber->get_default_datareader_qos(datareader_qos); if (retcode != DDS_RETCODE_OK) { return shutdown_participant( participant, "get_default_datareader_qos error", EXIT_FAILURE); } datareader_qos.reliability.kind = DDS_RELIABLE_RELIABILITY_QOS; datareader_qos.durability.kind = DDS_TRANSIENT_LOCAL_DURABILITY_QOS; datareader_qos.history.kind = DDS_KEEP_LAST_HISTORY_QOS; datareader_qos.history.depth = 20; if (!normal_topic) { std::cout << "Using ContentFiltered Topic\n"; untyped_reader = subscriber->create_datareader( cft, datareader_qos, NULL, DDS_STATUS_MASK_ALL); } else { std::cout << "Using Normal Topic\n"; untyped_reader = subscriber->create_datareader( topic, datareader_qos, NULL, DDS_STATUS_MASK_ALL); } if (untyped_reader == NULL) { return shutdown_participant( participant, "create_datareader error", EXIT_FAILURE); } */ /* Change the filter */ if (!normal_topic) { printf(">>> Now setting a new filter: name MATCH \"EVEN\"\n"); retcode = cft->append_to_expression_parameter(0, "EVEN"); if (retcode != DDS_RETCODE_OK) { return shutdown_participant( participant, "append_to_expression_parameter error", EXIT_FAILURE); } } // Narrow casts from a untyped DataReader to a reader of your type cftDataReader *typed_reader = cftDataReader::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); } if (normal_topic) { continue; } if (samples_read == 10) { std::cout << "\n===========================\n"; std::cout << "Changing filter parameters\n"; std::cout << "Append 'ODD' filter\n"; std::cout << "===========================\n"; retcode = cft->append_to_expression_parameter(0, "ODD"); if (retcode != DDS_RETCODE_OK) { return shutdown_participant( participant, "append_to_expression_parameter error", EXIT_FAILURE); } } else if (samples_read == 20) { std::cout << "\n===========================\n"; std::cout << "Changing filter parameters\n"; std::cout << "Removing 'EVEN' filter \n"; std::cout << "===========================\n"; retcode = cft->remove_from_expression_parameter(0, "EVEN"); if (retcode != DDS_RETCODE_OK) { return shutdown_participant( participant, "append_to_expression_parameter error", 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, subscriber); if (arguments.parse_result == PARSE_RETURN_EXIT) { return EXIT_SUCCESS; } else if (arguments.parse_result == PARSE_RETURN_FAILURE) { return EXIT_FAILURE; } setup_signal_handlers(); // Sets Connext verbosity to help debugging NDDSConfigLogger::get_instance()->set_verbosity(arguments.verbosity); int status = run_subscriber_application( arguments.domain_id, arguments.sample_count, arguments.normal_topic); // 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/content_filtered_topic_string_filter/c/cft_publisher.c
/******************************************************************************* (c) 2005-2014 Copyright, Real-Time Innovations, Inc. All rights reserved. RTI grants Licensee a license to use, modify, compile, and create derivative works of the Software. Licensee has the right to distribute object form only for use with RTI products. The Software is provided "as is", with no warranty of any type, including any warranty for fitness for any purpose. RTI is under no obligation to maintain or support the Software. RTI shall not be liable for any incidental or consequential damages arising out of the use or inability to use the software. ******************************************************************************/ /* cft_publisher.c A publication of data of type cft This file is derived from code automatically generated by the rtiddsgen command: rtiddsgen -language C -example <arch> cft.idl Example publication of type cft automatically generated by 'rtiddsgen'. To test them follow these steps: (1) Compile this file and the example subscription. (2) Start the subscription with the command objs/<arch>/cft_subscriber <domain_id> <sample_count> (3) Start the publication with the command objs/<arch>/cft_publisher <domain_id> <sample_count> (4) [Optional] Specify the list of discovery initial peers and multicast receive addresses via an environment variable or a file (in the current working directory) called NDDS_DISCOVERY_PEERS. You can run any number of publishers and subscribers programs, and can add and remove them dynamically from the domain. Example: To run the example application on domain <domain_id>: On Unix: objs/<arch>/cft_publisher <domain_id> objs/<arch>/cft_subscriber <domain_id> On Windows: objs\<arch>\cft_publisher <domain_id> objs\<arch>\cft_subscriber <domain_id> modification history ------------ ------- */ #include "cft.h" #include "cftSupport.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; cftDataWriter *cft_writer = NULL; cft *instance = NULL; DDS_ReturnCode_t retcode; DDS_InstanceHandle_t instance_handle = DDS_HANDLE_NIL; const char *type_name = NULL; int count = 0; struct DDS_Duration_t send_period = { 1, 0 }; char *even_string = DDS_String_dup("EVEN"); char *odd_string = DDS_String_dup("ODD"); /* We need this structure in case we want to change the datawriter_qos * programmatically.*/ /* struct DDS_DataWriterQos datawriter_qos = DDS_DataWriterQos_INITIALIZER; */ /* To customize participant QoS, use the configuration file USER_QOS_PROFILES.xml */ participant = DDS_DomainParticipantFactory_create_participant( DDS_TheParticipantFactory, domainId, &DDS_PARTICIPANT_QOS_DEFAULT, NULL /* listener */, DDS_STATUS_MASK_NONE); if (participant == NULL) { printf("create_participant error\n"); publisher_shutdown(participant); return -1; } /* To customize publisher QoS, use the configuration file USER_QOS_PROFILES.xml */ publisher = DDS_DomainParticipant_create_publisher( participant, &DDS_PUBLISHER_QOS_DEFAULT, NULL /* listener */, DDS_STATUS_MASK_NONE); if (publisher == NULL) { printf("create_publisher error\n"); publisher_shutdown(participant); return -1; } /* Register type before creating topic */ type_name = cftTypeSupport_get_type_name(); retcode = cftTypeSupport_register_type(participant, type_name); if (retcode != DDS_RETCODE_OK) { printf("register_type error %d\n", retcode); publisher_shutdown(participant); return -1; } /* To customize topic QoS, use the configuration file USER_QOS_PROFILES.xml */ topic = DDS_DomainParticipant_create_topic( participant, "Example cft", type_name, &DDS_TOPIC_QOS_DEFAULT, NULL /* listener */, DDS_STATUS_MASK_NONE); if (topic == NULL) { printf("create_topic error\n"); publisher_shutdown(participant); return -1; } /* To customize data writer QoS, use the configuration file USER_QOS_PROFILES.xml */ writer = DDS_Publisher_create_datawriter( publisher, topic, &DDS_DATAWRITER_QOS_DEFAULT, NULL /* listener */, DDS_STATUS_MASK_NONE); if (writer == NULL) { printf("create_datawriter error\n"); publisher_shutdown(participant); return -1; } /* If you want to set the reliability and history QoS settings * programmatically rather than using the XML, you will need to add * the following lines to your code and comment out the create_datawriter * call above. */ /* retcode = DDS_Publisher_get_default_datawriter_qos(publisher, &datawriter_qos); if (retcode != DDS_RETCODE_OK) { printf("get_default_datawriter_qos error\n"); return -1; } datawriter_qos.reliability.kind = DDS_RELIABLE_RELIABILITY_QOS; datawriter_qos.durability.kind = DDS_TRANSIENT_LOCAL_DURABILITY_QOS; datawriter_qos.history.kind = DDS_KEEP_LAST_HISTORY_QOS; datawriter_qos.history.depth = 20; writer = DDS_Publisher_create_datawriter( publisher, topic, &datawriter_qos, NULL, DDS_STATUS_MASK_NONE); if (writer == NULL) { printf("create_datawriter error\n"); publisher_shutdown(participant); return -1; } */ cft_writer = cftDataWriter_narrow(writer); if (cft_writer == NULL) { printf("DataWriter narrow error\n"); publisher_shutdown(participant); return -1; } /* Create data sample for writing */ instance = cftTypeSupport_create_data_ex(DDS_BOOLEAN_TRUE); if (instance == NULL) { printf("cftTypeSupport_create_data error\n"); publisher_shutdown(participant); return -1; } /* For a data type that has a key, if the same instance is going to be written multiple times, initialize the key here and register the keyed instance prior to writing */ /* instance_handle = cftDataWriter_register_instance( cft_writer, instance); */ /* Main loop */ for (count = 0; (sample_count == 0) || (count < sample_count); ++count) { printf("Writing cft, count %d\n", count); /* Modify the data to be written here */ if (count % 2 == 1) { instance->name = odd_string; } else { instance->name = even_string; } instance->count = count; /* Write data */ retcode = cftDataWriter_write(cft_writer, instance, &instance_handle); if (retcode != DDS_RETCODE_OK) { printf("write error %d\n", retcode); } NDDS_Utility_sleep(&send_period); } /* retcode = cftDataWriter_unregister_instance( cft_writer, instance, &instance_handle); if (retcode != DDS_RETCODE_OK) { printf("unregister instance error %d\n", retcode); } */ /* Delete data sample */ retcode = cftTypeSupport_delete_data_ex(instance, DDS_BOOLEAN_TRUE); if (retcode != DDS_RETCODE_OK) { printf("cftTypeSupport_delete_data error %d\n", retcode); } /* Cleanup and delete delete all entities */ return publisher_shutdown(participant); } #if defined(RTI_WINCE) int wmain(int argc, wchar_t **argv) { int domainId = 0; int sample_count = 0; /* infinite loop */ if (argc >= 2) { domainId = _wtoi(argv[1]); } if (argc >= 3) { sample_count = _wtoi(argv[2]); } /* Uncomment this to turn on additional logging NDDS_Config_Logger_set_verbosity_by_category( NDDS_Config_Logger_get_instance(), NDDS_CONFIG_LOG_CATEGORY_API, NDDS_CONFIG_LOG_VERBOSITY_STATUS_ALL); */ return publisher_main(domainId, sample_count); } #elif !(defined(RTI_VXWORKS) && !defined(__RTP__)) && !defined(RTI_PSOS) int main(int argc, char *argv[]) { int domainId = 0; int sample_count = 0; /* infinite loop */ if (argc >= 2) { domainId = atoi(argv[1]); } if (argc >= 3) { sample_count = atoi(argv[2]); } /* Uncomment this to turn on additional logging NDDS_Config_Logger_set_verbosity_by_category( NDDS_Config_Logger_get_instance(), NDDS_CONFIG_LOG_CATEGORY_API, NDDS_CONFIG_LOG_VERBOSITY_STATUS_ALL); */ return publisher_main(domainId, sample_count); } #endif #ifdef RTI_VX653 const unsigned char *__ctype = NULL; void usrAppInit() { #ifdef USER_APPL_INIT USER_APPL_INIT; /* for backwards compatibility */ #endif /* add application specific code here */ taskSpawn( "pub", RTI_OSAPI_THREAD_PRIORITY_NORMAL, 0x8, 0x150000, (FUNCPTR) publisher_main, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0); } #endif
c
rticonnextdds-examples
data/projects/rticonnextdds-examples/connext_dds/content_filtered_topic_string_filter/c/cft_subscriber.c
/******************************************************************************* (c) 2005-2014 Copyright, Real-Time Innovations, Inc. All rights reserved. RTI grants Licensee a license to use, modify, compile, and create derivative works of the Software. Licensee has the right to distribute object form only for use with RTI products. The Software is provided "as is", with no warranty of any type, including any warranty for fitness for any purpose. RTI is under no obligation to maintain or support the Software. RTI shall not be liable for any incidental or consequential damages arising out of the use or inability to use the software. ******************************************************************************/ /* cft_subscriber.c A subscription example This file is derived from code automatically generated by the rtiddsgen command: rtiddsgen -language C -example <arch> cft.idl Example subscription of type cft automatically generated by 'rtiddsgen'. To test them, follow these steps: (1) Compile this file and the example publication. (2) Start the subscription with the command objs/<arch>/cft_subscriber <domain_id> <sample_count> (3) Start the publication with the command objs/<arch>/cft_publisher <domain_id> <sample_count> (4) [Optional] Specify the list of discovery initial peers and multicast receive addresses via an environment variable or a file (in the current working directory) called NDDS_DISCOVERY_PEERS. You can run any number of publishers and subscribers programs, and can add and remove them dynamically from the domain. Example: To run the example application on domain <domain_id>: On UNIX systems: objs/<arch>/cft_publisher <domain_id> objs/<arch>/cft_subscriber <domain_id> On Windows systems: objs\<arch>\cft_publisher <domain_id> objs\<arch>\cft_subscriber <domain_id> modification history ------------ ------- */ #include "cft.h" #include "cftSupport.h" #include "ndds/ndds_c.h" #include <stdio.h> #include <stdlib.h> void cftListener_on_requested_deadline_missed( void *listener_data, DDS_DataReader *reader, const struct DDS_RequestedDeadlineMissedStatus *status) { } void cftListener_on_requested_incompatible_qos( void *listener_data, DDS_DataReader *reader, const struct DDS_RequestedIncompatibleQosStatus *status) { } void cftListener_on_sample_rejected( void *listener_data, DDS_DataReader *reader, const struct DDS_SampleRejectedStatus *status) { } void cftListener_on_liveliness_changed( void *listener_data, DDS_DataReader *reader, const struct DDS_LivelinessChangedStatus *status) { } void cftListener_on_sample_lost( void *listener_data, DDS_DataReader *reader, const struct DDS_SampleLostStatus *status) { } void cftListener_on_subscription_matched( void *listener_data, DDS_DataReader *reader, const struct DDS_SubscriptionMatchedStatus *status) { } void cftListener_on_data_available(void *listener_data, DDS_DataReader *reader) { cftDataReader *cft_reader = NULL; struct cftSeq data_seq = DDS_SEQUENCE_INITIALIZER; struct DDS_SampleInfoSeq info_seq = DDS_SEQUENCE_INITIALIZER; DDS_ReturnCode_t retcode; int i; cft_reader = cftDataReader_narrow(reader); if (cft_reader == NULL) { printf("DataReader narrow error\n"); return; } retcode = cftDataReader_take( cft_reader, &data_seq, &info_seq, DDS_LENGTH_UNLIMITED, DDS_ANY_SAMPLE_STATE, DDS_ANY_VIEW_STATE, DDS_ANY_INSTANCE_STATE); if (retcode == DDS_RETCODE_NO_DATA) { return; } else if (retcode != DDS_RETCODE_OK) { printf("take error %d\n", retcode); return; } for (i = 0; i < cftSeq_get_length(&data_seq); ++i) { if (DDS_SampleInfoSeq_get_reference(&info_seq, i)->valid_data) { cftTypeSupport_print_data(cftSeq_get_reference(&data_seq, i)); } } retcode = cftDataReader_return_loan(cft_reader, &data_seq, &info_seq); if (retcode != DDS_RETCODE_OK) { printf("return loan error %d\n", retcode); } } /* Delete all entities */ static int subscriber_shutdown(DDS_DomainParticipant *participant) { DDS_ReturnCode_t retcode; int status = 0; if (participant != NULL) { retcode = DDS_DomainParticipant_delete_contained_entities(participant); if (retcode != DDS_RETCODE_OK) { printf("delete_contained_entities error %d\n", retcode); status = -1; } retcode = DDS_DomainParticipantFactory_delete_participant( DDS_TheParticipantFactory, participant); if (retcode != DDS_RETCODE_OK) { printf("delete_participant error %d\n", retcode); status = -1; } } /* RTI Connext provides the finalize_instance() method on domain participant factory for users who want to release memory used by the participant factory. Uncomment the following block of code for clean destruction of the singleton. */ /* retcode = DDS_DomainParticipantFactory_finalize_instance(); if (retcode != DDS_RETCODE_OK) { printf("finalize_instance error %d\n", retcode); status = -1; } */ return status; } static int subscriber_main(int domainId, int sample_count, int sel_cft) { DDS_DomainParticipant *participant = NULL; DDS_Subscriber *subscriber = NULL; DDS_Topic *topic = NULL; struct DDS_DataReaderListener reader_listener = DDS_DataReaderListener_INITIALIZER; DDS_DataReader *reader = NULL; DDS_ReturnCode_t retcode; const char *type_name = NULL; int count = 0; struct DDS_Duration_t poll_period = { 1, 0 }; DDS_ContentFilteredTopic *cft = NULL; /* If you want to modify datareader_qos programatically you * will need to use the following structure. */ /* struct DDS_DataReaderQos datareader_qos = DDS_DataReaderQos_INITIALIZER; */ /* For this filter we only allow 1 parameter*/ struct DDS_StringSeq parameters; const char *param_list[] = { "SOME_STRING" }; /* To customize participant QoS, use the configuration file USER_QOS_PROFILES.xml */ participant = DDS_DomainParticipantFactory_create_participant( DDS_TheParticipantFactory, domainId, &DDS_PARTICIPANT_QOS_DEFAULT, NULL /* listener */, DDS_STATUS_MASK_NONE); if (participant == NULL) { printf("create_participant error\n"); subscriber_shutdown(participant); return -1; } /* To customize subscriber QoS, use the configuration file USER_QOS_PROFILES.xml */ subscriber = DDS_DomainParticipant_create_subscriber( participant, &DDS_SUBSCRIBER_QOS_DEFAULT, NULL /* listener */, DDS_STATUS_MASK_NONE); if (subscriber == NULL) { printf("create_subscriber error\n"); subscriber_shutdown(participant); return -1; } /* Register the type before creating the topic */ type_name = cftTypeSupport_get_type_name(); retcode = cftTypeSupport_register_type(participant, type_name); if (retcode != DDS_RETCODE_OK) { printf("register_type error %d\n", retcode); subscriber_shutdown(participant); return -1; } /* To customize topic QoS, use the configuration file USER_QOS_PROFILES.xml */ topic = DDS_DomainParticipant_create_topic( participant, "Example cft", type_name, &DDS_TOPIC_QOS_DEFAULT, NULL /* listener */, DDS_STATUS_MASK_NONE); if (topic == NULL) { printf("create_topic error\n"); subscriber_shutdown(participant); return -1; } DDS_StringSeq_initialize(&parameters); DDS_StringSeq_set_maximum(&parameters, 1); /* Here we set the default filter using the param_list */ DDS_StringSeq_from_array(&parameters, param_list, 1); if (sel_cft) { /* create_contentfilteredtopic_with_filter */ cft = DDS_DomainParticipant_create_contentfilteredtopic_with_filter( participant, "ContentFilteredTopic", topic, "name MATCH %0", &parameters, DDS_STRINGMATCHFILTER_NAME); if (cft == NULL) { printf("create_contentfilteredtopic error\n"); subscriber_shutdown(participant); return -1; } } /* Set up a data reader listener */ reader_listener.on_requested_deadline_missed = cftListener_on_requested_deadline_missed; reader_listener.on_requested_incompatible_qos = cftListener_on_requested_incompatible_qos; reader_listener.on_sample_rejected = cftListener_on_sample_rejected; reader_listener.on_liveliness_changed = cftListener_on_liveliness_changed; reader_listener.on_sample_lost = cftListener_on_sample_lost; reader_listener.on_subscription_matched = cftListener_on_subscription_matched; reader_listener.on_data_available = cftListener_on_data_available; /* To customize data reader QoS, use the configuration file USER_QOS_PROFILES.xml */ if (sel_cft) { printf("Using ContentFiltered Topic\n"); reader = DDS_Subscriber_create_datareader( subscriber, DDS_ContentFilteredTopic_as_topicdescription(cft), &DDS_DATAREADER_QOS_DEFAULT, &reader_listener, DDS_STATUS_MASK_ALL); } else { printf("Using Normal Topic\n"); reader = DDS_Subscriber_create_datareader( subscriber, DDS_Topic_as_topicdescription(topic), &DDS_DATAREADER_QOS_DEFAULT, &reader_listener, DDS_STATUS_MASK_ALL); } if (reader == NULL) { printf("create_datareader error\n"); subscriber_shutdown(participant); return -1; } /* If you want to set the reliability and history QoS settings * programmatically rather than using the XML, you will need to add * the following lines to your code and comment out the create_datareader * calls above. */ /* retcode = DDS_Subscriber_get_default_datareader_qos(subscriber, &datareader_qos); if (retcode != DDS_RETCODE_OK) { printf("get_default_datareader_qos error\n"); return -1; } datareader_qos.reliability.kind = DDS_RELIABLE_RELIABILITY_QOS; datareader_qos.durability.kind = DDS_TRANSIENT_LOCAL_DURABILITY_QOS; datareader_qos.history.kind = DDS_KEEP_LAST_HISTORY_QOS; datareader_qos.history.depth = 20; if (sel_cft) { printf("Using ContentFiltered Topic\n"); reader = DDS_Subscriber_create_datareader( subscriber, DDS_ContentFilteredTopic_as_topicdescription(cft), &datareader_qos, &reader_listener, DDS_STATUS_MASK_ALL); } else { printf("Using Normal Topic\n"); reader = DDS_Subscriber_create_datareader( subscriber, DDS_Topic_as_topicdescription(topic), &datareader_qos, &reader_listener, DDS_STATUS_MASK_ALL); } if (reader == NULL) { printf("create_datareader error\n"); subscriber_shutdown(participant); return -1; } */ /* Change the filter */ if (sel_cft) { printf(">>> Now setting a new filter: name MATCH \"EVEN\"\n"); retcode = DDS_ContentFilteredTopic_append_to_expression_parameter( cft, 0, "EVEN"); if (retcode != DDS_RETCODE_OK) { printf("append_to_expression_parameter error\n"); subscriber_shutdown(participant); return -1; } } /* Main loop */ for (count = 0; (sample_count == 0) || (count < sample_count); ++count) { NDDS_Utility_sleep(&poll_period); if (sel_cft == 0) { continue; } if (count == 10) { printf("\n===========================\n"); printf("Changing filter parameters\n"); printf("Append 'ODD' filter\n"); printf("===========================\n"); retcode = DDS_ContentFilteredTopic_append_to_expression_parameter( cft, 0, "ODD"); if (retcode != DDS_RETCODE_OK) { printf("append_to_expression_parameter error\n"); subscriber_shutdown(participant); return -1; } } else if (count == 20) { printf("\n===========================\n"); printf("Changing filter parameters\n"); printf("Removing 'EVEN' filter \n"); printf("===========================\n"); retcode = DDS_ContentFilteredTopic_remove_from_expression_parameter( cft, 0, "EVEN"); if (retcode != DDS_RETCODE_OK) { printf("append_to_expression_parameter error\n"); subscriber_shutdown(participant); return -1; } } } /* Cleanup and delete all entities */ return subscriber_shutdown(participant); } #if defined(RTI_WINCE) int wmain(int argc, wchar_t **argv) { int domainId = 0; int sample_count = 0; /* infinite loop */ if (argc >= 2) { domainId = _wtoi(argv[1]); } if (argc >= 3) { sample_count = _wtoi(argv[2]); } /* Uncomment this to turn on additional logging NDDS_Config_Logger_set_verbosity_by_category( NDDS_Config_Logger_get_instance(), NDDS_CONFIG_LOG_CATEGORY_API, NDDS_CONFIG_LOG_VERBOSITY_STATUS_ALL); */ return subscriber_main(domainId, sample_count); } #elif !(defined(RTI_VXWORKS) && !defined(__RTP__)) && !defined(RTI_PSOS) int main(int argc, char *argv[]) { int domainId = 0; int sample_count = 0; /* infinite loop */ int sel_cft = 1; if (argc >= 2) { domainId = atoi(argv[1]); } if (argc >= 3) { sample_count = atoi(argv[2]); } if (argc >= 4) { sel_cft = atoi(argv[3]); } /* Uncomment this to turn on additional logging NDDS_Config_Logger_set_verbosity_by_category( NDDS_Config_Logger_get_instance(), NDDS_CONFIG_LOG_CATEGORY_API, NDDS_CONFIG_LOG_VERBOSITY_STATUS_ALL); */ return subscriber_main(domainId, sample_count, sel_cft); } #endif #ifdef RTI_VX653 const unsigned char *__ctype = NULL; void usrAppInit() { #ifdef USER_APPL_INIT USER_APPL_INIT; /* for backwards compatibility */ #endif /* add application specific code here */ taskSpawn( "sub", RTI_OSAPI_THREAD_PRIORITY_NORMAL, 0x8, 0x150000, (FUNCPTR) subscriber_main, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0); } #endif
c
rticonnextdds-examples
data/projects/rticonnextdds-examples/connext_dds/content_filtered_topic_string_filter/c++03/cft_publisher.cxx
/******************************************************************************* (c) 2005-2015 Copyright, Real-Time Innovations, Inc. All rights reserved. RTI grants Licensee a license to use, modify, compile, and create derivative works of the Software. Licensee has the right to distribute object form only for use with RTI products. The Software is provided "as is", with no warranty of any type, including any warranty for fitness for any purpose. RTI is under no obligation to maintain or support the Software. RTI shall not be liable for any incidental or consequential damages arising out of the use or inability to use the software. ******************************************************************************/ #include <cstdlib> #include <iostream> #include "cft.hpp" #include <dds/dds.hpp> using namespace dds::core; using namespace dds::core::policy; using namespace dds::domain; using namespace dds::topic; using namespace dds::pub; using namespace dds::pub::qos; void publisher_main(int domain_id, int sample_count) { // Create a DomainParticipant with default Qos DomainParticipant participant(domain_id); // Create a Topic -- and automatically register the type Topic<cft> topic(participant, "Example cft"); // Retrieve the DataWriter QoS, from USER_QOS_PROFILES.xml. DataWriterQos writer_qos = QosProvider::Default().datawriter_qos(); // If you want to change the DataWriter's QoS programmatically rather // than using the XML file, you will need to uncomment the following lines. // writer_qos << Reliability::Reliable() // << Durability::TransientLocal() // << History::KeepLast(20); // Create a DataWriter with default Qos (Publisher created in-line) DataWriter<cft> writer(Publisher(participant), topic, writer_qos); cft sample; for (int count = 0; count < sample_count || sample_count == 0; count++) { std::cout << "Writing cft, count " << count << std::endl; // Modify sample data sample.count(count); if (count % 2 == 1) { sample.name("ODD"); } else { sample.name("EVEN"); } writer.write(sample); rti::util::sleep(Duration(1)); } } int main(int argc, char *argv[]) { int domain_id = 0; int sample_count = 0; // Infinite loop if (argc >= 2) { domain_id = atoi(argv[1]); } if (argc >= 3) { sample_count = atoi(argv[2]); } // To turn on additional logging, include <rti/config/Logger.hpp> and // uncomment the following line: // rti::config::Logger::instance().verbosity(rti::config::Verbosity::STATUS_ALL); try { publisher_main(domain_id, sample_count); } catch (const std::exception &ex) { // This will catch DDS exceptions std::cerr << "Exception in publisher_main(): " << ex.what() << std::endl; return -1; } return 0; }
cxx
rticonnextdds-examples
data/projects/rticonnextdds-examples/connext_dds/content_filtered_topic_string_filter/c++03/cft_subscriber.cxx
/******************************************************************************* (c) 2005-2015 Copyright, Real-Time Innovations, Inc. All rights reserved. RTI grants Licensee a license to use, modify, compile, and create derivative works of the Software. Licensee has the right to distribute object form only for use with RTI products. The Software is provided "as is", with no warranty of any type, including any warranty for fitness for any purpose. RTI is under no obligation to maintain or support the Software. RTI shall not be liable for any incidental or consequential damages arising out of the use or inability to use the software. ******************************************************************************/ #include <algorithm> #include <cstdlib> #include <iostream> #include "cft.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 rti::core; class cftReaderListener : public NoOpDataReaderListener<cft> { public: void on_data_available(dds::sub::DataReader<cft> &reader) { // Take all samples LoanedSamples<cft> samples = reader.take(); for (LoanedSamples<cft>::iterator sample_it = samples.begin(); sample_it != samples.end(); sample_it++) { if (sample_it->info().valid()) { std::cout << sample_it->data() << std::endl; } } } }; void subscriber_main(int domain_id, int sample_count, bool is_cft) { // Create a DomainParticipant with default Qos DomainParticipant participant(domain_id); // Create a Topic -- and automatically register the type Topic<cft> topic(participant, "Example cft"); // Define the default parameter of the filter. std::vector<std::string> parameters(1); parameters[0] = "SOME_STRING"; // Retrieve the default DataReader QoS, from USER_QOS_PROFILES.xml DataReaderQos reader_qos = QosProvider::Default().datareader_qos(); // If you want to change the DataReader's QoS programmatically rather than // using the XML file, uncomment the following lines. // reader_qos << Reliability::Reliable() // << Durability::TransientLocal() // << History::KeepLast(20); // Create the ContentFilteredTopic and DataReader. ContentFilteredTopic<cft> cft_topic = dds::core::null; DataReader<cft> reader = dds::core::null; if (is_cft) { std::cout << "Using ContentFiltered Topic" << std::endl; Filter filter("name MATCH %0", parameters); // If there is no filter name, the regular SQL filter will be used. filter->name(rti::topic::stringmatch_filter_name()); cft_topic = ContentFilteredTopic<cft>( topic, "ContentFilteredTopic", filter); reader = DataReader<cft>(Subscriber(participant), cft_topic, reader_qos); } else { std::cout << "Using Normal Topic" << std::endl; reader = DataReader<cft>(Subscriber(participant), topic, reader_qos); } // Create a DataReader listener using ListenerBinder, a RAII utility that // will take care of reseting it from the reader and deleting it. ListenerBinder<DataReader<cft> > scoped_listener = bind_and_manage_listener( reader, new cftReaderListener, StatusMask::data_available()); // Change the filter if (is_cft) { std::cout << "Now setting a new filter: 'name MATCH \"EVEN\"'" << std::endl; cft_topic->append_to_expression_parameter(0, "EVEN"); } // Main loop for (int count = 0; (sample_count == 0) || (count < sample_count); count++) { rti::util::sleep(dds::core::Duration(1)); if (!is_cft) { continue; } if (count == 10) { std::cout << std::endl << "===========================" << std::endl << "Changing filter parameters" << std::endl << "Append 'ODD' filter" << std::endl << "===========================" << std::endl; cft_topic->append_to_expression_parameter(0, "ODD"); } else if (count == 20) { std::cout << std::endl << "===========================" << std::endl << "Changing filter parameters" << std::endl << "Removing 'EVEN' filter" << std::endl << "===========================" << std::endl; cft_topic->remove_from_expression_parameter(0, "EVEN"); } } } int main(int argc, char *argv[]) { int domain_id = 0; int sample_count = 0; // Infinite loop bool is_cft = true; if (argc >= 2) { domain_id = atoi(argv[1]); } if (argc >= 3) { sample_count = atoi(argv[2]); } if (argc >= 4) { is_cft = (argv[3][0] == '1'); } // To turn on additional logging, include <rti/config/Logger.hpp> and // uncomment the following line: // rti::config::Logger::instance().verbosity(rti::config::Verbosity::STATUS_ALL); try { subscriber_main(domain_id, sample_count, is_cft); } catch (const std::exception &ex) { // This will catch DDS exceptions std::cerr << "Exception in subscriber_main(): " << ex.what() << std::endl; return -1; } return 0; }
cxx
rticonnextdds-examples
data/projects/rticonnextdds-examples/connext_dds/content_filtered_topic_string_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; bool use_cft; ApplicationArguments( ParseReturn parse_result_param, unsigned int domain_id_param, unsigned int sample_count_param, rti::config::Verbosity verbosity_param, bool use_cft_param) : parse_result(parse_result_param), domain_id(domain_id_param), sample_count(sample_count_param), verbosity(verbosity_param), use_cft(use_cft_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); bool use_cft = true; while (arg_processing < argc) { if ((argc > arg_processing + 1) && (strcmp(argv[arg_processing], "-d") == 0 || strcmp(argv[arg_processing], "--domain") == 0)) { domain_id = atoi(argv[arg_processing + 1]); arg_processing += 2; } else if ( (argc > arg_processing + 1) && (strcmp(argv[arg_processing], "-s") == 0 || strcmp(argv[arg_processing], "--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 if (strcmp(argv[arg_processing], "--normal-topic") == 0) { use_cft = false; arg_processing += 1; } 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\n" " --normal-topic (subscriber only) If this " "argument\n" " is given, it will use a " "normal\n" " Topic instead of a Content " "Filtered\n" " Topic." << std::endl; } return ApplicationArguments( parse_result, domain_id, sample_count, verbosity, use_cft); } } // namespace application #endif // APPLICATION_HPP
hpp
rticonnextdds-examples
data/projects/rticonnextdds-examples/connext_dds/content_filtered_topic_string_filter/c++11/cft_publisher.cxx
/******************************************************************************* (c) 2005-2015 Copyright, Real-Time Innovations, Inc. All rights reserved. RTI grants Licensee a license to use, modify, compile, and create derivative works of the Software. Licensee has the right to distribute object form only for use with RTI products. The Software is provided "as is", with no warranty of any type, including any warranty for fitness for any purpose. RTI is under no obligation to maintain or support the Software. RTI shall not be liable for any incidental or consequential damages arising out of the use or inability to use the software. ******************************************************************************/ #include <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 "cft.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<cft> topic(participant, "Example cft"); // 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() // << Durability::TransientLocal() // << History::KeepLast(20); // Create a DataWriter with default Qos dds::pub::Publisher publisher(participant); dds::pub::DataWriter<cft> writer(publisher, topic, writer_qos); cft sample; for (unsigned int samples_written = 0; !application::shutdown_requested && samples_written < sample_count; samples_written++) { std::cout << "Writing cft, count " << samples_written << std::endl; // Modify sample data sample.count(samples_written); if (samples_written % 2 == 1) { sample.name("ODD"); } else { sample.name("EVEN"); } writer.write(sample); rti::util::sleep(dds::core::Duration(1)); } } int main(int argc, char *argv[]) { using namespace application; // Parse arguments and handle control-C auto arguments = parse_arguments(argc, argv); if (arguments.parse_result == ParseReturn::exit) { return EXIT_SUCCESS; } else if (arguments.parse_result == ParseReturn::failure) { return EXIT_FAILURE; } setup_signal_handlers(); // Sets Connext verbosity to help debugging rti::config::Logger::instance().verbosity(arguments.verbosity); try { run_publisher_application(arguments.domain_id, arguments.sample_count); } catch (const std::exception &ex) { // This will catch DDS exceptions std::cerr << "Exception in run_publisher_application(): " << ex.what() << std::endl; return EXIT_FAILURE; } // Releases the memory used by the participant factory. Optional at // application exit dds::domain::DomainParticipant::finalize_participant_factory(); return EXIT_SUCCESS; }
cxx
rticonnextdds-examples
data/projects/rticonnextdds-examples/connext_dds/content_filtered_topic_string_filter/c++11/cft_subscriber.cxx
/******************************************************************************* (c) 2005-2015 Copyright, Real-Time Innovations, Inc. All rights reserved. RTI grants Licensee a license to use, modify, compile, and create derivative works of the Software. Licensee has the right to distribute object form only for use with RTI products. The Software is provided "as is", with no warranty of any type, including any warranty for fitness for any purpose. RTI is under no obligation to maintain or support the Software. RTI shall not be liable for any incidental or consequential damages arising out of the use or inability to use the software. ******************************************************************************/ #include <dds/sub/ddssub.hpp> #include <dds/core/ddscore.hpp> #include <rti/config/Logger.hpp> // for logging #include "cft.hpp" #include "application.hpp" // for command line parsing and ctrl-c int process_data(dds::sub::DataReader<cft> reader) { int count = 0; // Take all samples dds::sub::LoanedSamples<cft> samples = reader.take(); for (const auto &sample : samples) { if (sample.info().valid()) { count++; std::cout << sample.data() << std::endl; } } return count; } void run_subscriber_application( unsigned int domain_id, unsigned int sample_count, bool is_cft) { // Create a DomainParticipant with default Qos dds::domain::DomainParticipant participant(domain_id); // Create a Topic -- and automatically register the type dds::topic::Topic<cft> topic(participant, "Example cft"); // Define the default parameter of the filter. std::vector<std::string> parameters = { "SOME_STRING" }; // 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, uncomment the following lines. // reader_qos << Reliability::Reliable() // << Durability::TransientLocal() // << History::KeepLast(20); // Create the ContentFilteredTopic and DataReader. dds::topic::ContentFilteredTopic<cft> cft_topic = dds::core::null; dds::sub::DataReader<cft> reader = dds::core::null; dds::sub::Subscriber subscriber(participant); if (is_cft) { std::cout << "Using ContentFiltered Topic" << std::endl; dds::topic::Filter filter("name MATCH %0", parameters); // If there is no filter name, the regular SQL filter will be used. filter->name(rti::topic::stringmatch_filter_name()); cft_topic = dds::topic::ContentFilteredTopic<cft>( topic, "ContentFilteredTopic", filter); reader = dds::sub::DataReader<cft>(subscriber, cft_topic, reader_qos); } else { std::cout << "Using Normal Topic" << std::endl; reader = dds::sub::DataReader<cft>(subscriber, topic, reader_qos); } // WaitSet will be woken when the attached condition is triggered dds::core::cond::WaitSet waitset; // Create a ReadCondition for any data on this reader, and add to WaitSet unsigned int samples_read = 0; dds::sub::cond::ReadCondition read_condition( reader, dds::sub::status::DataState::new_data(), [reader, &samples_read]() { samples_read += process_data(reader); }); waitset += read_condition; // Change the filter if (is_cft) { std::cout << "Now setting a new filter: 'name MATCH \"EVEN\"'" << std::endl; cft_topic->append_to_expression_parameter(0, "EVEN"); } bool filter_changed1 = false; bool filter_changed2 = false; // Main loop while (!application::shutdown_requested && samples_read < sample_count) { // Wait for data and report if it does not arrive in 1 second waitset.dispatch(dds::core::Duration(1)); if (!is_cft) { continue; } if (samples_read == 10 && !filter_changed1) { std::cout << std::endl << "===========================" << std::endl << "Changing filter parameters" << std::endl << "Append 'ODD' filter" << std::endl << "===========================" << std::endl; cft_topic->append_to_expression_parameter(0, "ODD"); filter_changed1 = true; } else if (samples_read == 20 && !filter_changed2) { std::cout << std::endl << "===========================" << std::endl << "Changing filter parameters" << std::endl << "Removing 'EVEN' filter" << std::endl << "===========================" << std::endl; cft_topic->remove_from_expression_parameter(0, "EVEN"); filter_changed2 = true; } } } 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, arguments.use_cft); } 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/batching/c++/batch_data_subscriber.cxx
/******************************************************************************* (c) 2005-2014 Copyright, Real-Time Innovations, Inc. All rights reserved. RTI grants Licensee a license to use, modify, compile, and create derivative works of the Software. Licensee has the right to distribute object form only for use with RTI products. The Software is provided "as is", with no warranty of any type, including any warranty for fitness for any purpose. RTI is under no obligation to maintain or support the Software. RTI shall not be liable for any incidental or consequential damages arising out of the use or inability to use the software. ******************************************************************************/ /* batch_data_subscriber.cxx A subscription example This file is derived from code automatically generated by the rtiddsgen command: rtiddsgen -language C++ -example <arch> batch_data.idl Example subscription of type batch_data automatically generated by 'rtiddsgen'. To test them follow these steps: (1) Compile this file and the example publication. (2) Start the subscription with the command objs/<arch>/batch_data_subscriber <domain_id> <sample_count> (3) Start the publication with the command objs/<arch>/batch_data_publisher <domain_id> <sample_count> (4) [Optional] Specify the list of discovery initial peers and multicast receive addresses via an environment variable or a file (in the current working directory) called NDDS_DISCOVERY_PEERS. You can run any number of publishers and subscribers programs, and can add and remove them dynamically from the domain. Example: To run the example application on domain <domain_id>: On Unix: objs/<arch>/batch_data_publisher <domain_id> objs/<arch>/batch_data_subscriber <domain_id> On Windows: objs\<arch>\batch_data_publisher <domain_id> objs\<arch>\batch_data_subscriber <domain_id> */ #include <stdio.h> #include <stdlib.h> #ifdef RTI_VX653 #include <vThreadsData.h> #endif #include "batch_data.h" #include "batch_dataSupport.h" #include "ndds/ndds_cpp.h" class batch_dataListener : public DDSDataReaderListener { public: virtual void on_requested_deadline_missed( DDSDataReader * /*reader*/, const DDS_RequestedDeadlineMissedStatus & /*status*/) { } virtual void on_requested_incompatible_qos( DDSDataReader * /*reader*/, const DDS_RequestedIncompatibleQosStatus & /*status*/) { } virtual void on_sample_rejected( DDSDataReader * /*reader*/, const DDS_SampleRejectedStatus & /*status*/) { } virtual void on_liveliness_changed( DDSDataReader * /*reader*/, const DDS_LivelinessChangedStatus & /*status*/) { } virtual void on_sample_lost( DDSDataReader * /*reader*/, const DDS_SampleLostStatus & /*status*/) { } virtual void on_subscription_matched( DDSDataReader * /*reader*/, const DDS_SubscriptionMatchedStatus & /*status*/) { } virtual void on_data_available(DDSDataReader *reader); }; void batch_dataListener::on_data_available(DDSDataReader *reader) { batch_dataDataReader *batch_data_reader = NULL; batch_dataSeq data_seq; DDS_SampleInfoSeq info_seq; DDS_ReturnCode_t retcode; int i; batch_data_reader = batch_dataDataReader::narrow(reader); if (batch_data_reader == NULL) { printf("DataReader narrow error\n"); return; } retcode = batch_data_reader->take( data_seq, info_seq, DDS_LENGTH_UNLIMITED, DDS_ANY_SAMPLE_STATE, DDS_ANY_VIEW_STATE, DDS_ANY_INSTANCE_STATE); if (retcode == DDS_RETCODE_NO_DATA) { return; } else if (retcode != DDS_RETCODE_OK) { printf("take error %d\n", retcode); return; } for (i = 0; i < data_seq.length(); ++i) { if (info_seq[i].valid_data) { batch_dataTypeSupport::print_data(&data_seq[i]); } } retcode = batch_data_reader->return_loan(data_seq, info_seq); if (retcode != DDS_RETCODE_OK) { printf("return loan error %d\n", retcode); } } /* Delete all entities */ static int subscriber_shutdown(DDSDomainParticipant *participant) { DDS_ReturnCode_t retcode; int status = 0; if (participant != NULL) { retcode = participant->delete_contained_entities(); if (retcode != DDS_RETCODE_OK) { printf("delete_contained_entities error %d\n", retcode); status = -1; } retcode = DDSTheParticipantFactory->delete_participant(participant); if (retcode != DDS_RETCODE_OK) { printf("delete_participant error %d\n", retcode); status = -1; } } /* RTI Connext provides the finalize_instance() method on domain participant factory for people who want to release memory used by the participant factory. Uncomment the following block of code for clean destruction of the singleton. */ /* retcode = DDSDomainParticipantFactory::finalize_instance(); if (retcode != DDS_RETCODE_OK) { printf("finalize_instance error %d\n", retcode); status = -1; } */ return status; } extern "C" int subscriber_main(int domainId, int sample_count, int turbo_mode_on) { DDSDomainParticipant *participant = NULL; DDSSubscriber *subscriber = NULL; DDSTopic *topic = NULL; batch_dataListener *reader_listener = NULL; DDSDataReader *reader = NULL; DDS_ReturnCode_t retcode; const char *type_name = NULL; int count = 0; DDS_Duration_t receive_period = { 4, 0 }; int status = 0; const char *profile_name = NULL; const char *library_name = DDS_String_dup("batching_Library"); /* We pick the profile name if the turbo_mode is selected or not. * If Turbo_mode is not selected, the batching profile will be used. */ if (turbo_mode_on) { profile_name = DDS_String_dup("turbo_mode_profile"); printf("Turbo Mode enable\n"); } else { profile_name = DDS_String_dup("batch_profile"); printf("Manual batching enable\n"); } /* To customize the participant QoS, use the configuration file USER_QOS_PROFILES.xml */ participant = DDSTheParticipantFactory->create_participant_with_profile( domainId, library_name, profile_name, NULL /* listener */, DDS_STATUS_MASK_NONE); if (participant == NULL) { printf("create_participant error\n"); subscriber_shutdown(participant); return -1; } /* To customize the subscriber QoS, use the configuration file USER_QOS_PROFILES.xml */ subscriber = participant->create_subscriber_with_profile( library_name, profile_name, NULL /* listener */, DDS_STATUS_MASK_NONE); if (subscriber == NULL) { printf("create_subscriber error\n"); subscriber_shutdown(participant); return -1; } /* Register the type before creating the topic */ type_name = batch_dataTypeSupport::get_type_name(); retcode = batch_dataTypeSupport::register_type(participant, type_name); if (retcode != DDS_RETCODE_OK) { printf("register_type error %d\n", retcode); subscriber_shutdown(participant); return -1; } /* To customize the topic QoS, use the configuration file USER_QOS_PROFILES.xml */ topic = participant->create_topic( "Example batch_data", type_name, DDS_TOPIC_QOS_DEFAULT, NULL /* listener */, DDS_STATUS_MASK_NONE); if (topic == NULL) { printf("create_topic error\n"); subscriber_shutdown(participant); return -1; } /* Create a data reader listener */ reader_listener = new batch_dataListener(); /* To customize the data reader QoS, use the configuration file USER_QOS_PROFILES.xml */ reader = subscriber->create_datareader_with_profile( topic, library_name, profile_name, reader_listener, DDS_STATUS_MASK_ALL); if (reader == NULL) { printf("create_datareader error\n"); subscriber_shutdown(participant); delete reader_listener; return -1; } /* Main loop */ for (count = 0; (sample_count == 0) || (count < sample_count); ++count) { printf("batch_data subscriber sleeping for %d sec...\n", receive_period.sec); NDDSUtility::sleep(receive_period); } /* Delete all entities */ status = subscriber_shutdown(participant); delete reader_listener; return status; } #if defined(RTI_WINCE) int wmain(int argc, wchar_t **argv) { int domainId = 0; int sample_count = 0; /* infinite loop */ int turbo_mode_on = 0; if (argc >= 2) { domainId = _wtoi(argv[1]); } if (argc >= 3) { turbo_mode_on = _wtoi(argv[2]); } if (argc >= 4) { sample_count = _wtoi(argv[3]); } /* Uncomment this to turn on additional logging NDDSConfigLogger::get_instance()-> set_verbosity_by_category(NDDS_CONFIG_LOG_CATEGORY_API, NDDS_CONFIG_LOG_VERBOSITY_STATUS_ALL); */ return subscriber_main(domainId, sample_count); } #elif !(defined(RTI_VXWORKS) && !defined(__RTP__)) && !defined(RTI_PSOS) int main(int argc, char *argv[]) { int domainId = 0; int sample_count = 0; /* infinite loop */ int turbo_mode_on = 0; if (argc >= 2) { domainId = atoi(argv[1]); } if (argc >= 3) { turbo_mode_on = atoi(argv[2]); } if (argc >= 4) { sample_count = atoi(argv[3]); } /* Uncomment this to turn on additional logging NDDSConfigLogger::get_instance()-> set_verbosity_by_category(NDDS_CONFIG_LOG_CATEGORY_API, NDDS_CONFIG_LOG_VERBOSITY_STATUS_ALL); */ return subscriber_main(domainId, sample_count, turbo_mode_on); } #endif #ifdef RTI_VX653 const unsigned char *__ctype = *(__ctypePtrGet()); extern "C" void usrAppInit() { #ifdef USER_APPL_INIT USER_APPL_INIT; /* for backwards compatibility */ #endif /* add application specific code here */ taskSpawn( "sub", RTI_OSAPI_THREAD_PRIORITY_NORMAL, 0x8, 0x150000, (FUNCPTR) subscriber_main, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0); } #endif
cxx
rticonnextdds-examples
data/projects/rticonnextdds-examples/connext_dds/batching/c++/batch_data_publisher.cxx
/******************************************************************************* (c) 2005-2014 Copyright, Real-Time Innovations, Inc. All rights reserved. RTI grants Licensee a license to use, modify, compile, and create derivative works of the Software. Licensee has the right to distribute object form only for use with RTI products. The Software is provided "as is", with no warranty of any type, including any warranty for fitness for any purpose. RTI is under no obligation to maintain or support the Software. RTI shall not be liable for any incidental or consequential damages arising out of the use or inability to use the software. ******************************************************************************/ /* batch_data_publisher.cxx A publication of data of type batch_data This file is derived from code automatically generated by the rtiddsgen command: rtiddsgen -language C++ -example <arch> batch_data.idl Example publication of type batch_data automatically generated by 'rtiddsgen'. To test them follow these steps: (1) Compile this file and the example subscription. (2) Start the subscription with the command objs/<arch>/batch_data_subscriber <domain_id> <sample_count> (3) Start the publication with the command objs/<arch>/batch_data_publisher <domain_id> <sample_count> (4) [Optional] Specify the list of discovery initial peers and multicast receive addresses via an environment variable or a file (in the current working directory) called NDDS_DISCOVERY_PEERS. You can run any number of publishers and subscribers programs, and can add and remove them dynamically from the domain. Example: To run the example application on domain <domain_id>: On Unix: objs/<arch>/batch_data_publisher <domain_id> objs/<arch>/batch_data_subscriber <domain_id> On Windows: objs\<arch>\batch_data_publisher <domain_id> objs\<arch>\batch_data_subscriber <domain_id> */ #include <stdio.h> #include <stdlib.h> #ifdef RTI_VX653 #include <vThreadsData.h> #endif #include "batch_data.h" #include "batch_dataSupport.h" #include "ndds/ndds_cpp.h" /* Delete all entities */ static int publisher_shutdown(DDSDomainParticipant *participant) { DDS_ReturnCode_t retcode; int status = 0; if (participant != NULL) { retcode = participant->delete_contained_entities(); if (retcode != DDS_RETCODE_OK) { printf("delete_contained_entities error %d\n", retcode); status = -1; } retcode = DDSTheParticipantFactory->delete_participant(participant); if (retcode != DDS_RETCODE_OK) { printf("delete_participant error %d\n", retcode); status = -1; } } /* RTI Connext provides finalize_instance() method on domain participant factory for people who want to release memory used by the participant factory. Uncomment the following block of code for clean destruction of the singleton. */ /* retcode = DDSDomainParticipantFactory::finalize_instance(); if (retcode != DDS_RETCODE_OK) { printf("finalize_instance error %d\n", retcode); status = -1; } */ return status; } extern "C" int publisher_main(int domainId, int sample_count, int turbo_mode_on) { DDSDomainParticipant *participant = NULL; DDSPublisher *publisher = NULL; DDSTopic *topic = NULL; DDSDataWriter *writer = NULL; batch_dataDataWriter *batch_data_writer = NULL; batch_data *instance = NULL; DDS_ReturnCode_t retcode; DDS_InstanceHandle_t instance_handle = DDS_HANDLE_NIL; const char *type_name = NULL; int count = 0; DDS_Duration_t send_period = { 1, 0 }; const char *profile_name = NULL; const char *library_name = DDS_String_dup("batching_Library"); /* We pick the profile name if the turbo_mode is selected or not. * If Turbo_mode is not selected, the batching profile will be used. */ if (turbo_mode_on) { profile_name = DDS_String_dup("turbo_mode_profile"); /* In turbo_mode, we do not want to wait to send samples */ send_period.sec = 0; printf("Turbo Mode enable\n"); } else { profile_name = DDS_String_dup("batch_profile"); printf("Manual batching enable\n"); } /* To customize participant QoS, use the configuration file USER_QOS_PROFILES.xml */ participant = DDSTheParticipantFactory->create_participant_with_profile( domainId, library_name, profile_name, NULL /* listener */, DDS_STATUS_MASK_NONE); if (participant == NULL) { printf("create_participant error\n"); publisher_shutdown(participant); return -1; } /* To customize publisher QoS, use the configuration file USER_QOS_PROFILES.xml */ publisher = participant->create_publisher_with_profile( library_name, profile_name, NULL /* listener */, DDS_STATUS_MASK_NONE); if (publisher == NULL) { printf("create_publisher error\n"); publisher_shutdown(participant); return -1; } /* Register type before creating topic */ type_name = batch_dataTypeSupport::get_type_name(); retcode = batch_dataTypeSupport::register_type(participant, type_name); if (retcode != DDS_RETCODE_OK) { printf("register_type error %d\n", retcode); publisher_shutdown(participant); return -1; } /* To customize topic QoS, use the configuration file USER_QOS_PROFILES.xml */ topic = participant->create_topic( "Example batch_data", type_name, DDS_TOPIC_QOS_DEFAULT, NULL /* listener */, DDS_STATUS_MASK_NONE); if (topic == NULL) { printf("create_topic error\n"); publisher_shutdown(participant); return -1; } /* To customize data writer QoS, use the configuration file USER_QOS_PROFILES.xml */ writer = publisher->create_datawriter_with_profile( topic, library_name, profile_name, NULL /* listener */, DDS_STATUS_MASK_NONE); if (writer == NULL) { printf("create_datawriter error\n"); publisher_shutdown(participant); return -1; } batch_data_writer = batch_dataDataWriter::narrow(writer); if (batch_data_writer == NULL) { printf("DataWriter narrow error\n"); publisher_shutdown(participant); return -1; } /* Create data sample for writing */ instance = batch_dataTypeSupport::create_data(); if (instance == NULL) { printf("batch_dataTypeSupport::create_data error\n"); publisher_shutdown(participant); return -1; } /* For a data type that has a key, if the same instance is going to be written multiple times, initialize the key here and register the keyed instance prior to writing */ /* instance_handle = batch_data_writer->register_instance(*instance); */ /* Main loop */ for (count = 0; (sample_count == 0) || (count < sample_count); ++count) { printf("Writing batch_data, count %d\n", count); /* Modify the data to be sent here */ instance->x = count; retcode = batch_data_writer->write(*instance, instance_handle); if (retcode != DDS_RETCODE_OK) { printf("write error %d\n", retcode); } NDDSUtility::sleep(send_period); } /* retcode = batch_data_writer->unregister_instance( *instance, instance_handle); if (retcode != DDS_RETCODE_OK) { printf("unregister instance error %d\n", retcode); } */ /* Delete data sample */ retcode = batch_dataTypeSupport::delete_data(instance); if (retcode != DDS_RETCODE_OK) { printf("batch_dataTypeSupport::delete_data error %d\n", retcode); } /* Delete all entities */ return publisher_shutdown(participant); } #if defined(RTI_WINCE) int wmain(int argc, wchar_t **argv) { int domainId = 0; int sample_count = 0; /* infinite loop */ int turbo_mode_on = 0; if (argc >= 2) { domainId = _wtoi(argv[1]); } if (argc >= 3) { turbo_mode_on = _wtoi(argv[2]); } if (argc >= 4) { sample_count = _wtoi(argv[3]); } /* Uncomment this to turn on additional logging NDDSConfigLogger::get_instance()-> set_verbosity_by_category(NDDS_CONFIG_LOG_CATEGORY_API, NDDS_CONFIG_LOG_VERBOSITY_STATUS_ALL); */ return publisher_main(domainId, sample_count, turbo_mode_on); } #elif !(defined(RTI_VXWORKS) && !defined(__RTP__)) && !defined(RTI_PSOS) int main(int argc, char *argv[]) { int domainId = 0; int sample_count = 0; /* infinite loop */ int turbo_mode_on = 0; if (argc >= 2) { domainId = atoi(argv[1]); } if (argc >= 3) { turbo_mode_on = atoi(argv[2]); } if (argc >= 4) { sample_count = atoi(argv[3]); } /* Uncomment this to turn on additional logging NDDSConfigLogger::get_instance()-> set_verbosity_by_category(NDDS_CONFIG_LOG_CATEGORY_API, NDDS_CONFIG_LOG_VERBOSITY_STATUS_ALL); */ return publisher_main(domainId, sample_count, turbo_mode_on); } #endif #ifdef RTI_VX653 const unsigned char *__ctype = *(__ctypePtrGet()); extern "C" void usrAppInit() { #ifdef USER_APPL_INIT USER_APPL_INIT; /* for backwards compatibility */ #endif /* add application specific code here */ taskSpawn( "pub", RTI_OSAPI_THREAD_PRIORITY_NORMAL, 0x8, 0x150000, (FUNCPTR) publisher_main, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0); } #endif
cxx
rticonnextdds-examples
data/projects/rticonnextdds-examples/connext_dds/batching/c++98/batch_data_subscriber.cxx
/******************************************************************************* (c) 2005-2014 Copyright, Real-Time Innovations, Inc. All rights reserved. RTI grants Licensee a license to use, modify, compile, and create derivative works of the Software. Licensee has the right to distribute object form only for use with RTI products. The Software is provided "as is", with no warranty of any type, including any warranty for fitness for any purpose. RTI is under no obligation to maintain or support the Software. RTI shall not be liable for any incidental or consequential damages arising out of the use or inability to use the software. ******************************************************************************/ #include <iostream> #include <stdio.h> #include <stdlib.h> #include "batch_data.h" #include "batch_dataSupport.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(batch_dataDataReader *typed_reader) { batch_dataSeq 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++; batch_dataTypeSupport::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(int domain_id, int sample_count, bool turbo_mode) { DDS_Duration_t wait_timeout = { 4, 0 }; const char *profile_name = NULL; const char *library_name = DDS_String_dup("batching_Library"); /* We pick the profile name if the turbo_mode is selected or not. * If Turbo_mode is not selected, the batching profile will be used. */ if (turbo_mode) { profile_name = DDS_String_dup("turbo_mode_profile"); std::cout << "Turbo Mode enable\n"; } else { profile_name = DDS_String_dup("batch_profile"); std::cout << "Manual batching enable\n"; } // Start communicating in a domain, usually one participant per application DDSDomainParticipant *participant = DDSTheParticipantFactory->create_participant_with_profile( domain_id, library_name, profile_name, 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_with_profile( library_name, profile_name, 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 = batch_dataTypeSupport::get_type_name(); DDS_ReturnCode_t retcode = batch_dataTypeSupport::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 batch_data", 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 batch_data" Topic DDSDataReader *untyped_reader = subscriber->create_datareader_with_profile( topic, library_name, profile_name, NULL /* 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 batch_dataDataReader *typed_reader = batch_dataDataReader::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 << "batch_data subscriber sleeping for " << wait_timeout.sec << " sec...\n"; 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, arguments.turbo_mode); // 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/batching/c++98/batch_data_publisher.cxx
/******************************************************************************* (c) 2005-2014 Copyright, Real-Time Innovations, Inc. All rights reserved. RTI grants Licensee a license to use, modify, compile, and create derivative works of the Software. Licensee has the right to distribute object form only for use with RTI products. The Software is provided "as is", with no warranty of any type, including any warranty for fitness for any purpose. RTI is under no obligation to maintain or support the Software. RTI shall not be liable for any incidental or consequential damages arising out of the use or inability to use the software. ******************************************************************************/ #include <iostream> #include <stdio.h> #include <stdlib.h> #include "batch_data.h" #include "batch_dataSupport.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, bool turbo_mode) { DDS_Duration_t send_period = { 1, 0 }; const char *profile_name = NULL; const char *library_name = DDS_String_dup("batching_Library"); /* We pick the profile name if the turbo_mode is selected or not. * If Turbo_mode is not selected, the batching profile will be used. */ if (turbo_mode) { profile_name = DDS_String_dup("turbo_mode_profile"); /* In turbo_mode, we do not want to wait to send samples */ send_period.sec = 0; std::cout << "Turbo Mode enable\n"; } else { profile_name = DDS_String_dup("batch_profile"); std::cout << "Manual batching enable\n"; } // Start communicating in a domain, usually one participant per application DDSDomainParticipant *participant = DDSTheParticipantFactory->create_participant_with_profile( domain_id, library_name, profile_name, 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( library_name, profile_name, 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 = batch_dataTypeSupport::get_type_name(); DDS_ReturnCode_t retcode = batch_dataTypeSupport::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 batch_data", 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 batch_data" Topic DDSDataWriter *untyped_writer = publisher->create_datawriter_with_profile( topic, library_name, profile_name, 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 batch_dataDataWriter *typed_writer = batch_dataDataWriter::narrow(untyped_writer); if (typed_writer == NULL) { return shutdown_participant( participant, "DataWriter narrow error", EXIT_FAILURE); } // Create data for writing, allocating all members batch_data *data = batch_dataTypeSupport::create_data(); if (data == NULL) { return shutdown_participant( participant, "batch_dataTypeSupport::create_data error", EXIT_FAILURE); } DDS_InstanceHandle_t instance_handle = DDS_HANDLE_NIL; /* For a data type that has a key, if the same instance is going to be written multiple times, initialize the key here and register the keyed instance prior to writing */ /* instance_handle = typed_writer->register_instance(*data); */ // Main loop, write data for (unsigned int samples_written = 0; !shutdown_requested && samples_written < sample_count; ++samples_written) { std::cout << "Writing batch_data, count " << samples_written << std::endl; /* Modify the data to be sent here */ data->x = samples_written; retcode = typed_writer->write(*data, instance_handle); if (retcode != DDS_RETCODE_OK) { std::cout << "write error " << samples_written << 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 batch_data, including all contained elements retcode = batch_dataTypeSupport::delete_data(data); if (retcode != DDS_RETCODE_OK) { std::cerr << "batch_dataTypeSupport::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, arguments.turbo_mode); // 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/batching/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; bool turbo_mode; }; 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.turbo_mode = 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], "--turbo") == 0) { arguments.turbo_mode = true; arg_processing += 1; } 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" " --turbo Activates turbo mode.\n" " Default: desactivated" " -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/batching/c/batch_data_subscriber.c
/******************************************************************************* (c) 2005-2014 Copyright, Real-Time Innovations, Inc. All rights reserved. RTI grants Licensee a license to use, modify, compile, and create derivative works of the Software. Licensee has the right to distribute object form only for use with RTI products. The Software is provided "as is", with no warranty of any type, including any warranty for fitness for any purpose. RTI is under no obligation to maintain or support the Software. RTI shall not be liable for any incidental or consequential damages arising out of the use or inability to use the software. ******************************************************************************/ /* batch_data_subscriber.c A subscription example This file is derived from code automatically generated by the rtiddsgen command: rtiddsgen -language C -example <arch> batch_data.idl Example subscription of type batch_data automatically generated by 'rtiddsgen'. To test them, follow these steps: (1) Compile this file and the example publication. (2) Start the subscription with the command objs/<arch>/batch_data_subscriber <domain_id> <sample_count> (3) Start the publication with the command objs/<arch>/batch_data_publisher <domain_id> <sample_count> (4) [Optional] Specify the list of discovery initial peers and multicast receive addresses via an environment variable or a file (in the current working directory) called NDDS_DISCOVERY_PEERS. You can run any number of publishers and subscribers programs, and can add and remove them dynamically from the domain. Example: To run the example application on domain <domain_id>: On UNIX systems: objs/<arch>/batch_data_publisher <domain_id> objs/<arch>/batch_data_subscriber <domain_id> On Windows systems: objs\<arch>\batch_data_publisher <domain_id> objs\<arch>\batch_data_subscriber <domain_id> modification history ------------ ------- */ #include "batch_data.h" #include "batch_dataSupport.h" #include "ndds/ndds_c.h" #include <stdio.h> #include <stdlib.h> void batch_dataListener_on_requested_deadline_missed( void *listener_data, DDS_DataReader *reader, const struct DDS_RequestedDeadlineMissedStatus *status) { } void batch_dataListener_on_requested_incompatible_qos( void *listener_data, DDS_DataReader *reader, const struct DDS_RequestedIncompatibleQosStatus *status) { } void batch_dataListener_on_sample_rejected( void *listener_data, DDS_DataReader *reader, const struct DDS_SampleRejectedStatus *status) { } void batch_dataListener_on_liveliness_changed( void *listener_data, DDS_DataReader *reader, const struct DDS_LivelinessChangedStatus *status) { } void batch_dataListener_on_sample_lost( void *listener_data, DDS_DataReader *reader, const struct DDS_SampleLostStatus *status) { } void batch_dataListener_on_subscription_matched( void *listener_data, DDS_DataReader *reader, const struct DDS_SubscriptionMatchedStatus *status) { } void batch_dataListener_on_data_available( void *listener_data, DDS_DataReader *reader) { batch_dataDataReader *batch_data_reader = NULL; struct batch_dataSeq data_seq = DDS_SEQUENCE_INITIALIZER; struct DDS_SampleInfoSeq info_seq = DDS_SEQUENCE_INITIALIZER; DDS_ReturnCode_t retcode; int i; batch_data_reader = batch_dataDataReader_narrow(reader); if (batch_data_reader == NULL) { printf("DataReader narrow error\n"); return; } retcode = batch_dataDataReader_take( batch_data_reader, &data_seq, &info_seq, DDS_LENGTH_UNLIMITED, DDS_ANY_SAMPLE_STATE, DDS_ANY_VIEW_STATE, DDS_ANY_INSTANCE_STATE); if (retcode == DDS_RETCODE_NO_DATA) { return; } else if (retcode != DDS_RETCODE_OK) { printf("take error %d\n", retcode); return; } for (i = 0; i < batch_dataSeq_get_length(&data_seq); ++i) { if (DDS_SampleInfoSeq_get_reference(&info_seq, i)->valid_data) { batch_dataTypeSupport_print_data( batch_dataSeq_get_reference(&data_seq, i)); } } retcode = batch_dataDataReader_return_loan( batch_data_reader, &data_seq, &info_seq); if (retcode != DDS_RETCODE_OK) { printf("return loan error %d\n", retcode); } } /* Delete all entities */ static int subscriber_shutdown(DDS_DomainParticipant *participant) { DDS_ReturnCode_t retcode; int status = 0; if (participant != NULL) { retcode = DDS_DomainParticipant_delete_contained_entities(participant); if (retcode != DDS_RETCODE_OK) { printf("delete_contained_entities error %d\n", retcode); status = -1; } retcode = DDS_DomainParticipantFactory_delete_participant( DDS_TheParticipantFactory, participant); if (retcode != DDS_RETCODE_OK) { printf("delete_participant error %d\n", retcode); status = -1; } } /* RTI Connext provides the finalize_instance() method on domain participant factory for users who want to release memory used by the participant factory. Uncomment the following block of code for clean destruction of the singleton. */ /* retcode = DDS_DomainParticipantFactory_finalize_instance(); if (retcode != DDS_RETCODE_OK) { printf("finalize_instance error %d\n", retcode); status = -1; } */ return status; } static int subscriber_main(int domainId, int sample_count, int turbo_mode_on) { DDS_DomainParticipant *participant = NULL; DDS_Subscriber *subscriber = NULL; DDS_Topic *topic = NULL; struct DDS_DataReaderListener reader_listener = DDS_DataReaderListener_INITIALIZER; DDS_DataReader *reader = NULL; DDS_ReturnCode_t retcode; const char *type_name = NULL; int count = 0; struct DDS_Duration_t poll_period = { 4, 0 }; const char *profile_name = NULL; const char *library_name = DDS_String_dup("batching_Library"); /* We pick the profile name if the turbo_mode is selected or not. * If Turbo_mode is not selected, the batching profile will be used. */ if (turbo_mode_on) { profile_name = DDS_String_dup("turbo_mode_profile"); printf("Turbo Mode enable\n"); } else { profile_name = DDS_String_dup("batch_profile"); printf("Manual batching enable\n"); } /* To customize participant QoS, use the configuration file USER_QOS_PROFILES.xml */ participant = DDS_DomainParticipantFactory_create_participant_with_profile( DDS_TheParticipantFactory, domainId, library_name, profile_name, NULL /* listener */, DDS_STATUS_MASK_NONE); if (participant == NULL) { printf("create_participant error\n"); subscriber_shutdown(participant); return -1; } /* To customize subscriber QoS, use the configuration file USER_QOS_PROFILES.xml */ subscriber = DDS_DomainParticipant_create_subscriber_with_profile( participant, library_name, profile_name, NULL /* listener */, DDS_STATUS_MASK_NONE); if (subscriber == NULL) { printf("create_subscriber error\n"); subscriber_shutdown(participant); return -1; } /* Register the type before creating the topic */ type_name = batch_dataTypeSupport_get_type_name(); retcode = batch_dataTypeSupport_register_type(participant, type_name); if (retcode != DDS_RETCODE_OK) { printf("register_type error %d\n", retcode); subscriber_shutdown(participant); return -1; } /* To customize topic QoS, use the configuration file USER_QOS_PROFILES.xml */ topic = DDS_DomainParticipant_create_topic( participant, "Example batch_data", type_name, &DDS_TOPIC_QOS_DEFAULT, NULL /* listener */, DDS_STATUS_MASK_NONE); if (topic == NULL) { printf("create_topic error\n"); subscriber_shutdown(participant); return -1; } /* Set up a data reader listener */ reader_listener.on_requested_deadline_missed = batch_dataListener_on_requested_deadline_missed; reader_listener.on_requested_incompatible_qos = batch_dataListener_on_requested_incompatible_qos; reader_listener.on_sample_rejected = batch_dataListener_on_sample_rejected; reader_listener.on_liveliness_changed = batch_dataListener_on_liveliness_changed; reader_listener.on_sample_lost = batch_dataListener_on_sample_lost; reader_listener.on_subscription_matched = batch_dataListener_on_subscription_matched; reader_listener.on_data_available = batch_dataListener_on_data_available; /* To customize data reader QoS, use the configuration file USER_QOS_PROFILES.xml */ reader = DDS_Subscriber_create_datareader_with_profile( subscriber, DDS_Topic_as_topicdescription(topic), library_name, profile_name, &reader_listener, DDS_STATUS_MASK_ALL); if (reader == NULL) { printf("create_datareader error\n"); subscriber_shutdown(participant); return -1; } /* Main loop */ for (count = 0; (sample_count == 0) || (count < sample_count); ++count) { printf("batch_data subscriber sleeping for %d sec...\n", poll_period.sec); NDDS_Utility_sleep(&poll_period); } /* Cleanup and delete all entities */ return subscriber_shutdown(participant); } #if defined(RTI_WINCE) int wmain(int argc, wchar_t **argv) { int domainId = 0; int sample_count = 0; /* infinite loop */ int turbo_mode_on = 0; if (argc >= 2) { domainId = _wtoi(argv[1]); } if (argc >= 3) { turbo_mode_on = _wtoi(argv[2]); } if (argc >= 4) { sample_count = _wtoi(argv[3]); } /* Uncomment this to turn on additional logging NDDS_Config_Logger_set_verbosity_by_category( NDDS_Config_Logger_get_instance(), NDDS_CONFIG_LOG_CATEGORY_API, NDDS_CONFIG_LOG_VERBOSITY_STATUS_ALL); */ return subscriber_main(domainId, sample_count, turbo_mode_on); } #elif !(defined(RTI_VXWORKS) && !defined(__RTP__)) && !defined(RTI_PSOS) int main(int argc, char *argv[]) { int domainId = 0; int sample_count = 0; /* infinite loop */ int turbo_mode_on = 0; if (argc >= 2) { domainId = atoi(argv[1]); } if (argc >= 3) { turbo_mode_on = atoi(argv[2]); } if (argc >= 4) { sample_count = atoi(argv[3]); } /* Uncomment this to turn on additional logging NDDS_Config_Logger_set_verbosity_by_category( NDDS_Config_Logger_get_instance(), NDDS_CONFIG_LOG_CATEGORY_API, NDDS_CONFIG_LOG_VERBOSITY_STATUS_ALL); */ return subscriber_main(domainId, sample_count, turbo_mode_on); } #endif #ifdef RTI_VX653 const unsigned char *__ctype = NULL; void usrAppInit() { #ifdef USER_APPL_INIT USER_APPL_INIT; /* for backwards compatibility */ #endif /* add application specific code here */ taskSpawn( "sub", RTI_OSAPI_THREAD_PRIORITY_NORMAL, 0x8, 0x150000, (FUNCPTR) subscriber_main, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0); } #endif
c
rticonnextdds-examples
data/projects/rticonnextdds-examples/connext_dds/batching/c/batch_data_publisher.c
/******************************************************************************* (c) 2005-2014 Copyright, Real-Time Innovations, Inc. All rights reserved. RTI grants Licensee a license to use, modify, compile, and create derivative works of the Software. Licensee has the right to distribute object form only for use with RTI products. The Software is provided "as is", with no warranty of any type, including any warranty for fitness for any purpose. RTI is under no obligation to maintain or support the Software. RTI shall not be liable for any incidental or consequential damages arising out of the use or inability to use the software. ******************************************************************************/ /* batch_data_publisher.c A publication of data of type batch_data This file is derived from code automatically generated by the rtiddsgen command: rtiddsgen -language C -example <arch> batch_data.idl Example publication of type batch_data automatically generated by 'rtiddsgen'. To test them follow these steps: (1) Compile this file and the example subscription. (2) Start the subscription with the command objs/<arch>/batch_data_subscriber <domain_id> <sample_count> (3) Start the publication with the command objs/<arch>/batch_data_publisher <domain_id> <sample_count> (4) [Optional] Specify the list of discovery initial peers and multicast receive addresses via an environment variable or a file (in the current working directory) called NDDS_DISCOVERY_PEERS. You can run any number of publishers and subscribers programs, and can add and remove them dynamically from the domain. Example: To run the example application on domain <domain_id>: On Unix: objs/<arch>/batch_data_publisher <domain_id> objs/<arch>/batch_data_subscriber <domain_id> On Windows: objs\<arch>\batch_data_publisher <domain_id> objs\<arch>\batch_data_subscriber <domain_id> modification history ------------ ------- */ #include "batch_data.h" #include "batch_dataSupport.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, int turbo_mode_on) { DDS_DomainParticipant *participant = NULL; DDS_Publisher *publisher = NULL; DDS_Topic *topic = NULL; DDS_DataWriter *writer = NULL; batch_dataDataWriter *batch_data_writer = NULL; batch_data *instance = NULL; DDS_ReturnCode_t retcode; DDS_InstanceHandle_t instance_handle = DDS_HANDLE_NIL; const char *type_name = NULL; int count = 0; struct DDS_Duration_t send_period = { 1, 0 }; const char *profile_name = NULL; const char *library_name = DDS_String_dup("batching_Library"); /* We pick the profile name if the turbo_mode is selected or not. * If Turbo_mode is not selected, the batching profile will be used. */ if (turbo_mode_on) { profile_name = DDS_String_dup("turbo_mode_profile"); /* In turbo_mode, we do not want to wait to send samples */ send_period.sec = 0; printf("Turbo Mode enable\n"); } else { profile_name = DDS_String_dup("batch_profile"); printf("Manual batching enable\n"); } /* To customize participant QoS, use the configuration file USER_QOS_PROFILES.xml */ participant = DDS_DomainParticipantFactory_create_participant_with_profile( DDS_TheParticipantFactory, domainId, library_name, profile_name, NULL /* listener */, DDS_STATUS_MASK_NONE); if (participant == NULL) { printf("create_participant error\n"); publisher_shutdown(participant); return -1; } /* To customize publisher QoS, use the configuration file USER_QOS_PROFILES.xml */ publisher = DDS_DomainParticipant_create_publisher_with_profile( participant, library_name, profile_name, NULL /* listener */, DDS_STATUS_MASK_NONE); if (publisher == NULL) { printf("create_publisher error\n"); publisher_shutdown(participant); return -1; } /* Register type before creating topic */ type_name = batch_dataTypeSupport_get_type_name(); retcode = batch_dataTypeSupport_register_type(participant, type_name); if (retcode != DDS_RETCODE_OK) { printf("register_type error %d\n", retcode); publisher_shutdown(participant); return -1; } /* To customize topic QoS, use the configuration file USER_QOS_PROFILES.xml */ topic = DDS_DomainParticipant_create_topic( participant, "Example batch_data", type_name, &DDS_TOPIC_QOS_DEFAULT, NULL /* listener */, DDS_STATUS_MASK_NONE); if (topic == NULL) { printf("create_topic error\n"); publisher_shutdown(participant); return -1; } /* To customize data writer QoS, use the configuration file USER_QOS_PROFILES.xml */ writer = DDS_Publisher_create_datawriter_with_profile( publisher, topic, library_name, profile_name, NULL /* listener */, DDS_STATUS_MASK_NONE); if (writer == NULL) { printf("create_datawriter error\n"); publisher_shutdown(participant); return -1; } batch_data_writer = batch_dataDataWriter_narrow(writer); if (batch_data_writer == NULL) { printf("DataWriter narrow error\n"); publisher_shutdown(participant); return -1; } /* Create data sample for writing */ instance = batch_dataTypeSupport_create_data_ex(DDS_BOOLEAN_TRUE); if (instance == NULL) { printf("batch_dataTypeSupport_create_data error\n"); publisher_shutdown(participant); return -1; } /* For a data type that has a key, if the same instance is going to be written multiple times, initialize the key here and register the keyed instance prior to writing */ /* instance_handle = batch_dataDataWriter_register_instance( batch_data_writer, instance); */ /* Main loop */ for (count = 0; (sample_count == 0) || (count < sample_count); ++count) { printf("Writing batch_data, count %d\n", count); /* Modify the data to be written here */ instance->x = count; /* Write data */ retcode = batch_dataDataWriter_write( batch_data_writer, instance, &instance_handle); if (retcode != DDS_RETCODE_OK) { printf("write error %d\n", retcode); } NDDS_Utility_sleep(&send_period); } /* retcode = batch_dataDataWriter_unregister_instance( batch_data_writer, instance, &instance_handle); if (retcode != DDS_RETCODE_OK) { printf("unregister instance error %d\n", retcode); } */ /* Delete data sample */ retcode = batch_dataTypeSupport_delete_data_ex(instance, DDS_BOOLEAN_TRUE); if (retcode != DDS_RETCODE_OK) { printf("batch_dataTypeSupport_delete_data error %d\n", retcode); } /* Cleanup and delete delete all entities */ return publisher_shutdown(participant); } #if defined(RTI_WINCE) int wmain(int argc, wchar_t **argv) { int domainId = 0; int sample_count = 0; /* infinite loop */ int turbo_mode_on = 0; if (argc >= 2) { domainId = _wtoi(argv[1]); } if (argc >= 3) { turbo_mode_on = _wtoi(argv[2]); } if (argc >= 4) { sample_count = _wtoi(argv[3]); } /* Uncomment this to turn on additional logging NDDS_Config_Logger_set_verbosity_by_category( NDDS_Config_Logger_get_instance(), NDDS_CONFIG_LOG_CATEGORY_API, NDDS_CONFIG_LOG_VERBOSITY_STATUS_ALL); */ return publisher_main(domainId, sample_count, turbo_mode_on); } #elif !(defined(RTI_VXWORKS) && !defined(__RTP__)) && !defined(RTI_PSOS) int main(int argc, char *argv[]) { int domainId = 0; int sample_count = 0; /* infinite loop */ int turbo_mode_on = 0; if (argc >= 2) { domainId = atoi(argv[1]); } if (argc >= 3) { turbo_mode_on = atoi(argv[2]); } if (argc >= 4) { sample_count = atoi(argv[3]); } /* Uncomment this to turn on additional logging NDDS_Config_Logger_set_verbosity_by_category( NDDS_Config_Logger_get_instance(), NDDS_CONFIG_LOG_CATEGORY_API, NDDS_CONFIG_LOG_VERBOSITY_STATUS_ALL); */ return publisher_main(domainId, sample_count, turbo_mode_on); } #endif #ifdef RTI_VX653 const unsigned char *__ctype = NULL; void usrAppInit() { #ifdef USER_APPL_INIT USER_APPL_INIT; /* for backwards compatibility */ #endif /* add application specific code here */ taskSpawn( "pub", RTI_OSAPI_THREAD_PRIORITY_NORMAL, 0x8, 0x150000, (FUNCPTR) publisher_main, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0); } #endif
c
rticonnextdds-examples
data/projects/rticonnextdds-examples/connext_dds/batching/c++03/batch_data_subscriber.cxx
/******************************************************************************* (c) 2005-2015 Copyright, Real-Time Innovations, Inc. All rights reserved. RTI grants Licensee a license to use, modify, compile, and create derivative works of the Software. Licensee has the right to distribute object form only for use with RTI products. The Software is provided "as is", with no warranty of any type, including any warranty for fitness for any purpose. RTI is under no obligation to maintain or support the Software. RTI shall not be liable for any incidental or consequential damages arising out of the use or inability to use the software. ******************************************************************************/ #include <string> #include "batch_data.hpp" #include <dds/dds.hpp> #include <rti/core/ListenerBinder.hpp> using namespace dds::core; using namespace dds::core::policy; using namespace dds::core::status; using namespace dds::domain; using namespace dds::topic; using namespace dds::sub; using namespace dds::sub::qos; class BatchDataReaderListener : public NoOpDataReaderListener<batch_data> { public: void on_data_available(DataReader<batch_data> &reader) { // Take all samples LoanedSamples<batch_data> samples = reader.take(); for (LoanedSamples<batch_data>::iterator sample_it = samples.begin(); sample_it != samples.end(); sample_it++) { if (sample_it->info().valid()) { std::cout << sample_it->data() << std::endl; } } } }; void subscriber_main(int domain_id, int sample_count, bool turbo_mode_on) { // We pick the profile name if the turbo_mode is selected or not. // If turbo_mode is not selected, the batching profile will be used. std::string profile_name = "batching_Library::"; if (turbo_mode_on) { std::cout << "Turbo Mode enable" << std::endl; profile_name.append("turbo_mode_profile"); } else { std::cout << "Manual batching enable" << std::endl; profile_name.append("batch_profile"); } // To customize entities QoS use the file USER_QOS_PROFILES.xml DomainParticipant participant( domain_id, QosProvider::Default().participant_qos(profile_name)); Topic<batch_data> topic(participant, "Example batch_data"); Subscriber subscriber( participant, QosProvider::Default().subscriber_qos(profile_name)); DataReader<batch_data> reader( subscriber, topic, QosProvider::Default().datareader_qos(profile_name)); // Set the listener using a RAII so it's exception-safe rti::core::ListenerBinder<DataReader<batch_data> > scoped_listener = rti::core::bind_and_manage_listener( reader, new BatchDataReaderListener, StatusMask::data_available()); // Main loop for (int count = 0; count < sample_count || sample_count == 0; ++count) { std::cout << "batch_data subscriber sleeping for 4 sec...\n"; rti::util::sleep(Duration(4)); } } int main(int argc, char *argv[]) { int domain_id = 0; int sample_count = 0; // Infinite loop bool turbo_mode_on = false; if (argc >= 2) { domain_id = atoi(argv[1]); } if (argc >= 3) { turbo_mode_on = (argv[2][0] == '1'); } if (argc >= 4) { sample_count = atoi(argv[3]); } // To turn on additional logging, include <rti/config/Logger.hpp> and // uncomment the following line: // rti::config::Logger::instance().verbosity(rti::config::Verbosity::STATUS_ALL); try { subscriber_main(domain_id, sample_count, turbo_mode_on); } catch (const std::exception &ex) { // This will catch DDS exceptions std::cerr << "Exception in subscriber_main(): " << ex.what() << "\n"; return -1; } // RTI Connext provides a finalize_participant_factory() method // if you want to release memory used by the participant factory singleton. // dds::domain::DomainParticipant::finalize_participant_factory(); return 0; }
cxx
rticonnextdds-examples
data/projects/rticonnextdds-examples/connext_dds/batching/c++03/batch_data_publisher.cxx
/******************************************************************************* (c) 2005-2015 Copyright, Real-Time Innovations, Inc. All rights reserved. RTI grants Licensee a license to use, modify, compile, and create derivative works of the Software. Licensee has the right to distribute object form only for use with RTI products. The Software is provided "as is", with no warranty of any type, including any warranty for fitness for any purpose. RTI is under no obligation to maintain or support the Software. RTI shall not be liable for any incidental or consequential damages arising out of the use or inability to use the software. ******************************************************************************/ #include <string> #include "batch_data.hpp" #include <dds/dds.hpp> using namespace dds::core; using namespace dds::domain; using namespace dds::domain::qos; using namespace dds::topic; using namespace dds::pub; void publisher_main(int domain_id, int sample_count, bool turbo_mode_on) { // Seconds to wait between samples published. Duration send_period(1); // We pick the profile name if the turbo_mode is selected or not. // If turbo_mode is not selected, the batching profile will be used. std::string profile_name = "batching_Library::"; if (turbo_mode_on) { std::cout << "Turbo Mode enable" << std::endl; profile_name.append("turbo_mode_profile"); // If turbo_mode, we do not want to wait to send samples. send_period.sec(0); } else { std::cout << "Manual batching enable" << std::endl; profile_name.append("batch_profile"); } // To customize entities QoS use the file USER_QOS_PROFILES.xml DomainParticipant participant( domain_id, QosProvider::Default().participant_qos(profile_name)); Topic<batch_data> topic(participant, "Example batch_data"); Publisher publisher( participant, QosProvider::Default().publisher_qos(profile_name)); DataWriter<batch_data> writer( publisher, topic, QosProvider::Default().datawriter_qos(profile_name)); // Create data sample for writing. batch_data sample; // For a data type that has a key, if the same instance is going to be // written multiple times, initialize the key here and register the keyed // instance prior to writing. InstanceHandle instance_handle = InstanceHandle::nil(); // instance_handle = writer.register_instance(sample); for (int count = 0; count < sample_count || sample_count == 0; count++) { // Modify the data to be written here sample.x(count); std::cout << "Writing batch_data, count " << count << std::endl; writer.write(sample); rti::util::sleep(send_period); } // writer.unregister_instance(sample); } int main(int argc, char *argv[]) { int domain_id = 0; int sample_count = 0; // infinite loop bool turbo_mode_on = false; if (argc >= 2) { domain_id = atoi(argv[1]); } if (argc >= 3) { turbo_mode_on = (argv[2][0] == '1'); } if (argc >= 4) { sample_count = atoi(argv[3]); } // To turn on additional logging, include <rti/config/Logger.hpp> and // uncomment the following line: // rti::config::Logger::instance().verbosity(rti::config::Verbosity::STATUS_ALL); try { publisher_main(domain_id, sample_count, turbo_mode_on); } catch (const std::exception &ex) { // This will catch DDS exceptions std::cerr << "Exception in publisher_main(): " << ex.what() << std::endl; return -1; } // RTI Connext provides a finalize_participant_factory() method // if you want to release memory used by the participant factory singleton. // Uncomment the following line to release the singleton: // dds::domain::DomainParticipant::finalize_participant_factory(); return 0; }
cxx
rticonnextdds-examples
data/projects/rticonnextdds-examples/connext_dds/batching/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; bool turbo_mode; ApplicationArguments( ParseReturn parse_result_param, unsigned int domain_id_param, unsigned int sample_count_param, rti::config::Verbosity verbosity_param, bool turbo_mode_param) : parse_result(parse_result_param), domain_id(domain_id_param), sample_count(sample_count_param), verbosity(verbosity_param), turbo_mode(turbo_mode_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)(); bool turbo_mode = false; 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 if (strcmp(argv[arg_processing], "--turbo") == 0) { turbo_mode = true; arg_processing += 2; } 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\n" " --turbo Activates turbo mode.\n" " Default: desactivated" << std::endl; } return ApplicationArguments( parse_result, domain_id, sample_count, verbosity, turbo_mode); } } // namespace application #endif // APPLICATION_HPP
hpp
rticonnextdds-examples
data/projects/rticonnextdds-examples/connext_dds/batching/c++11/batch_data_subscriber.cxx
/******************************************************************************* (c) 2005-2015 Copyright, Real-Time Innovations, Inc. All rights reserved. RTI grants Licensee a license to use, modify, compile, and create derivative works of the Software. Licensee has the right to distribute object form only for use with RTI products. The Software is provided "as is", with no warranty of any type, including any warranty for fitness for any purpose. RTI is under no obligation to maintain or support the Software. RTI shall not be liable for any incidental or consequential damages arising out of the use or inability to use the software. ******************************************************************************/ #include <string> #include <dds/sub/ddssub.hpp> #include <dds/core/ddscore.hpp> #include <rti/config/Logger.hpp> // for logging #include "application.hpp" #include "batch_data.hpp" int process_data(dds::sub::DataReader<batch_data> reader) { // Take all samples int count = 0; dds::sub::LoanedSamples<batch_data> 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, bool turbo_mode_on) { // We pick the profile name if the turbo_mode is selected or not. // If turbo_mode is not selected, the batching profile will be used. std::string profile_name = "batching_Library::"; if (turbo_mode_on) { std::cout << "Turbo Mode enable" << std::endl; profile_name.append("turbo_mode_profile"); } else { std::cout << "Manual batching enable" << std::endl; profile_name.append("batch_profile"); } // To customize entities QoS use the file USER_QOS_PROFILES.xml dds::domain::DomainParticipant participant( domain_id, dds::core::QosProvider::Default().participant_qos(profile_name)); dds::topic::Topic<batch_data> topic(participant, "Example batch_data"); dds::sub::Subscriber subscriber( participant, dds::core::QosProvider::Default().subscriber_qos(profile_name)); dds::sub::DataReader<batch_data> reader( subscriber, topic, dds::core::QosProvider::Default().datareader_qos(profile_name)); // 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 << "batch_data subscriber sleeping for 4 sec...\n"; // Wait for data and report if it does not arrive in 1 second waitset.dispatch(dds::core::Duration(4)); } } int main(int argc, char *argv[]) { using namespace application; // Parse arguments and handle control-C auto arguments = parse_arguments(argc, argv); if (arguments.parse_result == ParseReturn::exit) { return EXIT_SUCCESS; } else if (arguments.parse_result == ParseReturn::failure) { return EXIT_FAILURE; } setup_signal_handlers(); // Sets Connext verbosity to help debugging rti::config::Logger::instance().verbosity(arguments.verbosity); try { run_subscriber_application( arguments.domain_id, arguments.sample_count, arguments.turbo_mode); } 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/batching/c++11/batch_data_publisher.cxx
/******************************************************************************* (c) 2005-2015 Copyright, Real-Time Innovations, Inc. All rights reserved. RTI grants Licensee a license to use, modify, compile, and create derivative works of the Software. Licensee has the right to distribute object form only for use with RTI products. The Software is provided "as is", with no warranty of any type, including any warranty for fitness for any purpose. RTI is under no obligation to maintain or support the Software. RTI shall not be liable for any incidental or consequential damages arising out of the use or inability to use the software. ******************************************************************************/ #include <string> #include <dds/pub/ddspub.hpp> #include <rti/util/util.hpp> // for sleep() #include <rti/config/Logger.hpp> // for logging #include "application.hpp" #include "batch_data.hpp" void run_publisher_application( unsigned int domain_id, unsigned int sample_count, bool turbo_mode_on) { // Seconds to wait between samples published. dds::core::Duration send_period(1); // We pick the profile name if the turbo_mode is selected or not. // If turbo_mode is not selected, the batching profile will be used. std::string profile_name = "batching_Library::"; if (turbo_mode_on) { std::cout << "Turbo Mode enable" << std::endl; profile_name.append("turbo_mode_profile"); // If turbo_mode, we do not want to wait to send samples. send_period.sec(0); } else { std::cout << "Manual batching enable" << std::endl; profile_name.append("batch_profile"); } // To customize entities QoS use the file USER_QOS_PROFILES.xml dds::domain::DomainParticipant participant( domain_id, dds::core::QosProvider::Default().participant_qos(profile_name)); dds::topic::Topic<batch_data> topic(participant, "Example batch_data"); dds::pub::Publisher publisher( participant, dds::core::QosProvider::Default().publisher_qos(profile_name)); dds::pub::DataWriter<batch_data> writer( publisher, topic, dds::core::QosProvider::Default().datawriter_qos(profile_name)); // Create data sample for writing. batch_data sample; // For a data type that has a key, if the same instance is going to be // written multiple times, initialize the key here and register the keyed // instance prior to writing. dds::core::InstanceHandle instance_handle = dds::core::InstanceHandle::nil(); // instance_handle = writer.register_instance(sample); for (unsigned int samples_written = 0; !application::shutdown_requested && samples_written < sample_count; samples_written++) { // Modify the data to be written here sample.x(samples_written); std::cout << "Writing batch_data, count " << samples_written << std::endl; writer.write(sample); rti::util::sleep(send_period); } // writer.unregister_instance(sample); } 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, arguments.turbo_mode); } 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_group/c++/ordered_group_publisher.cxx
/******************************************************************************* (c) 2005-2014 Copyright, Real-Time Innovations, Inc. All rights reserved. RTI grants Licensee a license to use, modify, compile, and create derivative works of the Software. Licensee has the right to distribute object form only for use with RTI products. The Software is provided "as is", with no warranty of any type, including any warranty for fitness for any purpose. RTI is under no obligation to maintain or support the Software. RTI shall not be liable for any incidental or consequential damages arising out of the use or inability to use the software. ******************************************************************************/ /* ordered_group_publisher.cxx A publication of data of type ordered_group This file is derived from code automatically generated by the rtiddsgen command: rtiddsgen -language C++ -example <arch> ordered_group.idl Example publication of type ordered_group automatically generated by 'rtiddsgen'. To test them follow these steps: (1) Compile this file and the example subscription. (2) Start the subscription with the command objs/<arch>/ordered_group_subscriber <domain_id> <sample_count> (3) Start the publication with the command objs/<arch>/ordered_group_publisher <domain_id> <sample_count> (4) [Optional] Specify the list of discovery initial peers and multicast receive addresses via an environment variable or a file (in the current working directory) called NDDS_DISCOVERY_PEERS. You can run any number of publishers and subscribers programs, and can add and remove them dynamically from the domain. Example: To run the example application on domain <domain_id>: On Unix: objs/<arch>/ordered_group_publisher <domain_id> o objs/<arch>/ordered_group_subscriber <domain_id> On Windows: objs\<arch>\ordered_group_publisher <domain_id> objs\<arch>\ordered_group_subscriber <domain_id> modification history ------------ ------- */ #include <stdio.h> #include <stdlib.h> #ifdef RTI_VX653 #include <vThreadsData.h> #endif #include "ndds/ndds_cpp.h" #include "ordered_group.h" #include "ordered_groupSupport.h" /* Delete all entities */ static int publisher_shutdown(DDSDomainParticipant *participant) { DDS_ReturnCode_t retcode; int status = 0; if (participant != NULL) { retcode = participant->delete_contained_entities(); if (retcode != DDS_RETCODE_OK) { printf("delete_contained_entities error %d\n", retcode); status = -1; } retcode = DDSTheParticipantFactory->delete_participant(participant); if (retcode != DDS_RETCODE_OK) { printf("delete_participant error %d\n", retcode); status = -1; } } /* RTI Connext provides finalize_instance() method on domain participant factory for people who want to release memory used by the participant factory. Uncomment the following block of code for clean destruction of the singleton. */ /* retcode = DDSDomainParticipantFactory::finalize_instance(); if (retcode != DDS_RETCODE_OK) { printf("finalize_instance error %d\n", retcode); status = -1; } */ return status; } extern "C" int publisher_main(int domainId, int sample_count) { DDSDomainParticipant *participant = NULL; DDSPublisher *publisher = NULL; /* Declaration of Topics */ DDSTopic *topic1 = NULL; DDSTopic *topic2 = NULL; DDSTopic *topic3 = NULL; /* Declaration of DataWriters */ DDSDataWriter *writer1 = NULL; DDSDataWriter *writer2 = NULL; DDSDataWriter *writer3 = NULL; ordered_groupDataWriter *ordered_group_writer1 = NULL; ordered_groupDataWriter *ordered_group_writer2 = NULL; ordered_groupDataWriter *ordered_group_writer3 = NULL; /* Declaration of instances */ ordered_group *instance1 = NULL; ordered_group *instance2 = NULL; ordered_group *instance3 = NULL; DDS_ReturnCode_t retcode; DDS_InstanceHandle_t instance_handle = DDS_HANDLE_NIL; const char *type_name = NULL; int count = 0; DDS_Duration_t send_period = { 1, 0 }; /* To customize participant QoS, use the configuration file USER_QOS_PROFILES.xml */ participant = DDSTheParticipantFactory->create_participant( domainId, DDS_PARTICIPANT_QOS_DEFAULT, NULL /* listener */, DDS_STATUS_MASK_NONE); if (participant == NULL) { printf("create_participant error\n"); publisher_shutdown(participant); return -1; } /* To customize publisher QoS, use the configuration file USER_QOS_PROFILES.xml */ publisher = participant->create_publisher( DDS_PUBLISHER_QOS_DEFAULT, NULL /* listener */, DDS_STATUS_MASK_NONE); if (publisher == NULL) { printf("create_publisher error\n"); publisher_shutdown(participant); return -1; } /* Register DATA TYPES. In this example, only one data type */ /* Register type before creating topic */ type_name = ordered_groupTypeSupport::get_type_name(); retcode = ordered_groupTypeSupport::register_type(participant, type_name); if (retcode != DDS_RETCODE_OK) { printf("register_type error %d\n", retcode); publisher_shutdown(participant); return -1; } /* TOPICS */ /* To customize topic QoS, use the configuration file USER_QOS_PROFILES.xml */ topic1 = participant->create_topic( "Topic1", type_name, DDS_TOPIC_QOS_DEFAULT, NULL /* listener */, DDS_STATUS_MASK_NONE); if (topic1 == NULL) { printf("create_topic error\n"); publisher_shutdown(participant); return -1; } topic2 = participant->create_topic( "Topic2", type_name, DDS_TOPIC_QOS_DEFAULT, NULL /* listener */, DDS_STATUS_MASK_NONE); if (topic2 == NULL) { printf("create_topic error\n"); publisher_shutdown(participant); return -1; } topic3 = participant->create_topic( "Topic3", type_name, DDS_TOPIC_QOS_DEFAULT, NULL /* listener */, DDS_STATUS_MASK_NONE); if (topic3 == NULL) { printf("create_topic error\n"); publisher_shutdown(participant); return -1; } /* DATAWRITERS */ /* To customize data writer QoS, use the configuration file USER_QOS_PROFILES.xml */ writer1 = publisher->create_datawriter( topic1, DDS_DATAWRITER_QOS_DEFAULT, NULL /* listener */, DDS_STATUS_MASK_NONE); if (writer1 == NULL) { printf("create_datawriter error\n"); publisher_shutdown(participant); return -1; } ordered_group_writer1 = ordered_groupDataWriter::narrow(writer1); if (ordered_group_writer1 == NULL) { printf("DataWriter narrow error\n"); publisher_shutdown(participant); return -1; } writer2 = publisher->create_datawriter( topic2, DDS_DATAWRITER_QOS_DEFAULT, NULL /* listener */, DDS_STATUS_MASK_NONE); if (writer2 == NULL) { printf("create_datawriter error\n"); publisher_shutdown(participant); return -1; } ordered_group_writer2 = ordered_groupDataWriter::narrow(writer2); if (ordered_group_writer2 == NULL) { printf("DataWriter narrow error\n"); publisher_shutdown(participant); return -1; } writer3 = publisher->create_datawriter( topic3, DDS_DATAWRITER_QOS_DEFAULT, NULL /* listener */, DDS_STATUS_MASK_NONE); if (writer3 == NULL) { printf("create_datawriter error\n"); publisher_shutdown(participant); return -1; } ordered_group_writer3 = ordered_groupDataWriter::narrow(writer3); if (ordered_group_writer3 == NULL) { printf("DataWriter narrow error\n"); publisher_shutdown(participant); return -1; } /* INSTANCES */ /* Create data sample for writing */ instance1 = ordered_groupTypeSupport::create_data(); if (instance1 == NULL) { printf("ordered_groupTypeSupport::create_data error\n"); publisher_shutdown(participant); return -1; } instance2 = ordered_groupTypeSupport::create_data(); if (instance2 == NULL) { printf("ordered_groupTypeSupport::create_data error\n"); publisher_shutdown(participant); return -1; } instance3 = ordered_groupTypeSupport::create_data(); if (instance3 == NULL) { printf("ordered_groupTypeSupport::create_data error\n"); publisher_shutdown(participant); return -1; } /* For a data type that has a key, if the same instance is going to be written multiple times, initialize the key here and register the keyed instance prior to writing */ /* instance_handle = ordered_group_writer->register_instance(*instance); */ /* Main loop */ for (count = 0; (sample_count == 0) || (count < sample_count); ++count) { printf("Writing ordered_group, count %d\n", count); /* Modify the data to be sent and Write data */ instance1->message = (char *) "First sample, Topic 1 sent by DataWriter number 1"; retcode = ordered_group_writer1->write(*instance1, instance_handle); if (retcode != DDS_RETCODE_OK) { printf("write error %d\n", retcode); } instance1->message = (char *) "Second sample, Topic 1 sent by DataWriter number 1"; retcode = ordered_group_writer1->write(*instance1, instance_handle); if (retcode != DDS_RETCODE_OK) { printf("write error %d\n", retcode); } instance2->message = (char *) "First sample, Topic 2 sent by DataWriter number 2"; retcode = ordered_group_writer2->write(*instance2, instance_handle); if (retcode != DDS_RETCODE_OK) { printf("write error %d\n", retcode); } instance2->message = (char *) "Second sample, Topic 2 sent by DataWriter number 2"; retcode = ordered_group_writer2->write(*instance2, instance_handle); if (retcode != DDS_RETCODE_OK) { printf("write error %d\n", retcode); } instance3->message = (char *) "First sample, Topic 3 sent by DataWriter number 3"; retcode = ordered_group_writer3->write(*instance3, instance_handle); if (retcode != DDS_RETCODE_OK) { printf("write error %d\n", retcode); } instance3->message = (char *) "Second sample, Topic 3 sent by DataWriter number 3"; retcode = ordered_group_writer3->write(*instance3, instance_handle); if (retcode != DDS_RETCODE_OK) { printf("write error %d\n", retcode); } NDDSUtility::sleep(send_period); } /* retcode = ordered_group_writer->unregister_instance( *instance, instance_handle); if (retcode != DDS_RETCODE_OK) { printf("unregister instance error %d\n", retcode); } */ /* Delete data sample */ retcode = ordered_groupTypeSupport::delete_data(instance1); if (retcode != DDS_RETCODE_OK) { printf("ordered_groupTypeSupport::delete_data error %d\n", retcode); } /* Delete data sample */ retcode = ordered_groupTypeSupport::delete_data(instance2); if (retcode != DDS_RETCODE_OK) { printf("ordered_groupTypeSupport::delete_data error %d\n", retcode); } /* Delete data sample */ retcode = ordered_groupTypeSupport::delete_data(instance3); if (retcode != DDS_RETCODE_OK) { printf("ordered_groupTypeSupport::delete_data error %d\n", retcode); } /* Delete all entities */ return publisher_shutdown(participant); } #if defined(RTI_WINCE) int wmain(int argc, wchar_t **argv) { int domainId = 0; int sample_count = 0; /* infinite loop */ if (argc >= 2) { domainId = _wtoi(argv[1]); } if (argc >= 3) { sample_count = _wtoi(argv[2]); } /* Uncomment this to turn on additional logging NDDSConfigLogger::get_instance()-> set_verbosity_by_category(NDDS_CONFIG_LOG_CATEGORY_API, NDDS_CONFIG_LOG_VERBOSITY_STATUS_ALL); */ return publisher_main(domainId, sample_count); } #elif !(defined(RTI_VXWORKS) && !defined(__RTP__)) && !defined(RTI_PSOS) int main(int argc, char *argv[]) { int domainId = 0; int sample_count = 0; /* infinite loop */ if (argc >= 2) { domainId = atoi(argv[1]); } if (argc >= 3) { sample_count = atoi(argv[2]); } /* Uncomment this to turn on additional logging NDDSConfigLogger::get_instance()-> set_verbosity_by_category(NDDS_CONFIG_LOG_CATEGORY_API, NDDS_CONFIG_LOG_VERBOSITY_STATUS_ALL); */ return publisher_main(domainId, sample_count); } #endif #ifdef RTI_VX653 const unsigned char *__ctype = *(__ctypePtrGet()); extern "C" void usrAppInit() { #ifdef USER_APPL_INIT USER_APPL_INIT; /* for backwards compatibility */ #endif /* add application specific code here */ taskSpawn( "pub", RTI_OSAPI_THREAD_PRIORITY_NORMAL, 0x8, 0x150000, (FUNCPTR) publisher_main, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0); } #endif
cxx
rticonnextdds-examples
data/projects/rticonnextdds-examples/connext_dds/ordered_presentation_group/c++/ordered_group_subscriber.cxx
/******************************************************************************* (c) 2005-2014 Copyright, Real-Time Innovations, Inc. All rights reserved. RTI grants Licensee a license to use, modify, compile, and create derivative works of the Software. Licensee has the right to distribute object form only for use with RTI products. The Software is provided "as is", with no warranty of any type, including any warranty for fitness for any purpose. RTI is under no obligation to maintain or support the Software. RTI shall not be liable for any incidental or consequential damages arising out of the use or inability to use the software. ******************************************************************************/ /* ordered_group_subscriber.cxx A subscription example This file is derived from code automatically generated by the rtiddsgen command: rtiddsgen -language C++ -example <arch> ordered_group.idl Example subscription of type ordered_group automatically generated by 'rtiddsgen'. To test them follow these steps: (1) Compile this file and the example publication. (2) Start the subscription with the command objs/<arch>/ordered_group_subscriber <domain_id> <sample_count> (3) Start the publication with the command objs/<arch>/ordered_group_publisher <domain_id> <sample_count> (4) [Optional] Specify the list of discovery initial peers and multicast receive addresses via an environment variable or a file (in the current working directory) called NDDS_DISCOVERY_PEERS. You can run any number of publishers and subscribers programs, and can add and remove them dynamically from the domain. Example: To run the example application on domain <domain_id>: On Unix: objs/<arch>/ordered_group_publisher <domain_id> objs/<arch>/ordered_group_subscriber <domain_id> On Windows: objs\<arch>\ordered_group_publisher <domain_id> objs\<arch>\ordered_group_subscriber <domain_id> modification history ------------ ------- */ #include <stdio.h> #include <stdlib.h> #ifdef RTI_VX653 #include <vThreadsData.h> #endif #include "ndds/ndds_cpp.h" #include "ordered_group.h" #include "ordered_groupSupport.h" //////////////////////////////////////////////////////////////////////// class ordered_groupSubscriberListener : public DDSSubscriberListener { public: virtual void on_data_on_readers(DDSSubscriber *subscriber); }; void ordered_groupSubscriberListener::on_data_on_readers( DDSSubscriber *subscriber) { DDSDataReaderSeq MyDataReaders; DDS_ReturnCode_t retcode; int i; /* IMPORTANT for GROUP access scope: Invoking begin_access() */ subscriber->begin_access(); /* Obtain DataReaders. We obtain a sequence of DataReaders that specifies the order in which each sample should be read */ retcode = subscriber->get_datareaders( MyDataReaders, DDS_ANY_SAMPLE_STATE, DDS_ANY_VIEW_STATE, DDS_ANY_INSTANCE_STATE); if (retcode != DDS_RETCODE_OK) { printf("ERROR error %d\n", retcode); /* IMPORTANT. Remember to invoke end_access() before a return call. Also reset DataReaders sequence */ MyDataReaders.ensure_length(0, 0); subscriber->end_access(); return; } /* Read the samples received, following the DataReaders sequence */ for (i = 0; i < MyDataReaders.length(); i++) { ordered_groupDataReader *ordered_group_reader = NULL; ordered_group data; DDS_SampleInfo info; ordered_group_initialize(&data); ordered_group_reader = ordered_groupDataReader::narrow(MyDataReaders.get_at(i)); if (ordered_group_reader == NULL) { printf("DataReader narrow error\n"); /* IMPORTANT. Remember to invoke end_access() before a return call. Also reset DataReaders sequence */ MyDataReaders.ensure_length(0, 0); subscriber->end_access(); return; } /* IMPORTANT. Use take_next_sample(). We need to take only * one sample each time, as we want to follow the sequence of * DataReaders. This way the samples will be returned in the * order in which they were modified */ retcode = ordered_group_reader->take_next_sample(data, info); /* In case there is no data in current DataReader, check next in the sequence */ if (retcode == DDS_RETCODE_NO_DATA) { continue; } else if (retcode != DDS_RETCODE_OK) { printf("take error %d\n", retcode); continue; } /* Print data sample */ if (info.valid_data) { ordered_groupTypeSupport::print_data(&data); } } /* Reset DataReaders sequence */ MyDataReaders.ensure_length(0, 0); /* IMPORTANT for GROUP access scope: Invoking end_access() */ subscriber->end_access(); } ///////////////////////////////////////////////////////////////////////// /* Delete all entities */ static int subscriber_shutdown(DDSDomainParticipant *participant) { DDS_ReturnCode_t retcode; int status = 0; if (participant != NULL) { retcode = participant->delete_contained_entities(); if (retcode != DDS_RETCODE_OK) { printf("delete_contained_entities error %d\n", retcode); status = -1; } retcode = DDSTheParticipantFactory->delete_participant(participant); if (retcode != DDS_RETCODE_OK) { printf("delete_participant error %d\n", retcode); status = -1; } } /* RTI Connext provides the finalize_instance() method on domain participant factory for people who want to release memory used by the participant factory. Uncomment the following block of code for clean destruction of the singleton. */ /* retcode = DDSDomainParticipantFactory::finalize_instance(); if (retcode != DDS_RETCODE_OK) { printf("finalize_instance error %d\n", retcode); status = -1; } */ return status; } extern "C" int subscriber_main(int domainId, int sample_count) { DDSDomainParticipant *participant = NULL; DDSSubscriber *subscriber = NULL; DDSTopic *topic1 = NULL; DDSTopic *topic2 = NULL; DDSTopic *topic3 = NULL; ordered_groupSubscriberListener *subscriber_listener = NULL; DDSDataReader *reader1 = NULL; DDSDataReader *reader2 = NULL; DDSDataReader *reader3 = NULL; DDS_ReturnCode_t retcode; const char *type_name = NULL; int count = 0; DDS_Duration_t receive_period = { 4, 0 }; int status = 0; /* To customize the participant QoS, use the configuration file USER_QOS_PROFILES.xml */ participant = DDSTheParticipantFactory->create_participant( domainId, DDS_PARTICIPANT_QOS_DEFAULT, NULL /* listener */, DDS_STATUS_MASK_NONE); if (participant == NULL) { printf("create_participant error\n"); subscriber_shutdown(participant); return -1; } /* Create Subscriber listener and establish on_data_on_readers callback */ subscriber_listener = new ordered_groupSubscriberListener(); /* To customize the subscriber QoS, use the configuration file USER_QOS_PROFILES.xml */ subscriber = participant->create_subscriber( DDS_SUBSCRIBER_QOS_DEFAULT, subscriber_listener, DDS_DATA_ON_READERS_STATUS); if (subscriber == NULL) { printf("create_subscriber error\n"); subscriber_shutdown(participant); delete subscriber_listener; return -1; } /* Register the type before creating the topic */ type_name = ordered_groupTypeSupport::get_type_name(); retcode = ordered_groupTypeSupport::register_type(participant, type_name); if (retcode != DDS_RETCODE_OK) { printf("register_type error %d\n", retcode); subscriber_shutdown(participant); return -1; } /* TOPICS */ /* To customize the topic QoS, use the configuration file USER_QOS_PROFILES.xml */ topic1 = participant->create_topic( "Topic1", type_name, DDS_TOPIC_QOS_DEFAULT, NULL /* listener */, DDS_STATUS_MASK_NONE); if (topic1 == NULL) { printf("create_topic error\n"); subscriber_shutdown(participant); return -1; } topic2 = participant->create_topic( "Topic2", type_name, DDS_TOPIC_QOS_DEFAULT, NULL /* listener */, DDS_STATUS_MASK_NONE); if (topic2 == NULL) { printf("create_topic error\n"); subscriber_shutdown(participant); return -1; } topic3 = participant->create_topic( "Topic3", type_name, DDS_TOPIC_QOS_DEFAULT, NULL /* listener */, DDS_STATUS_MASK_NONE); if (topic3 == NULL) { printf("create_topic error\n"); subscriber_shutdown(participant); return -1; } /* DATAREADERS */ /* To customize the data reader QoS, use the configuration file USER_QOS_PROFILES.xml */ reader1 = subscriber->create_datareader( topic1, DDS_DATAREADER_QOS_DEFAULT, NULL, DDS_STATUS_MASK_NONE); if (reader1 == NULL) { printf("create_datareader error\n"); subscriber_shutdown(participant); return -1; } reader2 = subscriber->create_datareader( topic2, DDS_DATAREADER_QOS_DEFAULT, NULL, DDS_STATUS_MASK_NONE); if (reader2 == NULL) { printf("create_datareader error\n"); subscriber_shutdown(participant); return -1; } reader3 = subscriber->create_datareader( topic3, DDS_DATAREADER_QOS_DEFAULT, NULL, DDS_STATUS_MASK_NONE); if (reader3 == NULL) { printf("create_datareader error\n"); subscriber_shutdown(participant); return -1; } /* Main loop */ for (count = 0; (sample_count == 0) || (count < sample_count); ++count) { printf("ordered_group subscriber sleeping for %d sec...\n", receive_period.sec); NDDSUtility::sleep(receive_period); } /* Delete all entities */ status = subscriber_shutdown(participant); delete subscriber_listener; return status; } #if defined(RTI_WINCE) int wmain(int argc, wchar_t **argv) { int domainId = 0; int sample_count = 0; /* infinite loop */ if (argc >= 2) { domainId = _wtoi(argv[1]); } if (argc >= 3) { sample_count = _wtoi(argv[2]); } /* Uncomment this to turn on additional logging NDDSConfigLogger::get_instance()-> set_verbosity_by_category(NDDS_CONFIG_LOG_CATEGORY_API, NDDS_CONFIG_LOG_VERBOSITY_STATUS_ALL); */ return subscriber_main(domainId, sample_count); } #elif !(defined(RTI_VXWORKS) && !defined(__RTP__)) && !defined(RTI_PSOS) int main(int argc, char *argv[]) { int domainId = 0; int sample_count = 0; /* infinite loop */ if (argc >= 2) { domainId = atoi(argv[1]); } if (argc >= 3) { sample_count = atoi(argv[2]); } /* Uncomment this to turn on additional logging NDDSConfigLogger::get_instance()-> set_verbosity_by_category(NDDS_CONFIG_LOG_CATEGORY_API, NDDS_CONFIG_LOG_VERBOSITY_STATUS_ALL); */ return subscriber_main(domainId, sample_count); } #endif #ifdef RTI_VX653 const unsigned char *__ctype = *(__ctypePtrGet()); extern "C" void usrAppInit() { #ifdef USER_APPL_INIT USER_APPL_INIT; /* for backwards compatibility */ #endif /* add application specific code here */ taskSpawn( "sub", RTI_OSAPI_THREAD_PRIORITY_NORMAL, 0x8, 0x150000, (FUNCPTR) subscriber_main, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0); } #endif
cxx
rticonnextdds-examples
data/projects/rticonnextdds-examples/connext_dds/ordered_presentation_group/c++98/ordered_group_publisher.cxx
/******************************************************************************* (c) 2005-2014 Copyright, Real-Time Innovations, Inc. All rights reserved. RTI grants Licensee a license to use, modify, compile, and create derivative works of the Software. Licensee has the right to distribute object form only for use with RTI products. The Software is provided "as is", with no warranty of any type, including any warranty for fitness for any purpose. RTI is under no obligation to maintain or support the Software. RTI shall not be liable for any incidental or consequential damages arising out of the use or inability to use the software. ******************************************************************************/ #include <iostream> #include <stdio.h> #include <stdlib.h> #include "ndds/ndds_cpp.h" #include "ordered_group.h" #include "ordered_groupSupport.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( 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 = ordered_groupTypeSupport::get_type_name(); DDS_ReturnCode_t retcode = ordered_groupTypeSupport::register_type(participant, type_name); if (retcode != DDS_RETCODE_OK) { return shutdown_participant( participant, "register_type error", EXIT_FAILURE); } /* TOPICS */ DDSTopic *topic1 = participant->create_topic( "Topic1", type_name, DDS_TOPIC_QOS_DEFAULT, NULL /* listener */, DDS_STATUS_MASK_NONE); if (topic1 == NULL) { return shutdown_participant( participant, "create_topic error", EXIT_FAILURE); } DDSTopic *topic2 = participant->create_topic( "Topic2", type_name, DDS_TOPIC_QOS_DEFAULT, NULL /* listener */, DDS_STATUS_MASK_NONE); if (topic2 == NULL) { return shutdown_participant( participant, "create_topic error", EXIT_FAILURE); } DDSTopic *topic3 = participant->create_topic( "Topic3", type_name, DDS_TOPIC_QOS_DEFAULT, NULL /* listener */, DDS_STATUS_MASK_NONE); if (topic3 == NULL) { return shutdown_participant( participant, "create_topic error", EXIT_FAILURE); } /* DATAWRITERS */ DDSDataWriter *untyped_writer1 = publisher->create_datawriter( topic1, DDS_DATAWRITER_QOS_DEFAULT, NULL /* listener */, DDS_STATUS_MASK_NONE); if (untyped_writer1 == NULL) { return shutdown_participant( participant, "create_datawriter error", EXIT_FAILURE); } ordered_groupDataWriter *typed_writer1 = ordered_groupDataWriter::narrow(untyped_writer1); if (typed_writer1 == NULL) { return shutdown_participant( participant, "DataWriter narrow error", EXIT_FAILURE); } DDSDataWriter *untyped_writer2 = publisher->create_datawriter( topic2, DDS_DATAWRITER_QOS_DEFAULT, NULL /* listener */, DDS_STATUS_MASK_NONE); if (untyped_writer2 == NULL) { return shutdown_participant( participant, "create_datawriter error", EXIT_FAILURE); } ordered_groupDataWriter *typed_writer2 = ordered_groupDataWriter::narrow(untyped_writer2); if (typed_writer2 == NULL) { return shutdown_participant( participant, "DataWriter narrow error", EXIT_FAILURE); } DDSDataWriter *untyped_writer3 = publisher->create_datawriter( topic3, DDS_DATAWRITER_QOS_DEFAULT, NULL /* listener */, DDS_STATUS_MASK_NONE); if (untyped_writer3 == NULL) { return shutdown_participant( participant, "create_datawriter error", EXIT_FAILURE); } ordered_groupDataWriter *typed_writer3 = ordered_groupDataWriter::narrow(untyped_writer3); if (typed_writer3 == NULL) { return shutdown_participant( participant, "DataWriter narrow error", EXIT_FAILURE); } /* INSTANCES */ ordered_group *instance1 = ordered_groupTypeSupport::create_data(); if (instance1 == NULL) { return shutdown_participant( participant, "ordered_groupTypeSupport::create_data error", EXIT_FAILURE); } ordered_group *instance2 = ordered_groupTypeSupport::create_data(); if (instance2 == NULL) { return shutdown_participant( participant, "ordered_groupTypeSupport::create_data error", EXIT_FAILURE); } ordered_group *instance3 = ordered_groupTypeSupport::create_data(); if (instance3 == NULL) { return shutdown_participant( participant, "ordered_groupTypeSupport::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 ordered_group, count " << samples_written << std::endl; // Modify the data to be sent and Write data strcpy(instance1->message, "First sample, Topic 1 sent by DataWriter number 1"); retcode = typed_writer1->write(*instance1, DDS_HANDLE_NIL); if (retcode != DDS_RETCODE_OK) { std::cerr << "write error " << retcode << std::endl; } strcpy(instance1->message, "Second sample, Topic 1 sent by DataWriter number 1"); retcode = typed_writer1->write(*instance1, DDS_HANDLE_NIL); if (retcode != DDS_RETCODE_OK) { std::cerr << "write error " << retcode << std::endl; } strcpy(instance2->message, "First sample, Topic 2 sent by DataWriter number 2"); retcode = typed_writer2->write(*instance2, DDS_HANDLE_NIL); if (retcode != DDS_RETCODE_OK) { std::cerr << "write error " << retcode << std::endl; } strcpy(instance2->message, "Second sample, Topic 2 sent by DataWriter number 2"); retcode = typed_writer2->write(*instance2, DDS_HANDLE_NIL); if (retcode != DDS_RETCODE_OK) { std::cerr << "write error " << retcode << std::endl; } strcpy(instance3->message, "First sample, Topic 3 sent by DataWriter number 3"); retcode = typed_writer3->write(*instance3, DDS_HANDLE_NIL); if (retcode != DDS_RETCODE_OK) { std::cerr << "write error " << retcode << std::endl; } strcpy(instance3->message, "Second sample, Topic 3 sent by DataWriter number 3"); retcode = typed_writer3->write(*instance3, DDS_HANDLE_NIL); if (retcode != DDS_RETCODE_OK) { std::cerr << "write error " << retcode << std::endl; } NDDSUtility::sleep(send_period); } // Delete data sample retcode = ordered_groupTypeSupport::delete_data(instance1); if (retcode != DDS_RETCODE_OK) { std::cerr << "ordered_groupTypeSupport::delete_data error " << retcode << std::endl; } // Delete data sample retcode = ordered_groupTypeSupport::delete_data(instance2); if (retcode != DDS_RETCODE_OK) { std::cerr << "ordered_groupTypeSupport::delete_data error " << retcode << std::endl; } // Delete data sample retcode = ordered_groupTypeSupport::delete_data(instance3); if (retcode != DDS_RETCODE_OK) { std::cerr << "ordered_groupTypeSupport::delete_data error " << retcode << std::endl; } // Delete all entities (DataWriter, Topic, Publisher, DomainParticipant) return shutdown_participant(participant, "Shutting down", EXIT_SUCCESS); } // Delete all entities static int shutdown_participant( DDSDomainParticipant *participant, const char *shutdown_message, int status) { DDS_ReturnCode_t retcode; std::cout << shutdown_message << std::endl; if (participant != NULL) { // Cleanup everything created by this Participant retcode = participant->delete_contained_entities(); if (retcode != DDS_RETCODE_OK) { std::cerr << "delete_contained_entities error " << retcode << std::endl; status = EXIT_FAILURE; } retcode = DDSTheParticipantFactory->delete_participant(participant); if (retcode != DDS_RETCODE_OK) { std::cerr << "delete_participant error " << retcode << std::endl; status = EXIT_FAILURE; } } return status; } int main(int argc, char *argv[]) { // Parse arguments and handle control-C ApplicationArguments arguments; parse_arguments(arguments, argc, argv, publisher); if (arguments.parse_result == PARSE_RETURN_EXIT) { return EXIT_SUCCESS; } else if (arguments.parse_result == PARSE_RETURN_FAILURE) { return EXIT_FAILURE; } setup_signal_handlers(); // Sets Connext verbosity to help debugging NDDSConfigLogger::get_instance()->set_verbosity(arguments.verbosity); int status = run_publisher_application( arguments.domain_id, arguments.sample_count); // Releases the memory used by the participant factory. Optional at // application exit DDS_ReturnCode_t retcode = DDSDomainParticipantFactory::finalize_instance(); if (retcode != DDS_RETCODE_OK) { std::cerr << "finalize_instance error " << retcode << std::endl; status = EXIT_FAILURE; } return status; }
cxx
rticonnextdds-examples
data/projects/rticonnextdds-examples/connext_dds/ordered_presentation_group/c++98/ordered_group_subscriber.cxx
/******************************************************************************* (c) 2005-2014 Copyright, Real-Time Innovations, Inc. All rights reserved. RTI grants Licensee a license to use, modify, compile, and create derivative works of the Software. Licensee has the right to distribute object form only for use with RTI products. The Software is provided "as is", with no warranty of any type, including any warranty for fitness for any purpose. RTI is under no obligation to maintain or support the Software. RTI shall not be liable for any incidental or consequential damages arising out of the use or inability to use the software. ******************************************************************************/ #include <iostream> #include <stdio.h> #include <stdlib.h> #include "ordered_group.h" #include "ordered_groupSupport.h" #include "ndds/ndds_cpp.h" #include "application.h" using namespace application; static int shutdown_participant( DDSDomainParticipant *participant, const char *shutdown_message, int status); class ordered_groupSubscriberListener : public DDSSubscriberListener { public: virtual void on_data_on_readers(DDSSubscriber *subscriber); }; void ordered_groupSubscriberListener::on_data_on_readers( DDSSubscriber *subscriber) { DDSDataReaderSeq MyDataReaders; DDS_ReturnCode_t retcode; int i; /* IMPORTANT for GROUP access scope: Invoking begin_access() */ subscriber->begin_access(); /* Obtain DataReaders. We obtain a sequence of DataReaders that specifies the order in which each sample should be read */ retcode = subscriber->get_datareaders( MyDataReaders, DDS_ANY_SAMPLE_STATE, DDS_ANY_VIEW_STATE, DDS_ANY_INSTANCE_STATE); if (retcode != DDS_RETCODE_OK) { std::cerr << "ERROR error " << retcode << std::endl; /* IMPORTANT. Remember to invoke end_access() before a return call. Also reset DataReaders sequence */ MyDataReaders.ensure_length(0, 0); subscriber->end_access(); return; } /* Read the samples received, following the DataReaders sequence */ for (i = 0; i < MyDataReaders.length(); i++) { ordered_groupDataReader *ordered_group_reader = NULL; ordered_group data; DDS_SampleInfo info; ordered_group_initialize(&data); ordered_group_reader = ordered_groupDataReader::narrow(MyDataReaders.get_at(i)); if (ordered_group_reader == NULL) { std::cerr << "DataReader narrow error\n"; /* IMPORTANT. Remember to invoke end_access() before a return call. Also reset DataReaders sequence */ MyDataReaders.ensure_length(0, 0); subscriber->end_access(); return; } /* IMPORTANT. Use take_next_sample(). We need to take only * one sample each time, as we want to follow the sequence of * DataReaders. This way the samples will be returned in the * order in which they were modified */ retcode = ordered_group_reader->take_next_sample(data, info); /* In case there is no data in current DataReader, check next in the sequence */ if (retcode == DDS_RETCODE_NO_DATA) { continue; } else if (retcode != DDS_RETCODE_OK) { std::cerr << "take error %d\n", retcode; continue; } /* Print data sample */ if (info.valid_data) { ordered_groupTypeSupport::print_data(&data); } } /* Reset DataReaders sequence */ MyDataReaders.ensure_length(0, 0); /* IMPORTANT for GROUP access scope: Invoking end_access() */ subscriber->end_access(); } int run_subscriber_application( unsigned int domain_id, unsigned int sample_count) { DDS_Duration_t receive_period = { 1, 0 }; // Start communicating in a domain, usually one participant per application DDSDomainParticipant *participant = DDSTheParticipantFactory->create_participant( domain_id, DDS_PARTICIPANT_QOS_DEFAULT, NULL /* listener */, DDS_STATUS_MASK_NONE); if (participant == NULL) { return shutdown_participant( participant, "create_participant error", EXIT_FAILURE); } ordered_groupSubscriberListener *subscriber_listener = new ordered_groupSubscriberListener(); // A Subscriber allows an application to create one or more DataReaders DDSSubscriber *subscriber = participant->create_subscriber( DDS_SUBSCRIBER_QOS_DEFAULT, subscriber_listener, DDS_DATA_ON_READERS_STATUS); 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 = ordered_groupTypeSupport::get_type_name(); DDS_ReturnCode_t retcode = ordered_groupTypeSupport::register_type(participant, type_name); if (retcode != DDS_RETCODE_OK) { return shutdown_participant( participant, "register_type error", EXIT_FAILURE); } /* TOPICS */ DDSTopic *topic1 = participant->create_topic( "Topic1", type_name, DDS_TOPIC_QOS_DEFAULT, NULL /* listener */, DDS_STATUS_MASK_NONE); if (topic1 == NULL) { return shutdown_participant( participant, "create_topic error", EXIT_FAILURE); } DDSTopic *topic2 = participant->create_topic( "Topic2", type_name, DDS_TOPIC_QOS_DEFAULT, NULL /* listener */, DDS_STATUS_MASK_NONE); if (topic2 == NULL) { return shutdown_participant( participant, "create_topic error", EXIT_FAILURE); } DDSTopic *topic3 = participant->create_topic( "Topic3", type_name, DDS_TOPIC_QOS_DEFAULT, NULL /* listener */, DDS_STATUS_MASK_NONE); if (topic3 == NULL) { return shutdown_participant( participant, "create_topic error", EXIT_FAILURE); } /* DATAREADERS */ DDSDataReader *untyped_reader1 = subscriber->create_datareader( topic1, DDS_DATAREADER_QOS_DEFAULT, NULL, DDS_STATUS_MASK_NONE); if (untyped_reader1 == NULL) { return shutdown_participant( participant, "create_datareader error", EXIT_FAILURE); } DDSDataReader *untyped_reader2 = subscriber->create_datareader( topic2, DDS_DATAREADER_QOS_DEFAULT, NULL, DDS_STATUS_MASK_NONE); if (untyped_reader2 == NULL) { return shutdown_participant( participant, "create_datareader error", EXIT_FAILURE); } DDSDataReader *untyped_reader3 = subscriber->create_datareader( topic3, DDS_DATAREADER_QOS_DEFAULT, NULL, DDS_STATUS_MASK_NONE); if (untyped_reader3 == NULL) { return shutdown_participant( participant, "create_datareader error", EXIT_FAILURE); } // Main loop. Wait for data to arrive, and process when it arrives for (int count = 0; count < sample_count && !shutdown_requested; ++count) { std::cout << "ordered_group subscriber sleeping for " << receive_period.sec << " sec...\n"; NDDSUtility::sleep(receive_period); } // Cleanup return shutdown_participant(participant, "Shutting down", 0); } // Delete all entities static int shutdown_participant( DDSDomainParticipant *participant, const char *shutdown_message, int status) { DDS_ReturnCode_t retcode; std::cout << shutdown_message << std::endl; if (participant != NULL) { // Cleanup everything created by this Participant retcode = participant->delete_contained_entities(); if (retcode != DDS_RETCODE_OK) { std::cerr << "delete_contained_entities error" << retcode << std::endl; status = EXIT_FAILURE; } retcode = DDSTheParticipantFactory->delete_participant(participant); if (retcode != DDS_RETCODE_OK) { std::cerr << "delete_participant error" << retcode << std::endl; status = EXIT_FAILURE; } } return status; } int main(int argc, char *argv[]) { // Parse arguments and handle control-C ApplicationArguments arguments; parse_arguments(arguments, argc, argv, subscriber); if (arguments.parse_result == PARSE_RETURN_EXIT) { return EXIT_SUCCESS; } else if (arguments.parse_result == PARSE_RETURN_FAILURE) { return EXIT_FAILURE; } setup_signal_handlers(); // Sets Connext verbosity to help debugging NDDSConfigLogger::get_instance()->set_verbosity(arguments.verbosity); int status = run_subscriber_application( arguments.domain_id, arguments.sample_count); // Releases the memory used by the participant factory. Optional at // application exit DDS_ReturnCode_t retcode = DDSDomainParticipantFactory::finalize_instance(); if (retcode != DDS_RETCODE_OK) { std::cerr << "finalize_instance error" << retcode << std::endl; status = EXIT_FAILURE; } return status; }
cxx
rticonnextdds-examples
data/projects/rticonnextdds-examples/connext_dds/ordered_presentation_group/c++98/application.h
/* * (c) Copyright, Real-Time Innovations, 2020. All rights reserved. * RTI grants Licensee a license to use, modify, compile, and create derivative * works of the software solely for use with RTI Connext DDS. Licensee may * redistribute copies of the software provided that all such copies are subject * to this license. The software is provided "as is", with no warranty of any * type, including any warranty for fitness for any purpose. RTI is under no * obligation to maintain or support the software. RTI shall not be liable for * any incidental or consequential damages arising out of the use or inability * to use the software. */ #ifndef APPLICATION_H #define APPLICATION_H #include <iostream> #include <csignal> #include <climits> namespace application { // Catch control-C and tell application to shut down bool shutdown_requested = false; inline void stop_handler(int) { shutdown_requested = true; std::cout << "preparing to shut down..." << std::endl; } inline void setup_signal_handlers() { signal(SIGINT, stop_handler); signal(SIGTERM, stop_handler); } enum ParseReturn { PARSE_RETURN_OK, PARSE_RETURN_FAILURE, PARSE_RETURN_EXIT }; enum ApplicationKind { publisher, subscriber }; struct ApplicationArguments { ParseReturn parse_result; unsigned int domain_id; unsigned int sample_count; NDDS_Config_LogVerbosity verbosity; }; inline void set_verbosity(ApplicationArguments &arguments, int verbosity) { switch (verbosity) { case 0: arguments.verbosity = NDDS_CONFIG_LOG_VERBOSITY_SILENT; break; case 1: arguments.verbosity = NDDS_CONFIG_LOG_VERBOSITY_ERROR; break; case 2: arguments.verbosity = NDDS_CONFIG_LOG_VERBOSITY_WARNING; break; case 3: arguments.verbosity = NDDS_CONFIG_LOG_VERBOSITY_STATUS_ALL; break; default: arguments.verbosity = NDDS_CONFIG_LOG_VERBOSITY_ERROR; break; } } // Parses application arguments for example. Returns whether to exit. inline void parse_arguments( ApplicationArguments &arguments, int argc, char *argv[], ApplicationKind current_application) { int arg_processing = 1; bool show_usage = false; arguments.domain_id = 0; arguments.sample_count = INT_MAX; arguments.verbosity = NDDS_CONFIG_LOG_VERBOSITY_ERROR; arguments.parse_result = PARSE_RETURN_OK; while (arg_processing < argc) { if ((argc > arg_processing + 1) && (strcmp(argv[arg_processing], "-d") == 0 || strcmp(argv[arg_processing], "--domain") == 0)) { arguments.domain_id = atoi(argv[arg_processing + 1]); arg_processing += 2; } else if ( (argc > arg_processing + 1) && (strcmp(argv[arg_processing], "-s") == 0 || strcmp(argv[arg_processing], "--sample-count") == 0 || strcmp(argv[arg_processing], "--sleep-periods") == 0)) { arguments.sample_count = atoi(argv[arg_processing + 1]); arg_processing += 2; } else if ( (argc > arg_processing + 1) && (strcmp(argv[arg_processing], "-v") == 0 || strcmp(argv[arg_processing], "--verbosity") == 0)) { set_verbosity(arguments, atoi(argv[arg_processing + 1])); arg_processing += 2; } else if ( strcmp(argv[arg_processing], "-h") == 0 || strcmp(argv[arg_processing], "--help") == 0) { std::cout << "Example application." << std::endl; show_usage = true; arguments.parse_result = PARSE_RETURN_EXIT; break; } else { std::cout << "Bad parameter." << std::endl; show_usage = true; arguments.parse_result = PARSE_RETURN_FAILURE; break; } } if (show_usage) { std::cout << "Usage:\n" " -d, --domain <int> Domain ID this " "application will\n" " subscribe in. \n" " Default: 0\n"; if (current_application == publisher) { std::cout << " -s, --sample-count <int> Number of samples to " "receive before\n" " cleanly shutting " "down. \n" " Default: infinite\n"; } else if (current_application == subscriber) { std::cout << " -s, --sleep-periods <int> Number of sleeps " "before cleanly\n" " shutting down. \n" " Default: infinite\n"; } std::cout << " -v, --verbosity <int> How much debugging output " "to show.\n" " Range: 0-3 \n" " Default: 1" << std::endl; } } } // namespace application #endif // APPLICATION_H
h
rticonnextdds-examples
data/projects/rticonnextdds-examples/connext_dds/ordered_presentation_group/c/ordered_group_publisher.c
/******************************************************************************* (c) 2005-2014 Copyright, Real-Time Innovations, Inc. All rights reserved. RTI grants Licensee a license to use, modify, compile, and create derivative works of the Software. Licensee has the right to distribute object form only for use with RTI products. The Software is provided "as is", with no warranty of any type, including any warranty for fitness for any purpose. RTI is under no obligation to maintain or support the Software. RTI shall not be liable for any incidental or consequential damages arising out of the use or inability to use the software. ******************************************************************************/ /* ordered_group_publisher.c A publication of data of type ordered_group This file is derived from code automatically generated by the rtiddsgen command: rtiddsgen -language C -example <arch> ordered_group.idl Example publication of type ordered_group automatically generated by 'rtiddsgen'. To test them follow these steps: (1) Compile this file and the example subscription. (2) Start the subscription with the command objs/<arch>/ordered_group_subscriber <domain_id> <sample_count> (3) Start the publication with the command objs/<arch>/ordered_group_publisher <domain_id> <sample_count> (4) [Optional] Specify the list of discovery initial peers and multicast receive addresses via an environment variable or a file (in the current working directory) called NDDS_DISCOVERY_PEERS. You can run any number of publishers and subscribers programs, and can add and remove them dynamically from the domain. Example: To run the example application on domain <domain_id>: On Unix: objs/<arch>/ordered_group_publisher <domain_id> objs/<arch>/ordered_group_subscriber <domain_id> On Windows: objs\<arch>\ordered_group_publisher <domain_id> objs\<arch>\ordered_group_subscriber <domain_id> modification history ------------ ------- */ #include "ndds/ndds_c.h" #include "ordered_group.h" #include "ordered_groupSupport.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; /* Declaration of Topics */ DDS_Topic *topic1 = NULL; DDS_Topic *topic2 = NULL; DDS_Topic *topic3 = NULL; /* Declaration of DataWriters */ DDS_DataWriter *writer1 = NULL; DDS_DataWriter *writer2 = NULL; DDS_DataWriter *writer3 = NULL; ordered_groupDataWriter *ordered_group_writer1 = NULL; ordered_groupDataWriter *ordered_group_writer2 = NULL; ordered_groupDataWriter *ordered_group_writer3 = NULL; /* Declaration of instances */ ordered_group *instance1 = NULL; ordered_group *instance2 = NULL; ordered_group *instance3 = NULL; DDS_ReturnCode_t retcode; DDS_InstanceHandle_t instance_handle = DDS_HANDLE_NIL; const char *type_name = NULL; int count = 0; struct DDS_Duration_t send_period = { 1, 0 }; /* To customize participant QoS, use the configuration file USER_QOS_PROFILES.xml */ participant = DDS_DomainParticipantFactory_create_participant( DDS_TheParticipantFactory, domainId, &DDS_PARTICIPANT_QOS_DEFAULT, NULL /* listener */, DDS_STATUS_MASK_NONE); if (participant == NULL) { printf("create_participant error\n"); publisher_shutdown(participant); return -1; } /* To customize publisher QoS, use the configuration file USER_QOS_PROFILES.xml */ publisher = DDS_DomainParticipant_create_publisher( participant, &DDS_PUBLISHER_QOS_DEFAULT, NULL /* listener */, DDS_STATUS_MASK_NONE); if (publisher == NULL) { printf("create_publisher error\n"); publisher_shutdown(participant); return -1; } /* Register DATA TYPES. In this example, only one data type */ /* Register type before creating topic */ type_name = ordered_groupTypeSupport_get_type_name(); retcode = ordered_groupTypeSupport_register_type(participant, type_name); if (retcode != DDS_RETCODE_OK) { printf("register_type error %d\n", retcode); publisher_shutdown(participant); return -1; } /* TOPICS */ /* To customize topic QoS, use the configuration file USER_QOS_PROFILES.xml */ topic1 = DDS_DomainParticipant_create_topic( participant, "Topic1", type_name, &DDS_TOPIC_QOS_DEFAULT, NULL /* listener */, DDS_STATUS_MASK_NONE); if (topic1 == NULL) { printf("create_topic error\n"); publisher_shutdown(participant); return -1; } topic2 = DDS_DomainParticipant_create_topic( participant, "Topic2", type_name, &DDS_TOPIC_QOS_DEFAULT, NULL /* listener */, DDS_STATUS_MASK_NONE); if (topic2 == NULL) { printf("create_topic error\n"); publisher_shutdown(participant); return -1; } topic3 = DDS_DomainParticipant_create_topic( participant, "Topic3", type_name, &DDS_TOPIC_QOS_DEFAULT, NULL /* listener */, DDS_STATUS_MASK_NONE); if (topic3 == NULL) { printf("create_topic error\n"); publisher_shutdown(participant); return -1; } /* DATAWRITERS */ /* To customize data writer QoS, use the configuration file USER_QOS_PROFILES.xml */ writer1 = DDS_Publisher_create_datawriter( publisher, topic1, &DDS_DATAWRITER_QOS_DEFAULT, NULL /* listener */, DDS_STATUS_MASK_NONE); if (writer1 == NULL) { printf("create_datawriter error\n"); publisher_shutdown(participant); return -1; } ordered_group_writer1 = ordered_groupDataWriter_narrow(writer1); if (ordered_group_writer1 == NULL) { printf("DataWriter narrow error\n"); publisher_shutdown(participant); return -1; } writer2 = DDS_Publisher_create_datawriter( publisher, topic2, &DDS_DATAWRITER_QOS_DEFAULT, NULL /* listener */, DDS_STATUS_MASK_NONE); if (writer2 == NULL) { printf("create_datawriter error\n"); publisher_shutdown(participant); return -1; } ordered_group_writer2 = ordered_groupDataWriter_narrow(writer2); if (ordered_group_writer2 == NULL) { printf("DataWriter narrow error\n"); publisher_shutdown(participant); return -1; } writer3 = DDS_Publisher_create_datawriter( publisher, topic3, &DDS_DATAWRITER_QOS_DEFAULT, NULL /* listener */, DDS_STATUS_MASK_NONE); if (writer3 == NULL) { printf("create_datawriter error\n"); publisher_shutdown(participant); return -1; } ordered_group_writer3 = ordered_groupDataWriter_narrow(writer3); if (ordered_group_writer3 == NULL) { printf("DataWriter narrow error\n"); publisher_shutdown(participant); return -1; } /* INSTANCES */ /* Create data sample for writing */ instance1 = ordered_groupTypeSupport_create_data_ex(DDS_BOOLEAN_TRUE); if (instance1 == NULL) { printf("ordered_groupTypeSupport_create_data error\n"); publisher_shutdown(participant); return -1; } instance2 = ordered_groupTypeSupport_create_data_ex(DDS_BOOLEAN_TRUE); if (instance2 == NULL) { printf("ordered_groupTypeSupport_create_data error\n"); publisher_shutdown(participant); return -1; } instance3 = ordered_groupTypeSupport_create_data_ex(DDS_BOOLEAN_TRUE); if (instance3 == NULL) { printf("ordered_groupTypeSupport_create_data error\n"); publisher_shutdown(participant); return -1; } /* For a data type that has a key, if the same instance is going to be written multiple times, initialize the key here and register the keyed instance prior to writing */ /* instance_handle = ordered_groupDataWriter_register_instance( ordered_group_writer, instance); */ /* Main loop */ for (count = 0; (sample_count == 0) || (count < sample_count); ++count) { printf("Writing ordered_group, count %d\n", count); /* Modify the data to be sent and Write data */ instance1->message = "First sample, Topic 1 sent by DataWriter number 1"; retcode = ordered_groupDataWriter_write( ordered_group_writer1, instance1, &instance_handle); if (retcode != DDS_RETCODE_OK) { printf("write error %d\n", retcode); } instance1->message = "Second sample, Topic 1 sent by DataWriter number 1"; retcode = ordered_groupDataWriter_write( ordered_group_writer1, instance1, &instance_handle); if (retcode != DDS_RETCODE_OK) { printf("write error %d\n", retcode); } instance2->message = "First sample, Topic 2 sent by DataWriter number 2"; retcode = ordered_groupDataWriter_write( ordered_group_writer2, instance2, &instance_handle); if (retcode != DDS_RETCODE_OK) { printf("write error %d\n", retcode); } instance2->message = "Second sample, Topic 2 sent by DataWriter number 2"; retcode = ordered_groupDataWriter_write( ordered_group_writer2, instance2, &instance_handle); if (retcode != DDS_RETCODE_OK) { printf("write error %d\n", retcode); } instance3->message = "First sample, Topic 3 sent by DataWriter number 3"; retcode = ordered_groupDataWriter_write( ordered_group_writer3, instance3, &instance_handle); if (retcode != DDS_RETCODE_OK) { printf("write error %d\n", retcode); } instance3->message = "Second sample, Topic 3 sent by DataWriter number 3"; retcode = ordered_groupDataWriter_write( ordered_group_writer3, instance3, &instance_handle); if (retcode != DDS_RETCODE_OK) { printf("write error %d\n", retcode); } NDDS_Utility_sleep(&send_period); } /* retcode = ordered_groupDataWriter_unregister_instance( ordered_group_writer, instance, &instance_handle); if (retcode != DDS_RETCODE_OK) { printf("unregister instance error %d\n", retcode); } */ /* Delete data sample */ retcode = ordered_groupTypeSupport_delete_data_ex( instance1, DDS_BOOLEAN_TRUE); if (retcode != DDS_RETCODE_OK) { printf("ordered_groupTypeSupport_delete_data error %d\n", retcode); } /* Delete data sample */ retcode = ordered_groupTypeSupport_delete_data_ex( instance2, DDS_BOOLEAN_TRUE); if (retcode != DDS_RETCODE_OK) { printf("ordered_groupTypeSupport_delete_data error %d\n", retcode); } /* Delete data sample */ retcode = ordered_groupTypeSupport_delete_data_ex( instance3, DDS_BOOLEAN_TRUE); if (retcode != DDS_RETCODE_OK) { printf("ordered_groupTypeSupport_delete_data error %d\n", retcode); } /* Cleanup and delete delete all entities */ return publisher_shutdown(participant); } #if defined(RTI_WINCE) int wmain(int argc, wchar_t **argv) { int domainId = 0; int sample_count = 0; /* infinite loop */ if (argc >= 2) { domainId = _wtoi(argv[1]); } if (argc >= 3) { sample_count = _wtoi(argv[2]); } /* Uncomment this to turn on additional logging NDDS_Config_Logger_set_verbosity_by_category( NDDS_Config_Logger_get_instance(), NDDS_CONFIG_LOG_CATEGORY_API, NDDS_CONFIG_LOG_VERBOSITY_STATUS_ALL); */ return publisher_main(domainId, sample_count); } #elif !(defined(RTI_VXWORKS) && !defined(__RTP__)) && !defined(RTI_PSOS) int main(int argc, char *argv[]) { int domainId = 0; int sample_count = 0; /* infinite loop */ if (argc >= 2) { domainId = atoi(argv[1]); } if (argc >= 3) { sample_count = atoi(argv[2]); } /* Uncomment this to turn on additional logging NDDS_Config_Logger_set_verbosity_by_category( NDDS_Config_Logger_get_instance(), NDDS_CONFIG_LOG_CATEGORY_API, NDDS_CONFIG_LOG_VERBOSITY_STATUS_ALL); */ return publisher_main(domainId, sample_count); } #endif #ifdef RTI_VX653 const unsigned char *__ctype = NULL; void usrAppInit() { #ifdef USER_APPL_INIT USER_APPL_INIT; /* for backwards compatibility */ #endif /* add application specific code here */ taskSpawn( "pub", RTI_OSAPI_THREAD_PRIORITY_NORMAL, 0x8, 0x150000, (FUNCPTR) publisher_main, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0); } #endif
c
rticonnextdds-examples
data/projects/rticonnextdds-examples/connext_dds/ordered_presentation_group/c/ordered_group_subscriber.c
/******************************************************************************* (c) 2005-2014 Copyright, Real-Time Innovations, Inc. All rights reserved. RTI grants Licensee a license to use, modify, compile, and create derivative works of the Software. Licensee has the right to distribute object form only for use with RTI products. The Software is provided "as is", with no warranty of any type, including any warranty for fitness for any purpose. RTI is under no obligation to maintain or support the Software. RTI shall not be liable for any incidental or consequential damages arising out of the use or inability to use the software. ******************************************************************************/ /* ordered_group_subscriber.c A subscription example This file is derived from code automatically generated by the rtiddsgen command: rtiddsgen -language C -example <arch> ordered_group.idl Example subscription of type ordered_group automatically generated by 'rtiddsgen'. To test them, follow these steps: (1) Compile this file and the example publication. (2) Start the subscription with the command objs/<arch>/ordered_group_subscriber <domain_id> <sample_count> (3) Start the publication with the command objs/<arch>/ordered_group_publisher <domain_id> <sample_count> (4) [Optional] Specify the list of discovery initial peers and multicast receive addresses via an environment variable or a file (in the current working directory) called NDDS_DISCOVERY_PEERS. You can run any number of publishers and subscribers programs, and can add and remove them dynamically from the domain. Example: To run the example application on domain <domain_id>: On UNIX systems: objs/<arch>/ordered_group_publisher <domain_id> objs/<arch>/ordered_group_subscriber <domain_id> On Windows systems: objs\<arch>\ordered_group_publisher <domain_id> objs\<arch>\ordered_group_subscriber <domain_id> modification history ------------ ------- */ #include "ndds/ndds_c.h" #include "ordered_group.h" #include "ordered_groupSupport.h" #include <stdio.h> #include <stdlib.h> void ordered_groupListener_on_data_on_readers( void *listener_data, DDS_Subscriber *subscriber) { struct DDS_DataReaderSeq MyDataReaders; DDS_ReturnCode_t retcode; int i; /* IMPORTANT for GROUP access scope: Invoking * DDS_Subscriber_begin_access() */ DDS_Subscriber_begin_access(subscriber); /* Obtain DataReaders. We obtain a sequence of DataReaders that * specifies the order in which each sample should be read */ retcode = DDS_Subscriber_get_datareaders( subscriber, &MyDataReaders, DDS_ANY_SAMPLE_STATE, DDS_ANY_VIEW_STATE, DDS_ANY_INSTANCE_STATE); if (retcode != DDS_RETCODE_OK) { printf("ERROR error %d\n", retcode); /* IMPORTANT. Remember to invoke DDS_Subscriber_end_access() before a * return call. Also reset DataReaders sequence */ DDS_DataReaderSeq_ensure_length(&MyDataReaders, 0, 0); DDS_Subscriber_end_access(subscriber); return; } /* Read the samples received, following the DataReaders sequence */ for (i = 0; i < DDS_DataReaderSeq_get_length(&MyDataReaders); i++) { ordered_groupDataReader *ordered_group_reader = NULL; struct ordered_group data; struct DDS_SampleInfo info; ordered_group_initialize(&data); ordered_group_reader = ordered_groupDataReader_narrow( DDS_DataReaderSeq_get(&MyDataReaders, i)); if (ordered_group_reader == NULL) { printf("DataReader narrow error\n"); /* IMPORTANT. Remember to invoke DDS_Subscriber_end_access() before * a return call. Also reset DataReaders sequence */ DDS_DataReaderSeq_ensure_length(&MyDataReaders, 0, 0); DDS_Subscriber_end_access(subscriber); return; } /* IMPORTANT. Use take_next_sample(). We need to take only one sample each time, as we want to follow the sequence of DataReaders. This way the samples will be returned in the order in which they were modified */ retcode = ordered_groupDataReader_take_next_sample( ordered_group_reader, &data, &info); /* In case there is no data in current DataReader, check next in the sequence */ if (retcode == DDS_RETCODE_NO_DATA) { continue; } else if (retcode != DDS_RETCODE_OK) { printf("take error %d\n", retcode); continue; } /* Print data sample */ if (info.valid_data) { ordered_groupTypeSupport_print_data(&data); } } /* Reset DataReaders sequence */ DDS_DataReaderSeq_ensure_length(&MyDataReaders, 0, 0); /* IMPORTANT for GROUP access scope: Invoking DDS_Subscriber_end_access() */ DDS_Subscriber_end_access(subscriber); } /* Delete all entities */ static int subscriber_shutdown(DDS_DomainParticipant *participant) { DDS_ReturnCode_t retcode; int status = 0; if (participant != NULL) { retcode = DDS_DomainParticipant_delete_contained_entities(participant); if (retcode != DDS_RETCODE_OK) { printf("delete_contained_entities error %d\n", retcode); status = -1; } retcode = DDS_DomainParticipantFactory_delete_participant( DDS_TheParticipantFactory, participant); if (retcode != DDS_RETCODE_OK) { printf("delete_participant error %d\n", retcode); status = -1; } } /* RTI Connext provides the finalize_instance() method on domain participant factory for users who want to release memory used by the participant factory. Uncomment the following block of code for clean destruction of the singleton. */ /* retcode = DDS_DomainParticipantFactory_finalize_instance(); if (retcode != DDS_RETCODE_OK) { printf("finalize_instance error %d\n", retcode); status = -1; } */ return status; } static int subscriber_main(int domainId, int sample_count) { DDS_DomainParticipant *participant = NULL; DDS_Subscriber *subscriber = NULL; DDS_Topic *topic1 = NULL; DDS_Topic *topic2 = NULL; DDS_Topic *topic3 = NULL; struct DDS_SubscriberListener subscriber_listener = DDS_SubscriberListener_INITIALIZER; DDS_DataReader *reader1 = NULL; DDS_DataReader *reader2 = NULL; DDS_DataReader *reader3 = NULL; DDS_ReturnCode_t retcode; const char *type_name = NULL; int count = 0; struct DDS_Duration_t poll_period = { 4, 0 }; /* To customize participant QoS, use the configuration file USER_QOS_PROFILES.xml */ participant = DDS_DomainParticipantFactory_create_participant( DDS_TheParticipantFactory, domainId, &DDS_PARTICIPANT_QOS_DEFAULT, NULL /* listener */, DDS_STATUS_MASK_NONE); if (participant == NULL) { printf("create_participant error\n"); subscriber_shutdown(participant); return -1; } /* Set up Subscriber listener and establish on_data_on_readers callback */ /* Set up a data reader listener */ subscriber_listener.on_data_on_readers = ordered_groupListener_on_data_on_readers; /* To customize subscriber QoS, use the configuration file USER_QOS_PROFILES.xml */ subscriber = DDS_DomainParticipant_create_subscriber( participant, &DDS_SUBSCRIBER_QOS_DEFAULT, &subscriber_listener /* listener */, DDS_DATA_ON_READERS_STATUS); if (subscriber == NULL) { printf("create_subscriber error\n"); subscriber_shutdown(participant); return -1; } /* Register the type before creating the topic */ type_name = ordered_groupTypeSupport_get_type_name(); retcode = ordered_groupTypeSupport_register_type(participant, type_name); if (retcode != DDS_RETCODE_OK) { printf("register_type error %d\n", retcode); subscriber_shutdown(participant); return -1; } /* TOPICS */ /* To customize topic QoS, use the configuration file USER_QOS_PROFILES.xml */ topic1 = DDS_DomainParticipant_create_topic( participant, "Topic1", type_name, &DDS_TOPIC_QOS_DEFAULT, NULL /* listener */, DDS_STATUS_MASK_NONE); if (topic1 == NULL) { printf("create_topic error\n"); subscriber_shutdown(participant); return -1; } topic2 = DDS_DomainParticipant_create_topic( participant, "Topic2", type_name, &DDS_TOPIC_QOS_DEFAULT, NULL /* listener */, DDS_STATUS_MASK_NONE); if (topic2 == NULL) { printf("create_topic error\n"); subscriber_shutdown(participant); return -1; } topic3 = DDS_DomainParticipant_create_topic( participant, "Topic3", type_name, &DDS_TOPIC_QOS_DEFAULT, NULL /* listener */, DDS_STATUS_MASK_NONE); if (topic3 == NULL) { printf("create_topic error\n"); subscriber_shutdown(participant); return -1; } /* DATAREADERS */ /* To customize data reader QoS, use the configuration file USER_QOS_PROFILES.xml */ reader1 = DDS_Subscriber_create_datareader( subscriber, DDS_Topic_as_topicdescription(topic1), &DDS_DATAREADER_QOS_DEFAULT, NULL, DDS_STATUS_MASK_NONE); if (reader1 == NULL) { printf("create_datareader error\n"); subscriber_shutdown(participant); return -1; } reader2 = DDS_Subscriber_create_datareader( subscriber, DDS_Topic_as_topicdescription(topic2), &DDS_DATAREADER_QOS_DEFAULT, NULL, DDS_STATUS_MASK_NONE); if (reader2 == NULL) { printf("create_datareader error\n"); subscriber_shutdown(participant); return -1; } reader3 = DDS_Subscriber_create_datareader( subscriber, DDS_Topic_as_topicdescription(topic3), &DDS_DATAREADER_QOS_DEFAULT, NULL, DDS_STATUS_MASK_NONE); if (reader3 == NULL) { printf("create_datareader error\n"); subscriber_shutdown(participant); return -1; } /* Main loop */ for (count = 0; (sample_count == 0) || (count < sample_count); ++count) { printf("ordered_group subscriber sleeping for %d sec...\n", poll_period.sec); NDDS_Utility_sleep(&poll_period); } /* Cleanup and delete all entities */ return subscriber_shutdown(participant); } #if defined(RTI_WINCE) int wmain(int argc, wchar_t **argv) { int domainId = 0; int sample_count = 0; /* infinite loop */ if (argc >= 2) { domainId = _wtoi(argv[1]); } if (argc >= 3) { sample_count = _wtoi(argv[2]); } /* Uncomment this to turn on additional logging NDDS_Config_Logger_set_verbosity_by_category( NDDS_Config_Logger_get_instance(), NDDS_CONFIG_LOG_CATEGORY_API, NDDS_CONFIG_LOG_VERBOSITY_STATUS_ALL); */ return subscriber_main(domainId, sample_count); } #elif !(defined(RTI_VXWORKS) && !defined(__RTP__)) && !defined(RTI_PSOS) int main(int argc, char *argv[]) { int domainId = 0; int sample_count = 0; /* infinite loop */ if (argc >= 2) { domainId = atoi(argv[1]); } if (argc >= 3) { sample_count = atoi(argv[2]); } /* Uncomment this to turn on additional logging NDDS_Config_Logger_set_verbosity_by_category( NDDS_Config_Logger_get_instance(), NDDS_CONFIG_LOG_CATEGORY_API, NDDS_CONFIG_LOG_VERBOSITY_STATUS_ALL); */ return subscriber_main(domainId, sample_count); } #endif #ifdef RTI_VX653 const unsigned char *__ctype = NULL; void usrAppInit() { #ifdef USER_APPL_INIT USER_APPL_INIT; /* for backwards compatibility */ #endif /* add application specific code here */ taskSpawn( "sub", RTI_OSAPI_THREAD_PRIORITY_NORMAL, 0x8, 0x150000, (FUNCPTR) subscriber_main, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0); } #endif
c
rticonnextdds-examples
data/projects/rticonnextdds-examples/connext_dds/ordered_presentation_group/c++03/ordered_group_publisher.cxx
/******************************************************************************* (c) 2005-2015 Copyright, Real-Time Innovations, Inc. All rights reserved. RTI grants Licensee a license to use, modify, compile, and create derivative works of the Software. Licensee has the right to distribute object form only for use with RTI products. The Software is provided "as is", with no warranty of any type, including any warranty for fitness for any purpose. RTI is under no obligation to maintain or support the Software. RTI shall not be liable for any incidental or consequential damages arising out of the use or inability to use the software. ******************************************************************************/ #include <iostream> #include "ordered_group.hpp" #include <dds/dds.hpp> using namespace dds::core; using namespace dds::core::policy; using namespace dds::domain; using namespace dds::pub; using namespace dds::pub::qos; using namespace dds::topic; void publisher_main(int domain_id, int sample_count) { // Create a DomainParticipant with default Qos DomainParticipant participant(domain_id); // Retrieve the default Publisher QoS, from USER_QOS_PROFILES.xml PublisherQos publisher_qos = QosProvider::Default().publisher_qos(); // If you want to change the Publisher's QoS programmatically rather than // using the XML file, uncomment the following line. // publisher_qos << Presentation::GroupAccessScope(false, true); // Create a single Publisher for all DataWriters. Publisher publisher(participant, publisher_qos); // Create three Topic, once for each DataWriter. Topic<ordered_group> topic1(participant, "Topic1"); Topic<ordered_group> topic2(participant, "Topic2"); Topic<ordered_group> topic3(participant, "Topic3"); // Create three DataWriter. Since the QoS policy is set to 'GROUP', // and the three writers belong to the same Publisher, the instance change // will be available for the Subscriber in the same order. DataWriter<ordered_group> writer1(publisher, topic1); DataWriter<ordered_group> writer2(publisher, topic2); DataWriter<ordered_group> writer3(publisher, topic3); // Create one instance for each DataWriter. ordered_group instance1; ordered_group instance2; ordered_group instance3; for (int count = 0; count < sample_count || sample_count == 0; count++) { std::cout << "Writing ordered_group, count " << count << std::endl; // Modify twice the first instance and send with the first writer. instance1.message("First sample, Topic 1 sent by DataWriter number 1"); writer1.write(instance1); instance1.message("Second sample, Topic 1 sent by DataWriter number 1"); writer1.write(instance1); // Modify twice the second instance and send with the second writer. instance2.message("First sample, Topic 2 sent by DataWriter number 2"); writer2.write(instance2); instance2.message("Second sample, Topic 2 sent by DataWriter number 2"); writer2.write(instance2); // Modify twice the third instance and send with the third writer. instance3.message("First sample, Topic 3 sent by DataWriter number 3"); writer3.write(instance3); instance3.message("Second sample, Topic 3 sent by DataWriter number 3"); writer3.write(instance3); rti::util::sleep(Duration(1)); } } int main(int argc, char *argv[]) { int domain_id = 0; int sample_count = 0; // Infinite loop if (argc >= 2) { domain_id = atoi(argv[1]); } if (argc >= 3) { sample_count = atoi(argv[2]); } // To turn on additional logging, include <rti/config/Logger.hpp> and // uncomment the following line: // rti::config::Logger::instance().verbosity(rti::config::Verbosity::STATUS_ALL); try { publisher_main(domain_id, sample_count); } catch (const std::exception &ex) { // This will catch DDS exceptions std::cerr << "Exception in publisher_main: " << ex.what() << std::endl; return -1; } return 0; }
cxx
rticonnextdds-examples
data/projects/rticonnextdds-examples/connext_dds/ordered_presentation_group/c++03/ordered_group_subscriber.cxx
/******************************************************************************* (c) 2005-2015 Copyright, Real-Time Innovations, Inc. All rights reserved. RTI grants Licensee a license to use, modify, compile, and create derivative works of the Software. Licensee has the right to distribute object form only for use with RTI products. The Software is provided "as is", with no warranty of any type, including any warranty for fitness for any purpose. RTI is under no obligation to maintain or support the Software. RTI shall not be liable for any incidental or consequential damages arising out of the use or inability to use the software. ******************************************************************************/ #include <iostream> #include "ordered_group.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::core::status; using namespace dds::domain; using namespace dds::sub; using namespace dds::sub::qos; using namespace rti::sub; using namespace dds::topic; class ordered_groupSubscriberListener : public NoOpSubscriberListener { public: void on_data_on_readers(Subscriber &subscriber) { // Create a coherent group access. CoherentAccess coherent_access(subscriber); // Get the sequence of DataReaders that specifies the order // in wich each sample should be read. std::vector<AnyDataReader> readers; int num_readers = find(subscriber, dds::sub::status::DataState::new_data(), std::back_inserter(readers)); std::cout << num_readers << std::endl; for (int i = 0; i < num_readers; i++) { DataReader<ordered_group> reader = readers[i].get<ordered_group>(); // We need to take only one sample each time, as we want to follow // the sequence of DataReaders. This way the samples will be // returned in the order in which they were modified. LoanedSamples<ordered_group> sample = reader.select().max_samples(1).take(); if (sample.length() > 0 && sample[0].info().valid()) { std::cout << sample[0].data() << std::endl; } } // The destructor will ends the coherent group access } }; void subscriber_main(int domain_id, int sample_count) { // Create a DomainParticipant with default Qos DomainParticipant participant(domain_id); // Retrieve the default Subscriber QoS, from USER_QOS_PROFILES.xml SubscriberQos subscriber_qos = QosProvider::Default().subscriber_qos(); // If you want to change the Subscriber's QoS programmatically rather than // using the XML file, uncomment the following line. // subscriber_qos << Presentation::GroupAccessScope(false, true); // Create a Subscriber. Subscriber subscriber(participant, subscriber_qos); // Associate a listener to the subscriber using ListenerBinder, a RAII that // will take care of setting it to NULL on destruction. ListenerBinder<Subscriber> subscriber_listener = rti::core::bind_and_manage_listener( subscriber, new ordered_groupSubscriberListener, dds::core::status::StatusMask::data_on_readers()); // Create three Topic, once for each DataReader. Topic<ordered_group> topic1(participant, "Topic1"); Topic<ordered_group> topic2(participant, "Topic2"); Topic<ordered_group> topic3(participant, "Topic3"); // Create one DataReader for each Topic. DataReader<ordered_group> reader1(subscriber, topic1); DataReader<ordered_group> reader2(subscriber, topic2); DataReader<ordered_group> reader3(subscriber, topic3); for (int count = 0; (sample_count == 0) || (count < sample_count); ++count) { std::cout << "ordered_group subscriber sleeping for 1 sec..." << std::endl; rti::util::sleep(Duration(1)); } } int main(int argc, char *argv[]) { int domain_id = 0; int sample_count = 0; // Infinite loop if (argc >= 2) { domain_id = atoi(argv[1]); } if (argc >= 3) { sample_count = atoi(argv[2]); } // To turn on additional logging, include <rti/config/Logger.hpp> and // uncomment the following line: // rti::config::Logger::instance().verbosity(rti::config::Verbosity::STATUS_ALL); try { subscriber_main(domain_id, sample_count); } catch (const std::exception &ex) { // This will catch DDS exceptions std::cerr << "Exception in subscriber_main: " << ex.what() << std::endl; return -1; } return 0; }
cxx
rticonnextdds-examples
data/projects/rticonnextdds-examples/connext_dds/ordered_presentation_group/c++11/application.hpp
/* * (c) Copyright, Real-Time Innovations, 2020. All rights reserved. * RTI grants Licensee a license to use, modify, compile, and create derivative * works of the software solely for use with RTI Connext DDS. Licensee may * redistribute copies of the software provided that all such copies are subject * to this license. The software is provided "as is", with no warranty of any * type, including any warranty for fitness for any purpose. RTI is under no * obligation to maintain or support the software. RTI shall not be liable for * any incidental or consequential damages arising out of the use or inability * to use the software. */ #ifndef APPLICATION_HPP #define APPLICATION_HPP #include <iostream> #include <csignal> #include <dds/core/ddscore.hpp> namespace application { // Catch control-C and tell application to shut down bool shutdown_requested = false; inline void stop_handler(int) { shutdown_requested = true; std::cout << "preparing to shut down..." << std::endl; } inline void setup_signal_handlers() { signal(SIGINT, stop_handler); signal(SIGTERM, stop_handler); } enum class ParseReturn { ok, failure, exit }; enum class ApplicationKind { publisher, subscriber }; struct ApplicationArguments { ParseReturn parse_result; unsigned int domain_id; unsigned int sample_count; rti::config::Verbosity verbosity; 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[], ApplicationKind current_application) { int arg_processing = 1; bool show_usage = false; ParseReturn parse_result = ParseReturn::ok; unsigned int domain_id = 0; unsigned int sample_count = (std::numeric_limits<unsigned int>::max)(); rti::config::Verbosity verbosity(rti::config::Verbosity::EXCEPTION); while (arg_processing < argc) { if ((argc > arg_processing + 1) && (strcmp(argv[arg_processing], "-d") == 0 || strcmp(argv[arg_processing], "--domain") == 0)) { domain_id = atoi(argv[arg_processing + 1]); arg_processing += 2; } else if ( (argc > arg_processing + 1) && current_application == ApplicationKind::publisher && (strcmp(argv[arg_processing], "-s") == 0 || strcmp(argv[arg_processing], "--sample-count") == 0)) { sample_count = atoi(argv[arg_processing + 1]); arg_processing += 2; } else if ( (argc > arg_processing + 1) && current_application == ApplicationKind::subscriber && (strcmp(argv[arg_processing], "-s") == 0 || strcmp(argv[arg_processing], "--sleeps") == 0)) { sample_count = atoi(argv[arg_processing + 1]); arg_processing += 2; } else if ( (argc > arg_processing + 1) && (strcmp(argv[arg_processing], "-v") == 0 || strcmp(argv[arg_processing], "--verbosity") == 0)) { set_verbosity(verbosity, atoi(argv[arg_processing + 1])); arg_processing += 2; } else if ( strcmp(argv[arg_processing], "-h") == 0 || strcmp(argv[arg_processing], "--help") == 0) { std::cout << "Example application." << std::endl; show_usage = true; parse_result = ParseReturn::exit; break; } else { std::cout << "Bad parameter." << std::endl; show_usage = true; parse_result = ParseReturn::failure; break; } } if (show_usage) { std::string usage = "Usage:\n" " -d, --domain <int> Domain ID this application " "will\n" " subscribe in. \n" " Default: 0\n"; if (current_application == ApplicationKind::publisher) { usage += " -s, --sample_count <int> Number of samples to send " "before\n" " cleanly shutting down. \n" " Default: infinite\n"; } else if (current_application == ApplicationKind::subscriber) { usage += " -s, --sleeps <int> Number of sleeps before " "cleanly\n" " shutting down. \n" " Default: infinite\n"; } usage += " -v, --verbosity <int> How much debugging output to " "show.\n" " Range: 0-3 \n" " Default: 1\n"; std::cout << usage; } return ApplicationArguments( parse_result, domain_id, sample_count, verbosity); } } // namespace application #endif // APPLICATION_HPP
hpp
rticonnextdds-examples
data/projects/rticonnextdds-examples/connext_dds/ordered_presentation_group/c++11/ordered_group_publisher.cxx
/******************************************************************************* (c) 2005-2015 Copyright, Real-Time Innovations, Inc. All rights reserved. RTI grants Licensee a license to use, modify, compile, and create derivative works of the Software. Licensee has the right to distribute object form only for use with RTI products. The Software is provided "as is", with no warranty of any type, including any warranty for fitness for any purpose. RTI is under no obligation to maintain or support the Software. RTI shall not be liable for any incidental or consequential damages arising out of the use or inability to use the software. ******************************************************************************/ #include <dds/pub/ddspub.hpp> #include <rti/util/util.hpp> // for sleep() #include <rti/config/Logger.hpp> // for logging #include "application.hpp" // for command line parsing and ctrl-c #include "ordered_group.hpp" void run_publisher_application( unsigned int domain_id, unsigned int sample_count) { // Create a DomainParticipant with default Qos dds::domain::DomainParticipant participant(domain_id); // Retrieve the default Publisher QoS, from USER_QOS_PROFILES.xml dds::pub::qos::PublisherQos publisher_qos = dds::core::QosProvider::Default().publisher_qos(); // If you want to change the Publisher's QoS programmatically rather than // using the XML file, uncomment the following line. // publisher_qos << Presentation::GroupAccessScope(false, true); // Create a single Publisher for all DataWriters. dds::pub::Publisher publisher(participant, publisher_qos); // Create three Topic, once for each DataWriter. dds::topic::Topic<ordered_group> topic1(participant, "Topic1"); dds::topic::Topic<ordered_group> topic2(participant, "Topic2"); dds::topic::Topic<ordered_group> topic3(participant, "Topic3"); // Create three DataWriter. Since the QoS policy is set to 'GROUP', // and the three writers belong to the same Publisher, the instance change // will be available for the Subscriber in the same order. dds::pub::DataWriter<ordered_group> writer1(publisher, topic1); dds::pub::DataWriter<ordered_group> writer2(publisher, topic2); dds::pub::DataWriter<ordered_group> writer3(publisher, topic3); // Create one instance for each DataWriter. ordered_group instance1; ordered_group instance2; ordered_group instance3; for (unsigned int samples_written = 0; !application::shutdown_requested && samples_written < sample_count; samples_written++) { std::cout << "Writing ordered_group, count " << samples_written << std::endl; // Modify twice the first instance and send with the first writer. instance1.message("First sample, Topic 1 sent by DataWriter number 1"); writer1.write(instance1); instance1.message("Second sample, Topic 1 sent by DataWriter number 1"); writer1.write(instance1); // Modify twice the second instance and send with the second writer. instance2.message("First sample, Topic 2 sent by DataWriter number 2"); writer2.write(instance2); instance2.message("Second sample, Topic 2 sent by DataWriter number 2"); writer2.write(instance2); // Modify twice the third instance and send with the third writer. instance3.message("First sample, Topic 3 sent by DataWriter number 3"); writer3.write(instance3); instance3.message("Second sample, Topic 3 sent by DataWriter number 3"); writer3.write(instance3); rti::util::sleep(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, ApplicationKind::publisher); if (arguments.parse_result == ParseReturn::exit) { return EXIT_SUCCESS; } else if (arguments.parse_result == ParseReturn::failure) { return EXIT_FAILURE; } setup_signal_handlers(); // Sets Connext verbosity to help debugging rti::config::Logger::instance().verbosity(arguments.verbosity); try { 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_group/c++11/ordered_group_subscriber.cxx
/******************************************************************************* (c) 2005-2015 Copyright, Real-Time Innovations, Inc. All rights reserved. RTI grants Licensee a license to use, modify, compile, and create derivative works of the Software. Licensee has the right to distribute object form only for use with RTI products. The Software is provided "as is", with no warranty of any type, including any warranty for fitness for any purpose. RTI is under no obligation to maintain or support the Software. RTI shall not be liable for any incidental or consequential damages arising out of the use or inability to use the software. ******************************************************************************/ #include <dds/sub/ddssub.hpp> #include <dds/core/ddscore.hpp> #include <rti/util/util.hpp> // for sleep() #include <rti/config/Logger.hpp> // for logging #include "ordered_group.hpp" #include "application.hpp" // for command line parsing and ctrl-c class ordered_groupSubscriberListener : public dds::sub::NoOpSubscriberListener { public: void on_data_on_readers(dds::sub::Subscriber &subscriber) { // Create a coherent group access. dds::sub::CoherentAccess coherent_access(subscriber); // Get the sequence of DataReaders that specifies the order // in wich each sample should be read. std::vector<dds::sub::AnyDataReader> readers; int num_readers = find(subscriber, dds::sub::status::DataState::new_data(), std::back_inserter(readers)); std::cout << num_readers << std::endl; for (int i = 0; i < num_readers; i++) { dds::sub::DataReader<ordered_group> reader = readers[i].get<ordered_group>(); // We need to take only one sample each time, as we want to follow // the sequence of DataReaders. This way the samples will be // returned in the order in which they were modified. dds::sub::LoanedSamples<ordered_group> sample = reader.select().max_samples(1).take(); if (sample.length() > 0 && sample[0].info().valid()) { std::cout << sample[0].data() << std::endl; } } // The destructor will ends the coherent group access } }; void run_subscriber_application( unsigned int domain_id, unsigned int sample_count) { // Create a DomainParticipant 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's QoS programmatically rather than // using the XML file, uncomment the following line. // subscriber_qos << Presentation::GroupAccessScope(false, true); // Create a shared pointer for the Subscriber Listener auto subscriber_listener = std::make_shared<ordered_groupSubscriberListener>(); // Create a Subscriber. dds::sub::Subscriber subscriber( participant, subscriber_qos, subscriber_listener); // Create three Topic, once for each DataReader. dds::topic::Topic<ordered_group> topic1(participant, "Topic1"); dds::topic::Topic<ordered_group> topic2(participant, "Topic2"); dds::topic::Topic<ordered_group> topic3(participant, "Topic3"); // Create one DataReader for each Topic. dds::sub::DataReader<ordered_group> reader1(subscriber, topic1); dds::sub::DataReader<ordered_group> reader2(subscriber, topic2); dds::sub::DataReader<ordered_group> reader3(subscriber, topic3); for (unsigned int samples_read = 0; !application::shutdown_requested && samples_read < sample_count; samples_read++) { std::cout << "ordered_group subscriber sleeping for 1 sec..." << std::endl; rti::util::sleep(dds::core::Duration(1)); } } int main(int argc, char *argv[]) { using namespace application; // Parse arguments and handle control-C auto arguments = parse_arguments(argc, argv, ApplicationKind::subscriber); if (arguments.parse_result == ParseReturn::exit) { return EXIT_SUCCESS; } else if (arguments.parse_result == ParseReturn::failure) { return EXIT_FAILURE; } setup_signal_handlers(); // Sets Connext verbosity to help debugging rti::config::Logger::instance().verbosity(arguments.verbosity); try { 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/dynamic_data_using_publisher_subscriber/c++/Shapes_subscriber.cxx
/******************************************************************************* (c) 2005-2014 Copyright, Real-Time Innovations, Inc. All rights reserved. RTI grants Licensee a license to use, modify, compile, and create derivative works of the Software. Licensee has the right to distribute object form only for use with RTI products. The Software is provided "as is", with no warranty of any type, including any warranty for fitness for any purpose. RTI is under no obligation to maintain or support the Software. RTI shall not be liable for any incidental or consequential damages arising out of the use or inability to use the software. ******************************************************************************/ /* Shapes_subscriber.cxx A subscription of data type ShapeType using DynamicData This file is derived from code automatically generated by the rtiddsgen command: rtiddsgen -language C++ -example <arch> Shapes.idl If you are not using and IDL to generate the TypeCode, you will need to create it manually. Follow other DynamicData examples (such as NestedStruct one) to learn how to do it. Example: To run the example application on domain <domain_id>: On Unix: objs/<arch>/Shapes_publisher <domain_id> <sample #> objs/<arch>/Shapes_subscriber <domain_id> <sample #> On Windows: objs\<arch>\Shapes_publisher <domain_id> <sample #> objs\<arch>\Shapes_subscriber <domain_id> <sample #> modification history ------------ ------- */ #include <stdio.h> #include <stdlib.h> #ifdef RTI_VX653 #include <vThreadsData.h> #endif #include "Shapes.h" #include "ndds/ndds_cpp.h" #define EXAMPLE_TYPE_NAME "ShapesType" class ShapeTypeListener : public DDSDataReaderListener { public: virtual void on_requested_deadline_missed( DDSDataReader * /*reader*/, const DDS_RequestedDeadlineMissedStatus & /*status*/) { } virtual void on_requested_incompatible_qos( DDSDataReader * /*reader*/, const DDS_RequestedIncompatibleQosStatus & /*status*/) { } virtual void on_sample_rejected( DDSDataReader * /*reader*/, const DDS_SampleRejectedStatus & /*status*/) { } virtual void on_liveliness_changed( DDSDataReader * /*reader*/, const DDS_LivelinessChangedStatus & /*status*/) { } virtual void on_sample_lost( DDSDataReader * /*reader*/, const DDS_SampleLostStatus & /*status*/) { } virtual void on_subscription_matched( DDSDataReader * /*reader*/, const DDS_SubscriptionMatchedStatus & /*status*/) { } virtual void on_data_available(DDSDataReader *reader); }; void ShapeTypeListener::on_data_available(DDSDataReader *reader) { /* We need to create a DynamicDataReader to receive the DynamicData * and a DynamicDataSeq to store there the available DynamicData received */ DDSDynamicDataReader *DynamicData_reader = NULL; DDS_DynamicDataSeq data_seq; DDS_SampleInfoSeq info_seq; DDS_ReturnCode_t retcode; int i; /* To use DynamicData, we need to assign the generic DataReader to * a DynamicDataReader, using DDS_DynamicDataReader_narrow. * The following narrow fuction should never fail, as it performs * only a safe cast. */ DynamicData_reader = DDSDynamicDataReader::narrow(reader); if (DynamicData_reader == NULL) { printf("DataReader narrow error\n"); return; } retcode = DynamicData_reader->take( data_seq, info_seq, DDS_LENGTH_UNLIMITED, DDS_ANY_SAMPLE_STATE, DDS_ANY_VIEW_STATE, DDS_ANY_INSTANCE_STATE); if (retcode == DDS_RETCODE_NO_DATA) { return; } else if (retcode != DDS_RETCODE_OK) { printf("take error %d\n", retcode); return; } for (i = 0; i < data_seq.length(); ++i) { if (info_seq[i].valid_data) { data_seq[i].print(stdout, 1); } } retcode = DynamicData_reader->return_loan(data_seq, info_seq); if (retcode != DDS_RETCODE_OK) { printf("return loan error %d\n", retcode); } } /* Delete all entities */ static int subscriber_shutdown( DDSDomainParticipant *participant, DDSDynamicDataTypeSupport *type_support) { DDS_ReturnCode_t retcode; int status = 0; if (participant != NULL) { if (type_support != NULL) { delete type_support; type_support = NULL; } retcode = participant->delete_contained_entities(); if (retcode != DDS_RETCODE_OK) { printf("delete_contained_entities error %d\n", retcode); status = -1; } retcode = DDSTheParticipantFactory->delete_participant(participant); if (retcode != DDS_RETCODE_OK) { printf("delete_participant error %d\n", retcode); status = -1; } } /* RTI Connext provides the finalize_instance() method on * domain participant factory for people who want to release memory used * by the participant factory. Uncomment the following block of code for * clean destruction of the singleton. */ retcode = DDSDomainParticipantFactory::finalize_instance(); if (retcode != DDS_RETCODE_OK) { printf("finalize_instance error %d\n", retcode); status = -1; } return status; } extern "C" int subscriber_main(int domainId, int sample_count) { DDSDomainParticipant *participant = NULL; DDSSubscriber *subscriber = NULL; DDSTopic *topic = NULL; ShapeTypeListener *reader_listener = NULL; DDSDataReader *reader = NULL; DDS_ReturnCode_t retcode; const char *type_name = NULL; int count = 0; DDS_Duration_t receive_period = { 1, 0 }; int status = 0; /* Dynamic Data parameters that we will need */ struct DDS_TypeCode *type_code = NULL; struct DDS_DynamicDataTypeProperty_t props; DDSDynamicDataTypeSupport *type_support = NULL; participant = DDSTheParticipantFactory->create_participant( domainId, DDS_PARTICIPANT_QOS_DEFAULT, NULL /* listener */, DDS_STATUS_MASK_NONE); if (participant == NULL) { printf("create_participant error\n"); subscriber_shutdown(participant, type_support); return -1; } subscriber = participant->create_subscriber( DDS_SUBSCRIBER_QOS_DEFAULT, NULL /* listener */, DDS_STATUS_MASK_NONE); if (subscriber == NULL) { printf("create_subscriber error\n"); subscriber_shutdown(participant, type_support); return -1; } /* Create DynamicData using TypeCode from Shapes.cxx * If you are NOT using a type generated with rtiddsgen, you * need to create this TypeCode from scratch. */ type_code = ShapeType_get_typecode(); if (type_code == NULL) { printf("get_typecode error\n"); subscriber_shutdown(participant, type_support); return -1; } /* Create the Dynamic data type support object */ type_support = new DDSDynamicDataTypeSupport(type_code, props); if (type_support == NULL) { fprintf(stderr, "create type_support error\n"); subscriber_shutdown(participant, type_support); return -1; } /* Register the type before creating the topic */ type_name = EXAMPLE_TYPE_NAME; retcode = type_support->register_type(participant, type_name); if (retcode != DDS_RETCODE_OK) { printf("register_type error %d\n", retcode); subscriber_shutdown(participant, type_support); return -1; } /* Make sure both publisher and subscriber share the same topic name. * In the Shapes example: we are subscribing to a Square, wich is the * topic name. If you want to publish other shapes (Triangle or Circle), * you just need to update the topic name. */ topic = participant->create_topic( "Square", type_name, DDS_TOPIC_QOS_DEFAULT, NULL /* listener */, DDS_STATUS_MASK_NONE); if (topic == NULL) { printf("create_topic error\n"); subscriber_shutdown(participant, type_support); return -1; } /* Create a data reader listener */ reader_listener = new ShapeTypeListener(); /* First, we create a generic DataReader for our topic */ reader = subscriber->create_datareader( topic, DDS_DATAREADER_QOS_DEFAULT, reader_listener, DDS_STATUS_MASK_ALL); if (reader == NULL) { printf("create_datareader error\n"); subscriber_shutdown(participant, type_support); delete reader_listener; return -1; } /* Main loop */ for (count = 0; (sample_count == 0) || (count < sample_count); ++count) { printf("ShapeType subscriber sleeping for %d sec...\n", receive_period.sec); NDDSUtility::sleep(receive_period); } /* Delete all entities */ status = subscriber_shutdown(participant, type_support); delete reader_listener; return status; } #if defined(RTI_WINCE) int wmain(int argc, wchar_t **argv) { int domainId = 0; int sample_count = 0; /* infinite loop */ if (argc >= 2) { domainId = _wtoi(argv[1]); } if (argc >= 3) { sample_count = _wtoi(argv[2]); } /* Uncomment this to turn on additional logging NDDSConfigLogger::get_instance()-> set_verbosity_by_category(NDDS_CONFIG_LOG_CATEGORY_API, NDDS_CONFIG_LOG_VERBOSITY_STATUS_ALL); */ return subscriber_main(domainId, sample_count); } #elif !(defined(RTI_VXWORKS) && !defined(__RTP__)) && !defined(RTI_PSOS) int main(int argc, char *argv[]) { int domainId = 0; int sample_count = 0; /* infinite loop */ if (argc >= 2) { domainId = atoi(argv[1]); } if (argc >= 3) { sample_count = atoi(argv[2]); } /* Uncomment this to turn on additional logging NDDSConfigLogger::get_instance()-> set_verbosity_by_category(NDDS_CONFIG_LOG_CATEGORY_API, NDDS_CONFIG_LOG_VERBOSITY_STATUS_ALL); */ return subscriber_main(domainId, sample_count); } #endif #ifdef RTI_VX653 const unsigned char *__ctype = *(__ctypePtrGet()); extern "C" void usrAppInit() { #ifdef USER_APPL_INIT USER_APPL_INIT; /* for backwards compatibility */ #endif /* add application specific code here */ taskSpawn( "sub", RTI_OSAPI_THREAD_PRIORITY_NORMAL, 0x8, 0x150000, (FUNCPTR) subscriber_main, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0); } #endif
cxx
rticonnextdds-examples
data/projects/rticonnextdds-examples/connext_dds/dynamic_data_using_publisher_subscriber/c++/Shapes_publisher.cxx
/******************************************************************************* (c) 2005-2014 Copyright, Real-Time Innovations, Inc. All rights reserved. RTI grants Licensee a license to use, modify, compile, and create derivative works of the Software. Licensee has the right to distribute object form only for use with RTI products. The Software is provided "as is", with no warranty of any type, including any warranty for fitness for any purpose. RTI is under no obligation to maintain or support the Software. RTI shall not be liable for any incidental or consequential damages arising out of the use or inability to use the software. ******************************************************************************/ /* Shapes_publisher.cxx A publication of data of type ShapeType using DynamicData This file is derived from code automatically generated by the rtiddsgen command: rtiddsgen -language C++ -example <arch> Shapes.idl If you are not using an IDL to generate the TypeCode, you will need to create it manually. Follow other DynamicData examples (such as NestedStruct one) to learn how to do it. Example: To run the example application on domain <domain_id>: On Unix: objs/<arch>/Shapes_publisher <domain_id> <sample #> objs/<arch>/Shapes_subscriber <domain_id> <sample #> On Windows: objs\<arch>\Shapes_publisher <domain_id> <sample #> objs\<arch>\Shapes_subscriber <domain_id> <sample #> modification history ------------ ------- */ #include <cstdio> #include <cstdlib> #ifdef RTI_VX653 #include <vThreadsData.h> #endif #include "Shapes.h" #include "ndds/ndds_cpp.h" #define EXAMPLE_TYPE_NAME "ShapesType" /* Delete all entities */ static int publisher_shutdown( DDSDomainParticipant *participant, DDSDynamicDataTypeSupport *type_support) { DDS_ReturnCode_t retcode; int status = 0; if (participant != NULL) { if (type_support != NULL) { delete type_support; type_support = NULL; } retcode = participant->delete_contained_entities(); if (retcode != DDS_RETCODE_OK) { printf("delete_contained_entities error %d\n", retcode); status = -1; } retcode = DDSTheParticipantFactory->delete_participant(participant); if (retcode != DDS_RETCODE_OK) { printf("delete_participant error %d\n", retcode); status = -1; } } /* RTI Connext provides finalize_instance() method on * domain participant factory for people who want to release memory used * by the participant factory. Uncomment the following block of code for * clean destruction of the singleton. */ retcode = DDSDomainParticipantFactory::finalize_instance(); if (retcode != DDS_RETCODE_OK) { printf("finalize_instance error %d\n", retcode); status = -1; } return status; } extern "C" int publisher_main(int domainId, int sample_count) { DDS_ReturnCode_t retcode; DDS_InstanceHandle_t instance_handle = DDS_HANDLE_NIL; const char *type_name = NULL; int count = 0; DDS_Duration_t send_period = { 0, 100000000 }; /* 100 ms */ /*** Shape direction variables ***/ int direction = 1; /* 1 means left to right and -1, right to left */ int x_position = 50; /* 50 is the initial position */ /*** DDS ENTITIES ***/ DDSDomainParticipant *participant = NULL; DDSPublisher *publisher = NULL; DDSTopic *topic = NULL; DDSDataWriter *writer = NULL; /*** Dynamic Data parameters that we will need ***/ struct DDS_TypeCode *type_code = NULL; DDS_DynamicData *data = NULL; DDS_Boolean data_is_initialized = DDS_BOOLEAN_FALSE; DDSDynamicDataWriter *DynamicData_writer = NULL; struct DDS_DynamicDataTypeProperty_t props; DDSDynamicDataTypeSupport *type_support = NULL; participant = DDSTheParticipantFactory->create_participant( domainId, DDS_PARTICIPANT_QOS_DEFAULT, NULL /* listener */, DDS_STATUS_MASK_NONE); if (participant == NULL) { printf("create_participant error\n"); publisher_shutdown(participant, type_support); return -1; } publisher = participant->create_publisher( DDS_PUBLISHER_QOS_DEFAULT, NULL /* listener */, DDS_STATUS_MASK_NONE); if (publisher == NULL) { printf("create_publisher error\n"); publisher_shutdown(participant, type_support); return -1; } /* Create DynamicData using TypeCode from Shapes.cxx * If you are NOT using a type generated with rtiddsgen, you * need to create this TypeCode from scratch. */ type_code = ShapeType_get_typecode(); if (type_code == NULL) { printf("get_typecode error\n"); publisher_shutdown(participant, type_support); return -1; } /* Create the Dynamic data type support object */ type_support = new DDSDynamicDataTypeSupport(type_code, props); if (type_support == NULL) { printf("constructor DynamicDataTypeSupport error\n"); publisher_shutdown(participant, type_support); return -1; } /* Register type before creating topic */ type_name = EXAMPLE_TYPE_NAME; retcode = type_support->register_type(participant, EXAMPLE_TYPE_NAME); if (retcode != DDS_RETCODE_OK) { printf("register_type error\n"); publisher_shutdown(participant, type_support); return -1; } /* Make sure both publisher and subscriber share the same topic * name. * In the Shapes example: we are publishing a Square, which is the * topic name. If you want to publish other shapes (Triangle or * Circle), you just need to update the topic name. */ topic = participant->create_topic( "Square", type_name, DDS_TOPIC_QOS_DEFAULT, NULL /* listener */, DDS_STATUS_MASK_NONE); if (topic == NULL) { printf("create_topic error\n"); publisher_shutdown(participant, type_support); return -1; } /* First, we create a generic DataWriter for our topic */ writer = publisher->create_datawriter( topic, DDS_DATAWRITER_QOS_DEFAULT, NULL /* listener */, DDS_STATUS_MASK_NONE); if (writer == NULL) { printf("create_datawriter error\n"); publisher_shutdown(participant, type_support); return -1; } /* Then, to use DynamicData, we need to assign the generic * DataWriter to a DynamicDataWriter, using * DDS_DynamicDataWriter_narrow. * The following narrow function should never fail, as it performs * only a safe cast. */ DynamicData_writer = DDSDynamicDataWriter::narrow(writer); if (DynamicData_writer == NULL) { printf("DynamicData_writer narrow error\n"); publisher_shutdown(participant, type_support); return -1; } /* Create an instance of the sparse data we are about to send */ data = type_support->create_data(); if (data == NULL) { printf("create_data error\n"); publisher_shutdown(participant, type_support); return -1; } /* Initialize the DynamicData object */ data->set_string("color", DDS_DYNAMIC_DATA_MEMBER_ID_UNSPECIFIED, "BLUE"); data->set_long("x", DDS_DYNAMIC_DATA_MEMBER_ID_UNSPECIFIED, 100); data->set_long("y", DDS_DYNAMIC_DATA_MEMBER_ID_UNSPECIFIED, 100); data->set_long("shapesize", DDS_DYNAMIC_DATA_MEMBER_ID_UNSPECIFIED, 30); /* Main loop */ for (count = 0; (sample_count == 0) || (count < sample_count); ++count) { printf("Sending shapesize %d\n", 30 + (count % 20)); printf("Sending x position %d\n", x_position); /* Modify the shapesize from 30 to 50 */ retcode = data->set_long( "shapesize", DDS_DYNAMIC_DATA_MEMBER_ID_UNSPECIFIED, 30 + (count % 20)); if (retcode != DDS_RETCODE_OK) { fprintf(stderr, "! Unable to set shapesize\n"); publisher_shutdown(participant, type_support); return -1; } /* Modify the position */ retcode = data->set_long( "x", DDS_DYNAMIC_DATA_MEMBER_ID_UNSPECIFIED, x_position); if (retcode != DDS_RETCODE_OK) { fprintf(stderr, "! Unable to set x\n"); publisher_shutdown(participant, type_support); return -1; } /* The x_position will be modified adding or substracting * 2 to the previous x_position depending on the direction. */ x_position += (direction * 2); /* The x_position will stay between 50 and 150 pixels. * When the position is greater than 150 'direction' will be negative * (moving to the left) and when it is lower than 50 'direction' will * be possitive (moving to the right). */ if (x_position >= 150) { direction = -1; } if (x_position <= 50) { direction = 1; } /* Write data */ retcode = DynamicData_writer->write(*data, instance_handle); if (retcode != DDS_RETCODE_OK) { printf("write error %d\n", retcode); publisher_shutdown(participant, type_support); return -1; } NDDSUtility::sleep(send_period); } /* Delete data sample */ retcode = type_support->delete_data(data); if (retcode != DDS_RETCODE_OK) { printf("ShapeTypeTypeSupport::delete_data error %d\n", retcode); } /* Delete all entities */ return publisher_shutdown(participant, type_support); } #if defined(RTI_WINCE) int wmain(int argc, wchar_t **argv) { int domainId = 0; int sample_count = 0; /* infinite loop */ if (argc >= 2) { domainId = _wtoi(argv[1]); } if (argc >= 3) { sample_count = _wtoi(argv[2]); } /* Uncomment this to turn on additional logging NDDSConfigLogger::get_instance()-> set_verbosity_by_category(NDDS_CONFIG_LOG_CATEGORY_API, NDDS_CONFIG_LOG_VERBOSITY_STATUS_ALL); */ return publisher_main(domainId, sample_count); } #elif !(defined(RTI_VXWORKS) && !defined(__RTP__)) && !defined(RTI_PSOS) int main(int argc, char *argv[]) { int domainId = 0; int sample_count = 0; /* infinite loop */ if (argc >= 2) { domainId = atoi(argv[1]); } if (argc >= 3) { sample_count = atoi(argv[2]); } /* Uncomment this to turn on additional logging NDDSConfigLogger::get_instance()-> set_verbosity_by_category(NDDS_CONFIG_LOG_CATEGORY_API, NDDS_CONFIG_LOG_VERBOSITY_STATUS_ALL); */ return publisher_main(domainId, sample_count); } #endif #ifdef RTI_VX653 const unsigned char *__ctype = *(__ctypePtrGet()); extern "C" void usrAppInit() { #ifdef USER_APPL_INIT USER_APPL_INIT; /* for backwards compatibility */ #endif /* add application specific code here */ taskSpawn( "pub", RTI_OSAPI_THREAD_PRIORITY_NORMAL, 0x8, 0x150000, (FUNCPTR) publisher_main, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0); } #endif
cxx
rticonnextdds-examples
data/projects/rticonnextdds-examples/connext_dds/dynamic_data_using_publisher_subscriber/c++98/Shapes_subscriber.cxx
/******************************************************************************* (c) 2005-2014 Copyright, Real-Time Innovations, Inc. All rights reserved. RTI grants Licensee a license to use, modify, compile, and create derivative works of the Software. Licensee has the right to distribute object form only for use with RTI products. The Software is provided "as is", with no warranty of any type, including any warranty for fitness for any purpose. RTI is under no obligation to maintain or support the Software. RTI shall not be liable for any incidental or consequential damages arising out of the use or inability to use the software. ******************************************************************************/ #include <iostream> #include <stdio.h> #include <stdlib.h> #include "Shapes.h" #include "ShapesSupport.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(DDSDynamicDataReader *typed_reader) { /* We need to create a DynamicDataSeq to store there the available * DynamicData received */ DDS_DynamicDataSeq 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) { data_seq[i].print(stdout, 1); 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 = { 1, 0 }; // Start communicating in a domain, usually one participant per application DDSDomainParticipant *participant = DDSTheParticipantFactory->create_participant( domain_id, DDS_PARTICIPANT_QOS_DEFAULT, NULL /* listener */, DDS_STATUS_MASK_NONE); if (participant == NULL) { return shutdown_participant( participant, "create_participant error", EXIT_FAILURE); } // A Subscriber allows an application to create one or more DataReaders DDSSubscriber *subscriber = participant->create_subscriber( DDS_SUBSCRIBER_QOS_DEFAULT, NULL /* listener */, DDS_STATUS_MASK_NONE); if (subscriber == NULL) { return shutdown_participant( participant, "create_subscriber error", EXIT_FAILURE); } /* Create DynamicData using TypeCode from Shapes.cxx * If you are NOT using a type generated with rtiddsgen, you * need to create this TypeCode from scratch. */ struct DDS_TypeCode *type_code = ShapeType_get_typecode(); if (type_code == NULL) { return shutdown_participant( participant, "get_typecode error", EXIT_FAILURE); } // Create the Dynamic data type support object struct DDS_DynamicDataTypeProperty_t props; DDSDynamicDataTypeSupport *type_support = new DDSDynamicDataTypeSupport(type_code, props); if (type_support == NULL) { return shutdown_participant( participant, "create type_support error", EXIT_FAILURE); } // Register the datatype to use when creating the Topic const char *type_name = ShapeTypeTypeSupport::get_type_name(); DDS_ReturnCode_t retcode = type_support->register_type(participant, type_name); if (retcode != DDS_RETCODE_OK) { return shutdown_participant( participant, "register_type error", EXIT_FAILURE); } /* Make sure both publisher and subscriber share the same topic name. * In the Shapes example: we are subscribing to a Square, wich is the * topic name. If you want to publish other shapes (Triangle or Circle), * you just need to update the topic name. */ DDSTopic *topic = participant->create_topic( "Square", 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 batch_data" 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 DDSDynamicDataReader *typed_reader = DDSDynamicDataReader::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/dynamic_data_using_publisher_subscriber/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/dynamic_data_using_publisher_subscriber/c++98/Shapes_publisher.cxx
/******************************************************************************* (c) 2005-2014 Copyright, Real-Time Innovations, Inc. All rights reserved. RTI grants Licensee a license to use, modify, compile, and create derivative works of the Software. Licensee has the right to distribute object form only for use with RTI products. The Software is provided "as is", with no warranty of any type, including any warranty for fitness for any purpose. RTI is under no obligation to maintain or support the Software. RTI shall not be liable for any incidental or consequential damages arising out of the use or inability to use the software. ******************************************************************************/ #include <iostream> #include <stdio.h> #include <stdlib.h> #include "Shapes.h" #include "ShapesSupport.h" #include "ndds/ndds_cpp.h" #include "application.h" using namespace application; static int shutdown_participant( DDSDomainParticipant *participant, const char *shutdown_message, int status); int run_publisher_application(unsigned int domain_id, unsigned int sample_count) { DDS_Duration_t send_period = { 0, 100000000 }; /* 100 ms */ /*** Shape direction variables ***/ int direction = 1; /* 1 means left to right and -1, right to left */ int x_position = 50; /* 50 is the initial position */ // 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); } /* Create DynamicData using TypeCode from Shapes.cxx * If you are NOT using a type generated with rtiddsgen, you * need to create this TypeCode from scratch. */ struct DDS_TypeCode *type_code = ShapeType_get_typecode(); if (type_code == NULL) { return shutdown_participant( participant, "get_typecode error", EXIT_FAILURE); } // Create the Dynamic data type support object struct DDS_DynamicDataTypeProperty_t props; DDSDynamicDataTypeSupport *type_support = new DDSDynamicDataTypeSupport(type_code, props); if (type_support == NULL) { return shutdown_participant( participant, "constructor DynamicDataTypeSupport error", EXIT_FAILURE); } // Register the datatype to use when creating the Topic const char *type_name = ShapeTypeTypeSupport::get_type_name(); DDS_ReturnCode_t retcode = type_support->register_type(participant, type_name); if (retcode != DDS_RETCODE_OK) { return shutdown_participant( participant, "register_type error", EXIT_FAILURE); } /* Make sure both publisher and subscriber share the same topic * name. * In the Shapes example: we are publishing a Square, which is the * topic name. If you want to publish other shapes (Triangle or * Circle), you just need to update the topic name. */ DDSTopic *topic = participant->create_topic( "Square", 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 batch_data" 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); } /* Then, to use DynamicData, we need to assign the generic * DataWriter to a DynamicDataWriter, using * DDS_DynamicDataWriter_narrow. * The following narrow function should never fail, as it performs * only a safe cast. */ DDSDynamicDataWriter *typed_writer = DDSDynamicDataWriter::narrow(untyped_writer); if (typed_writer == NULL) { return shutdown_participant( participant, "DataWriter narrow error", EXIT_FAILURE); } /* Create an instance of the sparse data we are about to send */ DDS_DynamicData *data = type_support->create_data(); if (data == NULL) { return shutdown_participant( participant, "create_data error", EXIT_FAILURE); } /* Initialize the DynamicData object */ data->set_string("color", DDS_DYNAMIC_DATA_MEMBER_ID_UNSPECIFIED, "BLUE"); data->set_long("x", DDS_DYNAMIC_DATA_MEMBER_ID_UNSPECIFIED, 100); data->set_long("y", DDS_DYNAMIC_DATA_MEMBER_ID_UNSPECIFIED, 100); data->set_long("shapesize", DDS_DYNAMIC_DATA_MEMBER_ID_UNSPECIFIED, 30); // Main loop, write data for (unsigned int samples_written = 0; !shutdown_requested && samples_written < sample_count; ++samples_written) { std::cout << "Sending shapesize " << 30 + (samples_written % 20) << std::endl; std::cout << "Sending x position " << x_position << std::endl; /* Modify the shapesize from 30 to 50 */ retcode = data->set_long( "shapesize", DDS_DYNAMIC_DATA_MEMBER_ID_UNSPECIFIED, 30 + (samples_written % 20)); if (retcode != DDS_RETCODE_OK) { return shutdown_participant( participant, "! Unable to set shapesize", EXIT_FAILURE); } /* Modify the position */ retcode = data->set_long( "x", DDS_DYNAMIC_DATA_MEMBER_ID_UNSPECIFIED, x_position); if (retcode != DDS_RETCODE_OK) { return shutdown_participant( participant, "! Unable to set x", EXIT_FAILURE); } /* The x_position will be modified adding or substracting * 2 to the previous x_position depending on the direction. */ x_position += (direction * 2); /* The x_position will stay between 50 and 150 pixels. * When the position is greater than 150 'direction' will be negative * (moving to the left) and when it is lower than 50 'direction' will * be possitive (moving to the right). */ if (x_position >= 150) { direction = -1; } if (x_position <= 50) { direction = 1; } /* Write data */ retcode = typed_writer->write(*data, DDS_HANDLE_NIL); if (retcode != DDS_RETCODE_OK) { return shutdown_participant( participant, "write error", EXIT_FAILURE); } NDDSUtility::sleep(send_period); } // Delete previously allocated ShapeType, including all contained elements retcode = type_support->delete_data(data); if (retcode != DDS_RETCODE_OK) { std::cerr << "ShapeTypeTypeSupport::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/dynamic_data_using_publisher_subscriber/c/Shapes_subscriber.c
/******************************************************************************* (c) 2005-2014 Copyright, Real-Time Innovations, Inc. All rights reserved. RTI grants Licensee a license to use, modify, compile, and create derivative works of the Software. Licensee has the right to distribute object form only for use with RTI products. The Software is provided "as is", with no warranty of any type, including any warranty for fitness for any purpose. RTI is under no obligation to maintain or support the Software. RTI shall not be liable for any incidental or consequential damages arising out of the use or inability to use the software. ******************************************************************************/ /* Shapes_subscriber.c A subscription of data of type ShapeType using DynamicData This file is derived from code automatically generated by the rtiddsgen command: rtiddsgen -language C -example <arch> Shapes.idl If you are not using and IDL to generate the TypeCode, you will need to create it manually. Follow other DynamicData examples (such as NestedStruct one) to learn how to do it. Example: To run the example application on domain <domain_id>: On UNIX systems: objs/<arch>/Shapes_publisher <domain_id> <sample #> objs/<arch>/Shapes_subscriber <domain_id> <sample #> On Windows systems: objs\<arch>\Shapes_publisher <domain_id> <sample #> objs\<arch>\Shapes_subscriber <domain_id> <sample #> */ #include "Shapes.h" #include "ndds/ndds_c.h" #include <stdio.h> #include <stdlib.h> #define EXAMPLE_TYPE_NAME "ShapesType" void ShapeTypeListener_on_requested_deadline_missed( void *listener_data, DDS_DataReader *reader, const struct DDS_RequestedDeadlineMissedStatus *status) { } void ShapeTypeListener_on_requested_incompatible_qos( void *listener_data, DDS_DataReader *reader, const struct DDS_RequestedIncompatibleQosStatus *status) { } void ShapeTypeListener_on_sample_rejected( void *listener_data, DDS_DataReader *reader, const struct DDS_SampleRejectedStatus *status) { } void ShapeTypeListener_on_liveliness_changed( void *listener_data, DDS_DataReader *reader, const struct DDS_LivelinessChangedStatus *status) { } void ShapeTypeListener_on_sample_lost( void *listener_data, DDS_DataReader *reader, const struct DDS_SampleLostStatus *status) { } void ShapeTypeListener_on_subscription_matched( void *listener_data, DDS_DataReader *reader, const struct DDS_SubscriptionMatchedStatus *status) { } void ShapeTypeListener_on_data_available( void *listener_data, DDS_DataReader *reader) { /* We need to create a DynamicDataReader to receive the DynamicData * and a DynamicDataSeq to store there the available DynamicData received */ DDS_DynamicDataReader *DynamicData_reader = NULL; struct DDS_DynamicDataSeq data_seq = DDS_SEQUENCE_INITIALIZER; struct DDS_SampleInfoSeq info_seq = DDS_SEQUENCE_INITIALIZER; DDS_ReturnCode_t retcode; int i; /* To use DynamicData, we need to assign the generic DataReader to * a DynamicDataReader, using DDS_DynamicDataReader_narrow. * The following narrow fuction should never fail, as it performs * only a safe cast. */ DynamicData_reader = DDS_DynamicDataReader_narrow(reader); if (DynamicData_reader == NULL) { printf("DataReader narrow error\n"); return; } retcode = DDS_DynamicDataReader_take( DynamicData_reader, &data_seq, &info_seq, DDS_LENGTH_UNLIMITED, DDS_ANY_SAMPLE_STATE, DDS_ANY_VIEW_STATE, DDS_ANY_INSTANCE_STATE); if (retcode == DDS_RETCODE_NO_DATA) { return; } else if (retcode != DDS_RETCODE_OK) { printf("take error %d\n", retcode); return; } for (i = 0; i < DDS_DynamicDataSeq_get_length(&data_seq); ++i) { if (DDS_SampleInfoSeq_get_reference(&info_seq, i)->valid_data) { DDS_DynamicData_print( DDS_DynamicDataSeq_get_reference(&data_seq, i), stdout, 1); } } retcode = DDS_DynamicDataReader_return_loan( DynamicData_reader, &data_seq, &info_seq); if (retcode != DDS_RETCODE_OK) { printf("return loan error %d\n", retcode); } DDS_DynamicDataSeq_finalize(&data_seq); DDS_SampleInfoSeq_finalize(&info_seq); } /* Delete all entities */ static int subscriber_shutdown( DDS_DomainParticipant *participant, struct DDS_DynamicDataTypeSupport *typeSupport) { DDS_ReturnCode_t retcode; int status = 0; if (participant != NULL) { if (typeSupport != NULL) { DDS_DynamicDataTypeSupport_delete(typeSupport); } retcode = DDS_DomainParticipant_delete_contained_entities(participant); if (retcode != DDS_RETCODE_OK) { printf("delete_contained_entities error %d\n", retcode); status = -1; } retcode = DDS_DomainParticipantFactory_delete_participant( DDS_TheParticipantFactory, participant); if (retcode != DDS_RETCODE_OK) { printf("delete_participant error %d\n", retcode); status = -1; } } /* RTI Connext provides the finalize_instance() method on * domain participant factory for users who want to release memory used * by the participant factory. Uncomment the following block of code for * clean destruction of the singleton. */ retcode = DDS_DomainParticipantFactory_finalize_instance(); if (retcode != DDS_RETCODE_OK) { printf("finalize_instance error %d\n", retcode); status = -1; } return status; } static int subscriber_main(int domainId, int sample_count) { DDS_DomainParticipant *participant = NULL; DDS_Subscriber *subscriber = NULL; DDS_Topic *topic = NULL; struct DDS_DataReaderListener reader_listener = DDS_DataReaderListener_INITIALIZER; DDS_DataReader *reader = NULL; DDS_ReturnCode_t retcode; const char *type_name = NULL; int count = 0; struct DDS_Duration_t poll_period = { 1, 0 }; /* Dynamic Data parameters that we will need */ struct DDS_TypeCode *type_code = NULL; struct DDS_DynamicDataTypeProperty_t props = DDS_DynamicDataTypeProperty_t_INITIALIZER; struct DDS_DynamicDataTypeSupport *type_support = NULL; participant = DDS_DomainParticipantFactory_create_participant( DDS_TheParticipantFactory, domainId, &DDS_PARTICIPANT_QOS_DEFAULT, NULL /* listener */, DDS_STATUS_MASK_NONE); if (participant == NULL) { printf("create_participant error\n"); subscriber_shutdown(participant, type_support); return -1; } subscriber = DDS_DomainParticipant_create_subscriber( participant, &DDS_SUBSCRIBER_QOS_DEFAULT, NULL /* listener */, DDS_STATUS_MASK_NONE); if (subscriber == NULL) { printf("create_subscriber error\n"); subscriber_shutdown(participant, type_support); return -1; } /* Create DynamicData using TypeCode from Shapes.c * If you are NOT using a type generated with rtiddsgen, you * need to create this TypeCode from scratch. */ type_code = ShapeType_get_typecode(); if (type_code == NULL) { printf("get_typecode error\n"); subscriber_shutdown(participant, type_support); return -1; } /* Create the Dynamic data type support object */ type_support = DDS_DynamicDataTypeSupport_new(type_code, &props); if (type_support == NULL) { fprintf(stderr, "! Unable to create dynamic data type support\n"); subscriber_shutdown(participant, type_support); return -1; } /* Register the type before creating the topic */ type_name = EXAMPLE_TYPE_NAME; retcode = DDS_DynamicDataTypeSupport_register_type( type_support, participant, type_name); if (retcode != DDS_RETCODE_OK) { printf("register_type error %d\n", retcode); subscriber_shutdown(participant, type_support); return -1; } /* Make sure both publisher and subscriber share the same topic name. * In the Shapes example: we are subscribing to a Square, wich is the * topic name. If you want to publish other shapes (Triangle or Circle), * you just need to update the topic name. */ topic = DDS_DomainParticipant_create_topic( participant, "Square", type_name, &DDS_TOPIC_QOS_DEFAULT, NULL /* listener */, DDS_STATUS_MASK_NONE); if (topic == NULL) { printf("create_topic error\n"); subscriber_shutdown(participant, type_support); return -1; } /* Set up a data reader listener */ reader_listener.on_requested_deadline_missed = ShapeTypeListener_on_requested_deadline_missed; reader_listener.on_requested_incompatible_qos = ShapeTypeListener_on_requested_incompatible_qos; reader_listener.on_sample_rejected = ShapeTypeListener_on_sample_rejected; reader_listener.on_liveliness_changed = ShapeTypeListener_on_liveliness_changed; reader_listener.on_sample_lost = ShapeTypeListener_on_sample_lost; reader_listener.on_subscription_matched = ShapeTypeListener_on_subscription_matched; reader_listener.on_data_available = ShapeTypeListener_on_data_available; /* First, we create a generic DataReader for our topic */ reader = DDS_Subscriber_create_datareader( subscriber, DDS_Topic_as_topicdescription(topic), &DDS_DATAREADER_QOS_DEFAULT, &reader_listener, DDS_STATUS_MASK_ALL); if (reader == NULL) { printf("create_datareader error\n"); subscriber_shutdown(participant, type_support); return -1; } /* Main loop */ for (count = 0; (sample_count == 0) || (count < sample_count); ++count) { printf("ShapeType subscriber sleeping for %d sec...\n", poll_period.sec); NDDS_Utility_sleep(&poll_period); } /* Cleanup and delete all entities */ return subscriber_shutdown(participant, type_support); } #if defined(RTI_WINCE) int wmain(int argc, wchar_t **argv) { int domainId = 0; int sample_count = 0; /* infinite loop */ if (argc >= 2) { domainId = _wtoi(argv[1]); } if (argc >= 3) { sample_count = _wtoi(argv[2]); } /* Uncomment this to turn on additional logging NDDS_Config_Logger_set_verbosity_by_category( NDDS_Config_Logger_get_instance(), NDDS_CONFIG_LOG_CATEGORY_API, NDDS_CONFIG_LOG_VERBOSITY_STATUS_ALL); */ return subscriber_main(domainId, sample_count); } #elif !(defined(RTI_VXWORKS) && !defined(__RTP__)) && !defined(RTI_PSOS) int main(int argc, char *argv[]) { int domainId = 0; int sample_count = 0; /* infinite loop */ if (argc >= 2) { domainId = atoi(argv[1]); } if (argc >= 3) { sample_count = atoi(argv[2]); } /* Uncomment this to turn on additional logging NDDS_Config_Logger_set_verbosity_by_category( NDDS_Config_Logger_get_instance(), NDDS_CONFIG_LOG_CATEGORY_API, NDDS_CONFIG_LOG_VERBOSITY_STATUS_ALL); */ return subscriber_main(domainId, sample_count); } #endif #ifdef RTI_VX653 const unsigned char *__ctype = NULL; void usrAppInit() { #ifdef USER_APPL_INIT USER_APPL_INIT; /* for backwards compatibility */ #endif /* add application specific code here */ taskSpawn( "sub", RTI_OSAPI_THREAD_PRIORITY_NORMAL, 0x8, 0x150000, (FUNCPTR) subscriber_main, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0); } #endif
c
rticonnextdds-examples
data/projects/rticonnextdds-examples/connext_dds/dynamic_data_using_publisher_subscriber/c/Shapes_publisher.c
/******************************************************************************* (c) 2005-2014 Copyright, Real-Time Innovations, Inc. All rights reserved. RTI grants Licensee a license to use, modify, compile, and create derivative works of the Software. Licensee has the right to distribute object form only for use with RTI products. The Software is provided "as is", with no warranty of any type, including any warranty for fitness for any purpose. RTI is under no obligation to maintain or support the Software. RTI shall not be liable for any incidental or consequential damages arising out of the use or inability to use the software. ******************************************************************************/ /* Shapes_publisher.c A publication of data of type ShapeType using DynamicData This file is derived from code automatically generated by the rtiddsgen command: rtiddsgen -language C -example <arch> Shapes.idl If you are not using an IDL to generate the TypeCode, you will need to create it manually. Follow other DynamicData examples (such as NestedStruct one) to learn how to do it. Example: To run the example application on domain <domain_id>: On Unix: objs/<arch>/Shapes_publisher <domain_id> <sample #> objs/<arch>/Shapes_subscriber <domain_id> <sample #> On Windows: objs\<arch>\Shapes_publisher <domain_id> <sample #> objs\<arch>\Shapes_subscriber <domain_id> <sample #> */ #include "Shapes.h" #include "ndds/ndds_c.h" #include <stdio.h> #include <stdlib.h> #define EXAMPLE_TYPE_NAME "ShapesType" /* Delete all created entities */ static int publisher_shutdown( DDS_DomainParticipant *participant, struct DDS_DynamicDataTypeSupport *type_support, DDS_Boolean data_is_initialized, struct DDS_DynamicData *data) { DDS_ReturnCode_t retcode; int status = 0; if (participant != NULL) { if (data_is_initialized) { DDS_DynamicData_finalize(data); } if (type_support != NULL) { DDS_DynamicDataTypeSupport_delete(type_support); } retcode = DDS_DomainParticipant_delete_contained_entities(participant); if (retcode != DDS_RETCODE_OK) { printf("delete_contained_entities error %d\n", retcode); status = -1; } retcode = DDS_DomainParticipantFactory_delete_participant( DDS_TheParticipantFactory, participant); if (retcode != DDS_RETCODE_OK) { printf("delete_participant error %d\n", retcode); status = -1; } } /* RTI Connext provides finalize_instance() method on * domain participant factory for people who want to release memory used * by the participant factory. Uncomment the following block of code for * clean destruction of the singleton. */ retcode = DDS_DomainParticipantFactory_finalize_instance(); if (retcode != DDS_RETCODE_OK) { printf("finalize_instance error %d\n", retcode); status = -1; } return status; } static int publisher_main(int domainId, int sample_count) { DDS_ReturnCode_t retcode; DDS_InstanceHandle_t instance_handle = DDS_HANDLE_NIL; const char *type_name = NULL; int count = 0; struct DDS_Duration_t send_period = { 0, 100000000 }; /* 100 ms */ /*** Shape direction variables ***/ int direction = 1; /* 1 means left to right and -1, right to left */ int x_position = 50; /* 50 is the initial position */ /*** DDS ENTITIES ***/ DDS_DomainParticipant *participant = NULL; DDS_Publisher *publisher = NULL; DDS_Topic *topic = NULL; DDS_DataWriter *writer = NULL; /*** Dynamic Data parameters that we will need ***/ struct DDS_TypeCode *type_code = NULL; struct DDS_DynamicData data; DDS_Boolean data_is_initialized = DDS_BOOLEAN_FALSE; DDS_DynamicDataWriter *DynamicData_writer = NULL; struct DDS_DynamicDataTypeProperty_t props = DDS_DynamicDataTypeProperty_t_INITIALIZER; struct DDS_DynamicDataTypeSupport *type_support = NULL; participant = DDS_DomainParticipantFactory_create_participant( DDS_TheParticipantFactory, domainId, &DDS_PARTICIPANT_QOS_DEFAULT, NULL /* listener */, DDS_STATUS_MASK_NONE); if (participant == NULL) { printf("create_participant error\n"); publisher_shutdown( participant, type_support, data_is_initialized, &data); return -1; } publisher = DDS_DomainParticipant_create_publisher( participant, &DDS_PUBLISHER_QOS_DEFAULT, NULL /* listener */, DDS_STATUS_MASK_NONE); if (publisher == NULL) { printf("create_publisher error\n"); publisher_shutdown( participant, type_support, data_is_initialized, &data); return -1; } /* Create DynamicData using TypeCode from Shapes.c * If you are NOT using a type generated with rtiddsgen, you * need to create this TypeCode from scratch. */ type_code = ShapeType_get_typecode(); if (type_code == NULL) { printf("get_typecode error\n"); publisher_shutdown( participant, type_support, data_is_initialized, &data); return -1; } /* Create the Dynamic Data TypeSupport object */ type_support = DDS_DynamicDataTypeSupport_new(type_code, &props); if (type_support == NULL) { fprintf(stderr, "! Unable to create dynamic data type support\n"); publisher_shutdown( participant, type_support, data_is_initialized, &data); return -1; } /* Register the type before creating the topic. */ type_name = EXAMPLE_TYPE_NAME; retcode = DDS_DynamicDataTypeSupport_register_type( type_support, participant, type_name); if (retcode != DDS_RETCODE_OK) { publisher_shutdown( participant, type_support, data_is_initialized, &data); return -1; } /* Make sure both publisher and subscriber share the same topic * name. * In the Shapes example: we are publishing a Square, which is the * topic name. If you want to publish other shapes (Triangle or * Circle), you just need to update the topic name. */ topic = DDS_DomainParticipant_create_topic( participant, "Square", type_name, &DDS_TOPIC_QOS_DEFAULT, NULL /* listener */, DDS_STATUS_MASK_NONE); if (topic == NULL) { printf("create_topic error\n"); publisher_shutdown( participant, type_support, data_is_initialized, &data); return -1; } /* First, we create a generic DataWriter for our topic */ writer = DDS_Publisher_create_datawriter( publisher, topic, &DDS_DATAWRITER_QOS_DEFAULT, NULL /* listener */, DDS_STATUS_MASK_NONE); if (writer == NULL) { printf("create_datawriter error\n"); publisher_shutdown( participant, type_support, data_is_initialized, &data); return -1; } /* Then, to use DynamicData, we need to assign the generic * DataWriter to a DynamicDataWriter, using * DDS_DynamicDataWriter_narrow. * The following narrow function should never fail, as it performs * only a safe cast. */ DynamicData_writer = DDS_DynamicDataWriter_narrow(writer); if (DynamicData_writer == NULL) { fprintf(stderr, "! Unable to narrow data writer into " "DDS_StringDataWriter\n"); publisher_shutdown( participant, type_support, data_is_initialized, &data); return -1; } /* Create an instance of the sparse data we are about to send */ data_is_initialized = DDS_DynamicData_initialize( &data, type_code, &DDS_DYNAMIC_DATA_PROPERTY_DEFAULT); if (!data_is_initialized) { printf("DynamicData_initialize error\n"); publisher_shutdown( participant, type_support, data_is_initialized, &data); return -1; } /* Initialize the DynamicData object */ DDS_DynamicData_set_string( &data, "color", DDS_DYNAMIC_DATA_MEMBER_ID_UNSPECIFIED, "BLUE"); DDS_DynamicData_set_long( &data, "x", DDS_DYNAMIC_DATA_MEMBER_ID_UNSPECIFIED, 0); DDS_DynamicData_set_long( &data, "y", DDS_DYNAMIC_DATA_MEMBER_ID_UNSPECIFIED, 100); DDS_DynamicData_set_long( &data, "shapesize", DDS_DYNAMIC_DATA_MEMBER_ID_UNSPECIFIED, 30); /* Main loop */ for (count = 0; (sample_count == 0) || (count < sample_count); ++count) { printf("Sending shapesize %d\n", 30 + (count % 20)); printf("Sending x position %d\n", x_position); /* Modify the shapesize from 30 to 50 */ retcode = DDS_DynamicData_set_long( &data, "shapesize", DDS_DYNAMIC_DATA_MEMBER_ID_UNSPECIFIED, 30 + (count % 20)); if (retcode != DDS_RETCODE_OK) { fprintf(stderr, "! Unable to set shapesize long\n"); publisher_shutdown( participant, type_support, data_is_initialized, &data); return -1; } /* Modify the position x from 50 to 150 */ retcode = DDS_DynamicData_set_long( &data, "x", DDS_DYNAMIC_DATA_MEMBER_ID_UNSPECIFIED, x_position); if (retcode != DDS_RETCODE_OK) { fprintf(stderr, "! Unable to set x\n"); publisher_shutdown( participant, type_support, data_is_initialized, &data); return -1; } /* The x_position will be modified adding or substracting * 2 to the previous x_position depending on the direction. */ x_position += (direction * 2); /* The x_position will stay between 50 and 150 pixels. * When the position is greater than 150 'direction' will be negative * (moving to the left) and when it is lower than 50 'direction' will * be possitive (moving to the right). */ if (x_position >= 150) { direction = -1; } if (x_position <= 50) { direction = 1; } /* Write data */ retcode = DDS_DynamicDataWriter_write( DynamicData_writer, &data, &instance_handle); if (retcode != DDS_RETCODE_OK) { printf("write error %d\n", retcode); publisher_shutdown( participant, type_support, data_is_initialized, &data); } NDDS_Utility_sleep(&send_period); } /* Cleanup and delete delete all entities */ return publisher_shutdown( participant, type_support, data_is_initialized, &data); } #if defined(RTI_WINCE) int wmain(int argc, wchar_t **argv) { int domainId = 0; int sample_count = 0; /* infinite loop */ if (argc >= 2) { domainId = _wtoi(argv[1]); } if (argc >= 3) { sample_count = _wtoi(argv[2]); } /* Uncomment this to turn on additional logging NDDS_Config_Logger_set_verbosity_by_category( NDDS_Config_Logger_get_instance(), NDDS_CONFIG_LOG_CATEGORY_API, NDDS_CONFIG_LOG_VERBOSITY_STATUS_ALL); */ return publisher_main(domainId, sample_count); } #elif !(defined(RTI_VXWORKS) && !defined(__RTP__)) && !defined(RTI_PSOS) int main(int argc, char *argv[]) { int domainId = 0; int sample_count = 0; /* infinite loop */ if (argc >= 2) { domainId = atoi(argv[1]); } if (argc >= 3) { sample_count = atoi(argv[2]); } /* Uncomment this to turn on additional logging NDDS_Config_Logger_set_verbosity_by_category( NDDS_Config_Logger_get_instance(), NDDS_CONFIG_LOG_CATEGORY_API, NDDS_CONFIG_LOG_VERBOSITY_STATUS_ALL); */ return publisher_main(domainId, sample_count); } #endif #ifdef RTI_VX653 const unsigned char *__ctype = NULL; void usrAppInit() { #ifdef USER_APPL_INIT USER_APPL_INIT; /* for backwards compatibility */ #endif /* add application specific code here */ taskSpawn( "pub", RTI_OSAPI_THREAD_PRIORITY_NORMAL, 0x8, 0x150000, (FUNCPTR) publisher_main, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0); } #endif
c