repo_name
stringclasses 10
values | file_path
stringlengths 29
222
| content
stringlengths 24
926k
| extention
stringclasses 5
values |
---|---|---|---|
rticonnextdds-robot-helpers
|
data/projects/rticonnextdds-robot-helpers/rclcpp_dds_examples/include/rclcpp_dds_examples/visibility_control.h
|
// Copyright 2015 Open Source Robotics Foundation, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#ifndef RCLCPP_DDS_EXAMPLES__VISIBILITY_CONTROL_H_
#define RCLCPP_DDS_EXAMPLES__VISIBILITY_CONTROL_H_
// This logic was borrowed (then namespaced) from the examples on the gcc wiki:
// https://gcc.gnu.org/wiki/Visibility
#if defined _WIN32 || defined __CYGWIN__
#ifdef __GNUC__
#define RCLCPP_DDS_EXAMPLES_EXPORT __attribute__ ((dllexport))
#define RCLCPP_DDS_EXAMPLES_IMPORT __attribute__ ((dllimport))
#else
#define RCLCPP_DDS_EXAMPLES_EXPORT __declspec(dllexport)
#define RCLCPP_DDS_EXAMPLES_IMPORT __declspec(dllimport)
#endif
#ifdef RCLCPP_DDS_EXAMPLES_BUILDING_LIBRARY
#define RCLCPP_DDS_EXAMPLES_PUBLIC RCLCPP_DDS_EXAMPLES_EXPORT
#else
#define RCLCPP_DDS_EXAMPLES_PUBLIC RCLCPP_DDS_EXAMPLES_IMPORT
#endif
#define RCLCPP_DDS_EXAMPLES_PUBLIC_TYPE RCLCPP_DDS_EXAMPLES_PUBLIC
#define RCLCPP_DDS_EXAMPLES_LOCAL
#else
#define RCLCPP_DDS_EXAMPLES_EXPORT __attribute__ ((visibility("default")))
#define RCLCPP_DDS_EXAMPLES_IMPORT
#if __GNUC__ >= 4
#define RCLCPP_DDS_EXAMPLES_PUBLIC __attribute__ ((visibility("default")))
#define RCLCPP_DDS_EXAMPLES_LOCAL __attribute__ ((visibility("hidden")))
#else
#define RCLCPP_DDS_EXAMPLES_PUBLIC
#define RCLCPP_DDS_EXAMPLES_LOCAL
#endif
#define RCLCPP_DDS_EXAMPLES_PUBLIC_TYPE
#endif
#endif // RCLCPP_DDS_EXAMPLES__VISIBILITY_CONTROL_H_
|
h
|
rticonnextdds-robot-helpers
|
data/projects/rticonnextdds-robot-helpers/rclcpp_dds_examples/include/rclcpp_dds_examples/ping/publisher.hpp
|
// Copyright 2021 Real-Time Innovations, Inc. (RTI)
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#ifndef RCLCPP_DDS_EXAMPLES__PING__PUBLISHER_HPP_
#define RCLCPP_DDS_EXAMPLES__PING__PUBLISHER_HPP_
#include "rclcpp_dds_examples/ping/tester.hpp"
namespace rclcpp_dds_examples
{
template<typename T>
class PingPongPublisher : public PingPongTester<T>
{
public:
PingPongPublisher(
const char * const name,
const rclcpp_dds::DDSNodeOptions & options)
: PingPongTester<T>(name, options, true /* ping */)
{}
protected:
// Helper function to fill in the contents of a sample
virtual void prepare_ping(T & sample, const bool final) = 0;
// Process received pong sample and return the timestamp
virtual void process_pong(
dds::sub::LoanedSamples<T> & pong_samples,
uint64_t & pong_timestamp) = 0;
virtual void init_test()
{
PingPongTester<T>::init_test();
// Start timer to periodically check exit conditions
if (this->test_options_.max_execution_time > 0) {
exit_timer_ = this->create_wall_timer(
std::chrono::seconds(1),
[this]() {
if (this->is_test_complete()) {
// Cancel timer and mark test as complete. The process will exit
// after detecting the subscriber going offline.
exit_timer_->cancel();
this->test_complete();
}
});
}
RCLCPP_INFO(
this->get_logger(),
"ping-pong publisher ready, waiting for subscriber...");
}
// Overload `test_start()` to initialize test state and send an initial ping.
virtual void test_start()
{
PingPongTester<T>::test_start();
ping();
}
// Overload `test_stop()` to print the final computed latency
virtual void test_stop()
{
if (this->test_complete_) {
print_latency(true /* final */);
}
PingPongTester<T>::test_stop();
}
// Once the test is complete, we send a final ping with timestamp=0 to notify
// that reader that the test is done. Once the reader is detected as offline,
// the writer will also exit.
virtual void test_complete()
{
PingPongTester<T>::test_complete();
ping(true /* final */);
}
// Compute a running average of the latency measurements and log it to stdout.
virtual void print_latency(const bool final_log = false)
{
std::ostringstream msg;
if (this->count_ > 0) {
const uint64_t avg_us = total_latency_ / (this->count_ * 2);
const double avg_ms = static_cast<double>(avg_us) / 1000.0;
msg << "Avg-Latency [" << this->count_ << "/" <<
this->test_options_.max_samples << "] ";
double avg_print = avg_ms;
const char * avg_unit = "ms";
if (avg_print < 1) {
avg_print = avg_print * 1000.0;
avg_unit = "us";
}
double avg_int;
if (std::modf(avg_print, &avg_int) >= 0.001) {
msg << std::fixed << std::setprecision(3);
} else {
msg << std::fixed << std::setprecision(1);
}
msg << avg_print << " " << avg_unit;
if (final_log) {
msg << " [FINAL]";
}
} else {
msg << "Avg-Latency: no samples yet";
}
RCLCPP_INFO(this->get_logger(), msg.str().c_str());
}
// Send a ping message unless the test has already completed.
virtual void ping(const bool final = false)
{
// Allocate a sample and prepare it for publishing
auto sample = this->alloc_sample();
prepare_ping(*sample, final);
// Write the sample out
this->writer_.write(*sample);
}
// Overload on_data() callback to process the pong sample and compute the
// round-trip latency. We store the value halved to compute a running average
// of one-way latency.
virtual void on_data(dds::sub::LoanedSamples<T> & pong_samples)
{
if (!this->test_active_) {
RCLCPP_ERROR(this->get_logger(), "pong received while test inactive");
this->shutdown();
return;
}
// Extract timestamp from pong sample.
uint64_t pong_ts = 0;
process_pong(pong_samples, pong_ts);
uint64_t receive_ts = this->ts_now();
// this test will not cope well with a drifting clock
assert(receive_ts >= pong_ts);
uint64_t latency = (receive_ts - pong_ts) / 2;
// we ignore the first few samples to let things ramp up to steady state
const bool ignored =
static_cast<uint64_t>(this->test_options_.ignored_initial_samples) > this->count_ignored_;
if (!ignored) {
this->count_ += 1;
total_latency_ += latency;
if (last_print_ == 0 ||
receive_ts - static_cast<uint64_t>(this->test_options_.print_interval) > last_print_)
{
print_latency();
last_print_ = receive_ts;
}
} else {
this->count_ignored_ += 1;
}
// Check if thest is complete, otherwise send another ping
if (this->is_test_complete()) {
test_complete();
} else {
ping();
}
}
uint64_t total_latency_ = 0;
uint64_t last_print_ = 0;
uint64_t ping_ts_ = 0;
rclcpp::TimerBase::SharedPtr exit_timer_;
};
} // namespace rclcpp_dds_examples
#endif // RCLCPP_DDS_EXAMPLES__PING__PUBLISHER_HPP_
|
hpp
|
rticonnextdds-robot-helpers
|
data/projects/rticonnextdds-robot-helpers/rclcpp_dds_examples/include/rclcpp_dds_examples/ping/subscriber.hpp
|
// Copyright 2021 Real-Time Innovations, Inc. (RTI)
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#ifndef RCLCPP_DDS_EXAMPLES__PING__SUBSCRIBER_HPP_
#define RCLCPP_DDS_EXAMPLES__PING__SUBSCRIBER_HPP_
#include "rclcpp_dds_examples/ping/tester.hpp"
namespace rclcpp_dds_examples
{
template<typename T>
class PingPongSubscriber : public PingPongTester<T>
{
public:
PingPongSubscriber(
const char * const name,
const rclcpp_dds::DDSNodeOptions & options)
: PingPongTester<T>(name, options, false /* pong */)
{}
protected:
// Helper function to fill in the contents of a pong
virtual void prepare_pong(T * const pong, const uint64_t ping_ts) = 0;
// Process received ping sample and return the timestamp
virtual void process_ping(
dds::sub::LoanedSamples<T> & ping_samples,
uint64_t & pong_timestamp) = 0;
// Helper function to dump the contents of a received ping to a string
virtual void dump_ping(
dds::sub::LoanedSamples<T> & ping_samples,
std::ostringstream & msg) = 0;
virtual void init_test()
{
PingPongTester<T>::init_test();
RCLCPP_INFO(
this->get_logger(),
"ping-pong subscriber ready, waiting for publisher...");
}
// Overload `on_data()` to propagate ping sample to the pong topic.
virtual void on_data(dds::sub::LoanedSamples<T> & ping_samples)
{
uint64_t ping_ts;
process_ping(ping_samples, ping_ts);
if (ping_ts == 0) {
RCLCPP_INFO(this->get_logger(), "received end ping, exiting");
this->shutdown();
return;
}
if (this->test_options_.display_received) {
std::ostringstream msg;
msg << "[CameraImage] ";
dump_ping(ping_samples, msg);
RCLCPP_INFO(this->get_logger(), msg.str().c_str());
}
// Send back the timestamp to the writer.
auto pong = this->alloc_sample();
prepare_pong(pong, ping_ts);
this->writer_.write(*pong);
}
};
} // namespace rclcpp_dds_examples
#endif // RCLCPP_DDS_EXAMPLES__PING__SUBSCRIBER_HPP_
|
hpp
|
rticonnextdds-robot-helpers
|
data/projects/rticonnextdds-robot-helpers/rclcpp_dds_examples/include/rclcpp_dds_examples/ping/tester.hpp
|
// Copyright 2021 Real-Time Innovations, Inc. (RTI)
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#ifndef RCLCPP_DDS_EXAMPLES__PING__TESTER_HPP_
#define RCLCPP_DDS_EXAMPLES__PING__TESTER_HPP_
#include <chrono>
#include <string>
#include <memory>
#include "rclcpp_dds/rclcpp_dds.hpp"
#ifndef UNUSED_ARG
#define UNUSED_ARG(a_) (void)a_
#endif // UNUSED_ARG
namespace rclcpp_dds_examples
{
struct PingPongTesterOptions
{
int32_t domain_id = 0;
int64_t max_samples = 0;
int64_t max_execution_time = 0;
int64_t ignored_initial_samples = 0;
int64_t print_interval = 0;
std::string type_name;
std::string topic_name_ping;
std::string topic_name_pong;
std::string qos_profile_ping;
std::string qos_profile_pong;
bool display_received{false};
bool dedicated_participant{false};
template<typename N>
static void declare(N * const node)
{
node->declare_parameter("domain_id", 0);
node->declare_parameter("max_samples", 0);
node->declare_parameter("max_execution_time", 30000000 /* 30s */);
node->declare_parameter("ignored_initial_samples", 3);
node->declare_parameter("print_interval", 1000000 /* 1s */);
node->declare_parameter("type_name", "PingMessage");
node->declare_parameter("topic_name_ping", "rt/ping");
node->declare_parameter("topic_name_pong", "rt/pong");
node->declare_parameter(
"qos_profile_ping",
"BuiltinQosLibExp::Generic.StrictReliable.LargeData");
node->declare_parameter(
"qos_profile_pong",
"BuiltinQosLibExp::Generic.StrictReliable.LargeData");
node->declare_parameter("display_received", false);
node->declare_parameter("dedicated_participant", false);
}
template<typename N>
static PingPongTesterOptions load(N * const node, const bool log_result = true)
{
PingPongTesterOptions opts;
node->get_parameter("domain_id", opts.domain_id);
node->get_parameter("max_samples", opts.max_samples);
node->get_parameter("max_execution_time", opts.max_execution_time);
node->get_parameter("ignored_initial_samples", opts.ignored_initial_samples);
node->get_parameter("print_interval", opts.print_interval);
node->get_parameter("type_name", opts.type_name);
node->get_parameter("topic_name_ping", opts.topic_name_ping);
node->get_parameter("topic_name_pong", opts.topic_name_pong);
node->get_parameter("qos_profile_ping", opts.qos_profile_ping);
node->get_parameter("qos_profile_pong", opts.qos_profile_pong);
node->get_parameter("display_received", opts.display_received);
node->get_parameter("dedicated_participant", opts.dedicated_participant);
if (log_result) {
log(node, opts);
}
return opts;
}
// Helper function to log test options to stdout.
template<typename N>
static void log(N * const node, const PingPongTesterOptions & opts)
{
RCLCPP_INFO(
node->get_logger(), "test options:\n"
"\tdomain_id = %d\n"
"\tmax_samples = %lu\n"
"\tmax_execution_time = %lfs\n"
"\tignored_initial_samples = %lu\n"
"\tprint_interval = %lfs\n"
"\ttype_name = '%s'\n"
"\ttopic_name_ping = '%s'\n"
"\ttopic_name_pong = '%s'\n"
"\tqos_profile_ping = '%s'\n"
"\tqos_profile_pong = '%s'\n"
"\tdisplay_received = %d\n"
"\tdedicated_participant = %d",
opts.domain_id,
opts.max_samples,
static_cast<double>(opts.max_execution_time) / 1000000.0,
opts.ignored_initial_samples,
static_cast<double>(opts.print_interval) / 1000000.0,
opts.type_name.c_str(),
opts.topic_name_ping.c_str(),
opts.topic_name_pong.c_str(),
opts.qos_profile_ping.c_str(),
opts.qos_profile_pong.c_str(),
opts.display_received,
opts.dedicated_participant);
}
};
template<typename T>
class PingPongTester : public rclcpp_dds::DDSNode
{
protected:
PingPongTester(
const char * const name,
const rclcpp_dds::DDSNodeOptions & options,
const bool ping)
: DDSNode(name, options),
ping_(ping)
{
// We use ROS 2 parameters to allow customization of test parameters, e.g.
// via a YAML parameter file with `--ros-args --params-file <file>`.
PingPongTesterOptions::declare(this);
}
// If we are using the "plain" binding this function will return a
// preallocated sample. If we are using Zero-Copy or Flat-Data, then this
// function must loan a sample from the writer.
virtual T * alloc_sample() = 0;
// Callback invoked every time (valid) data is received from the reader.
virtual void on_data(dds::sub::LoanedSamples<T> & samples) = 0;
// Initialize DDS entities and other data structures used by the tester.
// Each operation is delegated to a virtual function, so that subclasses may
// override each step as needed.
virtual void init_test()
{
// Load test configuration from ROS 2 parameters
test_options_ = PingPongTesterOptions::load(this);
const std::string * writer_topic,
* writer_profile,
* reader_topic,
* reader_profile;
if (ping_) {
writer_topic = &test_options_.topic_name_ping;
writer_profile = &test_options_.qos_profile_ping;
reader_topic = &test_options_.topic_name_pong;
reader_profile = &test_options_.qos_profile_pong;
} else {
writer_topic = &test_options_.topic_name_pong;
writer_profile = &test_options_.qos_profile_pong;
reader_topic = &test_options_.topic_name_ping;
reader_profile = &test_options_.qos_profile_ping;
}
create_endpoints(
*writer_topic, *writer_profile, *reader_topic, *reader_profile);
initialize_events();
publisher_->enable();
subscriber_->enable();
}
virtual void create_endpoints(
const std::string & writer_topic,
const std::string & writer_profile,
const std::string & reader_topic,
const std::string & reader_profile)
{
// Create a custom Publisher and Subscriber and configure them so that
// DataWriters and DataReaders are created disabled. This way we can
// configure them, and enable them without losing any discovery event.
auto participant = this->domain_participant();
dds::core::policy::EntityFactory entity_policy;
entity_policy.autoenable_created_entities(false);
auto publisher_qos = participant.default_publisher_qos();
publisher_qos << entity_policy;
publisher_ = dds::pub::Publisher(participant, publisher_qos);
auto subscriber_qos = participant.default_subscriber_qos();
subscriber_qos << entity_policy;
subscriber_ = dds::sub::Subscriber(participant, subscriber_qos);
// Create a DataWriter configured to handle "large data" (i.e. data which
// exceeds the transport's MTU). We also configure it to use "transient local"
// durability so that the first message is not lost in case of asymmetric
// discovery (i.e. the writer matches the reader before the reader has
// matched the writer).
auto writer_qos = this->get_datawriter_qos_profile(writer_profile);
// Only keep the latest written sample
writer_qos << dds::core::policy::History::KeepLast(1);
// Use transient local Durability
writer_qos << dds::core::policy::Durability::TransientLocal();
auto writer_dds_topic =
dds::topic::Topic<T>(participant, writer_topic, test_options_.type_name);
writer_ = dds::pub::DataWriter<T>(publisher_, writer_dds_topic, writer_qos);
auto reader_qos = this->get_datareader_qos_profile(reader_profile);
reader_qos << dds::core::policy::History::KeepLast(1);
// Optional optimization: prevent dynamic allocation of received fragments.
// This might cause more memory allocation upfront, but may improve latency.
rti::core::policy::DataReaderResourceLimits dr_limits;
dr_limits.dynamically_allocate_fragmented_samples(false);
reader_qos << dr_limits;
// Use transient local Durability
reader_qos << dds::core::policy::Durability::TransientLocal();
auto reader_dds_topic =
dds::topic::Topic<T>(participant, reader_topic, test_options_.type_name);
reader_ = dds::sub::DataReader<T>(subscriber_, reader_dds_topic, reader_qos);
}
// Disable event notification and call `rclcpp::shutdown()` to stop process.
virtual void shutdown()
{
test_active_ = false;
rclcpp::shutdown();
}
// Create an AsyncWaitSet to process events on dedicated pool of user threads,
// instead of calling them from the middleware's transport receive threads.
// By default, only 1 thread is allocated to the pool.
virtual void initialize_events()
{
using dds::core::status::StatusMask;
this->set_status_callback<T>(
reader_,
[this](dds::core::cond::StatusCondition &, dds::sub::DataReader<T> &) {
on_reader_active();
},
StatusMask::subscription_matched() | StatusMask::data_available());
this->set_status_callback<T>(
writer_,
[this](dds::core::cond::StatusCondition &, dds::pub::DataWriter<T> &) {
on_writer_active();
},
StatusMask::publication_matched());
// Start a watchdog timer to make sure that the test starts, because there
// is currently a race condition when using Zero-Copy where some "matched"
// events are never notified. To keep things consistent, we attach a
// "watchdog guard condition" to the waitset, and we will trigger it from
// the timer if it detects that the test is ready, but hasn't been marked
// as such. The only reason to do this (instead of calling `test_start()`
// directly from the timer) is so that the start event is processed on one
// of the AsyncWaitset's threads, as it would be if all match events were
// notified.
wd_condition_ = this->add_user_callback(
[this]() {
// Force test to start
test_start();
});
wd_ = this->create_wall_timer(
std::chrono::milliseconds(100),
[this]() {
if (is_test_ready()) {
// Cancel watchdog timer
wd_->cancel();
// Trigger watchdog condition to wake up waitset
wd_condition_.trigger_value(true);
}
});
}
// A simple wrapper to
virtual uint64_t ts_now()
{
return this->domain_participant().current_time().to_microsecs();
}
// Mark test as active
virtual void test_start()
{
wd_->cancel();
RCLCPP_INFO(this->get_logger(), "all endpoints matched, beginning test");
test_active_ = true;
test_complete_ = false;
count_ignored_ = 0;
count_ = 0;
start_ts_ = this->ts_now();
}
// Mark test as inactive and call shutdown() to terminate process.
virtual void test_stop()
{
auto stop_ts = this->ts_now();
const uint64_t run_time = stop_ts - start_ts_;
const double run_time_s = run_time / 1000000.0;
RCLCPP_INFO(this->get_logger(), "test stopped after %lf s", run_time_s);
test_active_ = false;
if (test_complete_) {
RCLCPP_INFO(this->get_logger(), "test completed");
} else {
RCLCPP_ERROR(this->get_logger(), "test interrupted before completion");
}
shutdown();
}
// Callback to perform custom operation when the test is considered complete.
virtual void test_complete()
{
test_complete_ = true;
}
// Consider the test "ready to run" if both the writer and the reader have at
// least one matched remote endpoint. This could lead to false positives, for
// example if there are some monitoring applications open (e.g. RTI Admin
// Console, or rtiddsspy). More sophisticated coordination could be implemented
// by introducing an explicit synchronization topic, but we keep things simple
// for the sake of example.
virtual bool is_test_ready()
{
auto sub_matched_status = writer_.publication_matched_status();
auto pub_matched_status = reader_.subscription_matched_status();
return sub_matched_status.current_count() > 0 &&
pub_matched_status.current_count() > 0;
}
// Check if the test is complete, because either:
// - The maximum number of samples were published/received.
// - The maximum allowed run time was reached.
virtual bool is_test_complete()
{
auto ts = this->ts_now();
const bool time_expired =
start_ts_ > 0 && test_options_.max_execution_time > 0 &&
ts - static_cast<uint64_t>(test_options_.max_execution_time) > start_ts_;
const bool max_samples_reached =
test_options_.max_samples > 0 &&
count_ >= static_cast<uint64_t>(test_options_.max_samples);
return time_expired || max_samples_reached;
}
// Check if the test is "ready to run", and activate/deactivate it based on
// outcome of the check and the current test state.
virtual void check_test_state()
{
if (is_test_ready()) {
if (!test_active_) {
test_start();
}
} else {
if (test_active_) {
test_stop();
}
}
}
// Default handler for "data available" events which calls take() to reset
// the status flag on the reader. Subclasses will tipically overload the
// on_data() callback.
virtual void on_data_available()
{
// Read samples from reader cache and notify a callback.
// Always peform a take so the listener is not called repeatedly.
auto samples = reader_.take();
const bool has_data = samples.length() > 0;
if (has_data && samples[0].info().valid()) {
on_data(samples);
} else if (has_data && !samples[0].info().valid()) {
// An "invalid" sample generally indicates a state transition from an
// unmatched/not-alive remote writer. Check this is expected (e.g if the
// test has already been completed), or terminate the test early otherwise.
if (!is_test_complete()) {
RCLCPP_ERROR(this->get_logger(), "lost peer before end of test");
test_stop();
}
} else if (!has_data) {
// This should never happen, but just in case, print an error and exit.
RCLCPP_ERROR(this->get_logger(), "woke up without data");
test_stop();
}
}
// Callback triggered when one of the enabled statuses is triggered on the
// reader's status condition.
virtual void on_reader_active()
{
using dds::core::status::StatusMask;
if ((reader_.status_changes() & StatusMask::subscription_matched()).any()) {
check_test_state();
}
if ((reader_.status_changes() & StatusMask::data_available()).any()) {
on_data_available();
}
}
// Callback triggered when one of the enabled statuses is triggered on the
// writer's status condition.
virtual void on_writer_active()
{
using dds::core::status::StatusMask;
// no need to differentiate, since we only enabled one status.
if ((writer_.status_changes() & StatusMask::publication_matched()).any()) {
check_test_state();
}
}
const bool ping_;
PingPongTesterOptions test_options_;
bool test_active_{false};
bool test_complete_{false};
uint64_t count_ = 0;
uint64_t count_ignored_ = 0;
uint64_t start_ts_ = 0;
dds::pub::Publisher publisher_{nullptr};
dds::sub::Subscriber subscriber_{nullptr};
dds::pub::DataWriter<T> writer_{nullptr};
dds::sub::DataReader<T> reader_{nullptr};
dds::core::cond::GuardCondition wd_condition_;
rclcpp::TimerBase::SharedPtr wd_;
};
} // namespace namespace rclcpp_dds_examples
#endif // RCLCPP_DDS_EXAMPLES__PING__TESTER_HPP_
|
hpp
|
rticonnextdds-robot-helpers
|
data/projects/rticonnextdds-robot-helpers/rclcpp_dds_examples/include/rclcpp_dds_examples/camera/CameraImagePublisher.hpp
|
// Copyright 2021 Real-Time Innovations, Inc. (RTI)
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#ifndef RCLCPP_DDS_EXAMPLES__CAMERA__CAMERAIMAGEPUBLISHER_HPP_
#define RCLCPP_DDS_EXAMPLES__CAMERA__CAMERAIMAGEPUBLISHER_HPP_
#include <string>
#include "rclcpp_dds_examples/ping/publisher.hpp"
#include "rti/ros2/data/access.hpp"
#include "rti/ros2/data/memory.hpp"
#include "camera/CameraCommon.hpp"
namespace rclcpp_dds_examples
{
// This is a generic implementation of the CameraImagePublisher classes, which
// can be instantiated independently of transfer method and memory binding
// through the use of metaprogramming.
template<typename T, typename A, typename M>
class CameraImagePublisher : public rclcpp_dds_examples::PingPongPublisher<T>
{
public:
CameraImagePublisher(
const char * const name,
const rclcpp::NodeOptions & options)
: rclcpp_dds_examples::PingPongPublisher<T>(name, options)
{
this->init_test();
}
protected:
virtual void create_endpoints(
const std::string & writer_topic,
const std::string & writer_profile,
const std::string & reader_topic,
const std::string & reader_profile)
{
rclcpp_dds_examples::PingPongPublisher<T>::create_endpoints(
writer_topic, writer_profile, reader_topic, reader_profile);
cached_sample_ = A::prealloc(writer_);
}
virtual T * alloc_sample()
{
return A::alloc(writer_, cached_sample_);
}
virtual void prepare_ping(T & ping, const bool final)
{
if (final) {
M::get(ping).timestamp(0);
return;
}
M::get(ping).format(rti::camera::common::Format::RGB);
M::get(ping).resolution().height(rti::camera::common::CAMERA_HEIGHT_DEFAULT);
M::get(ping).resolution().width(rti::camera::common::CAMERA_WIDTH_DEFAULT);
// Just set the first 4 bytes
for (int i = 0; i < 4; i++) {
uint8_t image_value = (48 + this->count_) % 124;
M::array::set(M::get(ping).data(), i, image_value);
}
// Update timestamp
M::get(ping).timestamp(this->participant_->current_time().to_microsecs());
}
// Process received pong sample and return the timestamp
virtual void process_pong(
dds::sub::LoanedSamples<T> & pong_samples,
uint64_t & pong_timestamp)
{
pong_timestamp = M::get(pong_samples[0].data()).timestamp();
}
CameraImage * cached_sample_;
};
} // namespace rclcpp_dds_examples
#endif // RCLCPP_DDS_EXAMPLES__CAMERA__CAMERAIMAGEPUBLISHER_HPP_
|
hpp
|
rticonnextdds-robot-helpers
|
data/projects/rticonnextdds-robot-helpers/rclcpp_dds_examples/include/rclcpp_dds_examples/camera/CameraImageSubscriber.hpp
|
// Copyright 2021 Real-Time Innovations, Inc. (RTI)
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#ifndef RCLCPP_DDS_EXAMPLES__CAMERA__CAMERAIMAGESUBSCRIBER_HPP_
#define RCLCPP_DDS_EXAMPLES__CAMERA__CAMERAIMAGESUBSCRIBER_HPP_
#include <string>
#include "rclcpp_dds_examples/ping/subscriber.hpp"
#include "camera/CameraCommon.hpp"
namespace rclcpp_dds_examples
{
// This is a generic implementation of the CameraImageSubscriber classes, which
// can be instantiated independently of transfer method and memory binding
// through the use of metaprogramming.
template<typename T>
class CameraImageSubscriber : public rclcpp_dds_examples::PingPongSubscriber<T>
{
public:
CameraImageSubscriber(
const char * const name,
const rclcpp::NodeOptions & options)
: PingPongSubscriber<T>(name, options)
{
this->init_test();
}
protected:
virtual void create_endpoints(
const std::string & writer_topic,
const std::string & writer_profile,
const std::string & reader_topic,
const std::string & reader_profile)
{
rclcpp_dds_examples::PingPongSubscriber<T>::create_endpoints(
writer_topic, writer_profile, reader_topic, reader_profile);
cached_sample_ = A::prealloc(writer_);
}
virtual T * alloc_sample()
{
return A::alloc(writer_, cached_sample_);
}
virtual void prepare_pong(T * const pong, const uint64_t ping_ts)
{
M::get(*pong).timestamp(ping_ts);
}
virtual void process_ping(
dds::sub::LoanedSamples<T> & ping_samples,
uint64_t & ping_timestamp)
{
ping_timestamp = M::get(ping_samples[0].data()).timestamp();
}
virtual void dump_ping(
dds::sub::LoanedSamples<T> & ping_samples,
std::ostringstream & msg)
{
auto & sample = ping_samples[0].data();
msg << "[" << M::get(sample).timestamp() << "] " << M::get(sample).format();
for (int i = 0; i < 4; i++) {
const uint8_t * el;
M::array::ref(M::get(sample).data(), i, el);
msg << "0x" <<
std::hex << std::uppercase <<
std::setfill('0') << std::setw(2) <<
static_cast<int>(*el) <<
std::nouppercase << std::dec <<
" ";
}
}
CameraImage * cached_sample_;
};
} // namespace rclcpp_dds_examples
#endif // RCLCPP_DDS_EXAMPLES__CAMERA__CAMERAIMAGESUBSCRIBER_HPP_
|
hpp
|
rticonnextdds-robot-helpers
|
data/projects/rticonnextdds-robot-helpers/rclcpp_dds_examples/include/rti/ros2/data/access.hpp
|
// Copyright 2021 Real-Time Innovations, Inc. (RTI)
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#ifndef RTI__ROS2__DATA__ACCESS_HPP_
#define RTI__ROS2__DATA__ACCESS_HPP_
#include <dds/dds.hpp>
#include "rti/topic/flat/FlatData.hpp"
namespace rti
{
namespace ros2
{
namespace data
{
template<typename T>
class DataAccessPlain
{
public:
static T & get(T & sample)
{
return sample;
}
static const T & get(const T & sample)
{
return sample;
}
class array
{
public:
template<typename A, typename E>
static void ref(A & array, const size_t i, E & val)
{
val = array.data() + i;
}
template<typename A, typename E>
static void set(A & array, const size_t i, E & val)
{
array[i] = val;
}
};
};
template<typename T>
class DataAccessFlat
{
public:
static typename rti::flat::flat_type_traits<T>::offset get(T & sample)
{
return sample.root();
}
static typename rti::flat::flat_type_traits<T>::offset::ConstOffset get(const T & sample)
{
return sample.root();
}
class array
{
public:
template<typename A, typename E>
static void ref(A array, const size_t i, E & val)
{
val = array.get_elements() + i;
}
template<typename A, typename E>
static void set(A array, const size_t i, E & val)
{
array.set_element(i, val);
}
};
};
} // namespace data
} // namespace ros2
} // namespace rti
#endif // RTI__ROS2__DATA__ACCESS_HPP_
|
hpp
|
rticonnextdds-robot-helpers
|
data/projects/rticonnextdds-robot-helpers/rclcpp_dds_examples/include/rti/ros2/data/memory.hpp
|
// Copyright 2021 Real-Time Innovations, Inc. (RTI)
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#ifndef RTI__ROS2__DATA__MEMORY_HPP_
#define RTI__ROS2__DATA__MEMORY_HPP_
#include <dds/dds.hpp>
namespace rti
{
namespace ros2
{
namespace data
{
template<typename T>
class DataMemoryDynamic
{
public:
// Dynamically pre-allocate a sample.
static T * prealloc(
dds::pub::DataWriter<T> & writer)
{
(void)writer;
return new T();
}
static T * alloc(
dds::pub::DataWriter<T> & writer,
T * const preallocd_sample)
{
(void)writer;
assert(preallocd_sample != nullptr);
return preallocd_sample;
}
};
template<typename T>
class DataMemoryLoan
{
public:
// No pre-allocated samples, since we are going to loan them from the writer
static T * prealloc(
dds::pub::DataWriter<T> & writer)
{
(void)writer;
return nullptr;
}
// Return a sample loaned from the DataWriter
static T * alloc(
dds::pub::DataWriter<T> & writer,
T * const preallocd_sample)
{
(void)preallocd_sample;
assert(preallocd_sample == nullptr);
return writer.extensions().get_loan();
}
};
} // namespace data
} // namespace ros2
} // namespace rti
#endif // RTI__ROS2__DATA__MEMORY_HPP_
|
hpp
|
rticonnextdds-robot-helpers
|
data/projects/rticonnextdds-robot-helpers/rclcpp_dds/src/dds_node.cpp
|
// Copyright 2021 Real-Time Innovations, Inc. (RTI)
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include <string>
#include "rclcpp_dds/dds_node.hpp"
namespace rclcpp_dds
{
DDSNode::DDSNode(
const std::string & node_name,
const DDSNodeOptions & options)
: DDSNodeMixin(node_name, options)
{}
DDSNode::DDSNode(
const std::string & node_name,
const std::string & namespace_,
const DDSNodeOptions & options)
: DDSNodeMixin(node_name, namespace_, options)
{}
} // namespace rclcpp_dds
|
cpp
|
rticonnextdds-robot-helpers
|
data/projects/rticonnextdds-robot-helpers/rclcpp_dds/test/rclcpp_dds/test_topic.cpp
|
// Copyright 2021 Real-Time Innovations, Inc. (RTI)
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include <gtest/gtest.h>
#include <cstdlib>
#include <memory>
#include <string>
#include <vector>
#include "std_msgs/msg/String.hpp"
#include "example_interfaces/srv/AddTwoInts.hpp"
#include "rclcpp_dds/rclcpp_dds.hpp"
class TestTopic : public ::testing::Test
{
protected:
static void SetUpTestCase()
{
rclcpp::init(0, nullptr);
}
static void TearDownTestCase()
{
rclcpp::shutdown();
}
void SetUp()
{
node = make_node();
}
void TearDown()
{
node.reset();
}
virtual rclcpp_dds::DDSNode::SharedPtr
make_node()
{
return std::make_shared<rclcpp_dds::DDSNode>("my_node", "/ns");
}
rclcpp_dds::DDSNode::SharedPtr node;
};
TEST_F(TestTopic, topic) {
using std_msgs::msg::String;
// Create a topic with default options
auto topic = node->create_topic<String>("foo");
ASSERT_NE(topic, dds::core::null);
ASSERT_STREQ(topic.name().c_str(), "rt/ns/foo");
ASSERT_STREQ(topic.type_name().c_str(), "std_msgs::msg::dds_::String_");
// Check that we can't create the topic again if it already exists
ASSERT_THROW(
{
node->create_topic<String>("foo");
}, dds::core::Error);
ASSERT_THROW(
{
node->create_topic<String>("foo", "custom_type");
}, dds::core::Error);
// Check that we can lookup topic by name
auto topic_lookup = node->lookup_topic<String>("foo");
ASSERT_EQ(topic, topic_lookup);
}
TEST_F(TestTopic, topic_w_custom_type) {
using std_msgs::msg::String;
// Create a "standard" topic with a custom type name
auto topic = node->create_topic<String>("foo", "custom_type");
ASSERT_NE(topic, dds::core::null);
ASSERT_STREQ(topic.name().c_str(), "rt/ns/foo");
ASSERT_STREQ(topic.type_name().c_str(), "dds_::custom_type_");
// Check that we can't create the topic again if it already exists
ASSERT_THROW(
{
node->create_topic<String>("foo");
}, dds::core::Error);
ASSERT_THROW(
{
node->create_topic<String>("foo", "custom_type");
}, dds::core::Error);
// Check that we can lookup() the topic again if it already exists
auto topic_lookup = node->lookup_topic<String>("foo");
ASSERT_EQ(topic, topic_lookup);
}
TEST_F(TestTopic, request_topic) {
using example_interfaces::srv::AddTwoInts_Request;
// Create a request topic with default options
auto topic = node->create_service_topic<AddTwoInts_Request>("foo");
ASSERT_NE(topic, dds::core::null);
ASSERT_STREQ(topic.name().c_str(), "rq/ns/fooRequest");
ASSERT_STREQ(
topic.type_name().c_str(),
"example_interfaces::srv::dds_::AddTwoInts_Request_");
// Check that we can't create the topic again
ASSERT_THROW(
{
node->create_service_topic<AddTwoInts_Request>("foo");
}, dds::core::Error);
// Check that we can lookup() the topic again if it already exists
auto topic_lookup = node->lookup_service_topic<AddTwoInts_Request>("foo");
ASSERT_EQ(topic, topic_lookup);
}
TEST_F(TestTopic, reply_topic) {
using example_interfaces::srv::AddTwoInts_Response;
// Create a reply topic with default options
auto topic = node->create_service_topic<AddTwoInts_Response>("foo", false);
ASSERT_NE(topic, dds::core::null);
ASSERT_STREQ(topic.name().c_str(), "rr/ns/fooReply");
ASSERT_STREQ(
topic.type_name().c_str(),
"example_interfaces::srv::dds_::AddTwoInts_Response_");
// Check that we can't create the topic again
ASSERT_THROW(
{
node->create_service_topic<AddTwoInts_Response>("foo", false);
}, dds::core::Error);
// Check that we can lookup() the topic again if it already exists
auto topic_assert = node->lookup_service_topic<AddTwoInts_Response>("foo", false);
ASSERT_EQ(topic, topic_assert);
}
/******************************************************************************
* Test native DDS topics
******************************************************************************/
class TestTopicDds : public TestTopic
{
protected:
virtual rclcpp_dds::DDSNode::SharedPtr
make_node()
{
rclcpp_dds::DDSNodeOptions opts;
opts.use_ros_naming_conventions(false);
return std::make_shared<rclcpp_dds::DDSNode>("my_node", "/ns", opts);
}
};
TEST_F(TestTopicDds, topic) {
using std_msgs::msg::String;
// Create a topic with default options
auto topic = node->create_topic<String>("foo");
ASSERT_NE(topic, dds::core::null);
ASSERT_STREQ(topic.name().c_str(), "foo");
ASSERT_STREQ(topic.type_name().c_str(), "std_msgs::msg::String");
// Check that we can't create the topic again
ASSERT_THROW(
{
node->create_topic<String>("foo");
}, dds::core::Error);
ASSERT_THROW(
{
node->create_topic<String>("foo", "custom_type");
}, dds::core::Error);
// Check that we can lookup() the topic
auto topic_lookup = node->lookup_topic<String>("foo");
ASSERT_EQ(topic, topic_lookup);
}
TEST_F(TestTopicDds, topic_w_custom_type) {
using std_msgs::msg::String;
// Create a "standard" topic with a custom type name
auto topic = node->create_topic<String>("foo", "custom_type");
ASSERT_NE(topic, dds::core::null);
ASSERT_STREQ(topic.name().c_str(), "foo");
ASSERT_STREQ(topic.type_name().c_str(), "custom_type");
// Check that we can't create the topic again
ASSERT_THROW(
{
node->create_topic<String>("foo");
}, dds::core::Error);
ASSERT_THROW(
{
node->create_topic<String>("foo", "custom_type");
}, dds::core::Error);
// Check that we can lookup() the topic
auto topic_lookup = node->lookup_topic<String>("foo");
ASSERT_EQ(topic, topic_lookup);
}
TEST_F(TestTopicDds, request_topic) {
using example_interfaces::srv::AddTwoInts_Request;
// Create a request topic with default options
auto topic = node->create_service_topic<AddTwoInts_Request>("foo");
ASSERT_NE(topic, dds::core::null);
ASSERT_STREQ(topic.name().c_str(), "fooRequest");
ASSERT_STREQ(
topic.type_name().c_str(),
"example_interfaces::srv::AddTwoInts_Request");
// Check that we can't create the topic again
ASSERT_THROW(
{
node->create_service_topic<AddTwoInts_Request>("foo");
}, dds::core::Error);
// Check that we can lookup() the topic
auto topic_lookup = node->lookup_service_topic<AddTwoInts_Request>("foo");
ASSERT_EQ(topic, topic_lookup);
}
TEST_F(TestTopicDds, reply_topic) {
using example_interfaces::srv::AddTwoInts_Response;
// Create a reply topic with default options
auto topic = node->create_service_topic<AddTwoInts_Response>("foo", false);
ASSERT_NE(topic, dds::core::null);
ASSERT_STREQ(topic.name().c_str(), "fooReply");
ASSERT_STREQ(
topic.type_name().c_str(),
"example_interfaces::srv::AddTwoInts_Response");
// Check that we can't create the topic again
ASSERT_THROW(
{
node->create_service_topic<AddTwoInts_Response>("foo", false);
}, dds::core::Error);
// Check that we can lookup() the topic
auto topic_lookup = node->lookup_service_topic<AddTwoInts_Response>("foo", false);
ASSERT_EQ(topic, topic_lookup);
}
TEST_F(TestTopicDds, content_filtered_topic) {
using std_msgs::msg::String;
// Create the base topic with default options
auto topic = node->create_topic<String>("foo");
ASSERT_NE(topic, dds::core::null);
// Create a CFT
const char * const cft_expr = "data LIKE 'Hello World!'";
auto cft = node->create_content_filtered_topic<String>(topic, "my_filter", cft_expr);
ASSERT_NE(cft, dds::core::null);
ASSERT_STREQ(cft.filter_expression().c_str(), cft_expr);
ASSERT_EQ(cft.filter_parameters().size(), 0U);
ASSERT_EQ(cft.topic(), topic);
// Look up CFT by name
auto cft_lookup = node->lookup_content_filtered_topic<String>("my_filter");
ASSERT_EQ(cft, cft_lookup);
// Try to look up an unknown CFT by name
cft_lookup = node->lookup_content_filtered_topic<String>("my_unknown_filter");
ASSERT_EQ(nullptr, cft_lookup);
// Check that we can't create another CFT with the same name
ASSERT_THROW(
{
node->create_content_filtered_topic<String>(topic, "my_filter", cft_expr);
}, dds::core::Error);
// Create a CFT with parameters
const char * const cft_expr_w_params = "data LIKE %0";
const std::vector<std::string> cft_params = {"'HelloWorld'"};
auto cft_w_params = node->create_content_filtered_topic<String>(
topic,
"my_filter_w_params", cft_expr_w_params, cft_params);
ASSERT_NE(cft_w_params, dds::core::null);
ASSERT_STREQ(cft_w_params.filter_expression().c_str(), cft_expr_w_params);
// ASSERT_EQ(cft.filter_parameters().size(), 1);
ASSERT_EQ(cft_params, cft_w_params.filter_parameters());
ASSERT_EQ(cft.topic(), topic);
}
|
cpp
|
rticonnextdds-robot-helpers
|
data/projects/rticonnextdds-robot-helpers/rclcpp_dds/test/rclcpp_dds/test_callback.cpp
|
// Copyright 2021 Real-Time Innovations, Inc. (RTI)
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include <gtest/gtest.h>
#include <cstdlib>
#include <memory>
#include "std_msgs/msg/String.hpp"
#include "rclcpp_dds/rclcpp_dds.hpp"
template<typename NodeT>
void wait_with_timeout(
NodeT & node,
const std::chrono::nanoseconds & max_wait,
const std::chrono::nanoseconds & step_wait,
std::function<bool()> functor,
bool & timed_out)
{
auto start_ts = std::chrono::steady_clock::now();
bool complete = false;
timed_out = false;
do {
timed_out = std::chrono::steady_clock::now() - start_ts >= max_wait;
complete = functor();
if (!timed_out && !complete) {
node->dds_executor()->spin(step_wait);
}
} while (!timed_out && !complete);
}
class TestCallback : public ::testing::Test
{
protected:
static void SetUpTestCase()
{
rclcpp::init(0, nullptr);
}
static void TearDownTestCase()
{
rclcpp::shutdown();
}
void SetUp()
{
node = std::make_shared<rclcpp_dds::DDSNode>("my_node", "/ns");
}
void TearDown()
{
node.reset();
}
template<typename T>
dds::pub::DataWriter<T>
CreateWriter()
{
dds::pub::qos::DataWriterQos writer_qos = node->get_default_datawriter_qos();
writer_qos << dds::core::policy::Durability::TransientLocal();
writer_qos << dds::core::policy::Reliability::Reliable();
writer_qos << dds::core::policy::History::KeepLast(10);
return node->create_datawriter<T>("foo", writer_qos);
}
template<typename T>
dds::sub::DataReader<T>
CreateReader()
{
dds::sub::qos::DataReaderQos reader_qos = node->get_default_datareader_qos();
reader_qos << dds::core::policy::Durability::TransientLocal();
reader_qos << dds::core::policy::Reliability::Reliable();
reader_qos << dds::core::policy::History::KeepLast(10);
return node->create_datareader<T>("foo", reader_qos);
}
rclcpp_dds::DDSNode::SharedPtr node;
};
TEST_F(TestCallback, data_callback) {
using std_msgs::msg::String;
bool timed_out = false;
auto writer = CreateWriter<String>();
auto reader = CreateReader<String>();
size_t received_count = 0;
node->set_data_callback<String>(
reader,
[&received_count](
dds::sub::cond::ReadCondition & condition,
dds::sub::DataReader<String> & reader)
{
auto samples = reader.select().condition(condition).read();
for (const auto & sample : samples) {
(void)sample;
received_count += 1;
}
});
String msg("Hello World");
writer.write(msg);
using namespace std::chrono_literals;
wait_with_timeout(
node, 1000ms, 50ms,
[&received_count]() {
return received_count == 1;
}, timed_out);
ASSERT_FALSE(timed_out);
// Replace callback and check previous one isn't notified;
size_t received_count_2 = 0;
received_count = 0;
node->set_data_callback<String>(
reader,
[&received_count_2](const String & msg)
{
(void)msg;
received_count_2 += 1;
});
// Callback should not be called for already read samples
wait_with_timeout(
node, 500ms, 50ms,
[&received_count, &received_count_2]() {
return received_count > 0 || received_count_2 > 0;
}, timed_out);
ASSERT_TRUE(timed_out);
// New messages should only be notified to the new callback
writer.write(msg);
writer.write(msg);
wait_with_timeout(
node, 1000ms, 50ms,
[&received_count, &received_count_2]() {
return
received_count == 0 &&
received_count_2 == 2;
}, timed_out);
ASSERT_FALSE(timed_out);
// Register another callback, this time to be notified of "any data".
// Also, take messages out of the reader cache by using take_data_callback().
size_t received_count_3 = 0;
received_count_2 = 0;
received_count = 0;
node->set_data_callback<String, true>(
reader,
[&received_count_3](const String & msg)
{
(void)msg;
received_count_3 += 1;
},
dds::sub::status::DataState::any_data());
wait_with_timeout(
node, 1000ms, 50ms,
[&received_count, &received_count_2, &received_count_3]() {
return
received_count == 0 &&
received_count_2 == 0 &&
received_count_3 == 3;
}, timed_out);
ASSERT_FALSE(timed_out);
}
TEST_F(TestCallback, data_callback_w_query) {
using std_msgs::msg::String;
bool timed_out = false;
auto writer = CreateWriter<String>();
auto reader = CreateReader<String>();
size_t received_count = 0;
node->set_data_callback<String>(
reader,
[&received_count](
dds::sub::cond::QueryCondition & condition,
dds::sub::DataReader<String> & reader)
{
auto samples = reader.select().condition(condition).read();
for (const auto & sample : samples) {
(void)sample;
received_count += 1;
}
},
"data MATCH 'Hello World [0-9]'");
writer.write(String("Hello World"));
writer.write(String("Hello World 1"));
writer.write(String("Hello World 2"));
writer.write(String("Hello World 3"));
using namespace std::chrono_literals;
wait_with_timeout(
node, 1000ms, 50ms,
[&received_count]() {
return received_count == 3;
}, timed_out);
ASSERT_FALSE(timed_out);
// Replace callback and check previous one isn't notified
// Use query parameters this time, and check for "any" data
// (instead of just new).
size_t received_count_2 = 0;
received_count = 0;
node->set_data_callback<String, true>(
reader,
[&received_count_2](const String & msg)
{
(void)msg;
received_count_2 += 1;
},
"data MATCH %0 OR data MATCH %1",
dds::sub::status::DataState::any_data(),
{"'Hello World 1'", "'Hello World 3'"});
wait_with_timeout(
node, 1000ms, 50ms,
[&received_count, &received_count_2]() {
return
received_count == 0 &&
received_count_2 == 2;
}, timed_out);
ASSERT_FALSE(timed_out);
// Replace callback to take() all samples out of the reader cache.
size_t received_count_3 = 0;
received_count_2 = 0;
received_count = 0;
node->set_data_callback<String, true>(
reader,
[&received_count_3](const String & msg)
{
(void)msg;
received_count_3 += 1;
},
"data MATCH 'Hello World*'",
dds::sub::status::DataState::any_data());
wait_with_timeout(
node, 1000ms, 50ms,
[&received_count, &received_count_2, &received_count_3]() {
return
received_count == 0 &&
received_count_2 == 0 &&
received_count_3 == 2;
}, timed_out);
ASSERT_FALSE(timed_out);
}
|
cpp
|
rticonnextdds-robot-helpers
|
data/projects/rticonnextdds-robot-helpers/rclcpp_dds/test/rclcpp_dds/test_sub.cpp
|
// Copyright 2021 Real-Time Innovations, Inc. (RTI)
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include <gtest/gtest.h>
#include <cstdlib>
#include <memory>
#include "std_msgs/msg/String.hpp"
#include "example_interfaces/srv/AddTwoInts.hpp"
#include "rclcpp_dds/rclcpp_dds.hpp"
class TestSub : public ::testing::Test
{
protected:
static void SetUpTestCase()
{
rclcpp::init(0, nullptr);
}
static void TearDownTestCase()
{
rclcpp::shutdown();
}
void SetUp()
{
node = std::make_shared<rclcpp_dds::DDSNode>("my_node", "/ns");
}
void TearDown()
{
node.reset();
}
rclcpp_dds::DDSNode::SharedPtr node;
};
TEST_F(TestSub, create_datareader) {
using std_msgs::msg::String;
using example_interfaces::srv::AddTwoInts_Request;
using example_interfaces::srv::AddTwoInts_Response;
// Create a reader for a standard ROS topic
auto reader = node->create_datareader<String>("foo");
ASSERT_NE(reader, dds::core::null);
ASSERT_STREQ(reader.topic_description().name().c_str(), "rt/ns/foo");
ASSERT_STREQ(reader.topic_description().type_name().c_str(), "std_msgs::msg::dds_::String_");
// Create a reader for a standard ROS topic w/custom type name
auto reader_alt = node->create_datareader<String>("foo_alt", "custom_type_name");
ASSERT_NE(reader_alt, dds::core::null);
ASSERT_STREQ(reader_alt.topic_description().name().c_str(), "rt/ns/foo_alt");
ASSERT_STREQ(reader_alt.topic_description().type_name().c_str(), "dds_::custom_type_name_");
// Create a reader for a Request ROS topic
auto reader_req = node->create_service_datareader<AddTwoInts_Request>("foo");
ASSERT_NE(reader_req, dds::core::null);
ASSERT_STREQ(reader_req.topic_description().name().c_str(), "rq/ns/fooRequest");
ASSERT_STREQ(
reader_req.topic_description().type_name().c_str(),
"example_interfaces::srv::dds_::AddTwoInts_Request_");
// Create a reader for a Reply ROS topic
auto reader_rep = node->create_service_datareader<AddTwoInts_Response>("foo", false);
ASSERT_NE(reader_rep, dds::core::null);
ASSERT_STREQ(reader_rep.topic_description().name().c_str(), "rr/ns/fooReply");
ASSERT_STREQ(
reader_rep.topic_description().type_name().c_str(),
"example_interfaces::srv::dds_::AddTwoInts_Response_");
}
/******************************************************************************
* Test readers of DDS topics
******************************************************************************/
class TestSubDds : public ::testing::Test
{
protected:
static void SetUpTestCase()
{
rclcpp::init(0, nullptr);
}
static void TearDownTestCase()
{
rclcpp::shutdown();
}
void SetUp()
{
rclcpp_dds::DDSNodeOptions opts;
opts.use_ros_naming_conventions(false);
node = std::make_shared<rclcpp_dds::DDSNode>("my_node", "/ns", opts);
}
void TearDown()
{
node.reset();
}
rclcpp_dds::DDSNode::SharedPtr node;
};
TEST_F(TestSubDds, create_datareader) {
using std_msgs::msg::String;
using example_interfaces::srv::AddTwoInts_Request;
using example_interfaces::srv::AddTwoInts_Response;
// Create a reader for a standard topic
auto reader = node->create_datareader<String>("foo");
ASSERT_NE(reader, dds::core::null);
ASSERT_STREQ(reader.topic_description().name().c_str(), "foo");
ASSERT_STREQ(reader.topic_description().type_name().c_str(), "std_msgs::msg::String");
// Create a reader for a standard topic w/custom type name
auto reader_alt = node->create_datareader<String>("foo_alt", "custom_type_name");
ASSERT_NE(reader_alt, dds::core::null);
ASSERT_STREQ(reader_alt.topic_description().name().c_str(), "foo_alt");
ASSERT_STREQ(reader_alt.topic_description().type_name().c_str(), "custom_type_name");
// Create a reader for a Request topic
auto reader_req = node->create_service_datareader<AddTwoInts_Request>("foo");
ASSERT_NE(reader_req, dds::core::null);
ASSERT_STREQ(reader_req.topic_description().name().c_str(), "fooRequest");
ASSERT_STREQ(
reader_req.topic_description().type_name().c_str(),
"example_interfaces::srv::AddTwoInts_Request");
// Create a reader for a Reply topic
auto reader_rep = node->create_service_datareader<AddTwoInts_Response>("foo", false);
ASSERT_NE(reader_rep, dds::core::null);
ASSERT_STREQ(reader_rep.topic_description().name().c_str(), "fooReply");
ASSERT_STREQ(
reader_rep.topic_description().type_name().c_str(),
"example_interfaces::srv::AddTwoInts_Response");
}
|
cpp
|
rticonnextdds-robot-helpers
|
data/projects/rticonnextdds-robot-helpers/rclcpp_dds/test/rclcpp_dds/test_pub.cpp
|
// Copyright 2021 Real-Time Innovations, Inc. (RTI)
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include <gtest/gtest.h>
#include <cstdlib>
#include <memory>
#include "std_msgs/msg/String.hpp"
#include "example_interfaces/srv/AddTwoInts.hpp"
#include "rclcpp_dds/rclcpp_dds.hpp"
class TestPub : public ::testing::Test
{
protected:
static void SetUpTestCase()
{
rclcpp::init(0, nullptr);
}
static void TearDownTestCase()
{
rclcpp::shutdown();
}
void SetUp()
{
node = std::make_shared<rclcpp_dds::DDSNode>("my_node", "/ns");
}
void TearDown()
{
node.reset();
}
rclcpp_dds::DDSNode::SharedPtr node;
};
TEST_F(TestPub, create_datawriter) {
using std_msgs::msg::String;
using example_interfaces::srv::AddTwoInts_Request;
using example_interfaces::srv::AddTwoInts_Response;
// Create a writer for a standard ROS topic
auto writer = node->create_datawriter<String>("foo");
ASSERT_NE(writer, dds::core::null);
ASSERT_STREQ(writer.topic().name().c_str(), "rt/ns/foo");
ASSERT_STREQ(writer.topic().type_name().c_str(), "std_msgs::msg::dds_::String_");
// Create a writer for a standard ROS topic w/custom type name
auto writer_alt = node->create_datawriter<String>("foo_alt", "custom_type_name");
ASSERT_NE(writer_alt, dds::core::null);
ASSERT_STREQ(writer_alt.topic().name().c_str(), "rt/ns/foo_alt");
ASSERT_STREQ(writer_alt.topic().type_name().c_str(), "dds_::custom_type_name_");
// Create a writer for a Request ROS topic
auto writer_req = node->create_service_datawriter<AddTwoInts_Request>("foo");
ASSERT_NE(writer_req, dds::core::null);
ASSERT_STREQ(writer_req.topic().name().c_str(), "rq/ns/fooRequest");
ASSERT_STREQ(
writer_req.topic().type_name().c_str(),
"example_interfaces::srv::dds_::AddTwoInts_Request_");
// Create a writer for a Reply ROS topic
auto writer_rep = node->create_service_datawriter<AddTwoInts_Response>("foo", false);
ASSERT_NE(writer_rep, dds::core::null);
ASSERT_STREQ(writer_rep.topic().name().c_str(), "rr/ns/fooReply");
ASSERT_STREQ(
writer_rep.topic().type_name().c_str(),
"example_interfaces::srv::dds_::AddTwoInts_Response_");
}
/******************************************************************************
* Test writers of DDS topics
******************************************************************************/
class TestPubDds : public ::testing::Test
{
protected:
static void SetUpTestCase()
{
rclcpp::init(0, nullptr);
}
static void TearDownTestCase()
{
rclcpp::shutdown();
}
void SetUp()
{
rclcpp_dds::DDSNodeOptions opts;
opts.use_ros_naming_conventions(false);
node = std::make_shared<rclcpp_dds::DDSNode>("my_node", "/ns", opts);
}
void TearDown()
{
node.reset();
}
rclcpp_dds::DDSNode::SharedPtr node;
};
TEST_F(TestPubDds, create_datawriter) {
using std_msgs::msg::String;
using example_interfaces::srv::AddTwoInts_Request;
using example_interfaces::srv::AddTwoInts_Response;
// Create a writer for a standard topic
auto writer = node->create_datawriter<String>("foo");
ASSERT_NE(writer, dds::core::null);
ASSERT_STREQ(writer.topic().name().c_str(), "foo");
ASSERT_STREQ(writer.topic().type_name().c_str(), "std_msgs::msg::String");
// Create a writer for a standard topic w/custom type name
auto writer_alt = node->create_datawriter<String>("foo_alt", "custom_type_name");
ASSERT_NE(writer_alt, dds::core::null);
ASSERT_STREQ(writer_alt.topic().name().c_str(), "foo_alt");
ASSERT_STREQ(writer_alt.topic().type_name().c_str(), "custom_type_name");
// Create a writer for a Request topic
auto writer_req = node->create_service_datawriter<AddTwoInts_Request>("foo");
ASSERT_NE(writer_req, dds::core::null);
ASSERT_STREQ(writer_req.topic().name().c_str(), "fooRequest");
ASSERT_STREQ(
writer_req.topic().type_name().c_str(),
"example_interfaces::srv::AddTwoInts_Request");
// Create a writer for a Reply topic
auto writer_rep = node->create_service_datawriter<AddTwoInts_Response>("foo", false);
ASSERT_NE(writer_rep, dds::core::null);
ASSERT_STREQ(writer_rep.topic().name().c_str(), "fooReply");
ASSERT_STREQ(
writer_rep.topic().type_name().c_str(),
"example_interfaces::srv::AddTwoInts_Response");
}
|
cpp
|
rticonnextdds-robot-helpers
|
data/projects/rticonnextdds-robot-helpers/rclcpp_dds/test/rclcpp_dds/test_domain.cpp
|
// Copyright 2021 Real-Time Innovations, Inc. (RTI)
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include <cstdlib>
#include <memory>
#include <string>
#include "gtest/gtest.h"
#include "rcutils/env.h"
#include "rclcpp/init_options.hpp"
#include "rclcpp/node_options.hpp"
#include "rclcpp_dds/rclcpp_dds.hpp"
class TestDomain : public ::testing::Test
{
protected:
static void SetUpTestCase()
{
rclcpp::init(0, nullptr);
}
static void TearDownTestCase()
{
rclcpp::shutdown();
}
void SetUp()
{
node = std::make_shared<rclcpp_dds::DDSNode>("my_node", "/ns");
}
void TearDown()
{
node.reset();
}
rclcpp_dds::DDSNode::SharedPtr node;
};
class TestDomainCustom : public TestDomain
{
protected:
static void SetUpTestCase()
{
#ifdef ROS_GALACTIC_OR_LATER
// In Galactic+, we can use InitOptions::set_domain_id().
// In earlier versions we must configure the domain id through env variables.
rclcpp::InitOptions opts;
opts.set_domain_id(46);
rclcpp::init(0, nullptr, opts);
#else
const char * const env_rc = rcutils_get_env("ROS_DOMAIN_ID", &env_domain_id);
if (nullptr != env_rc) {
throw std::runtime_error("failed to get ROS_DOMAIN_ID");
}
std::string custom_domain = std::to_string(46);
if (!rcutils_set_env("ROS_DOMAIN_ID", custom_domain.c_str())) {
throw std::runtime_error("failed to set ROS_DOMAIN_ID");
}
rclcpp::init(0, nullptr);
#endif
}
static void TearDownTestCase()
{
rclcpp::shutdown();
#ifndef ROS_GALACTIC_OR_LATER
if (!rcutils_set_env("ROS_DOMAIN_ID", env_domain_id)) {
throw std::runtime_error("failed to restore ROS_DOMAIN_ID");
}
env_domain_id = nullptr;
#endif
}
static const char * env_domain_id;
};
const char * TestDomainCustom::env_domain_id = nullptr;
TEST_F(TestDomain, domain_id) {
ASSERT_EQ(node->domain_id(), 0U);
}
TEST_F(TestDomainCustom, domain_id) {
ASSERT_EQ(node->domain_id(), 46U);
}
TEST_F(TestDomain, domain_participant) {
ASSERT_NO_THROW(
{
node->domain_participant();
});
auto participant = node->domain_participant();
ASSERT_NE(participant, dds::core::null);
ASSERT_EQ(participant.domain_id(), 0);
}
TEST_F(TestDomainCustom, domain_participant) {
ASSERT_NO_THROW(
{
node->domain_participant();
});
auto participant = node->domain_participant();
ASSERT_NE(participant, dds::core::null);
ASSERT_EQ(participant.domain_id(), 46);
}
|
cpp
|
rticonnextdds-robot-helpers
|
data/projects/rticonnextdds-robot-helpers/rclcpp_dds/include/rclcpp_dds/rclcpp_dds.hpp
|
// Copyright 2021 Real-Time Innovations, Inc. (RTI)
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#ifndef RCLCPP_DDS__RCLCPP_DDS_HPP_
#define RCLCPP_DDS__RCLCPP_DDS_HPP_
#include "rclcpp_dds/dds_node_options.hpp"
#include "rclcpp_dds/dds_node_mixin.hpp"
#include "rclcpp_dds/dds_node.hpp"
#endif // RCLCPP_DDS__RCLCPP_DDS_HPP_
|
hpp
|
rticonnextdds-robot-helpers
|
data/projects/rticonnextdds-robot-helpers/rclcpp_dds/include/rclcpp_dds/dds_node_options.hpp
|
// Copyright 2021 Real-Time Innovations, Inc. (RTI)
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#ifndef RCLCPP_DDS__DDS_NODE_OPTIONS_HPP_
#define RCLCPP_DDS__DDS_NODE_OPTIONS_HPP_
#include "rclcpp/rclcpp.hpp"
#include "ros2dds/ros2dds.hpp"
#include "rclcpp_dds/visibility_control.hpp"
namespace rclcpp_dds
{
class DDSNodeOptions : public rclcpp::NodeOptions
{
public:
RCLCPP_DDS_PUBLIC
explicit DDSNodeOptions(rcl_allocator_t allocator = rcl_get_default_allocator())
: NodeOptions(allocator)
{}
/// Destructor.
RCLCPP_DDS_PUBLIC
virtual
~DDSNodeOptions() = default;
/// Copy constructor.
RCLCPP_DDS_PUBLIC
DDSNodeOptions(const DDSNodeOptions & other)
: NodeOptions(other),
use_ros_naming_conventions_(other.use_ros_naming_conventions_),
dds_executor_(other.dds_executor_)
{}
RCLCPP_DDS_PUBLIC
DDSNodeOptions(const NodeOptions & other)
: NodeOptions(other)
{}
/// Assignment operator.
RCLCPP_DDS_PUBLIC
DDSNodeOptions &
operator=(const DDSNodeOptions & other)
{
rclcpp::NodeOptions::operator=(other);
if (this != &other) {
use_ros_naming_conventions_ = other.use_ros_naming_conventions_;
dds_executor_ = other.dds_executor_;
}
return *this;
}
RCLCPP_DDS_PUBLIC
DDSNodeOptions &
operator=(const NodeOptions & other)
{
rclcpp::NodeOptions::operator=(other);
return *this;
}
RCLCPP_DDS_PUBLIC
bool
use_ros_naming_conventions() const
{
return use_ros_naming_conventions_;
}
RCLCPP_DDS_PUBLIC
DDSNodeOptions &
use_ros_naming_conventions(const bool the_use_ros_naming_conventions)
{
use_ros_naming_conventions_ = the_use_ros_naming_conventions;
return *this;
}
RCLCPP_DDS_PUBLIC
std::shared_ptr<ros2dds::WaitSetExecutor> &
dds_executor()
{
return dds_executor_;
}
RCLCPP_DDS_PUBLIC
std::shared_ptr<ros2dds::WaitSetExecutor>
dds_executor() const
{
return dds_executor_;
}
RCLCPP_DDS_PUBLIC
DDSNodeOptions &
dds_executor(const std::shared_ptr<ros2dds::WaitSetExecutor> & the_dds_executor)
{
dds_executor_ = the_dds_executor;
return *this;
}
private:
bool use_ros_naming_conventions_{true};
std::shared_ptr<ros2dds::WaitSetExecutor> dds_executor_;
};
} // namespace rclcpp_dds
#endif // RCLCPP_DDS__DDS_NODE_OPTIONS_HPP_
|
hpp
|
rticonnextdds-robot-helpers
|
data/projects/rticonnextdds-robot-helpers/rclcpp_dds/include/rclcpp_dds/dds_node_mixin.hpp
|
// Copyright 2021 Real-Time Innovations, Inc. (RTI)
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#ifndef RCLCPP_DDS__DDS_NODE_MIXIN_HPP_
#define RCLCPP_DDS__DDS_NODE_MIXIN_HPP_
#include <string>
#include <vector>
#include <memory>
#include "ros2dds/ros2dds.hpp"
#include "rclcpp_dds/dds_node_options.hpp"
#include "rclcpp_dds/visibility_control.hpp"
namespace rclcpp_dds
{
// template<
// typename NodeT,
// typename ExecutorT>
template<typename NodeT>
class DDSNodeMixin : public NodeT
{
public:
using TopicKind = ros2dds::TopicKind;
explicit DDSNodeMixin(
const std::string & node_name,
const DDSNodeOptions & options = DDSNodeOptions())
: NodeT(node_name, options),
node_options_(options)
{
if (nullptr != options.dds_executor()) {
exec_ = options.dds_executor();
} else {
exec_ = std::make_shared<ros2dds::AsyncWaitSetExecutor>();
}
}
explicit DDSNodeMixin(
const std::string & node_name,
const std::string & namespace_,
const DDSNodeOptions & options = DDSNodeOptions())
: NodeT(node_name, namespace_, options),
node_options_(options)
{
if (nullptr != options.dds_executor()) {
exec_ = options.dds_executor();
} else {
exec_ = std::make_shared<ros2dds::AsyncWaitSetExecutor>();
}
}
virtual ~DDSNodeMixin() = default;
/**
* @brief Access the DDS domain joined by this node.
*
* @return An unsigned integer identifying the DDS domain joined by this node.
*/
size_t domain_id()
{
return ros2dds::domain_id(*this->as_rclcpp_node());
}
/**
* @brief Access the DDS DomainParticipant associated with this node.
*
* @return The dds::domain::DomainParticipant instance associated with this node.
*/
dds::domain::DomainParticipant &
domain_participant()
{
// Cache domain participant for later lookups.
if (nullptr == domain_participant_) {
domain_participant_ = ros2dds::domain_participant(*this->as_rclcpp_node());
}
return domain_participant_;
}
template<typename MessageT>
dds::topic::Topic<MessageT>
create_topic(
const std::string & topic_name,
const std::string & custom_type_name = std::string())
{
return ros2dds::create_topic<MessageT>(
*this->as_rclcpp_node(),
topic_name,
TopicKind::Topic,
node_options_.use_ros_naming_conventions(),
custom_type_name);
}
template<typename MessageT>
dds::topic::Topic<MessageT>
create_service_topic(
const std::string & service_name,
const bool request = true,
const std::string & custom_type_name = std::string())
{
return ros2dds::create_topic<MessageT>(
*this->as_rclcpp_node(),
service_name,
(request) ? TopicKind::Request : TopicKind::Reply,
node_options_.use_ros_naming_conventions(),
custom_type_name);
}
template<typename MessageT>
dds::topic::Topic<MessageT>
lookup_topic(const std::string & topic_name)
{
return ros2dds::lookup_topic<MessageT>(
*this->as_rclcpp_node(),
topic_name,
TopicKind::Topic,
node_options_.use_ros_naming_conventions());
}
template<typename MessageT>
dds::topic::Topic<MessageT>
lookup_service_topic(
const std::string & service_name,
const bool request = true)
{
return ros2dds::lookup_topic<MessageT>(
*this->as_rclcpp_node(),
service_name,
(request) ? TopicKind::Request : TopicKind::Reply,
node_options_.use_ros_naming_conventions());
}
template<typename MessageT>
dds::topic::ContentFilteredTopic<MessageT>
create_content_filtered_topic(
dds::topic::Topic<MessageT> & base_topic,
const std::string & filter_name,
const std::string & filter_expression,
const std::vector<std::string> & filter_parameters = std::vector<std::string>())
{
return ros2dds::create_content_filtered_topic<MessageT>(
*this->as_rclcpp_node(),
base_topic,
filter_name,
filter_expression,
filter_parameters);
}
template<typename MessageT>
dds::topic::ContentFilteredTopic<MessageT>
lookup_content_filtered_topic(const std::string & filter_name)
{
return ros2dds::lookup_content_filtered_topic<MessageT>(*this->as_rclcpp_node(), filter_name);
}
/**
* @brief
*
* @param fq_topic_name
* @return dds::pub::qos::DataWriterQos
*/
dds::pub::qos::DataWriterQos
get_default_datawriter_qos(const std::string & fq_topic_name = std::string())
{
if (fq_topic_name.length() > 0) {
return ros2dds::default_datawriter_qos(
*this->as_rclcpp_node(),
fq_topic_name,
false /* expand */);
} else {
return ros2dds::default_datawriter_qos(*this->as_rclcpp_node());
}
}
/**
* @brief
*
* @param fq_topic_name
* @return dds::sub::qos::DataReaderQos
*/
dds::sub::qos::DataReaderQos
get_default_datareader_qos(const std::string & fq_topic_name = std::string())
{
if (fq_topic_name.length() > 0) {
return ros2dds::default_datareader_qos(
*this->as_rclcpp_node(),
fq_topic_name,
false /* expand */);
} else {
return ros2dds::default_datareader_qos(*this->as_rclcpp_node());
}
}
/**
* @brief
*
* @param qos_profile
* @param topic_name
* @return dds::pub::qos::DataWriterQos
*/
dds::pub::qos::DataWriterQos
get_datawriter_qos_profile(const std::string & qos_profile)
{
// TODO(asorbini) support get_w_topic_name()
return ros2dds::datawriter_qos_profile(*this->as_rclcpp_node(), qos_profile);
}
/**
* @brief
*
* @param qos_profile
* @param topic_name
* @return dds::pub::qos::DataReaderQos
*/
dds::sub::qos::DataReaderQos
get_datareader_qos_profile(const std::string & qos_profile)
{
// TODO(asorbini) support get_w_topic_name()
return ros2dds::datareader_qos_profile(*this->as_rclcpp_node(), qos_profile);
}
template<typename MessageT>
dds::pub::DataWriter<MessageT>
create_datawriter(
const std::string & topic_name,
const std::string & type_name = std::string())
{
return ros2dds::create_datawriter<MessageT>(
*this->as_rclcpp_node(),
topic_name,
TopicKind::Topic,
node_options_.use_ros_naming_conventions(),
type_name);
}
template<typename MessageT>
dds::pub::DataWriter<MessageT>
create_datawriter(
const std::string & topic_name,
const dds::pub::qos::DataWriterQos & qos,
const std::string & type_name = std::string())
{
return ros2dds::create_datawriter<MessageT>(
*this->as_rclcpp_node(),
topic_name,
qos,
TopicKind::Topic,
node_options_.use_ros_naming_conventions(),
type_name);
}
template<typename MessageT>
dds::pub::DataWriter<MessageT>
create_datawriter(dds::topic::Topic<MessageT> & topic)
{
return ros2dds::create_datawriter<MessageT>(*this->as_rclcpp_node(), topic);
}
template<typename MessageT>
dds::pub::DataWriter<MessageT>
create_datawriter(
dds::topic::Topic<MessageT> & topic,
const dds::pub::qos::DataWriterQos & qos)
{
return ros2dds::create_datawriter<MessageT>(*this->as_rclcpp_node(), topic, qos);
}
/////
template<typename MessageT>
dds::pub::DataWriter<MessageT>
create_service_datawriter(
const std::string & topic_name,
const bool request = true,
const std::string & custom_type_name = std::string())
{
return ros2dds::create_datawriter<MessageT>(
*this->as_rclcpp_node(),
topic_name,
(request) ? TopicKind::Request : TopicKind::Reply,
node_options_.use_ros_naming_conventions(),
custom_type_name);
}
template<typename MessageT>
dds::pub::DataWriter<MessageT>
create_service_datawriter(
const std::string & topic_name,
const dds::pub::qos::DataWriterQos & qos,
const bool request = false,
const std::string & custom_type_name = std::string())
{
return ros2dds::create_datawriter<MessageT>(
*this->as_rclcpp_node(),
topic_name,
qos,
(request) ? TopicKind::Request : TopicKind::Reply,
node_options_.use_ros_naming_conventions(),
custom_type_name);
}
/////
template<typename MessageT>
dds::sub::DataReader<MessageT>
create_datareader(
const std::string & topic_name,
const std::string & custom_type_name = std::string())
{
return ros2dds::create_datareader<MessageT>(
*this->as_rclcpp_node(),
topic_name,
TopicKind::Topic,
node_options_.use_ros_naming_conventions(),
custom_type_name);
}
template<typename MessageT>
dds::sub::DataReader<MessageT>
create_datareader(
const std::string & topic_name,
const dds::sub::qos::DataReaderQos & qos,
const std::string & custom_type_name = std::string())
{
return ros2dds::create_datareader<MessageT>(
*this->as_rclcpp_node(),
topic_name,
qos,
TopicKind::Topic,
node_options_.use_ros_naming_conventions(),
custom_type_name);
}
template<typename MessageT>
dds::sub::DataReader<MessageT>
create_datareader(dds::topic::Topic<MessageT> & topic)
{
return ros2dds::create_datareader<MessageT>(*this->as_rclcpp_node(), topic);
}
template<typename MessageT>
dds::sub::DataReader<MessageT>
create_datareader(
dds::topic::Topic<MessageT> & topic,
const dds::sub::qos::DataReaderQos & qos)
{
return ros2dds::create_datareader<MessageT>(*this->as_rclcpp_node(), topic, qos);
}
////
template<typename MessageT>
dds::sub::DataReader<MessageT>
create_service_datareader(
const std::string & topic_name,
const bool request = true,
const std::string & custom_type_name = std::string())
{
return ros2dds::create_datareader<MessageT>(
*this->as_rclcpp_node(),
topic_name,
(request) ? TopicKind::Request : TopicKind::Reply,
node_options_.use_ros_naming_conventions(),
custom_type_name);
}
template<typename MessageT>
dds::sub::DataReader<MessageT>
create_service_datareader(
const std::string & topic_name,
const dds::sub::qos::DataReaderQos & qos,
const bool request = true,
const std::string & custom_type_name = std::string())
{
return ros2dds::create_datareader<MessageT>(
*this->as_rclcpp_node(),
topic_name,
qos,
(request) ? TopicKind::Request : TopicKind::Reply,
node_options_.use_ros_naming_conventions(),
custom_type_name);
}
////
template<typename MessageT>
void
set_data_callback(
dds::sub::DataReader<MessageT> reader,
ros2dds::condition::DataCallback<MessageT> cb,
dds::sub::status::DataState data_state = dds::sub::status::DataState::new_data())
{
detach_data_callback<MessageT>(reader);
auto condition = ros2dds::condition::template data<MessageT>(reader, cb, data_state);
attach_condition(condition);
read_conditions_.push_back(std::move(condition));
}
template<typename MessageT>
void
set_data_callback(
dds::sub::DataReader<MessageT> reader,
ros2dds::condition::DataQueryCallback<MessageT> cb,
const std::string & query_expression,
dds::sub::status::DataState data_state = dds::sub::status::DataState::new_data(),
const std::vector<std::string> & query_parameters = std::vector<std::string>())
{
detach_data_callback<MessageT>(reader);
auto condition = ros2dds::condition::template query<MessageT>(
reader, cb, query_expression, data_state, query_parameters);
attach_condition(condition);
query_conditions_.push_back(std::move(condition));
}
template<typename MessageT, bool Take = false>
void
set_data_callback(
dds::sub::DataReader<MessageT> reader,
ros2dds::condition::MessageCallback<MessageT> cb,
dds::sub::status::DataState data_state = dds::sub::status::DataState::new_data())
{
detach_data_callback<MessageT>(reader);
auto condition = ros2dds::condition::template read_data<MessageT, Take>(reader, cb, data_state);
attach_condition(condition);
read_conditions_.push_back(std::move(condition));
}
template<typename MessageT, bool Take = false>
void
set_data_callback(
dds::sub::DataReader<MessageT> reader,
ros2dds::condition::MessageCallback<MessageT> cb,
const std::string & query_expression,
dds::sub::status::DataState data_state = dds::sub::status::DataState::new_data(),
const std::vector<std::string> & query_parameters = std::vector<std::string>())
{
detach_data_callback<MessageT>(reader);
auto condition = ros2dds::condition::template read_query<MessageT, Take>(
reader, cb, query_expression, data_state, query_parameters);
attach_condition(condition);
query_conditions_.push_back(std::move(condition));
}
template<typename MessageT>
void
set_status_callback(
dds::sub::DataReader<MessageT> reader,
ros2dds::condition::DataReaderStatusCallback<MessageT> cb,
const dds::core::status::StatusMask enabled_statuses)
{
detach_status_callback<MessageT>(reader);
auto condition = ros2dds::condition::template status<MessageT>(reader, cb, enabled_statuses);
attach_condition(condition);
status_conditions_readers_.push_back(std::move(condition));
}
template<typename MessageT>
void
set_status_callback(
dds::pub::DataWriter<MessageT> writer,
ros2dds::condition::DataWriterStatusCallback<MessageT> cb,
const dds::core::status::StatusMask enabled_statuses)
{
detach_status_callback<MessageT>(writer);
auto condition = ros2dds::condition::template status<MessageT>(writer, cb, enabled_statuses);
attach_condition(condition);
status_conditions_writers_.push_back(std::move(condition));
}
template<typename CallbackT>
dds::core::cond::GuardCondition
add_user_callback(CallbackT cb)
{
auto condition = ros2dds::condition::guard(cb);
attach_condition(condition);
guard_conditions_.push_back(condition);
return condition;
}
void
cancel_user_callback(const dds::core::cond::GuardCondition & user_condition)
{
for (auto it = guard_conditions_.begin(); it != guard_conditions_.end(); ++it) {
if (*it == user_condition) {
detach_condition(*it);
guard_conditions_.erase(it);
return;
}
}
}
template<typename MessageT>
void
cancel_data_callback(const dds::sub::DataReader<MessageT> & reader)
{
detach_data_callback<MessageT>(reader);
}
template<typename MessageT>
void
cancel_status_callback(const dds::sub::DataReader<MessageT> & reader)
{
detach_status_callback<MessageT>(reader);
}
template<typename MessageT>
void
cancel_status_callback(const dds::pub::DataWriter<MessageT> & writer)
{
detach_status_callback<MessageT>(writer);
}
RCLCPP_DDS_PUBLIC
std::shared_ptr<ros2dds::WaitSetExecutor> &
dds_executor()
{
return exec_;
}
RCLCPP_DDS_PUBLIC
std::shared_ptr<ros2dds::WaitSetExecutor>
dds_executor() const
{
return exec_;
}
protected:
void
get_callback_conditions(std::vector<dds::core::cond::Condition> & conditions_seq)
{
for (auto && cond_ref : read_conditions_) {
dds::core::cond::Condition cond = cond_ref;
conditions_seq.push_back(std::move(cond));
}
for (auto && cond_ref : query_conditions_) {
dds::core::cond::Condition cond = cond_ref;
conditions_seq.push_back(std::move(cond));
}
for (auto && cond_ref : status_conditions_readers_) {
dds::core::cond::Condition cond = cond_ref;
conditions_seq.push_back(std::move(cond));
}
for (auto && cond_ref : status_conditions_writers_) {
dds::core::cond::Condition cond = cond_ref;
conditions_seq.push_back(std::move(cond));
}
}
void
attach_condition(const dds::core::cond::Condition & condition)
{
exec_->attach(condition);
}
void
detach_condition(const dds::core::cond::Condition & condition)
{
exec_->detach(condition);
}
template<typename MessageT>
bool detach_data_callback(const dds::sub::DataReader<MessageT> & reader)
{
auto any_reader = dds::sub::AnyDataReader(reader);
for (auto it = read_conditions_.begin(); it != read_conditions_.end(); ++it) {
if ((*it).data_reader() == any_reader) {
detach_condition(*it);
read_conditions_.erase(it);
return true;
}
}
for (auto it = query_conditions_.begin(); it != query_conditions_.end(); ++it) {
if ((*it).data_reader() == any_reader) {
detach_condition(*it);
query_conditions_.erase(it);
return true;
}
}
return false;
}
template<typename MessageT>
bool detach_status_callback(const dds::sub::DataReader<MessageT> & reader)
{
auto any_reader = dds::sub::AnyDataReader(reader);
for (auto it = status_conditions_readers_.begin();
it != status_conditions_readers_.end(); ++it)
{
auto e_any_reader = dds::core::polymorphic_cast<dds::sub::AnyDataReader>((*it).entity());
if (e_any_reader == any_reader) {
detach_condition(*it);
status_conditions_readers_.erase(it);
return true;
}
}
return false;
}
template<typename MessageT>
bool detach_status_callback(const dds::pub::DataWriter<MessageT> & writer)
{
auto any_writer = dds::pub::AnyDataWriter(writer);
for (auto it = status_conditions_writers_.begin();
it != status_conditions_writers_.end(); ++it)
{
auto e_any_writer = dds::core::polymorphic_cast<dds::pub::AnyDataWriter>((*it).entity());
if (e_any_writer == any_writer) {
detach_condition(*it);
status_conditions_writers_.erase(it);
return true;
}
}
return false;
}
protected:
rclcpp::Node* as_rclcpp_node()
{
return dynamic_cast<rclcpp::Node*>(this);
}
const rclcpp::Node* as_rclcpp_node() const
{
return dynamic_cast<const rclcpp::Node*>(this);
}
private:
const DDSNodeOptions node_options_;
dds::domain::DomainParticipant domain_participant_{nullptr};
// std::vector<dds::sub::AnyDataReader> datareaders_;
// std::vector<dds::pub::AnyDataWriter> datawriters_;
std::shared_ptr<ros2dds::WaitSetExecutor> exec_;
std::vector<dds::sub::cond::ReadCondition> read_conditions_;
std::vector<dds::sub::cond::QueryCondition> query_conditions_;
std::vector<dds::core::cond::StatusCondition> status_conditions_readers_;
std::vector<dds::core::cond::StatusCondition> status_conditions_writers_;
std::vector<dds::core::cond::GuardCondition> guard_conditions_;
};
} // namespace rclcpp_dds
#endif // RCLCPP_DDS__DDS_NODE_MIXIN_HPP_
|
hpp
|
rticonnextdds-robot-helpers
|
data/projects/rticonnextdds-robot-helpers/rclcpp_dds/include/rclcpp_dds/dds_node.hpp
|
// Copyright 2021 Real-Time Innovations, Inc. (RTI)
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#ifndef RCLCPP_DDS__DDS_NODE_HPP_
#define RCLCPP_DDS__DDS_NODE_HPP_
#include <string>
#include "rclcpp/macros.hpp"
#include "rclcpp_dds/dds_node_mixin.hpp"
namespace rclcpp_dds
{
class DDSNode : public DDSNodeMixin<rclcpp::Node>
{
public:
// NOTE: cppcheck on Foxy fails to correctly resolve the following macro's definition.
// This is resolved in later versions, see https://github.com/ament/ament_lint/issues/116
// The following #ifndef causes cppcheck to succeed even for Foxy.
#ifndef RCLCPP_SMART_PTR_DEFINITIONS
#error "RCLCPP_SMART_PTR_DEFINITIONS undefined"
#endif // RCLCPP_SMART_PTR_DEFINITIONS
RCLCPP_SMART_PTR_DEFINITIONS(DDSNode)
RCLCPP_DDS_PUBLIC
explicit DDSNode(
const std::string & node_name,
const DDSNodeOptions & options = DDSNodeOptions());
RCLCPP_DDS_PUBLIC
explicit DDSNode(
const std::string & node_name,
const std::string & namespace_,
const DDSNodeOptions & options = DDSNodeOptions());
private:
RCLCPP_DISABLE_COPY(DDSNode)
};
} // namespace rclcpp_dds
#endif // RCLCPP_DDS__DDS_NODE_HPP_
|
hpp
|
rticonnextdds-robot-helpers
|
data/projects/rticonnextdds-robot-helpers/rclcpp_dds/include/rclcpp_dds/visibility_control.hpp
|
// Copyright 2015 Open Source Robotics Foundation, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#ifndef RCLCPP_DDS__VISIBILITY_CONTROL_HPP_
#define RCLCPP_DDS__VISIBILITY_CONTROL_HPP_
// This logic was borrowed (then namespaced) from the examples on the gcc wiki:
// https://gcc.gnu.org/wiki/Visibility
#if defined _WIN32 || defined __CYGWIN__
#ifdef __GNUC__
#define RCLCPP_DDS_EXPORT __attribute__ ((dllexport))
#define RCLCPP_DDS_IMPORT __attribute__ ((dllimport))
#else
#define RCLCPP_DDS_EXPORT __declspec(dllexport)
#define RCLCPP_DDS_IMPORT __declspec(dllimport)
#endif
#ifdef RCLCPP_DDS_BUILDING_LIBRARY
#define RCLCPP_DDS_PUBLIC RCLCPP_DDS_EXPORT
#else
#define RCLCPP_DDS_PUBLIC RCLCPP_DDS_IMPORT
#endif
#define RCLCPP_DDS_PUBLIC_TYPE RCLCPP_DDS_PUBLIC
#define RCLCPP_DDS_LOCAL
#else
#define RCLCPP_DDS_EXPORT __attribute__ ((visibility("default")))
#define RCLCPP_DDS_IMPORT
#if __GNUC__ >= 4
#define RCLCPP_DDS_PUBLIC __attribute__ ((visibility("default")))
#define RCLCPP_DDS_LOCAL __attribute__ ((visibility("hidden")))
#else
#define RCLCPP_DDS_PUBLIC
#define RCLCPP_DDS_LOCAL
#endif
#define RCLCPP_DDS_PUBLIC_TYPE
#endif
#endif // RCLCPP_DDS__VISIBILITY_CONTROL_HPP_
|
hpp
|
rticonnextdds-robot-helpers
|
data/projects/rticonnextdds-robot-helpers/ros2dds/src/resolve.cpp
|
// Copyright 2021 Real-Time Innovations, Inc. (RTI)
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include <string>
#include "ros2dds/resolve.hpp"
namespace ros2dds
{
std::string
resolve_topic_name(
const std::string & node_name,
const std::string & node_namespace,
const std::string & topic_name,
const TopicKind topic_kind,
const bool use_ros_conventions)
{
static const char * topic_prefixes[] = {
"rt", // RosTopic
"rq", // RosRequest
"rr" // RosReply
};
static const char * topic_suffixes[] = {
"", // RosTopic
"Request", // RosRequest
"Reply" // RosReply
};
if (topic_name.length() == 0) {
throw rclcpp::exceptions::InvalidTopicNameError(
topic_name.c_str(), "topic name cannot be empty", 0);
}
std::string suffix = topic_suffixes[static_cast<int>(topic_kind)];
if (!use_ros_conventions) {
return topic_name + suffix;
} else {
const bool is_service = topic_kind != TopicKind::Topic;
std::string prefix = topic_prefixes[static_cast<int>(topic_kind)];
std::string fq_name = rclcpp::expand_topic_or_service_name(
topic_name, node_name, node_namespace, is_service);
return prefix + fq_name + suffix;
}
}
std::string
resolve_type_name(
const std::string & type_name,
const bool use_ros_conventions)
{
if (!use_ros_conventions) {
return type_name;
}
std::ostringstream ss;
const size_t base_name_pos = type_name.rfind("::");
std::string type_base_name;
std::string type_ns;
if (base_name_pos != std::string::npos) {
type_base_name = type_name.substr(base_name_pos + 2);
type_ns = type_name.substr(0, base_name_pos);
} else {
type_base_name = type_name;
}
const std::string dds_ns = "dds_";
const std::string dds_ns_sfx = "::" + dds_ns;
if (!type_ns.empty()) {
if (type_ns == dds_ns) {
ss << type_ns;
} else if (type_ns.length() > dds_ns.length()) {
ss << type_ns;
const size_t dds_ns_pos = type_ns.rfind(dds_ns_sfx);
if (dds_ns_pos != std::string::npos) {
if (type_ns.substr(dds_ns_pos).length() != dds_ns_sfx.length()) {
throw std::runtime_error(
"invalid type name: `dds_` should appear last in namespace");
}
} else {
ss << dds_ns_sfx;
}
} else {
ss << type_ns << dds_ns_sfx;
}
} else {
ss << dds_ns;
}
ss << "::" << type_base_name;
if (type_base_name[type_base_name.length() - 1] != '_') {
ss << "_";
}
return ss.str();
}
template<>
std::string
resolve_topic_name(
rclcpp::Node & node,
const std::string & topic_name,
const TopicKind topic_kind,
const bool use_ros_conventions)
{
if (!use_ros_conventions) {
return topic_name;
}
if (topic_kind == TopicKind::Request || topic_kind == TopicKind::Reply)
{
std::string sub_namespace = node.get_sub_namespace();
std::string res_topic_name(topic_name);
if (sub_namespace != "" && topic_name.front() != '/' && topic_name.front() != '~') {
res_topic_name = sub_namespace + "/" + topic_name;
}
return resolve_topic_name(
node_name(node), node_namespace(node), res_topic_name, topic_kind, true);
}
auto node_topics_interface = rclcpp::node_interfaces::get_node_topics_interface(node);
auto resolved = node_topics_interface->resolve_topic_name(topic_name);
return resolve_topic_name(
node_name(node), node_namespace(node), resolved.c_str(),
TopicKind::Topic, true);
}
} // namespace ros2dds
|
cpp
|
rticonnextdds-robot-helpers
|
data/projects/rticonnextdds-robot-helpers/ros2dds/test/ros2dds/test_topic.cpp
|
// Copyright 2021 Real-Time Innovations, Inc. (RTI)
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include <gtest/gtest.h>
#include <cstdlib>
#include <memory>
#include "std_msgs/msg/String.hpp"
#include "example_interfaces/srv/AddTwoInts.hpp"
#include "ros2dds/topic.hpp"
class TestTopic : public ::testing::Test
{
protected:
static void SetUpTestCase()
{
rclcpp::init(0, nullptr);
}
static void TearDownTestCase()
{
rclcpp::shutdown();
}
void SetUp()
{
node = std::make_shared<rclcpp::Node>("my_node", "/ns");
}
void TearDown()
{
node.reset();
}
rclcpp::Node::SharedPtr node;
};
TEST_F(TestTopic, create_topic_ros) {
using ros2dds::create_topic;
using ros2dds::TopicKind;
// Create a standard ROS topic
auto topic = create_topic<std_msgs::msg::String>(*node, "foo");
ASSERT_NE(topic, dds::core::null);
ASSERT_STREQ(topic.name().c_str(), "rt/ns/foo");
ASSERT_STREQ(topic.type_name().c_str(), "std_msgs::msg::dds_::String_");
// Create a standard ROS topic w/custom type name
auto topic_alt = create_topic<std_msgs::msg::String>(
*node, "foo_alt", TopicKind::Topic, true, "custom_type");
ASSERT_NE(topic_alt, dds::core::null);
ASSERT_STREQ(topic_alt.name().c_str(), "rt/ns/foo_alt");
ASSERT_STREQ(topic_alt.type_name().c_str(), "dds_::custom_type_");
// Create a Request ROS topic
auto topic_req = create_topic<example_interfaces::srv::AddTwoInts_Request>(
*node, "foo", TopicKind::Request);
ASSERT_NE(topic_req, dds::core::null);
ASSERT_STREQ(topic_req.name().c_str(), "rq/ns/fooRequest");
ASSERT_STREQ(topic_req.type_name().c_str(), "example_interfaces::srv::dds_::AddTwoInts_Request_");
// Create a Reply ROS topic
auto topic_rep = create_topic<example_interfaces::srv::AddTwoInts_Response>(
*node, "foo", TopicKind::Reply);
ASSERT_NE(topic_rep, dds::core::null);
ASSERT_STREQ(topic_rep.name().c_str(), "rr/ns/fooReply");
ASSERT_STREQ(
topic_rep.type_name().c_str(),
"example_interfaces::srv::dds_::AddTwoInts_Response_");
}
TEST_F(TestTopic, create_topic_dds) {
using ros2dds::create_topic;
using ros2dds::TopicKind;
using std_msgs::msg::String;
using example_interfaces::srv::AddTwoInts_Request;
using example_interfaces::srv::AddTwoInts_Response;
// Create a standard topic
auto topic = create_topic<String>(*node, "foo", TopicKind::Topic, false);
ASSERT_NE(topic, dds::core::null);
ASSERT_STREQ(topic.name().c_str(), "foo");
ASSERT_STREQ(topic.type_name().c_str(), "std_msgs::msg::String");
// Create a standard topic with a custom type name
auto topic_custom =
create_topic<String>(*node, "foo_custom", TopicKind::Topic, false, "custom_type");
ASSERT_NE(topic_custom, dds::core::null);
ASSERT_STREQ(topic_custom.name().c_str(), "foo_custom");
ASSERT_STREQ(topic_custom.type_name().c_str(), "custom_type");
// Create a Request ROS topic
auto topic_req = create_topic<AddTwoInts_Request>(*node, "foo", TopicKind::Request, false);
ASSERT_NE(topic_req, dds::core::null);
ASSERT_STREQ(topic_req.name().c_str(), "fooRequest");
ASSERT_STREQ(topic_req.type_name().c_str(), "example_interfaces::srv::AddTwoInts_Request");
// Create a Request ROS topic with a custom type name
auto topic_req_custom = create_topic<AddTwoInts_Request>(
*node, "foo_custom", TopicKind::Request, false, "custom_req_type");
ASSERT_NE(topic_req_custom, dds::core::null);
ASSERT_STREQ(topic_req_custom.name().c_str(), "foo_customRequest");
ASSERT_STREQ(topic_req_custom.type_name().c_str(), "custom_req_type");
// Create a Reply ROS topic
auto topic_rep = create_topic<AddTwoInts_Response>(*node, "foo", TopicKind::Reply, false);
ASSERT_NE(topic_rep, dds::core::null);
ASSERT_STREQ(topic_rep.name().c_str(), "fooReply");
ASSERT_STREQ(topic_rep.type_name().c_str(), "example_interfaces::srv::AddTwoInts_Response");
// Create a Reply ROS topic
auto topic_rep_custom = create_topic<AddTwoInts_Response>(
*node, "foo_custom", TopicKind::Reply, false, "custom_rep_type");
ASSERT_NE(topic_rep_custom, dds::core::null);
ASSERT_STREQ(topic_rep_custom.name().c_str(), "foo_customReply");
ASSERT_STREQ(topic_rep_custom.type_name().c_str(), "custom_rep_type");
}
TEST_F(TestTopic, lookup_topic) {
using ros2dds::create_topic;
using ros2dds::lookup_topic;
using std_msgs::msg::String;
auto topic_lookup = lookup_topic<String>(*node, "foo");
ASSERT_EQ(topic_lookup, dds::core::null);
auto topic = create_topic<String>(*node, "foo");
ASSERT_NE(topic, dds::core::null);
topic_lookup = lookup_topic<String>(*node, "foo");
ASSERT_NE(topic_lookup, dds::core::null);
}
TEST_F(TestTopic, assert_topic) {
using ros2dds::lookup_topic;
using ros2dds::assert_topic;
using ros2dds::create_topic;
using ros2dds::TopicKind;
using std_msgs::msg::String;
auto topic = lookup_topic<String>(*node, "foo");
ASSERT_EQ(topic, dds::core::null);
topic = assert_topic<String>(*node, "foo");
ASSERT_NE(topic, dds::core::null);
ASSERT_THROW(
{
create_topic<String>(*node, "foo");
}, dds::core::Error);
auto topic_2 = assert_topic<String>(*node, "foo");
ASSERT_EQ(topic, topic_2);
auto topic_3 = lookup_topic<String>(*node, "foo");
ASSERT_EQ(topic_2, topic_3);
// Can't assert with a different type name
ASSERT_THROW(
{
assert_topic<String>(*node, "foo", TopicKind::Topic, true, "different_type_name");
}, rclcpp::exceptions::RCLInvalidArgument);
}
|
cpp
|
rticonnextdds-robot-helpers
|
data/projects/rticonnextdds-robot-helpers/ros2dds/test/ros2dds/test_sub.cpp
|
// Copyright 2021 Real-Time Innovations, Inc. (RTI)
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include <gtest/gtest.h>
#include <cstdlib>
#include <memory>
#include "std_msgs/msg/String.hpp"
#include "example_interfaces/srv/AddTwoInts.hpp"
#include "ros2dds/sub.hpp"
class TestSub : public ::testing::Test
{
protected:
static void SetUpTestCase()
{
rclcpp::init(0, nullptr);
}
static void TearDownTestCase()
{
rclcpp::shutdown();
}
void SetUp()
{
node = std::make_shared<rclcpp::Node>("my_node", "/ns");
}
void TearDown()
{
node.reset();
}
rclcpp::Node::SharedPtr node;
};
TEST_F(TestSub, create_datareader_ros) {
using ros2dds::create_datareader;
using ros2dds::TopicKind;
using std_msgs::msg::String;
using example_interfaces::srv::AddTwoInts_Request;
using example_interfaces::srv::AddTwoInts_Response;
// Create a reader for a standard ROS topic
auto reader = create_datareader<String>(*node, "foo");
ASSERT_NE(reader, dds::core::null);
ASSERT_STREQ(reader.topic_description().name().c_str(), "rt/ns/foo");
ASSERT_STREQ(reader.topic_description().type_name().c_str(), "std_msgs::msg::dds_::String_");
// Create a reader for a standard ROS topic w/custom type name
auto reader_alt = create_datareader<String>(
*node, "foo_alt", TopicKind::Topic, true, "custom_type_name");
ASSERT_NE(reader_alt, dds::core::null);
ASSERT_STREQ(reader_alt.topic_description().name().c_str(), "rt/ns/foo_alt");
ASSERT_STREQ(reader_alt.topic_description().type_name().c_str(), "dds_::custom_type_name_");
// Create a reader for a Request ROS topic
auto reader_req = create_datareader<AddTwoInts_Request>(*node, "foo", TopicKind::Request);
ASSERT_NE(reader_req, dds::core::null);
ASSERT_STREQ(reader_req.topic_description().name().c_str(), "rq/ns/fooRequest");
ASSERT_STREQ(
reader_req.topic_description().type_name().c_str(),
"example_interfaces::srv::dds_::AddTwoInts_Request_");
// Create a reader for a Reply ROS topic
auto reader_rep = create_datareader<AddTwoInts_Response>(*node, "foo", TopicKind::Reply);
ASSERT_NE(reader_rep, dds::core::null);
ASSERT_STREQ(reader_rep.topic_description().name().c_str(), "rr/ns/fooReply");
ASSERT_STREQ(
reader_rep.topic_description().type_name().c_str(),
"example_interfaces::srv::dds_::AddTwoInts_Response_");
}
TEST_F(TestSub, create_reader_dds) {
using ros2dds::create_datareader;
using ros2dds::TopicKind;
using std_msgs::msg::String;
using example_interfaces::srv::AddTwoInts_Request;
using example_interfaces::srv::AddTwoInts_Response;
// Create a reader for a standard topic
auto reader = create_datareader<String>(*node, "foo", TopicKind::Topic, false);
ASSERT_NE(reader, dds::core::null);
ASSERT_STREQ(reader.topic_description().name().c_str(), "foo");
ASSERT_STREQ(reader.topic_description().type_name().c_str(), "std_msgs::msg::String");
// Create a reader for a standard topic w/custom type name
auto reader_alt = create_datareader<String>(
*node, "foo_alt", TopicKind::Topic, false, "custom_type_name");
ASSERT_NE(reader_alt, dds::core::null);
ASSERT_STREQ(reader_alt.topic_description().name().c_str(), "foo_alt");
ASSERT_STREQ(reader_alt.topic_description().type_name().c_str(), "custom_type_name");
// Create a reader for a Request topic
auto reader_req =
create_datareader<AddTwoInts_Request>(*node, "foo", TopicKind::Request, false);
ASSERT_NE(reader_req, dds::core::null);
ASSERT_STREQ(reader_req.topic_description().name().c_str(), "fooRequest");
ASSERT_STREQ(
reader_req.topic_description().type_name().c_str(),
"example_interfaces::srv::AddTwoInts_Request");
// Create a reader for a Reply topic
auto reader_rep =
create_datareader<AddTwoInts_Response>(*node, "foo", TopicKind::Reply, false);
ASSERT_NE(reader_rep, dds::core::null);
ASSERT_STREQ(reader_rep.topic_description().name().c_str(), "fooReply");
ASSERT_STREQ(
reader_rep.topic_description().type_name().c_str(),
"example_interfaces::srv::AddTwoInts_Response");
}
|
cpp
|
rticonnextdds-robot-helpers
|
data/projects/rticonnextdds-robot-helpers/ros2dds/test/ros2dds/test_waitset_executor.hpp
|
// Copyright 2021 Real-Time Innovations, Inc. (RTI)
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#ifndef ROS2DDS__TEST_WAITSET_EXECUTOR_HPP_
#define ROS2DDS__TEST_WAITSET_EXECUTOR_HPP_
#include <gtest/gtest.h>
#include <cstdlib>
#include <memory>
#include <sstream>
#include "std_msgs/msg/String.hpp"
#include "ros2dds/pub.hpp"
#include "ros2dds/sub.hpp"
// Some data structures use to keep track of callback events.
struct ReaderState
{
const size_t n;
size_t status_count{0};
size_t data_count{0};
size_t received_count{0};
size_t received_invalid_count{0};
dds::core::status::SubscriptionMatchedStatus matched_status;
explicit ReaderState(const size_t id)
: n(id)
{}
template<typename T>
void on_status(dds::sub::DataReader<T> & reader)
{
status_count += 1;
matched_status = reader.subscription_matched_status();
}
template<typename T, typename C>
void on_data(
dds::sub::DataReader<T> & reader,
C & condition,
const bool take = false)
{
data_count += 1;
auto samples = (take) ?
reader.select().condition(condition).take() :
reader.select().condition(condition).read();
for (const auto & sample : samples) {
if (sample.info().valid()) {
received_count += 1;
} else {
received_invalid_count += 1;
}
}
}
void on_data()
{
data_count += 1;
received_count += 1;
}
};
struct WriterState
{
size_t status_count{0};
dds::core::status::PublicationMatchedStatus matched_status;
template<typename T>
void on_status(dds::pub::DataWriter<T> & writer)
{
status_count += 1;
matched_status = writer.publication_matched_status();
}
};
#endif // ROS2DDS__TEST_WAITSET_EXECUTOR_HPP_
|
hpp
|
rticonnextdds-robot-helpers
|
data/projects/rticonnextdds-robot-helpers/ros2dds/test/ros2dds/test_waitset_executor.cpp
|
// Copyright 2021 Real-Time Innovations, Inc. (RTI)
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include <memory>
#include "test_waitset_executor.hpp"
#include "ros2dds/waitset_executor.hpp"
#include "ros2dds/condition.hpp"
class TestExecutor : public ::testing::Test
{
protected:
static void SetUpTestCase()
{
rclcpp::init(0, nullptr);
}
static void TearDownTestCase()
{
rclcpp::shutdown();
}
void SetUp()
{
node_a = std::make_shared<rclcpp::Node>("node_a", "/ns");
node_b = std::make_shared<rclcpp::Node>("node_b", "/ns");
}
void TearDown()
{
node_a.reset();
node_b.reset();
}
rclcpp::Node::SharedPtr node_a;
rclcpp::Node::SharedPtr node_b;
};
struct NotifierTestState
{
ReaderState node_a_reader_1{0};
ReaderState node_a_reader_2{1};
ReaderState node_a_reader_3{2};
ReaderState node_a_reader_4{3};
WriterState node_b_writer;
};
template<typename ExecutorT>
void wait_with_timeout(
ExecutorT & exec,
const std::chrono::nanoseconds & max_wait,
const std::chrono::nanoseconds & step_wait,
std::function<bool()> functor,
const bool expect_timeout)
{
auto start_ts = std::chrono::steady_clock::now();
bool timed_out = false;
bool complete = false;
do {
timed_out = std::chrono::steady_clock::now() - start_ts >= max_wait;
complete = functor();
if (!timed_out && !complete) {
exec.spin(step_wait);
}
} while (!timed_out && !complete);
if (expect_timeout) {
ASSERT_TRUE(timed_out);
} else { \
ASSERT_FALSE(timed_out);
}
}
template<typename ExecutorT>
void test_executor(
rclcpp::Node::SharedPtr node_a,
rclcpp::Node::SharedPtr node_b)
{
using std_msgs::msg::String;
// Common history size (used to drive the publishing of test samples)
const size_t history_depth = 10;
// Create two readers on Node A
dds::sub::qos::DataReaderQos reader_qos =
ros2dds::default_datareader_qos(*node_a, "bar");
reader_qos << dds::core::policy::Durability::TransientLocal();
reader_qos << dds::core::policy::Reliability::Reliable();
reader_qos << dds::core::policy::History::KeepLast(history_depth);
auto node_a_reader_1 =
ros2dds::template create_datareader<String>(*node_a, "bar", reader_qos);
// Create another reader to attach a query condition. Use different signature
// of create_datareader<T>() which takes an existing topic.
// NOTE: it would be nice to be able to "clone" the existing reader, and the
// only missing bit is being able to pass the existing reader's qos to create
// the new one. Unfortunately, if we do this, the creation fails, because the
// qos reaturned by DataReader::qos() contains some information uniquely
// identifying the reader which causes the new reader to be considered
// the same by Connext's persentation layer.
dds::topic::Topic<String> reader_topic =
ros2dds::template lookup_topic<String>(*node_a, "bar");
auto node_a_reader_2 =
ros2dds::template create_datareader<String>(*node_a, reader_topic, reader_qos);
// Create another reader which will use a query with parameters
auto node_a_reader_3 =
ros2dds::template create_datareader<String>(*node_a, "bar", reader_qos);
// Create another reader which will use a CFT
auto cft_topic = ros2dds::create_content_filtered_topic<String>(
*node_a,
reader_topic,
"filtered_samples",
"data MATCH %0 OR data MATCH %1",
{"'Hello World 1'", "'Hello World 3'"});
auto node_a_reader_4 =
ros2dds::template create_datareader<String>(*node_a, cft_topic, reader_qos);
// Register callbacks for readers on Node A
// - Both readers will have a "status" callback.
// - One reader will have a standard "data" callback.
// - The other driver will have a "data query" callback.
// The callbacks will collect the subscription matched status and count
// the received data samples.
NotifierTestState state;
ExecutorT exec;
// Simple data callback
auto condition_data_a_1 = ros2dds::condition::template read_data<String>(
node_a_reader_1,
[&state](const String & msg)
{
(void)msg;
state.node_a_reader_1.on_data();
});
// Test properties of returned condition
ASSERT_EQ(
dds::sub::status::DataState::new_data(),
condition_data_a_1.state_filter());
ASSERT_EQ(
dds::sub::AnyDataReader(node_a_reader_1),
condition_data_a_1.data_reader());
// Query data callback
auto condition_data_a_2 = ros2dds::condition::template read_query<String>(
node_a_reader_2,
[&state](const String & msg)
{
(void)msg;
state.node_a_reader_2.on_data();
},
"data MATCH 'Hello World [0-9]'");
// Query data callback with parameters
auto condition_data_a_3 = ros2dds::condition::template query<String>(
node_a_reader_3,
[&state](
dds::sub::cond::QueryCondition & condition,
dds::sub::DataReader<String> & reader)
{
state.node_a_reader_3.on_data(reader, condition, true /* take */);
},
"data MATCH %0 OR data MATCH %1",
// this reader's callback will take() messages, so notify any()
dds::sub::status::DataState::any(),
{"'Hello World 0'", "'Hello World 2'"});
// CFT reader can just use a regular callback
auto condition_data_a_4 = ros2dds::condition::template data<String>(
node_a_reader_4,
[&state](
dds::sub::cond::ReadCondition & condition,
dds::sub::DataReader<String> & reader)
{
state.node_a_reader_4.on_data(reader, condition);
});
auto on_reader_status =
[&node_a_reader_1,
&node_a_reader_2,
&node_a_reader_3,
&node_a_reader_4,
&state](
dds::core::cond::StatusCondition & condition,
dds::sub::DataReader<String> & reader)
{
(void)condition;
if (reader == node_a_reader_1) {
state.node_a_reader_1.on_status(reader);
} else if (reader == node_a_reader_2) {
state.node_a_reader_2.on_status(reader);
} else if (reader == node_a_reader_3) {
state.node_a_reader_3.on_status(reader);
} else if (reader == node_a_reader_4) {
state.node_a_reader_4.on_status(reader);
} else {
FAIL();
}
};
auto condition_status_a_1 =
ros2dds::condition::template status<String>(
node_a_reader_1, on_reader_status,
dds::core::status::StatusMask::subscription_matched());
auto condition_status_a_2 =
ros2dds::condition::template status<String>(
node_a_reader_2, on_reader_status,
dds::core::status::StatusMask::subscription_matched());
auto condition_status_a_3 =
ros2dds::condition::template status<String>(
node_a_reader_3, on_reader_status,
dds::core::status::StatusMask::subscription_matched());
auto condition_status_a_4 =
ros2dds::condition::template status<String>(
node_a_reader_4, on_reader_status,
dds::core::status::StatusMask::subscription_matched());
// Create a writer on Node B. We do this after configuring reader events so
// that none will be missed.
// The writer will have only a "status" callback which will collect
// the publication matched status.
dds::pub::qos::DataWriterQos writer_qos =
ros2dds::default_datawriter_qos(*node_b, "bar");
writer_qos << dds::core::policy::Durability::TransientLocal();
writer_qos << dds::core::policy::Reliability::Reliable();
writer_qos << dds::core::policy::History::KeepLast(history_depth);
auto node_b_writer =
ros2dds::template create_datawriter<String>(*node_b, "bar", writer_qos);
auto condition_status_b = ros2dds::condition::template status<String>(
node_b_writer,
[&state](
dds::core::cond::StatusCondition & condition,
dds::pub::DataWriter<String> & writer)
{
(void)condition;
state.node_b_writer.on_status(writer);
},
dds::core::status::StatusMask::publication_matched());
// Attach all conditions to the executor
exec.attach(condition_data_a_1);
exec.attach(condition_data_a_2);
exec.attach(condition_data_a_3);
exec.attach(condition_data_a_4);
exec.attach(condition_status_a_1);
exec.attach(condition_status_a_2);
exec.attach(condition_status_a_3);
exec.attach(condition_status_a_4);
exec.attach(condition_status_b);
// Publish half samples which should not be notified to the filtered callback,
// only to the standard data callback.
String msg("Hello World");
for (size_t i = 0; i < history_depth / 2; i++) {
node_b_writer.write(msg);
}
// Publish some sample that will be received by both callbacks.
for (size_t i = 0; i < history_depth / 2; i++) {
std::ostringstream msg_data;
msg_data << "Hello World " << i;
String msg(msg_data.str());
node_b_writer.write(msg);
}
using namespace std::literals::chrono_literals;
wait_with_timeout(
exec, 1000ms, 50ms,
[&state]() {
return
state.node_a_reader_1.data_count >= 1U &&
state.node_a_reader_2.data_count >= 1U &&
state.node_a_reader_3.data_count >= 1U &&
state.node_a_reader_4.data_count >= 1U &&
state.node_a_reader_1.received_count == history_depth &&
state.node_a_reader_2.received_count == history_depth / 2 &&
state.node_a_reader_3.received_count == 2U &&
state.node_a_reader_4.received_count == 2U &&
state.node_a_reader_1.received_invalid_count == 0 &&
state.node_a_reader_2.received_invalid_count == 0 &&
state.node_a_reader_3.received_invalid_count == 0 &&
state.node_a_reader_4.received_invalid_count == 0 &&
state.node_a_reader_1.status_count == 1U &&
state.node_a_reader_2.status_count == 1U &&
state.node_a_reader_3.status_count == 1U &&
state.node_a_reader_4.status_count == 1U &&
state.node_a_reader_1.matched_status.current_count() == 1 &&
state.node_a_reader_2.matched_status.current_count() == 1 &&
state.node_a_reader_3.matched_status.current_count() == 1 &&
state.node_a_reader_4.matched_status.current_count() == 1 &&
state.node_b_writer.status_count >= 1U &&
state.node_b_writer.matched_status.current_count() == 4;
},
false /* expect timeout */);
// Delete a reader 1 and check that the writer callback is notified.
state.node_b_writer.status_count = 0;
// Cancel events associated with the reader and delete it.
exec.detach(condition_data_a_1);
exec.detach(condition_status_a_1);
node_a_reader_1.close();
wait_with_timeout(
exec, 1000ms, 50ms,
[&state]() {
return
state.node_b_writer.status_count == 1U &&
state.node_b_writer.matched_status.current_count() == 3;
},
false /* expect timeout */);
// If we cancel the reader 2 status callback and delete the writer then
// we shouldn't receive a notification for reader 2, only for reader 1.
exec.detach(condition_status_a_2);
state.node_a_reader_2.status_count = 0;
state.node_a_reader_3.status_count = 0;
state.node_a_reader_4.status_count = 0;
// Cancel event associated with the writer and delete it.
exec.detach(condition_status_b);
node_b_writer.close();
wait_with_timeout(
exec, 1000ms, 50ms,
[&state]() {
return
state.node_a_reader_3.status_count == 1 &&
state.node_a_reader_3.matched_status.current_count() == 0 &&
state.node_a_reader_4.status_count == 1 &&
state.node_a_reader_4.matched_status.current_count() == 0;
},
false /* expect timeout */);
// Check that the writer was actually reported unmatched to reader 2
// but the callback was not call
ASSERT_EQ(state.node_a_reader_2.status_count, 0U);
ASSERT_TRUE(
(node_a_reader_2.status_changes() &
dds::core::status::StatusMask::subscription_matched()).any());
ASSERT_EQ(node_a_reader_2.subscription_matched_status().current_count(), 0);
}
class TestAsyncExecutor : public TestExecutor {};
TEST_F(TestAsyncExecutor, create) {
// Create with default properties
ros2dds::AsyncWaitSetExecutor exec;
(void)exec;
}
TEST_F(TestAsyncExecutor, notify) {
test_executor<ros2dds::AsyncWaitSetExecutor>(node_a, node_b);
}
class TestSyncExecutor : public TestExecutor {};
TEST_F(TestSyncExecutor, create) {
// Create with default properties
ros2dds::SyncWaitSetExecutor exec;
(void)exec;
}
TEST_F(TestSyncExecutor, notify) {
test_executor<ros2dds::SyncWaitSetExecutor>(node_a, node_b);
}
|
cpp
|
rticonnextdds-robot-helpers
|
data/projects/rticonnextdds-robot-helpers/ros2dds/test/ros2dds/test_resolve.cpp
|
// Copyright 2021 Real-Time Innovations, Inc. (RTI)
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include <gtest/gtest.h>
#include <rcutils/env.h>
#include <cstdlib>
#include <memory>
#include <string>
#include "ros2dds/resolve.hpp"
#include "rclcpp/init_options.hpp"
#include "rclcpp/node_options.hpp"
#include "std_msgs/msg/String.hpp"
#include "example_interfaces/srv/AddTwoInts.hpp"
class TestResolve : public ::testing::Test
{
protected:
static void SetUpTestCase()
{
rclcpp::init(0, nullptr);
}
static void TearDownTestCase()
{
rclcpp::shutdown();
}
void SetUp()
{
node = std::make_shared<rclcpp::Node>("my_node", "/ns");
other_node = std::make_shared<rclcpp::Node>("other_node", "/other_ns");
}
void TearDown()
{
node.reset();
}
rclcpp::Node::SharedPtr node;
rclcpp::Node::SharedPtr other_node;
};
TEST_F(TestResolve, resolve_topic_name_ros) {
using ros2dds::resolve_topic_name;
using ros2dds::TopicKind;
//
// Test resolve_topic_name(*node, ...)
//
// Standard ROS Topic
std::string resolved = resolve_topic_name(*node, "foo");
ASSERT_STREQ("rt/ns/foo", resolved.c_str());
// ROS Request Topic
resolved = resolve_topic_name(*node, "foo", TopicKind::Request);
ASSERT_STREQ("rq/ns/fooRequest", resolved.c_str());
// ROS Reply Topic
resolved = resolve_topic_name(*node, "foo", TopicKind::Reply);
ASSERT_STREQ("rr/ns/fooReply", resolved.c_str());
//
// Test resolve_topic_name(*other_node, ...)
//
resolved = resolve_topic_name(*other_node, "foo");
ASSERT_STREQ("rt/other_ns/foo", resolved.c_str());
// ROS Request Topic
resolved = resolve_topic_name(*other_node, "foo", TopicKind::Request);
ASSERT_STREQ("rq/other_ns/fooRequest", resolved.c_str());
// ROS Reply Topic
resolved = resolve_topic_name(*other_node, "foo", TopicKind::Reply);
ASSERT_STREQ("rr/other_ns/fooReply", resolved.c_str());
//
// Test resolve_topic_name(node_name, node_namespace, ...)
//
// Standard ROS Topic
resolved = resolve_topic_name("a_node", "/a_ns", "foo");
ASSERT_STREQ("rt/a_ns/foo", resolved.c_str());
resolved = resolve_topic_name("a_node", "/", "foo");
ASSERT_STREQ("rt/foo", resolved.c_str());
// ROS Request Topic to service
resolved = resolve_topic_name("a_node", "/a_ns", "foo", TopicKind::Request);
ASSERT_STREQ("rq/a_ns/fooRequest", resolved.c_str());
resolved = resolve_topic_name("a_node", "/", "foo", TopicKind::Request);
ASSERT_STREQ("rq/fooRequest", resolved.c_str());
// ROS Reply Topic to service
resolved = resolve_topic_name("a_node", "/a_ns", "foo", TopicKind::Reply);
ASSERT_STREQ("rr/a_ns/fooReply", resolved.c_str());
resolved = resolve_topic_name("a_node", "/", "foo", TopicKind::Reply);
ASSERT_STREQ("rr/fooReply", resolved.c_str());
}
TEST_F(TestResolve, resolve_topic_name_dds) {
using ros2dds::resolve_topic_name;
using ros2dds::TopicKind;
//
// Test resolve_topic_name(*node, ...)
//
// Standard Topic
std::string resolved = resolve_topic_name(*node, "foo", TopicKind::Topic, false);
ASSERT_STREQ("foo", resolved.c_str());
// Request Topic
resolved = resolve_topic_name(*node, "foo", TopicKind::Request, false);
ASSERT_STREQ("fooRequest", resolved.c_str());
// ROS Reply Topic
resolved = resolve_topic_name(*node, "foo", TopicKind::Reply, false);
ASSERT_STREQ("fooReply", resolved.c_str());
//
// Test resolve_topic_name(*other_node, ...)
//
resolved = resolve_topic_name(*other_node, "foo", TopicKind::Topic, false);
ASSERT_STREQ("foo", resolved.c_str());
resolved = resolve_topic_name(*other_node, "foo", TopicKind::Request, false);
ASSERT_STREQ("fooRequest", resolved.c_str());
resolved = resolve_topic_name(*other_node, "foo", TopicKind::Reply, false);
ASSERT_STREQ("fooReply", resolved.c_str());
//
// Test resolve_topic_name(node_name, node_namespace, ...)
//
// Standard Topic
resolved = resolve_topic_name("a_node", "/a_ns", "foo", TopicKind::Topic, false);
ASSERT_STREQ("foo", resolved.c_str());
resolved = resolve_topic_name("a_node", "/", "foo", TopicKind::Topic, false);
ASSERT_STREQ("foo", resolved.c_str());
// ROS Request Topic to service
resolved = resolve_topic_name("a_node", "/a_ns", "foo", TopicKind::Request, false);
ASSERT_STREQ("fooRequest", resolved.c_str());
resolved = resolve_topic_name("a_node", "/", "foo", TopicKind::Request, false);
ASSERT_STREQ("fooRequest", resolved.c_str());
// ROS Reply Topic to service
resolved = resolve_topic_name("a_node", "/a_ns", "foo", TopicKind::Reply, false);
ASSERT_STREQ("fooReply", resolved.c_str());
resolved = resolve_topic_name("a_node", "/", "foo", TopicKind::Reply, false);
ASSERT_STREQ("fooReply", resolved.c_str());
}
TEST_F(TestResolve, resolve_topic_name_invalid) {
using ros2dds::resolve_topic_name;
using ros2dds::TopicKind;
// Invalid topic name (empty)
ASSERT_THROW(
{
resolve_topic_name(*node, "");
}, rclcpp::exceptions::InvalidTopicNameError);
// Invalid node name (empty)
ASSERT_THROW(
{
resolve_topic_name("", "/", "foo");
}, rclcpp::exceptions::InvalidNodeNameError);
// Invalid node namespace (empty)
ASSERT_THROW(
{
resolve_topic_name("a_node", "", "foo");
}, rclcpp::exceptions::InvalidNamespaceError);
// TopicKind shouldn't make a difference in these cases
ASSERT_THROW(
{
resolve_topic_name(*node, "", TopicKind::Topic);
}, rclcpp::exceptions::InvalidTopicNameError);
ASSERT_THROW(
{
resolve_topic_name("", "/", "foo", TopicKind::Topic);
}, rclcpp::exceptions::InvalidNodeNameError);
ASSERT_THROW(
{
resolve_topic_name("a_node", "", "foo", TopicKind::Topic);
}, rclcpp::exceptions::InvalidNamespaceError);
ASSERT_THROW(
{
resolve_topic_name(*node, "", TopicKind::Request);
}, rclcpp::exceptions::InvalidTopicNameError);
ASSERT_THROW(
{
resolve_topic_name("", "/", "foo", TopicKind::Request);
}, rclcpp::exceptions::InvalidNodeNameError);
ASSERT_THROW(
{
resolve_topic_name("a_node", "", "foo", TopicKind::Request);
}, rclcpp::exceptions::InvalidNamespaceError);
ASSERT_THROW(
{
resolve_topic_name(*node, "", TopicKind::Reply);
}, rclcpp::exceptions::InvalidTopicNameError);
ASSERT_THROW(
{
resolve_topic_name("", "/", "foo", TopicKind::Reply);
}, rclcpp::exceptions::InvalidNodeNameError);
ASSERT_THROW(
{
resolve_topic_name("a_node", "", "foo", TopicKind::Reply);
}, rclcpp::exceptions::InvalidNamespaceError);
// If we disable ROS naming conventions, only invalid topic name should throw
ASSERT_THROW(
{
resolve_topic_name(*node, "", TopicKind::Topic, false);
}, rclcpp::exceptions::InvalidTopicNameError);
ASSERT_THROW(
{
resolve_topic_name(*node, "", TopicKind::Request, false);
}, rclcpp::exceptions::InvalidTopicNameError);
ASSERT_THROW(
{
resolve_topic_name(*node, "", TopicKind::Reply, false);
}, rclcpp::exceptions::InvalidTopicNameError);
ASSERT_NO_THROW(
{
resolve_topic_name("", "/", "foo", TopicKind::Topic, false);
resolve_topic_name("a_node", "", "foo", TopicKind::Topic, false);
resolve_topic_name("", "/", "foo", TopicKind::Request, false);
resolve_topic_name("a_node", "", "foo", TopicKind::Request, false);
resolve_topic_name("", "/", "foo", TopicKind::Reply, false);
resolve_topic_name("a_node", "", "foo", TopicKind::Reply, false);
});
}
|
cpp
|
rticonnextdds-robot-helpers
|
data/projects/rticonnextdds-robot-helpers/ros2dds/test/ros2dds/test_pub.cpp
|
// Copyright 2021 Real-Time Innovations, Inc. (RTI)
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include <gtest/gtest.h>
#include <cstdlib>
#include <memory>
#include "std_msgs/msg/String.hpp"
#include "example_interfaces/srv/AddTwoInts.hpp"
#include "ros2dds/pub.hpp"
class TestPub : public ::testing::Test
{
protected:
static void SetUpTestCase()
{
rclcpp::init(0, nullptr);
}
static void TearDownTestCase()
{
rclcpp::shutdown();
}
void SetUp()
{
node = std::make_shared<rclcpp::Node>("my_node", "/ns");
}
void TearDown()
{
node.reset();
}
rclcpp::Node::SharedPtr node;
};
TEST_F(TestPub, create_datawriter_ros) {
using ros2dds::create_datawriter;
using ros2dds::TopicKind;
using std_msgs::msg::String;
using example_interfaces::srv::AddTwoInts_Request;
using example_interfaces::srv::AddTwoInts_Response;
// Create a writer for a standard ROS topic
auto writer = create_datawriter<String>(*node, "foo");
ASSERT_NE(writer, dds::core::null);
ASSERT_STREQ(writer.topic().name().c_str(), "rt/ns/foo");
ASSERT_STREQ(writer.topic().type_name().c_str(), "std_msgs::msg::dds_::String_");
// Create a writer for a standard ROS topic w/custom type name
auto writer_alt = create_datawriter<String>(
*node, "foo_alt", TopicKind::Topic, true, "custom_type_name");
ASSERT_NE(writer_alt, dds::core::null);
ASSERT_STREQ(writer_alt.topic().name().c_str(), "rt/ns/foo_alt");
ASSERT_STREQ(writer_alt.topic().type_name().c_str(), "dds_::custom_type_name_");
// Create a writer for a Request ROS topic
auto writer_req =
create_datawriter<AddTwoInts_Request>(*node, "foo", TopicKind::Request);
ASSERT_NE(writer_req, dds::core::null);
ASSERT_STREQ(writer_req.topic().name().c_str(), "rq/ns/fooRequest");
ASSERT_STREQ(
writer_req.topic().type_name().c_str(),
"example_interfaces::srv::dds_::AddTwoInts_Request_");
// Create a writer for a Reply ROS topic
auto writer_rep =
create_datawriter<AddTwoInts_Response>(*node, "foo", TopicKind::Reply);
ASSERT_NE(writer_rep, dds::core::null);
ASSERT_STREQ(writer_rep.topic().name().c_str(), "rr/ns/fooReply");
ASSERT_STREQ(
writer_rep.topic().type_name().c_str(),
"example_interfaces::srv::dds_::AddTwoInts_Response_");
}
TEST_F(TestPub, create_writer_dds) {
using ros2dds::create_datawriter;
using ros2dds::TopicKind;
using std_msgs::msg::String;
using example_interfaces::srv::AddTwoInts_Request;
using example_interfaces::srv::AddTwoInts_Response;
// Create a writer for a standard topic
auto writer = create_datawriter<String>(*node, "foo", TopicKind::Topic, false);
ASSERT_NE(writer, dds::core::null);
ASSERT_STREQ(writer.topic().name().c_str(), "foo");
ASSERT_STREQ(writer.topic().type_name().c_str(), "std_msgs::msg::String");
// Create a writer for a standard topic w/custom type name
auto writer_alt = create_datawriter<String>(
*node, "foo_alt", TopicKind::Topic, false, "custom_type_name");
ASSERT_NE(writer_alt, dds::core::null);
ASSERT_STREQ(writer_alt.topic().name().c_str(), "foo_alt");
ASSERT_STREQ(writer_alt.topic().type_name().c_str(), "custom_type_name");
// Create a writer for a Request ROS topic
auto writer_req =
create_datawriter<AddTwoInts_Request>(*node, "foo", TopicKind::Request, false);
ASSERT_NE(writer_req, dds::core::null);
ASSERT_STREQ(writer_req.topic().name().c_str(), "fooRequest");
ASSERT_STREQ(
writer_req.topic().type_name().c_str(),
"example_interfaces::srv::AddTwoInts_Request");
// Create a writer for a Reply ROS topic
auto writer_rep =
create_datawriter<AddTwoInts_Response>(*node, "foo", TopicKind::Reply, false);
ASSERT_NE(writer_rep, dds::core::null);
ASSERT_STREQ(writer_rep.topic().name().c_str(), "fooReply");
ASSERT_STREQ(
writer_rep.topic().type_name().c_str(),
"example_interfaces::srv::AddTwoInts_Response");
}
|
cpp
|
rticonnextdds-robot-helpers
|
data/projects/rticonnextdds-robot-helpers/ros2dds/test/ros2dds/test_custom_node.cpp
|
// Copyright 2021 Real-Time Innovations, Inc. (RTI)
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include <cstdlib>
#include <memory>
#include <string>
#include "gtest/gtest.h"
#include "std_msgs/msg/String.hpp"
#include "ros2dds/ros2dds.hpp"
struct CustomNode
{
std::string name;
std::string namespace_;
dds::domain::DomainParticipant participant{0};
};
namespace ros2dds
{
template<>
size_t
domain_id(CustomNode & node)
{
return node.participant.domain_id();
}
template<>
dds::domain::DomainParticipant
domain_participant(CustomNode & node)
{
return node.participant;
}
template<>
std::string
node_name(CustomNode & node)
{
return node.name;
}
template<>
std::string
node_namespace(CustomNode & node)
{
return node.namespace_;
}
} // namespace ros2dds
class TestCustomNode : public ::testing::Test
{
protected:
static void SetUpTestCase()
{
rclcpp::init(0, nullptr);
}
static void TearDownTestCase()
{
rclcpp::shutdown();
}
void SetUp()
{
node = CustomNode();
node.name = "custom_node";
node.namespace_ = "/custom_ns";
}
void TearDown()
{
node.participant = nullptr;
}
CustomNode node;
};
TEST_F(TestCustomNode, custom_node) {
ASSERT_EQ(ros2dds::domain_id(node), 0U);
dds::domain::DomainParticipant participant(dds::core::null);
ASSERT_NO_THROW(
{
participant = ros2dds::domain_participant(node);
});
ASSERT_NE(participant, dds::core::null);
ASSERT_EQ(participant.domain_id(), 0);
auto writer = ros2dds::create_datawriter<std_msgs::msg::String>(node, "foo");
}
|
cpp
|
rticonnextdds-robot-helpers
|
data/projects/rticonnextdds-robot-helpers/ros2dds/test/ros2dds/test_request.cpp
|
// Copyright 2021 Real-Time Innovations, Inc. (RTI)
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include <gtest/gtest.h>
#include <cstdlib>
#include <memory>
#include <sstream>
#include "example_interfaces/srv/AddTwoInts.hpp"
#include "ros2dds/request.hpp"
class TestRequest : public ::testing::Test
{
protected:
static void SetUpTestCase()
{
rclcpp::init(0, nullptr);
}
static void TearDownTestCase()
{
rclcpp::shutdown();
}
void SetUp()
{
node = std::make_shared<rclcpp::Node>("my_node", "/ns");
}
void TearDown()
{
node.reset();
}
rclcpp::Node::SharedPtr node;
};
TEST_F(TestRequest, create_requester_ros) {
using example_interfaces::srv::AddTwoInts_Request;
using example_interfaces::srv::AddTwoInts_Response;
// Create a reader for a standard ROS topic
auto requester =
ros2dds::create_requester<AddTwoInts_Request, AddTwoInts_Response>(*node, "foo");
ASSERT_NE(requester, dds::core::null);
auto req_writer = requester.request_datawriter();
ASSERT_STREQ(req_writer.topic().name().c_str(), "rq/ns/fooRequest");
ASSERT_STREQ(
req_writer.topic().type_name().c_str(),
// TODO(asorbini) Types are always registed with the default DDS name for now.
// "example_interfaces::srv::dds_::AddTwoInts_Request_");
"example_interfaces::srv::AddTwoInts_Request");
auto req_reader = requester.reply_datareader();
std::stringstream reply_topic;
reply_topic << "rr/ns/fooReply_" << req_writer.instance_handle();
ASSERT_STREQ(req_reader.topic_description().name().c_str(), reply_topic.str().c_str());
ASSERT_STREQ(
req_reader.topic_description().type_name().c_str(),
// TODO(asorbini) Types are always registed with the default DDS name for now.
// "example_interfaces::srv::dds_::AddTwoInts_Response_");
"example_interfaces::srv::AddTwoInts_Response");
}
TEST_F(TestRequest, create_requester_dds) {
using example_interfaces::srv::AddTwoInts_Request;
using example_interfaces::srv::AddTwoInts_Response;
// Create a reader for a standard topic
auto requester =
ros2dds::create_requester<AddTwoInts_Request, AddTwoInts_Response>(*node, "foo", false);
ASSERT_NE(requester, dds::core::null);
auto req_writer = requester.request_datawriter();
ASSERT_STREQ(req_writer.topic().name().c_str(), "fooRequest");
ASSERT_STREQ(
req_writer.topic().type_name().c_str(),
// TODO(asorbini) Types are always registed with the default DDS name for now.
"example_interfaces::srv::AddTwoInts_Request");
auto req_reader = requester.reply_datareader();
std::stringstream reply_topic;
reply_topic << "fooReply_" << req_writer.instance_handle();
ASSERT_STREQ(req_reader.topic_description().name().c_str(), reply_topic.str().c_str());
ASSERT_STREQ(
req_reader.topic_description().type_name().c_str(),
"example_interfaces::srv::AddTwoInts_Response");
}
|
cpp
|
rticonnextdds-robot-helpers
|
data/projects/rticonnextdds-robot-helpers/ros2dds/test/ros2dds/test_domain.cpp
|
// Copyright 2021 Real-Time Innovations, Inc. (RTI)
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include <cstdlib>
#include <memory>
#include <string>
#include "gtest/gtest.h"
#include "rcutils/env.h"
#include "rclcpp/init_options.hpp"
#include "rclcpp/node_options.hpp"
#include "ros2dds/domain.hpp"
class TestDomain : public ::testing::Test
{
protected:
static void SetUpTestCase()
{
rclcpp::init(0, nullptr);
}
static void TearDownTestCase()
{
rclcpp::shutdown();
}
void SetUp()
{
node = std::make_shared<rclcpp::Node>("my_node", "/ns");
}
void TearDown()
{
node.reset();
}
rclcpp::Node::SharedPtr node;
};
class TestDomainCustom : public TestDomain
{
protected:
static void SetUpTestCase()
{
#ifdef ROS_GALACTIC_OR_LATER
// In Galactic+, we can use InitOptions::set_domain_id().
// In earlier versions we must configure the domain id through env variables.
rclcpp::InitOptions opts;
opts.set_domain_id(46);
rclcpp::init(0, nullptr, opts);
#else
const char * const env_rc = rcutils_get_env("ROS_DOMAIN_ID", &env_domain_id);
if (nullptr != env_rc) {
throw std::runtime_error("failed to get ROS_DOMAIN_ID");
}
std::string custom_domain = std::to_string(46);
if (!rcutils_set_env("ROS_DOMAIN_ID", custom_domain.c_str())) {
throw std::runtime_error("failed to set ROS_DOMAIN_ID");
}
rclcpp::init(0, nullptr);
#endif
}
static void TearDownTestCase()
{
rclcpp::shutdown();
#ifndef ROS_GALACTIC_OR_LATER
if (!rcutils_set_env("ROS_DOMAIN_ID", env_domain_id)) {
throw std::runtime_error("failed to restore ROS_DOMAIN_ID");
}
env_domain_id = nullptr;
#endif
}
static const char * env_domain_id;
};
const char * TestDomainCustom::env_domain_id = nullptr;
TEST_F(TestDomain, domain_id) {
ASSERT_EQ(ros2dds::domain_id(*node), 0U);
}
TEST_F(TestDomainCustom, domain_id) {
ASSERT_EQ(ros2dds::domain_id(*node), 46U);
}
TEST_F(TestDomain, domain_participant) {
dds::domain::DomainParticipant participant(dds::core::null);
ASSERT_NO_THROW(
{
participant = ros2dds::domain_participant(*node);
});
ASSERT_NE(participant, dds::core::null);
ASSERT_EQ(participant.domain_id(), 0);
}
TEST_F(TestDomainCustom, domain_participant) {
dds::domain::DomainParticipant participant(dds::core::null);
ASSERT_NO_THROW(
{
participant = ros2dds::domain_participant(*node);
});
ASSERT_NE(participant, dds::core::null);
ASSERT_EQ(participant.domain_id(), 46);
}
|
cpp
|
rticonnextdds-robot-helpers
|
data/projects/rticonnextdds-robot-helpers/ros2dds/include/ros2dds/pub.hpp
|
// Copyright 2021 Real-Time Innovations, Inc. (RTI)
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#ifndef ROS2DDS__PUB_HPP_
#define ROS2DDS__PUB_HPP_
#include <string>
#include "ros2dds/domain.hpp"
#include "ros2dds/topic.hpp"
#include "ros2dds/qos.hpp"
namespace ros2dds
{
template<typename NodeT = rclcpp::Node>
dds::pub::Publisher
default_publisher(NodeT & node)
{
return rti::pub::implicit_publisher(domain_participant<NodeT>(node));
}
template<
typename MessageT,
typename NodeT = rclcpp::Node>
dds::pub::DataWriter<MessageT>
create_datawriter(
NodeT & node,
const std::string & topic_name,
const TopicKind topic_kind = TopicKind::Topic,
const bool use_ros_conventions = true,
const std::string & type_name = std::string())
{
auto publisher = default_publisher<NodeT>(node);
auto topic = assert_topic<MessageT, NodeT>(
node, topic_name, topic_kind, use_ros_conventions, type_name);
auto qos = default_datawriter_qos<MessageT, NodeT>(node, topic);
return dds::pub::DataWriter<MessageT>(publisher, topic, qos);
}
template<
typename MessageT,
typename NodeT = rclcpp::Node>
dds::pub::DataWriter<MessageT>
create_datawriter(
NodeT & node,
const std::string & topic_name,
const dds::pub::qos::DataWriterQos & qos,
const TopicKind topic_kind = TopicKind::Topic,
const bool use_ros_conventions = true,
const std::string & type_name = std::string())
{
auto publisher = default_publisher<NodeT>(node);
auto topic = assert_topic<MessageT, NodeT>(
node, topic_name, topic_kind, use_ros_conventions, type_name);
return dds::pub::DataWriter<MessageT>(publisher, topic, qos);
}
template<
typename MessageT,
typename NodeT = rclcpp::Node>
dds::pub::DataWriter<MessageT>
create_datawriter(
NodeT & node,
dds::topic::Topic<MessageT> & topic)
{
auto publisher = default_publisher<NodeT>(node);
auto qos = default_datawriter_qos<MessageT, NodeT>(node, topic);
return dds::pub::DataWriter<MessageT>(publisher, topic, qos);
}
template<
typename MessageT,
typename NodeT = rclcpp::Node>
dds::pub::DataWriter<MessageT>
create_datawriter(
NodeT & node,
dds::topic::Topic<MessageT> & topic,
const dds::pub::qos::DataWriterQos & qos)
{
auto publisher = default_publisher<NodeT>(node);
return dds::pub::DataWriter<MessageT>(publisher, topic, qos);
}
} // namespace ros2dds
#endif // ROS2DDS__PUB_HPP_
|
hpp
|
rticonnextdds-robot-helpers
|
data/projects/rticonnextdds-robot-helpers/ros2dds/include/ros2dds/sub.hpp
|
// Copyright 2021 Real-Time Innovations, Inc. (RTI)
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#ifndef ROS2DDS__SUB_HPP_
#define ROS2DDS__SUB_HPP_
#include <string>
#include "ros2dds/domain.hpp"
#include "ros2dds/topic.hpp"
#include "ros2dds/qos.hpp"
namespace ros2dds
{
template<typename NodeT = rclcpp::Node>
dds::sub::Subscriber
default_subscriber(NodeT & node)
{
return rti::sub::implicit_subscriber(domain_participant<NodeT>(node));
}
template<
typename MessageT,
typename NodeT = rclcpp::Node>
dds::sub::DataReader<MessageT>
create_datareader(
NodeT & node,
const std::string & topic_name,
const TopicKind topic_kind = TopicKind::Topic,
const bool use_ros_conventions = true,
const std::string & type_name = std::string())
{
auto subscriber = default_subscriber<NodeT>(node);
auto topic = assert_topic<MessageT, NodeT>(
node, topic_name, topic_kind, use_ros_conventions, type_name);
auto qos = default_datareader_qos<MessageT, NodeT>(node, topic);
return dds::sub::DataReader<MessageT>(subscriber, topic, qos);
}
template<
typename MessageT,
typename NodeT = rclcpp::Node>
dds::sub::DataReader<MessageT>
create_datareader(
NodeT & node,
const std::string & topic_name,
const dds::sub::qos::DataReaderQos & qos,
const TopicKind topic_kind = TopicKind::Topic,
const bool use_ros_conventions = true,
const std::string & type_name = std::string())
{
auto subscriber = default_subscriber<NodeT>(node);
auto topic = assert_topic<MessageT, NodeT>(
node, topic_name, topic_kind, use_ros_conventions, type_name);
return dds::sub::DataReader<MessageT>(subscriber, topic, qos);
}
template<
typename MessageT,
typename NodeT = rclcpp::Node>
dds::sub::DataReader<MessageT>
create_datareader(
NodeT & node,
dds::topic::Topic<MessageT> & topic)
{
auto subscriber = default_subscriber<NodeT>(node);
auto qos = default_datareader_qos<MessageT, NodeT>(node, topic);
return dds::sub::DataReader<MessageT>(subscriber, topic, qos);
}
template<
typename MessageT,
typename NodeT = rclcpp::Node>
dds::sub::DataReader<MessageT>
create_datareader(
NodeT & node,
dds::topic::Topic<MessageT> & topic,
const dds::sub::qos::DataReaderQos & qos)
{
auto subscriber = default_subscriber<NodeT>(node);
return dds::sub::DataReader<MessageT>(subscriber, topic, qos);
}
template<
typename MessageT,
typename NodeT = rclcpp::Node>
dds::sub::DataReader<MessageT>
create_datareader(
NodeT & node,
dds::topic::ContentFilteredTopic<MessageT> & topic)
{
auto subscriber = default_subscriber<NodeT>(node);
auto qos = default_datareader_qos<MessageT, NodeT>(node, topic);
return dds::sub::DataReader<MessageT>(subscriber, topic, qos);
}
template<
typename MessageT,
typename NodeT = rclcpp::Node>
dds::sub::DataReader<MessageT>
create_datareader(
NodeT & node,
dds::topic::ContentFilteredTopic<MessageT> & topic,
const dds::sub::qos::DataReaderQos & qos)
{
auto subscriber = default_subscriber<NodeT>(node);
return dds::sub::DataReader<MessageT>(subscriber, topic, qos);
}
} // namespace ros2dds
#endif // ROS2DDS__SUB_HPP_
|
hpp
|
rticonnextdds-robot-helpers
|
data/projects/rticonnextdds-robot-helpers/ros2dds/include/ros2dds/topic.hpp
|
// Copyright 2021 Real-Time Innovations, Inc. (RTI)
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#ifndef ROS2DDS__TOPIC_HPP_
#define ROS2DDS__TOPIC_HPP_
#include <cstring>
#include <string>
// #include <exception>
#include <vector>
#include "ros2dds/domain.hpp"
#include "ros2dds/resolve.hpp"
namespace ros2dds
{
template<
typename MessageT,
typename NodeT = rclcpp::Node>
std::string
topic_type_name(
NodeT & node,
const bool use_ros_conventions = true,
const std::string & type_name = std::string())
{
(void)node;
if (type_name.length() == 0) {
const std::string default_type_name = dds::topic::topic_type_name<MessageT>::value();
return resolve_type_name(default_type_name, use_ros_conventions);
} else {
return resolve_type_name(type_name, use_ros_conventions);
}
}
template<
typename MessageT,
typename NodeT = rclcpp::Node>
dds::topic::Topic<MessageT>
create_topic(
NodeT & node,
const std::string & topic_name,
const TopicKind topic_kind = TopicKind::Topic,
const bool use_ros_conventions = true,
const std::string & type_name = std::string())
{
auto participant = domain_participant<NodeT>(node);
std::string fq_topic_name =
resolve_topic_name<NodeT>(node, topic_name, topic_kind, use_ros_conventions);
auto fq_type_name = topic_type_name<MessageT>(node, use_ros_conventions, type_name);
return dds::topic::Topic<MessageT>(participant, fq_topic_name, fq_type_name);
}
template<
typename MessageT,
typename NodeT = rclcpp::Node>
dds::topic::Topic<MessageT>
lookup_topic(
NodeT & node,
const std::string & topic_name,
const TopicKind topic_kind = TopicKind::Topic,
const bool use_ros_conventions = true)
{
auto participant = domain_participant<NodeT>(node);
std::string fq_topic_name =
resolve_topic_name<NodeT>(node, topic_name, topic_kind, use_ros_conventions);
return dds::topic::find<dds::topic::Topic<MessageT>>(participant, fq_topic_name);
}
template<
typename MessageT,
typename NodeT = rclcpp::Node>
dds::topic::Topic<MessageT>
assert_topic(
NodeT & node,
const std::string & topic_name,
const TopicKind topic_kind = TopicKind::Topic,
const bool use_ros_conventions = true,
const std::string & type_name = std::string())
{
auto participant = domain_participant<NodeT>(node);
auto existing_topic =
lookup_topic<MessageT, NodeT>(node, topic_name, topic_kind, use_ros_conventions);
if (dds::core::null != existing_topic) {
// Check that the type name matches, if one was specified.
auto fq_type_name = topic_type_name<MessageT>(node, use_ros_conventions, type_name);
if (fq_type_name != existing_topic.type_name()) {
rclcpp::exceptions::throw_from_rcl_error(
RCL_RET_INVALID_ARGUMENT, "Existing topic has mismatching type name");
}
return existing_topic;
}
return create_topic<MessageT, NodeT>(
node, topic_name, topic_kind, use_ros_conventions, type_name);
}
template<
typename MessageT,
typename NodeT = rclcpp::Node>
dds::topic::ContentFilteredTopic<MessageT>
create_content_filtered_topic(
NodeT & node,
dds::topic::Topic<MessageT> & topic,
const std::string & filter_name,
const std::string & query_expression,
const std::vector<std::string> & query_parameters = std::vector<std::string>())
{
(void)node;
dds::topic::Filter filter(query_expression, query_parameters);
return dds::topic::ContentFilteredTopic<MessageT>(topic, filter_name, filter);
}
template<
typename MessageT,
typename NodeT = rclcpp::Node>
dds::topic::ContentFilteredTopic<MessageT>
lookup_content_filtered_topic(
NodeT & node,
const std::string & filter_name)
{
auto participant = domain_participant<NodeT>(node);
return dds::topic::find<dds::topic::ContentFilteredTopic<MessageT>>(participant, filter_name);
}
} // namespace ros2dds
#endif // ROS2DDS__TOPIC_HPP_
|
hpp
|
rticonnextdds-robot-helpers
|
data/projects/rticonnextdds-robot-helpers/ros2dds/include/ros2dds/waitset_executor.hpp
|
// Copyright 2021 Real-Time Innovations, Inc. (RTI)
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#ifndef ROS2DDS__WAITSET_EXECUTOR_HPP_
#define ROS2DDS__WAITSET_EXECUTOR_HPP_
#include <condition_variable>
#include <chrono>
#include <memory>
#include <mutex>
#include <string>
#include <utility>
#include <limits>
#include <functional>
#include "rti/core/cond/AsyncWaitSet.hpp"
#include "rcpputils/scope_exit.hpp"
namespace ros2dds
{
class WaitSetExecutor
{
public:
virtual void attach(const dds::core::cond::Condition & condition) = 0;
virtual void detach(const dds::core::cond::Condition & condition) = 0;
virtual void
spin(std::chrono::nanoseconds max_duration = std::chrono::nanoseconds(0)) = 0;
virtual void
shutdown() = 0;
};
class AsyncWaitSetExecutor : public WaitSetExecutor
{
public:
explicit AsyncWaitSetExecutor(const rti::core::cond::AsyncWaitSetProperty & properties)
: waitset_(properties)
{
waitset_.start();
}
AsyncWaitSetExecutor()
{
waitset_.start();
}
virtual void attach(const dds::core::cond::Condition & condition)
{
waitset_ += condition;
}
virtual void detach(const dds::core::cond::Condition & condition)
{
waitset_ -= condition;
}
virtual void
spin(std::chrono::nanoseconds max_duration = std::chrono::nanoseconds(0))
{
auto start = std::chrono::steady_clock::now();
std::unique_lock<std::mutex> lock(wait_mutex_);
if (waiting_) {
throw std::runtime_error("notifier already spinning");
}
waiting_ = true;
auto wait_exit = rcpputils::make_scope_exit(
[this]() {
waiting_ = false;
});
wait_cond_.wait_for(
lock,
max_duration,
[this, max_duration, start]() {
// exit if notifier is stopped, or
// if max_duration is not infinite and it has expired
auto ts_now = std::chrono::steady_clock::now() - start;
const bool duration_elapsed =
(std::chrono::nanoseconds(0) != max_duration && ts_now >= max_duration);
return !active_ || duration_elapsed;
});
}
virtual void
shutdown()
{
// Cause an active spin() to exit
active_ = false;
wait_cond_.notify_all();
}
private:
rti::core::cond::AsyncWaitSet waitset_;
std::mutex wait_mutex_;
std::condition_variable wait_cond_;
bool waiting_{false};
bool active_{true};
};
class SyncWaitSetExecutor : public WaitSetExecutor
{
public:
explicit SyncWaitSetExecutor(const rti::core::cond::WaitSetProperty & properties)
: waitset_(properties)
{
init_conditions();
}
SyncWaitSetExecutor()
{
init_conditions();
}
virtual void attach(const dds::core::cond::Condition & condition)
{
waitset_ += condition;
}
virtual void detach(const dds::core::cond::Condition & condition)
{
waitset_ -= condition;
}
virtual void
spin(std::chrono::nanoseconds max_duration = std::chrono::nanoseconds(0))
{
auto start = std::chrono::steady_clock::now();
{
std::lock_guard<std::mutex> lock(wait_mutex_);
if (waiting_) {
throw std::runtime_error("notifier already spinning");
}
}
waiting_ = true;
auto wait_exit = rcpputils::make_scope_exit(
[this]() {
std::lock_guard<std::mutex> lock(wait_mutex_);
waiting_ = false;
});
const bool infinite_duration = std::chrono::nanoseconds(0) == max_duration;
bool timed_out = false;
do {
auto wait_duration = std::chrono::steady_clock::now() - start;
const bool duration_elapsed = (!infinite_duration && wait_duration >= max_duration);
timed_out = !active_ || duration_elapsed;
if (!timed_out) {
if (infinite_duration) {
waitset_->dispatch(dds::core::Duration::infinite());
} else {
// const auto wait_timeout_ns = max_duration - wait_duration;
const auto wait_timeout =
std::chrono::duration_cast<std::chrono::microseconds>(
max_duration - wait_duration);
waitset_->dispatch(dds::core::Duration::from_microsecs(wait_timeout.count()));
}
}
} while (!timed_out);
}
virtual void
shutdown()
{
// Cause an active spin() to exit.
active_ = false;
exit_condition_.trigger_value(true);
}
private:
void init_conditions()
{
exit_condition_->handler(
[this]()
{
active_ = false;
});
waitset_ += exit_condition_;
}
dds::core::cond::WaitSet waitset_;
std::mutex wait_mutex_;
bool waiting_{false};
bool active_{true};
dds::core::cond::GuardCondition exit_condition_;
};
} // namespace ros2dds
#endif // ROS2DDS__WAITSET_EXECUTOR_HPP_
|
hpp
|
rticonnextdds-robot-helpers
|
data/projects/rticonnextdds-robot-helpers/ros2dds/include/ros2dds/request.hpp
|
// Copyright 2021 Real-Time Innovations, Inc. (RTI)
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#ifndef ROS2DDS__REQUEST_HPP_
#define ROS2DDS__REQUEST_HPP_
#include <string>
#include <sstream>
#include "rti/request/rtirequest.hpp"
#include "ros2dds/domain.hpp"
#include "ros2dds/topic.hpp"
#include "ros2dds/qos.hpp"
#include "ros2dds/pub.hpp"
#include "ros2dds/sub.hpp"
namespace ros2dds
{
template<
typename MessageReqT,
typename MessageRepT,
typename NodeT = rclcpp::Node>
rti::request::Requester<MessageReqT, MessageRepT>
create_requester(
NodeT & node,
const std::string & service_name,
const bool use_ros_conventions = true)
{
const std::string req_topic = resolve_topic_name(
node, service_name, TopicKind::Request, use_ros_conventions);
const std::string rep_topic = resolve_topic_name(
node, service_name, TopicKind::Reply, use_ros_conventions);
// TODO(asorbini) create resolve_type() to return a DynamicType for the params
// const std::string req_type = resolve_type_name(req_topic, use_ros_conventions);
// const std::string rep_type = resolve_type_name(rep_topic, use_ros_conventions);
rti::request::RequesterParams params(domain_participant(node));
params.request_topic_name(req_topic);
params.reply_topic_name(rep_topic);
params.datawriter_qos(default_datawriter_qos<NodeT>(node, req_topic, false));
params.datareader_qos(default_datareader_qos<NodeT>(node, rep_topic, false));
params.publisher(default_publisher<NodeT>(node));
params.subscriber(default_subscriber<NodeT>(node));
return rti::request::Requester<MessageReqT, MessageRepT>(params);
}
template<
typename MessageReqT,
typename MessageRepT,
typename NodeT = rclcpp::Node>
rti::request::Replier<MessageReqT, MessageRepT>
create_replier(
NodeT & node,
const std::string & service_name,
const bool use_ros_conventions = true)
{
const std::string req_topic = resolve_topic_name(
node, service_name, TopicKind::Request, use_ros_conventions);
const std::string rep_topic = resolve_topic_name(
node, service_name, TopicKind::Reply, use_ros_conventions);
// TODO(asorbini) create resolve_type() to return a DynamicType for the params
// const std::string req_type = resolve_type_name(req_topic, use_ros_conventions);
// const std::string rep_type = resolve_type_name(rep_topic, use_ros_conventions);
rti::request::ReplierParams params(domain_participant(node));
params.request_topic_name(req_topic);
params.reply_topic_name(rep_topic);
params.datawriter_qos(default_datawriter_qos<NodeT>(node, rep_topic, false));
params.datareader_qos(default_datareader_qos<NodeT>(node, req_topic, false));
params.publisher(default_publisher<NodeT>(node));
params.subscriber(default_subscriber<NodeT>(node));
return rti::request::Replier<MessageReqT, MessageRepT>(params);
}
} // namespace ros2dds
#endif // ROS2DDS__REQUEST_HPP_
|
hpp
|
rticonnextdds-robot-helpers
|
data/projects/rticonnextdds-robot-helpers/ros2dds/include/ros2dds/domain.hpp
|
// Copyright 2021 Real-Time Innovations, Inc. (RTI)
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#ifndef ROS2DDS__DOMAIN_HPP_
#define ROS2DDS__DOMAIN_HPP_
#include <string>
#include "rclcpp/rclcpp.hpp"
#include "dds/dds.hpp"
namespace ros2dds
{
/**
* @brief Get the id of the DDS domain joined by the DomainParticipant
* associated with a ROS 2 Node.
*
* @param node The ROS 2 Node to inspect.
* @return size_t An integer value representing the id of the DDS domain.
*/
template<typename NodeT = rclcpp::Node>
size_t
domain_id(NodeT & node)
{
size_t id = 0;
auto rcl_node = node.get_node_base_interface()->get_rcl_node_handle();
rcl_ret_t rc = rcl_node_get_domain_id(rcl_node, &id);
if (RCL_RET_OK != rc) {
throw std::runtime_error("failed to retrieve DDS domain ID");
rclcpp::exceptions::throw_from_rcl_error(rc, "Failed to retrieve DDS domain id");
}
return id;
}
/**
* @brief Get the DDS DomainParticipant associated with a ROS 2 Node.
*
* The RMW layer automatically creates a DDS DomainParticipant for every ROS 2
* context (typically one per process). This DomainParticipant is shared among
* all Nodes associated with that Context.
*
* This operation requires the use of `rmw_connextdds` as the RMW layer.
*
* An `std::runtime_error` will be thrown if the DomainParticipant instance
* cannot be retrieved (typically because the Node is not running on
* `rmw_connextdds`).
*
* @param node The ROS 2 Node to inspect.
* @return The DDS DomainParticipant instance associated with this node.
*/
template<typename NodeT = rclcpp::Node>
dds::domain::DomainParticipant
domain_participant(NodeT & node)
{
auto participant = dds::domain::find(domain_id(node));
if (dds::core::null == participant) {
rclcpp::exceptions::throw_from_rcl_error(
RCL_RET_ERROR, "Failed to retrieve DDS DomainParticipant for node");
}
return participant;
}
template<typename NodeT = rclcpp::Node>
std::string
node_name(NodeT & node)
{
return node.get_name();
}
template<typename NodeT = rclcpp::Node>
std::string
node_namespace(NodeT & node)
{
return node.get_namespace();
}
} // namespace ros2dds
#endif // ROS2DDS__DOMAIN_HPP_
|
hpp
|
rticonnextdds-robot-helpers
|
data/projects/rticonnextdds-robot-helpers/ros2dds/include/ros2dds/condition.hpp
|
// Copyright 2021 Real-Time Innovations, Inc. (RTI)
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#ifndef ROS2DDS__CONDITION_HPP_
#define ROS2DDS__CONDITION_HPP_
#include <memory>
#include <string>
#include <vector>
#include "ros2dds/domain.hpp"
namespace ros2dds
{
namespace condition
{
template<typename ConditionT>
using ConditionCallback = std::function<void (ConditionT &)>;
template<typename EntityT, typename ConditionT>
using EntityCallback = std::function<void (ConditionT &, EntityT &)>;
template<typename MessageT>
using DataCallback =
EntityCallback<dds::sub::DataReader<MessageT>, dds::sub::cond::ReadCondition>;
template<typename MessageT>
using DataQueryCallback =
EntityCallback<dds::sub::DataReader<MessageT>, dds::sub::cond::QueryCondition>;
template<typename MessageT>
using DataReaderStatusCallback =
EntityCallback<dds::sub::DataReader<MessageT>, dds::core::cond::StatusCondition>;
template<typename MessageT>
using DataWriterStatusCallback =
EntityCallback<dds::pub::DataWriter<MessageT>, dds::core::cond::StatusCondition>;
template<typename MessageT>
using MessageCallback = std::function<void (const MessageT &)>;
template<typename StatusT>
using EntityStatusCallback = std::function<void (const StatusT &)>;
template<typename EntityT, typename StatusT>
using StatusGetter = std::function<StatusT(EntityT &)>;
using SubscriptionMatchedStatusCallback =
EntityStatusCallback<dds::core::status::SubscriptionMatchedStatus>;
using PublicationMatchedStatusCallback =
EntityStatusCallback<dds::core::status::PublicationMatchedStatus>;
using UserCallback = ConditionCallback<dds::core::cond::GuardCondition>;
using SimpleUserCallback = std::function<void ()>;
template<typename MessageT>
dds::sub::cond::ReadCondition
data(
dds::sub::DataReader<MessageT> reader,
DataCallback<MessageT> cb,
const dds::sub::status::DataState data_state = dds::sub::status::DataState::new_data())
{
auto cond_ref = std::make_shared<dds::sub::cond::ReadCondition>(nullptr);
auto reader_ref = std::make_shared<dds::sub::DataReader<MessageT>>(reader);
dds::sub::cond::ReadCondition cond(reader, data_state,
[cb, cond_ref, reader_ref]() {
cb(*cond_ref, *reader_ref);
});
*cond_ref = cond;
return cond;
}
template<typename MessageT, bool Take = false>
dds::sub::cond::ReadCondition
read_data(
dds::sub::DataReader<MessageT> reader,
MessageCallback<MessageT> cb,
dds::sub::status::DataState data_state = dds::sub::status::DataState::new_data())
{
auto cond_ref = std::make_shared<dds::sub::cond::ReadCondition>(nullptr);
auto reader_ref = std::make_shared<dds::sub::DataReader<MessageT>>(reader);
dds::sub::cond::ReadCondition cond(reader, data_state,
[cb, cond_ref, reader_ref]() {
auto selector = reader_ref->select().condition(*cond_ref);
auto samples = (Take) ? selector.take() : selector.read();
for (const auto & sample : samples) {
if (sample.info().valid()) {
cb(sample.data());
}
}
});
*cond_ref = cond;
return cond;
}
template<typename MessageT>
dds::sub::cond::QueryCondition
query(
dds::sub::DataReader<MessageT> reader,
DataQueryCallback<MessageT> cb,
const std::string & query_expression,
dds::sub::status::DataState data_state = dds::sub::status::DataState::new_data(),
const std::vector<std::string> & query_parameters = std::vector<std::string>())
{
auto cond_ref = std::make_shared<dds::sub::cond::QueryCondition>(nullptr);
auto reader_ref = std::make_shared<dds::sub::DataReader<MessageT>>(reader);
dds::sub::Query query(reader, query_expression, query_parameters);
dds::sub::cond::QueryCondition cond(query, data_state,
[cb, cond_ref, reader_ref]() {
cb(*cond_ref, *reader_ref);
});
*cond_ref = cond;
return cond;
}
template<typename MessageT, bool Take = false>
dds::sub::cond::QueryCondition
read_query(
dds::sub::DataReader<MessageT> reader,
MessageCallback<MessageT> cb,
const std::string & query_expression,
dds::sub::status::DataState data_state = dds::sub::status::DataState::new_data(),
const std::vector<std::string> & query_parameters = std::vector<std::string>())
{
auto cond_ref = std::make_shared<dds::sub::cond::QueryCondition>(nullptr);
auto reader_ref = std::make_shared<dds::sub::DataReader<MessageT>>(reader);
dds::sub::Query query(reader, query_expression, query_parameters);
dds::sub::cond::QueryCondition cond(query, data_state,
[cb, cond_ref, reader_ref]() {
auto selector = reader_ref->select().condition(*cond_ref);
auto samples = (Take) ? selector.take() : selector.read();
for (const auto & sample : samples) {
if (sample.info().valid()) {
cb(sample.data());
}
}
});
*cond_ref = cond;
return cond;
}
template<typename MessageT>
dds::sub::cond::ReadCondition
take_data(
dds::sub::DataReader<MessageT> reader,
MessageCallback<MessageT> cb,
dds::sub::status::DataState data_state = dds::sub::status::DataState::new_data())
{
return read_data<MessageT, true>(reader, cb, data_state);
}
template<typename MessageT>
dds::sub::cond::QueryCondition
take_query(
dds::sub::DataReader<MessageT> reader,
MessageCallback<MessageT> cb,
const std::string & query_expression,
dds::sub::status::DataState data_state = dds::sub::status::DataState::new_data(),
const std::vector<std::string> & query_parameters = std::vector<std::string>())
{
return read_query<MessageT, true>(
reader, cb, query_expression, data_state, query_parameters);
}
template<typename MessageT>
dds::core::cond::StatusCondition
status(
dds::sub::DataReader<MessageT> reader,
DataReaderStatusCallback<MessageT> cb,
const dds::core::status::StatusMask enabled_statuses)
{
dds::core::cond::StatusCondition cond(reader);
auto cond_ref = std::make_shared<dds::core::cond::StatusCondition>(cond);
auto reader_ref = std::make_shared<dds::sub::DataReader<MessageT>>(reader);
cond->enabled_statuses(enabled_statuses);
cond->handler(
[cb, cond_ref, reader_ref]() {
cb(*cond_ref, *reader_ref);
});
*cond_ref = cond;
return cond;
}
template<typename MessageT>
dds::core::cond::StatusCondition
status(
dds::pub::DataWriter<MessageT> writer,
DataWriterStatusCallback<MessageT> cb,
const dds::core::status::StatusMask enabled_statuses)
{
dds::core::cond::StatusCondition cond(writer);
auto cond_ref = std::make_shared<dds::core::cond::StatusCondition>(cond);
auto writer_ref = std::make_shared<dds::pub::DataWriter<MessageT>>(writer);
cond->enabled_statuses(enabled_statuses);
cond->handler(
[cb, cond_ref, writer_ref]() {
cb(*cond_ref, *writer_ref);
});
*cond_ref = cond;
return cond;
}
inline
dds::core::cond::GuardCondition
guard(UserCallback cb)
{
auto cond_ref = std::make_shared<dds::core::cond::GuardCondition>();
dds::core::cond::GuardCondition cond;
cond->handler(
[cb, cond_ref]() {
cb(*cond_ref);
});
*cond_ref = cond;
return cond;
}
inline
dds::core::cond::GuardCondition
guard(SimpleUserCallback cb)
{
auto cond_ref = std::make_shared<dds::core::cond::GuardCondition>();
dds::core::cond::GuardCondition cond;
cond->handler(
[cb, cond_ref]() {
cb();
cond_ref->trigger_value(false);
});
*cond_ref = cond;
return cond;
}
} // namespace condition
} // namespace ros2dds
#endif // ROS2DDS__CONDITION_HPP_
|
hpp
|
rticonnextdds-robot-helpers
|
data/projects/rticonnextdds-robot-helpers/ros2dds/include/ros2dds/qos.hpp
|
// Copyright 2021 Real-Time Innovations, Inc. (RTI)
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#ifndef ROS2DDS__QOS_HPP_
#define ROS2DDS__QOS_HPP_
#include <string>
#include "ros2dds/domain.hpp"
namespace ros2dds
{
inline
void set_default_qos_properties(dds::pub::qos::DataWriterQos & qos)
{
const char * const prop_name =
"dds.data_writer.history.memory_manager.fast_pool.pool_buffer_max_size";
if (!qos.policy<rti::core::policy::Property>().exists(prop_name)) {
rti::core::policy::Property props;
props.set({prop_name, "0"}, false);
qos << props;
}
}
inline
void set_default_qos_properties(dds::sub::qos::DataReaderQos & qos)
{
const char * const prop_name =
"dds.data_reader.history.memory_manager.fast_pool.pool_buffer_max_size";
if (!qos.policy<rti::core::policy::Property>().exists(prop_name)) {
rti::core::policy::Property props;
props.set({prop_name, "0"}, false);
qos << props;
}
}
template<typename NodeT = rclcpp::Node>
dds::pub::qos::DataWriterQos
default_datawriter_qos(NodeT & node)
{
auto participant = domain_participant<NodeT>(node);
auto publisher = rti::pub::implicit_publisher(participant);
auto qos = publisher.default_datawriter_qos();
set_default_qos_properties(qos);
return qos;
}
template<typename NodeT = rclcpp::Node>
dds::pub::qos::DataWriterQos
default_datawriter_qos(
NodeT & node,
const std::string & topic_name,
const bool expand_topic_name = true,
const TopicKind topic_kind = TopicKind::Topic,
const bool use_ros_conventions = true)
{
auto participant = domain_participant<NodeT>(node);
auto publisher = rti::pub::implicit_publisher(participant);
std::string fq_topic_name = topic_name;
if (expand_topic_name) {
fq_topic_name = resolve_topic_name<NodeT>(
node, topic_name, topic_kind, use_ros_conventions);
}
dds::pub::qos::DataWriterQos dw_qos;
if (DDS_RETCODE_OK !=
DDS_Publisher_get_default_datawriter_qos_w_topic_name(
publisher->native_publisher(), dw_qos->native(), fq_topic_name.c_str()))
{
throw std::runtime_error("failed to get C writer qos");
}
set_default_qos_properties(dw_qos);
return dw_qos;
// auto qos_provider = dds::core::QosProvider::Default();
// return qos_provider->datawriter_qos_w_topic_name(topic_name);
}
template<
typename MessageT,
typename NodeT = rclcpp::Node>
dds::pub::qos::DataWriterQos
default_datawriter_qos(
NodeT & node,
const dds::topic::TopicDescription<MessageT> & topic)
{
return default_datawriter_qos<NodeT>(
node, topic.name(), false /* expand_topic_name */);
}
template<typename NodeT = rclcpp::Node>
dds::sub::qos::DataReaderQos
default_datareader_qos(NodeT & node)
{
auto participant = domain_participant<NodeT>(node);
auto subscriber = rti::sub::implicit_subscriber(participant);
auto qos = subscriber.default_datareader_qos();
set_default_qos_properties(qos);
return qos;
}
template<typename NodeT = rclcpp::Node>
dds::sub::qos::DataReaderQos
default_datareader_qos(
NodeT & node,
const std::string & topic_name,
const bool expand_topic_name = true,
const TopicKind topic_kind = TopicKind::Topic,
const bool use_ros_conventions = true)
{
auto participant = domain_participant<NodeT>(node);
auto subscriber = rti::sub::implicit_subscriber(participant);
std::string fq_topic_name = topic_name;
if (expand_topic_name) {
fq_topic_name = resolve_topic_name<NodeT>(
node, topic_name, topic_kind, use_ros_conventions);
}
dds::sub::qos::DataReaderQos dr_qos;
if (DDS_RETCODE_OK !=
DDS_Subscriber_get_default_datareader_qos_w_topic_name(
subscriber->native_subscriber(), dr_qos->native(), fq_topic_name.c_str()))
{
throw std::runtime_error("failed to get C reader qos");
}
set_default_qos_properties(dr_qos);
return dr_qos;
// (void)node;
// auto qos_provider = dds::core::QosProvider::Default();
// return qos_provider.delegate()->datareader_qos_w_topic_name(topic_name);
}
template<
typename MessageT,
typename NodeT = rclcpp::Node>
dds::sub::qos::DataReaderQos
default_datareader_qos(
NodeT & node,
const dds::topic::TopicDescription<MessageT> & topic)
{
return default_datareader_qos<NodeT>(
node, topic->name(), false /* resolve_topic_name */);
}
template<typename NodeT = rclcpp::Node>
dds::pub::qos::DataWriterQos
datawriter_qos_profile(
NodeT & node,
const std::string & qos_profile)
{
(void)node;
auto qos_provider = dds::core::QosProvider::Default();
return qos_provider.datawriter_qos(qos_profile);
}
template<typename NodeT = rclcpp::Node>
dds::sub::qos::DataReaderQos
datareader_qos_profile(
NodeT & node,
const std::string & qos_profile)
{
(void)node;
auto qos_provider = dds::core::QosProvider::Default();
return qos_provider.datareader_qos(qos_profile);
}
} // namespace ros2dds
#endif // ROS2DDS__QOS_HPP_
|
hpp
|
rticonnextdds-robot-helpers
|
data/projects/rticonnextdds-robot-helpers/ros2dds/include/ros2dds/ros2dds.hpp
|
// Copyright 2021 Real-Time Innovations, Inc. (RTI)
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#ifndef ROS2DDS__ROS2DDS_HPP_
#define ROS2DDS__ROS2DDS_HPP_
#include "ros2dds/domain.hpp"
#include "ros2dds/resolve.hpp"
#include "ros2dds/topic.hpp"
#include "ros2dds/qos.hpp"
#include "ros2dds/pub.hpp"
#include "ros2dds/sub.hpp"
#include "ros2dds/request.hpp"
#include "ros2dds/condition.hpp"
#include "ros2dds/waitset_executor.hpp"
#endif // ROS2DDS__ROS2DDS_HPP_
|
hpp
|
rticonnextdds-robot-helpers
|
data/projects/rticonnextdds-robot-helpers/ros2dds/include/ros2dds/resolve.hpp
|
// Copyright 2021 Real-Time Innovations, Inc. (RTI)
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#ifndef ROS2DDS__RESOLVE_HPP_
#define ROS2DDS__RESOLVE_HPP_
#include <cstring>
#include <string>
#include <exception>
#include "rcpputils/find_and_replace.hpp"
#include "rclcpp/rclcpp.hpp"
#include "ros2dds/domain.hpp"
#include "ros2dds/visibility_control.hpp"
#include "rclcpp/node_interfaces/node_topics_interface.hpp"
namespace ros2dds
{
/**
* @brief Enumeration describing the purpose of a certain topic.
*
* DDS topics are used for various purposes:
*
* - Distribute sample of a certain type.
* - Send a request payload to a service.
* - Receive a reply payload from a service.
*
*/
enum class TopicKind
{
Topic = 0,
Request = 1,
Reply = 2
};
/**
* @brief
*
* @param node_name
* @param namespace
* @param topic_name
* @param topic_kind
* @param use_ros_conventions
* @return std::string
*/
ROS2DDS_PUBLIC
std::string
resolve_topic_name(
const std::string & node_name,
const std::string & node_namespace,
const std::string & topic_name,
const TopicKind topic_kind = TopicKind::Topic,
const bool use_ros_conventions = true);
/**
* @brief
*
* @param node
* @param topic_name
* @param topic_kind
* @param use_ros_conventions
* @return std::string
*/
template<typename NodeT>
std::string
resolve_topic_name(
NodeT & node,
const std::string & topic_name,
const TopicKind topic_kind = TopicKind::Topic,
const bool use_ros_conventions = true)
{
return resolve_topic_name(
node_name(node), node_namespace(node), topic_name, topic_kind, use_ros_conventions);
}
template<>
std::string
resolve_topic_name(
rclcpp::Node & node,
const std::string & topic_name,
const TopicKind topic_kind,
const bool use_ros_conventions);
ROS2DDS_PUBLIC
std::string
resolve_type_name(
const std::string & type_name,
const bool use_ros_conventions = true);
} // namespace ros2dds
#endif // ROS2DDS__RESOLVE_HPP_
|
hpp
|
rticonnextdds-robot-helpers
|
data/projects/rticonnextdds-robot-helpers/ros2dds/include/ros2dds/visibility_control.hpp
|
// Copyright 2015 Open Source Robotics Foundation, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#ifndef ROS2DDS__VISIBILITY_CONTROL_HPP_
#define ROS2DDS__VISIBILITY_CONTROL_HPP_
// This logic was borrowed (then namespaced) from the examples on the gcc wiki:
// https://gcc.gnu.org/wiki/Visibility
#if defined _WIN32 || defined __CYGWIN__
#ifdef __GNUC__
#define ROS2DDS_EXPORT __attribute__ ((dllexport))
#define ROS2DDS_IMPORT __attribute__ ((dllimport))
#else
#define ROS2DDS_EXPORT __declspec(dllexport)
#define ROS2DDS_IMPORT __declspec(dllimport)
#endif
#ifdef ROS2DDS_BUILDING_LIBRARY
#define ROS2DDS_PUBLIC ROS2DDS_EXPORT
#else
#define ROS2DDS_PUBLIC ROS2DDS_IMPORT
#endif
#define ROS2DDS_PUBLIC_TYPE ROS2DDS_PUBLIC
#define ROS2DDS_LOCAL
#else
#define ROS2DDS_EXPORT __attribute__ ((visibility("default")))
#define ROS2DDS_IMPORT
#if __GNUC__ >= 4
#define ROS2DDS_PUBLIC __attribute__ ((visibility("default")))
#define ROS2DDS_LOCAL __attribute__ ((visibility("hidden")))
#else
#define ROS2DDS_PUBLIC
#define ROS2DDS_LOCAL
#endif
#define ROS2DDS_PUBLIC_TYPE
#endif
#endif // ROS2DDS__VISIBILITY_CONTROL_HPP_
|
hpp
|
rticonnextdds-getting-started
|
data/projects/rticonnextdds-getting-started/3_streaming_data/c++98/chocolate_factory_publisher.cxx
|
/*
* (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.
*/
#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include "chocolate_factory.h"
#include "chocolate_factorySupport.h"
#include "ndds/ndds_cpp.h"
#include "application.h"
using namespace application;
static int shutdown(
DDSDomainParticipant *participant,
const char *shutdown_message,
int status);
int run_example(
unsigned int domain_id,
unsigned int sample_count,
const char *sensor_id)
{
// Connext DDS setup
// -----------------
// A DomainParticipant allows an application to begin communicating in
// a DDS domain. Typically there is one DomainParticipant per application.
// DomainParticipant QoS is configured in USER_QOS_PROFILES.xml
DDSDomainParticipant *participant =
DDSTheParticipantFactory->create_participant(
domain_id,
DDS_PARTICIPANT_QOS_DEFAULT,
NULL /* listener */,
DDS_STATUS_MASK_NONE);
if (participant == NULL) {
return shutdown(participant, "create_participant error", EXIT_FAILURE);
}
// A Publisher allows an application to create one or more DataWriters
// Publisher QoS is configured in USER_QOS_PROFILES.xml
DDSPublisher *publisher = participant->create_publisher(
DDS_PUBLISHER_QOS_DEFAULT,
NULL /* listener */,
DDS_STATUS_MASK_NONE);
if (publisher == NULL) {
return shutdown(participant, "create_publisher error", EXIT_FAILURE);
}
// Register the datatype to use when creating the Topic
const char *type_name = TemperatureTypeSupport::get_type_name();
DDS_ReturnCode_t retcode =
TemperatureTypeSupport::register_type(participant, type_name);
if (retcode != DDS_RETCODE_OK) {
return shutdown(participant, "register_type error", EXIT_FAILURE);
}
// A Topic has a name and a datatype. Create a Topic called
// "ChocolateTemperature" with your registered data type
DDSTopic *topic = participant->create_topic(
"ChocolateTemperature",
type_name,
DDS_TOPIC_QOS_DEFAULT,
NULL /* listener */,
DDS_STATUS_MASK_NONE);
if (topic == NULL) {
return shutdown(participant, "create_topic error", EXIT_FAILURE);
}
// This DataWriter writes data on Topic "ChocolateTemperature"
// DataWriter QoS is configured in USER_QOS_PROFILES.xml
DDSDataWriter *writer = publisher->create_datawriter(
topic,
DDS_DATAWRITER_QOS_DEFAULT,
NULL /* listener */,
DDS_STATUS_MASK_NONE);
if (writer == NULL) {
return shutdown(participant, "create_datawriter error", EXIT_FAILURE);
}
// A narrow is a cast from a generic DataWriter to one that is specific
// to your type. Use the type specific DataWriter to write()
TemperatureDataWriter *temperature_writer =
TemperatureDataWriter::narrow(writer);
if (temperature_writer == NULL) {
return shutdown(participant, "DataWriter narrow error", EXIT_FAILURE);
}
// Exercise #2.1: Add new Topic, data type, and DataWriter
// Create data sample for writing
Temperature *sample = TemperatureTypeSupport::create_data();
if (sample == NULL) {
return shutdown(
participant,
"TemperatureTypeSupport::create_data error",
EXIT_FAILURE);
}
// Main loop, write data
// ---------------------
for (unsigned int samples_written = 0;
!shutdown_requested && samples_written < sample_count;
++samples_written) {
// Modify the data to be written here
snprintf(sample->sensor_id, 255, "%s", sensor_id);
sample->degrees = rand() % 3 + 30; // Random number between 30 and 32
// Exercise #2.2 Write data with new ChocolateLotState DataWriter
std::cout << "Writing ChocolateTemperature, count " << samples_written
<< std::endl;
retcode = temperature_writer->write(*sample, DDS_HANDLE_NIL);
if (retcode != DDS_RETCODE_OK) {
std::cerr << "write error " << retcode << std::endl;
}
// Exercise #1.1: Change this to sleep 100 ms in between writing temperatures
DDS_Duration_t send_period = { 4, 0 };
NDDSUtility::sleep(send_period);
}
// Cleanup
// -------
// Exercise #2.3 Clean up ChocolateLotState data sample
// Delete data sample
retcode = TemperatureTypeSupport::delete_data(sample);
if (retcode != DDS_RETCODE_OK) {
std::cerr << "TemperatureTypeSupport::delete_data error " << retcode
<< std::endl;
}
// Delete all entities (DataWriter, Topic, Publisher, DomainParticipant)
return shutdown(participant, "shutting down", EXIT_SUCCESS);
}
// Delete all entities
static int shutdown(
DDSDomainParticipant *participant,
const char *shutdown_message,
int status)
{
DDS_ReturnCode_t retcode;
std::cout << shutdown_message << std::endl;
if (participant != NULL) {
// This includes everything created by this Participant, including
// DataWriters, Topics, Publishers. (and Subscribers and DataReaders)
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_example(
arguments.domain_id,
arguments.sample_count,
arguments.sensor_id);
// Releases the memory used by the participant factory. Optional at
// application shutdown
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-getting-started
|
data/projects/rticonnextdds-getting-started/3_streaming_data/c++98/chocolate_factory_subscriber.cxx
|
/*
* (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.
*/
#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include "chocolate_factory.h"
#include "chocolate_factorySupport.h"
#include "ndds/ndds_cpp.h"
#include "application.h"
using namespace application;
static int shutdown(
DDSDomainParticipant *participant,
const char *shutdown_message,
int status);
// Process data. Returns number of samples processed.
unsigned int process_data(TemperatureDataReader *temperature_reader)
{
TemperatureSeq data_seq;
DDS_SampleInfoSeq info_seq;
unsigned int samples_read = 0;
// Take available data from DataReader's queue
DDS_ReturnCode_t retcode = temperature_reader->take(data_seq, info_seq);
if (retcode != DDS_RETCODE_OK) {
std::cerr << "take error " << retcode << std::endl;
return 0;
}
// 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) {
std::cout << "Received instance state notification" << std::endl;
continue;
}
// Print data
TemperatureTypeSupport::print_data(&data_seq[i]);
samples_read++;
}
// Data sequence was loaned from middleware for performance.
// Return loan when application is finished with data.
temperature_reader->return_loan(data_seq, info_seq);
return samples_read;
}
int run_example(unsigned int domain_id, unsigned int sample_count)
{
// Connext DDS Setup
// -----------------
// A DomainParticipant allows an application to begin communicating in
// a DDS domain. Typically there is one DomainParticipant per application.
// DomainParticipant QoS is configured in USER_QOS_PROFILES.xml
DDSDomainParticipant *participant =
DDSTheParticipantFactory->create_participant(
domain_id,
DDS_PARTICIPANT_QOS_DEFAULT,
NULL /* listener */,
DDS_STATUS_MASK_NONE);
if (participant == NULL) {
shutdown(participant, "create_participant error", EXIT_FAILURE);
}
// A Subscriber allows an application to create one or more DataReaders
// Subscriber QoS is configured in USER_QOS_PROFILES.xml
DDSSubscriber *subscriber = participant->create_subscriber(
DDS_SUBSCRIBER_QOS_DEFAULT,
NULL /* listener */,
DDS_STATUS_MASK_NONE);
if (subscriber == NULL) {
shutdown(participant, "create_subscriber error", EXIT_FAILURE);
}
// Register the datatype to use when creating the Topic
const char *type_name = TemperatureTypeSupport::get_type_name();
DDS_ReturnCode_t retcode =
TemperatureTypeSupport::register_type(participant, type_name);
if (retcode != DDS_RETCODE_OK) {
shutdown(participant, "register_type error", EXIT_FAILURE);
}
// A Topic has a name and a datatype. Create a Topic called
// "ChocolateTemperature" with your registered data type
DDSTopic *topic = participant->create_topic(
"ChocolateTemperature",
type_name,
DDS_TOPIC_QOS_DEFAULT,
NULL /* listener */,
DDS_STATUS_MASK_NONE);
if (topic == NULL) {
shutdown(participant, "create_topic error", EXIT_FAILURE);
}
// This DataReader reads data of type Temperature on Topic
// "ChocolateTemperature". DataReader QoS is configured in
// USER_QOS_PROFILES.xml
DDSDataReader *reader = subscriber->create_datareader(
topic,
DDS_DATAREADER_QOS_DEFAULT,
NULL,
DDS_STATUS_MASK_NONE);
if (reader == NULL) {
shutdown(participant, "create_datareader error", EXIT_FAILURE);
}
// Get status condition: Each entity has a Status Condition, which
// gets triggered when a status becomes true
DDSStatusCondition *status_condition = reader->get_statuscondition();
if (status_condition == NULL) {
shutdown(participant, "get_statuscondition error", EXIT_FAILURE);
}
// Enable only the status we are interested in:
// DDS_DATA_AVAILABLE_STATUS
retcode = status_condition->set_enabled_statuses(DDS_DATA_AVAILABLE_STATUS);
if (retcode != DDS_RETCODE_OK) {
shutdown(participant, "set_enabled_statuses error", EXIT_FAILURE);
}
// Create the WaitSet and attach the Status Condition to it. The WaitSet
// will be woken when the condition is triggered.
DDSWaitSet waitset;
retcode = waitset.attach_condition(status_condition);
if (retcode != DDS_RETCODE_OK) {
shutdown(participant, "attach_condition error", EXIT_FAILURE);
}
// A narrow is a cast from a generic DataReader to one that is specific
// to your type. Use the type specific DataReader to read data
TemperatureDataReader *temperature_reader =
TemperatureDataReader::narrow(reader);
if (temperature_reader == NULL) {
shutdown(participant, "DataReader narrow error", EXIT_FAILURE);
}
// Main loop. Wait for data to arrive, and process when it arrives.
// ----------------------------------------------------------------
unsigned int samples_read = 0;
while (!shutdown_requested && samples_read < sample_count) {
DDSConditionSeq active_conditions_seq;
// wait() blocks execution of the thread until one or more attached
// Conditions become true, or until a user-specified timeout expires.
DDS_Duration_t wait_timeout = { 4, 0 };
retcode = waitset.wait(active_conditions_seq, wait_timeout);
// You get a timeout if no conditions were triggered before the timeout
if (retcode == DDS_RETCODE_TIMEOUT) {
std::cout << "Wait timed out after 4 seconds." << std::endl;
continue;
} else if (retcode != DDS_RETCODE_OK) {
std::cerr << "wait returned error: " << retcode << std::endl;
break;
}
// Get the status changes to check which status condition
// triggered the WaitSet to wake
DDS_StatusMask triggeredmask = temperature_reader->get_status_changes();
// If the status is "Data Available"
if (triggeredmask & DDS_DATA_AVAILABLE_STATUS) {
samples_read += process_data(temperature_reader);
}
}
// Cleanup
// -------
// Delete all entities (DataReader, Topic, Subscriber, DomainParticipant)
return shutdown(participant, "shutting down", 0);
}
// Delete all entities
static int shutdown(
DDSDomainParticipant *participant,
const char *shutdown_message,
int status)
{
DDS_ReturnCode_t retcode;
std::cout << shutdown_message << std::endl;
if (participant != NULL) {
// This includes everything created by this Participant, including
// DataWriters, Topics, Publishers. (and Subscribers and DataReaders)
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_example(arguments.domain_id, arguments.sample_count);
// Releases the memory used by the participant factory. Optional at
// application shutdown
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-getting-started
|
data/projects/rticonnextdds-getting-started/3_streaming_data/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 <ctime>
#include <limits>
#include "ndds/ndds_cpp.h"
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;
char sensor_id[256];
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 = (std::numeric_limits<unsigned int>::max)();
arguments.verbosity = NDDS_CONFIG_LOG_VERBOSITY_ERROR;
arguments.parse_result = PARSE_RETURN_OK;
// Initialize with an integer value
srand((unsigned int)time(NULL));
snprintf(arguments.sensor_id, 255, "%d", rand() % 10);
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], "-i") == 0
|| strcmp(argv[arg_processing], "--sensor-id") == 0)) {
snprintf(arguments.sensor_id, 255, "%s", 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"
" -i, --sensor-id <string> Unique ID of temperature sensor.\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-getting-started
|
data/projects/rticonnextdds-getting-started/3_streaming_data/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;
std::string sensor_id;
rti::config::Verbosity verbosity;
};
// 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)();
srand((unsigned int)time(NULL));
std::string sensor_id = std::to_string(rand() % 50);
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 ((argc > arg_processing + 1)
&& (strcmp(argv[arg_processing], "-i") == 0
|| strcmp(argv[arg_processing], "--sensor-id") == 0)) {
sensor_id = 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"
" cleanly shutting down. \n"
" -i, --sensor-id <string> Unique ID of temperature sensor.\n"\
" -v, --verbosity <int> How much debugging output to show.\n"\
" Range: 0-5 \n"
" Default: 0"
<< std::endl;
}
return { parse_result, domain_id, sample_count, sensor_id, verbosity };
}
} // namespace application
#endif // APPLICATION_HPP
|
hpp
|
rticonnextdds-getting-started
|
data/projects/rticonnextdds-getting-started/3_streaming_data/c++11/chocolate_factory_publisher.cxx
|
/*
* (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.
*/
#include <iostream>
#include <dds/pub/ddspub.hpp>
#include <rti/util/util.hpp> // for sleep()
#include <rti/config/Logger.hpp> // for logging
// Or simply include <dds/dds.hpp>
#include "chocolate_factory.hpp"
#include "application.hpp" // Argument parsing
using namespace application;
void run_example(
unsigned int domain_id,
unsigned int sample_count,
const std::string& sensor_id)
{
// A DomainParticipant allows an application to begin communicating in
// a DDS domain. Typically there is one DomainParticipant per application.
// DomainParticipant QoS is configured in USER_QOS_PROFILES.xml
dds::domain::DomainParticipant participant(domain_id);
// A Topic has a name and a datatype. Create a Topic named
// "ChocolateTemperature" with type Temperature
dds::topic::Topic<Temperature> topic(participant, "ChocolateTemperature");
// Exercise #2.1: Add new Topic
// A Publisher allows an application to create one or more DataWriters
// Publisher QoS is configured in USER_QOS_PROFILES.xml
dds::pub::Publisher publisher(participant);
// This DataWriter writes data on Topic "ChocolateTemperature"
// DataWriter QoS is configured in USER_QOS_PROFILES.xml
dds::pub::DataWriter<Temperature> writer(publisher, topic);
// Exercise #2.2: Add new DataWriter and data sample
// Create data sample for writing
Temperature sample;
for (unsigned int count = 0;
!shutdown_requested && count < sample_count;
count++) {
// Modify the data to be written here
sample.sensor_id(sensor_id);
sample.degrees(rand() % 3 + 30); // Random number between 30 and 32
// Exercise #2.3 Write data with new ChocolateLotState DataWriter
std::cout << "Writing ChocolateTemperature, count " << count
<< std::endl;
writer.write(sample);
// Exercise #1.1: Change this to sleep 100 ms in between writing temperatures
rti::util::sleep(dds::core::Duration(4));
}
}
int main(int argc, char *argv[])
{
// 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_example(
arguments.domain_id,
arguments.sample_count,
arguments.sensor_id);
} catch (const std::exception& ex) {
// This will catch DDS exceptions
std::cerr << "Exception in run_example(): " << ex.what()
<< std::endl;
return EXIT_FAILURE;
}
// Releases the memory used by the participant factory. Optional at
// application shutdown
dds::domain::DomainParticipant::finalize_participant_factory();
return EXIT_SUCCESS;
}
|
cxx
|
rticonnextdds-getting-started
|
data/projects/rticonnextdds-getting-started/3_streaming_data/c++11/chocolate_factory_subscriber.cxx
|
/*
* (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.
*/
#include <algorithm>
#include <iostream>
#include <dds/sub/ddssub.hpp>
#include <dds/core/ddscore.hpp>
#include <rti/config/Logger.hpp> // for logging
// Or simply include <dds/dds.hpp>
#include "chocolate_factory.hpp"
#include "application.hpp" // Argument parsing
using namespace application;
unsigned int process_data(dds::sub::DataReader<Temperature>& reader)
{
// Take all samples. Samples are loaned to application, loan is
// returned when LoanedSamples destructor called.
unsigned int samples_read = 0;
dds::sub::LoanedSamples<Temperature> samples = reader.take();
for (const auto& sample : samples) {
if (sample.info().valid()) {
samples_read++;
std::cout << sample.data() << std::endl;
}
}
return samples_read;
}
void run_example(unsigned int domain_id, unsigned int sample_count)
{
// A DomainParticipant allows an application to begin communicating in
// a DDS domain. Typically there is one DomainParticipant per application.
// Create a DomainParticipant with default Qos
dds::domain::DomainParticipant participant(domain_id);
// A Topic has a name and a datatype. Create a Topic named
// "ChocolateTemperature" with type Temperature
dds::topic::Topic<Temperature> topic(participant, "ChocolateTemperature");
// A Subscriber allows an application to create one or more DataReaders
// Subscriber QoS is configured in USER_QOS_PROFILES.xml
dds::sub::Subscriber subscriber(participant);
// This DataReader reads data of type Temperature on Topic
// "ChocolateTemperature". DataReader QoS is configured in
// USER_QOS_PROFILES.xml
dds::sub::DataReader<Temperature> reader(subscriber, topic);
// Obtain the DataReader's Status Condition
dds::core::cond::StatusCondition status_condition(reader);
// Enable the 'data available' status.
status_condition.enabled_statuses(
dds::core::status::StatusMask::data_available());
// Associate a handler with the status condition. This will run when the
// condition is triggered, in the context of the dispatch call (see below)
unsigned int samples_read = 0;
status_condition.extensions().handler([&reader, &samples_read]() {
samples_read += process_data(reader);
});
// Create a WaitSet and attach the StatusCondition
dds::core::cond::WaitSet waitset;
waitset += status_condition;
while (!shutdown_requested && samples_read < sample_count) {
// Dispatch will call the handlers associated to the WaitSet conditions
// when they activate
std::cout << "ChocolateTemperature subscriber sleeping for 4 sec..."
<< std::endl;
waitset.dispatch(dds::core::Duration(4)); // Wait up to 4s each time
}
}
int main(int argc, char *argv[])
{
// 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_example(arguments.domain_id, arguments.sample_count);
} catch (const std::exception& ex) {
// All DDS exceptions inherit from std::exception
std::cerr << "Exception in run_example(): " << ex.what()
<< std::endl;
return EXIT_FAILURE;
}
// Releases the memory used by the participant factory. Optional at
// application shutdown
dds::domain::DomainParticipant::finalize_participant_factory();
return EXIT_SUCCESS;
}
|
cxx
|
rticonnextdds-getting-started
|
data/projects/rticonnextdds-getting-started/2_hello_world/c++98/hello_world_subscriber.cxx
|
/*
* (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.
*/
#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include "hello_world.h"
#include "hello_worldSupport.h"
#include "ndds/ndds_cpp.h"
#include "application.h"
using namespace application;
static int shutdown(
DDSDomainParticipant *participant,
const char *shutdown_message,
int status);
// Process data. Returns number of samples processed.
unsigned int process_data(HelloWorldDataReader *hello_world_reader)
{
HelloWorldSeq data_seq;
DDS_SampleInfoSeq info_seq;
unsigned int samples_read = 0;
// Take available data from DataReader's queue
DDS_ReturnCode_t retcode = hello_world_reader->take(data_seq, info_seq);
if (retcode != DDS_RETCODE_OK) {
std::cerr << "take error " << retcode << std::endl;
return 0;
}
// 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) {
std::cout << "Received instance state notification" << std::endl;
continue;
}
// Print data
HelloWorldTypeSupport::print_data(&data_seq[i]);
samples_read++;
}
// Data sequence was loaned from middleware for performance.
// Return loan when application is finished with data.
hello_world_reader->return_loan(data_seq, info_seq);
return samples_read;
}
int run_example(unsigned int domain_id, unsigned int sample_count)
{
// Connext DDS Setup
// -----------------
// A DomainParticipant allows an application to begin communicating in
// a DDS domain. Typically there is one DomainParticipant per application.
// DomainParticipant QoS is configured in USER_QOS_PROFILES.xml
DDSDomainParticipant *participant =
DDSTheParticipantFactory->create_participant(
domain_id,
DDS_PARTICIPANT_QOS_DEFAULT,
NULL /* listener */,
DDS_STATUS_MASK_NONE);
if (participant == NULL) {
shutdown(participant, "create_participant error", EXIT_FAILURE);
}
// A Subscriber allows an application to create one or more DataReaders
// Subscriber QoS is configured in USER_QOS_PROFILES.xml
DDSSubscriber *subscriber = participant->create_subscriber(
DDS_SUBSCRIBER_QOS_DEFAULT,
NULL /* listener */,
DDS_STATUS_MASK_NONE);
if (subscriber == NULL) {
shutdown(participant, "create_subscriber error", EXIT_FAILURE);
}
// Register the datatype to use when creating the Topic
const char *type_name = HelloWorldTypeSupport::get_type_name();
DDS_ReturnCode_t retcode =
HelloWorldTypeSupport::register_type(participant, type_name);
if (retcode != DDS_RETCODE_OK) {
shutdown(participant, "register_type error", EXIT_FAILURE);
}
// A Topic has a name and a datatype. Create a Topic called
// "HelloWorld Topic" with your registered data type
DDSTopic *topic = participant->create_topic(
"Example HelloWorld",
type_name,
DDS_TOPIC_QOS_DEFAULT,
NULL /* listener */,
DDS_STATUS_MASK_NONE);
if (topic == NULL) {
shutdown(participant, "create_topic error", EXIT_FAILURE);
}
// This DataReader will read data of type HelloWorld on Topic
// "HelloWorld Topic". DataReader QoS is configured in
// USER_QOS_PROFILES.xml
DDSDataReader *reader = subscriber->create_datareader(
topic,
DDS_DATAREADER_QOS_DEFAULT,
NULL,
DDS_STATUS_MASK_NONE);
if (reader == NULL) {
shutdown(participant, "create_datareader error", EXIT_FAILURE);
}
// Get status condition: Each entity has a Status Condition, which
// gets triggered when a status becomes true
DDSStatusCondition *status_condition = reader->get_statuscondition();
if (status_condition == NULL) {
shutdown(participant, "get_statuscondition error", EXIT_FAILURE);
}
// Enable only the status we are interested in:
// DDS_DATA_AVAILABLE_STATUS
retcode = status_condition->set_enabled_statuses(DDS_DATA_AVAILABLE_STATUS);
if (retcode != DDS_RETCODE_OK) {
shutdown(participant, "set_enabled_statuses error", EXIT_FAILURE);
}
// Create the WaitSet and attach the Status Condition to it. The WaitSet
// will be woken when the condition is triggered.
DDSWaitSet waitset;
retcode = waitset.attach_condition(status_condition);
if (retcode != DDS_RETCODE_OK) {
shutdown(participant, "attach_condition error", EXIT_FAILURE);
}
// A narrow is a cast from a generic DataReader to one that is specific
// to your type. Use the type specific DataReader to read data
HelloWorldDataReader *hello_world_reader =
HelloWorldDataReader::narrow(reader);
if (hello_world_reader == NULL) {
shutdown(participant, "DataReader narrow error", EXIT_FAILURE);
}
// Main loop. Wait for data to arrive, and process when it arrives.
// ----------------------------------------------------------------
unsigned int samples_read = 0;
while (!shutdown_requested && samples_read < sample_count) {
DDSConditionSeq active_conditions_seq;
// wait() blocks execution of the thread until one or more attached
// Conditions become true, or until a user-specified timeout expires.
DDS_Duration_t wait_timeout = { 4, 0 };
retcode = waitset.wait(active_conditions_seq, wait_timeout);
// You get a timeout if no conditions were triggered before the timeout
if (retcode == DDS_RETCODE_TIMEOUT) {
std::cout << "Wait timed out after 4 seconds." << std::endl;
continue;
} else if (retcode != DDS_RETCODE_OK) {
std::cerr << "wait returned error: " << retcode << std::endl;
break;
}
// Get the status changes to check which status condition
// triggered the WaitSet to wake
DDS_StatusMask triggeredmask =
hello_world_reader->get_status_changes();
// If the status is "Data Available"
if (triggeredmask & DDS_DATA_AVAILABLE_STATUS) {
samples_read += process_data(hello_world_reader);
}
}
// Cleanup
// -------
// Delete all entities (DataReader, Topic, Subscriber, DomainParticipant)
return shutdown(participant, "shutting down", 0);
}
// Delete all entities
static int shutdown(
DDSDomainParticipant *participant,
const char *shutdown_message,
int status)
{
DDS_ReturnCode_t retcode;
std::cout << shutdown_message << std::endl;
if (participant != NULL) {
// This includes everything created by this Participant, including
// DataWriters, Topics, Publishers. (and Subscribers and DataReaders)
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_example(arguments.domain_id, arguments.sample_count);
// Releases the memory used by the participant factory. Optional at
// application shutdown
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-getting-started
|
data/projects/rticonnextdds-getting-started/2_hello_world/c++98/hello_world_publisher.cxx
|
/*
* (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.
*/
#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include "hello_world.h"
#include "hello_worldSupport.h"
#include "ndds/ndds_cpp.h"
#include "application.h"
using namespace application;
static int shutdown(
DDSDomainParticipant *participant,
const char *shutdown_message,
int status);
int run_example(unsigned int domain_id, unsigned int sample_count)
{
// Connext DDS setup
// -----------------
// A DomainParticipant allows an application to begin communicating in
// a DDS domain. Typically there is one DomainParticipant per application.
// DomainParticipant QoS is configured in USER_QOS_PROFILES.xml
DDSDomainParticipant *participant =
DDSTheParticipantFactory->create_participant(
domain_id,
DDS_PARTICIPANT_QOS_DEFAULT,
NULL /* listener */,
DDS_STATUS_MASK_NONE);
if (participant == NULL) {
return shutdown(participant, "create_participant error", EXIT_FAILURE);
}
// A Publisher allows an application to create one or more DataWriters
// Publisher QoS is configured in USER_QOS_PROFILES.xml
DDSPublisher *publisher = participant->create_publisher(
DDS_PUBLISHER_QOS_DEFAULT,
NULL /* listener */,
DDS_STATUS_MASK_NONE);
if (publisher == NULL) {
return shutdown(participant, "create_publisher error", EXIT_FAILURE);
}
// Register the datatype to use when creating the Topic
const char *type_name = HelloWorldTypeSupport::get_type_name();
DDS_ReturnCode_t retcode =
HelloWorldTypeSupport::register_type(participant, type_name);
if (retcode != DDS_RETCODE_OK) {
return shutdown(participant, "register_type error", EXIT_FAILURE);
}
// A Topic has a name and a datatype. Create a Topic called
// "HelloWorld Topic" with your registered data type
DDSTopic *topic = participant->create_topic(
"Example HelloWorld",
type_name,
DDS_TOPIC_QOS_DEFAULT,
NULL /* listener */,
DDS_STATUS_MASK_NONE);
if (topic == NULL) {
return shutdown(participant, "create_topic error", EXIT_FAILURE);
}
// This DataWriter will write data on Topic "HelloWorld Topic"
// DataWriter QoS is configured in USER_QOS_PROFILES.xml
DDSDataWriter *writer = publisher->create_datawriter(
topic,
DDS_DATAWRITER_QOS_DEFAULT,
NULL /* listener */,
DDS_STATUS_MASK_NONE);
if (writer == NULL) {
return shutdown(participant, "create_datawriter error", EXIT_FAILURE);
}
// A narrow is a cast from a generic DataWriter to one that is specific
// to your type. Use the type specific DataWriter to write()
HelloWorldDataWriter *hello_world_writer =
HelloWorldDataWriter::narrow(writer);
if (hello_world_writer == NULL) {
return shutdown(participant, "DataWriter narrow error", EXIT_FAILURE);
}
// Create data sample for writing
HelloWorld *sample = HelloWorldTypeSupport::create_data();
if (sample == NULL) {
return shutdown(
participant,
"HelloWorldTypeSupport::create_data error",
EXIT_FAILURE);
}
// Main loop, write data
// ---------------------
for (unsigned int count = 0;
!shutdown_requested && count < sample_count;
++count) {
// Modify the data to be written here
std::cout << "Writing HelloWorld, count " << count << std::endl;
retcode = hello_world_writer->write(*sample, DDS_HANDLE_NIL);
if (retcode != DDS_RETCODE_OK) {
std::cerr << "write error " << retcode << std::endl;
}
// Send every 4 seconds
DDS_Duration_t send_period = { 4, 0 };
NDDSUtility::sleep(send_period);
}
// Cleanup
// -------
// Delete data sample
retcode = HelloWorldTypeSupport::delete_data(sample);
if (retcode != DDS_RETCODE_OK) {
std::cerr << "HelloWorldTypeSupport::delete_data error " << retcode
<< std::endl;
}
// Delete all entities (DataWriter, Topic, Publisher, DomainParticipant)
return shutdown(participant, "shutting down", EXIT_SUCCESS);
}
// Delete all entities
static int shutdown(
DDSDomainParticipant *participant,
const char *shutdown_message,
int status)
{
DDS_ReturnCode_t retcode;
std::cout << shutdown_message << std::endl;
if (participant != NULL) {
// This includes everything created by this Participant, including
// DataWriters, Topics, Publishers. (and Subscribers and DataReaders)
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_example(arguments.domain_id, arguments.sample_count);
// Releases the memory used by the participant factory. Optional at
// application shutdown
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-getting-started
|
data/projects/rticonnextdds-getting-started/2_hello_world/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 <limits>
#include "ndds/ndds_cpp.h"
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 = (std::numeric_limits<unsigned 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-getting-started
|
data/projects/rticonnextdds-getting-started/2_hello_world/c++11/hello_world_subscriber.cxx
|
/*
* (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.
*/
#include <algorithm>
#include <iostream>
#include <dds/sub/ddssub.hpp>
#include <dds/core/ddscore.hpp>
#include <rti/config/Logger.hpp> // for logging
// Or simply include <dds/dds.hpp>
#include "hello_world.hpp"
#include "application.hpp" // Argument parsing
using namespace application;
unsigned int process_data(dds::sub::DataReader<HelloWorld>& reader)
{
// Take all samples. Samples are loaned to application, loan is
// returned when LoanedSamples destructor called.
unsigned int samples_read = 0;
dds::sub::LoanedSamples<HelloWorld> samples = reader.take();
for (const auto& sample : samples) {
if (sample.info().valid()) {
samples_read++;
std::cout << sample.data() << std::endl;
}
}
return samples_read;
}
void run_example(unsigned int domain_id, unsigned int sample_count)
{
// A DomainParticipant allows an application to begin communicating in
// a DDS domain. Typically there is one DomainParticipant per application.
// Create a DomainParticipant with default Qos
dds::domain::DomainParticipant participant(domain_id);
// A Topic has a name and a datatype. Create a Topic named
// "HelloWorld Topic" with type HelloWorld
dds::topic::Topic<HelloWorld> topic(participant, "Example HelloWorld");
// A Subscriber allows an application to create one or more DataReaders
// Subscriber QoS is configured in USER_QOS_PROFILES.xml
dds::sub::Subscriber subscriber(participant);
// This DataReader will read data of type HelloWorld on Topic
// "HelloWorld Topic". DataReader QoS is configured in
// USER_QOS_PROFILES.xml
dds::sub::DataReader<HelloWorld> reader(subscriber, topic);
// Obtain the DataReader's Status Condition
dds::core::cond::StatusCondition status_condition(reader);
// Enable the 'data available' status.
status_condition.enabled_statuses(
dds::core::status::StatusMask::data_available());
// Associate a handler with the status condition. This will run when the
// condition is triggered, in the context of the dispatch call (see below)
unsigned int samples_read = 0;
status_condition.extensions().handler([&reader, &samples_read]() {
samples_read += process_data(reader);
});
// Create a WaitSet and attach the StatusCondition
dds::core::cond::WaitSet waitset;
waitset += status_condition;
while (!shutdown_requested && samples_read < sample_count) {
// Dispatch will call the handlers associated to the WaitSet conditions
// when they activate
std::cout << "HelloWorld subscriber sleeping for 4 sec..."
<< std::endl;
waitset.dispatch(dds::core::Duration(4)); // Wait up to 4s each time
}
}
int main(int argc, char *argv[])
{
// 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_example(arguments.domain_id, arguments.sample_count);
} catch (const std::exception& ex) {
// All DDS exceptions inherit from std::exception
std::cerr << "Exception in run_example(): " << ex.what()
<< std::endl;
return EXIT_FAILURE;
}
// Releases the memory used by the participant factory. Optional at
// application shutdown
dds::domain::DomainParticipant::finalize_participant_factory();
return EXIT_SUCCESS;
}
|
cxx
|
rticonnextdds-getting-started
|
data/projects/rticonnextdds-getting-started/2_hello_world/c++11/hello_world_publisher.cxx
|
/*
* (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.
*/
#include <iostream>
#include <dds/pub/ddspub.hpp>
#include <rti/util/util.hpp> // for sleep()
#include <rti/config/Logger.hpp> // for logging
// Or simply include <dds/dds.hpp>
#include "hello_world.hpp"
#include "application.hpp" // Argument parsing
using namespace application;
void run_example(unsigned int domain_id, unsigned int sample_count)
{
// A DomainParticipant allows an application to begin communicating in
// a DDS domain. Typically there is one DomainParticipant per application.
// DomainParticipant QoS is configured in USER_QOS_PROFILES.xml
dds::domain::DomainParticipant participant(domain_id);
// A Topic has a name and a datatype. Create a Topic named
// "HelloWorld Topic" with type HelloWorld
dds::topic::Topic<HelloWorld> topic(participant, "Example HelloWorld");
// A Publisher allows an application to create one or more DataWriters
// Publisher QoS is configured in USER_QOS_PROFILES.xml
dds::pub::Publisher publisher(participant);
// This DataWriter will write data on Topic "HelloWorld Topic"
// DataWriter QoS is configured in USER_QOS_PROFILES.xml
dds::pub::DataWriter<HelloWorld> writer(publisher, topic);
// Create data sample for writing
HelloWorld sample;
for (unsigned int count = 0;
!shutdown_requested && count < sample_count;
count++) {
// Modify the data to be written here
std::cout << "Writing HelloWorld, count " << count << std::endl;
writer.write(sample);
rti::util::sleep(dds::core::Duration(4));
}
}
int main(int argc, char *argv[])
{
// 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_example(arguments.domain_id, arguments.sample_count);
} catch (const std::exception& ex) {
// This will catch DDS exceptions
std::cerr << "Exception in run_example(): " << ex.what()
<< std::endl;
return EXIT_FAILURE;
}
// Releases the memory used by the participant factory. Optional at
// application shutdown
dds::domain::DomainParticipant::finalize_participant_factory();
return EXIT_SUCCESS;
}
|
cxx
|
rticonnextdds-getting-started
|
data/projects/rticonnextdds-getting-started/2_hello_world/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;
};
// 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 { parse_result, domain_id, sample_count, verbosity };
}
} // namespace application
#endif // APPLICATION_HPP
|
hpp
|
rticonnextdds-getting-started
|
data/projects/rticonnextdds-getting-started/6_content_filters/c++98/ingredient_application.cxx
|
/*
* (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.
*/
#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include "chocolate_factory.h"
#include "chocolate_factorySupport.h"
#include "ndds/ndds_cpp.h"
#include "application.h"
using namespace application;
// Ingredient application:
// 1) Subscribes to the lot state
// 2) "Processes" the lot. (In this example, that means sleep for a time)
// 3) After "processing" the lot, publishes the lot state
static int shutdown(
DDSDomainParticipant *participant,
const char *shutdown_message,
int status);
void process_lot(
const StationKind station_kind,
ChocolateLotStateDataReader *lot_state_reader,
ChocolateLotStateDataWriter *lot_state_writer)
{
// Take all samples. Samples are loaned to application, loan is
// returned when LoanedSamples destructor called.
ChocolateLotStateSeq data_seq;
DDS_SampleInfoSeq info_seq;
// Take available data from DataReader's queue
DDS_ReturnCode_t retcode = lot_state_reader->take(data_seq, info_seq);
if (retcode != DDS_RETCODE_OK && retcode != DDS_RETCODE_NO_DATA) {
std::cerr << "take error " << retcode << std::endl;
return;
} else if (retcode == DDS_RETCODE_NO_DATA) {
return;
}
// Process lots waiting for ingredients
for (int i = 0; i < data_seq.length(); ++i) {
// Check if a sample is an instance lifecycle event
if (!info_seq[i].valid_data) {
// Received instance state update
continue;
}
// No need to check that this is the next station: content filter
// ensures that the reader only receives lots with
// next_station == this station.
std::cout << "Processing lot #" << data_seq[i].lot_id << std::endl;
// Send an update that the this station is processing lot
ChocolateLotState updated_state(data_seq[i]);
updated_state.lot_status = PROCESSING;
updated_state.next_station = INVALID_CONTROLLER;
updated_state.station = station_kind;
DDS_ReturnCode_t retcode =
lot_state_writer->write(updated_state, DDS_HANDLE_NIL);
if (retcode != DDS_RETCODE_OK) {
std::cerr << "write error " << retcode << std::endl;
}
// "Processing" the lot.
DDS_Duration_t processing_time = { 5, 0 };
NDDSUtility::sleep(processing_time);
// Send an update that this station is done processing the lot
updated_state.lot_status = COMPLETED;
updated_state.next_station = (StationKind)(station_kind + 1);
updated_state.station = station_kind;
retcode = lot_state_writer->write(updated_state, DDS_HANDLE_NIL);
if (retcode != DDS_RETCODE_OK) {
std::cerr << "write error " << retcode << std::endl;
}
}
// Data sequence was loaned from middleware for performance.
// Return loan when application is finished with data.
retcode = lot_state_reader->return_loan(data_seq, info_seq);
if (retcode != DDS_RETCODE_OK) {
std::cerr << "return_loan error " << retcode << std::endl;
}
}
void on_requested_incompatible_qos(DDSDataReader *reader)
{
DDS_RequestedIncompatibleQosStatus status;
reader->get_requested_incompatible_qos_status(status);
std::cout << "Discovered DataWriter with incompatible policy: ";
if (status.last_policy_id == DDS_RELIABILITY_QOS_POLICY_ID) {
std::cout << "Reliability" << std::endl;
}
if (status.last_policy_id == DDS_DURABILITY_QOS_POLICY_ID) {
std::cout << "Durability" << std::endl;
}
}
StationKind string_to_stationkind(const std::string& station_kind)
{
if (station_kind == "SUGAR_CONTROLLER") {
return SUGAR_CONTROLLER;
} else if (station_kind == "COCOA_BUTTER_CONTROLLER") {
return COCOA_BUTTER_CONTROLLER;
} else if (station_kind == "MILK_CONTROLLER") {
return MILK_CONTROLLER;
} else if (station_kind == "VANILLA_CONTROLLER") {
return VANILLA_CONTROLLER;
}
return INVALID_CONTROLLER;
}
int run_example(unsigned int domain_id, const std::string& station_kind)
{
StationKind current_station = string_to_stationkind(station_kind);
std::cout << station_kind << " station starting" << std::endl;
// Load XML QoS from a specific file
DDSDomainParticipantFactory *factory =
DDSDomainParticipantFactory::get_instance();
DDS_DomainParticipantFactoryQos factoryQos;
DDS_ReturnCode_t retcode = factory->get_qos(factoryQos);
if (retcode != DDS_RETCODE_OK) {
return shutdown(NULL, "get_qos error", EXIT_FAILURE);
}
const char *url_profiles[1] = { "qos_profiles.xml" };
factoryQos.profile.url_profile.from_array(url_profiles, 1);
factory->set_qos(factoryQos);
// Connext DDS setup
// -----------------
// A DomainParticipant allows an application to begin communicating in
// a DDS domain. Typically there is one DomainParticipant per application.
// Uses IngredientApplication QoS profile to set participant name.
DDSDomainParticipant *participant =
DDSTheParticipantFactory->create_participant_with_profile(
domain_id,
"ChocolateFactoryLibrary",
"IngredientApplication",
NULL /* listener */,
DDS_STATUS_MASK_NONE);
if (participant == NULL) {
return shutdown(participant, "create_participant error", EXIT_FAILURE);
}
// Create Topics
// Register the datatype to use when creating the Topic
const char *lot_state_type_name =
ChocolateLotStateTypeSupport::get_type_name();
retcode = ChocolateLotStateTypeSupport::register_type(
participant,
lot_state_type_name);
if (retcode != DDS_RETCODE_OK) {
return shutdown(participant, "register_type error", EXIT_FAILURE);
}
// A Topic has a name and a datatype. Create a Topic called
// "ChocolateLotState" with your registered ChocolateLotState data type
DDSTopic *lot_state_topic = participant->create_topic(
CHOCOLATE_LOT_STATE_TOPIC,
lot_state_type_name,
DDS_TOPIC_QOS_DEFAULT,
NULL /* listener */,
DDS_STATUS_MASK_NONE);
if (lot_state_topic == NULL) {
return shutdown(participant, "create_topic error", EXIT_FAILURE);
}
// Create content-filtered Topic
DDS_StringSeq parameters(1);
parameters.length(1);
char filter_value[256];
snprintf(filter_value, 256, "\'%s\'", station_kind.c_str());
// String sequence owns memory for the strings it contains, must allocate
parameters[0] = DDS_String_dup(filter_value);
DDSContentFilteredTopic *filtered_lot_state_topic =
participant->create_contentfilteredtopic(
"FilteredLotState",
lot_state_topic,
"next_station = %0",
parameters);
// Create Publisher and DataWriters
// A Publisher allows an application to create one or more DataWriters
// Publisher QoS is configured with default QoS
DDSPublisher *publisher = participant->create_publisher(
DDS_PUBLISHER_QOS_DEFAULT,
NULL /* listener */,
DDS_STATUS_MASK_NONE);
if (publisher == NULL) {
return shutdown(participant, "create_publisher error", EXIT_FAILURE);
}
// This DataWriter writes data on Topic "ChocolateLotState". DataWriter
// QoS is configured using ChocolateLotStateProfile QoS profile
DDSDataWriter *generic_lot_state_writer =
publisher->create_datawriter_with_profile(
lot_state_topic,
"ChocolateFactoryLibrary",
"ChocolateLotStateProfile",
NULL /* listener */,
DDS_STATUS_MASK_NONE);
if (generic_lot_state_writer == NULL) {
return shutdown(participant, "create_datawriter error", EXIT_FAILURE);
}
// A narrow is a cast from a generic DataWriter to one that is specific
// to your type. Use the type specific DataWriter to write()
ChocolateLotStateDataWriter *lot_state_writer =
ChocolateLotStateDataWriter::narrow(generic_lot_state_writer);
if (lot_state_writer == NULL) {
return shutdown(participant, "DataWriter narrow error", EXIT_FAILURE);
}
// Create Subscriber and DataReader
// A Subscriber allows an application to create one or more DataReaders
// Subscriber QoS is configured with default QoS
DDSSubscriber *subscriber = participant->create_subscriber(
DDS_SUBSCRIBER_QOS_DEFAULT,
NULL /* listener */,
DDS_STATUS_MASK_NONE);
if (subscriber == NULL) {
shutdown(participant, "create_subscriber error", EXIT_FAILURE);
}
// This DataReader reads data of type ChocolateLotState on Topic
// "ChocolateLotState" using ChocolateLotStateProfile QoS profile
DDSDataReader *generic_lot_state_reader =
subscriber->create_datareader_with_profile(
filtered_lot_state_topic,
"ChocolateFactoryLibrary",
"ChocolateLotStateProfile",
NULL,
DDS_STATUS_MASK_NONE);
if (generic_lot_state_reader == NULL) {
shutdown(participant, "create_datareader error", EXIT_FAILURE);
}
// Get status condition: Each entity has a Status Condition, which
// gets triggered when a status becomes true
DDSStatusCondition *status_condition =
generic_lot_state_reader->get_statuscondition();
if (status_condition == NULL) {
shutdown(participant, "get_statuscondition error", EXIT_FAILURE);
}
// Enable only the statuses we are interested in:
// DDS_DATA_AVAILABLE_STATUS, DDS_REQUESTED_INCOMPATIBLE_QOS_STATUS
retcode = status_condition->set_enabled_statuses(
DDS_DATA_AVAILABLE_STATUS | DDS_REQUESTED_INCOMPATIBLE_QOS_STATUS);
if (retcode != DDS_RETCODE_OK) {
shutdown(participant, "set_enabled_statuses error", EXIT_FAILURE);
}
// Create the WaitSet and attach the Status Condition to it. The WaitSet
// will be woken when the condition is triggered.
DDSWaitSet waitset;
retcode = waitset.attach_condition(status_condition);
if (retcode != DDS_RETCODE_OK) {
shutdown(participant, "attach_condition error", EXIT_FAILURE);
}
// A narrow is a cast from a generic DataReader to one that is specific
// to your type. Use the type specific DataReader to read data
ChocolateLotStateDataReader *lot_state_reader =
ChocolateLotStateDataReader::narrow(generic_lot_state_reader);
if (lot_state_reader == NULL) {
shutdown(participant, "DataReader narrow error", EXIT_FAILURE);
}
// Main loop, wait for lots
// ------------------------
while (!shutdown_requested) {
// Wait for ChocolateLotState
std::cout << "Waiting for lot" << std::endl;
// wait() blocks execution of the thread until one or more attached
// Conditions become true, or until a user-specified timeout expires.
DDSConditionSeq active_conditions_seq;
DDS_Duration_t wait_timeout = { 10, 0 };
retcode = waitset.wait(active_conditions_seq, wait_timeout);
// You get a timeout if no conditions were triggered before the timeout
if (retcode == DDS_RETCODE_TIMEOUT) {
std::cout << "Wait timed out after 10 seconds." << std::endl;
continue;
} else if (retcode != DDS_RETCODE_OK) {
std::cerr << "wait returned error: " << retcode << std::endl;
break;
}
// Get the status changes to check which status condition
// triggered the WaitSet to wake
DDS_StatusMask triggered_mask = lot_state_reader->get_status_changes();
// If the status is "Data Available"
if (triggered_mask & DDS_DATA_AVAILABLE_STATUS) {
process_lot(current_station, lot_state_reader, lot_state_writer);
}
if (triggered_mask & DDS_REQUESTED_INCOMPATIBLE_QOS_STATUS) {
on_requested_incompatible_qos(lot_state_reader);
}
}
// Cleanup
// -------
// Delete all entities (DataWriter, Topic, Publisher, DomainParticipant)
return shutdown(participant, "shutting down", EXIT_SUCCESS);
}
// Delete all entities
int shutdown(
DDSDomainParticipant *participant,
const char *shutdown_message,
int status)
{
DDS_ReturnCode_t retcode;
std::cout << shutdown_message << std::endl;
if (participant != NULL) {
// This includes everything created by this Participant, including
// DataWriters, Topics, Publishers. (and Subscribers and DataReaders)
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_example(arguments.domain_id, arguments.station_kind);
// Releases the memory used by the participant factory. Optional at
// application shutdown
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-getting-started
|
data/projects/rticonnextdds-getting-started/6_content_filters/c++98/chocolate_factory_print.h
|
#include <iostream>
#include "chocolate_factoryPlugin.h"
namespace chocolate_factory
{
inline void print_station_kind(StationKind station_kind)
{
switch(station_kind) {
case INVALID_CONTROLLER:
std::cout << "INVALID_CONTROLLER";
break;
case SUGAR_CONTROLLER:
std::cout << "SUGAR_CONTROLLER";
break;
case COCOA_BUTTER_CONTROLLER:
std::cout << "COCOA_BUTTER_CONTROLLER";
break;
case VANILLA_CONTROLLER:
std::cout << "VANILLA_CONTROLLER";
break;
case MILK_CONTROLLER:
std::cout << "MILK_CONTROLLER";
break;
case TEMPERING_CONTROLLER:
std::cout << "TEMPERING_CONTROLLER";
break;
}
}
inline void print_lot_status_kind(LotStatusKind lot_status_kind)
{
switch(lot_status_kind)
{
case WAITING:
std::cout << "WAITING";
break;
case PROCESSING:
std::cout << "PROCESSING";
break;
case COMPLETED:
std::cout << "COMPLETED";
break;
}
}
inline void print_chocolate_lot_data(const ChocolateLotState& sample)
{
std::cout << "[" << "lot_id: " << sample.lot_id << ", " << "station: ";
print_station_kind(sample.station);
std::cout << ", next_station: ";
print_station_kind(sample.next_station);
std::cout << ", lot_status: ";
print_lot_status_kind(sample.lot_status);
std::cout << "]" << std::endl;
}
}
|
h
|
rticonnextdds-getting-started
|
data/projects/rticonnextdds-getting-started/6_content_filters/c++98/monitoring_ctrl_application.cxx
|
/*
* (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.
*/
#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include "chocolate_factory.h"
#include "chocolate_factorySupport.h"
#include "ndds/ndds_cpp.h"
#include "application.h"
#include "chocolate_factory_print.h"
using namespace application;
static int shutdown(
DDSDomainParticipant *participant,
const char *shutdown_message,
int status);
// Structure to hold data for write lot sate thread
struct StartLotThreadData {
ChocolateLotStateDataWriter *writer;
unsigned int lots_to_process;
};
void publish_start_lot(StartLotThreadData *thread_data)
{
ChocolateLotState sample;
ChocolateLotStateTypeSupport::initialize_data(&sample);
unsigned int lots_to_process = thread_data->lots_to_process;
ChocolateLotStateDataWriter *writer = thread_data->writer;
for (unsigned int count = 0; !shutdown_requested && count < lots_to_process;
count++) {
// Set the values for a chocolate lot that is going to be sent to wait
// at the tempering station
sample.lot_id = count % 100;
sample.lot_status = WAITING;
sample.next_station = COCOA_BUTTER_CONTROLLER;
std::cout << std::endl
<< "Starting lot: " << std::endl
<< "[lot_id: " << sample.lot_id << " next_station: ";
chocolate_factory::print_station_kind(sample.next_station);
std::cout << "]" << std::endl;
// Send an update to station that there is a lot waiting for tempering
DDS_ReturnCode_t retcode = writer->write(sample, DDS_HANDLE_NIL);
if (retcode != DDS_RETCODE_OK) {
std::cerr << "write error " << retcode << std::endl;
}
// Start a new lot every 10 seconds
DDS_Duration_t send_period = { 30, 0 };
NDDSUtility::sleep(send_period);
}
ChocolateLotStateTypeSupport::finalize_data(&sample);
}
// Process data. Returns number of samples processed.
unsigned int monitor_lot_state(ChocolateLotStateDataReader *lot_state_reader)
{
ChocolateLotStateSeq data_seq;
DDS_SampleInfoSeq info_seq;
unsigned int samples_read = 0;
// Take available data from DataReader's queue
DDS_ReturnCode_t retcode = lot_state_reader->take(data_seq, info_seq);
if (retcode != DDS_RETCODE_OK && retcode != DDS_RETCODE_NO_DATA) {
std::cerr << "take error " << retcode << std::endl;
return 0;
}
// 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) {
std::cout << "Received lot update:" << std::endl;
chocolate_factory::print_chocolate_lot_data(data_seq[i]);
samples_read++;
} else {
// Detect that a lot is complete because the instance is disposed
if (info_seq[i].instance_state
== DDS_NOT_ALIVE_DISPOSED_INSTANCE_STATE) {
ChocolateLotState key_holder;
// Fills in only the key field values associated with the
// instance
lot_state_reader->get_key_value(
key_holder,
info_seq[i].instance_handle);
std::cout << "[lot_id: " << key_holder.lot_id
<< " is completed]" << std::endl;
}
}
}
// Data sequence was loaned from middleware for performance.
// Return loan when application is finished with data.
retcode = lot_state_reader->return_loan(data_seq, info_seq);
if (retcode != DDS_RETCODE_OK) {
std::cerr << "return_loan error " << retcode << std::endl;
}
return samples_read;
}
// Monitor the chocolate temperature
void monitor_temperature(TemperatureDataReader *temperature_reader)
{
TemperatureSeq data_seq;
DDS_SampleInfoSeq info_seq;
// Take available data from DataReader's queue
DDS_ReturnCode_t retcode = temperature_reader->take(data_seq, info_seq);
if (retcode != DDS_RETCODE_OK && retcode != DDS_RETCODE_NO_DATA) {
std::cerr << "take error " << retcode << std::endl;
return;
}
// Receive updates from tempering station about chocolate temperature.
// Only an error if below 30 or over 32 degrees Fahrenheit.
for (int i = 0; i < data_seq.length(); ++i) {
// Check if a sample is an instance lifecycle event
if (!info_seq[i].valid_data) {
std::cout << "Received instance state notification" << std::endl;
continue;
}
// Print data
std::cout << "Tempering temperature out of range: ";
TemperatureTypeSupport::print_data(&data_seq[i]);
}
// Data sequence was loaned from middleware for performance.
// Return loan when application is finished with data.
temperature_reader->return_loan(data_seq, info_seq);
}
int run_example(unsigned int domain_id, unsigned int sample_count)
{
// Connext DDS Setup
// -----------------
// Load QoS file
DDSDomainParticipantFactory *factory =
DDSDomainParticipantFactory::get_instance();
DDS_DomainParticipantFactoryQos factoryQos;
DDS_ReturnCode_t factory_retcode = factory->get_qos(factoryQos);
if (factory_retcode != DDS_RETCODE_OK) {
return shutdown(NULL, "get_qos error", EXIT_FAILURE);
}
const char *url_profiles[1] = { "qos_profiles.xml" };
factoryQos.profile.url_profile.from_array(url_profiles, 1);
factory->set_qos(factoryQos);
// A DomainParticipant allows an application to begin communicating in
// a DDS domain. Typically there is one DomainParticipant per application.
// DomainParticipant QoS is configured in USER_QOS_PROFILES.xml
// Load DomainParticipant QoS profile
DDSDomainParticipant *participant =
DDSTheParticipantFactory->create_participant_with_profile(
domain_id,
"ChocolateFactoryLibrary",
"TemperingApplication",
NULL /* listener */,
DDS_STATUS_MASK_NONE);
if (participant == NULL) {
shutdown(participant, "create_participant error", EXIT_FAILURE);
}
// Create Topics
// Register the datatype to use when creating the Topic
const char *lot_state_type_name =
ChocolateLotStateTypeSupport::get_type_name();
DDS_ReturnCode_t retcode = ChocolateLotStateTypeSupport::register_type(
participant,
lot_state_type_name);
if (retcode != DDS_RETCODE_OK) {
shutdown(participant, "register_type error", EXIT_FAILURE);
}
// A Topic has a name and a datatype. Create a Topic called
// "ChocolateLotState" with your registered data type
DDSTopic *lot_state_topic = participant->create_topic(
CHOCOLATE_LOT_STATE_TOPIC,
lot_state_type_name,
DDS_TOPIC_QOS_DEFAULT,
NULL /* listener */,
DDS_STATUS_MASK_NONE);
if (lot_state_topic == NULL) {
shutdown(participant, "create_topic error", EXIT_FAILURE);
}
// Register the datatype to use when creating the Topic
const char *temperature_type_name = TemperatureTypeSupport::get_type_name();
retcode = TemperatureTypeSupport::register_type(
participant,
temperature_type_name);
if (retcode != DDS_RETCODE_OK) {
shutdown(participant, "register_type error", EXIT_FAILURE);
}
// A Topic has a name and a datatype. Create a Topic called
// "ChocolateTemperature" with your registered data type
DDSTopic *temperature_topic = participant->create_topic(
CHOCOLATE_TEMPERATURE_TOPIC,
temperature_type_name,
DDS_TOPIC_QOS_DEFAULT,
NULL /* listener */,
DDS_STATUS_MASK_NONE);
if (temperature_topic == NULL) {
shutdown(participant, "create_topic error", EXIT_FAILURE);
}
DDS_StringSeq parameters(2);
const char *param_list[] = { "32", "30" };
parameters.from_array(param_list, 2);
DDSContentFilteredTopic *filtered_temperature_topic =
participant->create_contentfilteredtopic(
"FilteredTemperature",
temperature_topic,
"degrees > %0 or degrees < %1",
parameters);
// Create Publisher and DataWriter
// A Publisher allows an application to create one or more DataWriters
// Publisher QoS is configured in USER_QOS_PROFILES.xml
DDSPublisher *publisher = participant->create_publisher(
DDS_PUBLISHER_QOS_DEFAULT,
NULL /* listener */,
DDS_STATUS_MASK_NONE);
if (publisher == NULL) {
return shutdown(participant, "create_publisher error", EXIT_FAILURE);
}
// This DataWriter writes data on Topic "ChocolateLotState"
// DataWriter QoS is configured in USER_QOS_PROFILES.xml
DDSDataWriter *generic_lot_state_writer =
publisher->create_datawriter_with_profile(
lot_state_topic,
"ChocolateFactoryLibrary",
"ChocolateLotStateProfile",
NULL /* listener */,
DDS_STATUS_MASK_NONE);
if (generic_lot_state_writer == NULL) {
return shutdown(participant, "create_datawriter error", EXIT_FAILURE);
}
// A narrow is a cast from a generic DataWriter to one that is specific
// to your type. Use the type specific DataWriter to write()
ChocolateLotStateDataWriter *lot_state_writer =
ChocolateLotStateDataWriter::narrow(generic_lot_state_writer);
if (lot_state_writer == NULL) {
return shutdown(participant, "DataWriter narrow error", EXIT_FAILURE);
}
// Create Subscriber and DataReaders
// A Subscriber allows an application to create one or more DataReaders
// Subscriber QoS is configured in USER_QOS_PROFILES.xml
DDSSubscriber *subscriber = participant->create_subscriber(
DDS_SUBSCRIBER_QOS_DEFAULT,
NULL /* listener */,
DDS_STATUS_MASK_NONE);
if (subscriber == NULL) {
shutdown(participant, "create_subscriber error", EXIT_FAILURE);
}
// This DataReader reads data of type ChocolateLotState on Topic
// "ChocolateLotState". DataReader QoS is configured in
// USER_QOS_PROFILES.xml
DDSDataReader *lot_state_generic_reader =
subscriber->create_datareader_with_profile(
lot_state_topic,
"ChocolateFactoryLibrary",
"ChocolateLotStateProfile",
NULL,
DDS_STATUS_MASK_NONE);
if (lot_state_generic_reader == NULL) {
shutdown(participant, "create_datareader error", EXIT_FAILURE);
}
// Get status condition: Each entity has a Status Condition, which
// gets triggered when a status becomes true
DDSStatusCondition *lot_state_status_condition =
lot_state_generic_reader->get_statuscondition();
if (lot_state_status_condition == NULL) {
shutdown(participant, "get_statuscondition error", EXIT_FAILURE);
}
// Enable only the status we are interested in:
// DDS_DATA_AVAILABLE_STATUS
retcode = lot_state_status_condition->set_enabled_statuses(
DDS_DATA_AVAILABLE_STATUS);
if (retcode != DDS_RETCODE_OK) {
shutdown(participant, "set_enabled_statuses error", EXIT_FAILURE);
}
// This DataReader reads data of type Temperature on Topic
// "ChocolateTemperature". DataReader QoS is configured in
// USER_QOS_PROFILES.xml
DDSDataReader *temperature_generic_reader =
subscriber->create_datareader_with_profile(
filtered_temperature_topic,
"ChocolateFactoryLibrary",
"ChocolateTemperatureProfile",
NULL,
DDS_STATUS_MASK_NONE);
if (temperature_generic_reader == NULL) {
shutdown(participant, "create_datareader error", EXIT_FAILURE);
}
// Get status condition: Each entity has a Status Condition, which
// gets triggered when a status becomes true
DDSStatusCondition *temperature_status_condition =
temperature_generic_reader->get_statuscondition();
if (temperature_status_condition == NULL) {
shutdown(participant, "get_statuscondition error", EXIT_FAILURE);
}
// Enable only the status we are interested in:
// DDS_DATA_AVAILABLE_STATUS
retcode = temperature_status_condition->set_enabled_statuses(
DDS_DATA_AVAILABLE_STATUS);
if (retcode != DDS_RETCODE_OK) {
shutdown(participant, "set_enabled_statuses error", EXIT_FAILURE);
}
// Create the WaitSet and attach the Status Condition to it. The WaitSet
// will be woken when the condition is triggered.
DDSWaitSet waitset;
retcode = waitset.attach_condition(lot_state_status_condition);
if (retcode != DDS_RETCODE_OK) {
shutdown(participant, "attach_condition error", EXIT_FAILURE);
}
// Temperature condition
retcode = waitset.attach_condition(temperature_status_condition);
if (retcode != DDS_RETCODE_OK) {
shutdown(participant, "attach_condition error", EXIT_FAILURE);
}
// A narrow is a cast from a generic DataReader to one that is specific
// to your type. Use the type specific DataReader to read data
ChocolateLotStateDataReader *lot_state_reader =
ChocolateLotStateDataReader::narrow(lot_state_generic_reader);
if (lot_state_reader == NULL) {
shutdown(participant, "DataReader narrow error", EXIT_FAILURE);
}
TemperatureDataReader *temperature_reader =
TemperatureDataReader::narrow(temperature_generic_reader);
if (temperature_reader == NULL) {
shutdown(participant, "DataReader narrow error", EXIT_FAILURE);
}
// Create a thread to periodically start new chocolate lots
StartLotThreadData thread_data;
thread_data.writer = lot_state_writer;
thread_data.lots_to_process = sample_count;
OSThread thread((ThreadFunction) publish_start_lot, (void *) &thread_data);
thread.run();
// Main loop. Wait for data to arrive, and process when it arrives.
// ----------------------------------------------------------------
unsigned int samples_read = 0;
while (!shutdown_requested && samples_read < sample_count) {
DDSConditionSeq active_conditions_seq;
// wait() blocks execution of the thread until one or more attached
// Conditions become true, or until a user-specified timeout expires.
DDS_Duration_t wait_timeout = { 15, 0 };
retcode = waitset.wait(active_conditions_seq, wait_timeout);
// You get a timeout if no conditions were triggered before the timeout
if (retcode == DDS_RETCODE_TIMEOUT) {
std::cout << "Wait timed out after 10 seconds." << std::endl;
continue;
} else if (retcode != DDS_RETCODE_OK) {
std::cerr << "wait returned error: " << retcode << std::endl;
break;
}
// Get the status changes to check which status condition
// triggered the WaitSet to wake
DDS_StatusMask triggeredmask = lot_state_reader->get_status_changes();
// If the ChocolateLotState DataReader received DATA_AVAILABLE event
// notification
if (triggeredmask & DDS_DATA_AVAILABLE_STATUS) {
samples_read += monitor_lot_state(lot_state_reader);
}
// Check if the temperature DataReader received DATA_AVAILABLE event
// notification
triggeredmask = temperature_reader->get_status_changes();
if (triggeredmask & DDS_DATA_AVAILABLE_STATUS) {
monitor_temperature(temperature_reader);
}
}
// Cleanup
// -------
thread.join();
// Delete all entities (DataReader, Topic, Subscriber, DomainParticipant)
return shutdown(participant, "shutting down", 0);
}
// Delete all entities
int shutdown(
DDSDomainParticipant *participant,
const char *shutdown_message,
int status)
{
DDS_ReturnCode_t retcode;
std::cout << shutdown_message << std::endl;
if (participant != NULL) {
// This includes everything created by this Participant, including
// DataWriters, Topics, Publishers. (and Subscribers and DataReaders)
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_example(arguments.domain_id, arguments.sample_count);
// Releases the memory used by the participant factory. Optional at
// application shutdown
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-getting-started
|
data/projects/rticonnextdds-getting-started/6_content_filters/c++98/tempering_application.cxx
|
/*
* (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.
*/
#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include "chocolate_factory.h"
#include "chocolate_factorySupport.h"
#include "ndds/ndds_cpp.h"
#include "application.h"
using namespace application;
// Tempering application:
// 1) Publishes the temperature
// 2) Subscribes to the lot state
// 3) After "processing" the lot, publishes the lot state
static int shutdown(
DDSDomainParticipant *participant,
const char *shutdown_message,
int status);
// Structure to hold data for write thread
struct TemperatureWriteData {
TemperatureDataWriter *writer;
const char *sensor_id;
};
void publish_temperature(const TemperatureWriteData *write_data)
{
TemperatureDataWriter *writer = write_data->writer;
// Create temperature sample for writing
Temperature temperature;
TemperatureTypeSupport::initialize_data(&temperature);
int counter = 0;
while (!shutdown_requested) {
counter++;
// Occasionally make the temperature high
if (counter % 400 == 0) {
std::cout << "Temperature too high" << std::endl;
temperature.degrees = 33;
} else {
snprintf(temperature.sensor_id, 255, "%s", write_data->sensor_id);
temperature.degrees = rand() % 3 + 30; // Random num between 30 and 32
}
DDS_ReturnCode_t retcode = writer->write(temperature, DDS_HANDLE_NIL);
if (retcode != DDS_RETCODE_OK) {
std::cerr << "write error " << retcode << std::endl;
}
// Update temperature every 100 ms
DDS_Duration_t send_period = { 0, 100000000 };
NDDSUtility::sleep(send_period);
}
TemperatureTypeSupport::finalize_data(&temperature);
}
void process_lot(
ChocolateLotStateDataReader *lot_state_reader,
ChocolateLotStateDataWriter *lot_state_writer)
{
// Take all samples. Samples are loaned to application, loan is
// returned when LoanedSamples destructor called.
ChocolateLotStateSeq data_seq;
DDS_SampleInfoSeq info_seq;
// Take available data from DataReader's queue
DDS_ReturnCode_t retcode = lot_state_reader->take(data_seq, info_seq);
if (retcode != DDS_RETCODE_OK && retcode != DDS_RETCODE_NO_DATA) {
std::cerr << "take error " << retcode << std::endl;
return;
}
// Process lots waiting for tempering
for (int i = 0; i < data_seq.length(); ++i) {
// Check if a sample is an instance lifecycle event
if (info_seq[i].valid_data) {
// Exercise #1.3: Remove the check that the Tempering Application
// is the next_station. This will now be filtered automatically.
if (data_seq[i].next_station == TEMPERING_CONTROLLER) {
std::cout << "Processing lot #" << data_seq[i].lot_id
<< std::endl;
// Send an update that the tempering station is processing lot
ChocolateLotState updated_state(data_seq[i]);
updated_state.lot_status = PROCESSING;
updated_state.next_station = INVALID_CONTROLLER;
updated_state.station = TEMPERING_CONTROLLER;
DDS_ReturnCode_t retcode =
lot_state_writer->write(updated_state, DDS_HANDLE_NIL);
if (retcode != DDS_RETCODE_OK) {
std::cerr << "write error " << retcode << std::endl;
}
// "Processing" the lot.
DDS_Duration_t processing_time = { 5, 0 };
NDDSUtility::sleep(processing_time);
// Since this is the last step in processing, notify the
// monitoring application that the lot is complete using a
// dispose
retcode = lot_state_writer->dispose(
updated_state,
DDS_HANDLE_NIL);
std::cout << "Lot completed" << std::endl;
}
} else {
// Received instance state notification
continue;
}
}
// Data sequence was loaned from middleware for performance.
// Return loan when application is finished with data.
retcode = lot_state_reader->return_loan(data_seq, info_seq);
if (retcode != DDS_RETCODE_OK) {
std::cerr << "return_loan error " << retcode << std::endl;
}
}
void on_requested_incompatible_qos(DDSDataReader *reader)
{
DDS_RequestedIncompatibleQosStatus status;
reader->get_requested_incompatible_qos_status(status);
std::cout << "Discovered DataWriter with incompatible policy: ";
if (status.last_policy_id == DDS_RELIABILITY_QOS_POLICY_ID) {
std::cout << "Reliability" << std::endl;
}
if (status.last_policy_id == DDS_DURABILITY_QOS_POLICY_ID) {
std::cout << "Durability" << std::endl;
}
}
int run_example(
unsigned int domain_id,
unsigned int sample_count,
const char *sensor_id)
{
// Load XML QoS from a specific file
DDSDomainParticipantFactory *factory =
DDSDomainParticipantFactory::get_instance();
DDS_DomainParticipantFactoryQos factoryQos;
DDS_ReturnCode_t retcode = factory->get_qos(factoryQos);
if (retcode != DDS_RETCODE_OK) {
return shutdown(NULL, "get_qos error", EXIT_FAILURE);
}
const char *url_profiles[1] = { "qos_profiles.xml" };
factoryQos.profile.url_profile.from_array(url_profiles, 1);
factory->set_qos(factoryQos);
// Connext DDS setup
// -----------------
// A DomainParticipant allows an application to begin communicating in
// a DDS domain. Typically there is one DomainParticipant per application.
// Uses TemperingApplication QoS profile to set participant name.
DDSDomainParticipant *participant =
DDSTheParticipantFactory->create_participant_with_profile(
domain_id,
"ChocolateFactoryLibrary",
"TemperingApplication",
NULL /* listener */,
DDS_STATUS_MASK_NONE);
if (participant == NULL) {
return shutdown(participant, "create_participant error", EXIT_FAILURE);
}
// Create Topics
// Register the datatype to use when creating the Topic
const char *temperature_type_name = TemperatureTypeSupport::get_type_name();
retcode = TemperatureTypeSupport::register_type(
participant,
temperature_type_name);
if (retcode != DDS_RETCODE_OK) {
return shutdown(participant, "register_type error", EXIT_FAILURE);
}
const char *lot_state_type_name =
ChocolateLotStateTypeSupport::get_type_name();
retcode = ChocolateLotStateTypeSupport::register_type(
participant,
lot_state_type_name);
if (retcode != DDS_RETCODE_OK) {
return shutdown(participant, "register_type error", EXIT_FAILURE);
}
// A Topic has a name and a datatype. Create a Topic called
// "ChocolateTemperature" with your registered temperature data type
DDSTopic *temperature_topic = participant->create_topic(
CHOCOLATE_TEMPERATURE_TOPIC,
temperature_type_name,
DDS_TOPIC_QOS_DEFAULT,
NULL /* listener */,
DDS_STATUS_MASK_NONE);
if (temperature_topic == NULL) {
return shutdown(participant, "create_topic error", EXIT_FAILURE);
}
// A Topic has a name and a datatype. Create a Topic called
// "ChocolateLotState" with your registered ChocolateLotState data type
DDSTopic *lot_state_topic = participant->create_topic(
CHOCOLATE_LOT_STATE_TOPIC,
lot_state_type_name,
DDS_TOPIC_QOS_DEFAULT,
NULL /* listener */,
DDS_STATUS_MASK_NONE);
if (lot_state_topic == NULL) {
return shutdown(participant, "create_topic error", EXIT_FAILURE);
}
// Exercise #1.1: Create a Content-Filtered Topic that filters out
// chocolate lot state unless the next_station = TEMPERING_CONTROLLER
// Create Publisher and DataWriters
// A Publisher allows an application to create one or more DataWriters
// Publisher QoS is configured with default QoS
DDSPublisher *publisher = participant->create_publisher(
DDS_PUBLISHER_QOS_DEFAULT,
NULL /* listener */,
DDS_STATUS_MASK_NONE);
if (publisher == NULL) {
return shutdown(participant, "create_publisher error", EXIT_FAILURE);
}
// This DataWriter writes data on Topic "ChocolateTemperature" DataWriter
// QoS is configured using ChocolateTemperatureProfile QoS profile
DDSDataWriter *generic_temp_writer =
publisher->create_datawriter_with_profile(
temperature_topic,
"ChocolateFactoryLibrary",
"ChocolateTemperatureProfile",
NULL /* listener */,
DDS_STATUS_MASK_NONE);
if (generic_temp_writer == NULL) {
return shutdown(participant, "create_datawriter error", EXIT_FAILURE);
}
// This DataWriter writes data on Topic "ChocolateLotState". DataWriter
// QoS is configured using ChocolateLotStateProfile QoS profile
DDSDataWriter *generic_lot_state_writer =
publisher->create_datawriter_with_profile(
lot_state_topic,
"ChocolateFactoryLibrary",
"ChocolateLotStateProfile",
NULL /* listener */,
DDS_STATUS_MASK_NONE);
if (generic_lot_state_writer == NULL) {
return shutdown(participant, "create_datawriter error", EXIT_FAILURE);
}
// A narrow is a cast from a generic DataWriter to one that is specific
// to your type. Use the type specific DataWriter to write()
TemperatureDataWriter *temperature_writer =
TemperatureDataWriter::narrow(generic_temp_writer);
if (temperature_writer == NULL) {
return shutdown(participant, "DataWriter narrow error", EXIT_FAILURE);
}
ChocolateLotStateDataWriter *lot_state_writer =
ChocolateLotStateDataWriter::narrow(generic_lot_state_writer);
if (lot_state_writer == NULL) {
return shutdown(participant, "DataWriter narrow error", EXIT_FAILURE);
}
// Create Subscriber and DataReader
// A Subscriber allows an application to create one or more DataReaders
// Subscriber QoS is configured with default QoS
DDSSubscriber *subscriber = participant->create_subscriber(
DDS_SUBSCRIBER_QOS_DEFAULT,
NULL /* listener */,
DDS_STATUS_MASK_NONE);
if (subscriber == NULL) {
shutdown(participant, "create_subscriber error", EXIT_FAILURE);
}
// This DataReader reads data of type ChocolateLotStateProfile on Topic
// "ChocolateLotStateProfile" using ChocolateLotStateProfile QoS profile
// Exercise #1.2: Change the DataReader's Topic to use a
// Content-Filtered Topic
DDSDataReader *generic_lot_state_reader =
subscriber->create_datareader_with_profile(
lot_state_topic,
"ChocolateFactoryLibrary",
"ChocolateLotStateProfile",
NULL,
DDS_STATUS_MASK_NONE);
if (generic_lot_state_reader == NULL) {
shutdown(participant, "create_datareader error", EXIT_FAILURE);
}
// Get status condition: Each entity has a Status Condition, which
// gets triggered when a status becomes true
DDSStatusCondition *status_condition =
generic_lot_state_reader->get_statuscondition();
if (status_condition == NULL) {
shutdown(participant, "get_statuscondition error", EXIT_FAILURE);
}
// Enable only the statuses we are interested in:
// DDS_DATA_AVAILABLE_STATUS, DDS_REQUESTED_INCOMPATIBLE_QOS_STATUS
retcode = status_condition->set_enabled_statuses(
DDS_DATA_AVAILABLE_STATUS | DDS_REQUESTED_INCOMPATIBLE_QOS_STATUS);
if (retcode != DDS_RETCODE_OK) {
shutdown(participant, "set_enabled_statuses error", EXIT_FAILURE);
}
// Create the WaitSet and attach the Status Condition to it. The WaitSet
// will be woken when the condition is triggered.
DDSWaitSet waitset;
retcode = waitset.attach_condition(status_condition);
if (retcode != DDS_RETCODE_OK) {
shutdown(participant, "attach_condition error", EXIT_FAILURE);
}
// A narrow is a cast from a generic DataReader to one that is specific
// to your type. Use the type specific DataReader to read data
ChocolateLotStateDataReader *lot_state_reader =
ChocolateLotStateDataReader::narrow(generic_lot_state_reader);
if (lot_state_reader == NULL) {
shutdown(participant, "DataReader narrow error", EXIT_FAILURE);
}
// Create thread to periodically write temperature data
TemperatureWriteData write_data;
write_data.writer = temperature_writer;
write_data.sensor_id = sensor_id;
OSThread thread((ThreadFunction) publish_temperature, (void *) &write_data);
std::cout << "ChocolateTemperature Sensor with ID: " << write_data.sensor_id
<< " starting" << std::endl;
thread.run();
// Main loop, wait for lots
// ------------------------
while (!shutdown_requested) {
// Wait for ChocolateLotState
std::cout << "Waiting for lot" << std::endl;
// wait() blocks execution of the thread until one or more attached
// Conditions become true, or until a user-specified timeout expires.
DDSConditionSeq active_conditions_seq;
DDS_Duration_t wait_timeout = { 10, 0 };
retcode = waitset.wait(active_conditions_seq, wait_timeout);
// You get a timeout if no conditions were triggered before the timeout
if (retcode == DDS_RETCODE_TIMEOUT) {
std::cout << "Wait timed out after 10 seconds." << std::endl;
continue;
} else if (retcode != DDS_RETCODE_OK) {
std::cerr << "wait returned error: " << retcode << std::endl;
break;
}
// Get the status changes to check which status condition
// triggered the WaitSet to wake
DDS_StatusMask triggered_mask = lot_state_reader->get_status_changes();
// If the status is "Data Available"
if (triggered_mask & DDS_DATA_AVAILABLE_STATUS) {
process_lot(lot_state_reader, lot_state_writer);
}
if (triggered_mask & DDS_REQUESTED_INCOMPATIBLE_QOS_STATUS) {
on_requested_incompatible_qos(lot_state_reader);
}
}
// Cleanup
// -------
thread.join();
// Delete all entities (DataWriter, Topic, Publisher, DomainParticipant)
return shutdown(participant, "shutting down", EXIT_SUCCESS);
}
// Delete all entities
int shutdown(
DDSDomainParticipant *participant,
const char *shutdown_message,
int status)
{
DDS_ReturnCode_t retcode;
std::cout << shutdown_message << std::endl;
if (participant != NULL) {
// This includes everything created by this Participant, including
// DataWriters, Topics, Publishers. (and Subscribers and DataReaders)
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_example(
arguments.domain_id,
arguments.sample_count,
arguments.sensor_id);
// Releases the memory used by the participant factory. Optional at
// application shutdown
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-getting-started
|
data/projects/rticonnextdds-getting-started/6_content_filters/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 <ctime>
#include <limits>
#ifdef RTI_WIN32
/* strtok, fopen warnings */
#pragma warning( disable : 4996 )
#endif
#ifdef RTI_WIN32
#define DllExport __declspec( dllexport )
#include <Winsock2.h>
#include <process.h>
#else
#define DllExport
#include <sys/select.h>
#include <semaphore.h>
#include <pthread.h>
#endif
#include "ndds/ndds_cpp.h"
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);
}
// A function that takes a void pointer, and is passed to the thread creation
// function.
typedef void* (*ThreadFunction)(void *);
class OSThread
{
public:
OSThread(ThreadFunction function, void *function_param):
function(function),
function_param(function_param)
{
}
// Run the thread
void run()
{
#ifdef RTI_WIN32
thread = (HANDLE) _beginthread(
(void(__cdecl*)(void*))function,
0, (void*)function_param);
#else
pthread_attr_t thread_attr;
pthread_attr_init(&thread_attr);
pthread_attr_setdetachstate(&thread_attr, PTHREAD_CREATE_JOINABLE);
int error = pthread_create(
&thread,
&thread_attr,
function,
(void *)function_param);
pthread_attr_destroy(&thread_attr);
#endif
}
// Join the thread
void join()
{
#ifdef RTI_WIN32
WaitForSingleObject(thread, INFINITE);
#else
void *ret_val;
int error = pthread_join(thread, &ret_val);
#endif
}
private:
// OS-specific thread definition
#ifdef RTI_WIN32
HANDLE thread;
#else
pthread_t thread;
#endif
// Function called by OS-specific thread
ThreadFunction function;
// Parameter to the function
void *function_param;
};
enum ParseReturn { PARSE_RETURN_OK, PARSE_RETURN_FAILURE, PARSE_RETURN_EXIT };
struct ApplicationArguments {
ParseReturn parse_result;
unsigned int domain_id;
unsigned int sample_count;
char sensor_id[256];
char station_kind[256];
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 = (std::numeric_limits<unsigned int>::max)();
arguments.verbosity = NDDS_CONFIG_LOG_VERBOSITY_ERROR;
arguments.parse_result = PARSE_RETURN_OK;
// Initialize with an integer value
srand((unsigned int)time(NULL));
snprintf(arguments.sensor_id, 255, "%d", rand() % 10);
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], "-i") == 0
|| strcmp(argv[arg_processing], "--sensor-id") == 0)) {
snprintf(arguments.sensor_id, 255, "%s", argv[arg_processing + 1]);
arg_processing += 2;
} else if ((argc > arg_processing + 1)
&& (strcmp(argv[arg_processing], "-k") == 0
|| strcmp(argv[arg_processing], "--station-kind") == 0)) {
snprintf(arguments.station_kind, 255, "%s", 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"
" -i, --sensor-id <string> Unique ID of temperature sensor.\n"\
" -k, --station-kind <string> The type of ingredient station to start.\n"\
" Used only by ingredient application.\n"\
" Values:\n"\
" COCOA_BUTTER_CONTROLLER,\n"\
" SUGAR_CONTROLLER,\n"\
" MILK_CONTROLLER,\n"\
" VANILLA_CONTROLLER\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-getting-started
|
data/projects/rticonnextdds-getting-started/6_content_filters/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 <string>
#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;
std::string sensor_id;
rti::config::Verbosity verbosity;
std::string station_kind;
};
// 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)();
srand((unsigned int)time(NULL));
std::string sensor_id = std::to_string(rand() % 50);
std::string station_kind("COCOA_BUTTER_CONTROLLER");
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 ((argc > arg_processing + 1)
&& (strcmp(argv[arg_processing], "-i") == 0
|| strcmp(argv[arg_processing], "--sensor-id") == 0)) {
sensor_id = argv[arg_processing + 1];
arg_processing += 2;
} else if ((argc > arg_processing + 1)
&& (strcmp(argv[arg_processing], "-k") == 0
|| strcmp(argv[arg_processing], "--station-kind") == 0)) {
station_kind = 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"
" cleanly shutting down. \n"
" -i, --sensor-id <string> Unique ID of temperature sensor.\n"\
" Used only by tempering application.\n"\
" -k, --station-kind <string> The type of ingredient station to start.\n"\
" Used only by ingredient application.\n"\
" Values:\n"\
" COCOA_BUTTER_CONTROLLER,\n"\
" SUGAR_CONTROLLER,\n"\
" MILK_CONTROLLER,\n"\
" VANILLA_CONTROLLER\n"\
" -v, --verbosity <int> How much debugging output to show.\n"\
" Range: 0-5 \n"
" Default: 0"
<< std::endl;
}
return { parse_result, domain_id, sample_count, sensor_id, verbosity, station_kind };
}
} // namespace application
#endif // APPLICATION_HPP
|
hpp
|
rticonnextdds-getting-started
|
data/projects/rticonnextdds-getting-started/6_content_filters/c++11/ingredient_application.cxx
|
/*
* (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.
*/
#include <iostream>
#include <thread>
#include <dds/pub/ddspub.hpp>
#include <dds/sub/ddssub.hpp>
#include <rti/util/util.hpp> // for sleep()
#include <rti/config/Logger.hpp> // for logging
// Or simply include <dds/dds.hpp>
#include "chocolate_factory.hpp"
#include "application.hpp" // Argument parsing
using namespace application;
// Ingredient application:
// 1) Subscribes to the lot state
// 2) "Processes" the lot. (In this example, that means sleep for a time)
// 3) After "processing" the lot, publishes an updated lot state
void process_lot(
const StationKind station_kind,
const std::map<StationKind, StationKind>& next_station,
dds::sub::DataReader<ChocolateLotState>& lot_state_reader,
dds::pub::DataWriter<ChocolateLotState>& lot_state_writer)
{
// Take all samples. Samples are loaned to application, loan is
// returned when LoanedSamples destructor called.
dds::sub::LoanedSamples<ChocolateLotState> samples =
lot_state_reader.take();
// Process lots waiting for ingredients
for (const auto& sample : samples) {
if (!sample.info().valid() || shutdown_requested) {
break;
}
// No need to check that this is the next station: content filter
// ensures that the reader only receives lots with
// next_station == this station
std::cout << "Processing lot #" << sample.data().lot_id() << std::endl;
// Send an update that this station is processing lot
ChocolateLotState updated_state(sample.data());
updated_state.lot_status(LotStatusKind::PROCESSING);
updated_state.next_station(StationKind::INVALID_CONTROLLER);
updated_state.station(station_kind);
lot_state_writer.write(updated_state);
// "Processing" the lot.
rti::util::sleep(dds::core::Duration(5));
// Send an update that this station is done processing lot
updated_state.lot_status(LotStatusKind::COMPLETED);
updated_state.next_station(next_station.at(station_kind));
updated_state.station(station_kind);
lot_state_writer.write(updated_state);
}
} // The LoanedSamples destructor returns the loan
StationKind string_to_stationkind(const std::string& station_kind)
{
if (station_kind == "SUGAR_CONTROLLER") {
return StationKind::SUGAR_CONTROLLER;
} else if (station_kind == "COCOA_BUTTER_CONTROLLER") {
return StationKind::COCOA_BUTTER_CONTROLLER;
} else if (station_kind == "MILK_CONTROLLER") {
return StationKind::MILK_CONTROLLER;
} else if (station_kind == "VANILLA_CONTROLLER") {
return StationKind::VANILLA_CONTROLLER;
}
return StationKind::INVALID_CONTROLLER;
}
void run_example(unsigned int domain_id, const std::string& station_kind)
{
StationKind current_station = string_to_stationkind(station_kind);
std::cout << station_kind << " station starting" << std::endl;
// The stations are in a fixed order, this defines which station is next
const std::map<StationKind, StationKind> next_station {
{ StationKind::COCOA_BUTTER_CONTROLLER, StationKind::SUGAR_CONTROLLER },
{ StationKind::SUGAR_CONTROLLER, StationKind::MILK_CONTROLLER },
{ StationKind::MILK_CONTROLLER, StationKind::VANILLA_CONTROLLER },
{ StationKind::VANILLA_CONTROLLER, StationKind::TEMPERING_CONTROLLER }
};
// Loads the QoS from the qos_profiles.xml file.
dds::core::QosProvider qos_provider("./qos_profiles.xml");
// A DomainParticipant allows an application to begin communicating in
// a DDS domain. Typically there is one DomainParticipant per application.
// Uses IngredientApplication QoS profile to set participant name.
dds::domain::DomainParticipant participant(
domain_id,
qos_provider.participant_qos(
"ChocolateFactoryLibrary::IngredientApplication"));
// A Topic has a name and a datatype. Create Topics.
// Topic names are constants defined in the IDL file.
dds::topic::Topic<ChocolateLotState> lot_state_topic(
participant,
CHOCOLATE_LOT_STATE_TOPIC);
std::string filter_value = "'" + station_kind + "'";
dds::topic::ContentFilteredTopic<ChocolateLotState>
filtered_lot_state_topic(
lot_state_topic,
"FilteredLot",
dds::topic::Filter("next_station = %0", { filter_value }));
// A Publisher allows an application to create one or more DataWriters
// Create Publisher with default QoS
dds::pub::Publisher publisher(participant);
// Create DataWriter of Topic "ChocolateLotState"
// using ChocolateLotStateProfile QoS profile for State Data
dds::pub::DataWriter<ChocolateLotState> lot_state_writer(
publisher,
lot_state_topic,
qos_provider.datawriter_qos(
"ChocolateFactoryLibrary::ChocolateLotStateProfile"));
// A Subscriber allows an application to create one or more DataReaders
dds::sub::Subscriber subscriber(participant);
// Create DataReader of Topic "ChocolateLotState".
// using ChocolateLotStateProfile QoS profile for State Data
dds::sub::DataReader<ChocolateLotState> lot_state_reader(
subscriber,
filtered_lot_state_topic,
qos_provider.datareader_qos(
"ChocolateFactoryLibrary::ChocolateLotStateProfile"));
// Obtain the DataReader's Status Condition
dds::core::cond::StatusCondition reader_status_condition(lot_state_reader);
// Contains statuses that entities can be notified about
using dds::core::status::StatusMask;
// Enable the 'data available' and 'requested incompatible qos' statuses
reader_status_condition.enabled_statuses(StatusMask::data_available());
// Associate a handler with the status condition. This will run when the
// condition is triggered, in the context of the dispatch call (see below)
reader_status_condition.extensions().handler([&]() {
if ((lot_state_reader.status_changes() & StatusMask::data_available())
!= StatusMask::none()) {
process_lot(
current_station,
next_station,
lot_state_reader,
lot_state_writer);
}
});
// Create a WaitSet and attach the StatusCondition
dds::core::cond::WaitSet waitset;
waitset += reader_status_condition;
while (!shutdown_requested) {
// Wait for ChocolateLotState
std::cout << "Waiting for lot" << std::endl;
waitset.dispatch(dds::core::Duration(10)); // Wait up to 10s for update
}
}
int main(int argc, char *argv[])
{
// 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_example(arguments.domain_id, arguments.station_kind);
} catch (const std::exception& ex) {
// This will catch DDS exceptions
std::cerr << "Exception in run_example(): " << ex.what() << std::endl;
return EXIT_FAILURE;
}
// Releases the memory used by the participant factory. Optional at
// application shutdown
dds::domain::DomainParticipant::finalize_participant_factory();
return EXIT_SUCCESS;
}
|
cxx
|
rticonnextdds-getting-started
|
data/projects/rticonnextdds-getting-started/6_content_filters/c++11/monitoring_ctrl_application.cxx
|
/*
* (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.
*/
#include <iostream>
#include <thread>
#include <dds/pub/ddspub.hpp>
#include <dds/sub/ddssub.hpp>
#include <rti/util/util.hpp> // for sleep()
#include <rti/config/Logger.hpp> // for logging
// Or simply include <dds/dds.hpp>
#include "chocolate_factory.hpp"
#include "application.hpp" // Argument parsing
using namespace application;
void publish_start_lot(
dds::pub::DataWriter<ChocolateLotState> lot_state_writer,
unsigned int lots_to_process)
{
ChocolateLotState sample;
for (unsigned int count = 0; !shutdown_requested && count < lots_to_process;
count++) {
// Set the values for a chocolate lot that is going to be sent to wait
// at the tempering station
sample.lot_id(count % 100);
sample.lot_status(LotStatusKind::WAITING);
sample.next_station(StationKind::COCOA_BUTTER_CONTROLLER);
std::cout << std::endl << "Starting lot: " << std::endl;
std::cout << "[lot_id: " << sample.lot_id()
<< " next_station: " << sample.next_station() << "]"
<< std::endl;
// Send an update to station that there is a lot waiting for tempering
lot_state_writer.write(sample);
rti::util::sleep(dds::core::Duration(30));
}
}
unsigned int monitor_lot_state(dds::sub::DataReader<ChocolateLotState>& reader)
{
// Take all samples. Samples are loaned to application, loan is
// returned when LoanedSamples destructor called.
unsigned int samples_read = 0;
dds::sub::LoanedSamples<ChocolateLotState> samples = reader.take();
// Receive updates from stations about the state of current lots
for (const auto& sample : samples) {
std::cout << "Received Lot Update:" << std::endl;
if (sample.info().valid()) {
std::cout << sample.data() << std::endl;
samples_read++;
} else {
// Detect that a lot is complete by checking for
// the disposed state.
if (sample.info().state().instance_state()
== dds::sub::status::InstanceState::not_alive_disposed()) {
ChocolateLotState key_holder;
// Fills in only the key field values associated with the
// instance
reader.key_value(key_holder, sample.info().instance_handle());
std::cout << "[lot_id: " << key_holder.lot_id()
<< " is completed]" << std::endl;
}
}
}
return samples_read;
}
// Add monitor_temperature function
void monitor_temperature(dds::sub::DataReader<Temperature>& reader)
{
// Take all samples. Samples are loaned to application, loan is
// returned when LoanedSamples destructor called.
dds::sub::LoanedSamples<Temperature> samples = reader.take();
// Receive updates from tempering station about chocolate temperature.
// Only an error if below 30 or over 32 degrees Fahrenheit.
for (const auto& sample : samples) {
if (sample.info().valid()) {
std::cout << "Tempering temperature out of range: " << sample.data()
<< std::endl;
}
}
}
void run_example(unsigned int domain_id, unsigned int lots_to_process)
{
// Loads the QoS from the qos_profiles.xml file.
dds::core::QosProvider qos_provider("./qos_profiles.xml");
// A DomainParticipant allows an application to begin communicating in
// a DDS domain. Typically there is one DomainParticipant per application.
// Load DomainParticipant QoS profile
dds::domain::DomainParticipant participant(
domain_id,
qos_provider.participant_qos(
"ChocolateFactoryLibrary::MonitoringControlApplication"));
// A Topic has a name and a datatype. Create a Topic with type
// ChocolateLotState. Topic name is a constant defined in the IDL file.
dds::topic::Topic<ChocolateLotState> topic(
participant,
CHOCOLATE_LOT_STATE_TOPIC);
// Add a Topic for Temperature to this application
dds::topic::Topic<Temperature> temperature_topic(
participant,
CHOCOLATE_TEMPERATURE_TOPIC);
dds::topic::ContentFilteredTopic<Temperature>
filtered_temperature_topic(
temperature_topic,
"FilteredTemperature",
dds::topic::Filter(
"degrees > %0 or degrees < %1",
{ "32", "30" }));
// A Publisher allows an application to create one or more DataWriters
// Publisher QoS is configured in USER_QOS_PROFILES.xml
dds::pub::Publisher publisher(participant);
// This DataWriter writes data on Topic "ChocolateLotState"
dds::pub::DataWriter<ChocolateLotState> lot_state_writer(
publisher,
topic,
qos_provider.datawriter_qos(
"ChocolateFactoryLibrary::ChocolateLotStateProfile"));
// A Subscriber allows an application to create one or more DataReaders
// Subscriber QoS is configured in USER_QOS_PROFILES.xml
dds::sub::Subscriber subscriber(participant);
// Create DataReader of Topic "ChocolateLotState".
dds::sub::DataReader<ChocolateLotState> lot_state_reader(
subscriber,
topic,
qos_provider.datareader_qos(
"ChocolateFactoryLibrary::ChocolateLotStateProfile"));
// Add a DataReader for Temperature to this application
dds::sub::DataReader<Temperature> temperature_reader(
subscriber,
filtered_temperature_topic,
qos_provider.datareader_qos(
"ChocolateFactoryLibrary::ChocolateTemperatureProfile"));
// Obtain the DataReader's Status Condition
dds::core::cond::StatusCondition temperature_status_condition(
temperature_reader);
// Enable the 'data available' status.
temperature_status_condition.enabled_statuses(
dds::core::status::StatusMask::data_available());
// Associate a handler with the status condition. This will run when the
// condition is triggered, in the context of the dispatch call (see below)
temperature_status_condition.extensions().handler(
[&temperature_reader, &temperature_status_condition]() {
monitor_temperature(temperature_reader);
});
// Obtain the DataReader's Status Condition
dds::core::cond::StatusCondition lot_state_status_condition(
lot_state_reader);
// Enable the 'data available' status.
lot_state_status_condition.enabled_statuses(
dds::core::status::StatusMask::data_available());
// Associate a handler with the status condition. This will run when the
// condition is triggered, in the context of the dispatch call (see below)
unsigned int lots_processed = 0;
lot_state_status_condition.extensions().handler(
[&lot_state_reader, &lots_processed]() {
lots_processed += monitor_lot_state(lot_state_reader);
});
// Create a WaitSet and attach the StatusCondition
dds::core::cond::WaitSet waitset;
waitset += lot_state_status_condition;
// Add the new DataReader's StatusCondition to the Waitset
waitset += temperature_status_condition;
// Create a thread to periodically start new chocolate lots
std::thread start_lot_thread(
publish_start_lot,
lot_state_writer,
lots_to_process);
while (!shutdown_requested && lots_processed < lots_to_process) {
// Dispatch will call the handlers associated to the WaitSet conditions
// when they activate
waitset.dispatch(dds::core::Duration(10)); // Wait up to 10s each time
}
start_lot_thread.join();
}
int main(int argc, char *argv[])
{
// 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_example(arguments.domain_id, arguments.sample_count);
} catch (const std::exception& ex) {
// This will catch DDS exceptions
std::cerr << "Exception in run_example(): " << ex.what() << std::endl;
return EXIT_FAILURE;
}
// Releases the memory used by the participant factory. Optional at
// application shutdown
dds::domain::DomainParticipant::finalize_participant_factory();
return EXIT_SUCCESS;
}
|
cxx
|
rticonnextdds-getting-started
|
data/projects/rticonnextdds-getting-started/6_content_filters/c++11/tempering_application.cxx
|
/*
* (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.
*/
#include <iostream>
#include <thread>
#include <dds/pub/ddspub.hpp>
#include <dds/sub/ddssub.hpp>
#include <rti/util/util.hpp> // for sleep()
#include <rti/config/Logger.hpp> // for logging
// Or simply include <dds/dds.hpp>
#include "chocolate_factory.hpp"
#include "application.hpp" // Argument parsing
using namespace application;
// Tempering application:
// 1) Publishes the temperature
// 2) Subscribes to the lot state
// 3) After "processing" the lot, publishes the lot state
void publish_temperature(
dds::pub::DataWriter<Temperature> temperature_writer,
const std::string sensor_id)
{
// Create temperature sample for writing
int counter = 0;
Temperature temperature;
while (!shutdown_requested) {
counter++;
// Modify the data to be written here
temperature.sensor_id(sensor_id);
// Occasionally make the temperature high
if (counter % 400 == 0) {
std::cout << "Temperature too high" << std::endl;
temperature.degrees(33);
} else {
temperature.degrees(rand() % 3 + 30); // Random value between 30 and 32
}
temperature_writer.write(temperature);
rti::util::sleep(dds::core::Duration::from_millisecs(100));
}
}
void process_lot(
dds::sub::DataReader<ChocolateLotState>& lot_state_reader,
dds::pub::DataWriter<ChocolateLotState>& lot_state_writer)
{
// Take all samples. Samples are loaned to application, loan is
// returned when LoanedSamples destructor called.
dds::sub::LoanedSamples<ChocolateLotState> samples =
lot_state_reader.take();
// Process lots waiting for tempering
for (const auto& sample : samples) {
// Exercise #1.3: Remove the check that the Tempering Application is
// the next_station. This will now be filtered automatically.
if (sample.info().valid()
&& sample.data().next_station()
== StationKind::TEMPERING_CONTROLLER) {
std::cout << "Processing lot #" << sample.data().lot_id()
<< std::endl;
// Send an update that the tempering station is processing lot
ChocolateLotState updated_state(sample.data());
updated_state.lot_status(LotStatusKind::PROCESSING);
updated_state.next_station(StationKind::INVALID_CONTROLLER);
updated_state.station(StationKind::TEMPERING_CONTROLLER);
lot_state_writer.write(updated_state);
// "Processing" the lot.
rti::util::sleep(dds::core::Duration(5));
// Since this is the last step in processing,
// notify the monitoring application that the lot is complete
// using a dispose
dds::core::InstanceHandle instance_handle =
lot_state_writer.lookup_instance(updated_state);
lot_state_writer.dispose_instance(instance_handle);
std::cout << "Lot completed" << std::endl;
}
}
} // The LoanedSamples destructor returns the loan
template <typename T>
void on_requested_incompatible_qos(dds::sub::DataReader<T>& reader)
{
using namespace dds::core::policy;
QosPolicyId incompatible_policy =
reader.requested_incompatible_qos_status().last_policy_id();
// Print when this DataReader discovers an incompatible DataWriter
std::cout << "Discovered DataWriter with incompatible policy: ";
if (incompatible_policy == policy_id<Reliability>::value) {
std::cout << "Reliability";
} else if (incompatible_policy == policy_id<Durability>::value) {
std::cout << "Durability";
}
std::cout << std::endl;
}
void run_example(unsigned int domain_id, const std::string& sensor_id)
{
// Loads the QoS from the qos_profiles.xml file.
dds::core::QosProvider qos_provider("./qos_profiles.xml");
// A DomainParticipant allows an application to begin communicating in
// a DDS domain. Typically there is one DomainParticipant per application.
// Uses TemperingApplication QoS profile to set participant name.
dds::domain::DomainParticipant participant(
domain_id,
qos_provider.participant_qos(
"ChocolateFactoryLibrary::TemperingApplication"));
// A Topic has a name and a datatype. Create Topics.
// Topic names are constants defined in the IDL file.
dds::topic::Topic<Temperature> temperature_topic(
participant,
CHOCOLATE_TEMPERATURE_TOPIC);
dds::topic::Topic<ChocolateLotState> lot_state_topic(
participant,
CHOCOLATE_LOT_STATE_TOPIC);
// Exercise #1.1: Create a Content-Filtered Topic that filters out
// chocolate lot state unless the next_station = TEMPERING_CONTROLLER
// A Publisher allows an application to create one or more DataWriters
// Create Publisher with default QoS
dds::pub::Publisher publisher(participant);
// Create DataWriter of Topic "ChocolateTemperature"
// using ChocolateTemperatureProfile QoS profile for Streaming Data
dds::pub::DataWriter<Temperature> temperature_writer(
publisher,
temperature_topic,
qos_provider.datawriter_qos(
"ChocolateFactoryLibrary::ChocolateTemperatureProfile"));
// Create DataWriter of Topic "ChocolateLotState"
// using ChocolateLotStateProfile QoS profile for State Data
dds::pub::DataWriter<ChocolateLotState> lot_state_writer(
publisher,
lot_state_topic,
qos_provider.datawriter_qos(
"ChocolateFactoryLibrary::ChocolateLotStateProfile"));
// A Subscriber allows an application to create one or more DataReaders
dds::sub::Subscriber subscriber(participant);
// Create DataReader of Topic "ChocolateLotState".
// using ChocolateLotStateProfile QoS profile for State Data
// Exercise #1.2: Change the DataReader's Topic to use a
// Content-Filtered Topic
dds::sub::DataReader<ChocolateLotState> lot_state_reader(
subscriber,
lot_state_topic,
qos_provider.datareader_qos(
"ChocolateFactoryLibrary::ChocolateLotStateProfile"));
// Obtain the DataReader's Status Condition
dds::core::cond::StatusCondition reader_status_condition(lot_state_reader);
// Contains statuses that entities can be notified about
using dds::core::status::StatusMask;
// Enable the 'data available' and 'requested incompatible qos' statuses
reader_status_condition.enabled_statuses(
StatusMask::data_available()
| StatusMask::requested_incompatible_qos());
// Associate a handler with the status condition. This will run when the
// condition is triggered, in the context of the dispatch call (see below)
reader_status_condition.extensions().handler([&lot_state_reader,
&lot_state_writer]() {
if ((lot_state_reader.status_changes() & StatusMask::data_available())
!= StatusMask::none()) {
process_lot(lot_state_reader, lot_state_writer);
}
if ((lot_state_reader.status_changes()
& StatusMask::requested_incompatible_qos())
!= StatusMask::none()) {
on_requested_incompatible_qos(lot_state_reader);
}
});
// Create a WaitSet and attach the StatusCondition
dds::core::cond::WaitSet waitset;
waitset += reader_status_condition;
// Create a thread to periodically write the temperature
std::cout << "ChocolateTemperature Sensor with ID: " << sensor_id
<< " starting" << std::endl;
std::thread temperature_thread(
publish_temperature,
temperature_writer,
sensor_id);
while (!shutdown_requested) {
// Wait for ChocolateLotState
std::cout << "Waiting for lot" << std::endl;
waitset.dispatch(dds::core::Duration(10)); // Wait up to 10s for update
}
temperature_thread.join();
}
int main(int argc, char *argv[])
{
// 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_example(arguments.domain_id, arguments.sensor_id);
} catch (const std::exception& ex) {
// This will catch DDS exceptions
std::cerr << "Exception in run_example(): " << ex.what() << std::endl;
return EXIT_FAILURE;
}
// Releases the memory used by the participant factory. Optional at
// application shutdown
dds::domain::DomainParticipant::finalize_participant_factory();
return EXIT_SUCCESS;
}
|
cxx
|
rticonnextdds-getting-started
|
data/projects/rticonnextdds-getting-started/4_keys_instances/c++98/monitoring_ctrl_application.cxx
|
/*
* (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.
*/
#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include "chocolate_factory.h"
#include "chocolate_factorySupport.h"
#include "ndds/ndds_cpp.h"
#include "application.h"
using namespace application;
static int shutdown(
DDSDomainParticipant *participant,
const char *shutdown_message,
int status);
// Structure to hold data for write lot sate thread
struct StartLotThreadData {
ChocolateLotStateDataWriter *writer;
unsigned int lots_to_process;
};
void publish_start_lot(StartLotThreadData *thread_data)
{
ChocolateLotState sample;
ChocolateLotStateTypeSupport::initialize_data(&sample);
unsigned int lots_to_process = thread_data->lots_to_process;
ChocolateLotStateDataWriter *writer = thread_data->writer;
for (unsigned int count = 0; !shutdown_requested && count < lots_to_process;
count++) {
// Set the values for a chocolate lot that is going to be sent to wait
// at the tempering station
sample.lot_id = count % 100;
sample.lot_status = WAITING;
sample.next_station = TEMPERING_CONTROLLER;
std::cout << std::endl
<< "Starting lot: " << std::endl
<< "[lot_id: " << sample.lot_id << " next_station: ";
print_station_kind(sample.next_station);
std::cout << "]" << std::endl;
// Send an update to station that there is a lot waiting for tempering
DDS_ReturnCode_t retcode = writer->write(sample, DDS_HANDLE_NIL);
if (retcode != DDS_RETCODE_OK) {
std::cerr << "write error " << retcode << std::endl;
}
// Start a new lot every 10 seconds
DDS_Duration_t send_period = { 10, 0 };
NDDSUtility::sleep(send_period);
}
ChocolateLotStateTypeSupport::finalize_data(&sample);
}
// Process data. Returns number of samples processed.
unsigned int monitor_lot_state(ChocolateLotStateDataReader *lot_state_reader)
{
ChocolateLotStateSeq data_seq;
DDS_SampleInfoSeq info_seq;
unsigned int samples_read = 0;
// Take available data from DataReader's queue
DDS_ReturnCode_t retcode = lot_state_reader->take(data_seq, info_seq);
if (retcode != DDS_RETCODE_OK && retcode != DDS_RETCODE_NO_DATA) {
std::cerr << "take error " << retcode << std::endl;
return 0;
}
// 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) {
std::cout << "Received lot update:" << std::endl;
application::print_chocolate_lot_data(data_seq[i]);
samples_read++;
} else {
// Exercise #3.2: Detect that a lot is complete by checking for
// the disposed state.
}
}
// Data sequence was loaned from middleware for performance.
// Return loan when application is finished with data.
retcode = lot_state_reader->return_loan(data_seq, info_seq);
if (retcode != DDS_RETCODE_OK) {
std::cerr << "return_loan error " << retcode << std::endl;
}
return samples_read;
}
// Exercise #4.6: Add monitor_temperature function
int run_example(unsigned int domain_id, unsigned int sample_count)
{
// Connext DDS Setup
// -----------------
// A DomainParticipant allows an application to begin communicating in
// a DDS domain. Typically there is one DomainParticipant per application.
// DomainParticipant QoS is configured in USER_QOS_PROFILES.xml
DDSDomainParticipant *participant =
DDSTheParticipantFactory->create_participant(
domain_id,
DDS_PARTICIPANT_QOS_DEFAULT,
NULL /* listener */,
DDS_STATUS_MASK_NONE);
if (participant == NULL) {
shutdown(participant, "create_participant error", EXIT_FAILURE);
}
// Create Topics
// Register the datatype to use when creating the Topic
const char *lot_state_type_name =
ChocolateLotStateTypeSupport::get_type_name();
DDS_ReturnCode_t retcode = ChocolateLotStateTypeSupport::register_type(
participant,
lot_state_type_name);
if (retcode != DDS_RETCODE_OK) {
shutdown(participant, "register_type error", EXIT_FAILURE);
}
// A Topic has a name and a datatype. Create a Topic called
// "ChocolateLotState" with your registered data type
DDSTopic *lot_state_topic = participant->create_topic(
CHOCOLATE_LOT_STATE_TOPIC,
lot_state_type_name,
DDS_TOPIC_QOS_DEFAULT,
NULL /* listener */,
DDS_STATUS_MASK_NONE);
if (lot_state_topic == NULL) {
shutdown(participant, "create_topic error", EXIT_FAILURE);
}
// Exercise #4.1: Add a Topic for Temperature to this application
// Create Publisher and DataWriter
// A Publisher allows an application to create one or more DataWriters
// Publisher QoS is configured in USER_QOS_PROFILES.xml
DDSPublisher *publisher = participant->create_publisher(
DDS_PUBLISHER_QOS_DEFAULT,
NULL /* listener */,
DDS_STATUS_MASK_NONE);
if (publisher == NULL) {
return shutdown(participant, "create_publisher error", EXIT_FAILURE);
}
// This DataWriter writes data on Topic "ChocolateLotState"
// DataWriter QoS is configured in USER_QOS_PROFILES.xml
DDSDataWriter *generic_lot_state_writer = publisher->create_datawriter(
lot_state_topic,
DDS_DATAWRITER_QOS_DEFAULT,
NULL /* listener */,
DDS_STATUS_MASK_NONE);
if (generic_lot_state_writer == NULL) {
return shutdown(participant, "create_datawriter error", EXIT_FAILURE);
}
// A narrow is a cast from a generic DataWriter to one that is specific
// to your type. Use the type specific DataWriter to write()
ChocolateLotStateDataWriter *lot_state_writer =
ChocolateLotStateDataWriter::narrow(generic_lot_state_writer);
if (lot_state_writer == NULL) {
return shutdown(participant, "DataWriter narrow error", EXIT_FAILURE);
}
// Create Subscriber and DataReaders
// A Subscriber allows an application to create one or more DataReaders
// Subscriber QoS is configured in USER_QOS_PROFILES.xml
DDSSubscriber *subscriber = participant->create_subscriber(
DDS_SUBSCRIBER_QOS_DEFAULT,
NULL /* listener */,
DDS_STATUS_MASK_NONE);
if (subscriber == NULL) {
shutdown(participant, "create_subscriber error", EXIT_FAILURE);
}
// This DataReader reads data of type ChocolateLotState on Topic
// "ChocolateLotState". DataReader QoS is configured in
// USER_QOS_PROFILES.xml
DDSDataReader *lot_state_generic_reader = subscriber->create_datareader(
lot_state_topic,
DDS_DATAREADER_QOS_DEFAULT,
NULL,
DDS_STATUS_MASK_NONE);
if (lot_state_generic_reader == NULL) {
shutdown(participant, "create_datareader error", EXIT_FAILURE);
}
// Get status condition: Each entity has a Status Condition, which
// gets triggered when a status becomes true
DDSStatusCondition *lot_state_status_condition =
lot_state_generic_reader->get_statuscondition();
if (lot_state_status_condition == NULL) {
shutdown(participant, "get_statuscondition error", EXIT_FAILURE);
}
// Enable only the status we are interested in:
// DDS_DATA_AVAILABLE_STATUS
retcode = lot_state_status_condition->set_enabled_statuses(
DDS_DATA_AVAILABLE_STATUS);
if (retcode != DDS_RETCODE_OK) {
shutdown(participant, "set_enabled_statuses error", EXIT_FAILURE);
}
// Exercise #4.2: Add a DataReader for Temperature to this application
// Create the WaitSet and attach the Status Condition to it. The WaitSet
// will be woken when the condition is triggered.
DDSWaitSet waitset;
retcode = waitset.attach_condition(lot_state_status_condition);
if (retcode != DDS_RETCODE_OK) {
shutdown(participant, "attach_condition error", EXIT_FAILURE);
}
// Exercise #4.3: Add the new DataReader's StatusCondition to the Waitset
// A narrow is a cast from a generic DataReader to one that is specific
// to your type. Use the type specific DataReader to read data
ChocolateLotStateDataReader *lot_state_reader =
ChocolateLotStateDataReader::narrow(lot_state_generic_reader);
if (lot_state_reader == NULL) {
shutdown(participant, "DataReader narrow error", EXIT_FAILURE);
}
// Exercise #4.4: Cast from a generic DataReader to a TemperatureDataReader
// Create a thread to periodically start new chocolate lots
StartLotThreadData thread_data;
thread_data.writer = lot_state_writer;
thread_data.lots_to_process = sample_count;
OSThread thread((ThreadFunction) publish_start_lot, (void *) &thread_data);
thread.run();
// Main loop. Wait for data to arrive, and process when it arrives.
// ----------------------------------------------------------------
unsigned int samples_read = 0;
while (!shutdown_requested && samples_read < sample_count) {
DDSConditionSeq active_conditions_seq;
// wait() blocks execution of the thread until one or more attached
// Conditions become true, or until a user-specified timeout expires.
DDS_Duration_t wait_timeout = { 15, 0 };
retcode = waitset.wait(active_conditions_seq, wait_timeout);
// You get a timeout if no conditions were triggered before the timeout
if (retcode == DDS_RETCODE_TIMEOUT) {
std::cout << "Wait timed out after 10 seconds." << std::endl;
continue;
} else if (retcode != DDS_RETCODE_OK) {
std::cerr << "wait returned error: " << retcode << std::endl;
break;
}
// Get the status changes to check which status condition
// triggered the WaitSet to wake
DDS_StatusMask triggeredmask = lot_state_reader->get_status_changes();
// If the status is "Data Available"
if (triggeredmask & DDS_DATA_AVAILABLE_STATUS) {
samples_read += monitor_lot_state(lot_state_reader);
}
// Exercise #4.5: Check if the temperature DataReader received
// DATA_AVAILABLE event notification
}
// Cleanup
// -------
thread.join();
// Delete all entities (DataReader, Topic, Subscriber, DomainParticipant)
return shutdown(participant, "shutting down", 0);
}
// Delete all entities
int shutdown(
DDSDomainParticipant *participant,
const char *shutdown_message,
int status)
{
DDS_ReturnCode_t retcode;
std::cout << shutdown_message << std::endl;
if (participant != NULL) {
// This includes everything created by this Participant, including
// DataWriters, Topics, Publishers. (and Subscribers and DataReaders)
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_example(arguments.domain_id, arguments.sample_count);
// Releases the memory used by the participant factory. Optional at
// application shutdown
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-getting-started
|
data/projects/rticonnextdds-getting-started/4_keys_instances/c++98/tempering_application.cxx
|
/*
* (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.
*/
#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include "chocolate_factory.h"
#include "chocolate_factorySupport.h"
#include "ndds/ndds_cpp.h"
#include "application.h"
using namespace application;
// Tempering application:
// 1) Publishes the temperature
// 2) Subscribes to the lot state
// 3) After "processing" the lot, publishes the lot state
static int shutdown(
DDSDomainParticipant *participant,
const char *shutdown_message,
int status);
// Structure to hold data for write thread
struct TemperatureWriteData {
TemperatureDataWriter *writer;
const char *sensor_id;
};
void publish_temperature(const TemperatureWriteData *write_data)
{
TemperatureDataWriter *writer = write_data->writer;
// Create temperature sample for writing
Temperature temperature;
TemperatureTypeSupport::initialize_data(&temperature);
while (!shutdown_requested) {
// Modify the data to be written here
snprintf(temperature.sensor_id, 255, "%s", write_data->sensor_id);
temperature.degrees = rand() % 3 + 30; // Random num between 30 and 32
DDS_ReturnCode_t retcode = writer->write(temperature, DDS_HANDLE_NIL);
if (retcode != DDS_RETCODE_OK) {
std::cerr << "write error " << retcode << std::endl;
}
// Update temperature every 100 ms
DDS_Duration_t send_period = { 0, 100000000 };
NDDSUtility::sleep(send_period);
}
TemperatureTypeSupport::finalize_data(&temperature);
}
void process_lot(
ChocolateLotStateDataReader *lot_state_reader,
ChocolateLotStateDataWriter *lot_state_writer)
{
// Take all samples. Samples are loaned to application, loan is
// returned when LoanedSamples destructor called.
ChocolateLotStateSeq data_seq;
DDS_SampleInfoSeq info_seq;
// Take available data from DataReader's queue
DDS_ReturnCode_t retcode = lot_state_reader->take(data_seq, info_seq);
if (retcode != DDS_RETCODE_OK && retcode != DDS_RETCODE_NO_DATA) {
std::cerr << "take error " << retcode << std::endl;
return;
}
// Process lots waiting for tempering
for (int i = 0; i < data_seq.length(); ++i) {
// Check if a sample is an instance lifecycle event
if (info_seq[i].valid_data) {
if (data_seq[i].next_station == TEMPERING_CONTROLLER) {
std::cout << "Processing lot #" << data_seq[i].lot_id
<< std::endl;
// Send an update that the tempering station is processing lot
ChocolateLotState updated_state(data_seq[i]);
updated_state.lot_status = PROCESSING;
updated_state.next_station = INVALID_CONTROLLER;
updated_state.station = TEMPERING_CONTROLLER;
DDS_ReturnCode_t retcode =
lot_state_writer->write(updated_state, DDS_HANDLE_NIL);
if (retcode != DDS_RETCODE_OK) {
std::cerr << "write error " << retcode << std::endl;
}
// "Processing" the lot.
DDS_Duration_t processing_time = { 5, 0 };
NDDSUtility::sleep(processing_time);
// Exercise #3.1: Since this is the last step in processing,
// notify the monitoring application that the lot is complete
// using a dispose
}
} else {
// Received instance state notification
continue;
}
}
// Data sequence was loaned from middleware for performance.
// Return loan when application is finished with data.
retcode = lot_state_reader->return_loan(data_seq, info_seq);
if (retcode != DDS_RETCODE_OK) {
std::cerr << "return_loan error " << retcode << std::endl;
}
}
int run_example(
unsigned int domain_id,
unsigned int sample_count,
const char *sensor_id)
{
// Connext DDS setup
// -----------------
// A DomainParticipant allows an application to begin communicating in
// a DDS domain. Typically there is one DomainParticipant per application.
// DomainParticipant QoS is configured in USER_QOS_PROFILES.xml
DDSDomainParticipant *participant =
DDSTheParticipantFactory->create_participant(
domain_id,
DDS_PARTICIPANT_QOS_DEFAULT,
NULL /* listener */,
DDS_STATUS_MASK_NONE);
if (participant == NULL) {
return shutdown(participant, "create_participant error", EXIT_FAILURE);
}
// Create Topics
// Register the datatype to use when creating the Topic
const char *temperature_type_name = TemperatureTypeSupport::get_type_name();
DDS_ReturnCode_t retcode = TemperatureTypeSupport::register_type(
participant,
temperature_type_name);
if (retcode != DDS_RETCODE_OK) {
return shutdown(participant, "register_type error", EXIT_FAILURE);
}
const char *lot_state_type_name =
ChocolateLotStateTypeSupport::get_type_name();
retcode = ChocolateLotStateTypeSupport::register_type(
participant,
lot_state_type_name);
if (retcode != DDS_RETCODE_OK) {
return shutdown(participant, "register_type error", EXIT_FAILURE);
}
// A Topic has a name and a datatype. Create a Topic called
// "ChocolateTemperature" with your registered temperature data type
DDSTopic *temperature_topic = participant->create_topic(
CHOCOLATE_TEMPERATURE_TOPIC,
temperature_type_name,
DDS_TOPIC_QOS_DEFAULT,
NULL /* listener */,
DDS_STATUS_MASK_NONE);
if (temperature_topic == NULL) {
return shutdown(participant, "create_topic error", EXIT_FAILURE);
}
// A Topic has a name and a datatype. Create a Topic called
// "ChocolateLotState" with your registered ChocolateLotState data type
DDSTopic *lot_state_topic = participant->create_topic(
CHOCOLATE_LOT_STATE_TOPIC,
lot_state_type_name,
DDS_TOPIC_QOS_DEFAULT,
NULL /* listener */,
DDS_STATUS_MASK_NONE);
if (lot_state_topic == NULL) {
return shutdown(participant, "create_topic error", EXIT_FAILURE);
}
// Create Publisher and DataWriters
// A Publisher allows an application to create one or more DataWriters
// Publisher QoS is configured in USER_QOS_PROFILES.xml
DDSPublisher *publisher = participant->create_publisher(
DDS_PUBLISHER_QOS_DEFAULT,
NULL /* listener */,
DDS_STATUS_MASK_NONE);
if (publisher == NULL) {
return shutdown(participant, "create_publisher error", EXIT_FAILURE);
}
// This DataWriter writes data on Topic "ChocolateTemperature"
// DataWriter QoS is configured in USER_QOS_PROFILES.xml
DDSDataWriter *generic_temp_writer = publisher->create_datawriter(
temperature_topic,
DDS_DATAWRITER_QOS_DEFAULT,
NULL /* listener */,
DDS_STATUS_MASK_NONE);
if (generic_temp_writer == NULL) {
return shutdown(participant, "create_datawriter error", EXIT_FAILURE);
}
DDSDataWriter *generic_lot_state_writer = publisher->create_datawriter(
lot_state_topic,
DDS_DATAWRITER_QOS_DEFAULT,
NULL /* listener */,
DDS_STATUS_MASK_NONE);
if (generic_lot_state_writer == NULL) {
return shutdown(participant, "create_datawriter error", EXIT_FAILURE);
}
// A narrow is a cast from a generic DataWriter to one that is specific
// to your type. Use the type specific DataWriter to write()
TemperatureDataWriter *temperature_writer =
TemperatureDataWriter::narrow(generic_temp_writer);
if (temperature_writer == NULL) {
return shutdown(participant, "DataWriter narrow error", EXIT_FAILURE);
}
ChocolateLotStateDataWriter *lot_state_writer =
ChocolateLotStateDataWriter::narrow(generic_lot_state_writer);
if (lot_state_writer == NULL) {
return shutdown(participant, "DataWriter narrow error", EXIT_FAILURE);
}
// Create Subscriber and DataReader
// A Subscriber allows an application to create one or more DataReaders
// Subscriber QoS is configured in USER_QOS_PROFILES.xml
DDSSubscriber *subscriber = participant->create_subscriber(
DDS_SUBSCRIBER_QOS_DEFAULT,
NULL /* listener */,
DDS_STATUS_MASK_NONE);
if (subscriber == NULL) {
shutdown(participant, "create_subscriber error", EXIT_FAILURE);
}
// This DataReader reads data of type Temperature on Topic
// "ChocolateTemperature". DataReader QoS is configured in
// USER_QOS_PROFILES.xml
DDSDataReader *generic_lot_state_reader = subscriber->create_datareader(
lot_state_topic,
DDS_DATAREADER_QOS_DEFAULT,
NULL,
DDS_STATUS_MASK_NONE);
if (generic_lot_state_reader == NULL) {
shutdown(participant, "create_datareader error", EXIT_FAILURE);
}
// Get status condition: Each entity has a Status Condition, which
// gets triggered when a status becomes true
DDSStatusCondition *status_condition =
generic_lot_state_reader->get_statuscondition();
if (status_condition == NULL) {
shutdown(participant, "get_statuscondition error", EXIT_FAILURE);
}
// Enable only the status we are interested in:
// DDS_DATA_AVAILABLE_STATUS
retcode = status_condition->set_enabled_statuses(DDS_DATA_AVAILABLE_STATUS);
if (retcode != DDS_RETCODE_OK) {
shutdown(participant, "set_enabled_statuses error", EXIT_FAILURE);
}
// Create the WaitSet and attach the Status Condition to it. The WaitSet
// will be woken when the condition is triggered.
DDSWaitSet waitset;
retcode = waitset.attach_condition(status_condition);
if (retcode != DDS_RETCODE_OK) {
shutdown(participant, "attach_condition error", EXIT_FAILURE);
}
// A narrow is a cast from a generic DataReader to one that is specific
// to your type. Use the type specific DataReader to read data
ChocolateLotStateDataReader *lot_state_reader =
ChocolateLotStateDataReader::narrow(generic_lot_state_reader);
if (lot_state_reader == NULL) {
shutdown(participant, "DataReader narrow error", EXIT_FAILURE);
}
// Create thread to periodically write temperature data
TemperatureWriteData write_data;
write_data.writer = temperature_writer;
write_data.sensor_id = sensor_id;
OSThread thread((ThreadFunction) publish_temperature, (void *) &write_data);
std::cout << "ChocolateTemperature Sensor with ID: " << write_data.sensor_id
<< " starting" << std::endl;
thread.run();
// Main loop, wait for lots
// ------------------------
while (!shutdown_requested) {
// Wait for ChocolateLotState
std::cout << "Waiting for lot" << std::endl;
// wait() blocks execution of the thread until one or more attached
// Conditions become true, or until a user-specified timeout expires.
DDSConditionSeq active_conditions_seq;
DDS_Duration_t wait_timeout = { 10, 0 };
retcode = waitset.wait(active_conditions_seq, wait_timeout);
// You get a timeout if no conditions were triggered before the timeout
if (retcode == DDS_RETCODE_TIMEOUT) {
std::cout << "Wait timed out after 10 seconds." << std::endl;
continue;
} else if (retcode != DDS_RETCODE_OK) {
std::cerr << "wait returned error: " << retcode << std::endl;
break;
}
// Get the status changes to check which status condition
// triggered the WaitSet to wake
DDS_StatusMask triggered_mask = lot_state_reader->get_status_changes();
// If the status is "Data Available"
if (triggered_mask & DDS_DATA_AVAILABLE_STATUS) {
process_lot(lot_state_reader, lot_state_writer);
}
}
// Cleanup
// -------
thread.join();
// Delete all entities (DataWriter, Topic, Publisher, DomainParticipant)
return shutdown(participant, "shutting down", EXIT_SUCCESS);
}
// Delete all entities
int shutdown(
DDSDomainParticipant *participant,
const char *shutdown_message,
int status)
{
DDS_ReturnCode_t retcode;
std::cout << shutdown_message << std::endl;
if (participant != NULL) {
// This includes everything created by this Participant, including
// DataWriters, Topics, Publishers. (and Subscribers and DataReaders)
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_example(
arguments.domain_id,
arguments.sample_count,
arguments.sensor_id);
// Releases the memory used by the participant factory. Optional at
// application shutdown
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-getting-started
|
data/projects/rticonnextdds-getting-started/4_keys_instances/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 <ctime>
#include <limits>
#ifdef RTI_WIN32
/* strtok, fopen warnings */
#pragma warning( disable : 4996 )
#endif
#ifdef RTI_WIN32
#define DllExport __declspec( dllexport )
#include <Winsock2.h>
#include <process.h>
#else
#define DllExport
#include <sys/select.h>
#include <semaphore.h>
#include <pthread.h>
#endif
#include "ndds/ndds_cpp.h"
#include "chocolate_factoryPlugin.h"
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);
}
// A function that takes a void pointer, and is passed to the thread creation
// function.
typedef void* (*ThreadFunction)(void *);
class OSThread
{
public:
OSThread(ThreadFunction function, void *function_param):
function(function),
function_param(function_param)
{
}
// Run the thread
void run()
{
#ifdef RTI_WIN32
thread = (HANDLE) _beginthread(
(void(__cdecl*)(void*))function,
0, (void*)function_param);
#else
pthread_attr_t thread_attr;
pthread_attr_init(&thread_attr);
pthread_attr_setdetachstate(&thread_attr, PTHREAD_CREATE_JOINABLE);
int error = pthread_create(
&thread,
&thread_attr,
function,
(void *)function_param);
pthread_attr_destroy(&thread_attr);
#endif
}
// Join the thread
void join()
{
#ifdef RTI_WIN32
WaitForSingleObject(thread, INFINITE);
#else
void *ret_val;
int error = pthread_join(thread, &ret_val);
#endif
}
private:
// OS-specific thread definition
#ifdef RTI_WIN32
HANDLE thread;
#else
pthread_t thread;
#endif
// Function called by OS-specific thread
ThreadFunction function;
// Parameter to the function
void *function_param;
};
inline void print_station_kind(StationKind station_kind)
{
switch(station_kind) {
case INVALID_CONTROLLER:
std::cout << "INVALID_CONTROLLER";
break;
case SUGAR_CONTROLLER:
std::cout << "SUGAR_CONTROLLER";
break;
case COCOA_BUTTER_CONTROLLER:
std::cout << "COCOA_BUTTER_CONTROLLER";
break;
case VANILLA_CONTROLLER:
std::cout << "VANILLA_CONTROLLER";
break;
case MILK_CONTROLLER:
std::cout << "MILK_CONTROLLER";
break;
case TEMPERING_CONTROLLER:
std::cout << "TEMPERING_CONTROLLER";
break;
}
}
inline void print_lot_status_kind(LotStatusKind lot_status_kind)
{
switch(lot_status_kind)
{
case WAITING:
std::cout << "WAITING";
break;
case PROCESSING:
std::cout << "PROCESSING";
break;
case COMPLETED:
std::cout << "COMPLETED";
break;
}
}
inline void print_chocolate_lot_data(const ChocolateLotState& sample)
{
std::cout << "[" << "lot_id: " << sample.lot_id << ", " << "station: ";
print_station_kind(sample.station);
std::cout << ", next_station: ";
print_station_kind(sample.next_station);
std::cout << ", lot_status: ";
print_lot_status_kind(sample.lot_status);
std::cout << "]" << std::endl;
}
enum ParseReturn { PARSE_RETURN_OK, PARSE_RETURN_FAILURE, PARSE_RETURN_EXIT };
struct ApplicationArguments {
ParseReturn parse_result;
unsigned int domain_id;
unsigned int sample_count;
char sensor_id[256];
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 = (std::numeric_limits<unsigned int>::max)();
arguments.verbosity = NDDS_CONFIG_LOG_VERBOSITY_ERROR;
arguments.parse_result = PARSE_RETURN_OK;
// Initialize with an integer value
srand((unsigned int)time(NULL));
snprintf(arguments.sensor_id, 255, "%d", rand() % 10);
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], "-i") == 0
|| strcmp(argv[arg_processing], "--sensor-id") == 0)) {
snprintf(arguments.sensor_id, 255, "%s", 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"
" -i, --sensor-id <string> Unique ID of temperature sensor.\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-getting-started
|
data/projects/rticonnextdds-getting-started/4_keys_instances/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 <string>
#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;
std::string sensor_id;
rti::config::Verbosity verbosity;
};
// 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)();
srand((unsigned int)time(NULL));
std::string sensor_id = std::to_string(rand() % 50);
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 ((argc > arg_processing + 1)
&& (strcmp(argv[arg_processing], "-i") == 0
|| strcmp(argv[arg_processing], "--sensor-id") == 0)) {
sensor_id = 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"
" cleanly shutting down. \n"
" -i, --sensor-id <string> Unique ID of temperature sensor.\n"\
" -v, --verbosity <int> How much debugging output to show.\n"\
" Range: 0-5 \n"
" Default: 0"
<< std::endl;
}
return { parse_result, domain_id, sample_count, sensor_id, verbosity };
}
} // namespace application
#endif // APPLICATION_HPP
|
hpp
|
rticonnextdds-getting-started
|
data/projects/rticonnextdds-getting-started/4_keys_instances/c++11/monitoring_ctrl_application.cxx
|
/*
* (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.
*/
#include <iostream>
#include <thread>
#include <dds/pub/ddspub.hpp>
#include <dds/sub/ddssub.hpp>
#include <rti/util/util.hpp> // for sleep()
#include <rti/config/Logger.hpp> // for logging
// Or simply include <dds/dds.hpp>
#include "chocolate_factory.hpp"
#include "application.hpp" // Argument parsing
using namespace application;
void publish_start_lot(
dds::pub::DataWriter<ChocolateLotState> lot_state_writer,
unsigned int lots_to_process)
{
ChocolateLotState sample;
for (unsigned int count = 0; !shutdown_requested && count < lots_to_process;
count++) {
// Set the values for a chocolate lot that is going to be sent to wait
// at the tempering station
sample.lot_id(count % 100);
sample.lot_status(LotStatusKind::WAITING);
sample.next_station(StationKind::TEMPERING_CONTROLLER);
std::cout << std::endl << "Starting lot: " << std::endl;
std::cout << "[lot_id: " << sample.lot_id()
<< " next_station: " << sample.next_station() << "]"
<< std::endl;
// Send an update to station that there is a lot waiting for tempering
lot_state_writer.write(sample);
rti::util::sleep(dds::core::Duration(10));
}
}
unsigned int monitor_lot_state(dds::sub::DataReader<ChocolateLotState>& reader)
{
// Take all samples. Samples are loaned to application, loan is
// returned when LoanedSamples destructor called.
unsigned int samples_read = 0;
dds::sub::LoanedSamples<ChocolateLotState> samples = reader.take();
// Receive updates from stations about the state of current lots
for (const auto& sample : samples) {
std::cout << "Received Lot Update:" << std::endl;
if (sample.info().valid()) {
std::cout << sample.data() << std::endl;
samples_read++;
} else {
// Exercise #3.2: Detect that a lot is complete by checking for
// the disposed state.
}
}
return samples_read;
}
// Exercise #4.4: Add monitor_temperature function
void run_example(unsigned int domain_id, unsigned int lots_to_process)
{
// A DomainParticipant allows an application to begin communicating in
// a DDS domain. Typically there is one DomainParticipant per application.
// DomainParticipant QoS is configured in USER_QOS_PROFILES.xml
dds::domain::DomainParticipant participant(domain_id);
// A Topic has a name and a datatype. Create a Topic with type
// ChocolateLotState. Topic name is a constant defined in the IDL file.
dds::topic::Topic<ChocolateLotState> topic(
participant,
CHOCOLATE_LOT_STATE_TOPIC);
// Exercise #4.1: Add a Topic for Temperature to this application
// A Publisher allows an application to create one or more DataWriters
// Publisher QoS is configured in USER_QOS_PROFILES.xml
dds::pub::Publisher publisher(participant);
// This DataWriter writes data on Topic "ChocolateLotState"
// DataWriter QoS is configured in USER_QOS_PROFILES.xml
dds::pub::DataWriter<ChocolateLotState> lot_state_writer(publisher, topic);
// A Subscriber allows an application to create one or more DataReaders
// Subscriber QoS is configured in USER_QOS_PROFILES.xml
dds::sub::Subscriber subscriber(participant);
// Create DataReader of Topic "ChocolateLotState".
// DataReader QoS is configured in USER_QOS_PROFILES.xml
dds::sub::DataReader<ChocolateLotState> lot_state_reader(subscriber, topic);
// Exercise #4.2: Add a DataReader for Temperature to this application
// Obtain the DataReader's Status Condition
dds::core::cond::StatusCondition lot_state_status_condition(
lot_state_reader);
// Enable the 'data available' status.
lot_state_status_condition.enabled_statuses(
dds::core::status::StatusMask::data_available());
// Associate a handler with the status condition. This will run when the
// condition is triggered, in the context of the dispatch call (see below)
unsigned int lots_processed = 0;
lot_state_status_condition.extensions().handler(
[&lot_state_reader, &lots_processed]() {
lots_processed += monitor_lot_state(lot_state_reader);
});
// Create a WaitSet and attach the StatusCondition
dds::core::cond::WaitSet waitset;
waitset += lot_state_status_condition;
// Exercise #4.3: Add the new DataReader's StatusCondition to the Waitset
// Create a thread to periodically start new chocolate lots
std::thread start_lot_thread(
publish_start_lot,
lot_state_writer,
lots_to_process);
while (!shutdown_requested && lots_processed < lots_to_process) {
// Dispatch will call the handlers associated to the WaitSet conditions
// when they activate
waitset.dispatch(dds::core::Duration(10)); // Wait up to 10s each time
}
start_lot_thread.join();
}
int main(int argc, char *argv[])
{
// 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_example(arguments.domain_id, arguments.sample_count);
} catch (const std::exception& ex) {
// This will catch DDS exceptions
std::cerr << "Exception in run_example(): " << ex.what() << std::endl;
return EXIT_FAILURE;
}
// Releases the memory used by the participant factory. Optional at
// application shutdown
dds::domain::DomainParticipant::finalize_participant_factory();
return EXIT_SUCCESS;
}
|
cxx
|
rticonnextdds-getting-started
|
data/projects/rticonnextdds-getting-started/4_keys_instances/c++11/tempering_application.cxx
|
/*
* (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.
*/
#include <iostream>
#include <thread>
#include <dds/pub/ddspub.hpp>
#include <dds/sub/ddssub.hpp>
#include <rti/util/util.hpp> // for sleep()
#include <rti/config/Logger.hpp> // for logging
// Or simply include <dds/dds.hpp>
#include "chocolate_factory.hpp"
#include "application.hpp" // Argument parsing
using namespace application;
// Tempering application:
// 1) Publishes the temperature
// 2) Subscribes to the lot state
// 3) After "processing" the lot, publishes the lot state
void publish_temperature(
dds::pub::DataWriter<Temperature> temperature_writer,
const std::string sensor_id)
{
// Create temperature sample for writing
Temperature temperature;
while (!shutdown_requested) {
// Modify the data to be written here
temperature.sensor_id(sensor_id);
temperature.degrees(rand() % 3 + 30); // Random value between 30 and 32
temperature_writer.write(temperature);
rti::util::sleep(dds::core::Duration::from_millisecs(100));
}
}
void process_lot(
dds::sub::DataReader<ChocolateLotState>& lot_state_reader,
dds::pub::DataWriter<ChocolateLotState>& lot_state_writer)
{
// Take all samples. Samples are loaned to application, loan is
// returned when LoanedSamples destructor called.
dds::sub::LoanedSamples<ChocolateLotState> samples =
lot_state_reader.take();
// Process lots waiting for tempering
for (const auto& sample : samples) {
if (sample.info().valid()
&& sample.data().next_station()
== StationKind::TEMPERING_CONTROLLER) {
std::cout << "Processing lot #" << sample.data().lot_id()
<< std::endl;
// Send an update that the tempering station is processing lot
ChocolateLotState updated_state(sample.data());
updated_state.lot_status(LotStatusKind::PROCESSING);
updated_state.next_station(StationKind::INVALID_CONTROLLER);
updated_state.station(StationKind::TEMPERING_CONTROLLER);
lot_state_writer.write(updated_state);
// "Processing" the lot.
rti::util::sleep(dds::core::Duration(5));
// Exercise #3.1: Since this is the last step in processing,
// notify the monitoring application that the lot is complete
// using a dispose
}
}
} // The LoanedSamples destructor returns the loan
void run_example(unsigned int domain_id, const std::string& sensor_id)
{
// A DomainParticipant allows an application to begin communicating in
// a DDS domain. Typically there is one DomainParticipant per application.
// DomainParticipant QoS is configured in USER_QOS_PROFILES.xml
dds::domain::DomainParticipant participant(domain_id);
// A Topic has a name and a datatype. Create Topics.
// Topic names are constants defined in the IDL file.
dds::topic::Topic<Temperature> temperature_topic(
participant,
CHOCOLATE_TEMPERATURE_TOPIC);
dds::topic::Topic<ChocolateLotState> lot_state_topic(
participant,
CHOCOLATE_LOT_STATE_TOPIC);
// A Publisher allows an application to create one or more DataWriters
// Publisher QoS is configured in USER_QOS_PROFILES.xml
dds::pub::Publisher publisher(participant);
// Create DataWriters of Topics "ChocolateTemperature" & "ChocolateLotState"
// DataWriter QoS is configured in USER_QOS_PROFILES.xml
dds::pub::DataWriter<Temperature> temperature_writer(
publisher,
temperature_topic);
dds::pub::DataWriter<ChocolateLotState> lot_state_writer(
publisher,
lot_state_topic);
// A Subscriber allows an application to create one or more DataReaders
// Subscriber QoS is configured in USER_QOS_PROFILES.xml
dds::sub::Subscriber subscriber(participant);
// Create DataReader of Topic "ChocolateLotState".
// DataReader QoS is configured in USER_QOS_PROFILES.xml
dds::sub::DataReader<ChocolateLotState> lot_state_reader(
subscriber,
lot_state_topic);
// Obtain the DataReader's Status Condition
dds::core::cond::StatusCondition status_condition(lot_state_reader);
// Enable the 'data available' status.
status_condition.enabled_statuses(
dds::core::status::StatusMask::data_available());
// Associate a handler with the status condition. This will run when the
// condition is triggered, in the context of the dispatch call (see below)
status_condition.extensions().handler(
[&lot_state_reader, &lot_state_writer]() {
process_lot(lot_state_reader, lot_state_writer);
});
// Create a WaitSet and attach the StatusCondition
dds::core::cond::WaitSet waitset;
waitset += status_condition;
// Create a thread to periodically write the temperature
std::cout << "ChocolateTemperature Sensor with ID: " << sensor_id
<< " starting" << std::endl;
std::thread temperature_thread(
publish_temperature,
temperature_writer,
sensor_id);
while (!shutdown_requested) {
// Wait for ChocolateLotState
std::cout << "Waiting for lot" << std::endl;
waitset.dispatch(dds::core::Duration(10)); // Wait up to 10s for update
}
temperature_thread.join();
}
int main(int argc, char *argv[])
{
// 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_example(arguments.domain_id, arguments.sensor_id);
} catch (const std::exception& ex) {
// This will catch DDS exceptions
std::cerr << "Exception in run_example(): " << ex.what() << std::endl;
return EXIT_FAILURE;
}
// Releases the memory used by the participant factory. Optional at
// application shutdown
dds::domain::DomainParticipant::finalize_participant_factory();
return EXIT_SUCCESS;
}
|
cxx
|
rticonnextdds-getting-started
|
data/projects/rticonnextdds-getting-started/5_basic_qos/c++98/monitoring_ctrl_application.cxx
|
/*
* (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.
*/
#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include "chocolate_factory.h"
#include "chocolate_factorySupport.h"
#include "ndds/ndds_cpp.h"
#include "application.h"
using namespace application;
static int shutdown(
DDSDomainParticipant *participant,
const char *shutdown_message,
int status);
// Structure to hold data for write lot sate thread
struct StartLotThreadData {
ChocolateLotStateDataWriter *writer;
unsigned int lots_to_process;
};
void publish_start_lot(StartLotThreadData *thread_data)
{
ChocolateLotState sample;
ChocolateLotStateTypeSupport::initialize_data(&sample);
unsigned int lots_to_process = thread_data->lots_to_process;
ChocolateLotStateDataWriter *writer = thread_data->writer;
for (unsigned int count = 0; !shutdown_requested && count < lots_to_process;
count++) {
// Set the values for a chocolate lot that is going to be sent to wait
// at the tempering station
sample.lot_id = count % 100;
sample.lot_status = WAITING;
sample.next_station = TEMPERING_CONTROLLER;
std::cout << std::endl
<< "Starting lot: " << std::endl
<< "[lot_id: " << sample.lot_id << " next_station: ";
print_station_kind(sample.next_station);
std::cout << "]" << std::endl;
// Send an update to station that there is a lot waiting for tempering
DDS_ReturnCode_t retcode = writer->write(sample, DDS_HANDLE_NIL);
if (retcode != DDS_RETCODE_OK) {
std::cerr << "write error " << retcode << std::endl;
}
// Start a new lot every 10 seconds
DDS_Duration_t send_period = { 10, 0 };
NDDSUtility::sleep(send_period);
}
ChocolateLotStateTypeSupport::finalize_data(&sample);
}
// Process data. Returns number of samples processed.
unsigned int monitor_lot_state(ChocolateLotStateDataReader *lot_state_reader)
{
ChocolateLotStateSeq data_seq;
DDS_SampleInfoSeq info_seq;
unsigned int samples_read = 0;
// Take available data from DataReader's queue
DDS_ReturnCode_t retcode = lot_state_reader->take(data_seq, info_seq);
if (retcode != DDS_RETCODE_OK && retcode != DDS_RETCODE_NO_DATA) {
std::cerr << "take error " << retcode << std::endl;
return 0;
}
// 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) {
std::cout << "Received lot update:" << std::endl;
application::print_chocolate_lot_data(data_seq[i]);
samples_read++;
} else {
// Detect that a lot is complete because the instance is disposed
if (info_seq[i].instance_state
== DDS_NOT_ALIVE_DISPOSED_INSTANCE_STATE) {
ChocolateLotState key_holder;
// Fills in only the key field values associated with the
// instance
lot_state_reader->get_key_value(
key_holder,
info_seq[i].instance_handle);
std::cout << "[lot_id: " << key_holder.lot_id
<< " is completed]" << std::endl;
}
}
}
// Data sequence was loaned from middleware for performance.
// Return loan when application is finished with data.
retcode = lot_state_reader->return_loan(data_seq, info_seq);
if (retcode != DDS_RETCODE_OK) {
std::cerr << "return_loan error " << retcode << std::endl;
}
return samples_read;
}
// Monitor the chocolate temperature
void monitor_temperature(TemperatureDataReader *temperature_reader)
{
TemperatureSeq data_seq;
DDS_SampleInfoSeq info_seq;
// Take available data from DataReader's queue
DDS_ReturnCode_t retcode = temperature_reader->take(data_seq, info_seq);
if (retcode != DDS_RETCODE_OK && retcode != DDS_RETCODE_NO_DATA) {
std::cerr << "take error " << retcode << std::endl;
return;
}
// 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) {
std::cout << "Received instance state notification" << std::endl;
continue;
}
// Print data
if (data_seq[i].degrees > 32) {
std::cout << "Temperature high: ";
TemperatureTypeSupport::print_data(&data_seq[i]);
}
}
// Data sequence was loaned from middleware for performance.
// Return loan when application is finished with data.
temperature_reader->return_loan(data_seq, info_seq);
}
int run_example(unsigned int domain_id, unsigned int sample_count)
{
// Exercise #1.1: Load QoS file
// Connext DDS Setup
// -----------------
// A DomainParticipant allows an application to begin communicating in
// a DDS domain. Typically there is one DomainParticipant per application.
// DomainParticipant QoS is configured in USER_QOS_PROFILES.xml
// Exercise #1.2: Load DomainParticipant QoS profile
DDSDomainParticipant *participant =
DDSTheParticipantFactory->create_participant(
domain_id,
DDS_PARTICIPANT_QOS_DEFAULT,
NULL /* listener */,
DDS_STATUS_MASK_NONE);
if (participant == NULL) {
shutdown(participant, "create_participant error", EXIT_FAILURE);
}
// Create Topics
// Register the datatype to use when creating the Topic
const char *lot_state_type_name =
ChocolateLotStateTypeSupport::get_type_name();
DDS_ReturnCode_t retcode = ChocolateLotStateTypeSupport::register_type(
participant,
lot_state_type_name);
if (retcode != DDS_RETCODE_OK) {
shutdown(participant, "register_type error", EXIT_FAILURE);
}
// A Topic has a name and a datatype. Create a Topic called
// "ChocolateLotState" with your registered data type
DDSTopic *lot_state_topic = participant->create_topic(
CHOCOLATE_LOT_STATE_TOPIC,
lot_state_type_name,
DDS_TOPIC_QOS_DEFAULT,
NULL /* listener */,
DDS_STATUS_MASK_NONE);
if (lot_state_topic == NULL) {
shutdown(participant, "create_topic error", EXIT_FAILURE);
}
// Register the datatype to use when creating the Topic
const char *temperature_type_name =
TemperatureTypeSupport::get_type_name();
retcode = TemperatureTypeSupport::register_type(
participant,
temperature_type_name);
if (retcode != DDS_RETCODE_OK) {
shutdown(participant, "register_type error", EXIT_FAILURE);
}
// A Topic has a name and a datatype. Create a Topic called
// "ChocolateTemperature" with your registered data type
DDSTopic *temperature_topic = participant->create_topic(
CHOCOLATE_TEMPERATURE_TOPIC,
temperature_type_name,
DDS_TOPIC_QOS_DEFAULT,
NULL /* listener */,
DDS_STATUS_MASK_NONE);
if (temperature_topic == NULL) {
shutdown(participant, "create_topic error", EXIT_FAILURE);
}
// Create Publisher and DataWriter
// A Publisher allows an application to create one or more DataWriters
// Publisher QoS is configured in USER_QOS_PROFILES.xml
DDSPublisher *publisher = participant->create_publisher(
DDS_PUBLISHER_QOS_DEFAULT,
NULL /* listener */,
DDS_STATUS_MASK_NONE);
if (publisher == NULL) {
return shutdown(participant, "create_publisher error", EXIT_FAILURE);
}
// This DataWriter writes data on Topic "ChocolateLotState"
// DataWriter QoS is configured in USER_QOS_PROFILES.xml
// Exercise #4.1: Load ChocolateLotState DataWriter QoS profile after
// debugging incompatible QoS
DDSDataWriter *generic_lot_state_writer = publisher->create_datawriter(
lot_state_topic,
DDS_DATAWRITER_QOS_DEFAULT,
NULL /* listener */,
DDS_STATUS_MASK_NONE);
if (generic_lot_state_writer == NULL) {
return shutdown(participant, "create_datawriter error", EXIT_FAILURE);
}
// A narrow is a cast from a generic DataWriter to one that is specific
// to your type. Use the type specific DataWriter to write()
ChocolateLotStateDataWriter *lot_state_writer =
ChocolateLotStateDataWriter::narrow(generic_lot_state_writer);
if (lot_state_writer == NULL) {
return shutdown(participant, "DataWriter narrow error", EXIT_FAILURE);
}
// Create Subscriber and DataReaders
// A Subscriber allows an application to create one or more DataReaders
// Subscriber QoS is configured in USER_QOS_PROFILES.xml
DDSSubscriber *subscriber = participant->create_subscriber(
DDS_SUBSCRIBER_QOS_DEFAULT,
NULL /* listener */,
DDS_STATUS_MASK_NONE);
if (subscriber == NULL) {
shutdown(participant, "create_subscriber error", EXIT_FAILURE);
}
// This DataReader reads data of type ChocolateLotState on Topic
// "ChocolateLotState". DataReader QoS is configured in
// USER_QOS_PROFILES.xml
// Exercise #1.3: Update the lot_state_reader to use correct QoS
DDSDataReader *lot_state_generic_reader = subscriber->create_datareader(
lot_state_topic,
DDS_DATAREADER_QOS_DEFAULT,
NULL,
DDS_STATUS_MASK_NONE);
if (lot_state_generic_reader == NULL) {
shutdown(participant, "create_datareader error", EXIT_FAILURE);
}
// Get status condition: Each entity has a Status Condition, which
// gets triggered when a status becomes true
DDSStatusCondition *lot_state_status_condition =
lot_state_generic_reader->get_statuscondition();
if (lot_state_status_condition == NULL) {
shutdown(participant, "get_statuscondition error", EXIT_FAILURE);
}
// Enable only the status we are interested in:
// DDS_DATA_AVAILABLE_STATUS
retcode = lot_state_status_condition->set_enabled_statuses(
DDS_DATA_AVAILABLE_STATUS);
if (retcode != DDS_RETCODE_OK) {
shutdown(participant, "set_enabled_statuses error", EXIT_FAILURE);
}
// This DataReader reads data of type Temperature on Topic
// "ChocolateTemperature". DataReader QoS is configured in
// USER_QOS_PROFILES.xml
// Exercise #1.4: Update the lot_state_reader to use correct QoS
DDSDataReader *temperature_generic_reader = subscriber->create_datareader(
temperature_topic,
DDS_DATAREADER_QOS_DEFAULT,
NULL,
DDS_STATUS_MASK_NONE);
if (temperature_generic_reader == NULL) {
shutdown(participant, "create_datareader error", EXIT_FAILURE);
}
// Get status condition: Each entity has a Status Condition, which
// gets triggered when a status becomes true
DDSStatusCondition *temperature_status_condition =
temperature_generic_reader->get_statuscondition();
if (temperature_status_condition == NULL) {
shutdown(participant, "get_statuscondition error", EXIT_FAILURE);
}
// Enable only the status we are interested in:
// DDS_DATA_AVAILABLE_STATUS
retcode = temperature_status_condition->set_enabled_statuses(
DDS_DATA_AVAILABLE_STATUS);
if (retcode != DDS_RETCODE_OK) {
shutdown(participant, "set_enabled_statuses error", EXIT_FAILURE);
}
// Create the WaitSet and attach the Status Condition to it. The WaitSet
// will be woken when the condition is triggered.
DDSWaitSet waitset;
retcode = waitset.attach_condition(lot_state_status_condition);
if (retcode != DDS_RETCODE_OK) {
shutdown(participant, "attach_condition error", EXIT_FAILURE);
}
// Temperature condition
retcode = waitset.attach_condition(temperature_status_condition);
if (retcode != DDS_RETCODE_OK) {
shutdown(participant, "attach_condition error", EXIT_FAILURE);
}
// A narrow is a cast from a generic DataReader to one that is specific
// to your type. Use the type specific DataReader to read data
ChocolateLotStateDataReader *lot_state_reader =
ChocolateLotStateDataReader::narrow(lot_state_generic_reader);
if (lot_state_reader == NULL) {
shutdown(participant, "DataReader narrow error", EXIT_FAILURE);
}
TemperatureDataReader *temperature_reader =
TemperatureDataReader::narrow(temperature_generic_reader);
if (temperature_reader == NULL) {
shutdown(participant, "DataReader narrow error", EXIT_FAILURE);
}
// Create a thread to periodically start new chocolate lots
StartLotThreadData thread_data;
thread_data.writer = lot_state_writer;
thread_data.lots_to_process = sample_count;
OSThread thread((ThreadFunction) publish_start_lot, (void *) &thread_data);
thread.run();
// Main loop. Wait for data to arrive, and process when it arrives.
// ----------------------------------------------------------------
unsigned int samples_read = 0;
while (!shutdown_requested && samples_read < sample_count) {
DDSConditionSeq active_conditions_seq;
// wait() blocks execution of the thread until one or more attached
// Conditions become true, or until a user-specified timeout expires.
DDS_Duration_t wait_timeout = { 15, 0 };
retcode = waitset.wait(active_conditions_seq, wait_timeout);
// You get a timeout if no conditions were triggered before the timeout
if (retcode == DDS_RETCODE_TIMEOUT) {
std::cout << "Wait timed out after 10 seconds." << std::endl;
continue;
} else if (retcode != DDS_RETCODE_OK) {
std::cerr << "wait returned error: " << retcode << std::endl;
break;
}
// Get the status changes to check which status condition
// triggered the WaitSet to wake
DDS_StatusMask triggeredmask = lot_state_reader->get_status_changes();
// If the ChocolateLotState DataReader received DATA_AVAILABLE event
// notification
if (triggeredmask & DDS_DATA_AVAILABLE_STATUS) {
samples_read += monitor_lot_state(lot_state_reader);
}
// Check if the temperature DataReader received DATA_AVAILABLE event
// notification
triggeredmask = temperature_reader->get_status_changes();
if (triggeredmask & DDS_DATA_AVAILABLE_STATUS) {
monitor_temperature(temperature_reader);
}
}
// Cleanup
// -------
thread.join();
// Delete all entities (DataReader, Topic, Subscriber, DomainParticipant)
return shutdown(participant, "shutting down", 0);
}
// Delete all entities
int shutdown(
DDSDomainParticipant *participant,
const char *shutdown_message,
int status)
{
DDS_ReturnCode_t retcode;
std::cout << shutdown_message << std::endl;
if (participant != NULL) {
// This includes everything created by this Participant, including
// DataWriters, Topics, Publishers. (and Subscribers and DataReaders)
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_example(arguments.domain_id, arguments.sample_count);
// Releases the memory used by the participant factory. Optional at
// application shutdown
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-getting-started
|
data/projects/rticonnextdds-getting-started/5_basic_qos/c++98/tempering_application.cxx
|
/*
* (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.
*/
#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include "chocolate_factory.h"
#include "chocolate_factorySupport.h"
#include "ndds/ndds_cpp.h"
#include "application.h"
using namespace application;
// Tempering application:
// 1) Publishes the temperature
// 2) Subscribes to the lot state
// 3) After "processing" the lot, publishes the lot state
static int shutdown(
DDSDomainParticipant *participant,
const char *shutdown_message,
int status);
// Structure to hold data for write thread
struct TemperatureWriteData {
TemperatureDataWriter *writer;
const char *sensor_id;
};
void publish_temperature(const TemperatureWriteData *write_data)
{
TemperatureDataWriter *writer = write_data->writer;
// Create temperature sample for writing
Temperature temperature;
TemperatureTypeSupport::initialize_data(&temperature);
while (!shutdown_requested) {
// Modify the data to be written here
snprintf(temperature.sensor_id, 255, "%s", write_data->sensor_id);
temperature.degrees = rand() % 3 + 30; // Random num between 30 and 32
DDS_ReturnCode_t retcode = writer->write(temperature, DDS_HANDLE_NIL);
if (retcode != DDS_RETCODE_OK) {
std::cerr << "write error " << retcode << std::endl;
}
// Update temperature every 100 ms
DDS_Duration_t send_period = { 0, 100000000 };
NDDSUtility::sleep(send_period);
}
TemperatureTypeSupport::finalize_data(&temperature);
}
void process_lot(
ChocolateLotStateDataReader *lot_state_reader,
ChocolateLotStateDataWriter *lot_state_writer)
{
// Take all samples. Samples are loaned to application, loan is
// returned when LoanedSamples destructor called.
ChocolateLotStateSeq data_seq;
DDS_SampleInfoSeq info_seq;
// Take available data from DataReader's queue
DDS_ReturnCode_t retcode = lot_state_reader->take(data_seq, info_seq);
if (retcode != DDS_RETCODE_OK && retcode != DDS_RETCODE_NO_DATA) {
std::cerr << "take error " << retcode << std::endl;
return;
}
// Process lots waiting for tempering
for (int i = 0; i < data_seq.length(); ++i) {
// Check if a sample is an instance lifecycle event
if (info_seq[i].valid_data) {
if (data_seq[i].next_station == TEMPERING_CONTROLLER) {
std::cout << "Processing lot #" << data_seq[i].lot_id
<< std::endl;
// Send an update that the tempering station is processing lot
ChocolateLotState updated_state(data_seq[i]);
updated_state.lot_status = PROCESSING;
updated_state.next_station = INVALID_CONTROLLER;
updated_state.station = TEMPERING_CONTROLLER;
DDS_ReturnCode_t retcode =
lot_state_writer->write(updated_state, DDS_HANDLE_NIL);
if (retcode != DDS_RETCODE_OK) {
std::cerr << "write error " << retcode << std::endl;
}
// "Processing" the lot.
DDS_Duration_t processing_time = { 5, 0 };
NDDSUtility::sleep(processing_time);
// Since this is the last step in processing, notify the
// monitoring application that the lot is complete using a
// dispose
retcode = lot_state_writer->dispose(
updated_state,
DDS_HANDLE_NIL);
std::cout << "Lot completed" << std::endl;
}
} else {
// Received instance state notification
continue;
}
}
// Data sequence was loaned from middleware for performance.
// Return loan when application is finished with data.
retcode = lot_state_reader->return_loan(data_seq, info_seq);
if (retcode != DDS_RETCODE_OK) {
std::cerr << "return_loan error " << retcode << std::endl;
}
}
void on_requested_incompatible_qos(DDSDataReader *reader)
{
DDS_RequestedIncompatibleQosStatus status;
reader->get_requested_incompatible_qos_status(status);
// Exercise #3.1 add a message to print when this DataReader discovers an
// incompatible DataWriter
}
int run_example(
unsigned int domain_id,
unsigned int sample_count,
const char *sensor_id)
{
// Load XML QoS from a specific file
DDSDomainParticipantFactory *factory =
DDSDomainParticipantFactory::get_instance();
DDS_DomainParticipantFactoryQos factoryQos;
DDS_ReturnCode_t retcode = factory->get_qos(factoryQos);
if (retcode != DDS_RETCODE_OK) {
return shutdown(NULL, "get_qos error", EXIT_FAILURE);
}
const char *url_profiles[1] = {
"qos_profiles.xml" };
factoryQos.profile.url_profile.from_array(url_profiles, 1);
factory->set_qos(factoryQos);
// Connext DDS setup
// -----------------
// A DomainParticipant allows an application to begin communicating in
// a DDS domain. Typically there is one DomainParticipant per application.
// Uses TemperingApplication QoS profile to set participant name.
DDSDomainParticipant *participant =
DDSTheParticipantFactory->create_participant_with_profile(
domain_id,
"ChocolateFactoryLibrary",
"TemperingApplication",
NULL /* listener */,
DDS_STATUS_MASK_NONE);
if (participant == NULL) {
return shutdown(participant, "create_participant error", EXIT_FAILURE);
}
// Create Topics
// Register the datatype to use when creating the Topic
const char *temperature_type_name = TemperatureTypeSupport::get_type_name();
retcode = TemperatureTypeSupport::register_type(
participant,
temperature_type_name);
if (retcode != DDS_RETCODE_OK) {
return shutdown(participant, "register_type error", EXIT_FAILURE);
}
const char *lot_state_type_name =
ChocolateLotStateTypeSupport::get_type_name();
retcode = ChocolateLotStateTypeSupport::register_type(
participant,
lot_state_type_name);
if (retcode != DDS_RETCODE_OK) {
return shutdown(participant, "register_type error", EXIT_FAILURE);
}
// A Topic has a name and a datatype. Create a Topic called
// "ChocolateTemperature" with your registered temperature data type
DDSTopic *temperature_topic = participant->create_topic(
CHOCOLATE_TEMPERATURE_TOPIC,
temperature_type_name,
DDS_TOPIC_QOS_DEFAULT,
NULL /* listener */,
DDS_STATUS_MASK_NONE);
if (temperature_topic == NULL) {
return shutdown(participant, "create_topic error", EXIT_FAILURE);
}
// A Topic has a name and a datatype. Create a Topic called
// "ChocolateLotState" with your registered ChocolateLotState data type
DDSTopic *lot_state_topic = participant->create_topic(
CHOCOLATE_LOT_STATE_TOPIC,
lot_state_type_name,
DDS_TOPIC_QOS_DEFAULT,
NULL /* listener */,
DDS_STATUS_MASK_NONE);
if (lot_state_topic == NULL) {
return shutdown(participant, "create_topic error", EXIT_FAILURE);
}
// Create Publisher and DataWriters
// A Publisher allows an application to create one or more DataWriters
// Publisher QoS is configured with default QoS
DDSPublisher *publisher = participant->create_publisher(
DDS_PUBLISHER_QOS_DEFAULT,
NULL /* listener */,
DDS_STATUS_MASK_NONE);
if (publisher == NULL) {
return shutdown(participant, "create_publisher error", EXIT_FAILURE);
}
// This DataWriter writes data on Topic "ChocolateTemperature" DataWriter
// QoS is configured using ChocolateTemperatureProfile QoS profile
DDSDataWriter *generic_temp_writer = publisher->create_datawriter_with_profile(
temperature_topic,
"ChocolateFactoryLibrary",
"ChocolateTemperatureProfile",
NULL /* listener */,
DDS_STATUS_MASK_NONE);
if (generic_temp_writer == NULL) {
return shutdown(participant, "create_datawriter error", EXIT_FAILURE);
}
// This DataWriter writes data on Topic "ChocolateLotState". DataWriter
// QoS is configured using ChocolateTemperatureProfile QoS profile
DDSDataWriter *generic_lot_state_writer =
publisher->create_datawriter_with_profile(
lot_state_topic,
"ChocolateFactoryLibrary",
"ChocolateLotStateProfile",
NULL /* listener */,
DDS_STATUS_MASK_NONE);
if (generic_lot_state_writer == NULL) {
return shutdown(participant, "create_datawriter error", EXIT_FAILURE);
}
// A narrow is a cast from a generic DataWriter to one that is specific
// to your type. Use the type specific DataWriter to write()
TemperatureDataWriter *temperature_writer =
TemperatureDataWriter::narrow(generic_temp_writer);
if (temperature_writer == NULL) {
return shutdown(participant, "DataWriter narrow error", EXIT_FAILURE);
}
ChocolateLotStateDataWriter *lot_state_writer =
ChocolateLotStateDataWriter::narrow(generic_lot_state_writer);
if (lot_state_writer == NULL) {
return shutdown(participant, "DataWriter narrow error", EXIT_FAILURE);
}
// Create Subscriber and DataReader
// A Subscriber allows an application to create one or more DataReaders
// Subscriber QoS is configured with default QoS
DDSSubscriber *subscriber = participant->create_subscriber(
DDS_SUBSCRIBER_QOS_DEFAULT,
NULL /* listener */,
DDS_STATUS_MASK_NONE);
if (subscriber == NULL) {
shutdown(participant, "create_subscriber error", EXIT_FAILURE);
}
// This DataReader reads data of type Temperature on Topic
// "ChocolateTemperature" using ChocolateTemperatureProfile QoS profile
DDSDataReader *generic_lot_state_reader =
subscriber->create_datareader_with_profile(
lot_state_topic,
"ChocolateFactoryLibrary",
"ChocolateLotStateProfile",
NULL,
DDS_STATUS_MASK_NONE);
if (generic_lot_state_reader == NULL) {
shutdown(participant, "create_datareader error", EXIT_FAILURE);
}
// Get status condition: Each entity has a Status Condition, which
// gets triggered when a status becomes true
DDSStatusCondition *status_condition =
generic_lot_state_reader->get_statuscondition();
if (status_condition == NULL) {
shutdown(participant, "get_statuscondition error", EXIT_FAILURE);
}
// Enable only the statuses we are interested in:
// DDS_DATA_AVAILABLE_STATUS, DDS_REQUESTED_INCOMPATIBLE_QOS_STATUS
retcode = status_condition->set_enabled_statuses(
DDS_DATA_AVAILABLE_STATUS | DDS_REQUESTED_INCOMPATIBLE_QOS_STATUS);
if (retcode != DDS_RETCODE_OK) {
shutdown(participant, "set_enabled_statuses error", EXIT_FAILURE);
}
// Create the WaitSet and attach the Status Condition to it. The WaitSet
// will be woken when the condition is triggered.
DDSWaitSet waitset;
retcode = waitset.attach_condition(status_condition);
if (retcode != DDS_RETCODE_OK) {
shutdown(participant, "attach_condition error", EXIT_FAILURE);
}
// A narrow is a cast from a generic DataReader to one that is specific
// to your type. Use the type specific DataReader to read data
ChocolateLotStateDataReader *lot_state_reader =
ChocolateLotStateDataReader::narrow(generic_lot_state_reader);
if (lot_state_reader == NULL) {
shutdown(participant, "DataReader narrow error", EXIT_FAILURE);
}
// Create thread to periodically write temperature data
TemperatureWriteData write_data;
write_data.writer = temperature_writer;
write_data.sensor_id = sensor_id;
OSThread thread((ThreadFunction) publish_temperature, (void *) &write_data);
std::cout << "ChocolateTemperature Sensor with ID: " << write_data.sensor_id
<< " starting" << std::endl;
thread.run();
// Main loop, wait for lots
// ------------------------
while (!shutdown_requested) {
// Wait for ChocolateLotState
std::cout << "Waiting for lot" << std::endl;
// wait() blocks execution of the thread until one or more attached
// Conditions become true, or until a user-specified timeout expires.
DDSConditionSeq active_conditions_seq;
DDS_Duration_t wait_timeout = { 10, 0 };
retcode = waitset.wait(active_conditions_seq, wait_timeout);
// You get a timeout if no conditions were triggered before the timeout
if (retcode == DDS_RETCODE_TIMEOUT) {
std::cout << "Wait timed out after 10 seconds." << std::endl;
continue;
} else if (retcode != DDS_RETCODE_OK) {
std::cerr << "wait returned error: " << retcode << std::endl;
break;
}
// Get the status changes to check which status condition
// triggered the WaitSet to wake
DDS_StatusMask triggered_mask = lot_state_reader->get_status_changes();
// If the status is "Data Available"
if (triggered_mask & DDS_DATA_AVAILABLE_STATUS) {
process_lot(lot_state_reader, lot_state_writer);
}
if (triggered_mask & DDS_REQUESTED_INCOMPATIBLE_QOS_STATUS) {
on_requested_incompatible_qos(lot_state_reader);
}
}
// Cleanup
// -------
thread.join();
// Delete all entities (DataWriter, Topic, Publisher, DomainParticipant)
return shutdown(participant, "shutting down", EXIT_SUCCESS);
}
// Delete all entities
int shutdown(
DDSDomainParticipant *participant,
const char *shutdown_message,
int status)
{
DDS_ReturnCode_t retcode;
std::cout << shutdown_message << std::endl;
if (participant != NULL) {
// This includes everything created by this Participant, including
// DataWriters, Topics, Publishers. (and Subscribers and DataReaders)
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_example(
arguments.domain_id,
arguments.sample_count,
arguments.sensor_id);
// Releases the memory used by the participant factory. Optional at
// application shutdown
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-getting-started
|
data/projects/rticonnextdds-getting-started/5_basic_qos/c++98/application.h
|
/*
* (c) Copyright, Real-Time Innovations, 2020. All rights reserved.
* RTI grants Licensee a license to use, modify, compile, and create derivative
* works of the software solely for use with RTI Connext DDS. Licensee may
* redistribute copies of the software provided that all such copies are subject
* to this license. The software is provided "as is", with no warranty of any
* type, including any warranty for fitness for any purpose. RTI is under no
* obligation to maintain or support the software. RTI shall not be liable for
* any incidental or consequential damages arising out of the use or inability
* to use the software.
*/
#ifndef APPLICATION_H
#define APPLICATION_H
#include <iostream>
#include <csignal>
#include <ctime>
#include <limits>
#ifdef RTI_WIN32
/* strtok, fopen warnings */
#pragma warning( disable : 4996 )
#endif
#ifdef RTI_WIN32
#define DllExport __declspec( dllexport )
#include <Winsock2.h>
#include <process.h>
#else
#define DllExport
#include <sys/select.h>
#include <semaphore.h>
#include <pthread.h>
#endif
#include "ndds/ndds_cpp.h"
#include "chocolate_factoryPlugin.h"
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);
}
// A function that takes a void pointer, and is passed to the thread creation
// function.
typedef void* (*ThreadFunction)(void *);
class OSThread
{
public:
OSThread(ThreadFunction function, void *function_param):
function(function),
function_param(function_param)
{
}
// Run the thread
void run()
{
#ifdef RTI_WIN32
thread = (HANDLE) _beginthread(
(void(__cdecl*)(void*))function,
0, (void*)function_param);
#else
pthread_attr_t thread_attr;
pthread_attr_init(&thread_attr);
pthread_attr_setdetachstate(&thread_attr, PTHREAD_CREATE_JOINABLE);
int error = pthread_create(
&thread,
&thread_attr,
function,
(void *)function_param);
pthread_attr_destroy(&thread_attr);
#endif
}
// Join the thread
void join()
{
#ifdef RTI_WIN32
WaitForSingleObject(thread, INFINITE);
#else
void *ret_val;
int error = pthread_join(thread, &ret_val);
#endif
}
private:
// OS-specific thread definition
#ifdef RTI_WIN32
HANDLE thread;
#else
pthread_t thread;
#endif
// Function called by OS-specific thread
ThreadFunction function;
// Parameter to the function
void *function_param;
};
inline void print_station_kind(StationKind station_kind)
{
switch(station_kind) {
case INVALID_CONTROLLER:
std::cout << "INVALID_CONTROLLER";
break;
case SUGAR_CONTROLLER:
std::cout << "SUGAR_CONTROLLER";
break;
case COCOA_BUTTER_CONTROLLER:
std::cout << "COCOA_BUTTER_CONTROLLER";
break;
case VANILLA_CONTROLLER:
std::cout << "VANILLA_CONTROLLER";
break;
case MILK_CONTROLLER:
std::cout << "MILK_CONTROLLER";
break;
case TEMPERING_CONTROLLER:
std::cout << "TEMPERING_CONTROLLER";
break;
}
}
inline void print_lot_status_kind(LotStatusKind lot_status_kind)
{
switch(lot_status_kind)
{
case WAITING:
std::cout << "WAITING";
break;
case PROCESSING:
std::cout << "PROCESSING";
break;
case COMPLETED:
std::cout << "COMPLETED";
break;
}
}
inline void print_chocolate_lot_data(const ChocolateLotState& sample)
{
std::cout << "[" << "lot_id: " << sample.lot_id << ", " << "station: ";
print_station_kind(sample.station);
std::cout << ", next_station: ";
print_station_kind(sample.next_station);
std::cout << ", lot_status: ";
print_lot_status_kind(sample.lot_status);
std::cout << "]" << std::endl;
}
enum ParseReturn { PARSE_RETURN_OK, PARSE_RETURN_FAILURE, PARSE_RETURN_EXIT };
struct ApplicationArguments {
ParseReturn parse_result;
unsigned int domain_id;
unsigned int sample_count;
char sensor_id[256];
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 = (std::numeric_limits<unsigned int>::max)();
arguments.verbosity = NDDS_CONFIG_LOG_VERBOSITY_ERROR;
arguments.parse_result = PARSE_RETURN_OK;
// Initialize with an integer value
srand((unsigned int)time(NULL));
snprintf(arguments.sensor_id, 255, "%d", rand() % 10);
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], "-i") == 0
|| strcmp(argv[arg_processing], "--sensor-id") == 0)) {
snprintf(arguments.sensor_id, 255, "%s", 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"
" -i, --sensor-id <string> Unique ID of temperature sensor.\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-getting-started
|
data/projects/rticonnextdds-getting-started/5_basic_qos/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 <string>
#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;
std::string sensor_id;
rti::config::Verbosity verbosity;
};
// 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)();
srand((unsigned int)time(NULL));
std::string sensor_id = std::to_string(rand() % 50);
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 ((argc > arg_processing + 1)
&& (strcmp(argv[arg_processing], "-i") == 0
|| strcmp(argv[arg_processing], "--sensor-id") == 0)) {
sensor_id = 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"
" cleanly shutting down. \n"
" -i, --sensor-id <string> Unique ID of temperature sensor.\n"\
" -v, --verbosity <int> How much debugging output to show.\n"\
" Range: 0-5 \n"
" Default: 0"
<< std::endl;
}
return { parse_result, domain_id, sample_count, sensor_id, verbosity };
}
} // namespace application
#endif // APPLICATION_HPP
|
hpp
|
rticonnextdds-getting-started
|
data/projects/rticonnextdds-getting-started/5_basic_qos/c++11/monitoring_ctrl_application.cxx
|
/*
* (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.
*/
#include <iostream>
#include <thread>
#include <dds/pub/ddspub.hpp>
#include <dds/sub/ddssub.hpp>
#include <rti/util/util.hpp> // for sleep()
#include <rti/config/Logger.hpp> // for logging
// Or simply include <dds/dds.hpp>
#include "chocolate_factory.hpp"
#include "application.hpp" // Argument parsing
using namespace application;
void publish_start_lot(
dds::pub::DataWriter<ChocolateLotState> lot_state_writer,
unsigned int lots_to_process)
{
ChocolateLotState sample;
for (unsigned int count = 0; !shutdown_requested && count < lots_to_process;
count++) {
// Set the values for a chocolate lot that is going to be sent to wait
// at the tempering station
sample.lot_id(count % 100);
sample.lot_status(LotStatusKind::WAITING);
sample.next_station(StationKind::TEMPERING_CONTROLLER);
std::cout << std::endl << "Starting lot: " << std::endl;
std::cout << "[lot_id: " << sample.lot_id()
<< " next_station: " << sample.next_station() << "]"
<< std::endl;
// Send an update to station that there is a lot waiting for tempering
lot_state_writer.write(sample);
rti::util::sleep(dds::core::Duration(10));
}
}
unsigned int monitor_lot_state(dds::sub::DataReader<ChocolateLotState>& reader)
{
// Take all samples. Samples are loaned to application, loan is
// returned when LoanedSamples destructor called.
unsigned int samples_read = 0;
dds::sub::LoanedSamples<ChocolateLotState> samples = reader.take();
// Receive updates from stations about the state of current lots
for (const auto& sample : samples) {
std::cout << "Received Lot Update:" << std::endl;
if (sample.info().valid()) {
std::cout << sample.data() << std::endl;
samples_read++;
} else {
// Detect that a lot is complete by checking for
// the disposed state.
if (sample.info().state().instance_state()
== dds::sub::status::InstanceState::not_alive_disposed()) {
ChocolateLotState key_holder;
// Fills in only the key field values associated with the
// instance
reader.key_value(key_holder, sample.info().instance_handle());
std::cout << "[lot_id: " << key_holder.lot_id()
<< " is completed]" << std::endl;
}
}
}
return samples_read;
}
// Add monitor_temperature function
void monitor_temperature(dds::sub::DataReader<Temperature>& reader)
{
// Take all samples. Samples are loaned to application, loan is
// returned when LoanedSamples destructor called.
dds::sub::LoanedSamples<Temperature> samples = reader.take();
// Receive updates from tempering station about chocolate temperature.
// Only an error if over 32 degrees Fahrenheit.
for (const auto& sample : samples) {
if (sample.info().valid()) {
if (sample.data().degrees() > 32) {
std::cout << "Temperature high: " << sample.data() << std::endl;
}
}
}
}
void run_example(unsigned int domain_id, unsigned int lots_to_process)
{
// Exercise #1.1: Add QoS provider
// A DomainParticipant allows an application to begin communicating in
// a DDS domain. Typically there is one DomainParticipant per application.
// Exercise #1.2: Load DomainParticipant QoS profile
dds::domain::DomainParticipant participant(domain_id);
// A Topic has a name and a datatype. Create a Topic with type
// ChocolateLotState. Topic name is a constant defined in the IDL file.
dds::topic::Topic<ChocolateLotState> topic(
participant,
CHOCOLATE_LOT_STATE_TOPIC);
// Add a Topic for Temperature to this application
dds::topic::Topic<Temperature> temperature_topic(
participant,
CHOCOLATE_TEMPERATURE_TOPIC);
// A Publisher allows an application to create one or more DataWriters
// Publisher QoS is configured in USER_QOS_PROFILES.xml
dds::pub::Publisher publisher(participant);
// This DataWriter writes data on Topic "ChocolateLotState"
// Exercise #4.1: Load ChocolateLotState DataWriter QoS profile after
// debugging incompatible QoS
dds::pub::DataWriter<ChocolateLotState> lot_state_writer(publisher, topic);
// A Subscriber allows an application to create one or more DataReaders
// Subscriber QoS is configured in USER_QOS_PROFILES.xml
dds::sub::Subscriber subscriber(participant);
// Create DataReader of Topic "ChocolateLotState".
// Exercise #1.3: Update the lot_state_reader and temperature_reader
// to use correct QoS
dds::sub::DataReader<ChocolateLotState> lot_state_reader(subscriber, topic);
// Add a DataReader for Temperature to this application
dds::sub::DataReader<Temperature> temperature_reader(
subscriber,
temperature_topic);
// Obtain the DataReader's Status Condition
dds::core::cond::StatusCondition temperature_status_condition(
temperature_reader);
// Enable the 'data available' status.
temperature_status_condition.enabled_statuses(
dds::core::status::StatusMask::data_available());
// Associate a handler with the status condition. This will run when the
// condition is triggered, in the context of the dispatch call (see below)
temperature_status_condition.extensions().handler(
[&temperature_reader, &temperature_status_condition]() {
monitor_temperature(temperature_reader);
});
// Obtain the DataReader's Status Condition
dds::core::cond::StatusCondition lot_state_status_condition(
lot_state_reader);
// Enable the 'data available' status.
lot_state_status_condition.enabled_statuses(
dds::core::status::StatusMask::data_available());
// Associate a handler with the status condition. This will run when the
// condition is triggered, in the context of the dispatch call (see below)
unsigned int lots_processed = 0;
lot_state_status_condition.extensions().handler(
[&lot_state_reader, &lots_processed]() {
lots_processed += monitor_lot_state(lot_state_reader);
});
// Create a WaitSet and attach the StatusCondition
dds::core::cond::WaitSet waitset;
waitset += lot_state_status_condition;
// Add the new DataReader's StatusCondition to the Waitset
waitset += temperature_status_condition;
// Create a thread to periodically start new chocolate lots
std::thread start_lot_thread(
publish_start_lot,
lot_state_writer,
lots_to_process);
while (!shutdown_requested && lots_processed < lots_to_process) {
// Dispatch will call the handlers associated to the WaitSet conditions
// when they activate
waitset.dispatch(dds::core::Duration(10)); // Wait up to 10s each time
}
start_lot_thread.join();
}
int main(int argc, char *argv[])
{
// 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_example(arguments.domain_id, arguments.sample_count);
} catch (const std::exception& ex) {
// This will catch DDS exceptions
std::cerr << "Exception in run_example(): " << ex.what() << std::endl;
return EXIT_FAILURE;
}
// Releases the memory used by the participant factory. Optional at
// application shutdown
dds::domain::DomainParticipant::finalize_participant_factory();
return EXIT_SUCCESS;
}
|
cxx
|
rticonnextdds-getting-started
|
data/projects/rticonnextdds-getting-started/5_basic_qos/c++11/tempering_application.cxx
|
/*
* (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.
*/
#include <iostream>
#include <thread>
#include <dds/pub/ddspub.hpp>
#include <dds/sub/ddssub.hpp>
#include <rti/util/util.hpp> // for sleep()
#include <rti/config/Logger.hpp> // for logging
// Or simply include <dds/dds.hpp>
#include "chocolate_factory.hpp"
#include "application.hpp" // Argument parsing
using namespace application;
// Tempering application:
// 1) Publishes the temperature
// 2) Subscribes to the lot state
// 3) After "processing" the lot, publishes the lot state
void publish_temperature(
dds::pub::DataWriter<Temperature> temperature_writer,
const std::string sensor_id)
{
// Create temperature sample for writing
Temperature temperature;
while (!shutdown_requested) {
// Modify the data to be written here
temperature.sensor_id(sensor_id);
temperature.degrees(rand() % 3 + 30); // Random value between 30 and 32
temperature_writer.write(temperature);
rti::util::sleep(dds::core::Duration::from_millisecs(100));
}
}
void process_lot(
dds::sub::DataReader<ChocolateLotState>& lot_state_reader,
dds::pub::DataWriter<ChocolateLotState>& lot_state_writer)
{
// Take all samples. Samples are loaned to application, loan is
// returned when LoanedSamples destructor called.
dds::sub::LoanedSamples<ChocolateLotState> samples =
lot_state_reader.take();
// Process lots waiting for tempering
for (const auto& sample : samples) {
if (sample.info().valid()
&& sample.data().next_station()
== StationKind::TEMPERING_CONTROLLER) {
std::cout << "Processing lot #" << sample.data().lot_id()
<< std::endl;
// Send an update that the tempering station is processing lot
ChocolateLotState updated_state(sample.data());
updated_state.lot_status(LotStatusKind::PROCESSING);
updated_state.next_station(StationKind::INVALID_CONTROLLER);
updated_state.station(StationKind::TEMPERING_CONTROLLER);
lot_state_writer.write(updated_state);
// "Processing" the lot.
rti::util::sleep(dds::core::Duration(5));
// Since this is the last step in processing,
// notify the monitoring application that the lot is complete
// using a dispose
dds::core::InstanceHandle instance_handle =
lot_state_writer.lookup_instance(updated_state);
lot_state_writer.dispose_instance(instance_handle);
std::cout << "Lot completed" << std::endl;
}
}
} // The LoanedSamples destructor returns the loan
template <typename T>
void on_requested_incompatible_qos(dds::sub::DataReader<T>& reader)
{
using namespace dds::core::policy;
QosPolicyId incompatible_policy =
reader.requested_incompatible_qos_status().last_policy_id();
// Exercise #3.1 add a message to print when this DataReader discovers an
// incompatible DataWriter
}
void run_example(unsigned int domain_id, const std::string& sensor_id)
{
// Loads the QoS from the qos_profiles.xml file.
dds::core::QosProvider qos_provider("./qos_profiles.xml");
// A DomainParticipant allows an application to begin communicating in
// a DDS domain. Typically there is one DomainParticipant per application.
// Uses TemperingApplication QoS profile to set participant name.
dds::domain::DomainParticipant participant(
domain_id,
qos_provider.participant_qos(
"ChocolateFactoryLibrary::TemperingApplication"));
// A Topic has a name and a datatype. Create Topics.
// Topic names are constants defined in the IDL file.
dds::topic::Topic<Temperature> temperature_topic(
participant,
CHOCOLATE_TEMPERATURE_TOPIC);
dds::topic::Topic<ChocolateLotState> lot_state_topic(
participant,
CHOCOLATE_LOT_STATE_TOPIC);
// A Publisher allows an application to create one or more DataWriters
// Create Publisher with default QoS
dds::pub::Publisher publisher(participant);
// Create DataWriter of Topic "ChocolateTemperature"
// using ChocolateTemperatureProfile QoS profile for Streaming Data
dds::pub::DataWriter<Temperature> temperature_writer(
publisher,
temperature_topic,
qos_provider.datawriter_qos(
"ChocolateFactoryLibrary::ChocolateTemperatureProfile"));
// Create DataWriter of Topic "ChocolateLotState"
// using ChocolateLotStateProfile QoS profile for State Data
dds::pub::DataWriter<ChocolateLotState> lot_state_writer(
publisher,
lot_state_topic,
qos_provider.datawriter_qos(
"ChocolateFactoryLibrary::ChocolateLotStateProfile"));
// A Subscriber allows an application to create one or more DataReaders
dds::sub::Subscriber subscriber(participant);
// Create DataReader of Topic "ChocolateLotState".
// using ChocolateLotStateProfile QoS profile for State Data
dds::sub::DataReader<ChocolateLotState> lot_state_reader(
subscriber,
lot_state_topic,
qos_provider.datareader_qos(
"ChocolateFactoryLibrary::ChocolateLotStateProfile"));
// Obtain the DataReader's Status Condition
dds::core::cond::StatusCondition reader_status_condition(lot_state_reader);
// Contains statuses that entities can be notified about
using dds::core::status::StatusMask;
// Enable the 'data available' and 'requested incompatible qos' statuses
reader_status_condition.enabled_statuses(
StatusMask::data_available()
| StatusMask::requested_incompatible_qos());
// Associate a handler with the status condition. This will run when the
// condition is triggered, in the context of the dispatch call (see below)
reader_status_condition.extensions().handler([&lot_state_reader,
&lot_state_writer]() {
if ((lot_state_reader.status_changes() & StatusMask::data_available())
!= StatusMask::none()) {
process_lot(lot_state_reader, lot_state_writer);
}
if ((lot_state_reader.status_changes()
& StatusMask::requested_incompatible_qos())
!= StatusMask::none()) {
on_requested_incompatible_qos(lot_state_reader);
}
});
// Create a WaitSet and attach the StatusCondition
dds::core::cond::WaitSet waitset;
waitset += reader_status_condition;
// Create a thread to periodically write the temperature
std::cout << "ChocolateTemperature Sensor with ID: " << sensor_id
<< " starting" << std::endl;
std::thread temperature_thread(
publish_temperature,
temperature_writer,
sensor_id);
while (!shutdown_requested) {
// Wait for ChocolateLotState
std::cout << "Waiting for lot" << std::endl;
waitset.dispatch(dds::core::Duration(10)); // Wait up to 10s for update
}
temperature_thread.join();
}
int main(int argc, char *argv[])
{
// 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_example(arguments.domain_id, arguments.sensor_id);
} catch (const std::exception& ex) {
// This will catch DDS exceptions
std::cerr << "Exception in run_example(): " << ex.what() << std::endl;
return EXIT_FAILURE;
}
// Releases the memory used by the participant factory. Optional at
// application shutdown
dds::domain::DomainParticipant::finalize_participant_factory();
return EXIT_SUCCESS;
}
|
cxx
|
rticonnextdds-usecases
|
data/projects/rticonnextdds-usecases/VideoData/src/gst-connextsink/gstconnextsink.c
|
/*
* (c) 2023 Copyright, Real-Time Innovations, Inc. (RTI) All rights reserved.
*
* RTI grants Licensee a license to use, modify, compile, and create derivative
* works of the software. 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 <gst/gst.h>
#include <gst/video/gstvideosink.h>
#include <gst/video/video.h>
#include <stdio.h>
#include <string.h>
#include "gstconnextsink.h"
GST_DEBUG_CATEGORY_STATIC(gst_connextsink_debug_category);
#define GST_CAT_DEFAULT gst_connextsink_debug_category
#define PRINT_SIZE_EVERY_X_FRAMES 50
#define PROFILE_NAME_MAX_LEN 200
/* prototypes */
/* set gstreamer property */
static void gst_connextsink_set_property(GObject* object, guint property_id, const GValue* value, GParamSpec* pspec);
/* get gstreamer property */
static void gst_connextsink_get_property(GObject* object, guint property_id, GValue* value, GParamSpec* pspec);
/* dispose connextsink */
static void gst_connextsink_dispose(GObject* object);
/* finalize connext sink */
static void gst_connextsink_finalize(GObject* object);
/* write frame to connext */
static GstFlowReturn gst_connextsink_show_frame(GstVideoSink* video_sink, GstBuffer* buf);
/* parse qos profiles */
static int gst_connextsink_get_qos_library_profile(GstConnextSink* connextsink, gchar* qosProfile, char* qos_library_name, char* qos_profile_name);
/* initialize publisher */
static int gst_connextsink_publisher_init(GstConnextSink* connextsink);
/* shutdown publisher */
static int gst_connextsink_publisher_shutdown(DDS_DomainParticipant* participant);
/* element methods */
static GstStateChangeReturn gst_connextsink_change_state(GstElement* element, GstStateChange transition);
#define DEFAULT_QOS "BuiltinQosLibExp::Generic.StrictReliable"
enum
{
PROP_0,
PROP_CONNEXT_DOMAIN_ID,
PROP_CONNEXT_TOPIC,
PROP_CONNEXT_KEY,
PROP_CONNEXT_DP_QOS_PROFILE,
PROP_CONNEXT_DW_QOS_PROFILE,
PROP_CONNEXT_PRINT_FRAME_SIZE
};
#define CONNEXTSINK_VIDEO_CAPS \
GST_VIDEO_CAPS_MAKE(GST_VIDEO_FORMATS_ALL) \
";" \
"video/x-raw, format=(string) { bggr, rggb, grbg, gbrg }, " \
"width = " GST_VIDEO_SIZE_RANGE ", " \
"height = " GST_VIDEO_SIZE_RANGE ", " \
"framerate = " GST_VIDEO_FPS_RANGE ";" \
"video/x-h264, stream-format=(string) { avc, byte-stream }, " \
"width = " GST_VIDEO_SIZE_RANGE ", " \
"height = " GST_VIDEO_SIZE_RANGE ", " \
"framerate = " GST_VIDEO_FPS_RANGE
/* pad template */
static GstStaticPadTemplate gst_connextsink_sink_template =
GST_STATIC_PAD_TEMPLATE("sink", GST_PAD_SINK, GST_PAD_ALWAYS, GST_STATIC_CAPS_ANY);
/* class initialisation */
G_DEFINE_TYPE_WITH_CODE(
GstConnextSink,
gst_connextsink,
GST_TYPE_VIDEO_SINK,
GST_DEBUG_CATEGORY_INIT(gst_connextsink_debug_category, "connextsrc", 0, "debug category for connextsrc element"))
static void gst_connextsink_class_init(GstConnextSinkClass* class)
{
GObjectClass* gobject_class = G_OBJECT_CLASS(class);
GstElementClass* element_class = GST_ELEMENT_CLASS(class);
GstVideoSinkClass* video_sink_class = GST_VIDEO_SINK_CLASS(class);
/* Setting up pads and setting metadata should be moved to
base_class_init if you intend to subclass this class. */
gst_element_class_add_pad_template(GST_ELEMENT_CLASS(class),
gst_static_pad_template_get(&gst_connextsink_sink_template));
gst_element_class_set_static_metadata(GST_ELEMENT_CLASS(class),
"Connext VideoStream Sink",
"Sink/Network",
"Send data over networks using Connext middleware",
"RTI <[email protected]>");
gobject_class->set_property = gst_connextsink_set_property;
gobject_class->get_property = gst_connextsink_get_property;
gobject_class->dispose = gst_connextsink_dispose;
gobject_class->finalize = gst_connextsink_finalize;
video_sink_class->show_frame = GST_DEBUG_FUNCPTR(gst_connextsink_show_frame);
element_class->change_state = gst_connextsink_change_state;
/* define properties */
g_object_class_install_property(
gobject_class,
PROP_CONNEXT_DOMAIN_ID,
g_param_spec_uint(
"domain", "Connext domain ID", "The Domain ID used for the Connext publisher", 0, 231, 0, G_PARAM_READWRITE));
g_object_class_install_property(
gobject_class,
PROP_CONNEXT_TOPIC,
g_param_spec_string(
"topic", "Connext Topic", "The topic name to publish on the Connext network", NULL, G_PARAM_READWRITE));
g_object_class_install_property(
gobject_class,
PROP_CONNEXT_KEY,
g_param_spec_string(
"key", "Connext Topic Key", "The topic key to publish on the Connext network", NULL, G_PARAM_READWRITE));
g_object_class_install_property(
gobject_class,
PROP_CONNEXT_DP_QOS_PROFILE,
g_param_spec_string(
"dp-qos-profile",
"Connext DP Qos Profile",
"Default QoS profile used when creating the DP of this sink element",
DEFAULT_QOS,
G_PARAM_READWRITE));
g_object_class_install_property(
gobject_class,
PROP_CONNEXT_DW_QOS_PROFILE,
g_param_spec_string(
"dw-qos-profile",
"Connext DW Qos Profile",
"Default QoS profile used when creating the DW of this sink element",
DEFAULT_QOS,
G_PARAM_READWRITE));
g_object_class_install_property(
gobject_class,
PROP_CONNEXT_PRINT_FRAME_SIZE,
g_param_spec_uint(
"print-frame-size",
"Print size of frame",
"Print average frame size every 50 frames. Default: 0",
0, /* minimum */
1, /* maximum */
0, /* default */
G_PARAM_READWRITE));
}
static void gst_connextsink_init(GstConnextSink* connextsink)
{
connextsink->connext.domainId = 0;
connextsink->connext.topicName = NULL;
connextsink->connext.key = g_strdup("");
connextsink->connext.instance_handle = DDS_HANDLE_NIL;
connextsink->connext.dpQosProfile = g_strdup(DEFAULT_QOS);
connextsink->connext.dwQosProfile = g_strdup(DEFAULT_QOS);
connextsink->connext.numberFramesSent = 0;
connextsink->connext.printFrameSize = 0;
GST_INFO_OBJECT(connextsink, "connextsink initialization complete.");
}
void gst_connextsink_set_property(GObject* object, guint property_id, const GValue* value, GParamSpec* pspec)
{
GstConnextSink* connextsink = GST_CONNEXT_SINK(object);
GST_DEBUG_OBJECT(connextsink, "set_property");
switch (property_id)
{
case PROP_CONNEXT_DOMAIN_ID: connextsink->connext.domainId = g_value_get_uint(value); break;
case PROP_CONNEXT_TOPIC:
{
g_free(connextsink->connext.topicName);
connextsink->connext.topicName = g_value_dup_string(value);
break;
}
case PROP_CONNEXT_KEY:
{
g_free(connextsink->connext.key);
connextsink->connext.key = g_value_dup_string(value);
break;
}
case PROP_CONNEXT_DP_QOS_PROFILE:
{
g_free(connextsink->connext.dpQosProfile);
connextsink->connext.dpQosProfile = g_value_dup_string(value);
break;
}
case PROP_CONNEXT_DW_QOS_PROFILE:
{
g_free(connextsink->connext.dwQosProfile);
connextsink->connext.dwQosProfile = g_value_dup_string(value);
break;
}
case PROP_CONNEXT_PRINT_FRAME_SIZE:
{
connextsink->connext.printFrameSize = g_value_get_uint(value);
break;
}
default: G_OBJECT_WARN_INVALID_PROPERTY_ID(object, property_id, pspec); break;
}
}
void gst_connextsink_get_property(GObject* object, guint property_id, GValue* value, GParamSpec* pspec)
{
GstConnextSink* connextsink = GST_CONNEXT_SINK(object);
GST_DEBUG_OBJECT(connextsink, "get_property");
switch (property_id)
{
case PROP_CONNEXT_DOMAIN_ID: g_value_set_uint(value, connextsink->connext.domainId); break;
case PROP_CONNEXT_TOPIC: g_value_set_string(value, connextsink->connext.topicName); break;
case PROP_CONNEXT_KEY: g_value_set_string(value, connextsink->connext.key); break;
case PROP_CONNEXT_DP_QOS_PROFILE: g_value_set_string(value, connextsink->connext.dpQosProfile); break;
case PROP_CONNEXT_DW_QOS_PROFILE: g_value_set_string(value, connextsink->connext.dwQosProfile); break;
case PROP_CONNEXT_PRINT_FRAME_SIZE: g_value_set_uint(value, connextsink->connext.printFrameSize); break;
default: G_OBJECT_WARN_INVALID_PROPERTY_ID(object, property_id, pspec); break;
}
}
static GstStateChangeReturn gst_connextsink_change_state(GstElement* element, GstStateChange transition)
{
GstStateChangeReturn ret = GST_STATE_CHANGE_SUCCESS;
GstConnextSink* connextsink = GST_CONNEXT_SINK(element);
switch (transition)
{
case GST_STATE_CHANGE_NULL_TO_READY:
{
if (connextsink->connext.topicName == NULL)
{
GST_ERROR("\nConnext topic not specified in the pipeline. Cannot continue!\n\n");
return GST_STATE_CHANGE_FAILURE;
}
char msg[300];
snprintf(msg, sizeof(msg),
"Domain ID is %d; Topic is '%s' with key '%s', DP QoS is '%s' and DW QoS is '%s'",
connextsink->connext.domainId,
connextsink->connext.topicName,
connextsink->connext.key,
connextsink->connext.dpQosProfile,
connextsink->connext.dwQosProfile);
printf("%s\n", msg);
GST_INFO_OBJECT(connextsink, "%s", msg);
if (gst_connextsink_publisher_init(connextsink))
{
return GST_STATE_CHANGE_FAILURE;
}
break;
}
default: break;
}
ret = GST_ELEMENT_CLASS(gst_connextsink_parent_class)->change_state(element, transition);
return ret;
}
void gst_connextsink_dispose(GObject* object)
{
GstConnextSink* connextsink = GST_CONNEXT_SINK(object);
GST_DEBUG_OBJECT(connextsink, "dispose");
/* clean up. may be called multiple times */
Video_StreamTypeSupport_delete_data(connextsink->connext.instance);
if (gst_connextsink_publisher_shutdown(connextsink->connext.participant))
{
GST_ERROR("Failed to shutdown Connext publisher cleanly!");
}
G_OBJECT_CLASS(gst_connextsink_parent_class)->dispose(object);
}
void gst_connextsink_finalize(GObject* object)
{
GstConnextSink* connextsink = GST_CONNEXT_SINK(object);
GST_DEBUG_OBJECT(connextsink, "finalize");
/* clean up object here */
G_OBJECT_CLASS(gst_connextsink_parent_class)->finalize(object);
}
static GstFlowReturn gst_connextsink_show_frame(GstVideoSink* sink, GstBuffer* buf)
{
GstMapInfo mapInfo;
DDS_ReturnCode_t retcode;
GstConnextSink* connextsink = GST_CONNEXT_SINK(sink);
GST_DEBUG_OBJECT(connextsink, "copying gst frame to Connext data container");
gst_buffer_map(buf, &mapInfo, GST_MAP_READ);
/* loan the gstreamer buffer to Connext */
if(!DDS_OctetSeq_loan_contiguous(&connextsink->connext.instance->frame, (DDS_Octet*)mapInfo.data, mapInfo.size, mapInfo.size))
{
GST_ERROR_OBJECT(connextsink, "unable to loan buffer to Connext");
gst_buffer_unmap(buf, &mapInfo);
return GST_FLOW_ERROR;
}
connextsink->connext.numberFramesSent++;
connextsink->connext.accumulatedFrameSize += mapInfo.size;
if (connextsink->connext.printFrameSize && (connextsink->connext.numberFramesSent % PRINT_SIZE_EVERY_X_FRAMES == 0))
{
printf(
"Average size of frames: %lu\n",
connextsink->connext.accumulatedFrameSize / PRINT_SIZE_EVERY_X_FRAMES);
connextsink->connext.accumulatedFrameSize = 0;
}
GST_LOG_OBJECT(connextsink, "publishing frame via Connext, %ld Bytes", mapInfo.size);
/* Key is already in the sample object due to publisher_init() */
/* write the data */
retcode = Video_StreamDataWriter_write(
connextsink->connext.videostream_writer,
connextsink->connext.instance,
&connextsink->connext.instance_handle);
if (retcode != DDS_RETCODE_OK)
{
GST_ERROR_OBJECT(connextsink, "write error %d", retcode);
gst_buffer_unmap(buf, &mapInfo);
return GST_FLOW_ERROR;
}
/* return loan and unmap the gstreamer buffer */
if(!DDS_OctetSeq_unloan(&connextsink->connext.instance->frame))
{
GST_ERROR_OBJECT(connextsink, "unable to return buffer to Gstreamer");
gst_buffer_unmap(buf, &mapInfo);
return GST_FLOW_ERROR;
}
gst_buffer_unmap(buf, &mapInfo);
return GST_FLOW_OK;
}
static int gst_connextsink_get_qos_library_profile(GstConnextSink* connextsink, gchar* qosProfile, char* qos_library_name, char* qos_profile_name)
{
if(strlen(qosProfile) >= PROFILE_NAME_MAX_LEN){
GST_ERROR_OBJECT(connextsink, "QoS profile string is too long: %s", qosProfile);
return 1;
}
char str[PROFILE_NAME_MAX_LEN];
strcpy(str, qosProfile);
const char* delim = "::";
const char* token = strtok(str, delim);
if (token != NULL)
{
strcpy(qos_library_name, token);
}
else
{
GST_ERROR_OBJECT(connextsink, "Cannot parse provided QoS profile string: %s", qosProfile);
return 1;
}
token = strtok(NULL, delim);
if (token != NULL)
{
strcpy(qos_profile_name, token);
}
else
{
GST_ERROR_OBJECT(connextsink, "Cannot parse provided QoS profile string: %s", qosProfile);
return 1;
}
return 0;
}
static int gst_connextsink_publisher_init(GstConnextSink* connextsink)
{
char dpQosLib[PROFILE_NAME_MAX_LEN];
char dpQosProfile[PROFILE_NAME_MAX_LEN];
char dwQosLib[PROFILE_NAME_MAX_LEN];
char dwQosProfile[PROFILE_NAME_MAX_LEN];
int parse_ret = gst_connextsink_get_qos_library_profile(connextsink, connextsink->connext.dpQosProfile, dpQosLib, dpQosProfile);
if (parse_ret)
{
return 1;
}
parse_ret = gst_connextsink_get_qos_library_profile(connextsink, connextsink->connext.dwQosProfile, dwQosLib, dwQosProfile);
if (parse_ret)
{
return 1;
}
DDS_ReturnCode_t retcode = DDS_DomainParticipantFactory_set_default_participant_qos_with_profile(
DDS_TheParticipantFactory, dpQosLib, dpQosProfile);
if (retcode != DDS_RETCODE_OK)
{
GST_ERROR_OBJECT(connextsink, "error %d; cannot set partipant qos to %s::%s", retcode, dpQosLib, dpQosProfile);
return 1;
}
connextsink->connext.participant = DDS_DomainParticipantFactory_create_participant_with_profile(
DDS_TheParticipantFactory, connextsink->connext.domainId, dpQosLib, dpQosProfile, NULL, DDS_STATUS_MASK_NONE);
if (connextsink->connext.participant == NULL)
{
GST_ERROR_OBJECT(connextsink, "create_participant error");
return 1;
}
connextsink->connext.publisher = DDS_DomainParticipant_create_publisher(
connextsink->connext.participant, &DDS_PUBLISHER_QOS_DEFAULT, NULL, DDS_STATUS_MASK_NONE);
if (connextsink->connext.publisher == NULL)
{
GST_ERROR_OBJECT(connextsink, "create_publisher error %d", retcode);
return 1;
}
const char* type_name = Video_StreamTypeSupport_get_type_name();
retcode = Video_StreamTypeSupport_register_type(connextsink->connext.participant, type_name);
if (retcode != DDS_RETCODE_OK)
{
GST_ERROR_OBJECT(connextsink, "register_type error %d", retcode);
return 1;
}
connextsink->connext.topic = DDS_DomainParticipant_create_topic(
connextsink->connext.participant, connextsink->connext.topicName, type_name, &DDS_TOPIC_QOS_DEFAULT, NULL, DDS_STATUS_MASK_NONE);
if (connextsink->connext.topic == NULL)
{
GST_ERROR_OBJECT(connextsink, "create_topic error");
return 1;
}
connextsink->connext.writer = DDS_Publisher_create_datawriter_with_profile(
connextsink->connext.publisher, connextsink->connext.topic, dwQosLib, dwQosProfile, NULL, DDS_STATUS_MASK_NONE);
if (connextsink->connext.writer == NULL)
{
GST_ERROR_OBJECT(connextsink, "create_datawriter error");
return 1;
}
connextsink->connext.videostream_writer = Video_StreamDataWriter_narrow(connextsink->connext.writer);
if (connextsink->connext.videostream_writer == NULL)
{
GST_ERROR_OBJECT(connextsink, "DataWriter_narrow error");
return 1;
}
connextsink->connext.instance = Video_StreamTypeSupport_create_data_ex(DDS_BOOLEAN_TRUE);
if (connextsink->connext.instance == NULL)
{
GST_ERROR_OBJECT(connextsink, "VideoStreamTypeSupport_create_data error");
return 1;
}
connextsink->connext.instance->id = connextsink->connext.key;
connextsink->connext.instance_handle = Video_StreamDataWriter_register_instance(
connextsink->connext.videostream_writer,
connextsink->connext.instance);
if(DDS_InstanceHandle_equals(&connextsink->connext.instance_handle, &DDS_HANDLE_NIL))
{
GST_ERROR_OBJECT(connextsink, "Video_StreamDataWriter_register_instance error");
return 1;
}
if(!DDS_OctetSeq_initialize(&connextsink->connext.instance->frame))
{
GST_ERROR_OBJECT(connextsink, "frame sequence initialize error");
return 1;
}
return 0;
}
static int gst_connextsink_publisher_shutdown(DDS_DomainParticipant* participant)
{
DDS_ReturnCode_t retcode;
GST_INFO("Calling Connext publisher shut down\n");
if (participant != NULL)
{
retcode = DDS_DomainParticipant_delete_contained_entities(participant);
if (retcode != DDS_RETCODE_OK)
{
GST_ERROR("delete_contained_entities error %d", retcode);
return 1;
}
retcode = DDS_DomainParticipantFactory_delete_participant(DDS_TheParticipantFactory, participant);
if (retcode != DDS_RETCODE_OK)
{
GST_ERROR("delete_participant error %d", retcode);
return 1;
}
}
return 0;
}
static gboolean plugin_init(GstPlugin* plugin)
{
/* Remember to set the rank if it's an element that is meant
to be autoplugged by decodebin. */
return gst_element_register(plugin, "connextsink", GST_RANK_NONE, GST_TYPE_CONNEXT_SINK);
}
/* Plugin Information */
#ifndef VERSION
#define VERSION "0.0.3"
#endif
#ifndef PACKAGE
#define PACKAGE "gst_connext_package"
#endif
#ifndef PACKAGE_NAME
#define PACKAGE_NAME "gst-connext"
#endif
#ifndef GST_PACKAGE_ORIGIN
#define GST_PACKAGE_ORIGIN "rti.com"
#endif
GST_PLUGIN_DEFINE(GST_VERSION_MAJOR,
GST_VERSION_MINOR,
connextsink,
"Connext sink plugin",
plugin_init,
VERSION,
"Proprietary",
PACKAGE_NAME,
GST_PACKAGE_ORIGIN)
|
c
|
rticonnextdds-usecases
|
data/projects/rticonnextdds-usecases/VideoData/src/gst-connextsink/gstconnextsink.h
|
/*
* (c) 2023 Copyright, Real-Time Innovations, Inc. (RTI) All rights reserved.
*
* RTI grants Licensee a license to use, modify, compile, and create derivative
* works of the software. 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 _GST_CONNEXTSINK_H_
#define _GST_CONNEXTSINK_H_
#include <gst/video/gstvideosink.h>
#include <gst/video/video.h>
#include <stdio.h>
#include "video.h"
#include "videoSupport.h"
G_BEGIN_DECLS
#define GST_TYPE_CONNEXT_SINK (gst_connextsink_get_type())
#define GST_CONNEXT_SINK(obj) (G_TYPE_CHECK_INSTANCE_CAST((obj), GST_TYPE_CONNEXT_SINK, GstConnextSink))
#define GST_CONNEXTSINK_CLASS(class) (G_TYPE_CHECK_CLASS_CAST((class), GST_TYPE_CONNEXT_SINK, GstConnextSinkClass))
#define GST_IS_CONNEXT_SINK(obj) (G_TYPE_CHECK_INSTANCE_TYPE((obj), GST_TYPE_CONNEXT_SINK))
#define GST_IS_CONNEXTSINK_CLASS(obj) (G_TYPE_CHECK_CLASS_TYPE((class), GST_TYPE_CONNEXT_SINK))
typedef struct GstConnextSink_Context GstConnextSink_Context;
typedef struct GstConnextSink GstConnextSink;
typedef struct GstConnextSinkClass GstConnextSinkClass;
/* Contains the Connext DDS entities used to publish the data from a GStreamer pipeline*/
struct GstConnextSink_Context
{
DDS_DomainParticipant* participant;
DDS_Publisher* publisher;
DDS_Topic* topic;
DDS_DataWriter* writer;
Video_StreamDataWriter* videostream_writer;
Video_Stream* instance;
DDS_InstanceHandle_t instance_handle;
uint32_t domainId;
gchar* topicName;
gchar* key;
gchar* dpQosProfile;
gchar* dwQosProfile;
uint32_t numberFramesSent;
gsize accumulatedFrameSize;
uint32_t printFrameSize;
};
struct GstConnextSink
{
GstVideoSink base_connextsink;
GstConnextSink_Context connext;
};
struct GstConnextSinkClass
{
GstVideoSinkClass base_connextsink_class;
};
GType gst_connextsink_get_type(void);
G_END_DECLS
#endif //_GST_ConnextSINK_H_
|
h
|
rticonnextdds-usecases
|
data/projects/rticonnextdds-usecases/VideoData/src/gst-connextsrc/gstconnextsrc.h
|
/*
* (c) 2023 Copyright, Real-Time Innovations, Inc. (RTI) All rights reserved.
*
* RTI grants Licensee a license to use, modify, compile, and create derivative
* works of the software. 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 _GST_CONNEXTSRC_H_
#define _GST_CONNEXTSRC_H_
#include <gst/base/gstpushsrc.h>
#include "video.h"
#include "videoSupport.h"
G_BEGIN_DECLS
#define GST_TYPE_CONNEXTSRC (gst_connextsrc_get_type())
#define GST_CONNEXTSRC(obj) (G_TYPE_CHECK_INSTANCE_CAST((obj), GST_TYPE_CONNEXTSRC, GstConnextSrc))
#define GST_CONNEXTSRC_CLASS(class) (G_TYPE_CHECK_CLASS_CAST((class), GST_TYPE_CONNEXTSRC, GstConnextSrcClass))
#define GST_IS_CONNEXTSRC(obj) (G_TYPE_CHECK_INSTANCE_TYPE((obj), GST_TYPE_CONNEXTSRC))
#define GST_IS_CONNEXTSRC_CLASS(obj) (G_TYPE_CHECK_CLASS_TYPE((class), GST_TYPE_CONNEXTSRC))
typedef struct GstConnextSrc_Context GstConnextSrc_Context;
typedef struct GstConnextSrc GstConnextSrc;
typedef struct GstConnextSrcClass GstConnextSrcClass;
/* Contains the Connext DDS entities used to receive the data fed into the GStreamer pipeline */
struct GstConnextSrc_Context
{
DDS_DomainParticipant* participant;
DDS_Subscriber* subscriber;
DDS_Topic* topic;
struct DDS_DataReaderListener reader_listener;
DDS_DataReader* reader;
Video_StreamDataReader* videoStream_reader;
uint32_t domainId;
gchar* topicName;
gchar* key;
gchar* dpQosProfile;
gchar* drQosProfile;
gchar* prevKey;
DDS_ContentFilteredTopic* cft;
struct DDS_StringSeq cft_parameters;
GstBuffer* frame_buffer;
};
struct GstConnextSrc
{
GstPushSrc base_connextsrc;
GstConnextSrc_Context connext;
/* Queue in which Connext frames are placed in the on_data_available callback */
GAsyncQueue* g_filled_frame_queue;
};
struct GstConnextSrcClass
{
GstPushSrcClass base_connextsrc_class;
};
GType gst_connextsrc_get_type(void);
G_END_DECLS
#endif
|
h
|
rticonnextdds-usecases
|
data/projects/rticonnextdds-usecases/VideoData/src/gst-connextsrc/gstconnextsrc.c
|
/*
* (c) 2023 Copyright, Real-Time Innovations, Inc. (RTI) All rights reserved.
*
* RTI grants Licensee a license to use, modify, compile, and create derivative
* works of the software. 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.
*/
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include <glib.h>
#include <gst/base/gstpushsrc.h>
#include <gst/gst.h>
#include <gst/video/video.h>
#include <stdbool.h>
#include <stdlib.h>
#include <string.h>
#include "gstconnextsrc.h"
GST_DEBUG_CATEGORY_STATIC(gst_connextsrc_debug_category);
#define GST_CAT_DEFAULT gst_connextsrc_debug_category
#define PROFILE_NAME_MAX_LEN 200
/* prototypes */
/* set gstreamer property */
static void gst_connextsrc_set_property(GObject* object, guint property_id, const GValue* value, GParamSpec* pspec);
/* get gstreamer property */
static void gst_connextsrc_get_property(GObject* object, guint property_id, GValue* value, GParamSpec* pspec);
/* dispose connextsrc */
static void gst_connextsrc_dispose(GObject* object);
/* finalize connextsrc */
static void gst_connextsrc_finalize(GObject* object);
/* start connextsrc plugin */
static gboolean gst_connextsrc_start(GstBaseSrc* src);
/* stop connextsrc plugin */
static gboolean gst_connextsrc_stop(GstBaseSrc* src);
/* subscribe to get frame */
static GstFlowReturn gst_connextsrc_create(GstPushSrc* src, GstBuffer** buf);
/* handle caps events */
static gboolean gst_connextsrc_src_event(GstPad* pad, GstObject* parent, GstEvent* event);
/* parse qos profiles */
static int gst_connextsrc_get_qos_library_profile(GstConnextSrc* connext_sink, gchar* qosProfile, char* qos_library_name, char* qos_profile_name);
/* initialize subscriber */
static int gst_connextsrc_subscriber_init(GstConnextSrc* connextsrc);
/* shutdown subscriber */
static int gst_connextsrc_subscriber_shutdown(DDS_DomainParticipant* participant);
/* create content filter */
static void gst_connextsrc_create_connext_reader_content_filter(GstConnextSrc* connextsrc);
/* update content filter */
static int gst_connextsrc_update_connext_reader_content_filter(GstConnextSrc* connextsrc);
/* element methods */
static GstStateChangeReturn gst_connextsrc_change_state(GstElement* element, GstStateChange transition);
#define DEFAULT_QOS "BuiltinQosLibExp::Generic.StrictReliable"
enum
{
PROP_0,
PROP_CONNEXT_DOMAIN_ID,
PROP_CONNEXT_TOPIC,
PROP_CONNEXT_KEY,
PROP_CONNEXT_DP_QOS_PROFILE,
PROP_CONNEXT_DR_QOS_PROFILE,
PROP_EXTERNAL_CONNEXT_PARTICIPANT
};
#define CONNEXTSRC_VIDEO_CAPS \
"video/x-h264, stream-format=(string)byte-stream, " \
"alignment=(string) au, width=(int)1920, height=(int)1080, framerate=(fraction)30/1"
#define CONNEXTSRC_VIDEO_CAPS2 \
"video/x-raw, format=(string) RGB, " \
"width = (int) 1920, " \
"height = (int) 1080, " \
"framerate = (fraction) 30/1"
/* pad templates */
static GstStaticPadTemplate gst_connextsrc_src_template = GST_STATIC_PAD_TEMPLATE("src",
GST_PAD_SRC,
GST_PAD_ALWAYS,
GST_STATIC_CAPS(CONNEXTSRC_VIDEO_CAPS));
/* class initialization */
G_DEFINE_TYPE_WITH_CODE(
GstConnextSrc,
gst_connextsrc,
GST_TYPE_PUSH_SRC,
GST_DEBUG_CATEGORY_INIT(gst_connextsrc_debug_category, "connextsrc", 0, "debug category for connextsrc element"))
static void gst_connextsrc_class_init(GstConnextSrcClass* class)
{
GObjectClass* gobject_class = G_OBJECT_CLASS(class);
GstElementClass* element_class = GST_ELEMENT_CLASS(class);
GstBaseSrcClass* base_src_class = GST_BASE_SRC_CLASS(class);
GstPushSrcClass* push_src_class = GST_PUSH_SRC_CLASS(class);
/* Setting up pads and setting metadata should be moved to
base_class_init if you intend to subclass this class. */
gst_element_class_add_pad_template(GST_ELEMENT_CLASS(class), gst_static_pad_template_get(&gst_connextsrc_src_template));
gst_element_class_set_static_metadata(GST_ELEMENT_CLASS(class),
"Connext VideoStream Source",
"Source/Network",
"Receive data over networks using Connext middleware",
"RTI <[email protected]>");
gobject_class->set_property = gst_connextsrc_set_property;
gobject_class->get_property = gst_connextsrc_get_property;
gobject_class->dispose = gst_connextsrc_dispose;
gobject_class->finalize = gst_connextsrc_finalize;
base_src_class->start = GST_DEBUG_FUNCPTR(gst_connextsrc_start);
base_src_class->stop = GST_DEBUG_FUNCPTR(gst_connextsrc_stop);
push_src_class->create = GST_DEBUG_FUNCPTR(gst_connextsrc_create);
element_class->change_state = gst_connextsrc_change_state;
/* define properties */
g_object_class_install_property(
gobject_class,
PROP_CONNEXT_DOMAIN_ID,
g_param_spec_uint(
"domain",
"Connext domain ID",
"The Domain ID used for the Connext publisher",
0,
10000,
0,
G_PARAM_READWRITE));
g_object_class_install_property(
gobject_class,
PROP_CONNEXT_TOPIC,
g_param_spec_string(
"topic", "Connext Topic", "The topic name to publish on the Connext network", NULL, G_PARAM_READWRITE));
g_object_class_install_property(
gobject_class,
PROP_CONNEXT_KEY,
g_param_spec_string(
"key", "Connext Topic Key", "The topic key to publish on the Connext network", NULL, G_PARAM_READWRITE));
g_object_class_install_property(
gobject_class,
PROP_CONNEXT_DP_QOS_PROFILE,
g_param_spec_string(
"dp-qos-profile",
"Connext DP Qos Profile",
"Default QoS profile used when creating the the DP of this sink element",
DEFAULT_QOS,
G_PARAM_READWRITE));
g_object_class_install_property(
gobject_class,
PROP_CONNEXT_DR_QOS_PROFILE,
g_param_spec_string(
"dr-qos-profile",
"Connext DR Qos Profile",
"Default QoS profile used when creating the the DR of this sink element",
DEFAULT_QOS,
G_PARAM_READWRITE));
g_object_class_install_property(
gobject_class,
PROP_EXTERNAL_CONNEXT_PARTICIPANT,
g_param_spec_pointer(
"participant",
"External Connext Participant entity",
"Pointer to an externally created Connext participant entity",
G_PARAM_WRITABLE | G_PARAM_READABLE));
}
void sequencesListener_on_requested_deadline_missed(__attribute__((unused)) void* listener_data,
__attribute__((unused)) DDS_DataReader* reader,
__attribute__((unused))
const struct DDS_RequestedDeadlineMissedStatus* status)
{
}
void sequencesListener_on_requested_incompatible_qos(__attribute__((unused)) void* listener_data,
__attribute__((unused)) DDS_DataReader* reader,
__attribute__((unused))
const struct DDS_RequestedIncompatibleQosStatus* status)
{
}
void sequencesListener_on_sample_rejected(__attribute__((unused)) void* listener_data,
__attribute__((unused)) DDS_DataReader* reader,
__attribute__((unused)) const struct DDS_SampleRejectedStatus* status)
{
}
void sequencesListener_on_liveliness_changed(__attribute__((unused)) void* listener_data,
__attribute__((unused)) DDS_DataReader* reader,
__attribute__((unused)) const struct DDS_LivelinessChangedStatus* status)
{
}
void sequencesListener_on_sample_lost(__attribute__((unused)) void* listener_data,
__attribute__((unused)) DDS_DataReader* reader,
__attribute__((unused)) const struct DDS_SampleLostStatus* status)
{
}
void sequencesListener_on_subscription_matched(__attribute__((unused)) void* listener_data,
__attribute__((unused)) DDS_DataReader* reader,
__attribute__((unused))
const struct DDS_SubscriptionMatchedStatus* status)
{
}
void sequencesListener_on_data_available(__attribute__((unused)) void* listener_data, DDS_DataReader* reader)
{
Video_StreamDataReader* video_reader = Video_StreamDataReader_narrow(reader);
GstConnextSrc* connextsrc = (GstConnextSrc*)listener_data;
if (video_reader == NULL)
{
GST_ERROR_OBJECT(connextsrc, "CONNEXTSRC:on_data_available: Error receiving data\n");
return;
}
struct Video_StreamSeq dataSeq;
Video_StreamSeq_initialize(&dataSeq);
struct DDS_SampleInfoSeq infoSeq;
DDS_SampleInfoSeq_initialize(&infoSeq);
DDS_ReturnCode_t retCode = DDS_RETCODE_OK;
/* take samples */
retCode = Video_StreamDataReader_take(
video_reader,
&dataSeq,
&infoSeq,
DDS_LENGTH_UNLIMITED,
DDS_ANY_SAMPLE_STATE,
DDS_ANY_VIEW_STATE,
DDS_ANY_INSTANCE_STATE);
if (retCode != DDS_RETCODE_OK)
{
GST_ERROR_OBJECT(connextsrc, "on_data_available: failed to take new samples.");
}
/* process samples */
for (int i = 0; i < Video_StreamSeq_get_length(&dataSeq); i++)
{
if (DDS_SampleInfoSeq_get_reference(&infoSeq, i)->valid_data)
{
Video_Stream* sample = Video_StreamSeq_get_reference(&dataSeq, i);
uint32_t frame_buffer_size = DDS_OctetSeq_get_length(&sample->frame);
DDS_Octet* data = DDS_OctetSeq_get_contiguous_buffer(&sample->frame);
if(frame_buffer_size > 0)
{
connextsrc->connext.frame_buffer = gst_buffer_new_allocate(NULL, frame_buffer_size, NULL);
if (connextsrc->connext.frame_buffer != NULL)
{
/* copy the frame to a gstreamer buffer and push it into the queue*/
gst_buffer_fill(connextsrc->connext.frame_buffer, 0, data, frame_buffer_size);
g_async_queue_push(connextsrc->g_filled_frame_queue, connextsrc->connext.frame_buffer);
}
}
}
}
retCode = Video_StreamDataReader_return_loan(video_reader, &dataSeq, &infoSeq);
if (retCode != DDS_RETCODE_OK)
{
GST_ERROR_OBJECT(connextsrc,"on_data_available: Failed to return loaned samples");
}
}
static void gst_connextsrc_init(GstConnextSrc* connextsrc)
{
connextsrc->connext.domainId = 0;
connextsrc->connext.topicName = NULL;
connextsrc->connext.participant = NULL;
connextsrc->connext.key = g_strdup("*");
connextsrc->connext.prevKey = g_strdup("*");
connextsrc->connext.dpQosProfile = g_strdup(DEFAULT_QOS);
connextsrc->connext.drQosProfile = g_strdup(DEFAULT_QOS);
gst_base_src_set_live(GST_BASE_SRC(connextsrc), TRUE);
gst_pad_set_event_function(GST_BASE_SRC(connextsrc)->srcpad, gst_connextsrc_src_event);
GST_INFO_OBJECT(connextsrc, "connextsrc initialization complete.");
}
/* start and stop processing, ideal for opening/closing the resource */
static gboolean gst_connextsrc_start(GstBaseSrc* src)
{
GstConnextSrc* connextsrc = GST_CONNEXTSRC(src);
GST_TRACE_OBJECT(connextsrc, "start");
/* Prepare queue for filled frames from which connextsrc_create can take them */
connextsrc->g_filled_frame_queue = g_async_queue_new();
if(connextsrc->g_filled_frame_queue != NULL)
{
return TRUE;
}
else
{
GST_ERROR("Error initializing frame queue");
return FALSE;
}
}
static gboolean gst_connextsrc_stop(GstBaseSrc* src)
{
GstConnextSrc* connextsrc = GST_CONNEXTSRC(src);
GST_TRACE_OBJECT(connextsrc, "Stopping ConnextSrc");
/* Unref the filled frame queue so it is deleted properly */
g_async_queue_unref(connextsrc->g_filled_frame_queue);
connextsrc->g_filled_frame_queue = NULL;
return TRUE;
}
void gst_connextsrc_set_property(GObject* object, guint property_id, const GValue* value, GParamSpec* pspec)
{
GstConnextSrc* connextsrc = GST_CONNEXTSRC(object);
GST_DEBUG_OBJECT(connextsrc, "set_property");
switch (property_id)
{
case PROP_CONNEXT_DOMAIN_ID: connextsrc->connext.domainId = g_value_get_uint(value); break;
case PROP_CONNEXT_TOPIC:
{
g_free(connextsrc->connext.topicName);
connextsrc->connext.topicName = g_value_dup_string(value);
break;
}
case PROP_CONNEXT_KEY:
{
g_free(connextsrc->connext.prevKey);
connextsrc->connext.prevKey = connextsrc->connext.key;
connextsrc->connext.key = g_value_dup_string(value);
break;
}
case PROP_CONNEXT_DP_QOS_PROFILE:
{
g_free(connextsrc->connext.dpQosProfile);
connextsrc->connext.dpQosProfile = g_value_dup_string(value);
break;
}
case PROP_CONNEXT_DR_QOS_PROFILE:
{
g_free(connextsrc->connext.drQosProfile);
connextsrc->connext.drQosProfile = g_value_dup_string(value);
break;
}
case PROP_EXTERNAL_CONNEXT_PARTICIPANT:
{
g_free(connextsrc->connext.participant);
connextsrc->connext.participant = (DDS_DomainParticipant*)(g_value_get_pointer(value));
GST_INFO_OBJECT(connextsrc,"Connext Participant pointer set from external source; participant pointer is: %p\n",
(void*)connextsrc->connext.participant);
break;
}
default: G_OBJECT_WARN_INVALID_PROPERTY_ID(object, property_id, pspec); break;
}
}
void gst_connextsrc_get_property(GObject* object, guint property_id, GValue* value, GParamSpec* pspec)
{
GstConnextSrc* connextsrc = GST_CONNEXTSRC(object);
GST_DEBUG_OBJECT(connextsrc, "get_property");
switch (property_id)
{
case PROP_CONNEXT_DOMAIN_ID: g_value_set_uint(value, connextsrc->connext.domainId); break;
case PROP_CONNEXT_TOPIC: g_value_set_string(value, connextsrc->connext.topicName); break;
case PROP_CONNEXT_KEY: g_value_set_string(value, connextsrc->connext.key); break;
case PROP_CONNEXT_DP_QOS_PROFILE: g_value_set_string(value, connextsrc->connext.dpQosProfile); break;
case PROP_CONNEXT_DR_QOS_PROFILE: g_value_set_string(value, connextsrc->connext.drQosProfile); break;
case PROP_EXTERNAL_CONNEXT_PARTICIPANT: g_value_set_pointer(value, connextsrc->connext.participant); break;
default: G_OBJECT_WARN_INVALID_PROPERTY_ID(object, property_id, pspec); break;
}
}
void gst_connextsrc_dispose(GObject* object)
{
GstConnextSrc* connextsrc = GST_CONNEXTSRC(object);
GST_DEBUG_OBJECT(connextsrc, "dispose");
/* clean up as possible. may be called multiple times */
if (gst_connextsrc_subscriber_shutdown(connextsrc->connext.participant))
{
GST_ERROR("Failed to shutdown Connext subscriber cleanly!");
}
G_OBJECT_CLASS(gst_connextsrc_parent_class)->dispose(object);
}
void gst_connextsrc_finalize(GObject* object)
{
GstConnextSrc* connextsrc = GST_CONNEXTSRC(object);
GST_DEBUG_OBJECT(connextsrc, "finalize");
/* clean up object here */
G_OBJECT_CLASS(gst_connextsrc_parent_class)->finalize(object);
}
static GstStateChangeReturn gst_connextsrc_change_state(GstElement* element, GstStateChange transition)
{
GstStateChangeReturn ret = GST_STATE_CHANGE_SUCCESS;
GstConnextSrc* connextsrc = GST_CONNEXTSRC(element);
switch (transition)
{
case GST_STATE_CHANGE_NULL_TO_READY:
{
if (connextsrc->connext.topicName == NULL)
{
GST_ERROR("\nCONNEXTSRC: Connext topic not specified in the pipeline. Cannot continue!\n\n");
return GST_STATE_CHANGE_FAILURE;
}
char msg[300];
snprintf(msg, sizeof(msg),
"CONNEXTSRC: Domain ID is %d; Topic is '%s' with key '%s', DP QoS is '%s' and DR QoS is '%s'",
connextsrc->connext.domainId,
connextsrc->connext.topicName,
connextsrc->connext.key,
connextsrc->connext.dpQosProfile,
connextsrc->connext.drQosProfile);
printf("%s\n", msg);
GST_INFO_OBJECT(connextsrc, "%s", msg);
if (gst_connextsrc_subscriber_init(connextsrc))
{
return GST_STATE_CHANGE_FAILURE;
}
break;
}
default: break;
}
ret = GST_ELEMENT_CLASS(gst_connextsrc_parent_class)->change_state(element, transition);
gst_connextsrc_update_connext_reader_content_filter(connextsrc);
return ret;
}
static int gst_connextsrc_get_qos_library_profile(GstConnextSrc* connextsrc, gchar* qosProfile, char* qos_library_name, char* qos_profile_name)
{
if(strlen(qosProfile) >= PROFILE_NAME_MAX_LEN){
GST_ERROR_OBJECT(connextsrc, "QoS profile string is too long: %s", qosProfile);
return 1;
}
char str[PROFILE_NAME_MAX_LEN];
strcpy(str, qosProfile);
const char* delim = "::";
const char* token = strtok(str, delim);
if (token != NULL)
{
strcpy(qos_library_name, token);
}
else
{
GST_ERROR_OBJECT(connextsrc, "Cannot parse provided QoS profile string: %s", qosProfile);
return 1;
}
token = strtok(NULL, delim);
if (token != NULL)
{
strcpy(qos_profile_name, token);
}
else
{
GST_ERROR_OBJECT(connextsrc, "Cannot parse provided QoS profile string: %s", qosProfile);
return 1;
}
return 0;
}
static GstFlowReturn gst_connextsrc_create(GstPushSrc* src, GstBuffer** buf)
{
GstConnextSrc* connextsrc = GST_CONNEXTSRC(src);
bool frame_ready = false;
GstBuffer* frame;
/* Try to get a filled frame for 10 microseconds */
const int wait_timeout = 10;
do
{
/* Wait until we can get a filled frame from the on_data_available Connext callback */
frame = NULL;
GstState state;
do
{
frame = g_async_queue_timeout_pop(connextsrc->g_filled_frame_queue, wait_timeout);
/* Get the current state of the element. Should return immediately since we are not doing ASYNC state
changes but wait at most for 100 nanoseconds */
const int state_read_timeout = 100;
gst_element_get_state(GST_ELEMENT(connextsrc), &state, NULL, state_read_timeout);
if (state != GST_STATE_PLAYING)
{
/* The src should not create any more data. Stop waiting for frame and do not fill buf */
GST_INFO_OBJECT(connextsrc, "Element state is no longer \"GST_STATE_PLAYING\". Aborting create call.");
return GST_FLOW_FLUSHING;
}
} while (frame == NULL);
if (frame != NULL)
{
GST_TRACE_OBJECT(connextsrc, "Connext frame complete");
frame_ready = true;
}
else
{
GST_DEBUG_OBJECT(connextsrc, "Incomplete frame from Connext sequence");
return GST_FLOW_ERROR;
}
} while (!frame_ready);
GstClock* clock = NULL;
GstClockTime base_time, timestamp = GST_CLOCK_TIME_NONE;
/* obtain element clock and base time */
GST_OBJECT_LOCK(src);
if ((clock = GST_ELEMENT_CLOCK(src)) != NULL)
{
gst_object_ref(clock);
}
base_time = GST_ELEMENT_CAST(src)->base_time;
GST_OBJECT_UNLOCK(src);
timestamp = gst_clock_get_time(clock) - base_time;
GST_BUFFER_DTS(frame) = timestamp;
GST_BUFFER_PTS(frame) = GST_BUFFER_DTS(frame);
/* Set filled GstBuffer as output to pass down the pipeline */
*buf = frame;
return GST_FLOW_OK;
}
static gboolean gst_connextsrc_src_event(GstPad* pad, GstObject* parent, GstEvent* event)
{
gboolean ret;
GstConnextSrc* src = GST_CONNEXTSRC(parent);
switch (GST_EVENT_TYPE(event))
{
case GST_EVENT_CAPS:
ret = gst_pad_push_event(GST_BASE_SRC(src)->srcpad, event);
GST_INFO("Caps event handled!");
break;
default: ret = gst_pad_event_default(pad, parent, event); break;
}
return ret;
}
static int gst_connextsrc_subscriber_init(GstConnextSrc* connextsrc)
{
char dpQosLib[PROFILE_NAME_MAX_LEN];
char dpQosProfile[PROFILE_NAME_MAX_LEN];
char drQosLib[PROFILE_NAME_MAX_LEN];
char drQosProfile[PROFILE_NAME_MAX_LEN];
int parse_ret = gst_connextsrc_get_qos_library_profile(connextsrc, connextsrc->connext.dpQosProfile, dpQosLib, dpQosProfile);
if (parse_ret)
{
return 1;
}
parse_ret = gst_connextsrc_get_qos_library_profile(connextsrc, connextsrc->connext.drQosProfile, drQosLib, drQosProfile);
if (parse_ret)
{
return 1;
}
if (connextsrc->connext.participant == NULL)
{
GST_INFO_OBJECT(connextsrc, "CONNEXTSRC: Creating local Connext participant entity\n");
DDS_ReturnCode_t retcode = DDS_DomainParticipantFactory_set_default_participant_qos_with_profile(
DDS_TheParticipantFactory, dpQosLib, dpQosProfile);
if (retcode != DDS_RETCODE_OK)
{
GST_ERROR_OBJECT(connextsrc, "error %d; cannot set partipant qos to %s::%s", retcode, dpQosLib, dpQosProfile);
return 1;
}
connextsrc->connext.participant = DDS_DomainParticipantFactory_create_participant_with_profile(
DDS_TheParticipantFactory, connextsrc->connext.domainId, dpQosLib, dpQosProfile, NULL, DDS_STATUS_MASK_NONE);
if (connextsrc->connext.participant == NULL)
{
GST_ERROR_OBJECT(connextsrc, "create_participant error");
return 1;
}
}
else
{
GST_INFO_OBJECT(connextsrc, "CONNEXTSRC: Using externally created Connext participant\n");
}
connextsrc->connext.subscriber = DDS_DomainParticipant_create_subscriber(
connextsrc->connext.participant, &DDS_SUBSCRIBER_QOS_DEFAULT, NULL, DDS_STATUS_MASK_NONE);
if (connextsrc->connext.subscriber == NULL)
{
GST_ERROR_OBJECT(connextsrc, "create_subscriber error");
return 1;
}
const char* type_name = NULL;
type_name = Video_StreamTypeSupport_get_type_name();
DDS_ReturnCode_t retcode = Video_StreamTypeSupport_register_type(connextsrc->connext.participant, type_name);
if (retcode != DDS_RETCODE_OK)
{
GST_ERROR_OBJECT(connextsrc, "register_type error");
return 1;
}
connextsrc->connext.topic = DDS_DomainParticipant_create_topic(
connextsrc->connext.participant, connextsrc->connext.topicName, type_name, &DDS_TOPIC_QOS_DEFAULT, NULL, DDS_STATUS_MASK_NONE);
if (connextsrc->connext.topic == NULL)
{
GST_ERROR_OBJECT(connextsrc, "create_topic error");
return 1;
}
connextsrc->connext.reader_listener.as_listener.listener_data = (void*)connextsrc;
connextsrc->connext.reader_listener.on_requested_deadline_missed = sequencesListener_on_requested_deadline_missed;
connextsrc->connext.reader_listener.on_requested_incompatible_qos = sequencesListener_on_requested_incompatible_qos;
connextsrc->connext.reader_listener.on_sample_rejected = sequencesListener_on_sample_rejected;
connextsrc->connext.reader_listener.on_liveliness_changed = sequencesListener_on_liveliness_changed;
connextsrc->connext.reader_listener.on_sample_lost = sequencesListener_on_sample_lost;
connextsrc->connext.reader_listener.on_subscription_matched = sequencesListener_on_subscription_matched;
connextsrc->connext.reader_listener.on_data_available = sequencesListener_on_data_available;
gst_connextsrc_create_connext_reader_content_filter(connextsrc);
connextsrc->connext.reader = DDS_Subscriber_create_datareader_with_profile(
connextsrc->connext.subscriber,
DDS_ContentFilteredTopic_as_topicdescription(connextsrc->connext.cft),
drQosLib,
drQosProfile,
&(connextsrc->connext.reader_listener),
DDS_STATUS_MASK_ALL);
if (connextsrc->connext.reader == NULL)
{
GST_ERROR_OBJECT(connextsrc, "create_datareader error");
return 1;
}
connextsrc->connext.videoStream_reader = Video_StreamDataReader_narrow(connextsrc->connext.reader);
if (connextsrc->connext.videoStream_reader == NULL)
{
GST_ERROR_OBJECT(connextsrc, "DataReader_narrow error");
return 1;
}
return 0;
}
static void gst_connextsrc_create_connext_reader_content_filter(GstConnextSrc* connextsrc)
{
const char* cft_param_list[] = {connextsrc->connext.key};
DDS_StringSeq_initialize(&connextsrc->connext.cft_parameters);
DDS_StringSeq_set_maximum(&connextsrc->connext.cft_parameters, 1);
DDS_StringSeq_from_array(&connextsrc->connext.cft_parameters, cft_param_list, 1);
connextsrc->connext.cft = DDS_DomainParticipant_create_contentfilteredtopic_with_filter(
connextsrc->connext.participant,
"ContentFilteredTopic",
connextsrc->connext.topic,
"id MATCH %0",
&connextsrc->connext.cft_parameters,
DDS_STRINGMATCHFILTER_NAME);
}
static int gst_connextsrc_update_connext_reader_content_filter(GstConnextSrc* connextsrc)
{
if (strcmp(connextsrc->connext.prevKey, connextsrc->connext.key) != 0)
{
printf(
"Changing RTI content filter; from '%s' (prev) vs '%s' (latest) \n", connextsrc->connext.prevKey, connextsrc->connext.key);
/* set_expression_parameters */
DDS_String_free(DDS_StringSeq_get(&connextsrc->connext.cft_parameters, 0));
char RTI_key_format[PROFILE_NAME_MAX_LEN];
if((strlen(connextsrc->connext.key) + 3) > PROFILE_NAME_MAX_LEN)
{
GST_ERROR_OBJECT(connextsrc, "new key is too long");
return -1;
}
snprintf(RTI_key_format, sizeof(RTI_key_format), "'%s'", connextsrc->connext.key);
*DDS_StringSeq_get_reference(&connextsrc->connext.cft_parameters, 0) = DDS_String_dup(RTI_key_format);
printf("CONNEXTSRC: updating RTI content filter with key value: %s\n", connextsrc->connext.key);
DDS_ReturnCode_t retcode = DDS_ContentFilteredTopic_set_expression_parameters(
connextsrc->connext.cft,
&connextsrc->connext.cft_parameters);
if (retcode != DDS_RETCODE_OK)
{
GST_ERROR_OBJECT(connextsrc, "CONNEXTSRC: content filter set failed with error: %d\n", retcode);
return -1;
}
//free the previous key and update it to match the new key
g_free(connextsrc->connext.prevKey);
connextsrc->connext.prevKey = g_strdup(connextsrc->connext.key);
}
return 0;
}
static int gst_connextsrc_subscriber_shutdown(DDS_DomainParticipant* participant)
{
DDS_ReturnCode_t retcode;
GST_INFO("Calling Connext subscriber shut down\n");
if (participant != NULL)
{
retcode = DDS_DomainParticipant_delete_contained_entities(participant);
if (retcode != DDS_RETCODE_OK)
{
GST_ERROR("delete_contained_entities error %d", retcode);
return 1;
}
retcode = DDS_DomainParticipantFactory_delete_participant(DDS_TheParticipantFactory, participant);
if (retcode != DDS_RETCODE_OK)
{
GST_ERROR("delete_participant error %d", retcode);
return 1;
}
}
GST_INFO("subscriber_shutdown complete");
return 0;
}
static gboolean plugin_init(GstPlugin* plugin)
{
/* Remember to set the rank if it's an element that is meant
to be autoplugged by decodebin. */
return gst_element_register(plugin, "connextsrc", GST_RANK_NONE, GST_TYPE_CONNEXTSRC);
}
/* Plugin Information */
#ifndef VERSION
#define VERSION "0.0.3"
#endif
#ifndef PACKAGE
#define PACKAGE "gst_connext_package"
#endif
#ifndef PACKAGE_NAME
#define PACKAGE_NAME "gst-connext"
#endif
#ifndef GST_PACKAGE_ORIGIN
#define GST_PACKAGE_ORIGIN "rti.com"
#endif
GST_PLUGIN_DEFINE(GST_VERSION_MAJOR,
GST_VERSION_MINOR,
connextsrc,
"Connext source plugin",
plugin_init,
VERSION,
"Proprietary",
PACKAGE_NAME,
GST_PACKAGE_ORIGIN)
|
c
|
rticonnextdds-usecases
|
data/projects/rticonnextdds-usecases/VehicleTracking/ExampleCode/thirdparty/wxWidgets-3.1.2/Linux/include/gtk2-unicode-3.1/wx/setup.h
|
/* lib/wx/include/gtk2-unicode-3.1/wx/setup.h. Generated from setup.h.in by configure. */
/* This define (__WX_SETUP_H__) is used both to ensure setup.h is included
* only once and to indicate that we are building using configure. */
#ifndef __WX_SETUP_H__
#define __WX_SETUP_H__
/* never undefine inline or const keywords for C++ compilation */
#ifndef __cplusplus
/* Define to empty if the keyword does not work. */
/* #undef const */
/* Define as __inline if that's what the C compiler calls it. */
/* #undef inline */
#endif /* __cplusplus */
/* the installation location prefix from configure */
#define wxINSTALL_PREFIX "/usr/local"
/* Define to `int' if <sys/types.h> doesn't define. */
/* #undef gid_t */
/* Define to `int' if <sys/types.h> doesn't define. */
/* #undef mode_t */
/* Define to `long' if <sys/types.h> doesn't define. */
/* #undef off_t */
/* Define to `int' if <sys/types.h> doesn't define. */
/* #undef pid_t */
/* Define to `unsigned' if <sys/types.h> doesn't define. */
/* #undef size_t */
/* Define if ssize_t type is available. */
#define HAVE_SSIZE_T 1
/* Define if you have the ANSI C header files. */
#define STDC_HEADERS 1
/* Define this to get extra features from GNU libc. */
#ifndef _GNU_SOURCE
#define _GNU_SOURCE 1
#endif
/* Define to `int' if <sys/types.h> doesn't define. */
/* #undef uid_t */
/* Define if your processor stores words with the most significant
byte first (like Motorola and SPARC, unlike Intel and VAX). */
/* #undef WORDS_BIGENDIAN */
/* Define this if your version of GTK+ is greater than 1.2.7 */
/* #undef __WXGTK127__ */
/* Define this if your version of GTK+ is greater than 2.0 */
#define __WXGTK20__ 1
/* Define this if your version of GTK+ is greater than 2.10 */
#define __WXGTK210__ 1
/* Define this if your version of GTK+ is greater than 2.18 */
#define __WXGTK218__ 1
/* Define this if your version of GTK+ is greater than 2.20 */
#define __WXGTK220__ 1
/* Define this if your version of GTK+ is >= 3.0 */
/* #undef __WXGTK3__ */
/* Define this if your version of GTK+ is >= 3.90.0 */
/* #undef __WXGTK4__ */
/* Define this if you want to use GPE features */
/* #undef __WXGPE__ */
/* Define this if your version of Motif is greater than 2.0 */
/* #undef __WXMOTIF20__ */
/* Define this if you are using Lesstif */
/* #undef __WXLESSTIF__ */
/*
* Define to 1 for Unix[-like] system
*/
#define wxUSE_UNIX 1
#define __UNIX__ 1
/* #undef __AIX__ */
/* #undef __BSD__ */
/* #undef __DARWIN__ */
/* #undef __EMX__ */
/* #undef __FREEBSD__ */
/* #undef __HPUX__ */
#define __LINUX__ 1
/* #undef __NETBSD__ */
/* #undef __OPENBSD__ */
/* #undef __OSF__ */
/* #undef __QNX__ */
/* #undef __SGI__ */
/* #undef __SOLARIS__ */
/* #undef __SUN__ */
/* #undef __SUNOS__ */
/* #undef __SVR4__ */
/* #undef __SYSV__ */
/* #undef __ULTRIX__ */
/* #undef __UNIXWARE__ */
/* #undef __VMS__ */
/* #undef __IA64__ */
/* #undef __ALPHA__ */
/* NanoX (with wxX11) */
#define wxUSE_NANOX 0
/* PowerPC Darwin & Mac OS X */
/* #undef __POWERPC__ */
/* Hack to make IOGraphicsTypes.h not define Point conflicting with MacTypes */
/* #undef __Point__ */
/* MS-DOS with DJGPP */
/* #undef __DOS__ */
/* Stupid hack; __WINDOWS__ clashes with wx/defs.h */
#ifndef __WINDOWS__
/* #undef __WINDOWS__ */
#endif
#ifndef __WIN32__
/* #undef __WIN32__ */
#endif
#ifndef __GNUWIN32__
/* #undef __GNUWIN32__ */
#endif
#ifndef STRICT
/* #undef STRICT */
#endif
#ifndef WINVER
/* #undef WINVER */
#endif
/* --- start common options --- */
#ifndef wxUSE_GUI
#define wxUSE_GUI 1
#endif
#define WXWIN_COMPATIBILITY_2_8 0
#define WXWIN_COMPATIBILITY_3_0 1
#define wxDIALOG_UNIT_COMPATIBILITY 0
#define wxUSE_UNSAFE_WXSTRING_CONV 1
#define wxUSE_REPRODUCIBLE_BUILD 0
#define wxUSE_ON_FATAL_EXCEPTION 1
#define wxUSE_STACKWALKER 1
#define wxUSE_DEBUGREPORT 1
#define wxUSE_DEBUG_CONTEXT 0
#define wxUSE_MEMORY_TRACING 0
#define wxUSE_GLOBAL_MEMORY_OPERATORS 0
#define wxUSE_DEBUG_NEW_ALWAYS 0
#ifndef wxUSE_UNICODE
#define wxUSE_UNICODE 1
#endif
#define wxUSE_WCHAR_T 1
#define wxUSE_EXCEPTIONS 1
#define wxUSE_EXTENDED_RTTI 0
#define wxUSE_LOG 1
#define wxUSE_LOGWINDOW 1
#define wxUSE_LOGGUI 1
#define wxUSE_LOG_DIALOG 1
#define wxUSE_CMDLINE_PARSER 1
#define wxUSE_THREADS 1
#define wxUSE_STREAMS 1
#define wxUSE_PRINTF_POS_PARAMS 1
#define wxUSE_COMPILER_TLS 1
#define wxUSE_STL 0
#define wxUSE_STD_DEFAULT 0
#define wxUSE_STD_CONTAINERS_COMPATIBLY 1
#define wxUSE_STD_CONTAINERS 0
#define wxUSE_STD_IOSTREAM 1
#define wxUSE_STD_STRING 1
#define wxUSE_STD_STRING_CONV_IN_WXSTRING wxUSE_STL
#define wxUSE_IOSTREAMH 0
#define wxUSE_LONGLONG 1
#define wxUSE_BASE64 1
#define wxUSE_CONSOLE_EVENTLOOP 1
#define wxUSE_FILE 1
#define wxUSE_FFILE 1
#define wxUSE_FSVOLUME 1
#define wxUSE_SECRETSTORE 0
#define wxUSE_STDPATHS 1
#define wxUSE_TEXTBUFFER 1
#define wxUSE_TEXTFILE 1
#define wxUSE_INTL 1
#define wxUSE_XLOCALE 1
#define wxUSE_DATETIME 1
#define wxUSE_TIMER 1
#define wxUSE_STOPWATCH 1
#define wxUSE_FSWATCHER 1
#define wxUSE_CONFIG 1
#define wxUSE_CONFIG_NATIVE 1
#define wxUSE_DIALUP_MANAGER 1
#define wxUSE_DYNLIB_CLASS 1
#define wxUSE_DYNAMIC_LOADER 1
#define wxUSE_SOCKETS 1
#define wxUSE_IPV6 0
#define wxUSE_FILESYSTEM 1
#define wxUSE_FS_ZIP 1
#define wxUSE_FS_ARCHIVE 1
#define wxUSE_FS_INET 1
#define wxUSE_ARCHIVE_STREAMS 1
#define wxUSE_ZIPSTREAM 1
#define wxUSE_TARSTREAM 1
#define wxUSE_ZLIB 1
#define wxUSE_LIBLZMA 0
#define wxUSE_APPLE_IEEE 1
#define wxUSE_JOYSTICK 1
#define wxUSE_FONTENUM 1
#define wxUSE_FONTMAP 1
#define wxUSE_MIMETYPE 1
#define wxUSE_PROTOCOL 1
#define wxUSE_PROTOCOL_FILE 1
#define wxUSE_PROTOCOL_FTP 1
#define wxUSE_PROTOCOL_HTTP 1
#define wxUSE_URL 1
#define wxUSE_URL_NATIVE 0
#define wxUSE_VARIANT 1
#define wxUSE_ANY 1
#define wxUSE_REGEX 1
#define wxUSE_SYSTEM_OPTIONS 1
#define wxUSE_SOUND 1
#define wxUSE_MEDIACTRL 1
#define wxUSE_XRC 1
#define wxUSE_XML 1
#define wxUSE_AUI 1
#define wxUSE_RIBBON 1
#define wxUSE_PROPGRID 1
#define wxUSE_STC 1
#define wxUSE_WEBVIEW 0
#ifdef __WXMSW__
#define wxUSE_WEBVIEW_IE 0
#else
#define wxUSE_WEBVIEW_IE 0
#endif
#if (defined(__WXGTK__) && !defined(__WXGTK3__)) || defined(__WXOSX__)
#define wxUSE_WEBVIEW_WEBKIT 0
#else
#define wxUSE_WEBVIEW_WEBKIT 0
#endif
#if defined(__WXGTK3__)
#define wxUSE_WEBVIEW_WEBKIT2 0
#else
#define wxUSE_WEBVIEW_WEBKIT2 0
#endif
#if defined(_MSC_VER) || \
(defined(__MINGW32__) && (__GNUC__ > 4 || __GNUC_MINOR__ >= 8))
#define wxUSE_GRAPHICS_CONTEXT 1
#else
#define wxUSE_GRAPHICS_CONTEXT 1
#endif
#define wxUSE_CAIRO 1
#define wxUSE_CONTROLS 1
#define wxUSE_MARKUP 1
#define wxUSE_POPUPWIN 1
#define wxUSE_TIPWINDOW 1
#define wxUSE_ACTIVITYINDICATOR 1
#define wxUSE_ANIMATIONCTRL 1
#define wxUSE_BANNERWINDOW 1
#define wxUSE_BUTTON 1
#define wxUSE_BMPBUTTON 1
#define wxUSE_CALENDARCTRL 1
#define wxUSE_CHECKBOX 1
#define wxUSE_CHECKLISTBOX 1
#define wxUSE_CHOICE 1
#define wxUSE_COLLPANE 1
#define wxUSE_COLOURPICKERCTRL 1
#define wxUSE_COMBOBOX 1
#define wxUSE_COMMANDLINKBUTTON 1
#define wxUSE_DATAVIEWCTRL 1
#define wxUSE_DATEPICKCTRL 1
#define wxUSE_DIRPICKERCTRL 1
#define wxUSE_EDITABLELISTBOX 1
#define wxUSE_FILECTRL 1
#define wxUSE_FILEPICKERCTRL 1
#define wxUSE_FONTPICKERCTRL 1
#define wxUSE_GAUGE 1
#define wxUSE_HEADERCTRL 1
#define wxUSE_HYPERLINKCTRL 1
#define wxUSE_LISTBOX 1
#define wxUSE_LISTCTRL 1
#define wxUSE_RADIOBOX 1
#define wxUSE_RADIOBTN 1
#define wxUSE_RICHMSGDLG 1
#define wxUSE_SCROLLBAR 1
#define wxUSE_SEARCHCTRL 1
#define wxUSE_SLIDER 1
#define wxUSE_SPINBTN 1
#define wxUSE_SPINCTRL 1
#define wxUSE_STATBOX 1
#define wxUSE_STATLINE 1
#define wxUSE_STATTEXT 1
#define wxUSE_STATBMP 1
#define wxUSE_TEXTCTRL 1
#define wxUSE_TIMEPICKCTRL 1
#define wxUSE_TOGGLEBTN 1
#define wxUSE_TREECTRL 1
#define wxUSE_TREELISTCTRL 1
#define wxUSE_STATUSBAR 1
#define wxUSE_NATIVE_STATUSBAR 1
#define wxUSE_TOOLBAR 1
#define wxUSE_TOOLBAR_NATIVE 1
#define wxUSE_NOTEBOOK 1
#define wxUSE_LISTBOOK 1
#define wxUSE_CHOICEBOOK 1
#define wxUSE_TREEBOOK 1
#define wxUSE_TOOLBOOK 1
#define wxUSE_TASKBARICON 1
#define wxUSE_GRID 1
#define wxUSE_MINIFRAME 1
#define wxUSE_COMBOCTRL 1
#define wxUSE_ODCOMBOBOX 1
#define wxUSE_BITMAPCOMBOBOX 1
#define wxUSE_REARRANGECTRL 1
#define wxUSE_ADDREMOVECTRL 1
#define wxUSE_ACCEL 1
#define wxUSE_ARTPROVIDER_STD 1
#define wxUSE_ARTPROVIDER_TANGO 0
#define wxUSE_HOTKEY 0
#define wxUSE_CARET 1
#define wxUSE_DISPLAY 1
#define wxUSE_GEOMETRY 1
#define wxUSE_IMAGLIST 1
#define wxUSE_INFOBAR 1
#define wxUSE_MENUS 1
#define wxUSE_NOTIFICATION_MESSAGE 1
#define wxUSE_PREFERENCES_EDITOR 1
#define wxUSE_PRIVATE_FONTS 1
#define wxUSE_RICHTOOLTIP 1
#define wxUSE_SASH 1
#define wxUSE_SPLITTER 1
#define wxUSE_TOOLTIPS 1
#define wxUSE_VALIDATORS 1
#ifdef __WXMSW__
#define wxUSE_AUTOID_MANAGEMENT 0
#else
#define wxUSE_AUTOID_MANAGEMENT 0
#endif
#define wxUSE_COMMON_DIALOGS 0
#define wxUSE_BUSYINFO 1
#define wxUSE_CHOICEDLG 1
#define wxUSE_COLOURDLG 1
#define wxUSE_DIRDLG 1
#define wxUSE_FILEDLG 1
#define wxUSE_FINDREPLDLG 1
#define wxUSE_FONTDLG 1
#define wxUSE_MSGDLG 1
#define wxUSE_PROGRESSDLG 1
#define wxUSE_NATIVE_PROGRESSDLG 1
#define wxUSE_STARTUP_TIPS 1
#define wxUSE_TEXTDLG 1
#define wxUSE_NUMBERDLG 1
#define wxUSE_SPLASH 1
#define wxUSE_WIZARDDLG 1
#define wxUSE_ABOUTDLG 1
#define wxUSE_FILE_HISTORY 1
#define wxUSE_METAFILE 0
#define wxUSE_ENH_METAFILE 0
#define wxUSE_WIN_METAFILES_ALWAYS 0
#define wxUSE_MDI 1
#define wxUSE_DOC_VIEW_ARCHITECTURE 1
#define wxUSE_MDI_ARCHITECTURE 1
#define wxUSE_PRINTING_ARCHITECTURE 1
#define wxUSE_HTML 1
#define wxUSE_GLCANVAS 1
#define wxUSE_RICHTEXT 1
#define wxUSE_CLIPBOARD 1
#define wxUSE_DATAOBJ 1
#define wxUSE_DRAG_AND_DROP 1
#ifdef __WXMSW__
#define wxUSE_ACCESSIBILITY 0
#else
#define wxUSE_ACCESSIBILITY 0
#endif
#define wxUSE_SNGLINST_CHECKER 1
#define wxUSE_DRAGIMAGE 1
#define wxUSE_IPC 1
#define wxUSE_HELP 1
#define wxUSE_MS_HTML_HELP 0
#define wxUSE_WXHTML_HELP 1
#define wxUSE_CONSTRAINTS 1
#define wxUSE_SPLINES 1
#define wxUSE_MOUSEWHEEL 1
#define wxUSE_UIACTIONSIMULATOR 1
#define wxUSE_POSTSCRIPT 1
#define wxUSE_AFM_FOR_POSTSCRIPT 1
#define wxUSE_SVG 1
#define wxUSE_DC_TRANSFORM_MATRIX 1
#define wxUSE_IMAGE 1
#define wxUSE_LIBPNG 1
#define wxUSE_LIBJPEG 1
#define wxUSE_LIBTIFF 1
#define wxUSE_TGA 1
#define wxUSE_GIF 1
#define wxUSE_PNM 1
#define wxUSE_PCX 1
#define wxUSE_IFF 1
#define wxUSE_XPM 1
#define wxUSE_ICO_CUR 1
#define wxUSE_PALETTE 1
#define wxUSE_ALL_THEMES 0
#define wxUSE_THEME_GTK 0
#define wxUSE_THEME_METAL 0
#define wxUSE_THEME_MONO 0
#define wxUSE_THEME_WIN32 0
/* --- end common options --- */
/*
* Unix-specific options
*/
#define wxUSE_SELECT_DISPATCHER 1
#define wxUSE_EPOLL_DISPATCHER 1
#define wxUSE_UNICODE_UTF8 0
#define wxUSE_UTF8_LOCALE_ONLY 0
/*
Use GStreamer for Unix.
Default is 0 as this requires a lot of dependencies which might not be
available.
Recommended setting: 1 (wxMediaCtrl won't work by default without it).
*/
#define wxUSE_GSTREAMER 1
#define wxUSE_GSTREAMER_PLAYER 0
/*
Use XTest extension to implement wxUIActionSimulator?
Default is 1, it is set to 0 if the necessary headers/libraries are not
found by configure.
Recommended setting: 1, wxUIActionSimulator won't work in wxGTK3 without it.
*/
#define wxUSE_XTEST 0
/* --- start MSW options --- */
#define wxUSE_GRAPHICS_GDIPLUS wxUSE_GRAPHICS_CONTEXT
#if defined(_MSC_VER) && _MSC_VER >= 1600
#define wxUSE_GRAPHICS_DIRECT2D wxUSE_GRAPHICS_CONTEXT
#else
#define wxUSE_GRAPHICS_DIRECT2D 0
#endif
#define wxUSE_OLE 0
#define wxUSE_OLE_AUTOMATION 0
#define wxUSE_ACTIVEX 0
#if defined(_MSC_VER) && _MSC_VER >= 1700 && !defined(_USING_V110_SDK71_)
#define wxUSE_WINRT 0
#else
#define wxUSE_WINRT 0
#endif
#define wxUSE_DC_CACHEING 0
#define wxUSE_WXDIB 0
#define wxUSE_POSTSCRIPT_ARCHITECTURE_IN_MSW 0
#define wxUSE_REGKEY 0
#define wxUSE_RICHEDIT 1
#define wxUSE_RICHEDIT2 1
#define wxUSE_OWNER_DRAWN 0
#define wxUSE_TASKBARICON_BALLOONS 1
#define wxUSE_TASKBARBUTTON 0
#define wxUSE_UXTHEME 0
#define wxUSE_INKEDIT 0
#define wxUSE_INICONF 0
#define wxUSE_DATEPICKCTRL_GENERIC 0
#define wxUSE_TIMEPICKCTRL_GENERIC 0
#if defined(__VISUALC__) || defined(__MINGW64_TOOLCHAIN__)
#define wxUSE_DBGHELP 0
#else
#define wxUSE_DBGHELP 0
#endif
#define wxUSE_CRASHREPORT 0
/* --- end MSW options --- */
/*
* Define if your compiler has C99 va_copy
*/
#define HAVE_VA_COPY 1
/*
* Define if va_list type is an array
*/
/* #undef VA_LIST_IS_ARRAY */
/*
* Define if the compiler supports variadic macros
*/
#define HAVE_VARIADIC_MACROS 1
/*
* Define if you don't want variadic macros to be used even if they are
* supported by the compiler.
*/
/* #undef wxNO_VARIADIC_MACROS */
/*
* Define if your compiler has std::wstring
*/
#define HAVE_STD_WSTRING 1
/*
* Define if your compiler has compliant std::string::compare
*/
/* #undef HAVE_STD_STRING_COMPARE */
/*
* Define if your compiler has <hash_map>
*/
/* #undef HAVE_HASH_MAP */
/*
* Define if your compiler has <ext/hash_map>
*/
/* #undef HAVE_EXT_HASH_MAP */
/*
* Define if your compiler has std::hash_map/hash_set
*/
/* #undef HAVE_STD_HASH_MAP */
/*
* Define if your compiler has __gnu_cxx::hash_map/hash_set
*/
/* #undef HAVE_GNU_CXX_HASH_MAP */
/*
* Define if your compiler has std::unordered_map
*/
/* #undef HAVE_STD_UNORDERED_MAP */
/*
* Define if your compiler has std::unordered_set
*/
/* #undef HAVE_STD_UNORDERED_SET */
/*
* Define if your compiler has std::tr1::unordered_map
*/
/* #undef HAVE_TR1_UNORDERED_MAP */
/*
* Define if your compiler has std::tr1::unordered_set
*/
/* #undef HAVE_TR1_UNORDERED_SET */
/*
* Define if your compiler has <tr1/type_traits>
*/
#define HAVE_TR1_TYPE_TRAITS 1
/*
* Define if your compiler has <type_traits>
*/
/* #undef HAVE_TYPE_TRAITS */
/*
* Define if the compiler supports simple visibility declarations.
*/
#define HAVE_VISIBILITY 1
/*
* Define if the compiler supports GCC's atomic memory access builtins
*/
#define HAVE_GCC_ATOMIC_BUILTINS 1
/*
* Define if compiler's visibility support in libstdc++ is broken
*/
/* #undef HAVE_BROKEN_LIBSTDCXX_VISIBILITY */
/*
* The built-in regex supports advanced REs in additional to POSIX's basic
* and extended. Your system regex probably won't support this, and in this
* case WX_NO_REGEX_ADVANCED should be defined.
*/
/* #undef WX_NO_REGEX_ADVANCED */
/*
* On GNU systems use re_search instead of regexec, since the latter does a
* strlen on the search text affecting the performance of some operations.
*/
/* #undef HAVE_RE_SEARCH */
/*
* Use SDL for audio (Unix)
*/
#define wxUSE_LIBSDL 0
/*
* Compile sound backends as plugins
*/
#define wxUSE_PLUGINS 0
/*
* Use GTK print for printing under GTK+ 2.10+
*/
#define wxUSE_GTKPRINT 1
/*
* Use GNOME VFS for MIME types
*/
#define wxUSE_LIBGNOMEVFS 0
/*
* Use libnotify library.
*/
#define wxUSE_LIBNOTIFY 0
/*
* Use libnotify 0.7+ API.
*/
#define wxUSE_LIBNOTIFY_0_7 0
/*
* Use libXpm
*/
#define wxHAVE_LIB_XPM 0
/*
* Define if you have pthread_cleanup_push/pop()
*/
#define wxHAVE_PTHREAD_CLEANUP 1
/*
* Define if compiler has __thread keyword.
*/
/* #undef HAVE___THREAD_KEYWORD */
/*
* Define if large (64 bit file offsets) files are supported.
*/
#define HAVE_LARGEFILE_SUPPORT 1
/*
* Use OpenGL
*/
#define wxUSE_OPENGL 1
/*
* Use MS HTML Help via libmspack (Unix)
*/
#define wxUSE_LIBMSPACK 0
/*
* Matthews garbage collection (used for MrEd?)
*/
#define WXGARBAGE_COLLECTION_ON 0
/*
* wxWebKitCtrl
*/
#define wxUSE_WEBKIT 0
/*
* The const keyword is being introduced more in wxWindows.
* You can use this setting to maintain backward compatibility.
* If 0: will use const wherever possible.
* If 1: will use const only where necessary
* for precompiled headers to work.
* If 2: will be totally backward compatible, but precompiled
* headers may not work and program size will be larger.
*/
#define CONST_COMPATIBILITY 0
/*
* use the session manager to detect KDE/GNOME
*/
#define wxUSE_DETECT_SM 1
/* define with the name of timezone variable */
#define WX_TIMEZONE timezone
/* The type of 3rd argument to getsockname() - usually size_t or int */
#define WX_SOCKLEN_T socklen_t
/* The type of 5th argument to getsockopt() - usually size_t or int */
#define SOCKOPTLEN_T socklen_t
/* The type of statvfs(2) argument */
#define WX_STATFS_T struct statfs
/* The signal handler prototype */
#define wxTYPE_SA_HANDLER int
/* gettimeofday() usually takes 2 arguments, but some really old systems might
* have only one, in which case define WX_GETTIMEOFDAY_NO_TZ */
/* #undef WX_GETTIMEOFDAY_NO_TZ */
/* struct tm doesn't always have the tm_gmtoff field, define this if it does */
#define WX_GMTOFF_IN_TM 1
/* check if nl_langinfo() can be called with argument _NL_TIME_FIRST_WEEKDAY */
#define HAVE_NL_TIME_FIRST_WEEKDAY 1
/* Define if you have poll(2) function */
/* #undef HAVE_POLL */
/* Define if you have pw_gecos field in struct passwd */
#define HAVE_PW_GECOS 1
/* Define if you have __cxa_demangle() in <cxxabi.h> */
#define HAVE_CXA_DEMANGLE 1
/* Define if you have dlopen() */
#define HAVE_DLOPEN 1
/* Define if you have gettimeofday() */
#define HAVE_GETTIMEOFDAY 1
/* Define if fsync() is available */
#define HAVE_FSYNC 1
/* Define if round() is available */
#define HAVE_ROUND 1
/* Define if you have ftime() */
/* #undef HAVE_FTIME */
/* Define if you have nanosleep() */
#define HAVE_NANOSLEEP 1
/* Define if you have sched_yield */
#define HAVE_SCHED_YIELD 1
/* Define if you have pthread_mutexattr_t and functions to work with it */
#define HAVE_PTHREAD_MUTEXATTR_T 1
/* Define if you have pthread_mutexattr_settype() declaration */
#define HAVE_PTHREAD_MUTEXATTR_SETTYPE_DECL 1
/* Define if you have PTHREAD_RECURSIVE_MUTEX_INITIALIZER_NP */
/* #undef HAVE_PTHREAD_RECURSIVE_MUTEX_INITIALIZER */
/* Define if you have pthread_cancel */
#define HAVE_PTHREAD_CANCEL 1
/* Define if you have pthread_mutex_timedlock */
#define HAVE_PTHREAD_MUTEX_TIMEDLOCK 1
/* Define if you have pthread_attr_setstacksize */
#define HAVE_PTHREAD_ATTR_SETSTACKSIZE 1
/* Define if you have shl_load() */
/* #undef HAVE_SHL_LOAD */
/* Define if you have snprintf() */
#define HAVE_SNPRINTF 1
/* Define if you have snprintf() declaration in the header */
#define HAVE_SNPRINTF_DECL 1
/* Define if you have a snprintf() which supports positional arguments
(defined in the unix98 standard) */
#define HAVE_UNIX98_PRINTF 1
/* define if you have statfs function */
#define HAVE_STATFS 1
/* define if you have statfs prototype */
#define HAVE_STATFS_DECL 1
/* define if you have statvfs function */
/* #undef HAVE_STATVFS */
/* Define if you have strtoull() and strtoll() */
#define HAVE_STRTOULL 1
/* Define if you have all functions to set thread priority */
#define HAVE_THREAD_PRIORITY_FUNCTIONS 1
/* Define if you have vsnprintf() */
#define HAVE_VSNPRINTF 1
/* Define if you have vsnprintf() declaration in the header */
#define HAVE_VSNPRINTF_DECL 1
/* Define if you have a _broken_ vsnprintf() declaration in the header,
* with 'char*' for the 3rd parameter instead of 'const char*' */
/* #undef HAVE_BROKEN_VSNPRINTF_DECL */
/* Define if you have a _broken_ vsscanf() declaration in the header,
* with 'char*' for the 1st parameter instead of 'const char*' */
/* #undef HAVE_BROKEN_VSSCANF_DECL */
/* Define if you have vsscanf() */
#define HAVE_VSSCANF 1
/* Define if you have vsscanf() declaration in the header */
#define HAVE_VSSCANF_DECL 1
/* Define if you have usleep() */
/* #undef HAVE_USLEEP */
/* Define if you have wcscasecmp() function */
#define HAVE_WCSCASECMP 1
/* Define if you have wcsncasecmp() function */
#define HAVE_WCSNCASECMP 1
/* Define if you have wcslen function */
#define HAVE_WCSLEN 1
/* Define if you have wcsdup function */
#define HAVE_WCSDUP 1
/* Define if you have wcsftime() function */
#define HAVE_WCSFTIME 1
/* Define if you have strnlen() function */
#define HAVE_STRNLEN 1
/* Define if you have wcsnlen() function */
#define HAVE_WCSNLEN 1
/* Define if you have wcstoull() and wcstoll() */
/* #undef HAVE_WCSTOULL */
/* The number of bytes in a wchar_t. */
#define SIZEOF_WCHAR_T 4
/* The number of bytes in a int. */
#define SIZEOF_INT 4
/* The number of bytes in a pointer. */
#define SIZEOF_VOID_P 8
/* The number of bytes in a long. */
#define SIZEOF_LONG 8
/* The number of bytes in a long long. */
#define SIZEOF_LONG_LONG 8
/* The number of bytes in a short. */
#define SIZEOF_SHORT 2
/* The number of bytes in a size_t. */
#define SIZEOF_SIZE_T 8
/* Define if size_t on your machine is the same type as unsigned int. */
/* #undef wxSIZE_T_IS_UINT */
/* Define if size_t on your machine is the same type as unsigned long. */
#define wxSIZE_T_IS_ULONG 1
/* Define if wchar_t is distinct type in your compiler. */
#define wxWCHAR_T_IS_REAL_TYPE 1
/* Define if you have the dlerror function. */
#define HAVE_DLERROR 1
/* Define if you have the dladdr function. */
#define HAVE_DLADDR 1
/* Define if you have Posix fnctl() function. */
#define HAVE_FCNTL 1
/* Define if you have BSD flock() function. */
/* #undef HAVE_FLOCK */
/* Define if you have getaddrinfo function. */
/* #undef HAVE_GETADDRINFO */
/* Define if you have a gethostbyname_r function taking 6 arguments. */
#define HAVE_FUNC_GETHOSTBYNAME_R_6 1
/* Define if you have a gethostbyname_r function taking 5 arguments. */
/* #undef HAVE_FUNC_GETHOSTBYNAME_R_5 */
/* Define if you have a gethostbyname_r function taking 3 arguments. */
/* #undef HAVE_FUNC_GETHOSTBYNAME_R_3 */
/* Define if you only have a gethostbyname function */
/* #undef HAVE_GETHOSTBYNAME */
/* Define if you have the gethostname function. */
/* #undef HAVE_GETHOSTNAME */
/* Define if you have a getservbyname_r function taking 6 arguments. */
#define HAVE_FUNC_GETSERVBYNAME_R_6 1
/* Define if you have a getservbyname_r function taking 5 arguments. */
/* #undef HAVE_FUNC_GETSERVBYNAME_R_5 */
/* Define if you have a getservbyname_r function taking 4 arguments. */
/* #undef HAVE_FUNC_GETSERVBYNAME_R_4 */
/* Define if you only have a getservbyname function */
/* #undef HAVE_GETSERVBYNAME */
/* Define if you have the gmtime_r function. */
#define HAVE_GMTIME_R 1
/* Define if you have the inet_addr function. */
#define HAVE_INET_ADDR 1
/* Define if you have the inet_aton function. */
#define HAVE_INET_ATON 1
/* Define if you have the localtime_r function. */
#define HAVE_LOCALTIME_R 1
/* Define if you have the mktemp function. */
/* #undef HAVE_MKTEMP */
/* Define if you have the mkstemp function. */
#define HAVE_MKSTEMP 1
/* Define if you have the putenv function. */
/* #undef HAVE_PUTENV */
/* Define if you have the setenv function. */
#define HAVE_SETENV 1
/* Define if you have strtok_r function. */
#define HAVE_STRTOK_R 1
/* Define if you have thr_setconcurrency function */
/* #undef HAVE_THR_SETCONCURRENCY */
/* Define if you have pthread_setconcurrency function */
#define HAVE_PTHREAD_SET_CONCURRENCY 1
/* Define if you have the uname function. */
#define HAVE_UNAME 1
/* Define if you have the unsetenv function. */
#define HAVE_UNSETENV 1
/* Define if you have the <X11/XKBlib.h> header file. */
#define HAVE_X11_XKBLIB_H 1
/* Define if you have the <X11/extensions/xf86vmode.h> header file. */
#define HAVE_X11_EXTENSIONS_XF86VMODE_H 1
/* Define if you have the <sched.h> header file. */
#define HAVE_SCHED_H 1
/* Define if you have the <unistd.h> header file. */
#define HAVE_UNISTD_H 1
/* Define if you have the <fcntl.h> header file. */
/* #undef HAVE_FCNTL_H */
/* Define if you have the <wchar.h> header file. */
#define HAVE_WCHAR_H 1
/* Define if you have the <wcstr.h> header file. */
/* #undef HAVE_WCSTR_H */
/* Define if you have <widec.h> (Solaris only) */
/* #undef HAVE_WIDEC_H */
/* Define if you have the <iconv.h> header file and iconv() symbol. */
#define HAVE_ICONV 1
/* Define as "const" if the declaration of iconv() needs const. */
#define ICONV_CONST
/* Define if you have the <langinfo.h> header file. */
#define HAVE_LANGINFO_H 1
/* Define if you have the <w32api.h> header file (mingw,cygwin). */
/* #undef HAVE_W32API_H */
/* Define if you have the <sys/soundcard.h> header file. */
#define HAVE_SYS_SOUNDCARD_H 1
/* Define if you have wcsrtombs() function */
#define HAVE_WCSRTOMBS 1
/* Define this if you have putws() */
/* #undef HAVE_PUTWS */
/* Define this if you have fputws() */
#define HAVE_FPUTWS 1
/* Define this if you have wprintf() and related functions */
#define HAVE_WPRINTF 1
/* Define this if you have vswprintf() and related functions */
#define HAVE_VSWPRINTF 1
/* Define this if you have _vsnwprintf */
/* #undef HAVE__VSNWPRINTF */
/* vswscanf() */
#define HAVE_VSWSCANF 1
/* Define if fseeko and ftello are available. */
#define HAVE_FSEEKO 1
/* Define this if you are using gtk and gdk contains support for X11R6 XIM */
/* #undef HAVE_XIM */
/* Define this if you have X11/extensions/shape.h */
/* #undef HAVE_XSHAPE */
/* Define this if you have type SPBCDATA */
/* #undef HAVE_SPBCDATA */
/* Define if you have pango_font_family_is_monospace() (Pango >= 1.3.3) */
/* #undef HAVE_PANGO_FONT_FAMILY_IS_MONOSPACE */
/* Define if you have Pango xft support */
/* #undef HAVE_PANGO_XFT */
/* Define if you have the <sys/select.h> header file. */
#define HAVE_SYS_SELECT_H 1
/* Define if you have abi::__forced_unwind in your <cxxabi.h>. */
#define HAVE_ABI_FORCEDUNWIND 1
/* Define if fdopen is available. */
#define HAVE_FDOPEN 1
/* Define if sysconf is available. */
#define HAVE_SYSCONF 1
/* Define if getpwuid_r is available. */
#define HAVE_GETPWUID_R 1
/* Define if getgrgid_r is available. */
#define HAVE_GETGRGID_R 1
/* Define if setpriority() is available. */
#define HAVE_SETPRIORITY 1
/* Define if xlocale.h header file exists. */
#define HAVE_XLOCALE_H 1
/* Define if locale_t is available */
#define HAVE_LOCALE_T 1
/* Define if you have inotify_xxx() functions. */
#define wxHAS_INOTIFY 1
/* Define if you have kqueu_xxx() functions. */
/* #undef wxHAS_KQUEUE */
/* -------------------------------------------------------------------------
Win32 adjustments section
------------------------------------------------------------------------- */
#ifdef __WIN32__
/* When using an external jpeg library and the Windows headers already define
* boolean, define to the type used by the jpeg library for boolean. */
/* #undef wxHACK_BOOLEAN */
/* Define if the header pbt.h is missing. */
/* #undef NEED_PBT_H */
#endif /* __WIN32__ */
/* --------------------------------------------------------*
* This stuff is static, it doesn't get modified directly
* by configure.
*/
/*
define some constants identifying wxWindows version in more details than
just the version number
*/
/* wxLogChain class available */
#define wxHAS_LOG_CHAIN
/* define this when wxDC::Blit() respects SetDeviceOrigin() in wxGTK */
/* #undef wxHAS_WORKING_GTK_DC_BLIT */
#endif /* __WX_SETUP_H__ */
|
h
|
rticonnextdds-usecases
|
data/projects/rticonnextdds-usecases/VehicleTracking/ExampleCode/thirdparty/wxWidgets-3.1.2/Linux/include/wx/metafile.h
|
///////////////////////////////////////////////////////////////////////////////
// Name: wx/metafile.h
// Purpose: wxMetaFile class declaration
// Author: wxWidgets team
// Modified by:
// Created: 13.01.00
// Copyright: (c) wxWidgets team
// Licence: wxWindows licence
///////////////////////////////////////////////////////////////////////////////
#ifndef _WX_METAFILE_H_BASE_
#define _WX_METAFILE_H_BASE_
#include "wx/defs.h"
#if wxUSE_METAFILE
// provide synonyms for all metafile classes
#define wxMetaFile wxMetafile
#define wxMetaFileDC wxMetafileDC
#define wxMetaFileDataObject wxMetafileDataObject
#define wxMakeMetaFilePlaceable wxMakeMetafilePlaceable
#if defined(__WXMSW__)
#if wxUSE_ENH_METAFILE
#include "wx/msw/enhmeta.h"
#if wxUSE_WIN_METAFILES_ALWAYS
// use normal metafiles as well
#include "wx/msw/metafile.h"
#else // also map all metafile classes to enh metafile
typedef wxEnhMetaFile wxMetafile;
typedef wxEnhMetaFileDC wxMetafileDC;
#if wxUSE_DATAOBJ
typedef wxEnhMetaFileDataObject wxMetafileDataObject;
#endif
// this flag will be set if wxMetafile class is wxEnhMetaFile
#define wxMETAFILE_IS_ENH
#endif // wxUSE_WIN_METAFILES_ALWAYS
#else // !wxUSE_ENH_METAFILE
#include "wx/msw/metafile.h"
#endif
#elif defined(__WXMAC__)
#include "wx/osx/metafile.h"
#endif
#endif // wxUSE_METAFILE
#endif // _WX_METAFILE_H_BASE_
|
h
|
rticonnextdds-usecases
|
data/projects/rticonnextdds-usecases/VehicleTracking/ExampleCode/thirdparty/wxWidgets-3.1.2/Linux/include/wx/fs_zip.h
|
/////////////////////////////////////////////////////////////////////////////
// Name: wx/fs_zip.h
// Purpose: wxZipFSHandler typedef for compatibility
// Author: Mike Wetherell
// Copyright: (c) 2006 Mike Wetherell
// Licence: wxWindows licence
/////////////////////////////////////////////////////////////////////////////
#ifndef _WX_FS_ZIP_H_
#define _WX_FS_ZIP_H_
#include "wx/defs.h"
#if wxUSE_FS_ZIP
#include "wx/fs_arc.h"
typedef wxArchiveFSHandler wxZipFSHandler;
#endif // wxUSE_FS_ZIP
#endif // _WX_FS_ZIP_H_
|
h
|
rticonnextdds-usecases
|
data/projects/rticonnextdds-usecases/VehicleTracking/ExampleCode/thirdparty/wxWidgets-3.1.2/Linux/include/wx/imagbmp.h
|
/////////////////////////////////////////////////////////////////////////////
// Name: wx/imagbmp.h
// Purpose: wxImage BMP, ICO, CUR and ANI handlers
// Author: Robert Roebling, Chris Elliott
// Copyright: (c) Robert Roebling, Chris Elliott
// Licence: wxWindows licence
/////////////////////////////////////////////////////////////////////////////
#ifndef _WX_IMAGBMP_H_
#define _WX_IMAGBMP_H_
#include "wx/image.h"
// defines for saving the BMP file in different formats, Bits Per Pixel
// USE: wximage.SetOption( wxIMAGE_OPTION_BMP_FORMAT, wxBMP_xBPP );
#define wxIMAGE_OPTION_BMP_FORMAT wxString(wxT("wxBMP_FORMAT"))
// These two options are filled in upon reading CUR file and can (should) be
// specified when saving a CUR file - they define the hotspot of the cursor:
#define wxIMAGE_OPTION_CUR_HOTSPOT_X wxT("HotSpotX")
#define wxIMAGE_OPTION_CUR_HOTSPOT_Y wxT("HotSpotY")
enum
{
wxBMP_24BPP = 24, // default, do not need to set
//wxBMP_16BPP = 16, // wxQuantize can only do 236 colors?
wxBMP_8BPP = 8, // 8bpp, quantized colors
wxBMP_8BPP_GREY = 9, // 8bpp, rgb averaged to greys
wxBMP_8BPP_GRAY = wxBMP_8BPP_GREY,
wxBMP_8BPP_RED = 10, // 8bpp, red used as greyscale
wxBMP_8BPP_PALETTE = 11, // 8bpp, use the wxImage's palette
wxBMP_4BPP = 4, // 4bpp, quantized colors
wxBMP_1BPP = 1, // 1bpp, quantized "colors"
wxBMP_1BPP_BW = 2 // 1bpp, black & white from red
};
// ----------------------------------------------------------------------------
// wxBMPHandler
// ----------------------------------------------------------------------------
class WXDLLIMPEXP_CORE wxBMPHandler : public wxImageHandler
{
public:
wxBMPHandler()
{
m_name = wxT("Windows bitmap file");
m_extension = wxT("bmp");
m_type = wxBITMAP_TYPE_BMP;
m_mime = wxT("image/x-bmp");
}
#if wxUSE_STREAMS
virtual bool SaveFile( wxImage *image, wxOutputStream& stream, bool verbose=true ) wxOVERRIDE;
virtual bool LoadFile( wxImage *image, wxInputStream& stream, bool verbose=true, int index=-1 ) wxOVERRIDE;
protected:
virtual bool DoCanRead( wxInputStream& stream ) wxOVERRIDE;
bool SaveDib(wxImage *image, wxOutputStream& stream, bool verbose,
bool IsBmp, bool IsMask);
bool DoLoadDib(wxImage *image, int width, int height, int bpp, int ncolors,
int comp, wxFileOffset bmpOffset, wxInputStream& stream,
bool verbose, bool IsBmp, bool hasPalette, int colEntrySize = 4);
bool LoadDib(wxImage *image, wxInputStream& stream, bool verbose, bool IsBmp);
#endif // wxUSE_STREAMS
private:
wxDECLARE_DYNAMIC_CLASS(wxBMPHandler);
};
#if wxUSE_ICO_CUR
// ----------------------------------------------------------------------------
// wxICOHandler
// ----------------------------------------------------------------------------
class WXDLLIMPEXP_CORE wxICOHandler : public wxBMPHandler
{
public:
wxICOHandler()
{
m_name = wxT("Windows icon file");
m_extension = wxT("ico");
m_type = wxBITMAP_TYPE_ICO;
m_mime = wxT("image/x-ico");
}
#if wxUSE_STREAMS
virtual bool SaveFile( wxImage *image, wxOutputStream& stream, bool verbose=true ) wxOVERRIDE;
virtual bool LoadFile( wxImage *image, wxInputStream& stream, bool verbose=true, int index=-1 ) wxOVERRIDE;
virtual bool DoLoadFile( wxImage *image, wxInputStream& stream, bool verbose, int index );
protected:
virtual int DoGetImageCount( wxInputStream& stream ) wxOVERRIDE;
virtual bool DoCanRead( wxInputStream& stream ) wxOVERRIDE;
#endif // wxUSE_STREAMS
private:
wxDECLARE_DYNAMIC_CLASS(wxICOHandler);
};
// ----------------------------------------------------------------------------
// wxCURHandler
// ----------------------------------------------------------------------------
class WXDLLIMPEXP_CORE wxCURHandler : public wxICOHandler
{
public:
wxCURHandler()
{
m_name = wxT("Windows cursor file");
m_extension = wxT("cur");
m_type = wxBITMAP_TYPE_CUR;
m_mime = wxT("image/x-cur");
}
// VS: This handler's meat is implemented inside wxICOHandler (the two
// formats are almost identical), but we hide this fact at
// the API level, since it is a mere implementation detail.
protected:
#if wxUSE_STREAMS
virtual bool DoCanRead( wxInputStream& stream ) wxOVERRIDE;
#endif // wxUSE_STREAMS
private:
wxDECLARE_DYNAMIC_CLASS(wxCURHandler);
};
// ----------------------------------------------------------------------------
// wxANIHandler
// ----------------------------------------------------------------------------
class WXDLLIMPEXP_CORE wxANIHandler : public wxCURHandler
{
public:
wxANIHandler()
{
m_name = wxT("Windows animated cursor file");
m_extension = wxT("ani");
m_type = wxBITMAP_TYPE_ANI;
m_mime = wxT("image/x-ani");
}
#if wxUSE_STREAMS
virtual bool SaveFile( wxImage *WXUNUSED(image), wxOutputStream& WXUNUSED(stream), bool WXUNUSED(verbose=true) ) wxOVERRIDE{return false ;}
virtual bool LoadFile( wxImage *image, wxInputStream& stream, bool verbose=true, int index=-1 ) wxOVERRIDE;
protected:
virtual int DoGetImageCount( wxInputStream& stream ) wxOVERRIDE;
virtual bool DoCanRead( wxInputStream& stream ) wxOVERRIDE;
#endif // wxUSE_STREAMS
private:
wxDECLARE_DYNAMIC_CLASS(wxANIHandler);
};
#endif // wxUSE_ICO_CUR
#endif // _WX_IMAGBMP_H_
|
h
|
rticonnextdds-usecases
|
data/projects/rticonnextdds-usecases/VehicleTracking/ExampleCode/thirdparty/wxWidgets-3.1.2/Linux/include/wx/cpp.h
|
/*
* Name: wx/cpp.h
* Purpose: Various preprocessor helpers
* Author: Vadim Zeitlin
* Created: 2006-09-30
* Copyright: (c) 2006 Vadim Zeitlin <[email protected]>
* Licence: wxWindows licence
*/
/* THIS IS A C FILE, DON'T USE C++ FEATURES (IN PARTICULAR COMMENTS) IN IT */
#ifndef _WX_CPP_H_
#define _WX_CPP_H_
#include "wx/compiler.h" /* wxCHECK_XXX_VERSION() macros */
/* wxCONCAT works like preprocessor ## operator but also works with macros */
#define wxCONCAT_HELPER(text, line) text ## line
#define wxCONCAT(x1, x2) \
wxCONCAT_HELPER(x1, x2)
#define wxCONCAT3(x1, x2, x3) \
wxCONCAT(wxCONCAT(x1, x2), x3)
#define wxCONCAT4(x1, x2, x3, x4) \
wxCONCAT(wxCONCAT3(x1, x2, x3), x4)
#define wxCONCAT5(x1, x2, x3, x4, x5) \
wxCONCAT(wxCONCAT4(x1, x2, x3, x4), x5)
#define wxCONCAT6(x1, x2, x3, x4, x5, x6) \
wxCONCAT(wxCONCAT5(x1, x2, x3, x4, x5), x6)
#define wxCONCAT7(x1, x2, x3, x4, x5, x6, x7) \
wxCONCAT(wxCONCAT6(x1, x2, x3, x4, x5, x6), x7)
#define wxCONCAT8(x1, x2, x3, x4, x5, x6, x7, x8) \
wxCONCAT(wxCONCAT7(x1, x2, x3, x4, x5, x6, x7), x8)
#define wxCONCAT9(x1, x2, x3, x4, x5, x6, x7, x8, x9) \
wxCONCAT(wxCONCAT8(x1, x2, x3, x4, x5, x6, x7, x8), x9)
/* wxSTRINGIZE works as the preprocessor # operator but also works with macros */
#define wxSTRINGIZE_HELPER(x) #x
#define wxSTRINGIZE(x) wxSTRINGIZE_HELPER(x)
/* a Unicode-friendly version of wxSTRINGIZE_T */
#define wxSTRINGIZE_T(x) wxAPPLY_T(wxSTRINGIZE(x))
/*
Special workarounds for compilers with broken "##" operator. For all the
other ones we can just use it directly.
*/
#ifdef wxCOMPILER_BROKEN_CONCAT_OPER
#define wxPREPEND_L(x) L ## x
#define wxAPPEND_i64(x) x ## i64
#define wxAPPEND_ui64(x) x ## ui64
#endif /* wxCOMPILER_BROKEN_CONCAT_OPER */
/*
Helper macros for wxMAKE_UNIQUE_NAME: normally this works by appending the
current line number to the given identifier to reduce the probability of the
conflict (it may still happen if this is used in the headers, hence you
should avoid doing it or provide unique prefixes then) but we have to do it
differently for VC++
*/
#if defined(__VISUALC__)
/*
__LINE__ handling is completely broken in VC++ when using "Edit and
Continue" (/ZI option) and results in preprocessor errors if we use it
inside the macros. Luckily VC7 has another standard macro which can be
used like this and is even better than __LINE__ because it is globally
unique.
*/
# define wxCONCAT_LINE(text) wxCONCAT(text, __COUNTER__)
#else /* normal compilers */
# define wxCONCAT_LINE(text) wxCONCAT(text, __LINE__)
#endif
/* Create a "unique" name with the given prefix */
#define wxMAKE_UNIQUE_NAME(text) wxCONCAT_LINE(text)
/*
This macro can be passed as argument to another macro when you don't have
anything to pass in fact.
*/
#define wxEMPTY_PARAMETER_VALUE /* Fake macro parameter value */
/*
Helpers for defining macros that expand into a single statement.
The standard solution is to use "do { ... } while (0)" statement but MSVC
generates a C4127 "condition expression is constant" warning for it so we
use something which is just complicated enough to not be recognized as a
constant but still simple enough to be optimized away.
Another solution would be to use __pragma() to temporarily disable C4127.
Notice that wxASSERT_ARG_TYPE in wx/strvargarg.h relies on these macros
creating some kind of a loop because it uses "break".
*/
#define wxSTATEMENT_MACRO_BEGIN do {
#define wxSTATEMENT_MACRO_END } while ( (void)0, 0 )
/*
Define __WXFUNCTION__ which is like standard __FUNCTION__ but defined as
NULL for the compilers which don't support the latter.
*/
#ifndef __WXFUNCTION__
#if defined(__GNUC__) || \
defined(__VISUALC__) || \
defined(__FUNCTION__)
#define __WXFUNCTION__ __FUNCTION__
#else
/* still define __WXFUNCTION__ to avoid #ifdefs elsewhere */
#define __WXFUNCTION__ (NULL)
#endif
#endif /* __WXFUNCTION__ already defined */
/* Auto-detect variadic macros support unless explicitly disabled. */
#if !defined(HAVE_VARIADIC_MACROS) && !defined(wxNO_VARIADIC_MACROS)
/* Any C99 or C++11 compiler should have them. */
#if (defined(__STDC_VERSION__) && __STDC_VERSION__ >= 199901L) || \
(defined(__cplusplus) && __cplusplus >= 201103L)
#define HAVE_VARIADIC_MACROS 1
#elif defined(__GNUC__)
#define HAVE_VARIADIC_MACROS 1
#elif wxCHECK_VISUALC_VERSION(8)
#define HAVE_VARIADIC_MACROS 1
#endif
#endif /* !HAVE_VARIADIC_MACROS */
#ifdef HAVE_VARIADIC_MACROS
/*
This is a hack to make it possible to use variadic macros with g++ 3.x even
when using -pedantic[-errors] option: without this, it would complain that
"anonymous variadic macros were introduced in C99"
and the option disabling this warning (-Wno-variadic-macros) is only
available in gcc 4.0 and later, so until then this hack is the only thing we
can do.
*/
#if defined(__GNUC__) && __GNUC__ == 3
#pragma GCC system_header
#endif /* gcc-3.x */
/*
wxCALL_FOR_EACH(what, ...) calls the macro from its first argument, what(pos, x),
for every remaining argument 'x', with 'pos' being its 1-based index in
*reverse* order (with the last argument being numbered 1).
For example, wxCALL_FOR_EACH(test, a, b, c) expands into this:
test(3, a) \
test(2, b) \
test(1, c)
Up to eight arguments are supported.
(With thanks to https://groups.google.com/d/topic/comp.std.c/d-6Mj5Lko_s/discussion
and https://stackoverflow.com/questions/1872220/is-it-possible-to-iterate-over-arguments-in-variadic-macros)
*/
#define wxCALL_FOR_EACH_NARG(...) wxCALL_FOR_EACH_NARG_((__VA_ARGS__, wxCALL_FOR_EACH_RSEQ_N()))
#define wxCALL_FOR_EACH_NARG_(args) wxCALL_FOR_EACH_ARG_N args
#define wxCALL_FOR_EACH_ARG_N(_1, _2, _3, _4, _5, _6, _7, _8, N, ...) N
#define wxCALL_FOR_EACH_RSEQ_N() 8, 7, 6, 5, 4, 3, 2, 1, 0
#define wxCALL_FOR_EACH_1_(args) wxCALL_FOR_EACH_1 args
#define wxCALL_FOR_EACH_2_(args) wxCALL_FOR_EACH_2 args
#define wxCALL_FOR_EACH_3_(args) wxCALL_FOR_EACH_3 args
#define wxCALL_FOR_EACH_4_(args) wxCALL_FOR_EACH_4 args
#define wxCALL_FOR_EACH_5_(args) wxCALL_FOR_EACH_5 args
#define wxCALL_FOR_EACH_6_(args) wxCALL_FOR_EACH_6 args
#define wxCALL_FOR_EACH_7_(args) wxCALL_FOR_EACH_7 args
#define wxCALL_FOR_EACH_8_(args) wxCALL_FOR_EACH_8 args
#define wxCALL_FOR_EACH_1(what, x) what(1, x)
#define wxCALL_FOR_EACH_2(what, x, ...) what(2, x) wxCALL_FOR_EACH_1_((what, __VA_ARGS__))
#define wxCALL_FOR_EACH_3(what, x, ...) what(3, x) wxCALL_FOR_EACH_2_((what, __VA_ARGS__))
#define wxCALL_FOR_EACH_4(what, x, ...) what(4, x) wxCALL_FOR_EACH_3_((what, __VA_ARGS__))
#define wxCALL_FOR_EACH_5(what, x, ...) what(5, x) wxCALL_FOR_EACH_4_((what, __VA_ARGS__))
#define wxCALL_FOR_EACH_6(what, x, ...) what(6, x) wxCALL_FOR_EACH_5_((what, __VA_ARGS__))
#define wxCALL_FOR_EACH_7(what, x, ...) what(7, x) wxCALL_FOR_EACH_6_((what, __VA_ARGS__))
#define wxCALL_FOR_EACH_8(what, x, ...) what(8, x) wxCALL_FOR_EACH_7_((what, __VA_ARGS__))
#define wxCALL_FOR_EACH_(N, args) \
wxCONCAT(wxCALL_FOR_EACH_, N) args
#define wxCALL_FOR_EACH(what, ...) \
wxCALL_FOR_EACH_(wxCALL_FOR_EACH_NARG(__VA_ARGS__), (what, __VA_ARGS__))
#else
#define wxCALL_FOR_EACH Error_wx_CALL_FOR_EACH_requires_variadic_macros_support
#endif /* HAVE_VARIADIC_MACROS */
#endif /* _WX_CPP_H_ */
|
h
|
rticonnextdds-usecases
|
data/projects/rticonnextdds-usecases/VehicleTracking/ExampleCode/thirdparty/wxWidgets-3.1.2/Linux/include/wx/dcps.h
|
/////////////////////////////////////////////////////////////////////////////
// Name: wx/dcps.h
// Purpose: wxPostScriptDC base header
// Author: Julian Smart
// Modified by:
// Created:
// Copyright: (c) Julian Smart
// Licence: wxWindows Licence
/////////////////////////////////////////////////////////////////////////////
#ifndef _WX_DCPS_H_BASE_
#define _WX_DCPS_H_BASE_
#include "wx/generic/dcpsg.h"
#endif
|
h
|
rticonnextdds-usecases
|
data/projects/rticonnextdds-usecases/VehicleTracking/ExampleCode/thirdparty/wxWidgets-3.1.2/Linux/include/wx/helpwin.h
|
/////////////////////////////////////////////////////////////////////////////
// Name: wx/helpwin.h
// Purpose: Includes Windows help
// Author: Julian Smart
// Modified by:
// Created:
// Copyright: (c) Julian Smart
// Licence: wxWindows licence
/////////////////////////////////////////////////////////////////////////////
#ifndef _WX_HELPWIN_H_BASE_
#define _WX_HELPWIN_H_BASE_
#if defined(__WXMSW__)
#include "wx/msw/helpwin.h"
#endif
#endif
// _WX_HELPWIN_H_BASE_
|
h
|
rticonnextdds-usecases
|
data/projects/rticonnextdds-usecases/VehicleTracking/ExampleCode/thirdparty/wxWidgets-3.1.2/Linux/include/wx/dcclient.h
|
/////////////////////////////////////////////////////////////////////////////
// Name: wx/dcclient.h
// Purpose: wxClientDC base header
// Author: Julian Smart
// Copyright: (c) Julian Smart
// Licence: wxWindows Licence
/////////////////////////////////////////////////////////////////////////////
#ifndef _WX_DCCLIENT_H_BASE_
#define _WX_DCCLIENT_H_BASE_
#include "wx/dc.h"
//-----------------------------------------------------------------------------
// wxWindowDC
//-----------------------------------------------------------------------------
class WXDLLIMPEXP_CORE wxWindowDC : public wxDC
{
public:
wxWindowDC(wxWindow *win);
protected:
wxWindowDC(wxDCImpl *impl) : wxDC(impl) { }
private:
wxDECLARE_ABSTRACT_CLASS(wxWindowDC);
};
//-----------------------------------------------------------------------------
// wxClientDC
//-----------------------------------------------------------------------------
class WXDLLIMPEXP_CORE wxClientDC : public wxWindowDC
{
public:
wxClientDC(wxWindow *win);
protected:
wxClientDC(wxDCImpl *impl) : wxWindowDC(impl) { }
private:
wxDECLARE_ABSTRACT_CLASS(wxClientDC);
};
//-----------------------------------------------------------------------------
// wxPaintDC
//-----------------------------------------------------------------------------
class WXDLLIMPEXP_CORE wxPaintDC : public wxClientDC
{
public:
wxPaintDC(wxWindow *win);
protected:
wxPaintDC(wxDCImpl *impl) : wxClientDC(impl) { }
private:
wxDECLARE_ABSTRACT_CLASS(wxPaintDC);
};
#endif // _WX_DCCLIENT_H_BASE_
|
h
|
rticonnextdds-usecases
|
data/projects/rticonnextdds-usecases/VehicleTracking/ExampleCode/thirdparty/wxWidgets-3.1.2/Linux/include/wx/platinfo.h
|
///////////////////////////////////////////////////////////////////////////////
// Name: wx/platinfo.h
// Purpose: declaration of the wxPlatformInfo class
// Author: Francesco Montorsi
// Modified by:
// Created: 07.07.2006 (based on wxToolkitInfo)
// Copyright: (c) 2006 Francesco Montorsi
// Licence: wxWindows licence
///////////////////////////////////////////////////////////////////////////////
#ifndef _WX_PLATINFO_H_
#define _WX_PLATINFO_H_
#include "wx/string.h"
// ----------------------------------------------------------------------------
// wxPlatformInfo enums & structs
// ----------------------------------------------------------------------------
// VERY IMPORTANT: when changing these enum values, also change the relative
// string tables in src/common/platinfo.cpp
// families & sub-families of operating systems
enum wxOperatingSystemId
{
wxOS_UNKNOWN = 0, // returned on error
wxOS_MAC_OS = 1 << 0, // Apple Mac OS 8/9/X with Mac paths
wxOS_MAC_OSX_DARWIN = 1 << 1, // Apple Mac OS X with Unix paths
wxOS_MAC = wxOS_MAC_OS|wxOS_MAC_OSX_DARWIN,
wxOS_WINDOWS_9X = 1 << 2, // obsolete
wxOS_WINDOWS_NT = 1 << 3, // obsolete
wxOS_WINDOWS_MICRO = 1 << 4, // obsolete
wxOS_WINDOWS_CE = 1 << 5, // obsolete
wxOS_WINDOWS = wxOS_WINDOWS_9X |
wxOS_WINDOWS_NT |
wxOS_WINDOWS_MICRO |
wxOS_WINDOWS_CE,
wxOS_UNIX_LINUX = 1 << 6, // Linux
wxOS_UNIX_FREEBSD = 1 << 7, // FreeBSD
wxOS_UNIX_OPENBSD = 1 << 8, // OpenBSD
wxOS_UNIX_NETBSD = 1 << 9, // NetBSD
wxOS_UNIX_SOLARIS = 1 << 10, // SunOS
wxOS_UNIX_AIX = 1 << 11, // AIX
wxOS_UNIX_HPUX = 1 << 12, // HP/UX
wxOS_UNIX = wxOS_UNIX_LINUX |
wxOS_UNIX_FREEBSD |
wxOS_UNIX_OPENBSD |
wxOS_UNIX_NETBSD |
wxOS_UNIX_SOLARIS |
wxOS_UNIX_AIX |
wxOS_UNIX_HPUX,
// 1<<13 and 1<<14 available for other Unix flavours
wxOS_DOS = 1 << 15, // obsolete
wxOS_OS2 = 1 << 16 // obsolete
};
// list of wxWidgets ports - some of them can be used with more than
// a single toolkit.
enum wxPortId
{
wxPORT_UNKNOWN = 0, // returned on error
wxPORT_BASE = 1 << 0, // wxBase, no native toolkit used
wxPORT_MSW = 1 << 1, // wxMSW, native toolkit is Windows API
wxPORT_MOTIF = 1 << 2, // wxMotif, using [Open]Motif or Lesstif
wxPORT_GTK = 1 << 3, // wxGTK, using GTK+ 1.x, 2.x, 3.x
wxPORT_DFB = 1 << 4, // wxDFB, using wxUniversal
wxPORT_X11 = 1 << 5, // wxX11, using wxUniversal
wxPORT_PM = 1 << 6, // obsolete
wxPORT_OS2 = wxPORT_PM, // obsolete
wxPORT_MAC = 1 << 7, // wxOSX (former wxMac), using Cocoa or iPhone API
wxPORT_OSX = wxPORT_MAC, // wxOSX, using Cocoa or iPhone API
wxPORT_COCOA = 1 << 8, // wxCocoa, using Cocoa NextStep/Mac API
wxPORT_WINCE = 1 << 9, // obsolete
wxPORT_QT = 1 << 10 // wxQT, using QT4
};
// architecture of the operating system
// (regardless of the build environment of wxWidgets library - see
// wxIsPlatform64bit documentation for more info)
enum wxArchitecture
{
wxARCH_INVALID = -1, // returned on error
wxARCH_32, // 32 bit
wxARCH_64,
wxARCH_MAX
};
// endian-ness of the machine
enum wxEndianness
{
wxENDIAN_INVALID = -1, // returned on error
wxENDIAN_BIG, // 4321
wxENDIAN_LITTLE, // 1234
wxENDIAN_PDP, // 3412
wxENDIAN_MAX
};
// information about a linux distro returned by the lsb_release utility
struct wxLinuxDistributionInfo
{
wxString Id;
wxString Release;
wxString CodeName;
wxString Description;
bool operator==(const wxLinuxDistributionInfo& ldi) const
{
return Id == ldi.Id &&
Release == ldi.Release &&
CodeName == ldi.CodeName &&
Description == ldi.Description;
}
bool operator!=(const wxLinuxDistributionInfo& ldi) const
{ return !(*this == ldi); }
};
// ----------------------------------------------------------------------------
// wxPlatformInfo
// ----------------------------------------------------------------------------
// Information about the toolkit that the app is running under and some basic
// platform and architecture info
class WXDLLIMPEXP_BASE wxPlatformInfo
{
public:
wxPlatformInfo();
wxPlatformInfo(wxPortId pid,
int tkMajor = -1, int tkMinor = -1,
wxOperatingSystemId id = wxOS_UNKNOWN,
int osMajor = -1, int osMinor = -1,
wxArchitecture arch = wxARCH_INVALID,
wxEndianness endian = wxENDIAN_INVALID,
bool usingUniversal = false);
// default copy ctor, assignment operator and dtor are ok
bool operator==(const wxPlatformInfo &t) const;
bool operator!=(const wxPlatformInfo &t) const
{ return !(*this == t); }
// Gets a wxPlatformInfo already initialized with the values for
// the currently running platform.
static const wxPlatformInfo& Get();
// string -> enum conversions
// ---------------------------------
static wxOperatingSystemId GetOperatingSystemId(const wxString &name);
static wxPortId GetPortId(const wxString &portname);
static wxArchitecture GetArch(const wxString &arch);
static wxEndianness GetEndianness(const wxString &end);
// enum -> string conversions
// ---------------------------------
static wxString GetOperatingSystemFamilyName(wxOperatingSystemId os);
static wxString GetOperatingSystemIdName(wxOperatingSystemId os);
static wxString GetPortIdName(wxPortId port, bool usingUniversal);
static wxString GetPortIdShortName(wxPortId port, bool usingUniversal);
static wxString GetArchName(wxArchitecture arch);
static wxString GetEndiannessName(wxEndianness end);
// getters
// -----------------
int GetOSMajorVersion() const
{ return m_osVersionMajor; }
int GetOSMinorVersion() const
{ return m_osVersionMinor; }
int GetOSMicroVersion() const
{ return m_osVersionMicro; }
// return true if the OS version >= major.minor
bool CheckOSVersion(int major, int minor, int micro = 0) const;
int GetToolkitMajorVersion() const
{ return m_tkVersionMajor; }
int GetToolkitMinorVersion() const
{ return m_tkVersionMinor; }
int GetToolkitMicroVersion() const
{ return m_tkVersionMicro; }
bool CheckToolkitVersion(int major, int minor, int micro = 0) const
{
return DoCheckVersion(GetToolkitMajorVersion(),
GetToolkitMinorVersion(),
GetToolkitMicroVersion(),
major,
minor,
micro);
}
bool IsUsingUniversalWidgets() const
{ return m_usingUniversal; }
wxOperatingSystemId GetOperatingSystemId() const
{ return m_os; }
wxLinuxDistributionInfo GetLinuxDistributionInfo() const
{ return m_ldi; }
wxPortId GetPortId() const
{ return m_port; }
wxArchitecture GetArchitecture() const
{ return m_arch; }
wxEndianness GetEndianness() const
{ return m_endian; }
// string getters
// -----------------
wxString GetOperatingSystemFamilyName() const
{ return GetOperatingSystemFamilyName(m_os); }
wxString GetOperatingSystemIdName() const
{ return GetOperatingSystemIdName(m_os); }
wxString GetPortIdName() const
{ return GetPortIdName(m_port, m_usingUniversal); }
wxString GetPortIdShortName() const
{ return GetPortIdShortName(m_port, m_usingUniversal); }
wxString GetArchName() const
{ return GetArchName(m_arch); }
wxString GetEndiannessName() const
{ return GetEndiannessName(m_endian); }
wxString GetOperatingSystemDescription() const
{ return m_osDesc; }
wxString GetDesktopEnvironment() const
{ return m_desktopEnv; }
static wxString GetOperatingSystemDirectory();
// doesn't make sense to store inside wxPlatformInfo the OS directory,
// thus this function is static; note that this function simply calls
// wxGetOSDirectory() and is here just to make it easier for the user to
// find it that feature (global functions can be difficult to find in the docs)
// setters
// -----------------
void SetOSVersion(int major, int minor, int micro = 0)
{
m_osVersionMajor = major;
m_osVersionMinor = minor;
m_osVersionMicro = micro;
}
void SetToolkitVersion(int major, int minor, int micro = 0)
{
m_tkVersionMajor = major;
m_tkVersionMinor = minor;
m_tkVersionMicro = micro;
}
void SetOperatingSystemId(wxOperatingSystemId n)
{ m_os = n; }
void SetOperatingSystemDescription(const wxString& desc)
{ m_osDesc = desc; }
void SetPortId(wxPortId n)
{ m_port = n; }
void SetArchitecture(wxArchitecture n)
{ m_arch = n; }
void SetEndianness(wxEndianness n)
{ m_endian = n; }
void SetDesktopEnvironment(const wxString& de)
{ m_desktopEnv = de; }
void SetLinuxDistributionInfo(const wxLinuxDistributionInfo& di)
{ m_ldi = di; }
// miscellaneous
// -----------------
bool IsOk() const
{
return m_osVersionMajor != -1 && m_osVersionMinor != -1 &&
m_osVersionMicro != -1 &&
m_os != wxOS_UNKNOWN &&
!m_osDesc.IsEmpty() &&
m_tkVersionMajor != -1 && m_tkVersionMinor != -1 &&
m_tkVersionMicro != -1 &&
m_port != wxPORT_UNKNOWN &&
m_arch != wxARCH_INVALID &&
m_endian != wxENDIAN_INVALID;
// do not check linux-specific info; it's ok to have them empty
}
protected:
static bool DoCheckVersion(int majorCur, int minorCur, int microCur,
int major, int minor, int micro)
{
return majorCur > major
|| (majorCur == major && minorCur > minor)
|| (majorCur == major && minorCur == minor && microCur >= micro);
}
bool m_initializedForCurrentPlatform;
void InitForCurrentPlatform();
// OS stuff
// -----------------
// Version of the OS; valid if m_os != wxOS_UNKNOWN
// (-1 means not initialized yet).
int m_osVersionMajor,
m_osVersionMinor,
m_osVersionMicro;
// Operating system ID.
wxOperatingSystemId m_os;
// Operating system description.
wxString m_osDesc;
// linux-specific
// -----------------
wxString m_desktopEnv;
wxLinuxDistributionInfo m_ldi;
// toolkit
// -----------------
// Version of the underlying toolkit
// (-1 means not initialized yet; zero means no toolkit).
int m_tkVersionMajor, m_tkVersionMinor, m_tkVersionMicro;
// name of the wxWidgets port
wxPortId m_port;
// is using wxUniversal widgets?
bool m_usingUniversal;
// others
// -----------------
// architecture of the OS/machine
wxArchitecture m_arch;
// endianness of the machine
wxEndianness m_endian;
};
#endif // _WX_PLATINFO_H_
|
h
|
rticonnextdds-usecases
|
data/projects/rticonnextdds-usecases/VehicleTracking/ExampleCode/thirdparty/wxWidgets-3.1.2/Linux/include/wx/datetimectrl.h
|
///////////////////////////////////////////////////////////////////////////////
// Name: wx/timectrl.h
// Purpose: Declaration of wxDateTimePickerCtrl class.
// Author: Vadim Zeitlin
// Created: 2011-09-22
// Copyright: (c) 2011 Vadim Zeitlin <[email protected]>
// Licence: wxWindows licence
///////////////////////////////////////////////////////////////////////////////
#ifndef _WX_DATETIME_CTRL_H_
#define _WX_DATETIME_CTRL_H_
#include "wx/defs.h"
#if wxUSE_DATEPICKCTRL || wxUSE_TIMEPICKCTRL
#define wxNEEDS_DATETIMEPICKCTRL
#include "wx/control.h" // the base class
#include "wx/datetime.h"
// ----------------------------------------------------------------------------
// wxDateTimePickerCtrl: Private common base class of wx{Date,Time}PickerCtrl.
// ----------------------------------------------------------------------------
// This class is an implementation detail and should not be used directly, only
// use the documented API of wxDateTimePickerCtrl and wxTimePickerCtrl.
class WXDLLIMPEXP_ADV wxDateTimePickerCtrlBase : public wxControl
{
public:
// Set/get the date or time (in the latter case, time part is ignored).
virtual void SetValue(const wxDateTime& dt) = 0;
virtual wxDateTime GetValue() const = 0;
};
#if defined(__WXMSW__) && !defined(__WXUNIVERSAL__)
#include "wx/msw/datetimectrl.h"
#elif defined(__WXOSX_COCOA__) && !defined(__WXUNIVERSAL__)
#include "wx/osx/datetimectrl.h"
#else
typedef wxDateTimePickerCtrlBase wxDateTimePickerCtrl;
#endif
#endif // wxUSE_DATEPICKCTRL || wxUSE_TIMEPICKCTRL
#endif // _WX_DATETIME_CTRL_H_
|
h
|
rticonnextdds-usecases
|
data/projects/rticonnextdds-usecases/VehicleTracking/ExampleCode/thirdparty/wxWidgets-3.1.2/Linux/include/wx/collheaderctrl.h
|
/////////////////////////////////////////////////////////////////////////////
// Name: wx/collheaderctrl.h
// Purpose: wxCollapsibleHeaderCtrl
// Author: Tobias Taschner
// Created: 2015-09-19
// Copyright: (c) 2015 wxWidgets development team
// Licence: wxWindows licence
/////////////////////////////////////////////////////////////////////////////
#ifndef _WX_COLLAPSIBLEHEADER_CTRL_H_
#define _WX_COLLAPSIBLEHEADER_CTRL_H_
#include "wx/defs.h"
#if wxUSE_COLLPANE
#include "wx/control.h"
// class name
extern WXDLLIMPEXP_DATA_CORE(const char) wxCollapsibleHeaderCtrlNameStr[];
//
// wxGenericCollapsibleHeaderCtrl
//
class WXDLLIMPEXP_CORE wxCollapsibleHeaderCtrlBase : public wxControl
{
public:
wxCollapsibleHeaderCtrlBase() { }
wxCollapsibleHeaderCtrlBase(wxWindow *parent,
wxWindowID id,
const wxString& label,
const wxPoint& pos = wxDefaultPosition,
const wxSize& size = wxDefaultSize,
long style = wxBORDER_NONE,
const wxValidator& validator = wxDefaultValidator,
const wxString& name = wxCollapsibleHeaderCtrlNameStr)
{
Create(parent, id, label, pos, size, style, validator, name);
}
bool Create(wxWindow *parent,
wxWindowID id,
const wxString& label,
const wxPoint& pos = wxDefaultPosition,
const wxSize& size = wxDefaultSize,
long style = wxBORDER_NONE,
const wxValidator& validator = wxDefaultValidator,
const wxString& name = wxCollapsibleHeaderCtrlNameStr)
{
if ( !wxControl::Create(parent, id, pos, size, style, validator, name) )
return false;
SetLabel(label);
return true;
}
virtual void SetCollapsed(bool collapsed = true) = 0;
virtual bool IsCollapsed() const = 0;
private:
wxDECLARE_NO_COPY_CLASS(wxCollapsibleHeaderCtrlBase);
};
wxDECLARE_EXPORTED_EVENT(WXDLLIMPEXP_CORE, wxEVT_COLLAPSIBLEHEADER_CHANGED, wxCommandEvent);
#define wxCollapsibleHeaderChangedHandler(func) \
wxEVENT_HANDLER_CAST(wxCommandEventFunction, func)
#define EVT_COLLAPSIBLEHEADER_CHANGED(id, fn) \
wx__DECLARE_EVT1(wxEVT_COLLAPSIBLEHEADER_CHANGED, id, wxCollapsibleHeaderChangedHandler(fn))
// Currently there is only the native implementation, use it for all ports.
#include "wx/generic/collheaderctrl.h"
class WXDLLIMPEXP_CORE wxCollapsibleHeaderCtrl
: public wxGenericCollapsibleHeaderCtrl
{
public:
wxCollapsibleHeaderCtrl() { }
wxCollapsibleHeaderCtrl(wxWindow *parent,
wxWindowID id,
const wxString& label,
const wxPoint& pos = wxDefaultPosition,
const wxSize& size = wxDefaultSize,
long style = wxBORDER_NONE,
const wxValidator& validator = wxDefaultValidator,
const wxString& name = wxCollapsibleHeaderCtrlNameStr)
{
Create(parent, id, label, pos, size, style, validator, name);
}
private:
wxDECLARE_NO_COPY_CLASS(wxCollapsibleHeaderCtrl);
};
#endif // wxUSE_COLLPANE
#endif // _WX_COLLAPSIBLEHEADER_CTRL_H_
|
h
|
rticonnextdds-usecases
|
data/projects/rticonnextdds-usecases/VehicleTracking/ExampleCode/thirdparty/wxWidgets-3.1.2/Linux/include/wx/withimages.h
|
///////////////////////////////////////////////////////////////////////////////
// Name: wx/withimages.h
// Purpose: Declaration of a simple wxWithImages class.
// Author: Vadim Zeitlin
// Created: 2011-08-17
// Copyright: (c) 2011 Vadim Zeitlin <[email protected]>
// Licence: wxWindows licence
///////////////////////////////////////////////////////////////////////////////
#ifndef _WX_WITHIMAGES_H_
#define _WX_WITHIMAGES_H_
#include "wx/defs.h"
#include "wx/icon.h"
#include "wx/imaglist.h"
// ----------------------------------------------------------------------------
// wxWithImages: mix-in class providing access to wxImageList.
// ----------------------------------------------------------------------------
class WXDLLIMPEXP_CORE wxWithImages
{
public:
enum
{
NO_IMAGE = -1
};
wxWithImages()
{
m_imageList = NULL;
m_ownsImageList = false;
}
virtual ~wxWithImages()
{
FreeIfNeeded();
}
// Sets the image list to use, it is *not* deleted by the control.
virtual void SetImageList(wxImageList* imageList)
{
FreeIfNeeded();
m_imageList = imageList;
}
// As SetImageList() but we will delete the image list ourselves.
void AssignImageList(wxImageList* imageList)
{
SetImageList(imageList);
m_ownsImageList = true;
}
// Get pointer (may be NULL) to the associated image list.
wxImageList* GetImageList() const { return m_imageList; }
protected:
// Return true if we have a valid image list.
bool HasImageList() const { return m_imageList != NULL; }
// Return the image with the given index from the image list.
//
// If there is no image list or if index == NO_IMAGE, silently returns
// wxNullIcon.
wxIcon GetImage(int iconIndex) const
{
return m_imageList && iconIndex != NO_IMAGE
? m_imageList->GetIcon(iconIndex)
: wxNullIcon;
}
private:
// Free the image list if necessary, i.e. if we own it.
void FreeIfNeeded()
{
if ( m_ownsImageList )
{
delete m_imageList;
m_imageList = NULL;
// We don't own it any more.
m_ownsImageList = false;
}
}
// The associated image list or NULL.
wxImageList* m_imageList;
// False by default, if true then we delete m_imageList.
bool m_ownsImageList;
wxDECLARE_NO_COPY_CLASS(wxWithImages);
};
#endif // _WX_WITHIMAGES_H_
|
h
|
rticonnextdds-usecases
|
data/projects/rticonnextdds-usecases/VehicleTracking/ExampleCode/thirdparty/wxWidgets-3.1.2/Linux/include/wx/listctrl.h
|
///////////////////////////////////////////////////////////////////////////////
// Name: wx/listctrl.h
// Purpose: wxListCtrl class
// Author: Vadim Zeitlin
// Modified by:
// Created: 04.12.99
// Copyright: (c) wxWidgets team
// Licence: wxWindows licence
///////////////////////////////////////////////////////////////////////////////
#ifndef _WX_LISTCTRL_H_BASE_
#define _WX_LISTCTRL_H_BASE_
#include "wx/defs.h" // headers should include this before first wxUSE_XXX check
#if wxUSE_LISTCTRL
#include "wx/listbase.h"
// ----------------------------------------------------------------------------
// constants
// ----------------------------------------------------------------------------
extern WXDLLIMPEXP_DATA_CORE(const char) wxListCtrlNameStr[];
// ----------------------------------------------------------------------------
// include the wxListCtrl class declaration
// ----------------------------------------------------------------------------
#if defined(__WXMSW__) && !defined(__WXUNIVERSAL__)
#include "wx/msw/listctrl.h"
#elif defined(__WXQT__) && !defined(__WXUNIVERSAL__)
#include "wx/qt/listctrl.h"
#else
#include "wx/generic/listctrl.h"
#endif
// ----------------------------------------------------------------------------
// wxListView: a class which provides a better API for list control
// ----------------------------------------------------------------------------
class WXDLLIMPEXP_CORE wxListView : public wxListCtrl
{
public:
wxListView() { }
wxListView( wxWindow *parent,
wxWindowID winid = wxID_ANY,
const wxPoint& pos = wxDefaultPosition,
const wxSize& size = wxDefaultSize,
long style = wxLC_REPORT,
const wxValidator& validator = wxDefaultValidator,
const wxString &name = wxListCtrlNameStr)
{
Create(parent, winid, pos, size, style, validator, name);
}
// focus/selection stuff
// ---------------------
// [de]select an item
void Select(long n, bool on = true)
{
SetItemState(n, on ? wxLIST_STATE_SELECTED : 0, wxLIST_STATE_SELECTED);
}
// focus and show the given item
void Focus(long index)
{
SetItemState(index, wxLIST_STATE_FOCUSED, wxLIST_STATE_FOCUSED);
EnsureVisible(index);
}
// get the currently focused item or -1 if none
long GetFocusedItem() const
{
return GetNextItem(-1, wxLIST_NEXT_ALL, wxLIST_STATE_FOCUSED);
}
// get first and subsequent selected items, return -1 when no more
long GetNextSelected(long item) const
{ return GetNextItem(item, wxLIST_NEXT_ALL, wxLIST_STATE_SELECTED); }
long GetFirstSelected() const
{ return GetNextSelected(-1); }
// return true if the item is selected
bool IsSelected(long index) const
{ return GetItemState(index, wxLIST_STATE_SELECTED) != 0; }
// columns
// -------
void SetColumnImage(int col, int image)
{
wxListItem item;
item.SetMask(wxLIST_MASK_IMAGE);
item.SetImage(image);
SetColumn(col, item);
}
void ClearColumnImage(int col) { SetColumnImage(col, -1); }
private:
wxDECLARE_DYNAMIC_CLASS_NO_COPY(wxListView);
};
#endif // wxUSE_LISTCTRL
#endif
// _WX_LISTCTRL_H_BASE_
|
h
|
rticonnextdds-usecases
|
data/projects/rticonnextdds-usecases/VehicleTracking/ExampleCode/thirdparty/wxWidgets-3.1.2/Linux/include/wx/progdlg.h
|
/////////////////////////////////////////////////////////////////////////////
// Name: wx/progdlg.h
// Purpose: Base header for wxProgressDialog
// Author: Julian Smart
// Modified by:
// Created:
// Copyright: (c) Julian Smart
// Licence: wxWindows Licence
/////////////////////////////////////////////////////////////////////////////
#ifndef _WX_PROGDLG_H_BASE_
#define _WX_PROGDLG_H_BASE_
#include "wx/defs.h"
#if wxUSE_PROGRESSDLG
/*
* wxProgressDialog flags
*/
#define wxPD_CAN_ABORT 0x0001
#define wxPD_APP_MODAL 0x0002
#define wxPD_AUTO_HIDE 0x0004
#define wxPD_ELAPSED_TIME 0x0008
#define wxPD_ESTIMATED_TIME 0x0010
#define wxPD_SMOOTH 0x0020
#define wxPD_REMAINING_TIME 0x0040
#define wxPD_CAN_SKIP 0x0080
#include "wx/generic/progdlgg.h"
#if defined(__WXMSW__) && !defined(__WXUNIVERSAL__)
// The native implementation requires the use of threads and still has some
// problems, so it can be explicitly disabled.
#if wxUSE_THREADS && wxUSE_NATIVE_PROGRESSDLG
#define wxHAS_NATIVE_PROGRESSDIALOG
#include "wx/msw/progdlg.h"
#endif
#endif
// If there is no native one, just use the generic version.
#ifndef wxHAS_NATIVE_PROGRESSDIALOG
class WXDLLIMPEXP_CORE wxProgressDialog
: public wxGenericProgressDialog
{
public:
wxProgressDialog( const wxString& title, const wxString& message,
int maximum = 100,
wxWindow *parent = NULL,
int style = wxPD_APP_MODAL | wxPD_AUTO_HIDE )
: wxGenericProgressDialog( title, message, maximum,
parent, style )
{ }
private:
wxDECLARE_DYNAMIC_CLASS_NO_COPY( wxProgressDialog );
};
#endif // !wxHAS_NATIVE_PROGRESSDIALOG
#endif // wxUSE_PROGRESSDLG
#endif // _WX_PROGDLG_H_BASE_
|
h
|
rticonnextdds-usecases
|
data/projects/rticonnextdds-usecases/VehicleTracking/ExampleCode/thirdparty/wxWidgets-3.1.2/Linux/include/wx/font.h
|
/////////////////////////////////////////////////////////////////////////////
// Name: wx/font.h
// Purpose: wxFontBase class: the interface of wxFont
// Author: Vadim Zeitlin
// Modified by:
// Created: 20.09.99
// Copyright: (c) wxWidgets team
// Licence: wxWindows licence
/////////////////////////////////////////////////////////////////////////////
#ifndef _WX_FONT_H_BASE_
#define _WX_FONT_H_BASE_
// ----------------------------------------------------------------------------
// headers
// ----------------------------------------------------------------------------
#include "wx/defs.h" // for wxDEFAULT &c
#include "wx/fontenc.h" // the font encoding constants
#include "wx/gdiobj.h" // the base class
#include "wx/gdicmn.h" // for wxGDIObjListBase
#include "wx/math.h" // for wxRound()
// ----------------------------------------------------------------------------
// forward declarations
// ----------------------------------------------------------------------------
class WXDLLIMPEXP_FWD_CORE wxFont;
// ----------------------------------------------------------------------------
// font constants
// ----------------------------------------------------------------------------
// standard font families: these may be used only for the font creation, it
// doesn't make sense to query an existing font for its font family as,
// especially if the font had been created from a native font description, it
// may be unknown
enum wxFontFamily
{
wxFONTFAMILY_DEFAULT = wxDEFAULT,
wxFONTFAMILY_DECORATIVE = wxDECORATIVE,
wxFONTFAMILY_ROMAN = wxROMAN,
wxFONTFAMILY_SCRIPT = wxSCRIPT,
wxFONTFAMILY_SWISS = wxSWISS,
wxFONTFAMILY_MODERN = wxMODERN,
wxFONTFAMILY_TELETYPE = wxTELETYPE,
wxFONTFAMILY_MAX,
wxFONTFAMILY_UNKNOWN = wxFONTFAMILY_MAX
};
// font styles
enum wxFontStyle
{
wxFONTSTYLE_NORMAL = wxNORMAL,
wxFONTSTYLE_ITALIC = wxITALIC,
wxFONTSTYLE_SLANT = wxSLANT,
wxFONTSTYLE_MAX
};
// font weights
enum wxFontWeight
{
wxFONTWEIGHT_INVALID = 0,
wxFONTWEIGHT_THIN = 100,
wxFONTWEIGHT_EXTRALIGHT = 200,
wxFONTWEIGHT_LIGHT = 300,
wxFONTWEIGHT_NORMAL = 400,
wxFONTWEIGHT_MEDIUM = 500,
wxFONTWEIGHT_SEMIBOLD = 600,
wxFONTWEIGHT_BOLD = 700,
wxFONTWEIGHT_EXTRABOLD = 800,
wxFONTWEIGHT_HEAVY = 900,
wxFONTWEIGHT_EXTRAHEAVY = 1000,
wxFONTWEIGHT_MAX = wxFONTWEIGHT_EXTRAHEAVY
};
// Symbolic font sizes as defined in CSS specification.
enum wxFontSymbolicSize
{
wxFONTSIZE_XX_SMALL = -3,
wxFONTSIZE_X_SMALL,
wxFONTSIZE_SMALL,
wxFONTSIZE_MEDIUM,
wxFONTSIZE_LARGE,
wxFONTSIZE_X_LARGE,
wxFONTSIZE_XX_LARGE
};
// the font flag bits for the new font ctor accepting one combined flags word
enum wxFontFlag
{
// no special flags: font with default weight/slant/anti-aliasing
wxFONTFLAG_DEFAULT = 0,
// slant flags (default: no slant)
wxFONTFLAG_ITALIC = 1 << 0,
wxFONTFLAG_SLANT = 1 << 1,
// weight flags (default: medium):
wxFONTFLAG_LIGHT = 1 << 2,
wxFONTFLAG_BOLD = 1 << 3,
// anti-aliasing flag: force on or off (default: the current system default)
wxFONTFLAG_ANTIALIASED = 1 << 4,
wxFONTFLAG_NOT_ANTIALIASED = 1 << 5,
// underlined/strikethrough flags (default: no lines)
wxFONTFLAG_UNDERLINED = 1 << 6,
wxFONTFLAG_STRIKETHROUGH = 1 << 7,
// the mask of all currently used flags
wxFONTFLAG_MASK = wxFONTFLAG_ITALIC |
wxFONTFLAG_SLANT |
wxFONTFLAG_LIGHT |
wxFONTFLAG_BOLD |
wxFONTFLAG_ANTIALIASED |
wxFONTFLAG_NOT_ANTIALIASED |
wxFONTFLAG_UNDERLINED |
wxFONTFLAG_STRIKETHROUGH
};
// ----------------------------------------------------------------------------
// wxFontInfo describes a wxFont
// ----------------------------------------------------------------------------
class wxFontInfo
{
public:
// Default ctor uses the default font size appropriate for the current
// platform.
wxFontInfo()
{ InitPointSize(-1.0f); }
// These ctors specify the font size, either in points or in pixels.
// Point size is a floating point number, however we also accept all
// integer sizes using the simple template ctor below.
explicit wxFontInfo(float pointSize)
{ InitPointSize(pointSize); }
explicit wxFontInfo(const wxSize& pixelSize) : m_pixelSize(pixelSize)
{ Init(); }
// Need to define this one to avoid casting double to int too.
explicit wxFontInfo(double pointSize)
{ InitPointSize(static_cast<float>(pointSize)); }
template <typename T>
explicit wxFontInfo(T pointSize)
{ InitPointSize(ToFloatPointSize(pointSize)); }
// Setters for the various attributes. All of them return the object itself
// so that the calls to them could be chained.
wxFontInfo& Family(wxFontFamily family)
{ m_family = family; return *this; }
wxFontInfo& FaceName(const wxString& faceName)
{ m_faceName = faceName; return *this; }
wxFontInfo& Weight(int weight)
{ m_weight = weight; return *this; }
wxFontInfo& Bold(bool bold = true)
{ return Weight(bold ? wxFONTWEIGHT_BOLD : wxFONTWEIGHT_NORMAL); }
wxFontInfo& Light(bool light = true)
{ return Weight(light ? wxFONTWEIGHT_LIGHT : wxFONTWEIGHT_NORMAL); }
wxFontInfo& Italic(bool italic = true)
{ SetFlag(wxFONTFLAG_ITALIC, italic); return *this; }
wxFontInfo& Slant(bool slant = true)
{ SetFlag(wxFONTFLAG_SLANT, slant); return *this; }
wxFontInfo& Style(wxFontStyle style)
{
if ( style == wxFONTSTYLE_ITALIC )
return Italic();
if ( style == wxFONTSTYLE_SLANT )
return Slant();
return *this;
}
wxFontInfo& AntiAliased(bool antiAliased = true)
{ SetFlag(wxFONTFLAG_ANTIALIASED, antiAliased); return *this; }
wxFontInfo& Underlined(bool underlined = true)
{ SetFlag(wxFONTFLAG_UNDERLINED, underlined); return *this; }
wxFontInfo& Strikethrough(bool strikethrough = true)
{ SetFlag(wxFONTFLAG_STRIKETHROUGH, strikethrough); return *this; }
wxFontInfo& Encoding(wxFontEncoding encoding)
{ m_encoding = encoding; return *this; }
// Set all flags at once.
wxFontInfo& AllFlags(int flags)
{
m_flags = flags;
m_weight = m_flags & wxFONTFLAG_BOLD
? wxFONTWEIGHT_BOLD
: m_flags & wxFONTFLAG_LIGHT
? wxFONTWEIGHT_LIGHT
: wxFONTWEIGHT_NORMAL;
return *this;
}
// Accessors are mostly meant to be used by wxFont itself to extract the
// various pieces of the font description.
bool IsUsingSizeInPixels() const { return m_pixelSize != wxDefaultSize; }
float GetFractionalPointSize() const { return m_pointSize; }
int GetPointSize() const { return ToIntPointSize(m_pointSize); }
wxSize GetPixelSize() const { return m_pixelSize; }
// If face name is not empty, it has priority, otherwise use family.
bool HasFaceName() const { return !m_faceName.empty(); }
wxFontFamily GetFamily() const { return m_family; }
const wxString& GetFaceName() const { return m_faceName; }
wxFontStyle GetStyle() const
{
return m_flags & wxFONTFLAG_ITALIC
? wxFONTSTYLE_ITALIC
: m_flags & wxFONTFLAG_SLANT
? wxFONTSTYLE_SLANT
: wxFONTSTYLE_NORMAL;
}
int GetNumericWeight() const
{
return m_weight;
}
wxFontWeight GetWeight() const
{
return GetWeightClosestToNumericValue(m_weight);
}
bool IsAntiAliased() const
{
return (m_flags & wxFONTFLAG_ANTIALIASED) != 0;
}
bool IsUnderlined() const
{
return (m_flags & wxFONTFLAG_UNDERLINED) != 0;
}
bool IsStrikethrough() const
{
return (m_flags & wxFONTFLAG_STRIKETHROUGH) != 0;
}
wxFontEncoding GetEncoding() const { return m_encoding; }
// Default copy ctor, assignment operator and dtor are OK.
// Helper functions for converting between integer and fractional sizes.
static int ToIntPointSize(float pointSize) { return wxRound(pointSize); }
static float ToFloatPointSize(int pointSize)
{
wxCHECK_MSG( pointSize == -1 || pointSize >= 0,
-1, "Invalid font point size" );
// Huge values are not exactly representable as floats, so don't accept
// those neither as they can only be due to a mistake anyhow: nobody
// could possibly need a font of size 16777217pt (which is the first
// value for which this fails).
const float f = static_cast<float>(pointSize);
wxCHECK_MSG( static_cast<int>(f) == pointSize,
-1, "Font point size out of range" );
return f;
}
// Another helper for converting arbitrary numeric weight to the closest
// value of wxFontWeight enum. It should be avoided in the new code (also
// note that the function for the conversion in the other direction is
// trivial and so is not provided, we only have GetNumericWeightOf() which
// contains backwards compatibility hacks, but we don't need it here).
static wxFontWeight GetWeightClosestToNumericValue(int numWeight)
{
wxASSERT(numWeight > 0);
wxASSERT(numWeight <= 1000);
// round to nearest hundredth = wxFONTWEIGHT_ constant
int weight = ((numWeight + 50) / 100) * 100;
if (weight < wxFONTWEIGHT_THIN)
weight = wxFONTWEIGHT_THIN;
if (weight > wxFONTWEIGHT_MAX)
weight = wxFONTWEIGHT_MAX;
return static_cast<wxFontWeight>(weight);
}
private:
void Init()
{
m_pointSize = -1;
m_family = wxFONTFAMILY_DEFAULT;
m_flags = wxFONTFLAG_DEFAULT;
m_weight = wxFONTWEIGHT_NORMAL;
m_encoding = wxFONTENCODING_DEFAULT;
}
void InitPointSize(float pointSize)
{
Init();
m_pointSize = pointSize;
m_pixelSize = wxDefaultSize;
}
// Turn on or off the given bit in m_flags depending on the value of the
// boolean argument.
void SetFlag(int flag, bool on)
{
if ( on )
m_flags |= flag;
else
m_flags &= ~flag;
}
// The size information: if m_pixelSize is valid (!= wxDefaultSize), then
// it is used. Otherwise m_pointSize is used, except if it is < 0, which
// means that the platform dependent font size should be used instead.
float m_pointSize;
wxSize m_pixelSize;
wxFontFamily m_family;
wxString m_faceName;
int m_flags;
int m_weight;
wxFontEncoding m_encoding;
};
// ----------------------------------------------------------------------------
// wxFontBase represents a font object
// ----------------------------------------------------------------------------
class WXDLLIMPEXP_FWD_CORE wxNativeFontInfo;
class WXDLLIMPEXP_CORE wxFontBase : public wxGDIObject
{
public:
/*
derived classes should provide the following ctors:
wxFont();
wxFont(const wxFontInfo& info);
wxFont(const wxString& nativeFontInfoString);
wxFont(const wxNativeFontInfo& info);
wxFont(int size,
wxFontFamily family,
wxFontStyle style,
wxFontWeight weight,
bool underlined = false,
const wxString& face = wxEmptyString,
wxFontEncoding encoding = wxFONTENCODING_DEFAULT);
wxFont(const wxSize& pixelSize,
wxFontFamily family,
wxFontStyle style,
wxFontWeight weight,
bool underlined = false,
const wxString& face = wxEmptyString,
wxFontEncoding encoding = wxFONTENCODING_DEFAULT);
*/
// creator function
virtual ~wxFontBase();
// from the font components
static wxFont *New(
int pointSize, // size of the font in points
wxFontFamily family, // see wxFontFamily enum
wxFontStyle style, // see wxFontStyle enum
wxFontWeight weight, // see wxFontWeight enum
bool underlined = false, // not underlined by default
const wxString& face = wxEmptyString, // facename
wxFontEncoding encoding = wxFONTENCODING_DEFAULT); // ISO8859-X, ...
// from the font components
static wxFont *New(
const wxSize& pixelSize, // size of the font in pixels
wxFontFamily family, // see wxFontFamily enum
wxFontStyle style, // see wxFontStyle enum
wxFontWeight weight, // see wxFontWeight enum
bool underlined = false, // not underlined by default
const wxString& face = wxEmptyString, // facename
wxFontEncoding encoding = wxFONTENCODING_DEFAULT); // ISO8859-X, ...
// from the font components but using the font flags instead of separate
// parameters for each flag
static wxFont *New(int pointSize,
wxFontFamily family,
int flags = wxFONTFLAG_DEFAULT,
const wxString& face = wxEmptyString,
wxFontEncoding encoding = wxFONTENCODING_DEFAULT);
// from the font components but using the font flags instead of separate
// parameters for each flag
static wxFont *New(const wxSize& pixelSize,
wxFontFamily family,
int flags = wxFONTFLAG_DEFAULT,
const wxString& face = wxEmptyString,
wxFontEncoding encoding = wxFONTENCODING_DEFAULT);
// from the (opaque) native font description object
static wxFont *New(const wxNativeFontInfo& nativeFontDesc);
// from the string representation of wxNativeFontInfo
static wxFont *New(const wxString& strNativeFontDesc);
// Load the font from the given file and return true on success or false on
// error (an error message will be logged in this case).
#if wxUSE_PRIVATE_FONTS
static bool AddPrivateFont(const wxString& filename);
#endif // wxUSE_PRIVATE_FONTS
// comparison
bool operator==(const wxFont& font) const;
bool operator!=(const wxFont& font) const { return !(*this == font); }
// accessors: get the font characteristics
virtual int GetPointSize() const;
virtual float GetFractionalPointSize() const = 0;
virtual wxSize GetPixelSize() const;
virtual bool IsUsingSizeInPixels() const;
wxFontFamily GetFamily() const;
virtual wxFontStyle GetStyle() const = 0;
virtual int GetNumericWeight() const = 0;
virtual bool GetUnderlined() const = 0;
virtual bool GetStrikethrough() const { return false; }
virtual wxString GetFaceName() const = 0;
virtual wxFontEncoding GetEncoding() const = 0;
virtual const wxNativeFontInfo *GetNativeFontInfo() const = 0;
// Accessors that can be overridden in the platform-specific code but for
// which we provide a reasonable default implementation in the base class.
virtual wxFontWeight GetWeight() const;
virtual bool IsFixedWidth() const;
wxString GetNativeFontInfoDesc() const;
wxString GetNativeFontInfoUserDesc() const;
// change the font characteristics
virtual void SetPointSize( int pointSize );
virtual void SetFractionalPointSize( float pointSize ) = 0;
virtual void SetPixelSize( const wxSize& pixelSize );
virtual void SetFamily( wxFontFamily family ) = 0;
virtual void SetStyle( wxFontStyle style ) = 0;
virtual void SetNumericWeight( int weight ) = 0;
virtual void SetUnderlined( bool underlined ) = 0;
virtual void SetStrikethrough( bool WXUNUSED(strikethrough) ) {}
virtual void SetEncoding(wxFontEncoding encoding) = 0;
virtual bool SetFaceName( const wxString& faceName );
void SetNativeFontInfo(const wxNativeFontInfo& info)
{ DoSetNativeFontInfo(info); }
// Similarly to the accessors above, the functions in this group have a
// reasonable default implementation in the base class.
virtual void SetWeight( wxFontWeight weight );
bool SetNativeFontInfo(const wxString& info);
bool SetNativeFontInfoUserDesc(const wxString& info);
// Symbolic font sizes support: set the font size to "large" or "very
// small" either absolutely (i.e. compared to the default font size) or
// relatively to the given font size.
void SetSymbolicSize(wxFontSymbolicSize size);
void SetSymbolicSizeRelativeTo(wxFontSymbolicSize size, int base)
{
SetPointSize(AdjustToSymbolicSize(size, base));
}
// Adjust the base size in points according to symbolic size.
static int AdjustToSymbolicSize(wxFontSymbolicSize size, int base);
// translate the fonts into human-readable string (i.e. GetStyleString()
// will return "wxITALIC" for an italic font, ...)
wxString GetFamilyString() const;
wxString GetStyleString() const;
wxString GetWeightString() const;
// the default encoding is used for creating all fonts with default
// encoding parameter
static wxFontEncoding GetDefaultEncoding() { return ms_encodingDefault; }
static void SetDefaultEncoding(wxFontEncoding encoding);
// Account for legacy font weight values: if the argument is one of
// wxNORMAL, wxLIGHT or wxBOLD, return the corresponding wxFONTWEIGHT_XXX
// enum value. Otherwise just return it unchanged.
static int ConvertFromLegacyWeightIfNecessary(int weight);
// Convert between symbolic and numeric font weights. This function uses
// ConvertFromLegacyWeightIfNecessary(), so takes legacy values into
// account as well.
static int GetNumericWeightOf(wxFontWeight weight);
// this doesn't do anything and is kept for compatibility only
#if WXWIN_COMPATIBILITY_2_8
wxDEPRECATED_INLINE(void SetNoAntiAliasing(bool no = true), wxUnusedVar(no);)
wxDEPRECATED_INLINE(bool GetNoAntiAliasing() const, return false;)
#endif // WXWIN_COMPATIBILITY_2_8
wxDEPRECATED_MSG("use wxFONTWEIGHT_XXX constants instead of raw values")
void SetWeight(int weight)
{ SetWeight(static_cast<wxFontWeight>(weight)); }
wxDEPRECATED_MSG("use wxFONTWEIGHT_XXX constants instead of wxLIGHT/wxNORMAL/wxBOLD")
void SetWeight(wxDeprecatedGUIConstants weight)
{ SetWeight(static_cast<wxFontWeight>(weight)); }
// from the font components
wxDEPRECATED_MSG("use wxFONT{FAMILY,STYLE,WEIGHT}_XXX constants")
static wxFont *New(
int pointSize, // size of the font in points
int family, // see wxFontFamily enum
int style, // see wxFontStyle enum
int weight, // see wxFontWeight enum
bool underlined = false, // not underlined by default
const wxString& face = wxEmptyString, // facename
wxFontEncoding encoding = wxFONTENCODING_DEFAULT) // ISO8859-X, ...
{ return New(pointSize, (wxFontFamily)family, (wxFontStyle)style,
(wxFontWeight)weight, underlined, face, encoding); }
// from the font components
wxDEPRECATED_MSG("use wxFONT{FAMILY,STYLE,WEIGHT}_XXX constants")
static wxFont *New(
const wxSize& pixelSize, // size of the font in pixels
int family, // see wxFontFamily enum
int style, // see wxFontStyle enum
int weight, // see wxFontWeight enum
bool underlined = false, // not underlined by default
const wxString& face = wxEmptyString, // facename
wxFontEncoding encoding = wxFONTENCODING_DEFAULT) // ISO8859-X, ...
{ return New(pixelSize, (wxFontFamily)family, (wxFontStyle)style,
(wxFontWeight)weight, underlined, face, encoding); }
protected:
// the function called by both overloads of SetNativeFontInfo()
virtual void DoSetNativeFontInfo(const wxNativeFontInfo& info);
// The function called by public GetFamily(): it can return
// wxFONTFAMILY_UNKNOWN unlike the public method (see comment there).
virtual wxFontFamily DoGetFamily() const = 0;
// Helper functions to recover wxFONTSTYLE/wxFONTWEIGHT and underlined flag
// values from flags containing a combination of wxFONTFLAG_XXX.
static wxFontStyle GetStyleFromFlags(int flags)
{
return flags & wxFONTFLAG_ITALIC
? wxFONTSTYLE_ITALIC
: flags & wxFONTFLAG_SLANT
? wxFONTSTYLE_SLANT
: wxFONTSTYLE_NORMAL;
}
static wxFontWeight GetWeightFromFlags(int flags)
{
return flags & wxFONTFLAG_LIGHT
? wxFONTWEIGHT_LIGHT
: flags & wxFONTFLAG_BOLD
? wxFONTWEIGHT_BOLD
: wxFONTWEIGHT_NORMAL;
}
static bool GetUnderlinedFromFlags(int flags)
{
return (flags & wxFONTFLAG_UNDERLINED) != 0;
}
static bool GetStrikethroughFromFlags(int flags)
{
return (flags & wxFONTFLAG_STRIKETHROUGH) != 0;
}
// Create wxFontInfo object from the parameters passed to the legacy wxFont
// ctor/Create() overload. This function implements the compatibility hack
// which interprets wxDEFAULT value of size as meaning -1 and also supports
// specifying wxNORMAL, wxLIGHT and wxBOLD as weight values.
static wxFontInfo InfoFromLegacyParams(int pointSize,
wxFontFamily family,
wxFontStyle style,
wxFontWeight weight,
bool underlined,
const wxString& face,
wxFontEncoding encoding);
static wxFontInfo InfoFromLegacyParams(const wxSize& pixelSize,
wxFontFamily family,
wxFontStyle style,
wxFontWeight weight,
bool underlined,
const wxString& face,
wxFontEncoding encoding);
private:
// the currently default encoding: by default, it's the default system
// encoding, but may be changed by the application using
// SetDefaultEncoding() to make all subsequent fonts created without
// specifying encoding parameter using this encoding
static wxFontEncoding ms_encodingDefault;
};
// wxFontBase <-> wxString utilities, used by wxConfig
WXDLLIMPEXP_CORE wxString wxToString(const wxFontBase& font);
WXDLLIMPEXP_CORE bool wxFromString(const wxString& str, wxFontBase* font);
// this macro must be used in all derived wxFont classes declarations
#define wxDECLARE_COMMON_FONT_METHODS() \
wxDEPRECATED_MSG("use wxFONTFAMILY_XXX constants") \
void SetFamily(int family) \
{ SetFamily((wxFontFamily)family); } \
wxDEPRECATED_MSG("use wxFONTSTYLE_XXX constants") \
void SetStyle(int style) \
{ SetStyle((wxFontStyle)style); } \
wxDEPRECATED_MSG("use wxFONTFAMILY_XXX constants") \
void SetFamily(wxDeprecatedGUIConstants family) \
{ SetFamily((wxFontFamily)family); } \
wxDEPRECATED_MSG("use wxFONTSTYLE_XXX constants") \
void SetStyle(wxDeprecatedGUIConstants style) \
{ SetStyle((wxFontStyle)style); } \
\
/* functions for modifying font in place */ \
wxFont& MakeBold(); \
wxFont& MakeItalic(); \
wxFont& MakeUnderlined(); \
wxFont& MakeStrikethrough(); \
wxFont& MakeLarger() { return Scale(1.2f); } \
wxFont& MakeSmaller() { return Scale(1/1.2f); } \
wxFont& Scale(float x); \
/* functions for creating fonts based on this one */ \
wxFont Bold() const; \
wxFont GetBaseFont() const; \
wxFont Italic() const; \
wxFont Underlined() const; \
wxFont Strikethrough() const; \
wxFont Larger() const { return Scaled(1.2f); } \
wxFont Smaller() const { return Scaled(1/1.2f); } \
wxFont Scaled(float x) const
// include the real class declaration
#if defined(__WXMSW__)
#include "wx/msw/font.h"
#elif defined(__WXMOTIF__)
#include "wx/motif/font.h"
#elif defined(__WXGTK20__)
#include "wx/gtk/font.h"
#elif defined(__WXGTK__)
#include "wx/gtk1/font.h"
#elif defined(__WXX11__)
#include "wx/x11/font.h"
#elif defined(__WXDFB__)
#include "wx/dfb/font.h"
#elif defined(__WXMAC__)
#include "wx/osx/font.h"
#elif defined(__WXQT__)
#include "wx/qt/font.h"
#endif
class WXDLLIMPEXP_CORE wxFontList: public wxGDIObjListBase
{
public:
wxFont *FindOrCreateFont(int pointSize,
wxFontFamily family,
wxFontStyle style,
wxFontWeight weight,
bool underline = false,
const wxString& face = wxEmptyString,
wxFontEncoding encoding = wxFONTENCODING_DEFAULT);
wxDEPRECATED_MSG("use wxFONT{FAMILY,STYLE,WEIGHT}_XXX constants")
wxFont *FindOrCreateFont(int pointSize, int family, int style, int weight,
bool underline = false,
const wxString& face = wxEmptyString,
wxFontEncoding encoding = wxFONTENCODING_DEFAULT)
{ return FindOrCreateFont(pointSize, (wxFontFamily)family, (wxFontStyle)style,
(wxFontWeight)weight, underline, face, encoding); }
wxFont *FindOrCreateFont(const wxFontInfo& fontInfo)
{ return FindOrCreateFont(fontInfo.GetPointSize(), fontInfo.GetFamily(),
fontInfo.GetStyle(), fontInfo.GetWeight(),
fontInfo.IsUnderlined(), fontInfo.GetFaceName(),
fontInfo.GetEncoding()); }
};
extern WXDLLIMPEXP_DATA_CORE(wxFontList*) wxTheFontList;
// provide comparison operators to allow code such as
//
// if ( font.GetStyle() == wxFONTSTYLE_SLANT )
//
// to compile without warnings which it would otherwise provoke from some
// compilers as it compares elements of different enums
// Unfortunately some compilers have ambiguity issues when enum comparisons are
// overloaded so we have to disable the overloads in this case, see
// wxCOMPILER_NO_OVERLOAD_ON_ENUM definition in wx/platform.h for more details.
#ifndef wxCOMPILER_NO_OVERLOAD_ON_ENUM
wxDEPRECATED_MSG("use wxFONTFAMILY_XXX constants") \
inline bool operator==(wxFontFamily s, wxDeprecatedGUIConstants t)
{ return static_cast<int>(s) == static_cast<int>(t); }
wxDEPRECATED_MSG("use wxFONTFAMILY_XXX constants") \
inline bool operator!=(wxFontFamily s, wxDeprecatedGUIConstants t)
{ return static_cast<int>(s) != static_cast<int>(t); }
wxDEPRECATED_MSG("use wxFONTSTYLE_XXX constants") \
inline bool operator==(wxFontStyle s, wxDeprecatedGUIConstants t)
{ return static_cast<int>(s) == static_cast<int>(t); }
wxDEPRECATED_MSG("use wxFONTSTYLE_XXX constants") \
inline bool operator!=(wxFontStyle s, wxDeprecatedGUIConstants t)
{ return static_cast<int>(s) != static_cast<int>(t); }
wxDEPRECATED_MSG("use wxFONTWEIGHT_XXX constants") \
inline bool operator==(wxFontWeight s, wxDeprecatedGUIConstants t)
{ return static_cast<int>(s) == static_cast<int>(t); }
wxDEPRECATED_MSG("use wxFONTWEIGHT_XXX constants") \
inline bool operator!=(wxFontWeight s, wxDeprecatedGUIConstants t)
{ return static_cast<int>(s) != static_cast<int>(t); }
#endif // // wxCOMPILER_NO_OVERLOAD_ON_ENUM
#endif // _WX_FONT_H_BASE_
|
h
|
rticonnextdds-usecases
|
data/projects/rticonnextdds-usecases/VehicleTracking/ExampleCode/thirdparty/wxWidgets-3.1.2/Linux/include/wx/msgqueue.h
|
///////////////////////////////////////////////////////////////////////////////
// Name: wx/msqqueue.h
// Purpose: Message queues for inter-thread communication
// Author: Evgeniy Tarassov
// Created: 2007-10-31
// Copyright: (C) 2007 TT-Solutions SARL
// Licence: wxWindows licence
///////////////////////////////////////////////////////////////////////////////
#ifndef _WX_MSGQUEUE_H_
#define _WX_MSGQUEUE_H_
// ----------------------------------------------------------------------------
// headers
// ----------------------------------------------------------------------------
#include "wx/thread.h"
#if wxUSE_THREADS
#include "wx/stopwatch.h"
#include "wx/beforestd.h"
#include <queue>
#include "wx/afterstd.h"
enum wxMessageQueueError
{
wxMSGQUEUE_NO_ERROR = 0, // operation completed successfully
wxMSGQUEUE_TIMEOUT, // no messages received before timeout expired
wxMSGQUEUE_MISC_ERROR // some unexpected (and fatal) error has occurred
};
// ---------------------------------------------------------------------------
// Message queue allows passing message between threads.
//
// This class is typically used for communicating between the main and worker
// threads. The main thread calls Post() and the worker thread calls Receive().
//
// For this class a message is an object of arbitrary type T. Notice that
// typically there must be some special message indicating that the thread
// should terminate as there is no other way to gracefully shutdown a thread
// waiting on the message queue.
// ---------------------------------------------------------------------------
template <typename T>
class wxMessageQueue
{
public:
// The type of the messages transported by this queue
typedef T Message;
// Default ctor creates an initially empty queue
wxMessageQueue()
: m_conditionNotEmpty(m_mutex)
{
}
// Add a message to this queue and signal the threads waiting for messages.
//
// This method is safe to call from multiple threads in parallel.
wxMessageQueueError Post(const Message& msg)
{
wxMutexLocker locker(m_mutex);
wxCHECK( locker.IsOk(), wxMSGQUEUE_MISC_ERROR );
m_messages.push(msg);
m_conditionNotEmpty.Signal();
return wxMSGQUEUE_NO_ERROR;
}
// Remove all messages from the queue.
//
// This method is meant to be called from the same thread(s) that call
// Post() to discard any still pending requests if they became unnecessary.
wxMessageQueueError Clear()
{
wxCHECK( IsOk(), wxMSGQUEUE_MISC_ERROR );
wxMutexLocker locker(m_mutex);
std::queue<T> empty;
std::swap(m_messages, empty);
return wxMSGQUEUE_NO_ERROR;
}
// Wait no more than timeout milliseconds until a message becomes available.
//
// Setting timeout to 0 is equivalent to an infinite timeout. See Receive().
wxMessageQueueError ReceiveTimeout(long timeout, T& msg)
{
wxCHECK( IsOk(), wxMSGQUEUE_MISC_ERROR );
wxMutexLocker locker(m_mutex);
wxCHECK( locker.IsOk(), wxMSGQUEUE_MISC_ERROR );
const wxMilliClock_t waitUntil = wxGetLocalTimeMillis() + timeout;
while ( m_messages.empty() )
{
wxCondError result = m_conditionNotEmpty.WaitTimeout(timeout);
if ( result == wxCOND_NO_ERROR )
continue;
wxCHECK( result == wxCOND_TIMEOUT, wxMSGQUEUE_MISC_ERROR );
const wxMilliClock_t now = wxGetLocalTimeMillis();
if ( now >= waitUntil )
return wxMSGQUEUE_TIMEOUT;
timeout = (waitUntil - now).ToLong();
wxASSERT(timeout > 0);
}
msg = m_messages.front();
m_messages.pop();
return wxMSGQUEUE_NO_ERROR;
}
// Same as ReceiveTimeout() but waits for as long as it takes for a message
// to become available (so it can't return wxMSGQUEUE_TIMEOUT)
wxMessageQueueError Receive(T& msg)
{
wxCHECK( IsOk(), wxMSGQUEUE_MISC_ERROR );
wxMutexLocker locker(m_mutex);
wxCHECK( locker.IsOk(), wxMSGQUEUE_MISC_ERROR );
while ( m_messages.empty() )
{
wxCondError result = m_conditionNotEmpty.Wait();
wxCHECK( result == wxCOND_NO_ERROR, wxMSGQUEUE_MISC_ERROR );
}
msg = m_messages.front();
m_messages.pop();
return wxMSGQUEUE_NO_ERROR;
}
// Return false only if there was a fatal error in ctor
bool IsOk() const
{
return m_conditionNotEmpty.IsOk();
}
private:
// Disable copy ctor and assignment operator
wxMessageQueue(const wxMessageQueue<T>& rhs);
wxMessageQueue<T>& operator=(const wxMessageQueue<T>& rhs);
mutable wxMutex m_mutex;
wxCondition m_conditionNotEmpty;
std::queue<T> m_messages;
};
#endif // wxUSE_THREADS
#endif // _WX_MSGQUEUE_H_
|
h
|
rticonnextdds-usecases
|
data/projects/rticonnextdds-usecases/VehicleTracking/ExampleCode/thirdparty/wxWidgets-3.1.2/Linux/include/wx/tokenzr.h
|
/////////////////////////////////////////////////////////////////////////////
// Name: wx/tokenzr.h
// Purpose: String tokenizer - a C++ replacement for strtok(3)
// Author: Guilhem Lavaux
// Modified by: (or rather rewritten by) Vadim Zeitlin
// Created: 04/22/98
// Copyright: (c) Guilhem Lavaux
// Licence: wxWindows licence
/////////////////////////////////////////////////////////////////////////////
#ifndef _WX_TOKENZRH
#define _WX_TOKENZRH
#include "wx/object.h"
#include "wx/string.h"
#include "wx/arrstr.h"
// ----------------------------------------------------------------------------
// constants
// ----------------------------------------------------------------------------
// default: delimiters are usual white space characters
#define wxDEFAULT_DELIMITERS (wxT(" \t\r\n"))
// wxStringTokenizer mode flags which determine its behaviour
enum wxStringTokenizerMode
{
wxTOKEN_INVALID = -1, // set by def ctor until SetString() is called
wxTOKEN_DEFAULT, // strtok() for whitespace delims, RET_EMPTY else
wxTOKEN_RET_EMPTY, // return empty token in the middle of the string
wxTOKEN_RET_EMPTY_ALL, // return trailing empty tokens too
wxTOKEN_RET_DELIMS, // return the delim with token (implies RET_EMPTY)
wxTOKEN_STRTOK // behave exactly like strtok(3)
};
// ----------------------------------------------------------------------------
// wxStringTokenizer: replaces infamous strtok() and has some other features
// ----------------------------------------------------------------------------
class WXDLLIMPEXP_BASE wxStringTokenizer : public wxObject
{
public:
// ctors and initializers
// default ctor, call SetString() later
wxStringTokenizer() { m_mode = wxTOKEN_INVALID; }
// ctor which gives us the string
wxStringTokenizer(const wxString& str,
const wxString& delims = wxDEFAULT_DELIMITERS,
wxStringTokenizerMode mode = wxTOKEN_DEFAULT);
// copy ctor and assignment operator
wxStringTokenizer(const wxStringTokenizer& src);
wxStringTokenizer& operator=(const wxStringTokenizer& src);
// args are same as for the non default ctor above
void SetString(const wxString& str,
const wxString& delims = wxDEFAULT_DELIMITERS,
wxStringTokenizerMode mode = wxTOKEN_DEFAULT);
// reinitialize the tokenizer with the same delimiters/mode
void Reinit(const wxString& str);
// tokens access
// return the number of remaining tokens
size_t CountTokens() const;
// did we reach the end of the string?
bool HasMoreTokens() const;
// get the next token, will return empty string if !HasMoreTokens()
wxString GetNextToken();
// get the delimiter which terminated the token last retrieved by
// GetNextToken() or NUL if there had been no tokens yet or the last
// one wasn't terminated (but ran to the end of the string)
wxChar GetLastDelimiter() const { return m_lastDelim; }
// get current tokenizer state
// returns the part of the string which remains to tokenize (*not* the
// initial string)
wxString GetString() const { return wxString(m_pos, m_string.end()); }
// returns the current position (i.e. one index after the last
// returned token or 0 if GetNextToken() has never been called) in the
// original string
size_t GetPosition() const { return m_pos - m_string.begin(); }
// misc
// get the current mode - can be different from the one passed to the
// ctor if it was wxTOKEN_DEFAULT
wxStringTokenizerMode GetMode() const { return m_mode; }
// do we return empty tokens?
bool AllowEmpty() const { return m_mode != wxTOKEN_STRTOK; }
// backwards compatibility section from now on
// -------------------------------------------
// for compatibility only, use GetNextToken() instead
wxString NextToken() { return GetNextToken(); }
// compatibility only, don't use
void SetString(const wxString& to_tokenize,
const wxString& delims,
bool WXUNUSED(ret_delim))
{
SetString(to_tokenize, delims, wxTOKEN_RET_DELIMS);
}
wxStringTokenizer(const wxString& to_tokenize,
const wxString& delims,
bool ret_delim)
{
SetString(to_tokenize, delims, ret_delim);
}
protected:
bool IsOk() const { return m_mode != wxTOKEN_INVALID; }
bool DoHasMoreTokens() const;
void DoCopyFrom(const wxStringTokenizer& src);
enum MoreTokensState
{
MoreTokens_Unknown,
MoreTokens_Yes,
MoreTokens_No
};
MoreTokensState m_hasMoreTokens;
wxString m_string; // the string we tokenize
wxString::const_iterator m_stringEnd;
// FIXME-UTF8: use wxWcharBuffer
wxWxCharBuffer m_delims; // all possible delimiters
size_t m_delimsLen;
wxString::const_iterator m_pos; // the current position in m_string
wxStringTokenizerMode m_mode; // see wxTOKEN_XXX values
wxChar m_lastDelim; // delimiter after last token or '\0'
};
// ----------------------------------------------------------------------------
// convenience function which returns all tokens at once
// ----------------------------------------------------------------------------
// the function takes the same parameters as wxStringTokenizer ctor and returns
// the array containing all tokens
wxArrayString WXDLLIMPEXP_BASE
wxStringTokenize(const wxString& str,
const wxString& delims = wxDEFAULT_DELIMITERS,
wxStringTokenizerMode mode = wxTOKEN_DEFAULT);
#endif // _WX_TOKENZRH
|
h
|
rticonnextdds-usecases
|
data/projects/rticonnextdds-usecases/VehicleTracking/ExampleCode/thirdparty/wxWidgets-3.1.2/Linux/include/wx/filectrl.h
|
///////////////////////////////////////////////////////////////////////////////
// Name: wx/filectrl.h
// Purpose: Header for wxFileCtrlBase and other common functions used by
// platform-specific wxFileCtrl's
// Author: Diaa M. Sami
// Modified by:
// Created: Jul-07-2007
// Copyright: (c) Diaa M. Sami
// Licence: wxWindows licence
///////////////////////////////////////////////////////////////////////////////
#ifndef _WX_FILECTRL_H_BASE_
#define _WX_FILECTRL_H_BASE_
#include "wx/defs.h"
#if wxUSE_FILECTRL
#include "wx/string.h"
#include "wx/event.h"
enum
{
wxFC_OPEN = 0x0001,
wxFC_SAVE = 0x0002,
wxFC_MULTIPLE = 0x0004,
wxFC_NOSHOWHIDDEN = 0x0008
};
#define wxFC_DEFAULT_STYLE wxFC_OPEN
extern WXDLLIMPEXP_DATA_CORE(const char) wxFileCtrlNameStr[]; // in filectrlcmn.cpp
class WXDLLIMPEXP_CORE wxFileCtrlBase
{
public:
virtual ~wxFileCtrlBase() {}
virtual void SetWildcard( const wxString& wildCard ) = 0;
virtual void SetFilterIndex( int filterindex ) = 0;
virtual bool SetDirectory( const wxString& dir ) = 0;
// Selects a certain file.
// In case the filename specified isn't found/couldn't be shown with
// currently selected filter, false is returned and nothing happens
virtual bool SetFilename( const wxString& name ) = 0;
// chdirs to a certain directory and selects a certain file.
// In case the filename specified isn't found/couldn't be shown with
// currently selected filter, false is returned and if directory exists
// it's chdir'ed to
virtual bool SetPath( const wxString& path ) = 0;
virtual wxString GetFilename() const = 0;
virtual wxString GetDirectory() const = 0;
virtual wxString GetWildcard() const = 0;
virtual wxString GetPath() const = 0;
virtual void GetPaths( wxArrayString& paths ) const = 0;
virtual void GetFilenames( wxArrayString& files ) const = 0;
virtual int GetFilterIndex() const = 0;
virtual bool HasMultipleFileSelection() const = 0;
virtual void ShowHidden(bool show) = 0;
};
void wxGenerateFilterChangedEvent( wxFileCtrlBase *fileCtrl, wxWindow *wnd );
void wxGenerateFolderChangedEvent( wxFileCtrlBase *fileCtrl, wxWindow *wnd );
void wxGenerateSelectionChangedEvent( wxFileCtrlBase *fileCtrl, wxWindow *wnd );
void wxGenerateFileActivatedEvent( wxFileCtrlBase *fileCtrl, wxWindow *wnd, const wxString& filename = wxEmptyString );
#if defined(__WXGTK20__) && !defined(__WXUNIVERSAL__)
#define wxFileCtrl wxGtkFileCtrl
#include "wx/gtk/filectrl.h"
#else
#define wxFileCtrl wxGenericFileCtrl
#include "wx/generic/filectrlg.h"
#endif
// Some documentation
// On wxEVT_FILECTRL_FILTERCHANGED, only the value returned by GetFilterIndex is
// valid and it represents the (new) current filter index for the wxFileCtrl.
// On wxEVT_FILECTRL_FOLDERCHANGED, only the value returned by GetDirectory is
// valid and it represents the (new) current directory for the wxFileCtrl.
// On wxEVT_FILECTRL_FILEACTIVATED, GetDirectory returns the current directory
// for the wxFileCtrl and GetFiles returns the names of the file(s) activated.
// On wxEVT_FILECTRL_SELECTIONCHANGED, GetDirectory returns the current directory
// for the wxFileCtrl and GetFiles returns the names of the currently selected
// file(s).
// In wxGTK, after each wxEVT_FILECTRL_FOLDERCHANGED, wxEVT_FILECTRL_SELECTIONCHANGED
// is fired automatically once or more with 0 files.
class WXDLLIMPEXP_CORE wxFileCtrlEvent : public wxCommandEvent
{
public:
wxFileCtrlEvent() {}
wxFileCtrlEvent( wxEventType type, wxObject *evtObject, int id )
: wxCommandEvent( type, id )
{
SetEventObject( evtObject );
}
// no need for the copy constructor as the default one will be fine.
virtual wxEvent *Clone() const wxOVERRIDE { return new wxFileCtrlEvent( *this ); }
void SetFiles( const wxArrayString &files ) { m_files = files; }
void SetDirectory( const wxString &directory ) { m_directory = directory; }
void SetFilterIndex( int filterIndex ) { m_filterIndex = filterIndex; }
wxArrayString GetFiles() const { return m_files; }
wxString GetDirectory() const { return m_directory; }
int GetFilterIndex() const { return m_filterIndex; }
wxString GetFile() const;
protected:
int m_filterIndex;
wxString m_directory;
wxArrayString m_files;
wxDECLARE_DYNAMIC_CLASS_NO_ASSIGN(wxFileCtrlEvent);
};
typedef void ( wxEvtHandler::*wxFileCtrlEventFunction )( wxFileCtrlEvent& );
wxDECLARE_EXPORTED_EVENT( WXDLLIMPEXP_CORE, wxEVT_FILECTRL_SELECTIONCHANGED, wxFileCtrlEvent );
wxDECLARE_EXPORTED_EVENT( WXDLLIMPEXP_CORE, wxEVT_FILECTRL_FILEACTIVATED, wxFileCtrlEvent );
wxDECLARE_EXPORTED_EVENT( WXDLLIMPEXP_CORE, wxEVT_FILECTRL_FOLDERCHANGED, wxFileCtrlEvent );
wxDECLARE_EXPORTED_EVENT( WXDLLIMPEXP_CORE, wxEVT_FILECTRL_FILTERCHANGED, wxFileCtrlEvent );
#define wxFileCtrlEventHandler(func) \
wxEVENT_HANDLER_CAST( wxFileCtrlEventFunction, func )
#define EVT_FILECTRL_FILEACTIVATED(id, fn) \
wx__DECLARE_EVT1(wxEVT_FILECTRL_FILEACTIVATED, id, wxFileCtrlEventHandler(fn))
#define EVT_FILECTRL_SELECTIONCHANGED(id, fn) \
wx__DECLARE_EVT1(wxEVT_FILECTRL_SELECTIONCHANGED, id, wxFileCtrlEventHandler(fn))
#define EVT_FILECTRL_FOLDERCHANGED(id, fn) \
wx__DECLARE_EVT1(wxEVT_FILECTRL_FOLDERCHANGED, id, wxFileCtrlEventHandler(fn))
#define EVT_FILECTRL_FILTERCHANGED(id, fn) \
wx__DECLARE_EVT1(wxEVT_FILECTRL_FILTERCHANGED, id, wxFileCtrlEventHandler(fn))
#endif // wxUSE_FILECTRL
#endif // _WX_FILECTRL_H_BASE_
|
h
|
rticonnextdds-usecases
|
data/projects/rticonnextdds-usecases/VehicleTracking/ExampleCode/thirdparty/wxWidgets-3.1.2/Linux/include/wx/wxcrtbase.h
|
/*
* Name: wx/wxcrtbase.h
* Purpose: Type-safe ANSI and Unicode builds compatible wrappers for
* CRT functions
* Author: Joel Farley, Ove Kaaven
* Modified by: Vadim Zeitlin, Robert Roebling, Ron Lee
* Created: 1998/06/12
* Copyright: (c) 1998-2006 wxWidgets dev team
* Licence: wxWindows licence
*/
/* THIS IS A C FILE, DON'T USE C++ FEATURES (IN PARTICULAR COMMENTS) IN IT */
#ifndef _WX_WXCRTBASE_H_
#define _WX_WXCRTBASE_H_
/* -------------------------------------------------------------------------
headers and missing declarations
------------------------------------------------------------------------- */
#include "wx/chartype.h"
/*
Standard headers we need here.
NB: don't include any wxWidgets headers here because almost all of them
include this one!
NB2: User code should include wx/crt.h instead of including this
header directly.
*/
#include <stdio.h>
#include <string.h>
#include <ctype.h>
#include <wctype.h>
#include <time.h>
#if defined(__WINDOWS__)
#include <io.h>
#endif
#if defined(HAVE_STRTOK_R) && defined(__DARWIN__) && defined(_MSL_USING_MW_C_HEADERS) && _MSL_USING_MW_C_HEADERS
char *strtok_r(char *, const char *, char **);
#endif
/*
Traditional MinGW doesn't declare isascii() in strict ANSI mode and we can't
declare it here ourselves as it's an inline function, so use our own
replacement instead.
*/
#ifndef isascii
#if defined(wxNEEDS_STRICT_ANSI_WORKAROUNDS)
#define wxNEED_ISASCII
#endif
#endif /* isascii */
#ifdef wxNEED_ISASCII
inline int isascii(int c) { return (unsigned)c < 0x80; }
// Avoid further (re)definitions of it.
#define isascii isascii
#endif
/* string.h functions */
#ifdef wxNEED_STRDUP
WXDLLIMPEXP_BASE char *strdup(const char* s);
#endif
/* -------------------------------------------------------------------------
UTF-8 locale handling
------------------------------------------------------------------------- */
#ifdef __cplusplus
/* flag indicating whether the current locale uses UTF-8 or not; must be
updated every time the locale is changed! */
#if wxUSE_UTF8_LOCALE_ONLY
#define wxLocaleIsUtf8 true
#else
extern WXDLLIMPEXP_BASE bool wxLocaleIsUtf8;
#endif
/* function used to update the flag: */
extern WXDLLIMPEXP_BASE void wxUpdateLocaleIsUtf8();
#endif /* __cplusplus */
/* -------------------------------------------------------------------------
string.h
------------------------------------------------------------------------- */
#define wxCRT_StrcatA strcat
#define wxCRT_StrchrA strchr
#define wxCRT_StrcmpA strcmp
#define wxCRT_StrcpyA strcpy
#define wxCRT_StrcspnA strcspn
#define wxCRT_StrlenA strlen
#define wxCRT_StrncatA strncat
#define wxCRT_StrncmpA strncmp
#define wxCRT_StrncpyA strncpy
#define wxCRT_StrpbrkA strpbrk
#define wxCRT_StrrchrA strrchr
#define wxCRT_StrspnA strspn
#define wxCRT_StrstrA strstr
#define wxCRT_StrcatW wcscat
#define wxCRT_StrchrW wcschr
#define wxCRT_StrcmpW wcscmp
#define wxCRT_StrcpyW wcscpy
#define wxCRT_StrcspnW wcscspn
#define wxCRT_StrncatW wcsncat
#define wxCRT_StrncmpW wcsncmp
#define wxCRT_StrncpyW wcsncpy
#define wxCRT_StrpbrkW wcspbrk
#define wxCRT_StrrchrW wcsrchr
#define wxCRT_StrspnW wcsspn
#define wxCRT_StrstrW wcsstr
#define wxCRT_StrcollA strcoll
#define wxCRT_StrxfrmA strxfrm
#define wxCRT_StrcollW wcscoll
#define wxCRT_StrxfrmW wcsxfrm
/* Almost all compilers have strdup(), but VC++ and MinGW call it _strdup().
And we need to declare it manually for MinGW in strict ANSI mode. */
#if (defined(__VISUALC__) && __VISUALC__ >= 1400)
#define wxCRT_StrdupA _strdup
#elif defined(__MINGW32__)
wxDECL_FOR_STRICT_MINGW32(char*, _strdup, (const char *))
#define wxCRT_StrdupA _strdup
#else
#define wxCRT_StrdupA strdup
#endif
/* Windows compilers provide _wcsdup() except for (old) Cygwin */
#if defined(__WINDOWS__) && !defined(__CYGWIN__)
wxDECL_FOR_STRICT_MINGW32(wchar_t*, _wcsdup, (const wchar_t*))
#define wxCRT_StrdupW _wcsdup
#elif defined(HAVE_WCSDUP)
#define wxCRT_StrdupW wcsdup
#endif
#ifdef wxHAVE_TCHAR_SUPPORT
/* we surely have wchar_t if we have TCHAR have wcslen() */
#ifndef HAVE_WCSLEN
#define HAVE_WCSLEN
#endif
#endif /* wxHAVE_TCHAR_SUPPORT */
#ifdef HAVE_WCSLEN
#define wxCRT_StrlenW wcslen
#endif
#define wxCRT_StrtodA strtod
#define wxCRT_StrtolA strtol
#define wxCRT_StrtoulA strtoul
#ifdef __ANDROID__ // these functions are broken on android
extern double android_wcstod(const wchar_t *nptr, wchar_t **endptr);
extern long android_wcstol(const wchar_t *nptr, wchar_t **endptr, int base);
extern unsigned long android_wcstoul(const wchar_t *nptr, wchar_t **endptr, int base);
#define wxCRT_StrtodW android_wcstod
#define wxCRT_StrtolW android_wcstol
#define wxCRT_StrtoulW android_wcstoul
#else
#define wxCRT_StrtodW wcstod
#define wxCRT_StrtolW wcstol
#define wxCRT_StrtoulW wcstoul
#endif
#ifdef __VISUALC__
#define wxCRT_StrtollA _strtoi64
#define wxCRT_StrtoullA _strtoui64
#define wxCRT_StrtollW _wcstoi64
#define wxCRT_StrtoullW _wcstoui64
#else
/* Both of these functions are implemented in C++11 compilers */
#if defined(__cplusplus) && __cplusplus >= 201103L
#ifndef HAVE_STRTOULL
#define HAVE_STRTOULL
#endif
#ifndef HAVE_WCSTOULL
#define HAVE_WCSTOULL
#endif
#endif
#ifdef HAVE_STRTOULL
wxDECL_FOR_STRICT_MINGW32(long long, strtoll, (const char*, char**, int))
wxDECL_FOR_STRICT_MINGW32(unsigned long long, strtoull, (const char*, char**, int))
#define wxCRT_StrtollA strtoll
#define wxCRT_StrtoullA strtoull
#endif /* HAVE_STRTOULL */
#ifdef HAVE_WCSTOULL
/* assume that we have wcstoull(), which is also C99, too */
#define wxCRT_StrtollW wcstoll
#define wxCRT_StrtoullW wcstoull
#endif /* HAVE_WCSTOULL */
#endif
/*
Only VC8 and later provide strnlen() and wcsnlen() functions under Windows.
*/
#if wxCHECK_VISUALC_VERSION(8)
#ifndef HAVE_STRNLEN
#define HAVE_STRNLEN
#endif
#ifndef HAVE_WCSNLEN
#define HAVE_WCSNLEN
#endif
#endif
#ifdef HAVE_STRNLEN
#define wxCRT_StrnlenA strnlen
#endif
#ifdef HAVE_WCSNLEN
/*
When using MinGW, wcsnlen() is not declared, but is still found by
configure -- just declare it in this case as it seems better to use it
if it's available (see https://sourceforge.net/p/mingw/bugs/2332/)
*/
wxDECL_FOR_MINGW32_ALWAYS(size_t, wcsnlen, (const wchar_t*, size_t))
#define wxCRT_StrnlenW wcsnlen
#endif
/* define wxCRT_StricmpA/W and wxCRT_StrnicmpA/W for various compilers */
#if defined(__BORLANDC__)
#define wxCRT_StricmpA stricmp
#define wxCRT_StrnicmpA strnicmp
#elif defined(__VISUALC__) || defined(__MINGW32__)
/*
Due to MinGW 5.3 bug (https://sourceforge.net/p/mingw/bugs/2322/),
_stricmp() and _strnicmp() are not declared in its standard headers
when compiling without optimizations. Work around this by always
declaring them ourselves (notice that if/when this bug were fixed, we'd
still need to use wxDECL_FOR_STRICT_MINGW32() for them here.
*/
wxDECL_FOR_MINGW32_ALWAYS(int, _stricmp, (const char*, const char*))
wxDECL_FOR_MINGW32_ALWAYS(int, _strnicmp, (const char*, const char*, size_t))
#define wxCRT_StricmpA _stricmp
#define wxCRT_StrnicmpA _strnicmp
#elif defined(__UNIX__)
#define wxCRT_StricmpA strcasecmp
#define wxCRT_StrnicmpA strncasecmp
/* #else -- use wxWidgets implementation */
#endif
#ifdef __VISUALC__
#define wxCRT_StricmpW _wcsicmp
#define wxCRT_StrnicmpW _wcsnicmp
#elif defined(__UNIX__)
#ifdef HAVE_WCSCASECMP
#define wxCRT_StricmpW wcscasecmp
#endif
#ifdef HAVE_WCSNCASECMP
#define wxCRT_StrnicmpW wcsncasecmp
#endif
/* #else -- use wxWidgets implementation */
#endif
#ifdef HAVE_STRTOK_R
#define wxCRT_StrtokA(str, sep, last) strtok_r(str, sep, last)
#endif
/* FIXME-UTF8: detect and use wcstok() if available for wxCRT_StrtokW */
/* these are extern "C" because they are used by regex lib: */
#ifdef __cplusplus
extern "C" {
#endif
#ifndef wxCRT_StrlenW
WXDLLIMPEXP_BASE size_t wxCRT_StrlenW(const wchar_t *s);
#endif
#ifndef wxCRT_StrncmpW
WXDLLIMPEXP_BASE int wxCRT_StrncmpW(const wchar_t *s1, const wchar_t *s2, size_t n);
#endif
#ifdef __cplusplus
}
#endif
/* FIXME-UTF8: remove this once we are Unicode only */
#if wxUSE_UNICODE
#define wxCRT_StrlenNative wxCRT_StrlenW
#define wxCRT_StrncmpNative wxCRT_StrncmpW
#define wxCRT_ToupperNative wxCRT_ToupperW
#define wxCRT_TolowerNative wxCRT_TolowerW
#else
#define wxCRT_StrlenNative wxCRT_StrlenA
#define wxCRT_StrncmpNative wxCRT_StrncmpA
#define wxCRT_ToupperNative toupper
#define wxCRT_TolowerNative tolower
#endif
#ifndef wxCRT_StrcatW
WXDLLIMPEXP_BASE wchar_t *wxCRT_StrcatW(wchar_t *dest, const wchar_t *src);
#endif
#ifndef wxCRT_StrchrW
WXDLLIMPEXP_BASE const wchar_t *wxCRT_StrchrW(const wchar_t *s, wchar_t c);
#endif
#ifndef wxCRT_StrcmpW
WXDLLIMPEXP_BASE int wxCRT_StrcmpW(const wchar_t *s1, const wchar_t *s2);
#endif
#ifndef wxCRT_StrcollW
WXDLLIMPEXP_BASE int wxCRT_StrcollW(const wchar_t *s1, const wchar_t *s2);
#endif
#ifndef wxCRT_StrcpyW
WXDLLIMPEXP_BASE wchar_t *wxCRT_StrcpyW(wchar_t *dest, const wchar_t *src);
#endif
#ifndef wxCRT_StrcspnW
WXDLLIMPEXP_BASE size_t wxCRT_StrcspnW(const wchar_t *s, const wchar_t *reject);
#endif
#ifndef wxCRT_StrncatW
WXDLLIMPEXP_BASE wchar_t *wxCRT_StrncatW(wchar_t *dest, const wchar_t *src, size_t n);
#endif
#ifndef wxCRT_StrncpyW
WXDLLIMPEXP_BASE wchar_t *wxCRT_StrncpyW(wchar_t *dest, const wchar_t *src, size_t n);
#endif
#ifndef wxCRT_StrpbrkW
WXDLLIMPEXP_BASE const wchar_t *wxCRT_StrpbrkW(const wchar_t *s, const wchar_t *accept);
#endif
#ifndef wxCRT_StrrchrW
WXDLLIMPEXP_BASE const wchar_t *wxCRT_StrrchrW(const wchar_t *s, wchar_t c);
#endif
#ifndef wxCRT_StrspnW
WXDLLIMPEXP_BASE size_t wxCRT_StrspnW(const wchar_t *s, const wchar_t *accept);
#endif
#ifndef wxCRT_StrstrW
WXDLLIMPEXP_BASE const wchar_t *wxCRT_StrstrW(const wchar_t *haystack, const wchar_t *needle);
#endif
#ifndef wxCRT_StrtodW
WXDLLIMPEXP_BASE double wxCRT_StrtodW(const wchar_t *nptr, wchar_t **endptr);
#endif
#ifndef wxCRT_StrtolW
WXDLLIMPEXP_BASE long int wxCRT_StrtolW(const wchar_t *nptr, wchar_t **endptr, int base);
#endif
#ifndef wxCRT_StrtoulW
WXDLLIMPEXP_BASE unsigned long int wxCRT_StrtoulW(const wchar_t *nptr, wchar_t **endptr, int base);
#endif
#ifndef wxCRT_StrxfrmW
WXDLLIMPEXP_BASE size_t wxCRT_StrxfrmW(wchar_t *dest, const wchar_t *src, size_t n);
#endif
#ifndef wxCRT_StrdupA
WXDLLIMPEXP_BASE char *wxCRT_StrdupA(const char *psz);
#endif
#ifndef wxCRT_StrdupW
WXDLLIMPEXP_BASE wchar_t *wxCRT_StrdupW(const wchar_t *pwz);
#endif
#ifndef wxCRT_StricmpA
WXDLLIMPEXP_BASE int wxCRT_StricmpA(const char *psz1, const char *psz2);
#endif
#ifndef wxCRT_StricmpW
WXDLLIMPEXP_BASE int wxCRT_StricmpW(const wchar_t *psz1, const wchar_t *psz2);
#endif
#ifndef wxCRT_StrnicmpA
WXDLLIMPEXP_BASE int wxCRT_StrnicmpA(const char *psz1, const char *psz2, size_t len);
#endif
#ifndef wxCRT_StrnicmpW
WXDLLIMPEXP_BASE int wxCRT_StrnicmpW(const wchar_t *psz1, const wchar_t *psz2, size_t len);
#endif
#ifndef wxCRT_StrtokA
WXDLLIMPEXP_BASE char *wxCRT_StrtokA(char *psz, const char *delim, char **save_ptr);
#endif
#ifndef wxCRT_StrtokW
WXDLLIMPEXP_BASE wchar_t *wxCRT_StrtokW(wchar_t *psz, const wchar_t *delim, wchar_t **save_ptr);
#endif
/* supply strtoll and strtoull, if needed */
#ifdef wxLongLong_t
#ifndef wxCRT_StrtollA
WXDLLIMPEXP_BASE wxLongLong_t wxCRT_StrtollA(const char* nptr,
char** endptr,
int base);
WXDLLIMPEXP_BASE wxULongLong_t wxCRT_StrtoullA(const char* nptr,
char** endptr,
int base);
#endif
#ifndef wxCRT_StrtollW
WXDLLIMPEXP_BASE wxLongLong_t wxCRT_StrtollW(const wchar_t* nptr,
wchar_t** endptr,
int base);
WXDLLIMPEXP_BASE wxULongLong_t wxCRT_StrtoullW(const wchar_t* nptr,
wchar_t** endptr,
int base);
#endif
#endif /* wxLongLong_t */
/* -------------------------------------------------------------------------
stdio.h
------------------------------------------------------------------------- */
#if defined(__UNIX__) || defined(__WXMAC__)
#define wxMBFILES 1
#else
#define wxMBFILES 0
#endif
/* these functions are only needed in the form used for filenames (i.e. char*
on Unix, wchar_t* on Windows), so we don't need to use A/W suffix: */
#if wxMBFILES || !wxUSE_UNICODE /* ANSI filenames */
#define wxCRT_Fopen fopen
#define wxCRT_Freopen freopen
#define wxCRT_Remove remove
#define wxCRT_Rename rename
#else /* Unicode filenames */
wxDECL_FOR_STRICT_MINGW32(FILE*, _wfopen, (const wchar_t*, const wchar_t*))
wxDECL_FOR_STRICT_MINGW32(FILE*, _wfreopen, (const wchar_t*, const wchar_t*, FILE*))
wxDECL_FOR_STRICT_MINGW32(int, _wrename, (const wchar_t*, const wchar_t*))
wxDECL_FOR_STRICT_MINGW32(int, _wremove, (const wchar_t*))
#define wxCRT_Rename _wrename
#define wxCRT_Remove _wremove
#define wxCRT_Fopen _wfopen
#define wxCRT_Freopen _wfreopen
#endif /* wxMBFILES/!wxMBFILES */
#define wxCRT_PutsA puts
#define wxCRT_FputsA fputs
#define wxCRT_FgetsA fgets
#define wxCRT_FputcA fputc
#define wxCRT_FgetcA fgetc
#define wxCRT_UngetcA ungetc
#ifdef wxHAVE_TCHAR_SUPPORT
#define wxCRT_PutsW _putws
#define wxCRT_FputsW fputws
#define wxCRT_FputcW fputwc
#endif
#ifdef HAVE_FPUTWS
#define wxCRT_FputsW fputws
#endif
#ifdef HAVE_PUTWS
#define wxCRT_PutsW putws
#endif
#ifdef HAVE_FPUTWC
#define wxCRT_FputcW fputwc
#endif
#define wxCRT_FgetsW fgetws
#ifndef wxCRT_PutsW
WXDLLIMPEXP_BASE int wxCRT_PutsW(const wchar_t *ws);
#endif
#ifndef wxCRT_FputsW
WXDLLIMPEXP_BASE int wxCRT_FputsW(const wchar_t *ch, FILE *stream);
#endif
#ifndef wxCRT_FputcW
WXDLLIMPEXP_BASE int wxCRT_FputcW(wchar_t wc, FILE *stream);
#endif
/*
NB: tmpnam() is unsafe and thus is not wrapped!
Use other wxWidgets facilities instead:
wxFileName::CreateTempFileName, wxTempFile, or wxTempFileOutputStream
*/
#define wxTmpnam(x) wxTmpnam_is_insecure_use_wxTempFile_instead
#define wxCRT_PerrorA perror
#ifdef wxHAVE_TCHAR_SUPPORT
#define wxCRT_PerrorW _wperror
#endif
/* -------------------------------------------------------------------------
stdlib.h
------------------------------------------------------------------------- */
#define wxCRT_GetenvA getenv
#ifdef _tgetenv
#define wxCRT_GetenvW _wgetenv
#endif
#ifndef wxCRT_GetenvW
WXDLLIMPEXP_BASE wchar_t * wxCRT_GetenvW(const wchar_t *name);
#endif
#define wxCRT_SystemA system
/* mingw32 doesn't provide _tsystem() or _wsystem(): */
#if defined(_tsystem)
#define wxCRT_SystemW _wsystem
#endif
#define wxCRT_AtofA atof
#define wxCRT_AtoiA atoi
#define wxCRT_AtolA atol
#if defined(wxHAVE_TCHAR_SUPPORT)
wxDECL_FOR_STRICT_MINGW32(int, _wtoi, (const wchar_t*))
wxDECL_FOR_STRICT_MINGW32(long, _wtol, (const wchar_t*))
#define wxCRT_AtoiW _wtoi
#define wxCRT_AtolW _wtol
/* _wtof doesn't exist */
#else
#ifndef __VMS
#define wxCRT_AtofW(s) wcstod(s, NULL)
#endif
#define wxCRT_AtolW(s) wcstol(s, NULL, 10)
/* wcstoi doesn't exist */
#endif
/* -------------------------------------------------------------------------
time.h
------------------------------------------------------------------------- */
#define wxCRT_StrftimeA strftime
#ifdef __SGI__
/*
IRIX provides not one but two versions of wcsftime(): XPG4 one which
uses "const char*" for the third parameter and so can't be used and the
correct, XPG5, one. Unfortunately we can't just define _XOPEN_SOURCE
high enough to get XPG5 version as this undefines other symbols which
make other functions we use unavailable (see <standards.h> for gory
details). So just declare the XPG5 version ourselves, we're extremely
unlikely to ever be compiled on a system without it. But if we ever do,
a configure test would need to be added for it (and _MIPS_SYMBOL_PRESENT
should be used to check for its presence during run-time, i.e. it would
probably be simpler to just always use our own wxCRT_StrftimeW() below
if it does ever become a problem).
*/
#ifdef __cplusplus
extern "C"
#endif
size_t
_xpg5_wcsftime(wchar_t *, size_t, const wchar_t *, const struct tm * );
#define wxCRT_StrftimeW _xpg5_wcsftime
#else
/*
Assume it's always available under non-Unix systems as this does seem
to be the case for now. And under Unix we trust configure to detect it
(except for SGI special case above).
*/
#if defined(HAVE_WCSFTIME) || !defined(__UNIX__)
#define wxCRT_StrftimeW wcsftime
#endif
#endif
#ifndef wxCRT_StrftimeW
WXDLLIMPEXP_BASE size_t wxCRT_StrftimeW(wchar_t *s, size_t max,
const wchar_t *fmt,
const struct tm *tm);
#endif
/* -------------------------------------------------------------------------
ctype.h
------------------------------------------------------------------------- */
#define wxCRT_IsalnumW(c) iswalnum(c)
#define wxCRT_IsalphaW(c) iswalpha(c)
#define wxCRT_IscntrlW(c) iswcntrl(c)
#define wxCRT_IsdigitW(c) iswdigit(c)
#define wxCRT_IsgraphW(c) iswgraph(c)
#define wxCRT_IslowerW(c) iswlower(c)
#define wxCRT_IsprintW(c) iswprint(c)
#define wxCRT_IspunctW(c) iswpunct(c)
#define wxCRT_IsspaceW(c) iswspace(c)
#define wxCRT_IsupperW(c) iswupper(c)
#define wxCRT_IsxdigitW(c) iswxdigit(c)
#ifdef __GLIBC__
#if defined(__GLIBC__) && (__GLIBC__ == 2) && (__GLIBC_MINOR__ == 0)
/* /usr/include/wctype.h incorrectly declares translations */
/* tables which provokes tons of compile-time warnings -- try */
/* to correct this */
#define wxCRT_TolowerW(wc) towctrans((wc), (wctrans_t)__ctype_tolower)
#define wxCRT_ToupperW(wc) towctrans((wc), (wctrans_t)__ctype_toupper)
#else /* !glibc 2.0 */
#define wxCRT_TolowerW towlower
#define wxCRT_ToupperW towupper
#endif
#else /* !__GLIBC__ */
/* There is a bug in MSVC RTL: toxxx() functions don't do anything
with signed chars < 0, so "fix" it here. */
#define wxCRT_TolowerW(c) towlower((wxUChar)(wxChar)(c))
#define wxCRT_ToupperW(c) towupper((wxUChar)(wxChar)(c))
#endif /* __GLIBC__/!__GLIBC__ */
/* The Android platform, as of 2014, only support most wide-char function with
the exception of multi-byte encoding/decoding functions & wsprintf/wsscanf
See android-ndk-r9d/docs/STANDALONE-TOOLCHAIN.html (section 7.2)
In fact, mbstowcs/wcstombs are defined and compile, but don't work correctly
*/
#if defined(__WXQT__) && defined(__ANDROID__)
#define wxNEED_WX_MBSTOWCS
#undef HAVE_WCSRTOMBS
// TODO: use Qt built-in required functionality
#endif
#if defined(wxNEED_WX_MBSTOWCS) && defined(__ANDROID__)
#warning "Custom mb/wchar conv. only works for ASCII, see Android NDK notes"
WXDLLIMPEXP_BASE size_t android_mbstowcs(wchar_t *, const char *, size_t);
WXDLLIMPEXP_BASE size_t android_wcstombs(char *, const wchar_t *, size_t);
#define wxMbstowcs android_mbstowcs
#define wxWcstombs android_wcstombs
#else
#define wxMbstowcs mbstowcs
#define wxWcstombs wcstombs
#endif
/* -------------------------------------------------------------------------
wx wrappers for CRT functions in both char* and wchar_t* versions
------------------------------------------------------------------------- */
#ifdef __cplusplus
/* NB: this belongs to wxcrt.h and not this header, but it makes life easier
* for buffer.h and stringimpl.h (both of which must be included before
* string.h, which is required by wxcrt.h) to have them here: */
/* safe version of strlen() (returns 0 if passed NULL pointer) */
inline size_t wxStrlen(const char *s) { return s ? wxCRT_StrlenA(s) : 0; }
inline size_t wxStrlen(const wchar_t *s) { return s ? wxCRT_StrlenW(s) : 0; }
#ifndef wxWCHAR_T_IS_WXCHAR16
WXDLLIMPEXP_BASE size_t wxStrlen(const wxChar16 *s );
#endif
#ifndef wxWCHAR_T_IS_WXCHAR32
WXDLLIMPEXP_BASE size_t wxStrlen(const wxChar32 *s );
#endif
#define wxWcslen wxCRT_StrlenW
#define wxStrdupA wxCRT_StrdupA
#define wxStrdupW wxCRT_StrdupW
inline char* wxStrdup(const char *s) { return wxCRT_StrdupA(s); }
inline wchar_t* wxStrdup(const wchar_t *s) { return wxCRT_StrdupW(s); }
#ifndef wxWCHAR_T_IS_WXCHAR16
WXDLLIMPEXP_BASE wxChar16* wxStrdup(const wxChar16* s);
#endif
#ifndef wxWCHAR_T_IS_WXCHAR32
WXDLLIMPEXP_BASE wxChar32* wxStrdup(const wxChar32* s);
#endif
#endif /* __cplusplus */
#endif /* _WX_WXCRTBASE_H_ */
|
h
|
rticonnextdds-usecases
|
data/projects/rticonnextdds-usecases/VehicleTracking/ExampleCode/thirdparty/wxWidgets-3.1.2/Linux/include/wx/imagtiff.h
|
/////////////////////////////////////////////////////////////////////////////
// Name: wx/imagtiff.h
// Purpose: wxImage TIFF handler
// Author: Robert Roebling
// Copyright: (c) Robert Roebling
// Licence: wxWindows licence
/////////////////////////////////////////////////////////////////////////////
#ifndef _WX_IMAGTIFF_H_
#define _WX_IMAGTIFF_H_
#include "wx/defs.h"
//-----------------------------------------------------------------------------
// wxTIFFHandler
//-----------------------------------------------------------------------------
#if wxUSE_LIBTIFF
#include "wx/image.h"
#include "wx/versioninfo.h"
// defines for wxImage::SetOption
#define wxIMAGE_OPTION_TIFF_BITSPERSAMPLE wxString(wxT("BitsPerSample"))
#define wxIMAGE_OPTION_TIFF_SAMPLESPERPIXEL wxString(wxT("SamplesPerPixel"))
#define wxIMAGE_OPTION_TIFF_COMPRESSION wxString(wxT("Compression"))
#define wxIMAGE_OPTION_TIFF_PHOTOMETRIC wxString(wxT("Photometric"))
#define wxIMAGE_OPTION_TIFF_IMAGEDESCRIPTOR wxString(wxT("ImageDescriptor"))
// for backwards compatibility
#define wxIMAGE_OPTION_BITSPERSAMPLE wxIMAGE_OPTION_TIFF_BITSPERSAMPLE
#define wxIMAGE_OPTION_SAMPLESPERPIXEL wxIMAGE_OPTION_TIFF_SAMPLESPERPIXEL
#define wxIMAGE_OPTION_COMPRESSION wxIMAGE_OPTION_TIFF_COMPRESSION
#define wxIMAGE_OPTION_IMAGEDESCRIPTOR wxIMAGE_OPTION_TIFF_IMAGEDESCRIPTOR
class WXDLLIMPEXP_CORE wxTIFFHandler: public wxImageHandler
{
public:
wxTIFFHandler();
static wxVersionInfo GetLibraryVersionInfo();
#if wxUSE_STREAMS
virtual bool LoadFile( wxImage *image, wxInputStream& stream, bool verbose=true, int index=-1 ) wxOVERRIDE;
virtual bool SaveFile( wxImage *image, wxOutputStream& stream, bool verbose=true ) wxOVERRIDE;
protected:
virtual int DoGetImageCount( wxInputStream& stream ) wxOVERRIDE;
virtual bool DoCanRead( wxInputStream& stream ) wxOVERRIDE;
#endif
private:
wxDECLARE_DYNAMIC_CLASS(wxTIFFHandler);
};
#endif // wxUSE_LIBTIFF
#endif // _WX_IMAGTIFF_H_
|
h
|
rticonnextdds-usecases
|
data/projects/rticonnextdds-usecases/VehicleTracking/ExampleCode/thirdparty/wxWidgets-3.1.2/Linux/include/wx/nonownedwnd.h
|
///////////////////////////////////////////////////////////////////////////////
// Name: wx/nonownedwnd.h
// Purpose: declares wxNonTopLevelWindow class
// Author: Vaclav Slavik
// Modified by:
// Created: 2006-12-24
// Copyright: (c) 2006 TT-Solutions
// Licence: wxWindows licence
///////////////////////////////////////////////////////////////////////////////
#ifndef _WX_NONOWNEDWND_H_
#define _WX_NONOWNEDWND_H_
#include "wx/window.h"
// Styles that can be used with any wxNonOwnedWindow:
#define wxFRAME_SHAPED 0x0010 // Create a window that is able to be shaped
class WXDLLIMPEXP_FWD_CORE wxGraphicsPath;
// ----------------------------------------------------------------------------
// wxNonOwnedWindow: a window that is not a child window of another one.
// ----------------------------------------------------------------------------
class WXDLLIMPEXP_CORE wxNonOwnedWindowBase : public wxWindow
{
public:
// Set the shape of the window to the given region.
// Returns true if the platform supports this feature (and the
// operation is successful.)
bool SetShape(const wxRegion& region)
{
// This style is in fact only needed by wxOSX/Carbon so once we don't
// use this port any more, we could get rid of this requirement, but
// for now you must specify wxFRAME_SHAPED for SetShape() to work on
// all platforms.
wxCHECK_MSG
(
HasFlag(wxFRAME_SHAPED), false,
wxS("Shaped windows must be created with the wxFRAME_SHAPED style.")
);
return region.IsEmpty() ? DoClearShape() : DoSetRegionShape(region);
}
#if wxUSE_GRAPHICS_CONTEXT
// Set the shape using the specified path.
bool SetShape(const wxGraphicsPath& path)
{
wxCHECK_MSG
(
HasFlag(wxFRAME_SHAPED), false,
wxS("Shaped windows must be created with the wxFRAME_SHAPED style.")
);
return DoSetPathShape(path);
}
#endif // wxUSE_GRAPHICS_CONTEXT
// Overridden base class methods.
// ------------------------------
virtual void AdjustForParentClientOrigin(int& WXUNUSED(x), int& WXUNUSED(y),
int WXUNUSED(sizeFlags) = 0) const wxOVERRIDE
{
// Non owned windows positions don't need to be adjusted for parent
// client area origin so simply do nothing here.
}
virtual void InheritAttributes() wxOVERRIDE
{
// Non owned windows don't inherit attributes from their parent window
// (if the parent frame is red, it doesn't mean that all dialogs shown
// by it should be red as well), so don't do anything here neither.
}
protected:
virtual bool DoClearShape()
{
return false;
}
virtual bool DoSetRegionShape(const wxRegion& WXUNUSED(region))
{
return false;
}
#if wxUSE_GRAPHICS_CONTEXT
virtual bool DoSetPathShape(const wxGraphicsPath& WXUNUSED(path))
{
return false;
}
#endif // wxUSE_GRAPHICS_CONTEXT
};
#if defined(__WXDFB__)
#include "wx/dfb/nonownedwnd.h"
#elif defined(__WXGTK20__)
#include "wx/gtk/nonownedwnd.h"
#elif defined(__WXMAC__)
#include "wx/osx/nonownedwnd.h"
#elif defined(__WXMSW__)
#include "wx/msw/nonownedwnd.h"
#elif defined(__WXQT__)
#include "wx/qt/nonownedwnd.h"
#else
// No special class needed in other ports, they can derive both wxTLW and
// wxPopupWindow directly from wxWindow and don't implement SetShape().
class wxNonOwnedWindow : public wxNonOwnedWindowBase
{
};
#endif
#endif // _WX_NONOWNEDWND_H_
|
h
|
rticonnextdds-usecases
|
data/projects/rticonnextdds-usecases/VehicleTracking/ExampleCode/thirdparty/wxWidgets-3.1.2/Linux/include/wx/activityindicator.h
|
///////////////////////////////////////////////////////////////////////////////
// Name: wx/activityindicator.h
// Purpose: wxActivityIndicator declaration.
// Author: Vadim Zeitlin
// Created: 2015-03-05
// Copyright: (c) 2015 Vadim Zeitlin <[email protected]>
// Licence: wxWindows licence
///////////////////////////////////////////////////////////////////////////////
#ifndef _WX_ACTIVITYINDICATOR_H_
#define _WX_ACTIVITYINDICATOR_H_
#include "wx/defs.h"
#if wxUSE_ACTIVITYINDICATOR
#include "wx/control.h"
#define wxActivityIndicatorNameStr wxS("activityindicator")
// ----------------------------------------------------------------------------
// wxActivityIndicator: small animated indicator of some application activity.
// ----------------------------------------------------------------------------
class WXDLLIMPEXP_ADV wxActivityIndicatorBase : public wxControl
{
public:
// Start or stop the activity animation (it is stopped initially).
virtual void Start() = 0;
virtual void Stop() = 0;
// Return true if the control is currently showing activity.
virtual bool IsRunning() const = 0;
// Override some base class virtual methods.
virtual bool AcceptsFocus() const wxOVERRIDE { return false; }
virtual bool HasTransparentBackground() wxOVERRIDE { return true; }
protected:
// choose the default border for this window
virtual wxBorder GetDefaultBorder() const wxOVERRIDE { return wxBORDER_NONE; }
};
#ifndef __WXUNIVERSAL__
#if defined(__WXGTK220__)
#define wxHAS_NATIVE_ACTIVITYINDICATOR
#include "wx/gtk/activityindicator.h"
#elif defined(__WXOSX_COCOA__)
#define wxHAS_NATIVE_ACTIVITYINDICATOR
#include "wx/osx/activityindicator.h"
#endif
#endif // !__WXUNIVERSAL__
#ifndef wxHAS_NATIVE_ACTIVITYINDICATOR
#include "wx/generic/activityindicator.h"
#endif
#endif // wxUSE_ACTIVITYINDICATOR
#endif // _WX_ACTIVITYINDICATOR_H_
|
h
|
rticonnextdds-usecases
|
data/projects/rticonnextdds-usecases/VehicleTracking/ExampleCode/thirdparty/wxWidgets-3.1.2/Linux/include/wx/app.h
|
/////////////////////////////////////////////////////////////////////////////
// Name: wx/app.h
// Purpose: wxAppBase class and macros used for declaration of wxApp
// derived class in the user code
// Author: Julian Smart
// Modified by:
// Created: 01/02/97
// Copyright: (c) Julian Smart
// Licence: wxWindows licence
/////////////////////////////////////////////////////////////////////////////
#ifndef _WX_APP_H_BASE_
#define _WX_APP_H_BASE_
// ----------------------------------------------------------------------------
// headers we have to include here
// ----------------------------------------------------------------------------
#include "wx/event.h" // for the base class
#include "wx/eventfilter.h" // (and another one)
#include "wx/build.h"
#include "wx/cmdargs.h" // for wxCmdLineArgsArray used by wxApp::argv
#include "wx/init.h" // we must declare wxEntry()
#include "wx/intl.h" // for wxLayoutDirection
#include "wx/log.h" // for wxDISABLE_DEBUG_LOGGING_IN_RELEASE_BUILD()
class WXDLLIMPEXP_FWD_BASE wxAppConsole;
class WXDLLIMPEXP_FWD_BASE wxAppTraits;
class WXDLLIMPEXP_FWD_BASE wxCmdLineParser;
class WXDLLIMPEXP_FWD_BASE wxEventLoopBase;
class WXDLLIMPEXP_FWD_BASE wxMessageOutput;
#if wxUSE_GUI
struct WXDLLIMPEXP_FWD_CORE wxVideoMode;
class WXDLLIMPEXP_FWD_CORE wxWindow;
#endif
// this macro should be used in any main() or equivalent functions defined in wx
#define wxDISABLE_DEBUG_SUPPORT() \
wxDISABLE_ASSERTS_IN_RELEASE_BUILD(); \
wxDISABLE_DEBUG_LOGGING_IN_RELEASE_BUILD()
// ----------------------------------------------------------------------------
// typedefs
// ----------------------------------------------------------------------------
// the type of the function used to create a wxApp object on program start up
typedef wxAppConsole* (*wxAppInitializerFunction)();
// ----------------------------------------------------------------------------
// constants
// ----------------------------------------------------------------------------
enum
{
wxPRINT_WINDOWS = 1,
wxPRINT_POSTSCRIPT = 2
};
// ----------------------------------------------------------------------------
// global variables
// ----------------------------------------------------------------------------
// use of this list is strongly deprecated, use wxApp ScheduleForDestruction()
// and IsScheduledForDestruction() methods instead of this list directly, it
// is here for compatibility purposes only
extern WXDLLIMPEXP_DATA_BASE(wxList) wxPendingDelete;
// ----------------------------------------------------------------------------
// wxAppConsoleBase: wxApp for non-GUI applications
// ----------------------------------------------------------------------------
class WXDLLIMPEXP_BASE wxAppConsoleBase : public wxEvtHandler,
public wxEventFilter
{
public:
// ctor and dtor
wxAppConsoleBase();
virtual ~wxAppConsoleBase();
// the virtual functions which may/must be overridden in the derived class
// -----------------------------------------------------------------------
// This is the very first function called for a newly created wxApp object,
// it is used by the library to do the global initialization. If, for some
// reason, you must override it (instead of just overriding OnInit(), as
// usual, for app-specific initializations), do not forget to call the base
// class version!
virtual bool Initialize(int& argc, wxChar **argv);
// This gives wxCocoa a chance to call OnInit() with a memory pool in place
virtual bool CallOnInit() { return OnInit(); }
// Called before OnRun(), this is a good place to do initialization -- if
// anything fails, return false from here to prevent the program from
// continuing. The command line is normally parsed here, call the base
// class OnInit() to do it.
virtual bool OnInit();
// This is the replacement for the normal main(): all program work should
// be done here. When OnRun() returns, the programs starts shutting down.
virtual int OnRun();
// Called before the first events are handled, called from within MainLoop()
virtual void OnLaunched();
// This is called by wxEventLoopBase::SetActive(): you should put the code
// which needs an active event loop here.
// Note that this function is called whenever an event loop is activated;
// you may want to use wxEventLoopBase::IsMain() to perform initialization
// specific for the app's main event loop.
virtual void OnEventLoopEnter(wxEventLoopBase* WXUNUSED(loop)) {}
// This is only called if OnInit() returned true so it's a good place to do
// any cleanup matching the initializations done there.
virtual int OnExit();
// This is called by wxEventLoopBase::OnExit() for each event loop which
// is exited.
virtual void OnEventLoopExit(wxEventLoopBase* WXUNUSED(loop)) {}
// This is the very last function called on wxApp object before it is
// destroyed. If you override it (instead of overriding OnExit() as usual)
// do not forget to call the base class version!
virtual void CleanUp();
// Called when a fatal exception occurs, this function should take care not
// to do anything which might provoke a nested exception! It may be
// overridden if you wish to react somehow in non-default way (core dump
// under Unix, application crash under Windows) to fatal program errors,
// however extreme care should be taken if you don't want this function to
// crash.
virtual void OnFatalException() { }
// Called from wxExit() function, should terminate the application a.s.a.p.
virtual void Exit();
// application info: name, description, vendor
// -------------------------------------------
// NB: all these should be set by the application itself, there are no
// reasonable default except for the application name which is taken to
// be argv[0]
// set/get the application name
wxString GetAppName() const;
void SetAppName(const wxString& name) { m_appName = name; }
// set/get the application display name: the display name is the name
// shown to the user in titles, reports, etc while the app name is
// used for paths, config, and other places the user doesn't see
//
// by default the display name is the same as app name or a capitalized
// version of the program if app name was not set neither but it's
// usually better to set it explicitly to something nicer
wxString GetAppDisplayName() const;
void SetAppDisplayName(const wxString& name) { m_appDisplayName = name; }
// set/get the app class name
wxString GetClassName() const { return m_className; }
void SetClassName(const wxString& name) { m_className = name; }
// set/get the vendor name
const wxString& GetVendorName() const { return m_vendorName; }
void SetVendorName(const wxString& name) { m_vendorName = name; }
// set/get the vendor display name: the display name is shown
// in titles/reports/dialogs to the user, while the vendor name
// is used in some areas such as wxConfig, wxStandardPaths, etc
const wxString& GetVendorDisplayName() const
{
return m_vendorDisplayName.empty() ? GetVendorName()
: m_vendorDisplayName;
}
void SetVendorDisplayName(const wxString& name)
{
m_vendorDisplayName = name;
}
// cmd line parsing stuff
// ----------------------
// all of these methods may be overridden in the derived class to
// customize the command line parsing (by default only a few standard
// options are handled)
//
// you also need to call wxApp::OnInit() from YourApp::OnInit() for all
// this to work
#if wxUSE_CMDLINE_PARSER
// this one is called from OnInit() to add all supported options
// to the given parser (don't forget to call the base class version if you
// override it!)
virtual void OnInitCmdLine(wxCmdLineParser& parser);
// called after successfully parsing the command line, return true
// to continue and false to exit (don't forget to call the base class
// version if you override it!)
virtual bool OnCmdLineParsed(wxCmdLineParser& parser);
// called if "--help" option was specified, return true to continue
// and false to exit
virtual bool OnCmdLineHelp(wxCmdLineParser& parser);
// called if incorrect command line options were given, return
// false to abort and true to continue
virtual bool OnCmdLineError(wxCmdLineParser& parser);
#endif // wxUSE_CMDLINE_PARSER
// miscellaneous customization functions
// -------------------------------------
// create the app traits object to which we delegate for everything which
// either should be configurable by the user (then he can change the
// default behaviour simply by overriding CreateTraits() and returning his
// own traits object) or which is GUI/console dependent as then wxAppTraits
// allows us to abstract the differences behind the common facade
wxAppTraits *GetTraits();
// this function provides safer access to traits object than
// wxTheApp->GetTraits() during startup or termination when the global
// application object itself may be unavailable
//
// of course, it still returns NULL in this case and the caller must check
// for it
static wxAppTraits *GetTraitsIfExists();
// Return some valid traits object.
//
// This method checks if we have wxTheApp and returns its traits if it does
// exist and the traits are non-NULL, similarly to GetTraitsIfExists(), but
// falls back to wxConsoleAppTraits to ensure that it always returns
// something valid.
static wxAppTraits& GetValidTraits();
// returns the main event loop instance, i.e. the event loop which is started
// by OnRun() and which dispatches all events sent from the native toolkit
// to the application (except when new event loops are temporarily set-up).
// The returned value maybe NULL. Put initialization code which needs a
// non-NULL main event loop into OnEventLoopEnter().
wxEventLoopBase* GetMainLoop() const
{ return m_mainLoop; }
// This function sets the C locale to the default locale for the current
// environment. It is advised to call this to ensure that the underlying
// toolkit uses the locale in which the numbers and monetary amounts are
// shown in the format expected by user and so on.
//
// Notice that this does _not_ change the global C++ locale, you need to do
// it explicitly if you want.
//
// Finally, notice that while this function is virtual, it is not supposed
// to be overridden outside of the library itself.
virtual void SetCLocale();
// event processing functions
// --------------------------
// Implement the inherited wxEventFilter method but just return -1 from it
// to indicate that default processing should take place.
virtual int FilterEvent(wxEvent& event) wxOVERRIDE;
// return true if we're running event loop, i.e. if the events can
// (already) be dispatched
static bool IsMainLoopRunning();
#if wxUSE_EXCEPTIONS
// execute the functor to handle the given event
//
// this is a generalization of HandleEvent() below and the base class
// implementation of CallEventHandler() still calls HandleEvent() for
// compatibility for functors which are just wxEventFunctions (i.e. methods
// of wxEvtHandler)
virtual void CallEventHandler(wxEvtHandler *handler,
wxEventFunctor& functor,
wxEvent& event) const;
// call the specified handler on the given object with the given event
//
// this method only exists to allow catching the exceptions thrown by any
// event handler, it would lead to an extra (useless) virtual function call
// if the exceptions were not used, so it doesn't even exist in that case
virtual void HandleEvent(wxEvtHandler *handler,
wxEventFunction func,
wxEvent& event) const;
// Called when an unhandled C++ exception occurs inside OnRun(): note that
// the main event loop has already terminated by now and the program will
// exit, if you need to really handle the exceptions you need to override
// OnExceptionInMainLoop()
virtual void OnUnhandledException();
// Function called if an uncaught exception is caught inside the main
// event loop: it may return true to continue running the event loop or
// false to stop it. If this function rethrows the exception, as it does by
// default, simply because there is no general way to handle exceptions,
// StoreCurrentException() will be called to store it because in any case
// the exception can't be allowed to escape.
virtual bool OnExceptionInMainLoop();
// This function can be overridden to store the current exception, in view
// of rethrowing it later when RethrowStoredException() is called. If the
// exception was stored, return true. If the exception can't be stored,
// i.e. if this function returns false, the program will abort after
// calling OnUnhandledException().
//
// The default implementation of this function when using C++98 compiler
// just returns false, as there is no generic way to store an arbitrary
// exception in C++98 and each application must do it on its own for the
// exceptions it uses in its overridden version. When using C++11, the
// default implementation uses std::current_exception() and returns true,
// so it's normally not necessary to override this method when using C++11.
virtual bool StoreCurrentException();
// If StoreCurrentException() is overridden, this function should be
// overridden as well to rethrow the exceptions stored by it when the
// control gets back to our code, i.e. when it's safe to do it.
//
// The default version does nothing when using C++98 and uses
// std::rethrow_exception() in C++11.
virtual void RethrowStoredException();
#endif // wxUSE_EXCEPTIONS
// pending events
// --------------
// IMPORTANT: all these methods conceptually belong to wxEventLoopBase
// but for many reasons we need to allow queuing of events
// even when there's no event loop (e.g. in wxApp::OnInit);
// this feature is used e.g. to queue events on secondary threads
// or in wxPython to use wx.CallAfter before the GUI is initialized
// process all events in the m_handlersWithPendingEvents list -- it is necessary
// to call this function to process posted events. This happens during each
// event loop iteration in GUI mode but if there is no main loop, it may be
// also called directly.
virtual void ProcessPendingEvents();
// check if there are pending events on global pending event list
bool HasPendingEvents() const;
// temporary suspends processing of the pending events
void SuspendProcessingOfPendingEvents();
// resume processing of the pending events previously stopped because of a
// call to SuspendProcessingOfPendingEvents()
void ResumeProcessingOfPendingEvents();
// called by ~wxEvtHandler to (eventually) remove the handler from the list of
// the handlers with pending events
void RemovePendingEventHandler(wxEvtHandler* toRemove);
// adds an event handler to the list of the handlers with pending events
void AppendPendingEventHandler(wxEvtHandler* toAppend);
// moves the event handler from the list of the handlers with pending events
//to the list of the handlers with _delayed_ pending events
void DelayPendingEventHandler(wxEvtHandler* toDelay);
// deletes the current pending events
void DeletePendingEvents();
// delayed destruction
// -------------------
// If an object may have pending events for it, it shouldn't be deleted
// immediately as this would result in a crash when trying to handle these
// events: instead, it should be scheduled for destruction and really
// destroyed only after processing all pending events.
//
// Notice that this is only possible if we have a running event loop,
// otherwise the object is just deleted directly by ScheduleForDestruction()
// and IsScheduledForDestruction() always returns false.
// schedule the object for destruction in the near future
void ScheduleForDestruction(wxObject *object);
// return true if the object is scheduled for destruction
bool IsScheduledForDestruction(wxObject *object) const;
// wxEventLoop-related methods
// ---------------------------
// all these functions are forwarded to the corresponding methods of the
// currently active event loop -- and do nothing if there is none
virtual bool Pending();
virtual bool Dispatch();
virtual int MainLoop();
virtual void ExitMainLoop();
bool Yield(bool onlyIfNeeded = false);
virtual void WakeUpIdle();
// this method is called by the active event loop when there are no events
// to process
//
// by default it generates the idle events and if you override it in your
// derived class you should call the base class version to ensure that idle
// events are still sent out
virtual bool ProcessIdle();
// this virtual function is overridden in GUI wxApp to always return true
// as GUI applications always have an event loop -- but console ones may
// have it or not, so it simply returns true if already have an event loop
// running but false otherwise
virtual bool UsesEventLoop() const;
// debugging support
// -----------------
// this function is called when an assert failure occurs, the base class
// version does the normal processing (i.e. shows the usual assert failure
// dialog box)
//
// the arguments are the location of the failed assert (func may be empty
// if the compiler doesn't support C99 __FUNCTION__), the text of the
// assert itself and the user-specified message
virtual void OnAssertFailure(const wxChar *file,
int line,
const wxChar *func,
const wxChar *cond,
const wxChar *msg);
// old version of the function without func parameter, for compatibility
// only, override OnAssertFailure() in the new code
virtual void OnAssert(const wxChar *file,
int line,
const wxChar *cond,
const wxChar *msg);
// check that the wxBuildOptions object (constructed in the application
// itself, usually the one from wxIMPLEMENT_APP() macro) matches the build
// options of the library and abort if it doesn't
static bool CheckBuildOptions(const char *optionsSignature,
const char *componentName);
// implementation only from now on
// -------------------------------
// helpers for dynamic wxApp construction
static void SetInitializerFunction(wxAppInitializerFunction fn)
{ ms_appInitFn = fn; }
static wxAppInitializerFunction GetInitializerFunction()
{ return ms_appInitFn; }
// accessors for ms_appInstance field (external code might wish to modify
// it, this is why we provide a setter here as well, but you should really
// know what you're doing if you call it), wxTheApp is usually used instead
// of GetInstance()
static wxAppConsole *GetInstance() { return ms_appInstance; }
static void SetInstance(wxAppConsole *app) { ms_appInstance = app; }
// command line arguments (public for backwards compatibility)
int argc;
// this object is implicitly convertible to either "char**" (traditional
// type of argv parameter of main()) or to "wchar_t **" (for compatibility
// with Unicode build in previous wx versions and because the command line
// can, in pr
#if wxUSE_UNICODE
wxCmdLineArgsArray argv;
#else
char **argv;
#endif
protected:
// delete all objects in wxPendingDelete list
//
// called from ProcessPendingEvents()
void DeletePendingObjects();
// the function which creates the traits object when GetTraits() needs it
// for the first time
virtual wxAppTraits *CreateTraits();
// function used for dynamic wxApp creation
static wxAppInitializerFunction ms_appInitFn;
// the one and only global application object
static wxAppConsole *ms_appInstance;
// create main loop from AppTraits or return NULL if
// there is no main loop implementation
wxEventLoopBase *CreateMainLoop();
// application info (must be set from the user code)
wxString m_vendorName, // vendor name ("acme")
m_vendorDisplayName, // vendor display name (e.g. "ACME Inc")
m_appName, // app name ("myapp")
m_appDisplayName, // app display name ("My Application")
m_className; // class name
// the class defining the application behaviour, NULL initially and created
// by GetTraits() when first needed
wxAppTraits *m_traits;
// the main event loop of the application (may be NULL if the loop hasn't
// been started yet or has already terminated)
wxEventLoopBase *m_mainLoop;
// pending events management vars:
// the array of the handlers with pending events which needs to be processed
// inside ProcessPendingEvents()
wxEvtHandlerArray m_handlersWithPendingEvents;
// helper array used by ProcessPendingEvents() to store the event handlers
// which have pending events but of these events none can be processed right now
// (because of a call to wxEventLoop::YieldFor() which asked to selectively process
// pending events)
wxEvtHandlerArray m_handlersWithPendingDelayedEvents;
#if wxUSE_THREADS
// this critical section protects both the lists above
wxCriticalSection m_handlersWithPendingEventsLocker;
#endif
// flag modified by Suspend/ResumeProcessingOfPendingEvents()
bool m_bDoPendingEventProcessing;
friend class WXDLLIMPEXP_FWD_BASE wxEvtHandler;
// the application object is a singleton anyhow, there is no sense in
// copying it
wxDECLARE_NO_COPY_CLASS(wxAppConsoleBase);
};
#if defined(__UNIX__) && !defined(__WINDOWS__)
#include "wx/unix/app.h"
#else
// this has to be a class and not a typedef as we forward declare it
class wxAppConsole : public wxAppConsoleBase { };
#endif
// ----------------------------------------------------------------------------
// wxAppBase: the common part of wxApp implementations for all platforms
// ----------------------------------------------------------------------------
#if wxUSE_GUI
class WXDLLIMPEXP_CORE wxAppBase : public wxAppConsole
{
public:
wxAppBase();
virtual ~wxAppBase();
// the virtual functions which may/must be overridden in the derived class
// -----------------------------------------------------------------------
// very first initialization function
//
// Override: very rarely
virtual bool Initialize(int& argc, wxChar **argv) wxOVERRIDE;
// a platform-dependent version of OnInit(): the code here is likely to
// depend on the toolkit. default version does nothing.
//
// Override: rarely.
virtual bool OnInitGui();
// called to start program execution - the default version just enters
// the main GUI loop in which events are received and processed until
// the last window is not deleted (if GetExitOnFrameDelete) or
// ExitMainLoop() is called. In console mode programs, the execution
// of the program really starts here
//
// Override: rarely in GUI applications, always in console ones.
virtual int OnRun() wxOVERRIDE;
// a matching function for OnInit()
virtual int OnExit() wxOVERRIDE;
// very last clean up function
//
// Override: very rarely
virtual void CleanUp() wxOVERRIDE;
// the worker functions - usually not used directly by the user code
// -----------------------------------------------------------------
// safer alternatives to Yield(), using wxWindowDisabler
virtual bool SafeYield(wxWindow *win, bool onlyIfNeeded);
virtual bool SafeYieldFor(wxWindow *win, long eventsToProcess);
// this virtual function is called in the GUI mode when the application
// becomes idle and normally just sends wxIdleEvent to all interested
// parties
//
// it should return true if more idle events are needed, false if not
virtual bool ProcessIdle() wxOVERRIDE;
// override base class version: GUI apps always use an event loop
virtual bool UsesEventLoop() const wxOVERRIDE { return true; }
// top level window functions
// --------------------------
// return true if our app has focus
virtual bool IsActive() const { return m_isActive; }
// set the "main" top level window
void SetTopWindow(wxWindow *win) { m_topWindow = win; }
// return the "main" top level window (if it hadn't been set previously
// with SetTopWindow(), will return just some top level window and, if
// there are none, will return NULL)
virtual wxWindow *GetTopWindow() const;
// control the exit behaviour: by default, the program will exit the
// main loop (and so, usually, terminate) when the last top-level
// program window is deleted. Beware that if you disable this behaviour
// (with SetExitOnFrameDelete(false)), you'll have to call
// ExitMainLoop() explicitly from somewhere.
void SetExitOnFrameDelete(bool flag)
{ m_exitOnFrameDelete = flag ? Yes : No; }
bool GetExitOnFrameDelete() const
{ return m_exitOnFrameDelete == Yes; }
// display mode, visual, printing mode, ...
// ------------------------------------------------------------------------
// Get display mode that is used use. This is only used in framebuffer
// wxWin ports such as wxDFB.
virtual wxVideoMode GetDisplayMode() const;
// Set display mode to use. This is only used in framebuffer wxWin
// ports such as wxDFB. This method should be called from
// wxApp::OnInitGui
virtual bool SetDisplayMode(const wxVideoMode& WXUNUSED(info)) { return true; }
// set use of best visual flag (see below)
void SetUseBestVisual( bool flag, bool forceTrueColour = false )
{ m_useBestVisual = flag; m_forceTrueColour = forceTrueColour; }
bool GetUseBestVisual() const { return m_useBestVisual; }
// set/get printing mode: see wxPRINT_XXX constants.
//
// default behaviour is the normal one for Unix: always use PostScript
// printing.
virtual void SetPrintMode(int WXUNUSED(mode)) { }
int GetPrintMode() const { return wxPRINT_POSTSCRIPT; }
// Return the layout direction for the current locale or wxLayout_Default
// if it's unknown
virtual wxLayoutDirection GetLayoutDirection() const;
// Change the theme used by the application, return true on success.
virtual bool SetNativeTheme(const wxString& WXUNUSED(theme)) { return false; }
// command line parsing (GUI-specific)
// ------------------------------------------------------------------------
#if wxUSE_CMDLINE_PARSER
virtual bool OnCmdLineParsed(wxCmdLineParser& parser) wxOVERRIDE;
virtual void OnInitCmdLine(wxCmdLineParser& parser) wxOVERRIDE;
#endif
// miscellaneous other stuff
// ------------------------------------------------------------------------
// called by toolkit-specific code to set the app status: active (we have
// focus) or not and also the last window which had focus before we were
// deactivated
virtual void SetActive(bool isActive, wxWindow *lastFocus);
protected:
// override base class method to use GUI traits
virtual wxAppTraits *CreateTraits() wxOVERRIDE;
// Helper method deleting all existing top level windows: this is used
// during the application shutdown.
void DeleteAllTLWs();
// the main top level window (may be NULL)
wxWindow *m_topWindow;
// if Yes, exit the main loop when the last top level window is deleted, if
// No don't do it and if Later -- only do it once we reach our OnRun()
//
// the explanation for using this strange scheme is given in appcmn.cpp
enum
{
Later = -1,
No,
Yes
} m_exitOnFrameDelete;
// true if the app wants to use the best visual on systems where
// more than one are available (Sun, SGI, XFree86 4.0 ?)
bool m_useBestVisual;
// force TrueColour just in case "best" isn't TrueColour
bool m_forceTrueColour;
// does any of our windows have focus?
bool m_isActive;
wxDECLARE_NO_COPY_CLASS(wxAppBase);
};
// ----------------------------------------------------------------------------
// now include the declaration of the real class
// ----------------------------------------------------------------------------
#if defined(__WXMSW__)
#include "wx/msw/app.h"
#elif defined(__WXMOTIF__)
#include "wx/motif/app.h"
#elif defined(__WXDFB__)
#include "wx/dfb/app.h"
#elif defined(__WXGTK20__)
#include "wx/gtk/app.h"
#elif defined(__WXGTK__)
#include "wx/gtk1/app.h"
#elif defined(__WXX11__)
#include "wx/x11/app.h"
#elif defined(__WXMAC__)
#include "wx/osx/app.h"
#elif defined(__WXQT__)
#include "wx/qt/app.h"
#endif
#else // !GUI
// wxApp is defined in core and we cannot define another one in wxBase,
// so use the preprocessor to allow using wxApp in console programs too
#define wxApp wxAppConsole
#endif // GUI/!GUI
// ----------------------------------------------------------------------------
// the global data
// ----------------------------------------------------------------------------
// for compatibility, we define this macro to access the global application
// object of type wxApp
//
// note that instead of using of wxTheApp in application code you should
// consider using wxDECLARE_APP() after which you may call wxGetApp() which will
// return the object of the correct type (i.e. MyApp and not wxApp)
//
// the cast is safe as in GUI build we only use wxApp, not wxAppConsole, and in
// console mode it does nothing at all
#define wxTheApp static_cast<wxApp*>(wxApp::GetInstance())
// ----------------------------------------------------------------------------
// global functions
// ----------------------------------------------------------------------------
// event loop related functions only work in GUI programs
// ------------------------------------------------------
// Force an exit from main loop
WXDLLIMPEXP_BASE void wxExit();
// avoid redeclaring this function here if it had been already declared by
// wx/utils.h, this results in warnings from g++ with -Wredundant-decls
#ifndef wx_YIELD_DECLARED
#define wx_YIELD_DECLARED
// Yield to other apps/messages
WXDLLIMPEXP_CORE bool wxYield();
#endif // wx_YIELD_DECLARED
// Yield to other apps/messages
WXDLLIMPEXP_BASE void wxWakeUpIdle();
// ----------------------------------------------------------------------------
// macros for dynamic creation of the application object
// ----------------------------------------------------------------------------
// Having a global instance of this class allows wxApp to be aware of the app
// creator function. wxApp can then call this function to create a new app
// object. Convoluted, but necessary.
class WXDLLIMPEXP_BASE wxAppInitializer
{
public:
wxAppInitializer(wxAppInitializerFunction fn)
{ wxApp::SetInitializerFunction(fn); }
};
// the code below defines a wxIMPLEMENT_WXWIN_MAIN macro which you can use if
// your compiler really, really wants main() to be in your main program (e.g.
// hello.cpp). Now wxIMPLEMENT_APP should add this code if required.
// For compilers that support it, prefer to use wmain() and let the CRT parse
// the command line for us, for the others parse it ourselves under Windows to
// ensure that wxWidgets console applications accept arbitrary Unicode strings
// as command line parameters and not just those representable in the current
// locale (under Unix UTF-8, capable of representing any Unicode string, is
// almost always used and there is no way to retrieve the Unicode command line
// anyhow).
#if wxUSE_UNICODE && defined(__WINDOWS__)
#ifdef __VISUALC__
#define wxIMPLEMENT_WXWIN_MAIN_CONSOLE \
int wmain(int argc, wchar_t **argv) \
{ \
wxDISABLE_DEBUG_SUPPORT(); \
\
return wxEntry(argc, argv); \
}
#else // No wmain(), use main() but don't trust its arguments.
#define wxIMPLEMENT_WXWIN_MAIN_CONSOLE \
int main(int, char **) \
{ \
wxDISABLE_DEBUG_SUPPORT(); \
\
return wxEntry(); \
}
#endif
#else // Use standard main()
#define wxIMPLEMENT_WXWIN_MAIN_CONSOLE \
int main(int argc, char **argv) \
{ \
wxDISABLE_DEBUG_SUPPORT(); \
\
return wxEntry(argc, argv); \
}
#endif
// port-specific header could have defined it already in some special way
#ifndef wxIMPLEMENT_WXWIN_MAIN
#define wxIMPLEMENT_WXWIN_MAIN wxIMPLEMENT_WXWIN_MAIN_CONSOLE
#endif // defined(wxIMPLEMENT_WXWIN_MAIN)
#ifdef __WXUNIVERSAL__
#include "wx/univ/theme.h"
#ifdef wxUNIV_DEFAULT_THEME
#define wxIMPLEMENT_WX_THEME_SUPPORT \
WX_USE_THEME(wxUNIV_DEFAULT_THEME);
#else
#define wxIMPLEMENT_WX_THEME_SUPPORT
#endif
#else
#define wxIMPLEMENT_WX_THEME_SUPPORT
#endif
// Use this macro if you want to define your own main() or WinMain() function
// and call wxEntry() from there.
#define wxIMPLEMENT_APP_NO_MAIN(appname) \
appname& wxGetApp() { return *static_cast<appname*>(wxApp::GetInstance()); } \
wxAppConsole *wxCreateApp() \
{ \
wxAppConsole::CheckBuildOptions(WX_BUILD_OPTIONS_SIGNATURE, \
"your program"); \
return new appname; \
} \
wxAppInitializer \
wxTheAppInitializer((wxAppInitializerFunction) wxCreateApp)
// Same as wxIMPLEMENT_APP() normally but doesn't include themes support in
// wxUniversal builds
#define wxIMPLEMENT_APP_NO_THEMES(appname) \
wxIMPLEMENT_WXWIN_MAIN \
wxIMPLEMENT_APP_NO_MAIN(appname)
// Use this macro exactly once, the argument is the name of the wxApp-derived
// class which is the class of your application.
#define wxIMPLEMENT_APP(appname) \
wxIMPLEMENT_WX_THEME_SUPPORT \
wxIMPLEMENT_APP_NO_THEMES(appname)
// Same as wxIMPLEMENT_APP(), but for console applications.
#define wxIMPLEMENT_APP_CONSOLE(appname) \
wxIMPLEMENT_WXWIN_MAIN_CONSOLE \
wxIMPLEMENT_APP_NO_MAIN(appname)
// this macro can be used multiple times and just allows you to use wxGetApp()
// function
#define wxDECLARE_APP(appname) \
extern appname& wxGetApp()
// declare the stuff defined by wxIMPLEMENT_APP() macro, it's not really needed
// anywhere else but at the very least it suppresses icc warnings about
// defining extern symbols without prior declaration, and it shouldn't do any
// harm
extern wxAppConsole *wxCreateApp();
extern wxAppInitializer wxTheAppInitializer;
// ----------------------------------------------------------------------------
// Compatibility macro aliases
// ----------------------------------------------------------------------------
// deprecated variants _not_ requiring a semicolon after them
// (note that also some wx-prefixed macro do _not_ require a semicolon because
// it's not always possible to force the compiler to require it)
#define IMPLEMENT_WXWIN_MAIN_CONSOLE wxIMPLEMENT_WXWIN_MAIN_CONSOLE
#define IMPLEMENT_WXWIN_MAIN wxIMPLEMENT_WXWIN_MAIN
#define IMPLEMENT_WX_THEME_SUPPORT wxIMPLEMENT_WX_THEME_SUPPORT
#define IMPLEMENT_APP_NO_MAIN(app) wxIMPLEMENT_APP_NO_MAIN(app);
#define IMPLEMENT_APP_NO_THEMES(app) wxIMPLEMENT_APP_NO_THEMES(app);
#define IMPLEMENT_APP(app) wxIMPLEMENT_APP(app);
#define IMPLEMENT_APP_CONSOLE(app) wxIMPLEMENT_APP_CONSOLE(app);
#define DECLARE_APP(app) wxDECLARE_APP(app);
#endif // _WX_APP_H_BASE_
|
h
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.