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/dynamic_data_using_publisher_subscriber/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/dynamic_data_using_publisher_subscriber/c++11/Shapes_subscriber.cxx
/******************************************************************************* (c) 2005-2015 Copyright, Real-Time Innovations, Inc. All rights reserved. RTI grants Licensee a license to use, modify, compile, and create derivative works of the Software. Licensee has the right to distribute object form only for use with RTI products. The Software is provided "as is", with no warranty of any type, including any warranty for fitness for any purpose. RTI is under no obligation to maintain or support the Software. RTI shall not be liable for any incidental or consequential damages arising out of the use or inability to use the software. ******************************************************************************/ #include <dds/sub/ddssub.hpp> #include <dds/core/ddscore.hpp> #include <rti/config/Logger.hpp> // for logging #include <rti/core/xtypes/DynamicDataTuples.hpp> #include "Shapes.hpp" #include "application.hpp" // for command line parsing and ctrl-c void print_shape_data(const dds::core::xtypes::DynamicData &data) { // First method: using C++ tuples (C++11 only). auto shape_tuple_data = rti::core::xtypes:: get_tuple<std::string, int32_t, int32_t, int32_t>(data); std::cout << "\t color: " << std::get<0>(shape_tuple_data) << std::endl << "\t x: " << std::get<1>(shape_tuple_data) << std::endl << "\t y: " << std::get<2>(shape_tuple_data) << std::endl << "\t shapesize: " << std::get<3>(shape_tuple_data) << std::endl; // Second method: using DynamicData getters. std::cout << "\t color: " << data.value<std::string>("color") << std::endl << "\t x: " << data.value<int32_t>("x") << std::endl << "\t y: " << data.value<int32_t>("y") << std::endl << "\t shapesize: " << data.value<int32_t>("shapesize") << std::endl; // Third method: automatic with the '<<' operator overload. std::cout << data << std::endl; } void run_subscriber_application( unsigned int domain_id, unsigned int sample_count) { // Create the participant. dds::domain::DomainParticipant participant(domain_id); // Create DynamicData using the type defined in the IDL file. const dds::core::xtypes::StructType &shape_type = rti::topic::dynamic_type<ShapeType>::get(); // If you want to create the type from code instead of using an IDL // file with rtiddsgen, comment out the previous declaration and // uncomment the following code. // StructType shape_type("ShapeType"); // shape_type.add_member(Member("color", StringType(128)).key(true)); // shape_type.add_member(Member("x", primitive_type<int32_t>())); // shape_type.add_member(Member("y", primitive_type<int32_t>())); // shape_type.add_member(Member("shapesize", primitive_type<int32_t>())); // Create a Topic -- and automatically register the type. // Make sure both publisher and subscriber share the same topic name. // In the Shapes example: we are subscribing to a Square, wich is the // topic name. If you want to publish other shapes (Triangle or Circle), // you just need to update the topic name. dds::topic::Topic<dds::core::xtypes::DynamicData> topic( participant, "Square", shape_type); // Create a subscriber dds::sub::Subscriber subscriber(participant); // Create a DataReader. dds::sub::DataReader<dds::core::xtypes::DynamicData> reader( subscriber, topic); // Create a ReadCondition for any data on this reader and associate // a handler. int count = 0; dds::sub::cond::ReadCondition read_condition( reader, dds::sub::status::DataState::any(), [&reader, &count]() { // Take all samples dds::sub::LoanedSamples<dds::core::xtypes::DynamicData> samples = reader.take(); for (auto sample : samples) { if (sample.info().valid()) { count++; // Print sample with different methods. print_shape_data(sample.data()); } } }); // Create a WaitSet and attach the ReadCondition 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 << "ShapeType subscriber sleeping for 1 sec..." << std::endl; waitset.dispatch(dds::core::Duration(1)); // Wait up to 1s each time } } int main(int argc, char *argv[]) { 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/dynamic_data_using_publisher_subscriber/c++11/Shapes_publisher.cxx
/******************************************************************************* (c) 2005-2015 Copyright, Real-Time Innovations, Inc. All rights reserved. RTI grants Licensee a license to use, modify, compile, and create derivative works of the Software. Licensee has the right to distribute object form only for use with RTI products. The Software is provided "as is", with no warranty of any type, including any warranty for fitness for any purpose. RTI is under no obligation to maintain or support the Software. RTI shall not be liable for any incidental or consequential damages arising out of the use or inability to use the software. ******************************************************************************/ #include <dds/pub/ddspub.hpp> #include <rti/util/util.hpp> // for sleep() #include <rti/config/Logger.hpp> // for logging #include <rti/core/xtypes/DynamicDataTuples.hpp> #include "application.hpp" // for command line parsing and ctrl-c #include "Shapes.hpp" void run_publisher_application( unsigned int domain_id, unsigned int sample_count) { // Create the participant. dds::domain::DomainParticipant participant(domain_id); // Create DynamicData using the type defined in the IDL file. const dds::core::xtypes::StructType &shape_type = rti::topic::dynamic_type<ShapeType>::get(); // If you want to create the type from code instead of using an IDL // file with rtiddsgen, comment out the previous declaration and // uncomment the following code. // StructType shape_type("ShapeType"); // shape_type.add_member(Member("color", StringType(128)).key(true)); // shape_type.add_member(Member("x", primitive_type<int32_t>())); // shape_type.add_member(Member("y", primitive_type<int32_t>())); // shape_type.add_member(Member("shapesize", primitive_type<int32_t>())); // Create a Topic -- and automatically register the type. // Make sure both publisher and subscriber share the same topic // name. In the Shapes example: we are publishing a Square, which is the // topic name. If you want to publish other shapes (Triangle or // Circle), you just need to update the topic name. dds::topic::Topic<dds::core::xtypes::DynamicData> topic( participant, "Square", shape_type); // Create a Publisher dds::pub::Publisher publisher(participant); // Create a DataWriter. dds::pub::DataWriter<dds::core::xtypes::DynamicData> writer( publisher, topic); // Create an instance of DynamicData. dds::core::xtypes::DynamicData shape_data(shape_type); // Initialize the data values. int direction = 1; int x_position = 50; int shape_size = 30; // Set data with C++ tuples (C++11 only). rti::core::xtypes::set_tuple( shape_data, std::make_tuple(std::string("BLUE"), x_position, 100, shape_size)); // Standard method with setters (C++03 compatible). // shape_data.value<std::string>("color", "BLUE"); // shape_data.value("x", x_position); // shape_data.value("y", 100); // shape_data.value("shapesize", shape_size); // Main loop for (unsigned int samples_written = 0; !application::shutdown_requested && samples_written < sample_count; samples_written++) { // Modify and set the shape size from 30 to 50. shape_size = 30 + (samples_written % 20); shape_data.value("shapesize", shape_size); // Set the position X. shape_data.value("x", x_position); // Publish data. std::cout << "Sending [shapesize=" << shape_size << ", x=" << x_position << "]" << std::endl; writer.write(shape_data); // Update the position X. // It will be modified adding or substraction 2 to the previous value // depending on the direction. The value will be between 50 and 150. // When it reachs one border, the direction is inverted. x_position += (direction * 2); if (x_position >= 150) { direction = -1; } else if (x_position <= 50) { direction = 1; } rti::util::sleep(dds::core::Duration::from_millisecs(100)); } } 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/instance_statistics/c++/instance_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 "instance.h" #include "instanceSupport.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(instanceDataReader *typed_reader) { instanceSeq 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; instanceTypeSupport::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 = instanceTypeSupport::get_type_name(); DDS_ReturnCode_t retcode = instanceTypeSupport::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 instance", 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 instance" Topic DDSDataReader *untyped_reader = subscriber->create_datareader( topic, DDS_DATAREADER_QOS_DEFAULT, NULL, DDS_STATUS_MASK_NONE); if (untyped_reader == NULL) { return shutdown_participant(participant, "create_datareader error", EXIT_FAILURE); } // Narrow casts from a untyped DataReader to a reader of your type instanceDataReader *typed_reader = instanceDataReader::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; // 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; } } retcode = untyped_reader->get_datareader_cache_status(status); if (retcode != DDS_RETCODE_OK) { return shutdown_participant( participant, "get_datareader_cache_status error", EXIT_FAILURE); } std::cout << "Instance statistics:" << "\n\t alive_instance_count " << status.alive_instance_count << "\n\t no_writers_instance_count " << status.no_writers_instance_count << "\n\t detached_instance_count " << status.detached_instance_count << "\n\t disposed_instance_count " << status.disposed_instance_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/instance_statistics/c++/instance_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 "instance.h" #include "instanceSupport.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 = instanceTypeSupport::get_type_name(); DDS_ReturnCode_t retcode = instanceTypeSupport::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 instance", 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 instance" 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 instanceDataWriter *typed_writer = instanceDataWriter::narrow(untyped_writer); if (typed_writer == NULL) { return shutdown_participant( participant, "DataWriter narrow error", EXIT_FAILURE); } // Create data for writing, allocating all members instance *data = instanceTypeSupport::create_data(); if (data == NULL) { return shutdown_participant( participant, "instanceTypeSupport::create_data error", EXIT_FAILURE); } // Main loop, write data DDS_InstanceHandle_t instance_handle = DDS_HANDLE_NIL; DDS_DataWriterCacheStatus status; 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 instance, count " << samples_written << std::endl; instance_handle = typed_writer->register_instance(*data); retcode = typed_writer->write(*data, instance_handle); 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); if (samples_written % 2 == 0) { // Unregister the instance retcode = typed_writer->unregister_instance(*data, instance_handle); if (retcode != DDS_RETCODE_OK) { std::cerr << "unregister_instance error " << retcode << std::endl; } } else if (samples_written % 3 == 0) { // Dispose the instance retcode = typed_writer->dispose(*data, instance_handle); if (retcode != DDS_RETCODE_OK) { std::cerr << "dispose instance error " << retcode << std::endl; } } retcode = typed_writer->get_datawriter_cache_status(status); if (retcode != DDS_RETCODE_OK) { return shutdown_participant( participant, "get_datawriter_cache_status error", EXIT_FAILURE); } std::cout << "Instance statistics:" << "\n\t alive_instance_count " << status.alive_instance_count << "\n\t unregistered_instance_count " << status.unregistered_instance_count << "\n\t disposed_instance_count " << status.disposed_instance_count << std::endl; } // Delete previously allocated instance, including all contained elements retcode = instanceTypeSupport::delete_data(data); if (retcode != DDS_RETCODE_OK) { std::cerr << "instanceTypeSupport::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/instance_statistics/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/instance_statistics/c++98/instance_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 "instance.h" #include "instanceSupport.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(instanceDataReader *typed_reader) { instanceSeq 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; instanceTypeSupport::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 = instanceTypeSupport::get_type_name(); DDS_ReturnCode_t retcode = instanceTypeSupport::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 instance", 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 instance" Topic DDSDataReader *untyped_reader = subscriber->create_datareader( topic, DDS_DATAREADER_QOS_DEFAULT, NULL, DDS_STATUS_MASK_NONE); if (untyped_reader == NULL) { return shutdown_participant( participant, "create_datareader error", EXIT_FAILURE); } // Narrow casts from a untyped DataReader to a reader of your type instanceDataReader *typed_reader = instanceDataReader::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; // 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; } } retcode = untyped_reader->get_datareader_cache_status(status); if (retcode != DDS_RETCODE_OK) { return shutdown_participant( participant, "get_datareader_cache_status error", EXIT_FAILURE); } std::cout << "Instance statistics:" << "\n\t alive_instance_count " << status.alive_instance_count << "\n\t no_writers_instance_count " << status.no_writers_instance_count << "\n\t detached_instance_count " << status.detached_instance_count << "\n\t disposed_instance_count " << status.disposed_instance_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/instance_statistics/c++98/instance_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 "instance.h" #include "instanceSupport.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 = instanceTypeSupport::get_type_name(); DDS_ReturnCode_t retcode = instanceTypeSupport::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 instance", 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 instance" 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 instanceDataWriter *typed_writer = instanceDataWriter::narrow(untyped_writer); if (typed_writer == NULL) { return shutdown_participant( participant, "DataWriter narrow error", EXIT_FAILURE); } // Create data for writing, allocating all members instance *data = instanceTypeSupport::create_data(); if (data == NULL) { return shutdown_participant( participant, "instanceTypeSupport::create_data error", EXIT_FAILURE); } // Main loop, write data DDS_InstanceHandle_t instance_handle = DDS_HANDLE_NIL; DDS_DataWriterCacheStatus status; 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 instance, count " << samples_written << std::endl; instance_handle = typed_writer->register_instance(*data); retcode = typed_writer->write(*data, instance_handle); 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); if (samples_written % 2 == 0) { // Unregister the instance retcode = typed_writer->unregister_instance(*data, instance_handle); if (retcode != DDS_RETCODE_OK) { std::cerr << "unregister_instance error " << retcode << std::endl; } } else if (samples_written % 3 == 0) { // Dispose the instance retcode = typed_writer->dispose(*data, instance_handle); if (retcode != DDS_RETCODE_OK) { std::cerr << "dispose instance error " << retcode << std::endl; } } retcode = typed_writer->get_datawriter_cache_status(status); if (retcode != DDS_RETCODE_OK) { return shutdown_participant( participant, "get_datawriter_cache_status error", EXIT_FAILURE); } std::cout << "Instance statistics:" << "\n\t alive_instance_count " << status.alive_instance_count << "\n\t unregistered_instance_count " << status.unregistered_instance_count << "\n\t disposed_instance_count " << status.disposed_instance_count << std::endl; } // Delete previously allocated instance, including all contained elements retcode = instanceTypeSupport::delete_data(data); if (retcode != DDS_RETCODE_OK) { std::cerr << "instanceTypeSupport::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/instance_statistics/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/instance_statistics/c/instance_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. */ /* instance_publisher.c A publication of data of type instance This file is derived from code automatically generated by the rtiddsgen command: rtiddsgen -language C -example <arch> instance.idl Example publication of type instance 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 "instance.h" #include "instanceSupport.h" /* Delete all entities */ static int publisher_shutdown( DDS_DomainParticipant *participant) { DDS_ReturnCode_t retcode; int status = 0; if (participant != NULL) { retcode = DDS_DomainParticipant_delete_contained_entities(participant); if (retcode != DDS_RETCODE_OK) { fprintf(stderr, "delete_contained_entities error %d\n", retcode); status = -1; } retcode = DDS_DomainParticipantFactory_delete_participant( DDS_TheParticipantFactory, participant); if (retcode != DDS_RETCODE_OK) { fprintf(stderr, "delete_participant error %d\n", retcode); status = -1; } } /* RTI Data Distribution Service provides finalize_instance() method on domain participant factory for people who want to release memory used by the participant factory. Uncomment the following block of code for clean destruction of the singleton. */ /* retcode = DDS_DomainParticipantFactory_finalize_instance(); if (retcode != DDS_RETCODE_OK) { fprintf(stderr, "finalize_instance error %d\n", retcode); status = -1; } */ return status; } int publisher_main(int domainId, int sample_count) { DDS_DomainParticipant *participant = NULL; DDS_Publisher *publisher = NULL; DDS_Topic *topic = NULL; DDS_DataWriter *writer = NULL; instanceDataWriter *instance_writer = NULL; instance *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_DataWriterCacheStatus cache_status = DDS_DataWriterCacheStatus_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); return -1; } /* To customize publisher QoS, use the configuration file USER_QOS_PROFILES.xml */ publisher = DDS_DomainParticipant_create_publisher( participant, &DDS_PUBLISHER_QOS_DEFAULT, NULL /* listener */, DDS_STATUS_MASK_NONE); if (publisher == NULL) { fprintf(stderr, "create_publisher error\n"); publisher_shutdown(participant); return -1; } /* Register type before creating topic */ type_name = instanceTypeSupport_get_type_name(); retcode = instanceTypeSupport_register_type( participant, type_name); if (retcode != DDS_RETCODE_OK) { fprintf(stderr, "register_type error %d\n", retcode); publisher_shutdown(participant); return -1; } /* To customize topic QoS, use the configuration file USER_QOS_PROFILES.xml */ topic = DDS_DomainParticipant_create_topic( participant, "Example instance", type_name, &DDS_TOPIC_QOS_DEFAULT, NULL /* listener */, DDS_STATUS_MASK_NONE); if (topic == NULL) { fprintf(stderr, "create_topic error\n"); publisher_shutdown(participant); return -1; } /* To customize data writer QoS, use the configuration file USER_QOS_PROFILES.xml */ writer = DDS_Publisher_create_datawriter( publisher, topic, &DDS_DATAWRITER_QOS_DEFAULT, NULL /* listener */, DDS_STATUS_MASK_NONE); if (writer == NULL) { fprintf(stderr, "create_datawriter error\n"); publisher_shutdown(participant); return -1; } instance_writer = instanceDataWriter_narrow(writer); if (instance_writer == NULL) { fprintf(stderr, "DataWriter narrow error\n"); publisher_shutdown(participant); return -1; } /* Create data sample for writing */ instance = instanceTypeSupport_create_data_ex(DDS_BOOLEAN_TRUE); if (instance == NULL) { fprintf(stderr, "instanceTypeSupport_create_data error\n"); publisher_shutdown(participant); return -1; } /* Main loop */ for (count=0; (sample_count == 0) || (count < sample_count); ++count) { printf("Writing instance, count %d\n", count); /* Modify the data to be written here */ instance->x = count; /* register the keyed instance prior to writing */ instance_handle = instanceDataWriter_register_instance( instance_writer, instance); /* Write data */ retcode = instanceDataWriter_write( instance_writer, instance, &instance_handle); if (retcode != DDS_RETCODE_OK) { fprintf(stderr, "write error %d\n", retcode); } NDDS_Utility_sleep(&send_period); if (count % 2 == 0) { /* Unregister the instance */ retcode = instanceDataWriter_unregister_instance( instance_writer, instance, &instance_handle); if (retcode != DDS_RETCODE_OK) { fprintf(stderr, "unregister instance error %d\n", retcode); } } else if (count % 3 == 0) { /* Dispose the instance */ retcode = instanceDataWriter_dispose( instance_writer, instance, &instance_handle); if (retcode != DDS_RETCODE_OK) { fprintf(stderr, "unregister instance error %d\n", retcode); } } retcode = DDS_DataWriter_get_datawriter_cache_status( writer, &cache_status); if (retcode != DDS_RETCODE_OK) { fprintf(stderr, "get_datawriter_cache_status error\n"); publisher_shutdown(participant); return -1; } printf("Instance statistics:\n" "\t alive_instance_count %lld\n" "\t unregistered_instance_count %lld\n" "\t disposed_instance_count %lld\n", cache_status.alive_instance_count, cache_status.unregistered_instance_count, cache_status.disposed_instance_count); } /* Delete data sample */ retcode = instanceTypeSupport_delete_data_ex(instance, DDS_BOOLEAN_TRUE); if (retcode != DDS_RETCODE_OK) { fprintf(stderr, "instanceTypeSupport_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/instance_statistics/c/instance_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. */ /* instance_subscriber.c A subscription example This file is derived from code automatically generated by the rtiddsgen command: rtiddsgen -language C -example <arch> instance.idl Example subscription of type instance 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 "instance.h" #include "instanceSupport.h" void instanceListener_on_requested_deadline_missed( void* listener_data, DDS_DataReader* reader, const struct DDS_RequestedDeadlineMissedStatus *status) { } void instanceListener_on_requested_incompatible_qos( void* listener_data, DDS_DataReader* reader, const struct DDS_RequestedIncompatibleQosStatus *status) { } void instanceListener_on_sample_rejected( void* listener_data, DDS_DataReader* reader, const struct DDS_SampleRejectedStatus *status) { } void instanceListener_on_liveliness_changed( void* listener_data, DDS_DataReader* reader, const struct DDS_LivelinessChangedStatus *status) { } void instanceListener_on_sample_lost( void* listener_data, DDS_DataReader* reader, const struct DDS_SampleLostStatus *status) { } void instanceListener_on_subscription_matched( void* listener_data, DDS_DataReader* reader, const struct DDS_SubscriptionMatchedStatus *status) { } void instanceListener_on_data_available( void* listener_data, DDS_DataReader* reader) { instanceDataReader *instance_reader = NULL; struct instanceSeq data_seq = DDS_SEQUENCE_INITIALIZER; struct DDS_SampleInfoSeq info_seq = DDS_SEQUENCE_INITIALIZER; DDS_ReturnCode_t retcode; int i; instance_reader = instanceDataReader_narrow(reader); if (instance_reader == NULL) { fprintf(stderr, "DataReader narrow error\n"); return; } retcode = instanceDataReader_take( instance_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 < instanceSeq_get_length(&data_seq); ++i) { if (DDS_SampleInfoSeq_get_reference(&info_seq, i)->valid_data) { printf("Received data\n"); instanceTypeSupport_print_data( instanceSeq_get_reference(&data_seq, i)); } } retcode = instanceDataReader_return_loan( instance_reader, &data_seq, &info_seq); if (retcode != DDS_RETCODE_OK) { fprintf(stderr, "return loan error %d\n", retcode); } } /* Delete all entities */ static int subscriber_shutdown( DDS_DomainParticipant *participant) { DDS_ReturnCode_t retcode; int status = 0; if (participant != NULL) { retcode = DDS_DomainParticipant_delete_contained_entities(participant); if (retcode != DDS_RETCODE_OK) { fprintf(stderr, "delete_contained_entities error %d\n", retcode); status = -1; } retcode = DDS_DomainParticipantFactory_delete_participant( DDS_TheParticipantFactory, participant); if (retcode != DDS_RETCODE_OK) { fprintf(stderr, "delete_participant error %d\n", retcode); status = -1; } } /* RTI Data Distribution Service provides the finalize_instance() method on domain participant factory for users who want to release memory used by the participant factory. Uncomment the following block of code for clean destruction of the singleton. */ /* retcode = DDS_DomainParticipantFactory_finalize_instance(); if (retcode != DDS_RETCODE_OK) { fprintf(stderr, "finalize_instance error %d\n", retcode); status = -1; } */ return status; } 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_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); return -1; } /* To customize subscriber QoS, use the configuration file USER_QOS_PROFILES.xml */ subscriber = DDS_DomainParticipant_create_subscriber( participant, &DDS_SUBSCRIBER_QOS_DEFAULT, NULL /* listener */, DDS_STATUS_MASK_NONE); if (subscriber == NULL) { fprintf(stderr, "create_subscriber error\n"); subscriber_shutdown(participant); return -1; } /* Register the type before creating the topic */ type_name = instanceTypeSupport_get_type_name(); retcode = instanceTypeSupport_register_type(participant, type_name); if (retcode != DDS_RETCODE_OK) { fprintf(stderr, "register_type error %d\n", retcode); subscriber_shutdown(participant); return -1; } /* To customize topic QoS, use the configuration file USER_QOS_PROFILES.xml */ topic = DDS_DomainParticipant_create_topic( participant, "Example instance", type_name, &DDS_TOPIC_QOS_DEFAULT, NULL /* listener */, DDS_STATUS_MASK_NONE); if (topic == NULL) { fprintf(stderr, "create_topic error\n"); subscriber_shutdown(participant); return -1; } /* Set up a data reader listener */ reader_listener.on_requested_deadline_missed = instanceListener_on_requested_deadline_missed; reader_listener.on_requested_incompatible_qos = instanceListener_on_requested_incompatible_qos; reader_listener.on_sample_rejected = instanceListener_on_sample_rejected; reader_listener.on_liveliness_changed = instanceListener_on_liveliness_changed; reader_listener.on_sample_lost = instanceListener_on_sample_lost; reader_listener.on_subscription_matched = instanceListener_on_subscription_matched; reader_listener.on_data_available = instanceListener_on_data_available; /* To customize data reader QoS, use the configuration file USER_QOS_PROFILES.xml */ reader = DDS_Subscriber_create_datareader( subscriber, DDS_Topic_as_topicdescription(topic), &DDS_DATAREADER_QOS_DEFAULT, &reader_listener, DDS_STATUS_MASK_ALL); if (reader == NULL) { fprintf(stderr, "create_datareader error\n"); subscriber_shutdown(participant); return -1; } /* Main loop */ for (count=0; (sample_count == 0) || (count < sample_count); ++count) { printf("instance 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); return -1; } printf("Instance statistics:\n" "\t alive_instance_count %lld\n" "\t no_writers_instance_count %lld\n" "\t detached_instance_count %lld\n" "\t disposed_instance_count %lld\n", cache_status.alive_instance_count, cache_status.no_writers_instance_count, cache_status.detached_instance_count, cache_status.disposed_instance_count); } /* 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 */ 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/instance_statistics/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/instance_statistics/c++11/instance_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 "instance.hpp" #include "application.hpp" // for command line parsing and ctrl-c int process_data(dds::sub::DataReader<instance> reader) { // Take all samples int count = 0; dds::sub::LoanedSamples<instance> 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<instance> topic(participant, "Example instance"); // Create a Subscriber and DataReader with default Qos dds::sub::Subscriber subscriber(participant); dds::sub::DataReader<instance> 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; rti::core::status::DataReaderCacheStatus status; while (!application::shutdown_requested && samples_read < sample_count) { std::cout << "instance 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)); status = reader.extensions().datareader_cache_status(); std::cout << "Instance statistics:" << "\n\t alive_instance_count " << status.alive_instance_count() << "\n\t no_writers_instance_count " << status.no_writers_instance_count() << "\n\t detached_instance_count " << status.detached_instance_count() << "\n\t disposed_instance_count " << status.disposed_instance_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/instance_statistics/c++11/instance_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 "instance.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<instance> topic(participant, "Example instance"); // Create a Publisher dds::pub::Publisher publisher(participant); // Create a DataWriter with default QoS dds::pub::DataWriter<instance> writer(publisher, topic); instance data; dds::core::InstanceHandle instance_handle = dds::core::InstanceHandle::nil(); rti::core::status::DataWriterCacheStatus status; 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 instance, count " << samples_written << std::endl; instance_handle = writer.register_instance(data); writer.write(data, instance_handle); // Send once every second rti::util::sleep(dds::core::Duration(1)); if (samples_written % 2 == 0) { /* Unregister the instance */ writer.unregister_instance(instance_handle); } else if (samples_written % 3 == 0) { /* Dispose the instance */ writer.dispose_instance(instance_handle); } status = writer.extensions().datawriter_cache_status(); std::cout << "Instance statistics:" << "\n\t alive_instance_count " << status.alive_instance_count() << "\n\t unregistered_instance_count " << status.unregistered_instance_count() << "\n\t disposed_instance_count " << status.disposed_instance_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_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/polling_read/c++/poll_publisher.cxx
/******************************************************************************* (c) 2005-2014 Copyright, Real-Time Innovations, Inc. All rights reserved. RTI grants Licensee a license to use, modify, compile, and create derivative works of the Software. Licensee has the right to distribute object form only for use with RTI products. The Software is provided "as is", with no warranty of any type, including any warranty for fitness for any purpose. RTI is under no obligation to maintain or support the Software. RTI shall not be liable for any incidental or consequential damages arising out of the use or inability to use the software. ******************************************************************************/ /* poll_publisher.cxx A publication of data of type poll This file is derived from code automatically generated by the rtiddsgen command: rtiddsgen -language C++ -example <arch> poll.idl Example publication of type poll automatically generated by 'rtiddsgen'. To test them follow these steps: (1) Compile this file and the example subscription. (2) Start the subscription with the command objs/<arch>/poll_subscriber <domain_id> <sample_count> (3) Start the publication with the command objs/<arch>/poll_publisher <domain_id> <sample_count> (4) [Optional] Specify the list of discovery initial peers and multicast receive addresses via an environment variable or a file (in the current working directory) called NDDS_DISCOVERY_PEERS. You can run any number of publishers and subscribers programs, and can add and remove them dynamically from the domain. Example: To run the example application on domain <domain_id>: On Unix: objs/<arch>/poll_publisher <domain_id> o objs/<arch>/poll_subscriber <domain_id> On Windows: objs\<arch>\poll_publisher <domain_id> objs\<arch>\poll_subscriber <domain_id> modification history ------------ ------- */ #include <stdio.h> #include <stdlib.h> #ifdef RTI_VX653 #include <vThreadsData.h> #endif #include "ndds/ndds_cpp.h" #include "poll.h" #include "pollSupport.h" #include <ctime> /* Delete all entities */ static int publisher_shutdown(DDSDomainParticipant *participant) { DDS_ReturnCode_t retcode; int status = 0; if (participant != NULL) { retcode = participant->delete_contained_entities(); if (retcode != DDS_RETCODE_OK) { printf("delete_contained_entities error %d\n", retcode); status = -1; } retcode = DDSTheParticipantFactory->delete_participant(participant); if (retcode != DDS_RETCODE_OK) { printf("delete_participant error %d\n", retcode); status = -1; } } /* RTI Connext provides finalize_instance() method on domain participant factory for people who want to release memory used by the participant factory. Uncomment the following block of code for clean destruction of the singleton. */ /* retcode = DDSDomainParticipantFactory::finalize_instance(); if (retcode != DDS_RETCODE_OK) { printf("finalize_instance error %d\n", retcode); status = -1; } */ return status; } extern "C" int publisher_main(int domainId, int sample_count) { DDSDomainParticipant *participant = NULL; DDSPublisher *publisher = NULL; DDSTopic *topic = NULL; DDSDataWriter *writer = NULL; pollDataWriter *poll_writer = NULL; poll *instance = NULL; DDS_ReturnCode_t retcode; DDS_InstanceHandle_t instance_handle = DDS_HANDLE_NIL; const char *type_name = NULL; int count = 0; /* Send a new sample every second */ DDS_Duration_t send_period = { 1, 0 }; /* To customize participant QoS, use the configuration file USER_QOS_PROFILES.xml */ participant = DDSTheParticipantFactory->create_participant( domainId, DDS_PARTICIPANT_QOS_DEFAULT, NULL /* listener */, DDS_STATUS_MASK_NONE); if (participant == NULL) { printf("create_participant error\n"); publisher_shutdown(participant); return -1; } /* To customize publisher QoS, use the configuration file USER_QOS_PROFILES.xml */ publisher = participant->create_publisher( DDS_PUBLISHER_QOS_DEFAULT, NULL /* listener */, DDS_STATUS_MASK_NONE); if (publisher == NULL) { printf("create_publisher error\n"); publisher_shutdown(participant); return -1; } /* Register type before creating topic */ type_name = pollTypeSupport::get_type_name(); retcode = pollTypeSupport::register_type(participant, type_name); if (retcode != DDS_RETCODE_OK) { printf("register_type error %d\n", retcode); publisher_shutdown(participant); return -1; } /* To customize topic QoS, use the configuration file USER_QOS_PROFILES.xml */ topic = participant->create_topic( "Example poll", type_name, DDS_TOPIC_QOS_DEFAULT, NULL /* listener */, DDS_STATUS_MASK_NONE); if (topic == NULL) { printf("create_topic error\n"); publisher_shutdown(participant); return -1; } /* To customize data writer QoS, use the configuration file USER_QOS_PROFILES.xml */ writer = publisher->create_datawriter( topic, DDS_DATAWRITER_QOS_DEFAULT, NULL /* listener */, DDS_STATUS_MASK_NONE); if (writer == NULL) { printf("create_datawriter error\n"); publisher_shutdown(participant); return -1; } poll_writer = pollDataWriter::narrow(writer); if (poll_writer == NULL) { printf("DataWriter narrow error\n"); publisher_shutdown(participant); return -1; } /* Create data sample for writing */ instance = pollTypeSupport::create_data(); if (instance == NULL) { printf("pollTypeSupport::create_data error\n"); publisher_shutdown(participant); return -1; } /* For a data type that has a key, if the same instance is going to be written multiple times, initialize the key here and register the keyed instance prior to writing */ /* instance_handle = poll_writer->register_instance(*instance); */ /* Initialize random seed before entering the loop */ srand(time(NULL)); /* Main loop */ for (count = 0; (sample_count == 0) || (count < sample_count); ++count) { /* Modify the data to be written here */ /* Set x to a random number between 0 and 9 */ instance->x = (int) (rand() / (RAND_MAX / 10.0)); printf("Writing poll, count %d, x = %d\n", count, instance->x); retcode = poll_writer->write(*instance, instance_handle); if (retcode != DDS_RETCODE_OK) { printf("write error %d\n", retcode); } NDDSUtility::sleep(send_period); } /* retcode = poll_writer->unregister_instance( *instance, instance_handle); if (retcode != DDS_RETCODE_OK) { printf("unregister instance error %d\n", retcode); } */ /* Delete data sample */ retcode = pollTypeSupport::delete_data(instance); if (retcode != DDS_RETCODE_OK) { printf("pollTypeSupport::delete_data error %d\n", retcode); } /* Delete all entities */ return publisher_shutdown(participant); } #if defined(RTI_WINCE) int wmain(int argc, wchar_t **argv) { int domainId = 0; int sample_count = 0; /* infinite loop */ if (argc >= 2) { domainId = _wtoi(argv[1]); } if (argc >= 3) { sample_count = _wtoi(argv[2]); } /* Uncomment this to turn on additional logging NDDSConfigLogger::get_instance()-> set_verbosity_by_category(NDDS_CONFIG_LOG_CATEGORY_API, NDDS_CONFIG_LOG_VERBOSITY_STATUS_ALL); */ return publisher_main(domainId, sample_count); } #elif !(defined(RTI_VXWORKS) && !defined(__RTP__)) && !defined(RTI_PSOS) int main(int argc, char *argv[]) { int domainId = 0; int sample_count = 0; /* infinite loop */ if (argc >= 2) { domainId = atoi(argv[1]); } if (argc >= 3) { sample_count = atoi(argv[2]); } /* Uncomment this to turn on additional logging NDDSConfigLogger::get_instance()-> set_verbosity_by_category(NDDS_CONFIG_LOG_CATEGORY_API, NDDS_CONFIG_LOG_VERBOSITY_STATUS_ALL); */ return publisher_main(domainId, sample_count); } #endif #ifdef RTI_VX653 const unsigned char *__ctype = *(__ctypePtrGet()); extern "C" void usrAppInit() { #ifdef USER_APPL_INIT USER_APPL_INIT; /* for backwards compatibility */ #endif /* add application specific code here */ taskSpawn( "pub", RTI_OSAPI_THREAD_PRIORITY_NORMAL, 0x8, 0x150000, (FUNCPTR) publisher_main, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0); } #endif
cxx
rticonnextdds-examples
data/projects/rticonnextdds-examples/connext_dds/polling_read/c++/poll_subscriber.cxx
/******************************************************************************* (c) 2005-2014 Copyright, Real-Time Innovations, Inc. All rights reserved. RTI grants Licensee a license to use, modify, compile, and create derivative works of the Software. Licensee has the right to distribute object form only for use with RTI products. The Software is provided "as is", with no warranty of any type, including any warranty for fitness for any purpose. RTI is under no obligation to maintain or support the Software. RTI shall not be liable for any incidental or consequential damages arising out of the use or inability to use the software. ******************************************************************************/ /* poll_subscriber.cxx A subscription example This file is derived from code automatically generated by the rtiddsgen command: rtiddsgen -language C++ -example <arch> poll.idl Example subscription of type poll automatically generated by 'rtiddsgen'. To test them follow these steps: (1) Compile this file and the example publication. (2) Start the subscription with the command objs/<arch>/poll_subscriber <domain_id> <sample_count> (3) Start the publication with the command objs/<arch>/poll_publisher <domain_id> <sample_count> (4) [Optional] Specify the list of discovery initial peers and multicast receive addresses via an environment variable or a file (in the current working directory) called NDDS_DISCOVERY_PEERS. You can run any number of publishers and subscribers programs, and can add and remove them dynamically from the domain. Example: To run the example application on domain <domain_id>: On Unix: objs/<arch>/poll_publisher <domain_id> objs/<arch>/poll_subscriber <domain_id> On Windows: objs\<arch>\poll_publisher <domain_id> objs\<arch>\poll_subscriber <domain_id> modification history ------------ ------- */ #include <stdio.h> #include <stdlib.h> #ifdef RTI_VX653 #include <vThreadsData.h> #endif #include "ndds/ndds_cpp.h" #include "poll.h" #include "pollSupport.h" /* We remove all the listener code as we won't use any listener */ /* Delete all entities */ static int subscriber_shutdown(DDSDomainParticipant *participant) { DDS_ReturnCode_t retcode; int status = 0; if (participant != NULL) { retcode = participant->delete_contained_entities(); if (retcode != DDS_RETCODE_OK) { printf("delete_contained_entities error %d\n", retcode); status = -1; } retcode = DDSTheParticipantFactory->delete_participant(participant); if (retcode != DDS_RETCODE_OK) { printf("delete_participant error %d\n", retcode); status = -1; } } /* RTI Connext provides the finalize_instance() method on domain participant factory for people who want to release memory used by the participant factory. Uncomment the following block of code for clean destruction of the singleton. */ /* retcode = DDSDomainParticipantFactory::finalize_instance(); if (retcode != DDS_RETCODE_OK) { printf("finalize_instance error %d\n", retcode); status = -1; } */ return status; } extern "C" int subscriber_main(int domainId, int sample_count) { DDSDomainParticipant *participant = NULL; DDSSubscriber *subscriber = NULL; DDSTopic *topic = NULL; DDSDataReader *reader = NULL; DDS_ReturnCode_t retcode; const char *type_name = NULL; int count = 0; /* Poll for new samples every 5 seconds */ DDS_Duration_t receive_period = { 5, 0 }; int status = 0; /* To customize the participant QoS, use the configuration file USER_QOS_PROFILES.xml */ participant = DDSTheParticipantFactory->create_participant( domainId, DDS_PARTICIPANT_QOS_DEFAULT, NULL /* listener */, DDS_STATUS_MASK_NONE); if (participant == NULL) { printf("create_participant error\n"); subscriber_shutdown(participant); return -1; } /* To customize the subscriber QoS, use the configuration file USER_QOS_PROFILES.xml */ subscriber = participant->create_subscriber( DDS_SUBSCRIBER_QOS_DEFAULT, NULL /* listener */, DDS_STATUS_MASK_NONE); if (subscriber == NULL) { printf("create_subscriber error\n"); subscriber_shutdown(participant); return -1; } /* Register the type before creating the topic */ type_name = pollTypeSupport::get_type_name(); retcode = pollTypeSupport::register_type(participant, type_name); if (retcode != DDS_RETCODE_OK) { printf("register_type error %d\n", retcode); subscriber_shutdown(participant); return -1; } /* To customize the topic QoS, use the configuration file USER_QOS_PROFILES.xml */ topic = participant->create_topic( "Example poll", type_name, DDS_TOPIC_QOS_DEFAULT, NULL /* listener */, DDS_STATUS_MASK_NONE); if (topic == NULL) { printf("create_topic error\n"); subscriber_shutdown(participant); return -1; } /* Call create_datareader passing NULL in the listener parameter */ reader = subscriber->create_datareader( topic, DDS_DATAREADER_QOS_DEFAULT, NULL, DDS_STATUS_MASK_ALL); if (reader == NULL) { printf("create_datareader error\n"); subscriber_shutdown(participant); return -1; } /* If you want to change datareader_qos.history.kind programmatically rather * than using the XML file, you will need to add the following lines to your * code and comment out the create_datareader call above. */ /* DDS_DataReaderQos datareader_qos; retcode = subscriber->get_default_datareader_qos(datareader_qos); if (retcode != DDS_RETCODE_OK) { printf("get_default_datareader_qos error\n"); return -1; } datareader_qos.history.kind = DDS_KEEP_ALL_HISTORY_QOS; reader = subscriber->create_datareader( topic, datareader_qos, NULL, DDS_STATUS_MASK_ALL); if (reader == NULL) { printf("create_datareader error\n"); subscriber_shutdown(participant); return -1; } */ pollDataReader *poll_reader = pollDataReader::narrow(reader); if (poll_reader == NULL) { printf("DataReader narrow error\n"); return -1; } /* Main loop */ for (count = 0; (sample_count == 0) || (count < sample_count); ++count) { NDDSUtility::sleep(receive_period); DDS_SampleInfoSeq info_seq; pollSeq data_seq; /* Check for new data calling the DataReader's take() method */ retcode = poll_reader->take( data_seq, info_seq, DDS_LENGTH_UNLIMITED, DDS_ANY_SAMPLE_STATE, DDS_ANY_VIEW_STATE, DDS_ANY_INSTANCE_STATE); if (retcode == DDS_RETCODE_NO_DATA) { /// Not an error continue; } else if (retcode != DDS_RETCODE_OK) { // Is an error printf("take error: %d\n", retcode); continue; } int len = 0; double sum = 0; /* Iterate through the samples read using the take() method, getting * the number of samples got and, adding the value of x on each of * them to calculate the average afterwards. */ for (int i = 0; i < data_seq.length(); ++i) { if (!info_seq[i].valid_data) continue; len++; sum += data_seq[i].x; } if (len > 0) printf("Got %d samples. Avg = %.1f\n", len, sum / len); retcode = poll_reader->return_loan(data_seq, info_seq); if (retcode != DDS_RETCODE_OK) { printf("return loan error %d\n", retcode); } } /* Delete all entities */ status = subscriber_shutdown(participant); return status; } #if defined(RTI_WINCE) int wmain(int argc, wchar_t **argv) { int domainId = 0; int sample_count = 0; /* infinite loop */ if (argc >= 2) { domainId = _wtoi(argv[1]); } if (argc >= 3) { sample_count = _wtoi(argv[2]); } /* Uncomment this to turn on additional logging NDDSConfigLogger::get_instance()-> set_verbosity_by_category(NDDS_CONFIG_LOG_CATEGORY_API, NDDS_CONFIG_LOG_VERBOSITY_STATUS_ALL); */ return subscriber_main(domainId, sample_count); } #elif !(defined(RTI_VXWORKS) && !defined(__RTP__)) && !defined(RTI_PSOS) int main(int argc, char *argv[]) { int domainId = 0; int sample_count = 0; /* infinite loop */ if (argc >= 2) { domainId = atoi(argv[1]); } if (argc >= 3) { sample_count = atoi(argv[2]); } /* Uncomment this to turn on additional logging NDDSConfigLogger::get_instance()-> set_verbosity_by_category(NDDS_CONFIG_LOG_CATEGORY_API, NDDS_CONFIG_LOG_VERBOSITY_STATUS_ALL); */ return subscriber_main(domainId, sample_count); } #endif #ifdef RTI_VX653 const unsigned char *__ctype = *(__ctypePtrGet()); extern "C" void usrAppInit() { #ifdef USER_APPL_INIT USER_APPL_INIT; /* for backwards compatibility */ #endif /* add application specific code here */ taskSpawn( "sub", RTI_OSAPI_THREAD_PRIORITY_NORMAL, 0x8, 0x150000, (FUNCPTR) subscriber_main, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0); } #endif
cxx
rticonnextdds-examples
data/projects/rticonnextdds-examples/connext_dds/polling_read/c++98/poll_publisher.cxx
/******************************************************************************* (c) 2005-2014 Copyright, Real-Time Innovations, Inc. All rights reserved. RTI grants Licensee a license to use, modify, compile, and create derivative works of the Software. Licensee has the right to distribute object form only for use with RTI products. The Software is provided "as is", with no warranty of any type, including any warranty for fitness for any purpose. RTI is under no obligation to maintain or support the Software. RTI shall not be liable for any incidental or consequential damages arising out of the use or inability to use the software. ******************************************************************************/ #include <iostream> #include <stdio.h> #include <stdlib.h> #include "poll.h" #include "pollSupport.h" #include "ndds/ndds_cpp.h" #include "application.h" #include <ctime> 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 = pollTypeSupport::get_type_name(); DDS_ReturnCode_t retcode = pollTypeSupport::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 poll", 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 poll" 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); } pollDataWriter *typed_writer = pollDataWriter::narrow(untyped_writer); if (typed_writer == NULL) { return shutdown_participant( participant, "DataWriter narrow error", EXIT_FAILURE); } /* Create data sample for writing */ poll *data = pollTypeSupport::create_data(); if (data == NULL) { return shutdown_participant( participant, "pollTypeSupport::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); */ /* Initialize random seed before entering the loop */ srand(time(NULL)); // 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 */ /* Set x to a random number between 0 and 9 */ data->x = (int) (rand() / (RAND_MAX / 10.0)); std::cout << "Writing poll, count " << samples_written << ", x = " << 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 = poll_writer->unregister_instance( *instance, instance_handle); if (retcode != DDS_RETCODE_OK) { printf("unregister instance error %d\n", retcode); } */ /* Delete data sample */ retcode = pollTypeSupport::delete_data(data); if (retcode != DDS_RETCODE_OK) { std::cerr << "pollTypeSupport::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/polling_read/c++98/poll_subscriber.cxx
/******************************************************************************* (c) 2005-2014 Copyright, Real-Time Innovations, Inc. All rights reserved. RTI grants Licensee a license to use, modify, compile, and create derivative works of the Software. Licensee has the right to distribute object form only for use with RTI products. The Software is provided "as is", with no warranty of any type, including any warranty for fitness for any purpose. RTI is under no obligation to maintain or support the Software. RTI shall not be liable for any incidental or consequential damages arising out of the use or inability to use the software. ******************************************************************************/ #include <iostream> #include <stdio.h> #include <stdlib.h> #include "poll.h" #include "pollSupport.h" #include "ndds/ndds_cpp.h" #include "application.h" using namespace application; static int shutdown_participant( DDSDomainParticipant *participant, const char *shutdown_message, int status); /* We remove all the listener code as we won't use any listener */ int run_subscriber_application( unsigned int domain_id, unsigned int sample_count) { /* Poll for new samples every 5 seconds */ DDS_Duration_t receive_period = { 5, 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 = pollTypeSupport::get_type_name(); DDS_ReturnCode_t retcode = pollTypeSupport::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 poll", 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 poll" Topic DDSDataReader *untyped_reader = subscriber->create_datareader( topic, DDS_DATAREADER_QOS_DEFAULT, NULL, DDS_STATUS_MASK_ALL); if (untyped_reader == NULL) { return shutdown_participant( participant, "create_datareader error", EXIT_FAILURE); } /* If you want to change datareader_qos.history.kind programmatically rather * than using the XML file, you will need to add the following lines to your * code and comment out the create_datareader call above. */ /* DDS_DataReaderQos datareader_qos; retcode = subscriber->get_default_datareader_qos(datareader_qos); if (retcode != DDS_RETCODE_OK) { return shutdown_participant( participant, "get_default_datareader_qos error", EXIT_FAILURE); } datareader_qos.history.kind = DDS_KEEP_ALL_HISTORY_QOS; DDSDataReader *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); } */ pollDataReader *typed_reader = pollDataReader::narrow(untyped_reader); if (typed_reader == NULL) { return shutdown_participant( participant, "DataReader narrow error", EXIT_FAILURE); } // Main loop. Wait for data to arrive, and process when it arrives unsigned int samples_read = 0; while (!shutdown_requested && samples_read < sample_count) { NDDSUtility::sleep(receive_period); DDS_SampleInfoSeq info_seq; pollSeq data_seq; /* Check for new data calling the DataReader's take() method */ retcode = typed_reader->take( data_seq, info_seq, DDS_LENGTH_UNLIMITED, DDS_ANY_SAMPLE_STATE, DDS_ANY_VIEW_STATE, DDS_ANY_INSTANCE_STATE); if (retcode == DDS_RETCODE_NO_DATA) { /// Not an error continue; } else if (retcode != DDS_RETCODE_OK) { // Is an error std::cerr << "take error: " << retcode << std::endl; continue; } int len = 0; double sum = 0; /* Iterate through the samples read using the take() method, getting * the number of samples got and, adding the value of x on each of * them to calculate the average afterwards. */ for (int i = 0; i < data_seq.length(); ++i) { if (!info_seq[i].valid_data) continue; len++; sum += data_seq[i].x; } if (len > 0) { std::cout << "Got " << len << " samples. Avg = " << sum / len << std::endl; samples_read += len; } retcode = typed_reader->return_loan(data_seq, info_seq); if (retcode != DDS_RETCODE_OK) { std::cerr << "return loan error " << retcode << 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/polling_read/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/polling_read/c/poll_publisher.c
/******************************************************************************* (c) 2005-2014 Copyright, Real-Time Innovations, Inc. All rights reserved. RTI grants Licensee a license to use, modify, compile, and create derivative works of the Software. Licensee has the right to distribute object form only for use with RTI products. The Software is provided "as is", with no warranty of any type, including any warranty for fitness for any purpose. RTI is under no obligation to maintain or support the Software. RTI shall not be liable for any incidental or consequential damages arising out of the use or inability to use the software. ******************************************************************************/ /* poll_publisher.c A publication of data of type poll This file is derived from code automatically generated by the rtiddsgen command: rtiddsgen -language C -example <arch> poll.idl Example publication of type poll automatically generated by 'rtiddsgen'. To test them follow these steps: (1) Compile this file and the example subscription. (2) Start the subscription with the command objs/<arch>/poll_subscriber <domain_id> <sample_count> (3) Start the publication with the command objs/<arch>/poll_publisher <domain_id> <sample_count> (4) [Optional] Specify the list of discovery initial peers and multicast receive addresses via an environment variable or a file (in the current working directory) called NDDS_DISCOVERY_PEERS. You can run any number of publishers and subscribers programs, and can add and remove them dynamically from the domain. Example: To run the example application on domain <domain_id>: On Unix: objs/<arch>/poll_publisher <domain_id> objs/<arch>/poll_subscriber <domain_id> On Windows: objs\<arch>\poll_publisher <domain_id> objs\<arch>\poll_subscriber <domain_id> modification history ------------ ------- */ #include "ndds/ndds_c.h" #include "poll.h" #include "pollSupport.h" #include <stdio.h> #include <stdlib.h> #include <time.h> /* Delete all entities */ static int publisher_shutdown(DDS_DomainParticipant *participant) { DDS_ReturnCode_t retcode; int status = 0; if (participant != NULL) { retcode = DDS_DomainParticipant_delete_contained_entities(participant); if (retcode != DDS_RETCODE_OK) { printf("delete_contained_entities error %d\n", retcode); status = -1; } retcode = DDS_DomainParticipantFactory_delete_participant( DDS_TheParticipantFactory, participant); if (retcode != DDS_RETCODE_OK) { printf("delete_participant error %d\n", retcode); status = -1; } } /* RTI Connext provides finalize_instance() method on domain participant factory for people who want to release memory used by the participant factory. Uncomment the following block of code for clean destruction of the singleton. */ /* retcode = DDS_DomainParticipantFactory_finalize_instance(); if (retcode != DDS_RETCODE_OK) { printf("finalize_instance error %d\n", retcode); status = -1; } */ return status; } static int publisher_main(int domainId, int sample_count) { DDS_DomainParticipant *participant = NULL; DDS_Publisher *publisher = NULL; DDS_Topic *topic = NULL; DDS_DataWriter *writer = NULL; pollDataWriter *poll_writer = NULL; poll *instance = NULL; DDS_ReturnCode_t retcode; DDS_InstanceHandle_t instance_handle = DDS_HANDLE_NIL; const char *type_name = NULL; int count = 0; /* Send a new sample every second */ struct DDS_Duration_t send_period = { 1, 0 }; /* To customize participant QoS, use the configuration file USER_QOS_PROFILES.xml */ participant = DDS_DomainParticipantFactory_create_participant( DDS_TheParticipantFactory, domainId, &DDS_PARTICIPANT_QOS_DEFAULT, NULL /* listener */, DDS_STATUS_MASK_NONE); if (participant == NULL) { printf("create_participant error\n"); publisher_shutdown(participant); return -1; } /* To customize publisher QoS, use the configuration file USER_QOS_PROFILES.xml */ publisher = DDS_DomainParticipant_create_publisher( participant, &DDS_PUBLISHER_QOS_DEFAULT, NULL /* listener */, DDS_STATUS_MASK_NONE); if (publisher == NULL) { printf("create_publisher error\n"); publisher_shutdown(participant); return -1; } /* Register type before creating topic */ type_name = pollTypeSupport_get_type_name(); retcode = pollTypeSupport_register_type(participant, type_name); if (retcode != DDS_RETCODE_OK) { printf("register_type error %d\n", retcode); publisher_shutdown(participant); return -1; } /* To customize topic QoS, use the configuration file USER_QOS_PROFILES.xml */ topic = DDS_DomainParticipant_create_topic( participant, "Example poll", type_name, &DDS_TOPIC_QOS_DEFAULT, NULL /* listener */, DDS_STATUS_MASK_NONE); if (topic == NULL) { printf("create_topic error\n"); publisher_shutdown(participant); return -1; } /* To customize data writer QoS, use the configuration file USER_QOS_PROFILES.xml */ writer = DDS_Publisher_create_datawriter( publisher, topic, &DDS_DATAWRITER_QOS_DEFAULT, NULL /* listener */, DDS_STATUS_MASK_NONE); if (writer == NULL) { printf("create_datawriter error\n"); publisher_shutdown(participant); return -1; } poll_writer = pollDataWriter_narrow(writer); if (poll_writer == NULL) { printf("DataWriter narrow error\n"); publisher_shutdown(participant); return -1; } /* Create data sample for writing */ instance = pollTypeSupport_create_data_ex(DDS_BOOLEAN_TRUE); if (instance == NULL) { printf("pollTypeSupport_create_data error\n"); publisher_shutdown(participant); return -1; } /* For a data type that has a key, if the same instance is going to be written multiple times, initialize the key here and register the keyed instance prior to writing */ /* instance_handle = pollDataWriter_register_instance( poll_writer, instance); */ /* Initialize random seed before entering the loop */ srand(time(NULL)); /* Main loop */ for (count = 0; (sample_count == 0) || (count < sample_count); ++count) { /* Modify the data to be written here */ /* Set x to a random number between 0 and 9 */ instance->x = (int) (rand() / (RAND_MAX / 10.0)); printf("Writing poll, count %d, x = %d\n", count, instance->x); /* Write data */ retcode = pollDataWriter_write(poll_writer, instance, &instance_handle); if (retcode != DDS_RETCODE_OK) { printf("write error %d\n", retcode); } NDDS_Utility_sleep(&send_period); } /* retcode = pollDataWriter_unregister_instance( poll_writer, instance, &instance_handle); if (retcode != DDS_RETCODE_OK) { printf("unregister instance error %d\n", retcode); } */ /* Delete data sample */ retcode = pollTypeSupport_delete_data_ex(instance, DDS_BOOLEAN_TRUE); if (retcode != DDS_RETCODE_OK) { printf("pollTypeSupport_delete_data error %d\n", retcode); } /* Cleanup and delete delete all entities */ return publisher_shutdown(participant); } #if defined(RTI_WINCE) int wmain(int argc, wchar_t **argv) { int domainId = 0; int sample_count = 0; /* infinite loop */ if (argc >= 2) { domainId = _wtoi(argv[1]); } if (argc >= 3) { sample_count = _wtoi(argv[2]); } /* Uncomment this to turn on additional logging NDDS_Config_Logger_set_verbosity_by_category( NDDS_Config_Logger_get_instance(), NDDS_CONFIG_LOG_CATEGORY_API, NDDS_CONFIG_LOG_VERBOSITY_STATUS_ALL); */ return publisher_main(domainId, sample_count); } #elif !(defined(RTI_VXWORKS) && !defined(__RTP__)) && !defined(RTI_PSOS) int main(int argc, char *argv[]) { int domainId = 0; int sample_count = 0; /* infinite loop */ if (argc >= 2) { domainId = atoi(argv[1]); } if (argc >= 3) { sample_count = atoi(argv[2]); } /* Uncomment this to turn on additional logging NDDS_Config_Logger_set_verbosity_by_category( NDDS_Config_Logger_get_instance(), NDDS_CONFIG_LOG_CATEGORY_API, NDDS_CONFIG_LOG_VERBOSITY_STATUS_ALL); */ return publisher_main(domainId, sample_count); } #endif #ifdef RTI_VX653 const unsigned char *__ctype = NULL; void usrAppInit() { #ifdef USER_APPL_INIT USER_APPL_INIT; /* for backwards compatibility */ #endif /* add application specific code here */ taskSpawn( "pub", RTI_OSAPI_THREAD_PRIORITY_NORMAL, 0x8, 0x150000, (FUNCPTR) publisher_main, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0); } #endif
c
rticonnextdds-examples
data/projects/rticonnextdds-examples/connext_dds/polling_read/c/poll_subscriber.c
/******************************************************************************* (c) 2005-2014 Copyright, Real-Time Innovations, Inc. All rights reserved. RTI grants Licensee a license to use, modify, compile, and create derivative works of the Software. Licensee has the right to distribute object form only for use with RTI products. The Software is provided "as is", with no warranty of any type, including any warranty for fitness for any purpose. RTI is under no obligation to maintain or support the Software. RTI shall not be liable for any incidental or consequential damages arising out of the use or inability to use the software. ******************************************************************************/ /* poll_subscriber.c A subscription example This file is derived from code automatically generated by the rtiddsgen command: rtiddsgen -language C -example <arch> poll.idl Example subscription of type poll automatically generated by 'rtiddsgen'. To test them, follow these steps: (1) Compile this file and the example publication. (2) Start the subscription with the command objs/<arch>/poll_subscriber <domain_id> <sample_count> (3) Start the publication with the command objs/<arch>/poll_publisher <domain_id> <sample_count> (4) [Optional] Specify the list of discovery initial peers and multicast receive addresses via an environment variable or a file (in the current working directory) called NDDS_DISCOVERY_PEERS. You can run any number of publishers and subscribers programs, and can add and remove them dynamically from the domain. Example: To run the example application on domain <domain_id>: On UNIX systems: objs/<arch>/poll_publisher <domain_id> objs/<arch>/poll_subscriber <domain_id> On Windows systems: objs\<arch>\poll_publisher <domain_id> objs\<arch>\poll_subscriber <domain_id> modification history ------------ ------- */ #include "ndds/ndds_c.h" #include "poll.h" #include "pollSupport.h" #include <stdio.h> #include <stdlib.h> /* We remove all the listener code as we won't use any listener */ /* Delete all entities */ static int subscriber_shutdown(DDS_DomainParticipant *participant) { DDS_ReturnCode_t retcode; int status = 0; if (participant != NULL) { retcode = DDS_DomainParticipant_delete_contained_entities(participant); if (retcode != DDS_RETCODE_OK) { printf("delete_contained_entities error %d\n", retcode); status = -1; } retcode = DDS_DomainParticipantFactory_delete_participant( DDS_TheParticipantFactory, participant); if (retcode != DDS_RETCODE_OK) { printf("delete_participant error %d\n", retcode); status = -1; } } /* RTI Connext provides the finalize_instance() method on domain participant factory for users who want to release memory used by the participant factory. Uncomment the following block of code for clean destruction of the singleton. */ /* retcode = DDS_DomainParticipantFactory_finalize_instance(); if (retcode != DDS_RETCODE_OK) { printf("finalize_instance error %d\n", retcode); status = -1; } */ return status; } static int subscriber_main(int domainId, int sample_count) { DDS_DomainParticipant *participant = NULL; DDS_Subscriber *subscriber = NULL; DDS_Topic *topic = NULL; /* struct DDS_DataReaderListener reader_listener = DDS_DataReaderListener_INITIALIZER; */ DDS_DataReader *reader = NULL; pollDataReader *poll_reader = NULL; DDS_ReturnCode_t retcode; const char *type_name = NULL; int count = 0; /* Poll for new samples every 5 seconds */ struct DDS_Duration_t poll_period = { 5, 0 }; /* We need to change the datareader_qos for this example. * If you want to do it programmatically, you will need to declare to * use the following struct.*/ /* struct DDS_DataReaderQos datareader_qos = DDS_DataReaderQos_INITIALIZER; */ /* To customize participant QoS, use the configuration file USER_QOS_PROFILES.xml */ participant = DDS_DomainParticipantFactory_create_participant( DDS_TheParticipantFactory, domainId, &DDS_PARTICIPANT_QOS_DEFAULT, NULL /* listener */, DDS_STATUS_MASK_NONE); if (participant == NULL) { printf("create_participant error\n"); subscriber_shutdown(participant); return -1; } /* To customize subscriber QoS, use the configuration file USER_QOS_PROFILES.xml */ subscriber = DDS_DomainParticipant_create_subscriber( participant, &DDS_SUBSCRIBER_QOS_DEFAULT, NULL /* listener */, DDS_STATUS_MASK_NONE); if (subscriber == NULL) { printf("create_subscriber error\n"); subscriber_shutdown(participant); return -1; } /* Register the type before creating the topic */ type_name = pollTypeSupport_get_type_name(); retcode = pollTypeSupport_register_type(participant, type_name); if (retcode != DDS_RETCODE_OK) { printf("register_type error %d\n", retcode); subscriber_shutdown(participant); return -1; } /* To customize topic QoS, use the configuration file USER_QOS_PROFILES.xml */ topic = DDS_DomainParticipant_create_topic( participant, "Example poll", type_name, &DDS_TOPIC_QOS_DEFAULT, NULL /* listener */, DDS_STATUS_MASK_NONE); if (topic == NULL) { printf("create_topic error\n"); subscriber_shutdown(participant); return -1; } /* Call create_datareader passing NULL in the listener parameter */ reader = DDS_Subscriber_create_datareader( subscriber, DDS_Topic_as_topicdescription(topic), &DDS_DATAREADER_QOS_DEFAULT, NULL, DDS_STATUS_MASK_ALL); if (reader == NULL) { printf("create_datareader error\n"); subscriber_shutdown(participant); return -1; } /* If you want to change datareader_qos.history.kind programmatically rather * than using the XML file, you will need to add the following lines to your * code and comment out the create_datareader call above. */ /* retcode = DDS_Subscriber_get_default_datareader_qos(subscriber, &datareader_qos); if (retcode != DDS_RETCODE_OK) { printf("get_default_datareader_qos error\n"); return -1; } datareader_qos.history.kind = DDS_KEEP_ALL_HISTORY_QOS; reader = DDS_Subscriber_create_datareader( subscriber, DDS_Topic_as_topicdescription(topic), &datareader_qos, NULL, DDS_STATUS_MASK_NONE); if (reader == NULL) { printf("create_datareader error\n"); subscriber_shutdown(participant); return -1; } */ poll_reader = pollDataReader_narrow(reader); if (poll_reader == NULL) { printf("DataReader narrow error\n"); return -1; } /* Main loop */ for (count = 0; (sample_count == 0) || (count < sample_count); ++count) { struct DDS_SampleInfoSeq info_seq; struct pollSeq data_seq; int i, len; double sum; DDS_ReturnCode_t retcode; NDDS_Utility_sleep(&poll_period); /* Check for new data calling the DataReader's take() method */ retcode = pollDataReader_take( poll_reader, &data_seq, &info_seq, DDS_LENGTH_UNLIMITED, DDS_ANY_SAMPLE_STATE, DDS_ANY_VIEW_STATE, DDS_ANY_INSTANCE_STATE); if (retcode == DDS_RETCODE_NO_DATA) { /* Not an error */ continue; } else if (retcode != DDS_RETCODE_OK) { /* Is an error */ printf("take error: %d\n", retcode); continue; } sum = 0; len = 0; /* Iterate through the samples read using the take() method, getting * the number of samples got and, adding the value of x on each of * them to calculate the average afterwards. */ for (i = 0; i < pollSeq_get_length(&data_seq); ++i) { if (DDS_SampleInfoSeq_get_reference(&info_seq, i)->valid_data) { len++; sum += pollSeq_get_reference(&data_seq, i)->x; } } if (len > 0) printf("Got %d samples. Avg = %.1f\n", len, sum / len); retcode = pollDataReader_return_loan(poll_reader, &data_seq, &info_seq); if (retcode != DDS_RETCODE_OK) { printf("return loan error %d\n", retcode); } } /* Cleanup and delete all entities */ return subscriber_shutdown(participant); } #if defined(RTI_WINCE) int wmain(int argc, wchar_t **argv) { int domainId = 0; int sample_count = 0; /* infinite loop */ if (argc >= 2) { domainId = _wtoi(argv[1]); } if (argc >= 3) { sample_count = _wtoi(argv[2]); } /* Uncomment this to turn on additional logging NDDS_Config_Logger_set_verbosity_by_category( NDDS_Config_Logger_get_instance(), NDDS_CONFIG_LOG_CATEGORY_API, NDDS_CONFIG_LOG_VERBOSITY_STATUS_ALL); */ return subscriber_main(domainId, sample_count); } #elif !(defined(RTI_VXWORKS) && !defined(__RTP__)) && !defined(RTI_PSOS) int main(int argc, char *argv[]) { int domainId = 0; int sample_count = 0; /* infinite loop */ if (argc >= 2) { domainId = atoi(argv[1]); } if (argc >= 3) { sample_count = atoi(argv[2]); } /* Uncomment this to turn on additional logging NDDS_Config_Logger_set_verbosity_by_category( NDDS_Config_Logger_get_instance(), NDDS_CONFIG_LOG_CATEGORY_API, NDDS_CONFIG_LOG_VERBOSITY_STATUS_ALL); */ return subscriber_main(domainId, sample_count); } #endif #ifdef RTI_VX653 const unsigned char *__ctype = NULL; void usrAppInit() { #ifdef USER_APPL_INIT USER_APPL_INIT; /* for backwards compatibility */ #endif /* add application specific code here */ taskSpawn( "sub", RTI_OSAPI_THREAD_PRIORITY_NORMAL, 0x8, 0x150000, (FUNCPTR) subscriber_main, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0); } #endif
c
rticonnextdds-examples
data/projects/rticonnextdds-examples/connext_dds/polling_read/c++03/poll_publisher.cxx
/******************************************************************************* (c) 2005-2015 Copyright, Real-Time Innovations, Inc. All rights reserved. RTI grants Licensee a license to use, modify, compile, and create derivative works of the Software. Licensee has the right to distribute object form only for use with RTI products. The Software is provided "as is", with no warranty of any type, including any warranty for fitness for any purpose. RTI is under no obligation to maintain or support the Software. RTI shall not be liable for any incidental or consequential damages arising out of the use or inability to use the software. ******************************************************************************/ #include <cstdlib> #include <iostream> #include "poll.hpp" #include <dds/dds.hpp> using namespace dds::core; using namespace dds::domain; using namespace dds::topic; using namespace dds::pub; void publisher_main(int domain_id, int sample_count) { // Create a DomainParticipant with default Qos DomainParticipant participant(domain_id); // Create a Topic -- and automatically register the type Topic<poll> topic(participant, "Example poll"); // Create a DataWriter with default Qos (Publisher created in-line) DataWriter<poll> writer(Publisher(participant), topic); poll sample; for (int count = 0; count < sample_count || sample_count == 0; count++) { // Set x to a random number between 0 and 9. sample.x((int) (rand() / (RAND_MAX / 10.0))); std::cout << "Writing poll, count " << count << ", x = " << sample.x() << std::endl; writer.write(sample); rti::util::sleep(Duration(1)); } } int main(int argc, char *argv[]) { int domain_id = 0; int sample_count = 0; // Infinite loop if (argc >= 2) { domain_id = atoi(argv[1]); } if (argc >= 3) { sample_count = atoi(argv[2]); } // To turn on additional logging, include <rti/config/Logger.hpp> and // uncomment the following line: // rti::config::Logger::instance().verbosity(rti::config::Verbosity::STATUS_ALL); try { publisher_main(domain_id, sample_count); } catch (const std::exception &ex) { // This will catch DDS exceptions std::cerr << "Exception in publisher_main: " << ex.what() << std::endl; return -1; } return 0; }
cxx
rticonnextdds-examples
data/projects/rticonnextdds-examples/connext_dds/polling_read/c++03/poll_subscriber.cxx
/******************************************************************************* (c) 2005-2015 Copyright, Real-Time Innovations, Inc. All rights reserved. RTI grants Licensee a license to use, modify, compile, and create derivative works of the Software. Licensee has the right to distribute object form only for use with RTI products. The Software is provided "as is", with no warranty of any type, including any warranty for fitness for any purpose. RTI is under no obligation to maintain or support the Software. RTI shall not be liable for any incidental or consequential damages arising out of the use or inability to use the software. ******************************************************************************/ #include <algorithm> #include <iostream> #include "poll.hpp" #include <dds/dds.hpp> using namespace dds::core; using namespace dds::domain; using namespace dds::topic; using namespace dds::sub; void subscriber_main(int domain_id, int sample_count) { // Create a DomainParticipant with default Qos DomainParticipant participant(domain_id); // Create a Topic -- and automatically register the type Topic<poll> topic(participant, "Example poll"); // Create a DataReader with default Qos (Subscriber created in-line) DataReader<poll> reader(Subscriber(participant), topic); std::cout << std::fixed; for (int count = 0; sample_count == 0 || count < sample_count; ++count) { // Poll for new data every 5 seconds. rti::util::sleep(Duration(5)); // Check for new data calling the DataReader's take() method. LoanedSamples<poll> samples = reader.take(); // Iterate through the samples read using the 'take()' method and // adding the value of x on each of them to calculate the average // afterwards. double sum = 0; for (LoanedSamples<poll>::iterator sample_it = samples.begin(); sample_it != samples.end(); sample_it++) { if (sample_it->info().valid()) { sum += sample_it->data().x(); } } if (samples.length() > 0) { std::cout << "Got " << samples.length() << " samples. " << "Avg = " << sum / samples.length() << std::endl; } } } int main(int argc, char *argv[]) { int domain_id = 0; int sample_count = 0; // Infinite loop if (argc >= 2) { domain_id = atoi(argv[1]); } if (argc >= 3) { sample_count = atoi(argv[2]); } // To turn on additional logging, include <rti/config/Logger.hpp> and // uncomment the following line: // rti::config::Logger::instance().verbosity(rti::config::Verbosity::STATUS_ALL); try { subscriber_main(domain_id, sample_count); } catch (const std::exception &ex) { // This will catch DDS exceptions std::cerr << "Exception in subscriber_main: " << ex.what() << std::endl; return -1; } return 0; }
cxx
rticonnextdds-examples
data/projects/rticonnextdds-examples/connext_dds/polling_read/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/polling_read/c++11/poll_publisher.cxx
/******************************************************************************* (c) 2005-2015 Copyright, Real-Time Innovations, Inc. All rights reserved. RTI grants Licensee a license to use, modify, compile, and create derivative works of the Software. Licensee has the right to distribute object form only for use with RTI products. The Software is provided "as is", with no warranty of any type, including any warranty for fitness for any purpose. RTI is under no obligation to maintain or support the Software. RTI shall not be liable for any incidental or consequential damages arising out of the use or inability to use the software. ******************************************************************************/ #include <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 "poll.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<poll> topic(participant, "Example poll"); // Create a Publisher with default QoS dds::pub::Publisher publisher(participant); // Create a DataWriter with default Qos dds::pub::DataWriter<poll> writer(publisher, topic); poll sample; for (unsigned int samples_written = 0; !application::shutdown_requested && samples_written < sample_count; samples_written++) { // Set x to a random number between 0 and 9. sample.x((int) (rand() / (RAND_MAX / 10.0))); std::cout << "Writing poll, count " << samples_written << ", x = " << sample.x() << std::endl; 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/polling_read/c++11/poll_subscriber.cxx
/******************************************************************************* (c) 2005-2015 Copyright, Real-Time Innovations, Inc. All rights reserved. RTI grants Licensee a license to use, modify, compile, and create derivative works of the Software. Licensee has the right to distribute object form only for use with RTI products. The Software is provided "as is", with no warranty of any type, including any warranty for fitness for any purpose. RTI is under no obligation to maintain or support the Software. RTI shall not be liable for any incidental or consequential damages arising out of the use or inability to use the software. ******************************************************************************/ #include <dds/sub/ddssub.hpp> #include <dds/core/ddscore.hpp> #include <rti/util/util.hpp> // for sleep() #include <rti/config/Logger.hpp> // for logging #include "poll.hpp" #include "application.hpp" // for command line parsing and ctrl-c void run_subscriber_application( unsigned int domain_id, unsigned int sample_count) { // Create a DomainParticipant with default Qos dds::domain::DomainParticipant participant(domain_id); // Create a Topic -- and automatically register the type dds::topic::Topic<poll> topic(participant, "Example poll"); // Create a Subscriber with default QoS dds::sub::Subscriber subscriber(participant); // Create a DataReader with default Qos dds::sub::DataReader<poll> reader(subscriber, topic); std::cout << std::fixed; int samples_read = 0; while (!application::shutdown_requested && samples_read < sample_count) { // Poll for new data every 5 seconds. rti::util::sleep(dds::core::Duration(5)); // Check for new data calling the DataReader's take() method. dds::sub::LoanedSamples<poll> samples = reader.take(); // Iterate through the samples read using the 'take()' method and // adding the value of x on each of them to calculate the average // afterwards. double sum = 0; for (const auto &sample : samples) { if (sample.info().valid()) { samples_read++; sum += sample.data().x(); } } if (samples.length() > 0) { std::cout << "Got " << samples.length() << " samples. " << "Avg = " << sum / samples.length() << 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/custom_flow_controller/c++/cfc_subscriber.cxx
/******************************************************************************* (c) 2005-2014 Copyright, Real-Time Innovations, Inc. All rights reserved. RTI grants Licensee a license to use, modify, compile, and create derivative works of the Software. Licensee has the right to distribute object form only for use with RTI products. The Software is provided "as is", with no warranty of any type, including any warranty for fitness for any purpose. RTI is under no obligation to maintain or support the Software. RTI shall not be liable for any incidental or consequential damages arising out of the use or inability to use the software. ******************************************************************************/ /* cfc_subscriber.cxx A subscription example This file is derived from code automatically generated by the rtiddsgen command: rtiddsgen -language C++ -example <arch> cfc.idl Example subscription of type cfc automatically generated by 'rtiddsgen'. To test them follow these steps: (1) Compile this file and the example publication. (2) Start the subscription with the command objs/<arch>/cfc_subscriber <domain_id> <sample_count> (3) Start the publication with the command objs/<arch>/cfc_publisher <domain_id> <sample_count> (4) [Optional] Specify the list of discovery initial peers and multicast receive addresses via an environment variable or a file (in the current working directory) called NDDS_DISCOVERY_PEERS. You can run any number of publishers and subscribers programs, and can add and remove them dynamically from the domain. Example: To run the example application on domain <domain_id>: On Unix: objs/<arch>/cfc_publisher <domain_id> objs/<arch>/cfc_subscriber <domain_id> On Windows: objs\<arch>\cfc_publisher <domain_id> objs\<arch>\cfc_subscriber <domain_id> modification history ------------ ------- */ #include <stdio.h> #include <stdlib.h> #ifdef RTI_VX653 #include <vThreadsData.h> #endif #include "cfc.h" #include "cfcSupport.h" #include "ndds/ndds_cpp.h" /* Changes for Custom_Flowcontroller */ /* For timekeeping */ #include <time.h> clock_t init; class cfcListener : public DDSDataReaderListener { public: virtual void on_requested_deadline_missed( DDSDataReader * /*reader*/, const DDS_RequestedDeadlineMissedStatus & /*status*/) { } virtual void on_requested_incompatible_qos( DDSDataReader * /*reader*/, const DDS_RequestedIncompatibleQosStatus & /*status*/) { } virtual void on_sample_rejected( DDSDataReader * /*reader*/, const DDS_SampleRejectedStatus & /*status*/) { } virtual void on_liveliness_changed( DDSDataReader * /*reader*/, const DDS_LivelinessChangedStatus & /*status*/) { } virtual void on_sample_lost( DDSDataReader * /*reader*/, const DDS_SampleLostStatus & /*status*/) { } virtual void on_subscription_matched( DDSDataReader * /*reader*/, const DDS_SubscriptionMatchedStatus & /*status*/) { } virtual void on_data_available(DDSDataReader *reader); }; void cfcListener::on_data_available(DDSDataReader *reader) { cfcDataReader *cfc_reader = NULL; cfcSeq data_seq; DDS_SampleInfoSeq info_seq; DDS_ReturnCode_t retcode; int i; cfc_reader = cfcDataReader::narrow(reader); if (cfc_reader == NULL) { printf("DataReader narrow error\n"); return; } retcode = cfc_reader->take( data_seq, info_seq, DDS_LENGTH_UNLIMITED, DDS_ANY_SAMPLE_STATE, DDS_ANY_VIEW_STATE, DDS_ANY_INSTANCE_STATE); if (retcode == DDS_RETCODE_NO_DATA) { return; } else if (retcode != DDS_RETCODE_OK) { printf("take error %d\n", retcode); return; } for (i = 0; i < data_seq.length(); ++i) { if (info_seq[i].valid_data) { /* Start changes for Custom_Flowcontroller */ /* print the time we get each sample. */ double elapsed_ticks = clock() - init; double elapsed_secs = elapsed_ticks / CLOCKS_PER_SEC; printf("@ t=%.2fs, got x = %d\n", elapsed_secs, data_seq[i].x); /* End changes for Custom_Flowcontroller */ } } retcode = cfc_reader->return_loan(data_seq, info_seq); if (retcode != DDS_RETCODE_OK) { printf("return loan error %d\n", retcode); } } /* Delete all entities */ static int subscriber_shutdown(DDSDomainParticipant *participant) { DDS_ReturnCode_t retcode; int status = 0; if (participant != NULL) { retcode = participant->delete_contained_entities(); if (retcode != DDS_RETCODE_OK) { printf("delete_contained_entities error %d\n", retcode); status = -1; } retcode = DDSTheParticipantFactory->delete_participant(participant); if (retcode != DDS_RETCODE_OK) { printf("delete_participant error %d\n", retcode); status = -1; } } /* RTI Connext provides the finalize_instance() method on domain participant factory for people who want to release memory used by the participant factory. Uncomment the following block of code for clean destruction of the singleton. */ /* retcode = DDSDomainParticipantFactory::finalize_instance(); if (retcode != DDS_RETCODE_OK) { printf("finalize_instance error %d\n", retcode); status = -1; } */ return status; } extern "C" int subscriber_main(int domainId, int sample_count) { DDSDomainParticipant *participant = NULL; DDSSubscriber *subscriber = NULL; DDSTopic *topic = NULL; cfcListener *reader_listener = NULL; DDSDataReader *reader = NULL; DDS_ReturnCode_t retcode; const char *type_name = NULL; int count = 0; DDS_Duration_t receive_period = { 1, 0 }; int status = 0; /* Start changes for Custom_Flowcontroller */ /* for timekeeping */ init = clock(); /* To customize the participant QoS, use the configuration file USER_QOS_PROFILES.xml */ participant = DDSTheParticipantFactory->create_participant( domainId, DDS_PARTICIPANT_QOS_DEFAULT, NULL /* listener */, DDS_STATUS_MASK_NONE); if (participant == NULL) { printf("create_participant error\n"); subscriber_shutdown(participant); return -1; } /* If you want to change the Participant's QoS programmatically rather than * using the XML file, you will need to add the following lines to your * code and comment out the create_participant call above. */ /* By default, discovery will communicate via shared memory for platforms * that support it. Because we disable shared memory on the publishing * side, we do so here to ensure the reader and writer discover each other. */ /* Get default participant QoS to customize */ /* DDS_DomainParticipantQos participant_qos; retcode = DDSTheParticipantFactory->get_default_participant_qos( participant_qos); if (retcode != DDS_RETCODE_OK) { printf("get_default_participant_qos error\n"); return -1; } participant_qos.transport_builtin.mask = DDS_TRANSPORTBUILTIN_UDPv4; */ /* To create participant with default QoS, use DDS_PARTICIPANT_QOS_DEFAULT instead of participant_qos */ /* participant = DDSTheParticipantFactory->create_participant(domainId, participant_qos, NULL, DDS_STATUS_MASK_NONE); if (participant == NULL) { printf("create_participant error\n"); subscriber_shutdown(participant); return -1; } */ /* End changes for custom_flowcontroller */ /* To customize the subscriber QoS, use the configuration file USER_QOS_PROFILES.xml */ subscriber = participant->create_subscriber( DDS_SUBSCRIBER_QOS_DEFAULT, NULL, DDS_STATUS_MASK_NONE); if (subscriber == NULL) { printf("create_subscriber error\n"); subscriber_shutdown(participant); return -1; } /* Register the type before creating the topic */ type_name = cfcTypeSupport::get_type_name(); retcode = cfcTypeSupport::register_type(participant, type_name); if (retcode != DDS_RETCODE_OK) { printf("register_type error %d\n", retcode); subscriber_shutdown(participant); return -1; } /* To customize the topic QoS, use the configuration file USER_QOS_PROFILES.xml */ topic = participant->create_topic( "Example cfc", type_name, DDS_TOPIC_QOS_DEFAULT, NULL /* listener */, DDS_STATUS_MASK_NONE); if (topic == NULL) { printf("create_topic error\n"); subscriber_shutdown(participant); return -1; } /* Create a data reader listener */ reader_listener = new cfcListener(); /* To customize the data reader QoS, use the configuration file USER_QOS_PROFILES.xml */ reader = subscriber->create_datareader( topic, DDS_DATAREADER_QOS_DEFAULT, reader_listener, DDS_STATUS_MASK_ALL); if (reader == NULL) { printf("create_datareader error\n"); subscriber_shutdown(participant); delete reader_listener; return -1; } /* Main loop */ for (count = 0; (sample_count == 0) || (count < sample_count); ++count) { NDDSUtility::sleep(receive_period); } /* Delete all entities */ status = subscriber_shutdown(participant); delete reader_listener; return status; } #if defined(RTI_WINCE) int wmain(int argc, wchar_t **argv) { int domainId = 0; int sample_count = 0; /* infinite loop */ if (argc >= 2) { domainId = _wtoi(argv[1]); } if (argc >= 3) { sample_count = _wtoi(argv[2]); } /* Uncomment this to turn on additional logging NDDSConfigLogger::get_instance()-> set_verbosity_by_category(NDDS_CONFIG_LOG_CATEGORY_API, NDDS_CONFIG_LOG_VERBOSITY_STATUS_ALL); */ return subscriber_main(domainId, sample_count); } #elif !(defined(RTI_VXWORKS) && !defined(__RTP__)) && !defined(RTI_PSOS) int main(int argc, char *argv[]) { int domainId = 0; int sample_count = 0; /* infinite loop */ if (argc >= 2) { domainId = atoi(argv[1]); } if (argc >= 3) { sample_count = atoi(argv[2]); } /* Uncomment this to turn on additional logging NDDSConfigLogger::get_instance()-> set_verbosity_by_category(NDDS_CONFIG_LOG_CATEGORY_API, NDDS_CONFIG_LOG_VERBOSITY_STATUS_ALL); */ return subscriber_main(domainId, sample_count); } #endif #ifdef RTI_VX653 const unsigned char *__ctype = *(__ctypePtrGet()); extern "C" void usrAppInit() { #ifdef USER_APPL_INIT USER_APPL_INIT; /* for backwards compatibility */ #endif /* add application specific code here */ taskSpawn( "sub", RTI_OSAPI_THREAD_PRIORITY_NORMAL, 0x8, 0x150000, (FUNCPTR) subscriber_main, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0); } #endif
cxx
rticonnextdds-examples
data/projects/rticonnextdds-examples/connext_dds/custom_flow_controller/c++/cfc_publisher.cxx
/******************************************************************************* (c) 2005-2014 Copyright, Real-Time Innovations, Inc. All rights reserved. RTI grants Licensee a license to use, modify, compile, and create derivative works of the Software. Licensee has the right to distribute object form only for use with RTI products. The Software is provided "as is", with no warranty of any type, including any warranty for fitness for any purpose. RTI is under no obligation to maintain or support the Software. RTI shall not be liable for any incidental or consequential damages arising out of the use or inability to use the software. ******************************************************************************/ /* cfc_publisher.cxx A publication of data of type cfc This file is derived from code automatically generated by the rtiddsgen command: rtiddsgen -language C++ -example <arch> cfc.idl Example publication of type cfc automatically generated by 'rtiddsgen'. To test them follow these steps: (1) Compile this file and the example subscription. (2) Start the subscription with the command objs/<arch>/cfc_subscriber <domain_id> <sample_count> (3) Start the publication with the command objs/<arch>/cfc_publisher <domain_id> <sample_count> (4) [Optional] Specify the list of discovery initial peers and multicast receive addresses via an environment variable or a file (in the current working directory) called NDDS_DISCOVERY_PEERS. You can run any number of publishers and subscribers programs, and can add and remove them dynamically from the domain. Example: To run the example application on domain <domain_id>: On Unix: objs/<arch>/cfc_publisher <domain_id> o objs/<arch>/cfc_subscriber <domain_id> On Windows: objs\<arch>\cfc_publisher <domain_id> objs\<arch>\cfc_subscriber <domain_id> modification history ------------ ------- */ #include <stdio.h> #include <stdlib.h> #ifdef RTI_VX653 #include <vThreadsData.h> #endif #include "cfc.h" #include "cfcSupport.h" #include "ndds/ndds_cpp.h" /* Delete all entities */ static int publisher_shutdown(DDSDomainParticipant *participant) { DDS_ReturnCode_t retcode; int status = 0; if (participant != NULL) { retcode = participant->delete_contained_entities(); if (retcode != DDS_RETCODE_OK) { printf("delete_contained_entities error %d\n", retcode); status = -1; } retcode = DDSTheParticipantFactory->delete_participant(participant); if (retcode != DDS_RETCODE_OK) { printf("delete_participant error %d\n", retcode); status = -1; } } /* RTI Connext provides finalize_instance() method on domain participant factory for people who want to release memory used by the participant factory. Uncomment the following block of code for clean destruction of the singleton. */ /* retcode = DDSDomainParticipantFactory::finalize_instance(); if (retcode != DDS_RETCODE_OK) { printf("finalize_instance error %d\n", retcode); status = -1; } */ return status; } extern "C" int publisher_main(int domainId, int sample_count) { DDSDomainParticipant *participant = NULL; DDSPublisher *publisher = NULL; DDSTopic *topic = NULL; DDSDataWriter *writer = NULL; cfcDataWriter *cfc_writer = NULL; cfc *instance = NULL; DDS_ReturnCode_t retcode; DDS_InstanceHandle_t instance_handle = DDS_HANDLE_NIL; const char *type_name = NULL; int count = 0; DDS_Duration_t send_period = { 1, 0 }; int i; int sample; const char *cfc_name = "custom_flowcontroller"; participant = DDSTheParticipantFactory->create_participant( domainId, DDS_PARTICIPANT_QOS_DEFAULT, NULL /* listener */, DDS_STATUS_MASK_NONE); if (participant == NULL) { printf("create_participant error\n"); publisher_shutdown(participant); return -1; } /* Start changes for custom_flowcontroller */ /* If you want to change the Participant's QoS programmatically rather than * using the XML file, you will need to add the following lines to your * code and comment out the create_participant call above. */ /* Get default participant QoS to customize */ /* DDS_DomainParticipantQos participant_qos; retcode = DDSTheParticipantFactory->get_default_participant_qos( participant_qos); if (retcode != DDS_RETCODE_OK) { printf("get_default_participant_qos error\n"); return -1; } */ /* By default, data will be sent via shared memory _and_ UDPv4. Because * the flowcontroller limits writes across all interfaces, this halves the * effective send rate. To avoid this, we enable only the UDPv4 transport */ /* participant_qos.transport_builtin.mask = DDS_TRANSPORTBUILTIN_UDPv4; */ /* To create participant with default QoS, use DDS_PARTICIPANT_QOS_DEFAULT instead of participant_qos */ /* participant = DDSTheParticipantFactory->create_participant(domainId, participant_qos, NULL, DDS_STATUS_MASK_NONE); if (participant == NULL) { printf("create_participant error\n"); publisher_shutdown(participant); return -1; } */ /* End changes for custom_flowcontroller /* To customize publisher QoS, use the configuration file USER_QOS_PROFILES.xml */ publisher = participant->create_publisher( DDS_PUBLISHER_QOS_DEFAULT, NULL /* listener */, DDS_STATUS_MASK_NONE); if (publisher == NULL) { printf("create_publisher error\n"); publisher_shutdown(participant); return -1; } /* Register type before creating topic */ type_name = cfcTypeSupport::get_type_name(); retcode = cfcTypeSupport::register_type(participant, type_name); if (retcode != DDS_RETCODE_OK) { printf("register_type error %d\n", retcode); publisher_shutdown(participant); return -1; } /* To customize topic QoS, use the configuration file USER_QOS_PROFILES.xml */ topic = participant->create_topic( "Example cfc", type_name, DDS_TOPIC_QOS_DEFAULT, NULL /* listener */, DDS_STATUS_MASK_NONE); if (topic == NULL) { printf("create_topic error\n"); publisher_shutdown(participant); return -1; } /* To customize data writer QoS, use the configuration file USER_QOS_PROFILES.xml */ writer = publisher->create_datawriter( topic, DDS_DATAWRITER_QOS_DEFAULT, NULL /* listener */, DDS_STATUS_MASK_NONE); if (writer == NULL) { printf("create_datawriter error\n"); publisher_shutdown(participant); return -1; } /* Start changes for custom_flowcontroller */ /* If you want to change the Datawriter's QoS programmatically rather than * using the XML file, you will need to add the following lines to your * code and comment out the create_datawriter call above. * * In this case we create the flowcontroller and the neccesary QoS * for the datawriter. */ /* DDS_FlowControllerProperty_t custom_fcp; retcode = participant->get_default_flowcontroller_property(custom_fcp); if (retcode != DDS_RETCODE_OK) { printf("get_default_flowcontroller_property error \n"); return -1; } */ /* Don't allow too many tokens to accumulate */ /* custom_fcp.token_bucket.max_tokens = custom_fcp.token_bucket.tokens_added_per_period = 2; custom_fcp.token_bucket.tokens_leaked_per_period = DDS_LENGTH_UNLIMITED; */ /* 100ms */ /* custom_fcp.token_bucket.period.sec = 0; custom_fcp.token_bucket.period.nanosec = 100000000; */ /* The sample size is 1000, but the minimum bytes_per_token is 1024. * Furthermore, we want to allow some overhead. */ /* custom_fcp.token_bucket.bytes_per_token = 1024; */ /* So, in summary, each token can be used to send about one message, * and we get 2 tokens every 100ms, so this limits transmissions to * about 20 messages per second. */ /* Create flowcontroller and set properties */ /* DDSFlowController* cfc = NULL; cfc = participant->create_flowcontroller(DDS_String_dup(cfc_name), custom_fcp); if (cfc == NULL) { printf("create_flowcontroller error\n"); return -1; } */ /* Get default datawriter QoS to customize */ /* DDS_DataWriterQos datawriter_qos; retcode = publisher->get_default_datawriter_qos(datawriter_qos); if (retcode != DDS_RETCODE_OK) { printf("get_default_datawriter_qos error\n"); return -1; } */ /* As an alternative to increasing h istory depth, we can just * set the qos to keep all samples */ /* datawriter_qos.history.kind = DDS_KEEP_ALL_HISTORY_QOS; */ /* Set flowcontroller for datawriter */ /* datawriter_qos.publish_mode.kind = DDS_ASYNCHRONOUS_PUBLISH_MODE_QOS; datawriter_qos.publish_mode.flow_controller_name = DDS_String_dup(cfc_name); */ /* To create datawriter with default QoS, use DDS_DATAWRITER_QOS_DEFAULT instead of datawriter_qos */ /* writer = publisher->create_datawriter(topic, datawriter_qos, NULL, DDS_STATUS_MASK_NONE); if (writer == NULL) { printf("create_datawriter error\n"); publisher_shutdown(participant); return -1; } */ /* End changes for custom_flowcontroller */ cfc_writer = cfcDataWriter::narrow(writer); if (cfc_writer == NULL) { printf("DataWriter narrow error\n"); publisher_shutdown(participant); return -1; } /* Create data sample for writing */ instance = cfcTypeSupport::create_data(); if (instance == NULL) { printf("cfcTypeSupport::create_data error\n"); publisher_shutdown(participant); return -1; } /* For a data type that has a key, if the same instance is going to be written multiple times, initialize the key here and register the keyed instance prior to writing */ /* instance_handle = cfc_writer->register_instance(*instance); */ /* Main loop */ for (count = 0; (sample_count == 0) || (count < sample_count); ++count) { /* Changes for custom_flowcontroller */ /* Simulate bursty writer */ NDDSUtility::sleep(send_period); for (i = 0; i < 10; ++i) { sample = count * 10 + i; printf("Writing cfc, sample %d\n", sample); instance->x = sample; memset(instance->str, 1, 999); instance->str[999] = 0; retcode = cfc_writer->write(*instance, instance_handle); if (retcode != DDS_RETCODE_OK) { printf("write error %d\n", retcode); } } } /* This new sleep it is for let time to the subscriber to read all the * sent samples. */ send_period.sec = 4; NDDS_Utility_sleep(&send_period); /* retcode = cfc_writer->unregister_instance( *instance, instance_handle); if (retcode != DDS_RETCODE_OK) { printf("unregister instance error %d\n", retcode); } */ /* Delete data sample */ retcode = cfcTypeSupport::delete_data(instance); if (retcode != DDS_RETCODE_OK) { printf("cfcTypeSupport::delete_data error %d\n", retcode); } /* Delete all entities */ return publisher_shutdown(participant); } #if defined(RTI_WINCE) int wmain(int argc, wchar_t **argv) { int domainId = 0; int sample_count = 0; /* infinite loop */ if (argc >= 2) { domainId = _wtoi(argv[1]); } if (argc >= 3) { sample_count = _wtoi(argv[2]); } /* Uncomment this to turn on additional logging NDDSConfigLogger::get_instance()-> set_verbosity_by_category(NDDS_CONFIG_LOG_CATEGORY_API, NDDS_CONFIG_LOG_VERBOSITY_STATUS_ALL); */ return publisher_main(domainId, sample_count); } #elif !(defined(RTI_VXWORKS) && !defined(__RTP__)) && !defined(RTI_PSOS) int main(int argc, char *argv[]) { int domainId = 0; int sample_count = 0; /* infinite loop */ if (argc >= 2) { domainId = atoi(argv[1]); } if (argc >= 3) { sample_count = atoi(argv[2]); } /* Uncomment this to turn on additional logging NDDSConfigLogger::get_instance()-> set_verbosity_by_category(NDDS_CONFIG_LOG_CATEGORY_API, NDDS_CONFIG_LOG_VERBOSITY_STATUS_ALL); */ return publisher_main(domainId, sample_count); } #endif #ifdef RTI_VX653 const unsigned char *__ctype = *(__ctypePtrGet()); extern "C" void usrAppInit() { #ifdef USER_APPL_INIT USER_APPL_INIT; /* for backwards compatibility */ #endif /* add application specific code here */ taskSpawn( "pub", RTI_OSAPI_THREAD_PRIORITY_NORMAL, 0x8, 0x150000, (FUNCPTR) publisher_main, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0); } #endif
cxx
rticonnextdds-examples
data/projects/rticonnextdds-examples/connext_dds/custom_flow_controller/c++98/cfc_subscriber.cxx
/******************************************************************************* (c) 2005-2014 Copyright, Real-Time Innovations, Inc. All rights reserved. RTI grants Licensee a license to use, modify, compile, and create derivative works of the Software. Licensee has the right to distribute object form only for use with RTI products. The Software is provided "as is", with no warranty of any type, including any warranty for fitness for any purpose. RTI is under no obligation to maintain or support the Software. RTI shall not be liable for any incidental or consequential damages arising out of the use or inability to use the software. ******************************************************************************/ #include <iostream> #include <stdio.h> #include <stdlib.h> #include <iomanip> #include "cfc.h" #include "cfcSupport.h" #include "ndds/ndds_cpp.h" #include "application.h" using namespace application; /* Changes for Custom_Flowcontroller */ /* For timekeeping */ #include <time.h> clock_t init; static int shutdown_participant( DDSDomainParticipant *participant, const char *shutdown_message, int status); unsigned int process_data(cfcDataReader *typed_reader) { cfcSeq data_seq; DDS_SampleInfoSeq info_seq; unsigned int samples_read = 0; typed_reader->take( data_seq, info_seq, DDS_LENGTH_UNLIMITED, DDS_ANY_SAMPLE_STATE, DDS_ANY_VIEW_STATE, DDS_ANY_INSTANCE_STATE); std::cout << std::fixed; std::cout << std::setprecision(2); for (int i = 0; i < data_seq.length(); ++i) { if (info_seq[i].valid_data) { /* Start changes for Custom_Flowcontroller */ /* print the time we get each sample. */ double elapsed_ticks = clock() - init; double elapsed_secs = elapsed_ticks / CLOCKS_PER_SEC; std::cout << "@ t=" << elapsed_secs << ", got x = " << data_seq[i].x << std::endl; samples_read++; /* End changes for Custom_Flowcontroller */ } } // Data loaned from Connext for performance. Return loan when done. DDS_ReturnCode_t retcode = typed_reader->return_loan(data_seq, info_seq); if (retcode != DDS_RETCODE_OK) { std::cerr << "return loan error " << retcode << std::endl; } return samples_read; } int run_subscriber_application( unsigned int domain_id, unsigned int sample_count) { DDS_Duration_t wait_timeout = { 1, 0 }; /* Start changes for Custom_Flowcontroller */ /* for timekeeping */ init = clock(); // Start communicating in a domain, usually one participant per application DDSDomainParticipant *participant = DDSTheParticipantFactory->create_participant( domain_id, DDS_PARTICIPANT_QOS_DEFAULT, NULL /* listener */, DDS_STATUS_MASK_NONE); if (participant == NULL) { return shutdown_participant( participant, "create_participant error", EXIT_FAILURE); } /* If you want to change the Participant's QoS programmatically rather than * using the XML file, you will need to add the following lines to your * code and comment out the create_participant call above. */ /* By default, discovery will communicate via shared memory for platforms * that support it. Because we disable shared memory on the publishing * side, we do so here to ensure the reader and writer discover each other. */ /* Get default participant QoS to customize */ /* DDS_DomainParticipantQos participant_qos; retcode = DDSTheParticipantFactory->get_default_participant_qos( participant_qos); if (retcode != DDS_RETCODE_OK) { std::cerr << "get_default_participant_qos error\n"; return EXIT_FAILURE; } participant_qos.transport_builtin.mask = DDS_TRANSPORTBUILTIN_UDPv4; */ /* To create participant with default QoS, use DDS_PARTICIPANT_QOS_DEFAULT instead of participant_qos */ /* DDSDomainParticipant *participant = DDSTheParticipantFactory->create_participant( domain_id, participant_qos, NULL, DDS_STATUS_MASK_NONE); if (participant == NULL) { return shutdown_participant( participant, "create_participant error", EXIT_FAILURE); } */ /* End changes for custom_flowcontroller */ // A Subscriber allows an application to create one or more DataReaders DDSSubscriber *subscriber = participant->create_subscriber( DDS_SUBSCRIBER_QOS_DEFAULT, NULL, DDS_STATUS_MASK_NONE); if (subscriber == NULL) { return shutdown_participant( participant, "create_subscriber error", EXIT_FAILURE); } // Register the datatype to use when creating the Topic const char *type_name = cfcTypeSupport::get_type_name(); DDS_ReturnCode_t retcode = cfcTypeSupport::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 cfc", 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 cfc" 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 cfcDataReader *typed_reader = cfcDataReader::narrow(untyped_reader); if (typed_reader == NULL) { return shutdown_participant( participant, "DataReader narrow error", EXIT_FAILURE); } // Create ReadCondition that triggers when unread data in reader's queue DDSReadCondition *read_condition = typed_reader->create_readcondition( DDS_NOT_READ_SAMPLE_STATE, DDS_ANY_VIEW_STATE, DDS_ANY_INSTANCE_STATE); if (read_condition == NULL) { return shutdown_participant( participant, "create_readcondition error", EXIT_FAILURE); } // WaitSet will be woken when the attached condition is triggered DDSWaitSet waitset; retcode = waitset.attach_condition(read_condition); if (retcode != DDS_RETCODE_OK) { return shutdown_participant( participant, "attach_condition error", EXIT_FAILURE); } // Main loop. Wait for data to arrive, and process when it arrives unsigned int samples_read = 0; while (!shutdown_requested && samples_read < sample_count) { DDSConditionSeq active_conditions_seq; // Wait for data retcode = waitset.wait(active_conditions_seq, wait_timeout); if (retcode == DDS_RETCODE_OK) { // If the read condition is triggered, process data samples_read += process_data(typed_reader); } } // Cleanup return shutdown_participant(participant, "Shutting down", 0); } // Delete all entities static int shutdown_participant( DDSDomainParticipant *participant, const char *shutdown_message, int status) { DDS_ReturnCode_t retcode; std::cout << shutdown_message << std::endl; if (participant != NULL) { // Cleanup everything created by this Participant retcode = participant->delete_contained_entities(); if (retcode != DDS_RETCODE_OK) { std::cerr << "delete_contained_entities error" << retcode << std::endl; status = EXIT_FAILURE; } retcode = DDSTheParticipantFactory->delete_participant(participant); if (retcode != DDS_RETCODE_OK) { std::cerr << "delete_participant error" << retcode << std::endl; status = EXIT_FAILURE; } } return status; } int main(int argc, char *argv[]) { // Parse arguments and handle control-C ApplicationArguments arguments; parse_arguments(arguments, argc, argv); if (arguments.parse_result == PARSE_RETURN_EXIT) { return EXIT_SUCCESS; } else if (arguments.parse_result == PARSE_RETURN_FAILURE) { return EXIT_FAILURE; } setup_signal_handlers(); // Sets Connext verbosity to help debugging NDDSConfigLogger::get_instance()->set_verbosity(arguments.verbosity); int status = run_subscriber_application( arguments.domain_id, arguments.sample_count); // Releases the memory used by the participant factory. Optional at // application exit DDS_ReturnCode_t retcode = DDSDomainParticipantFactory::finalize_instance(); if (retcode != DDS_RETCODE_OK) { std::cerr << "finalize_instance error" << retcode << std::endl; status = EXIT_FAILURE; } return status; }
cxx
rticonnextdds-examples
data/projects/rticonnextdds-examples/connext_dds/custom_flow_controller/c++98/cfc_publisher.cxx
/******************************************************************************* (c) 2005-2014 Copyright, Real-Time Innovations, Inc. All rights reserved. RTI grants Licensee a license to use, modify, compile, and create derivative works of the Software. Licensee has the right to distribute object form only for use with RTI products. The Software is provided "as is", with no warranty of any type, including any warranty for fitness for any purpose. RTI is under no obligation to maintain or support the Software. RTI shall not be liable for any incidental or consequential damages arising out of the use or inability to use the software. ******************************************************************************/ #include <iostream> #include <stdio.h> #include <stdlib.h> #include "cfc.h" #include "cfcSupport.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 }; const char *cfc_name = "custom_flowcontroller"; // Start communicating in a domain, usually one participant per application DDSDomainParticipant *participant = DDSTheParticipantFactory->create_participant( domain_id, DDS_PARTICIPANT_QOS_DEFAULT, NULL /* listener */, DDS_STATUS_MASK_NONE); if (participant == NULL) { return shutdown_participant( participant, "create_participant error", EXIT_FAILURE); } /* Start changes for custom_flowcontroller */ /* If you want to change the Participant's QoS programmatically rather than * using the XML file, you will need to add the following lines to your * code and comment out the create_participant call above. */ /* Get default participant QoS to customize */ /* DDS_DomainParticipantQos participant_qos; 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; } */ /* By default, data will be sent via shared memory _and_ UDPv4. Because * the flowcontroller limits writes across all interfaces, this halves the * effective send rate. To avoid this, we enable only the UDPv4 transport */ /* participant_qos.transport_builtin.mask = DDS_TRANSPORTBUILTIN_UDPv4; */ /* To create participant with default QoS, use DDS_PARTICIPANT_QOS_DEFAULT instead of participant_qos */ /* DDSDomainParticipant *participant = DDSTheParticipantFactory ->create_participant( domain_id, participant_qos, NULL, DDS_STATUS_MASK_NONE); if (participant == NULL) { return shutdown_participant( participant, "create_participant error", EXIT_FAILURE); } */ /* End changes for custom_flowcontroller */ // 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 = cfcTypeSupport::get_type_name(); DDS_ReturnCode_t retcode = cfcTypeSupport::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 cfc", 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 cfc" 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); } /* Start changes for custom_flowcontroller */ /* If you want to change the Datawriter's QoS programmatically rather than * using the XML file, you will need to add the following lines to your * code and comment out the create_datawriter call above. * * In this case we create the flowcontroller and the neccesary QoS * for the datawriter. */ /* DDS_FlowControllerProperty_t custom_fcp; retcode = participant->get_default_flowcontroller_property(custom_fcp); if (retcode != DDS_RETCODE_OK) { return shutdown_participant( participant, "get_default_flowcontroller_property error", EXIT_FAILURE); } */ /* Don't allow too many tokens to accumulate */ /* custom_fcp.token_bucket.max_tokens = custom_fcp.token_bucket.tokens_added_per_period = 2; custom_fcp.token_bucket.tokens_leaked_per_period = DDS_LENGTH_UNLIMITED; */ /* 100ms */ /* custom_fcp.token_bucket.period.sec = 0; custom_fcp.token_bucket.period.nanosec = 100000000; */ /* The sample size is 1000, but the minimum bytes_per_token is 1024. * Furthermore, we want to allow some overhead. */ /* custom_fcp.token_bucket.bytes_per_token = 1024; */ /* So, in summary, each token can be used to send about one message, * and we get 2 tokens every 100ms, so this limits transmissions to * about 20 messages per second. */ /* Create flowcontroller and set properties */ /* DDSFlowController* cfc = NULL; cfc = participant->create_flowcontroller(DDS_String_dup(cfc_name), custom_fcp); if (cfc == NULL) { return shutdown_participant( participant, "create_flowcontroller error", EXIT_FAILURE); } */ /* Get default datawriter QoS to customize */ /* 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); } */ /* As an alternative to increasing h istory depth, we can just * set the qos to keep all samples */ /* datawriter_qos.history.kind = DDS_KEEP_ALL_HISTORY_QOS; */ /* Set flowcontroller for datawriter */ /* datawriter_qos.publish_mode.kind = DDS_ASYNCHRONOUS_PUBLISH_MODE_QOS; datawriter_qos.publish_mode.flow_controller_name = DDS_String_dup(cfc_name); */ /* To create datawriter with default QoS, use DDS_DATAWRITER_QOS_DEFAULT instead of datawriter_qos */ /* DDSDataWriter *untyped_writer = publisher->create_datawriter( topic, datawriter_qos, NULL, DDS_STATUS_MASK_NONE); if (untyped_writer == NULL) { return shutdown_participant( participant, "create_datawriter error", EXIT_FAILURE); } */ /* End changes for custom_flowcontroller */ cfcDataWriter *typed_writer = cfcDataWriter::narrow(untyped_writer); if (typed_writer == NULL) { return shutdown_participant( participant, "DataWriter narrow error", EXIT_FAILURE); } /* Create data sample for writing */ cfc *data = cfcTypeSupport::create_data(); if (data == NULL) { return shutdown_participant( participant, "cfcTypeSupport::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 = cfc_writer->register_instance(*data); */ // Main loop, write data int sample; for (unsigned int samples_written = 0; !shutdown_requested && samples_written < sample_count; ++samples_written) { /* Changes for custom_flowcontroller */ /* Simulate bursty writer */ NDDSUtility::sleep(send_period); for (int i = 0; i < 10; ++i) { sample = samples_written * 10 + i; std::cout << "Writing cfc, sample " << sample << std::endl; data->x = sample; memset(data->str, 1, 999); data->str[999] = 0; retcode = typed_writer->write(*data, instance_handle); if (retcode != DDS_RETCODE_OK) { std::cerr << "write error " << retcode << std::endl; } } } /* This new sleep it is for let time to the subscriber to read all the * sent samples. */ send_period.sec = 4; NDDS_Utility_sleep(&send_period); /* retcode = typed_writer->unregister_instance(*data, instance_handle); if (retcode != DDS_RETCODE_OK) { std::cerr << "unregister instance error " << retcode << std::endl; } */ // Delete previously allocated cfc, including all contained elements retcode = cfcTypeSupport::delete_data(data); if (retcode != DDS_RETCODE_OK) { std::cerr << "cfcTypeSupport::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/custom_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/custom_flow_controller/c/cfc_publisher.c
/******************************************************************************* (c) 2005-2014 Copyright, Real-Time Innovations, Inc. All rights reserved. RTI grants Licensee a license to use, modify, compile, and create derivative works of the Software. Licensee has the right to distribute object form only for use with RTI products. The Software is provided "as is", with no warranty of any type, including any warranty for fitness for any purpose. RTI is under no obligation to maintain or support the Software. RTI shall not be liable for any incidental or consequential damages arising out of the use or inability to use the software. ******************************************************************************/ /* cfc_publisher.c A publication of data of type cfc This file is derived from code automatically generated by the rtiddsgen command: rtiddsgen -language C -example <arch> cfc.idl Example publication of type cfc automatically generated by 'rtiddsgen'. To test them follow these steps: (1) Compile this file and the example subscription. (2) Start the subscription with the command objs/<arch>/cfc_subscriber <domain_id> <sample_count> (3) Start the publication with the command objs/<arch>/cfc_publisher <domain_id> <sample_count> (4) [Optional] Specify the list of discovery initial peers and multicast receive addresses via an environment variable or a file (in the current working directory) called NDDS_DISCOVERY_PEERS. You can run any number of publishers and subscribers programs, and can add and remove them dynamically from the domain. Example: To run the example application on domain <domain_id>: On Unix: objs/<arch>/cfc_publisher <domain_id> objs/<arch>/cfc_subscriber <domain_id> On Windows: objs\<arch>\cfc_publisher <domain_id> objs\<arch>\cfc_subscriber <domain_id> modification history ------------ ------- */ #include "cfc.h" #include "cfcSupport.h" #include "ndds/ndds_c.h" #include <stdio.h> #include <stdlib.h> /* Delete all entities */ static int publisher_shutdown( DDS_DomainParticipant *participant, struct DDS_DomainParticipantQos *participant_qos, struct DDS_DataWriterQos *datawriter_qos) { DDS_ReturnCode_t retcode; int status = 0; if (participant != NULL) { retcode = DDS_DomainParticipant_delete_contained_entities(participant); if (retcode != DDS_RETCODE_OK) { printf("delete_contained_entities error %d\n", retcode); status = -1; } retcode = DDS_DomainParticipantFactory_delete_participant( DDS_TheParticipantFactory, participant); if (retcode != DDS_RETCODE_OK) { printf("delete_participant error %d\n", retcode); status = -1; } } retcode = DDS_DomainParticipantQos_finalize(participant_qos); if (retcode != DDS_RETCODE_OK) { printf("participantQos_finalize error %d\n", retcode); status = -1; } retcode = DDS_DataWriterQos_finalize(datawriter_qos); if (retcode != DDS_RETCODE_OK) { printf("dataWriterQos_finalize error %d\n", retcode); status = -1; } /* RTI Connext provides finalize_instance() method on domain participant factory for people who want to release memory used by the participant factory. Uncomment the following block of code for clean destruction of the singleton. */ /* retcode = DDS_DomainParticipantFactory_finalize_instance(); if (retcode != DDS_RETCODE_OK) { printf("finalize_instance error %d\n", retcode); status = -1; } */ return status; } static int publisher_main(int domainId, int sample_count) { DDS_DomainParticipant *participant = NULL; DDS_Publisher *publisher = NULL; DDS_Topic *topic = NULL; DDS_DataWriter *writer = NULL; cfcDataWriter *cfc_writer = NULL; cfc *instance = NULL; DDS_ReturnCode_t retcode; DDS_InstanceHandle_t instance_handle = DDS_HANDLE_NIL; const char *type_name = NULL; int count = 0; int i; int sample; struct DDS_Duration_t send_period = { 1, 0 }; const char *cfc_name = "custom_flowcontroller"; struct DDS_FlowControllerProperty_t custom_fcp; DDS_FlowController *cfc = NULL; struct DDS_DataWriterQos datawriter_qos = DDS_DataWriterQos_INITIALIZER; struct DDS_DomainParticipantQos participant_qos = DDS_DomainParticipantQos_INITIALIZER; participant = DDS_DomainParticipantFactory_create_participant( DDS_TheParticipantFactory, domainId, &DDS_PARTICIPANT_QOS_DEFAULT, NULL /* listener */, DDS_STATUS_MASK_NONE); if (participant == NULL) { printf("create_participant error\n"); publisher_shutdown(participant, &participant_qos, &datawriter_qos); return -1; } /* Start changes for custom_flowcontroller */ /* If you want to change the Participant's QoS programmatically rather than * using the XML file, you will need to add the following lines to your * code and comment out the create_participant call above. */ /* Get default participant QoS to customize */ /* retcode = DDS_DomainParticipantFactory_get_default_participant_qos( DDS_TheParticipantFactory, &participant_qos); if (retcode != DDS_RETCODE_OK) { printf("get_default_participant_qos error\n"); return -1; } */ /* By default, data will be sent via shared memory _and_ UDPv4. Because * the flowcontroller limits writes across all interfaces, this halves the * effective send rate. To avoid this, we enable only the UDPv4 transport */ /* participant_qos.transport_builtin.mask = DDS_TRANSPORTBUILTIN_UDPv4; */ /* To create participant with default QoS, use DDS_PARTICIPANT_QOS_DEFAULT instead of participant_qos */ /* participant = DDS_DomainParticipantFactory_create_participant( DDS_TheParticipantFactory, domainId, &participant_qos, NULL, DDS_STATUS_MASK_NONE); if (participant == NULL) { printf("create_participant error\n"); publisher_shutdown(participant, &participant_qos, &datawriter_qos); return -1; } */ /* End changes for Custom_Flowcontroller */ /* To customize publisher QoS, use the configuration file USER_QOS_PROFILES.xml */ publisher = DDS_DomainParticipant_create_publisher( participant, &DDS_PUBLISHER_QOS_DEFAULT, NULL /* listener */, DDS_STATUS_MASK_NONE); if (publisher == NULL) { printf("create_publisher error\n"); publisher_shutdown(participant, &participant_qos, &datawriter_qos); return -1; } /* Register type before creating topic */ type_name = cfcTypeSupport_get_type_name(); retcode = cfcTypeSupport_register_type(participant, type_name); if (retcode != DDS_RETCODE_OK) { printf("register_type error %d\n", retcode); publisher_shutdown(participant, &participant_qos, &datawriter_qos); return -1; } /* To customize topic QoS, use the configuration file USER_QOS_PROFILES.xml */ topic = DDS_DomainParticipant_create_topic( participant, "Example cfc", type_name, &DDS_TOPIC_QOS_DEFAULT, NULL /* listener */, DDS_STATUS_MASK_NONE); if (topic == NULL) { printf("create_topic error\n"); publisher_shutdown(participant, &participant_qos, &datawriter_qos); return -1; } /* To customize data writer QoS, use the configuration file USER_QOS_PROFILES.xml */ writer = DDS_Publisher_create_datawriter( publisher, topic, &DDS_DATAWRITER_QOS_DEFAULT, NULL /* listener */, DDS_STATUS_MASK_NONE); if (writer == NULL) { printf("create_datawriter error\n"); publisher_shutdown(participant, &participant_qos, &datawriter_qos); return -1; } /* Start changes for custom_flowcontroller */ /* If you want to change the Datawriter's QoS programmatically rather than * using the XML file, you will need to add the following lines to your * code and comment out the create_datawriter call above. * * In this case we create the flowcontroller and the neccesary QoS * for the datawriter. */ /* retcode = DDS_DomainParticipant_get_default_flowcontroller_property( participant, &custom_fcp); if (retcode != DDS_RETCODE_OK) { printf("get_default_flowcontroller_property error \n"); return -1; } */ /* Don't allow too many tokens to accumulate */ /* custom_fcp.token_bucket.max_tokens = custom_fcp.token_bucket.tokens_added_per_period = 2; custom_fcp.token_bucket.tokens_leaked_per_period = DDS_LENGTH_UNLIMITED; */ /* 100ms */ /* custom_fcp.token_bucket.period.sec = 0; custom_fcp.token_bucket.period.nanosec = 100000000; */ /* The sample size is 1000, but the minimum bytes_per_token is 1024. * Furthermore, we want to allow some overhead. */ /* custom_fcp.token_bucket.bytes_per_token = 1024; */ /* So, in summary, each token can be used to send about one message, * and we get 2 tokens every 100ms, so this limits transmissions to * about 20 messages per second. */ /* Create flowcontroller and set properties */ /* cfc = DDS_DomainParticipant_create_flowcontroller( participant, DDS_String_dup(cfc_name), &custom_fcp); if (cfc == NULL) { printf("create_flowcontroller error\n"); return -1; } */ /* Get default datawriter QoS to customize */ /* retcode = DDS_Publisher_get_default_datawriter_qos(publisher, &datawriter_qos); if (retcode != DDS_RETCODE_OK) { printf("get_default_datawriter_qos error\n"); return -1; } */ /* As an alternative to increasing history depth, we can just * set the qos to keep all samples */ /* datawriter_qos.history.kind = DDS_KEEP_ALL_HISTORY_QOS; */ /* Set flowcontroller for datawriter */ /* datawriter_qos.publish_mode.kind = DDS_ASYNCHRONOUS_PUBLISH_MODE_QOS; datawriter_qos.publish_mode.flow_controller_name = DDS_String_dup(cfc_name); */ /* To create datawriter with default QoS, use DDS_DATAWRITER_QOS_DEFAULT instead of datawriter_qos */ /* writer = DDS_Publisher_create_datawriter( publisher, topic, &datawriter_qos, NULL, DDS_STATUS_MASK_NONE); if (writer == NULL) { printf("create_datawriter error\n"); publisher_shutdown(participant, &participant_qos, &datawriter_qos); return -1; } */ /* End changes for Custom_Flowcontroller */ cfc_writer = cfcDataWriter_narrow(writer); if (cfc_writer == NULL) { printf("DataWriter narrow error\n"); publisher_shutdown(participant, &participant_qos, &datawriter_qos); return -1; } /* Create data sample for writing */ instance = cfcTypeSupport_create_data_ex(DDS_BOOLEAN_TRUE); if (instance == NULL) { printf("cfcTypeSupport_create_data error\n"); publisher_shutdown(participant, &participant_qos, &datawriter_qos); return -1; } /* For a data type that has a key, if the same instance is going to be written multiple times, initialize the key here and register the keyed instance prior to writing */ /* instance_handle = cfcDataWriter_register_instance( cfc_writer, instance); */ /* Main loop */ for (count = 0; (sample_count == 0) || (count < sample_count); ++count) { /* Changes for custom_flowcontroller */ /* Simulate bursty writer */ NDDS_Utility_sleep(&send_period); for (i = 0; i < 10; ++i) { sample = count * 10 + i; printf("Writing cfc, sample %d\n", sample); instance->x = sample; memset(instance->str, 1, 999); instance->str[999] = 0; retcode = cfcDataWriter_write(cfc_writer, instance, &instance_handle); if (retcode != DDS_RETCODE_OK) { printf("write error %d\n", retcode); } } } /* This new sleep it is for let time to the subscriber to read all the * sent samples. */ send_period.sec = 4; NDDS_Utility_sleep(&send_period); /* retcode = cfcDataWriter_unregister_instance( cfc_writer, instance, &instance_handle); if (retcode != DDS_RETCODE_OK) { printf("unregister instance error %d\n", retcode); } */ /* Delete data sample */ retcode = cfcTypeSupport_delete_data_ex(instance, DDS_BOOLEAN_TRUE); if (retcode != DDS_RETCODE_OK) { printf("cfcTypeSupport_delete_data error %d\n", retcode); } /* Cleanup and delete delete all entities */ return publisher_shutdown(participant, &participant_qos, &datawriter_qos); } #if defined(RTI_WINCE) int wmain(int argc, wchar_t **argv) { int domainId = 0; int sample_count = 0; /* infinite loop */ if (argc >= 2) { domainId = _wtoi(argv[1]); } if (argc >= 3) { sample_count = _wtoi(argv[2]); } /* Uncomment this to turn on additional logging NDDS_Config_Logger_set_verbosity_by_category( NDDS_Config_Logger_get_instance(), NDDS_CONFIG_LOG_CATEGORY_API, NDDS_CONFIG_LOG_VERBOSITY_STATUS_ALL); */ return publisher_main(domainId, sample_count); } #elif !(defined(RTI_VXWORKS) && !defined(__RTP__)) && !defined(RTI_PSOS) int main(int argc, char *argv[]) { int domainId = 0; int sample_count = 0; /* infinite loop */ if (argc >= 2) { domainId = atoi(argv[1]); } if (argc >= 3) { sample_count = atoi(argv[2]); } /* Uncomment this to turn on additional logging NDDS_Config_Logger_set_verbosity_by_category( NDDS_Config_Logger_get_instance(), NDDS_CONFIG_LOG_CATEGORY_API, NDDS_CONFIG_LOG_VERBOSITY_STATUS_ALL); */ return publisher_main(domainId, sample_count); } #endif #ifdef RTI_VX653 const unsigned char *__ctype = NULL; void usrAppInit() { #ifdef USER_APPL_INIT USER_APPL_INIT; /* for backwards compatibility */ #endif /* add application specific code here */ taskSpawn( "pub", RTI_OSAPI_THREAD_PRIORITY_NORMAL, 0x8, 0x150000, (FUNCPTR) publisher_main, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0); } #endif
c
rticonnextdds-examples
data/projects/rticonnextdds-examples/connext_dds/custom_flow_controller/c/cfc_subscriber.c
/******************************************************************************* (c) 2005-2014 Copyright, Real-Time Innovations, Inc. All rights reserved. RTI grants Licensee a license to use, modify, compile, and create derivative works of the Software. Licensee has the right to distribute object form only for use with RTI products. The Software is provided "as is", with no warranty of any type, including any warranty for fitness for any purpose. RTI is under no obligation to maintain or support the Software. RTI shall not be liable for any incidental or consequential damages arising out of the use or inability to use the software. ******************************************************************************/ /* cfc_subscriber.c A subscription example This file is derived from code automatically generated by the rtiddsgen command: rtiddsgen -language C -example <arch> cfc.idl Example subscription of type cfc automatically generated by 'rtiddsgen'. To test them, follow these steps: (1) Compile this file and the example publication. (2) Start the subscription with the command objs/<arch>/cfc_subscriber <domain_id> <sample_count> (3) Start the publication with the command objs/<arch>/cfc_publisher <domain_id> <sample_count> (4) [Optional] Specify the list of discovery initial peers and multicast receive addresses via an environment variable or a file (in the current working directory) called NDDS_DISCOVERY_PEERS. You can run any number of publishers and subscribers programs, and can add and remove them dynamically from the domain. Example: To run the example application on domain <domain_id>: On UNIX systems: objs/<arch>/cfc_publisher <domain_id> objs/<arch>/cfc_subscriber <domain_id> On Windows systems: objs\<arch>\cfc_publisher <domain_id> objs\<arch>\cfc_subscriber <domain_id> modification history ------------ ------- */ #include "cfc.h" #include "cfcSupport.h" #include "ndds/ndds_c.h" #include <stdio.h> #include <stdlib.h> /* Changes for Custom_Flowcontroller */ /* For timekeeping */ #include <time.h> clock_t init; void cfcListener_on_requested_deadline_missed( void *listener_data, DDS_DataReader *reader, const struct DDS_RequestedDeadlineMissedStatus *status) { } void cfcListener_on_requested_incompatible_qos( void *listener_data, DDS_DataReader *reader, const struct DDS_RequestedIncompatibleQosStatus *status) { } void cfcListener_on_sample_rejected( void *listener_data, DDS_DataReader *reader, const struct DDS_SampleRejectedStatus *status) { } void cfcListener_on_liveliness_changed( void *listener_data, DDS_DataReader *reader, const struct DDS_LivelinessChangedStatus *status) { } void cfcListener_on_sample_lost( void *listener_data, DDS_DataReader *reader, const struct DDS_SampleLostStatus *status) { } void cfcListener_on_subscription_matched( void *listener_data, DDS_DataReader *reader, const struct DDS_SubscriptionMatchedStatus *status) { } void cfcListener_on_data_available(void *listener_data, DDS_DataReader *reader) { cfcDataReader *cfc_reader = NULL; struct cfcSeq data_seq = DDS_SEQUENCE_INITIALIZER; struct DDS_SampleInfoSeq info_seq = DDS_SEQUENCE_INITIALIZER; DDS_ReturnCode_t retcode; int i; double elapsed_ticks, elapsed_secs; cfc_reader = cfcDataReader_narrow(reader); if (cfc_reader == NULL) { printf("DataReader narrow error\n"); return; } retcode = cfcDataReader_take( cfc_reader, &data_seq, &info_seq, DDS_LENGTH_UNLIMITED, DDS_ANY_SAMPLE_STATE, DDS_ANY_VIEW_STATE, DDS_ANY_INSTANCE_STATE); if (retcode == DDS_RETCODE_NO_DATA) { return; } else if (retcode != DDS_RETCODE_OK) { printf("take error %d\n", retcode); return; } for (i = 0; i < cfcSeq_get_length(&data_seq); ++i) { if (DDS_SampleInfoSeq_get_reference(&info_seq, i)->valid_data) { /* Start changes for flow_controller */ /* print the time we get each sample */ elapsed_ticks = clock() - init; elapsed_secs = elapsed_ticks / CLOCKS_PER_SEC; printf("@ t=%.2fs, got x = %d\n", elapsed_secs, cfcSeq_get_reference(&data_seq, i)->x); /* End changes for flow_controller */ } } retcode = cfcDataReader_return_loan(cfc_reader, &data_seq, &info_seq); if (retcode != DDS_RETCODE_OK) { printf("return loan error %d\n", retcode); } } /* Delete all entities */ static int subscriber_shutdown( DDS_DomainParticipant *participant, struct DDS_DomainParticipantQos *participant_qos) { DDS_ReturnCode_t retcode; int status = 0; if (participant != NULL) { retcode = DDS_DomainParticipant_delete_contained_entities(participant); if (retcode != DDS_RETCODE_OK) { printf("delete_contained_entities error %d\n", retcode); status = -1; } retcode = DDS_DomainParticipantFactory_delete_participant( DDS_TheParticipantFactory, participant); if (retcode != DDS_RETCODE_OK) { printf("delete_participant error %d\n", retcode); status = -1; } } retcode = DDS_DomainParticipantQos_finalize(participant_qos); if (retcode != DDS_RETCODE_OK) { printf("participantQos_finalize error %d\n", retcode); status = -1; } /* RTI Connext provides the finalize_instance() method on domain participant factory for users who want to release memory used by the participant factory. Uncomment the following block of code for clean destruction of the singleton. */ /* retcode = DDS_DomainParticipantFactory_finalize_instance(); if (retcode != DDS_RETCODE_OK) { printf("finalize_instance error %d\n", retcode); status = -1; } */ return status; } static int subscriber_main(int domainId, int sample_count) { DDS_DomainParticipant *participant = NULL; DDS_Subscriber *subscriber = NULL; DDS_Topic *topic = NULL; struct DDS_DataReaderListener reader_listener = DDS_DataReaderListener_INITIALIZER; DDS_DataReader *reader = NULL; DDS_ReturnCode_t retcode; const char *type_name = NULL; int count = 0; struct DDS_Duration_t poll_period = { 1, 0 }; struct DDS_DomainParticipantQos participant_qos = DDS_DomainParticipantQos_INITIALIZER; /* Start changes for Custom_Flowcontroller */ /* for timekeeping */ init = clock(); /* To customize participant QoS, use the configuration file USER_QOS_PROFILES.xml */ participant = DDS_DomainParticipantFactory_create_participant( DDS_TheParticipantFactory, domainId, &DDS_PARTICIPANT_QOS_DEFAULT, NULL /* listener */, DDS_STATUS_MASK_NONE); if (participant == NULL) { printf("create_participant error\n"); subscriber_shutdown(participant, &participant_qos); return -1; } /* If you want to change the Participant's QoS programmatically rather than * using the XML file, you will need to add the following lines to your * code and comment out the create_participant call above. */ /* By default, discovery will communicate via shared memory for platforms * that support it. Because we disable shared memory on the publishing * side, we do so here to ensure the reader and writer discover each other. */ /* retcode = DDS_DomainParticipantFactory_get_default_participant_qos( DDS_TheParticipantFactory, &participant_qos); if (retcode != DDS_RETCODE_OK) { printf("get_default_participant_qos error\n"); return -1; } participant_qos.transport_builtin.mask = DDS_TRANSPORTBUILTIN_UDPv4; */ /* To create participant with default QoS, use DDS_PARTICIPANT_QOS_DEFAULT instead of participant_qos */ /* participant = DDS_DomainParticipantFactory_create_participant( DDS_TheParticipantFactory, domainId, &participant_qos, NULL, DDS_STATUS_MASK_NONE); if (participant == NULL) { printf("create_participant error\n"); subscriber_shutdown(participant, &participant_qos); return -1; } */ /* End changes for Custom_Flowcontroller */ /* To customize subscriber QoS, use the configuration file USER_QOS_PROFILES.xml */ subscriber = DDS_DomainParticipant_create_subscriber( participant, &DDS_SUBSCRIBER_QOS_DEFAULT, NULL /* listener */, DDS_STATUS_MASK_NONE); if (subscriber == NULL) { printf("create_subscriber error\n"); subscriber_shutdown(participant, &participant_qos); return -1; } /* Register the type before creating the topic */ type_name = cfcTypeSupport_get_type_name(); retcode = cfcTypeSupport_register_type(participant, type_name); if (retcode != DDS_RETCODE_OK) { printf("register_type error %d\n", retcode); subscriber_shutdown(participant, &participant_qos); return -1; } /* To customize topic QoS, use the configuration file USER_QOS_PROFILES.xml */ topic = DDS_DomainParticipant_create_topic( participant, "Example cfc", type_name, &DDS_TOPIC_QOS_DEFAULT, NULL /* listener */, DDS_STATUS_MASK_NONE); if (topic == NULL) { printf("create_topic error\n"); subscriber_shutdown(participant, &participant_qos); return -1; } /* Set up a data reader listener */ reader_listener.on_requested_deadline_missed = cfcListener_on_requested_deadline_missed; reader_listener.on_requested_incompatible_qos = cfcListener_on_requested_incompatible_qos; reader_listener.on_sample_rejected = cfcListener_on_sample_rejected; reader_listener.on_liveliness_changed = cfcListener_on_liveliness_changed; reader_listener.on_sample_lost = cfcListener_on_sample_lost; reader_listener.on_subscription_matched = cfcListener_on_subscription_matched; reader_listener.on_data_available = cfcListener_on_data_available; /* To customize data reader QoS, use the configuration file USER_QOS_PROFILES.xml */ reader = DDS_Subscriber_create_datareader( subscriber, DDS_Topic_as_topicdescription(topic), &DDS_DATAREADER_QOS_DEFAULT, &reader_listener, DDS_STATUS_MASK_ALL); if (reader == NULL) { printf("create_datareader error\n"); subscriber_shutdown(participant, &participant_qos); return -1; } /* Main loop */ for (count = 0; (sample_count == 0) || (count < sample_count); ++count) { NDDS_Utility_sleep(&poll_period); } /* Cleanup and delete all entities */ return subscriber_shutdown(participant, &participant_qos); } #if defined(RTI_WINCE) int wmain(int argc, wchar_t **argv) { int domainId = 0; int sample_count = 0; /* infinite loop */ if (argc >= 2) { domainId = _wtoi(argv[1]); } if (argc >= 3) { sample_count = _wtoi(argv[2]); } /* Uncomment this to turn on additional logging NDDS_Config_Logger_set_verbosity_by_category( NDDS_Config_Logger_get_instance(), NDDS_CONFIG_LOG_CATEGORY_API, NDDS_CONFIG_LOG_VERBOSITY_STATUS_ALL); */ return subscriber_main(domainId, sample_count); } #elif !(defined(RTI_VXWORKS) && !defined(__RTP__)) && !defined(RTI_PSOS) int main(int argc, char *argv[]) { int domainId = 0; int sample_count = 0; /* infinite loop */ if (argc >= 2) { domainId = atoi(argv[1]); } if (argc >= 3) { sample_count = atoi(argv[2]); } /* Uncomment this to turn on additional logging NDDS_Config_Logger_set_verbosity_by_category( NDDS_Config_Logger_get_instance(), NDDS_CONFIG_LOG_CATEGORY_API, NDDS_CONFIG_LOG_VERBOSITY_STATUS_ALL); */ return subscriber_main(domainId, sample_count); } #endif #ifdef RTI_VX653 const unsigned char *__ctype = NULL; void usrAppInit() { #ifdef USER_APPL_INIT USER_APPL_INIT; /* for backwards compatibility */ #endif /* add application specific code here */ taskSpawn( "sub", RTI_OSAPI_THREAD_PRIORITY_NORMAL, 0x8, 0x150000, (FUNCPTR) subscriber_main, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0); } #endif
c
rticonnextdds-examples
data/projects/rticonnextdds-examples/connext_dds/custom_flow_controller/c++03/cfc_subscriber.cxx
/******************************************************************************* (c) 2005-2015 Copyright, Real-Time Innovations, Inc. All rights reserved. RTI grants Licensee a license to use, modify, compile, and create derivative works of the Software. Licensee has the right to distribute object form only for use with RTI products. The Software is provided "as is", with no warranty of any type, including any warranty for fitness for any purpose. RTI is under no obligation to maintain or support the Software. RTI shall not be liable for any incidental or consequential damages arising out of the use or inability to use the software. ******************************************************************************/ #include <cstdlib> #include <ctime> #include <iostream> #include "cfc.hpp" #include <dds/dds.hpp> #include <rti/core/ListenerBinder.hpp> using namespace dds::core; using namespace rti::core; using namespace dds::core::status; using namespace dds::domain; using namespace dds::domain::qos; using namespace dds::sub; using namespace dds::topic; clock_t Init_time; class cfcReaderListener : public NoOpDataReaderListener<cfc> { public: void on_data_available(DataReader<cfc> &reader) { // Take all samples LoanedSamples<cfc> samples = reader.take(); for (LoanedSamples<cfc>::iterator sample_it = samples.begin(); sample_it != samples.end(); sample_it++) { if (sample_it->info().valid()) { // Print the time we get each sample. double elapsed_ticks = clock() - Init_time; double elapsed_secs = elapsed_ticks / CLOCKS_PER_SEC; std::cout << "@ t=" << elapsed_secs << "s, got x = " << sample_it->data().x() << std::endl; } } } }; void subscriber_main(int domain_id, int sample_count) { // For timekeeping. Init_time = clock(); // Retrieve the default Participant QoS, from USER_QOS_PROFILES.xml DomainParticipantQos participant_qos = QosProvider::Default().participant_qos(); // If you want to change the Participant's QoS programmatically rather than // using the XML file, uncomment the following lines. // // By default, data will be sent via shared memory "and" UDPv4. // Because the flowcontroller limits writes across all interfaces, // this halves the effective send rate. To avoid this, we enable only the // UDPv4 transport. // participant_qos << TransportBuiltin::UDPv4(); // Create a DomainParticipant. DomainParticipant participant(domain_id, participant_qos); // Create a Topic -- and automatically register the type Topic<cfc> topic(participant, "Example cfc"); // Create a DataReader with default Qos (Subscriber created in-line) DataReader<cfc> reader(Subscriber(participant), topic); // Associate a listener to the DataReader using ListenerBinder, a RAII that // will take care of setting it to NULL on destruction. ListenerBinder<DataReader<cfc> > reader_listener = rti::core::bind_and_manage_listener( reader, new cfcReaderListener, StatusMask::all()); std::cout << std::fixed; for (int count = 0; sample_count == 0 || count < sample_count; ++count) { rti::util::sleep(dds::core::Duration(1)); } } int main(int argc, char *argv[]) { int domain_id = 0; int sample_count = 0; // infinite loop if (argc >= 2) { domain_id = atoi(argv[1]); } if (argc >= 3) { sample_count = atoi(argv[2]); } // To turn on additional logging, include <rti/config/Logger.hpp> and // uncomment the following line: // rti::config::Logger::instance().verbosity(rti::config::Verbosity::STATUS_ALL); try { subscriber_main(domain_id, sample_count); } catch (const std::exception &ex) { // This will catch DDS exceptions std::cerr << "Exception in subscriber_main(): " << ex.what() << std::endl; return -1; } // RTI Connext provides a finalize_participant_factory() method // if you want to release memory used by the participant factory singleton. // Uncomment the following line to release the singleton: // // dds::domain::DomainParticipant::finalize_participant_factory(); return 0; }
cxx
rticonnextdds-examples
data/projects/rticonnextdds-examples/connext_dds/custom_flow_controller/c++03/cfc_publisher.cxx
/******************************************************************************* (c) 2005-2015 Copyright, Real-Time Innovations, Inc. All rights reserved. RTI grants Licensee a license to use, modify, compile, and create derivative works of the Software. Licensee has the right to distribute object form only for use with RTI products. The Software is provided "as is", with no warranty of any type, including any warranty for fitness for any purpose. RTI is under no obligation to maintain or support the Software. RTI shall not be liable for any incidental or consequential damages arising out of the use or inability to use the software. ******************************************************************************/ #include <cstdlib> #include <iostream> #include "cfc.hpp" #include <dds/dds.hpp> #include <rti/pub/FlowController.hpp> using namespace dds::core; using namespace dds::core::policy; using namespace rti::core::policy; using namespace dds::domain; using namespace dds::domain::qos; using namespace dds::topic; using namespace dds::pub; using namespace rti::pub; using namespace dds::pub::qos; const std::string flow_controller_name = "custom_flowcontroller"; FlowControllerProperty define_flowcontroller(DomainParticipant &participant) { // Create a custom FlowController based on tocken-bucket mechanism. // First specify the token-bucket configuration. // In summary, each token can be used to send about one message, // and we get 2 tokens every 100 ms, so this limits transmissions to // about 20 messages per second. FlowControllerTokenBucketProperty flowcontroller_tokenbucket; // Don't allow too many tokens to accumulate. flowcontroller_tokenbucket.max_tokens(2); flowcontroller_tokenbucket.tokens_added_per_period(2); flowcontroller_tokenbucket.tokens_leaked_per_period(LENGTH_UNLIMITED); // Period of 100 ms. flowcontroller_tokenbucket.period(Duration::from_millisecs(100)); // The sample size is 1000, but the minimum bytes_per_token is 1024. // Furthermore, we want to allow some overhead. flowcontroller_tokenbucket.bytes_per_token(1024); // Create a FlowController Property to set the TokenBucket definition. FlowControllerProperty flowcontroller_property( FlowControllerSchedulingPolicy::EARLIEST_DEADLINE_FIRST, flowcontroller_tokenbucket); return flowcontroller_property; } void publisher_main(int domain_id, int sample_count) { // Retrieve the default Participant QoS, from USER_QOS_PROFILES.xml DomainParticipantQos participant_qos = QosProvider::Default().participant_qos(); // If you want to change the Participant's QoS programmatically rather than // using the XML file, uncomment the following lines. // // By default, data will be sent via shared memory "and" UDPv4. // Because the flowcontroller limits writes across all interfaces, // this halves the effective send rate. To avoid this, we enable only the // UDPv4 transport. // participant_qos << TransportBuiltin::UDPv4(); // Create a DomainParticipant. DomainParticipant participant(domain_id, participant_qos); // Create the FlowController by code instead of from USER_QOS_PROFILES.xml. FlowControllerProperty flow_controller_property = define_flowcontroller(participant); FlowController flowcontroller( participant, flow_controller_name, flow_controller_property); // Create a Topic -- and automatically register the type Topic<cfc> topic(participant, "Example cfc"); // Retrieve the default DataWriter QoS, from USER_QOS_PROFILES.xml DataWriterQos writer_qos = QosProvider::Default().datawriter_qos(); // If you want to change the DataWriter's QoS programmatically rather than // using the XML file, uncomment the following lines. // writer_qos << History::KeepAll() // << PublishMode::Asynchronous(flow_controller_name); // Create a DataWriter (Publisher created in-line) DataWriter<cfc> writer(Publisher(participant), topic, writer_qos); // Create a sample to write with a long payload. cfc sample; sample.str(std::string(999, 'A')); for (int count = 0; count < sample_count || sample_count == 0; count++) { // Simulate bursty writer. rti::util::sleep(Duration(1)); for (int i = 0; i < 10; i++) { sample.x(count * 10 + i); std::cout << "Writing cfc, sample " << sample.x() << std::endl; writer.write(sample); } } // This new sleep is to give the subscriber time to read all the samples. rti::util::sleep(Duration(4)); } int main(int argc, char *argv[]) { int domain_id = 0; int sample_count = 0; // Infinite loop if (argc >= 2) { domain_id = atoi(argv[1]); } if (argc >= 3) { sample_count = atoi(argv[2]); } // To turn on additional logging, include <rti/config/Logger.hpp> and // uncomment the following line: // rti::config::Logger::instance().verbosity(rti::config::Verbosity::STATUS_ALL); try { publisher_main(domain_id, sample_count); } catch (const std::exception &ex) { // This will catch DDS exceptions std::cerr << "Exception in publisher_main: " << ex.what() << std::endl; return -1; } return 0; }
cxx
rticonnextdds-examples
data/projects/rticonnextdds-examples/connext_dds/custom_flow_controller/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/custom_flow_controller/c++11/cfc_subscriber.cxx
/******************************************************************************* (c) 2005-2015 Copyright, Real-Time Innovations, Inc. All rights reserved. RTI grants Licensee a license to use, modify, compile, and create derivative works of the Software. Licensee has the right to distribute object form only for use with RTI products. The Software is provided "as is", with no warranty of any type, including any warranty for fitness for any purpose. RTI is under no obligation to maintain or support the Software. RTI shall not be liable for any incidental or consequential damages arising out of the use or inability to use the software. ******************************************************************************/ #include <dds/sub/ddssub.hpp> #include <dds/core/ddscore.hpp> #include <rti/config/Logger.hpp> // for logging #include "cfc.hpp" #include "application.hpp" // for command line parsing and ctrl-c clock_t Init_time; int process_data(dds::sub::DataReader<cfc> reader) { int count = 0; // Take all samples dds::sub::LoanedSamples<cfc> samples = reader.take(); for (const auto &sample : samples) { if (sample.info().valid()) { count++; // Print the time we get each sample. double elapsed_ticks = clock() - Init_time; double elapsed_secs = elapsed_ticks / CLOCKS_PER_SEC; std::cout << "@ t=" << elapsed_secs << "s, got x = " << sample.data().x() << std::endl; } } return count; } void run_subscriber_application( unsigned int domain_id, unsigned int sample_count) { // For timekeeping. Init_time = clock(); // Retrieve the default 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. // // By default, data will be sent via shared memory "and" UDPv4. // Because the flowcontroller limits writes across all interfaces, // this halves the effective send rate. To avoid this, we enable only the // UDPv4 transport. // participant_qos << TransportBuiltin::UDPv4(); // Create a DomainParticipant. dds::domain::DomainParticipant participant(domain_id, participant_qos); // Create a Topic -- and automatically register the type dds::topic::Topic<cfc> topic(participant, "Example cfc"); // Create a subscriber dds::sub::Subscriber subscriber(participant); // Create a DataReader with default Qos (Subscriber created in-line) dds::sub::DataReader<cfc> 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::new_data(), [reader, &samples_read]() { samples_read += process_data(reader); }); waitset += read_condition; std::cout << std::fixed; // Main loop 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/custom_flow_controller/c++11/cfc_publisher.cxx
/******************************************************************************* (c) 2005-2015 Copyright, Real-Time Innovations, Inc. All rights reserved. RTI grants Licensee a license to use, modify, compile, and create derivative works of the Software. Licensee has the right to distribute object form only for use with RTI products. The Software is provided "as is", with no warranty of any type, including any warranty for fitness for any purpose. RTI is under no obligation to maintain or support the Software. RTI shall not be liable for any incidental or consequential damages arising out of the use or inability to use the software. ******************************************************************************/ #include <dds/pub/ddspub.hpp> #include <rti/util/util.hpp> // for sleep() #include <rti/config/Logger.hpp> // for logging #include <rti/pub/FlowController.hpp> // for FlowController #include "application.hpp" // for command line parsing and ctrl-c #include "cfc.hpp" const std::string flow_controller_name = "custom_flowcontroller"; rti::pub::FlowControllerProperty define_flowcontroller( dds::domain::DomainParticipant &participant) { // Create a custom FlowController based on tocken-bucket mechanism. // First specify the token-bucket configuration. // In summary, each token can be used to send about one message, // and we get 2 tokens every 100 ms, so this limits transmissions to // about 20 messages per second. rti::pub::FlowControllerTokenBucketProperty flowcontroller_tokenbucket; // Don't allow too many tokens to accumulate. flowcontroller_tokenbucket.max_tokens(2); flowcontroller_tokenbucket.tokens_added_per_period(2); flowcontroller_tokenbucket.tokens_leaked_per_period( dds::core::LENGTH_UNLIMITED); // Period of 100 ms. flowcontroller_tokenbucket.period(dds::core::Duration::from_millisecs(100)); // The sample size is 1000, but the minimum bytes_per_token is 1024. // Furthermore, we want to allow some overhead. flowcontroller_tokenbucket.bytes_per_token(1024); // Create a FlowController Property to set the TokenBucket definition. rti::pub::FlowControllerProperty flowcontroller_property( rti::pub::FlowControllerSchedulingPolicy::EARLIEST_DEADLINE_FIRST, flowcontroller_tokenbucket); return flowcontroller_property; } void run_publisher_application( unsigned int domain_id, unsigned int sample_count) { // Retrieve the default 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. // // By default, data will be sent via shared memory "and" UDPv4. // Because the flowcontroller limits writes across all interfaces, // this halves the effective send rate. To avoid this, we enable only the // UDPv4 transport. // participant_qos << TransportBuiltin::UDPv4(); // Create a DomainParticipant. dds::domain::DomainParticipant participant(domain_id, participant_qos); // Create the FlowController by code instead of from USER_QOS_PROFILES.xml. rti::pub::FlowControllerProperty flow_controller_property = define_flowcontroller(participant); rti::pub::FlowController flowcontroller( participant, flow_controller_name, flow_controller_property); // Create a Topic -- and automatically register the type dds::topic::Topic<cfc> topic(participant, "Example cfc"); // Retrieve the default DataWriter QoS, from USER_QOS_PROFILES.xml dds::pub::qos::DataWriterQos writer_qos = dds::core::QosProvider::Default().datawriter_qos(); // If you want to change the DataWriter's QoS programmatically rather than // using the XML file, uncomment the following lines. // writer_qos << History::KeepAll() // << PublishMode::Asynchronous(flow_controller_name); // Create a publisher dds::pub::Publisher publisher(participant); // Create a DataWriter (Publisher created in-line) dds::pub::DataWriter<cfc> writer(publisher, topic, writer_qos); // Create a sample to write with a long payload. cfc sample; sample.str(std::string(999, 'A')); for (unsigned int samples_written = 0; !application::shutdown_requested && samples_written < sample_count; samples_written++) { // Simulate bursty writer. rti::util::sleep(dds::core::Duration(1)); for (int i = 0; i < 10; i++) { sample.x(samples_written * 10 + i); std::cout << "Writing cfc, sample " << sample.x() << std::endl; writer.write(sample); } } // This new sleep is to give the subscriber time to read all the samples. rti::util::sleep(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/build_systems/cmake/HelloWorld_publisher.c
/* * (c) 2019 Copyright, Real-Time Innovations, Inc. All rights reserved. * No duplications, whole or partial, manual or electronic, may be made * without express written permission. Any such copies, or revisions thereof, * must display this notice unaltered. * This code contains trade secrets of Real-Time Innovations, Inc. * * A publication example. * * (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 * HelloWorld_subscriber <domain_id> <sample_count> * * (3) Start the publication on the same domain used for RTI Data Distribution * Service with the command * HelloWorld_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. * */ #include "HelloWorld.h" #include "HelloWorldSupport.h" #include "ndds/ndds_c.h" #include <stdio.h> #include <stdlib.h> /* Delete all entities */ static int publisher_shutdown(DDS_DomainParticipant *participant) { DDS_ReturnCode_t retcode; int status = 0; if (participant != NULL) { retcode = DDS_DomainParticipant_delete_contained_entities(participant); if (retcode != DDS_RETCODE_OK) { fprintf(stderr, "delete_contained_entities error %d\n", retcode); status = -1; } retcode = DDS_DomainParticipantFactory_delete_participant( DDS_TheParticipantFactory, participant); if (retcode != DDS_RETCODE_OK) { fprintf(stderr, "delete_participant error %d\n", retcode); status = -1; } } /* RTI Data Distribution Service provides finalize_instance() method on * domain participant factory for people who want to release memory used * by the participant factory. Uncomment the following block of code for * clean destruction of the singleton. * * retcode = DDS_DomainParticipantFactory_finalize_instance(); * if (retcode != DDS_RETCODE_OK) { * fprintf(stderr, "finalize_instance error %d\n", retcode); * status = -1; * } */ return status; } int publisher_main(int domainId, int sample_count) { DDS_DomainParticipant *participant = NULL; DDS_Publisher *publisher = NULL; DDS_Topic *topic = NULL; DDS_DataWriter *writer = NULL; HelloWorldDataWriter *HelloWorld_writer = NULL; HelloWorld *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); return -1; } /* * To customize publisher QoS, use the configuration file * USER_QOS_PROFILES.xml */ publisher = DDS_DomainParticipant_create_publisher( participant, &DDS_PUBLISHER_QOS_DEFAULT, NULL /* listener */, DDS_STATUS_MASK_NONE); if (publisher == NULL) { fprintf(stderr, "create_publisher error\n"); publisher_shutdown(participant); return -1; } /* Register type before creating topic */ type_name = HelloWorldTypeSupport_get_type_name(); retcode = HelloWorldTypeSupport_register_type(participant, type_name); if (retcode != DDS_RETCODE_OK) { fprintf(stderr, "register_type error %d\n", retcode); publisher_shutdown(participant); return -1; } /* * To customize topic QoS, use the configuration file USER_QOS_PROFILES.xml */ topic = DDS_DomainParticipant_create_topic( participant, "Example HelloWorld", type_name, &DDS_TOPIC_QOS_DEFAULT, NULL /* listener */, DDS_STATUS_MASK_NONE); if (topic == NULL) { fprintf(stderr, "create_topic error\n"); publisher_shutdown(participant); return -1; } /* * To customize data writer QoS, use the configuration file * USER_QOS_PROFILES.xml */ writer = DDS_Publisher_create_datawriter( publisher, topic, &DDS_DATAWRITER_QOS_DEFAULT, NULL /* listener */, DDS_STATUS_MASK_NONE); if (writer == NULL) { fprintf(stderr, "create_datawriter error\n"); publisher_shutdown(participant); return -1; } HelloWorld_writer = HelloWorldDataWriter_narrow(writer); if (HelloWorld_writer == NULL) { fprintf(stderr, "DataWriter narrow error\n"); publisher_shutdown(participant); return -1; } /* Create data sample for writing */ instance = HelloWorldTypeSupport_create_data_ex(DDS_BOOLEAN_TRUE); if (instance == NULL) { fprintf(stderr, "HelloWorldTypeSupport_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 = HelloWorldDataWriter_register_instance( * HelloWorld_writer, * instance); */ /* Main loop */ for (count = 0; (sample_count == 0) || (count < sample_count); ++count) { printf("Writing HelloWorld, count %d\n", count); /* Modify the data to be written here */ /* Write data */ retcode = HelloWorldDataWriter_write( HelloWorld_writer, instance, &instance_handle); if (retcode != DDS_RETCODE_OK) { fprintf(stderr, "write error %d\n", retcode); } NDDS_Utility_sleep(&send_period); } /* * * retcode = HelloWorldDataWriter_unregister_instance( * HelloWorld_writer, * instance, * &instance_handle); * if (retcode != DDS_RETCODE_OK) { * fprintf(stderr, "unregister instance error %d\n", retcode); * } */ /* Delete data sample */ retcode = HelloWorldTypeSupport_delete_data_ex(instance, DDS_BOOLEAN_TRUE); if (retcode != DDS_RETCODE_OK) { fprintf(stderr, "HelloWorldTypeSupport_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/build_systems/cmake/HelloWorld_subscriber.c
/* * (c) 2019 Copyright, Real-Time Innovations, Inc. All rights reserved. * No duplications, whole or partial, manual or electronic, may be made * without express written permission. Any such copies, or revisions thereof, * must display this notice unaltered. * This code contains trade secrets of Real-Time Innovations, Inc. * * A subscription example. * * (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 * HelloWorld_subscriber <domain_id> <sample_count> * * (3) Start the publication on the same domain used for RTI Data Distribution * Service with the command * HelloWorld_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. * */ #include "HelloWorld.h" #include "HelloWorldSupport.h" #include "ndds/ndds_c.h" #include <stdio.h> #include <stdlib.h> void HelloWorldListener_on_requested_deadline_missed( void *listener_data, DDS_DataReader *reader, const struct DDS_RequestedDeadlineMissedStatus *status) { } void HelloWorldListener_on_requested_incompatible_qos( void *listener_data, DDS_DataReader *reader, const struct DDS_RequestedIncompatibleQosStatus *status) { } void HelloWorldListener_on_sample_rejected( void *listener_data, DDS_DataReader *reader, const struct DDS_SampleRejectedStatus *status) { } void HelloWorldListener_on_liveliness_changed( void *listener_data, DDS_DataReader *reader, const struct DDS_LivelinessChangedStatus *status) { } void HelloWorldListener_on_sample_lost( void *listener_data, DDS_DataReader *reader, const struct DDS_SampleLostStatus *status) { } void HelloWorldListener_on_subscription_matched( void *listener_data, DDS_DataReader *reader, const struct DDS_SubscriptionMatchedStatus *status) { } void HelloWorldListener_on_data_available( void *listener_data, DDS_DataReader *reader) { HelloWorldDataReader *HelloWorld_reader = NULL; struct HelloWorldSeq data_seq = DDS_SEQUENCE_INITIALIZER; struct DDS_SampleInfoSeq info_seq = DDS_SEQUENCE_INITIALIZER; DDS_ReturnCode_t retcode; int i; HelloWorld_reader = HelloWorldDataReader_narrow(reader); if (HelloWorld_reader == NULL) { fprintf(stderr, "DataReader narrow error\n"); return; } retcode = HelloWorldDataReader_take( HelloWorld_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 < HelloWorldSeq_get_length(&data_seq); ++i) { if (DDS_SampleInfoSeq_get_reference(&info_seq, i)->valid_data) { printf("Received data\n"); HelloWorldTypeSupport_print_data( HelloWorldSeq_get_reference(&data_seq, i)); } } retcode = HelloWorldDataReader_return_loan( HelloWorld_reader, &data_seq, &info_seq); if (retcode != DDS_RETCODE_OK) { fprintf(stderr, "return loan error %d\n", retcode); } } /* Delete all entities */ static int subscriber_shutdown(DDS_DomainParticipant *participant) { DDS_ReturnCode_t retcode; int status = 0; if (participant != NULL) { retcode = DDS_DomainParticipant_delete_contained_entities(participant); if (retcode != DDS_RETCODE_OK) { fprintf(stderr, "delete_contained_entities error %d\n", retcode); status = -1; } retcode = DDS_DomainParticipantFactory_delete_participant( DDS_TheParticipantFactory, participant); if (retcode != DDS_RETCODE_OK) { fprintf(stderr, "delete_participant error %d\n", retcode); status = -1; } } /* RTI Data Distribution Service provides the finalize_instance() method on * domain participant factory for users who want to release memory used * by the participant factory. Uncomment the following block of code for * clean destruction of the singleton. * * retcode = DDS_DomainParticipantFactory_finalize_instance(); * if (retcode != DDS_RETCODE_OK) { * fprintf(stderr, "finalize_instance error %d\n", retcode); * status = -1; * } */ return status; } int subscriber_main(int domainId, int sample_count) { DDS_DomainParticipant *participant = NULL; DDS_Subscriber *subscriber = NULL; DDS_Topic *topic = NULL; struct DDS_DataReaderListener reader_listener = DDS_DataReaderListener_INITIALIZER; DDS_DataReader *reader = NULL; DDS_ReturnCode_t retcode; const char *type_name = NULL; int count = 0; struct DDS_Duration_t poll_period = { 4, 0 }; /* * To customize participant QoS, use the configuration file * USER_QOS_PROFILES.xml */ participant = DDS_DomainParticipantFactory_create_participant( DDS_TheParticipantFactory, domainId, &DDS_PARTICIPANT_QOS_DEFAULT, NULL /* listener */, DDS_STATUS_MASK_NONE); if (participant == NULL) { fprintf(stderr, "create_participant error\n"); subscriber_shutdown(participant); return -1; } /* * To customize subscriber QoS, use the configuration file * USER_QOS_PROFILES.xml */ subscriber = DDS_DomainParticipant_create_subscriber( participant, &DDS_SUBSCRIBER_QOS_DEFAULT, NULL /* listener */, DDS_STATUS_MASK_NONE); if (subscriber == NULL) { fprintf(stderr, "create_subscriber error\n"); subscriber_shutdown(participant); return -1; } /* Register the type before creating the topic */ type_name = HelloWorldTypeSupport_get_type_name(); retcode = HelloWorldTypeSupport_register_type(participant, type_name); if (retcode != DDS_RETCODE_OK) { fprintf(stderr, "register_type error %d\n", retcode); subscriber_shutdown(participant); return -1; } /* * To customize topic QoS, use the configuration file USER_QOS_PROFILES.xml */ topic = DDS_DomainParticipant_create_topic( participant, "Example HelloWorld", type_name, &DDS_TOPIC_QOS_DEFAULT, NULL /* listener */, DDS_STATUS_MASK_NONE); if (topic == NULL) { fprintf(stderr, "create_topic error\n"); subscriber_shutdown(participant); return -1; } /* Set up a data reader listener */ reader_listener.on_requested_deadline_missed = HelloWorldListener_on_requested_deadline_missed; reader_listener.on_requested_incompatible_qos = HelloWorldListener_on_requested_incompatible_qos; reader_listener.on_sample_rejected = HelloWorldListener_on_sample_rejected; reader_listener.on_liveliness_changed = HelloWorldListener_on_liveliness_changed; reader_listener.on_sample_lost = HelloWorldListener_on_sample_lost; reader_listener.on_subscription_matched = HelloWorldListener_on_subscription_matched; reader_listener.on_data_available = HelloWorldListener_on_data_available; /* * To customize data reader QoS, use the configuration file * USER_QOS_PROFILES.xml */ reader = DDS_Subscriber_create_datareader( subscriber, DDS_Topic_as_topicdescription(topic), &DDS_DATAREADER_QOS_DEFAULT, &reader_listener, DDS_STATUS_MASK_ALL); if (reader == NULL) { fprintf(stderr, "create_datareader error\n"); subscriber_shutdown(participant); return -1; } /* Main loop */ for (count = 0; (sample_count == 0) || (count < sample_count); ++count) { printf("HelloWorld 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 */ 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/custom_content_filter/c++/ccf_subscriber.cxx
/******************************************************************************* (c) 2005-2014 Copyright, Real-Time Innovations, Inc. All rights reserved. RTI grants Licensee a license to use, modify, compile, and create derivative works of the Software. Licensee has the right to distribute object form only for use with RTI products. The Software is provided "as is", with no warranty of any type, including any warranty for fitness for any purpose. RTI is under no obligation to maintain or support the Software. RTI shall not be liable for any incidental or consequential damages arising out of the use or inability to use the software. ******************************************************************************/ /* ccf_subscriber.cxx A subscription example This file is derived from code automatically generated by the rtiddsgen command: rtiddsgen -language C++ -example <arch> ccf.idl Example subscription of type ccf automatically generated by 'rtiddsgen'. To test them follow these steps: (1) Compile this file and the example publication. (2) Start the subscription with the command objs/<arch>/ccf_subscriber <domain_id> <sample_count> (3) Start the publication with the command objs/<arch>/ccf_publisher <domain_id> <sample_count> (4) [Optional] Specify the list of discovery initial peers and multicast receive addresses via an environment variable or a file (in the current working directory) called NDDS_DISCOVERY_PEERS. You can run any number of publishers and subscribers programs, and can add and remove them dynamically from the domain. Example: To run the example application on domain <domain_id>: On Unix: objs/<arch>/ccf_publisher <domain_id> objs/<arch>/ccf_subscriber <domain_id> On Windows: objs\<arch>\ccf_publisher <domain_id> objs\<arch>\ccf_subscriber <domain_id> modification history ------------ ------- 21May2014,amb Example adapted for RTI Connext DDS 5.1 */ #include <stdio.h> #include <stdlib.h> #ifdef RTI_VX653 #include <vThreadsData.h> #endif #include "ccf.h" #include "ccfSupport.h" #include "ndds/ndds_cpp.h" /* Custom filter defined here */ #include "filter.cxx" class ccfListener : public DDSDataReaderListener { public: virtual void on_requested_deadline_missed( DDSDataReader * /*reader*/, const DDS_RequestedDeadlineMissedStatus & /*status*/) { } virtual void on_requested_incompatible_qos( DDSDataReader * /*reader*/, const DDS_RequestedIncompatibleQosStatus & /*status*/) { } virtual void on_sample_rejected( DDSDataReader * /*reader*/, const DDS_SampleRejectedStatus & /*status*/) { } virtual void on_liveliness_changed( DDSDataReader * /*reader*/, const DDS_LivelinessChangedStatus & /*status*/) { } virtual void on_sample_lost( DDSDataReader * /*reader*/, const DDS_SampleLostStatus & /*status*/) { } virtual void on_subscription_matched( DDSDataReader * /*reader*/, const DDS_SubscriptionMatchedStatus & /*status*/) { } virtual void on_data_available(DDSDataReader *reader); }; void ccfListener::on_data_available(DDSDataReader *reader) { ccfDataReader *ccf_reader = NULL; ccfSeq data_seq; DDS_SampleInfoSeq info_seq; DDS_ReturnCode_t retcode; int i; ccf_reader = ccfDataReader::narrow(reader); if (ccf_reader == NULL) { printf("DataReader narrow error\n"); return; } retcode = ccf_reader->take( data_seq, info_seq, DDS_LENGTH_UNLIMITED, DDS_ANY_SAMPLE_STATE, DDS_ANY_VIEW_STATE, DDS_ANY_INSTANCE_STATE); if (retcode == DDS_RETCODE_NO_DATA) { return; } else if (retcode != DDS_RETCODE_OK) { printf("take error %d\n", retcode); return; } for (i = 0; i < data_seq.length(); ++i) { if (info_seq[i].valid_data) { ccfTypeSupport::print_data(&data_seq[i]); } } retcode = ccf_reader->return_loan(data_seq, info_seq); if (retcode != DDS_RETCODE_OK) { printf("return loan error %d\n", retcode); } } /* Delete all entities */ static int subscriber_shutdown(DDSDomainParticipant *participant) { DDS_ReturnCode_t retcode; int status = 0; if (participant != NULL) { retcode = participant->delete_contained_entities(); if (retcode != DDS_RETCODE_OK) { printf("delete_contained_entities error %d\n", retcode); status = -1; } retcode = DDSTheParticipantFactory->delete_participant(participant); if (retcode != DDS_RETCODE_OK) { printf("delete_participant error %d\n", retcode); status = -1; } } /* RTI Connext provides the finalize_instance() method on domain participant factory for people who want to release memory used by the participant factory. Uncomment the following block of code for clean destruction of the singleton. */ /* retcode = DDSDomainParticipantFactory::finalize_instance(); if (retcode != DDS_RETCODE_OK) { printf("finalize_instance error %d\n", retcode); status = -1; } */ return status; } extern "C" int subscriber_main(int domainId, int sample_count) { DDSDomainParticipant *participant = NULL; DDSSubscriber *subscriber = NULL; DDSTopic *topic = NULL; ccfListener *reader_listener = NULL; DDSDataReader *reader = NULL; DDS_ReturnCode_t retcode; const char *type_name = NULL; int count = 0; DDS_Duration_t receive_period = { 1, 0 }; int status = 0; /* To customize the participant QoS, use the configuration file USER_QOS_PROFILES.xml */ participant = DDSTheParticipantFactory->create_participant( domainId, DDS_PARTICIPANT_QOS_DEFAULT, NULL /* listener */, DDS_STATUS_MASK_NONE); if (participant == NULL) { printf("create_participant error\n"); subscriber_shutdown(participant); return -1; } /* To customize the subscriber QoS, use the configuration file USER_QOS_PROFILES.xml */ subscriber = participant->create_subscriber( DDS_SUBSCRIBER_QOS_DEFAULT, NULL /* listener */, DDS_STATUS_MASK_NONE); if (subscriber == NULL) { printf("create_subscriber error\n"); subscriber_shutdown(participant); return -1; } /* Register the type before creating the topic */ type_name = ccfTypeSupport::get_type_name(); retcode = ccfTypeSupport::register_type(participant, type_name); if (retcode != DDS_RETCODE_OK) { printf("register_type error %d\n", retcode); subscriber_shutdown(participant); return -1; } /* To customize the topic QoS, use the configuration file USER_QOS_PROFILES.xml */ topic = participant->create_topic( "Example ccf", type_name, DDS_TOPIC_QOS_DEFAULT, NULL /* listener */, DDS_STATUS_MASK_NONE); if (topic == NULL) { printf("create_topic error\n"); subscriber_shutdown(participant); return -1; } /* Start changes for Custom Content Filter */ /* Create and register custom filter */ custom_filter_type *custom_filter = new custom_filter_type(); retcode = participant->register_contentfilter("CustomFilter", custom_filter); if (retcode != DDS_RETCODE_OK) { printf("Failed to register custom content filter"); subscriber_shutdown(participant); return -1; } DDS_StringSeq parameters(2); const char *param_list[] = { "2", "divides" }; parameters.from_array(param_list, 2); /* Create content filtered topic */ DDSContentFilteredTopic *cft = NULL; cft = participant->create_contentfilteredtopic_with_filter( "ContentFilteredTopic", topic, "%0 %1 x", parameters, "CustomFilter"); if (cft == NULL) { printf("create_contentfilteredtopic error\n"); subscriber_shutdown(participant); return -1; } printf("Filter: 2 divides x\n"); /* Also note that we pass 'cft' rather than 'topic' to the datareader * below */ /* End changes for Custom_Content_Filter */ /* Create a data reader listener */ reader_listener = new ccfListener(); /* * NOTE THAT WE USE THE PREVIOUSLY CREATED CUSTOM FILTERED TOPIC TO READ * NEW SAMPLES */ reader = subscriber->create_datareader( cft, DDS_DATAREADER_QOS_DEFAULT, reader_listener, DDS_STATUS_MASK_ALL); if (reader == NULL) { printf("create_datareader error\n"); subscriber_shutdown(participant); delete reader_listener; return -1; } /* Start Topics/ContentFilter changes */ /* Main loop */ for (count = 0; (sample_count == 0) || (count < sample_count); ++count) { if (count == 10) { printf("changing filter parameters\n"); printf("Filter: 15 greater-than x\n"); DDS_String_free(parameters[0]); DDS_String_free(parameters[1]); parameters[0] = DDS_String_dup("15"); parameters[1] = DDS_String_dup("greater-than"); retcode = cft->set_expression_parameters(parameters); if (retcode != DDS_RETCODE_OK) { printf("set_expression_parameters error\n"); subscriber_shutdown(participant); return -1; } } else if (count == 20) { printf("changing filter parameters\n"); printf("Filter: 3 divides x\n"); DDS_StringSeq oldParameters; cft->get_expression_parameters(oldParameters); DDS_String_free(oldParameters[0]); DDS_String_free(oldParameters[1]); oldParameters[0] = DDS_String_dup("3"); oldParameters[1] = DDS_String_dup("divides"); retcode = cft->set_expression_parameters(oldParameters); if (retcode != DDS_RETCODE_OK) { printf("set_expression_parameters error\n"); subscriber_shutdown(participant); return -1; } } NDDSUtility::sleep(receive_period); } /* End Topics/ContentFilter changes */ /* Delete all entities */ status = subscriber_shutdown(participant); delete reader_listener; return status; } #if defined(RTI_WINCE) int wmain(int argc, wchar_t **argv) { int domainId = 0; int sample_count = 0; /* infinite loop */ if (argc >= 2) { domainId = _wtoi(argv[1]); } if (argc >= 3) { sample_count = _wtoi(argv[2]); } /* Uncomment this to turn on additional logging NDDSConfigLogger::get_instance()-> set_verbosity_by_category(NDDS_CONFIG_LOG_CATEGORY_API, NDDS_CONFIG_LOG_VERBOSITY_STATUS_ALL); */ return subscriber_main(domainId, sample_count); } #elif !(defined(RTI_VXWORKS) && !defined(__RTP__)) && !defined(RTI_PSOS) int main(int argc, char *argv[]) { int domainId = 0; int sample_count = 0; /* infinite loop */ if (argc >= 2) { domainId = atoi(argv[1]); } if (argc >= 3) { sample_count = atoi(argv[2]); } /* Uncomment this to turn on additional logging NDDSConfigLogger::get_instance()-> set_verbosity_by_category(NDDS_CONFIG_LOG_CATEGORY_API, NDDS_CONFIG_LOG_VERBOSITY_STATUS_ALL); */ return subscriber_main(domainId, sample_count); } #endif #ifdef RTI_VX653 const unsigned char *__ctype = *(__ctypePtrGet()); extern "C" void usrAppInit() { #ifdef USER_APPL_INIT USER_APPL_INIT; /* for backwards compatibility */ #endif /* add application specific code here */ taskSpawn( "sub", RTI_OSAPI_THREAD_PRIORITY_NORMAL, 0x8, 0x150000, (FUNCPTR) subscriber_main, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0); } #endif
cxx
rticonnextdds-examples
data/projects/rticonnextdds-examples/connext_dds/custom_content_filter/c++/ccf_publisher.cxx
/******************************************************************************* (c) 2005-2014 Copyright, Real-Time Innovations, Inc. All rights reserved. RTI grants Licensee a license to use, modify, compile, and create derivative works of the Software. Licensee has the right to distribute object form only for use with RTI products. The Software is provided "as is", with no warranty of any type, including any warranty for fitness for any purpose. RTI is under no obligation to maintain or support the Software. RTI shall not be liable for any incidental or consequential damages arising out of the use or inability to use the software. ******************************************************************************/ /* ccf_publisher.cxx A publication of data of type ccf This file is derived from code automatically generated by the rtiddsgen command: rtiddsgen -language C++ -example <arch> ccf.idl Example publication of type ccf automatically generated by 'rtiddsgen'. To test them follow these steps: (1) Compile this file and the example subscription. (2) Start the subscription with the command objs/<arch>/ccf_subscriber <domain_id> <sample_count> (3) Start the publication with the command objs/<arch>/ccf_publisher <domain_id> <sample_count> (4) [Optional] Specify the list of discovery initial peers and multicast receive addresses via an environment variable or a file (in the current working directory) called NDDS_DISCOVERY_PEERS. You can run any number of publishers and subscribers programs, and can add and remove them dynamically from the domain. Example: To run the example application on domain <domain_id>: On Unix: objs/<arch>/ccf_publisher <domain_id> o objs/<arch>/ccf_subscriber <domain_id> On Windows: objs\<arch>\ccf_publisher <domain_id> objs\<arch>\ccf_subscriber <domain_id> modification history ------------ ------- 21May2014,amb Example adapted for RTI Connext DDS 5.1 */ #include <stdio.h> #include <stdlib.h> #ifdef RTI_VX653 #include <vThreadsData.h> #endif #include "ccf.h" #include "ccfSupport.h" #include "ndds/ndds_cpp.h" /* Custom filter defined here */ #include "filter.cxx" /* Delete all entities */ static int publisher_shutdown(DDSDomainParticipant *participant) { DDS_ReturnCode_t retcode; int status = 0; if (participant != NULL) { retcode = participant->delete_contained_entities(); if (retcode != DDS_RETCODE_OK) { printf("delete_contained_entities error %d\n", retcode); status = -1; } retcode = DDSTheParticipantFactory->delete_participant(participant); if (retcode != DDS_RETCODE_OK) { printf("delete_participant error %d\n", retcode); status = -1; } } /* RTI Connext provides finalize_instance() method on domain participant factory for people who want to release memory used by the participant factory. Uncomment the following block of code for clean destruction of the singleton. */ /* retcode = DDSDomainParticipantFactory::finalize_instance(); if (retcode != DDS_RETCODE_OK) { printf("finalize_instance error %d\n", retcode); status = -1; } */ return status; } extern "C" int publisher_main(int domainId, int sample_count) { DDSDomainParticipant *participant = NULL; DDSPublisher *publisher = NULL; DDSTopic *topic = NULL; DDSDataWriter *writer = NULL; ccfDataWriter *ccf_writer = NULL; ccf *instance = NULL; DDS_ReturnCode_t retcode; DDS_InstanceHandle_t instance_handle = DDS_HANDLE_NIL; const char *type_name = NULL; int count = 0; DDS_Duration_t send_period = { 1, 0 }; /* To customize participant QoS, use the configuration file USER_QOS_PROFILES.xml */ participant = DDSTheParticipantFactory->create_participant( domainId, DDS_PARTICIPANT_QOS_DEFAULT, NULL /* listener */, DDS_STATUS_MASK_NONE); if (participant == NULL) { printf("create_participant error\n"); publisher_shutdown(participant); return -1; } /* To customize publisher QoS, use the configuration file USER_QOS_PROFILES.xml */ publisher = participant->create_publisher( DDS_PUBLISHER_QOS_DEFAULT, NULL /* listener */, DDS_STATUS_MASK_NONE); if (publisher == NULL) { printf("create_publisher error\n"); publisher_shutdown(participant); return -1; } /* Register type before creating topic */ type_name = ccfTypeSupport::get_type_name(); retcode = ccfTypeSupport::register_type(participant, type_name); if (retcode != DDS_RETCODE_OK) { printf("register_type error %d\n", retcode); publisher_shutdown(participant); return -1; } /* To customize topic QoS, use the configuration file USER_QOS_PROFILES.xml */ topic = participant->create_topic( "Example ccf", type_name, DDS_TOPIC_QOS_DEFAULT, NULL /* listener */, DDS_STATUS_MASK_NONE); if (topic == NULL) { printf("create_topic error\n"); publisher_shutdown(participant); return -1; } /* Start changes for Custom_Content_Filter */ /* Create and register custom filter */ custom_filter_type *custom_filter = new custom_filter_type(); retcode = participant->register_contentfilter("CustomFilter", custom_filter); if (retcode != DDS_RETCODE_OK) { printf("Failed to register custom content filter"); publisher_shutdown(participant); return -1; } /* End changes for Custom_Content_Filter */ /* To customize data writer QoS, use the configuration file USER_QOS_PROFILES.xml */ writer = publisher->create_datawriter( topic, DDS_DATAWRITER_QOS_DEFAULT, NULL /* listener */, DDS_STATUS_MASK_NONE); if (writer == NULL) { printf("create_datawriter error\n"); publisher_shutdown(participant); return -1; } ccf_writer = ccfDataWriter::narrow(writer); if (ccf_writer == NULL) { printf("DataWriter narrow error\n"); publisher_shutdown(participant); return -1; } /* Create data sample for writing */ instance = ccfTypeSupport::create_data(); if (instance == NULL) { printf("ccfTypeSupport::create_data error\n"); publisher_shutdown(participant); return -1; } /* For a data type that has a key, if the same instance is going to be written multiple times, initialize the key here and register the keyed instance prior to writing */ /* instance_handle = ccf_writer->register_instance(*instance); */ /* Main loop */ for (count = 0; (sample_count == 0) || (count < sample_count); ++count) { printf("Writing ccf, count %d\n", count); /* Modify the data to be sent here */ instance->x = count; retcode = ccf_writer->write(*instance, instance_handle); if (retcode != DDS_RETCODE_OK) { printf("write error %d\n", retcode); } NDDSUtility::sleep(send_period); } /* retcode = ccf_writer->unregister_instance( *instance, instance_handle); if (retcode != DDS_RETCODE_OK) { printf("unregister instance error %d\n", retcode); } */ /* Delete data sample */ retcode = ccfTypeSupport::delete_data(instance); if (retcode != DDS_RETCODE_OK) { printf("ccfTypeSupport::delete_data error %d\n", retcode); } /* Delete all entities */ return publisher_shutdown(participant); } #if defined(RTI_WINCE) int wmain(int argc, wchar_t **argv) { int domainId = 0; int sample_count = 0; /* infinite loop */ if (argc >= 2) { domainId = _wtoi(argv[1]); } if (argc >= 3) { sample_count = _wtoi(argv[2]); } /* Uncomment this to turn on additional logging NDDSConfigLogger::get_instance()-> set_verbosity_by_category(NDDS_CONFIG_LOG_CATEGORY_API, NDDS_CONFIG_LOG_VERBOSITY_STATUS_ALL); */ return publisher_main(domainId, sample_count); } #elif !(defined(RTI_VXWORKS) && !defined(__RTP__)) && !defined(RTI_PSOS) int main(int argc, char *argv[]) { int domainId = 0; int sample_count = 0; /* infinite loop */ if (argc >= 2) { domainId = atoi(argv[1]); } if (argc >= 3) { sample_count = atoi(argv[2]); } /* Uncomment this to turn on additional logging NDDSConfigLogger::get_instance()-> set_verbosity_by_category(NDDS_CONFIG_LOG_CATEGORY_API, NDDS_CONFIG_LOG_VERBOSITY_STATUS_ALL); */ return publisher_main(domainId, sample_count); } #endif #ifdef RTI_VX653 const unsigned char *__ctype = *(__ctypePtrGet()); extern "C" void usrAppInit() { #ifdef USER_APPL_INIT USER_APPL_INIT; /* for backwards compatibility */ #endif /* add application specific code here */ taskSpawn( "pub", RTI_OSAPI_THREAD_PRIORITY_NORMAL, 0x8, 0x150000, (FUNCPTR) publisher_main, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0); } #endif
cxx
rticonnextdds-examples
data/projects/rticonnextdds-examples/connext_dds/custom_content_filter/c++/filter.cxx
/******************************************************************************* (c) 2005-2014 Copyright, Real-Time Innovations, Inc. All rights reserved. RTI grants Licensee a license to use, modify, compile, and create derivative works of the Software. Licensee has the right to distribute object form only for use with RTI products. The Software is provided "as is", with no warranty of any type, including any warranty for fitness for any purpose. RTI is under no obligation to maintain or support the Software. RTI shall not be liable for any incidental or consequential damages arising out of the use or inability to use the software. ******************************************************************************/ /* filter.cxx * * This file contains the functions needed by the Custom Content Filter to work. * * See the example README.txt file for details about each of these functions. * * modification history * ------------ ------- * 21May2014,amb Example adapted for RTI Connext DDS 5.1 */ class custom_filter_type : public DDSContentFilter { public: virtual DDS_ReturnCode_t compile(void **new_compile_data, const char *expression, const DDS_StringSeq &parameters, const DDS_TypeCode *type_code, const char *type_class_name, void *old_compile_data); virtual DDS_Boolean evaluate( void *compile_data, const void *sample, const struct DDS_FilterSampleInfo *meta_data); virtual void finalize(void *compile_data); }; bool divide_test(long sample_data, long p) { return (sample_data % p == 0); } bool gt_test(long sample_data, long p) { return (p > sample_data); } /* Custom compile data */ struct cdata { long param; bool (*eval_func)(long, long); }; /* Called when Custom Filter is created, or when parameters are changed */ DDS_ReturnCode_t custom_filter_type::compile( void **new_compile_data, const char *expression, const DDS_StringSeq &parameters, const DDS_TypeCode *type_code, const char *type_class_name, void *old_compile_data) { struct cdata *cd = NULL; /* First free old data, if any */ free(old_compile_data); /* We expect an expression of the form "%0 %1 <var>" * where %1 = "divides" or "greater-than" * and <var> is an integral member of the msg structure. * * We don't actually check that <var> has the correct typecode, * (or even that it exists!). See example Typecodes to see * how to work with typecodes. * * The compile information is a structure including the first filter * parameter (%0) and a function pointer to evaluate the sample */ /* Check form: */ if (strncmp(expression, "%0 %1 ", 6) != 0) { goto err; } if (strlen(expression) < 7) { goto err; } /* Check that we have params */ if (parameters.length() < 2) { goto err; } cd = (struct cdata *) malloc(sizeof(struct cdata)); sscanf(parameters[0], "%ld", &cd->param); if (strcmp(parameters[1], "greater-than") == 0) { cd->eval_func = gt_test; } else if (strcmp(parameters[1], "divides") == 0) { cd->eval_func = divide_test; } else { goto err; } *new_compile_data = cd; return DDS_RETCODE_OK; err: printf("CustomFilter: Unable to compile expression '%s'\n", expression); printf(" with parameters '%s' '%s'\n", parameters[0], parameters[1]); *new_compile_data = NULL; return DDS_RETCODE_BAD_PARAMETER; } /* Called to evaluated each sample */ DDS_Boolean custom_filter_type::evaluate( void *compile_data, const void *sample, const struct DDS_FilterSampleInfo *meta_data) { cdata *cd = (cdata *) compile_data; ccf *msg = (ccf *) sample; if (cd->eval_func(msg->x, cd->param)) return DDS_BOOLEAN_TRUE; else return DDS_BOOLEAN_FALSE; } void custom_filter_type::finalize(void *compile_data) { if (compile_data != NULL) free(compile_data); }
cxx
rticonnextdds-examples
data/projects/rticonnextdds-examples/connext_dds/custom_content_filter/c++98/ccf_subscriber.cxx
/******************************************************************************* (c) 2005-2014 Copyright, Real-Time Innovations, Inc. All rights reserved. RTI grants Licensee a license to use, modify, compile, and create derivative works of the Software. Licensee has the right to distribute object form only for use with RTI products. The Software is provided "as is", with no warranty of any type, including any warranty for fitness for any purpose. RTI is under no obligation to maintain or support the Software. RTI shall not be liable for any incidental or consequential damages arising out of the use or inability to use the software. ******************************************************************************/ #include <iostream> #include <stdio.h> #include <stdlib.h> #include "ccf.h" #include "ccfSupport.h" #include "ndds/ndds_cpp.h" #include "application.h" /* Custom filter defined here */ #include "filter.cxx" using namespace application; static int shutdown_participant( DDSDomainParticipant *participant, const char *shutdown_message, int status); unsigned int process_data(ccfDataReader *typed_reader) { ccfSeq 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) { ccfTypeSupport::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) { 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 = ccfTypeSupport::get_type_name(); DDS_ReturnCode_t retcode = ccfTypeSupport::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 ccf", 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 Custom Content Filter */ /* Create and register custom filter */ custom_filter_type *custom_filter = new custom_filter_type(); retcode = participant->register_contentfilter("CustomFilter", custom_filter); if (retcode != DDS_RETCODE_OK) { return shutdown_participant( participant, "Failed to register custom content filter", EXIT_FAILURE); } DDS_StringSeq parameters(2); const char *param_list[] = { "2", "divides" }; parameters.from_array(param_list, 2); // Create content filtered topic DDSContentFilteredTopic *cft = participant->create_contentfilteredtopic_with_filter( "ContentFilteredTopic", topic, "%0 %1 x", parameters, "CustomFilter"); if (cft == NULL) { return shutdown_participant( participant, "create_contentfilteredtopic error", EXIT_FAILURE); } std::cout << "Filter: 2 divides x\n"; /* Also note that we pass 'cft' rather than 'topic' to the datareader * below */ /* End changes for Custom_Content_Filter */ /* * NOTE THAT WE USE THE PREVIOUSLY CREATED CUSTOM FILTERED TOPIC TO READ * NEW SAMPLES */ // This DataReader reads data on "Example ccf" Topic DDSDataReader *untyped_reader = subscriber->create_datareader( cft, 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 ccfDataReader *typed_reader = ccfDataReader::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 (samples_read == 4) { std::cout << "changing filter parameters\n"; std::cout << "Filter: 15 greater-than x\n"; DDS_String_free(parameters[0]); DDS_String_free(parameters[1]); parameters[0] = DDS_String_dup("15"); parameters[1] = DDS_String_dup("greater-than"); retcode = cft->set_expression_parameters(parameters); if (retcode != DDS_RETCODE_OK) { return shutdown_participant( participant, "set_expression_parameters error", EXIT_FAILURE); } } else if (samples_read == 10) { std::cout << "changing filter parameters\n"; std::cout << "Filter: 3 divides x\n"; DDS_StringSeq oldParameters; cft->get_expression_parameters(oldParameters); DDS_String_free(oldParameters[0]); DDS_String_free(oldParameters[1]); oldParameters[0] = DDS_String_dup("3"); oldParameters[1] = DDS_String_dup("divides"); retcode = cft->set_expression_parameters(oldParameters); if (retcode != DDS_RETCODE_OK) { return shutdown_participant( participant, "set_expression_parameters error", EXIT_FAILURE); } } } /* End Topics/ContentFilter changes */ // 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/custom_content_filter/c++98/ccf_publisher.cxx
/******************************************************************************* (c) 2005-2014 Copyright, Real-Time Innovations, Inc. All rights reserved. RTI grants Licensee a license to use, modify, compile, and create derivative works of the Software. Licensee has the right to distribute object form only for use with RTI products. The Software is provided "as is", with no warranty of any type, including any warranty for fitness for any purpose. RTI is under no obligation to maintain or support the Software. RTI shall not be liable for any incidental or consequential damages arising out of the use or inability to use the software. ******************************************************************************/ #include <iostream> #include <stdio.h> #include <stdlib.h> #include "ccf.h" #include "ccfSupport.h" #include "ndds/ndds_cpp.h" #include "application.h" /* Custom filter defined here */ #include "filter.cxx" 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 = ccfTypeSupport::get_type_name(); DDS_ReturnCode_t retcode = ccfTypeSupport::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 ccf", 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 Custom_Content_Filter */ // Create and register custom filter custom_filter_type *custom_filter = new custom_filter_type(); retcode = participant->register_contentfilter("CustomFilter", custom_filter); if (retcode != DDS_RETCODE_OK) { return shutdown_participant( participant, "Failed to register custom content filter", EXIT_FAILURE); } /* End changes for Custom_Content_Filter */ // This DataWriter writes data on "Example ccf" 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); } ccfDataWriter *typed_writer = ccfDataWriter::narrow(untyped_writer); if (typed_writer == NULL) { return shutdown_participant( participant, "DataWriter narrow error", EXIT_FAILURE); } /* Create data sample for writing */ ccf *data = ccfTypeSupport::create_data(); if (data == NULL) { return shutdown_participant( participant, "ccfTypeSupport::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 = ccf_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 ccf, count " << samples_written << std::endl; // Modify the data to be sent here data->x = samples_written; retcode = typed_writer->write(*data, instance_handle); if (retcode != DDS_RETCODE_OK) { std::cerr << "write error " << retcode << std::endl; } NDDSUtility::sleep(send_period); } /* retcode = ccf_writer->unregister_instance(*data, instance_handle); if (retcode != DDS_RETCODE_OK) { std::cerr << "unregister instance error " << retcode << std::endl; } */ // Delete previously allocated ccf, including all contained elements retcode = ccfTypeSupport::delete_data(data); if (retcode != DDS_RETCODE_OK) { std::cerr << "ccfTypeSupport::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/custom_content_filter/c++98/application.h
/* * (c) Copyright, Real-Time Innovations, 2020. All rights reserved. * RTI grants Licensee a license to use, modify, compile, and create derivative * works of the software solely for use with RTI Connext DDS. Licensee may * redistribute copies of the software provided that all such copies are subject * to this license. The software is provided "as is", with no warranty of any * type, including any warranty for fitness for any purpose. RTI is under no * obligation to maintain or support the software. RTI shall not be liable for * any incidental or consequential damages arising out of the use or inability * to use the software. */ #ifndef APPLICATION_H #define APPLICATION_H #include <iostream> #include <csignal> #include <climits> namespace application { // Catch control-C and tell application to shut down bool shutdown_requested = false; inline void stop_handler(int) { shutdown_requested = true; std::cout << "preparing to shut down..." << std::endl; } inline void setup_signal_handlers() { signal(SIGINT, stop_handler); signal(SIGTERM, stop_handler); } enum ParseReturn { PARSE_RETURN_OK, PARSE_RETURN_FAILURE, PARSE_RETURN_EXIT }; struct ApplicationArguments { ParseReturn parse_result; unsigned int domain_id; unsigned int sample_count; NDDS_Config_LogVerbosity verbosity; }; inline void set_verbosity(ApplicationArguments &arguments, int verbosity) { switch (verbosity) { case 0: arguments.verbosity = NDDS_CONFIG_LOG_VERBOSITY_SILENT; break; case 1: arguments.verbosity = NDDS_CONFIG_LOG_VERBOSITY_ERROR; break; case 2: arguments.verbosity = NDDS_CONFIG_LOG_VERBOSITY_WARNING; break; case 3: arguments.verbosity = NDDS_CONFIG_LOG_VERBOSITY_STATUS_ALL; break; default: arguments.verbosity = NDDS_CONFIG_LOG_VERBOSITY_ERROR; break; } } // Parses application arguments for example. Returns whether to exit. inline void parse_arguments( ApplicationArguments &arguments, int argc, char *argv[]) { int arg_processing = 1; bool show_usage = false; arguments.domain_id = 0; arguments.sample_count = INT_MAX; arguments.verbosity = NDDS_CONFIG_LOG_VERBOSITY_ERROR; arguments.parse_result = PARSE_RETURN_OK; while (arg_processing < argc) { if ((argc > arg_processing + 1) && (strcmp(argv[arg_processing], "-d") == 0 || strcmp(argv[arg_processing], "--domain") == 0)) { arguments.domain_id = atoi(argv[arg_processing + 1]); arg_processing += 2; } else if ( (argc > arg_processing + 1) && (strcmp(argv[arg_processing], "-s") == 0 || strcmp(argv[arg_processing], "--sample-count") == 0)) { arguments.sample_count = atoi(argv[arg_processing + 1]); arg_processing += 2; } else if ( (argc > arg_processing + 1) && (strcmp(argv[arg_processing], "-v") == 0 || strcmp(argv[arg_processing], "--verbosity") == 0)) { set_verbosity(arguments, atoi(argv[arg_processing + 1])); arg_processing += 2; } else if ( strcmp(argv[arg_processing], "-h") == 0 || strcmp(argv[arg_processing], "--help") == 0) { std::cout << "Example application." << std::endl; show_usage = true; arguments.parse_result = PARSE_RETURN_EXIT; break; } else { std::cout << "Bad parameter." << std::endl; show_usage = true; arguments.parse_result = PARSE_RETURN_FAILURE; break; } } if (show_usage) { std::cout << "Usage:\n" " -d, --domain <int> Domain ID this " "application will\n" " subscribe in. \n" " Default: 0\n" " -s, --sample_count <int> Number of samples to " "receive before\n" " cleanly shutting down. \n" " Default: infinite\n" " -v, --verbosity <int> How much debugging output " "to show.\n" " Range: 0-3 \n" " Default: 1" << std::endl; } } } // namespace application #endif // APPLICATION_H
h
rticonnextdds-examples
data/projects/rticonnextdds-examples/connext_dds/custom_content_filter/c++98/filter.cxx
/******************************************************************************* (c) 2005-2014 Copyright, Real-Time Innovations, Inc. All rights reserved. RTI grants Licensee a license to use, modify, compile, and create derivative works of the Software. Licensee has the right to distribute object form only for use with RTI products. The Software is provided "as is", with no warranty of any type, including any warranty for fitness for any purpose. RTI is under no obligation to maintain or support the Software. RTI shall not be liable for any incidental or consequential damages arising out of the use or inability to use the software. ******************************************************************************/ /* filter.cxx * * This file contains the functions needed by the Custom Content Filter to work. * * See the example README.txt file for details about each of these functions. * * modification history * ------------ ------- * 21May2014,amb Example adapted for RTI Connext DDS 5.1 */ class custom_filter_type : public DDSContentFilter { public: virtual DDS_ReturnCode_t compile( void **new_compile_data, const char *expression, const DDS_StringSeq &parameters, const DDS_TypeCode *type_code, const char *type_class_name, void *old_compile_data); virtual DDS_Boolean evaluate( void *compile_data, const void *sample, const struct DDS_FilterSampleInfo *meta_data); virtual void finalize(void *compile_data); }; bool divide_test(long sample_data, long p) { return (sample_data % p == 0); } bool gt_test(long sample_data, long p) { return (p > sample_data); } /* Custom compile data */ struct cdata { long param; bool (*eval_func)(long, long); }; /* Called when Custom Filter is created, or when parameters are changed */ DDS_ReturnCode_t custom_filter_type::compile( void **new_compile_data, const char *expression, const DDS_StringSeq &parameters, const DDS_TypeCode *type_code, const char *type_class_name, void *old_compile_data) { struct cdata *cd = NULL; /* First free old data, if any */ free(old_compile_data); /* We expect an expression of the form "%0 %1 <var>" * where %1 = "divides" or "greater-than" * and <var> is an integral member of the msg structure. * * We don't actually check that <var> has the correct typecode, * (or even that it exists!). See example Typecodes to see * how to work with typecodes. * * The compile information is a structure including the first filter * parameter (%0) and a function pointer to evaluate the sample */ /* Check form: */ if (strncmp(expression, "%0 %1 ", 6) != 0) { goto err; } if (strlen(expression) < 7) { goto err; } /* Check that we have params */ if (parameters.length() < 2) { goto err; } cd = (struct cdata *) malloc(sizeof(struct cdata)); sscanf(parameters[0], "%ld", &cd->param); if (strcmp(parameters[1], "greater-than") == 0) { cd->eval_func = gt_test; } else if (strcmp(parameters[1], "divides") == 0) { cd->eval_func = divide_test; } else { goto err; } *new_compile_data = cd; return DDS_RETCODE_OK; err: printf("CustomFilter: Unable to compile expression '%s'\n", expression); printf(" with parameters '%s' '%s'\n", parameters[0], parameters[1]); *new_compile_data = NULL; return DDS_RETCODE_BAD_PARAMETER; } /* Called to evaluated each sample */ DDS_Boolean custom_filter_type::evaluate( void *compile_data, const void *sample, const struct DDS_FilterSampleInfo *meta_data) { cdata *cd = (cdata *) compile_data; ccf *msg = (ccf *) sample; if (cd->eval_func(msg->x, cd->param)) return DDS_BOOLEAN_TRUE; else return DDS_BOOLEAN_FALSE; } void custom_filter_type::finalize(void *compile_data) { if (compile_data != NULL) free(compile_data); }
cxx
rticonnextdds-examples
data/projects/rticonnextdds-examples/connext_dds/custom_content_filter/c/ccf_publisher.c
/******************************************************************************* (c) 2005-2014 Copyright, Real-Time Innovations, Inc. All rights reserved. RTI grants Licensee a license to use, modify, compile, and create derivative works of the Software. Licensee has the right to distribute object form only for use with RTI products. The Software is provided "as is", with no warranty of any type, including any warranty for fitness for any purpose. RTI is under no obligation to maintain or support the Software. RTI shall not be liable for any incidental or consequential damages arising out of the use or inability to use the software. ******************************************************************************/ /* ccf_publisher.c A publication of data of type ccf This file is derived from code automatically generated by the rtiddsgen command: rtiddsgen -language C -example <arch> ccf.idl Example publication of type ccf automatically generated by 'rtiddsgen'. To test them follow these steps: (1) Compile this file and the example subscription. (2) Start the subscription with the command objs/<arch>/ccf_subscriber <domain_id> <sample_count> (3) Start the publication with the command objs/<arch>/ccf_publisher <domain_id> <sample_count> (4) [Optional] Specify the list of discovery initial peers and multicast receive addresses via an environment variable or a file (in the current working directory) called NDDS_DISCOVERY_PEERS. You can run any number of publishers and subscribers programs, and can add and remove them dynamically from the domain. Example: To run the example application on domain <domain_id>: On Unix: objs/<arch>/ccf_publisher <domain_id> objs/<arch>/ccf_subscriber <domain_id> On Windows: objs\<arch>\ccf_publisher <domain_id> objs\<arch>\ccf_subscriber <domain_id> modification history ------------ ------- 20May2014,amb Example adapted for RTI Connext DDS 5.1 */ #include "ccf.h" #include "ccfSupport.h" #include "ndds/ndds_c.h" #include <stdio.h> #include <stdlib.h> /* Custom filter defined here */ #include "filter.c" /* Delete all entities */ static int publisher_shutdown(DDS_DomainParticipant *participant) { DDS_ReturnCode_t retcode; int status = 0; if (participant != NULL) { retcode = DDS_DomainParticipant_delete_contained_entities(participant); if (retcode != DDS_RETCODE_OK) { printf("delete_contained_entities error %d\n", retcode); status = -1; } retcode = DDS_DomainParticipantFactory_delete_participant( DDS_TheParticipantFactory, participant); if (retcode != DDS_RETCODE_OK) { printf("delete_participant error %d\n", retcode); status = -1; } } /* RTI Connext provides finalize_instance() method on domain participant factory for people who want to release memory used by the participant factory. Uncomment the following block of code for clean destruction of the singleton. */ /* retcode = DDS_DomainParticipantFactory_finalize_instance(); if (retcode != DDS_RETCODE_OK) { printf("finalize_instance error %d\n", retcode); status = -1; } */ return status; } static int publisher_main(int domainId, int sample_count) { DDS_DomainParticipant *participant = NULL; DDS_Publisher *publisher = NULL; DDS_Topic *topic = NULL; DDS_DataWriter *writer = NULL; ccfDataWriter *ccf_writer = NULL; ccf *instance = NULL; DDS_ReturnCode_t retcode; DDS_InstanceHandle_t instance_handle = DDS_HANDLE_NIL; const char *type_name = NULL; int count = 0; struct DDS_Duration_t send_period = { 1, 0 }; struct DDS_ContentFilter custom_filter = DDS_ContentFilter_INITIALIZER; /* To customize participant QoS, use the configuration file USER_QOS_PROFILES.xml */ participant = DDS_DomainParticipantFactory_create_participant( DDS_TheParticipantFactory, domainId, &DDS_PARTICIPANT_QOS_DEFAULT, NULL /* listener */, DDS_STATUS_MASK_NONE); if (participant == NULL) { printf("create_participant error\n"); publisher_shutdown(participant); return -1; } /* To customize publisher QoS, use the configuration file USER_QOS_PROFILES.xml */ publisher = DDS_DomainParticipant_create_publisher( participant, &DDS_PUBLISHER_QOS_DEFAULT, NULL /* listener */, DDS_STATUS_MASK_NONE); if (publisher == NULL) { printf("create_publisher error\n"); publisher_shutdown(participant); return -1; } /* Register type before creating topic */ type_name = ccfTypeSupport_get_type_name(); retcode = ccfTypeSupport_register_type(participant, type_name); if (retcode != DDS_RETCODE_OK) { printf("register_type error %d\n", retcode); publisher_shutdown(participant); return -1; } /* To customize topic QoS, use the configuration file USER_QOS_PROFILES.xml */ topic = DDS_DomainParticipant_create_topic( participant, "Example ccf", type_name, &DDS_TOPIC_QOS_DEFAULT, NULL /* listener */, DDS_STATUS_MASK_NONE); if (topic == NULL) { printf("create_topic error\n"); publisher_shutdown(participant); return -1; } /*------ Start changes for Custom_Content_Filter ------*/ /* Create and register custom filter */ custom_filter.compile = custom_filter_compile_function; custom_filter.evaluate = custom_filter_evaluate_function; custom_filter.finalize = custom_filter_finalize_function; custom_filter.filter_data = NULL; retcode = DDS_DomainParticipant_register_contentfilter( participant, "CustomFilter", &custom_filter); if (retcode != DDS_RETCODE_OK) { printf("Failed to register custom content filter"); publisher_shutdown(participant); return -1; } /*------ End changes for Custom_Content_Filter ------*/ /* To customize data writer QoS, use the configuration file USER_QOS_PROFILES.xml */ writer = DDS_Publisher_create_datawriter( publisher, topic, &DDS_DATAWRITER_QOS_DEFAULT, NULL /* listener */, DDS_STATUS_MASK_NONE); if (writer == NULL) { printf("create_datawriter error\n"); publisher_shutdown(participant); return -1; } ccf_writer = ccfDataWriter_narrow(writer); if (ccf_writer == NULL) { printf("DataWriter narrow error\n"); publisher_shutdown(participant); return -1; } /* Create data sample for writing */ instance = ccfTypeSupport_create_data_ex(DDS_BOOLEAN_TRUE); if (instance == NULL) { printf("ccfTypeSupport_create_data error\n"); publisher_shutdown(participant); return -1; } /* For a data type that has a key, if the same instance is going to be written multiple times, initialize the key here and register the keyed instance prior to writing */ /* instance_handle = ccfDataWriter_register_instance( ccf_writer, instance); */ /* Main loop */ for (count = 0; (sample_count == 0) || (count < sample_count); ++count) { printf("Writing ccf, count %d\n", count); /* Modify the data to be written here */ instance->x = count; /* Write data */ retcode = ccfDataWriter_write(ccf_writer, instance, &instance_handle); if (retcode != DDS_RETCODE_OK) { printf("write error %d\n", retcode); } NDDS_Utility_sleep(&send_period); } /* retcode = ccfDataWriter_unregister_instance( ccf_writer, instance, &instance_handle); if (retcode != DDS_RETCODE_OK) { printf("unregister instance error %d\n", retcode); } */ /* Delete data sample */ retcode = ccfTypeSupport_delete_data_ex(instance, DDS_BOOLEAN_TRUE); if (retcode != DDS_RETCODE_OK) { printf("ccfTypeSupport_delete_data error %d\n", retcode); } /* Cleanup and delete delete all entities */ return publisher_shutdown(participant); } #if defined(RTI_WINCE) int wmain(int argc, wchar_t **argv) { int domainId = 0; int sample_count = 0; /* infinite loop */ if (argc >= 2) { domainId = _wtoi(argv[1]); } if (argc >= 3) { sample_count = _wtoi(argv[2]); } /* Uncomment this to turn on additional logging NDDS_Config_Logger_set_verbosity_by_category( NDDS_Config_Logger_get_instance(), NDDS_CONFIG_LOG_CATEGORY_API, NDDS_CONFIG_LOG_VERBOSITY_STATUS_ALL); */ return publisher_main(domainId, sample_count); } #elif !(defined(RTI_VXWORKS) && !defined(__RTP__)) && !defined(RTI_PSOS) int main(int argc, char *argv[]) { int domainId = 0; int sample_count = 0; /* infinite loop */ if (argc >= 2) { domainId = atoi(argv[1]); } if (argc >= 3) { sample_count = atoi(argv[2]); } /* Uncomment this to turn on additional logging NDDS_Config_Logger_set_verbosity_by_category( NDDS_Config_Logger_get_instance(), NDDS_CONFIG_LOG_CATEGORY_API, NDDS_CONFIG_LOG_VERBOSITY_STATUS_ALL); */ return publisher_main(domainId, sample_count); } #endif #ifdef RTI_VX653 const unsigned char *__ctype = NULL; void usrAppInit() { #ifdef USER_APPL_INIT USER_APPL_INIT; /* for backwards compatibility */ #endif /* add application specific code here */ taskSpawn( "pub", RTI_OSAPI_THREAD_PRIORITY_NORMAL, 0x8, 0x150000, (FUNCPTR) publisher_main, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0); } #endif
c
rticonnextdds-examples
data/projects/rticonnextdds-examples/connext_dds/custom_content_filter/c/ccf_subscriber.c
/******************************************************************************* (c) 2005-2014 Copyright, Real-Time Innovations, Inc. All rights reserved. RTI grants Licensee a license to use, modify, compile, and create derivative works of the Software. Licensee has the right to distribute object form only for use with RTI products. The Software is provided "as is", with no warranty of any type, including any warranty for fitness for any purpose. RTI is under no obligation to maintain or support the Software. RTI shall not be liable for any incidental or consequential damages arising out of the use or inability to use the software. ******************************************************************************/ /* ccf_subscriber.c A subscription example This file is derived from code automatically generated by the rtiddsgen command: rtiddsgen -language C -example <arch> ccf.idl Example subscription of type ccf automatically generated by 'rtiddsgen'. To test them, follow these steps: (1) Compile this file and the example publication. (2) Start the subscription with the command objs/<arch>/ccf_subscriber <domain_id> <sample_count> (3) Start the publication with the command objs/<arch>/ccf_publisher <domain_id> <sample_count> (4) [Optional] Specify the list of discovery initial peers and multicast receive addresses via an environment variable or a file (in the current working directory) called NDDS_DISCOVERY_PEERS. You can run any number of publishers and subscribers programs, and can add and remove them dynamically from the domain. Example: To run the example application on domain <domain_id>: On UNIX systems: objs/<arch>/ccf_publisher <domain_id> objs/<arch>/ccf_subscriber <domain_id> On Windows systems: objs\<arch>\ccf_publisher <domain_id> objs\<arch>\ccf_subscriber <domain_id> modification history ------------ ------- 21May2014,amb Example adapted for RTI Connext DDS 5.1 */ #include "ccf.h" #include "ccfSupport.h" #include "ndds/ndds_c.h" #include <stdio.h> #include <stdlib.h> /* Custom filter defined here */ #include "filter.c" void ccfListener_on_requested_deadline_missed( void *listener_data, DDS_DataReader *reader, const struct DDS_RequestedDeadlineMissedStatus *status) { } void ccfListener_on_requested_incompatible_qos( void *listener_data, DDS_DataReader *reader, const struct DDS_RequestedIncompatibleQosStatus *status) { } void ccfListener_on_sample_rejected( void *listener_data, DDS_DataReader *reader, const struct DDS_SampleRejectedStatus *status) { } void ccfListener_on_liveliness_changed( void *listener_data, DDS_DataReader *reader, const struct DDS_LivelinessChangedStatus *status) { } void ccfListener_on_sample_lost( void *listener_data, DDS_DataReader *reader, const struct DDS_SampleLostStatus *status) { } void ccfListener_on_subscription_matched( void *listener_data, DDS_DataReader *reader, const struct DDS_SubscriptionMatchedStatus *status) { } void ccfListener_on_data_available(void *listener_data, DDS_DataReader *reader) { ccfDataReader *ccf_reader = NULL; struct ccfSeq data_seq = DDS_SEQUENCE_INITIALIZER; struct DDS_SampleInfoSeq info_seq = DDS_SEQUENCE_INITIALIZER; DDS_ReturnCode_t retcode; int i; ccf_reader = ccfDataReader_narrow(reader); if (ccf_reader == NULL) { printf("DataReader narrow error\n"); return; } retcode = ccfDataReader_take( ccf_reader, &data_seq, &info_seq, DDS_LENGTH_UNLIMITED, DDS_ANY_SAMPLE_STATE, DDS_ANY_VIEW_STATE, DDS_ANY_INSTANCE_STATE); if (retcode == DDS_RETCODE_NO_DATA) { return; } else if (retcode != DDS_RETCODE_OK) { printf("take error %d\n", retcode); return; } for (i = 0; i < ccfSeq_get_length(&data_seq); ++i) { if (DDS_SampleInfoSeq_get_reference(&info_seq, i)->valid_data) { ccfTypeSupport_print_data(ccfSeq_get_reference(&data_seq, i)); } } retcode = ccfDataReader_return_loan(ccf_reader, &data_seq, &info_seq); if (retcode != DDS_RETCODE_OK) { printf("return loan error %d\n", retcode); } } /* Delete all entities */ static int subscriber_shutdown(DDS_DomainParticipant *participant) { DDS_ReturnCode_t retcode; int status = 0; if (participant != NULL) { retcode = DDS_DomainParticipant_delete_contained_entities(participant); if (retcode != DDS_RETCODE_OK) { printf("delete_contained_entities error %d\n", retcode); status = -1; } retcode = DDS_DomainParticipantFactory_delete_participant( DDS_TheParticipantFactory, participant); if (retcode != DDS_RETCODE_OK) { printf("delete_participant error %d\n", retcode); status = -1; } } /* RTI Connext provides the finalize_instance() method on domain participant factory for users who want to release memory used by the participant factory. Uncomment the following block of code for clean destruction of the singleton. */ /* retcode = DDS_DomainParticipantFactory_finalize_instance(); if (retcode != DDS_RETCODE_OK) { printf("finalize_instance error %d\n", retcode); status = -1; } */ return status; } static int subscriber_main(int domainId, int sample_count) { DDS_DomainParticipant *participant = NULL; DDS_Subscriber *subscriber = NULL; DDS_Topic *topic = NULL; struct DDS_DataReaderListener reader_listener = DDS_DataReaderListener_INITIALIZER; DDS_DataReader *reader = NULL; DDS_ReturnCode_t retcode; const char *type_name = NULL; int count = 0; struct DDS_Duration_t poll_period = { 1, 0 }; const char *param_list[] = { "2", "divides" }; DDS_ContentFilteredTopic *cft = NULL; struct DDS_StringSeq parameters; struct DDS_ContentFilter custom_filter = DDS_ContentFilter_INITIALIZER; /* To customize participant QoS, use the configuration file USER_QOS_PROFILES.xml */ participant = DDS_DomainParticipantFactory_create_participant( DDS_TheParticipantFactory, domainId, &DDS_PARTICIPANT_QOS_DEFAULT, NULL /* listener */, DDS_STATUS_MASK_NONE); if (participant == NULL) { printf("create_participant error\n"); subscriber_shutdown(participant); return -1; } /* To customize subscriber QoS, use the configuration file USER_QOS_PROFILES.xml */ subscriber = DDS_DomainParticipant_create_subscriber( participant, &DDS_SUBSCRIBER_QOS_DEFAULT, NULL /* listener */, DDS_STATUS_MASK_NONE); if (subscriber == NULL) { printf("create_subscriber error\n"); subscriber_shutdown(participant); return -1; } /* Register the type before creating the topic */ type_name = ccfTypeSupport_get_type_name(); retcode = ccfTypeSupport_register_type(participant, type_name); if (retcode != DDS_RETCODE_OK) { printf("register_type error %d\n", retcode); subscriber_shutdown(participant); return -1; } /* To customize topic QoS, use the configuration file USER_QOS_PROFILES.xml */ topic = DDS_DomainParticipant_create_topic( participant, "Example ccf", type_name, &DDS_TOPIC_QOS_DEFAULT, NULL /* listener */, DDS_STATUS_MASK_NONE); if (topic == NULL) { printf("create_topic error\n"); subscriber_shutdown(participant); return -1; } /*------ Start changes for Custom_Content_Filter ------*/ /* Create and register custom filter */ custom_filter.compile = custom_filter_compile_function; custom_filter.evaluate = custom_filter_evaluate_function; custom_filter.finalize = custom_filter_finalize_function; custom_filter.filter_data = NULL; retcode = DDS_DomainParticipant_register_contentfilter( participant, "CustomFilter", &custom_filter); if (retcode != DDS_RETCODE_OK) { printf("Failed to register custom content filter"); subscriber_shutdown(participant); return -1; } DDS_StringSeq_initialize(&parameters); DDS_StringSeq_set_maximum(&parameters, 2); DDS_StringSeq_from_array(&parameters, param_list, 2); cft = DDS_DomainParticipant_create_contentfilteredtopic_with_filter( participant, "ContentFilteredTopic", topic, "%0 %1 x", &parameters, "CustomFilter"); if (cft == NULL) { printf("create_contentfilteredtopic error\n"); subscriber_shutdown(participant); return -1; } printf("Filter: 2 divides x\n"); /* Note that we pass 'ccf' rather than 'topic' to the datareader below */ /*------ End changes for Custom_Content_Filter ------*/ /* Set up a data reader listener */ reader_listener.on_requested_deadline_missed = ccfListener_on_requested_deadline_missed; reader_listener.on_requested_incompatible_qos = ccfListener_on_requested_incompatible_qos; reader_listener.on_sample_rejected = ccfListener_on_sample_rejected; reader_listener.on_liveliness_changed = ccfListener_on_liveliness_changed; reader_listener.on_sample_lost = ccfListener_on_sample_lost; reader_listener.on_subscription_matched = ccfListener_on_subscription_matched; reader_listener.on_data_available = ccfListener_on_data_available; /* * NOTE THAT WE USE THE PREVIOUSLY CREATED CUSTOM FILTERED TOPIC TO READ * NEW SAMPLES */ reader = DDS_Subscriber_create_datareader( subscriber, DDS_Topic_as_topicdescription(cft), &DDS_DATAREADER_QOS_DEFAULT, &reader_listener, DDS_STATUS_MASK_ALL); if (reader == NULL) { printf("create_datareader error\n"); subscriber_shutdown(participant); return -1; } /* Start changes for Custom_Content_Filter */ /* Main loop */ for (count = 0; (sample_count == 0) || (count < sample_count); ++count) { if (count == 10) { printf("changing filter parameters\n"); printf("Filter: 15 greater-than x\n"); DDS_String_free(DDS_StringSeq_get(&parameters, 0)); DDS_String_free(DDS_StringSeq_get(&parameters, 1)); *DDS_StringSeq_get_reference(&parameters, 0) = DDS_String_dup("15"); *DDS_StringSeq_get_reference(&parameters, 1) = DDS_String_dup("greater-than"); 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("changing filter parameters\n"); printf("Filter: 3 divides x\n"); DDS_ContentFilteredTopic_get_expression_parameters( cft, &oldParameters); DDS_String_free(DDS_StringSeq_get(&oldParameters, 0)); *DDS_StringSeq_get_reference(&oldParameters, 0) = DDS_String_dup("3"); *DDS_StringSeq_get_reference(&oldParameters, 1) = DDS_String_dup("divides"); retcode = DDS_ContentFilteredTopic_set_expression_parameters( cft, &oldParameters); if (retcode != DDS_RETCODE_OK) { printf("set_expression_parameters error\n"); subscriber_shutdown(participant); return -1; } } NDDS_Utility_sleep(&poll_period); } /* Cleanup and delete all entities */ return subscriber_shutdown(participant); } #if defined(RTI_WINCE) int wmain(int argc, wchar_t **argv) { int domainId = 0; int sample_count = 0; /* infinite loop */ if (argc >= 2) { domainId = _wtoi(argv[1]); } if (argc >= 3) { sample_count = _wtoi(argv[2]); } /* Uncomment this to turn on additional logging NDDS_Config_Logger_set_verbosity_by_category( NDDS_Config_Logger_get_instance(), NDDS_CONFIG_LOG_CATEGORY_API, NDDS_CONFIG_LOG_VERBOSITY_STATUS_ALL); */ return subscriber_main(domainId, sample_count); } #elif !(defined(RTI_VXWORKS) && !defined(__RTP__)) && !defined(RTI_PSOS) int main(int argc, char *argv[]) { int domainId = 0; int sample_count = 0; /* infinite loop */ if (argc >= 2) { domainId = atoi(argv[1]); } if (argc >= 3) { sample_count = atoi(argv[2]); } /* Uncomment this to turn on additional logging NDDS_Config_Logger_set_verbosity_by_category( NDDS_Config_Logger_get_instance(), NDDS_CONFIG_LOG_CATEGORY_API, NDDS_CONFIG_LOG_VERBOSITY_STATUS_ALL); */ return subscriber_main(domainId, sample_count); } #endif #ifdef RTI_VX653 const unsigned char *__ctype = NULL; void usrAppInit() { #ifdef USER_APPL_INIT USER_APPL_INIT; /* for backwards compatibility */ #endif /* add application specific code here */ taskSpawn( "sub", RTI_OSAPI_THREAD_PRIORITY_NORMAL, 0x8, 0x150000, (FUNCPTR) subscriber_main, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0); } #endif
c
rticonnextdds-examples
data/projects/rticonnextdds-examples/connext_dds/custom_content_filter/c/filter.c
/******************************************************************************* (c) 2005-2014 Copyright, Real-Time Innovations, Inc. All rights reserved. RTI grants Licensee a license to use, modify, compile, and create derivative works of the Software. Licensee has the right to distribute object form only for use with RTI products. The Software is provided "as is", with no warranty of any type, including any warranty for fitness for any purpose. RTI is under no obligation to maintain or support the Software. RTI shall not be liable for any incidental or consequential damages arising out of the use or inability to use the software. ******************************************************************************/ /* filter.c * * This file contains the functions needed by the Custom Content Filter to work. * * See the example README.txt file for details about each of these functions. * * modification history * ------------ ------- * 21May2014,amb Example adapted for RTI Connext DDS 5.1 */ /* Custom compile data */ struct cdata { long param; int (*eval_func)(long, long); }; /* Evaluation function for 'divides' filter */ int divide_test(long sample_data, long p) { return (sample_data % p == 0); } /* Evaluation function for 'greater than' filter */ int gt_test(long sample_data, long p) { return (p > sample_data); } DDS_ReturnCode_t custom_filter_compile_function( void *filter_data, void **new_compile_data, const char *expression, const struct DDS_StringSeq *parameters, const struct DDS_TypeCode *type_code, const char *type_class_name, void *old_compile_data) { struct cdata *cd; /* First free old data, if any */ if (old_compile_data != NULL) { free(old_compile_data); } /* We expect an expression of the form "%0 %1 <var>" * where %1 = "divides" or "greater-than" * and <var> is an integral member of the msg structure. * * We don't actually check that <var> has the correct typecode, * (or even that it exists!). See example Typecodes to see * how to work with typecodes. * * The compile information is a structure including the first filter * parameter (%0) and a function pointer to evaluate the sample */ /* Check form: */ if (strncmp(expression, "%0 %1 ", 6) != 0) { goto err; } if (strlen(expression) < 7) { goto err; } /* Check that we have params */ if (DDS_StringSeq_get_length(parameters) < 2) { goto err; } cd = (struct cdata *) malloc(sizeof(struct cdata)); sscanf(DDS_StringSeq_get(parameters, 0), "%ld", &cd->param); /* Establish the correct evaluation function depending on the filter */ if (strcmp(DDS_StringSeq_get(parameters, 1), "greater-than") == 0) { cd->eval_func = gt_test; } else if (strcmp(DDS_StringSeq_get(parameters, 1), "divides") == 0) { cd->eval_func = divide_test; } else { goto err; } *new_compile_data = cd; return DDS_RETCODE_OK; err: printf("CustomFilter: Unable to compile expression '%s'\n", expression); printf(" with parameters '%s' '%s'\n", DDS_StringSeq_get(parameters, 0), DDS_StringSeq_get(parameters, 1)); *new_compile_data = NULL; return DDS_RETCODE_BAD_PARAMETER; } /* Called to evaluated each sample. Will vary depending on the filter. */ DDS_Boolean custom_filter_evaluate_function( void *filter_data, void *compile_data, const void *sample, const struct DDS_FilterSampleInfo *meta_data) { struct cdata *cd; struct ccf *msg; cd = (struct cdata *) compile_data; msg = (struct ccf *) sample; if (cd->eval_func(msg->x, cd->param)) { return DDS_BOOLEAN_TRUE; } else { return DDS_BOOLEAN_FALSE; } } void custom_filter_finalize_function(void *filter_data, void *compile_data) { if (compile_data != NULL) { free(compile_data); } }
c
rticonnextdds-examples
data/projects/rticonnextdds-examples/connext_dds/custom_content_filter/c++03/ccf_subscriber.cxx
/******************************************************************************* (c) 2005-2015 Copyright, Real-Time Innovations, Inc. All rights reserved. RTI grants Licensee a license to use, modify, compile, and create derivative works of the Software. Licensee has the right to distribute object form only for use with RTI products. The Software is provided "as is", with no warranty of any type, including any warranty for fitness for any purpose. RTI is under no obligation to maintain or support the Software. RTI shall not be liable for any incidental or consequential damages arising out of the use or inability to use the software. ******************************************************************************/ #include <cstdlib> #include <iostream> #include "ccf.hpp" #include "filter.hpp" #include <dds/dds.hpp> #include <rti/core/ListenerBinder.hpp> using namespace dds::core; using namespace dds::core::status; using namespace dds::domain; using namespace dds::topic; using namespace dds::sub; class CcfListener : public NoOpDataReaderListener<Foo> { public: void on_data_available(DataReader<Foo> &reader) { // Take the available data LoanedSamples<Foo> samples = reader.take(); for (LoanedSamples<Foo>::iterator sampleIt = samples.begin(); sampleIt != samples.end(); ++sampleIt) { if (sampleIt->info().valid()) { std::cout << sampleIt->data() << std::endl; } } } }; void subscriber_main(int domain_id, int sample_count) { // Create a DomainParticipant. DomainParticipant participant(domain_id); // Create a Topic -- and automatically register the type. Topic<Foo> topic(participant, "Example ccf"); // Register the custom filter type. It must be registered in both sides. participant->register_contentfilter( CustomFilter<CustomFilterType>(new CustomFilterType()), "CustomFilter"); // The default filter parameters will filter values that are divisible by 2. std::vector<std::string> parameters(2); parameters[0] = "2"; parameters[1] = "divides"; // Create the filter with the expression and the type registered. Filter filter("%0 %1 x", parameters); filter->name("CustomFilter"); // Create the content filtered topic. ContentFilteredTopic<Foo> cft_topic(topic, "ContentFilteredTopic", filter); std::cout << "Filter: 2 divides x" << std::endl; // Create a DataReader. Note that we are using the content filtered topic. DataReader<Foo> reader(Subscriber(participant), cft_topic); // Create a data reader listener using ListenerBinder, a RAII that // will take care of setting it to NULL on destruction. rti::core::ListenerBinder<DataReader<Foo> > scoped_listener = rti::core::bind_and_manage_listener( reader, new CcfListener, StatusMask::data_available()); // Main loop for (int count = 0; (sample_count == 0) || (count < sample_count); ++count) { if (count == 10) { std::cout << "Changing filter parameters" << std::endl << "Filter: 15 greater-than x" << std::endl; parameters[0] = "15"; parameters[1] = "greater-than"; cft_topic.filter_parameters(parameters.begin(), parameters.end()); } else if (count == 20) { std::cout << "Changing filter parameters" << std::endl << "Filter: 3 divides x" << std::endl; parameters[0] = "3"; parameters[1] = "divides"; cft_topic.filter_parameters(parameters.begin(), parameters.end()); } rti::util::sleep(Duration(1)); } } int main(int argc, char *argv[]) { int domain_id = 0; int sample_count = 0; // Infinite loop if (argc >= 2) { domain_id = atoi(argv[1]); } if (argc >= 3) { sample_count = atoi(argv[2]); } // To turn on additional logging, include <rti/config/Logger.hpp> and // uncomment the following line: // rti::config::Logger::instance()l.verbosity(rti::config::Verbosity::STATUS_ALL); try { subscriber_main(domain_id, sample_count); } catch (std::exception ex) { std::cout << "Exception caught: " << ex.what() << std::endl; return -1; } return 0; }
cxx
rticonnextdds-examples
data/projects/rticonnextdds-examples/connext_dds/custom_content_filter/c++03/filter.hpp
/******************************************************************************* (c) 2005-2015 Copyright, Real-Time Innovations, Inc. All rights reserved. RTI grants Licensee a license to use, modify, compile, and create derivative works of the Software. Licensee has the right to distribute object form only for use with RTI products. The Software is provided "as is", with no warranty of any type, including any warranty for fitness for any purpose. RTI is under no obligation to maintain or support the Software. RTI shall not be liable for any incidental or consequential damages arising out of the use or inability to use the software. ******************************************************************************/ #include "ccf.hpp" #include <cstdlib> #include <dds/dds.hpp> using namespace dds::core; using namespace dds::core::xtypes; using namespace rti::topic; struct CustomCompileData { long param; bool (*eval_func)(long, long); }; bool divide_test(long sample_data, long p) { return (sample_data % p == 0); } bool gt_test(long sample_data, long p) { return (p > sample_data); } class CustomFilterType : public ContentFilter<Foo, CustomCompileData> { public: // Called when Custom Filter is created, or when parameters are changed. virtual CustomCompileData & compile(const std::string &expression, const StringSeq &parameters, const optional<DynamicType> &type_code, const std::string &type_class_name, CustomCompileData *old_compile_data) { // First free old data, if any. if (old_compile_data != NULL) delete old_compile_data; // We expect an expression of the form "%0 %1 <var>" where // %1 = "divides" or "greater-than" and <var> is an integral member of // the msg structure. // We don't actually check that <var> has the correct typecode, // (or even that it exists!). See example Typecodes to see // how to work with typecodes. // The compile information is a structure including the first filter // parameter (%0) and a function pointer to evaluate the sample // Check form. if (expression.compare(0, 6, "%0 %1 ") != 0) { throw std::invalid_argument("Invalid filter expression"); } if (expression.size() < 7) { throw std::invalid_argument("Invalid filter expression size"); } /* Check that we have params */ if (parameters.size() < 2) { throw std::invalid_argument("Invalid filter parameters number"); } CustomCompileData *cd = new CustomCompileData(); cd->param = atol(parameters[0].c_str()); if (parameters[1] == "greater-than") { cd->eval_func = &gt_test; } else if (parameters[1] == "divides") { cd->eval_func = &divide_test; } else { throw std::invalid_argument("Invad filter operation"); } return *cd; } // Called to evaluated each sample. virtual bool evaluate( CustomCompileData &compile_data, const Foo &sample, const FilterSampleInfo &meta_data) { return compile_data.eval_func(sample.x(), compile_data.param); } virtual void finalize(CustomCompileData &compile_data) { // This is the pointer allocated in "compile" method. // For this reason we need to take the address. if (&compile_data != NULL) delete &compile_data; } };
hpp
rticonnextdds-examples
data/projects/rticonnextdds-examples/connext_dds/custom_content_filter/c++03/ccf_publisher.cxx
/******************************************************************************* (c) 2005-2015 Copyright, Real-Time Innovations, Inc. All rights reserved. RTI grants Licensee a license to use, modify, compile, and create derivative works of the Software. Licensee has the right to distribute object form only for use with RTI products. The Software is provided "as is", with no warranty of any type, including any warranty for fitness for any purpose. RTI is under no obligation to maintain or support the Software. RTI shall not be liable for any incidental or consequential damages arising out of the use or inability to use the software. ******************************************************************************/ #include <cstdlib> #include <iostream> #include "ccf.hpp" #include "filter.hpp" #include <dds/dds.hpp> using namespace dds::core; using namespace dds::core::policy; using namespace dds::domain; using namespace rti::domain; using namespace dds::topic; using namespace dds::pub; using namespace dds::pub::qos; void publisher_main(int domain_id, int sample_count) { // Create a DomainParticipant. DomainParticipant participant(domain_id); // Register the custom filter type. It must be registered in both sides. participant->register_contentfilter( CustomFilter<CustomFilterType>(new CustomFilterType()), "CustomFilter"); // Create a Topic -- and automatically register the type. Topic<Foo> topic(participant, "Example ccf"); // Create a DataWriter. DataWriter<Foo> writer(Publisher(participant), topic); // Create an instance for writing. Foo instance; // Main loop for (int count = 0; (sample_count == 0) || (count < sample_count); count++) { std::cout << "Writing ccf, count " << count << std::endl; instance.x(count); writer.write(instance); rti::util::sleep(Duration(1)); } } int main(int argc, char *argv[]) { int domain_id = 0; int sample_count = 0; // Infinite loop if (argc >= 2) { domain_id = atoi(argv[1]); } if (argc >= 3) { sample_count = atoi(argv[2]); } // To turn on additional logging, include <rti/config/Logger.hpp> and // uncomment the following line: // rti::config::Logger::instance().verbosity(rti::config::Verbosity::STATUS_ALL); try { publisher_main(domain_id, sample_count); } catch (std::exception ex) { std::cout << "Exception caught: " << ex.what() << std::endl; return -1; } return 0; }
cxx
rticonnextdds-examples
data/projects/rticonnextdds-examples/connext_dds/custom_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/custom_content_filter/c++11/ccf_subscriber.cxx
/******************************************************************************* (c) 2005-2015 Copyright, Real-Time Innovations, Inc. All rights reserved. RTI grants Licensee a license to use, modify, compile, and create derivative works of the Software. Licensee has the right to distribute object form only for use with RTI products. The Software is provided "as is", with no warranty of any type, including any warranty for fitness for any purpose. RTI is under no obligation to maintain or support the Software. RTI shall not be liable for any incidental or consequential damages arising out of the use or inability to use the software. ******************************************************************************/ #include <dds/sub/ddssub.hpp> #include <dds/core/ddscore.hpp> #include <rti/config/Logger.hpp> // for logging #include "ccf.hpp" #include "filter.hpp" #include "application.hpp" // for command line parsing and ctrl-c int process_data(dds::sub::DataReader<Foo> reader) { int count = 0; // Take the available data dds::sub::LoanedSamples<Foo> 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) { // Create a DomainParticipant. dds::domain::DomainParticipant participant(domain_id); // Create a Topic -- and automatically register the type. dds::topic::Topic<Foo> topic(participant, "Example ccf"); // Register the custom filter type. It must be registered in both sides. participant->register_contentfilter( rti::topic::CustomFilter<CustomFilterType>(new CustomFilterType()), "CustomFilter"); // Create the filter with the expression and the type registered. dds::topic::Filter filter("%0 %1 x", { "2", "divides" }); filter->name("CustomFilter"); // Create the content filtered topic. dds::topic::ContentFilteredTopic<Foo> cft_topic( topic, "ContentFilteredTopic", filter); std::cout << "Filter: 2 divides x" << std::endl; // Create a DataReader. Note that we are using the content filtered topic. dds::sub::Subscriber subcriber(participant); dds::sub::DataReader<Foo> reader(subcriber, cft_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; bool filter_changed1 = false; bool filter_changed2 = false; // Main loop while (!application::shutdown_requested && samples_read < sample_count) { if (samples_read == 4 && !filter_changed1) { std::cout << "Changing filter parameters" << std::endl << "Filter: 15 greater-than x" << std::endl; std::vector<std::string> parameters = { "15", "greater-than" }; cft_topic.filter_parameters(parameters.begin(), parameters.end()); filter_changed1 = true; } else if (samples_read == 10 && !filter_changed2) { std::cout << "Changing filter parameters" << std::endl << "Filter: 3 divides x" << std::endl; std::vector<std::string> parameters = { "3", "divides" }; cft_topic.filter_parameters(parameters.begin(), parameters.end()); filter_changed2 = true; } 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/custom_content_filter/c++11/filter.hpp
/******************************************************************************* (c) 2005-2015 Copyright, Real-Time Innovations, Inc. All rights reserved. RTI grants Licensee a license to use, modify, compile, and create derivative works of the Software. Licensee has the right to distribute object form only for use with RTI products. The Software is provided "as is", with no warranty of any type, including any warranty for fitness for any purpose. RTI is under no obligation to maintain or support the Software. RTI shall not be liable for any incidental or consequential damages arising out of the use or inability to use the software. ******************************************************************************/ #include "ccf.hpp" #include <dds/core/ddscore.hpp> struct CustomCompileData { long param; bool (*eval_func)(long, long); }; class CustomFilterType : public rti::topic::ContentFilter<Foo, CustomCompileData> { public: // Called when Custom Filter is created, or when parameters are changed. virtual CustomCompileData &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, CustomCompileData *old_compile_data) { // First free old data, if any. if (old_compile_data != NULL) delete old_compile_data; // We expect an expression of the form "%0 %1 <var>" where // %1 = "divides" or "greater-than" and <var> is an integral member of // the msg structure. // We don't actually check that <var> has the correct typecode, // (or even that it exists!). See example Typecodes to see // how to work with typecodes. // The compile information is a structure including the first filter // parameter (%0) and a function pointer to evaluate the sample // Check form. if (expression.compare(0, 6, "%0 %1 ") != 0) { throw std::invalid_argument("Invalid filter expression"); } if (expression.size() < 7) { throw std::invalid_argument("Invalid filter expression size"); } /* Check that we have params */ if (parameters.size() < 2) { throw std::invalid_argument("Invalid filter parameters number"); } CustomCompileData *cd = new CustomCompileData(); cd->param = atol(parameters[0].c_str()); if (parameters[1] == "greater-than") { cd->eval_func = [](long sample_data, long p) { return (p > sample_data); }; } else if (parameters[1] == "divides") { cd->eval_func = [](long sample_data, long p) { return (sample_data % p == 0); }; } else { throw std::invalid_argument("Invad filter operation"); } return *cd; } // Called to evaluated each sample. virtual bool evaluate( CustomCompileData &compile_data, const Foo &sample, const rti::topic::FilterSampleInfo &meta_data) { return compile_data.eval_func(sample.x(), compile_data.param); } virtual void finalize(CustomCompileData &compile_data) { // This is the pointer allocated in "compile" method. // For this reason we need to take the address. if (&compile_data != NULL) delete &compile_data; } };
hpp
rticonnextdds-examples
data/projects/rticonnextdds-examples/connext_dds/custom_content_filter/c++11/ccf_publisher.cxx
/******************************************************************************* (c) 2005-2015 Copyright, Real-Time Innovations, Inc. All rights reserved. RTI grants Licensee a license to use, modify, compile, and create derivative works of the Software. Licensee has the right to distribute object form only for use with RTI products. The Software is provided "as is", with no warranty of any type, including any warranty for fitness for any purpose. RTI is under no obligation to maintain or support the Software. RTI shall not be liable for any incidental or consequential damages arising out of the use or inability to use the software. ******************************************************************************/ #include <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 "filter.hpp" #include "ccf.hpp" void run_publisher_application( unsigned int domain_id, unsigned int sample_count) { // Create a DomainParticipant. dds::domain::DomainParticipant participant(domain_id); // Register the custom filter type. It must be registered in both sides. participant.extensions().register_contentfilter( rti::topic::CustomFilter<CustomFilterType>(new CustomFilterType()), "CustomFilter"); // Create a Topic -- and automatically register the type. dds::topic::Topic<Foo> topic(participant, "Example ccf"); // Create a DataWriter. dds::pub::Publisher publisher(participant); dds::pub::DataWriter<Foo> writer(publisher, topic); // Create an instance for writing. Foo instance; // Main loop for (unsigned int samples_written = 0; !application::shutdown_requested && samples_written < sample_count; samples_written++) { std::cout << "Writing ccf, count " << samples_written << std::endl; instance.x(samples_written); writer.write(instance); rti::util::sleep(dds::core::Duration(1)); } } int main(int argc, char *argv[]) { using namespace application; // Parse arguments and handle control-C auto arguments = parse_arguments(argc, argv); if (arguments.parse_result == ParseReturn::exit) { return EXIT_SUCCESS; } else if (arguments.parse_result == ParseReturn::failure) { return EXIT_FAILURE; } setup_signal_handlers(); // Sets Connext verbosity to help debugging rti::config::Logger::instance().verbosity(arguments.verbosity); try { run_publisher_application(arguments.domain_id, arguments.sample_count); } catch (const std::exception &ex) { // This will catch DDS exceptions std::cerr << "Exception in run_publisher_application(): " << ex.what() << std::endl; return EXIT_FAILURE; } // Releases the memory used by the participant factory. Optional at // application exit dds::domain::DomainParticipant::finalize_participant_factory(); return EXIT_SUCCESS; }
cxx
rticonnextdds-examples
data/projects/rticonnextdds-examples/connext_dds/multichannel/c++/market_data_subscriber.cxx
/******************************************************************************* (c) 2005-2014 Copyright, Real-Time Innovations, Inc. All rights reserved. RTI grants Licensee a license to use, modify, compile, and create derivative works of the Software. Licensee has the right to distribute object form only for use with RTI products. The Software is provided "as is", with no warranty of any type, including any warranty for fitness for any purpose. RTI is under no obligation to maintain or support the Software. RTI shall not be liable for any incidental or consequential damages arising out of the use or inability to use the software. ******************************************************************************/ /* market_data_subscriber.cxx A subscription example This file is derived from code automatically generated by the rtiddsgen command: rtiddsgen -language C++ -example <arch> market_data.idl Example subscription of type market_data automatically generated by 'rtiddsgen'. To test them follow these steps: (1) Compile this file and the example publication. (2) Start the subscription with the command objs/<arch>/market_data_subscriber <domain_id> <sample_count> (3) Start the publication with the command objs/<arch>/market_data_publisher <domain_id> <sample_count> (4) [Optional] Specify the list of discovery initial peers and multicast receive addresses via an environment variable or a file (in the current working directory) called NDDS_DISCOVERY_PEERS. You can run any number of publishers and subscribers programs, and can add and remove them dynamically from the domain. Example: To run the example application on domain <domain_id>: On Unix: objs/<arch>/market_data_publisher <domain_id> objs/<arch>/market_data_subscriber <domain_id> On Windows: objs\<arch>\market_data_publisher <domain_id> objs\<arch>\market_data_subscriber <domain_id> modification history ------------ ------- */ #include <stdio.h> #include <stdlib.h> #ifdef RTI_VX653 #include <vThreadsData.h> #endif #include "market_data.h" #include "market_dataSupport.h" #include "ndds/ndds_cpp.h" class market_dataListener : public DDSDataReaderListener { public: virtual void on_requested_deadline_missed( DDSDataReader * /*reader*/, const DDS_RequestedDeadlineMissedStatus & /*status*/) { } virtual void on_requested_incompatible_qos( DDSDataReader * /*reader*/, const DDS_RequestedIncompatibleQosStatus & /*status*/) { } virtual void on_sample_rejected( DDSDataReader * /*reader*/, const DDS_SampleRejectedStatus & /*status*/) { } virtual void on_liveliness_changed( DDSDataReader * /*reader*/, const DDS_LivelinessChangedStatus & /*status*/) { } virtual void on_sample_lost( DDSDataReader * /*reader*/, const DDS_SampleLostStatus & /*status*/) { } virtual void on_subscription_matched( DDSDataReader * /*reader*/, const DDS_SubscriptionMatchedStatus & /*status*/) { } virtual void on_data_available(DDSDataReader *reader); }; void market_dataListener::on_data_available(DDSDataReader *reader) { market_dataDataReader *market_data_reader = NULL; market_dataSeq data_seq; DDS_SampleInfoSeq info_seq; DDS_ReturnCode_t retcode; int i; market_data_reader = market_dataDataReader::narrow(reader); if (market_data_reader == NULL) { printf("DataReader narrow error\n"); return; } retcode = market_data_reader->take( data_seq, info_seq, DDS_LENGTH_UNLIMITED, DDS_ANY_SAMPLE_STATE, DDS_ANY_VIEW_STATE, DDS_ANY_INSTANCE_STATE); if (retcode == DDS_RETCODE_NO_DATA) { return; } else if (retcode != DDS_RETCODE_OK) { printf("take error %d\n", retcode); return; } for (i = 0; i < data_seq.length(); ++i) { if (info_seq[i].valid_data) { market_dataTypeSupport::print_data(&data_seq[i]); } } retcode = market_data_reader->return_loan(data_seq, info_seq); if (retcode != DDS_RETCODE_OK) { printf("return loan error %d\n", retcode); } } /* Delete all entities */ static int subscriber_shutdown(DDSDomainParticipant *participant) { DDS_ReturnCode_t retcode; int status = 0; if (participant != NULL) { retcode = participant->delete_contained_entities(); if (retcode != DDS_RETCODE_OK) { printf("delete_contained_entities error %d\n", retcode); status = -1; } retcode = DDSTheParticipantFactory->delete_participant(participant); if (retcode != DDS_RETCODE_OK) { printf("delete_participant error %d\n", retcode); status = -1; } } /* RTI Connext provides the finalize_instance() method on domain participant factory for people who want to release memory used by the participant factory. Uncomment the following block of code for clean destruction of the singleton. */ /* retcode = DDSDomainParticipantFactory::finalize_instance(); if (retcode != DDS_RETCODE_OK) { printf("finalize_instance error %d\n", retcode); status = -1; } */ return status; } extern "C" int subscriber_main(int domainId, int sample_count) { DDSDomainParticipant *participant = NULL; DDSSubscriber *subscriber = NULL; DDSTopic *topic = NULL; DDSContentFilteredTopic *filtered_topic = NULL; DDS_StringSeq expression_parameters; market_dataListener *reader_listener = NULL; DDSDataReader *reader = NULL; DDS_ReturnCode_t retcode; const char *type_name = NULL; int count = 0; DDS_Duration_t receive_period = { 4, 0 }; int status = 0; /* To customize the participant QoS, use the configuration file USER_QOS_PROFILES.xml */ participant = DDSTheParticipantFactory->create_participant( domainId, DDS_PARTICIPANT_QOS_DEFAULT, NULL /* listener */, DDS_STATUS_MASK_NONE); if (participant == NULL) { printf("create_participant error\n"); subscriber_shutdown(participant); return -1; } /* To customize the subscriber QoS, use the configuration file USER_QOS_PROFILES.xml */ subscriber = participant->create_subscriber( DDS_SUBSCRIBER_QOS_DEFAULT, NULL /* listener */, DDS_STATUS_MASK_NONE); if (subscriber == NULL) { printf("create_subscriber error\n"); subscriber_shutdown(participant); return -1; } /* Register the type before creating the topic */ type_name = market_dataTypeSupport::get_type_name(); retcode = market_dataTypeSupport::register_type(participant, type_name); if (retcode != DDS_RETCODE_OK) { printf("register_type error %d\n", retcode); subscriber_shutdown(participant); return -1; } /* To customize the topic QoS, use the configuration file USER_QOS_PROFILES.xml */ topic = participant->create_topic( "Example market_data", type_name, DDS_TOPIC_QOS_DEFAULT, NULL /* listener */, DDS_STATUS_MASK_NONE); if (topic == NULL) { printf("create_topic error\n"); subscriber_shutdown(participant); return -1; } /* Start changes for MultiChannel */ filtered_topic = participant->create_contentfilteredtopic_with_filter( "Example market_data", topic, "Symbol MATCH 'A'", expression_parameters, DDS_STRINGMATCHFILTER_NAME); if (filtered_topic == NULL) { printf("create_contentfilteredtopic error\n"); subscriber_shutdown(participant); return -1; } /* Create a data reader listener */ reader_listener = new market_dataListener(); /* To customize the data reader QoS, use the configuration file USER_QOS_PROFILES.xml */ reader = subscriber->create_datareader( filtered_topic, DDS_DATAREADER_QOS_DEFAULT, reader_listener, DDS_STATUS_MASK_ALL); if (reader == NULL) { printf("create_datareader error\n"); subscriber_shutdown(participant); delete reader_listener; return -1; } printf("filter is Symbol MATCH 'A'\n"); /* Main loop */ for (count = 0; (sample_count == 0) || (count < sample_count); ++count) { /* printf("market_data subscriber sleeping for %d sec...\n", * receive_period.sec); */ if (count == 3) { retcode = filtered_topic->append_to_expression_parameter(0, "D"); if (retcode != DDS_RETCODE_OK) { printf("append_to_expression_parameter %d\n", retcode); subscriber_shutdown(participant); return -1; } printf("changed filter to Symbol MATCH 'A,D'\n"); } if (count == 6) { retcode = filtered_topic->remove_from_expression_parameter(0, "A"); if (retcode != DDS_RETCODE_OK) { printf("append_to_expression_parameter %d\n", retcode); subscriber_shutdown(participant); return -1; } printf("changed filter to Symbol MATCH 'D'\n"); } NDDSUtility::sleep(receive_period); } /* End changes for MultiChannel */ /* Delete all entities */ status = subscriber_shutdown(participant); delete reader_listener; return status; } #if defined(RTI_WINCE) int wmain(int argc, wchar_t **argv) { int domainId = 0; int sample_count = 0; /* infinite loop */ if (argc >= 2) { domainId = _wtoi(argv[1]); } if (argc >= 3) { sample_count = _wtoi(argv[2]); } /* Uncomment this to turn on additional logging NDDSConfigLogger::get_instance()-> set_verbosity_by_category(NDDS_CONFIG_LOG_CATEGORY_API, NDDS_CONFIG_LOG_VERBOSITY_STATUS_ALL); */ return subscriber_main(domainId, sample_count); } #elif !(defined(RTI_VXWORKS) && !defined(__RTP__)) && !defined(RTI_PSOS) int main(int argc, char *argv[]) { int domainId = 0; int sample_count = 0; /* infinite loop */ if (argc >= 2) { domainId = atoi(argv[1]); } if (argc >= 3) { sample_count = atoi(argv[2]); } /* Uncomment this to turn on additional logging NDDSConfigLogger::get_instance()-> set_verbosity_by_category(NDDS_CONFIG_LOG_CATEGORY_API, NDDS_CONFIG_LOG_VERBOSITY_STATUS_ALL); */ return subscriber_main(domainId, sample_count); } #endif #ifdef RTI_VX653 const unsigned char *__ctype = *(__ctypePtrGet()); extern "C" void usrAppInit() { #ifdef USER_APPL_INIT USER_APPL_INIT; /* for backwards compatibility */ #endif /* add application specific code here */ taskSpawn( "sub", RTI_OSAPI_THREAD_PRIORITY_NORMAL, 0x8, 0x150000, (FUNCPTR) subscriber_main, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0); } #endif
cxx
rticonnextdds-examples
data/projects/rticonnextdds-examples/connext_dds/multichannel/c++/market_data_publisher.cxx
/******************************************************************************* (c) 2005-2014 Copyright, Real-Time Innovations, Inc. All rights reserved. RTI grants Licensee a license to use, modify, compile, and create derivative works of the Software. Licensee has the right to distribute object form only for use with RTI products. The Software is provided "as is", with no warranty of any type, including any warranty for fitness for any purpose. RTI is under no obligation to maintain or support the Software. RTI shall not be liable for any incidental or consequential damages arising out of the use or inability to use the software. ******************************************************************************/ /* market_data_publisher.cxx A publication of data of type market_data This file is derived from code automatically generated by the rtiddsgen command: rtiddsgen -language C++ -example <arch> market_data.idl Example publication of type market_data automatically generated by 'rtiddsgen'. To test them follow these steps: (1) Compile this file and the example subscription. (2) Start the subscription with the command objs/<arch>/market_data_subscriber <domain_id> <sample_count> (3) Start the publication with the command objs/<arch>/market_data_publisher <domain_id> <sample_count> (4) [Optional] Specify the list of discovery initial peers and multicast receive addresses via an environment variable or a file (in the current working directory) called NDDS_DISCOVERY_PEERS. You can run any number of publishers and subscribers programs, and can add and remove them dynamically from the domain. Example: To run the example application on domain <domain_id>: On Unix: objs/<arch>/market_data_publisher <domain_id> o objs/<arch>/market_data_subscriber <domain_id> On Windows: objs\<arch>\market_data_publisher <domain_id> objs\<arch>\market_data_subscriber <domain_id> modification history ------------ ------- */ #include <stdio.h> #include <stdlib.h> #ifdef RTI_VX653 #include <vThreadsData.h> #endif #include "market_data.h" #include "market_dataSupport.h" #include "ndds/ndds_cpp.h" /* Delete all entities */ static int publisher_shutdown(DDSDomainParticipant *participant) { DDS_ReturnCode_t retcode; int status = 0; if (participant != NULL) { retcode = participant->delete_contained_entities(); if (retcode != DDS_RETCODE_OK) { printf("delete_contained_entities error %d\n", retcode); status = -1; } retcode = DDSTheParticipantFactory->delete_participant(participant); if (retcode != DDS_RETCODE_OK) { printf("delete_participant error %d\n", retcode); status = -1; } } /* RTI Connext provides finalize_instance() method on domain participant factory for people who want to release memory used by the participant factory. Uncomment the following block of code for clean destruction of the singleton. */ /* retcode = DDSDomainParticipantFactory::finalize_instance(); if (retcode != DDS_RETCODE_OK) { printf("finalize_instance error %d\n", retcode); status = -1; } */ return status; } extern "C" int publisher_main(int domainId, int sample_count) { DDSDomainParticipant *participant = NULL; DDSPublisher *publisher = NULL; DDSTopic *topic = NULL; DDS_DataWriterQos writer_qos; DDSDataWriter *writer = NULL; market_dataDataWriter *market_data_writer = NULL; market_data *instance = NULL; DDS_ReturnCode_t retcode; DDS_InstanceHandle_t instance_handle = DDS_HANDLE_NIL; const char *type_name = NULL; int count = 0; DDS_Duration_t send_period = { 0, 100000000 }; /* To customize participant QoS, use the configuration file USER_QOS_PROFILES.xml */ participant = DDSTheParticipantFactory->create_participant( domainId, DDS_PARTICIPANT_QOS_DEFAULT, NULL /* listener */, DDS_STATUS_MASK_NONE); if (participant == NULL) { printf("create_participant error\n"); publisher_shutdown(participant); return -1; } /* To customize publisher QoS, use the configuration file USER_QOS_PROFILES.xml */ publisher = participant->create_publisher( DDS_PUBLISHER_QOS_DEFAULT, NULL /* listener */, DDS_STATUS_MASK_NONE); if (publisher == NULL) { printf("create_publisher error\n"); publisher_shutdown(participant); return -1; } /* Register type before creating topic */ type_name = market_dataTypeSupport::get_type_name(); retcode = market_dataTypeSupport::register_type(participant, type_name); if (retcode != DDS_RETCODE_OK) { printf("register_type error %d\n", retcode); publisher_shutdown(participant); return -1; } /* To customize topic QoS, use the configuration file USER_QOS_PROFILES.xml */ topic = participant->create_topic( "Example market_data", type_name, DDS_TOPIC_QOS_DEFAULT, NULL /* listener */, DDS_STATUS_MASK_NONE); if (topic == NULL) { printf("create_topic error\n"); publisher_shutdown(participant); return -1; } /* If you want to change the DataWriter's QoS programmatically rather than * using the XML file, you will need to add the following lines to your * code and modify the datawriter creation fuction using writer_qos. * * In this case, we set the publish as multichannel using the differents * channel to send differents symbol. Every channel have a IP to send the * data. */ /* Start changes for MultiChannel */ /* retcode = publisher->get_default_datawriter_qos(writer_qos); if (retcode != DDS_RETCODE_OK) { printf("get_default_datawriter_qos error\n"); publisher_shutdown(participant); return -1; } */ /* Create 8 channels based on Symbol */ /* writer_qos.multi_channel.channels.ensure_length(8, 8); writer_qos.multi_channel.channels[0].filter_expression = DDS_String_dup( "Symbol MATCH '[A-C]*'"); writer_qos.multi_channel.channels[0].multicast_settings.ensure_length(1, 1); writer_qos.multi_channel.channels[0].multicast_settings[0].receive_address = DDS_String_dup("239.255.0.2"); writer_qos.multi_channel.channels[1].filter_expression = DDS_String_dup( "Symbol MATCH '[D-F]*'"); writer_qos.multi_channel.channels[1].multicast_settings.ensure_length(1, 1); writer_qos.multi_channel.channels[1].multicast_settings[0].receive_address = DDS_String_dup("239.255.0.3"); writer_qos.multi_channel.channels[2].filter_expression = DDS_String_dup( "Symbol MATCH '[G-I]*'"); writer_qos.multi_channel.channels[2].multicast_settings.ensure_length(1, 1); writer_qos.multi_channel.channels[2].multicast_settings[0].receive_address = DDS_String_dup("239.255.0.4"); writer_qos.multi_channel.channels[3].filter_expression = DDS_String_dup( "Symbol MATCH '[J-L]*'"); writer_qos.multi_channel.channels[3].multicast_settings.ensure_length(1, 1); writer_qos.multi_channel.channels[3].multicast_settings[0].receive_address = DDS_String_dup("239.255.0.5"); writer_qos.multi_channel.channels[4].filter_expression = DDS_String_dup( "Symbol MATCH '[M-O]*'"); writer_qos.multi_channel.channels[4].multicast_settings.ensure_length(1, 1); writer_qos.multi_channel.channels[4].multicast_settings[0].receive_address = DDS_String_dup("239.255.0.6"); writer_qos.multi_channel.channels[5].filter_expression = DDS_String_dup( "Symbol MATCH '[P-S]*'"); writer_qos.multi_channel.channels[5].multicast_settings.ensure_length(1, 1); writer_qos.multi_channel.channels[5].multicast_settings[0].receive_address = DDS_String_dup("239.255.0.7"); writer_qos.multi_channel.channels[6].filter_expression = DDS_String_dup( "Symbol MATCH '[T-V]*'"); writer_qos.multi_channel.channels[6].multicast_settings.ensure_length(1, 1); writer_qos.multi_channel.channels[6].multicast_settings[0].receive_address = DDS_String_dup("239.255.0.8"); writer_qos.multi_channel.channels[7].filter_expression = DDS_String_dup( "Symbol MATCH '[W-Z]*'"); writer_qos.multi_channel.channels[7].multicast_settings.ensure_length(1, 1); writer_qos.multi_channel.channels[7].multicast_settings[0].receive_address = DDS_String_dup("239.255.0.9"); */ /* To customize data writer QoS, use the configuration file USER_QOS_PROFILES.xml */ /* toggle between writer_qos and DDS_DATAWRITER_QOS_DEFAULT to alternate * between using code and using XML to specify the Qos */ writer = publisher->create_datawriter( topic, /*writer_qos*/ DDS_DATAWRITER_QOS_DEFAULT, NULL /* listener */, DDS_STATUS_MASK_NONE); if (writer == NULL) { printf("create_datawriter error\n"); publisher_shutdown(participant); return -1; } /* End changes for MultiChannel */ market_data_writer = market_dataDataWriter::narrow(writer); if (market_data_writer == NULL) { printf("DataWriter narrow error\n"); publisher_shutdown(participant); return -1; } /* Create data sample for writing */ instance = market_dataTypeSupport::create_data(); if (instance == NULL) { printf("market_dataTypeSupport::create_data error\n"); publisher_shutdown(participant); return -1; } /* For a data type that has a key, if the same instance is going to be written multiple times, initialize the key here and register the keyed instance prior to writing */ /* instance_handle = market_data_writer->register_instance(*instance); */ /* Main loop */ for (count = 0; (sample_count == 0) || (count < sample_count); ++count) { /* Changes for MultiChannel */ /* Modify the data to be sent here */ sprintf(instance->Symbol, "%c", 'A' + (count % 26)); instance->Price = count; retcode = market_data_writer->write(*instance, instance_handle); if (retcode != DDS_RETCODE_OK) { printf("write error %d\n", retcode); } NDDSUtility::sleep(send_period); } /* retcode = market_data_writer->unregister_instance( *instance, instance_handle); if (retcode != DDS_RETCODE_OK) { printf("unregister instance error %d\n", retcode); } */ /* Delete data sample */ retcode = market_dataTypeSupport::delete_data(instance); if (retcode != DDS_RETCODE_OK) { printf("market_dataTypeSupport::delete_data error %d\n", retcode); } /* Delete all entities */ return publisher_shutdown(participant); } #if defined(RTI_WINCE) int wmain(int argc, wchar_t **argv) { int domainId = 0; int sample_count = 0; /* infinite loop */ if (argc >= 2) { domainId = _wtoi(argv[1]); } if (argc >= 3) { sample_count = _wtoi(argv[2]); } /* Uncomment this to turn on additional logging NDDSConfigLogger::get_instance()-> set_verbosity_by_category(NDDS_CONFIG_LOG_CATEGORY_API, NDDS_CONFIG_LOG_VERBOSITY_STATUS_ALL); */ return publisher_main(domainId, sample_count); } #elif !(defined(RTI_VXWORKS) && !defined(__RTP__)) && !defined(RTI_PSOS) int main(int argc, char *argv[]) { int domainId = 0; int sample_count = 0; /* infinite loop */ if (argc >= 2) { domainId = atoi(argv[1]); } if (argc >= 3) { sample_count = atoi(argv[2]); } /* Uncomment this to turn on additional logging NDDSConfigLogger::get_instance()-> set_verbosity_by_category(NDDS_CONFIG_LOG_CATEGORY_API, NDDS_CONFIG_LOG_VERBOSITY_STATUS_ALL); */ return publisher_main(domainId, sample_count); } #endif #ifdef RTI_VX653 const unsigned char *__ctype = *(__ctypePtrGet()); extern "C" void usrAppInit() { #ifdef USER_APPL_INIT USER_APPL_INIT; /* for backwards compatibility */ #endif /* add application specific code here */ taskSpawn( "pub", RTI_OSAPI_THREAD_PRIORITY_NORMAL, 0x8, 0x150000, (FUNCPTR) publisher_main, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0); } #endif
cxx
rticonnextdds-examples
data/projects/rticonnextdds-examples/connext_dds/multichannel/c++98/market_data_subscriber.cxx
/******************************************************************************* (c) 2005-2014 Copyright, Real-Time Innovations, Inc. All rights reserved. RTI grants Licensee a license to use, modify, compile, and create derivative works of the Software. Licensee has the right to distribute object form only for use with RTI products. The Software is provided "as is", with no warranty of any type, including any warranty for fitness for any purpose. RTI is under no obligation to maintain or support the Software. RTI shall not be liable for any incidental or consequential damages arising out of the use or inability to use the software. ******************************************************************************/ #include <iostream> #include <stdio.h> #include <stdlib.h> #include "market_data.h" #include "market_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(market_dataDataReader *typed_reader) { market_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) { market_dataTypeSupport::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 }; DDS_StringSeq expression_parameters; // 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 = market_dataTypeSupport::get_type_name(); DDS_ReturnCode_t retcode = market_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 market_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); } /* Start changes for MultiChannel */ DDSContentFilteredTopic *filtered_topic = participant->create_contentfilteredtopic_with_filter( "Example market_data", topic, "Symbol MATCH 'A'", expression_parameters, DDS_STRINGMATCHFILTER_NAME); if (filtered_topic == NULL) { return shutdown_participant( participant, "create_contentfilteredtopic error", EXIT_FAILURE); } // This DataReader reads data on "Example market_data" Topic DDSDataReader *untyped_reader = subscriber->create_datareader( filtered_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 market_dataDataReader *typed_reader = market_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); } std::cout << "filter is Symbol MATCH 'A'\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; if (samples_read == 3 && !changed_filter1) { retcode = filtered_topic->append_to_expression_parameter(0, "D"); if (retcode != DDS_RETCODE_OK) { return shutdown_participant( participant, "append_to_expression_parameter", EXIT_FAILURE); } std::cout << "changed filter to Symbol MATCH 'A,D'\n"; changed_filter1 = true; } if (samples_read == 6 && !changed_filter2) { retcode = filtered_topic->remove_from_expression_parameter(0, "A"); if (retcode != DDS_RETCODE_OK) { return shutdown_participant( participant, "append_to_expression_parameter", EXIT_FAILURE); } std::cout << "changed filter to Symbol MATCH 'D'\n"; changed_filter2 = true; } 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); } } /* End changes for MultiChannel */ // 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/multichannel/c++98/market_data_publisher.cxx
/******************************************************************************* (c) 2005-2014 Copyright, Real-Time Innovations, Inc. All rights reserved. RTI grants Licensee a license to use, modify, compile, and create derivative works of the Software. Licensee has the right to distribute object form only for use with RTI products. The Software is provided "as is", with no warranty of any type, including any warranty for fitness for any purpose. RTI is under no obligation to maintain or support the Software. RTI shall not be liable for any incidental or consequential damages arising out of the use or inability to use the software. ******************************************************************************/ #include <iostream> #include <stdio.h> #include <stdlib.h> #include "market_data.h" #include "market_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) { DDS_Duration_t send_period = { 0, 100000000 }; // 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 = market_dataTypeSupport::get_type_name(); DDS_ReturnCode_t retcode = market_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 market_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); } /* If you want to change the DataWriter's QoS programmatically rather than * using the XML file, you will need to add the following lines to your * code and modify the datawriter creation fuction using writer_qos. * * In this case, we set the publish as multichannel using the differents * channel to send differents symbol. Every channel have a IP to send the * data. */ /* Start changes for MultiChannel */ /* retcode = publisher->get_default_datawriter_qos(writer_qos); if (retcode != DDS_RETCODE_OK) { return shutdown_participant( participant, "get_default_datawriter_qos error", EXIT_FAILURE); } */ /* Create 8 channels based on Symbol */ /* writer_qos.multi_channel.channels.ensure_length(8, 8); writer_qos.multi_channel.channels[0].filter_expression = DDS_String_dup( "Symbol MATCH '[A-C]*'"); writer_qos.multi_channel.channels[0].multicast_settings.ensure_length(1, 1); writer_qos.multi_channel.channels[0].multicast_settings[0].receive_address = DDS_String_dup("239.255.0.2"); writer_qos.multi_channel.channels[1].filter_expression = DDS_String_dup( "Symbol MATCH '[D-F]*'"); writer_qos.multi_channel.channels[1].multicast_settings.ensure_length(1, 1); writer_qos.multi_channel.channels[1].multicast_settings[0].receive_address = DDS_String_dup("239.255.0.3"); writer_qos.multi_channel.channels[2].filter_expression = DDS_String_dup( "Symbol MATCH '[G-I]*'"); writer_qos.multi_channel.channels[2].multicast_settings.ensure_length(1, 1); writer_qos.multi_channel.channels[2].multicast_settings[0].receive_address = DDS_String_dup("239.255.0.4"); writer_qos.multi_channel.channels[3].filter_expression = DDS_String_dup( "Symbol MATCH '[J-L]*'"); writer_qos.multi_channel.channels[3].multicast_settings.ensure_length(1, 1); writer_qos.multi_channel.channels[3].multicast_settings[0].receive_address = DDS_String_dup("239.255.0.5"); writer_qos.multi_channel.channels[4].filter_expression = DDS_String_dup( "Symbol MATCH '[M-O]*'"); writer_qos.multi_channel.channels[4].multicast_settings.ensure_length(1, 1); writer_qos.multi_channel.channels[4].multicast_settings[0].receive_address = DDS_String_dup("239.255.0.6"); writer_qos.multi_channel.channels[5].filter_expression = DDS_String_dup( "Symbol MATCH '[P-S]*'"); writer_qos.multi_channel.channels[5].multicast_settings.ensure_length(1, 1); writer_qos.multi_channel.channels[5].multicast_settings[0].receive_address = DDS_String_dup("239.255.0.7"); writer_qos.multi_channel.channels[6].filter_expression = DDS_String_dup( "Symbol MATCH '[T-V]*'"); writer_qos.multi_channel.channels[6].multicast_settings.ensure_length(1, 1); writer_qos.multi_channel.channels[6].multicast_settings[0].receive_address = DDS_String_dup("239.255.0.8"); writer_qos.multi_channel.channels[7].filter_expression = DDS_String_dup( "Symbol MATCH '[W-Z]*'"); writer_qos.multi_channel.channels[7].multicast_settings.ensure_length(1, 1); writer_qos.multi_channel.channels[7].multicast_settings[0].receive_address = DDS_String_dup("239.255.0.9"); */ // This DataWriter writes data on "Example prueba" Topic DDSDataWriter *untyped_writer = publisher->create_datawriter( topic, /*writer_qos*/ DDS_DATAWRITER_QOS_DEFAULT, NULL /* listener */, DDS_STATUS_MASK_NONE); if (untyped_writer == NULL) { return shutdown_participant( participant, "create_datawriter error", EXIT_FAILURE); } /* End changes for MultiChannel */ market_dataDataWriter *typed_writer = market_dataDataWriter::narrow(untyped_writer); if (typed_writer == NULL) { return shutdown_participant( participant, "DataWriter narrow error", EXIT_FAILURE); } // Create data for writing, allocating all members market_data *data = market_dataTypeSupport::create_data(); if (data == NULL) { return shutdown_participant( participant, "market_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) { // Changes for MultiChannel // Modify the data to be sent here sprintf(data->Symbol, "%c", 'A' + (samples_written % 26)); data->Price = 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 prueba, including all contained elements retcode = market_dataTypeSupport::delete_data(data); if (retcode != DDS_RETCODE_OK) { std::cerr << "market_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); // 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/multichannel/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/multichannel/c/market_data_publisher.c
/******************************************************************************* (c) 2005-2014 Copyright, Real-Time Innovations, Inc. All rights reserved. RTI grants Licensee a license to use, modify, compile, and create derivative works of the Software. Licensee has the right to distribute object form only for use with RTI products. The Software is provided "as is", with no warranty of any type, including any warranty for fitness for any purpose. RTI is under no obligation to maintain or support the Software. RTI shall not be liable for any incidental or consequential damages arising out of the use or inability to use the software. ******************************************************************************/ /* market_data_publisher.c A publication of data of type market_data This file is derived from code automatically generated by the rtiddsgen command: rtiddsgen -language C -example <arch> market_data.idl Example publication of type market_data automatically generated by 'rtiddsgen'. To test them follow these steps: (1) Compile this file and the example subscription. (2) Start the subscription with the command objs/<arch>/market_data_subscriber <domain_id> <sample_count> (3) Start the publication with the command objs/<arch>/market_data_publisher <domain_id> <sample_count> (4) [Optional] Specify the list of discovery initial peers and multicast receive addresses via an environment variable or a file (in the current working directory) called NDDS_DISCOVERY_PEERS. You can run any number of publishers and subscribers programs, and can add and remove them dynamically from the domain. Example: To run the example application on domain <domain_id>: On Unix: objs/<arch>/market_data_publisher <domain_id> objs/<arch>/market_data_subscriber <domain_id> On Windows: objs\<arch>\market_data_publisher <domain_id> objs\<arch>\market_data_subscriber <domain_id> modification history ------------ ------- */ #include "market_data.h" #include "market_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) { DDS_DomainParticipant *participant = NULL; DDS_Publisher *publisher = NULL; DDS_Topic *topic = NULL; DDS_DataWriter *writer = NULL; market_dataDataWriter *market_data_writer = NULL; market_data *instance = NULL; DDS_ReturnCode_t retcode; DDS_InstanceHandle_t instance_handle = DDS_HANDLE_NIL; const char *type_name = NULL; int count = 0; /* struct DDS_DataWriterQos writer_qos = DDS_DataWriterQos_INITIALIZER; */ struct DDS_ChannelSettings_t *curr_channel; /* Changes for MultiChannel */ struct DDS_Duration_t send_period = { 0, 100000000 }; /* To customize participant QoS, use the configuration file USER_QOS_PROFILES.xml */ participant = DDS_DomainParticipantFactory_create_participant( DDS_TheParticipantFactory, domainId, &DDS_PARTICIPANT_QOS_DEFAULT, NULL /* listener */, DDS_STATUS_MASK_NONE); if (participant == NULL) { printf("create_participant error\n"); publisher_shutdown(participant); return -1; } /* To customize publisher QoS, use the configuration file USER_QOS_PROFILES.xml */ publisher = DDS_DomainParticipant_create_publisher( participant, &DDS_PUBLISHER_QOS_DEFAULT, NULL /* listener */, DDS_STATUS_MASK_NONE); if (publisher == NULL) { printf("create_publisher error\n"); publisher_shutdown(participant); return -1; } /* Register type before creating topic */ type_name = market_dataTypeSupport_get_type_name(); retcode = market_dataTypeSupport_register_type(participant, type_name); if (retcode != DDS_RETCODE_OK) { printf("register_type error %d\n", retcode); publisher_shutdown(participant); return -1; } /* To customize topic QoS, use the configuration file USER_QOS_PROFILES.xml */ topic = DDS_DomainParticipant_create_topic( participant, "Example market_data", type_name, &DDS_TOPIC_QOS_DEFAULT, NULL /* listener */, DDS_STATUS_MASK_NONE); if (topic == NULL) { printf("create_topic error\n"); publisher_shutdown(participant); return -1; } /* If you want to change the DataWriter's QoS programmatically rather than * using the XML file, you will need to add the following lines to your * code and modify the datawriter creation fuction using writer_qos. * * In this case, we set the publish as multichannel using the differents * channel to send differents symbol. Every channel have a IP to send the * data. */ /* Start changes for MultiChannel */ /* retcode = DDS_Publisher_get_default_datawriter_qos(publisher, &writer_qos); if (retcode != DDS_RETCODE_OK) { printf("get_default_datawriter_qos error\n"); publisher_shutdown(participant); return -1; } */ /* Create 8 channels based on Symbol */ /* DDS_ChannelSettingsSeq_ensure_length(&writer_qos.multi_channel.channels, 8, 8); curr_channel = DDS_ChannelSettingsSeq_get_reference( &writer_qos.multi_channel.channels, 0); curr_channel->filter_expression = DDS_String_dup("Symbol MATCH '[A-C]*'"); DDS_TransportMulticastSettingsSeq_ensure_length( &curr_channel->multicast_settings, 1, 1); DDS_TransportMulticastSettingsSeq_get_reference( &curr_channel->multicast_settings, 0)->receive_address = DDS_String_dup("239.255.0.2"); curr_channel = DDS_ChannelSettingsSeq_get_reference( &writer_qos.multi_channel.channels, 1); curr_channel->filter_expression = DDS_String_dup("Symbol MATCH '[D-F]*'"); DDS_TransportMulticastSettingsSeq_ensure_length( &curr_channel->multicast_settings, 1, 1); DDS_TransportMulticastSettingsSeq_get_reference( &curr_channel->multicast_settings, 0)->receive_address = DDS_String_dup("239.255.0.3"); curr_channel = DDS_ChannelSettingsSeq_get_reference( &writer_qos.multi_channel.channels, 2); curr_channel->filter_expression = DDS_String_dup("Symbol MATCH '[G-I]*'"); DDS_TransportMulticastSettingsSeq_ensure_length( &curr_channel->multicast_settings, 1, 1); DDS_TransportMulticastSettingsSeq_get_reference( &curr_channel->multicast_settings, 0)->receive_address = DDS_String_dup("239.255.0.4"); curr_channel = DDS_ChannelSettingsSeq_get_reference( &writer_qos.multi_channel.channels, 3); curr_channel->filter_expression = DDS_String_dup("Symbol MATCH '[J-L]*'"); DDS_TransportMulticastSettingsSeq_ensure_length( &curr_channel->multicast_settings, 1, 1); DDS_TransportMulticastSettingsSeq_get_reference( &curr_channel->multicast_settings, 0)->receive_address = DDS_String_dup("239.255.0.5"); curr_channel = DDS_ChannelSettingsSeq_get_reference( &writer_qos.multi_channel.channels, 4); curr_channel->filter_expression = DDS_String_dup("Symbol MATCH '[M-O]*'"); DDS_TransportMulticastSettingsSeq_ensure_length( &curr_channel->multicast_settings, 1, 1); DDS_TransportMulticastSettingsSeq_get_reference( &curr_channel->multicast_settings, 0)->receive_address = DDS_String_dup("239.255.0.6"); curr_channel = DDS_ChannelSettingsSeq_get_reference( &writer_qos.multi_channel.channels, 5); curr_channel->filter_expression = DDS_String_dup("Symbol MATCH '[P-S]*'"); DDS_TransportMulticastSettingsSeq_ensure_length( &curr_channel->multicast_settings, 1, 1); DDS_TransportMulticastSettingsSeq_get_reference( &curr_channel->multicast_settings, 0)->receive_address = DDS_String_dup("239.255.0.7"); curr_channel = DDS_ChannelSettingsSeq_get_reference( &writer_qos.multi_channel.channels, 6); curr_channel->filter_expression = DDS_String_dup("Symbol MATCH '[T-V]*'"); DDS_TransportMulticastSettingsSeq_ensure_length( &curr_channel->multicast_settings, 1, 1); DDS_TransportMulticastSettingsSeq_get_reference( &curr_channel->multicast_settings, 0)->receive_address = DDS_String_dup("239.255.0.8"); curr_channel = DDS_ChannelSettingsSeq_get_reference( &writer_qos.multi_channel.channels, 7); curr_channel->filter_expression = DDS_String_dup("Symbol MATCH '[W-Z]*'"); DDS_TransportMulticastSettingsSeq_ensure_length( &curr_channel->multicast_settings, 1, 1); DDS_TransportMulticastSettingsSeq_get_reference( &curr_channel->multicast_settings, 0)->receive_address = DDS_String_dup("239.255.0.9"); */ /* To customize data writer QoS, use * the configuration file USER_QOS_PROFILES.xml */ /* toggle between writer_qos and DDS_DATAWRITER_QOS_DEFAULT to alternate * between using code and using XML to specify the Qos */ writer = DDS_Publisher_create_datawriter( publisher, topic, /*&writer_qos*/ &DDS_DATAWRITER_QOS_DEFAULT, NULL /* listener */, DDS_STATUS_MASK_NONE); if (writer == NULL) { printf("create_datawriter error\n"); publisher_shutdown(participant); return -1; } /* End changes for MultiChannel */ market_data_writer = market_dataDataWriter_narrow(writer); if (market_data_writer == NULL) { printf("DataWriter narrow error\n"); publisher_shutdown(participant); return -1; } /* Create data sample for writing */ instance = market_dataTypeSupport_create_data_ex(DDS_BOOLEAN_TRUE); if (instance == NULL) { printf("market_dataTypeSupport_create_data error\n"); publisher_shutdown(participant); return -1; } /* For a data type that has a key, if the same instance is going to be written multiple times, initialize the key here and register the keyed instance prior to writing */ /* instance_handle = market_dataDataWriter_register_instance( market_data_writer, instance); */ /* Main loop */ for (count = 0; (sample_count == 0) || (count < sample_count); ++count) { /* printf("Writing market_data, count %d\n", count); */ /* Changes for MultiChannel */ /* Everey time a character is sent between ['A'-'Z'] */ sprintf(instance->Symbol, "%c", 'A' + (count % 26)); instance->Price = count; /* Write data */ retcode = market_dataDataWriter_write( market_data_writer, instance, &instance_handle); if (retcode != DDS_RETCODE_OK) { printf("write error %d\n", retcode); } NDDS_Utility_sleep(&send_period); } /* retcode = market_dataDataWriter_unregister_instance( market_data_writer, instance, &instance_handle); if (retcode != DDS_RETCODE_OK) { printf("unregister instance error %d\n", retcode); } */ /* Delete data sample */ retcode = market_dataTypeSupport_delete_data_ex(instance, DDS_BOOLEAN_TRUE); if (retcode != DDS_RETCODE_OK) { printf("market_dataTypeSupport_delete_data error %d\n", retcode); } /* Cleanup and delete delete all entities */ return publisher_shutdown(participant); } #if defined(RTI_WINCE) int wmain(int argc, wchar_t **argv) { int domainId = 0; int sample_count = 0; /* infinite loop */ if (argc >= 2) { domainId = _wtoi(argv[1]); } if (argc >= 3) { sample_count = _wtoi(argv[2]); } /* Uncomment this to turn on additional logging NDDS_Config_Logger_set_verbosity_by_category( NDDS_Config_Logger_get_instance(), NDDS_CONFIG_LOG_CATEGORY_API, NDDS_CONFIG_LOG_VERBOSITY_STATUS_ALL); */ return publisher_main(domainId, sample_count); } #elif !(defined(RTI_VXWORKS) && !defined(__RTP__)) && !defined(RTI_PSOS) int main(int argc, char *argv[]) { int domainId = 0; int sample_count = 0; /* infinite loop */ if (argc >= 2) { domainId = atoi(argv[1]); } if (argc >= 3) { sample_count = atoi(argv[2]); } /* Uncomment this to turn on additional logging NDDS_Config_Logger_set_verbosity_by_category( NDDS_Config_Logger_get_instance(), NDDS_CONFIG_LOG_CATEGORY_API, NDDS_CONFIG_LOG_VERBOSITY_STATUS_ALL); */ return publisher_main(domainId, sample_count); } #endif #ifdef RTI_VX653 const unsigned char *__ctype = NULL; void usrAppInit() { #ifdef USER_APPL_INIT USER_APPL_INIT; /* for backwards compatibility */ #endif /* add application specific code here */ taskSpawn( "pub", RTI_OSAPI_THREAD_PRIORITY_NORMAL, 0x8, 0x150000, (FUNCPTR) publisher_main, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0); } #endif
c
rticonnextdds-examples
data/projects/rticonnextdds-examples/connext_dds/multichannel/c/market_data_subscriber.c
/******************************************************************************* (c) 2005-2014 Copyright, Real-Time Innovations, Inc. All rights reserved. RTI grants Licensee a license to use, modify, compile, and create derivative works of the Software. Licensee has the right to distribute object form only for use with RTI products. The Software is provided "as is", with no warranty of any type, including any warranty for fitness for any purpose. RTI is under no obligation to maintain or support the Software. RTI shall not be liable for any incidental or consequential damages arising out of the use or inability to use the software. ******************************************************************************/ /* market_data_subscriber.c A subscription example This file is derived from code automatically generated by the rtiddsgen command: rtiddsgen -language C -example <arch> market_data.idl Example subscription of type market_data automatically generated by 'rtiddsgen'. To test them, follow these steps: (1) Compile this file and the example publication. (2) Start the subscription with the command objs/<arch>/market_data_subscriber <domain_id> <sample_count> (3) Start the publication with the command objs/<arch>/market_data_publisher <domain_id> <sample_count> (4) [Optional] Specify the list of discovery initial peers and multicast receive addresses via an environment variable or a file (in the current working directory) called NDDS_DISCOVERY_PEERS. You can run any number of publishers and subscribers programs, and can add and remove them dynamically from the domain. Example: To run the example application on domain <domain_id>: On UNIX systems: objs/<arch>/market_data_publisher <domain_id> objs/<arch>/market_data_subscriber <domain_id> On Windows systems: objs\<arch>\market_data_publisher <domain_id> objs\<arch>\market_data_subscriber <domain_id> modification history ------------ ------- */ #include "market_data.h" #include "market_dataSupport.h" #include "ndds/ndds_c.h" #include <stdio.h> #include <stdlib.h> void market_dataListener_on_requested_deadline_missed( void *listener_data, DDS_DataReader *reader, const struct DDS_RequestedDeadlineMissedStatus *status) { } void market_dataListener_on_requested_incompatible_qos( void *listener_data, DDS_DataReader *reader, const struct DDS_RequestedIncompatibleQosStatus *status) { } void market_dataListener_on_sample_rejected( void *listener_data, DDS_DataReader *reader, const struct DDS_SampleRejectedStatus *status) { } void market_dataListener_on_liveliness_changed( void *listener_data, DDS_DataReader *reader, const struct DDS_LivelinessChangedStatus *status) { } void market_dataListener_on_sample_lost( void *listener_data, DDS_DataReader *reader, const struct DDS_SampleLostStatus *status) { } void market_dataListener_on_subscription_matched( void *listener_data, DDS_DataReader *reader, const struct DDS_SubscriptionMatchedStatus *status) { } void market_dataListener_on_data_available( void *listener_data, DDS_DataReader *reader) { market_dataDataReader *market_data_reader = NULL; struct market_dataSeq data_seq = DDS_SEQUENCE_INITIALIZER; struct DDS_SampleInfoSeq info_seq = DDS_SEQUENCE_INITIALIZER; DDS_ReturnCode_t retcode; int i; market_data_reader = market_dataDataReader_narrow(reader); if (market_data_reader == NULL) { printf("DataReader narrow error\n"); return; } retcode = market_dataDataReader_take( market_data_reader, &data_seq, &info_seq, DDS_LENGTH_UNLIMITED, DDS_ANY_SAMPLE_STATE, DDS_ANY_VIEW_STATE, DDS_ANY_INSTANCE_STATE); if (retcode == DDS_RETCODE_NO_DATA) { return; } else if (retcode != DDS_RETCODE_OK) { printf("take error %d\n", retcode); return; } for (i = 0; i < market_dataSeq_get_length(&data_seq); ++i) { if (DDS_SampleInfoSeq_get_reference(&info_seq, i)->valid_data) { market_dataTypeSupport_print_data( market_dataSeq_get_reference(&data_seq, i)); } } retcode = market_dataDataReader_return_loan( market_data_reader, &data_seq, &info_seq); if (retcode != DDS_RETCODE_OK) { printf("return loan error %d\n", retcode); } } /* Delete all entities */ static int subscriber_shutdown(DDS_DomainParticipant *participant) { DDS_ReturnCode_t retcode; int status = 0; if (participant != NULL) { retcode = DDS_DomainParticipant_delete_contained_entities(participant); if (retcode != DDS_RETCODE_OK) { printf("delete_contained_entities error %d\n", retcode); status = -1; } retcode = DDS_DomainParticipantFactory_delete_participant( DDS_TheParticipantFactory, participant); if (retcode != DDS_RETCODE_OK) { printf("delete_participant error %d\n", retcode); status = -1; } } /* RTI Connext provides the finalize_instance() method on domain participant factory for users who want to release memory used by the participant factory. Uncomment the following block of code for clean destruction of the singleton. */ /* retcode = DDS_DomainParticipantFactory_finalize_instance(); if (retcode != DDS_RETCODE_OK) { printf("finalize_instance error %d\n", retcode); status = -1; } */ return status; } static int subscriber_main(int domainId, int sample_count) { DDS_DomainParticipant *participant = NULL; DDS_Subscriber *subscriber = NULL; DDS_Topic *topic = NULL; struct DDS_DataReaderListener reader_listener = DDS_DataReaderListener_INITIALIZER; DDS_DataReader *reader = NULL; DDS_ReturnCode_t retcode; const char *type_name = NULL; int count = 0; struct DDS_Duration_t poll_period = { 4, 0 }; DDS_ContentFilteredTopic *filtered_topic = NULL; struct DDS_StringSeq expression_parameters; /* To customize participant QoS, use the configuration file USER_QOS_PROFILES.xml */ participant = DDS_DomainParticipantFactory_create_participant( DDS_TheParticipantFactory, domainId, &DDS_PARTICIPANT_QOS_DEFAULT, NULL /* listener */, DDS_STATUS_MASK_NONE); if (participant == NULL) { printf("create_participant error\n"); subscriber_shutdown(participant); return -1; } /* To customize subscriber QoS, use the configuration file USER_QOS_PROFILES.xml */ subscriber = DDS_DomainParticipant_create_subscriber( participant, &DDS_SUBSCRIBER_QOS_DEFAULT, NULL /* listener */, DDS_STATUS_MASK_NONE); if (subscriber == NULL) { printf("create_subscriber error\n"); subscriber_shutdown(participant); return -1; } /* Register the type before creating the topic */ type_name = market_dataTypeSupport_get_type_name(); retcode = market_dataTypeSupport_register_type(participant, type_name); if (retcode != DDS_RETCODE_OK) { printf("register_type error %d\n", retcode); subscriber_shutdown(participant); return -1; } /* To customize topic QoS, use the configuration file USER_QOS_PROFILES.xml */ topic = DDS_DomainParticipant_create_topic( participant, "Example market_data", type_name, &DDS_TOPIC_QOS_DEFAULT, NULL /* listener */, DDS_STATUS_MASK_NONE); if (topic == NULL) { printf("create_topic error\n"); subscriber_shutdown(participant); return -1; } /* Start changes for MultiChannel */ filtered_topic = DDS_DomainParticipant_create_contentfilteredtopic_with_filter( participant, "Example market_data", topic, "Symbol MATCH 'A'", &expression_parameters, DDS_STRINGMATCHFILTER_NAME); if (filtered_topic == NULL) { printf("create_contentfilteredtopic error\n"); subscriber_shutdown(participant); return -1; } /* Set up a data reader listener */ reader_listener.on_requested_deadline_missed = market_dataListener_on_requested_deadline_missed; reader_listener.on_requested_incompatible_qos = market_dataListener_on_requested_incompatible_qos; reader_listener.on_sample_rejected = market_dataListener_on_sample_rejected; reader_listener.on_liveliness_changed = market_dataListener_on_liveliness_changed; reader_listener.on_sample_lost = market_dataListener_on_sample_lost; reader_listener.on_subscription_matched = market_dataListener_on_subscription_matched; reader_listener.on_data_available = market_dataListener_on_data_available; /* To customize data reader QoS, use the configuration file USER_QOS_PROFILES.xml */ reader = DDS_Subscriber_create_datareader( subscriber, DDS_Topic_as_topicdescription(filtered_topic), &DDS_DATAREADER_QOS_DEFAULT, &reader_listener, DDS_STATUS_MASK_ALL); if (reader == NULL) { printf("create_datareader error\n"); subscriber_shutdown(participant); return -1; } printf("filter is Symbol MATCH 'A'\n"); /* Main loop */ for (count = 0; (sample_count == 0) || (count < sample_count); ++count) { /* printf("market_data subscriber sleeping for %d sec...\n", poll_period.sec); */ if (count == 3) { retcode = DDS_ContentFilteredTopic_append_to_expression_parameter( filtered_topic, 0, "D"); if (retcode != DDS_RETCODE_OK) { printf("append_to_expression_parameter %d\n", retcode); subscriber_shutdown(participant); return -1; } printf("changed filter to Symbol MATCH 'A,D'\n"); } if (count == 6) { retcode = DDS_ContentFilteredTopic_remove_from_expression_parameter( filtered_topic, 0, "A"); if (retcode != DDS_RETCODE_OK) { printf("append_to_expression_parameter %d\n", retcode); subscriber_shutdown(participant); return -1; } printf("changed filter to Symbol MATCH 'D'\n"); } NDDS_Utility_sleep(&poll_period); } /* End changes for MultiChannel */ /* Cleanup and delete all entities */ return subscriber_shutdown(participant); } #if defined(RTI_WINCE) int wmain(int argc, wchar_t **argv) { int domainId = 0; int sample_count = 0; /* infinite loop */ if (argc >= 2) { domainId = _wtoi(argv[1]); } if (argc >= 3) { sample_count = _wtoi(argv[2]); } /* Uncomment this to turn on additional logging NDDS_Config_Logger_set_verbosity_by_category( NDDS_Config_Logger_get_instance(), NDDS_CONFIG_LOG_CATEGORY_API, NDDS_CONFIG_LOG_VERBOSITY_STATUS_ALL); */ return subscriber_main(domainId, sample_count); } #elif !(defined(RTI_VXWORKS) && !defined(__RTP__)) && !defined(RTI_PSOS) int main(int argc, char *argv[]) { int domainId = 0; int sample_count = 0; /* infinite loop */ if (argc >= 2) { domainId = atoi(argv[1]); } if (argc >= 3) { sample_count = atoi(argv[2]); } /* Uncomment this to turn on additional logging NDDS_Config_Logger_set_verbosity_by_category( NDDS_Config_Logger_get_instance(), NDDS_CONFIG_LOG_CATEGORY_API, NDDS_CONFIG_LOG_VERBOSITY_STATUS_ALL); */ return subscriber_main(domainId, sample_count); } #endif #ifdef RTI_VX653 const unsigned char *__ctype = NULL; void usrAppInit() { #ifdef USER_APPL_INIT USER_APPL_INIT; /* for backwards compatibility */ #endif /* add application specific code here */ taskSpawn( "sub", RTI_OSAPI_THREAD_PRIORITY_NORMAL, 0x8, 0x150000, (FUNCPTR) subscriber_main, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0); } #endif
c
rticonnextdds-examples
data/projects/rticonnextdds-examples/connext_dds/multichannel/c++03/market_data_subscriber.cxx
/******************************************************************************* (c) 2005-2015 Copyright, Real-Time Innovations, Inc. All rights reserved. RTI grants Licensee a license to use, modify, compile, and create derivative works of the Software. Licensee has the right to distribute object form only for use with RTI products. The Software is provided "as is", with no warranty of any type, including any warranty for fitness for any purpose. RTI is under no obligation to maintain or support the Software. RTI shall not be liable for any incidental or consequential damages arising out of the use or inability to use the software. ******************************************************************************/ #include <algorithm> #include <iostream> #include "market_data.hpp" #include <dds/dds.hpp> #include <rti/core/ListenerBinder.hpp> using namespace dds::core; using namespace rti::core; using namespace dds::core::status; using namespace dds::domain; using namespace dds::sub; using namespace dds::topic; class MarketDataReaderListener : public NoOpDataReaderListener<market_data> { public: void on_data_available(DataReader<market_data> &reader) { // Take all samples LoanedSamples<market_data> samples = reader.take(); for (LoanedSamples<market_data>::iterator sample_it = samples.begin(); sample_it != samples.end(); sample_it++) { if (sample_it->info().valid()) { std::cout << sample_it->data() << std::endl; } } } }; void subscriber_main(int domain_id, int sample_count) { // Create a DomainParticipant with default Qos DomainParticipant participant(domain_id); // Create a Topic -- and automatically register the type Topic<market_data> topic(participant, "Example market_data"); // Create a ContentFiltered Topic and specify the STRINGMATCH filter name // to use a built-in filter for matching multiple strings. // More information can be found in the example // 'content_filtered_topic_string_filter'. Filter filter("Symbol MATCH 'A'", std::vector<std::string>()); filter->name(rti::topic::stringmatch_filter_name()); std::cout << "filter is " << filter.expression() << std::endl; ContentFilteredTopic<market_data> cft_topic( topic, "ContentFilteredTopic", filter); // Create a DataReader with default Qos (Subscriber created in-line) DataReader<market_data> reader(Subscriber(participant), cft_topic); // Create a data reader listener using ListenerBinder, a RAII that // will take care of setting it to NULL on destruction. rti::core::ListenerBinder<DataReader<market_data> > scoped_listener = rti::core::bind_and_manage_listener( reader, new MarketDataReaderListener, StatusMask::data_available()); // Main loop. for (int count = 0; sample_count == 0 || count < sample_count; count++) { if (count == 3) { // On t=3 we add the symbol 'D' to the filter parameter // to match 'A' and 'D'. cft_topic->append_to_expression_parameter(0, "D"); std::cout << "changed filter to Symbol MATCH 'A,D'" << std::endl; } else if (count == 6) { // On t=6 we remove the symbol 'A' to the filter parameter // to match only 'D'. cft_topic->remove_from_expression_parameter(0, "A"); std::cout << "changed filter to Symbol MATCH 'D'" << std::endl; } rti::util::sleep(Duration(4)); } } int main(int argc, char *argv[]) { int domain_id = 0; int sample_count = 0; // Infinite loop if (argc >= 2) { domain_id = atoi(argv[1]); } if (argc >= 3) { sample_count = atoi(argv[2]); } // To turn on additional logging, include <rti/config/Logger.hpp> and // uncomment the following line: // rti::config::Logger::instance().verbosity(rti::config::Verbosity::STATUS_ALL); try { subscriber_main(domain_id, sample_count); } catch (const std::exception &ex) { // This will catch DDS exceptions std::cerr << "Exception in subscriber_main: " << ex.what() << std::endl; return -1; } return 0; }
cxx
rticonnextdds-examples
data/projects/rticonnextdds-examples/connext_dds/multichannel/c++03/market_data_publisher.cxx
/******************************************************************************* (c) 2005-2015 Copyright, Real-Time Innovations, Inc. All rights reserved. RTI grants Licensee a license to use, modify, compile, and create derivative works of the Software. Licensee has the right to distribute object form only for use with RTI products. The Software is provided "as is", with no warranty of any type, including any warranty for fitness for any purpose. RTI is under no obligation to maintain or support the Software. RTI shall not be liable for any incidental or consequential damages arising out of the use or inability to use the software. ******************************************************************************/ #include <iostream> #include "market_data.hpp" #include <dds/dds.hpp> using namespace dds::core; using namespace rti::core; using namespace rti::core::policy; using namespace dds::domain; using namespace dds::topic; using namespace dds::pub; using namespace dds::pub::qos; MultiChannel create_multichannel_qos() { // We set the publish as multichannel using the different // channels to send different symbols. Every channel have a IP to send the // data. // Create 8 channels based on Symbol. std::vector<ChannelSettings> channels; channels.push_back(ChannelSettings( std::vector<TransportMulticastSettings>( 1, TransportMulticastSettings( std::vector<std::string>(), // All the transports // available "239.255.0.2", 0)), // Port determined automatically "Symbol MATCH '[A-C]*'", PUBLICATION_PRIORITY_UNDEFINED)); channels.push_back(ChannelSettings( std::vector<TransportMulticastSettings>( 1, TransportMulticastSettings( std::vector<std::string>(), "239.255.0.3", 0)), "Symbol MATCH '[D-F]*'", PUBLICATION_PRIORITY_UNDEFINED)); channels.push_back(ChannelSettings( std::vector<TransportMulticastSettings>( 1, TransportMulticastSettings( std::vector<std::string>(), "239.255.0.4", 0)), "Symbol MATCH '[G-I]*'", PUBLICATION_PRIORITY_UNDEFINED)); channels.push_back(ChannelSettings( std::vector<TransportMulticastSettings>( 1, TransportMulticastSettings( std::vector<std::string>(), "239.255.0.5", 0)), "Symbol MATCH '[J-L]*'", PUBLICATION_PRIORITY_UNDEFINED)); channels.push_back(ChannelSettings( std::vector<TransportMulticastSettings>( 1, TransportMulticastSettings( std::vector<std::string>(), "239.255.0.6", 0)), "Symbol MATCH '[M-O]*'", PUBLICATION_PRIORITY_UNDEFINED)); channels.push_back(ChannelSettings( std::vector<TransportMulticastSettings>( 1, TransportMulticastSettings( std::vector<std::string>(), "239.255.0.7", 0)), "Symbol MATCH '[P-S]*'", PUBLICATION_PRIORITY_UNDEFINED)); channels.push_back(ChannelSettings( std::vector<TransportMulticastSettings>( 1, TransportMulticastSettings( std::vector<std::string>(), "239.255.0.8", 0)), "Symbol MATCH '[T-V]*'", PUBLICATION_PRIORITY_UNDEFINED)); channels.push_back(ChannelSettings( std::vector<TransportMulticastSettings>( 1, TransportMulticastSettings( std::vector<std::string>(), "239.255.0.9", 0)), "Symbol MATCH '[W-Z]*'", PUBLICATION_PRIORITY_UNDEFINED)); // Set the MultiChannel QoS. return MultiChannel(channels, rti::topic::stringmatch_filter_name()); } void publisher_main(int domain_id, int sample_count) { // Create a DomainParticipant with default Qos DomainParticipant participant(domain_id); // Create a Topic -- and automatically register the type Topic<market_data> topic(participant, "Example market_data"); // Retrieve the default DataWriter QoS, from USER_QOS_PROFILES.xml DataWriterQos writer_qos = QosProvider::Default().datawriter_qos(); // If you want to change the DataWriter's QoS programmatically rather than // using the XML file, uncomment the following line. // writer_qos << create_multichannel_qos(); // Create a DataWriter (Publisher created in-line) DataWriter<market_data> writer(Publisher(participant), topic, writer_qos); // Create a data sample for writing. market_data sample; // Main loop. for (int count = 0; count < sample_count || sample_count == 0; count++) { // Update the sample. char symbol = (char) ('A' + (count % 26)); sample.Symbol(std::string(1, symbol)); sample.Price(count); // Send and wait. writer.write(sample); rti::util::sleep(Duration::from_millisecs(100)); } } int main(int argc, char *argv[]) { int domain_id = 0; int sample_count = 0; // Infinite loop if (argc >= 2) { domain_id = atoi(argv[1]); } if (argc >= 3) { sample_count = atoi(argv[2]); } // To turn on additional logging, include <rti/config/Logger.hpp> and // uncomment the following line: // rti::config::Logger::instance().verbosity(rti::config::Verbosity::STATUS_ALL); try { publisher_main(domain_id, sample_count); } catch (const std::exception &ex) { // This will catch DDS exceptions std::cerr << "Exception in publisher_main: " << ex.what() << std::endl; return -1; } return 0; }
cxx
rticonnextdds-examples
data/projects/rticonnextdds-examples/connext_dds/multichannel/c++11/market_data_subscriber.cxx
/******************************************************************************* (c) 2005-2015 Copyright, Real-Time Innovations, Inc. All rights reserved. RTI grants Licensee a license to use, modify, compile, and create derivative works of the Software. Licensee has the right to distribute object form only for use with RTI products. The Software is provided "as is", with no warranty of any type, including any warranty for fitness for any purpose. RTI is under no obligation to maintain or support the Software. RTI shall not be liable for any incidental or consequential damages arising out of the use or inability to use the software. ******************************************************************************/ #include <dds/sub/ddssub.hpp> #include <dds/core/ddscore.hpp> #include <rti/config/Logger.hpp> // for logging #include "market_data.hpp" #include "application.hpp" // for command line parsing and ctrl-c int process_data(dds::sub::DataReader<market_data> reader) { int count = 0; // Take all samples dds::sub::LoanedSamples<market_data> 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) { // Create a DomainParticipant with default Qos dds::domain::DomainParticipant participant(domain_id); // Create a Topic -- and automatically register the type dds::topic::Topic<market_data> topic(participant, "Example market_data"); // Create a ContentFiltered Topic and specify the STRINGMATCH filter name // to use a built-in filter for matching multiple strings. // More information can be found in the example // 'content_filtered_topic_string_filter'. dds::topic::Filter filter("Symbol MATCH 'A'", std::vector<std::string>()); filter->name(rti::topic::stringmatch_filter_name()); std::cout << "filter is " << filter.expression() << std::endl; dds::topic::ContentFilteredTopic<market_data> cft_topic( topic, "ContentFilteredTopic", filter); // Create a subscriber with default QoS dds::sub::Subscriber subscriber(participant); // Create a DataReader with default Qos (Subscriber created in-line) dds::sub::DataReader<market_data> reader(subscriber, cft_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) { if (samples_read == 3) { // On t=3 we add the symbol 'D' to the filter parameter // to match 'A' and 'D'. cft_topic.extensions().append_to_expression_parameter(0, "D"); std::cout << "changed filter to Symbol MATCH 'A,D'" << std::endl; } else if (samples_read == 6) { // On t=6 we remove the symbol 'A' to the filter parameter // to match only 'D'. cft_topic.extensions().remove_from_expression_parameter(0, "A"); std::cout << "changed filter to Symbol MATCH 'D'" << std::endl; } waitset.dispatch(dds::core::Duration(4)); } } int main(int argc, char *argv[]) { using namespace application; // Parse arguments and handle control-C auto arguments = parse_arguments(argc, argv); if (arguments.parse_result == ParseReturn::exit) { return EXIT_SUCCESS; } else if (arguments.parse_result == ParseReturn::failure) { return EXIT_FAILURE; } setup_signal_handlers(); // Sets Connext verbosity to help debugging rti::config::Logger::instance().verbosity(arguments.verbosity); try { run_subscriber_application(arguments.domain_id, arguments.sample_count); } catch (const std::exception &ex) { // This will catch DDS exceptions std::cerr << "Exception in run_subscriber_application(): " << ex.what() << std::endl; return EXIT_FAILURE; } // Releases the memory used by the participant factory. Optional at // application exit dds::domain::DomainParticipant::finalize_participant_factory(); return EXIT_SUCCESS; }
cxx
rticonnextdds-examples
data/projects/rticonnextdds-examples/connext_dds/multichannel/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/multichannel/c++11/market_data_publisher.cxx
/******************************************************************************* (c) 2005-2015 Copyright, Real-Time Innovations, Inc. All rights reserved. RTI grants Licensee a license to use, modify, compile, and create derivative works of the Software. Licensee has the right to distribute object form only for use with RTI products. The Software is provided "as is", with no warranty of any type, including any warranty for fitness for any purpose. RTI is under no obligation to maintain or support the Software. RTI shall not be liable for any incidental or consequential damages arising out of the use or inability to use the software. ******************************************************************************/ #include <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 "market_data.hpp" rti::core::policy::MultiChannel create_multichannel_qos() { // We set the publish as multichannel using the different // channels to send different symbols. Every channel have a IP to send the // data. // Create 8 channels based on Symbol. std::vector<rti::core::ChannelSettings> channels; channels.push_back(rti::core::ChannelSettings( { rti::core::TransportMulticastSettings( {}, // All the transports available "239.255.0.2", 0) }, // Port determined automatically "Symbol MATCH '[A-C]*'", rti::core::PUBLICATION_PRIORITY_UNDEFINED)); channels.push_back(rti::core::ChannelSettings( { rti::core::TransportMulticastSettings({}, "239.255.0.3", 0) }, "Symbol MATCH '[D-F]*'", rti::core::PUBLICATION_PRIORITY_UNDEFINED)); channels.push_back(rti::core::ChannelSettings( { rti::core::TransportMulticastSettings({}, "239.255.0.4", 0) }, "Symbol MATCH '[G-I]*'", rti::core::PUBLICATION_PRIORITY_UNDEFINED)); channels.push_back(rti::core::ChannelSettings( { rti::core::TransportMulticastSettings({}, "239.255.0.5", 0) }, "Symbol MATCH '[J-L]*'", rti::core::PUBLICATION_PRIORITY_UNDEFINED)); channels.push_back(rti::core::ChannelSettings( { rti::core::TransportMulticastSettings({}, "239.255.0.6", 0) }, "Symbol MATCH '[M-O]*'", rti::core::PUBLICATION_PRIORITY_UNDEFINED)); channels.push_back(rti::core::ChannelSettings( { rti::core::TransportMulticastSettings({}, "239.255.0.7", 0) }, "Symbol MATCH '[P-S]*'", rti::core::PUBLICATION_PRIORITY_UNDEFINED)); channels.push_back(rti::core::ChannelSettings( { rti::core::TransportMulticastSettings({}, "239.255.0.8", 0) }, "Symbol MATCH '[T-V]*'", rti::core::PUBLICATION_PRIORITY_UNDEFINED)); channels.push_back(rti::core::ChannelSettings( { rti::core::TransportMulticastSettings({}, "239.255.0.9", 0) }, "Symbol MATCH '[W-Z]*'", rti::core::PUBLICATION_PRIORITY_UNDEFINED)); // Set the MultiChannel QoS. return rti::core::policy::MultiChannel( channels, rti::topic::stringmatch_filter_name()); } 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<market_data> topic(participant, "Example market_data"); // Retrieve the default DataWriter QoS, from USER_QOS_PROFILES.xml dds::pub::qos::DataWriterQos writer_qos = dds::core::QosProvider::Default().datawriter_qos(); // If you want to change the DataWriter's QoS programmatically rather than // using the XML file, uncomment the following line. // writer_qos << create_multichannel_qos(); // Create a publisher dds::pub::Publisher publisher(participant); // Create a DataWriter dds::pub::DataWriter<market_data> writer(publisher, topic, writer_qos); // Create a data sample for writing. market_data sample; // Main loop. for (unsigned int samples_written = 0; !application::shutdown_requested && samples_written < sample_count; samples_written++) { // Update the sample. char symbol = (char) ('A' + (samples_written % 26)); sample.Symbol(std::string(1, symbol)); sample.Price(samples_written); // Send and wait. writer.write(sample); rti::util::sleep(dds::core::Duration::from_millisecs(100)); } } int main(int argc, char *argv[]) { using namespace application; // Parse arguments and handle control-C auto arguments = parse_arguments(argc, argv); if (arguments.parse_result == ParseReturn::exit) { return EXIT_SUCCESS; } else if (arguments.parse_result == ParseReturn::failure) { return EXIT_FAILURE; } setup_signal_handlers(); // Sets Connext verbosity to help debugging rti::config::Logger::instance().verbosity(arguments.verbosity); try { run_publisher_application(arguments.domain_id, arguments.sample_count); } catch (const std::exception &ex) { // This will catch DDS exceptions std::cerr << "Exception in run_publisher_application(): " << ex.what() << std::endl; return EXIT_FAILURE; } // Releases the memory used by the participant factory. Optional at // application exit dds::domain::DomainParticipant::finalize_participant_factory(); return EXIT_SUCCESS; }
cxx
rticonnextdds-examples
data/projects/rticonnextdds-examples/connext_dds/flat_data_latency/c++11/application.hpp
/* * (c) Copyright, Real-Time Innovations, 2020. All rights reserved. * RTI grants Licensee a license to use, modify, compile, and create derivative * works of the software solely for use with RTI Connext DDS. Licensee may * redistribute copies of the software provided that all such copies are subject * to this license. The software is provided "as is", with no warranty of any * type, including any warranty for fitness for any purpose. RTI is under no * obligation to maintain or support the software. RTI shall not be liable for * any incidental or consequential damages arising out of the use or inability * to use the software. */ #ifndef APPLICATION_HPP #define APPLICATION_HPP #include <iostream> #include <csignal> #include <dds/core/ddscore.hpp> namespace application { // Catch control-C and tell application to shut down bool shutdown_requested = false; inline void stop_handler(int) { shutdown_requested = true; std::cout << "preparing to shut down..." << std::endl; } inline void setup_signal_handlers() { signal(SIGINT, stop_handler); signal(SIGTERM, stop_handler); } enum class ParseReturn { ok, failure, exit }; enum class ApplicationKind { publisher, subscriber }; struct ApplicationArguments { ParseReturn parse_result; unsigned int domain_id; unsigned int sample_count; rti::config::Verbosity verbosity; unsigned int mode; unsigned int execution_time; bool display_sample; std::string nic; ApplicationArguments( ParseReturn parse_result_param, unsigned int domain_id_param, unsigned int sample_count_param, rti::config::Verbosity verbosity_param, unsigned int mode_param, unsigned int execution_time_param, bool display_sample_param, std::string nic_param) : parse_result(parse_result_param), domain_id(domain_id_param), sample_count(sample_count_param), verbosity(verbosity_param), mode(mode_param), execution_time(execution_time_param), display_sample(display_sample_param), nic(nic_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); unsigned int mode = 1; bool display_sample = false; unsigned int execution_time = 30000000; std::string nic; 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], "-m") == 0 || strcmp(argv[arg_processing], "--mode") == 0)) { mode = 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::publisher) && (strcmp(argv[arg_processing], "-e") == 0 || strcmp(argv[arg_processing], "--exec_time") == 0)) { execution_time = atoi(argv[arg_processing + 1]); arg_processing += 2; } else if ( (current_application == ApplicationKind::subscriber) && (strcmp(argv[arg_processing], "-ds") == 0 || strcmp(argv[arg_processing], "--display_samples") == 0)) { display_sample = true; arg_processing += 1; } else if ( (argc > arg_processing + 1) && (strcmp(argv[arg_processing], "-n") == 0 || strcmp(argv[arg_processing], "--nic") == 0)) { nic = 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" " -m, --mode <int> Publisher modes\n" " 1. publisher_flat\n" " 2. publisher_zero_copy\n" " 3. " "publisher_flat_zero_copy\n" " 4. publisher_plain\n" " Default: 1\n"; if (current_application == ApplicationKind::publisher) { std::cout << " -s, --sample_count <int> Number of samples to " "receive before\n" " cleanly shutting down.\n" " Default: infinite\n" " -e, --exec_time <int> Execution time in " "seconds.\n"; } else { std::cout << " -d, --display_sample Displays the sample.\n"; } std::cout << " -n, --nic <string> Use the nic specified by " "<ipaddr> to send.\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, mode, execution_time, display_sample, nic); } } // namespace application #endif // APPLICATION_HPP
hpp
rticonnextdds-examples
data/projects/rticonnextdds-examples/connext_dds/flat_data_latency/c++11/CameraImage_publisher.cxx
/* * (c) 2019 Copyright, Real-Time Innovations, Inc. All rights reserved. * * RTI grants Licensee a license to use, modify, compile, and create derivative * works of the Software. Licensee has the right to distribute object form * only for use with RTI products. The Software is provided "as is", with no * warranty of any type, including any warranty for fitness for any purpose. * RTI is under no obligation to maintain or support the Software. RTI shall * not be liable for any incidental or consequential damages arising out of the * use or inability to use the software. */ #include <iostream> #include <memory> // for shared_ptr and unique_ptr #include <signal.h> #include <dds/core/ddscore.hpp> #include <dds/pub/ddspub.hpp> #include <dds/sub/ddssub.hpp> #include <rti/config/Logger.hpp> #include <rti/util/util.hpp> // for sleep() #include "CameraImage.hpp" #include <rti/zcopy/pub/ZcopyDataWriter.hpp> #include <rti/zcopy/sub/ZcopyDataReader.hpp> #include "Common.hpp" void publisher_flat(const application::ApplicationArguments &options) { using namespace flat_types; using namespace dds::core::policy; std::cout << "Running publisher_flat\n"; auto participant_qos = dds::core::QosProvider::Default().participant_qos(); configure_nic(participant_qos, options.nic); dds::domain::DomainParticipant participant( options.domain_id, participant_qos); // Create the ping DataWriter dds::topic::Topic<CameraImage> ping_topic(participant, "CameraImagePing"); dds::pub::DataWriter<CameraImage> writer( dds::pub::Publisher(participant), ping_topic); // Create the pong DataReader dds::topic::Topic<CameraImage> pong_topic(participant, "CameraImagePong"); dds::sub::DataReader<CameraImage> reader( dds::sub::Subscriber(participant), pong_topic); // Create a ReadCondition for any data on the pong reader, and attach it to // a Waitset dds::sub::cond::ReadCondition read_condition( reader, dds::sub::status::DataState::any()); dds::core::cond::WaitSet waitset; waitset += read_condition; std::cout << "Waiting for the subscriber application\n"; wait_for_reader(writer); wait_for_writer(reader); std::cout << "Discovery complete\n"; int count = 0; uint64_t total_latency = 0; uint64_t latency_interval_start_time = 0; uint64_t start_ts = participant->current_time().to_microsecs(); while (!application::shutdown_requested && count < options.sample_count) { // Get and populate the sample auto ping_sample = writer.extensions().get_loan(); populate_flat_sample(*ping_sample, count); // Write the ping sample: auto ping = ping_sample->root(); uint64_t send_ts = participant->current_time().to_microsecs(); if ((count == options.sample_count) || (send_ts - start_ts >= options.execution_time)) { // notify reader about last sample ping.timestamp(0); writer.write(*ping_sample); break; } ping.timestamp(send_ts); // Write the ping sample. // // The DataWriter now owns the buffer and the application should not // reuse the sample. writer.write(*ping_sample); if (latency_interval_start_time == 0) { latency_interval_start_time = send_ts; } // Wait for the pong auto conditions = waitset.wait(dds::core::Duration(10)); if (conditions.empty()) { std::cout << "Wait for pong: timeout\n"; } auto pong_samples = reader.take(); if (pong_samples.length() > 0 && pong_samples[0].info().valid()) { count++; auto pong = pong_samples[0].data().root(); uint64_t receive_ts = participant->current_time().to_microsecs(); uint64_t latency = receive_ts - pong.timestamp(); total_latency += latency; if (receive_ts - latency_interval_start_time > 4000000) { print_latency(total_latency, count); latency_interval_start_time = 0; } } } // Wait for unmatch wait_for_reader(writer, false); std::cout << "Publisher shutting down\n"; } void publisher_zero_copy(const application::ApplicationArguments &options) { using namespace zero_copy_types; using namespace rti::core::policy; std::cout << "Running publisher_zero_copy\n"; dds::domain::DomainParticipant participant(options.domain_id); // Create the ping DataWriter. dds::topic::Topic<CameraImage> ping_topic(participant, "CameraImagePing"); dds::pub::DataWriter<CameraImage> writer( dds::pub::Publisher(participant), ping_topic); // Create the pong DataReader dds::topic::Topic<CameraImage> pong_topic(participant, "CameraImagePong"); dds::sub::DataReader<CameraImage> reader( dds::sub::Subscriber(participant), pong_topic); // Create a ReadCondition for any data on the pong reader, and attach it to // a Waitset dds::sub::cond::ReadCondition read_condition( reader, dds::sub::status::DataState::any()); dds::core::cond::WaitSet waitset; waitset += read_condition; std::cout << "Waiting for the subscriber application\n"; wait_for_reader(writer); wait_for_writer(reader); std::cout << "Discovery complete\n"; // In this loop we write pings and wait for pongs, measuring the end-to-end // latency uint64_t total_latency = 0; uint64_t latency_interval_start_time = 0; int count = 0; uint64_t start_ts = participant->current_time().to_microsecs(); while (!application::shutdown_requested && count < options.sample_count) { // Create and write the ping sample: // The DataWriter gets a sample from its shared memory sample pool. This // operation does not allocate memory. Samples are returned to the // sample pool when they are returned from the DataWriter queue. CameraImage *ping_sample = writer.extensions().get_loan(); // Populate the sample populate_plain_sample(*ping_sample, count); uint64_t send_ts = participant->current_time().to_microsecs(); if ((count == options.sample_count) || (send_ts - start_ts >= options.execution_time)) { // notify reader about last sample ping_sample->timestamp(0); writer.write(*ping_sample); break; } ping_sample->timestamp(send_ts); writer.write(*ping_sample); if (latency_interval_start_time == 0) { latency_interval_start_time = send_ts; } // Wait for the pong auto conditions = waitset.wait(dds::core::Duration(10)); if (conditions.empty()) { std::cout << "Wait for pong: timeout\n"; } auto pong_samples = reader.take(); if (pong_samples.length() > 0 && pong_samples[0].info().valid()) { count++; uint64_t recv_ts = participant->current_time().to_microsecs(); uint64_t latency = recv_ts - pong_samples[0].data().timestamp(); total_latency += latency; if (recv_ts - latency_interval_start_time > 4000000) { print_latency(total_latency, count); latency_interval_start_time = 0; } } } // Wait for unmatch wait_for_reader(writer, false); std::cout << "Publisher shutting down\n"; } void publisher_flat_zero_copy(const application::ApplicationArguments &options) { using namespace flat_zero_copy_types; using namespace rti::core::policy; using namespace dds::core::policy; std::cout << "Running publisher_flat_zero_copy\n"; auto participant_qos = dds::core::QosProvider::Default().participant_qos(); configure_nic(participant_qos, options.nic); dds::domain::DomainParticipant participant( options.domain_id, participant_qos); // Create the ping DataWriter. We configure the pool of shared-memory // samples to contain 10 at all times. dds::topic::Topic<CameraImage> ping_topic(participant, "CameraImagePing"); dds::pub::DataWriter<CameraImage> writer( dds::pub::Publisher(participant), ping_topic); // Create the pong DataReader dds::topic::Topic<CameraImage> pong_topic(participant, "CameraImagePong"); dds::sub::DataReader<CameraImage> reader( dds::sub::Subscriber(participant), pong_topic); // Create a ReadCondition for any data on the pong reader, and attach it to // a Waitset dds::sub::cond::ReadCondition read_condition( reader, dds::sub::status::DataState::any()); dds::core::cond::WaitSet waitset; waitset += read_condition; std::cout << "Waiting for the subscriber application\n"; wait_for_reader(writer); wait_for_writer(reader); std::cout << "Discovery complete\n"; // In this loop we write pings and wait for pongs, measuring the end-to-end // latency uint64_t total_latency = 0; int count = 0; uint64_t latency_interval_start_time = 0; uint64_t start_ts = participant->current_time().to_microsecs(); while (!application::shutdown_requested && count < options.sample_count) { // Create and write the ping sample: CameraImage *ping_sample = writer.extensions().get_loan(); // Populate the sample populate_flat_sample(*ping_sample, count); auto ping = ping_sample->root(); uint64_t send_ts = participant->current_time().to_microsecs(); if ((count == options.sample_count) || (send_ts - start_ts >= options.execution_time)) { // notify reader about last sample ping.timestamp(0); writer.write(*ping_sample); break; } ping.timestamp(send_ts); writer.write(*ping_sample); if (latency_interval_start_time == 0) { latency_interval_start_time = send_ts; } // Wait for the pong auto conditions = waitset.wait(dds::core::Duration(10)); if (conditions.empty()) { std::cout << "Wait for pong: timeout\n"; } auto pong_samples = reader.take(); if (pong_samples.length() > 0 && pong_samples[0].info().valid()) { count++; auto pong = pong_samples[0].data().root(); uint64_t recv_ts = participant->current_time().to_microsecs(); uint64_t latency = recv_ts - pong.timestamp(); total_latency += latency; if (recv_ts - latency_interval_start_time > 4000000) { print_latency(total_latency, count); latency_interval_start_time = 0; } } } print_latency(total_latency, count); // Wait for unmatch wait_for_reader(writer, false); std::cout << "Publisher shutting down\n"; } void publisher_plain(const application::ApplicationArguments &options) { using namespace plain_types; using namespace dds::core::policy; std::cout << "Running publisher_plain\n"; auto participant_qos = dds::core::QosProvider::Default().participant_qos(); configure_nic(participant_qos, options.nic); dds::domain::DomainParticipant participant( options.domain_id, participant_qos); // Create the ping DataWriter dds::topic::Topic<CameraImage> ping_topic(participant, "CameraImagePing"); // Create the pong DataWriter with a profile from USER_QOS_PROFILES.xml dds::pub::DataWriter<CameraImage> writer( dds::pub::Publisher(participant), ping_topic); // Create the pong DataReader dds::topic::Topic<CameraImage> pong_topic(participant, "CameraImagePong"); dds::sub::DataReader<CameraImage> reader( dds::sub::Subscriber(participant), pong_topic); // Create a ReadCondition for any data on the pong reader, and attach it to // a Waitset dds::sub::cond::ReadCondition read_condition( reader, dds::sub::status::DataState::any()); dds::core::cond::WaitSet waitset; waitset += read_condition; std::unique_ptr<CameraImage> ping_sample(new CameraImage); std::cout << "Waiting for the subscriber application\n"; wait_for_reader(writer); wait_for_writer(reader); std::cout << "Discovery complete\n"; int count = 0; uint64_t total_latency = 0; uint64_t latency_interval_start_time = 0; uint64_t start_ts = participant->current_time().to_microsecs(); while (!application::shutdown_requested && count < options.sample_count) { uint64_t send_ts = participant->current_time().to_microsecs(); if ((count == options.sample_count) || (send_ts - start_ts >= options.execution_time)) { ping_sample->timestamp(0); writer.write(*ping_sample); break; } // Write the ping sample: ping_sample->timestamp(send_ts); writer.write(*ping_sample); if (latency_interval_start_time == 0) { latency_interval_start_time = send_ts; } // Wait for the pong auto conditions = waitset.wait(dds::core::Duration(10)); if (conditions.empty()) { std::cout << "Wait for pong: timeout\n"; } auto pong_samples = reader.take(); if (pong_samples.length() > 0 && pong_samples[0].info().valid()) { count++; uint64_t recv_ts = participant->current_time().to_microsecs(); uint64_t latency = recv_ts - pong_samples[0].data().timestamp(); total_latency += latency; if (recv_ts - latency_interval_start_time > 4000000) { print_latency(total_latency, count); latency_interval_start_time = 0; } } } print_latency(total_latency, count); // Wait for unmatch wait_for_reader(writer, false); std::cout << "Publisher shutting down\n"; } void publisher_copy_sample(unsigned int domain_id, unsigned int sample_count) { using namespace plain_types; std::cout << "Running publisher_copy_sample\n"; dds::domain::DomainParticipant participant(domain_id); std::unique_ptr<CameraImage> ping_sample(new CameraImage); std::unique_ptr<CameraImage> copy(new CameraImage); int count = 0; uint64_t total_latency = 0; while (!application::shutdown_requested && count < sample_count) { ping_sample->data()[45345] = count + sample_count + 100; ping_sample->timestamp(participant->current_time().to_microsecs()); *copy = *ping_sample; if (copy->data()[45345] == 3) { return; } count++; uint64_t latency = participant->current_time().to_microsecs() - ping_sample->timestamp(); total_latency += latency; if (count % 10 == 0) { std::cout << "Average end-to-end latency: " << total_latency / (count * 1) << " microseconds\n"; } } } 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 { switch (arguments.mode) { case 1: publisher_flat(arguments); break; case 2: publisher_zero_copy(arguments); break; case 3: publisher_flat_zero_copy(arguments); break; case 4: publisher_plain(arguments); break; case 5: publisher_copy_sample(arguments.domain_id, arguments.sample_count); break; } } catch (const std::exception &ex) { // This will catch DDS exceptions std::cerr << "Exception in publisher: " << ex.what() << std::endl; return EXIT_FAILURE; } dds::domain::DomainParticipant::finalize_participant_factory(); return EXIT_SUCCESS; }
cxx
rticonnextdds-examples
data/projects/rticonnextdds-examples/connext_dds/flat_data_latency/c++11/Common.hpp
/* * (c) 2019 Copyright, Real-Time Innovations, Inc. All rights reserved. * * RTI grants Licensee a license to use, modify, compile, and create derivative * works of the Software. Licensee has the right to distribute object form * only for use with RTI products. The Software is provided "as is", with no * warranty of any type, including any warranty for fitness for any purpose. * RTI is under no obligation to maintain or support the Software. RTI shall * not be liable for any incidental or consequential damages arising out of the * use or inability to use the software. */ /* Common.hpp * * Utilities used by CameraImage_publisher.cxx and CameraImage_subscriber.cxx. */ #include <dds/core/cond/GuardCondition.hpp> #include <dds/pub/DataWriter.hpp> #include <dds/pub/DataWriterListener.hpp> #include <rti/util/util.hpp> #include "application.hpp" /** * Wait for discovery */ template<typename T> void wait_for_reader(dds::pub::DataWriter<T> &writer, bool match = true) { while (((match && dds::pub::matched_subscriptions(writer).empty()) || (!match && !dds::pub::matched_subscriptions(writer).empty())) && (!application::shutdown_requested)) { rti::util::sleep(dds::core::Duration::from_millisecs(100)); } } template<typename T> void wait_for_writer(dds::sub::DataReader<T> &reader) { while (dds::sub::matched_publications(reader).empty() && !application::shutdown_requested) { rti::util::sleep(dds::core::Duration::from_millisecs(100)); } } // CameraImageType can be flat_types::CameraImage or // flat_zero_copy_types::CameraImage template<typename CameraImageType> void populate_flat_sample(CameraImageType &sample, int count) { auto image = sample.root(); image.format(common::Format::RGB); image.resolution().height(4320); image.resolution().width(7680); auto image_data = image.data(); for (int i = 0; i < 4; i++) { uint8_t image_value = (48 + count) % 124; image_data.set_element(i, image_value); } } // CameraImageType can be zero_copy_types::CameraImage or // plain_types::CameraImage template<typename CameraImageType> void populate_plain_sample(CameraImageType &sample, int count) { sample.format(common::Format::RGB); sample.resolution().height(4320); sample.resolution().width(7680); for (int i = 0; i < 4; i++) { uint8_t image_value = (48 + count) % 124; sample.data()[i] = image_value; } } template<typename CameraImageType> void display_flat_sample(const CameraImageType &sample) { auto image = sample.root(); std::cout << "\nTimestamp " << image.timestamp() << " " << image.format(); std::cout << " Data (4 Bytes) "; const uint8_t *image_data = image.data().get_elements(); for (int i = 0; i < 4; i++) { std::cout << image_data[i]; } std::cout << std::endl; } template<typename CameraImageType> void display_plain_sample(const CameraImageType &sample) { std::cout << "\nTimestamp " << sample.timestamp() << " " << sample.format(); std::cout << " Data (4 Bytes) "; for (int i = 0; i < 4; i++) { std::cout << sample.data()[i]; } std::cout << std::endl; } struct ApplicationOptions { ApplicationOptions() : domain_id(0), mode(1), sample_count(-1), // infinite execution_time(30000000), display_sample(false) { } int domain_id; int mode; int sample_count; uint64_t execution_time; bool display_sample; std::string nic; // default: empty (no nic will be explicitly picked) }; inline void configure_nic( dds::domain::qos::DomainParticipantQos &qos, const std::string &nic) { using rti::core::policy::Property; if (!nic.empty()) { qos.policy<Property>().set( { "dds.transport.UDPv4.builtin.parent.allow_interfaces", nic }); } } inline void print_latency(int total_latency, int count) { if (count > 0) { std::cout << "Average end-to-end latency: " << total_latency / (count * 2) << " microseconds\n"; } else { std::cout << "No samples received\n"; } }
hpp
rticonnextdds-examples
data/projects/rticonnextdds-examples/connext_dds/flat_data_latency/c++11/CameraImage_subscriber.cxx
/* * (c) 2019 Copyright, Real-Time Innovations, Inc. All rights reserved. * * RTI grants Licensee a license to use, modify, compile, and create derivative * works of the Software. Licensee has the right to distribute object form * only for use with RTI products. The Software is provided "as is", with no * warranty of any type, including any warranty for fitness for any purpose. * RTI is under no obligation to maintain or support the Software. RTI shall * not be liable for any incidental or consequential damages arising out of the * use or inability to use the software. */ #include <algorithm> #include <iostream> #include <memory> // for unique_ptr #include "CameraImage.hpp" #include <signal.h> #include <dds/core/ddscore.hpp> #include <dds/pub/ddspub.hpp> #include <dds/sub/ddssub.hpp> #include <rti/config/Logger.hpp> #include <rti/zcopy/pub/ZcopyDataWriter.hpp> #include <rti/zcopy/sub/ZcopyDataReader.hpp> #include "Common.hpp" void subscriber_flat(const application::ApplicationArguments &options) { using namespace flat_types; using namespace dds::core::policy; std::cout << "Running subscriber_flat\n"; auto participant_qos = dds::core::QosProvider::Default().participant_qos(); configure_nic(participant_qos, options.nic); dds::domain::DomainParticipant participant( options.domain_id, participant_qos); // Create the ping DataReader dds::topic::Topic<CameraImage> ping_topic(participant, "CameraImagePing"); dds::sub::DataReader<CameraImage> reader( dds::sub::Subscriber(participant), ping_topic); // Create the pong DataWriter dds::topic::Topic<CameraImage> pong_topic(participant, "CameraImagePong"); dds::pub::DataWriter<CameraImage> writer( dds::pub::Publisher(participant), pong_topic); // Create a ReadCondition for any data on the ping reader, and attach it to // a Waitset dds::sub::cond::ReadCondition read_condition( reader, dds::sub::status::DataState::any()); dds::core::cond::WaitSet waitset; waitset += read_condition; std::cout << "Waiting for the publisher application\n"; wait_for_reader(writer); wait_for_writer(reader); std::cout << "Discovery complete\n"; while (!application::shutdown_requested) { // Wait for a ping auto conditions = waitset.wait(dds::core::Duration(10)); if (conditions.empty()) { std::cout << "Wait for ping: timeout\n"; continue; } auto ping_samples = reader.take(); if ((ping_samples.length() > 0) && (ping_samples[0].info().valid())) { auto ping = ping_samples[0].data().root(); if (ping.timestamp() == 0) { // last sample received, break out of receive loop break; } if (options.display_sample) { display_flat_sample(ping_samples[0].data()); } auto pong_sample = writer.extensions().get_loan(); auto pong = pong_sample->root(); pong.timestamp(ping.timestamp()); writer.write(*pong_sample); } } std::cout << "Subscriber shutting down\n"; } void subscriber_zero_copy(const application::ApplicationArguments &options) { using namespace zero_copy_types; using namespace rti::core::policy; std::cout << "Running subscriber_zero_copy\n"; dds::domain::DomainParticipant participant(options.domain_id); // Create the ping DataReader dds::topic::Topic<CameraImage> ping_topic(participant, "CameraImagePing"); dds::sub::DataReader<CameraImage> reader( dds::sub::Subscriber(participant), ping_topic); // Create the pong DataWriter dds::topic::Topic<CameraImage> pong_topic(participant, "CameraImagePong"); dds::pub::DataWriter<CameraImage> writer( dds::pub::Publisher(participant), pong_topic); // Create a ReadCondition for any data on the ping reader, and attach it to // a Waitset dds::sub::cond::ReadCondition read_condition( reader, dds::sub::status::DataState::any()); dds::core::cond::WaitSet waitset; waitset += read_condition; std::cout << "Waiting for the publisher application\n"; wait_for_reader(writer); wait_for_writer(reader); std::cout << "Discovery complete\n"; while (!application::shutdown_requested) { // Wait for a ping auto conditions = waitset.wait(dds::core::Duration(10)); if (conditions.empty()) { std::cout << "Wait for ping: timeout\n"; } auto ping_samples = reader.take(); if (ping_samples.length() > 0 && ping_samples[0].info().valid()) { if (ping_samples[0].data().timestamp() == 0) { // last sample received, break out of receive loop break; } if (options.display_sample) { display_plain_sample(ping_samples[0].data()); } // Write the pong sample: CameraImage *pong_sample = writer.extensions().get_loan(); pong_sample->timestamp(ping_samples[0].data().timestamp()); if (reader->is_data_consistent(ping_samples[0])) { writer.write(*pong_sample); } } } std::cout << "Subscriber shutting down\n"; } void subscriber_flat_zero_copy(const application::ApplicationArguments &options) { using namespace flat_zero_copy_types; using namespace rti::core::policy; std::cout << "Running subscriber_flat_zero_copy\n"; auto participant_qos = dds::core::QosProvider::Default().participant_qos(); configure_nic(participant_qos, options.nic); dds::domain::DomainParticipant participant( options.domain_id, participant_qos); // Create the ping DataReader dds::topic::Topic<CameraImage> ping_topic(participant, "CameraImagePing"); dds::sub::DataReader<CameraImage> reader( dds::sub::Subscriber(participant), ping_topic); // Create the pong DataWriter dds::topic::Topic<CameraImage> pong_topic(participant, "CameraImagePong"); dds::pub::DataWriter<CameraImage> writer( dds::pub::Publisher(participant), pong_topic); // Create a ReadCondition for any data on the ping reader, and attach it to // a Waitset dds::sub::cond::ReadCondition read_condition( reader, dds::sub::status::DataState::any()); dds::core::cond::WaitSet waitset; waitset += read_condition; std::cout << "Waiting for the publisher application\n"; wait_for_reader(writer); wait_for_writer(reader); std::cout << "Discovery complete\n"; while (!application::shutdown_requested) { // Wait for a ping auto conditions = waitset.wait(dds::core::Duration(10)); if (conditions.empty()) { std::cout << "Wait for ping: timeout\n"; continue; } auto ping_samples = reader.take(); if (ping_samples.length() > 0 && ping_samples[0].info().valid()) { if (ping_samples[0].info().valid()) { auto ping = ping_samples[0].data().root(); if (ping.timestamp() == 0) { // last sample received, break out of receive loop break; } if (options.display_sample) { display_flat_sample(ping_samples[0].data()); } // Write the pong sample: CameraImage *pong_sample = writer.extensions().get_loan(); auto pong = pong_sample->root(); pong.timestamp(ping.timestamp()); if (reader->is_data_consistent(ping_samples[0])) { writer.write(*pong_sample); } } } } std::cout << "Subscriber shutting down\n"; } void subscriber_plain(const application::ApplicationArguments &options) { using namespace plain_types; using namespace dds::core::policy; std::cout << "Running subscriber_plain\n"; auto participant_qos = dds::core::QosProvider::Default().participant_qos(); configure_nic(participant_qos, options.nic); dds::domain::DomainParticipant participant( options.domain_id, participant_qos); // Create the ping DataReader dds::topic::Topic<CameraImage> ping_topic(participant, "CameraImagePing"); dds::sub::DataReader<CameraImage> reader( dds::sub::Subscriber(participant), ping_topic); // Create the pong DataWriter dds::topic::Topic<CameraImage> pong_topic(participant, "CameraImagePong"); dds::pub::DataWriter<CameraImage> writer( dds::pub::Publisher(participant), pong_topic); // Create a ReadCondition for any data on the ping reader, and attach it to // a Waitset dds::sub::cond::ReadCondition read_condition( reader, dds::sub::status::DataState::any()); dds::core::cond::WaitSet waitset; waitset += read_condition; // We create the sample in the heap because is to large to be in the stack std::unique_ptr<CameraImage> pong_sample(new CameraImage); std::cout << "Waiting for the publisher application\n"; wait_for_reader(writer); wait_for_writer(reader); std::cout << "Discovery complete\n"; int count = 0; while (!application::shutdown_requested) { // Wait for a ping auto conditions = waitset.wait(dds::core::Duration(10)); if (conditions.empty()) { std::cout << "Wait for ping: timeout\n"; } auto ping_samples = reader.take(); // Write the pong sample if (ping_samples.length() && ping_samples[0].info().valid()) { if (ping_samples[0].data().timestamp() == 0) { // last sample received, break out of receive loop break; } if (options.display_sample) { display_plain_sample(ping_samples[0].data()); } pong_sample->timestamp(ping_samples[0].data().timestamp()); writer.write(*pong_sample); count++; } } std::cout << "Subscriber shutting down\n"; } 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 { switch (arguments.mode) { case 1: subscriber_flat(arguments); break; case 2: subscriber_zero_copy(arguments); break; case 3: subscriber_flat_zero_copy(arguments); break; case 4: subscriber_plain(arguments); break; } } catch (const std::exception &ex) { // This will catch DDS exceptions std::cerr << "Exception in subscriber: " << ex.what() << std::endl; return EXIT_FAILURE; } dds::domain::DomainParticipant::finalize_participant_factory(); return EXIT_SUCCESS; }
cxx
rticonnextdds-examples
data/projects/rticonnextdds-examples/connext_dds/dynamic_data_nested_structs/c++/dynamic_data_nested_struct_example.cxx
/******************************************************************************* (c) 2005-2014 Copyright, Real-Time Innovations, Inc. All rights reserved. RTI grants Licensee a license to use, modify, compile, and create derivative works of the Software. Licensee has the right to distribute object form only for use with RTI products. The Software is provided "as is", with no warranty of any type, including any warranty for fitness for any purpose. RTI is under no obligation to maintain or support the Software. RTI shall not be liable for any incidental or consequential damages arising out of the use or inability to use the software. ******************************************************************************/ /* dynamic_data_nested_struct_example.cxx This example - creates the type code of for a nested struct (with inner and outer structs) - creates a DynamicData instance - sets the values of the inner struct - shows the differences between set_complex_member and bind_complex_member Example: To run the example application: On Unix: objs/<arch>/NestedStructExample On Windows: objs\<arch>\NestedStructExample */ /********* IDL representation for this example ************ struct InnerStruct { double x; double y; }; struct OuterStruct { InnerStruct inner; }; */ #include <iostream> #include <ndds_cpp.h> using namespace std; DDS_TypeCode *inner_struct_get_typecode(DDS_TypeCodeFactory *tcf) { static DDS_TypeCode *tc = NULL; DDS_StructMemberSeq members; DDS_ExceptionCode_t err; /* First, we create the typeCode for a struct */ tc = tcf->create_struct_tc("InnerStruct", members, err); if (err != DDS_NO_EXCEPTION_CODE) { cerr << "! Unable to create struct TC" << endl; goto fail; } /* Member 1 will be a double named x */ tc->add_member( "x", DDS_TYPECODE_MEMBER_ID_INVALID, DDS_TypeCodeFactory_get_primitive_tc(tcf, DDS_TK_DOUBLE), DDS_TYPECODE_NONKEY_REQUIRED_MEMBER, err); if (err != DDS_NO_EXCEPTION_CODE) { cerr << "! Unable to add member x" << endl; goto fail; } /* Member 2 will be a double named y */ tc->add_member( "y", DDS_TYPECODE_MEMBER_ID_INVALID, DDS_TypeCodeFactory_get_primitive_tc(tcf, DDS_TK_DOUBLE), DDS_TYPECODE_NONKEY_REQUIRED_MEMBER, err); if (err != DDS_NO_EXCEPTION_CODE) { cerr << "! Unable to add member y" << endl; goto fail; } DDS_StructMemberSeq_finalize(&members); return tc; fail: if (tc != NULL) { tcf->delete_tc(tc, err); } DDS_StructMemberSeq_finalize(&members); return NULL; } DDS_TypeCode *outer_struct_get_typecode(DDS_TypeCodeFactory *tcf) { static DDS_TypeCode *tc = NULL; DDS_TypeCode *innerTC = NULL; struct DDS_StructMemberSeq members; DDS_ExceptionCode_t err; /* First, we create the typeCode for a struct */ tc = tcf->create_struct_tc("OuterStruct", members, err); if (err != DDS_NO_EXCEPTION_CODE) { cerr << "! Unable to create struct TC" << endl; goto fail; } innerTC = inner_struct_get_typecode(tcf); if (innerTC == NULL) { cerr << "! Unable to create innerTC" << endl; goto fail; } /* Member 1 of outer struct will be a struct of type inner_struct * called inner*/ tc->add_member( "inner", DDS_TYPECODE_MEMBER_ID_INVALID, innerTC, DDS_TYPECODE_NONKEY_REQUIRED_MEMBER, err); if (err != DDS_NO_EXCEPTION_CODE) { cerr << "! Unable to add member inner struct" << endl; goto fail; } if (innerTC != NULL) { tcf->delete_tc(innerTC, err); } DDS_StructMemberSeq_finalize(&members); return tc; fail: if (tc != NULL) { tcf->delete_tc(tc, err); } DDS_StructMemberSeq_finalize(&members); if (innerTC != NULL) { tcf->delete_tc(innerTC, err); } return NULL; } int main() { DDS_TypeCodeFactory *tcf = NULL; DDS_ExceptionCode_t err; /* Getting a reference to the type code factory */ tcf = DDS_TypeCodeFactory::get_instance(); if (tcf == NULL) { cerr << "! Unable to get type code factory singleton" << endl; return -1; } /* Creating the typeCode of the inner_struct */ struct DDS_TypeCode *inner_tc = inner_struct_get_typecode(tcf); if (inner_tc == NULL) { cerr << "! Unable to create inner typecode " << endl; return -1; } /* Creating the typeCode of the outer_struct that contains an inner_struct */ struct DDS_TypeCode *outer_tc = outer_struct_get_typecode(tcf); if (inner_tc == NULL) { cerr << "! Unable to create outer typecode " << endl; tcf->delete_tc(outer_tc, err); return -1; } DDS_ReturnCode_t retcode; int ret = -1; /* Now, we create a dynamicData instance for each type */ DDS_DynamicData outer_data(outer_tc, DDS_DYNAMIC_DATA_PROPERTY_DEFAULT); DDS_DynamicData inner_data(inner_tc, DDS_DYNAMIC_DATA_PROPERTY_DEFAULT); DDS_DynamicData bounded_data(NULL, DDS_DYNAMIC_DATA_PROPERTY_DEFAULT); cout << " Connext Dynamic Data Nested Struct Example" << endl << "--------------------------------------------" << endl; cout << " Data Types" << endl << "------------------" << endl; inner_tc->print_IDL(0, err); outer_tc->print_IDL(0, err); /* Setting the inner data */ retcode = inner_data.set_double( "x", DDS_DYNAMIC_DATA_MEMBER_ID_UNSPECIFIED, 3.14159); if (retcode != DDS_RETCODE_OK) { cerr << "! Unable to set value 'x' in the inner struct" << endl; goto fail; } retcode = inner_data.set_double( "y", DDS_DYNAMIC_DATA_MEMBER_ID_UNSPECIFIED, 2.71828); if (retcode != DDS_RETCODE_OK) { cerr << "! Unable to set value 'y' in the inner struct" << endl; goto fail; } cout << endl << endl << " get/set_complex_member API" << endl << "------------------" << endl; /* Using set_complex_member, we copy inner_data values in inner_struct of * outer_data */ cout << "Setting the initial values of struct with set_complex_member()" << endl; retcode = outer_data.set_complex_member( "inner", DDS_DYNAMIC_DATA_MEMBER_ID_UNSPECIFIED, inner_data); if (retcode != DDS_RETCODE_OK) { cerr << "! Unable to set complex struct value " << "(member inner in the outer struct)" << endl; goto fail; } outer_data.print(stdout, 1); retcode = inner_data.clear_all_members(); if (retcode != DDS_RETCODE_OK) { cerr << "! Unable to clear all member in the inner struct" << endl; goto fail; } cout << endl << " + get_complex_member() called" << endl; retcode = outer_data.get_complex_member( inner_data, "inner", DDS_DYNAMIC_DATA_MEMBER_ID_UNSPECIFIED); if (retcode != DDS_RETCODE_OK) { cerr << "! Unable to get complex struct value" << "(member inner in the outer struct)" << endl; goto fail; } cout << endl << " + inner_data value" << endl; inner_data.print(stdout, 1); /* get_complex_member made a copy of the inner_struct. If we modify * inner_data values, outer_data inner_struct WILL NOT be modified. */ cout << endl << " + setting new values to inner_data" << endl; retcode = inner_data.set_double( "x", DDS_DYNAMIC_DATA_MEMBER_ID_UNSPECIFIED, 1.00000); if (retcode != DDS_RETCODE_OK) { cerr << "! Unable to set value 'x' in the inner struct" << endl; goto fail; } retcode = inner_data.set_double( "y", DDS_DYNAMIC_DATA_MEMBER_ID_UNSPECIFIED, 0.00001); if (retcode != DDS_RETCODE_OK) { cerr << "! Unable to set value 'y' in the inner struct" << endl; goto fail; } /* Current value of outer_data * outer: * inner: * x: 3.141590 * y: 2.718280 * inner_data: * x: 1.000000 * y: 0.000010 */ cout << endl << " + current outer_data value " << endl; outer_data.print(stdout, 1); /* Bind/Unbind member API */ cout << endl << endl << "bind/unbind API" << endl << "------------------" << endl; /* Using bind_complex_member, we do not copy inner_struct, but bind it. * So, if we modify bounded_data, the inner member inside outer_data WILL * also be modified */ cout << endl << " + bind complex member called" << endl; retcode = outer_data.bind_complex_member( bounded_data, "inner", DDS_DYNAMIC_DATA_MEMBER_ID_UNSPECIFIED); if (retcode != DDS_RETCODE_OK) { cerr << "! Unable to bind the structs" << endl; goto fail; } bounded_data.print(stdout, 1); cout << endl << " + setting new values to bounded_data" << endl; retcode = bounded_data.set_double( "x", DDS_DYNAMIC_DATA_MEMBER_ID_UNSPECIFIED, 1.00000); if (retcode != DDS_RETCODE_OK) { cerr << "! Unable to set value to 'x' with the bounded data" << endl; goto fail; } retcode = bounded_data.set_double( "y", DDS_DYNAMIC_DATA_MEMBER_ID_UNSPECIFIED, 0.00001); if (retcode != DDS_RETCODE_OK) { cerr << "! Unable to set value to 'y' in the bounded data" << endl; goto fail; } /* Current value of outer data * outer: * inner: * x: 1.000000 * y: 0.000010 */ bounded_data.print(stdout, 1); retcode = outer_data.unbind_complex_member(bounded_data); if (retcode != DDS_RETCODE_OK) { cerr << "! Unable to unbind the data" << endl; goto fail; } cout << endl << " + current outer_data value " << endl; outer_data.print(stdout, 1); ret = 1; fail: if (inner_tc != NULL) { tcf->delete_tc(inner_tc, err); } if (outer_tc != NULL) { tcf->delete_tc(outer_tc, err); } return ret; }
cxx
rticonnextdds-examples
data/projects/rticonnextdds-examples/connext_dds/dynamic_data_nested_structs/c++98/dynamic_data_nested_struct_example.cxx
/******************************************************************************* (c) 2005-2014 Copyright, Real-Time Innovations, Inc. All rights reserved. RTI grants Licensee a license to use, modify, compile, and create derivative works of the Software. Licensee has the right to distribute object form only for use with RTI products. The Software is provided "as is", with no warranty of any type, including any warranty for fitness for any purpose. RTI is under no obligation to maintain or support the Software. RTI shall not be liable for any incidental or consequential damages arising out of the use or inability to use the software. ******************************************************************************/ /* dynamic_data_nested_struct_example.cxx This example - creates the type code of for a nested struct (with inner and outer structs) - creates a DynamicData instance - sets the values of the inner struct - shows the differences between set_complex_member and bind_complex_member Example: To run the example application: On Unix: objs/<arch>/NestedStructExample On Windows: objs\<arch>\NestedStructExample */ /********* IDL representation for this example ************ struct InnerStruct { double x; double y; }; struct OuterStruct { InnerStruct inner; }; */ #include <iostream> #include <ndds_cpp.h> using namespace std; DDS_TypeCode *inner_struct_get_typecode(DDS_TypeCodeFactory *tcf) { static DDS_TypeCode *tc = NULL; DDS_StructMemberSeq members; DDS_ExceptionCode_t err; /* First, we create the typeCode for a struct */ tc = tcf->create_struct_tc("InnerStruct", members, err); if (err != DDS_NO_EXCEPTION_CODE) { cerr << "! Unable to create struct TC" << endl; goto fail; } /* Member 1 will be a double named x */ tc->add_member( "x", DDS_TYPECODE_MEMBER_ID_INVALID, DDS_TypeCodeFactory_get_primitive_tc(tcf, DDS_TK_DOUBLE), DDS_TYPECODE_NONKEY_REQUIRED_MEMBER, err); if (err != DDS_NO_EXCEPTION_CODE) { cerr << "! Unable to add member x" << endl; goto fail; } /* Member 2 will be a double named y */ tc->add_member( "y", DDS_TYPECODE_MEMBER_ID_INVALID, DDS_TypeCodeFactory_get_primitive_tc(tcf, DDS_TK_DOUBLE), DDS_TYPECODE_NONKEY_REQUIRED_MEMBER, err); if (err != DDS_NO_EXCEPTION_CODE) { cerr << "! Unable to add member y" << endl; goto fail; } DDS_StructMemberSeq_finalize(&members); return tc; fail: if (tc != NULL) { tcf->delete_tc(tc, err); } DDS_StructMemberSeq_finalize(&members); return NULL; } DDS_TypeCode *outer_struct_get_typecode(DDS_TypeCodeFactory *tcf) { static DDS_TypeCode *tc = NULL; DDS_TypeCode *innerTC = NULL; struct DDS_StructMemberSeq members; DDS_ExceptionCode_t err; /* First, we create the typeCode for a struct */ tc = tcf->create_struct_tc("OuterStruct", members, err); if (err != DDS_NO_EXCEPTION_CODE) { cerr << "! Unable to create struct TC" << endl; goto fail; } innerTC = inner_struct_get_typecode(tcf); if (innerTC == NULL) { cerr << "! Unable to create innerTC" << endl; goto fail; } /* Member 1 of outer struct will be a struct of type inner_struct * called inner*/ tc->add_member( "inner", DDS_TYPECODE_MEMBER_ID_INVALID, innerTC, DDS_TYPECODE_NONKEY_REQUIRED_MEMBER, err); if (err != DDS_NO_EXCEPTION_CODE) { cerr << "! Unable to add member inner struct" << endl; goto fail; } if (innerTC != NULL) { tcf->delete_tc(innerTC, err); } DDS_StructMemberSeq_finalize(&members); return tc; fail: if (tc != NULL) { tcf->delete_tc(tc, err); } DDS_StructMemberSeq_finalize(&members); if (innerTC != NULL) { tcf->delete_tc(innerTC, err); } return NULL; } int main() { DDS_TypeCodeFactory *tcf = NULL; DDS_ExceptionCode_t err; /* Getting a reference to the type code factory */ tcf = DDS_TypeCodeFactory::get_instance(); if (tcf == NULL) { cerr << "! Unable to get type code factory singleton" << endl; return -1; } /* Creating the typeCode of the inner_struct */ struct DDS_TypeCode *inner_tc = inner_struct_get_typecode(tcf); if (inner_tc == NULL) { cerr << "! Unable to create inner typecode " << endl; return -1; } /* Creating the typeCode of the outer_struct that contains an inner_struct */ struct DDS_TypeCode *outer_tc = outer_struct_get_typecode(tcf); if (inner_tc == NULL) { cerr << "! Unable to create outer typecode " << endl; tcf->delete_tc(outer_tc, err); return -1; } DDS_ReturnCode_t retcode; int ret = -1; /* Now, we create a dynamicData instance for each type */ DDS_DynamicData outer_data(outer_tc, DDS_DYNAMIC_DATA_PROPERTY_DEFAULT); DDS_DynamicData inner_data(inner_tc, DDS_DYNAMIC_DATA_PROPERTY_DEFAULT); DDS_DynamicData bounded_data(NULL, DDS_DYNAMIC_DATA_PROPERTY_DEFAULT); cout << " Connext Dynamic Data Nested Struct Example" << endl << "--------------------------------------------" << endl; cout << " Data Types" << endl << "------------------" << endl; inner_tc->print_IDL(0, err); outer_tc->print_IDL(0, err); /* Setting the inner data */ retcode = inner_data.set_double( "x", DDS_DYNAMIC_DATA_MEMBER_ID_UNSPECIFIED, 3.14159); if (retcode != DDS_RETCODE_OK) { cerr << "! Unable to set value 'x' in the inner struct" << endl; goto fail; } retcode = inner_data.set_double( "y", DDS_DYNAMIC_DATA_MEMBER_ID_UNSPECIFIED, 2.71828); if (retcode != DDS_RETCODE_OK) { cerr << "! Unable to set value 'y' in the inner struct" << endl; goto fail; } cout << endl << endl << " get/set_complex_member API" << endl << "------------------" << endl; /* Using set_complex_member, we copy inner_data values in inner_struct of * outer_data */ cout << "Setting the initial values of struct with set_complex_member()" << endl; retcode = outer_data.set_complex_member( "inner", DDS_DYNAMIC_DATA_MEMBER_ID_UNSPECIFIED, inner_data); if (retcode != DDS_RETCODE_OK) { cerr << "! Unable to set complex struct value " << "(member inner in the outer struct)" << endl; goto fail; } outer_data.print(stdout, 1); retcode = inner_data.clear_all_members(); if (retcode != DDS_RETCODE_OK) { cerr << "! Unable to clear all member in the inner struct" << endl; goto fail; } cout << endl << " + get_complex_member() called" << endl; retcode = outer_data.get_complex_member( inner_data, "inner", DDS_DYNAMIC_DATA_MEMBER_ID_UNSPECIFIED); if (retcode != DDS_RETCODE_OK) { cerr << "! Unable to get complex struct value" << "(member inner in the outer struct)" << endl; goto fail; } cout << endl << " + inner_data value" << endl; inner_data.print(stdout, 1); /* get_complex_member made a copy of the inner_struct. If we modify * inner_data values, outer_data inner_struct WILL NOT be modified. */ cout << endl << " + setting new values to inner_data" << endl; retcode = inner_data.set_double( "x", DDS_DYNAMIC_DATA_MEMBER_ID_UNSPECIFIED, 1.00000); if (retcode != DDS_RETCODE_OK) { cerr << "! Unable to set value 'x' in the inner struct" << endl; goto fail; } retcode = inner_data.set_double( "y", DDS_DYNAMIC_DATA_MEMBER_ID_UNSPECIFIED, 0.00001); if (retcode != DDS_RETCODE_OK) { cerr << "! Unable to set value 'y' in the inner struct" << endl; goto fail; } /* Current value of outer_data * outer: * inner: * x: 3.141590 * y: 2.718280 * inner_data: * x: 1.000000 * y: 0.000010 */ cout << endl << " + current outer_data value " << endl; outer_data.print(stdout, 1); /* Bind/Unbind member API */ cout << endl << endl << "bind/unbind API" << endl << "------------------" << endl; /* Using bind_complex_member, we do not copy inner_struct, but bind it. * So, if we modify bounded_data, the inner member inside outer_data WILL * also be modified */ cout << endl << " + bind complex member called" << endl; retcode = outer_data.bind_complex_member( bounded_data, "inner", DDS_DYNAMIC_DATA_MEMBER_ID_UNSPECIFIED); if (retcode != DDS_RETCODE_OK) { cerr << "! Unable to bind the structs" << endl; goto fail; } bounded_data.print(stdout, 1); cout << endl << " + setting new values to bounded_data" << endl; retcode = bounded_data.set_double( "x", DDS_DYNAMIC_DATA_MEMBER_ID_UNSPECIFIED, 1.00000); if (retcode != DDS_RETCODE_OK) { cerr << "! Unable to set value to 'x' with the bounded data" << endl; goto fail; } retcode = bounded_data.set_double( "y", DDS_DYNAMIC_DATA_MEMBER_ID_UNSPECIFIED, 0.00001); if (retcode != DDS_RETCODE_OK) { cerr << "! Unable to set value to 'y' in the bounded data" << endl; goto fail; } /* Current value of outer data * outer: * inner: * x: 1.000000 * y: 0.000010 */ bounded_data.print(stdout, 1); retcode = outer_data.unbind_complex_member(bounded_data); if (retcode != DDS_RETCODE_OK) { cerr << "! Unable to unbind the data" << endl; goto fail; } cout << endl << " + current outer_data value " << endl; outer_data.print(stdout, 1); ret = 1; fail: if (inner_tc != NULL) { tcf->delete_tc(inner_tc, err); } if (outer_tc != NULL) { tcf->delete_tc(outer_tc, err); } return ret; }
cxx
rticonnextdds-examples
data/projects/rticonnextdds-examples/connext_dds/dynamic_data_nested_structs/c/dynamic_data_nested_struct_example.c
/******************************************************************************* (c) 2005-2014 Copyright, Real-Time Innovations, Inc. All rights reserved. RTI grants Licensee a license to use, modify, compile, and create derivative works of the Software. Licensee has the right to distribute object form only for use with RTI products. The Software is provided "as is", with no warranty of any type, including any warranty for fitness for any purpose. RTI is under no obligation to maintain or support the Software. RTI shall not be liable for any incidental or consequential damages arising out of the use or inability to use the software. ******************************************************************************/ /* dynamic_data_nested_struct_example.c This example - creates the type code of for a nested struct (with inner and outer structs) - creates a DynamicData instance - sets the values of the inner struct - shows the differences between set_complex_member and bind_complex_member Example: To run the example application: On Unix: objs/<arch>/UnionExample On Windows: objs\<arch>\UnionExample */ /********* IDL representation for this example ************ struct InnerStruct { double x; double y; }; struct OuterStruct { InnerStruct inner; }; */ #include <ndds_c.h> DDS_TypeCode *inner_struct_get_typecode(struct DDS_TypeCodeFactory *tcf) { static DDS_TypeCode *tc = NULL; struct DDS_StructMemberSeq members = DDS_SEQUENCE_INITIALIZER; DDS_ExceptionCode_t ex; /* First, we create the typeCode for a struct */ tc = DDS_TypeCodeFactory_create_struct_tc( tcf, "InnerStruct", &members, &ex); if (ex != DDS_NO_EXCEPTION_CODE) { fprintf(stderr, "! Unable to create struct TC\n"); goto fail; } /* Member 1 will be a double named x */ DDS_TypeCode_add_member( tc, "x", DDS_TYPECODE_MEMBER_ID_INVALID, DDS_TypeCodeFactory_get_primitive_tc(tcf, DDS_TK_DOUBLE), DDS_TYPECODE_NONKEY_REQUIRED_MEMBER, &ex); if (ex != DDS_NO_EXCEPTION_CODE) { fprintf(stderr, "! Unable to add member x\n"); goto fail; } /* Member 2 will be a double named y */ DDS_TypeCode_add_member( tc, "y", DDS_TYPECODE_MEMBER_ID_INVALID, DDS_TypeCodeFactory_get_primitive_tc(tcf, DDS_TK_DOUBLE), DDS_TYPECODE_NONKEY_REQUIRED_MEMBER, &ex); if (ex != DDS_NO_EXCEPTION_CODE) { fprintf(stderr, "! Unable to add member y\n"); goto fail; } DDS_StructMemberSeq_finalize(&members); return tc; fail: if (tc != NULL) { DDS_TypeCodeFactory_delete_tc(tcf, tc, &ex); } DDS_StructMemberSeq_finalize(&members); return NULL; } DDS_TypeCode *outer_struct_get_typecode(struct DDS_TypeCodeFactory *tcf) { static DDS_TypeCode *tc = NULL; DDS_TypeCode *innerTC = NULL; struct DDS_StructMemberSeq members = DDS_SEQUENCE_INITIALIZER; DDS_ExceptionCode_t ex; /* First, we create the typeCode for a struct */ tc = DDS_TypeCodeFactory_create_struct_tc( tcf, "OuterStruct", &members, &ex); if (ex != DDS_NO_EXCEPTION_CODE) { fprintf(stderr, "! Unable to create struct TC\n"); goto fail; } innerTC = inner_struct_get_typecode(tcf); if (innerTC == NULL) { fprintf(stderr, "! Unable to create struct TC\n"); goto fail; } /* Member 1 of outer struct will be a struct of type inner_struct * called inner*/ DDS_TypeCode_add_member( tc, "inner", DDS_TYPECODE_MEMBER_ID_INVALID, innerTC, DDS_TYPECODE_NONKEY_REQUIRED_MEMBER, &ex); if (ex != DDS_NO_EXCEPTION_CODE) { fprintf(stderr, "! Unable to add member x\n"); goto fail; } if (innerTC != NULL) { DDS_TypeCodeFactory_delete_tc(tcf, innerTC, NULL); } DDS_StructMemberSeq_finalize(&members); return tc; fail: if (tc != NULL) { DDS_TypeCodeFactory_delete_tc(tcf, tc, &ex); } if (innerTC != NULL) { DDS_TypeCodeFactory_delete_tc(tcf, innerTC, NULL); } DDS_StructMemberSeq_finalize(&members); return NULL; } int main() { struct DDS_TypeCode *inner_tc = NULL; struct DDS_TypeCode *outer_tc = NULL; struct DDS_TypeCodeFactory *factory = NULL; DDS_ExceptionCode_t err; DDS_ReturnCode_t retcode; int ret = -1; DDS_DynamicData *outer_data = NULL; DDS_DynamicData *inner_data = NULL; DDS_DynamicData *bounded_data = NULL; /* Getting a reference to the type code factory */ factory = DDS_TypeCodeFactory_get_instance(); if (factory == NULL) { fprintf(stderr, "! Unable to get type code factory singleton\n"); goto fail; } /* Creating the typeCode of the inner_struct */ inner_tc = inner_struct_get_typecode(factory); if (inner_tc == NULL) { fprintf(stderr, "! Unable to create typeCode\n"); goto fail; } /* Creating the typeCode of the outer_struct that contains an inner_struct */ outer_tc = outer_struct_get_typecode(factory); if (inner_tc == NULL) { fprintf(stderr, "! Unable to create typeCode\n"); goto fail; } printf(" Connext Dynamic Data Nested Struct Example \n" "--------------------------------------------\n"); printf(" Data Types\n" "------------------\n"); DDS_TypeCode_print_IDL(inner_tc, 0, &err); DDS_TypeCode_print_IDL(outer_tc, 0, &err); /* Now, we create a dynamicData instance for each type */ outer_data = DDS_DynamicData_new(outer_tc, &DDS_DYNAMIC_DATA_PROPERTY_DEFAULT); if (outer_data == NULL) { fprintf(stderr, "! Unable to create outer dynamicData\n"); goto fail; } inner_data = DDS_DynamicData_new(inner_tc, &DDS_DYNAMIC_DATA_PROPERTY_DEFAULT); if (outer_data == NULL) { fprintf(stderr, "! Unable to create inner dynamicData\n"); goto fail; } /* Setting the inner data */ retcode = DDS_DynamicData_set_double( inner_data, "x", DDS_DYNAMIC_DATA_MEMBER_ID_UNSPECIFIED, 3.14159); if (retcode != DDS_RETCODE_OK) { fprintf(stderr, "! Unable to set value 'x' in the inner struct \n"); goto fail; } retcode = DDS_DynamicData_set_double( inner_data, "y", DDS_DYNAMIC_DATA_MEMBER_ID_UNSPECIFIED, 2.71828); if (retcode != DDS_RETCODE_OK) { fprintf(stderr, "! Unable to set value 'y' in the inner struct\n"); goto fail; } printf("\n\n get/set_complex_member API\n" "----------------------------\n"); /* Using set_complex_member, we copy inner_data values in inner_struct of * outer_data */ printf("Setting initial values of outer_data with " "set_complex_member()\n"); retcode = DDS_DynamicData_set_complex_member( outer_data, "inner", DDS_DYNAMIC_DATA_MEMBER_ID_UNSPECIFIED, inner_data); if (retcode != DDS_RETCODE_OK) { fprintf(stderr, "! Unable to set complex struct value " "(member inner in the outer struct)\n"); goto fail; } DDS_DynamicData_print(outer_data, stdout, 1); retcode = DDS_DynamicData_clear_all_members(inner_data); if (retcode != DDS_RETCODE_OK) { fprintf(stderr, "! Unable to clear all member in the inner data\n"); goto fail; } printf("\n + get_complex_member() called\n"); retcode = DDS_DynamicData_get_complex_member( outer_data, inner_data, "inner", DDS_DYNAMIC_DATA_MEMBER_ID_UNSPECIFIED); if (retcode != DDS_RETCODE_OK) { fprintf(stderr, "! Unable to get complex struct value " "(member inner in the outer struct)\n"); goto fail; } printf("\n + inner_data value\n"); DDS_DynamicData_print(inner_data, stdout, 1); /* get_complex_member made a copy of the inner_struct. If we modify * inner_data values, outer_data inner_struct WILL NOT be modified. */ printf("\n + setting new values to inner_data\n"); retcode = DDS_DynamicData_set_double( inner_data, "x", DDS_DYNAMIC_DATA_MEMBER_ID_UNSPECIFIED, 1.00000); if (retcode != DDS_RETCODE_OK) { fprintf(stderr, "! Unable to set value 'x' in the inner struct \n"); goto fail; } retcode = DDS_DynamicData_set_double( inner_data, "y", DDS_DYNAMIC_DATA_MEMBER_ID_UNSPECIFIED, 0.00001); if (retcode != DDS_RETCODE_OK) { fprintf(stderr, "! Unable to set value 'y' in the inner struct \n"); goto fail; } DDS_DynamicData_print(inner_data, stdout, 1); /* Current value of outer_data * outer_data: * inner: * x: 3.141590 * y: 2.718280 * * inner_data: * x: 1.000000 * y: 0.000010 */ printf("\n + current outer_data value \n"); DDS_DynamicData_print(outer_data, stdout, 1); /* Bind/Unbind member API */ printf("\n\n bind/unbind API\n" "------------------\n"); printf("Creating a new dynamic data called bounded_data\n"); bounded_data = DDS_DynamicData_new(NULL, &DDS_DYNAMIC_DATA_PROPERTY_DEFAULT); if (bounded_data == NULL) { fprintf(stderr, "! Unable to create new dynamic data\n"); goto fail; } printf("\n + binding bounded_data to outer_data's inner_struct\n"); /* Using bind_complex_member, we do not copy inner_struct, but bind it. * So, if we modify bounded_data, the inner member inside outer_data WILL * also be modified */ retcode = DDS_DynamicData_bind_complex_member( outer_data, bounded_data, "inner", DDS_DYNAMIC_DATA_MEMBER_ID_UNSPECIFIED); if (retcode != DDS_RETCODE_OK) { fprintf(stderr, "! Unable to bind the structs\n"); goto fail; } DDS_DynamicData_print(bounded_data, stdout, 1); printf("\n + setting new values to bounded_data\n"); retcode = DDS_DynamicData_set_double( bounded_data, "x", DDS_DYNAMIC_DATA_MEMBER_ID_UNSPECIFIED, 1.00000); if (retcode != DDS_RETCODE_OK) { fprintf(stderr, "! Unable to set value to 'x' with the bounded data\n"); goto fail; } retcode = DDS_DynamicData_set_double( bounded_data, "y", DDS_DYNAMIC_DATA_MEMBER_ID_UNSPECIFIED, 0.00001); if (retcode != DDS_RETCODE_OK) { fprintf(stderr, "! Unable to set value to 'x' with the bounded data\n"); goto fail; } /* Current value of outer data * outer: * inner: * x: 1.000000 * y: 0.000010 */ DDS_DynamicData_print(bounded_data, stdout, 1); retcode = DDS_DynamicData_unbind_complex_member(outer_data, bounded_data); if (retcode != DDS_RETCODE_OK) { fprintf(stderr, "! Unable to unbind the data\n"); goto fail; } printf("\n + current outer_data value \n"); DDS_DynamicData_print(outer_data, stdout, 1); ret = 1; fail: if (inner_tc != NULL) { DDS_TypeCodeFactory_delete_tc(factory, inner_tc, NULL); } if (outer_tc != NULL) { DDS_TypeCodeFactory_delete_tc(factory, outer_tc, NULL); } if (inner_data != NULL) { DDS_DynamicData_delete(inner_data); } if (outer_data != NULL) { DDS_DynamicData_delete(outer_data); } if (bounded_data != NULL) { DDS_DynamicData_delete(bounded_data); } return ret; }
c
rticonnextdds-examples
data/projects/rticonnextdds-examples/connext_dds/dynamic_data_nested_structs/c++03/dynamic_data_nested_struct_example.cxx
/******************************************************************************* (c) 2005-2015 Copyright, Real-Time Innovations, Inc. All rights reserved. RTI grants Licensee a license to use, modify, compile, and create derivative works of the Software. Licensee has the right to distribute object form only for use with RTI products. The Software is provided "as is", with no warranty of any type, including any warranty for fitness for any purpose. RTI is under no obligation to maintain or support the Software. RTI shall not be liable for any incidental or consequential damages arising out of the use or inability to use the software. ******************************************************************************/ #include <dds/dds.hpp> #include <iostream> using namespace dds::core::xtypes; using namespace rti::core::xtypes; DynamicType create_typecode_inner_struct() { // First create the type code for a struct StructType inner_struct("InnerStruct"); // Member 1 will be a double named x inner_struct.add_member(Member("x", primitive_type<double>())); // Member 2 will be a double named y inner_struct.add_member(Member("y", primitive_type<double>())); return inner_struct; } DynamicType create_typecode_outer_struct() { // First create the type code for a struct StructType outer_struct("OuterStruct"); // Member 1 of outer struct will be a struct of type InnerStruct outer_struct.add_member(Member("inner", create_typecode_inner_struct())); return outer_struct; } int main() { // Create the type code of the InnerStruct and OuterStruct DynamicType inner_type = create_typecode_inner_struct(); DynamicType outer_type = create_typecode_outer_struct(); // Create a DynamicData instance for each type DynamicData outer_data(outer_type); DynamicData inner_data(inner_type); std::cout << " Connext Dynamic Data Nested Struct Example " << std::endl << "--------------------------------------------" << std::endl << " Data Type " << std::endl << "-----------" << std::endl; print_idl(inner_type); print_idl(outer_type); std::cout << std::endl; // Setting the inner data inner_data.value("x", 3.14159); inner_data.value("y", 2.71828); // Copy inner_data values in inner_struct of outer_data std::cout << " Setting the initial values of struct " << std::endl << "--------------------------------------" << std::endl; outer_data.value("inner", inner_data); std::cout << outer_data; // Clear inner_data members to copy data from outer_data inner_data.clear_all_members(); inner_data = outer_data.value<DynamicData>("inner"); std::cout << std::endl << " + copied struct from outer_data" << std::endl << " + inner_data value" << std::endl; std::cout << inner_data; // inner_data is a copy of the values. If we modify it, outer_data inner // field WILL NOT be modified. std::cout << std::endl << " + setting new values to inner_data" << std::endl; inner_data.value("x", 1.00000); inner_data.value("y", 0.00001); std::cout << inner_data << std::endl << " + current outer_data value " << std::endl << outer_data << std::endl << std::endl; // Using loan_value, we do not copy inner, but bind it. // So, if we modify loaned_inner, the inner member inside outer_data WILL // also be modified. std::cout << " loan/unloan API" << std::endl << "-----------------" << std::endl << " + loan member called" << std::endl; LoanedDynamicData loaned_inner = outer_data.loan_value("inner"); std::cout << loaned_inner.get() << std::endl << " + setting new values to loaned_data" << std::endl; loaned_inner.get().value("x", 1.00000); loaned_inner.get().value("y", 0.00001); std::cout << loaned_inner.get() << std::endl << " + current outer_data value" << std::endl; std::cout << outer_data; // The destructor will unloan the member return 0; }
cxx
rticonnextdds-examples
data/projects/rticonnextdds-examples/connext_dds/dynamic_data_nested_structs/c++11/dynamic_data_nested_struct_example.cxx
/******************************************************************************* (c) 2005-2015 Copyright, Real-Time Innovations, Inc. All rights reserved. RTI grants Licensee a license to use, modify, compile, and create derivative works of the Software. Licensee has the right to distribute object form only for use with RTI products. The Software is provided "as is", with no warranty of any type, including any warranty for fitness for any purpose. RTI is under no obligation to maintain or support the Software. RTI shall not be liable for any incidental or consequential damages arising out of the use or inability to use the software. ******************************************************************************/ #include <dds/dds.hpp> #include <iostream> using namespace dds::core::xtypes; using namespace rti::core::xtypes; DynamicType create_typecode_inner_struct() { // First create the type code for a struct StructType inner_struct("InnerStruct"); // Member 1 will be a double named x inner_struct.add_member(Member("x", primitive_type<double>())); // Member 2 will be a double named y inner_struct.add_member(Member("y", primitive_type<double>())); return inner_struct; } DynamicType create_typecode_outer_struct() { // First create the type code for a struct StructType outer_struct("OuterStruct"); // Member 1 of outer struct will be a struct of type InnerStruct outer_struct.add_member(Member("inner", create_typecode_inner_struct())); return outer_struct; } int main() { // Create the type code of the InnerStruct and OuterStruct DynamicType inner_type = create_typecode_inner_struct(); DynamicType outer_type = create_typecode_outer_struct(); // Create a DynamicData instance for each type DynamicData outer_data(outer_type); DynamicData inner_data(inner_type); std::cout << " Connext Dynamic Data Nested Struct Example " << std::endl << "--------------------------------------------" << std::endl << " Data Type " << std::endl << "-----------" << std::endl; print_idl(inner_type); print_idl(outer_type); std::cout << std::endl; // Setting the inner data inner_data.value("x", 3.14159); inner_data.value("y", 2.71828); // Copy inner_data values in inner_struct of outer_data std::cout << " Setting the initial values of struct " << std::endl << "--------------------------------------" << std::endl; outer_data.value("inner", inner_data); std::cout << outer_data; // Clear inner_data members to copy data from outer_data inner_data.clear_all_members(); inner_data = outer_data.value<DynamicData>("inner"); std::cout << std::endl << " + copied struct from outer_data" << std::endl << " + inner_data value" << std::endl; std::cout << inner_data; // inner_data is a copy of the values. If we modify it, outer_data inner // field WILL NOT be modified. std::cout << std::endl << " + setting new values to inner_data" << std::endl; inner_data.value("x", 1.00000); inner_data.value("y", 0.00001); std::cout << inner_data << std::endl << " + current outer_data value " << std::endl << outer_data << std::endl << std::endl; // Using loan_value, we do not copy inner, but bind it. // So, if we modify loaned_inner, the inner member inside outer_data WILL // also be modified. std::cout << " loan/unloan API" << std::endl << "-----------------" << std::endl << " + loan member called" << std::endl; LoanedDynamicData loaned_inner = outer_data.loan_value("inner"); std::cout << loaned_inner.get() << std::endl << " + setting new values to loaned_data" << std::endl; loaned_inner.get().value("x", 1.00000); loaned_inner.get().value("y", 0.00001); std::cout << loaned_inner.get() << std::endl << " + current outer_data value" << std::endl; std::cout << outer_data; // The destructor will unloan the member return 0; }
cxx
rticonnextdds-examples
data/projects/rticonnextdds-examples/connext_dds/listeners/c++/listeners_publisher.cxx
/******************************************************************************* (c) 2005-2014 Copyright, Real-Time Innovations, Inc. All rights reserved. RTI grants Licensee a license to use, modify, compile, and create derivative works of the Software. Licensee has the right to distribute object form only for use with RTI products. The Software is provided "as is", with no warranty of any type, including any warranty for fitness for any purpose. RTI is under no obligation to maintain or support the Software. RTI shall not be liable for any incidental or consequential damages arising out of the use or inability to use the software. ******************************************************************************/ /* listeners_publisher.cxx A publication of data of type listeners This file is derived from code automatically generated by the rtiddsgen command: rtiddsgen -language C++ -example <arch> listeners.idl Example publication of type listeners automatically generated by 'rtiddsgen'. To test them follow these steps: (1) Compile this file and the example subscription. (2) Start the subscription with the command objs/<arch>/listeners_subscriber <domain_id> <sample_count> (3) Start the publication with the command objs/<arch>/listeners_publisher <domain_id> <sample_count> (4) [Optional] Specify the list of discovery initial peers and multicast receive addresses via an environment variable or a file (in the current working directory) called NDDS_DISCOVERY_PEERS. You can run any number of publishers and subscribers programs, and can add and remove them dynamically from the domain. Example: To run the example application on domain <domain_id>: On Unix: objs/<arch>/listeners_publisher <domain_id> o objs/<arch>/listeners_subscriber <domain_id> On Windows: objs\<arch>\listeners_publisher <domain_id> objs\<arch>\listeners_subscriber <domain_id> modification history ------------ ------- */ #include <stdio.h> #include <stdlib.h> #ifdef RTI_VX653 #include <vThreadsData.h> #endif #include "listeners.h" #include "listenersSupport.h" #include "ndds/ndds_cpp.h" class DataWriterListener : public DDSDataWriterListener { public: virtual void on_offered_deadline_missed( DDSDataWriter * /*writer*/, const DDS_OfferedDeadlineMissedStatus & /*status*/) { printf("DataWriterListener: on_offered_deadline_missed()\n"); } virtual void on_liveliness_lost( DDSDataWriter * /*writer*/, const DDS_LivelinessLostStatus & /*status*/) { printf("DataWriterListener: on_liveliness_lost()\n"); } virtual void on_offered_incompatible_qos( DDSDataWriter * /*writer*/, const DDS_OfferedIncompatibleQosStatus & /*status*/) { printf("DataWriterListener: on_offered_incompatible_qos()\n"); } virtual void on_publication_matched( DDSDataWriter *writer, const DDS_PublicationMatchedStatus &status) { printf("DataWriterListener: on_publication_matched()\n"); if (status.current_count_change < 0) { printf("lost a subscription\n"); } else { printf("found a subscription\n"); } } virtual void on_reliable_writer_cache_changed( DDSDataWriter *writer, const DDS_ReliableWriterCacheChangedStatus &status) { printf("DataWriterListener: on_reliable_writer_cache_changed()\n"); } virtual void on_reliable_reader_activity_changed( DDSDataWriter *writer, const DDS_ReliableReaderActivityChangedStatus &status) { printf("DataWriterListener: on_reliable_reader_activity_changed()\n"); } }; /* Delete all entities */ static int publisher_shutdown(DDSDomainParticipant *participant) { DDS_ReturnCode_t retcode; int status = 0; if (participant != NULL) { retcode = participant->delete_contained_entities(); if (retcode != DDS_RETCODE_OK) { printf("delete_contained_entities error %d\n", retcode); status = -1; } retcode = DDSTheParticipantFactory->delete_participant(participant); if (retcode != DDS_RETCODE_OK) { printf("delete_participant error %d\n", retcode); status = -1; } } /* RTI Connext provides finalize_instance() method on domain participant factory for people who want to release memory used by the participant factory. Uncomment the following block of code for clean destruction of the singleton. */ /* retcode = DDSDomainParticipantFactory::finalize_instance(); if (retcode != DDS_RETCODE_OK) { printf("finalize_instance error %d\n", retcode); status = -1; } */ return status; } extern "C" int publisher_main(int domainId, int sample_count) { DDSDomainParticipant *participant = NULL; DDSPublisher *publisher = NULL; DDSTopic *topic = NULL; DDSDataWriter *writer = NULL; listenersDataWriter *listeners_writer = NULL; listeners *instance = NULL; DDS_ReturnCode_t retcode; DDS_InstanceHandle_t instance_handle = DDS_HANDLE_NIL; const char *type_name = NULL; int count = 0; DDS_Duration_t send_period = { 1, 0 }; DDS_Duration_t sleep_period = { 2, 0 }; /* To customize participant QoS, use the configuration file USER_QOS_PROFILES.xml */ participant = DDSTheParticipantFactory->create_participant( domainId, DDS_PARTICIPANT_QOS_DEFAULT, NULL /* listener */, DDS_STATUS_MASK_NONE); if (participant == NULL) { printf("create_participant error\n"); publisher_shutdown(participant); return -1; } /* To customize publisher QoS, use the configuration file USER_QOS_PROFILES.xml */ publisher = participant->create_publisher( DDS_PUBLISHER_QOS_DEFAULT, NULL /* listener */, DDS_STATUS_MASK_NONE); if (publisher == NULL) { printf("create_publisher error\n"); publisher_shutdown(participant); return -1; } /* Create ande Delete Inconsistent Topic * --------------------------------------------------------------- * Here we create an inconsistent topic to trigger the subscriber * application's callback. * The inconsistent topic is created with the topic name used in * the Subscriber application, but with a different data type -- * the msg data type defined in partitions.idl. * Once it is created, we sleep to ensure the applications discover * each other and delete the Data Writer and Topic. */ /* First we register the msg type -- we name it * inconsistent_topic_type_name to avoid confusion. */ printf("Creating Inconsistent Topic... \n"); const char *inconsistent_type_name; inconsistent_type_name = msgTypeSupport::get_type_name(); retcode = msgTypeSupport::register_type(participant, inconsistent_type_name); if (retcode != DDS_RETCODE_OK) { printf("register_type error %d\n", retcode); publisher_shutdown(participant); return -1; } DDSTopic *inconsistent_topic = NULL; inconsistent_topic = participant->create_topic( "Example listeners", inconsistent_type_name, DDS_TOPIC_QOS_DEFAULT, NULL /* listener */, DDS_STATUS_MASK_NONE); if (inconsistent_topic == NULL) { printf("create_topic error\n"); publisher_shutdown(participant); return -1; } /* We have to associate a writer to the topic, as Topic information is not * actually propagated until the creation of an associated writer. */ DDSDataWriter *inconsistent_topic_writer = NULL; inconsistent_topic_writer = publisher->create_datawriter( inconsistent_topic, DDS_DATAWRITER_QOS_DEFAULT, NULL /* listener */, DDS_STATUS_MASK_NONE); if (inconsistent_topic == NULL) { printf("create_datawriter error\n"); publisher_shutdown(participant); return -1; } msgDataWriter *msg_writer = NULL; msg_writer = msgDataWriter::narrow(inconsistent_topic_writer); if (msg_writer == NULL) { printf("DataWriter narrow error\n"); publisher_shutdown(participant); return -1; } /* Sleep to leave time for applications to discover each other */ NDDSUtility::sleep(sleep_period); retcode = publisher->delete_datawriter(inconsistent_topic_writer); if (retcode != DDS_RETCODE_OK) { printf("delete_datawriter error %d\n", retcode); publisher_shutdown(participant); return -1; } retcode = participant->delete_topic(inconsistent_topic); if (retcode != DDS_RETCODE_OK) { printf("delete_topic error %d\n", retcode); publisher_shutdown(participant); return -1; } printf("... Deleted Inconsistent Topic\n\n"); /* Create Consistent Topic * ----------------------------------------------------------------- * Once we have created the inconsistent topic with the wrong type, * we create a topic with the right type name -- listeners -- that we * will use to publish data. */ /* Register type before creating topic */ type_name = listenersTypeSupport::get_type_name(); retcode = listenersTypeSupport::register_type(participant, type_name); if (retcode != DDS_RETCODE_OK) { printf("register_type error %d\n", retcode); publisher_shutdown(participant); return -1; } /* To customize topic QoS, use the configuration file USER_QOS_PROFILES.xml */ topic = participant->create_topic( "Example listeners", type_name, DDS_TOPIC_QOS_DEFAULT, NULL /* listener */, DDS_STATUS_MASK_NONE); if (topic == NULL) { printf("create_topic error\n"); publisher_shutdown(participant); return -1; } /* We will use the Data Writer Listener defined above to print * a message when some of events are triggered in the DataWriter. * To do that, first we have to pass the writer_listener and then * we have to enable all status in the status mask. */ DataWriterListener *writer_listener = new DataWriterListener(); writer = publisher->create_datawriter( topic, DDS_DATAWRITER_QOS_DEFAULT, writer_listener /* listener */, DDS_STATUS_MASK_ALL /* enable all statuses */); if (writer == NULL) { printf("create_datawriter error\n"); publisher_shutdown(participant); delete writer_listener; return -1; } listeners_writer = listenersDataWriter::narrow(writer); if (listeners_writer == NULL) { printf("DataWriter narrow error\n"); publisher_shutdown(participant); delete writer_listener; return -1; } /* Create data sample for writing */ instance = listenersTypeSupport::create_data(); if (instance == NULL) { printf("listenersTypeSupport::create_data error\n"); publisher_shutdown(participant); return -1; } /* For a data type that has a key, if the same instance is going to be written multiple times, initialize the key here and register the keyed instance prior to writing */ /* instance_handle = listeners_writer->register_instance(*instance); */ /* Main loop */ for (count = 0; (sample_count == 0) || (count < sample_count); ++count) { printf("Writing listeners, count %d\n", count); /* Modify the data to be sent here */ instance->x = count; retcode = listeners_writer->write(*instance, instance_handle); if (retcode != DDS_RETCODE_OK) { printf("write error %d\n", retcode); } NDDSUtility::sleep(send_period); } /* retcode = listeners_writer->unregister_instance( *instance, instance_handle); if (retcode != DDS_RETCODE_OK) { printf("unregister instance error %d\n", retcode); } */ /* Delete data sample */ retcode = listenersTypeSupport::delete_data(instance); if (retcode != DDS_RETCODE_OK) { printf("listenersTypeSupport::delete_data error %d\n", retcode); } /* Delete all entities */ return publisher_shutdown(participant); delete writer_listener; } #if defined(RTI_WINCE) int wmain(int argc, wchar_t **argv) { int domainId = 0; int sample_count = 0; /* infinite loop */ if (argc >= 2) { domainId = _wtoi(argv[1]); } if (argc >= 3) { sample_count = _wtoi(argv[2]); } /* Uncomment this to turn on additional logging NDDSConfigLogger::get_instance()-> set_verbosity_by_category(NDDS_CONFIG_LOG_CATEGORY_API, NDDS_CONFIG_LOG_VERBOSITY_STATUS_ALL); */ return publisher_main(domainId, sample_count); } #elif !(defined(RTI_VXWORKS) && !defined(__RTP__)) && !defined(RTI_PSOS) int main(int argc, char *argv[]) { int domainId = 0; int sample_count = 0; /* infinite loop */ if (argc >= 2) { domainId = atoi(argv[1]); } if (argc >= 3) { sample_count = atoi(argv[2]); } /* Uncomment this to turn on additional logging NDDSConfigLogger::get_instance()-> set_verbosity_by_category(NDDS_CONFIG_LOG_CATEGORY_API, NDDS_CONFIG_LOG_VERBOSITY_STATUS_ALL); */ return publisher_main(domainId, sample_count); } #endif #ifdef RTI_VX653 const unsigned char *__ctype = *(__ctypePtrGet()); extern "C" void usrAppInit() { #ifdef USER_APPL_INIT USER_APPL_INIT; /* for backwards compatibility */ #endif /* add application specific code here */ taskSpawn( "pub", RTI_OSAPI_THREAD_PRIORITY_NORMAL, 0x8, 0x150000, (FUNCPTR) publisher_main, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0); } #endif
cxx
rticonnextdds-examples
data/projects/rticonnextdds-examples/connext_dds/listeners/c++/listeners_subscriber.cxx
/******************************************************************************* (c) 2005-2014 Copyright, Real-Time Innovations, Inc. All rights reserved. RTI grants Licensee a license to use, modify, compile, and create derivative works of the Software. Licensee has the right to distribute object form only for use with RTI products. The Software is provided "as is", with no warranty of any type, including any warranty for fitness for any purpose. RTI is under no obligation to maintain or support the Software. RTI shall not be liable for any incidental or consequential damages arising out of the use or inability to use the software. ******************************************************************************/ /* listeners_subscriber.cxx A subscription example This file is derived from code automatically generated by the rtiddsgen command: rtiddsgen -language C++ -example <arch> listeners.idl Example subscription of type listeners automatically generated by 'rtiddsgen'. To test them follow these steps: (1) Compile this file and the example publication. (2) Start the subscription with the command objs/<arch>/listeners_subscriber <domain_id> <sample_count> (3) Start the publication with the command objs/<arch>/listeners_publisher <domain_id> <sample_count> (4) [Optional] Specify the list of discovery initial peers and multicast receive addresses via an environment variable or a file (in the current working directory) called NDDS_DISCOVERY_PEERS. You can run any number of publishers and subscribers programs, and can add and remove them dynamically from the domain. Example: To run the example application on domain <domain_id>: On Unix: objs/<arch>/listeners_publisher <domain_id> objs/<arch>/listeners_subscriber <domain_id> On Windows: objs\<arch>\listeners_publisher <domain_id> objs\<arch>\listeners_subscriber <domain_id> modification history ------------ ------- */ #include <stdio.h> #include <stdlib.h> #ifdef RTI_VX653 #include <vThreadsData.h> #endif #include "listeners.h" #include "listenersSupport.h" #include "ndds/ndds_cpp.h" class ParticipantListener : public DDSDomainParticipantListener { public: virtual void on_requested_deadline_missed( DDSDataReader * /*reader*/, const DDS_RequestedDeadlineMissedStatus & /*status*/) { printf("ParticipantListener: on_requested_deadline_missed()\n"); } virtual void on_requested_incompatible_qos( DDSDataReader * /*reader*/, const DDS_RequestedIncompatibleQosStatus & /*status*/) { printf("ParticipantListener: on_requested_incompatible_qos()\n"); } virtual void on_sample_rejected( DDSDataReader * /*reader*/, const DDS_SampleRejectedStatus & /*status*/) { printf("ParticipantListener: on_sample_rejected()\n"); } virtual void on_liveliness_changed( DDSDataReader * /*reader*/, const DDS_LivelinessChangedStatus & /*status*/) { printf("ParticipantListener: on_liveliness_changed()\n"); } virtual void on_sample_lost( DDSDataReader * /*reader*/, const DDS_SampleLostStatus & /*status*/) { printf("ParticipantListener: on_sample_lost()\n"); } virtual void on_subscription_matched( DDSDataReader * /*reader*/, const DDS_SubscriptionMatchedStatus & /*status*/) { printf("ParticipantListener: on_subscription_matched()\n"); } virtual void on_data_available(DDSDataReader *reader) { printf("ParticipantListener: on_data_available()\n"); } virtual void on_data_on_readers(DDSSubscriber *subscriber /*subscriber*/) { printf("ParticipantListener: on_data_on_readers()\n"); /* notify_datareaders() only calls on_data_available for * DataReaders with unread samples */ DDS_ReturnCode_t retcode = subscriber->notify_datareaders(); if (retcode != DDS_RETCODE_OK) { printf("notify_datareaders() error: %d\n", retcode); } } virtual void on_inconsistent_topic( DDSTopic *topic, const DDS_InconsistentTopicStatus &status) { printf("ParticipantListener: on_inconsistent_topic()\n"); } }; class SubscriberListener : public DDSSubscriberListener { public: virtual void on_requested_deadline_missed( DDSDataReader * /*reader*/, const DDS_RequestedDeadlineMissedStatus & /*status*/) { printf("SubscriberListener: on_requested_deadline_missed()\n"); } virtual void on_requested_incompatible_qos( DDSDataReader * /*reader*/, const DDS_RequestedIncompatibleQosStatus & /*status*/) { printf("SubscriberListener: on_requested_incompatible_qos()\n"); } virtual void on_sample_rejected( DDSDataReader * /*reader*/, const DDS_SampleRejectedStatus & /*status*/) { printf("SubscriberListener: on_sample_rejected()\n"); } virtual void on_liveliness_changed( DDSDataReader * /*reader*/, const DDS_LivelinessChangedStatus & /*status*/) { printf("SubscriberListener: on_liveliness_changed()\n"); } virtual void on_sample_lost( DDSDataReader * /*reader*/, const DDS_SampleLostStatus & /*status*/) { printf("SubscriberListener: on_sample_lost()\n"); } virtual void on_subscription_matched( DDSDataReader * /*reader*/, const DDS_SubscriptionMatchedStatus & /*status*/) { printf("SubscriberListener: on_subscription_matched()\n"); } virtual void on_data_available(DDSDataReader *reader) { printf("SubscriberListener: on_data_available()\n"); } virtual void on_data_on_readers(DDSSubscriber *sub /*subscriber*/) { static int count = 0; printf("SubscriberListener: on_data_on_readers()\n"); // notify_datareaders() only calls on_data_available for // DataReaders with unread samples DDS_ReturnCode_t retcode = sub->notify_datareaders(); if (retcode != DDS_RETCODE_OK) { printf("notify_datareaders() error: %d\n", retcode); } if (++count > 3) { DDS_StatusMask newmask = DDS_STATUS_MASK_ALL; // 'Unmask' DATA_ON_READERS status for listener newmask &= ~DDS_DATA_ON_READERS_STATUS; sub->set_listener(this, newmask); printf("Unregistering SubscriberListener::on_data_on_readers()\n"); } } }; class ReaderListener : public DDSDataReaderListener { public: virtual void on_requested_deadline_missed( DDSDataReader * /*reader*/, const DDS_RequestedDeadlineMissedStatus & /*status*/) { printf("ReaderListener: on_requested_deadline_missed()\n"); } virtual void on_requested_incompatible_qos( DDSDataReader * /*reader*/, const DDS_RequestedIncompatibleQosStatus & /*status*/) { printf("ReaderListener: on_requested_incompatible_qos()\n"); } virtual void on_sample_rejected( DDSDataReader * /*reader*/, const DDS_SampleRejectedStatus & /*status*/) { printf("ReaderListener: on_sample_rejected()\n"); } virtual void on_liveliness_changed( DDSDataReader * /*reader*/, const DDS_LivelinessChangedStatus &status) { printf("ReaderListener: on_liveliness_changed()\n"); printf(" Alive writers: %d\n", status.alive_count); } virtual void on_sample_lost( DDSDataReader * /*reader*/, const DDS_SampleLostStatus & /*status*/) { printf("ReaderListener: on_sample_lost()\n"); } virtual void on_subscription_matched( DDSDataReader * /*reader*/, const DDS_SubscriptionMatchedStatus & /*status*/) { printf("ReaderListener: on_subscription_matched()\n"); } virtual void on_data_available(DDSDataReader *reader); }; void ReaderListener::on_data_available(DDSDataReader *reader) { listenersDataReader *listeners_reader = NULL; listenersSeq data_seq; DDS_SampleInfoSeq info_seq; DDS_ReturnCode_t retcode; int i; listeners_reader = listenersDataReader::narrow(reader); if (listeners_reader == NULL) { printf("DataReader narrow error\n"); return; } retcode = listeners_reader->take( data_seq, info_seq, DDS_LENGTH_UNLIMITED, DDS_ANY_SAMPLE_STATE, DDS_ANY_VIEW_STATE, DDS_ANY_INSTANCE_STATE); if (retcode == DDS_RETCODE_NO_DATA) { return; } else if (retcode != DDS_RETCODE_OK) { printf("take error %d\n", retcode); return; } for (i = 0; i < data_seq.length(); ++i) { /* If the reference we get is valid data, it means we have actual * data available, otherwise we got metadata */ if (info_seq[i].valid_data) { listenersTypeSupport::print_data(&data_seq[i]); } else { printf(" Got metadata\n"); } } retcode = listeners_reader->return_loan(data_seq, info_seq); if (retcode != DDS_RETCODE_OK) { printf("return loan error %d\n", retcode); } } /* Delete all entities */ static int subscriber_shutdown(DDSDomainParticipant *participant) { DDS_ReturnCode_t retcode; int status = 0; if (participant != NULL) { retcode = participant->delete_contained_entities(); if (retcode != DDS_RETCODE_OK) { printf("delete_contained_entities error %d\n", retcode); status = -1; } retcode = DDSTheParticipantFactory->delete_participant(participant); if (retcode != DDS_RETCODE_OK) { printf("delete_participant error %d\n", retcode); status = -1; } } /* RTI Connext provides the finalize_instance() method on domain participant factory for people who want to release memory used by the participant factory. Uncomment the following block of code for clean destruction of the singleton. */ /* retcode = DDSDomainParticipantFactory::finalize_instance(); if (retcode != DDS_RETCODE_OK) { printf("finalize_instance error %d\n", retcode); status = -1; } */ return status; } extern "C" int subscriber_main(int domainId, int sample_count) { DDSDomainParticipant *participant = NULL; DDSSubscriber *subscriber = NULL; DDSTopic *topic = NULL; DDSDataReader *reader = NULL; DDS_ReturnCode_t retcode; const char *type_name = NULL; int count = 0; DDS_Duration_t receive_period = { 4, 0 }; int status = 0; /* Create Particiant Listener */ ParticipantListener *participant_listener = new ParticipantListener(); if (participant_listener == NULL) { printf("participant listener instantiation error\n"); subscriber_shutdown(participant); return -1; } /* We associate the participant_listener to the participant and set the * status mask to get all the statuses */ participant = DDSTheParticipantFactory->create_participant( domainId, DDS_PARTICIPANT_QOS_DEFAULT, participant_listener /* listener */, DDS_STATUS_MASK_ALL /* get all statuses */); if (participant == NULL) { printf("create_participant error\n"); subscriber_shutdown(participant); delete participant_listener; return -1; } /* Create Subscriber Listener */ SubscriberListener *subscriber_listener = new SubscriberListener(); if (subscriber_listener == NULL) { printf("subscriber listener instantiation error\n"); subscriber_shutdown(participant); delete participant_listener; return -1; } /* Here we associate the subscriber listener to the subscriber and set the * status mask to get all the statuses */ subscriber = participant->create_subscriber( DDS_SUBSCRIBER_QOS_DEFAULT, subscriber_listener /* listener */, DDS_STATUS_MASK_ALL /* get all statuses */); if (subscriber == NULL) { printf("create_subscriber error\n"); subscriber_shutdown(participant); delete participant_listener; delete subscriber_listener; return -1; } /* Register the type before creating the topic */ type_name = listenersTypeSupport::get_type_name(); retcode = listenersTypeSupport::register_type(participant, type_name); if (retcode != DDS_RETCODE_OK) { printf("register_type error %d\n", retcode); subscriber_shutdown(participant); delete participant_listener; delete subscriber_listener; return -1; } /* To customize the topic QoS, use the configuration file USER_QOS_PROFILES.xml */ topic = participant->create_topic( "Example listeners", type_name, DDS_TOPIC_QOS_DEFAULT, NULL /* listener */, DDS_STATUS_MASK_NONE); if (topic == NULL) { printf("create_topic error\n"); subscriber_shutdown(participant); delete participant_listener; delete subscriber_listener; return -1; } /* Create a data reader listener */ ReaderListener *reader_listener = new ReaderListener(); if (reader_listener == NULL) { printf("reader listener instantiation error\n"); subscriber_shutdown(participant); delete participant_listener; delete subscriber_listener; return -1; } /* Here we associate the data reader listener to the reader. * We just listen for liveliness changed and data available, * since most specific listeners will get called */ reader = subscriber->create_datareader( topic, DDS_DATAREADER_QOS_DEFAULT, reader_listener /* listener */, DDS_LIVELINESS_CHANGED_STATUS | DDS_DATA_AVAILABLE_STATUS /* statuses */); if (reader == NULL) { printf("create_datareader error\n"); subscriber_shutdown(participant); delete participant_listener; delete subscriber_listener; delete reader_listener; return -1; } /* Main loop */ for (count = 0; (sample_count == 0) || (count < sample_count); ++count) { NDDSUtility::sleep(receive_period); } /* Delete all entities */ status = subscriber_shutdown(participant); delete reader_listener; delete subscriber_listener; delete participant_listener; return status; } #if defined(RTI_WINCE) int wmain(int argc, wchar_t **argv) { int domainId = 0; int sample_count = 0; /* infinite loop */ if (argc >= 2) { domainId = _wtoi(argv[1]); } if (argc >= 3) { sample_count = _wtoi(argv[2]); } /* Uncomment this to turn on additional logging NDDSConfigLogger::get_instance()-> set_verbosity_by_category(NDDS_CONFIG_LOG_CATEGORY_API, NDDS_CONFIG_LOG_VERBOSITY_STATUS_ALL); */ return subscriber_main(domainId, sample_count); } #elif !(defined(RTI_VXWORKS) && !defined(__RTP__)) && !defined(RTI_PSOS) int main(int argc, char *argv[]) { int domainId = 0; int sample_count = 0; /* infinite loop */ if (argc >= 2) { domainId = atoi(argv[1]); } if (argc >= 3) { sample_count = atoi(argv[2]); } /* Uncomment this to turn on additional logging NDDSConfigLogger::get_instance()-> set_verbosity_by_category(NDDS_CONFIG_LOG_CATEGORY_API, NDDS_CONFIG_LOG_VERBOSITY_STATUS_ALL); */ return subscriber_main(domainId, sample_count); } #endif #ifdef RTI_VX653 const unsigned char *__ctype = *(__ctypePtrGet()); extern "C" void usrAppInit() { #ifdef USER_APPL_INIT USER_APPL_INIT; /* for backwards compatibility */ #endif /* add application specific code here */ taskSpawn( "sub", RTI_OSAPI_THREAD_PRIORITY_NORMAL, 0x8, 0x150000, (FUNCPTR) subscriber_main, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0); } #endif
cxx
rticonnextdds-examples
data/projects/rticonnextdds-examples/connext_dds/listeners/c++98/listeners_publisher.cxx
/******************************************************************************* (c) 2005-2014 Copyright, Real-Time Innovations, Inc. All rights reserved. RTI grants Licensee a license to use, modify, compile, and create derivative works of the Software. Licensee has the right to distribute object form only for use with RTI products. The Software is provided "as is", with no warranty of any type, including any warranty for fitness for any purpose. RTI is under no obligation to maintain or support the Software. RTI shall not be liable for any incidental or consequential damages arising out of the use or inability to use the software. ******************************************************************************/ #include <iostream> #include <stdio.h> #include <stdlib.h> #include "listeners.h" #include "listenersSupport.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 DataWriterListener : public DDSDataWriterListener { public: virtual void on_offered_deadline_missed( DDSDataWriter * /*writer*/, const DDS_OfferedDeadlineMissedStatus & /*status*/) { std::cout << "DataWriterListener: on_offered_deadline_missed()\n"; } virtual void on_liveliness_lost( DDSDataWriter * /*writer*/, const DDS_LivelinessLostStatus & /*status*/) { std::cout << "DataWriterListener: on_liveliness_lost()\n"; } virtual void on_offered_incompatible_qos( DDSDataWriter * /*writer*/, const DDS_OfferedIncompatibleQosStatus & /*status*/) { std::cout << "DataWriterListener: on_offered_incompatible_qos()\n"; } virtual void on_publication_matched( DDSDataWriter *writer, const DDS_PublicationMatchedStatus &status) { std::cout << "DataWriterListener: on_publication_matched()\n"; if (status.current_count_change < 0) { std::cout << "lost a subscription\n"; } else { std::cout << "found a subscription\n"; } } virtual void on_reliable_writer_cache_changed( DDSDataWriter *writer, const DDS_ReliableWriterCacheChangedStatus &status) { std::cout << "DataWriterListener: on_reliable_writer_cache_changed()\n"; } virtual void on_reliable_reader_activity_changed( DDSDataWriter *writer, const DDS_ReliableReaderActivityChangedStatus &status) { std::cout << "DataWriterListener: " "on_reliable_reader_activity_changed()\n"; } }; int run_publisher_application(unsigned int domain_id, unsigned int sample_count) { DDS_Duration_t send_period = { 1, 0 }; DDS_Duration_t sleep_period = { 2, 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); } /* Create ande Delete Inconsistent Topic * --------------------------------------------------------------- * Here we create an inconsistent topic to trigger the subscriber * application's callback. * The inconsistent topic is created with the topic name used in * the Subscriber application, but with a different data type -- * the msg data type defined in partitions.idl. * Once it is created, we sleep to ensure the applications discover * each other and delete the Data Writer and Topic. */ /* First we register the msg type -- we name it * inconsistent_topic_type_name to avoid confusion. */ std::cout << "Creating Inconsistent Topic... \n"; const char *inconsistent_type_name = msgTypeSupport::get_type_name(); DDS_ReturnCode_t retcode = msgTypeSupport::register_type(participant, inconsistent_type_name); if (retcode != DDS_RETCODE_OK) { return shutdown_participant( participant, "register_type error", EXIT_FAILURE); } DDSTopic *inconsistent_topic = participant->create_topic( "Example listeners", inconsistent_type_name, DDS_TOPIC_QOS_DEFAULT, NULL /* listener */, DDS_STATUS_MASK_NONE); if (inconsistent_topic == NULL) { return shutdown_participant( participant, "create_topic error", EXIT_FAILURE); } /* We have to associate a writer to the topic, as Topic information is not * actually propagated until the creation of an associated writer. */ DDSDataWriter *inconsistent_topic_writer = publisher->create_datawriter( inconsistent_topic, DDS_DATAWRITER_QOS_DEFAULT, NULL /* listener */, DDS_STATUS_MASK_NONE); if (inconsistent_topic == NULL) { return shutdown_participant( participant, "create_datawriter error", EXIT_FAILURE); } msgDataWriter *msg_writer = msgDataWriter::narrow(inconsistent_topic_writer); if (msg_writer == NULL) { return shutdown_participant( participant, "DataWriter narrow error", EXIT_FAILURE); } /* Sleep to leave time for applications to discover each other */ NDDSUtility::sleep(sleep_period); retcode = publisher->delete_datawriter(inconsistent_topic_writer); if (retcode != DDS_RETCODE_OK) { return shutdown_participant( participant, "delete_datawriter error", EXIT_FAILURE); } retcode = participant->delete_topic(inconsistent_topic); if (retcode != DDS_RETCODE_OK) { return shutdown_participant( participant, "delete_topic error", EXIT_FAILURE); } std::cout << "... Deleted Inconsistent Topic\n\n"; /* Create Consistent Topic * ----------------------------------------------------------------- * Once we have created the inconsistent topic with the wrong type, * we create a topic with the right type name -- listeners -- that we * will use to publish data. */ // Register the datatype to use when creating the Topic const char *type_name = listenersTypeSupport::get_type_name(); retcode = listenersTypeSupport::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 listeners", type_name, DDS_TOPIC_QOS_DEFAULT, NULL /* listener */, DDS_STATUS_MASK_NONE); if (topic == NULL) { return shutdown_participant( participant, "create_topic error", EXIT_FAILURE); } /* We will use the Data Writer Listener defined above to print * a message when some of events are triggered in the DataWriter. * To do that, first we have to pass the writer_listener and then * we have to enable all status in the status mask. */ DataWriterListener *writer_listener = new DataWriterListener(); DDSDataWriter *untyped_writer = publisher->create_datawriter( topic, DDS_DATAWRITER_QOS_DEFAULT, writer_listener /* listener */, DDS_STATUS_MASK_ALL /* enable all statuses */); if (untyped_writer == NULL) { return shutdown_participant( participant, "create_datawriter error", EXIT_FAILURE); } listenersDataWriter *typed_writer = listenersDataWriter::narrow(untyped_writer); if (typed_writer == NULL) { return shutdown_participant( participant, "DataWriter narrow error", EXIT_FAILURE); } /* Create data sample for writing */ listeners *data = listenersTypeSupport::create_data(); if (data == NULL) { return shutdown_participant( participant, "listenersTypeSupport::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 listeners, count " << samples_written << std::endl; // Modify the data to be sent here data->x = samples_written; retcode = typed_writer->write(*data, instance_handle); if (retcode != DDS_RETCODE_OK) { std::cerr << "write error " << retcode << std::endl; } NDDSUtility::sleep(send_period); } /* retcode = typed_writer->unregister_instance( *data, instance_handle); if (retcode != DDS_RETCODE_OK) { std::cerr "unregister instance error " << retcode << std::endl); } */ // Delete previously allocated data, including all contained elements retcode = listenersTypeSupport::delete_data(data); if (retcode != DDS_RETCODE_OK) { std::cerr << "listenersTypeSupport::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/listeners/c++98/listeners_subscriber.cxx
/******************************************************************************* (c) 2005-2014 Copyright, Real-Time Innovations, Inc. All rights reserved. RTI grants Licensee a license to use, modify, compile, and create derivative works of the Software. Licensee has the right to distribute object form only for use with RTI products. The Software is provided "as is", with no warranty of any type, including any warranty for fitness for any purpose. RTI is under no obligation to maintain or support the Software. RTI shall not be liable for any incidental or consequential damages arising out of the use or inability to use the software. ******************************************************************************/ #include <iostream> #include <stdio.h> #include <stdlib.h> #include "listeners.h" #include "listenersSupport.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 ParticipantListener : public DDSDomainParticipantListener { public: virtual void on_requested_deadline_missed( DDSDataReader * /*reader*/, const DDS_RequestedDeadlineMissedStatus & /*status*/) { std::cout << "ParticipantListener: on_requested_deadline_missed()\n"; } virtual void on_requested_incompatible_qos( DDSDataReader * /*reader*/, const DDS_RequestedIncompatibleQosStatus & /*status*/) { std::cout << "ParticipantListener: on_requested_incompatible_qos()\n"; } virtual void on_sample_rejected( DDSDataReader * /*reader*/, const DDS_SampleRejectedStatus & /*status*/) { std::cout << "ParticipantListener: on_sample_rejected()\n"; } virtual void on_liveliness_changed( DDSDataReader * /*reader*/, const DDS_LivelinessChangedStatus & /*status*/) { std::cout << "ParticipantListener: on_liveliness_changed()\n"; } virtual void on_sample_lost( DDSDataReader * /*reader*/, const DDS_SampleLostStatus & /*status*/) { std::cout << "ParticipantListener: on_sample_lost()\n"; } virtual void on_subscription_matched( DDSDataReader * /*reader*/, const DDS_SubscriptionMatchedStatus & /*status*/) { std::cout << "ParticipantListener: on_subscription_matched()\n"; } virtual void on_data_available(DDSDataReader *reader) { std::cout << "ParticipantListener: on_data_available()\n"; } virtual void on_data_on_readers(DDSSubscriber *subscriber /*subscriber*/) { std::cout << "ParticipantListener: on_data_on_readers()\n"; /* notify_datareaders() only calls on_data_available for * DataReaders with unread samples */ DDS_ReturnCode_t retcode = subscriber->notify_datareaders(); if (retcode != DDS_RETCODE_OK) { std::cout << "notify_datareaders() error: " << retcode << std::endl; } } virtual void on_inconsistent_topic( DDSTopic *topic, const DDS_InconsistentTopicStatus &status) { std::cout << "ParticipantListener: on_inconsistent_topic()\n"; } }; class SubscriberListener : public DDSSubscriberListener { public: virtual void on_requested_deadline_missed( DDSDataReader * /*reader*/, const DDS_RequestedDeadlineMissedStatus & /*status*/) { std::cout << "SubscriberListener: on_requested_deadline_missed()\n"; } virtual void on_requested_incompatible_qos( DDSDataReader * /*reader*/, const DDS_RequestedIncompatibleQosStatus & /*status*/) { std::cout << "SubscriberListener: on_requested_incompatible_qos()\n"; } virtual void on_sample_rejected( DDSDataReader * /*reader*/, const DDS_SampleRejectedStatus & /*status*/) { std::cout << "SubscriberListener: on_sample_rejected()\n"; } virtual void on_liveliness_changed( DDSDataReader * /*reader*/, const DDS_LivelinessChangedStatus & /*status*/) { std::cout << "SubscriberListener: on_liveliness_changed()\n"; } virtual void on_sample_lost( DDSDataReader * /*reader*/, const DDS_SampleLostStatus & /*status*/) { std::cout << "SubscriberListener: on_sample_lost()\n"; } virtual void on_subscription_matched( DDSDataReader * /*reader*/, const DDS_SubscriptionMatchedStatus & /*status*/) { std::cout << "SubscriberListener: on_subscription_matched()\n"; } virtual void on_data_available(DDSDataReader *reader) { std::cout << "SubscriberListener: on_data_available()\n"; } virtual void on_data_on_readers(DDSSubscriber *sub /*subscriber*/) { static int count = 0; std::cout << "SubscriberListener: on_data_on_readers()\n"; // notify_datareaders() only calls on_data_available for // DataReaders with unread samples DDS_ReturnCode_t retcode = sub->notify_datareaders(); if (retcode != DDS_RETCODE_OK) { std::cout << "notify_datareaders() error: " << retcode << std::endl; } if (++count > 3) { DDS_StatusMask newmask = DDS_STATUS_MASK_ALL; // 'Unmask' DATA_ON_READERS status for listener newmask &= ~DDS_DATA_ON_READERS_STATUS; sub->set_listener(this, newmask); std::cout << "Unregistering " "SubscriberListener::on_data_on_readers()\n"; } } }; class ReaderListener : public DDSDataReaderListener { public: virtual void on_requested_deadline_missed( DDSDataReader * /*reader*/, const DDS_RequestedDeadlineMissedStatus & /*status*/) { std::cout << "ReaderListener: on_requested_deadline_missed()\n"; } virtual void on_requested_incompatible_qos( DDSDataReader * /*reader*/, const DDS_RequestedIncompatibleQosStatus & /*status*/) { std::cout << "ReaderListener: on_requested_incompatible_qos()\n"; } virtual void on_sample_rejected( DDSDataReader * /*reader*/, const DDS_SampleRejectedStatus & /*status*/) { std::cout << "ReaderListener: on_sample_rejected()\n"; } virtual void on_liveliness_changed( DDSDataReader * /*reader*/, const DDS_LivelinessChangedStatus &status) { std::cout << "ReaderListener: on_liveliness_changed()\n"; std::cout << " Alive writers: " << status.alive_count << std::endl; } virtual void on_sample_lost( DDSDataReader * /*reader*/, const DDS_SampleLostStatus & /*status*/) { std::cout << "ReaderListener: on_sample_lost()\n"; } virtual void on_subscription_matched( DDSDataReader * /*reader*/, const DDS_SubscriptionMatchedStatus & /*status*/) { std::cout << "ReaderListener: on_subscription_matched()\n"; } virtual void on_data_available(DDSDataReader *reader); }; void ReaderListener::on_data_available(DDSDataReader *reader) { listenersDataReader *listeners_reader = NULL; listenersSeq data_seq; DDS_SampleInfoSeq info_seq; DDS_ReturnCode_t retcode; int i; listeners_reader = listenersDataReader::narrow(reader); if (listeners_reader == NULL) { std::cout << "DataReader narrow error\n"; return; } retcode = listeners_reader->take( data_seq, info_seq, DDS_LENGTH_UNLIMITED, DDS_ANY_SAMPLE_STATE, DDS_ANY_VIEW_STATE, DDS_ANY_INSTANCE_STATE); if (retcode == DDS_RETCODE_NO_DATA) { return; } else if (retcode != DDS_RETCODE_OK) { std::cout << "take error %d\n", retcode; return; } for (i = 0; i < data_seq.length(); ++i) { /* If the reference we get is valid data, it means we have actual * data available, otherwise we got metadata */ if (info_seq[i].valid_data) { listenersTypeSupport::print_data(&data_seq[i]); } else { std::cout << " Got metadata\n"; } } retcode = listeners_reader->return_loan(data_seq, info_seq); if (retcode != DDS_RETCODE_OK) { std::cout << "return loan error " << retcode << std::endl; } } int run_subscriber_application( unsigned int domain_id, unsigned int sample_count) { DDS_Duration_t wait_timeout = { 4, 0 }; // Create Particiant Listener ParticipantListener *participant_listener = new ParticipantListener(); if (participant_listener == NULL) { std::cerr << "participant listener instantiation error" << std::endl; return EXIT_FAILURE; } // Start communicating in a domain, usually one participant per application DDSDomainParticipant *participant = DDSTheParticipantFactory->create_participant( domain_id, DDS_PARTICIPANT_QOS_DEFAULT, participant_listener /* listener */, DDS_STATUS_MASK_ALL /* get all statuses */); if (participant == NULL) { return shutdown_participant( participant, "create_participant error", EXIT_FAILURE); } /* Create Subscriber Listener */ SubscriberListener *subscriber_listener = new SubscriberListener(); if (subscriber_listener == NULL) { return shutdown_participant( participant, "subscriber listener instantiation error", EXIT_FAILURE); } // A Subscriber allows an application to create one or more DataReaders DDSSubscriber *subscriber = participant->create_subscriber( DDS_SUBSCRIBER_QOS_DEFAULT, subscriber_listener /* listener */, DDS_STATUS_MASK_ALL /* get all statuses */); 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 = listenersTypeSupport::get_type_name(); DDS_ReturnCode_t retcode = listenersTypeSupport::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 listeners", type_name, DDS_TOPIC_QOS_DEFAULT, NULL /* listener */, DDS_STATUS_MASK_NONE); if (topic == NULL) { return shutdown_participant( participant, "create_topic error", EXIT_FAILURE); } // Create a data reader listener ReaderListener *reader_listener = new ReaderListener(); if (reader_listener == NULL) { return shutdown_participant( participant, "reader listener instantiation error", EXIT_FAILURE); } /* Here we associate the data reader listener to the reader. * We just listen for liveliness changed and data available, * since most specific listeners will get called */ DDSDataReader *untyped_reader = subscriber->create_datareader( topic, DDS_DATAREADER_QOS_DEFAULT, reader_listener /* listener */, DDS_LIVELINESS_CHANGED_STATUS | DDS_DATA_AVAILABLE_STATUS /* statuses */); if (untyped_reader == NULL) { return shutdown_participant( participant, "create_datareader error", EXIT_FAILURE); } /* Main loop */ for (int count = 0; !shutdown_requested && (count < sample_count); ++count) { NDDSUtility::sleep(wait_timeout); } // 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/listeners/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/listeners/c/listeners_subscriber.c
/******************************************************************************* (c) 2005-2014 Copyright, Real-Time Innovations, Inc. All rights reserved. RTI grants Licensee a license to use, modify, compile, and create derivative works of the Software. Licensee has the right to distribute object form only for use with RTI products. The Software is provided "as is", with no warranty of any type, including any warranty for fitness for any purpose. RTI is under no obligation to maintain or support the Software. RTI shall not be liable for any incidental or consequential damages arising out of the use or inability to use the software. ******************************************************************************/ /* listeners_subscriber.c A subscription example This file is derived from code automatically generated by the rtiddsgen command: rtiddsgen -language C -example <arch> listeners.idl Example subscription of type listeners automatically generated by 'rtiddsgen'. To test them, follow these steps: (1) Compile this file and the example publication. (2) Start the subscription with the command objs/<arch>/listeners_subscriber <domain_id> <sample_count> (3) Start the publication with the command objs/<arch>/listeners_publisher <domain_id> <sample_count> (4) [Optional] Specify the list of discovery initial peers and multicast receive addresses via an environment variable or a file (in the current working directory) called NDDS_DISCOVERY_PEERS. You can run any number of publishers and subscribers programs, and can add and remove them dynamically from the domain. Example: To run the example application on domain <domain_id>: On UNIX systems: objs/<arch>/listeners_publisher <domain_id> objs/<arch>/listeners_subscriber <domain_id> On Windows systems: objs\<arch>\listeners_publisher <domain_id> objs\<arch>\listeners_subscriber <domain_id> modification history ------------ ------- */ #include "listeners.h" #include "listenersSupport.h" #include "ndds/ndds_c.h" #include <stdio.h> #include <stdlib.h> /* ------------------------------------------------------- * Participant Listener events * ------------------------------------------------------- */ void ParticipantListener_on_requested_deadline_missed( void *listener_data, DDS_DataReader *reader, const struct DDS_RequestedDeadlineMissedStatus *status) { printf("ParticipantListener: on_requested_deadline_missed()\n"); } void ParticipantListener_on_requested_incompatible_qos( void *listener_data, DDS_DataReader *reader, const struct DDS_RequestedIncompatibleQosStatus *status) { printf("ParticipantListener: on_requested_incompatible_qos()\n"); } void ParticipantListener_on_sample_rejected( void *listener_data, DDS_DataReader *reader, const struct DDS_SampleRejectedStatus *status) { printf("ParticipantListener: on_sample_rejected()\n"); } void ParticipantListener_on_liveliness_changed( void *listener_data, DDS_DataReader *reader, const struct DDS_LivelinessChangedStatus *status) { printf("ParticipantListener: on_liveliness_changed()\n"); } void ParticipantListener_on_sample_lost( void *listener_data, DDS_DataReader *reader, const struct DDS_SampleLostStatus *status) { printf("ParticipantListener: on_sample_lost()\n"); } void ParticipantListener_on_subscription_matched( void *listener_data, DDS_DataReader *reader, const struct DDS_SubscriptionMatchedStatus *status) { printf("ParticipantListener: on_subscription_matched()\n"); } void ParticipantListener_on_data_available( void *listener_data, DDS_DataReader *reader) { printf("ParticipantListener: on_data_available()\n"); } void ParticipantListener_on_data_on_readers( void *listener_data, DDS_Subscriber *sub) { DDS_ReturnCode_t retcode; printf("ParticipantListener: on_data_on_readers()\n"); /* notify_datareaders() only calls on_data_available for * DataReaders with unread samples */ retcode = DDS_Subscriber_notify_datareaders(sub); if (retcode != DDS_RETCODE_OK) { printf("notify_datareaders() error: %d\n", retcode); } } void ParticipantListener_on_inconsistent_topic( void *listener_data, DDS_Topic *topic, const struct DDS_InconsistentTopicStatus *status) { printf("ParticipantListener: on_inconsistent_topic()\n"); } /* ------------------------------------------------------- * Subscriber Listener events * ------------------------------------------------------- */ void SubscriberListener_on_requested_deadline_missed( void *listener_data, DDS_DataReader *reader, const struct DDS_RequestedDeadlineMissedStatus *status) { printf("SubscriberListener: on_requested_deadline_missed()\n"); } void SubscriberListener_on_requested_incompatible_qos( void *listener_data, DDS_DataReader *reader, const struct DDS_RequestedIncompatibleQosStatus *status) { printf("SubscriberListener: on_requested_incompatible_qos()\n"); } void SubscriberListener_on_sample_rejected( void *listener_data, DDS_DataReader *reader, const struct DDS_SampleRejectedStatus *status) { printf("SubscriberListener: on_sample_rejected()\n"); } void SubscriberListener_on_liveliness_changed( void *listener_data, DDS_DataReader *reader, const struct DDS_LivelinessChangedStatus *status) { printf("SubscriberListener: on_liveliness_changed()\n"); } void SubscriberListener_on_sample_lost( void *listener_data, DDS_DataReader *reader, const struct DDS_SampleLostStatus *status) { printf("SubscriberListener: on_sample_lost()\n"); } void SubscriberListener_on_subscription_matched( void *listener_data, DDS_DataReader *reader, const struct DDS_SubscriptionMatchedStatus *status) { printf("SubscriberListener: on_subscription_matched()\n"); } void SubscriberListener_on_data_available( void *listener_data, DDS_DataReader *reader) { printf("SubscriberListener: on_data_available()\n"); } void SubscriberListener_on_data_on_readers( void *listener_data, DDS_Subscriber *sub) { DDS_ReturnCode_t retcode; static int count = 0; printf("SubscriberListener: on_data_on_readers()\n"); /* notify_datareaders() only calls on_data_available for * DataReaders with unread samples */ retcode = DDS_Subscriber_notify_datareaders(sub); if (retcode != DDS_RETCODE_OK) { printf("notify_datareaders() error: %d\n", retcode); } if (++count > 3) { /* Stop receiving DATA_ON_READERS status */ DDS_StatusMask newmask = DDS_REQUESTED_DEADLINE_MISSED_STATUS | DDS_REQUESTED_INCOMPATIBLE_QOS_STATUS | DDS_SAMPLE_REJECTED_STATUS | DDS_LIVELINESS_CHANGED_STATUS | DDS_SAMPLE_LOST_STATUS | DDS_SUBSCRIPTION_MATCHED_STATUS | DDS_DATA_AVAILABLE_STATUS; DDS_Subscriber_set_listener(sub, listener_data, newmask); printf("Unregistering SubscriberListener::on_data_on_readers()\n"); } } /* ------------------------------------------------------- * Reader Listener events * ------------------------------------------------------- */ void ReaderListener_on_requested_deadline_missed( void *listener_data, DDS_DataReader *reader, const struct DDS_RequestedDeadlineMissedStatus *status) { printf("ReaderListener: on_requested_deadline_missed()\n"); } void ReaderListener_on_requested_incompatible_qos( void *listener_data, DDS_DataReader *reader, const struct DDS_RequestedIncompatibleQosStatus *status) { printf("ReaderListener: on_requested_incompatible_qos()\n"); } void ReaderListener_on_sample_rejected( void *listener_data, DDS_DataReader *reader, const struct DDS_SampleRejectedStatus *status) { printf("ReaderListener: on_sample_rejected()\n"); } void ReaderListener_on_liveliness_changed( void *listener_data, DDS_DataReader *reader, const struct DDS_LivelinessChangedStatus *status) { printf("ReaderListener: on_liveliness_changed()\n"); printf(" Alive writers: %d\n", status->alive_count); } void ReaderListener_on_sample_lost( void *listener_data, DDS_DataReader *reader, const struct DDS_SampleLostStatus *status) { printf("ReaderListener: on_sample_lost()\n"); } void ReaderListener_on_subscription_matched( void *listener_data, DDS_DataReader *reader, const struct DDS_SubscriptionMatchedStatus *status) { printf("ReaderListener: on_subscription_matched()\n"); } void ReaderListener_on_data_available( void *listener_data, DDS_DataReader *reader) { listenersDataReader *listeners_reader = NULL; struct listenersSeq data_seq = DDS_SEQUENCE_INITIALIZER; struct DDS_SampleInfoSeq info_seq = DDS_SEQUENCE_INITIALIZER; DDS_ReturnCode_t retcode; int i; printf("ReaderListener: on_data_available()\n"); listeners_reader = listenersDataReader_narrow(reader); if (listeners_reader == NULL) { printf("DataReader narrow error\n"); return; } retcode = listenersDataReader_take( listeners_reader, &data_seq, &info_seq, DDS_LENGTH_UNLIMITED, DDS_ANY_SAMPLE_STATE, DDS_ANY_VIEW_STATE, DDS_ANY_INSTANCE_STATE); if (retcode == DDS_RETCODE_NO_DATA) { return; } else if (retcode != DDS_RETCODE_OK) { printf("take error %d\n", retcode); return; } for (i = 0; i < listenersSeq_get_length(&data_seq); ++i) { /* If the reference we get is valid data, it means we have actual * data available, otherwise we got metadata */ if (DDS_SampleInfoSeq_get_reference(&info_seq, i)->valid_data) { listenersTypeSupport_print_data( listenersSeq_get_reference(&data_seq, i)); } else { printf(" Got metadata\n"); } } retcode = listenersDataReader_return_loan( listeners_reader, &data_seq, &info_seq); if (retcode != DDS_RETCODE_OK) { printf("return loan error %d\n", retcode); } } /* Delete all entities */ static int subscriber_shutdown(DDS_DomainParticipant *participant) { DDS_ReturnCode_t retcode; int status = 0; if (participant != NULL) { retcode = DDS_DomainParticipant_delete_contained_entities(participant); if (retcode != DDS_RETCODE_OK) { printf("delete_contained_entities error %d\n", retcode); status = -1; } retcode = DDS_DomainParticipantFactory_delete_participant( DDS_TheParticipantFactory, participant); if (retcode != DDS_RETCODE_OK) { printf("delete_participant error %d\n", retcode); status = -1; } } /* RTI Connext provides the finalize_instance() method on domain participant factory for users who want to release memory used by the participant factory. Uncomment the following block of code for clean destruction of the singleton. */ /* retcode = DDS_DomainParticipantFactory_finalize_instance(); if (retcode != DDS_RETCODE_OK) { printf("finalize_instance error %d\n", retcode); status = -1; } */ return status; } static int subscriber_main(int domainId, int sample_count) { DDS_DomainParticipant *participant = NULL; DDS_Subscriber *subscriber = NULL; DDS_Topic *topic = NULL; struct DDS_DomainParticipantListener participant_listener = DDS_DomainParticipantListener_INITIALIZER; struct DDS_SubscriberListener subscriber_listener = DDS_SubscriberListener_INITIALIZER; struct DDS_DataReaderListener reader_listener = DDS_DataReaderListener_INITIALIZER; DDS_StatusMask mask; DDS_DataReader *reader = NULL; DDS_ReturnCode_t retcode; const char *type_name = NULL; int count = 0; struct DDS_Duration_t poll_period = { 1, 0 }; /* Set up participant listener */ participant_listener.as_subscriberlistener.as_datareaderlistener .on_requested_deadline_missed = ParticipantListener_on_requested_deadline_missed; participant_listener.as_subscriberlistener.as_datareaderlistener .on_requested_incompatible_qos = ParticipantListener_on_requested_incompatible_qos; participant_listener.as_subscriberlistener.as_datareaderlistener .on_sample_rejected = ParticipantListener_on_sample_rejected; participant_listener.as_subscriberlistener.as_datareaderlistener .on_liveliness_changed = ParticipantListener_on_liveliness_changed; participant_listener.as_subscriberlistener.as_datareaderlistener .on_sample_lost = ParticipantListener_on_sample_lost; participant_listener.as_subscriberlistener.as_datareaderlistener .on_subscription_matched = ParticipantListener_on_subscription_matched; participant_listener.as_subscriberlistener.as_datareaderlistener .on_data_available = ParticipantListener_on_data_available; participant_listener.as_subscriberlistener.on_data_on_readers = ParticipantListener_on_data_on_readers; participant_listener.as_topiclistener.on_inconsistent_topic = ParticipantListener_on_inconsistent_topic; participant_listener.as_subscriberlistener.as_datareaderlistener.as_listener .listener_data = &participant_listener; mask = DDS_REQUESTED_DEADLINE_MISSED_STATUS | DDS_REQUESTED_INCOMPATIBLE_QOS_STATUS | DDS_SAMPLE_REJECTED_STATUS | DDS_LIVELINESS_CHANGED_STATUS | DDS_SAMPLE_LOST_STATUS | DDS_SUBSCRIPTION_MATCHED_STATUS | DDS_DATA_AVAILABLE_STATUS | DDS_DATA_ON_READERS_STATUS | DDS_INCONSISTENT_TOPIC_STATUS; /* We associate the participant_listener to the participant and set the * status mask just defined */ participant = DDS_DomainParticipantFactory_create_participant( DDS_TheParticipantFactory, domainId, &DDS_PARTICIPANT_QOS_DEFAULT, &participant_listener /* listener */, mask /* status mask */); if (participant == NULL) { printf("create_participant error\n"); subscriber_shutdown(participant); return -1; } /* Setup subscriber listener */ subscriber_listener.as_datareaderlistener.on_requested_deadline_missed = SubscriberListener_on_requested_deadline_missed; subscriber_listener.as_datareaderlistener.on_requested_incompatible_qos = SubscriberListener_on_requested_incompatible_qos; subscriber_listener.as_datareaderlistener.on_sample_rejected = SubscriberListener_on_sample_rejected; subscriber_listener.as_datareaderlistener.on_liveliness_changed = SubscriberListener_on_liveliness_changed; subscriber_listener.as_datareaderlistener.on_sample_lost = SubscriberListener_on_sample_lost; subscriber_listener.as_datareaderlistener.on_subscription_matched = SubscriberListener_on_subscription_matched; subscriber_listener.as_datareaderlistener.on_data_available = SubscriberListener_on_data_available; subscriber_listener.on_data_on_readers = SubscriberListener_on_data_on_readers; subscriber_listener.as_datareaderlistener.as_listener.listener_data = &subscriber_listener; mask = DDS_REQUESTED_DEADLINE_MISSED_STATUS | DDS_REQUESTED_INCOMPATIBLE_QOS_STATUS | DDS_SAMPLE_REJECTED_STATUS | DDS_LIVELINESS_CHANGED_STATUS | DDS_SAMPLE_LOST_STATUS | DDS_SUBSCRIPTION_MATCHED_STATUS | DDS_DATA_AVAILABLE_STATUS | DDS_DATA_ON_READERS_STATUS; /* Here we associate the subscriber listener to the subscriber and set the * status mask to the mask we have just defined */ subscriber = DDS_DomainParticipant_create_subscriber( participant, &DDS_SUBSCRIBER_QOS_DEFAULT, &subscriber_listener /* listener */, mask /* status mask */); if (subscriber == NULL) { printf("create_subscriber error\n"); subscriber_shutdown(participant); return -1; } /* Register the type before creating the topic */ type_name = listenersTypeSupport_get_type_name(); retcode = listenersTypeSupport_register_type(participant, type_name); if (retcode != DDS_RETCODE_OK) { printf("register_type error %d\n", retcode); subscriber_shutdown(participant); return -1; } topic = DDS_DomainParticipant_create_topic( participant, "Example listeners", type_name, &DDS_TOPIC_QOS_DEFAULT, NULL /* listener */, DDS_STATUS_MASK_NONE); if (topic == NULL) { printf("create_topic error\n"); subscriber_shutdown(participant); return -1; } /* Setup data reader listener */ reader_listener.on_requested_deadline_missed = ReaderListener_on_requested_deadline_missed; reader_listener.on_requested_incompatible_qos = ReaderListener_on_requested_incompatible_qos; reader_listener.on_sample_rejected = ReaderListener_on_sample_rejected; reader_listener.on_liveliness_changed = ReaderListener_on_liveliness_changed; reader_listener.on_sample_lost = ReaderListener_on_sample_lost; reader_listener.on_subscription_matched = ReaderListener_on_subscription_matched; reader_listener.on_data_available = ReaderListener_on_data_available; reader_listener.as_listener.listener_data = &reader_listener; /* Just listen for liveliness changed and data available, * since most specific listeners will get called */ mask = DDS_LIVELINESS_CHANGED_STATUS | DDS_DATA_AVAILABLE_STATUS; /* In the data reader we change the status mask to the mask * we have just defined */ reader = DDS_Subscriber_create_datareader( subscriber, DDS_Topic_as_topicdescription(topic), &DDS_DATAREADER_QOS_DEFAULT, &reader_listener, mask); if (reader == NULL) { printf("create_datareader error\n"); subscriber_shutdown(participant); return -1; } /* Main loop */ for (count = 0; (sample_count == 0) || (count < sample_count); ++count) { NDDS_Utility_sleep(&poll_period); } /* Cleanup and delete all entities */ return subscriber_shutdown(participant); } #if defined(RTI_WINCE) int wmain(int argc, wchar_t **argv) { int domainId = 0; int sample_count = 0; /* infinite loop */ if (argc >= 2) { domainId = _wtoi(argv[1]); } if (argc >= 3) { sample_count = _wtoi(argv[2]); } /* Uncomment this to turn on additional logging NDDS_Config_Logger_set_verbosity_by_category( NDDS_Config_Logger_get_instance(), NDDS_CONFIG_LOG_CATEGORY_API, NDDS_CONFIG_LOG_VERBOSITY_STATUS_ALL); */ return subscriber_main(domainId, sample_count); } #elif !(defined(RTI_VXWORKS) && !defined(__RTP__)) && !defined(RTI_PSOS) int main(int argc, char *argv[]) { int domainId = 0; int sample_count = 0; /* infinite loop */ if (argc >= 2) { domainId = atoi(argv[1]); } if (argc >= 3) { sample_count = atoi(argv[2]); } /* Uncomment this to turn on additional logging NDDS_Config_Logger_set_verbosity_by_category( NDDS_Config_Logger_get_instance(), NDDS_CONFIG_LOG_CATEGORY_API, NDDS_CONFIG_LOG_VERBOSITY_STATUS_ALL); */ return subscriber_main(domainId, sample_count); } #endif #ifdef RTI_VX653 const unsigned char *__ctype = NULL; void usrAppInit() { #ifdef USER_APPL_INIT USER_APPL_INIT; /* for backwards compatibility */ #endif /* add application specific code here */ taskSpawn( "sub", RTI_OSAPI_THREAD_PRIORITY_NORMAL, 0x8, 0x150000, (FUNCPTR) subscriber_main, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0); } #endif
c
rticonnextdds-examples
data/projects/rticonnextdds-examples/connext_dds/listeners/c/listeners_publisher.c
/******************************************************************************* (c) 2005-2014 Copyright, Real-Time Innovations, Inc. All rights reserved. RTI grants Licensee a license to use, modify, compile, and create derivative works of the Software. Licensee has the right to distribute object form only for use with RTI products. The Software is provided "as is", with no warranty of any type, including any warranty for fitness for any purpose. RTI is under no obligation to maintain or support the Software. RTI shall not be liable for any incidental or consequential damages arising out of the use or inability to use the software. ******************************************************************************/ /* listeners_publisher.c A publication of data of type listeners This file is derived from code automatically generated by the rtiddsgen command: rtiddsgen -language C -example <arch> listeners.idl Example publication of type listeners automatically generated by 'rtiddsgen'. To test them follow these steps: (1) Compile this file and the example subscription. (2) Start the subscription with the command objs/<arch>/listeners_subscriber <domain_id> <sample_count> (3) Start the publication with the command objs/<arch>/listeners_publisher <domain_id> <sample_count> (4) [Optional] Specify the list of discovery initial peers and multicast receive addresses via an environment variable or a file (in the current working directory) called NDDS_DISCOVERY_PEERS. You can run any number of publishers and subscribers programs, and can add and remove them dynamically from the domain. Example: To run the example application on domain <domain_id>: On Unix: objs/<arch>/listeners_publisher <domain_id> objs/<arch>/listeners_subscriber <domain_id> On Windows: objs\<arch>\listeners_publisher <domain_id> objs\<arch>\listeners_subscriber <domain_id> modification history ------------ ------- */ #include "listeners.h" #include "listenersSupport.h" #include "ndds/ndds_c.h" #include <stdio.h> #include <stdlib.h> void DataWriterListener_on_offered_deadline_missed( void *listener_data, DDS_DataWriter *writer, const struct DDS_OfferedDeadlineMissedStatus *status) { printf("DataWriterListener: on_offered_deadline_missed()\n"); } void DataWriterListener_on_liveliness_lost( void *listener_data, DDS_DataWriter *writer, const struct DDS_LivelinessLostStatus *status) { printf("DataWriterListener: on_liveliness_lost()\n"); } void DataWriterListener_on_offered_incompatible_qos( void *listener_data, DDS_DataWriter *writer, const struct DDS_OfferedIncompatibleQosStatus *status) { printf("DataWriterListener: on_offered_incompatible_qos()\n"); } void DataWriterListener_on_publication_matched( void *listener_data, DDS_DataWriter *writer, const struct DDS_PublicationMatchedStatus *status) { printf("DataWriterListener: on_publication_matched()\n"); if (status->current_count_change < 0) { printf("lost a subscription\n"); } else { printf("found a subscription\n"); } } void DataWriterListener_on_reliable_writer_cache_changed( void *listener_data, DDS_DataWriter *writer, const struct DDS_ReliableWriterCacheChangedStatus *status) { printf("DataWriterListener: on_reliable_writer_cache_changed()\n"); } void DataWriterListener_on_reliable_reader_activity_changed( void *listener_data, DDS_DataWriter *writer, const struct DDS_ReliableReaderActivityChangedStatus *status) { printf("DataWriterListener: on_reliable_reader_activity_changed()\n"); } void DataWratierListener_on_sample_removed( void *listener_data, DDS_DataWriter *writer, const struct DDS_Cookie_t *cookie) { printf("DataWriterListener: on_sample_removed()\n"); } void DataWratierListener_on_instance_replaced( void *listener_data, DDS_DataWriter *writer, const DDS_InstanceHandle_t *handle) { printf("DataWriterListener: on_instance_replaced()\n"); } void DataWratierListener_on_application_acknowledgment( void *listener_data, DDS_DataWriter *writer, const struct DDS_AcknowledgmentInfo *info) { printf("DataWriterListener: on_application_acknowledgmentd()\n"); } void DataWratierListener_on_service_request_accepted( void *listener_data, DDS_DataWriter *writer, const struct DDS_ServiceRequestAcceptedStatus *status) { printf("DataWriterListener: on_service_request_accepted()\n"); } /* Delete all entities */ static int publisher_shutdown(DDS_DomainParticipant *participant) { DDS_ReturnCode_t retcode; int status = 0; if (participant != NULL) { retcode = DDS_DomainParticipant_delete_contained_entities(participant); if (retcode != DDS_RETCODE_OK) { printf("delete_contained_entities error %d\n", retcode); status = -1; } retcode = DDS_DomainParticipantFactory_delete_participant( DDS_TheParticipantFactory, participant); if (retcode != DDS_RETCODE_OK) { printf("delete_participant error %d\n", retcode); status = -1; } } /* RTI Connext provides finalize_instance() method on domain participant factory for people who want to release memory used by the participant factory. Uncomment the following block of code for clean destruction of the singleton. */ /* retcode = DDS_DomainParticipantFactory_finalize_instance(); if (retcode != DDS_RETCODE_OK) { printf("finalize_instance error %d\n", retcode); status = -1; } */ return status; } static int publisher_main(int domainId, int sample_count) { DDS_DomainParticipant *participant = NULL; DDS_Publisher *publisher = NULL; DDS_Topic *topic = NULL; DDS_DataWriter *writer = NULL; listenersDataWriter *listeners_writer = NULL; listeners *instance = NULL; DDS_ReturnCode_t retcode; DDS_InstanceHandle_t instance_handle = DDS_HANDLE_NIL; const char *type_name = NULL; struct DDS_DataWriterListener writer_listener = DDS_DataWriterListener_INITIALIZER; DDS_Topic *inconsistent_topic = NULL; DDS_DataWriter *inconsistent_topic_writer = NULL; const char *inconsistent_topic_type_name = NULL; msgDataWriter *msg_writer = NULL; int count = 0; struct DDS_Duration_t send_period = { 1, 0 }; struct DDS_Duration_t sleep_period = { 2, 0 }; /* To customize participant QoS, use the configuration file USER_QOS_PROFILES.xml */ participant = DDS_DomainParticipantFactory_create_participant( DDS_TheParticipantFactory, domainId, &DDS_PARTICIPANT_QOS_DEFAULT, NULL /* listener */, DDS_STATUS_MASK_NONE); if (participant == NULL) { printf("create_participant error\n"); publisher_shutdown(participant); return -1; } /* To customize publisher QoS, use the configuration file USER_QOS_PROFILES.xml */ publisher = DDS_DomainParticipant_create_publisher( participant, &DDS_PUBLISHER_QOS_DEFAULT, NULL /* listener */, DDS_STATUS_MASK_NONE); if (publisher == NULL) { printf("create_publisher error\n"); publisher_shutdown(participant); return -1; } /* Create ande Delete Inconsistent Topic * --------------------------------------------------------------- * Here we create an inconsistent topic to trigger the subscriber * application's callback. * The inconsistent topic is created with the topic name used in * the Subscriber application, but with a different data type -- * the msg data type defined in partitions.idl. * Once it is created, we sleep to ensure the applications discover * each other and delete the Data Writer and Topic. */ /* First we register the msg type -- we name it * inconsistent_topic_type_name to avoid confusion. */ printf("Creating Inconsistent Topic... \n"); inconsistent_topic_type_name = msgTypeSupport_get_type_name(); retcode = msgTypeSupport_register_type( participant, inconsistent_topic_type_name); if (retcode != DDS_RETCODE_OK) { printf("register_type error %d\n", retcode); publisher_shutdown(participant); return -1; } inconsistent_topic = DDS_DomainParticipant_create_topic( participant, "Example listeners", inconsistent_topic_type_name, &DDS_TOPIC_QOS_DEFAULT, NULL, DDS_STATUS_MASK_NONE); if (inconsistent_topic == NULL) { printf("create_topic error (inconsistent topic)\n"); publisher_shutdown(participant); return -1; } /* We have to associate a writer to the topic, as Topic information is not * actually propagated until the creation of an associated writer. */ inconsistent_topic_writer = DDS_Publisher_create_datawriter( publisher, inconsistent_topic, &DDS_DATAWRITER_QOS_DEFAULT, NULL /* listener */, DDS_STATUS_MASK_NONE); if (inconsistent_topic_writer == NULL) { printf("create_datawriter error\n"); publisher_shutdown(participant); return -1; } msg_writer = msgDataWriter_narrow(inconsistent_topic_writer); if (msg_writer == NULL) { printf("DataWriter narrow error\n"); publisher_shutdown(participant); return -1; } /* Sleep to leave time for applications to discover each other */ NDDS_Utility_sleep(&sleep_period); /* Before creating the "consistent" topic, we delete the Data Writer and the * inconsistent topic. */ retcode = DDS_Publisher_delete_datawriter( publisher, inconsistent_topic_writer); if (retcode != DDS_RETCODE_OK) { printf("delete_datawriter error %d\n", retcode); publisher_shutdown(participant); return -1; } retcode = DDS_DomainParticipant_delete_topic(participant, inconsistent_topic); if (retcode != DDS_RETCODE_OK) { printf("delete_topic error %d\n", retcode); publisher_shutdown(participant); return -1; } printf("... Deleted Inconsistent Topic\n\n"); /* Create Consistent Topic * ----------------------------------------------------------------- * Once we have created the inconsistent topic with the wrong type, * we create a topic with the right type name -- listeners -- that we * will use to publish data. */ /* Register type before creating topic */ type_name = listenersTypeSupport_get_type_name(); retcode = listenersTypeSupport_register_type(participant, type_name); if (retcode != DDS_RETCODE_OK) { printf("register_type error %d\n", retcode); publisher_shutdown(participant); return -1; } /* To customize topic QoS, use the configuration file USER_QOS_PROFILES.xml */ topic = DDS_DomainParticipant_create_topic( participant, "Example listeners", type_name, &DDS_TOPIC_QOS_DEFAULT, NULL /* listener */, DDS_STATUS_MASK_NONE); if (topic == NULL) { printf("create_topic error\n"); publisher_shutdown(participant); return -1; } /* We will use the Data Writer Listener defined above to print * a message when some of events are triggered in the DataWriter. * To do that, first we have to pass the writer_listener and then * we have to enable all status in the status mask. */ /* Set up participant listener */ writer_listener.on_offered_deadline_missed = DataWriterListener_on_offered_deadline_missed; writer_listener.on_liveliness_lost = DataWriterListener_on_liveliness_lost; writer_listener.on_offered_incompatible_qos = DataWriterListener_on_offered_incompatible_qos; writer_listener.on_publication_matched = DataWriterListener_on_publication_matched; writer_listener.on_reliable_writer_cache_changed = DataWriterListener_on_reliable_writer_cache_changed; writer_listener.on_reliable_reader_activity_changed = DataWriterListener_on_reliable_reader_activity_changed; writer_listener.on_sample_removed = DataWratierListener_on_sample_removed; writer_listener.on_instance_replaced = DataWratierListener_on_instance_replaced; writer_listener.on_application_acknowledgment = DataWratierListener_on_application_acknowledgment; writer_listener.on_service_request_accepted = DataWratierListener_on_service_request_accepted; writer = DDS_Publisher_create_datawriter( publisher, topic, &DDS_DATAWRITER_QOS_DEFAULT, &writer_listener /* listener */, DDS_STATUS_MASK_ALL /* enable all statuses */); if (writer == NULL) { printf("create_datawriter error\n"); publisher_shutdown(participant); return -1; } listeners_writer = listenersDataWriter_narrow(writer); if (listeners_writer == NULL) { printf("DataWriter narrow error\n"); publisher_shutdown(participant); return -1; } /* Create data sample for writing */ instance = listenersTypeSupport_create_data_ex(DDS_BOOLEAN_TRUE); if (instance == NULL) { printf("listenersTypeSupport_create_data error\n"); publisher_shutdown(participant); return -1; } /* For a data type that has a key, if the same instance is going to be written multiple times, initialize the key here and register the keyed instance prior to writing */ /* instance_handle = listenersDataWriter_register_instance( listeners_writer, instance); */ printf("Publishing data using Consinstent Topic... \n"); /* Main loop */ for (count = 0; (sample_count == 0) || (count < sample_count); ++count) { printf("Writing listeners, count %d\n", count); /* Modify the data to be written here */ instance->x = count; /* Write data */ retcode = listenersDataWriter_write( listeners_writer, instance, &instance_handle); if (retcode != DDS_RETCODE_OK) { printf("write error %d\n", retcode); } NDDS_Utility_sleep(&send_period); } /* retcode = listenersDataWriter_unregister_instance( listeners_writer, instance, &instance_handle); if (retcode != DDS_RETCODE_OK) { printf("unregister instance error %d\n", retcode); } */ /* Delete data sample */ retcode = listenersTypeSupport_delete_data_ex(instance, DDS_BOOLEAN_TRUE); if (retcode != DDS_RETCODE_OK) { printf("listenersTypeSupport_delete_data error %d\n", retcode); } /* Cleanup and delete delete all entities */ return publisher_shutdown(participant); } #if defined(RTI_WINCE) int wmain(int argc, wchar_t **argv) { int domainId = 0; int sample_count = 0; /* infinite loop */ if (argc >= 2) { domainId = _wtoi(argv[1]); } if (argc >= 3) { sample_count = _wtoi(argv[2]); } /* Uncomment this to turn on additional logging NDDS_Config_Logger_set_verbosity_by_category( NDDS_Config_Logger_get_instance(), NDDS_CONFIG_LOG_CATEGORY_API, NDDS_CONFIG_LOG_VERBOSITY_STATUS_ALL); */ return publisher_main(domainId, sample_count); } #elif !(defined(RTI_VXWORKS) && !defined(__RTP__)) && !defined(RTI_PSOS) int main(int argc, char *argv[]) { int domainId = 0; int sample_count = 0; /* infinite loop */ if (argc >= 2) { domainId = atoi(argv[1]); } if (argc >= 3) { sample_count = atoi(argv[2]); } /* Uncomment this to turn on additional logging NDDS_Config_Logger_set_verbosity_by_category( NDDS_Config_Logger_get_instance(), NDDS_CONFIG_LOG_CATEGORY_API, NDDS_CONFIG_LOG_VERBOSITY_STATUS_ALL); */ return publisher_main(domainId, sample_count); } #endif #ifdef RTI_VX653 const unsigned char *__ctype = NULL; void usrAppInit() { #ifdef USER_APPL_INIT USER_APPL_INIT; /* for backwards compatibility */ #endif /* add application specific code here */ taskSpawn( "pub", RTI_OSAPI_THREAD_PRIORITY_NORMAL, 0x8, 0x150000, (FUNCPTR) publisher_main, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0); } #endif
c
rticonnextdds-examples
data/projects/rticonnextdds-examples/connext_dds/listeners/c++03/listeners_publisher.cxx
/******************************************************************************* (c) 2005-2015 Copyright, Real-Time Innovations, Inc. All rights reserved. RTI grants Licensee a license to use, modify, compile, and create derivative works of the Software. Licensee has the right to distribute object form only for use with RTI products. The Software is provided "as is", with no warranty of any type, including any warranty for fitness for any purpose. RTI is under no obligation to maintain or support the Software. RTI shall not be liable for any incidental or consequential damages arising out of the use or inability to use the software. ******************************************************************************/ #include <iostream> #include "listeners.hpp" #include <dds/dds.hpp> #include <rti/core/ListenerBinder.hpp> using namespace dds::core; using namespace dds::domain; using namespace dds::pub; using namespace dds::topic; class MyDataWriterListener : public NoOpDataWriterListener<listeners> { public: virtual void on_offered_deadline_missed( dds::pub::DataWriter<listeners> &writer, const dds::core::status::OfferedDeadlineMissedStatus &status) { std::cout << "DataWriterListener: on_offered_deadline_missed()" << std::endl; } virtual void on_liveliness_lost( dds::pub::DataWriter<listeners> &writer, const dds::core::status::LivelinessLostStatus &status) { std::cout << "DataWriterListener: on_liveliness_lost()" << std::endl; } virtual void on_offered_incompatible_qos( dds::pub::DataWriter<listeners> &writer, const dds::core::status::OfferedIncompatibleQosStatus &status) { std::cout << "DataWriterListener: on_offered_incompatible_qos()" << std::endl; } virtual void on_publication_matched( dds::pub::DataWriter<listeners> &writer, const dds::core::status::PublicationMatchedStatus &status) { std::cout << "DataWriterListener: on_publication_matched()" << std::endl; if (status.current_count_change() < 0) { std::cout << "lost a subscription" << std::endl; } else { std::cout << "found a subscription" << std::endl; } } virtual void on_reliable_writer_cache_changed( dds::pub::DataWriter<listeners> &writer, const rti::core::status::ReliableWriterCacheChangedStatus &status) { std::cout << "DataWriterListener: on_reliable_writer_cache_changed()" << std::endl; } virtual void on_reliable_reader_activity_changed( dds::pub::DataWriter<listeners> &writer, const rti::core::status::ReliableReaderActivityChangedStatus &status) { std::cout << "DataWriterListener: on_reliable_reader_activity_changed()" << std::endl; } }; void publisher_main(int domain_id, int sample_count) { // Create the participant. // To customize QoS, use the configuration file USER_QOS_PROFILES.xml DomainParticipant participant(domain_id); // Create the publisher // To customize QoS, use the configuration file USER_QOS_PROFILES.xml Publisher publisher(participant); // Create ande Delete Inconsistent Topic // --------------------------------------------------------------- // Here we create an inconsistent topic to trigger the subscriber // application's callback. // The inconsistent topic is created with the topic name used in // the Subscriber application, but with a different data type -- // the msg data type defined in listener.idl. // Once it is created, we sleep to ensure the applications discover // each other and delete the Data Writer and Topic. std::cout << "Creating Inconsistent Topic..." << std::endl; Topic<msg> inconsistent_topic(participant, "Example listeners"); // We have to associate a writer to the topic, as Topic information is not // actually propagated until the creation of an associated writer. DataWriter<msg> inconsistent_writer(publisher, inconsistent_topic); // Sleep to leave time for applications to discover each other. rti::util::sleep(Duration(2)); inconsistent_writer.close(); inconsistent_topic.close(); std::cout << "... Deleted Incosistent Topic" << std::endl << std::endl; // Create Consistent Topic // ----------------------------------------------------------------- // Once we have created the inconsistent topic with the wrong type, // we create a topic with the right type name -- listeners -- that we // will use to publish data. Topic<listeners> topic(participant, "Example listeners"); // We will use the Data Writer Listener defined above to print // a message when some of events are triggered in the DataWriter. // By using ListenerBinder (a RAII) it will take care of setting the // listener to NULL on destruction. DataWriter<listeners> writer(publisher, topic); rti::core::ListenerBinder<DataWriter<listeners> > writer_listener = rti::core::bind_and_manage_listener( writer, new MyDataWriterListener, dds::core::status::StatusMask::all()); // Create data sample for writing listeners instance; // Main loop for (int count = 0; (sample_count == 0) || (count < sample_count); ++count) { std::cout << "Writing listeners, count " << count << std::endl; // Modify data and send it. instance.x(count); writer.write(instance); rti::util::sleep(Duration(2)); } } int main(int argc, char *argv[]) { int domain_id = 0; int sample_count = 0; // Infinite loop if (argc >= 2) { domain_id = atoi(argv[1]); } if (argc >= 3) { sample_count = atoi(argv[2]); } // To turn on additional logging, include <rti/config/Logger.hpp> and // uncomment the following line: // rti::config::Logger::instance().verbosity(rti::config::Verbosity::STATUS_ALL); try { publisher_main(domain_id, sample_count); } catch (std::exception ex) { std::cout << "Exception caught: " << ex.what() << std::endl; return -1; } return 0; }
cxx
rticonnextdds-examples
data/projects/rticonnextdds-examples/connext_dds/listeners/c++03/listeners_subscriber.cxx
/******************************************************************************* (c) 2005-2015 Copyright, Real-Time Innovations, Inc. All rights reserved. RTI grants Licensee a license to use, modify, compile, and create derivative works of the Software. Licensee has the right to distribute object form only for use with RTI products. The Software is provided "as is", with no warranty of any type, including any warranty for fitness for any purpose. RTI is under no obligation to maintain or support the Software. RTI shall not be liable for any incidental or consequential damages arising out of the use or inability to use the software. ******************************************************************************/ #include <iostream> #include "listeners.hpp" #include <dds/dds.hpp> #include <rti/core/ListenerBinder.hpp> using namespace dds::core; using namespace rti::core; using namespace dds::core::status; using namespace dds::domain; using namespace dds::sub; using namespace dds::topic; class MyParticipantListener : public NoOpDomainParticipantListener { public: virtual void on_requested_deadline_missed( dds::pub::AnyDataWriter &writer, const dds::core::status::OfferedDeadlineMissedStatus &status) { std::cout << "ParticipantListener: on_requested_deadline_missed()" << std::endl; } virtual void on_offered_incompatible_qos( dds::pub::AnyDataWriter &writer, const ::dds::core::status::OfferedIncompatibleQosStatus &status) { std::cout << "ParticipantListener: on_offered_incompatible_qos()" << std::endl; } virtual void on_sample_rejected( dds::sub::AnyDataReader &the_reader, const dds::core::status::SampleRejectedStatus &status) { std::cout << "ParticipantListener: on_sample_rejected()" << std::endl; } virtual void on_liveliness_changed( dds::sub::AnyDataReader &the_reader, const dds::core::status::LivelinessChangedStatus &status) { std::cout << "ParticipantListener: on_liveliness_changed()" << std::endl; } virtual void on_sample_lost( dds::sub::AnyDataReader &the_reader, const dds::core::status::SampleLostStatus &status) { std::cout << "ParticipantListener: on_sample_lost()" << std::endl; } virtual void on_subscription_matched( dds::sub::AnyDataReader &the_reader, const dds::core::status::SubscriptionMatchedStatus &status) { std::cout << "ParticipantListener: on_subscription_matched()" << std::endl; } virtual void on_data_available(dds::sub::AnyDataReader &the_reader) { std::cout << "ParticipantListener: on_data_available()" << std::endl; } virtual void on_data_on_readers(dds::sub::Subscriber &sub) { // Notify DataReaders only calls on_data_available for // DataReaders with unread samples. sub.notify_datareaders(); std::cout << "ParticipantListener: on_data_on_readers()" << std::endl; } virtual void on_inconsistent_topic( dds::topic::AnyTopic &topic, const dds::core::status::InconsistentTopicStatus &status) { std::cout << "ParticipantListener: on_inconsistent_topic()" << std::endl; } }; class MySubscriberListener : public NoOpSubscriberListener { public: virtual void on_requested_deadline_missed( AnyDataReader &the_reader, const dds::core::status::RequestedDeadlineMissedStatus &status) { std::cout << "SubscriberListener: on_requested_deadline_missed()" << std::endl; } virtual void on_requested_incompatible_qos( AnyDataReader &the_reader, const dds::core::status::RequestedIncompatibleQosStatus &status) { std::cout << "SubscriberListener: on_requested_incompatible_qos()" << std::endl; } virtual void on_sample_rejected( AnyDataReader &the_reader, const dds::core::status::SampleRejectedStatus &status) { std::cout << "SubscriberListener: on_sample_rejected()" << std::endl; } virtual void on_liveliness_changed( AnyDataReader &the_reader, const dds::core::status::LivelinessChangedStatus &status) { std::cout << "SubscriberListener: on_liveliness_changed()" << std::endl; } virtual void on_sample_lost( AnyDataReader &the_reader, const dds::core::status::SampleLostStatus &status) { std::cout << "SubscriberListener: on_sample_lost()" << std::endl; } virtual void on_subscription_matched( AnyDataReader &the_reader, const dds::core::status::SubscriptionMatchedStatus &status) { std::cout << "SubscriberListener: on_subscription_matched()" << std::endl; } virtual void on_data_available(AnyDataReader &the_reader) { std::cout << "SubscriberListener: on_data_available()" << std::endl; } virtual void on_data_on_readers(Subscriber &sub) { static int count = 0; std::cout << "SubscriberListener: on_data_on_readers()" << std::endl; sub->notify_datareaders(); if (++count > 3) { StatusMask new_mask = StatusMask::all(); new_mask &= ~StatusMask::data_on_readers(); sub.listener(this, new_mask); } } }; class MyDataReaderListener : public NoOpDataReaderListener<listeners> { virtual void on_requested_deadline_missed( DataReader<listeners> &reader, const dds::core::status::RequestedDeadlineMissedStatus &status) { std::cout << "ReaderListener: on_requested_deadline_missed()" << std::endl; } virtual void on_requested_incompatible_qos( DataReader<listeners> &reader, const dds::core::status::RequestedIncompatibleQosStatus &status) { std::cout << "ReaderListener: on_requested_incompatible_qos()" << std::endl; } virtual void on_sample_rejected( DataReader<listeners> &reader, const dds::core::status::SampleRejectedStatus &status) { std::cout << "ReaderListener: on_sample_rejected()" << std::endl; } virtual void on_liveliness_changed( DataReader<listeners> &reader, const dds::core::status::LivelinessChangedStatus &status) { std::cout << "ReaderListener: on_liveliness_changed()" << std::endl << " Alive writers: " << status.alive_count() << std::endl; } virtual void on_sample_lost( DataReader<listeners> &reader, const dds::core::status::SampleLostStatus &status) { std::cout << "ReaderListener: on_sample_lost()" << std::endl; } virtual void on_subscription_matched( DataReader<listeners> &reader, const dds::core::status::SubscriptionMatchedStatus &status) { std::cout << "ReaderListener: on_subscription_matched()" << std::endl; } virtual void on_data_available(DataReader<listeners> &reader) { LoanedSamples<listeners> samples = reader.take(); for (LoanedSamples<listeners>::iterator sampleIt = samples.begin(); sampleIt != samples.end(); ++sampleIt) { // If the reference we get is valid data, it means we have actual // data available, otherwise we got metadata. if (sampleIt->info().valid()) { std::cout << sampleIt->data() << std::endl; } else { std::cout << " Got metadata" << std::endl; } } } }; void subscriber_main(int domain_id, int sample_count) { // Create the participant DomainParticipant participant(domain_id); // Associate a listener to the participant using ListenerBinder, a RAII that // will take care of setting it to NULL on destruction. ListenerBinder<DomainParticipant> participant_listener = rti::core::bind_and_manage_listener( participant, new MyParticipantListener, dds::core::status::StatusMask::all()); // To customize topic QoS, use the configuration file USER_QOS_PROFILES.xml Topic<listeners> topic(participant, "Example listeners"); // Create the subscriber and associate a listener Subscriber subscriber(participant); ListenerBinder<Subscriber> subscriber_listener = rti::core::bind_and_manage_listener( subscriber, new MySubscriberListener, dds::core::status::StatusMask::all()); // Create the DataReader and associate a listener DataReader<listeners> reader(subscriber, topic); ListenerBinder<DataReader<listeners> > datareader_listener = rti::core::bind_and_manage_listener( reader, new MyDataReaderListener, dds::core::status::StatusMask::all()); // Main loop for (int count = 0; (sample_count == 0) || (count < sample_count); ++count) { // Each "sample_count" is four seconds. rti::util::sleep(Duration(4)); } } int main(int argc, char *argv[]) { int domain_id = 0; int sample_count = 0; // Infinite loop if (argc >= 2) { domain_id = atoi(argv[1]); } if (argc >= 3) { sample_count = atoi(argv[2]); } // To turn on additional logging, include <rti/config/Logger.hpp> and // uncomment the following line: // rti::config::Logger::instance().verbosity(rti::config::Verbosity::STATUS_ALL); try { subscriber_main(domain_id, sample_count); } catch (std::exception ex) { std::cout << "Exception caught: " << ex.what() << std::endl; return -1; } return 0; }
cxx
rticonnextdds-examples
data/projects/rticonnextdds-examples/connext_dds/listeners/c++11/listeners_publisher.cxx
/******************************************************************************* (c) 2005-2015 Copyright, Real-Time Innovations, Inc. All rights reserved. RTI grants Licensee a license to use, modify, compile, and create derivative works of the Software. Licensee has the right to distribute object form only for use with RTI products. The Software is provided "as is", with no warranty of any type, including any warranty for fitness for any purpose. RTI is under no obligation to maintain or support the Software. RTI shall not be liable for any incidental or consequential damages arising out of the use or inability to use the software. ******************************************************************************/ #include <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 "listeners.hpp" class MyDataWriterListener : public dds::pub::NoOpDataWriterListener<listeners> { public: virtual void on_offered_deadline_missed( dds::pub::DataWriter<listeners> &writer, const dds::core::status::OfferedDeadlineMissedStatus &status) { std::cout << "DataWriterListener: on_offered_deadline_missed()" << std::endl; } virtual void on_liveliness_lost( dds::pub::DataWriter<listeners> &writer, const dds::core::status::LivelinessLostStatus &status) { std::cout << "DataWriterListener: on_liveliness_lost()" << std::endl; } virtual void on_offered_incompatible_qos( dds::pub::DataWriter<listeners> &writer, const dds::core::status::OfferedIncompatibleQosStatus &status) { std::cout << "DataWriterListener: on_offered_incompatible_qos()" << std::endl; } virtual void on_publication_matched( dds::pub::DataWriter<listeners> &writer, const dds::core::status::PublicationMatchedStatus &status) { std::cout << "DataWriterListener: on_publication_matched()" << std::endl; if (status.current_count_change() < 0) { std::cout << "lost a subscription" << std::endl; } else { std::cout << "found a subscription" << std::endl; } } virtual void on_reliable_writer_cache_changed( dds::pub::DataWriter<listeners> &writer, const rti::core::status::ReliableWriterCacheChangedStatus &status) { std::cout << "DataWriterListener: on_reliable_writer_cache_changed()" << std::endl; } virtual void on_reliable_reader_activity_changed( dds::pub::DataWriter<listeners> &writer, const rti::core::status::ReliableReaderActivityChangedStatus &status) { std::cout << "DataWriterListener: on_reliable_reader_activity_changed()" << std::endl; } }; void run_publisher_application( unsigned int domain_id, unsigned int sample_count) { // Create the participant. // To customize QoS, use the configuration file USER_QOS_PROFILES.xml dds::domain::DomainParticipant participant(domain_id); // Create the publisher // To customize QoS, use the configuration file USER_QOS_PROFILES.xml dds::pub::Publisher publisher(participant); // Create ande Delete Inconsistent Topic // --------------------------------------------------------------- // Here we create an inconsistent topic to trigger the subscriber // application's callback. // The inconsistent topic is created with the topic name used in // the Subscriber application, but with a different data type -- // the msg data type defined in listener.idl. // Once it is created, we sleep to ensure the applications discover // each other and delete the Data Writer and Topic. std::cout << "Creating Inconsistent Topic..." << std::endl; dds::topic::Topic<msg> inconsistent_topic(participant, "Example listeners"); // We have to associate a writer to the topic, as Topic information is not // actually propagated until the creation of an associated writer. dds::pub::DataWriter<msg> inconsistent_writer( publisher, inconsistent_topic); // Sleep to leave time for applications to discover each other. rti::util::sleep(dds::core::Duration(2)); inconsistent_writer.close(); inconsistent_topic.close(); std::cout << "... Deleted Incosistent Topic" << std::endl << std::endl; // Create Consistent Topic // ----------------------------------------------------------------- // Once we have created the inconsistent topic with the wrong type, // we create a topic with the right type name -- listeners -- that we // will use to publish data. dds::topic::Topic<listeners> topic(participant, "Example listeners"); // Create a shared pointer for the Data Writer Listener defined above auto dw_listener = std::make_shared<MyDataWriterListener>(); // We will use the Data Writer Listener defined above to print // a message when some of events are triggered in the DataWriter. // By using shared_pointer it will take care of setting the // listener to NULL on destruction. dds::pub::DataWriter<listeners> writer(publisher, topic); writer.set_listener(dw_listener); // Create data sample for writing listeners instance; // Main loop for (unsigned int samples_written = 0; !application::shutdown_requested && samples_written < sample_count; samples_written++) { std::cout << "Writing listeners, count " << samples_written << std::endl; // Modify data and send it. instance.x(samples_written); writer.write(instance); rti::util::sleep(dds::core::Duration(2)); } } int main(int argc, char *argv[]) { using namespace application; // Parse arguments and handle control-C auto arguments = parse_arguments(argc, argv); if (arguments.parse_result == ParseReturn::exit) { return EXIT_SUCCESS; } else if (arguments.parse_result == ParseReturn::failure) { return EXIT_FAILURE; } setup_signal_handlers(); // Sets Connext verbosity to help debugging rti::config::Logger::instance().verbosity(arguments.verbosity); try { run_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/listeners/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/listeners/c++11/listeners_subscriber.cxx
/******************************************************************************* (c) 2005-2015 Copyright, Real-Time Innovations, Inc. All rights reserved. RTI grants Licensee a license to use, modify, compile, and create derivative works of the Software. Licensee has the right to distribute object form only for use with RTI products. The Software is provided "as is", with no warranty of any type, including any warranty for fitness for any purpose. RTI is under no obligation to maintain or support the Software. RTI shall not be liable for any incidental or consequential damages arising out of the use or inability to use the software. ******************************************************************************/ #include <dds/sub/ddssub.hpp> #include <dds/core/ddscore.hpp> #include <rti/util/util.hpp> // for sleep() #include <rti/config/Logger.hpp> // for logging #include "listeners.hpp" #include "application.hpp" // for command line parsing and ctrl-c class MyParticipantListener : public dds::domain::NoOpDomainParticipantListener { public: virtual void on_requested_deadline_missed( dds::pub::AnyDataWriter &writer, const dds::core::status::OfferedDeadlineMissedStatus &status) { std::cout << "ParticipantListener: on_requested_deadline_missed()" << std::endl; } virtual void on_offered_incompatible_qos( dds::pub::AnyDataWriter &writer, const ::dds::core::status::OfferedIncompatibleQosStatus &status) { std::cout << "ParticipantListener: on_offered_incompatible_qos()" << std::endl; } virtual void on_sample_rejected( dds::sub::AnyDataReader &the_reader, const dds::core::status::SampleRejectedStatus &status) { std::cout << "ParticipantListener: on_sample_rejected()" << std::endl; } virtual void on_liveliness_changed( dds::sub::AnyDataReader &the_reader, const dds::core::status::LivelinessChangedStatus &status) { std::cout << "ParticipantListener: on_liveliness_changed()" << std::endl; } virtual void on_sample_lost( dds::sub::AnyDataReader &the_reader, const dds::core::status::SampleLostStatus &status) { std::cout << "ParticipantListener: on_sample_lost()" << std::endl; } virtual void on_subscription_matched( dds::sub::AnyDataReader &the_reader, const dds::core::status::SubscriptionMatchedStatus &status) { std::cout << "ParticipantListener: on_subscription_matched()" << std::endl; } virtual void on_data_available(dds::sub::AnyDataReader &the_reader) { std::cout << "ParticipantListener: on_data_available()" << std::endl; } virtual void on_data_on_readers(dds::sub::Subscriber &sub) { // Notify DataReaders only calls on_data_available for // DataReaders with unread samples. sub.notify_datareaders(); std::cout << "ParticipantListener: on_data_on_readers()" << std::endl; } virtual void on_inconsistent_topic( dds::topic::AnyTopic &topic, const dds::core::status::InconsistentTopicStatus &status) { std::cout << "ParticipantListener: on_inconsistent_topic()" << std::endl; } }; class MySubscriberListener : public dds::sub::NoOpSubscriberListener, public std::enable_shared_from_this<MySubscriberListener> { public: virtual void on_requested_deadline_missed( dds::sub::AnyDataReader &the_reader, const dds::core::status::RequestedDeadlineMissedStatus &status) { std::cout << "SubscriberListener: on_requested_deadline_missed()" << std::endl; } virtual void on_requested_incompatible_qos( dds::sub::AnyDataReader &the_reader, const dds::core::status::RequestedIncompatibleQosStatus &status) { std::cout << "SubscriberListener: on_requested_incompatible_qos()" << std::endl; } virtual void on_sample_rejected( dds::sub::AnyDataReader &the_reader, const dds::core::status::SampleRejectedStatus &status) { std::cout << "SubscriberListener: on_sample_rejected()" << std::endl; } virtual void on_liveliness_changed( dds::sub::AnyDataReader &the_reader, const dds::core::status::LivelinessChangedStatus &status) { std::cout << "SubscriberListener: on_liveliness_changed()" << std::endl; } virtual void on_sample_lost( dds::sub::AnyDataReader &the_reader, const dds::core::status::SampleLostStatus &status) { std::cout << "SubscriberListener: on_sample_lost()" << std::endl; } virtual void on_subscription_matched( dds::sub::AnyDataReader &the_reader, const dds::core::status::SubscriptionMatchedStatus &status) { std::cout << "SubscriberListener: on_subscription_matched()" << std::endl; } virtual void on_data_available(dds::sub::AnyDataReader &the_reader) { std::cout << "SubscriberListener: on_data_available()" << std::endl; } virtual void on_data_on_readers(dds::sub::Subscriber &sub) { static int count = 0; std::cout << "SubscriberListener: on_data_on_readers()" << std::endl; sub->notify_datareaders(); if (++count > 3) { auto subscriber_listener = shared_from_this(); dds::core::status::StatusMask new_mask = dds::core::status::StatusMask::all(); new_mask &= ~dds::core::status::StatusMask::data_on_readers(); sub.set_listener(subscriber_listener, new_mask); } } }; class MyDataReaderListener : public dds::sub::NoOpDataReaderListener<listeners> { virtual void on_requested_deadline_missed( dds::sub::DataReader<listeners> &reader, const dds::core::status::RequestedDeadlineMissedStatus &status) { std::cout << "ReaderListener: on_requested_deadline_missed()" << std::endl; } virtual void on_requested_incompatible_qos( dds::sub::DataReader<listeners> &reader, const dds::core::status::RequestedIncompatibleQosStatus &status) { std::cout << "ReaderListener: on_requested_incompatible_qos()" << std::endl; } virtual void on_sample_rejected( dds::sub::DataReader<listeners> &reader, const dds::core::status::SampleRejectedStatus &status) { std::cout << "ReaderListener: on_sample_rejected()" << std::endl; } virtual void on_liveliness_changed( dds::sub::DataReader<listeners> &reader, const dds::core::status::LivelinessChangedStatus &status) { std::cout << "ReaderListener: on_liveliness_changed()" << std::endl << " Alive writers: " << status.alive_count() << std::endl; } virtual void on_sample_lost( dds::sub::DataReader<listeners> &reader, const dds::core::status::SampleLostStatus &status) { std::cout << "ReaderListener: on_sample_lost()" << std::endl; } virtual void on_subscription_matched( dds::sub::DataReader<listeners> &reader, const dds::core::status::SubscriptionMatchedStatus &status) { std::cout << "ReaderListener: on_subscription_matched()" << std::endl; } virtual void on_data_available(dds::sub::DataReader<listeners> &reader) { dds::sub::LoanedSamples<listeners> samples = reader.take(); for (const auto &sample : samples) { // If the reference we get is valid data, it means we have actual // data available, otherwise we got metadata. if (sample.info().valid()) { std::cout << sample.data() << std::endl; } else { std::cout << " Got metadata" << std::endl; } } } }; void run_subscriber_application( unsigned int domain_id, unsigned int sample_count) { // Create a shared pointer for the Participant Listener auto participant_listener = std::make_shared<MyParticipantListener>(); // Create the participant dds::domain::DomainParticipant participant(domain_id); // Associate a listener to the participant using a shared pointer. It // will take care of setting it to NULL on destruction. participant.set_listener(participant_listener); // To customize topic QoS, use the configuration file USER_QOS_PROFILES.xml dds::topic::Topic<listeners> topic(participant, "Example listeners"); // Create the subscriber and associate a listener dds::sub::Subscriber subscriber(participant); auto subscriber_listener = std::make_shared<MySubscriberListener>(); subscriber.set_listener(subscriber_listener); // Create the DataReader and associate a listener dds::sub::DataReader<listeners> reader(subscriber, topic); auto dw_listener = std::make_shared<MyDataReaderListener>(); reader.set_listener(dw_listener); // Main loop for (int count = 0; !application::shutdown_requested && (count < sample_count); ++count) { // Each "sample_count" is four seconds. 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_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/compression/c++/compression_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 "compression.h" #include "compressionSupport.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(StringLineDataReader *typed_reader) { StringLineSeq 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) { // Uncomment if you want to print the received data. // std::cout << "Received data" << std::endl; // StringLineTypeSupport::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 = StringLineTypeSupport::get_type_name(); DDS_ReturnCode_t retcode = StringLineTypeSupport::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 StringLine", 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 StringLine" Topic DDSDataReader *untyped_reader = subscriber->create_datareader( topic, DDS_DATAREADER_QOS_DEFAULT, NULL, DDS_STATUS_MASK_NONE); if (untyped_reader == NULL) { return shutdown_participant(participant, "create_datareader error", EXIT_FAILURE); } // Narrow casts from a untyped DataReader to a reader of your type StringLineDataReader *typed_reader = StringLineDataReader::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); if (!(samples_read%10)) { std::cout << "Received " << samples_read << " samples." << std::endl; } } else { if (retcode == DDS_RETCODE_TIMEOUT) { std::cout << "No data after 1 second" << std::endl; } } } struct NDDS_Transport_UDPv4_Statistics subParticipantUdpStats; retcode = NDDS_Transport_Support_get_udpv4_statistics( participant->get_c_domain_participantI(), &subParticipantUdpStats); if (retcode != DDS_RETCODE_OK) { std::cout << "Failed reading Udp Statistic" << std::endl; } struct DDS_DataReaderCacheStatus cacheStatus = DDS_DataReaderCacheStatus_INITIALIZER; untyped_reader->get_datareader_cache_status(cacheStatus); std::cout << std::endl << "--> Read: " << samples_read << " samples from witch " << cacheStatus.compressed_sample_count << " has been compressed" << std::endl; std::cout << std::endl << "--> User Bytes received: " << subParticipantUdpStats.user_bytes_received << 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/compression/c++/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 << std::endl << "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; std::string compression_id; std::string input_file; 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], "-c") == 0 || strcmp(argv[arg_processing], "--compression-id") == 0)) { arguments.compression_id = (argv[arg_processing + 1]); arg_processing += 2; } else if ((argc > arg_processing + 1) && (strcmp(argv[arg_processing], "-i") == 0 || strcmp(argv[arg_processing], "--input-file") == 0)) { arguments.input_file = (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" " -c, --compression-id <string> Enable or disable compression with\n" " a given compression algorithm. \n" " Accepted values: NONE, LZ4, ZLIB, BZIP2\n" " Default: LZ4\n" " -i, --input-file <string> Path to the file to read. The file\n" " will be read line by line (each line\n" " represent a sample). If no file is\n" " given a 1K sample filled with zeros\n" " will be sent\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/compression/c++/compression_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 <fstream> #include <iostream> #include <stdio.h> #include <stdlib.h> #include <vector> #include "compression.h" #include "compressionSupport.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, const std::string &compression_id, const std::string &input_file) { // 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 = StringLineTypeSupport::get_type_name(); DDS_ReturnCode_t retcode = StringLineTypeSupport::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 StringLine", 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_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; } if (compression_id.find("NONE") != std::string::npos) { datawriter_qos.representation.compression_settings.compression_ids = DDS_COMPRESSION_ID_MASK_NONE; } if (compression_id.find("ZLIB") != std::string::npos) { datawriter_qos.representation.compression_settings.compression_ids = DDS_COMPRESSION_ID_ZLIB_BIT; } if (compression_id.find("BZIP2") != std::string::npos) { datawriter_qos.representation.compression_settings.compression_ids = DDS_COMPRESSION_ID_BZIP2_BIT; } if (compression_id.find("LZ4") != std::string::npos) { datawriter_qos.representation.compression_settings.compression_ids = DDS_COMPRESSION_ID_LZ4_BIT; } // This DataWriter writes data on "Example StringLine" Topic DDSDataWriter *untyped_writer = publisher->create_datawriter( topic, datawriter_qos, 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 StringLineDataWriter *typed_writer = StringLineDataWriter::narrow(untyped_writer); if (typed_writer == NULL) { return shutdown_participant(participant, "DataWriter narrow error", EXIT_FAILURE); } std::vector<StringLine> samples; if (!input_file.empty()) { // Open file to compress std::ifstream fileToCompress(input_file.c_str()); if (!fileToCompress) { printf("open file %s error\n", input_file.c_str()); return -1; } std::string new_line; while (!std::getline(fileToCompress,new_line).eof()) { StringLine new_sample; new_sample.str = DDS_String_dup(new_line.c_str()); samples.push_back(new_sample); } } else { // Create a sample fill with 1024 zeros to send if no file has been provided StringLine new_sample; new_sample.str = DDS_String_dup(std::string(1024,'0').c_str()); samples.push_back(new_sample); } // Wait at least 1 second for discovery DDS_Duration_t discovery_period = { 1, 0 }; NDDSUtility::sleep(discovery_period); std::vector<StringLine>::iterator it = samples.begin(); // Main loop, write data for (unsigned int samples_written = 0; !shutdown_requested && samples_written < sample_count; ++samples_written, ++it) { /* Loop over the lines on the file */ if (it==samples.end()) { it = samples.begin(); } if (!(samples_written%10)) { std::cout << "Writing StringLine, count " << samples_written << std::endl; } retcode = typed_writer->write((*it), DDS_HANDLE_NIL); if (retcode != DDS_RETCODE_OK) { std::cerr << "write error " << retcode << std::endl; } // Send once every 100 millisec DDS_Duration_t send_period = { 0, 100000 }; NDDSUtility::sleep(send_period); } for (std::vector<StringLine>::iterator it = samples.begin() ; it != samples.end(); ++it) { // Delete previously allocated strings DDS_String_free((*it).str); } // 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.compression_id, arguments.input_file); // 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/compression/c++98/compression_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 "compression.h" #include "compressionSupport.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(StringLineDataReader *typed_reader) { StringLineSeq 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) { // Uncomment if you want to print the received data. // std::cout << "Received data" << std::endl; // StringLineTypeSupport::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 = StringLineTypeSupport::get_type_name(); DDS_ReturnCode_t retcode = StringLineTypeSupport::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 StringLine", 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 StringLine" Topic DDSDataReader *untyped_reader = subscriber->create_datareader( topic, DDS_DATAREADER_QOS_DEFAULT, NULL, DDS_STATUS_MASK_NONE); if (untyped_reader == NULL) { return shutdown_participant( participant, "create_datareader error", EXIT_FAILURE); } // Narrow casts from a untyped DataReader to a reader of your type StringLineDataReader *typed_reader = StringLineDataReader::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); if (!(samples_read % 10)) { std::cout << "Received " << samples_read << " samples." << std::endl; } } else { if (retcode == DDS_RETCODE_TIMEOUT) { std::cout << "No data after 1 second" << std::endl; } } } struct NDDS_Transport_UDPv4_Statistics subParticipantUdpStats; retcode = NDDS_Transport_Support_get_udpv4_statistics( participant->get_c_domain_participantI(), &subParticipantUdpStats); if (retcode != DDS_RETCODE_OK) { std::cout << "Failed reading Udp Statistic" << std::endl; } struct DDS_DataReaderCacheStatus cacheStatus = DDS_DataReaderCacheStatus_INITIALIZER; untyped_reader->get_datareader_cache_status(cacheStatus); std::cout << std::endl << "--> Read: " << samples_read << " samples from witch " << cacheStatus.compressed_sample_count << " has been compressed" << std::endl; std::cout << std::endl << "--> User Bytes received: " << subParticipantUdpStats.user_bytes_received << 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/compression/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 << std::endl << "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; std::string compression_id; std::string input_file; 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], "-c") == 0 || strcmp(argv[arg_processing], "--compression-id") == 0)) { arguments.compression_id = (argv[arg_processing + 1]); arg_processing += 2; } else if ( (argc > arg_processing + 1) && (strcmp(argv[arg_processing], "-i") == 0 || strcmp(argv[arg_processing], "--input-file") == 0)) { arguments.input_file = (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" " -c, --compression-id <string> Enable or disable " "compression with\n" " a given compression " "algorithm. \n" " Accepted values: NONE, " "LZ4, ZLIB, BZIP2\n" " Default: LZ4\n" " -i, --input-file <string> Path to the file to read. " "The file\n" " will be read line by line " "(each line\n" " represent a sample). If " "no file is\n" " given a 1K sample filled " "with zeros\n" " will be sent\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/compression/c++98/compression_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 <fstream> #include <iostream> #include <stdio.h> #include <stdlib.h> #include <vector> #include "compression.h" #include "compressionSupport.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, const std::string &compression_id, const std::string &input_file) { // 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 = StringLineTypeSupport::get_type_name(); DDS_ReturnCode_t retcode = StringLineTypeSupport::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 StringLine", 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_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; } if (compression_id.find("NONE") != std::string::npos) { datawriter_qos.representation.compression_settings.compression_ids = DDS_COMPRESSION_ID_MASK_NONE; } if (compression_id.find("ZLIB") != std::string::npos) { datawriter_qos.representation.compression_settings.compression_ids = DDS_COMPRESSION_ID_ZLIB_BIT; } if (compression_id.find("BZIP2") != std::string::npos) { datawriter_qos.representation.compression_settings.compression_ids = DDS_COMPRESSION_ID_BZIP2_BIT; } if (compression_id.find("LZ4") != std::string::npos) { datawriter_qos.representation.compression_settings.compression_ids = DDS_COMPRESSION_ID_LZ4_BIT; } // This DataWriter writes data on "Example StringLine" Topic DDSDataWriter *untyped_writer = publisher->create_datawriter( topic, datawriter_qos, 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 StringLineDataWriter *typed_writer = StringLineDataWriter::narrow(untyped_writer); if (typed_writer == NULL) { return shutdown_participant( participant, "DataWriter narrow error", EXIT_FAILURE); } std::vector<StringLine> samples; if (!input_file.empty()) { // Open file to compress std::ifstream fileToCompress(input_file.c_str()); if (!fileToCompress) { printf("open file %s error\n", input_file.c_str()); return -1; } std::string new_line; while (!std::getline(fileToCompress, new_line).eof()) { StringLine new_sample; new_sample.str = DDS_String_dup(new_line.c_str()); samples.push_back(new_sample); } } else { // Create a sample fill with 1024 zeros to send if no file has been // provided StringLine new_sample; new_sample.str = DDS_String_dup(std::string(1024, '0').c_str()); samples.push_back(new_sample); } // Wait at least 1 second for discovery DDS_Duration_t discovery_period = { 1, 0 }; NDDSUtility::sleep(discovery_period); std::vector<StringLine>::iterator it = samples.begin(); // Main loop, write data for (unsigned int samples_written = 0; !shutdown_requested && samples_written < sample_count; ++samples_written, ++it) { /* Loop over the lines on the file */ if (it == samples.end()) { it = samples.begin(); } if (!(samples_written % 10)) { std::cout << "Writing StringLine, count " << samples_written << std::endl; } retcode = typed_writer->write((*it), DDS_HANDLE_NIL); if (retcode != DDS_RETCODE_OK) { std::cerr << "write error " << retcode << std::endl; } // Send once every 100 millisec DDS_Duration_t send_period = { 0, 100000 }; NDDSUtility::sleep(send_period); } for (std::vector<StringLine>::iterator it = samples.begin(); it != samples.end(); ++it) { // Delete previously allocated strings DDS_String_free((*it).str); } // 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.compression_id, arguments.input_file); // 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/logging_config/c++/logging_publisher.cxx
/* * (c) Copyright, Real-Time Innovations, 2021. All rights reserved. * RTI grants Licensee a license to use, modify, compile, and create derivative * works of the software solely for use with RTI Connext DDS. Licensee may * redistribute copies of the software provided that all such copies are subject * to this license. The software is provided "as is", with no warranty of any * type, including any warranty for fitness for any purpose. RTI is under no * obligation to maintain or support the software. RTI shall not be liable for * any incidental or consequential damages arising out of the use or inability * to use the software. */ #include <iostream> #include <stdio.h> #include <stdlib.h> #include "logging.h" #include "loggingSupport.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); } /* * Start - modifying the generated example to showcase the usage of * the Logging API. */ /* * Set NDDS_CONFIG_LOG_VERBOSITY_WARNING NDDS_Config_LogVerbosity. * Set NDDS_CONFIG_LOG_PRINT_FORMAT_MAXIMAL NDDS_Config_LogPrintFormat * for NDDS_CONFIG_LOG_LEVEL_WARNING. */ NDDSConfigLogger *logger = NULL; logger = NDDSConfigLogger::get_instance(); if (logger == NULL) { return shutdown_participant( participant, "loggingTypeSupport::NDDSConfigLogger::get_instance error", EXIT_FAILURE); } logger->set_verbosity(NDDS_CONFIG_LOG_VERBOSITY_WARNING); if (!logger->set_print_format_by_log_level( NDDS_CONFIG_LOG_PRINT_FORMAT_MAXIMAL, NDDS_CONFIG_LOG_LEVEL_WARNING)) { return shutdown_participant( participant, "loggingTypeSupport::NDDSConfigLogger::set_print_format_by_log_level 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 = loggingTypeSupport::get_type_name(); DDS_ReturnCode_t retcode = loggingTypeSupport::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 logging", 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 logging" 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 loggingDataWriter *typed_writer = loggingDataWriter::narrow(untyped_writer); if (typed_writer == NULL) { return shutdown_participant(participant, "DataWriter narrow error", EXIT_FAILURE); } // Create data for writing, allocating all members logging *data = loggingTypeSupport::create_data(); if (data == NULL) { return shutdown_participant( participant, "loggingTypeSupport::create_data error", EXIT_FAILURE); } // Write data retcode = typed_writer->write(*data, DDS_HANDLE_NIL); if (retcode != DDS_RETCODE_OK) { std::cerr << "write error " << retcode << std::endl; } /* * Force a warning by writing a sample where the source time stamp is older * than that of a previously sent sample. When using * DDS_BY_SOURCE_TIMESTAMP_DESTINATIONORDER_QOS: If source timestamp is * older than in previous write a warnings message will be logged. */ struct DDS_Time_t sourceTimestamp = {0, 0}; retcode = typed_writer->write_w_timestamp( *data, DDS_HANDLE_NIL, sourceTimestamp); if (retcode == DDS_RETCODE_OK) { std::cerr << "write error " << retcode << std::endl; } /* * End - modifying the generated example to showcase the usage of * the Logging API. */ // Delete previously allocated logging, including all contained elements retcode = loggingTypeSupport::delete_data(data); if (retcode != DDS_RETCODE_OK) { std::cerr << "loggingTypeSupport::delete_data error " << retcode << std::endl; } NDDSConfigLogger::finalize_instance(); // 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/logging_config/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/logging_config/c++98/logging_publisher.cxx
/* * (c) Copyright, Real-Time Innovations, 2021. All rights reserved. * RTI grants Licensee a license to use, modify, compile, and create derivative * works of the software solely for use with RTI Connext DDS. Licensee may * redistribute copies of the software provided that all such copies are subject * to this license. The software is provided "as is", with no warranty of any * type, including any warranty for fitness for any purpose. RTI is under no * obligation to maintain or support the software. RTI shall not be liable for * any incidental or consequential damages arising out of the use or inability * to use the software. */ #include <iostream> #include <stdio.h> #include <stdlib.h> #include "logging.h" #include "loggingSupport.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); } /* * Start - modifying the generated example to showcase the usage of * the Logging API. */ /* * Set NDDS_CONFIG_LOG_VERBOSITY_WARNING NDDS_Config_LogVerbosity. * Set NDDS_CONFIG_LOG_PRINT_FORMAT_MAXIMAL NDDS_Config_LogPrintFormat * for NDDS_CONFIG_LOG_LEVEL_WARNING. */ NDDSConfigLogger *logger = NULL; logger = NDDSConfigLogger::get_instance(); if (logger == NULL) { return shutdown_participant( participant, "loggingTypeSupport::NDDSConfigLogger::get_instance error", EXIT_FAILURE); } logger->set_verbosity(NDDS_CONFIG_LOG_VERBOSITY_WARNING); if (!logger->set_print_format_by_log_level( NDDS_CONFIG_LOG_PRINT_FORMAT_MAXIMAL, NDDS_CONFIG_LOG_LEVEL_WARNING)) { return shutdown_participant( participant, "loggingTypeSupport::NDDSConfigLogger::set_print_format_by_log_" "level 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 = loggingTypeSupport::get_type_name(); DDS_ReturnCode_t retcode = loggingTypeSupport::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 logging", 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 logging" 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 loggingDataWriter *typed_writer = loggingDataWriter::narrow(untyped_writer); if (typed_writer == NULL) { return shutdown_participant( participant, "DataWriter narrow error", EXIT_FAILURE); } // Create data for writing, allocating all members logging *data = loggingTypeSupport::create_data(); if (data == NULL) { return shutdown_participant( participant, "loggingTypeSupport::create_data error", EXIT_FAILURE); } // Write data retcode = typed_writer->write(*data, DDS_HANDLE_NIL); if (retcode != DDS_RETCODE_OK) { std::cerr << "write error " << retcode << std::endl; } /* * Force a warning by writing a sample where the source time stamp is older * than that of a previously sent sample. When using * DDS_BY_SOURCE_TIMESTAMP_DESTINATIONORDER_QOS: If source timestamp is * older than in previous write a warnings message will be logged. */ struct DDS_Time_t sourceTimestamp = { 0, 0 }; retcode = typed_writer->write_w_timestamp( *data, DDS_HANDLE_NIL, sourceTimestamp); if (retcode == DDS_RETCODE_OK) { std::cerr << "write error " << retcode << std::endl; } /* * End - modifying the generated example to showcase the usage of * the Logging API. */ // Delete previously allocated logging, including all contained elements retcode = loggingTypeSupport::delete_data(data); if (retcode != DDS_RETCODE_OK) { std::cerr << "loggingTypeSupport::delete_data error " << retcode << std::endl; } NDDSConfigLogger::finalize_instance(); // 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/logging_config/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], "-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" " -v, --verbosity <int> How much debugging output " "to show.\n" " Range: 0-5 \n" " Default: 0" << std::endl; } } } // namespace application #endif // APPLICATION_H
h