repo_name
stringclasses 10
values | file_path
stringlengths 29
222
| content
stringlengths 24
926k
| extention
stringclasses 5
values |
---|---|---|---|
oneAPI-samples | data/projects/oneAPI-samples/Libraries/oneDPL/dynamic_selection/sepia-filter-ds/src/1_sepia_sycl.cpp | //==============================================================
// Copyright © 2019 Intel Corporation
//
// SPDX-License-Identifier: MIT
// =============================================================
#include <chrono>
#include <cmath>
#include <iostream>
#include <sycl/sycl.hpp>
// dpc_common.hpp can be found in the dev-utilities include folder.
// e.g., $ONEAPI_ROOT/dev-utilities/<version>/include/dpc_common.hpp
#include "dpc_common.hpp"
// stb/*.h files can be found in the dev-utilities include folder.
// e.g., $ONEAPI_ROOT/dev-utilities/<version>/include/stb/*.h
#define STB_IMAGE_IMPLEMENTATION
#include "stb/stb_image.h"
#define STB_IMAGE_WRITE_IMPLEMENTATION
#include "stb/stb_image_write.h"
using namespace std;
using namespace sycl;
// Few useful acronyms.
constexpr auto sycl_read = access::mode::read;
constexpr auto sycl_write = access::mode::write;
constexpr auto sycl_device = access::target::device;
int g_num_images = 4;
#if !WINDOWS
const char* g_fnames[3] = { "../input/silver512.png", "../input/nahelam512.bmp", "../input/silverfalls1.png" };
#else
const char* g_fnames[3] = { "../../input/silver512.png", "../../input/nahelam512.bmp", "../../input/silverfalls1.png" };
#endif
int g_width[4] = {0, 0, 0, 0};
int g_height[4] = {0, 0, 0, 0};
int g_channels[4] = {0, 0, 0, 0};
void fillVectors(int mix,
std::vector<size_t>& num_pixels,
std::vector<sycl::buffer<uint8_t>>& input_buffers,
std::vector<sycl::buffer<uint8_t>>& output_buffers) {
if (mix > 3)
g_num_images = 3;
else
g_num_images = 4;
for (int i = 0; i < g_num_images; ++i) {
int img_width, img_height, channels;
int index = 0;
switch (mix) {
case 1:
// 1 - Small images only
index = i%2;
break;
case 2:
// 2 - Large images only
index = 2;
break;
case 3:
// 3 - 2 small : 2 large
index = std::min(i%4, 2);
break;
case 4:
// 4 - 2 small : 1 large
index = i%3;
break;
case 5:
// 5 - 1 small : 2 large
index = std::min(i%3+1, 2);
break;
}
uint8_t *image = stbi_load(g_fnames[index], &img_width, &img_height, &channels, 0);
if (image == NULL) {
cout << "Error in loading the image " << g_fnames[index] << "\n";
exit(1);
}
g_width[i] = img_width;
g_height[i] = img_height;
g_channels[i] = channels;
size_t npixels = img_width * img_height;
size_t img_size = img_width * img_height * channels;
input_buffers.push_back(sycl::buffer{image, sycl::range(img_size)});
num_pixels.push_back(npixels);
uint8_t *out_data = new uint8_t[img_size];
memset(out_data, 0, img_size * sizeof(uint8_t));
output_buffers.push_back(sycl::buffer{out_data, sycl::range(img_size)});
}
}
void writeImages(std::vector<sycl::buffer<uint8_t>>& output_buffers) {
const char *out_names[4] = { "out0.png", "out1.png", "out2.png", "out3.png" };
for (int i = 0; i < g_num_images; ++i) {
stbi_write_png(out_names[i], g_width[i], g_height[i], g_channels[i],
reinterpret_cast<uint8_t*>(output_buffers[i].get_host_access().get_pointer()), g_width[i] * g_channels[i]);
}
}
// SYCL does not need any special mark-up for functions which are called from
// SYCL kernel and defined in the same compilation unit. SYCL compiler must be
// able to find the full call graph automatically.
// always_inline as calls are expensive on Gen GPU.
// Notes:
// - coeffs can be declared outside of the function, but still must be constant
// - SYCL compiler will automatically deduce the address space for the two
// pointers; sycl::multi_ptr specialization for particular address space
// can used for more control
__attribute__((always_inline)) static void ApplyFilter(uint8_t *src_image,
uint8_t *dst_image,
int i) {
i *= 3;
float temp;
temp = (0.393f * src_image[i]) + (0.769f * src_image[i + 1]) +
(0.189f * src_image[i + 2]);
dst_image[i] = temp > 255 ? 255 : temp;
temp = (0.349f * src_image[i]) + (0.686f * src_image[i + 1]) +
(0.168f * src_image[i + 2]);
dst_image[i + 1] = temp > 255 ? 255 : temp;
temp = (0.272f * src_image[i]) + (0.534f * src_image[i + 1]) +
(0.131f * src_image[i + 2]);
dst_image[i + 2] = temp > 255 ? 255 : temp;
}
void printUsage(char *exe_name)
{
std::cout << "Application requires arguments. Usage: " << exe_name << " <num_images> <mix>" << std::endl
<< "Mix:" << std::endl
<< "1 - Small images only" << std::endl
<< "2 - Large images only" << std::endl
<< "3 - 2 small : 2 large" << std::endl
<< "4 - 2 small : 1 large" << std::endl
<< "5 - 1 small : 2 large" << std::endl;
}
void displayConfig(int mix, sycl::queue q, int num_offloads) {
std::cout << "Processing " << num_offloads << " images\n";
switch (mix) {
case 1:
// 1 - Small images only
std::cout << "Only small images\n";
break;
case 2:
// 2 - Large images only
std::cout << "Only large images\n";
break;
case 3:
// 3 - 2 small : 2 large
std::cout << "50/50 small images and large images\n";
break;
case 4:
// 4 - 2 small : 1 large
std::cout << "2 small images for each large image\n";
break;
case 5:
// 5 - 1 small : 2 large
std::cout << "2 large images for each small image\n";
break;
}
cout << "Will submit all offloads to default device: " << q.get_device().get_info<info::device::name>() << "\n";
std::cout << "\n";
}
int main(int argc, char **argv) {
int num_offloads{100}, mix{2};
std::vector<sycl::buffer<uint8_t>> input_buffers;
std::vector<size_t> npixels;
std::vector<sycl::buffer<uint8_t>> output_buffers;
auto prop_list = property_list{property::queue::enable_profiling()};
queue q(default_selector_v, dpc_common::exception_handler, prop_list);
if (argc < 3) {
printUsage(argv[0]);
return -1;
} else {
int n = std::atoi(argv[1]);
if (n <= 0) {
std::cout << "num offloads must be a positive integer." << std::endl;
return -1;
} else {
num_offloads = n;
}
int m = std::atoi(argv[2]);
if (m <= 0 || m > 5) {
std::cout << "Improper mix choice.\n";
printUsage(argv[0]);
return -1;
} else {
mix = m;
}
}
displayConfig(mix, q, num_offloads);
fillVectors(mix, npixels, input_buffers, output_buffers);
auto t_begin = std::chrono::high_resolution_clock::now();
for (int i = 0; i < num_offloads; ++i) {
try {
sycl::buffer<uint8_t>& in = input_buffers[i%g_num_images];
sycl::buffer<uint8_t>& out = output_buffers[i%g_num_images];
size_t num_pixels = npixels[i%g_num_images];
q.submit([&](auto &h) {
// This lambda defines a "command group" - a set of commands for the
// device sharing some state and executed in-order - i.e. creation of
// accessors may lead to on-device memory allocation, only after that
// the kernel will be enqueued.
// A command group can contain at most one parallel_for, single_task or
// parallel_for_workgroup construct.
accessor image_acc(in, h, read_only);
accessor image_exp_acc(out, h, write_only);
// This is the simplest form sycl::handler::parallel_for -
// - it specifies "flat" 1D ND range(num_pixels), runtime will select
// local size
// - kernel lambda accepts single sycl::id argument, which has very
// limited API; see the spec for more complex forms
// the lambda parameter of the parallel_for is the kernel, which
// actually executes on device
h.parallel_for(range<1>(num_pixels), [=](auto i) {
ApplyFilter(image_acc.get_pointer(), image_exp_acc.get_pointer(), i);
});
}).wait();
} catch (sycl::exception e) {
// This catches only synchronous exceptions that happened in current thread
// during execution. The asynchronous exceptions caused by execution of the
// command group are caught by the asynchronous exception handler
// registered. Synchronous exceptions are usually those which are thrown
// from the SYCL runtime code, such as on invalid constructor arguments. An
// example of asynchronous exceptions is error occurred during execution of
// a kernel. Make sure sycl::exception is caught, not std::exception.
cout << "SYCL exception caught: " << e.what() << "\n";
return 1;
}
}
auto t_end = std::chrono::high_resolution_clock::now();
auto total_time = std::chrono::duration_cast<std::chrono::microseconds>(t_end-t_begin).count();
cout << "Total time == " << total_time << " us\n";
writeImages(output_buffers);
return 0;
}
| cpp |
oneAPI-samples | data/projects/oneAPI-samples/Libraries/oneDPL/stable_sort_by_key/src/main.cpp | //==============================================================
// Copyright © 2020 Intel Corporation
//
// SPDX-License-Identifier: MIT
// =============================================================
// oneDPL headers should be included before standard headers
#include <oneapi/dpl/algorithm>
#include <oneapi/dpl/execution>
#include <oneapi/dpl/iterator>
#include <sycl/sycl.hpp>
#include <iostream>
using namespace sycl;
using namespace std;
int main() {
const int n = 1000000;
buffer<int> keys_buf{n}; // buffer with keys
buffer<int> vals_buf{n}; // buffer with values
// create objects to iterate over buffers
auto keys_begin = oneapi::dpl::begin(keys_buf);
auto vals_begin = oneapi::dpl::begin(vals_buf);
auto counting_begin = oneapi::dpl::counting_iterator<int>{0};
// use default policy for algorithms execution
auto policy = oneapi::dpl::execution::dpcpp_default;
// 1. Initialization of buffers
// let keys_buf contain {n, n, n-2, n-2, ..., 4, 4, 2, 2}
transform(policy, counting_begin, counting_begin + n, keys_begin,
[n](int i) { return n - (i / 2) * 2; });
// fill vals_buf with the analogue of std::iota using counting_iterator
copy(policy, counting_begin, counting_begin + n, vals_begin);
// 2. Sorting
auto zipped_begin = oneapi::dpl::make_zip_iterator(keys_begin, vals_begin);
// stable sort by keys
stable_sort(
policy, zipped_begin, zipped_begin + n,
// Generic lambda is needed because type of lhs and rhs is unspecified.
[](auto lhs, auto rhs) { return get<0>(lhs) < get<0>(rhs); });
// 3.Checking results
auto host_keys = keys_buf.get_access<access::mode::read>();
auto host_vals = vals_buf.get_access<access::mode::read>();
// expected output:
// keys: {2, 2, 4, 4, ..., n - 2, n - 2, n, n}
// vals: {n - 2, n - 1, n - 4, n - 3, ..., 2, 3, 0, 1}
for (int i = 0; i < n; ++i) {
if (host_keys[i] != (i / 2) * 2 &&
host_vals[i] != n - (i / 2) * 2 - (i % 2 == 0 ? 2 : 1)) {
cout << "fail: i = " << i << ", host_keys[i] = " << host_keys[i]
<< ", host_vals[i] = " << host_vals[i] << "\n";
return 1;
}
}
cout << "success\nRun on "
<< policy.queue().get_device().template get_info<info::device::name>()
<< "\n";
return 0;
}
| cpp |
oneAPI-samples | data/projects/oneAPI-samples/Libraries/oneDPL/gamma-correction/src/main.cpp | //==============================================================
// Copyright © 2019 Intel Corporation
//
// SPDX-License-Identifier: MIT
// =============================================================
// oneDPL headers should be included before standard headers
#include <oneapi/dpl/algorithm>
#include <oneapi/dpl/execution>
#include <oneapi/dpl/iterator>
#include <iomanip>
#include <iostream>
#include <sycl/sycl.hpp>
#include "utils.hpp"
using namespace sycl;
using namespace std;
int main() {
// Image size is width x height
int width = 2560;
int height = 1600;
Img<ImgFormat::BMP> image{width, height};
ImgFractal fractal{width, height};
// Lambda to process image with gamma = 2
auto gamma_f = [](ImgPixel &pixel) {
auto v = (0.3f * pixel.r + 0.59f * pixel.g + 0.11f * pixel.b) / 255.0f;
auto gamma_pixel = static_cast<uint8_t>(255 * v * v);
if (gamma_pixel > 255) gamma_pixel = 255;
pixel.set(gamma_pixel, gamma_pixel, gamma_pixel, gamma_pixel);
};
// fill image with created fractal
int index = 0;
image.fill([&index, width, &fractal](ImgPixel &pixel) {
int x = index % width;
int y = index / width;
auto fractal_pixel = fractal(x, y);
if (fractal_pixel < 0) fractal_pixel = 0;
if (fractal_pixel > 255) fractal_pixel = 255;
pixel.set(fractal_pixel, fractal_pixel, fractal_pixel, fractal_pixel);
++index;
});
string original_image = "fractal_original.bmp";
string processed_image = "fractal_gamma.bmp";
Img<ImgFormat::BMP> image2 = image;
image.write(original_image);
// call standard serial function for correctness check
image.fill(gamma_f);
// use default policy for algorithms execution
auto policy = oneapi::dpl::execution::dpcpp_default;
// We need to have the scope to have data in image2 after buffer's destruction
{
// create a buffer, being responsible for moving data around and counting
// dependencies
buffer<ImgPixel> b(image2.data(), image2.width() * image2.height());
// create iterator to pass buffer to the algorithm
auto b_begin = oneapi::dpl::begin(b);
auto b_end = oneapi::dpl::end(b);
// call std::for_each with DPC++ support
std::for_each(policy, b_begin, b_end, gamma_f);
}
image2.write(processed_image);
// check correctness
if (check(image.begin(), image.end(), image2.begin())) {
cout << "success\n";
} else {
cout << "fail\n";
return 1;
}
cout << "Run on "
<< policy.queue().get_device().template get_info<info::device::name>()
<< "\n";
cout << "Original image is in " << original_image << "\n";
cout << "Image after applying gamma correction on the device is in "
<< processed_image << "\n";
return 0;
}
| cpp |
oneAPI-samples | data/projects/oneAPI-samples/Libraries/oneDPL/gamma-correction/src/utils.hpp | //==============================================================
// Copyright © 2019 Intel Corporation
//
// SPDX-License-Identifier: MIT
// =============================================================
#ifndef _GAMMA_UTILS_HPP
#define _GAMMA_UTILS_HPP
#include "utils/Img.hpp"
#include "utils/ImgAlgorithm.hpp"
#include "utils/ImgFormat.hpp"
#include "utils/ImgPixel.hpp"
#include "utils/Other.hpp"
#endif // _GAMMA_UTILS_HPP
| hpp |
oneAPI-samples | data/projects/oneAPI-samples/Libraries/oneDPL/gamma-correction/src/utils/ImgFormat.hpp | //==============================================================
// Copyright © 2019 Intel Corporation
//
// SPDX-License-Identifier: MIT
// =============================================================
#ifndef _GAMMA_UTILS_IMGFORMAT_HPP
#define _GAMMA_UTILS_IMGFORMAT_HPP
#include "ImgPixel.hpp"
#include <fstream>
using namespace std;
namespace ImgFormat {
// struct to store an image in BMP format
struct BMP {
private:
using FileHeader = struct {
// not from specification
// was added for alignemt
// store size of rest of the fields
uint16_t sizeRest; // file header size in bytes
uint16_t type;
uint32_t size; // file size in bytes
uint32_t reserved;
uint32_t offBits; // cumulative header size in bytes
};
using InfoHeader = struct {
// from specification
// store size of rest of the fields
uint32_t size; // info header size in bytes
int32_t width; // image width in pixels
int32_t height; // image height in pixels
uint16_t planes;
uint16_t bitCount; // color depth
uint32_t compression; // compression
uint32_t sizeImage; // image map size in bytes
int32_t xPelsPerMeter; // pixel per metre (y axis)
int32_t yPelsPerMeter; // pixel per metre (y axis)
uint32_t clrUsed; // color pallete (0 is default)
uint32_t clrImportant;
};
FileHeader _fileHeader;
InfoHeader _infoHeader;
public:
BMP(int32_t width, int32_t height) noexcept { reset(width, height); }
void reset(int32_t width, int32_t height) noexcept {
uint32_t padSize = (4 - (width * sizeof(ImgPixel)) % 4) % 4;
uint32_t mapSize = width * height * sizeof(ImgPixel) + height * padSize;
uint32_t allSize = mapSize + _fileHeader.sizeRest + _infoHeader.size;
_fileHeader.sizeRest = 14; // file header size in bytes
_fileHeader.type = 0x4d42;
_fileHeader.size = allSize; // file size in bytes
_fileHeader.reserved = 0;
_fileHeader.offBits = 54; // sizeRest + size -> 14 + 40 -> 54
_infoHeader.size = 40; // info header size in bytes
_infoHeader.width = width; // image width in pixels
_infoHeader.height = height; // image height in pixels
_infoHeader.planes = 1;
_infoHeader.bitCount = 32; // color depth
_infoHeader.compression = 0; // compression
_infoHeader.sizeImage = mapSize; // image map size in bytes
_infoHeader.xPelsPerMeter = 0; // pixel per metre (x axis)
_infoHeader.yPelsPerMeter = 0; // pixel per metre (y axis)
_infoHeader.clrUsed = 0; // color pallete (0 is default)
_infoHeader.clrImportant = 0;
}
template <template <class> class Image, typename Format>
void write(ofstream& ostream, Image<Format> const& image) const {
ostream.write(reinterpret_cast<char const*>(&_fileHeader.type),
_fileHeader.sizeRest);
ostream.write(reinterpret_cast<char const*>(&_infoHeader),
_infoHeader.size);
ostream.write(reinterpret_cast<char const*>(image.data()),
image.width() * image.height() * sizeof(image.data()[0]));
}
FileHeader const& fileHeader() const noexcept { return _fileHeader; }
InfoHeader const& infoHeader() const noexcept { return _infoHeader; }
};
} // namespace ImgFormat
#endif // _GAMMA_UTILS_IMGFORMAT_HPP
| hpp |
oneAPI-samples | data/projects/oneAPI-samples/Libraries/oneDPL/gamma-correction/src/utils/ImgPixel.hpp | //==============================================================
// Copyright © 2019 Intel Corporation
//
// SPDX-License-Identifier: MIT
// =============================================================
#ifndef _GAMMA_UTILS_IMGPIXEL_HPP
#define _GAMMA_UTILS_IMGPIXEL_HPP
#include <cstdint>
#include <ostream>
using namespace std;
// struct to store a pixel of image
struct ImgPixel {
uint8_t b;
uint8_t g;
uint8_t r;
uint8_t a;
bool operator==(ImgPixel const& other) const {
return (b == other.b) && (g == other.g) && (r == other.r) && (a == other.a);
}
bool operator!=(ImgPixel const& other) const { return !(*this == other); }
void set(uint8_t blue, uint8_t green, uint8_t red, uint8_t alpha) {
b = blue;
g = green;
r = red;
a = alpha;
}
};
ostream& operator<<(ostream& output, ImgPixel const& pixel) {
return output << "(" << unsigned(pixel.r) << ", " << unsigned(pixel.g) << ", "
<< unsigned(pixel.b) << ", " << unsigned(pixel.a) << ")";
}
#endif // _GAMMA_UTILS_IMGPIXEL_HPP
| hpp |
oneAPI-samples | data/projects/oneAPI-samples/Libraries/oneDPL/gamma-correction/src/utils/Img.hpp | //==============================================================
// Copyright © 2019 Intel Corporation
//
// SPDX-License-Identifier: MIT
// =============================================================
#ifndef _GAMMA_UTILS_IMG_HPP
#define _GAMMA_UTILS_IMG_HPP
#include "ImgPixel.hpp"
#include <algorithm>
#include <fstream>
#include <iostream>
#include <vector>
using namespace std;
// Image class definition
template <typename Format>
class Img {
private:
Format _format;
int32_t _width;
int32_t _height;
vector<ImgPixel> _pixels;
using Iterator = vector<ImgPixel>::iterator;
using ConstIterator = vector<ImgPixel>::const_iterator;
public:
/////////////////////
// SPECIAL METHODS //
/////////////////////
Img(int32_t width, int32_t height);
void reset(int32_t width, int32_t height);
///////////////
// ITERATORS //
///////////////
Iterator begin() noexcept;
Iterator end() noexcept;
ConstIterator begin() const noexcept;
ConstIterator end() const noexcept;
ConstIterator cbegin() const noexcept;
ConstIterator cend() const noexcept;
/////////////
// GETTERS //
/////////////
int32_t width() const noexcept;
int32_t height() const noexcept;
ImgPixel const* data() const noexcept;
ImgPixel* data() noexcept;
///////////////////
// FUNCTIONALITY //
///////////////////
void write(string const& filename) const;
template <typename Functor>
void fill(Functor f);
void fill(ImgPixel pixel);
void fill(ImgPixel pixel, int32_t row, int32_t col);
};
///////////////////////////////////////////////
// IMG CLASS IMPLEMENTATION: SPECIAL METHODS //
///////////////////////////////////////////////
template <typename Format>
Img<Format>::Img(int32_t width, int32_t height) : _format(width, height) {
_pixels.resize(width * height);
_width = width;
_height = height;
}
template <typename Format>
void Img<Format>::reset(int32_t width, int32_t height) {
_pixels.resize(width * height);
_width = width;
_height = height;
_format.reset(width, height);
}
/////////////////////////////////////////
// IMG CLASS IMPLEMENTATION: ITERATORS //
/////////////////////////////////////////
template <typename Format>
typename Img<Format>::Iterator Img<Format>::begin() noexcept {
return _pixels.begin();
}
template <typename Format>
typename Img<Format>::Iterator Img<Format>::end() noexcept {
return _pixels.end();
}
template <typename Format>
typename Img<Format>::ConstIterator Img<Format>::begin() const noexcept {
return _pixels.begin();
}
template <typename Format>
typename Img<Format>::ConstIterator Img<Format>::end() const noexcept {
return _pixels.end();
}
template <typename Format>
typename Img<Format>::ConstIterator Img<Format>::cbegin() const noexcept {
return _pixels.begin();
}
template <typename Format>
typename Img<Format>::ConstIterator Img<Format>::cend() const noexcept {
return _pixels.end();
}
///////////////////////////////////////
// IMG CLASS IMPLEMENTATION: GETTERS //
///////////////////////////////////////
template <typename Format>
int32_t Img<Format>::width() const noexcept {
return _width;
}
template <typename Format>
int32_t Img<Format>::height() const noexcept {
return _height;
}
template <typename Format>
ImgPixel const* Img<Format>::data() const noexcept {
return _pixels.data();
}
template <typename Format>
ImgPixel* Img<Format>::data() noexcept {
return _pixels.data();
}
/////////////////////////////////////////////
// IMG CLASS IMPLEMENTATION: FUNCTIONALITY //
/////////////////////////////////////////////
template <typename Format>
void Img<Format>::write(string const& filename) const {
if (_pixels.empty()) {
cerr << "Img::write:: image is empty\n";
return;
}
ofstream filestream(filename, ios::binary);
_format.write(filestream, *this);
}
template <typename Format>
template <typename Functor>
void Img<Format>::fill(Functor f) {
if (_pixels.empty()) {
cerr << "Img::fill(Functor): image is empty\n";
return;
}
for (auto& pixel : _pixels) f(pixel);
}
template <typename Format>
void Img<Format>::fill(ImgPixel pixel) {
if (_pixels.empty()) {
cerr << "Img::fill(ImgPixel): image is empty\n";
return;
}
fill(_pixels.begin(), _pixels.end(), pixel);
}
template <typename Format>
void Img<Format>::fill(ImgPixel pixel, int row, int col) {
if (_pixels.empty()) {
cerr << "Img::fill(ImgPixel): image is empty\n";
return;
}
if (row >= _height || row < 0 || col >= _width || col < 0) {
cerr << "Img::fill(ImgPixel, int, int): out of range\n";
return;
}
_pixels.at(row * _width + col) = pixel;
}
#endif // _GAMMA_UTILS_IMG_HPP
| hpp |
oneAPI-samples | data/projects/oneAPI-samples/Libraries/oneDPL/gamma-correction/src/utils/ImgAlgorithm.hpp | //==============================================================
// Copyright © 2019 Intel Corporation
//
// SPDX-License-Identifier: MIT
// =============================================================
#ifndef _GAMMA_UTILS_IMGALGORITHM_HPP
#define _GAMMA_UTILS_IMGALGORITHM_HPP
#include <cmath>
#include <cstdint>
using namespace std;
// struct to store fractal that image will fill from
class ImgFractal {
private:
const int32_t _width;
const int32_t _height;
double _cx = -0.7436;
double _cy = 0.1319;
double _magn = 2000000.0;
int _maxIterations = 1000;
public:
ImgFractal(int32_t width, int32_t height) : _width(width), _height(height) {}
double operator()(int32_t x, int32_t y) const {
double fx = (double(x) - double(_width) / 2) * (1 / _magn) + _cx;
double fy = (double(y) - double(_height) / 2) * (1 / _magn) + _cy;
double res = 0;
double nx = 0;
double ny = 0;
double val = 0;
for (int i = 0; nx * nx + ny * ny <= 4 && i < _maxIterations; ++i) {
val = nx * nx - ny * ny + fx;
ny = 2 * nx * ny + fy;
nx = val;
res += exp(-sqrt(nx * nx + ny * ny));
}
return res;
}
};
#endif // _GAMMA_UTILS_IMGALGORITHM_HPP
| hpp |
oneAPI-samples | data/projects/oneAPI-samples/Libraries/oneDPL/gamma-correction/src/utils/Other.hpp | //==============================================================
// Copyright © 2019 Intel Corporation
//
// SPDX-License-Identifier: MIT
// =============================================================
#ifndef _GAMMA_UTILS_OTHER_HPP
#define _GAMMA_UTILS_OTHER_HPP
#include <chrono>
// function for time measuring
inline double get_time_in_sec() {
namespace ch = std::chrono;
return ch::time_point_cast<ch::milliseconds>(ch::steady_clock::now())
.time_since_epoch()
.count() *
1.e-3;
}
// function to check correctness
template <typename It>
bool check(It begin1, It end1, It begin2) {
for (; begin1 != end1; ++begin1, ++begin2) {
if (*begin1 != *begin2) return false;
}
return true;
}
#endif // _GAMMA_UTILS_OTHER_HPP
| hpp |
rticonnextdds-examples | data/projects/rticonnextdds-examples/routing_service_shapes_processor/cpp/ShapesProcessor.cxx | /*
* (c) 2018 Copyright, Real-Time Innovations, Inc. All rights reserved.
*
* RTI grants Licensee a license to use, modify, compile, and create derivative
* works of the Software. Licensee has the right to distribute object form
* only for use with RTI products. The Software is provided "as is", with no
* warranty of any type, including any warranty for fitness for any purpose.
* RTI is under no obligation to maintain or support the Software. RTI shall
* not be liable for any incidental or consequential damages arising out of the
* use or inability to use the software.
*/
#include <stdio.h>
#include <stdlib.h>
#include <iterator>
#include <dds/core/corefwd.hpp>
#include <rti/routing/processor/ProcessorPlugin.hpp>
#include <rti/routing/processor/Processor.hpp>
#include <dds/core/xtypes/DynamicData.hpp>
#include <dds/core/xtypes/StructType.hpp>
#include "ShapesProcessor.hpp"
using namespace rti::routing;
using namespace rti::routing::processor;
using namespace rti::routing::adapter;
using namespace dds::core::xtypes;
using namespace dds::sub::status;
/*
* --- ShapesAggregatorSimple -------------------------------------------------
*/
ShapesAggregatorSimple::ShapesAggregatorSimple()
{
}
ShapesAggregatorSimple::~ShapesAggregatorSimple()
{
}
void ShapesAggregatorSimple::on_output_enabled(
rti::routing::processor::Route& route,
rti::routing::processor::Output& output)
{
// initialize the output_data buffer using the type from the output
output_data_ = output.get<DynamicData>().create_data();
}
void ShapesAggregatorSimple::on_data_available(
rti::routing::processor::Route& route)
{
// Use squares as 'leading' input. For each Square instance, get the
// equivalent instance from the Circle topic
auto squares = route.input<DynamicData>("Square").read();
for (auto square_sample : squares) {
if (square_sample.info().valid()) {
output_data_ = square_sample.data();
// read equivalent existing instance in the Circles stream
auto circles = route.input<DynamicData>("Circle").select()
.instance(square_sample.info().instance_handle()).read();
if (circles.length() != 0
&& circles[0].info().valid()) {
output_data_.get().value<int32_t>(
"shapesize",
circles[0].data().value<int32_t>("y"));
}
// Write aggregated sample intro Triangles
route.output<DynamicData>("Triangle").write(output_data_.get());
} else {
// propagate the dispose
route.output<DynamicData>("Triangle").write(
output_data_.get(),
square_sample.info());
//clear instance instance
route.input<DynamicData>("Square").select()
.instance(square_sample.info().instance_handle()).take();
}
}
}
/*
* --- ShapesAggregatorAdv -------------------------------------------------------
*/
ShapesAggregatorAdv::ShapesAggregatorAdv(int32_t leading_input_index)
: leading_input_index_(leading_input_index)
{
}
ShapesAggregatorAdv::~ShapesAggregatorAdv()
{
}
void ShapesAggregatorAdv::on_output_enabled(
rti::routing::processor::Route& route,
rti::routing::processor::Output& output)
{
// initialize the output_data buffer using the type from the output
output_data_ = output.get<DynamicData>().create_data();
}
void ShapesAggregatorAdv::on_data_available(
rti::routing::processor::Route& route)
{
// Read all data from leading input, then select equivalent instance from
// other inputs
DataState new_data = DataState(
SampleState::not_read(),
ViewState::any(),
InstanceState::any());
auto leading_samples = route.input<DynamicData>(leading_input_index_)
.select().state(new_data).read();
for (auto leading : leading_samples) {
std::pair<int, int> output_xy(0, 0);
if (leading.info().valid()) {
output_data_ = leading.data();
output_xy.first += leading.data().value<int32_t>("x");
output_xy.second += leading.data().value<int32_t>("y");
for (int32_t i = 0; i < route.input_count(); i++) {
if (i == leading_input_index_) {
continue;
}
auto aggregated_samples = route.input<DynamicData>(i).select()
.instance(leading.info().instance_handle()).read();
if (aggregated_samples.length() != 0) {
//use last value cached
output_xy.first += aggregated_samples[0].data().value<int32_t>("x");
output_xy.second += aggregated_samples[0].data().value<int32_t>("y");
}
}
output_xy.first /= route.input_count();
output_xy.second /= route.input_count();
output_data_.get().value<int32_t>(
"x",
output_xy.first);
output_data_.get().value<int32_t>(
"y",
output_xy.second);
// Write aggregated sample into single output
route.output<DynamicData>(0).write(output_data_.get());
} else {
// propagate the dispose
route.output<DynamicData>(0).write(
output_data_.get(),
leading.info());
}
}
}
/*
* --- ShapesSplitter ---------------------------------------------------------
*/
ShapesSplitter::ShapesSplitter()
{
}
ShapesSplitter::~ShapesSplitter()
{
}
void ShapesSplitter::on_input_enabled(
rti::routing::processor::Route& route,
rti::routing::processor::Input& input)
{
// The type this processor works with is the ShapeType, which shall
// be the type the input as well as the two outputs. Hence we can use
// the input type to initialize the output data buffer
output_data_ = input.get<DynamicData>().create_data();
}
void ShapesSplitter::on_data_available(
rti::routing::processor::Route& route)
{
// Split input shapes into mono-dimensional output shapes
auto input_samples = route.input<DynamicData>(0).take();
for (auto sample : input_samples) {
if (sample.info().valid()) {
// split into first output
output_data_ = sample.data();
output_data_.get().value<int32_t>("y", 0);
route.output<DynamicData>(0).write(
output_data_.get(),
sample.info());
// split into second output
output_data_ = sample.data();
output_data_.get().value<int32_t>("x", 0);
route.output<DynamicData>(1).write(
output_data_.get(),
sample.info());
} else {
// propagate dispose
route.output<DynamicData>(0).write(
output_data_.get(),
sample.info());
route.output<DynamicData>(1).write(
output_data_.get(),
sample.info());
}
}
}
/*
* --- ShapesProcessorPlugin --------------------------------------------------
*/
const std::string ShapesProcessorPlugin::PROCESSOR_KIND_PROPERTY_NAME =
"shapes_processor.kind";
const std::string ShapesProcessorPlugin::PROCESSOR_LEADING_INPUT_PROPERTY_NAME =
"shapes_processor.leading_input_index";
const std::string ShapesProcessorPlugin::PROCESSOR_AGGREGATOR_SIMPLE_NAME =
"aggregator_simple";
const std::string ShapesProcessorPlugin::PROCESSOR_AGGREGATOR_ADV_NAME =
"aggregator_adv";
const std::string ShapesProcessorPlugin::PROCESSOR_SPLITTER_NAME =
"splitter";
ShapesProcessorPlugin::ShapesProcessorPlugin(
const rti::routing::PropertySet&)
{
}
rti::routing::processor::Processor* ShapesProcessorPlugin::create_processor(
rti::routing::processor::Route&,
const rti::routing::PropertySet& properties)
{
PropertySet::const_iterator it = properties.find(PROCESSOR_KIND_PROPERTY_NAME);
if (it != properties.end()) {
if (it->second == PROCESSOR_AGGREGATOR_ADV_NAME) {
int32_t leading_input_index = 0;
it = properties.find(PROCESSOR_LEADING_INPUT_PROPERTY_NAME);
if (it != properties.end()) {
std::stringstream stream;
stream << it->second;
stream >> leading_input_index;
}
return new ShapesAggregatorAdv(leading_input_index);
} else if (it->second == PROCESSOR_AGGREGATOR_SIMPLE_NAME) {
return new ShapesAggregatorSimple();
} else if (it->second != PROCESSOR_SPLITTER_NAME) {
throw dds::core::InvalidArgumentError(
"unknown processor kind with name=" + it->second);
}
}
return new ShapesSplitter();
}
void ShapesProcessorPlugin::delete_processor(
rti::routing::processor::Route&,
rti::routing::processor::Processor *processor)
{
delete processor;
}
RTI_PROCESSOR_PLUGIN_CREATE_FUNCTION_DEF(ShapesProcessorPlugin); | cxx |
rticonnextdds-examples | data/projects/rticonnextdds-examples/routing_service_shapes_processor/cpp/ShapesProcessor.hpp | /*
* (c) 2018 Copyright, Real-Time Innovations, Inc. All rights reserved.
*
* RTI grants Licensee a license to use, modify, compile, and create derivative
* works of the Software. Licensee has the right to distribute object form
* only for use with RTI products. The Software is provided "as is", with no
* warranty of any type, including any warranty for fitness for any purpose.
* RTI is under no obligation to maintain or support 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 SHAPES_PROCESSOR_HPP_
#define SHAPES_PROCESSOR_HPP_
#include <stdio.h>
#include <stdlib.h>
#include <iterator>
#include <dds/core/corefwd.hpp>
#include <rti/routing/processor/ProcessorPlugin.hpp>
#include <rti/routing/processor/Processor.hpp>
#include <dds/core/xtypes/DynamicData.hpp>
#include <dds/core/xtypes/StructType.hpp>
#include <dds/core/Optional.hpp>
class ShapesAggregatorSimple :
public rti::routing::processor::NoOpProcessor {
public:
void on_data_available(rti::routing::processor::Route&);
void on_output_enabled(
rti::routing::processor::Route& route,
rti::routing::processor::Output& output);
ShapesAggregatorSimple();
~ShapesAggregatorSimple();
private:
// Optional member for deferred initialization: this object can be created
// only when the output is enabled.
// You can use std::optional if supported in your platform
dds::core::optional<dds::core::xtypes::DynamicData> output_data_;
};
class ShapesAggregatorAdv :
public rti::routing::processor::NoOpProcessor {
public:
void on_data_available(rti::routing::processor::Route&);
void on_output_enabled(
rti::routing::processor::Route& route,
rti::routing::processor::Output& output);
ShapesAggregatorAdv(int32_t leading_input_index);
~ShapesAggregatorAdv();
private:
// Optional member for deferred initialization: this object can be created
// only when the output is enabled.
// You can use std::optional if supported in your platform
dds::core::optional<dds::core::xtypes::DynamicData> output_data_;
// index of leading input from which data is read first
int32_t leading_input_index_;
};
class ShapesSplitter :
public rti::routing::processor::NoOpProcessor {
public:
void on_data_available(rti::routing::processor::Route&) override;
void on_input_enabled(
rti::routing::processor::Route& route,
rti::routing::processor::Input& input) override;
ShapesSplitter();
~ShapesSplitter();
private:
// Optional member for deferred initialization: this object can be created
// only when the output is enabled.
// You can use std::optional if supported in your platform
dds::core::optional<dds::core::xtypes::DynamicData> output_data_;
};
class ShapesProcessorPlugin :
public rti::routing::processor::ProcessorPlugin {
public:
static const std::string PROCESSOR_KIND_PROPERTY_NAME;
static const std::string PROCESSOR_LEADING_INPUT_PROPERTY_NAME;
static const std::string PROCESSOR_AGGREGATOR_SIMPLE_NAME;
static const std::string PROCESSOR_AGGREGATOR_ADV_NAME;
static const std::string PROCESSOR_SPLITTER_NAME;
rti::routing::processor::Processor* create_processor(
rti::routing::processor::Route& route,
const rti::routing::PropertySet& properties) override;
void delete_processor(
rti::routing::processor::Route& route,
rti::routing::processor::Processor *processor) override;
ShapesProcessorPlugin(
const rti::routing::PropertySet& properties);
};
/**
* This macro defines a C-linkage symbol that can be used as create function
* for plug-in registration through XML.
*
* The generated symbol has the name:
*
* \code
* ShapesProcessorPlugin_create_processor_plugin
* \endcode
*/
RTI_PROCESSOR_PLUGIN_CREATE_FUNCTION_DECL(ShapesProcessorPlugin);
#endif | hpp |
rticonnextdds-examples | data/projects/rticonnextdds-examples/dynamic_data_sequences/c++/dynamic_data_sequences.cxx | /*******************************************************************************
(c) 2005-2014 Copyright, Real-Time Innovations, Inc. All rights reserved.
RTI grants Licensee a license to use, modify, compile, and create derivative
works of the Software. Licensee has the right to distribute object form only
for use with RTI products. The Software is provided "as is", with no warranty
of any type, including any warranty for fitness for any purpose. RTI is under
no obligation to maintain or support the Software. RTI shall not be liable for
any incidental or consequential damages arising out of the use or inability to
use the software.
******************************************************************************/
/* dynamic_data_sequences.cxx
This example
- creates the type code of a sequence
- creates a DynamicData instance
- writes and reads the values
Example:
To run the example application:
On Unix:
objs/<arch>/SequencesExample
On Windows:
objs\<arch>\SequencesExample
*/
#include <ndds_cpp.h>
#include <iostream>
using namespace std;
/********* IDL representation for this example ************
*
* struct SimpleStruct {
* long a_member;
* };
*
* struct TypeWithSequence {
* sequence<SimpleStruct,5> sequence_member;
* };
*/
#define MAX_SEQ_LEN 5
/*
* Uncomment to use the bind api instead of the get API.
*/
/* #define USE_BIND_API */
DDS_TypeCode *
sequence_element_get_typecode(DDS_TypeCodeFactory *tcf) {
static DDS_TypeCode * tc = NULL;
struct DDS_StructMemberSeq members;
DDS_ExceptionCode_t err;
/* First, we create the typeCode for the simple struct */
tc = tcf->create_struct_tc("SimpleStruct", members, err);
if (err != DDS_NO_EXCEPTION_CODE) {
cerr << stderr << "! Unable to create sequence TC" << endl;
goto fail;
}
tc->add_member("a_member", DDS_TYPECODE_MEMBER_ID_INVALID,
tcf->get_primitive_tc(DDS_TK_LONG), DDS_TYPECODE_NONKEY_MEMBER,
err);
if (err != DDS_NO_EXCEPTION_CODE) {
cerr << stderr << "! Unable to add a_member to SimpleStruct" << endl;
goto fail;
}
return tc;
fail:
if (tc != NULL) {
tcf->delete_tc(tc, err);
}
return NULL;
}
DDS_TypeCode *
sequence_get_typecode(DDS_TypeCodeFactory *tcf) {
static DDS_TypeCode * tc = NULL;
DDS_TypeCode *seqElementTC = NULL;
DDS_ExceptionCode_t err;
seqElementTC = sequence_element_get_typecode(tcf);
if (seqElementTC == NULL) {
cerr << "! Unable to create TypeCode" << endl;
goto fail;
}
/* We create the typeCode for the sequence */
tc = tcf->create_sequence_tc(MAX_SEQ_LEN, seqElementTC, err);
if (err != DDS_NO_EXCEPTION_CODE) {
cerr << "! Unable to create the sequence TC" << endl;
goto fail;
}
if (seqElementTC != NULL) {
tcf->delete_tc(seqElementTC, err);
}
return tc;
fail:
if (seqElementTC != NULL) {
tcf->delete_tc(seqElementTC, err);
}
if (tc != NULL) {
tcf->delete_tc(tc, err);
}
return NULL;
}
DDS_TypeCode *
type_w_sequence_get_typecode(DDS_TypeCodeFactory *tcf) {
static DDS_TypeCode * tc = NULL;
DDS_TypeCode * sequenceTC = NULL;
struct DDS_StructMemberSeq members;
DDS_ExceptionCode_t err;
sequenceTC = sequence_get_typecode(tcf);
if (sequenceTC == NULL) {
cerr << "! Unable to get sequenceTC" << endl;
goto fail;
}
tc = tcf->create_struct_tc("TypeWithSequence", members, err);
if (tc == NULL) {
cerr << "! Unable to create Type with sequence TC" << endl;
goto fail;
}
tc->add_member("sequence_member", DDS_TYPECODE_MEMBER_ID_INVALID,
sequenceTC, DDS_TYPECODE_NONKEY_MEMBER, err);
if (sequenceTC != NULL) {
tcf->delete_tc(sequenceTC, err);
}
return tc;
fail: if (sequenceTC != NULL) {
tcf->delete_tc(sequenceTC, err);
}
if (tc != NULL) {
tcf->delete_tc(tc, err);
}
return NULL;
}
void write_data(DDS_DynamicData *sample, DDS_TypeCodeFactory *factory) {
/* Creating typecodes */
DDS_TypeCode *sequenceTC = sequence_get_typecode(factory);
if (sequenceTC == NULL) {
cerr << "! Unable to create sequence typecode " << endl;
return;
}
DDS_TypeCode *sequenceElementTC = sequence_element_get_typecode(factory);
if (sequenceElementTC == NULL) {
cerr << "! Unable to create sequence element typecode " << endl;
return;
}
DDS_ReturnCode_t retcode;
DDS_ExceptionCode_t err;
DDS_DynamicData seqmember(sequenceTC, DDS_DYNAMIC_DATA_PROPERTY_DEFAULT);
DDS_DynamicData seqelement(sequenceElementTC,
DDS_DYNAMIC_DATA_PROPERTY_DEFAULT);
int i = 0;
for (i = 0; i < MAX_SEQ_LEN; ++i) {
/* To access the elements of a sequence it is necessary
* to use their id. This parameter allows accessing to every element
* of the sequence using a 1-based index.
* There are two ways of doing this: bind API and get API.
* See the NestedStructExample for further details about the
* differences between these two APIs. */
#ifdef USE_BIND_API
retcode = seqmember.bind_complex_member(seqelement, NULL,
i + 1);
if (retcode != DDS_RETCODE_OK) {
cerr << "! Unable to bind complex member" << endl;
goto fail;
}
retcode = seqelement.set_long( "a_member",
DDS_DYNAMIC_DATA_MEMBER_ID_UNSPECIFIED, i);
if (retcode != DDS_RETCODE_OK) {
cerr << "! Unable to set a_member long" << endl;
goto fail;
}
printf("Writing sequence element #%d : \n", i + 1);
seqelement.print(stdout, 1);
retcode = seqmember.unbind_complex_member(seqelement);
if (retcode != DDS_RETCODE_OK) {
cerr << "! Unable to unbind complex member" << endl;
goto fail;
}
#else
retcode = seqelement.set_long("a_member",
DDS_DYNAMIC_DATA_MEMBER_ID_UNSPECIFIED, i);
if (retcode != DDS_RETCODE_OK) {
cerr << "! Unable to set a_member long" << endl;
goto fail;
}
printf("Writing sequence element #%d : \n", i + 1);
seqelement.print(stdout, 1);
retcode = seqmember.set_complex_member(NULL, i + 1, seqelement);
if (retcode != DDS_RETCODE_OK) {
cerr << "! Unable to set complex member" << endl;
goto fail;
}
#endif
}
retcode = DDS_DynamicData_set_complex_member(sample, "sequence_member",
DDS_DYNAMIC_DATA_MEMBER_ID_UNSPECIFIED, &seqmember);
if (retcode != DDS_RETCODE_OK) {
cerr << "! Unable to set complex member" << endl;
goto fail;
}
fail: if (sequenceTC != NULL) {
factory->delete_tc(sequenceTC, err);
}
if (sequenceElementTC != NULL) {
factory->delete_tc(sequenceElementTC, err);
}
return;
}
void read_data(DDS_DynamicData *sample, DDS_TypeCodeFactory *factory) {
DDS_TypeCode * sequenceTC = sequence_get_typecode(factory);
if (sequenceTC == NULL) {
cerr << "! Unable to get sequence type code" << endl;
return;
}
DDS_DynamicData seqmember(sequenceTC, DDS_DYNAMIC_DATA_PROPERTY_DEFAULT);
DDS_DynamicData seqelement(NULL, DDS_DYNAMIC_DATA_PROPERTY_DEFAULT);
DDS_ReturnCode_t retcode;
DDS_ExceptionCode_t err;
DDS_Long value;
struct DDS_DynamicDataInfo info;
int i, seqlen;
sample->get_complex_member(seqmember, "sequence_member",
DDS_DYNAMIC_DATA_MEMBER_ID_UNSPECIFIED);
/* Now we get the total amount of elements contained in the array
* by accessing the dynamic data info
*/
cout << "* Getting sequence member info...." << endl;
seqmember.get_info(info);
seqlen = info.member_count;
cout << "* Sequence contains " << seqlen << " elements" << endl;
for (i = 0; i < seqlen; ++i) {
/*
* The same results can be obtained using
* bind_complex_member method. The main difference, is that
* in that case the members are not copied, just referenced
*/
#ifdef USE_BIND_API
retcode = seqmember.bind_complex_member(seqelement, NULL,
i + 1);
if (retcode != DDS_RETCODE_OK) {
cerr << "! Unable to bind complex member" << endl;
goto fail;
}
#else
retcode = seqmember.get_complex_member(seqelement, NULL, i + 1);
if (retcode != DDS_RETCODE_OK) {
cerr << "! Unable to bind complex member" << endl;
goto fail;
}
#endif
retcode = seqelement.get_long(value, "a_member",
DDS_DYNAMIC_DATA_MEMBER_ID_UNSPECIFIED);
if (retcode != DDS_RETCODE_OK) {
cerr << "! Unable to get long member from seq element" << endl;
goto fail;
}
cout << "Reading sequence element #" << i + 1 << " :" << endl;
seqelement.print(stdout, 1);
#ifdef USE_BIND_API
retcode = seqmember.unbind_complex_member(seqelement);
if (retcode != DDS_RETCODE_OK) {
cerr << "! Unable to u8nbind complex member" << endl;
}
#endif
}
fail:
if (sequenceTC != NULL) {
factory->delete_tc(sequenceTC, err);
}
return;
}
int main() {
DDS_TypeCodeFactory *factory = NULL;
DDS_TypeCode * wSequenceTC = NULL;
DDS_ExceptionCode_t err;
factory = DDS_TypeCodeFactory::get_instance();
if (factory == NULL) {
cerr << "! Unable to get type code factory singleton" << endl;
return -1;
}
wSequenceTC = type_w_sequence_get_typecode(factory);
if (wSequenceTC == NULL) {
cerr << "! Unable to create wSequence Type Code" << endl;
return -1;
}
DDS_DynamicData sample(wSequenceTC, DDS_DYNAMIC_DATA_PROPERTY_DEFAULT);
cout << "***** Writing a sample *****" << endl;
write_data(&sample, factory);
cout << "***** Reading a sample *****" << endl;
read_data(&sample, factory);
/* Delete the created TC */
if (wSequenceTC != NULL) {
factory->delete_tc(wSequenceTC, err);
}
return 0;
}
| cxx |
rticonnextdds-examples | data/projects/rticonnextdds-examples/dynamic_data_sequences/c/dynamic_data_sequences.c | /*******************************************************************************
(c) 2005-2014 Copyright, Real-Time Innovations, Inc. All rights reserved.
RTI grants Licensee a license to use, modify, compile, and create derivative
works of the Software. Licensee has the right to distribute object form only
for use with RTI products. The Software is provided "as is", with no warranty
of any type, including any warranty for fitness for any purpose. RTI is under
no obligation to maintain or support the Software. RTI shall not be liable for
any incidental or consequential damages arising out of the use or inability to
use the software.
******************************************************************************/
/* dynamic_data_sequences.c
This example
- creates the type code of a sequence
- creates a DynamicData instance
- writes and reads the values
Example:
To run the example application:
On Unix:
objs/<arch>/SequencesExample
On Windows:
objs\<arch>\SequencesExample
*/
#include <ndds_c.h>
/********* IDL representation for this example ************
*
* struct SimpleStruct {
* long a_member;
* };
*
* struct TypeWithSequence {
* sequence<SimpleStruct,5> sequence_member;
* };
*/
#define MAX_SEQ_LEN 5
/*
* Uncomment to use the bind api instead of the get API.
*/
/* #define USE_BIND_API */
DDS_TypeCode *
sequence_element_get_typecode(DDS_TypeCodeFactory *tcf) {
static DDS_TypeCode * tc = NULL;
struct DDS_StructMemberSeq members = DDS_SEQUENCE_INITIALIZER;
DDS_ExceptionCode_t err;
/* First, we create the typeCode for the simple struct */
tc = DDS_TypeCodeFactory_create_struct_tc(tcf, "SimpleStruct", &members,
&err);
if (err != DDS_NO_EXCEPTION_CODE) {
fprintf(stderr, "! Unable to create sequence TC\n");
goto fail;
}
DDS_TypeCode_add_member(tc, "a_member", DDS_TYPECODE_MEMBER_ID_INVALID,
DDS_TypeCodeFactory_get_primitive_tc(tcf, DDS_TK_LONG),
DDS_TYPECODE_NONKEY_MEMBER, &err);
if (err != DDS_NO_EXCEPTION_CODE) {
fprintf(stderr, "! Unable to add a_member to SimpleStruct\n");
goto fail;
}
return tc;
fail:
if (tc != NULL) {
DDS_TypeCodeFactory_delete_tc(tcf, tc, &err);
}
return NULL;
}
DDS_TypeCode *
sequence_get_typecode(DDS_TypeCodeFactory *tcf) {
static DDS_TypeCode * tc = NULL;
DDS_TypeCode * seqElementTC = NULL;
DDS_ExceptionCode_t err;
seqElementTC = sequence_element_get_typecode(tcf);
if (seqElementTC == NULL) {
fprintf(stderr, "! Unable to create typeCode\n");
goto fail;
}
/* We create the typeCode for the sequence */
tc = DDS_TypeCodeFactory_create_sequence_tc(tcf, MAX_SEQ_LEN, seqElementTC,
&err);
if (err != DDS_NO_EXCEPTION_CODE) {
fprintf(stderr, "! Unable to create the sequence TC\n");
goto fail;
}
if (seqElementTC != NULL) {
DDS_TypeCodeFactory_delete_tc(tcf, seqElementTC, &err);
}
return tc;
fail:
if (seqElementTC != NULL) {
DDS_TypeCodeFactory_delete_tc(tcf, seqElementTC, &err);
}
if (tc != NULL) {
DDS_TypeCodeFactory_delete_tc(tcf, tc, &err);
}
return NULL;
}
DDS_TypeCode *
type_w_sequence_get_typecode(DDS_TypeCodeFactory *tcf) {
static DDS_TypeCode * tc = NULL;
struct DDS_TypeCode * sequenceTC = NULL;
struct DDS_StructMemberSeq members = DDS_SEQUENCE_INITIALIZER;
DDS_ExceptionCode_t err;
sequenceTC = sequence_get_typecode(tcf);
if (sequenceTC == NULL) {
fprintf(stderr, "! Unable to get sequenceTC\n");
goto fail;
}
tc = DDS_TypeCodeFactory_create_struct_tc(tcf, "TypeWithSequence", &members,
&err);
if (tc == NULL) {
fprintf(stderr, "! Unable to create Type with sequence TC\n");
goto fail;
}
DDS_TypeCode_add_member(tc, "sequence_member",
DDS_TYPECODE_MEMBER_ID_INVALID, sequenceTC,
DDS_TYPECODE_NONKEY_MEMBER, &err);
if (sequenceTC != NULL) {
DDS_TypeCodeFactory_delete_tc(tcf, sequenceTC, &err);
}
DDS_StructMemberSeq_finalize(&members);
return tc;
fail:
if (tc != NULL) {
DDS_TypeCodeFactory_delete_tc(tcf, tc, &err);
}
if (sequenceTC != NULL) {
DDS_TypeCodeFactory_delete_tc(tcf, sequenceTC, &err);
}
DDS_StructMemberSeq_finalize(&members);
return NULL;
}
void write_data(DDS_DynamicData *sample, DDS_TypeCodeFactory *factory) {
DDS_DynamicData seqmember;
DDS_DynamicData seqelement;
DDS_Boolean seqMemberIsInitialized = DDS_BOOLEAN_FALSE;
DDS_Boolean seqElementIsInitialized = DDS_BOOLEAN_FALSE;
DDS_TypeCode *sequenceTC = NULL;
DDS_TypeCode *sequenceElementTC = NULL;
DDS_ExceptionCode_t err;
DDS_ReturnCode_t retcode;
int i = 0;
sequenceTC = sequence_get_typecode(factory);
if (sequenceTC == NULL) {
fprintf(stderr, "! Unable to create typeCode\n");
goto fail;
}
sequenceElementTC = sequence_element_get_typecode(factory);
if (sequenceElementTC == NULL) {
fprintf(stderr, "! Unable to create typeCode\n");
goto fail;
}
seqMemberIsInitialized = DDS_DynamicData_initialize(&seqmember, sequenceTC,
&DDS_DYNAMIC_DATA_PROPERTY_DEFAULT);
if (!seqMemberIsInitialized) {
fprintf(stderr, "! Unable to initialize seqMember\n");
goto fail;
}
seqElementIsInitialized = DDS_DynamicData_initialize(&seqelement,
sequenceElementTC, &DDS_DYNAMIC_DATA_PROPERTY_DEFAULT);
if (!seqElementIsInitialized) {
fprintf(stderr, "! Unable to initialize seqElement\n");
goto fail;
}
for (i = 0; i < MAX_SEQ_LEN; ++i) {
/* To access the elements of a sequence it is necessary
* to use their id. This parameter allows accessing to every element
* of the sequence using a 1-based index.
* There are two ways of doing this: bind API and get API.
* See the NestedStructExample for further details about the
* differences between these two APIs. */
#ifdef USE_BIND_API
retcode = DDS_DynamicData_bind_complex_member(&seqmember, &seqelement,
NULL, i + 1);
if (retcode != DDS_RETCODE_OK) {
fprintf(stderr,"! Unable to bind complex member\n");
goto fail;
}
retcode = DDS_DynamicData_set_long(&seqelement, "a_member",
DDS_DYNAMIC_DATA_MEMBER_ID_UNSPECIFIED, i);
if (retcode != DDS_RETCODE_OK) {
fprintf(stderr,"! Unable to set a_member long\n");
goto fail;
}
printf("Writing sequence element #%d : \n", i + 1);
DDS_DynamicData_print(&seqelement, stdout, 1);
retcode = DDS_DynamicData_unbind_complex_member(&seqmember, &seqelement);
if (retcode != DDS_RETCODE_OK) {
fprintf(stderr,"! Unable to unbind complex member\n");
goto fail;
}
#else
retcode = DDS_DynamicData_set_long(&seqelement, "a_member",
DDS_DYNAMIC_DATA_MEMBER_ID_UNSPECIFIED, i);
if (retcode != DDS_RETCODE_OK) {
fprintf(stderr, "! Unable to set a_member long\n");
goto fail;
}
printf("Writing sequence element #%d : \n", i + 1);
DDS_DynamicData_print(&seqelement, stdout, 1);
retcode = DDS_DynamicData_set_complex_member(&seqmember, NULL, i + 1,
&seqelement);
if (retcode != DDS_RETCODE_OK) {
fprintf(stderr, "! Unable to set complex member\n");
goto fail;
}
#endif
}
retcode = DDS_DynamicData_set_complex_member(sample, "sequence_member",
DDS_DYNAMIC_DATA_MEMBER_ID_UNSPECIFIED, &seqmember);
if (retcode != DDS_RETCODE_OK) {
fprintf(stderr, "! Unable to set complex member\n");
goto fail;
}
fail:
if (sequenceTC != NULL) {
DDS_TypeCodeFactory_delete_tc(factory, sequenceTC, &err);
}
if (sequenceElementTC != NULL) {
DDS_TypeCodeFactory_delete_tc(factory, sequenceElementTC, &err);
}
if (seqMemberIsInitialized) {
DDS_DynamicData_finalize(&seqmember);
}
if (seqElementIsInitialized) {
DDS_DynamicData_finalize(&seqelement);
}
return;
}
void read_data(DDS_DynamicData *sample, DDS_TypeCodeFactory *factory) {
struct DDS_TypeCode *sequenceTC = NULL;
DDS_DynamicData seqmember;
DDS_DynamicData seqelement;
DDS_Boolean seqMemberIsInitialized = DDS_BOOLEAN_FALSE;
DDS_Boolean seqElementIsInitialized = DDS_BOOLEAN_FALSE;
DDS_Long value;
struct DDS_DynamicDataInfo info;
int i, seqlen;
DDS_ReturnCode_t retcode;
DDS_ExceptionCode_t err;
sequenceTC = sequence_get_typecode(factory);
if (sequenceTC == NULL) {
fprintf(stderr, "! Unable to get sequence type code\n");
goto fail;
}
seqMemberIsInitialized = DDS_DynamicData_initialize(&seqmember, sequenceTC,
&DDS_DYNAMIC_DATA_PROPERTY_DEFAULT);
if (!seqMemberIsInitialized) {
fprintf(stderr, "! Unable to initialize seqMember\n");
goto fail;
}
seqElementIsInitialized = DDS_DynamicData_initialize(&seqelement, NULL,
&DDS_DYNAMIC_DATA_PROPERTY_DEFAULT);
if (!seqElementIsInitialized) {
fprintf(stderr, "! Unable to initialize seqElement\n");
goto fail;
}
retcode = DDS_DynamicData_get_complex_member(sample, &seqmember,
"sequence_member", DDS_DYNAMIC_DATA_MEMBER_ID_UNSPECIFIED);
if (retcode != DDS_RETCODE_OK) {
fprintf(stderr, "! Unable to get complex member from seq member\n");
goto fail;
}
/* Now we get the total amount of elements contained in the sequence
* by accessing the dynamic data info
*/
printf("* Getting sequence member info....\n");
DDS_DynamicData_get_info(&seqmember, &info);
seqlen = info.member_count;
printf("* Sequence contains %d elements\n", seqlen);
for (i = 0; i < seqlen; ++i) {
/*
* The same results can be obtained using
* bind_complex_member method. The main difference, is that
* in that case the members are not copied, just referenced
*/
#ifdef USE_BIND_API
retcode = DDS_DynamicData_bind_complex_member(&seqmember, &seqelement,
NULL, i + 1);
if (retcode != DDS_RETCODE_OK) {
fprintf(stderr,"! Unable to bind complex member\n");
goto fail;
}
#else
retcode = DDS_DynamicData_get_complex_member(&seqmember, &seqelement,
NULL, i + 1);
if (retcode != DDS_RETCODE_OK) {
fprintf(stderr, "! Unable to get complex member\n");
goto fail;
}
#endif
retcode = DDS_DynamicData_get_long(&seqelement, &value, "a_member",
DDS_DYNAMIC_DATA_MEMBER_ID_UNSPECIFIED);
if (retcode != DDS_RETCODE_OK) {
fprintf(stderr, "! Unable to get long member from seq element\n");
goto fail;
}
printf("Reading sequence element #%d : \n", i + 1);
DDS_DynamicData_print(&seqelement, stdout, 1);
#ifdef USE_BIND_API
retcode = DDS_DynamicData_unbind_complex_member(&seqmember, &seqelement);
if (retcode != DDS_RETCODE_OK) {
fprintf(stderr, "! Unable to unbind complex member\n");
}
#endif
}
fail: if (sequenceTC != NULL) {
DDS_TypeCodeFactory_delete_tc(factory, sequenceTC, &err);
}
if (seqMemberIsInitialized) {
DDS_DynamicData_finalize(&seqmember);
}
if (seqElementIsInitialized) {
DDS_DynamicData_finalize(&seqelement);
}
return;
}
int main() {
DDS_DynamicData sample;
DDS_TypeCodeFactory *factory = NULL;
DDS_TypeCode *wSequenceTC = NULL;
DDS_Boolean dynamicDataIsInitialized = DDS_BOOLEAN_FALSE;
factory = DDS_TypeCodeFactory_get_instance();
if (factory == NULL) {
fprintf(stderr, "! Unable to get type code factory singleton\n");
goto fail;
}
wSequenceTC = type_w_sequence_get_typecode(factory);
if (wSequenceTC == NULL) {
fprintf(stderr, "! Unable to create wSequence Type Code\n");
goto fail;
}
dynamicDataIsInitialized = DDS_DynamicData_initialize(&sample, wSequenceTC,
&DDS_DYNAMIC_DATA_PROPERTY_DEFAULT);
if (!dynamicDataIsInitialized) {
fprintf(stderr, "! Unable to create dynamicData\n");
goto fail;
}
printf("***** Writing a sample *****\n");
write_data(&sample, factory);
printf("***** Reading a sample *****\n");
read_data(&sample, factory);
fail:
if (wSequenceTC != NULL) {
DDS_TypeCodeFactory_delete_tc(factory, wSequenceTC, NULL);
}
if (dynamicDataIsInitialized) {
DDS_DynamicData_finalize(&sample);
}
return 0;
}
| c |
rticonnextdds-examples | data/projects/rticonnextdds-examples/dynamic_data_sequences/c++03/dynamic_data_sequences.cxx | /*******************************************************************************
(c) 2005-2015 Copyright, Real-Time Innovations, Inc. All rights reserved.
RTI grants Licensee a license to use, modify, compile, and create derivative
works of the Software. Licensee has the right to distribute object form only
for use with RTI products. The Software is provided "as is", with no warranty
of any type, including any warranty for fitness for any purpose. RTI is under
no obligation to maintain or support the Software. RTI shall not be liable for
any incidental or consequential damages arising out of the use or inability to
use the software.
******************************************************************************/
#include <iostream>
#include <dds/dds.hpp>
using namespace dds::core::xtypes;
using namespace rti::core::xtypes;
// IDL representation for this example:
//
// struct SimpleStruct {
// long a_member;
// };
//
// struct TypeWithSequence {
// sequence<SimpleStruct,5> sequence_member;
// };
//
const int MAX_SEQ_LEN = 5;
DynamicType create_dynamictype_simple_struct()
{
// First create the type code for a struct.
StructType simple_struct("SimpleStruct");
// The member will be a integer named "a_member".
simple_struct.add_member(Member("a_member", primitive_type<int32_t>()));
return simple_struct;
}
DynamicType create_dynamictype_sequence_struct()
{
// First create the type code for a struct.
StructType type_with_sequence("TypeWithSequence");
// Add a sequence of type SimpleStruct
DynamicType simple_struct = create_dynamictype_simple_struct();
type_with_sequence.add_member(Member(
"sequence_member",
SequenceType(simple_struct, MAX_SEQ_LEN)));
return type_with_sequence;
}
void write_data(DynamicData& sample)
{
// Get the sequence member to set its elements.
DynamicData sequence_member = sample.value<DynamicData>("sequence_member");
// Get the type of the sequence members.
DynamicType simple_struct_dynamic_type = static_cast<const SequenceType&>(
sequence_member.type()).content_type();
// Write a new struct for each member of the sequence.
for (int i = 0; i < MAX_SEQ_LEN; i++) {
// To access the elements of a sequence it is necessary
// to use their id. This parameter allows accessing to every element
// of the sequence using a 1-based index.
// There are two ways of doing this: loan API and value API.
// See the dynamic_data_nested_structs for further details about the
// differences between these two APIs.
// **Loan**:
// Get a reference to the i+1 element (1-based index).
LoanedDynamicData loaned_data = sequence_member.loan_value(i + 1);
// We're setting "a_member" whose type is int32_t, the same type as i.
// If the value had a different type (e.g. short) a cast or a explicit
// use of the template parameter would be required to avoid a runtime
// error.
loaned_data.get().value("a_member", i);
// We're returning the loan explicitly; the destructor
// of loaned_data would do it too.
loaned_data.return_loan();
// **Value**:
// Create a simple_struct for this sequence element.
DynamicData simple_struct_element(simple_struct_dynamic_type);
simple_struct_element.value("a_member", i);
// Add to the sequence.
std::cout << "Writing sequence element #" << (i + 1) << " :"
<< std::endl << simple_struct_element;
sequence_member.value(i + 1, simple_struct_element);
}
sample.value("sequence_member", sequence_member);
}
void read_data(const DynamicData& sample)
{
// Get the sequence member
DynamicData sequence_member = sample.value<DynamicData>("sequence_member");
// Get the total amount of elements contained in the sequence by accessing
// the dynamic data info.
std::cout << "* Getting sequence member info..." << std::endl;
const DynamicDataInfo& info = sequence_member.info();
int seq_len = info.member_count();
std::cout << "* Sequence contains " << seq_len << " elements" << std::endl;
for (int i = 0; i < seq_len; i++) {
// Value getter:
DynamicData struct_element = sequence_member.value<DynamicData>(i + 1);
// Loan:
// The same results can be obtained using 'loan_value' method.
// The main difference, is that in that case the members are not copied,
// just referenced. To access to the member value call 'get()' method.
// The destructor will unloan the member.
LoanedDynamicData loaned_struct = sequence_member.loan_value(i + 1);
std::cout << "Reading sequence element #" << (i + 1) << " :"
<< std::endl << struct_element; // or loaned_struct.get();
}
}
int main()
{
try {
// Create the struct with the sequence member.
DynamicType struct_sequence_type = create_dynamictype_sequence_struct();
DynamicData struct_sequence_data(struct_sequence_type);
std::cout << "***** Writing a sample *****" << std::endl;
write_data(struct_sequence_data);
std::cout << std::endl;
std::cout << "***** Reading a sample *****" << std::endl;
read_data(struct_sequence_data);
} catch (const std::exception& ex) {
// This will catch DDS exceptions.
std::cerr << "Exception: " << ex.what() << std::endl;
return -1;
}
return 0;
}
| cxx |
rticonnextdds-examples | data/projects/rticonnextdds-examples/asynchronous_publication/c++/async_publisher.cxx | /*******************************************************************************
(c) 2005-2014 Copyright, Real-Time Innovations, Inc. All rights reserved.
RTI grants Licensee a license to use, modify, compile, and create derivative
works of the Software. Licensee has the right to distribute object form only
for use with RTI products. The Software is provided "as is", with no warranty
of any type, including any warranty for fitness for any purpose. RTI is under
no obligation to maintain or support the Software. RTI shall not be liable for
any incidental or consequential damages arising out of the use or inability to
use the software.
******************************************************************************/
/* async_publisher.cxx
A publication of data of type async
This file is derived from code automatically generated by the rtiddsgen
command:
rtiddsgen -language C++ -example <arch> async.idl
Example publication of type async automatically generated by
'rtiddsgen'. To test them follow these steps:
(1) Compile this file and the example subscription.
(2) Start the subscription with the command
objs/<arch>/async_subscriber <domain_id> <sample_count>
(3) Start the publication with the command
objs/<arch>/async_publisher <domain_id> <sample_count>
(4) [Optional] Specify the list of discovery initial peers and
multicast receive addresses via an environment variable or a file
(in the current working directory) called NDDS_DISCOVERY_PEERS.
You can run any number of publishers and subscribers programs, and can
add and remove them dynamically from the domain.
Example:
To run the example application on domain <domain_id>:
On Unix:
objs/<arch>/async_publisher <domain_id> o
objs/<arch>/async_subscriber <domain_id>
On Windows:
objs\<arch>\async_publisher <domain_id>
objs\<arch>\async_subscriber <domain_id>
modification history
------------ -------
*/
#include <stdio.h>
#include <stdlib.h>
#ifdef RTI_VX653
#include <vThreadsData.h>
#endif
#include "async.h"
#include "asyncSupport.h"
#include "ndds/ndds_cpp.h"
/* Delete all entities */
static int publisher_shutdown(
DDSDomainParticipant *participant)
{
DDS_ReturnCode_t retcode;
int status = 0;
if (participant != NULL) {
retcode = participant->delete_contained_entities();
if (retcode != DDS_RETCODE_OK) {
printf("delete_contained_entities error %d\n", retcode);
status = -1;
}
retcode = DDSTheParticipantFactory->delete_participant(participant);
if (retcode != DDS_RETCODE_OK) {
printf("delete_participant error %d\n", retcode);
status = -1;
}
}
/* RTI Connext provides finalize_instance() method on
domain participant factory for people who want to release memory used
by the participant factory. Uncomment the following block of code for
clean destruction of the singleton. */
/*
retcode = DDSDomainParticipantFactory::finalize_instance();
if (retcode != DDS_RETCODE_OK) {
printf("finalize_instance error %d\n", retcode);
status = -1;
}
*/
return status;
}
extern "C" int publisher_main(int domainId, int sample_count)
{
DDSDomainParticipant *participant = NULL;
DDSPublisher *publisher = NULL;
DDSTopic *topic = NULL;
DDSDataWriter *writer = NULL;
asyncDataWriter * async_writer = NULL;
async *instance = NULL;
DDS_ReturnCode_t retcode;
DDS_InstanceHandle_t instance_handle = DDS_HANDLE_NIL;
const char *type_name = NULL;
int count = 0;
struct DDS_Duration_t send_period = {0,100000000};
/* To customize participant QoS, use
the configuration file USER_QOS_PROFILES.xml */
participant = DDSTheParticipantFactory->create_participant(
domainId, DDS_PARTICIPANT_QOS_DEFAULT,
NULL /* listener */, DDS_STATUS_MASK_NONE);
if (participant == NULL) {
printf("create_participant error\n");
publisher_shutdown(participant);
return -1;
}
/* To customize publisher QoS, use
the configuration file USER_QOS_PROFILES.xml */
publisher = participant->create_publisher(
DDS_PUBLISHER_QOS_DEFAULT, NULL /* listener */, DDS_STATUS_MASK_NONE);
if (publisher == NULL) {
printf("create_publisher error\n");
publisher_shutdown(participant);
return -1;
}
/* Register type before creating topic */
type_name = asyncTypeSupport::get_type_name();
retcode = asyncTypeSupport::register_type(
participant, type_name);
if (retcode != DDS_RETCODE_OK) {
printf("register_type error %d\n", retcode);
publisher_shutdown(participant);
return -1;
}
/* To customize topic QoS, use
the configuration file USER_QOS_PROFILES.xml */
topic = participant->create_topic(
"Example async",
type_name, DDS_TOPIC_QOS_DEFAULT, NULL /* listener */,
DDS_STATUS_MASK_NONE);
if (topic == NULL) {
printf("create_topic error\n");
publisher_shutdown(participant);
return -1;
}
/* To customize data writer QoS, use
the configuration file USER_QOS_PROFILES.xml */
writer = publisher->create_datawriter(
topic, DDS_DATAWRITER_QOS_DEFAULT, NULL /* listener */,
DDS_STATUS_MASK_NONE);
if (writer == NULL) {
printf("create_datawriter error\n");
publisher_shutdown(participant);
return -1;
}
/* If you want to change the DataWriter's QoS programmatically rather than
* using the XML file, you will need to add the following lines to your
* code and comment out the create_datawriter call above.
*
* In this case, we set the publish mode qos to asynchronous publish mode,
* which enables asynchronous publishing. We also set the flow controller
* to be the fixed rate flow controller, and we increase the history depth.
*/
/* Get default datawriter QoS to customize * /
DDS_DataWriterQos datawriter_qos;
retcode = publisher->get_default_datawriter_qos(datawriter_qos);
if (retcode != DDS_RETCODE_OK) {
printf("get_default_datawriter_qos error\n");
return -1;
}
// Since samples are only being sent once per second, datawriter will need
// to keep them on queue. History defaults to only keeping the last
// sample enqueued, so we increase that here.
datawriter_qos.history.depth = 12;
// Set flowcontroller for datawriter
datawriter_qos.publish_mode.kind = DDS_ASYNCHRONOUS_PUBLISH_MODE_QOS;
datawriter_qos.publish_mode.flow_controller_name = DDS_FIXED_RATE_FLOW_CONTROLLER_NAME;
/* To create datawriter with default QoS, use DDS_DATAWRITER_QOS_DEFAULT
instead of datawriter_qos * /
writer = publisher->create_datawriter(
topic, datawriter_qos, NULL /* listener * /,
DDS_STATUS_MASK_NONE);
if (writer == NULL) {
printf("create_datawriter error\n");
publisher_shutdown(participant);
return -1;
}
//// End changes for Asynchronous_Publication
*/
async_writer = asyncDataWriter::narrow(writer);
if (async_writer == NULL) {
printf("DataWriter narrow error\n");
publisher_shutdown(participant);
return -1;
}
/* Create data sample for writing */
instance = asyncTypeSupport::create_data();
if (instance == NULL) {
printf("asyncTypeSupport::create_data error\n");
publisher_shutdown(participant);
return -1;
}
/* For a data type that has a key, if the same instance is going to be
written multiple times, initialize the key here
and register the keyed instance prior to writing */
/*
instance_handle = async_writer->register_instance(*instance);
*/
/* Main loop */
for (count=0; (sample_count == 0) || (count < sample_count); ++count) {
printf("Writing async, count %d\n", count);
// send count as data.
instance->x = count;
retcode = async_writer->write(*instance, instance_handle);
if (retcode != DDS_RETCODE_OK) {
printf("write error %d\n", retcode);
}
NDDSUtility::sleep(send_period);
}
//// Changes for Asynchronous_Publication
// Give time for publisher to send out last few samples
send_period.sec = 1;
NDDSUtility::sleep(send_period);
/*
retcode = async_writer->unregister_instance(
*instance, instance_handle);
if (retcode != DDS_RETCODE_OK) {
printf("unregister instance error %d\n", retcode);
}
*/
/* Delete data sample */
retcode = asyncTypeSupport::delete_data(instance);
if (retcode != DDS_RETCODE_OK) {
printf("asyncTypeSupport::delete_data error %d\n", retcode);
}
/* Delete all entities */
return publisher_shutdown(participant);
}
#if defined(RTI_WINCE)
int wmain(int argc, wchar_t** argv)
{
int domainId = 0;
int sample_count = 0; /* infinite loop */
if (argc >= 2) {
domainId = _wtoi(argv[1]);
}
if (argc >= 3) {
sample_count = _wtoi(argv[2]);
}
/* Uncomment this to turn on additional logging
NDDSConfigLogger::get_instance()->
set_verbosity_by_category(NDDS_CONFIG_LOG_CATEGORY_API,
NDDS_CONFIG_LOG_VERBOSITY_STATUS_ALL);
*/
return publisher_main(domainId, sample_count);
}
#elif !(defined(RTI_VXWORKS) && !defined(__RTP__)) && !defined(RTI_PSOS)
int main(int argc, char *argv[])
{
int domainId = 0;
int sample_count = 0; /* infinite loop */
if (argc >= 2) {
domainId = atoi(argv[1]);
}
if (argc >= 3) {
sample_count = atoi(argv[2]);
}
/* Uncomment this to turn on additional logging
NDDSConfigLogger::get_instance()->
set_verbosity_by_category(NDDS_CONFIG_LOG_CATEGORY_API,
NDDS_CONFIG_LOG_VERBOSITY_STATUS_ALL);
*/
return publisher_main(domainId, sample_count);
}
#endif
#ifdef RTI_VX653
const unsigned char* __ctype = *(__ctypePtrGet());
extern "C" void usrAppInit ()
{
#ifdef USER_APPL_INIT
USER_APPL_INIT; /* for backwards compatibility */
#endif
/* add application specific code here */
taskSpawn("pub", RTI_OSAPI_THREAD_PRIORITY_NORMAL, 0x8, 0x150000, (FUNCPTR)publisher_main, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
}
#endif
| cxx |
rticonnextdds-examples | data/projects/rticonnextdds-examples/asynchronous_publication/c++/async_subscriber.cxx | /*******************************************************************************
(c) 2005-2014 Copyright, Real-Time Innovations, Inc. All rights reserved.
RTI grants Licensee a license to use, modify, compile, and create derivative
works of the Software. Licensee has the right to distribute object form only
for use with RTI products. The Software is provided "as is", with no warranty
of any type, including any warranty for fitness for any purpose. RTI is under
no obligation to maintain or support the Software. RTI shall not be liable for
any incidental or consequential damages arising out of the use or inability to
use the software.
******************************************************************************/
/* async_subscriber.cxx
A subscription example
This file is derived from code automatically generated by the rtiddsgen
command:
rtiddsgen -language C++ -example <arch> async.idl
Example subscription of type async automatically generated by
'rtiddsgen'. To test them follow these steps:
(1) Compile this file and the example publication.
(2) Start the subscription with the command
objs/<arch>/async_subscriber <domain_id> <sample_count>
(3) Start the publication with the command
objs/<arch>/async_publisher <domain_id> <sample_count>
(4) [Optional] Specify the list of discovery initial peers and
multicast receive addresses via an environment variable or a file
(in the current working directory) called NDDS_DISCOVERY_PEERS.
You can run any number of publishers and subscribers programs, and can
add and remove them dynamically from the domain.
Example:
To run the example application on domain <domain_id>:
On Unix:
objs/<arch>/async_publisher <domain_id>
objs/<arch>/async_subscriber <domain_id>
On Windows:
objs\<arch>\async_publisher <domain_id>
objs\<arch>\async_subscriber <domain_id>
modification history
------------ -------
*/
#include <stdio.h>
#include <stdlib.h>
#ifdef RTI_VX653
#include <vThreadsData.h>
#endif
#include "async.h"
#include "asyncSupport.h"
#include "ndds/ndds_cpp.h"
//// Changes for Asynchronous_Publication
// For timekeeping
#include <time.h>
clock_t init;
class asyncListener : public DDSDataReaderListener {
public:
virtual void on_requested_deadline_missed(
DDSDataReader* /*reader*/,
const DDS_RequestedDeadlineMissedStatus& /*status*/) {}
virtual void on_requested_incompatible_qos(
DDSDataReader* /*reader*/,
const DDS_RequestedIncompatibleQosStatus& /*status*/) {}
virtual void on_sample_rejected(
DDSDataReader* /*reader*/,
const DDS_SampleRejectedStatus& /*status*/) {}
virtual void on_liveliness_changed(
DDSDataReader* /*reader*/,
const DDS_LivelinessChangedStatus& /*status*/) {}
virtual void on_sample_lost(
DDSDataReader* /*reader*/,
const DDS_SampleLostStatus& /*status*/) {}
virtual void on_subscription_matched(
DDSDataReader* /*reader*/,
const DDS_SubscriptionMatchedStatus& /*status*/) {}
virtual void on_data_available(DDSDataReader* reader);
};
void asyncListener::on_data_available(DDSDataReader* reader)
{
asyncDataReader *async_reader = NULL;
asyncSeq data_seq;
DDS_SampleInfoSeq info_seq;
DDS_ReturnCode_t retcode;
int i;
async_reader = asyncDataReader::narrow(reader);
if (async_reader == NULL) {
printf("DataReader narrow error\n");
return;
}
retcode = async_reader->take(
data_seq, info_seq, DDS_LENGTH_UNLIMITED,
DDS_ANY_SAMPLE_STATE, DDS_ANY_VIEW_STATE, DDS_ANY_INSTANCE_STATE);
if (retcode == DDS_RETCODE_NO_DATA) {
return;
} else if (retcode != DDS_RETCODE_OK) {
printf("take error %d\n", retcode);
return;
}
for (i = 0; i < data_seq.length(); ++i) {
if (info_seq[i].valid_data) {
//// Start changes for Asynchronous_Publication
// print the time we get each sample.
double elapsed_ticks = clock() - init;
double elapsed_secs = elapsed_ticks/CLOCKS_PER_SEC;
printf("@ t=%.2fs, got x = %d\n",
elapsed_secs, data_seq[i].x);
//// End changes for Asynchronous_Publication
}
}
retcode = async_reader->return_loan(data_seq, info_seq);
if (retcode != DDS_RETCODE_OK) {
printf("return loan error %d\n", retcode);
}
}
/* Delete all entities */
static int subscriber_shutdown(
DDSDomainParticipant *participant)
{
DDS_ReturnCode_t retcode;
int status = 0;
if (participant != NULL) {
retcode = participant->delete_contained_entities();
if (retcode != DDS_RETCODE_OK) {
printf("delete_contained_entities error %d\n", retcode);
status = -1;
}
retcode = DDSTheParticipantFactory->delete_participant(participant);
if (retcode != DDS_RETCODE_OK) {
printf("delete_participant error %d\n", retcode);
status = -1;
}
}
/* RTI Connext provides the finalize_instance() method on
domain participant factory for people who want to release memory used
by the participant factory. Uncomment the following block of code for
clean destruction of the singleton. */
/*
retcode = DDSDomainParticipantFactory::finalize_instance();
if (retcode != DDS_RETCODE_OK) {
printf("finalize_instance error %d\n", retcode);
status = -1;
}
*/
return status;
}
extern "C" int subscriber_main(int domainId, int sample_count)
{
DDSDomainParticipant *participant = NULL;
DDSSubscriber *subscriber = NULL;
DDSTopic *topic = NULL;
asyncListener *reader_listener = NULL;
DDSDataReader *reader = NULL;
DDS_ReturnCode_t retcode;
const char *type_name = NULL;
int count = 0;
DDS_Duration_t receive_period = {4,0};
int status = 0;
//// Changes for Asynchronous_Publication
// for timekeeping
init = clock();
/* To customize the participant QoS, use
the configuration file USER_QOS_PROFILES.xml */
participant = DDSTheParticipantFactory->create_participant(
domainId, DDS_PARTICIPANT_QOS_DEFAULT,
NULL /* listener */, DDS_STATUS_MASK_NONE);
if (participant == NULL) {
printf("create_participant error\n");
subscriber_shutdown(participant);
return -1;
}
/* To customize the subscriber QoS, use
the configuration file USER_QOS_PROFILES.xml */
subscriber = participant->create_subscriber(
DDS_SUBSCRIBER_QOS_DEFAULT, NULL /* listener */, DDS_STATUS_MASK_NONE);
if (subscriber == NULL) {
printf("create_subscriber error\n");
subscriber_shutdown(participant);
return -1;
}
/* Register the type before creating the topic */
type_name = asyncTypeSupport::get_type_name();
retcode = asyncTypeSupport::register_type(
participant, type_name);
if (retcode != DDS_RETCODE_OK) {
printf("register_type error %d\n", retcode);
subscriber_shutdown(participant);
return -1;
}
/* To customize the topic QoS, use
the configuration file USER_QOS_PROFILES.xml */
topic = participant->create_topic(
"Example async",
type_name, DDS_TOPIC_QOS_DEFAULT, NULL /* listener */,
DDS_STATUS_MASK_NONE);
if (topic == NULL) {
printf("create_topic error\n");
subscriber_shutdown(participant);
return -1;
}
/* Create a data reader listener */
reader_listener = new asyncListener();
/* To customize the data reader QoS, use
the configuration file USER_QOS_PROFILES.xml */
reader = subscriber->create_datareader(
topic, DDS_DATAREADER_QOS_DEFAULT, reader_listener,
DDS_STATUS_MASK_ALL);
if (reader == NULL) {
printf("create_datareader error\n");
subscriber_shutdown(participant);
delete reader_listener;
return -1;
}
/* Main loop */
for (count=0; (sample_count == 0) || (count < sample_count); ++count) {
printf("async subscriber sleeping for %d sec...\n",
receive_period.sec);
NDDSUtility::sleep(receive_period);
}
/* Delete all entities */
status = subscriber_shutdown(participant);
delete reader_listener;
return status;
}
#if defined(RTI_WINCE)
int wmain(int argc, wchar_t** argv)
{
int domainId = 0;
int sample_count = 0; /* infinite loop */
if (argc >= 2) {
domainId = _wtoi(argv[1]);
}
if (argc >= 3) {
sample_count = _wtoi(argv[2]);
}
/* Uncomment this to turn on additional logging
NDDSConfigLogger::get_instance()->
set_verbosity_by_category(NDDS_CONFIG_LOG_CATEGORY_API,
NDDS_CONFIG_LOG_VERBOSITY_STATUS_ALL);
*/
return subscriber_main(domainId, sample_count);
}
#elif !(defined(RTI_VXWORKS) && !defined(__RTP__)) && !defined(RTI_PSOS)
int main(int argc, char *argv[])
{
int domainId = 0;
int sample_count = 0; /* infinite loop */
if (argc >= 2) {
domainId = atoi(argv[1]);
}
if (argc >= 3) {
sample_count = atoi(argv[2]);
}
/* Uncomment this to turn on additional logging
NDDSConfigLogger::get_instance()->
set_verbosity_by_category(NDDS_CONFIG_LOG_CATEGORY_API,
NDDS_CONFIG_LOG_VERBOSITY_STATUS_ALL);
*/
return subscriber_main(domainId, sample_count);
}
#endif
#ifdef RTI_VX653
const unsigned char* __ctype = *(__ctypePtrGet());
extern "C" void usrAppInit ()
{
#ifdef USER_APPL_INIT
USER_APPL_INIT; /* for backwards compatibility */
#endif
/* add application specific code here */
taskSpawn("sub", RTI_OSAPI_THREAD_PRIORITY_NORMAL, 0x8, 0x150000, (FUNCPTR)subscriber_main, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
}
#endif
| cxx |
rticonnextdds-examples | data/projects/rticonnextdds-examples/asynchronous_publication/c/async_publisher.c | /*******************************************************************************
(c) 2005-2014 Copyright, Real-Time Innovations, Inc. All rights reserved.
RTI grants Licensee a license to use, modify, compile, and create derivative
works of the Software. Licensee has the right to distribute object form only
for use with RTI products. The Software is provided "as is", with no warranty
of any type, including any warranty for fitness for any purpose. RTI is under
no obligation to maintain or support the Software. RTI shall not be liable for
any incidental or consequential damages arising out of the use or inability to
use the software.
******************************************************************************/
/* async_publisher.c
A publication of data of type async
This file is derived from code automatically generated by the rtiddsgen
command:
rtiddsgen -language C -example <arch> async.idl
Example publication of type async automatically generated by
'rtiddsgen'. To test them follow these steps:
(1) Compile this file and the example subscription.
(2) Start the subscription with the command
objs/<arch>/async_subscriber <domain_id> <sample_count>
(3) Start the publication with the command
objs/<arch>/async_publisher <domain_id> <sample_count>
(4) [Optional] Specify the list of discovery initial peers and
multicast receive addresses via an environment variable or a file
(in the current working directory) called NDDS_DISCOVERY_PEERS.
You can run any number of publishers and subscribers programs, and can
add and remove them dynamically from the domain.
Example:
To run the example application on domain <domain_id>:
On Unix:
objs/<arch>/async_publisher <domain_id>
objs/<arch>/async_subscriber <domain_id>
On Windows:
objs\<arch>\async_publisher <domain_id>
objs\<arch>\async_subscriber <domain_id>
modification history
------------ -------
*/
#include <stdio.h>
#include <stdlib.h>
#include "ndds/ndds_c.h"
#include "async.h"
#include "asyncSupport.h"
/* Delete all entities */
static int publisher_shutdown(
DDS_DomainParticipant *participant)
{
DDS_ReturnCode_t retcode;
int status = 0;
if (participant != NULL) {
retcode = DDS_DomainParticipant_delete_contained_entities(participant);
if (retcode != DDS_RETCODE_OK) {
printf("delete_contained_entities error %d\n", retcode);
status = -1;
}
retcode = DDS_DomainParticipantFactory_delete_participant(
DDS_TheParticipantFactory, participant);
if (retcode != DDS_RETCODE_OK) {
printf("delete_participant error %d\n", retcode);
status = -1;
}
}
/* RTI Connext provides finalize_instance() method on
domain participant factory for people who want to release memory used
by the participant factory. Uncomment the following block of code for
clean destruction of the singleton. */
/*
retcode = DDS_DomainParticipantFactory_finalize_instance();
if (retcode != DDS_RETCODE_OK) {
printf("finalize_instance error %d\n", retcode);
status = -1;
}
*/
return status;
}
static int publisher_main(int domainId, int sample_count)
{
DDS_DomainParticipant *participant = NULL;
DDS_Publisher *publisher = NULL;
DDS_Topic *topic = NULL;
DDS_DataWriter *writer = NULL;
asyncDataWriter *async_writer = NULL;
async *instance = NULL;
DDS_ReturnCode_t retcode;
DDS_InstanceHandle_t instance_handle = DDS_HANDLE_NIL;
const char *type_name = NULL;
int count = 0;
struct DDS_Duration_t send_period = {0,100000000};
/* struct DDS_DataWriterQos datawriter_qos = DDS_DataWriterQos_INITIALIZER;*/
/* To customize participant QoS, use
the configuration file USER_QOS_PROFILES.xml */
participant = DDS_DomainParticipantFactory_create_participant(
DDS_TheParticipantFactory, domainId, &DDS_PARTICIPANT_QOS_DEFAULT,
NULL /* listener */, DDS_STATUS_MASK_NONE);
if (participant == NULL) {
printf("create_participant error\n");
publisher_shutdown(participant);
return -1;
}
/* To customize publisher QoS, use
the configuration file USER_QOS_PROFILES.xml */
publisher = DDS_DomainParticipant_create_publisher(
participant, &DDS_PUBLISHER_QOS_DEFAULT, NULL /* listener */,
DDS_STATUS_MASK_NONE);
if (publisher == NULL) {
printf("create_publisher error\n");
publisher_shutdown(participant);
return -1;
}
/* Register type before creating topic */
type_name = asyncTypeSupport_get_type_name();
retcode = asyncTypeSupport_register_type(
participant, type_name);
if (retcode != DDS_RETCODE_OK) {
printf("register_type error %d\n", retcode);
publisher_shutdown(participant);
return -1;
}
/* To customize topic QoS, use
the configuration file USER_QOS_PROFILES.xml */
topic = DDS_DomainParticipant_create_topic(
participant, "Example async",
type_name, &DDS_TOPIC_QOS_DEFAULT, NULL /* listener */,
DDS_STATUS_MASK_NONE);
if (topic == NULL) {
printf("create_topic error\n");
publisher_shutdown(participant);
return -1;
}
/* To customize data writer QoS, use
the configuration file USER_QOS_PROFILES.xml */
writer = DDS_Publisher_create_datawriter(
publisher, topic,
&DDS_DATAWRITER_QOS_DEFAULT, NULL /* listener */, DDS_STATUS_MASK_NONE);
if (writer == NULL) {
printf("create_datawriter error\n");
publisher_shutdown(participant);
return -1;
}
/* If you want to change the DataWriter's QoS programmatically rather than
* using the XML file, you will need to add the following lines to your
* code and comment out the create_datawriter call above.
*
* In this case, we set the publish mode qos to asynchronous publish mode,
* which enables asynchronous publishing. We also set the flow controller
* to be the fixed rate flow controller, and we increase the history depth.
*/
/*
/* Start changes for Asynchronous_Publication */
/* Get default datawriter QoS to customize */
/* retcode = DDS_Publisher_get_default_datawriter_qos(publisher, &datawriter_qos);
if (retcode != DDS_RETCODE_OK) {
printf("get_default_datawriter_qos error\n");
return -1;
}
*/ /* Since samples are only being sent once per second, datawriter will need
to keep them on queue. History defaults to only keeping the last
sample enqueued, so we increase that here.
*/
/* datawriter_qos.history.depth = 12;
*/ /* Set flowcontroller for datawriter */
/* datawriter_qos.publish_mode.kind = DDS_ASYNCHRONOUS_PUBLISH_MODE_QOS;
datawriter_qos.publish_mode.flow_controller_name = DDS_FIXED_RATE_FLOW_CONTROLLER_NAME;
*/ /* To create datawriter with default QoS, use DDS_DATAWRITER_QOS_DEFAULT
instead of datawriter_qos */
/* writer = DDS_Publisher_create_datawriter(
publisher, topic,
&datawriter_qos, NULL, DDS_STATUS_MASK_NONE);
if (writer == NULL) {
printf("create_datawriter error\n");
publisher_shutdown(participant);
return -1;
}
*/
async_writer = asyncDataWriter_narrow(writer);
if (async_writer == NULL) {
printf("DataWriter narrow error\n");
publisher_shutdown(participant);
return -1;
}
/* Create data sample for writing */
instance = asyncTypeSupport_create_data_ex(DDS_BOOLEAN_TRUE);
if (instance == NULL) {
printf("asyncTypeSupport_create_data error\n");
publisher_shutdown(participant);
return -1;
}
/* For a data type that has a key, if the same instance is going to be
written multiple times, initialize the key here
and register the keyed instance prior to writing */
/*
instance_handle = asyncDataWriter_register_instance(
async_writer, instance);
*/
/* Main loop */
for (count=0; (sample_count == 0) || (count < sample_count); ++count) {
printf("Writing async, count %d\n", count);
/* Modify the data to be written here */
/* send count as data. */
instance->x = count;
/* Write data */
retcode = asyncDataWriter_write(
async_writer, instance, &instance_handle);
if (retcode != DDS_RETCODE_OK) {
printf("write error %d\n", retcode);
}
NDDS_Utility_sleep(&send_period);
}
/* Changes for Asynchronous_Publication */
/* Give time for publisher to send out last few samples */
send_period.sec = 1;
NDDS_Utility_sleep(&send_period);
/*
retcode = asyncDataWriter_unregister_instance(
async_writer, instance, &instance_handle);
if (retcode != DDS_RETCODE_OK) {
printf("unregister instance error %d\n", retcode);
}
*/
/* Delete data sample */
retcode = asyncTypeSupport_delete_data_ex(instance, DDS_BOOLEAN_TRUE);
if (retcode != DDS_RETCODE_OK) {
printf("asyncTypeSupport_delete_data error %d\n", retcode);
}
/* Cleanup and delete delete all entities */
return publisher_shutdown(participant);
}
#if defined(RTI_WINCE)
int wmain(int argc, wchar_t** argv)
{
int domainId = 0;
int sample_count = 0; /* infinite loop */
if (argc >= 2) {
domainId = _wtoi(argv[1]);
}
if (argc >= 3) {
sample_count = _wtoi(argv[2]);
}
/* Uncomment this to turn on additional logging
NDDS_Config_Logger_set_verbosity_by_category(
NDDS_Config_Logger_get_instance(),
NDDS_CONFIG_LOG_CATEGORY_API,
NDDS_CONFIG_LOG_VERBOSITY_STATUS_ALL);
*/
return publisher_main(domainId, sample_count);
}
#elif !(defined(RTI_VXWORKS) && !defined(__RTP__)) && !defined(RTI_PSOS)
int main(int argc, char *argv[])
{
int domainId = 0;
int sample_count = 0; /* infinite loop */
if (argc >= 2) {
domainId = atoi(argv[1]);
}
if (argc >= 3) {
sample_count = atoi(argv[2]);
}
/* Uncomment this to turn on additional logging
NDDS_Config_Logger_set_verbosity_by_category(
NDDS_Config_Logger_get_instance(),
NDDS_CONFIG_LOG_CATEGORY_API,
NDDS_CONFIG_LOG_VERBOSITY_STATUS_ALL);
*/
return publisher_main(domainId, sample_count);
}
#endif
#ifdef RTI_VX653
const unsigned char* __ctype = NULL;
void usrAppInit ()
{
#ifdef USER_APPL_INIT
USER_APPL_INIT; /* for backwards compatibility */
#endif
/* add application specific code here */
taskSpawn("pub", RTI_OSAPI_THREAD_PRIORITY_NORMAL, 0x8, 0x150000, (FUNCPTR)publisher_main, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
}
#endif
| c |
rticonnextdds-examples | data/projects/rticonnextdds-examples/asynchronous_publication/c/async_subscriber.c | /*******************************************************************************
(c) 2005-2014 Copyright, Real-Time Innovations, Inc. All rights reserved.
RTI grants Licensee a license to use, modify, compile, and create derivative
works of the Software. Licensee has the right to distribute object form only
for use with RTI products. The Software is provided "as is", with no warranty
of any type, including any warranty for fitness for any purpose. RTI is under
no obligation to maintain or support the Software. RTI shall not be liable for
any incidental or consequential damages arising out of the use or inability to
use the software.
******************************************************************************/
/* async_subscriber.c
A subscription example
This file is derived from code automatically generated by the rtiddsgen
command:
rtiddsgen -language C -example <arch> async.idl
Example subscription of type async automatically generated by
'rtiddsgen'. To test them, follow these steps:
(1) Compile this file and the example publication.
(2) Start the subscription with the command
objs/<arch>/async_subscriber <domain_id> <sample_count>
(3) Start the publication with the command
objs/<arch>/async_publisher <domain_id> <sample_count>
(4) [Optional] Specify the list of discovery initial peers and
multicast receive addresses via an environment variable or a file
(in the current working directory) called NDDS_DISCOVERY_PEERS.
You can run any number of publishers and subscribers programs, and can
add and remove them dynamically from the domain.
Example:
To run the example application on domain <domain_id>:
On UNIX systems:
objs/<arch>/async_publisher <domain_id>
objs/<arch>/async_subscriber <domain_id>
On Windows systems:
objs\<arch>\async_publisher <domain_id>
objs\<arch>\async_subscriber <domain_id>
modification history
------------ -------
*/
#include <stdio.h>
#include <stdlib.h>
#include "ndds/ndds_c.h"
#include "async.h"
#include "asyncSupport.h"
/* Changes for Asynchronous_Publication*/
/* For timekeeping */
#include <time.h>
clock_t init;
void asyncListener_on_requested_deadline_missed(
void* listener_data,
DDS_DataReader* reader,
const struct DDS_RequestedDeadlineMissedStatus *status)
{
}
void asyncListener_on_requested_incompatible_qos(
void* listener_data,
DDS_DataReader* reader,
const struct DDS_RequestedIncompatibleQosStatus *status)
{
}
void asyncListener_on_sample_rejected(
void* listener_data,
DDS_DataReader* reader,
const struct DDS_SampleRejectedStatus *status)
{
}
void asyncListener_on_liveliness_changed(
void* listener_data,
DDS_DataReader* reader,
const struct DDS_LivelinessChangedStatus *status)
{
}
void asyncListener_on_sample_lost(
void* listener_data,
DDS_DataReader* reader,
const struct DDS_SampleLostStatus *status)
{
}
void asyncListener_on_subscription_matched(
void* listener_data,
DDS_DataReader* reader,
const struct DDS_SubscriptionMatchedStatus *status)
{
}
void asyncListener_on_data_available(
void* listener_data,
DDS_DataReader* reader)
{
asyncDataReader *async_reader = NULL;
struct asyncSeq data_seq = DDS_SEQUENCE_INITIALIZER;
struct DDS_SampleInfoSeq info_seq = DDS_SEQUENCE_INITIALIZER;
DDS_ReturnCode_t retcode;
int i;
async_reader = asyncDataReader_narrow(reader);
if (async_reader == NULL) {
printf("DataReader narrow error\n");
return;
}
retcode = asyncDataReader_take(
async_reader,
&data_seq, &info_seq, DDS_LENGTH_UNLIMITED,
DDS_ANY_SAMPLE_STATE, DDS_ANY_VIEW_STATE, DDS_ANY_INSTANCE_STATE);
if (retcode == DDS_RETCODE_NO_DATA) {
return;
} else if (retcode != DDS_RETCODE_OK) {
printf("take error %d\n", retcode);
return;
}
for (i = 0; i < asyncSeq_get_length(&data_seq); ++i) {
if (DDS_SampleInfoSeq_get_reference(&info_seq, i)->valid_data) {
/* Start changes for Asynchronous_Publication */
/* print the time we get each sample. */
double elapsed_ticks = clock() - init;
double elapsed_secs = elapsed_ticks/CLOCKS_PER_SEC;
printf("@ t=%.2fs, got x = %d\n",
elapsed_secs, asyncSeq_get_reference(&data_seq, i)->x);
/* End changes for Asynchronous_Publication */
}
}
retcode = asyncDataReader_return_loan(
async_reader,
&data_seq, &info_seq);
if (retcode != DDS_RETCODE_OK) {
printf("return loan error %d\n", retcode);
}
}
/* Delete all entities */
static int subscriber_shutdown(
DDS_DomainParticipant *participant)
{
DDS_ReturnCode_t retcode;
int status = 0;
if (participant != NULL) {
retcode = DDS_DomainParticipant_delete_contained_entities(participant);
if (retcode != DDS_RETCODE_OK) {
printf("delete_contained_entities error %d\n", retcode);
status = -1;
}
retcode = DDS_DomainParticipantFactory_delete_participant(
DDS_TheParticipantFactory, participant);
if (retcode != DDS_RETCODE_OK) {
printf("delete_participant error %d\n", retcode);
status = -1;
}
}
/* RTI Connext provides the finalize_instance() method on
domain participant factory for users who want to release memory used
by the participant factory. Uncomment the following block of code for
clean destruction of the singleton. */
/*
retcode = DDS_DomainParticipantFactory_finalize_instance();
if (retcode != DDS_RETCODE_OK) {
printf("finalize_instance error %d\n", retcode);
status = -1;
}
*/
return status;
}
static int subscriber_main(int domainId, int sample_count)
{
DDS_DomainParticipant *participant = NULL;
DDS_Subscriber *subscriber = NULL;
DDS_Topic *topic = NULL;
struct DDS_DataReaderListener reader_listener =
DDS_DataReaderListener_INITIALIZER;
DDS_DataReader *reader = NULL;
DDS_ReturnCode_t retcode;
const char *type_name = NULL;
int count = 0;
struct DDS_Duration_t poll_period = {4,0};
/* Changes for Asynchronous_Publication */
/* for timekeeping */
init = clock();
/* To customize participant QoS, use
the configuration file USER_QOS_PROFILES.xml */
participant = DDS_DomainParticipantFactory_create_participant(
DDS_TheParticipantFactory, domainId, &DDS_PARTICIPANT_QOS_DEFAULT,
NULL /* listener */, DDS_STATUS_MASK_NONE);
if (participant == NULL) {
printf("create_participant error\n");
subscriber_shutdown(participant);
return -1;
}
/* To customize subscriber QoS, use
the configuration file USER_QOS_PROFILES.xml */
subscriber = DDS_DomainParticipant_create_subscriber(
participant, &DDS_SUBSCRIBER_QOS_DEFAULT, NULL /* listener */,
DDS_STATUS_MASK_NONE);
if (subscriber == NULL) {
printf("create_subscriber error\n");
subscriber_shutdown(participant);
return -1;
}
/* Register the type before creating the topic */
type_name = asyncTypeSupport_get_type_name();
retcode = asyncTypeSupport_register_type(participant, type_name);
if (retcode != DDS_RETCODE_OK) {
printf("register_type error %d\n", retcode);
subscriber_shutdown(participant);
return -1;
}
/* To customize topic QoS, use
the configuration file USER_QOS_PROFILES.xml */
topic = DDS_DomainParticipant_create_topic(
participant, "Example async",
type_name, &DDS_TOPIC_QOS_DEFAULT, NULL /* listener */,
DDS_STATUS_MASK_NONE);
if (topic == NULL) {
printf("create_topic error\n");
subscriber_shutdown(participant);
return -1;
}
/* Set up a data reader listener */
reader_listener.on_requested_deadline_missed =
asyncListener_on_requested_deadline_missed;
reader_listener.on_requested_incompatible_qos =
asyncListener_on_requested_incompatible_qos;
reader_listener.on_sample_rejected =
asyncListener_on_sample_rejected;
reader_listener.on_liveliness_changed =
asyncListener_on_liveliness_changed;
reader_listener.on_sample_lost =
asyncListener_on_sample_lost;
reader_listener.on_subscription_matched =
asyncListener_on_subscription_matched;
reader_listener.on_data_available =
asyncListener_on_data_available;
/* To customize data reader QoS, use
the configuration file USER_QOS_PROFILES.xml */
reader = DDS_Subscriber_create_datareader(
subscriber, DDS_Topic_as_topicdescription(topic),
&DDS_DATAREADER_QOS_DEFAULT, &reader_listener, DDS_STATUS_MASK_ALL);
if (reader == NULL) {
printf("create_datareader error\n");
subscriber_shutdown(participant);
return -1;
}
/* Main loop */
for (count=0; (sample_count == 0) || (count < sample_count); ++count) {
printf("async subscriber sleeping for %d sec...\n",
poll_period.sec);
NDDS_Utility_sleep(&poll_period);
}
/* Cleanup and delete all entities */
return subscriber_shutdown(participant);
}
#if defined(RTI_WINCE)
int wmain(int argc, wchar_t** argv)
{
int domainId = 0;
int sample_count = 0; /* infinite loop */
if (argc >= 2) {
domainId = _wtoi(argv[1]);
}
if (argc >= 3) {
sample_count = _wtoi(argv[2]);
}
/* Uncomment this to turn on additional logging
NDDS_Config_Logger_set_verbosity_by_category(
NDDS_Config_Logger_get_instance(),
NDDS_CONFIG_LOG_CATEGORY_API,
NDDS_CONFIG_LOG_VERBOSITY_STATUS_ALL);
*/
return subscriber_main(domainId, sample_count);
}
#elif !(defined(RTI_VXWORKS) && !defined(__RTP__)) && !defined(RTI_PSOS)
int main(int argc, char *argv[])
{
int domainId = 0;
int sample_count = 0; /* infinite loop */
if (argc >= 2) {
domainId = atoi(argv[1]);
}
if (argc >= 3) {
sample_count = atoi(argv[2]);
}
/* Uncomment this to turn on additional logging
NDDS_Config_Logger_set_verbosity_by_category(
NDDS_Config_Logger_get_instance(),
NDDS_CONFIG_LOG_CATEGORY_API,
NDDS_CONFIG_LOG_VERBOSITY_STATUS_ALL);
*/
return subscriber_main(domainId, sample_count);
}
#endif
#ifdef RTI_VX653
const unsigned char* __ctype = NULL;
void usrAppInit ()
{
#ifdef USER_APPL_INIT
USER_APPL_INIT; /* for backwards compatibility */
#endif
/* add application specific code here */
taskSpawn("sub", RTI_OSAPI_THREAD_PRIORITY_NORMAL, 0x8, 0x150000, (FUNCPTR)subscriber_main, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
}
#endif
| c |
rticonnextdds-examples | data/projects/rticonnextdds-examples/asynchronous_publication/c++03/async_publisher.cxx | /*******************************************************************************
(c) 2005-2015 Copyright, Real-Time Innovations, Inc. All rights reserved.
RTI grants Licensee a license to use, modify, compile, and create derivative
works of the Software. Licensee has the right to distribute object form only
for use with RTI products. The Software is provided "as is", with no warranty
of any type, including any warranty for fitness for any purpose. RTI is under
no obligation to maintain or support the Software. RTI shall not be liable for
any incidental or consequential damages arising out of the use or inability to
use the software.
******************************************************************************/
#include <iostream>
#include "async.hpp"
#include <dds/dds.hpp>
#include <rti/pub/FlowController.hpp>
using namespace dds::core;
using namespace dds::core::policy;
using namespace rti::core::policy;
using namespace dds::domain;
using namespace dds::topic;
using namespace dds::pub;
using namespace dds::pub::qos;
using namespace rti::pub;
void publisher_main(int domain_id, int sample_count)
{
// To customize participant QoS, use file USER_QOS_PROFILES.xml
DomainParticipant participant (domain_id);
// To customize topic QoS, use file USER_QOS_PROFILES.xml
Topic<async> topic (participant, "Example async");
// Retrieve the default DataWriter QoS, from USER_QOS_PROFILES.xml
DataWriterQos writer_qos = QosProvider::Default().datawriter_qos();
// If you want to change the DataWriter's QoS programmatically rather than
// using the XML file, uncomment the following lines.
//
// In this case, we set the publish mode QoS to asynchronous publish mode,
// which enables asynchronous publishing. We also set the flow controller
// to be the fixed rate flow controller, and we increase the history depth.
// writer_qos << Reliability::Reliable(Duration(60));
// DataWriterProtocol writer_protocol_qos;
// RtpsReliableWriterProtocol rtps_writer_protocol;
// rtps_writer_protocol.min_send_window_size(50);
// rtps_writer_protocol.max_send_window_size(50);
// writer_protocol_qos.rtps_reliable_writer(rtps_writer_protocol);
// writer_qos << writer_protocol_qos;
// Since samples are only being sent once per second, DataWriter will need
// to keep them on queue. History defaults to only keeping the last
// sample enqueued, so we increase that here.
// writer_qos << History::KeepLast(12);
// Set flowcontroller for DataWriter
// writer_qos << PublishMode::Asynchronous(FlowController::FIXED_RATE_NAME);
// Create the DataWriter with a QoS.
DataWriter<async> writer (Publisher(participant), topic, writer_qos);
// Create data sample for writing
async instance;
// For a data type that has a key, if the same instance is going to be
// written multiple times, initialize the key here
// and register the keyed instance prior to writing.
// InstanceHandle instance_handle = writer.register_instance(instance);
// Main loop
for (int count = 0; (sample_count == 0) || (count < sample_count); ++count){
std::cout << "Writing async, count " << count << std::endl;
// Send count as data
instance.x(count);
// Send it, if using instance_handle:
// writer.write(instance, instance_handle);
writer.write(instance);
rti::util::sleep(Duration(0,100000000));
}
// If using instance_handle, unregister it.
//writer.unregister_instance(instance_handle);
}
int main(int argc, char* argv[])
{
int domain_id = 0;
int sample_count = 0; /* infinite loop */
if (argc >= 2) {
domain_id = atoi(argv[1]);
}
if (argc >= 3) {
sample_count = atoi(argv[2]);
}
// To turn on additional logging, include <rti/config/Logger.hpp> and
// uncomment the following line:
// rti::config::Logger::instance().verbosity(rti::config::Verbosity::STATUS_ALL);
try {
publisher_main(domain_id, sample_count);
} catch (std::exception ex) {
std::cout << "Exception caught: " << ex.what() << std::endl;
return -1;
}
return 0;
}
| cxx |
rticonnextdds-examples | data/projects/rticonnextdds-examples/asynchronous_publication/c++03/async_subscriber.cxx | /*******************************************************************************
(c) 2005-2015 Copyright, Real-Time Innovations, Inc. All rights reserved.
RTI grants Licensee a license to use, modify, compile, and create derivative
works of the Software. Licensee has the right to distribute object form only
for use with RTI products. The Software is provided "as is", with no warranty
of any type, including any warranty for fitness for any purpose. RTI is under
no obligation to maintain or support the Software. RTI shall not be liable for
any incidental or consequential damages arising out of the use or inability to
use the software.
******************************************************************************/
#include <iostream>
#include <ctime>
#include "async.hpp"
#include <dds/dds.hpp>
#include <rti/core/ListenerBinder.hpp>
using namespace dds::core;
using namespace dds::core::policy;
using namespace dds::domain;
using namespace dds::topic;
using namespace dds::sub;
using namespace dds::sub::qos;
// For timekeeping
clock_t InitTime;
class AsyncListener : public NoOpDataReaderListener<async> {
public:
void on_data_available(DataReader<async>& reader)
{
LoanedSamples<async> samples = reader.take();
for (LoanedSamples<async>::iterator sampleIt = samples.begin();
sampleIt != samples.end();
++sampleIt) {
// Print the time we get each sample.
if (sampleIt->info().valid()) {
double elapsed_ticks = clock() - InitTime;
double elapsed_secs = elapsed_ticks / CLOCKS_PER_SEC;
std::cout << "@ t=" << elapsed_secs << "s"
<< ", got x = " << sampleIt->data().x() << std::endl;
}
}
}
};
void subscriber_main(int domain_id, int sample_count)
{
// For timekeeping
InitTime = clock();
// To customize the paritcipant QoS, use the file USER_QOS_PROFILES.xml
DomainParticipant participant (domain_id);
// To customize the topic QoS, use the file USER_QOS_PROFILES.xml
Topic<async> topic (participant, "Example async");
// Retrieve the default DataReader QoS, from USER_QOS_PROFILES.xml
DataReaderQos reader_qos = QosProvider::Default().datareader_qos();
// If you want to change the DataWriter's QoS programmatically rather than
// using the XML file, uncomment the following lines.
// reader_qos << Reliability::Reliable(Duration(60));
// reader_qos << History::KeepAll();
// Create a DataReader with a QoS
DataReader<async> reader (Subscriber(participant), topic, reader_qos);
// Create a data reader listener using ListenerBinder, a RAII utility that
// will take care of reseting it from the reader and deleting it.
rti::core::ListenerBinder< DataReader<async> > scoped_listener =
rti::core::bind_and_manage_listener(
reader,
new AsyncListener,
dds::core::status::StatusMask::data_available());
// Main loop
for (int count = 0; (sample_count == 0) || (count < sample_count); ++count){
std::cout << "async subscriber sleeping for 4 sec..." << std::endl;
rti::util::sleep(Duration(4));
}
}
int main(int argc, char* argv[])
{
int domain_id = 0;
int sample_count = 0; // Infinite loop
if (argc >= 2) {
domain_id = atoi(argv[1]);
}
if (argc >= 3) {
sample_count = atoi(argv[2]);
}
// To turn on additional logging, include <rti/config/Logger.hpp> and
// uncomment the following line:
// rti::config::Logger::instance().verbosity(rti::config::Verbosity::STATUS_ALL);
try {
subscriber_main(domain_id, sample_count);
} catch (std::exception ex) {
std::cout << "Exception caught: " << ex.what() << std::endl;
return -1;
}
return 0;
}
| cxx |
rticonnextdds-examples | data/projects/rticonnextdds-examples/zero_copy/c++/zero_copy_subscriber.cxx | /*******************************************************************************
(c) 2005-2017 Copyright, Real-Time Innovations, Inc. All rights reserved.
RTI grants Licensee a license to use, modify, compile, and create derivative
works of the Software. Licensee has the right to distribute object form only
for use with RTI products. The Software is provided "as is", with no warranty
of any type, including any warranty for fitness for any purpose. RTI is under
no obligation to maintain or support 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 <cstdio>
#include <cstdlib>
#include <map>
#include <iostream>
#include <sstream>
#include "zero_copy.h"
#include "zero_copySupport.h"
#include "FrameSupport.h"
#include "ndds/ndds_cpp.h"
#include "ndds/ndds_namespace_cpp.h"
#include "ndds/clock/clock_highResolution.h"
#include "ndds/osapi/osapi_ntptime.h"
using namespace DDS;
struct CommandLineArguments {
public:
int domain_id;
int size;
int sample_count;
bool verbose;
CommandLineArguments() {
domain_id = 0;
sample_count = 1200;
size = 1048576;
verbose = false;
}
};
CommandLineArguments arg;
// Compute the latency with the given current_time and source_timestamp
static void compute_latency(
DDS_Duration_t &latency,
RTINtpTime current_time,
const DDS_Time_t &source_timestamp)
{
RTINtpTime source_time = RTI_NTP_TIME_ZERO;
// Convert DDS_Time_t format to RTINtpTime format
RTINtpTime_packFromNanosec(
source_time,
source_timestamp.sec,
source_timestamp.nanosec);
// Compute the difference and store in current_time
RTINtpTime_decrement(current_time, source_time);
// Convert RTINtpTime format to DDS_Duration_t format
RTINtpTime_unpackToNanosec(latency.sec, latency.nanosec, current_time);
}
// Get the shared memory key from the publication data property
static int lookup_shmem_key_property(DDS::PropertyQosPolicy& property)
{
const DDS::Property_t *p = DDS::PropertyQosPolicyHelper::lookup_property(
property,
"shmem_key");
if (p == NULL) {
return -1;
}
int key;
std::istringstream str_to_key(p->value);
str_to_key >> key;
return key;
}
bool operator<(const DDS::GUID_t& a, const DDS::GUID_t& b)
{
return DDS_GUID_compare(&a, &b) < 0;
}
bool operator==(const DDS::GUID_t& a, const DDS::GUID_t& b)
{
return DDS_GUID_equals(&a, &b) == DDS_BOOLEAN_TRUE;
}
class ShmemKeyTrackingReaderListener : public DDSDataReaderListener {
public:
~ShmemKeyTrackingReaderListener()
{
for (FrameSetViewMap::iterator iter = frame_set_views.begin();
iter != frame_set_views.end(); ++iter) {
delete iter->second;
}
}
FrameSetView* get_frame_set_view(const DDS::GUID_t& publication_guid) const
{
FrameSetViewMap::const_iterator key_it = frame_set_views.find(
publication_guid);
if (key_it == frame_set_views.end()) {
return NULL;
}
return key_it->second;
}
size_t get_frame_set_view_count() const
{
return frame_set_views.size();
}
private:
typedef std::map<DDS::GUID_t, FrameSetView*> FrameSetViewMap;
// Map to store the frame_set_views created for each matched frame_set
FrameSetViewMap frame_set_views;
void on_subscription_matched(
DDSDataReader* reader,
const DDS_SubscriptionMatchedStatus& status) /* override */
{
try {
DDS::PublicationBuiltinTopicData publication_data;
if (reader->get_matched_publication_data(
publication_data,
status.last_publication_handle) != DDS_RETCODE_OK) {
return;
}
int key = lookup_shmem_key_property(publication_data.property);
if (key == -1) {
return;
}
DDS::GUID_t publication_guid;
DDS_BuiltinTopicKey_to_guid(
&publication_data.key,
&publication_guid);
if (frame_set_views.find(publication_guid)
== frame_set_views.end()){
// Create the frame_set_view with the key and size. This frame
// set view attaches to the shared memory segment created by the
// frame set managed by the matched DataWriter
FrameSetView *frame_set_view = new FrameSetView(key, arg.size);
frame_set_views[publication_guid] = frame_set_view;
} else {
std::cout << "Unable to track the key " << key << std::endl;
}
} catch (...) {
std::cout << "Exception in on_subscription_matched. " << std::endl;
}
}
};
class ZeroCopyListener : public ShmemKeyTrackingReaderListener {
public:
virtual void on_requested_deadline_missed(
DataReader* /*reader*/,
const RequestedDeadlineMissedStatus& /*status*/) {}
virtual void on_requested_incompatible_qos(
DataReader* /*reader*/,
const RequestedIncompatibleQosStatus& /*status*/) {}
virtual void on_sample_rejected(
DataReader* /*reader*/,
const SampleRejectedStatus& /*status*/) {}
virtual void on_liveliness_changed(
DataReader* /*reader*/,
const LivelinessChangedStatus& /*status*/) {}
virtual void on_sample_lost(
DataReader* /*reader*/,
const SampleLostStatus& /*status*/) {}
virtual void on_data_available(DataReader* reader);
ZeroCopyListener() :
total_latency(DDS_DURATION_ZERO),
received_frames(0),
shutdown_application(false)
{
clock = RTIHighResolutionClock_new();
}
~ZeroCopyListener()
{
RTIHighResolutionClock_delete(clock);
}
bool start_shutdown()
{
return shutdown_application;
}
private:
// Sum of frame latency
DDS_Duration_t total_latency;
// Total number of received frames
int received_frames;
// Used for getting system time
RTIClock *clock;
RTINtpTime previous_print_time;
bool shutdown_application;
// Prints average latency in micro seconds
void print_average_latency()
{
std::cout << "Average latency: "
<< ((total_latency.sec * 1000000)
+ (total_latency.nanosec / 1000)) / received_frames
<< " microseconds" << std::endl;
}
};
void ZeroCopyListener::on_data_available(DataReader* reader)
{
ZeroCopyDataReader *ZeroCopy_reader = ZeroCopyDataReader::narrow(reader);
if (ZeroCopy_reader == NULL) {
std::cout << "DataReader narrow error" << std::endl;
return;
}
ZeroCopySeq data_seq;
SampleInfoSeq info_seq;
ReturnCode_t retcode;
retcode = ZeroCopy_reader->take(
data_seq, info_seq, LENGTH_UNLIMITED,
ANY_SAMPLE_STATE, ANY_VIEW_STATE, ANY_INSTANCE_STATE);
if (retcode == RETCODE_NO_DATA) {
return;
} else if (retcode != RETCODE_OK) {
std::cout << "take error "<< retcode << std::endl;
return;
}
unsigned int received_checksum = 0, computed_checksum = 0;
RTINtpTime current_time = RTI_NTP_TIME_ZERO;
DDS_Duration_t latency;
for (int i = 0; i < data_seq.length(); ++i) {
if (info_seq[i].valid_data) {
// Get the frame_set_view associated with the virtual guid
// This is done because there may be multiple Publishers
// publishing frames. Each publisher creates its own
// shared memory segement to store frames and is identified by
// info_seq[i].publication_virtual_guid
FrameSetView *frame_set_view = get_frame_set_view(
info_seq[i].publication_virtual_guid);
if (frame_set_view == NULL) {
std::cout << "Received data from an un recognized frame "
"writer" << std::endl;
continue;
}
// Get the frame checksum from the sample
received_checksum = data_seq[i].checksum;
// Get the frame from the shared memory segment
// at the provided index
const Frame *frame = (*frame_set_view)[data_seq[i].index];
// Compute the checksum of the frame
// We only compute the checksum of the first 4 bytes. These
// are the bytes that we change in each frame for this example
// We dont compute CRC for the whole frame because it would add
// a latency component not due to the middleware. Real
// application may compute CRC differently
computed_checksum = RTIOsapiUtility_crc32(
frame->get_buffer(),
sizeof(int),
0);
// Validate the computed checksum with the checksum sent by the
// DataWriter
if (computed_checksum != received_checksum) {
std::cout << "Checksum NOT OK" << std::endl;
}
// Compute the latency from the source time
clock->getTime(clock, ¤t_time);
compute_latency(latency, current_time, info_seq[i].source_timestamp);
// Keep track of total latency for computing averages
total_latency = total_latency + latency;
received_frames++;
if (arg.verbose) {
std::cout << "Received frame " << received_frames
<< " from DataWriter with key "
<< frame_set_view->get_key() << " with checksum: "
<< frame->checksum << std::endl;
}
if (received_frames == 1) {
previous_print_time = current_time;
}
if (((current_time.sec - previous_print_time.sec) >= 1)
|| (received_frames == arg.sample_count)) {
previous_print_time = current_time;
print_average_latency();
}
}
}
retcode = ZeroCopy_reader->return_loan(data_seq, info_seq);
if (retcode != RETCODE_OK) {
std::cout << "return loan error " << retcode << std::endl;
}
if ((received_frames == arg.sample_count) && (!shutdown_application)) {
std::cout << "Received " << received_frames << " frames " << std::endl;
shutdown_application = true;
}
}
// Delete all entities
static int subscriber_shutdown(
DomainParticipant *participant)
{
ReturnCode_t retcode;
int status = 0;
if (participant != NULL) {
retcode = participant->delete_contained_entities();
if (retcode != RETCODE_OK) {
std::cout << "delete_contained_entities error " << retcode
<< std::endl;
status = -1;
}
retcode = TheParticipantFactory->delete_participant(participant);
if (retcode != RETCODE_OK) {
std::cout << "delete_participant error " << retcode << std::endl;
status = -1;
}
}
// RTI Connext provides the finalize_instance() method on
// domain participant factory for people who want to release memory used
// by the participant factory. Uncomment the following block of code for
// clean destruction of the singleton.
// retcode = DomainParticipantFactory::finalize_instance();
// if (retcode != RETCODE_OK) {
// std::cout << "finalize_instance error " << retcode << std::endl;
// status = -1;
// }
return status;
}
extern "C" int subscriber_main()
{
// To customize the participant QoS, use
// the configuration file USER_QOS_PROFILES.xml
DomainParticipant *participant = TheParticipantFactory->create_participant(
arg.domain_id, PARTICIPANT_QOS_DEFAULT,
NULL /* listener */, STATUS_MASK_NONE);
if (participant == NULL) {
std::cout << "create_participant error" << std::endl;
subscriber_shutdown(participant);
return -1;
}
// To customize the subscriber QoS, use
// the configuration file USER_QOS_PROFILES.xml
Subscriber *subscriber = participant->create_subscriber(
SUBSCRIBER_QOS_DEFAULT, NULL /* listener */, STATUS_MASK_NONE);
if (subscriber == NULL) {
std::cout << "create_subscriber error" << std::endl;
subscriber_shutdown(participant);
return -1;
}
// Register the type before creating the topic
const char *type_name = ZeroCopyTypeSupport::get_type_name();
ReturnCode_t retcode = ZeroCopyTypeSupport::register_type(
participant, type_name);
if (retcode != RETCODE_OK) {
std::cout << "register_type error " << retcode << std::endl;
subscriber_shutdown(participant);
return -1;
}
// To customize the topic QoS, use
// the configuration file USER_QOS_PROFILES.xml
Topic *topic = participant->create_topic(
"Example ZeroCopy",
type_name, TOPIC_QOS_DEFAULT, NULL /* listener */,
STATUS_MASK_NONE);
if (topic == NULL) {
std::cout << "create_topic error" << std::endl;
subscriber_shutdown(participant);
return -1;
}
// Create a data reader listener
ZeroCopyListener *reader_listener = new ZeroCopyListener();
// To customize the data reader QoS, use
// the configuration file USER_QOS_PROFILES.xml
DataReader *reader = subscriber->create_datareader(
topic, DATAREADER_QOS_DEFAULT, reader_listener,
STATUS_MASK_ALL);
if (reader == NULL) {
std::cout << "create_datareader error" << std::endl;
subscriber_shutdown(participant);
delete reader_listener;
return -1;
}
// Main loop
std::cout << "ZeroCopy subscriber waiting to receive samples..."
<< std::endl;
Duration_t receive_period = {4,0};
while (!reader_listener->start_shutdown()) {
NDDSUtility::sleep(receive_period);
};
std::cout << "Subscriber application shutting down" << std::endl;
// Delete all entities
int status = subscriber_shutdown(participant);
delete reader_listener;
return status;
}
void ZeroCopy_print_usage()
{
std::cout << "Usage: ZeroCopy_subscriber [options]" << std::endl;
std::cout << "Where arguments are:" << std::endl;
std::cout << " -h Shows this page" << std::endl;
std::cout << " -d <domain_id> Sets the domain id [default = 0]" << std::endl;
std::cout << " -sc <sample count> Sets the number of frames to receive "
"[default = 1200]" << std::endl;
std::cout << " -s <buffer size> Sets the payload size of the frame in bytes "
"[default = 1048576 (1MB)]" << std::endl;
std::cout << " -v Displays checksum and computed latency of "
"each received frame " << std::endl;
}
int main(int argc, char *argv[])
{
// Parse the optional arguments
for (int i = 1; i < argc; ++i) {
if (!strncmp(argv[i], "-h", 2)) {
ZeroCopy_print_usage();
return 0;
} else if (!strncmp(argv[i], "-d", 2)) {
char *ptr;
arg.domain_id = strtol(argv[++i], &ptr, 10);
} else if (!strncmp(argv[i], "-sc", 3)) {
char *ptr;
arg.sample_count = strtol(argv[++i], &ptr, 10);
} else if (!strncmp(argv[i], "-s", 2)) {
char *ptr;
arg.size = strtol(argv[++i], &ptr, 10);
} else if (!strncmp(argv[i], "-v", 2)) {
arg.verbose = true;
} else {
std::cout << "Invalid command-line parameter: " << argv[i] << std::endl;
return -1;
}
}
std::cout << "Running using:" << std::endl;
std::cout << " Domain ID: " << arg.domain_id << std::endl;
std::cout << " Sample Count: " << arg.sample_count << std::endl;
std::cout << " Frame size: " << arg.size << " bytes" << std::endl;
// Uncomment this to turn on additional logging
// NDDSConfigLogger::get_instance()->
// set_verbosity_by_category(NDDS_CONFIG_LOG_CATEGORY_API,
// NDDS_CONFIG_LOG_VERBOSITY_STATUS_ALL);
return subscriber_main();
}
| cxx |
rticonnextdds-examples | data/projects/rticonnextdds-examples/zero_copy/c++/Frame.h | /*******************************************************************************
(c) 2005-2017 Copyright, Real-Time Innovations, Inc. All rights reserved.
RTI grants Licensee a license to use, modify, compile, and create derivative
works of the Software. Licensee has the right to distribute object form only
for use with RTI products. The Software is provided "as is", with no warranty
of any type, including any warranty for fitness for any purpose. RTI is under
no obligation to maintain or support the Software. RTI shall not be liable for
any incidental or consequential damages arising out of the use or inability to
use the software.
******************************************************************************/
struct Dimension {
int x;
int y;
};
class Frame {
public:
char* get_buffer();
const char* get_buffer() const;
int length;
unsigned int checksum;
Dimension dimension;
};
char* Frame::get_buffer()
{
return ((char *)this) + sizeof(Frame);
}
const char* Frame::get_buffer() const
{
return ((char *)this) + sizeof(Frame);
}
| h |
rticonnextdds-examples | data/projects/rticonnextdds-examples/zero_copy/c++/zero_copy_publisher.cxx | /*******************************************************************************
(c) 2005-2017 Copyright, Real-Time Innovations, Inc. All rights reserved.
RTI grants Licensee a license to use, modify, compile, and create derivative
works of the Software. Licensee has the right to distribute object form only
for use with RTI products. The Software is provided "as is", with no warranty
of any type, including any warranty for fitness for any purpose. RTI is under
no obligation to maintain or support the Software. RTI shall not be liable for
any incidental or consequential damages arising out of the use or inability to
use the software.
******************************************************************************/
#include <stdio.h>
#include <stdlib.h>
#include <iostream>
#include <sstream>
#include "zero_copy.h"
#include "zero_copySupport.h"
#include "FrameSupport.h"
#include "ndds/ndds_cpp.h"
#include "ndds/ndds_namespace_cpp.h"
#include "ndds/osapi/osapi_utility.h"
#include "ndds/clock/clock_highResolution.h"
#include "ndds/osapi/osapi_ntptime.h"
using namespace DDS;
struct CommandLineArguments {
int domain_id;
int frame_count;
int frame_rate;
int sample_count;
int key;
int size;
int dr_count;
bool verbose;
CommandLineArguments() {
domain_id = 0;
frame_count = 0;
frame_rate = 60;
sample_count = 1200;
key = -1;
size = 1048576;
dr_count = 1;
verbose = false;
}
};
static void set_current_timestamp(RTIClock *clock, DDS_Time_t ×tamp)
{
if (clock == NULL) {
std::cout << "Clock not available" << std::endl;
return;
}
RTINtpTime current_time = RTI_NTP_TIME_ZERO;
clock->getTime(clock, ¤t_time);
RTINtpTime_unpackToNanosec(
timestamp.sec,
timestamp.nanosec,
current_time);
}
static void add_shmem_key_property(DDS::PropertyQosPolicy& property, int key)
{
std::ostringstream key_to_str;
key_to_str << key;
DDS::PropertyQosPolicyHelper::assert_property(
property,
"shmem_key",
key_to_str.str().c_str(),
true);
}
static void fill_frame_data(Frame* frame)
{
char *buffer = frame->get_buffer();
int random_number = RTIOsapiUtility_rand();
memcpy(buffer, &random_number, sizeof(random_number));
// We dont compute CRC for the whole frame because it would add
// a latency component not due to the middleware. Real
// application may compute CRC differently
frame->checksum = RTIOsapiUtility_crc32(buffer, sizeof(random_number), 0);
}
// Delete all entities
static int publisher_shutdown(
DomainParticipant *participant)
{
ReturnCode_t retcode;
int status = 0;
if (participant != NULL) {
retcode = participant->delete_contained_entities();
if (retcode != RETCODE_OK) {
std::cout << "delete_contained_entities error " << retcode
<< std::endl;
status = -1;
}
retcode = TheParticipantFactory->delete_participant(participant);
if (retcode != RETCODE_OK) {
std::cout << "delete_participant error " << retcode << std::endl;
status = -1;
}
}
// RTI Connext provides finalize_instance() method on
// domain participant factory for people who want to release memory used
// by the participant factory. Uncomment the following block of code for
// clean destruction of the singleton.
//retcode = DomainParticipantFactory::finalize_instance();
//if (retcode != RETCODE_OK) {
// std::cout << "finalize_instance error " << retcode << std::endl;
// status = -1;
//}
return status;
}
extern "C" int publisher_main(CommandLineArguments arg)
{
// Creates a frame set in shared memory with the user provided settings
FrameSet frame_set(
arg.key, //shared memory key
arg.frame_count, //number of frames contained in the shared memory segment
arg.size //size of a frame
);
// To customize participant QoS, use
// the configuration file USER_QOS_PROFILES.xml
DomainParticipant *participant = TheParticipantFactory->create_participant(
arg.domain_id, PARTICIPANT_QOS_DEFAULT,
NULL /* listener */, STATUS_MASK_NONE);
if (participant == NULL) {
std::cout << "create_participant error" << std::endl;
publisher_shutdown(participant);
return -1;
}
// To customize publisher QoS, use
// the configuration file USER_QOS_PROFILES.xml
Publisher *publisher = participant->create_publisher(
PUBLISHER_QOS_DEFAULT, NULL /* listener */, STATUS_MASK_NONE);
if (publisher == NULL) {
std::cout << "create_publisher error" << std::endl;
publisher_shutdown(participant);
return -1;
}
// Register type before creating topic
const char *type_name = ZeroCopyTypeSupport::get_type_name();
ReturnCode_t retcode = ZeroCopyTypeSupport::register_type(
participant, type_name);
if (retcode != RETCODE_OK) {
std::cout << "register_type error " << retcode << std::endl;
publisher_shutdown(participant);
return -1;
}
// To customize topic QoS, use
// the configuration file USER_QOS_PROFILES.xml
Topic *topic = participant->create_topic(
"Example ZeroCopy",
type_name, TOPIC_QOS_DEFAULT, NULL /* listener */,
STATUS_MASK_NONE);
if (topic == NULL) {
std::cout << "create_topic error" << std::endl;
publisher_shutdown(participant);
return -1;
}
// To customize data writer QoS, use
// the configuration file USER_QOS_PROFILES.xml
DDS::DataWriterQos writer_qos;
publisher->get_default_datawriter_qos(writer_qos);
// The key identifying the shared memory segment containing the frames
// is sent to the Subscriber app so that it can attcah to it
add_shmem_key_property(writer_qos.property, arg.key);
DataWriter *writer = publisher->create_datawriter(
topic, writer_qos, NULL /* listener */,
STATUS_MASK_NONE);
if (writer == NULL) {
std::cout << "create_datawriter error" << std::endl;
publisher_shutdown(participant);
return -1;
}
ZeroCopyDataWriter *ZeroCopy_writer = ZeroCopyDataWriter::narrow(writer);
if (ZeroCopy_writer == NULL) {
std::cout << "DataWriter narrow error" << std::endl;
publisher_shutdown(participant);
return -1;
}
// Create data sample for writing
ZeroCopy *instance = ZeroCopyTypeSupport::create_data();
if (instance == NULL) {
std::cout << "ZeroCopyTypeSupport::create_data error" << std::endl;
publisher_shutdown(participant);
return -1;
}
// Waiting to discover the expected number of DataReaders
std::cout << "Waiting until " << arg.dr_count
<< " DataReaders are discovered" << std::endl;
DDS_PublicationMatchedStatus matchedStatus;
do {
writer->get_publication_matched_status(matchedStatus);
} while (matchedStatus.total_count < arg.dr_count);
// Configuring the send period with frame rate
Duration_t send_period = {0, 0};
send_period.sec = 0;
send_period.nanosec = 1000000000 / arg.frame_rate;
// Create a clock to get the write timestamp
RTIClock *clock = RTIHighResolutionClock_new();
if (clock == NULL) {
std::cout << "Failed to create the System clock" << std::endl;
ZeroCopyTypeSupport::delete_data(instance);
publisher_shutdown(participant);
return -1;
}
// Main loop
std::cout << "Going to send " << arg.sample_count << " frames at "
<< arg.frame_rate << " fps" << std::endl;
DDS_WriteParams_t write_params = DDS_WRITEPARAMS_DEFAULT;
int index = 0;
for (int count = 0; count < arg.sample_count; ++count) {
index = count % arg.frame_count;
// Setting the source_timestamp before the shared memory segment is
// updated
set_current_timestamp(clock, write_params.source_timestamp);
// Getting the frame at the desired index
Frame *frame = frame_set[index];
// Updating the frame with the desired data and setting the checksum
frame->length = arg.size;
frame->dimension.x = 800;
frame->dimension.y = 1600;
fill_frame_data(frame);
if (arg.verbose) {
std::cout << "Sending frame " << count + 1 << " with checksum: "
<< frame->checksum << std::endl;
}
// Sending the index and checksum
instance->index = index;
instance->checksum = frame->checksum;
retcode = ZeroCopy_writer->write_w_params(*instance, write_params);
if (retcode != RETCODE_OK) {
std::cout << "write error " << retcode << std::endl;
}
if ((count % arg.frame_rate) == (arg.frame_rate-1)) {
std::cout << "Writen " << count+1 <<" frames" << std::endl;
}
NDDSUtility::sleep(send_period);
}
std::cout << "Written " << arg.sample_count << " frames" << std::endl;
std::cout << "Publisher application shutting down" << std::endl;
RTIHighResolutionClock_delete(clock);
// Delete data sample
retcode = ZeroCopyTypeSupport::delete_data(instance);
if (retcode != RETCODE_OK) {
std::cout << "ZeroCopyTypeSupport::delete_data error " << retcode
<< std::endl;
}
// Delete all entities
return publisher_shutdown(participant);
}
void ZeroCopy_print_usage()
{
std::cout << "Usage: ZeroCopy_publisher [options]" << std::endl;
std::cout << "Where arguments are:" << std::endl;
std::cout << " -h Shows this page" << std::endl;
std::cout << " -d <domain_id> Sets the domain id [default = 0]" << std::endl;
std::cout << " -fc <frame count> Sets the total number of frames to be mapped "
"in the shared memory queue [default = frame rate]" << std::endl;
std::cout << " -fr <frame rate> Sets the rate at which frames are written "
"[default = 60fps]" << std::endl;
std::cout << " -sc <sample count> Sets the number of frames to send "
"[default = 1200]" << std::endl;
std::cout << " -k <key> Sets the key for shared memory segment "
"[default = 10] " << std::endl;
std::cout << " -s <buffer size> Sets payload size of the frame in bytes "
"[default = 1048576 (1MB)]" << std::endl;
std::cout << " -rc <dr count> Expected number of DataReaders that will receive frames "
"[default = 1]" << std::endl;
std::cout << " -v Displays the checksum for each frame " << std::endl;
}
int main(int argc, char *argv[])
{
CommandLineArguments arg;
// Parse the optional arguments
for (int i = 1; i < argc; ++i) {
if (!strncmp(argv[i], "-h", 2)) {
ZeroCopy_print_usage();
return 0;
} else if (!strncmp(argv[i], "-d", 2)) {
char *ptr;
arg.domain_id = strtol(argv[++i], &ptr, 10);
} else if (!strncmp(argv[i], "-fc", 3)) {
char *ptr;
arg.frame_count = strtol(argv[++i], &ptr, 10);
} else if (!strncmp(argv[i], "-fr", 3)) {
char *ptr;
arg.frame_rate = strtol(argv[++i], &ptr, 10);
} else if (!strncmp(argv[i], "-sc", 3)) {
char *ptr;
arg.sample_count = strtol(argv[++i], &ptr, 10);
} else if (!strncmp(argv[i], "-k", 2)) {
char *ptr;
arg.key = strtol(argv[++i], &ptr, 10);
} else if (!strncmp(argv[i], "-s", 2)) {
char *ptr;
arg.size = strtol(argv[++i], &ptr, 10);
if (arg.size < 4) {
std::cout << "-s must be greater or equal to 4" << std::endl;
return -1;
}
} else if (!strncmp(argv[i], "-rc", 3)) {
char *ptr;
arg.dr_count = strtol(argv[++i], &ptr, 10);
} else if (!strncmp(argv[i], "-v", 2)) {
arg.verbose = true;
} else {
std::cout << "Invalid command-line parameter: " << argv[i]
<< std::endl;
return -1;
}
}
if (arg.frame_count == 0) {
arg.frame_count = arg.frame_rate;
}
if (arg.key == -1) {
CommandLineArguments * argPtr = &arg;
memcpy(&arg.key,&argPtr, sizeof(int));
}
std::cout << "Running using:" << std::endl;
std::cout << " Domain ID: " << arg.domain_id << std::endl;
std::cout << " Frame Count in SHMEM segment: " << arg.frame_count << std::endl;
std::cout << " Frame Rate: " << arg.frame_rate << " fps" << std::endl;
std::cout << " Sample Count: " << arg.sample_count << std::endl;
std::cout << " SHMEM Key: " << arg.key << std::endl;
std::cout << " Frame size: " << arg.size << " bytes" << std::endl;
std::cout << " Expected DataReader Count: " << arg.dr_count << std::endl;
// Uncomment this to turn on additional logging
// NDDSConfigLogger::get_instance()->
// set_verbosity_by_category(NDDS_CONFIG_LOG_CATEGORY_API,
// NDDS_CONFIG_LOG_VERBOSITY_STATUS_ALL);
return publisher_main(arg);
}
| cxx |
rticonnextdds-examples | data/projects/rticonnextdds-examples/zero_copy/c++/FrameSupport.h | /*******************************************************************************
(c) 2005-2017 Copyright, Real-Time Innovations, Inc. All rights reserved.
RTI grants Licensee a license to use, modify, compile, and create derivative
works of the Software. Licensee has the right to distribute object form only
for use with RTI products. The Software is provided "as is", with no warranty
of any type, including any warranty for fitness for any purpose. RTI is under
no obligation to maintain or support 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 <stdexcept>
#include "ndds/osapi/osapi_sharedMemorySegment.h"
#include "ndds/osapi/osapi_process.h"
#include "ndds/osapi/osapi_alignment.h"
#include "ndds/osapi/osapi_utility.h"
#include "string.h"
#include "Frame.h"
//
// Implementation details to access frames in shared memory
//
class FrameSupport {
public:
explicit FrameSupport(int payload_size);
// Gets the adress of the Frame Header located at given offset
Frame* get_frame(int index);
const Frame* get_const_frame(int index) const;
// Sets the base address of the frame
void set_frame_base_address(RTIOsapiSharedMemorySegmentHandle *handle);
// Gets the frame size
int get_frame_size();
private:
// Points to the begining of a Frame header
char *frame_base_address;
// Size of the payload
int buffer_size;
// Size of Frame including Frame header, payload and alignment
int frame_size;
};
//
// Provides write access to a set of frames in shared memory
//
class FrameSet {
public:
//
// Creates a shared memory segment to contain frames of fixed-sized payload
// identified by a key
//
FrameSet(int key, int frame_count, int payload_size);
~FrameSet();
// Obtains a frame in the specified position
Frame* operator[](int index)
{
if ((index >= 0) && (index < frame_count)) {
return frame_support.get_frame(index);
} else {
return NULL;
}
}
private:
FrameSupport frame_support;
// Shared memory handle
RTIOsapiSharedMemorySegmentHandle handle;
// Number of frames being mapped into shared memory
int frame_count;
};
//
// Provides read-only access to a set of frames in shared memory
//
class FrameSetView {
public:
// Attaches to a shared memory segment that contains frames of a fixed-size
// payload, identified by a key.
//
// The key and the payload_size must match those used to create a
// FrameSet.
FrameSetView(int key, int payload_size);
~FrameSetView();
// Obtains a read-only frame in the specified position
const Frame* operator[](int index) const
{
if ((index >= 0) && (index < frame_count)) {
return frame_support.get_const_frame(index);
} else {
return NULL;
}
}
// Returns the key used to attach to the shared memory segment
int get_key()
{
return key;
}
private:
FrameSupport frame_support;
// Shared memory handle
RTIOsapiSharedMemorySegmentHandle handle;
// Number of frames being mapped into shared memory
int frame_count;
// Key used for attaching to shared memory segments
int key;
};
// --- FrameSupport: ----------------------------------------------------------
FrameSupport::FrameSupport(int payload_size)
: frame_base_address(NULL),
buffer_size(payload_size)
{
struct FrameOffset { char c; class Frame member; };
int alignment = offsetof (FrameOffset, member);
frame_size = sizeof(Frame) + buffer_size + alignment;
}
Frame* FrameSupport::get_frame(int index)
{
Frame *frame =
(Frame *)((char *)frame_base_address + (index * frame_size));
frame->length = buffer_size;
return frame;
}
const Frame* FrameSupport::get_const_frame(int index) const
{
return (const Frame *)((char *)frame_base_address + (index * frame_size));
}
void FrameSupport::set_frame_base_address(
RTIOsapiSharedMemorySegmentHandle *handle) {
frame_base_address = (char *)RTIOsapiSharedMemorySegment_getAddress(handle);
}
int FrameSupport::get_frame_size() {
return frame_size;
}
// --- FrameSet: --------------------------------------------------------------
FrameSet::FrameSet(int key, int frame_count, int payload_size)
: frame_support(payload_size), frame_count(frame_count)
{
int frame_size = frame_support.get_frame_size();
int total_size = frame_size * frame_count;
RTI_UINT64 pid = RTIOsapiProcess_getId();
int status = 0;
RTIBool result = RTIOsapiSharedMemorySegment_createOrAttach(
&handle,
&status,
key,
total_size,
pid);
if (!result) {
std::ostringstream status_to_str;
status_to_str << "create shared memory segments error " << status;
throw std::runtime_error(status_to_str.str().c_str());
}
if (status == RTI_OSAPI_SHARED_MEMORY_ATTACHED) {
// The shared memory segement already exists. Because the settings
// maybe different we have to destroy it a recreate it
RTIOsapiSharedMemorySegment_delete(&handle);
result = RTIOsapiSharedMemorySegment_create(
&handle,
&status,
key,
total_size,
pid);
if (!result) {
std::ostringstream status_to_str;
status_to_str << "create shared memory segments error " << status;
throw std::runtime_error(status_to_str.str().c_str());
}
}
frame_support.set_frame_base_address(&handle);
}
FrameSet::~FrameSet()
{
if (!RTIOsapiSharedMemorySegment_delete(&handle)) {
std::cout << "delete shared memory segments error" << std::endl;
}
}
// --- FrameSetView: ----------------------------------------------------------
FrameSetView::FrameSetView(int key, int payload_size)
: frame_support(payload_size), key(key)
{
int status = 0;
RTIBool result = RTIOsapiSharedMemorySegment_attach(
&handle,
&status,
key);
if (!result) {
std::ostringstream status_to_str;
status_to_str << "attach to shared memory segments error " << status;
throw std::runtime_error(status_to_str.str().c_str());
}
frame_support.set_frame_base_address(&handle);
int total_size = RTIOsapiSharedMemorySegment_getSize(&handle);
int frame_size = frame_support.get_frame_size();
frame_count = total_size/frame_size;
}
FrameSetView::~FrameSetView()
{
if (!RTIOsapiSharedMemorySegment_detach(&handle)) {
std::cout << "detach shared memory segments error" << std::endl;
}
}
| h |
rticonnextdds-examples | data/projects/rticonnextdds-examples/access_union_discriminator_dynamicdata/c/UnionExample.c | /* UnionExample.c
This example
- creates the type code of for a union
- creates a DynamicData instance
- sets one of the fields of the union
- shows how to retrieve the discriminator
Example:
To run the example application:
On Unix:
objs/<arch>/UnionExample
On Windows:
objs\<arch>\UnionExample
*/
#include <stdio.h>
#include <stdlib.h>
#include "ndds/ndds_c.h"
struct DDS_TypeCode *createTypeCode(struct DDS_TypeCodeFactory *factory) {
struct DDS_TypeCode *unionTC = NULL;
DDS_ExceptionCode_t ex;
/* First, we create the typeCode for a union*/
unionTC = DDS_TypeCodeFactory_create_union_tc(
factory,
"Foo",
DDS_TypeCodeFactory_get_primitive_tc(factory, DDS_TK_LONG),
1, /* default index */
NULL, /* For now, it does not have any member */
&ex);
if (ex != DDS_NO_EXCEPTION_CODE) {
fprintf(stderr,"! Unable to create union TC\n");
goto fail;
}
/* Case 1 will be a short named aShort */
DDS_TypeCode_add_member(
unionTC,
"aShort",
-1, /* no default member */
DDS_TypeCodeFactory_get_primitive_tc(factory, DDS_TK_SHORT),
DDS_TYPECODE_NONKEY_MEMBER,
&ex);
if (ex != DDS_NO_EXCEPTION_CODE) {
fprintf(stderr,"! Unable to add member aShort\n");
goto fail;
}
/* Case 2 will be a long named aLong */
DDS_TypeCode_add_member(
unionTC,
"aLong",
2,
DDS_TypeCodeFactory_get_primitive_tc(factory, DDS_TK_LONG),
DDS_TYPECODE_NONKEY_MEMBER,
&ex);
if (ex != DDS_NO_EXCEPTION_CODE) {
fprintf(stderr,"! Unable to add member aLong\n");
goto fail;
}
/* Case 3, the default, will be a double named aDouble */
DDS_TypeCode_add_member(
unionTC,
"aDouble",
3,
DDS_TypeCodeFactory_get_primitive_tc(factory, DDS_TK_DOUBLE),
DDS_TYPECODE_NONKEY_MEMBER,
&ex);
if (ex != DDS_NO_EXCEPTION_CODE) {
fprintf(stderr,"! Unable to add member aDouble\n");
goto fail;
}
return unionTC;
fail:
if (unionTC != NULL) {
DDS_TypeCodeFactory_delete_tc(factory, unionTC,&ex);
}
return NULL;
}
int example () {
struct DDS_TypeCode *unionTC = NULL;
struct DDS_DynamicData data;
DDS_ReturnCode_t retcode;
struct DDS_DynamicDataMemberInfo info;
struct DDS_TypeCodeFactory *factory = NULL;
int ret = -1;
struct DDS_DynamicDataProperty_t myProperty = DDS_DYNAMIC_DATA_PROPERTY_DEFAULT;
/* I get a reference to the type code factory */
factory = DDS_TypeCodeFactory_get_instance();
if (factory == NULL) {
fprintf(stderr, "! Unable to get type code factory singleton\n");
goto fail;
}
/* Creating the union typeCode */
unionTC = createTypeCode(factory);
if (unionTC == NULL) {
fprintf(stderr,"! Unable to create typeCode\n");
goto fail;
}
/* Creating a new dynamicData instance based on the union type code */
if (!DDS_DynamicData_initialize(&data,unionTC,&myProperty)) {
fprintf(stderr,"! Unable to create dynamicData\n");
goto fail;
}
/* If I get the discriminator now, I will get the first one added */
retcode = DDS_DynamicData_get_member_info_by_index(
&data,&info,0);
if (retcode != DDS_RETCODE_OK) {
fprintf(stderr,"! Unable to get member info\n");
goto fail;
}
fprintf(stdout, "The field selected is %s\n", info.member_name);
/* Now I set one of the members */
retcode = DDS_DynamicData_set_short(&data,
"aShort",DDS_DYNAMIC_DATA_MEMBER_ID_UNSPECIFIED, 42);
if (retcode != DDS_RETCODE_OK) {
fprintf(stderr,"! Unable to create dynamicData\n");
goto fail;
}
/* The discriminator should now reflect the new situation */
retcode = DDS_DynamicData_get_member_info_by_index(
&data,&info,0);
if (retcode != DDS_RETCODE_OK) {
fprintf(stderr,"! Unable to get member info\n");
goto fail;
}
fprintf(stdout, "The field selected is %s\n", info.member_name);
ret = 1;
fail:
if (unionTC != NULL) {
DDS_TypeCodeFactory_delete_tc(factory, unionTC,NULL);
}
return ret;
}
int main(int argc, char *argv[]) {
return example();
}
| c |
rticonnextdds-examples | data/projects/rticonnextdds-examples/waitset_status_cond/c++/waitset_statuscond_publisher.cxx | /*******************************************************************************
(c) 2005-2014 Copyright, Real-Time Innovations, Inc. All rights reserved.
RTI grants Licensee a license to use, modify, compile, and create derivative
works of the Software. Licensee has the right to distribute object form only
for use with RTI products. The Software is provided "as is", with no warranty
of any type, including any warranty for fitness for any purpose. RTI is under
no obligation to maintain or support the Software. RTI shall not be liable for
any incidental or consequential damages arising out of the use or inability to
use the software.
******************************************************************************/
/* waitset_statuscond_publisher.cxx
A publication of data of type waitset_statuscond
This file is derived from code automatically generated by the rtiddsgen
command:
rtiddsgen -language C++ -example <arch> waitset_statuscond.idl
Example publication of type waitset_statuscond automatically generated by
'rtiddsgen'. To test them follow these steps:
(1) Compile this file and the example subscription.
(2) Start the subscription with the command
objs/<arch>/waitset_statuscond_subscriber <domain_id> <sample_count>
(3) Start the publication with the command
objs/<arch>/waitset_statuscond_publisher <domain_id> <sample_count>
(4) [Optional] Specify the list of discovery initial peers and
multicast receive addresses via an environment variable or a file
(in the current working directory) called NDDS_DISCOVERY_PEERS.
You can run any number of publishers and subscribers programs, and can
add and remove them dynamically from the domain.
Example:
To run the example application on domain <domain_id>:
On Unix:
objs/<arch>/waitset_statuscond_publisher <domain_id> o
objs/<arch>/waitset_statuscond_subscriber <domain_id>
On Windows:
objs\<arch>\waitset_statuscond_publisher <domain_id>
objs\<arch>\waitset_statuscond_subscriber <domain_id>
modification history
------------ -------
*/
#include <stdio.h>
#include <stdlib.h>
#ifdef RTI_VX653
#include <vThreadsData.h>
#endif
#include "waitset_statuscond.h"
#include "waitset_statuscondSupport.h"
#include "ndds/ndds_cpp.h"
/* Delete all entities */
static int publisher_shutdown(
DDSDomainParticipant *participant)
{
DDS_ReturnCode_t retcode;
int status = 0;
if (participant != NULL) {
retcode = participant->delete_contained_entities();
if (retcode != DDS_RETCODE_OK) {
printf("delete_contained_entities error %d\n", retcode);
status = -1;
}
retcode = DDSTheParticipantFactory->delete_participant(participant);
if (retcode != DDS_RETCODE_OK) {
printf("delete_participant error %d\n", retcode);
status = -1;
}
}
/* RTI Connext provides finalize_instance() method on
domain participant factory for people who want to release memory used
by the participant factory. Uncomment the following block of code for
clean destruction of the singleton. */
/*
retcode = DDSDomainParticipantFactory::finalize_instance();
if (retcode != DDS_RETCODE_OK) {
printf("finalize_instance error %d\n", retcode);
status = -1;
}
*/
return status;
}
extern "C" int publisher_main(int domainId, int sample_count)
{
DDSDomainParticipant *participant = NULL;
DDSPublisher *publisher = NULL;
DDSTopic *topic = NULL;
DDSDataWriter *writer = NULL;
waitset_statuscondDataWriter * waitset_statuscond_writer = NULL;
waitset_statuscond *instance = NULL;
DDS_ReturnCode_t retcode;
DDS_InstanceHandle_t instance_handle = DDS_HANDLE_NIL;
const char *type_name = NULL;
int count = 0;
/* Send a new sample every second */
DDS_Duration_t send_period = {1,0};
/* To customize participant QoS, use
the configuration file USER_QOS_PROFILES.xml */
participant = DDSTheParticipantFactory->create_participant(
domainId, DDS_PARTICIPANT_QOS_DEFAULT,
NULL /* listener */, DDS_STATUS_MASK_NONE);
if (participant == NULL) {
printf("create_participant error\n");
publisher_shutdown(participant);
return -1;
}
/* To customize publisher QoS, use
the configuration file USER_QOS_PROFILES.xml */
publisher = participant->create_publisher(
DDS_PUBLISHER_QOS_DEFAULT, NULL /* listener */, DDS_STATUS_MASK_NONE);
if (publisher == NULL) {
printf("create_publisher error\n");
publisher_shutdown(participant);
return -1;
}
/* Register type before creating topic */
type_name = waitset_statuscondTypeSupport::get_type_name();
retcode = waitset_statuscondTypeSupport::register_type(
participant, type_name);
if (retcode != DDS_RETCODE_OK) {
printf("register_type error %d\n", retcode);
publisher_shutdown(participant);
return -1;
}
/* To customize topic QoS, use
the configuration file USER_QOS_PROFILES.xml */
topic = participant->create_topic(
"Example waitset_statuscond",
type_name, DDS_TOPIC_QOS_DEFAULT, NULL /* listener */,
DDS_STATUS_MASK_NONE);
if (topic == NULL) {
printf("create_topic error\n");
publisher_shutdown(participant);
return -1;
}
/* To customize data writer QoS, use
the configuration file USER_QOS_PROFILES.xml */
writer = publisher->create_datawriter(
topic, DDS_DATAWRITER_QOS_DEFAULT, NULL,
DDS_STATUS_MASK_NONE);
if (writer == NULL) {
printf("create_datawriter error\n");
publisher_shutdown(participant);
return -1;
}
waitset_statuscond_writer = waitset_statuscondDataWriter::narrow(writer);
if (waitset_statuscond_writer == NULL) {
printf("DataWriter narrow error\n");
publisher_shutdown(participant);
return -1;
}
/* Create data sample for writing */
instance = waitset_statuscondTypeSupport::create_data();
if (instance == NULL) {
printf("waitset_statuscondTypeSupport::create_data error\n");
publisher_shutdown(participant);
return -1;
}
/* For a data type that has a key, if the same instance is going to be
written multiple times, initialize the key here
and register the keyed instance prior to writing */
/*
instance_handle = waitset_statuscond_writer->register_instance(*instance);
*/
/* Main loop */
for (count=0; (sample_count == 0) || (count < sample_count); ++count) {
printf("Writing waitset_statuscond, count %d\n", count);
/* Modify the data to be sent here */
instance->x = count;
retcode = waitset_statuscond_writer->write(*instance, instance_handle);
if (retcode != DDS_RETCODE_OK) {
printf("write error %d\n", retcode);
}
NDDSUtility::sleep(send_period);
}
/*
retcode = waitset_statuscond_writer->unregister_instance(
*instance, instance_handle);
if (retcode != DDS_RETCODE_OK) {
printf("unregister instance error %d\n", retcode);
}
*/
/* Delete data sample */
retcode = waitset_statuscondTypeSupport::delete_data(instance);
if (retcode != DDS_RETCODE_OK) {
printf("waitset_statuscondTypeSupport::delete_data error %d\n",
retcode);
}
/* Delete all entities */
return publisher_shutdown(participant);
}
#if defined(RTI_WINCE)
int wmain(int argc, wchar_t** argv)
{
int domainId = 0;
int sample_count = 0; /* infinite loop */
if (argc >= 2) {
domainId = _wtoi(argv[1]);
}
if (argc >= 3) {
sample_count = _wtoi(argv[2]);
}
/* Uncomment this to turn on additional logging
NDDSConfigLogger::get_instance()->
set_verbosity_by_category(NDDS_CONFIG_LOG_CATEGORY_API,
NDDS_CONFIG_LOG_VERBOSITY_STATUS_ALL);
*/
return publisher_main(domainId, sample_count);
}
#elif !(defined(RTI_VXWORKS) && !defined(__RTP__)) && !defined(RTI_PSOS)
int main(int argc, char *argv[])
{
int domainId = 0;
int sample_count = 0; /* infinite loop */
if (argc >= 2) {
domainId = atoi(argv[1]);
}
if (argc >= 3) {
sample_count = atoi(argv[2]);
}
/* Uncomment this to turn on additional logging
NDDSConfigLogger::get_instance()->
set_verbosity_by_category(NDDS_CONFIG_LOG_CATEGORY_API,
NDDS_CONFIG_LOG_VERBOSITY_STATUS_ALL);
*/
return publisher_main(domainId, sample_count);
}
#endif
#ifdef RTI_VX653
const unsigned char* __ctype = *(__ctypePtrGet());
extern "C" void usrAppInit ()
{
#ifdef USER_APPL_INIT
USER_APPL_INIT; /* for backwards compatibility */
#endif
/* add application specific code here */
taskSpawn("pub", RTI_OSAPI_THREAD_PRIORITY_NORMAL, 0x8, 0x150000,
(FUNCPTR)publisher_main, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
}
#endif
| cxx |
rticonnextdds-examples | data/projects/rticonnextdds-examples/waitset_status_cond/c++/waitset_statuscond_subscriber.cxx | /*******************************************************************************
(c) 2005-2014 Copyright, Real-Time Innovations, Inc. All rights reserved.
RTI grants Licensee a license to use, modify, compile, and create derivative
works of the Software. Licensee has the right to distribute object form only
for use with RTI products. The Software is provided "as is", with no warranty
of any type, including any warranty for fitness for any purpose. RTI is under
no obligation to maintain or support the Software. RTI shall not be liable for
any incidental or consequential damages arising out of the use or inability to
use the software.
******************************************************************************/
/* waitset_statuscond_subscriber.cxx
A subscription example
This file is derived from code automatically generated by the rtiddsgen
command:
rtiddsgen -language C++ -example <arch> waitset_statuscond.idl
Example subscription of type waitset_statuscond automatically generated by
'rtiddsgen'. To test them follow these steps:
(1) Compile this file and the example publication.
(2) Start the subscription with the command
objs/<arch>/waitset_statuscond_subscriber <domain_id> <sample_count>
(3) Start the publication with the command
objs/<arch>/waitset_statuscond_publisher <domain_id> <sample_count>
(4) [Optional] Specify the list of discovery initial peers and
multicast receive addresses via an environment variable or a file
(in the current working directory) called NDDS_DISCOVERY_PEERS.
You can run any number of publishers and subscribers programs, and can
add and remove them dynamically from the domain.
Example:
To run the example application on domain <domain_id>:
On Unix:
objs/<arch>/waitset_statuscond_publisher <domain_id>
objs/<arch>/waitset_statuscond_subscriber <domain_id>
On Windows:
objs\<arch>\waitset_statuscond_publisher <domain_id>
objs\<arch>\waitset_statuscond_subscriber <domain_id>
modification history
------------ -------
*/
#include <stdio.h>
#include <stdlib.h>
#ifdef RTI_VX653
#include <vThreadsData.h>
#endif
#include "waitset_statuscond.h"
#include "waitset_statuscondSupport.h"
#include "ndds/ndds_cpp.h"
/* We don't need to use listeners as we are going to use waitset_statuscond and
* Conditions so we have removed the auto generated code for listeners here
*/
/* Delete all entities */
static int subscriber_shutdown(
DDSDomainParticipant *participant)
{
DDS_ReturnCode_t retcode;
int status = 0;
if (participant != NULL) {
retcode = participant->delete_contained_entities();
if (retcode != DDS_RETCODE_OK) {
printf("delete_contained_entities error %d\n", retcode);
status = -1;
}
retcode = DDSTheParticipantFactory->delete_participant(participant);
if (retcode != DDS_RETCODE_OK) {
printf("delete_participant error %d\n", retcode);
status = -1;
}
}
/* RTI Connext provides the finalize_instance() method on
domain participant factory for people who want to release memory used
by the participant factory. Uncomment the following block of code for
clean destruction of the singleton. */
/*
retcode = DDSDomainParticipantFactory::finalize_instance();
if (retcode != DDS_RETCODE_OK) {
printf("finalize_instance error %d\n", retcode);
status = -1;
}
*/
return status;
}
extern "C" int subscriber_main(int domainId, int sample_count)
{
DDSDomainParticipant *participant = NULL;
DDSSubscriber *subscriber = NULL;
DDSTopic *topic = NULL;
DDSDataReader *reader = NULL;
DDS_ReturnCode_t retcode;
const char *type_name = NULL;
int count = 0;
int status = 0;
struct DDS_Duration_t wait_timeout = {1,500000000};
/* To customize the participant QoS, use
the configuration file USER_QOS_PROFILES.xml */
participant = DDSTheParticipantFactory->create_participant(
domainId, DDS_PARTICIPANT_QOS_DEFAULT,
NULL /* listener */, DDS_STATUS_MASK_NONE);
if (participant == NULL) {
printf("create_participant error\n");
subscriber_shutdown(participant);
return -1;
}
/* To customize the subscriber QoS, use
the configuration file USER_QOS_PROFILES.xml */
subscriber = participant->create_subscriber(
DDS_SUBSCRIBER_QOS_DEFAULT, NULL /* listener */, DDS_STATUS_MASK_NONE);
if (subscriber == NULL) {
printf("create_subscriber error\n");
subscriber_shutdown(participant);
return -1;
}
/* Register the type before creating the topic */
type_name = waitset_statuscondTypeSupport::get_type_name();
retcode = waitset_statuscondTypeSupport::register_type(
participant, type_name);
if (retcode != DDS_RETCODE_OK) {
printf("register_type error %d\n", retcode);
subscriber_shutdown(participant);
return -1;
}
/* To customize the topic QoS, use
the configuration file USER_QOS_PROFILES.xml */
topic = participant->create_topic(
"Example waitset_statuscond",
type_name, DDS_TOPIC_QOS_DEFAULT, NULL /* listener */,
DDS_STATUS_MASK_NONE);
if (topic == NULL) {
printf("create_topic error\n");
subscriber_shutdown(participant);
return -1;
}
/* To customize the data reader QoS, use
the configuration file USER_QOS_PROFILES.xml */
reader = subscriber->create_datareader(
topic, DDS_DATAREADER_QOS_DEFAULT, NULL,
DDS_STATUS_MASK_NONE);
if (reader == NULL) {
printf("create_datareader error\n");
subscriber_shutdown(participant);
return -1;
}
/* Get status conditions
* ---------------------
* Each entity may have an attached Status Condition. To modify the
* statuses we need to get the reader's Status Conditions first.
*/
DDSStatusCondition* status_condition = reader->get_statuscondition();
if (status_condition == NULL) {
printf("get_statuscondition error\n");
subscriber_shutdown(participant);
return -1;
}
/* Set enabled statuses
* --------------------
* Now that we have the Status Condition, we are going to enable the
* status we are interested in: knowing that data is available
*/
retcode = status_condition->set_enabled_statuses(
DDS_DATA_AVAILABLE_STATUS);
if (retcode != DDS_RETCODE_OK) {
printf("set_enabled_statuses error\n");
subscriber_shutdown(participant);
return -1;
}
/* Create and attach conditions to the WaitSet
* -------------------------------------------
* Finally, we create the WaitSet and attach both the Read Conditions
* and the Status Condition to it.
*/
DDSWaitSet* waitset = new DDSWaitSet();
/* Attach Status Conditions */
retcode = waitset->attach_condition(status_condition);
if (retcode != DDS_RETCODE_OK) {
printf("attach_condition error\n");
subscriber_shutdown(participant);
return -1;
}
/* Narrow the reader into your specific data type */
waitset_statuscondDataReader *waitset_statuscond_reader =
waitset_statuscondDataReader::narrow(reader);
if (waitset_statuscond_reader == NULL) {
printf("DataReader narrow error\n");
return -1;
}
/* Main loop */
for (count=0; (sample_count == 0) || (count < sample_count); ++count) {
DDSConditionSeq active_conditions_seq;
/* wait() blocks execution of the thread until one or more attached
* Conditions become true, or until a user-specified timeout expires.
*/
retcode = waitset->wait(active_conditions_seq, wait_timeout);
/* We get to timeout if no conditions were triggered */
if (retcode == DDS_RETCODE_TIMEOUT) {
printf("Wait timed out!! No conditions were triggered.\n");
continue;
} else if (retcode != DDS_RETCODE_OK) {
printf("wait returned error: %d\n", retcode);
break;
}
/* Get the number of active conditions */
int active_conditions = active_conditions_seq.length();
printf("Got %d active conditions\n", active_conditions);
/* In this case, we have only a single condition, but
if we had multiple, we would need to iterate over
them and check which one is true. Leaving the logic
for the more complex case. */
for (int i = 0; i < active_conditions; ++i) {
/* Compare with Status Conditions */
if (active_conditions_seq[i] == status_condition) {
/* Get the status changes so we can check which status
* condition triggered. */
DDS_StatusMask triggeredmask =
waitset_statuscond_reader->get_status_changes();
/* Subscription matched */
if (triggeredmask & DDS_DATA_AVAILABLE_STATUS) {
/* Current conditions match our conditions to read data, so
* we can read data just like we would do in any other
* example. */
waitset_statuscondSeq data_seq;
DDS_SampleInfoSeq info_seq;
/* Access data using read(), take(), etc. If you fail to do
* this the condition will remain true, and the WaitSet will
* wake up immediately - causing high CPU usage when it does
* not sleep in the loop */
retcode = DDS_RETCODE_OK;
while (retcode != DDS_RETCODE_NO_DATA) {
retcode = waitset_statuscond_reader->take(
data_seq, info_seq, DDS_LENGTH_UNLIMITED,
DDS_ANY_SAMPLE_STATE, DDS_ANY_VIEW_STATE,
DDS_ANY_INSTANCE_STATE);
for (int j = 0; j < data_seq.length(); ++j) {
if (!info_seq[j].valid_data) {
printf("Got metadata\n");
continue;
}
waitset_statuscondTypeSupport::print_data(
&data_seq[j]);
}
/* Return the loaned data */
waitset_statuscond_reader->return_loan(data_seq,
info_seq);
}
}
}
}
}
/* Delete all entities */
delete waitset;
status = subscriber_shutdown(participant);
return status;
}
#if defined(RTI_WINCE)
int wmain(int argc, wchar_t** argv)
{
int domainId = 0;
int sample_count = 0; /* infinite loop */
if (argc >= 2) {
domainId = _wtoi(argv[1]);
}
if (argc >= 3) {
sample_count = _wtoi(argv[2]);
}
/* Uncomment this to turn on additional logging
NDDSConfigLogger::get_instance()->
set_verbosity_by_category(NDDS_CONFIG_LOG_CATEGORY_API,
NDDS_CONFIG_LOG_VERBOSITY_STATUS_ALL);
*/
return subscriber_main(domainId, sample_count);
}
#elif !(defined(RTI_VXWORKS) && !defined(__RTP__)) && !defined(RTI_PSOS)
int main(int argc, char *argv[])
{
int domainId = 0;
int sample_count = 0; /* infinite loop */
if (argc >= 2) {
domainId = atoi(argv[1]);
}
if (argc >= 3) {
sample_count = atoi(argv[2]);
}
/* Uncomment this to turn on additional logging
NDDSConfigLogger::get_instance()->
set_verbosity_by_category(NDDS_CONFIG_LOG_CATEGORY_API,
NDDS_CONFIG_LOG_VERBOSITY_STATUS_ALL);
*/
return subscriber_main(domainId, sample_count);
}
#endif
#ifdef RTI_VX653
const unsigned char* __ctype = *(__ctypePtrGet());
extern "C" void usrAppInit ()
{
#ifdef USER_APPL_INIT
USER_APPL_INIT; /* for backwards compatibility */
#endif
/* add application specific code here */
taskSpawn("sub", RTI_OSAPI_THREAD_PRIORITY_NORMAL, 0x8, 0x150000,
(FUNCPTR)subscriber_main, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
}
#endif
| cxx |
rticonnextdds-examples | data/projects/rticonnextdds-examples/waitset_status_cond/c/waitset_statuscond_publisher.c | /*******************************************************************************
(c) 2005-2014 Copyright, Real-Time Innovations, Inc. All rights reserved.
RTI grants Licensee a license to use, modify, compile, and create derivative
works of the Software. Licensee has the right to distribute object form only
for use with RTI products. The Software is provided "as is", with no warranty
of any type, including any warranty for fitness for any purpose. RTI is under
no obligation to maintain or support the Software. RTI shall not be liable for
any incidental or consequential damages arising out of the use or inability to
use the software.
******************************************************************************/
/* waitset_statuscond_publisher.c
A publication of data of type waitset_statuscond
This file is derived from code automatically generated by the rtiddsgen
command:
rtiddsgen -language C -example <arch> waitset_statuscond.idl
Example publication of type waitset_statuscond automatically generated by
'rtiddsgen'. To test them follow these steps:
(1) Compile this file and the example subscription.
(2) Start the subscription with the command
objs/<arch>/waitset_statuscond_subscriber <domain_id> <sample_count>
(3) Start the publication with the command
objs/<arch>/waitset_statuscond_publisher <domain_id> <sample_count>
(4) [Optional] Specify the list of discovery initial peers and
multicast receive addresses via an environment variable or a file
(in the current working directory) called NDDS_DISCOVERY_PEERS.
You can run any number of publishers and subscribers programs, and can
add and remove them dynamically from the domain.
Example:
To run the example application on domain <domain_id>:
On Unix:
objs/<arch>/waitset_statuscond_publisher <domain_id>
objs/<arch>/waitset_statuscond_subscriber <domain_id>
On Windows:
objs\<arch>\waitset_statuscond_publisher <domain_id>
objs\<arch>\waitset_statuscond_subscriber <domain_id>
modification history
------------ -------
*/
#include <stdio.h>
#include <stdlib.h>
#include "ndds/ndds_c.h"
#include "waitset_statuscond.h"
#include "waitset_statuscondSupport.h"
/* Delete all entities */
static int publisher_shutdown(
DDS_DomainParticipant *participant)
{
DDS_ReturnCode_t retcode;
int status = 0;
if (participant != NULL) {
retcode = DDS_DomainParticipant_delete_contained_entities(participant);
if (retcode != DDS_RETCODE_OK) {
printf("delete_contained_entities error %d\n", retcode);
status = -1;
}
retcode = DDS_DomainParticipantFactory_delete_participant(
DDS_TheParticipantFactory, participant);
if (retcode != DDS_RETCODE_OK) {
printf("delete_participant error %d\n", retcode);
status = -1;
}
}
/* RTI Connext provides finalize_instance() method on
domain participant factory for people who want to release memory used
by the participant factory. Uncomment the following block of code for
clean destruction of the singleton. */
/*
retcode = DDS_DomainParticipantFactory_finalize_instance();
if (retcode != DDS_RETCODE_OK) {
printf("finalize_instance error %d\n", retcode);
status = -1;
}
*/
return status;
}
static int publisher_main(int domainId, int sample_count)
{
DDS_DomainParticipant *participant = NULL;
DDS_Publisher *publisher = NULL;
DDS_Topic *topic = NULL;
DDS_DataWriter *writer = NULL;
waitset_statuscondDataWriter *waitset_statuscond_writer = NULL;
waitset_statuscond *instance = NULL;
DDS_ReturnCode_t retcode;
DDS_InstanceHandle_t instance_handle = DDS_HANDLE_NIL;
const char *type_name = NULL;
int count = 0;
struct DDS_Duration_t send_period = {1,0};
/* To customize participant QoS, use
the configuration file USER_QOS_PROFILES.xml */
participant = DDS_DomainParticipantFactory_create_participant(
DDS_TheParticipantFactory, domainId, &DDS_PARTICIPANT_QOS_DEFAULT,
NULL /* listener */, DDS_STATUS_MASK_NONE);
if (participant == NULL) {
printf("create_participant error\n");
publisher_shutdown(participant);
return -1;
}
/* To customize publisher QoS, use
the configuration file USER_QOS_PROFILES.xml */
publisher = DDS_DomainParticipant_create_publisher(
participant, &DDS_PUBLISHER_QOS_DEFAULT, NULL /* listener */,
DDS_STATUS_MASK_NONE);
if (publisher == NULL) {
printf("create_publisher error\n");
publisher_shutdown(participant);
return -1;
}
/* Register type before creating topic */
type_name = waitset_statuscondTypeSupport_get_type_name();
retcode = waitset_statuscondTypeSupport_register_type(
participant, type_name);
if (retcode != DDS_RETCODE_OK) {
printf("register_type error %d\n", retcode);
publisher_shutdown(participant);
return -1;
}
/* To customize topic QoS, use
the configuration file USER_QOS_PROFILES.xml */
topic = DDS_DomainParticipant_create_topic(
participant, "Example waitset_statuscond",
type_name, &DDS_TOPIC_QOS_DEFAULT, NULL /* listener */,
DDS_STATUS_MASK_NONE);
if (topic == NULL) {
printf("create_topic error\n");
publisher_shutdown(participant);
return -1;
}
/* To customize data writer QoS, use
the configuration file USER_QOS_PROFILES.xml */
writer = DDS_Publisher_create_datawriter(
publisher, topic,
&DDS_DATAWRITER_QOS_DEFAULT, NULL /* listener */, DDS_STATUS_MASK_NONE);
if (writer == NULL) {
printf("create_datawriter error\n");
publisher_shutdown(participant);
return -1;
}
waitset_statuscond_writer = waitset_statuscondDataWriter_narrow(writer);
if (waitset_statuscond_writer == NULL) {
printf("DataWriter narrow error\n");
publisher_shutdown(participant);
return -1;
}
/* Create data sample for writing */
instance = waitset_statuscondTypeSupport_create_data_ex(DDS_BOOLEAN_TRUE);
if (instance == NULL) {
printf("waitset_statuscondTypeSupport_create_data error\n");
publisher_shutdown(participant);
return -1;
}
/* For a data type that has a key, if the same instance is going to be
written multiple times, initialize the key here
and register the keyed instance prior to writing */
/*
instance_handle = waitset_statuscondDataWriter_register_instance(
waitset_statuscond_writer, instance);
*/
/* Main loop */
for (count=0; (sample_count == 0) || (count < sample_count); ++count) {
printf("Writing waitset_statuscond, count %d\n", count);
/* Modify the data to be written here */
instance->x = count;
/* Write data */
retcode = waitset_statuscondDataWriter_write(
waitset_statuscond_writer, instance, &instance_handle);
if (retcode != DDS_RETCODE_OK) {
printf("write error %d\n", retcode);
}
NDDS_Utility_sleep(&send_period);
}
/*
retcode = waitset_statuscondDataWriter_unregister_instance(
waitset_statuscond_writer, instance, &instance_handle);
if (retcode != DDS_RETCODE_OK) {
printf("unregister instance error %d\n", retcode);
}
*/
/* Delete data sample */
retcode = waitset_statuscondTypeSupport_delete_data_ex(instance,
DDS_BOOLEAN_TRUE);
if (retcode != DDS_RETCODE_OK) {
printf("waitset_statuscondTypeSupport_delete_data error %d\n", retcode);
}
/* Cleanup and delete delete all entities */
return publisher_shutdown(participant);
}
#if defined(RTI_WINCE)
int wmain(int argc, wchar_t** argv)
{
int domainId = 0;
int sample_count = 0; /* infinite loop */
if (argc >= 2) {
domainId = _wtoi(argv[1]);
}
if (argc >= 3) {
sample_count = _wtoi(argv[2]);
}
/* Uncomment this to turn on additional logging
NDDS_Config_Logger_set_verbosity_by_category(
NDDS_Config_Logger_get_instance(),
NDDS_CONFIG_LOG_CATEGORY_API,
NDDS_CONFIG_LOG_VERBOSITY_STATUS_ALL);
*/
return publisher_main(domainId, sample_count);
}
#elif !(defined(RTI_VXWORKS) && !defined(__RTP__)) && !defined(RTI_PSOS)
int main(int argc, char *argv[])
{
int domainId = 0;
int sample_count = 0; /* infinite loop */
if (argc >= 2) {
domainId = atoi(argv[1]);
}
if (argc >= 3) {
sample_count = atoi(argv[2]);
}
/* Uncomment this to turn on additional logging
NDDS_Config_Logger_set_verbosity_by_category(
NDDS_Config_Logger_get_instance(),
NDDS_CONFIG_LOG_CATEGORY_API,
NDDS_CONFIG_LOG_VERBOSITY_STATUS_ALL);
*/
return publisher_main(domainId, sample_count);
}
#endif
#ifdef RTI_VX653
const unsigned char* __ctype = NULL;
void usrAppInit ()
{
#ifdef USER_APPL_INIT
USER_APPL_INIT; /* for backwards compatibility */
#endif
/* add application specific code here */
taskSpawn("pub", RTI_OSAPI_THREAD_PRIORITY_NORMAL, 0x8, 0x150000,
(FUNCPTR)publisher_main, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
}
#endif
| c |
rticonnextdds-examples | data/projects/rticonnextdds-examples/waitset_status_cond/c/waitset_statuscond_subscriber.c | /*******************************************************************************
(c) 2005-2014 Copyright, Real-Time Innovations, Inc. All rights reserved.
RTI grants Licensee a license to use, modify, compile, and create derivative
works of the Software. Licensee has the right to distribute object form only
for use with RTI products. The Software is provided "as is", with no warranty
of any type, including any warranty for fitness for any purpose. RTI is under
no obligation to maintain or support the Software. RTI shall not be liable for
any incidental or consequential damages arising out of the use or inability to
use the software.
******************************************************************************/
/* waitset_statuscond_subscriber.c
A subscription example
This file is derived from code automatically generated by the rtiddsgen
command:
rtiddsgen -language C -example <arch> waitset_statuscond.idl
Example subscription of type waitset_statuscond automatically generated by
'rtiddsgen'. To test them, follow these steps:
(1) Compile this file and the example publication.
(2) Start the subscription with the command
objs/<arch>/waitset_statuscond_subscriber <domain_id> <sample_count>
(3) Start the publication with the command
objs/<arch>/waitset_statuscond_publisher <domain_id> <sample_count>
(4) [Optional] Specify the list of discovery initial peers and
multicast receive addresses via an environment variable or a file
(in the current working directory) called NDDS_DISCOVERY_PEERS.
You can run any number of publishers and subscribers programs, and can
add and remove them dynamically from the domain.
Example:
To run the example application on domain <domain_id>:
On UNIX systems:
objs/<arch>/waitset_statuscond_publisher <domain_id>
objs/<arch>/waitset_statuscond_subscriber <domain_id>
On Windows systems:
objs\<arch>\waitset_statuscond_publisher <domain_id>
objs\<arch>\waitset_statuscond_subscriber <domain_id>
modification history
------------ -------
*/
#include <stdio.h>
#include <stdlib.h>
#include "ndds/ndds_c.h"
#include "waitset_statuscond.h"
#include "waitset_statuscondSupport.h"
/* Delete all entities */
static int subscriber_shutdown(
DDS_DomainParticipant *participant)
{
DDS_ReturnCode_t retcode;
int status = 0;
if (participant != NULL) {
retcode = DDS_DomainParticipant_delete_contained_entities(participant);
if (retcode != DDS_RETCODE_OK) {
printf("delete_contained_entities error %d\n", retcode);
status = -1;
}
retcode = DDS_DomainParticipantFactory_delete_participant(
DDS_TheParticipantFactory, participant);
if (retcode != DDS_RETCODE_OK) {
printf("delete_participant error %d\n", retcode);
status = -1;
}
}
/* RTI Connext provides the finalize_instance() method on
domain participant factory for users who want to release memory used
by the participant factory. Uncomment the following block of code for
clean destruction of the singleton. */
/*
retcode = DDS_DomainParticipantFactory_finalize_instance();
if (retcode != DDS_RETCODE_OK) {
printf("finalize_instance error %d\n", retcode);
status = -1;
}
*/
return status;
}
static int subscriber_main(int domainId, int sample_count)
{
DDS_DomainParticipant *participant = NULL;
DDS_Subscriber *subscriber = NULL;
DDS_Topic *topic = NULL;
struct DDS_DataReaderListener reader_listener =
DDS_DataReaderListener_INITIALIZER;
DDS_DataReader *reader = NULL;
DDS_ReturnCode_t retcode;
const char *type_name = NULL;
int count = 0;
DDS_StatusCondition *status_condition;
DDS_WaitSet *waitset = NULL;
waitset_statuscondDataReader *waitsets_reader = NULL;
struct DDS_Duration_t timeout = {4,0};
/* To customize participant QoS, use
the configuration file USER_QOS_PROFILES.xml */
participant = DDS_DomainParticipantFactory_create_participant(
DDS_TheParticipantFactory, domainId, &DDS_PARTICIPANT_QOS_DEFAULT,
NULL /* listener */, DDS_STATUS_MASK_NONE);
if (participant == NULL) {
printf("create_participant error\n");
subscriber_shutdown(participant);
return -1;
}
/* To customize subscriber QoS, use
the configuration file USER_QOS_PROFILES.xml */
subscriber = DDS_DomainParticipant_create_subscriber(
participant, &DDS_SUBSCRIBER_QOS_DEFAULT, NULL /* listener */,
DDS_STATUS_MASK_NONE);
if (subscriber == NULL) {
printf("create_subscriber error\n");
subscriber_shutdown(participant);
return -1;
}
/* Register the type before creating the topic */
type_name = waitset_statuscondTypeSupport_get_type_name();
retcode = waitset_statuscondTypeSupport_register_type(participant,
type_name);
if (retcode != DDS_RETCODE_OK) {
printf("register_type error %d\n", retcode);
subscriber_shutdown(participant);
return -1;
}
/* To customize topic QoS, use
the configuration file USER_QOS_PROFILES.xml */
topic = DDS_DomainParticipant_create_topic(
participant, "Example waitset_statuscond",
type_name, &DDS_TOPIC_QOS_DEFAULT, NULL /* listener */,
DDS_STATUS_MASK_NONE);
if (topic == NULL) {
printf("create_topic error\n");
subscriber_shutdown(participant);
return -1;
}
/* To customize data reader QoS, use
the configuration file USER_QOS_PROFILES.xml */
reader = DDS_Subscriber_create_datareader(
subscriber, DDS_Topic_as_topicdescription(topic),
&DDS_DATAREADER_QOS_DEFAULT, NULL, DDS_STATUS_MASK_NONE);
if (reader == NULL) {
printf("create_datareader error\n");
subscriber_shutdown(participant);
return -1;
}
status_condition = DDS_Entity_get_statuscondition((DDS_Entity*)reader);
if (status_condition == NULL) {
printf("get_statuscondition error\n");
subscriber_shutdown(participant);
return -1;
}
// Since a single status condition can match many statuses,
// enable only those we're interested in.
retcode = DDS_StatusCondition_set_enabled_statuses(
status_condition,
DDS_DATA_AVAILABLE_STATUS);
if (retcode != DDS_RETCODE_OK) {
printf("set_enabled_statuses error\n");
subscriber_shutdown(participant);
return -1;
}
// Create WaitSet, and attach conditions
waitset = DDS_WaitSet_new();
if (waitset == NULL) {
printf("create waitset error\n");
subscriber_shutdown(participant);
return -1;
}
retcode = DDS_WaitSet_attach_condition(waitset,
(DDS_Condition*)status_condition);
if (retcode != DDS_RETCODE_OK) {
printf("attach_condition error\n");
subscriber_shutdown(participant);
return -1;
}
// Get narrowed datareader
waitsets_reader = waitset_statuscondDataReader_narrow(reader);
if (waitsets_reader == NULL) {
printf("DataReader narrow error\n");
return -1;
}
/* Main loop */
for (count=0; (sample_count == 0) || (count < sample_count); ++count) {
struct DDS_ConditionSeq active_conditions = DDS_SEQUENCE_INITIALIZER;
int i, j;
retcode = DDS_WaitSet_wait(waitset, &active_conditions, &timeout);
if (retcode == DDS_RETCODE_TIMEOUT) {
printf("wait timed out\n");
count+=2;
continue;
} else if (retcode != DDS_RETCODE_OK) {
printf("wait returned error: %d\n", retcode);
break;
}
printf("got %d active conditions\n",
DDS_ConditionSeq_get_length(&active_conditions));
for (i = 0; i < DDS_ConditionSeq_get_length(&active_conditions); ++i) {
/* Compare with Status Conditions */
if (DDS_ConditionSeq_get(&active_conditions, i) ==
(DDS_Condition*)status_condition) {
/* A status condition triggered--see which ones */
DDS_StatusMask triggeredmask;
triggeredmask = DDS_Entity_get_status_changes(
(DDS_Entity*)waitsets_reader);
/* Subscription matched */
if (triggeredmask & DDS_DATA_AVAILABLE_STATUS) {
/* Current conditions match our conditions to read data, so
* we can read data just like we would do in any other
* example.
*/
struct waitset_statuscondSeq data_seq =
DDS_SEQUENCE_INITIALIZER;
struct DDS_SampleInfoSeq info_seq =
DDS_SEQUENCE_INITIALIZER;
/* Access data using read(), take(), etc. If you fail to do
* this the condition will remain true, and the WaitSet will
* wake up immediately - causing high CPU usage when it does
* not sleep in the loop */
retcode = DDS_RETCODE_OK;
while (retcode != DDS_RETCODE_NO_DATA) {
retcode = waitset_statuscondDataReader_take(
waitsets_reader, &data_seq, &info_seq,
DDS_LENGTH_UNLIMITED, DDS_ANY_SAMPLE_STATE,
DDS_ANY_VIEW_STATE, DDS_ANY_INSTANCE_STATE);
for (j = 0;
j < waitset_statuscondSeq_get_length(&data_seq);
++j) {
if (!DDS_SampleInfoSeq_get_reference(
&info_seq, j)->valid_data) {
printf(" Got metadata\n");
continue;
}
waitset_statuscondTypeSupport_print_data(
waitset_statuscondSeq_get_reference(&data_seq, j));
}
waitset_statuscondDataReader_return_loan(
waitsets_reader, &data_seq, &info_seq);
}
}
}
}
}
/* Delete all entities */
retcode = DDS_WaitSet_delete(waitset);
if (retcode != DDS_RETCODE_OK) {
printf("delete waitset error %d\n", retcode);
}
/* Cleanup and delete all entities */
return subscriber_shutdown(participant);
}
#if defined(RTI_WINCE)
int wmain(int argc, wchar_t** argv)
{
int domainId = 0;
int sample_count = 0; /* infinite loop */
if (argc >= 2) {
domainId = _wtoi(argv[1]);
}
if (argc >= 3) {
sample_count = _wtoi(argv[2]);
}
/* Uncomment this to turn on additional logging
NDDS_Config_Logger_set_verbosity_by_category(
NDDS_Config_Logger_get_instance(),
NDDS_CONFIG_LOG_CATEGORY_API,
NDDS_CONFIG_LOG_VERBOSITY_STATUS_ALL);
*/
return subscriber_main(domainId, sample_count);
}
#elif !(defined(RTI_VXWORKS) && !defined(__RTP__)) && !defined(RTI_PSOS)
int main(int argc, char *argv[])
{
int domainId = 0;
int sample_count = 0; /* infinite loop */
if (argc >= 2) {
domainId = atoi(argv[1]);
}
if (argc >= 3) {
sample_count = atoi(argv[2]);
}
/* Uncomment this to turn on additional logging
NDDS_Config_Logger_set_verbosity_by_category(
NDDS_Config_Logger_get_instance(),
NDDS_CONFIG_LOG_CATEGORY_API,
NDDS_CONFIG_LOG_VERBOSITY_STATUS_ALL);
*/
return subscriber_main(domainId, sample_count);
}
#endif
#ifdef RTI_VX653
const unsigned char* __ctype = NULL;
void usrAppInit ()
{
#ifdef USER_APPL_INIT
USER_APPL_INIT; /* for backwards compatibility */
#endif
/* add application specific code here */
taskSpawn("sub", RTI_OSAPI_THREAD_PRIORITY_NORMAL, 0x8, 0x150000,
(FUNCPTR)subscriber_main, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
}
#endif
| c |
rticonnextdds-examples | data/projects/rticonnextdds-examples/waitset_status_cond/c++03/waitset_statuscond_publisher.cxx | /*******************************************************************************
(c) 2005-2015 Copyright, Real-Time Innovations, Inc. All rights reserved.
RTI grants Licensee a license to use, modify, compile, and create derivative
works of the Software. Licensee has the right to distribute object form only
for use with RTI products. The Software is provided "as is", with no warranty
of any type, including any warranty for fitness for any purpose. RTI is under
no obligation to maintain or support the Software. RTI shall not be liable for
any incidental or consequential damages arising out of the use or inability to
use the software.
******************************************************************************/
#include <cstdlib>
#include <iostream>
#include <dds/dds.hpp>
#include "waitset_statuscond.hpp"
using namespace dds::core;
using namespace dds::core::policy;
using namespace dds::domain;
using namespace dds::topic;
using namespace dds::pub;
using namespace dds::pub::qos;
void publisher_main(int domain_id, int sample_count)
{
// Create a DomainParticipant.
DomainParticipant participant(domain_id);
// Create a Topic -- and automatically register the type.
Topic<Foo> topic(participant, "Example waitset_statuscond");
// Retrieve the DataWriter QoS, from USER_QOS_PROFILES.xml.
DataWriterQos writer_qos = QosProvider::Default().datawriter_qos();
// If you want to change the DataWriter's QoS programmatically rather
// than using the XML file, you will need to comment out the previous
// publisher_qos assignment and uncomment these files.
// writer_qos << Reliability::Reliable()
// << History::KeepAll();
// Create a DataWriter.
DataWriter<Foo> writer(Publisher(participant), topic, writer_qos);
// Create a sample for writing.
Foo instance;
for (int count = 0; (sample_count == 0) || (count < sample_count); ++count){
std::cout << "Writing waitset_statuscond, count " << count << std::endl;
instance.x(count);
writer.write(instance);
rti::util::sleep(Duration(1));
}
}
int main(int argc, char *argv[])
{
int domain_id = 0;
int sample_count = 0; // Infinite loop
if (argc >= 2) {
domain_id = atoi(argv[1]);
}
if (argc >= 3) {
sample_count = atoi(argv[2]);
}
// To turn on additional logging, include <rti/config/Logger.hpp> and
// uncomment the following line:
// rti::config::Logger::instance().verbosity(rti::config::Verbosity::STATUS_ALL);
try {
publisher_main(domain_id, sample_count);
} catch (std::exception ex) {
std::cout << "Exception caught: " << ex.what() << std::endl;
return -1;
}
return 0;
}
| cxx |
rticonnextdds-examples | data/projects/rticonnextdds-examples/waitset_status_cond/c++03/waitset_statuscond_subscriber.cxx | /*******************************************************************************
(c) 2005-2015 Copyright, Real-Time Innovations, Inc. All rights reserved.
RTI grants Licensee a license to use, modify, compile, and create derivative
works of the Software. Licensee has the right to distribute object form only
for use with RTI products. The Software is provided "as is", with no warranty
of any type, including any warranty for fitness for any purpose. RTI is under
no obligation to maintain or support the Software. RTI shall not be liable for
any incidental or consequential damages arising out of the use or inability to
use the software.
******************************************************************************/
#include <cstdlib>
#include <iostream>
#include <dds/dds.hpp>
#include "waitset_statuscond.hpp"
using namespace dds::core;
using namespace dds::core::cond;
using namespace dds::core::policy;
using namespace dds::core::status;
using namespace dds::domain;
using namespace dds::topic;
using namespace dds::sub;
using namespace dds::sub::qos;
void subscriber_main(int domain_id, int sample_count)
{
// Create a DomainParticipant.
DomainParticipant participant(domain_id);
// Create a Topic -- and automatically register the type.
Topic<Foo> topic(participant, "Example waitset_statuscond");
// Retrieve the subscriber QoS from USER_QOS_PROFILES.xml
DataReaderQos reader_qos = QosProvider::Default().datareader_qos();
// If you want to change the DataReader's QoS programmatically rather
// than using the XML file, you will need to comment out the previous
// publisher_qos assignment and uncomment these files.
// reader_qos << Reliability::Reliable()
// << History::KeepAll();
// Create a DataReader.
DataReader<Foo> reader(Subscriber(participant), topic, reader_qos);
// Get status conditions.
// Each entity may have an attached Status Condition. To modify the
// statuses we need to get the reader's Status Conditions first.
// By instantiating a StatusCondition we are obtaining a reference to this
// reader's StatusCondition
StatusCondition status_condition(reader);
// Set enabled statuses.
// Now that we have the Status Condition, we are going to enable the
// statuses we are interested in:
status_condition.enabled_statuses(StatusMask::data_available());
// Create the waitset and attach the condition.
WaitSet waitset;
waitset += status_condition;
// Main loop
for (int count = 0; (sample_count == 0) || (count < sample_count); count++){
// 'wait()' blocks execution of the thread until one or more attached
// Conditions become true, or until a user-specified timeout expires.
// Another way would be to use 'dispatch()' to wait and dispatch the
// events as it's done in the "waitset_query_cond" example.
WaitSet::ConditionSeq active_conditions = waitset.wait(
Duration::from_millisecs(1500));
if (active_conditions.size() == 0) {
std::cout << "Wait timed out!! No conditions were triggered."
<< std::endl;
continue;
}
std::cout << "Got " << active_conditions.size() << " active conditions"
<< std::endl;
// In this case, we have only a single condition, but if we had
// multiple, we would need to iterate over them and check which one is
// true. Leaving the logic for the more complex case.
for (std::vector<int>::size_type i=0; i<active_conditions.size(); i++) {
// Compare with Status Condition
if (active_conditions[i] == status_condition) {
// Get the status changes so we can check witch status condition
// triggered.
StatusMask triggeredmask = reader.status_changes();
// Subscription matched
if ((triggeredmask & StatusMask::data_available()).any()){
// Current conditions match our conditions to read data, so
// we can read data just like we would do in any other
// example.
LoanedSamples<Foo> samples = reader.take();
for (LoanedSamples<Foo>::iterator sampleIt=samples.begin();
sampleIt != samples.end();
++sampleIt) {
if (!sampleIt->info().valid()) {
std::cout << "Got metadata" << std::endl;
} else {
std::cout << sampleIt->data() << std::endl;
}
}
}
}
}
}
}
int main(int argc, char *argv[])
{
int domain_id = 0;
int sample_count = 0; // Infinite loop
if (argc >= 2) {
domain_id = atoi(argv[1]);
}
if (argc >= 3) {
sample_count = atoi(argv[2]);
}
// To turn on additional logging, include <rti/config/Logger.hpp> and
// uncomment the following line:
// rti::config::Logger::instance().verbosity(rti::config::Verbosity::STATUS_ALL);
try {
subscriber_main(domain_id, sample_count);
} catch (std::exception ex) {
std::cout << "Exception caught: " << ex.what() << std::endl;
return -1;
}
return 0;
}
| cxx |
rticonnextdds-examples | data/projects/rticonnextdds-examples/waitset_status_cond/c++11/waitset_cond_modern_subscriber.cxx | /*******************************************************************************
(c) 2005-2017 Copyright, Real-Time Innovations, Inc. All rights reserved.
RTI grants Licensee a license to use, modify, compile, and create derivative
works of the Software. Licensee has the right to distribute object form only
for use with RTI products. The Software is provided "as is", with no warranty
of any type, including any warranty for fitness for any purpose. RTI is under
no obligation to maintain or support the Software. RTI shall not be liable for
any incidental or consequential damages arising out of the use or inability to
use the software.
******************************************************************************/
#include <algorithm>
#include <iostream>
#include <dds/sub/ddssub.hpp>
#include <dds/core/ddscore.hpp>
// Or simply include <dds/dds.hpp>
#include "waitset_cond_modern.hpp"
int subscriber_main(int domain_id, int sample_count)
{
// Create a DomainParticipant with default Qos
dds::domain::DomainParticipant participant(domain_id);
// Create a Topic -- and automatically register the type
dds::topic::Topic<Foo> topic(participant, "Example Foo");
// Create a DataReader with default Qos (Subscriber created in-line)
dds::sub::DataReader<Foo> reader(dds::sub::Subscriber(participant), topic);
// Create a Status Condition for the reader
dds::core::cond::StatusCondition status_condition(reader);
//Enable statuses configuration for the status that it is desired
status_condition.enabled_statuses(dds::core::status::StatusMask::liveliness_changed());
// Lambda function for the status_condition
// Handler register a custom handler with the condition
status_condition->handler([&reader]() {
// Get the status changes so we can check witch status condition triggered
dds::core::status::StatusMask status_mask = reader.status_changes();
// In Case of Liveliness changed
if ((status_mask &
dds::core::status::StatusMask::liveliness_changed()).any()) {
dds::core::status::LivelinessChangedStatus st =
reader.liveliness_changed_status();
std::cout << "Liveliness changed => Active writers = "
<< st.alive_count() << std::endl;
}
}
); // Create a ReadCondition for any data on this reader and associate a handler
int count = 0;
dds::sub::cond::ReadCondition read_condition(
reader,
dds::sub::status::DataState::any(),
[&reader, &count]()
{
// Take all samples
dds::sub::LoanedSamples<Foo> samples = reader.take();
for (auto sample : samples){
if (sample.info().valid()){
count++;
std::cout << sample.data() << std::endl;
}
}
} // The LoanedSamples destructor returns the loan
);
// Create a WaitSet and attach both ReadCondition and StatusCondition
dds::core::cond::WaitSet waitset;
waitset += read_condition;
waitset += status_condition;
while (count < sample_count || sample_count == 0) {
// Dispatch will call the handlers associated to the WaitSet conditions
// when they activate
waitset.dispatch(dds::core::Duration(4)); // Wait up to 4s each time
}
return 1;
}
int main(int argc, char *argv[])
{
int domain_id = 0;
int sample_count = 0; // infinite loop
if (argc >= 2) {
domain_id = atoi(argv[1]);
}
if (argc >= 3) {
sample_count = atoi(argv[2]);
}
// To turn on additional logging, include <rti/config/Logger.hpp> and
// uncomment the following line:
// rti::config::Logger::instance().verbosity(rti::config::Verbosity::STATUS_ALL);
try {
subscriber_main(domain_id, sample_count);
} catch (const std::exception& ex) {
// This will catch DDS exceptions
std::cerr << "Exception in subscriber_main(): " << ex.what() << std::endl;
return -1;
}
// RTI Connext provides a finalize_participant_factory() method
// if you want to release memory used by the participant factory singleton.
// Uncomment the following line to release the singleton:
//
// dds::domain::DomainParticipant::finalize_participant_factory();
return 0;
}
| cxx |
rticonnextdds-examples | data/projects/rticonnextdds-examples/waitset_status_cond/c++11/waitset_cond_modern_publisher.cxx | /*******************************************************************************
(c) 2005-2017 Copyright, Real-Time Innovations, Inc. All rights reserved.
RTI grants Licensee a license to use, modify, compile, and create derivative
works of the Software. Licensee has the right to distribute object form only
for use with RTI products. The Software is provided "as is", with no warranty
of any type, including any warranty for fitness for any purpose. RTI is under
no obligation to maintain or support 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 "waitset_cond_modern.hpp"
void publisher_main(int domain_id, int sample_count)
{
// Create a DomainParticipant with default Qos
dds::domain::DomainParticipant participant (domain_id);
// Create a Topic -- and automatically register the type
dds::topic::Topic<Foo> topic (participant, "Example Foo");
// Create a DataWriter with default Qos (Publisher created in-line)
dds::pub::DataWriter<Foo> writer(dds::pub::Publisher(participant), topic);
Foo sample;
for (int count = 0; count < sample_count || sample_count == 0; count++) {
std::cout << "Writing Foo, count " << count << std::endl;
sample.x(count);
writer.write(sample);
rti::util::sleep(dds::core::Duration(1));
}
}
int main(int argc, char *argv[])
{
int domain_id = 0;
int sample_count = 0; // infinite loop
if (argc >= 2) {
domain_id = atoi(argv[1]);
}
if (argc >= 3) {
sample_count = atoi(argv[2]);
}
// To turn on additional logging, include <rti/config/Logger.hpp> and
// uncomment the following line:
// rti::config::Logger::instance().verbosity(rti::config::Verbosity::STATUS_ALL);
try {
publisher_main(domain_id, sample_count);
} catch (const std::exception& ex) {
// This will catch DDS exceptions
std::cerr << "Exception in publisher_main(): " << ex.what() << std::endl;
return -1;
}
// RTI Connext provides a finalize_participant_factory() method
// if you want to release memory used by the participant factory singleton.
// Uncomment the following line to release the singleton:
//
// dds::domain::DomainParticipant::finalize_participant_factory();
return 0;
}
| cxx |
rticonnextdds-examples | data/projects/rticonnextdds-examples/using_qos_profiles/c++/profiles_subscriber.cxx | /*******************************************************************************
(c) 2005-2014 Copyright, Real-Time Innovations, Inc. All rights reserved.
RTI grants Licensee a license to use, modify, compile, and create derivative
works of the Software. Licensee has the right to distribute object form only
for use with RTI products. The Software is provided "as is", with no warranty
of any type, including any warranty for fitness for any purpose. RTI is under
no obligation to maintain or support the Software. RTI shall not be liable for
any incidental or consequential damages arising out of the use or inability to
use the software.
******************************************************************************/
/* profiles_subscriber.cxx
A subscription example
This file is derived from code automatically generated by the rtiddsgen
command:
rtiddsgen -language C++ -example <arch> profiles.idl
Example subscription of type profiles automatically generated by
'rtiddsgen'. To test them follow these steps:
(1) Compile this file and the example publication.
(2) Start the subscription with the command
objs/<arch>/profiles_subscriber <domain_id> <sample_count>
(3) Start the publication with the command
objs/<arch>/profiles_publisher <domain_id> <sample_count>
(4) [Optional] Specify the list of discovery initial peers and
multicast receive addresses via an environment variable or a file
(in the current working directory) called NDDS_DISCOVERY_PEERS.
You can run any number of publishers and subscribers programs, and can
add and remove them dynamically from the domain.
Example:
To run the example application on domain <domain_id>:
On Unix:
objs/<arch>/profiles_publisher <domain_id>
objs/<arch>/profiles_subscriber <domain_id>
On Windows:
objs\<arch>\profiles_publisher <domain_id>
objs\<arch>\profiles_subscriber <domain_id>
modification history
------------ -------
*/
#include <stdio.h>
#include <stdlib.h>
#ifdef RTI_VX653
#include <vThreadsData.h>
#endif
#include "profiles.h"
#include "profilesSupport.h"
#include "ndds/ndds_cpp.h"
#define PROFILE_NAME_STRING_LEN 100
class profilesListener : public DDSDataReaderListener {
public:
profilesListener(char listener_name[PROFILE_NAME_STRING_LEN])
{
strcpy(_listener_name, listener_name);
}
virtual void on_requested_deadline_missed(
DDSDataReader* /*reader*/,
const DDS_RequestedDeadlineMissedStatus& /*status*/) {}
virtual void on_requested_incompatible_qos(
DDSDataReader* /*reader*/,
const DDS_RequestedIncompatibleQosStatus& /*status*/) {}
virtual void on_sample_rejected(
DDSDataReader* /*reader*/,
const DDS_SampleRejectedStatus& /*status*/) {}
virtual void on_liveliness_changed(
DDSDataReader* /*reader*/,
const DDS_LivelinessChangedStatus& /*status*/) {}
virtual void on_sample_lost(
DDSDataReader* /*reader*/,
const DDS_SampleLostStatus& /*status*/) {}
virtual void on_subscription_matched(
DDSDataReader* /*reader*/,
const DDS_SubscriptionMatchedStatus& /*status*/) {}
virtual void on_data_available(DDSDataReader* reader);
private:
char _listener_name[PROFILE_NAME_STRING_LEN];
};
void profilesListener::on_data_available(DDSDataReader* reader)
{
profilesDataReader *profiles_reader = NULL;
profilesSeq data_seq;
DDS_SampleInfoSeq info_seq;
DDS_ReturnCode_t retcode;
int i;
profiles_reader = profilesDataReader::narrow(reader);
if (profiles_reader == NULL) {
printf("DataReader narrow error\n");
return;
}
retcode = profiles_reader->take(
data_seq, info_seq, DDS_LENGTH_UNLIMITED,
DDS_ANY_SAMPLE_STATE, DDS_ANY_VIEW_STATE, DDS_ANY_INSTANCE_STATE);
if (retcode == DDS_RETCODE_NO_DATA) {
return;
} else if (retcode != DDS_RETCODE_OK) {
printf("take error %d\n", retcode);
return;
}
printf("=============================================\n");
printf("%s listener received\n", _listener_name);
printf("=============================================\n");
for (i = 0; i < data_seq.length(); ++i) {
if (info_seq[i].valid_data) {
profilesTypeSupport::print_data(&data_seq[i]);
}
}
retcode = profiles_reader->return_loan(data_seq, info_seq);
if (retcode != DDS_RETCODE_OK) {
printf("return loan error %d\n", retcode);
}
}
/* Delete all entities */
static int subscriber_shutdown(
DDSDomainParticipant *participant)
{
DDS_ReturnCode_t retcode;
int status = 0;
if (participant != NULL) {
retcode = participant->delete_contained_entities();
if (retcode != DDS_RETCODE_OK) {
printf("delete_contained_entities error %d\n", retcode);
status = -1;
}
retcode = DDSTheParticipantFactory->delete_participant(participant);
if (retcode != DDS_RETCODE_OK) {
printf("delete_participant error %d\n", retcode);
status = -1;
}
}
/* RTI Connext provides the finalize_instance() method on
domain participant factory for people who want to release memory used
by the participant factory. Uncomment the following block of code for
clean destruction of the singleton. */
/*
retcode = DDSDomainParticipantFactory::finalize_instance();
if (retcode != DDS_RETCODE_OK) {
printf("finalize_instance error %d\n", retcode);
status = -1;
}
*/
return status;
}
extern "C" int subscriber_main(int domainId, int sample_count)
{
DDSDomainParticipant *participant = NULL;
DDSSubscriber *subscriber = NULL;
DDSTopic *topic = NULL;
/* Volatile and transient local readers and profilesListeners */
DDSDataReader *reader_volatile = NULL;
DDSDataReader *reader_transient_local = NULL;
profilesListener *reader_volatile_listener = NULL;
profilesListener *reader_transient_local_listener = NULL;
DDS_ReturnCode_t retcode;
const char *type_name = NULL;
int count = 0;
DDS_Duration_t receive_period = {1,0};
int status = 0;
/* There are several different approaches for loading QoS profiles from XML
* files (see Configuring QoS with XML chapter in the RTI Connext Core
* Libraries and Utilities User's Manual). In this example we illustrate
* two of them:
*
* 1) Creating a file named USER_QOS_PROFILES.xml, which is loaded,
* automatically by the DomainParticipantFactory. In this case, the file
* defines a QoS profile named volatile_profile that configures reliable,
* volatile DataWriters and DataReaders.
*
* 2) Adding XML documents to the DomainParticipantFactory using its
* Profile QoSPolicy (DDS Extension). In this case, we add
* my_custom_qos_profiles.xml to the url_profile sequence, which stores
* the URLs of all the XML documents with QoS policies that are loaded by
* the DomainParticipantFactory aside from the ones that are automatically
* loaded.
* my_custom_qos_profiles.xml defines a QoS profile named
* transient_local_profile that configures reliable, transient local
* DataWriters and DataReaders.
*/
/* To load my_custom_qos_profiles.xml, as explained above, we need to modify
* the DDSTheParticipantFactory Profile QoSPolicy */
DDS_DomainParticipantFactoryQos factory_qos;
DDSTheParticipantFactory->get_qos(factory_qos);
/* We are only going to add one XML file to the url_profile sequence, so we
* ensure a length of 1,1. */
factory_qos.profile.url_profile.ensure_length(1, 1);
/* The XML file will be loaded from the working directory. That means, you
* need to run the example like this:
* ./objs/<architecture>/profiles_publisher
* (see README.txt for more information on how to run the example).
*
* Note that you can specify the absolute path of the XML QoS file to avoid
* this problem.
*/
factory_qos.profile.url_profile[0] =
DDS_String_dup("my_custom_qos_profiles.xml");
DDSTheParticipantFactory->set_qos(factory_qos);
/* Our default Qos profile, volatile_profile, sets the participant name.
* This is the only participant_qos policy that we change in our
* example. As this is done in the default QoS profile, we don't need
* to specify its name, so we can create the participant using the
* create_participant() method rather than using
* create_participant_with_profile(). */
participant = DDSTheParticipantFactory->create_participant(
domainId, DDS_PARTICIPANT_QOS_DEFAULT,
NULL /* listener */, DDS_STATUS_MASK_NONE);
if (participant == NULL) {
printf("create_participant error\n");
subscriber_shutdown(participant);
return -1;
}
/* We haven't changed the subscriber_qos in any of QoS profiles we use in
* this example, so we can just use the create_topic() method. If you want
* to load an specific profile in which you may have changed the
* publisher_qos, use the create_publisher_with_profile() method. */
subscriber = participant->create_subscriber(
DDS_SUBSCRIBER_QOS_DEFAULT, NULL /* listener */, DDS_STATUS_MASK_NONE);
if (subscriber == NULL) {
printf("create_subscriber error\n");
subscriber_shutdown(participant);
return -1;
}
/* Register the type before creating the topic */
type_name = profilesTypeSupport::get_type_name();
retcode = profilesTypeSupport::register_type(
participant, type_name);
if (retcode != DDS_RETCODE_OK) {
printf("register_type error %d\n", retcode);
subscriber_shutdown(participant);
return -1;
}
/* We haven't changed the topic_qos in any of QoS profiles we use in this
* example, so we can just use the create_topic() method. If you want to
* load an specific profile in which you may have changed the topic_qos,
* use the create_topic_with_profile() method. */
topic = participant->create_topic(
"Example profiles",
type_name, DDS_TOPIC_QOS_DEFAULT, NULL /* listener */,
DDS_STATUS_MASK_NONE);
if (topic == NULL) {
printf("create_topic error\n");
subscriber_shutdown(participant);
return -1;
}
/* Create Data Readers listeners */
reader_volatile_listener =
new profilesListener("volatile_profile");
reader_transient_local_listener =
new profilesListener("transient_local_profile");
/* Volatile reader -- As volatile_profile is the default qos profile
* we don't need to specify the profile we are going to use, we can
* just call create_datareader passing DDS_DATAWRITER_QOS_DEFAULT. */
reader_volatile = subscriber->create_datareader(
topic, DDS_DATAREADER_QOS_DEFAULT, reader_volatile_listener,
DDS_STATUS_MASK_ALL);
if (reader_volatile == NULL) {
printf("create_datareader error\n");
subscriber_shutdown(participant);
delete reader_volatile_listener;
return -1;
}
/* Transient Local writer -- In this case we use
* create_datareader_with_profile, because we have to use a profile other
* than the default one. This profile has been defined in
* my_custom_qos_profiles.xml, but since we already loaded the XML file
* we don't need to specify anything else. */
reader_transient_local = subscriber->create_datareader_with_profile(
topic, /* DDS_Topic* */
"profiles_Library", /* library_name */
"transient_local_profile", /* profile_name */
reader_transient_local_listener /* listener */,
DDS_STATUS_MASK_ALL /* DDS_StatusMask */
);
if (reader_transient_local == NULL) {
printf("create_datareader error\n");
subscriber_shutdown(participant);
delete reader_transient_local_listener;
return -1;
}
printf("Created reader_transient_local");
/* Main loop */
for (count=0; (sample_count == 0) || (count < sample_count); ++count) {
NDDSUtility::sleep(receive_period);
}
/* Delete all entities */
status = subscriber_shutdown(participant);
delete reader_volatile_listener;
delete reader_transient_local_listener;
return status;
}
#if defined(RTI_WINCE)
int wmain(int argc, wchar_t** argv)
{
int domainId = 0;
int sample_count = 0; /* infinite loop */
if (argc >= 2) {
domainId = _wtoi(argv[1]);
}
if (argc >= 3) {
sample_count = _wtoi(argv[2]);
}
/* Uncomment this to turn on additional logging
NDDSConfigLogger::get_instance()->
set_verbosity_by_category(NDDS_CONFIG_LOG_CATEGORY_API,
NDDS_CONFIG_LOG_VERBOSITY_STATUS_ALL);
*/
return subscriber_main(domainId, sample_count);
}
#elif !(defined(RTI_VXWORKS) && !defined(__RTP__)) && !defined(RTI_PSOS)
int main(int argc, char *argv[])
{
int domainId = 0;
int sample_count = 0; /* infinite loop */
if (argc >= 2) {
domainId = atoi(argv[1]);
}
if (argc >= 3) {
sample_count = atoi(argv[2]);
}
/* Uncomment this to turn on additional logging
NDDSConfigLogger::get_instance()->
set_verbosity_by_category(NDDS_CONFIG_LOG_CATEGORY_API,
NDDS_CONFIG_LOG_VERBOSITY_STATUS_ALL);
*/
return subscriber_main(domainId, sample_count);
}
#endif
#ifdef RTI_VX653
const unsigned char* __ctype = *(__ctypePtrGet());
extern "C" void usrAppInit ()
{
#ifdef USER_APPL_INIT
USER_APPL_INIT; /* for backwards compatibility */
#endif
/* add application specific code here */
taskSpawn("sub", RTI_OSAPI_THREAD_PRIORITY_NORMAL, 0x8, 0x150000, (FUNCPTR)subscriber_main, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
}
#endif
| cxx |
rticonnextdds-examples | data/projects/rticonnextdds-examples/using_qos_profiles/c++/profiles_publisher.cxx | /*******************************************************************************
(c) 2005-2014 Copyright, Real-Time Innovations, Inc. All rights reserved.
RTI grants Licensee a license to use, modify, compile, and create derivative
works of the Software. Licensee has the right to distribute object form only
for use with RTI products. The Software is provided "as is", with no warranty
of any type, including any warranty for fitness for any purpose. RTI is under
no obligation to maintain or support the Software. RTI shall not be liable for
any incidental or consequential damages arising out of the use or inability to
use the software.
******************************************************************************/
/* profiles_publisher.cxx
A publication of data of type profiles
This file is derived from code automatically generated by the rtiddsgen
command:
rtiddsgen -language C++ -example <arch> profiles.idl
Example publication of type profiles automatically generated by
'rtiddsgen'. To test them follow these steps:
(1) Compile this file and the example subscription.
(2) Start the subscription with the command
objs/<arch>/profiles_subscriber <domain_id> <sample_count>
(3) Start the publication with the command
objs/<arch>/profiles_publisher <domain_id> <sample_count>
(4) [Optional] Specify the list of discovery initial peers and
multicast receive addresses via an environment variable or a file
(in the current working directory) called NDDS_DISCOVERY_PEERS.
You can run any number of publishers and subscribers programs, and can
add and remove them dynamically from the domain.
Example:
To run the example application on domain <domain_id>:
On Unix:
objs/<arch>/profiles_publisher <domain_id> o
objs/<arch>/profiles_subscriber <domain_id>
On Windows:
objs\<arch>\profiles_publisher <domain_id>
objs\<arch>\profiles_subscriber <domain_id>
modification history
------------ -------
*/
#include <stdio.h>
#include <stdlib.h>
#ifdef RTI_VX653
#include <vThreadsData.h>
#endif
#include "profiles.h"
#include "profilesSupport.h"
#include "ndds/ndds_cpp.h"
/* Delete all entities */
static int publisher_shutdown(
DDSDomainParticipant *participant)
{
DDS_ReturnCode_t retcode;
int status = 0;
if (participant != NULL) {
retcode = participant->delete_contained_entities();
if (retcode != DDS_RETCODE_OK) {
printf("delete_contained_entities error %d\n", retcode);
status = -1;
}
retcode = DDSTheParticipantFactory->delete_participant(participant);
if (retcode != DDS_RETCODE_OK) {
printf("delete_participant error %d\n", retcode);
status = -1;
}
}
/* RTI Connext provides finalize_instance() method on
domain participant factory for people who want to release memory used
by the participant factory. Uncomment the following block of code for
clean destruction of the singleton. */
/*
retcode = DDSDomainParticipantFactory::finalize_instance();
if (retcode != DDS_RETCODE_OK) {
printf("finalize_instance error %d\n", retcode);
status = -1;
}
*/
return status;
}
extern "C" int publisher_main(int domainId, int sample_count)
{
DDSDomainParticipant *participant = NULL;
DDSPublisher *publisher = NULL;
DDSTopic *topic = NULL;
/* Volatile and transient local writers and profilesDataWriters */
DDSDataWriter *writer_volatile = NULL;
DDSDataWriter *writer_transient_local = NULL;
profilesDataWriter * profiles_writer_volatile = NULL;
profilesDataWriter * profiles_writer_transient_local = NULL;
profiles *instance = NULL;
DDS_ReturnCode_t retcode;
DDS_InstanceHandle_t instance_handle = DDS_HANDLE_NIL;
const char *type_name = NULL;
int count = 0;
/* Send a new sample every second */
DDS_Duration_t send_period = {1,0};
/* There are several different approaches for loading QoS profiles from XML
* files (see Configuring QoS with XML chapter in the RTI Connext Core
* Libraries and Utilities User's Manual). In this example we illustrate
* two of them:
*
* 1) Creating a file named USER_QOS_PROFILES.xml, which is loaded,
* automatically by the DomainParticipantFactory. In this case, the file
* defines a QoS profile named volatile_profile that configures reliable,
* volatile DataWriters and DataReaders.
*
* 2) Adding XML documents to the DomainParticipantFactory using its
* Profile QoSPolicy (DDS Extension). In this case, we add
* my_custom_qos_profiles.xml to the url_profile sequence, which stores
* the URLs of all the XML documents with QoS policies that are loaded by
* the DomainParticipantFactory aside from the ones that are automatically
* loaded.
* my_custom_qos_profiles.xml defines a QoS profile named
* transient_local_profile that configures reliable, transient local
* DataWriters and DataReaders.
*/
/* To load my_custom_qos_profiles.xml, as explained above, we need to modify
* the DDSTheParticipantFactory Profile QoSPolicy */
DDS_DomainParticipantFactoryQos factory_qos;
DDSTheParticipantFactory->get_qos(factory_qos);
/* We are only going to add one XML file to the url_profile sequence, so we
* ensure a length of 1,1. */
factory_qos.profile.url_profile.ensure_length(1, 1);
/* The XML file will be loaded from the working directory. That means, you
* need to run the example like this:
* ./objs/<architecture>/profiles_publisher
* (see README.txt for more information on how to run the example).
*
* Note that you can specify the absolute path of the XML QoS file to avoid
* this problem.
*/
factory_qos.profile.url_profile[0] =
DDS_String_dup("my_custom_qos_profiles.xml");
DDSTheParticipantFactory->set_qos(factory_qos);
/* Our default Qos profile, volatile_profile, sets the participant name.
* This is the only participant_qos policy that we change in our
* example. As this is done in the default QoS profile, we don't need
* to specify its name, so we can create the participant using the
* create_participant() method rather than using
* create_participant_with_profile(). */
participant = DDSTheParticipantFactory->create_participant(
domainId, DDS_PARTICIPANT_QOS_DEFAULT,
NULL /* listener */, DDS_STATUS_MASK_NONE);
if (participant == NULL) {
printf("create_participant error\n");
publisher_shutdown(participant);
return -1;
}
/* We haven't changed the publisher_qos in any of QoS profiles we use in
* this example, so we can just use the create_publisher() method. If you
* want to load an specific profile in which you may have changed the
* publisher_qos, use the create_publisher_with_profile() method. */
publisher = participant->create_publisher(
DDS_PUBLISHER_QOS_DEFAULT, NULL /* listener */,
DDS_STATUS_MASK_NONE);
if (publisher == NULL) {
printf("create_publisher error\n");
publisher_shutdown(participant);
return -1;
}
/* Register type before creating topic */
type_name = profilesTypeSupport::get_type_name();
retcode = profilesTypeSupport::register_type(
participant, type_name);
if (retcode != DDS_RETCODE_OK) {
printf("register_type error %d\n", retcode);
publisher_shutdown(participant);
return -1;
}
/* We haven't changed the topic_qos in any of QoS profiles we use in this
* example, so we can just use the create_topic() method. If you want to
* load an specific profile in which you may have changed the topic_qos,
* use the create_topic_with_profile() method. */
topic = participant->create_topic(
"Example profiles",
type_name, DDS_TOPIC_QOS_DEFAULT, NULL /* listener */,
DDS_STATUS_MASK_NONE);
if (topic == NULL) {
printf("create_topic error\n");
publisher_shutdown(participant);
return -1;
}
/* Volatile writer -- As volatile_profile is the default qos profile
* we don't need to specify the profile we are going to use, we can
* just call create_datawriter passing DDS_DATAWRITER_QOS_DEFAULT. */
writer_volatile = publisher->create_datawriter(
topic,
DDS_DATAWRITER_QOS_DEFAULT, /* Default datawriter_qos */
NULL /* listener */,
DDS_STATUS_MASK_NONE);
if (writer_volatile == NULL) {
printf("create_datawriter error\n");
publisher_shutdown(participant);
return -1;
}
/* Transient Local writer -- In this case we use
* create_datawriter_with_profile, because we have to use a profile other
* than the default one. This profile has been defined in
* my_custom_qos_profiles.xml, but since we already loaded the XML file
* we don't need to specify anything else. */
writer_transient_local = publisher->create_datawriter_with_profile(
topic, /* DDS_Topic* */
"profiles_Library", /* library_name */
"transient_local_profile", /* profile_name */
NULL /* listener */,
DDS_STATUS_MASK_NONE /* DDS_StatusMask */
);
if (writer_transient_local == NULL) {
printf("create_datawriter error\n");
publisher_shutdown(participant);
return -1;
}
profiles_writer_volatile =
profilesDataWriter::narrow(writer_volatile);
if (profiles_writer_volatile == NULL) {
printf("DataWriter narrow error\n");
publisher_shutdown(participant);
return -1;
}
profiles_writer_transient_local =
profilesDataWriter::narrow(writer_transient_local);
if (profiles_writer_volatile == NULL) {
printf("DataWriter narrow error\n");
publisher_shutdown(participant);
return -1;
}
/* Create data sample for writing */
instance = profilesTypeSupport::create_data();
if (instance == NULL) {
printf("profilesTypeSupport::create_data error\n");
publisher_shutdown(participant);
return -1;
}
/* For a data type that has a key, if the same instance is going to be
written multiple times, initialize the key here
and register the keyed instance prior to writing */
/*
instance_handle = profiles_writer->register_instance(*instance);
*/
/* Main loop */
for (count=0; (sample_count == 0) || (count < sample_count); ++count) {
/* Modify the data to be sent here */
strcpy(instance->profile_name, "volatile_profile");
instance->x = count;
printf("Writing profile_name = %s,\t x = %d\n",
instance->profile_name,
instance->x);
retcode = profiles_writer_volatile->write(*instance, instance_handle);
if (retcode != DDS_RETCODE_OK) {
printf("write error %d\n", retcode);
}
strcpy(instance->profile_name, "transient_local_profile");
instance->x = count;
printf("Writing profile_name = %s,\t x = %d\n\n",
instance->profile_name,
instance->x);
retcode = profiles_writer_transient_local->write(*instance,
instance_handle);
if (retcode != DDS_RETCODE_OK) {
printf("write error %d\n", retcode);
}
NDDSUtility::sleep(send_period);
}
/*
retcode = profiles_writer->unregister_instance(
*instance, instance_handle);
if (retcode != DDS_RETCODE_OK) {
printf("unregister instance error %d\n", retcode);
}
*/
/* Delete data sample */
retcode = profilesTypeSupport::delete_data(instance);
if (retcode != DDS_RETCODE_OK) {
printf("profilesTypeSupport::delete_data error %d\n", retcode);
}
/* Delete all entities */
return publisher_shutdown(participant);
}
#if defined(RTI_WINCE)
int wmain(int argc, wchar_t** argv)
{
int domainId = 0;
int sample_count = 0; /* infinite loop */
if (argc >= 2) {
domainId = _wtoi(argv[1]);
}
if (argc >= 3) {
sample_count = _wtoi(argv[2]);
}
/* Uncomment this to turn on additional logging
NDDSConfigLogger::get_instance()->
set_verbosity_by_category(NDDS_CONFIG_LOG_CATEGORY_API,
NDDS_CONFIG_LOG_VERBOSITY_STATUS_ALL);
*/
return publisher_main(domainId, sample_count);
}
#elif !(defined(RTI_VXWORKS) && !defined(__RTP__)) && !defined(RTI_PSOS)
int main(int argc, char *argv[])
{
int domainId = 0;
int sample_count = 0; /* infinite loop */
if (argc >= 2) {
domainId = atoi(argv[1]);
}
if (argc >= 3) {
sample_count = atoi(argv[2]);
}
/* Uncomment this to turn on additional logging
NDDSConfigLogger::get_instance()->
set_verbosity_by_category(NDDS_CONFIG_LOG_CATEGORY_API,
NDDS_CONFIG_LOG_VERBOSITY_STATUS_ALL);
*/
return publisher_main(domainId, sample_count);
}
#endif
#ifdef RTI_VX653
const unsigned char* __ctype = *(__ctypePtrGet());
extern "C" void usrAppInit ()
{
#ifdef USER_APPL_INIT
USER_APPL_INIT; /* for backwards compatibility */
#endif
/* add application specific code here */
taskSpawn("pub", RTI_OSAPI_THREAD_PRIORITY_NORMAL, 0x8, 0x150000, (FUNCPTR)publisher_main, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
}
#endif
| cxx |
rticonnextdds-examples | data/projects/rticonnextdds-examples/using_qos_profiles/c/profiles_publisher.c | /*******************************************************************************
(c) 2005-2014 Copyright, Real-Time Innovations, Inc. All rights reserved.
RTI grants Licensee a license to use, modify, compile, and create derivative
works of the Software. Licensee has the right to distribute object form only
for use with RTI products. The Software is provided "as is", with no warranty
of any type, including any warranty for fitness for any purpose. RTI is under
no obligation to maintain or support the Software. RTI shall not be liable for
any incidental or consequential damages arising out of the use or inability to
use the software.
******************************************************************************/
/* profiles_publisher.c
A publication of data of type profiles
This file is derived from code automatically generated by the rtiddsgen
command:
rtiddsgen -language C -example <arch> profiles.idl
Example publication of type profiles automatically generated by
'rtiddsgen'. To test them follow these steps:
(1) Compile this file and the example subscription.
(2) Start the subscription with the command
objs/<arch>/profiles_subscriber <domain_id> <sample_count>
(3) Start the publication with the command
objs/<arch>/profiles_publisher <domain_id> <sample_count>
(4) [Optional] Specify the list of discovery initial peers and
multicast receive addresses via an environment variable or a file
(in the current working directory) called NDDS_DISCOVERY_PEERS.
You can run any number of publishers and subscribers programs, and can
add and remove them dynamically from the domain.
Example:
To run the example application on domain <domain_id>:
On Unix:
objs/<arch>/profiles_publisher <domain_id>
objs/<arch>/profiles_subscriber <domain_id>
On Windows:
objs\<arch>\profiles_publisher <domain_id>
objs\<arch>\profiles_subscriber <domain_id>
modification history
------------ -------
*/
#include <stdio.h>
#include <stdlib.h>
#include "ndds/ndds_c.h"
#include "profiles.h"
#include "profilesSupport.h"
#define NUM_PROFILE_FILES 1
/* Delete all entities */
static int publisher_shutdown(
DDS_DomainParticipant *participant,
struct DDS_DomainParticipantFactoryQos *factory_qos)
{
DDS_ReturnCode_t retcode;
int status = 0;
retcode = DDS_DomainParticipantFactoryQos_finalize(factory_qos);
if (retcode != DDS_RETCODE_OK) {
printf("FactoryQos_finalize error %d\n", retcode);
status = -1;
}
if (participant != NULL) {
retcode = DDS_DomainParticipant_delete_contained_entities(participant);
if (retcode != DDS_RETCODE_OK) {
printf("delete_contained_entities error %d\n", retcode);
status = -1;
}
retcode = DDS_DomainParticipantFactory_delete_participant(
DDS_TheParticipantFactory, participant);
if (retcode != DDS_RETCODE_OK) {
printf("delete_participant error %d\n", retcode);
status = -1;
}
}
/* RTI Connext provides finalize_instance() method on
domain participant factory for people who want to release memory used
by the participant factory. Uncomment the following block of code for
clean destruction of the singleton. */
/*
retcode = DDS_DomainParticipantFactory_finalize_instance();
if (retcode != DDS_RETCODE_OK) {
printf("finalize_instance error %d\n", retcode);
status = -1;
}
*/
return status;
}
static int publisher_main(int domainId, int sample_count)
{
DDS_DomainParticipant *participant = NULL;
DDS_Publisher *publisher = NULL;
DDS_Topic *topic = NULL;
/* Volatile and transient local writers and profilesDataWriters */
DDS_DataWriter *writer_volatile = NULL;
DDS_DataWriter * writer_transient_local = NULL;
profilesDataWriter *profiles_writer_volatile = NULL;
profilesDataWriter *profiles_writer_transient_local = NULL;
profiles *instance = NULL;
DDS_ReturnCode_t retcode;
DDS_InstanceHandle_t instance_handle = DDS_HANDLE_NIL;
const char *type_name = NULL;
int count = 0;
/* Send a new sample every second */
struct DDS_Duration_t send_period = {1,0};
struct DDS_DomainParticipantFactoryQos factory_qos =
DDS_DomainParticipantFactoryQos_INITIALIZER;
static const char *myUrlProfile[NUM_PROFILE_FILES] =
{"file://./my_custom_qos_profiles.xml"};
/* There are several different approaches for loading QoS profiles from XML
* files (see Configuring QoS with XML chapter in the RTI Connext Core
* Libraries and Utilities User's Manual). In this example we illustrate
* two of them:
*
* 1) Creating a file named USER_QOS_PROFILES.xml, which is loaded,
* automatically by the DomainParticipantFactory. In this case, the file
* defines a QoS profile named volatile_profile that configures reliable,
* volatile DataWriters and DataReaders.
*
* 2) Adding XML documents to the DomainParticipantFactory using its
* Profile QoSPolicy (DDS Extension). In this case, we add
* my_custom_qos_profiles.xml to the url_profile sequence, which stores
* the URLs of all the XML documents with QoS policies that are loaded by
* the DomainParticipantFactory aside from the ones that are automatically
* loaded.
* my_custom_qos_profiles.xml defines a QoS profile named
* transient_local_profile that configures reliable, transient local
* DataWriters and DataReaders.
*/
/* To load my_custom_qos_profiles.xml, as explained above, we need to modify
* the DDSTheParticipantFactory Profile QoSPolicy */
DDS_DomainParticipantFactory_get_qos(DDS_TheParticipantFactory,
&factory_qos);
/* We are only going to add one XML file to the url_profile sequence, so our
* NUM_PROFILE_FILES is 1 (defined at start) */
DDS_StringSeq_from_array(&(factory_qos.profile.url_profile),
(const char **) myUrlProfile, NUM_PROFILE_FILES);
/* The XML file will be loaded from the working directory. That means, you
* need to run the example like this:
* ./objs/<architecture>/profiles_publisher
* (see README.txt for more information on how to run the example).
*
* Note that you can specify the absolute path of the XML QoS file to avoid
* this problem.
*/
retcode = DDS_DomainParticipantFactory_set_qos(DDS_TheParticipantFactory,
&factory_qos);
if (retcode != DDS_RETCODE_OK) {
printf("set_qos error %d\n", retcode);
publisher_shutdown(participant, &factory_qos);
return -1;
}
/* Our default Qos profile, volatile_profile, sets the participant name.
* This is the only participant_qos policy that we change in our
* example. As this is done in the default QoS profile, we don't need
* to specify its name, so we can create the participant using the
* create_participant() method rather than using
* create_participant_with_profile(). */
participant = DDS_DomainParticipantFactory_create_participant(
DDS_TheParticipantFactory, domainId, &DDS_PARTICIPANT_QOS_DEFAULT,
NULL /* listener */, DDS_STATUS_MASK_NONE);
if (participant == NULL) {
printf("create_participant error\n");
publisher_shutdown(participant, &factory_qos);
return -1;
}
/* We haven't changed the publisher_qos in any of QoS profiles we use in
* this example, so we can just use the create_publisher() method. If you
* want to load an specific profile in which you may have changed the
* publisher_qos, use the create_publisher_with_profile() method. */
publisher = DDS_DomainParticipant_create_publisher(
participant, &DDS_PUBLISHER_QOS_DEFAULT, NULL /* listener */,
DDS_STATUS_MASK_NONE);
if (publisher == NULL) {
printf("create_publisher error\n");
publisher_shutdown(participant, &factory_qos);
return -1;
}
/* Register type before creating topic */
type_name = profilesTypeSupport_get_type_name();
retcode = profilesTypeSupport_register_type(
participant, type_name);
if (retcode != DDS_RETCODE_OK) {
printf("register_type error %d\n", retcode);
publisher_shutdown(participant, &factory_qos);
return -1;
}
/* We haven't changed the topic_qos in any of QoS profiles we use in this
* example, so we can just use the create_topic() method. If you want to
* load an specific profile in which you may have changed the topic_qos,
* use the create_topic_with_profile() method. */
topic = DDS_DomainParticipant_create_topic(
participant, "Example profiles",
type_name, &DDS_TOPIC_QOS_DEFAULT, NULL /* listener */,
DDS_STATUS_MASK_NONE);
if (topic == NULL) {
printf("create_topic error\n");
publisher_shutdown(participant, &factory_qos);
return -1;
}
/* Volatile writer -- As volatile_profile is the default qos profile
* we don't need to specify the profile we are going to use, we can
* just call create_datawriter passing DDS_DATAWRITER_QOS_DEFAULT. */
writer_volatile = DDS_Publisher_create_datawriter(
publisher,
topic,
&DDS_DATAWRITER_QOS_DEFAULT, /* Default datawriter_qos */
NULL /* listener */,
DDS_STATUS_MASK_NONE);
if (writer_volatile == NULL) {
printf("create_datawriter error\n");
publisher_shutdown(participant, &factory_qos);
return -1;
}
/* Transient Local writer -- In this case we use
* create_datawriter_with_profile, because we have to use a profile other
* than the default one. This profile has been defined in
* my_custom_qos_profiles.xml, but since we already loaded the XML file
* we don't need to specify anything else. */
writer_transient_local = DDS_Publisher_create_datawriter_with_profile(
publisher, /* publisher which creates the writer */
topic, /* DDS_topic */
"profiles_Library", /* library_name */
"transient_local_profile", /*profile_name */
NULL /* listener */,
DDS_STATUS_MASK_NONE);
if (writer_transient_local == NULL) {
printf("create_datawriter_with_profile error\n");
publisher_shutdown(participant, &factory_qos);
return -1;
}
profiles_writer_volatile = profilesDataWriter_narrow(writer_volatile);
if (profiles_writer_volatile == NULL) {
printf("DataWriter narrow error\n");
publisher_shutdown(participant, &factory_qos);
return -1;
}
profiles_writer_transient_local = profilesDataWriter_narrow(
writer_transient_local);
if (profiles_writer_transient_local == NULL) {
printf("DataWriter narrow error\n");
publisher_shutdown(participant, &factory_qos);
return -1;
}
/* Create data sample for writing */
instance = profilesTypeSupport_create_data_ex(DDS_BOOLEAN_TRUE);
if (instance == NULL) {
printf("profilesTypeSupport_create_data error\n");
publisher_shutdown(participant, &factory_qos);
return -1;
}
/* For a data type that has a key, if the same instance is going to be
written multiple times, initialize the key here
and register the keyed instance prior to writing */
/*
instance_handle = profilesDataWriter_register_instance(
profiles_writer, instance);
*/
/* Main loop */
for (count=0; (sample_count == 0) || (count < sample_count); ++count) {
printf("Writing profiles, count %d\n", count);
/* Modify the data to be written here */
strcpy(instance->profile_name, "volatile_profile");
instance->x = count;
printf("Writing profile_name = %s,\t x = %d\n",
instance->profile_name,
instance->x);
retcode = profilesDataWriter_write(profiles_writer_volatile, instance,
&instance_handle);
if (retcode != DDS_RETCODE_OK) {
printf("write error %d\n", retcode);
}
strcpy(instance->profile_name, "transient_local_profile");
instance->x = count;
printf("Writing profile_name = %s,\t x = %d\n\n",
instance->profile_name,
instance->x);
retcode = profilesDataWriter_write(
profiles_writer_transient_local, instance, &instance_handle);
if (retcode != DDS_RETCODE_OK) {
printf("write error %d\n", retcode);
}
NDDS_Utility_sleep(&send_period);
}
/*
retcode = profilesDataWriter_unregister_instance(
profiles_writer, instance, &instance_handle);
if (retcode != DDS_RETCODE_OK) {
printf("unregister instance error %d\n", retcode);
}
*/
/* Delete data sample */
retcode = profilesTypeSupport_delete_data_ex(instance, DDS_BOOLEAN_TRUE);
if (retcode != DDS_RETCODE_OK) {
printf("profilesTypeSupport_delete_data error %d\n", retcode);
}
/* Cleanup and delete delete all entities */
return publisher_shutdown(participant, &factory_qos);
}
#if defined(RTI_WINCE)
int wmain(int argc, wchar_t** argv)
{
int domainId = 0;
int sample_count = 0; /* infinite loop */
if (argc >= 2) {
domainId = _wtoi(argv[1]);
}
if (argc >= 3) {
sample_count = _wtoi(argv[2]);
}
/* Uncomment this to turn on additional logging
NDDS_Config_Logger_set_verbosity_by_category(
NDDS_Config_Logger_get_instance(),
NDDS_CONFIG_LOG_CATEGORY_API,
NDDS_CONFIG_LOG_VERBOSITY_STATUS_ALL);
*/
return publisher_main(domainId, sample_count);
}
#elif !(defined(RTI_VXWORKS) && !defined(__RTP__)) && !defined(RTI_PSOS)
int main(int argc, char *argv[])
{
int domainId = 0;
int sample_count = 0; /* infinite loop */
if (argc >= 2) {
domainId = atoi(argv[1]);
}
if (argc >= 3) {
sample_count = atoi(argv[2]);
}
/* Uncomment this to turn on additional logging
NDDS_Config_Logger_set_verbosity_by_category(
NDDS_Config_Logger_get_instance(),
NDDS_CONFIG_LOG_CATEGORY_API,
NDDS_CONFIG_LOG_VERBOSITY_STATUS_ALL);
*/
return publisher_main(domainId, sample_count);
}
#endif
#ifdef RTI_VX653
const unsigned char* __ctype = NULL;
void usrAppInit ()
{
#ifdef USER_APPL_INIT
USER_APPL_INIT; /* for backwards compatibility */
#endif
/* add application specific code here */
taskSpawn("pub", RTI_OSAPI_THREAD_PRIORITY_NORMAL, 0x8, 0x150000, (FUNCPTR)publisher_main, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
}
#endif
| c |
rticonnextdds-examples | data/projects/rticonnextdds-examples/using_qos_profiles/c/profiles_subscriber.c | /*******************************************************************************
(c) 2005-2014 Copyright, Real-Time Innovations, Inc. All rights reserved.
RTI grants Licensee a license to use, modify, compile, and create derivative
works of the Software. Licensee has the right to distribute object form only
for use with RTI products. The Software is provided "as is", with no warranty
of any type, including any warranty for fitness for any purpose. RTI is under
no obligation to maintain or support the Software. RTI shall not be liable for
any incidental or consequential damages arising out of the use or inability to
use the software.
******************************************************************************/
/* profiles_subscriber.c
A subscription example
This file is derived from code automatically generated by the rtiddsgen
command:
rtiddsgen -language C -example <arch> profiles.idl
Example subscription of type profiles automatically generated by
'rtiddsgen'. To test them, follow these steps:
(1) Compile this file and the example publication.
(2) Start the subscription with the command
objs/<arch>/profiles_subscriber <domain_id> <sample_count>
(3) Start the publication with the command
objs/<arch>/profiles_publisher <domain_id> <sample_count>
(4) [Optional] Specify the list of discovery initial peers and
multicast receive addresses via an environment variable or a file
(in the current working directory) called NDDS_DISCOVERY_PEERS.
You can run any number of publishers and subscribers programs, and can
add and remove them dynamically from the domain.
Example:
To run the example application on domain <domain_id>:
On UNIX systems:
objs/<arch>/profiles_publisher <domain_id>
objs/<arch>/profiles_subscriber <domain_id>
On Windows systems:
objs\<arch>\profiles_publisher <domain_id>
objs\<arch>\profiles_subscriber <domain_id>
modification history
------------ -------
*/
#include <stdio.h>
#include <stdlib.h>
#include "ndds/ndds_c.h"
#include "profiles.h"
#include "profilesSupport.h"
#define NUM_PROFILE_FILES 1
void profilesListener_on_requested_deadline_missed(
void* listener_data,
DDS_DataReader* reader,
const struct DDS_RequestedDeadlineMissedStatus *status)
{
}
void profilesListener_on_requested_incompatible_qos(
void* listener_data,
DDS_DataReader* reader,
const struct DDS_RequestedIncompatibleQosStatus *status)
{
}
void profilesListener_on_sample_rejected(
void* listener_data,
DDS_DataReader* reader,
const struct DDS_SampleRejectedStatus *status)
{
}
void profilesListener_on_liveliness_changed(
void* listener_data,
DDS_DataReader* reader,
const struct DDS_LivelinessChangedStatus *status)
{
}
void profilesListener_on_sample_lost(
void* listener_data,
DDS_DataReader* reader,
const struct DDS_SampleLostStatus *status)
{
}
void profilesListener_on_subscription_matched(
void* listener_data,
DDS_DataReader* reader,
const struct DDS_SubscriptionMatchedStatus *status)
{
}
void profilesListener_on_data_available(
void* listener_data,
DDS_DataReader* reader)
{
profilesDataReader *profiles_reader = NULL;
struct profilesSeq data_seq = DDS_SEQUENCE_INITIALIZER;
struct DDS_SampleInfoSeq info_seq = DDS_SEQUENCE_INITIALIZER;
DDS_ReturnCode_t retcode;
int i;
profiles_reader = profilesDataReader_narrow(reader);
if (profiles_reader == NULL) {
printf("DataReader narrow error\n");
return;
}
retcode = profilesDataReader_take(
profiles_reader,
&data_seq, &info_seq, DDS_LENGTH_UNLIMITED,
DDS_ANY_SAMPLE_STATE, DDS_ANY_VIEW_STATE, DDS_ANY_INSTANCE_STATE);
if (retcode == DDS_RETCODE_NO_DATA) {
return;
} else if (retcode != DDS_RETCODE_OK) {
printf("take error %d\n", retcode);
return;
}
printf("=============================================\n");
printf("listener received\n");
printf("=============================================\n");
for (i = 0; i < profilesSeq_get_length(&data_seq); ++i) {
if (DDS_SampleInfoSeq_get_reference(&info_seq, i)->valid_data) {
profilesTypeSupport_print_data(
profilesSeq_get_reference(&data_seq, i));
}
}
retcode = profilesDataReader_return_loan(
profiles_reader,
&data_seq, &info_seq);
if (retcode != DDS_RETCODE_OK) {
printf("return loan error %d\n", retcode);
}
}
/* Delete all entities */
static int subscriber_shutdown(
DDS_DomainParticipant *participant,
struct DDS_DomainParticipantFactoryQos *factory_qos)
{
DDS_ReturnCode_t retcode;
int status = 0;
retcode = DDS_DomainParticipantFactoryQos_finalize(factory_qos);
if (retcode != DDS_RETCODE_OK) {
printf("FactoryQos_finalize error %d\n", retcode);
status = -1;
}
if (participant != NULL) {
retcode = DDS_DomainParticipant_delete_contained_entities(participant);
if (retcode != DDS_RETCODE_OK) {
printf("delete_contained_entities error %d\n", retcode);
status = -1;
}
retcode = DDS_DomainParticipantFactory_delete_participant(
DDS_TheParticipantFactory, participant);
if (retcode != DDS_RETCODE_OK) {
printf("delete_participant error %d\n", retcode);
status = -1;
}
}
/* RTI Connext provides the finalize_instance() method on
domain participant factory for users who want to release memory used
by the participant factory. Uncomment the following block of code for
clean destruction of the singleton. */
/*
retcode = DDS_DomainParticipantFactory_finalize_instance();
if (retcode != DDS_RETCODE_OK) {
printf("finalize_instance error %d\n", retcode);
status = -1;
}
*/
return status;
}
static int subscriber_main(int domainId, int sample_count)
{
DDS_DomainParticipant *participant = NULL;
DDS_Subscriber *subscriber = NULL;
DDS_Topic *topic = NULL;
struct DDS_DataReaderListener reader_volatile_listener =
DDS_DataReaderListener_INITIALIZER;
struct DDS_DataReaderListener reader_transient_local_listener =
DDS_DataReaderListener_INITIALIZER;
DDS_DataReader *reader_volatile = NULL;
DDS_DataReader *reader_transient_local = NULL;
DDS_ReturnCode_t retcode;
const char *type_name = NULL;
int count = 0;
struct DDS_Duration_t poll_period = {1,0};
int status = 0;
struct DDS_DomainParticipantFactoryQos factory_qos =
DDS_DomainParticipantFactoryQos_INITIALIZER;
static const char *myUrlProfile[NUM_PROFILE_FILES] =
{"file://./my_custom_qos_profiles.xml"};
/* There are several different approaches for loading QoS profiles from XML
* files (see Configuring QoS with XML chapter in the RTI Connext Core
* Libraries and Utilities User's Manual). In this example we illustrate
* two of them:
*
* 1) Creating a file named USER_QOS_PROFILES.xml, which is loaded,
* automatically by the DomainParticipantFactory. In this case, the file
* defines a QoS profile named volatile_profile that configures reliable,
* volatile DataWriters and DataReaders.
*
* 2) Adding XML documents to the DomainParticipantFactory using its
* Profile QoSPolicy (DDS Extension). In this case, we add
* my_custom_qos_profiles.xml to the url_profile sequence, which stores
* the URLs of all the XML documents with QoS policies that are loaded by
* the DomainParticipantFactory aside from the ones that are automatically
* loaded.
* my_custom_qos_profiles.xml defines a QoS profile named
* transient_local_profile that configures reliable, transient local
* DataWriters and DataReaders.
*/
/* To load my_custom_qos_profiles.xml, as explained above, we need to modify
* the DDSTheParticipantFactory Profile QoSPolicy */
DDS_DomainParticipantFactory_get_qos(DDS_TheParticipantFactory,
&factory_qos);
/* We are only going to add one XML file to the url_profile sequence, so our
* NUM_PROFILE_FILES is 1 (defined at start) */
DDS_StringSeq_from_array(&(factory_qos.profile.url_profile),
(const char **) myUrlProfile, NUM_PROFILE_FILES);
/* The XML file will be loaded from the working directory. That means, you
* need to run the example like this:
* ./objs/<architecture>/profiles_publisher
* (see README.txt for more information on how to run the example).
*
* Note that you can specify the absolute path of the XML QoS file to avoid
* this problem.
*/
retcode = DDS_DomainParticipantFactory_set_qos(DDS_TheParticipantFactory,
&factory_qos);
if (retcode != DDS_RETCODE_OK) {
printf("set_qos error %d\n", retcode);
subscriber_shutdown(participant, &factory_qos);
return -1;
}
/* Our default Qos profile, volatile_profile, sets the participant name.
* This is the only participant_qos policy that we change in our
* example. As this is done in the default QoS profile, we don't need
* to specify its name, so we can create the participant using the
* create_participant() method rather than using
* create_participant_with_profile(). */
participant = DDS_DomainParticipantFactory_create_participant(
DDS_TheParticipantFactory, domainId, &DDS_PARTICIPANT_QOS_DEFAULT,
NULL /* listener */, DDS_STATUS_MASK_NONE);
if (participant == NULL) {
printf("create_participant error\n");
subscriber_shutdown(participant, &factory_qos);
return -1;
}
/* We haven't changed the subscriber_qos in any of QoS profiles we use in
* this example, so we can just use the create_topic() method. If you want
* to load an specific profile in which you may have changed the
* publisher_qos, use the create_publisher_with_profile() method. */
subscriber = DDS_DomainParticipant_create_subscriber(
participant, &DDS_SUBSCRIBER_QOS_DEFAULT, NULL /* listener */,
DDS_STATUS_MASK_NONE);
if (subscriber == NULL) {
printf("create_subscriber error\n");
subscriber_shutdown(participant, &factory_qos);
return -1;
}
/* Register the type before creating the topic */
type_name = profilesTypeSupport_get_type_name();
retcode = profilesTypeSupport_register_type(participant, type_name);
if (retcode != DDS_RETCODE_OK) {
printf("register_type error %d\n", retcode);
subscriber_shutdown(participant, &factory_qos);
return -1;
}
/* We haven't changed the topic_qos in any of QoS profiles we use in this
* example, so we can just use the create_topic() method. If you want to
* load an specific profile in which you may have changed the topic_qos,
* use the create_topic_with_profile() method. */
topic = DDS_DomainParticipant_create_topic(
participant, "Example profiles",
type_name, &DDS_TOPIC_QOS_DEFAULT, NULL /* listener */,
DDS_STATUS_MASK_NONE);
if (topic == NULL) {
printf("create_topic error\n");
subscriber_shutdown(participant, &factory_qos);
return -1;
}
/* Set up a data reader listener */
reader_volatile_listener.on_requested_deadline_missed =
profilesListener_on_requested_deadline_missed;
reader_volatile_listener.on_requested_incompatible_qos =
profilesListener_on_requested_incompatible_qos;
reader_volatile_listener.on_sample_rejected =
profilesListener_on_sample_rejected;
reader_volatile_listener.on_liveliness_changed =
profilesListener_on_liveliness_changed;
reader_volatile_listener.on_sample_lost =
profilesListener_on_sample_lost;
reader_volatile_listener.on_subscription_matched =
profilesListener_on_subscription_matched;
reader_volatile_listener.on_data_available =
profilesListener_on_data_available;
reader_transient_local_listener.on_requested_deadline_missed =
profilesListener_on_requested_deadline_missed;
reader_transient_local_listener.on_requested_incompatible_qos =
profilesListener_on_requested_incompatible_qos;
reader_transient_local_listener.on_sample_rejected =
profilesListener_on_sample_rejected;
reader_transient_local_listener.on_liveliness_changed =
profilesListener_on_liveliness_changed;
reader_transient_local_listener.on_sample_lost =
profilesListener_on_sample_lost;
reader_transient_local_listener.on_subscription_matched =
profilesListener_on_subscription_matched;
reader_transient_local_listener.on_data_available =
profilesListener_on_data_available;
/* Volatile reader -- As volatile_profile is the default qos profile
* we don't need to specify the profile we are going to use, we can
* just call create_datareader passing DDS_DATAWRITER_QOS_DEFAULT. */
reader_volatile = DDS_Subscriber_create_datareader(
subscriber, DDS_Topic_as_topicdescription(topic),
&DDS_DATAREADER_QOS_DEFAULT, &reader_volatile_listener,
DDS_STATUS_MASK_ALL);
if (reader_volatile == NULL) {
printf("create_datareader error\n");
subscriber_shutdown(participant, &factory_qos);
return -1;
}
/* Transient Local writer -- In this case we use
* create_datareader_with_profile, because we have to use a profile other
* than the default one. This profile has been defined in
* my_custom_qos_profiles.xml, but since we already loaded the XML file
* we don't need to specify anything else. */
reader_transient_local = DDS_Subscriber_create_datareader_with_profile(
subscriber,
DDS_Topic_as_topicdescription(topic),
"profiles_Library", /* library_name */
"transient_local_profile", /* profile_name */
&reader_transient_local_listener, /* listener */
DDS_STATUS_MASK_ALL);
if (reader_transient_local == NULL) {
printf("create_datareader error\n");
subscriber_shutdown(participant, &factory_qos);
return -1;
}
/* Main loop */
for (count=0; (sample_count == 0) || (count < sample_count); ++count) {
printf("profiles subscriber sleeping for %d sec...\n",
poll_period.sec);
NDDS_Utility_sleep(&poll_period);
}
/* Cleanup and delete all entities */
return subscriber_shutdown(participant, &factory_qos);
}
#if defined(RTI_WINCE)
int wmain(int argc, wchar_t** argv)
{
int domainId = 0;
int sample_count = 0; /* infinite loop */
if (argc >= 2) {
domainId = _wtoi(argv[1]);
}
if (argc >= 3) {
sample_count = _wtoi(argv[2]);
}
/* Uncomment this to turn on additional logging
NDDS_Config_Logger_set_verbosity_by_category(
NDDS_Config_Logger_get_instance(),
NDDS_CONFIG_LOG_CATEGORY_API,
NDDS_CONFIG_LOG_VERBOSITY_STATUS_ALL);
*/
return subscriber_main(domainId, sample_count);
}
#elif !(defined(RTI_VXWORKS) && !defined(__RTP__)) && !defined(RTI_PSOS)
int main(int argc, char *argv[])
{
int domainId = 0;
int sample_count = 0; /* infinite loop */
if (argc >= 2) {
domainId = atoi(argv[1]);
}
if (argc >= 3) {
sample_count = atoi(argv[2]);
}
/* Uncomment this to turn on additional logging
NDDS_Config_Logger_set_verbosity_by_category(
NDDS_Config_Logger_get_instance(),
NDDS_CONFIG_LOG_CATEGORY_API,
NDDS_CONFIG_LOG_VERBOSITY_STATUS_ALL);
*/
return subscriber_main(domainId, sample_count);
}
#endif
#ifdef RTI_VX653
const unsigned char* __ctype = NULL;
void usrAppInit ()
{
#ifdef USER_APPL_INIT
USER_APPL_INIT; /* for backwards compatibility */
#endif
/* add application specific code here */
taskSpawn("sub", RTI_OSAPI_THREAD_PRIORITY_NORMAL, 0x8, 0x150000, (FUNCPTR)subscriber_main, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
}
#endif
| c |
rticonnextdds-examples | data/projects/rticonnextdds-examples/using_qos_profiles/c++03/profiles_subscriber.cxx | /*******************************************************************************
(c) 2005-2015 Copyright, Real-Time Innovations, Inc. All rights reserved.
RTI grants Licensee a license to use, modify, compile, and create derivative
works of the Software. Licensee has the right to distribute object form only
for use with RTI products. The Software is provided "as is", with no warranty
of any type, including any warranty for fitness for any purpose. RTI is under
no obligation to maintain or support the Software. RTI shall not be liable for
any incidental or consequential damages arising out of the use or inability to
use the software.
******************************************************************************/
#include <iostream>
#include <cstdlib>
#include <dds/dds.hpp>
#include <rti/core/ListenerBinder.hpp>
#include "profiles.hpp"
using namespace dds::core;
using namespace dds::core::status;
using namespace dds::domain;
using namespace dds::topic;
using namespace dds::sub;
class ProfilesListener : public NoOpDataReaderListener<profiles> {
public:
ProfilesListener(std::string name) : listener_name_(name)
{
}
void on_data_available(DataReader<profiles>& reader)
{
// Take all samples
LoanedSamples<profiles> samples = reader.take();
std::cout << "============================================="
<< std::endl << listener_name() << " listener received"
<< std::endl;
for (LoanedSamples<profiles>::iterator sample_it = samples.begin();
sample_it != samples.end(); sample_it++) {
if (sample_it->info().valid()) {
std::cout << sample_it->data() << std::endl;
}
}
std::cout << "============================================="
<< std::endl << std::endl;
}
std::string listener_name() const
{
return listener_name_;
}
private:
const std::string listener_name_;
};
void subscriber_main(int domain_id, int sample_count)
{
// Retrieve QoS from custom profile XML and USER_QOS_PROFILES.xml
QosProvider qos_provider("my_custom_qos_profiles.xml");
// Create a DomainParticipant with the default QoS of the provider.
DomainParticipant participant(domain_id, qos_provider.participant_qos());
// Create a Subscriber with default QoS.
Subscriber subscriber(participant, qos_provider.subscriber_qos());
// Create a Topic with default QoS.
Topic<profiles> topic(
participant,
"Example profiles",
qos_provider.topic_qos());
// Create a DataWriter with the QoS profile "transient_local_profile" that
// it is inside the QoS library "profiles_Library".
DataReader<profiles> reader_transient_local(subscriber, topic,
qos_provider.datareader_qos(
"profiles_Library::transient_local_profile"));
// Use a ListeberBinder to take care of resetting and deleting the listener.
rti::core::ListenerBinder<DataReader<profiles> > scoped_transient_listener =
rti::core::bind_and_manage_listener(
reader_transient_local,
new ProfilesListener("transient_local_profile"),
StatusMask::data_available());
// Create a DataReader with the QoS profile "volatile_profile" that it is
// inside the QoS library "profiles_Library".
DataReader<profiles> reader_volatile(subscriber, topic,
qos_provider.datareader_qos(
"profiles_Library::volatile_profile"));
// Use a ListeberBinder to take care of resetting and deleting the listener.
rti::core::ListenerBinder<DataReader<profiles> > scoped_volatile_listener =
rti::core::bind_and_manage_listener(
reader_volatile,
new ProfilesListener("volatile_profile"),
StatusMask::data_available());
// Main loop.
for (int count = 0; (sample_count == 0) || (count < sample_count); ++count){
rti::util::sleep(Duration(1));
}
}
int main(int argc, char* argv[])
{
int domain_id = 0;
int sample_count = 0; // Infinite loop
if (argc >= 2) {
domain_id = atoi(argv[1]);
}
if (argc >= 3) {
sample_count = atoi(argv[2]);
}
// To turn on additional logging, include <rti/config/Logger.hpp> and
// uncomment the following line:
// rti::config::Logger::instance().verbosity(rti::config::Verbosity::STATUS_ALL);
try {
subscriber_main(domain_id, sample_count);
} catch (const std::exception& ex) {
// This will catch DDS exceptions
std::cerr << "Exception in subscriber_main: " << ex.what() << std::endl;
return -1;
}
return 0;
}
| cxx |
rticonnextdds-examples | data/projects/rticonnextdds-examples/using_qos_profiles/c++03/profiles_publisher.cxx | /*******************************************************************************
(c) 2005-2015 Copyright, Real-Time Innovations, Inc. All rights reserved.
RTI grants Licensee a license to use, modify, compile, and create derivative
works of the Software. Licensee has the right to distribute object form only
for use with RTI products. The Software is provided "as is", with no warranty
of any type, including any warranty for fitness for any purpose. RTI is under
no obligation to maintain or support the Software. RTI shall not be liable for
any incidental or consequential damages arising out of the use or inability to
use the software.
******************************************************************************/
#include <iostream>
#include <cstdlib>
#include <dds/dds.hpp>
#include "profiles.hpp"
using namespace dds::core;
using namespace dds::domain;
using namespace dds::topic;
using namespace dds::pub;
void publisher_main(int domain_id, int sample_count)
{
// Retrieve QoS from custom profile XML and USER_QOS_PROFILES.xml
QosProvider qos_provider("my_custom_qos_profiles.xml");
// Create a DomainParticipant with the default QoS of the provider.
DomainParticipant participant(domain_id, qos_provider.participant_qos());
// Create a Publisher with default QoS.
Publisher publisher(participant, qos_provider.publisher_qos());
// Create a Topic with default QoS.
Topic<profiles> topic(
participant,
"Example profiles",
qos_provider.topic_qos());
// Create a DataWriter with the QoS profile "transient_local_profile",
// from QoS library "profiles_Library".
DataWriter<profiles> writer_transient_local(publisher, topic,
qos_provider.datawriter_qos(
"profiles_Library::transient_local_profile"));
// Create a DataReader with the QoS profile "volatile_profile",
// from the QoS library "profiles_Library".
DataWriter<profiles> writer_volatile(publisher, topic,
qos_provider.datawriter_qos(
"profiles_Library::volatile_profile"));
// Create a data sample for writing.
profiles instance;
// Main loop.
for (int count = 0; (sample_count == 0) || (count < sample_count); ++count){
// Update the counter value of the sample.
instance.x(count);
// Send the sample using the DataWriter with "volatile" durability.
std::cout << "Writing profile_name = volatile_profile,\t x = " << count
<< std::endl;
instance.profile_name("volatile_profile");
writer_volatile.write(instance);
// Send the sample using the DataWriter with "transient_local"
// durability.
std::cout << "Writing profile_name = transient_local_profile,\t x = "
<< count << std::endl << std::endl;
instance.profile_name("transient_local_profile");
writer_transient_local.write(instance);
// Send the sample every second.
rti::util::sleep(Duration(1));
}
}
int main(int argc, char* argv[])
{
int domain_id = 0;
int sample_count = 0; // Infinite loop
if (argc >= 2) {
domain_id = atoi(argv[1]);
}
if (argc >= 3) {
sample_count = atoi(argv[2]);
}
// To turn on additional logging, include <rti/config/Logger.hpp> and
// uncomment the following line:
// rti::config::Logger::instance().verbosity(rti::config::Verbosity::STATUS_ALL);
try {
publisher_main(domain_id, sample_count);
} catch (const std::exception& ex) {
std::cout << "Exception caught: " << ex.what() << std::endl;
return -1;
}
return 0;
}
| cxx |
rticonnextdds-examples | data/projects/rticonnextdds-examples/polling_querycondition/c++/flights_subscriber.cxx | /*******************************************************************************
(c) 2005-2015 Copyright, Real-Time Innovations, Inc. All rights reserved.
RTI grants Licensee a license to use, modify, compile, and create derivative
works of the Software. Licensee has the right to distribute object form only
for use with RTI products. The Software is provided "as is", with no warranty
of any type, including any warranty for fitness for any purpose. RTI is under
no obligation to maintain or support the Software. RTI shall not be liable for
any incidental or consequential damages arising out of the use or inability to
use the software.
******************************************************************************/
#include <stdio.h>
#include <stdlib.h>
#ifdef RTI_VX653
#include <vThreadsData.h>
#endif
#include "flights.h"
#include "flightsSupport.h"
#include "ndds/ndds_cpp.h"
/* We remove all the listener code as we won't use any listener */
/* Delete all entities */
static int subscriber_shutdown(
DDSDomainParticipant *participant)
{
DDS_ReturnCode_t retcode;
int status = 0;
if (participant != NULL) {
retcode = participant->delete_contained_entities();
if (retcode != DDS_RETCODE_OK) {
printf("delete_contained_entities error %d\n", retcode);
status = -1;
}
retcode = DDSTheParticipantFactory->delete_participant(participant);
if (retcode != DDS_RETCODE_OK) {
printf("delete_participant error %d\n", retcode);
status = -1;
}
}
/* RTI Connext provides the finalize_instance() method on
domain participant factory for people who want to release memory used
by the participant factory. Uncomment the following block of code for
clean destruction of the singleton. */
/*
retcode = DDSDomainParticipantFactory::finalize_instance();
if (retcode != DDS_RETCODE_OK) {
printf("finalize_instance error %d\n", retcode);
status = -1;
}
*/
return status;
}
extern "C" int subscriber_main(int domainId, int sample_count)
{
DDSDomainParticipant *participant = NULL;
DDSSubscriber *subscriber = NULL;
DDSTopic *topic = NULL;
DDSDataReader *reader = NULL;
DDS_ReturnCode_t retcode;
const char *type_name = NULL;
int count = 0;
/* Poll for new samples every second. */
DDS_Duration_t receive_period = {1,0};
int status = 0;
/* Create the Participant. */
participant = DDSTheParticipantFactory->create_participant(
domainId, DDS_PARTICIPANT_QOS_DEFAULT,
NULL /* listener */, DDS_STATUS_MASK_NONE);
if (participant == NULL) {
printf("create_participant error\n");
subscriber_shutdown(participant);
return -1;
}
/* Create a Subscriber. */
subscriber = participant->create_subscriber(
DDS_SUBSCRIBER_QOS_DEFAULT, NULL /* listener */, DDS_STATUS_MASK_NONE);
if (subscriber == NULL) {
printf("create_subscriber error\n");
subscriber_shutdown(participant);
return -1;
}
/* Register the type before creating the topic. */
type_name = FlightTypeSupport::get_type_name();
retcode = FlightTypeSupport::register_type(
participant, type_name);
if (retcode != DDS_RETCODE_OK) {
printf("register_type error %d\n", retcode);
subscriber_shutdown(participant);
return -1;
}
/* Create a Topic. */
topic = participant->create_topic(
"Example Flight",
type_name, DDS_TOPIC_QOS_DEFAULT, NULL /* listener */,
DDS_STATUS_MASK_NONE);
if (topic == NULL) {
printf("create_topic error\n");
subscriber_shutdown(participant);
return -1;
}
/* Call create_datareader passing NULL in the listener parameter. */
reader = subscriber->create_datareader(
topic, DDS_DATAREADER_QOS_DEFAULT, NULL,
DDS_STATUS_MASK_ALL);
if (reader == NULL) {
printf("create_datareader error\n");
subscriber_shutdown(participant);
return -1;
}
FlightDataReader *flight_reader =
FlightDataReader::narrow(reader);
if (reader == NULL) {
printf("DataReader narrow error\n");
return -1;
}
/* Query for company named 'CompanyA' and for flights in cruise
* (about 30,000ft). The company parameter will be changed in run-time.
* NOTE: There must be single-quotes in the query parameters around-any
* strings! The single-quote do NOT go in the query condition itself. */
DDS_StringSeq query_parameters;
query_parameters.ensure_length(2, 2);
query_parameters[0] = "'CompanyA'";
query_parameters[1] = "30000";
printf("Setting parameter to company %s, altitude bigger or equals to %s\n",
query_parameters[0], query_parameters[1]);
/* Create the query condition with an expession to MATCH the id field in
* the structure and a numeric comparison. Note that you should make a copy
* of the expression string when creating the query condition - beware it
* going out of scope! */
DDSQueryCondition *query_condition = flight_reader->create_querycondition(
DDS_ANY_SAMPLE_STATE, DDS_ANY_VIEW_STATE,
DDS_ALIVE_INSTANCE_STATE,
DDS_String_dup("company MATCH %0 AND altitude >= %1"),
query_parameters);
/* Main loop */
for (count=0; (sample_count == 0) || (count < sample_count); ++count) {
/* Poll for a new samples every second. */
NDDSUtility::sleep(receive_period);
/* Change the filter parameter after 5 seconds. */
bool update = false;
if ((count + 1) % 10 == 5) {
query_parameters[0] = "'CompanyB'";
update = true;
} else if ((count + 1) % 10 == 0) {
query_parameters[0] = "'CompanyA'";
update = true;
}
/* Set new parameters. */
if (update) {
printf("Changing parameter to %s\n", query_parameters[0]);
query_condition->set_query_parameters(query_parameters);
update = false;
}
DDS_SampleInfoSeq info_seq;
FlightSeq data_seq;
/* Iterate through the samples read using the read_w_condition method */
retcode = flight_reader->read_w_condition(data_seq, info_seq,
DDS_LENGTH_UNLIMITED, query_condition);
if (retcode == DDS_RETCODE_NO_DATA) {
// Not an error
continue;
} else if (retcode != DDS_RETCODE_OK) {
// Is an error
printf("take error: %d\n", retcode);
break;
}
for (int i = 0; i < data_seq.length(); ++i) {
if (info_seq[i].valid_data) {
printf("\t[trackId: %d, company: %s, altitude: %d]\n",
data_seq[i].trackId, data_seq[i].company,
data_seq[i].altitude);
}
}
retcode = flight_reader->return_loan(data_seq, info_seq);
if (retcode != DDS_RETCODE_OK) {
printf("return loan error %d\n", retcode);
}
}
/* Delete all entities */
status = subscriber_shutdown(participant);
return status;
}
#if !(defined(RTI_VXWORKS) && !defined(__RTP__)) && !defined(RTI_PSOS)
int main(int argc, char *argv[])
{
int domainId = 0;
int sample_count = 0; /* infinite loop */
if (argc >= 2) {
domainId = atoi(argv[1]);
}
if (argc >= 3) {
sample_count = atoi(argv[2]);
}
/* Uncomment this to turn on additional logging
NDDSConfigLogger::get_instance()->
set_verbosity_by_category(NDDS_CONFIG_LOG_CATEGORY_API,
NDDS_CONFIG_LOG_VERBOSITY_STATUS_ALL);
*/
return subscriber_main(domainId, sample_count);
}
#endif
#ifdef RTI_VX653
const unsigned char* __ctype = *(__ctypePtrGet());
extern "C" void usrAppInit ()
{
#ifdef USER_APPL_INIT
USER_APPL_INIT; /* for backwards compatibility */
#endif
/* add application specific code here */
taskSpawn("sub", RTI_OSAPI_THREAD_PRIORITY_NORMAL, 0x8, 0x150000, (FUNCPTR)subscriber_main, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
}
#endif
| cxx |
rticonnextdds-examples | data/projects/rticonnextdds-examples/polling_querycondition/c++/flights_publisher.cxx | /*******************************************************************************
(c) 2005-2014 Copyright, Real-Time Innovations, Inc. All rights reserved.
RTI grants Licensee a license to use, modify, compile, and create derivative
works of the Software. Licensee has the right to distribute object form only
for use with RTI products. The Software is provided "as is", with no warranty
of any type, including any warranty for fitness for any purpose. RTI is under
no obligation to maintain or support the Software. RTI shall not be liable for
any incidental or consequential damages arising out of the use or inability to
use the software.
******************************************************************************/
#include <stdio.h>
#include <stdlib.h>
#ifdef RTI_VX653
#include <vThreadsData.h>
#endif
#include "flights.h"
#include "flightsSupport.h"
#include "ndds/ndds_cpp.h"
/* Delete all entities */
static int publisher_shutdown(
DDSDomainParticipant *participant)
{
DDS_ReturnCode_t retcode;
int status = 0;
if (participant != NULL) {
retcode = participant->delete_contained_entities();
if (retcode != DDS_RETCODE_OK) {
printf("delete_contained_entities error %d\n", retcode);
status = -1;
}
retcode = DDSTheParticipantFactory->delete_participant(participant);
if (retcode != DDS_RETCODE_OK) {
printf("delete_participant error %d\n", retcode);
status = -1;
}
}
/* RTI Connext provides finalize_instance() method on
domain participant factory for people who want to release memory used
by the participant factory. Uncomment the following block of code for
clean destruction of the singleton. */
/*
retcode = DDSDomainParticipantFactory::finalize_instance();
if (retcode != DDS_RETCODE_OK) {
printf("finalize_instance error %d\n", retcode);
status = -1;
}
*/
return status;
}
extern "C" int publisher_main(int domainId, int sample_count)
{
DDSDomainParticipant *participant = NULL;
DDSPublisher *publisher = NULL;
DDSTopic *topic = NULL;
DDSDataWriter *writer = NULL;
FlightDataWriter * flights_writer = NULL;
DDS_ReturnCode_t retcode;
DDS_InstanceHandle_t instance_handle = DDS_HANDLE_NIL;
const char *type_name = NULL;
int count = 0;
/* Send a new sample every second */
DDS_Duration_t send_period = {1,0};
/* Create a Participant. */
participant = DDSTheParticipantFactory->create_participant(
domainId, DDS_PARTICIPANT_QOS_DEFAULT,
NULL /* listener */, DDS_STATUS_MASK_NONE);
if (participant == NULL) {
printf("create_participant error\n");
publisher_shutdown(participant);
return -1;
}
/* Create a Publisher. */
publisher = participant->create_publisher(
DDS_PUBLISHER_QOS_DEFAULT, NULL /* listener */, DDS_STATUS_MASK_NONE);
if (publisher == NULL) {
printf("create_publisher error\n");
publisher_shutdown(participant);
return -1;
}
/* Register type before creating topic. */
type_name = FlightTypeSupport::get_type_name();
retcode = FlightTypeSupport::register_type(
participant, type_name);
if (retcode != DDS_RETCODE_OK) {
printf("register_type error %d\n", retcode);
publisher_shutdown(participant);
return -1;
}
/* Create the Topic. */
topic = participant->create_topic(
"Example Flight",
type_name, DDS_TOPIC_QOS_DEFAULT, NULL /* listener */,
DDS_STATUS_MASK_NONE);
if (topic == NULL) {
printf("create_topic error\n");
publisher_shutdown(participant);
return -1;
}
/* Create a DataWriter. */
writer = publisher->create_datawriter(
topic, DDS_DATAWRITER_QOS_DEFAULT, NULL /* listener */,
DDS_STATUS_MASK_NONE);
if (writer == NULL) {
printf("create_datawriter error\n");
publisher_shutdown(participant);
return -1;
}
flights_writer = FlightDataWriter::narrow(writer);
if (flights_writer == NULL) {
printf("DataWriter narrow error\n");
publisher_shutdown(participant);
return -1;
}
/* Create the flight info samples. */
const int num_flights = 4;
Flight flights_info[4];
flights_info[0].trackId = 1111;
flights_info[0].company = "CompanyA";
flights_info[0].altitude = 15000;
flights_info[1].trackId = 2222;
flights_info[1].company = "CompanyB";
flights_info[1].altitude = 20000;
flights_info[2].trackId = 3333;
flights_info[2].company = "CompanyA";
flights_info[2].altitude = 30000;
flights_info[3].trackId = 4444;
flights_info[3].company = "CompanyB";
flights_info[3].altitude = 25000;
/* Main loop */
for (count=0; (sample_count==0)||(count<sample_count); count+=num_flights) {
/* Update flight info latitude and write. */
printf("Updating and sending values\n");
for (int i = 0; i < num_flights; i++) {
/* Set the plane altitude lineally
* (usually the max is at 41,000ft). */
flights_info[i].altitude += count * 100;
if (flights_info[i].altitude >= 41000) {
flights_info[i].altitude = 41000;
}
printf("\t[trackId: %d, company: %s, altitude: %d]\n",
flights_info[i].trackId, flights_info[i].company,
flights_info[i].altitude);
/* Write the instance */
retcode = flights_writer->write(
flights_info[i], instance_handle);
if (retcode != DDS_RETCODE_OK) {
printf("write error %d\n", retcode);
}
}
NDDSUtility::sleep(send_period);
}
/* Delete all entities */
return publisher_shutdown(participant);
}
#if !(defined(RTI_VXWORKS) && !defined(__RTP__)) && !defined(RTI_PSOS)
int main(int argc, char *argv[])
{
int domainId = 0;
int sample_count = 0; /* infinite loop */
if (argc >= 2) {
domainId = atoi(argv[1]);
}
if (argc >= 3) {
sample_count = atoi(argv[2]);
}
/* Uncomment this to turn on additional logging
NDDSConfigLogger::get_instance()->
set_verbosity_by_category(NDDS_CONFIG_LOG_CATEGORY_API,
NDDS_CONFIG_LOG_VERBOSITY_STATUS_ALL);
*/
return publisher_main(domainId, sample_count);
}
#endif
#ifdef RTI_VX653
const unsigned char* __ctype = *(__ctypePtrGet());
extern "C" void usrAppInit ()
{
#ifdef USER_APPL_INIT
USER_APPL_INIT; /* for backwards compatibility */
#endif
/* add application specific code here */
taskSpawn("pub", RTI_OSAPI_THREAD_PRIORITY_NORMAL, 0x8, 0x150000, (FUNCPTR)publisher_main, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
}
#endif
| cxx |
rticonnextdds-examples | data/projects/rticonnextdds-examples/polling_querycondition/c++/querycondition_publisher.cxx | /*******************************************************************************
(c) 2005-2014 Copyright, Real-Time Innovations, Inc. All rights reserved.
RTI grants Licensee a license to use, modify, compile, and create derivative
works of the Software. Licensee has the right to distribute object form only
for use with RTI products. The Software is provided "as is", with no warranty
of any type, including any warranty for fitness for any purpose. RTI is under
no obligation to maintain or support the Software. RTI shall not be liable for
any incidental or consequential damages arising out of the use or inability to
use the software.
******************************************************************************/
/* querycondition_publisher.cxx
A publication of data of type querycondition
This file is derived from code automatically generated by the rtiddsgen
command:
rtiddsgen -language C++ -example <arch> querycondition.idl
Example publication of type querycondition automatically generated by
'rtiddsgen'. To test them follow these steps:
(1) Compile this file and the example subscription.
(2) Start the subscription with the command
objs/<arch>/querycondition_subscriber <domain_id> <sample_count>
(3) Start the publication with the command
objs/<arch>/querycondition_publisher <domain_id> <sample_count>
(4) [Optional] Specify the list of discovery initial peers and
multicast receive addresses via an environment variable or a file
(in the current working directory) called NDDS_DISCOVERY_PEERS.
You can run any number of publishers and subscribers programs, and can
add and remove them dynamically from the domain.
Example:
To run the example application on domain <domain_id>:
On Unix:
objs/<arch>/querycondition_publisher <domain_id> o
objs/<arch>/querycondition_subscriber <domain_id>
On Windows:
objs\<arch>\querycondition_publisher <domain_id>
objs\<arch>\querycondition_subscriber <domain_id>
modification history
------------ -------
*/
#include <stdio.h>
#include <stdlib.h>
#ifdef RTI_VX653
#include <vThreadsData.h>
#endif
#include "querycondition.h"
#include "queryconditionSupport.h"
#include "ndds/ndds_cpp.h"
#include <ctime>
/* Delete all entities */
static int publisher_shutdown(
DDSDomainParticipant *participant)
{
DDS_ReturnCode_t retcode;
int status = 0;
if (participant != NULL) {
retcode = participant->delete_contained_entities();
if (retcode != DDS_RETCODE_OK) {
printf("delete_contained_entities error %d\n", retcode);
status = -1;
}
retcode = DDSTheParticipantFactory->delete_participant(participant);
if (retcode != DDS_RETCODE_OK) {
printf("delete_participant error %d\n", retcode);
status = -1;
}
}
/* RTI Connext provides finalize_instance() method on
domain participant factory for people who want to release memory used
by the participant factory. Uncomment the following block of code for
clean destruction of the singleton. */
/*
retcode = DDSDomainParticipantFactory::finalize_instance();
if (retcode != DDS_RETCODE_OK) {
printf("finalize_instance error %d\n", retcode);
status = -1;
}
*/
return status;
}
extern "C" int publisher_main(int domainId, int sample_count)
{
DDSDomainParticipant *participant = NULL;
DDSPublisher *publisher = NULL;
DDSTopic *topic = NULL;
DDSDataWriter *writer = NULL;
queryconditionDataWriter * querycondition_writer = NULL;
querycondition *instance = NULL;
DDS_ReturnCode_t retcode;
DDS_InstanceHandle_t instance_handle = DDS_HANDLE_NIL;
const char *type_name = NULL;
int count = 0;
/* Send a new sample every second */
DDS_Duration_t send_period = {1,0};
/* To customize participant QoS, use
the configuration file USER_QOS_PROFILES.xml */
participant = DDSTheParticipantFactory->create_participant(
domainId, DDS_PARTICIPANT_QOS_DEFAULT,
NULL /* listener */, DDS_STATUS_MASK_NONE);
if (participant == NULL) {
printf("create_participant error\n");
publisher_shutdown(participant);
return -1;
}
/* To customize publisher QoS, use
the configuration file USER_QOS_PROFILES.xml */
publisher = participant->create_publisher(
DDS_PUBLISHER_QOS_DEFAULT, NULL /* listener */, DDS_STATUS_MASK_NONE);
if (publisher == NULL) {
printf("create_publisher error\n");
publisher_shutdown(participant);
return -1;
}
/* Register type before creating topic */
type_name = queryconditionTypeSupport::get_type_name();
retcode = queryconditionTypeSupport::register_type(
participant, type_name);
if (retcode != DDS_RETCODE_OK) {
printf("register_type error %d\n", retcode);
publisher_shutdown(participant);
return -1;
}
/* To customize topic QoS, use
the configuration file USER_QOS_PROFILES.xml */
topic = participant->create_topic(
"Example querycondition",
type_name, DDS_TOPIC_QOS_DEFAULT, NULL /* listener */,
DDS_STATUS_MASK_NONE);
if (topic == NULL) {
printf("create_topic error\n");
publisher_shutdown(participant);
return -1;
}
/* To customize data writer QoS, use
the configuration file USER_QOS_PROFILES.xml */
writer = publisher->create_datawriter(
topic, DDS_DATAWRITER_QOS_DEFAULT, NULL /* listener */,
DDS_STATUS_MASK_NONE);
if (writer == NULL) {
printf("create_datawriter error\n");
publisher_shutdown(participant);
return -1;
}
querycondition_writer = queryconditionDataWriter::narrow(writer);
if (querycondition_writer == NULL) {
printf("DataWriter narrow error\n");
publisher_shutdown(participant);
return -1;
}
/* Create data sample for writing */
instance = queryconditionTypeSupport::create_data();
if (instance == NULL) {
printf("queryconditionTypeSupport::create_data error\n");
publisher_shutdown(participant);
return -1;
}
/* For a data type that has a key, if the same instance is going to be
written multiple times, initialize the key here
and register the keyed instance prior to writing */
/*
instance_handle = querycondition_writer->register_instance(*instance);
*/
/* Initialize random seed before entering the loop */
srand(time(NULL));
char *myIds[] = {"GUID1", "GUID2", "GUID3"};
/* Main loop */
for (count=0; (sample_count == 0) || (count < sample_count); ++count) {
/* Modify the data to be written here */
/* Set id to be one of the three options */
sprintf(instance->id, "%s", myIds[count%3]);
/* Set x to a random number between 0 and 9 */
instance->value = (int)(rand()/(RAND_MAX/10.0));
printf("Writing querycondition, count %d, id = %s, value = %d\n", count,
instance->id,
instance->value);
retcode = querycondition_writer->write(*instance, instance_handle);
if (retcode != DDS_RETCODE_OK) {
printf("write error %d\n", retcode);
}
NDDSUtility::sleep(send_period);
}
/*
retcode = querycondition_writer->unregister_instance(
*instance, instance_handle);
if (retcode != DDS_RETCODE_OK) {
printf("unregister instance error %d\n", retcode);
}
*/
/* Delete data sample */
retcode = queryconditionTypeSupport::delete_data(instance);
if (retcode != DDS_RETCODE_OK) {
printf("queryconditionTypeSupport::delete_data error %d\n", retcode);
}
/* Delete all entities */
return publisher_shutdown(participant);
}
#if defined(RTI_WINCE)
int wmain(int argc, wchar_t** argv)
{
int domainId = 0;
int sample_count = 0; /* infinite loop */
if (argc >= 2) {
domainId = _wtoi(argv[1]);
}
if (argc >= 3) {
sample_count = _wtoi(argv[2]);
}
/* Uncomment this to turn on additional logging
NDDSConfigLogger::get_instance()->
set_verbosity_by_category(NDDS_CONFIG_LOG_CATEGORY_API,
NDDS_CONFIG_LOG_VERBOSITY_STATUS_ALL);
*/
return publisher_main(domainId, sample_count);
}
#elif !(defined(RTI_VXWORKS) && !defined(__RTP__)) && !defined(RTI_PSOS)
int main(int argc, char *argv[])
{
int domainId = 0;
int sample_count = 0; /* infinite loop */
if (argc >= 2) {
domainId = atoi(argv[1]);
}
if (argc >= 3) {
sample_count = atoi(argv[2]);
}
/* Uncomment this to turn on additional logging
NDDSConfigLogger::get_instance()->
set_verbosity_by_category(NDDS_CONFIG_LOG_CATEGORY_API,
NDDS_CONFIG_LOG_VERBOSITY_STATUS_ALL);
*/
return publisher_main(domainId, sample_count);
}
#endif
#ifdef RTI_VX653
const unsigned char* __ctype = *(__ctypePtrGet());
extern "C" void usrAppInit ()
{
#ifdef USER_APPL_INIT
USER_APPL_INIT; /* for backwards compatibility */
#endif
/* add application specific code here */
taskSpawn("pub", RTI_OSAPI_THREAD_PRIORITY_NORMAL, 0x8, 0x150000, (FUNCPTR)publisher_main, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
}
#endif
| cxx |
rticonnextdds-examples | data/projects/rticonnextdds-examples/polling_querycondition/c++/querycondition_subscriber.cxx | /*******************************************************************************
(c) 2005-2014 Copyright, Real-Time Innovations, Inc. All rights reserved.
RTI grants Licensee a license to use, modify, compile, and create derivative
works of the Software. Licensee has the right to distribute object form only
for use with RTI products. The Software is provided "as is", with no warranty
of any type, including any warranty for fitness for any purpose. RTI is under
no obligation to maintain or support the Software. RTI shall not be liable for
any incidental or consequential damages arising out of the use or inability to
use the software.
******************************************************************************/
/* querycondition_subscriber.cxx
A subscription example
This file is derived from code automatically generated by the rtiddsgen
command:
rtiddsgen -language C++ -example <arch> querycondition.idl
Example subscription of type querycondition automatically generated by
'rtiddsgen'. To test them follow these steps:
(1) Compile this file and the example publication.
(2) Start the subscription with the command
objs/<arch>/querycondition_subscriber <domain_id> <sample_count>
(3) Start the publication with the command
objs/<arch>/querycondition_publisher <domain_id> <sample_count>
(4) [Optional] Specify the list of discovery initial peers and
multicast receive addresses via an environment variable or a file
(in the current working directory) called NDDS_DISCOVERY_PEERS.
You can run any number of publishers and subscribers programs, and can
add and remove them dynamically from the domain.
Example:
To run the example application on domain <domain_id>:
On Unix:
objs/<arch>/querycondition_publisher <domain_id>
objs/<arch>/querycondition_subscriber <domain_id>
On Windows:
objs\<arch>\querycondition_publisher <domain_id>
objs\<arch>\querycondition_subscriber <domain_id>
modification history
------------ -------
*/
#include <stdio.h>
#include <stdlib.h>
#ifdef RTI_VX653
#include <vThreadsData.h>
#endif
#include "querycondition.h"
#include "queryconditionSupport.h"
#include "ndds/ndds_cpp.h"
/* We remove all the listener code as we won't use any listener */
/* Delete all entities */
static int subscriber_shutdown(
DDSDomainParticipant *participant)
{
DDS_ReturnCode_t retcode;
int status = 0;
if (participant != NULL) {
retcode = participant->delete_contained_entities();
if (retcode != DDS_RETCODE_OK) {
printf("delete_contained_entities error %d\n", retcode);
status = -1;
}
retcode = DDSTheParticipantFactory->delete_participant(participant);
if (retcode != DDS_RETCODE_OK) {
printf("delete_participant error %d\n", retcode);
status = -1;
}
}
/* RTI Connext provides the finalize_instance() method on
domain participant factory for people who want to release memory used
by the participant factory. Uncomment the following block of code for
clean destruction of the singleton. */
/*
retcode = DDSDomainParticipantFactory::finalize_instance();
if (retcode != DDS_RETCODE_OK) {
printf("finalize_instance error %d\n", retcode);
status = -1;
}
*/
return status;
}
extern "C" int subscriber_main(int domainId, int sample_count)
{
DDSDomainParticipant *participant = NULL;
DDSSubscriber *subscriber = NULL;
DDSTopic *topic = NULL;
DDSDataReader *reader = NULL;
DDS_ReturnCode_t retcode;
const char *type_name = NULL;
int count = 0;
/* Poll for new samples every 5 seconds */
DDS_Duration_t receive_period = {5,0};
int status = 0;
/* To customize the participant QoS, use
the configuration file USER_QOS_PROFILES.xml */
participant = DDSTheParticipantFactory->create_participant(
domainId, DDS_PARTICIPANT_QOS_DEFAULT,
NULL /* listener */, DDS_STATUS_MASK_NONE);
if (participant == NULL) {
printf("create_participant error\n");
subscriber_shutdown(participant);
return -1;
}
/* To customize the subscriber QoS, use
the configuration file USER_QOS_PROFILES.xml */
subscriber = participant->create_subscriber(
DDS_SUBSCRIBER_QOS_DEFAULT, NULL /* listener */, DDS_STATUS_MASK_NONE);
if (subscriber == NULL) {
printf("create_subscriber error\n");
subscriber_shutdown(participant);
return -1;
}
/* Register the type before creating the topic */
type_name = queryconditionTypeSupport::get_type_name();
retcode = queryconditionTypeSupport::register_type(
participant, type_name);
if (retcode != DDS_RETCODE_OK) {
printf("register_type error %d\n", retcode);
subscriber_shutdown(participant);
return -1;
}
/* To customize the topic QoS, use
the configuration file USER_QOS_PROFILES.xml */
topic = participant->create_topic(
"Example querycondition",
type_name, DDS_TOPIC_QOS_DEFAULT, NULL /* listener */,
DDS_STATUS_MASK_NONE);
if (topic == NULL) {
printf("create_topic error\n");
subscriber_shutdown(participant);
return -1;
}
/* Call create_datareader passing NULL in the listener parameter */
reader = subscriber->create_datareader(
topic, DDS_DATAREADER_QOS_DEFAULT, NULL,
DDS_STATUS_MASK_ALL);
if (reader == NULL) {
printf("create_datareader error\n");
subscriber_shutdown(participant);
return -1;
}
/* If you want to change datareader_qos.history programmatically rather
* than using the XML file, you will need to add the following lines to your
* code and comment out the create_datareader call above. */
/*
DDS_DataReaderQos datareader_qos;
retcode = subscriber->get_default_datareader_qos(datareader_qos);
if (retcode != DDS_RETCODE_OK) {
printf("get_default_datareader_qos error\n");
return -1;
}
datareader_qos.history.kind = DDS_KEEP_LAST_HISTORY_QOS;
datareader_qos.history.depth = 6;
reader = subscriber->create_datareader(
topic, datareader_qos, NULL,
DDS_STATUS_MASK_ALL);
if (reader == NULL) {
printf("create_datareader error\n");
subscriber_shutdown(participant);
return -1;
}
*/
queryconditionDataReader *querycondition_reader =
queryconditionDataReader::narrow(reader);
if (querycondition_reader == NULL) {
printf("DataReader narrow error\n");
return -1;
}
/* NOTE: There must be single-quotes in the query parameters around
* any strings! The single-quotes do NOT go in the query condition
* itself.
*/
DDSQueryCondition *query_for_guid2;
/* Query for 'GUID2' This query parameter can be changed at runtime,
* allowing an application to selectively look at subsets of data
* at different times. */
DDS_StringSeq query_parameters;
query_parameters.ensure_length(1,1);
query_parameters[0] = DDS_String_dup("'GUID2'");
/* Create the query condition with an expession to MATCH the id field in
* the structure. Note that you should make a copy of the expression string
* when creating the query condition - beware it going out of scope! */
query_for_guid2 = querycondition_reader->create_querycondition(
DDS_ANY_SAMPLE_STATE, DDS_ANY_VIEW_STATE,
DDS_ALIVE_INSTANCE_STATE,
DDS_String_dup("id MATCH %0"),
query_parameters);
/* Main loop */
for (count=0; (sample_count == 0) || (count < sample_count); ++count) {
NDDSUtility::sleep(receive_period);
DDS_SampleInfoSeq info_seq;
queryconditionSeq data_seq;
/* Check for new data calling the DataReader's read_w_condition()
method */
retcode = querycondition_reader->read_w_condition(data_seq, info_seq,
DDS_LENGTH_UNLIMITED, query_for_guid2);
if (retcode == DDS_RETCODE_NO_DATA) {
/// Not an error
continue;
} else if (retcode != DDS_RETCODE_OK) {
// Is an error
printf("take error: %d\n", retcode);
break;
}
int len = 0;
double sum = 0;
/* Iterate through the samples read using the read_w_condition() method,
* accessing only the samples of GUID2. Then, show the number of samples
* received and, adding the value of x on each of them to calculate the
* average afterwards. */
for (int i = 0; i < data_seq.length(); ++i) {
if (!info_seq[i].valid_data)
continue;
len ++;
sum += data_seq[i].value;
printf("Guid = %s\n", data_seq[i].id);
}
if (len > 0)
printf("Got %d samples. Avg = %.1f\n", len, sum/len);
retcode = querycondition_reader->return_loan(data_seq, info_seq);
if (retcode != DDS_RETCODE_OK) {
printf("return loan error %d\n", retcode);
}
}
/* Delete all entities */
status = subscriber_shutdown(participant);
return status;
}
#if defined(RTI_WINCE)
int wmain(int argc, wchar_t** argv)
{
int domainId = 0;
int sample_count = 0; /* infinite loop */
if (argc >= 2) {
domainId = _wtoi(argv[1]);
}
if (argc >= 3) {
sample_count = _wtoi(argv[2]);
}
/* Uncomment this to turn on additional logging
NDDSConfigLogger::get_instance()->
set_verbosity_by_category(NDDS_CONFIG_LOG_CATEGORY_API,
NDDS_CONFIG_LOG_VERBOSITY_STATUS_ALL);
*/
return subscriber_main(domainId, sample_count);
}
#elif !(defined(RTI_VXWORKS) && !defined(__RTP__)) && !defined(RTI_PSOS)
int main(int argc, char *argv[])
{
int domainId = 0;
int sample_count = 0; /* infinite loop */
if (argc >= 2) {
domainId = atoi(argv[1]);
}
if (argc >= 3) {
sample_count = atoi(argv[2]);
}
/* Uncomment this to turn on additional logging
NDDSConfigLogger::get_instance()->
set_verbosity_by_category(NDDS_CONFIG_LOG_CATEGORY_API,
NDDS_CONFIG_LOG_VERBOSITY_STATUS_ALL);
*/
return subscriber_main(domainId, sample_count);
}
#endif
#ifdef RTI_VX653
const unsigned char* __ctype = *(__ctypePtrGet());
extern "C" void usrAppInit ()
{
#ifdef USER_APPL_INIT
USER_APPL_INIT; /* for backwards compatibility */
#endif
/* add application specific code here */
taskSpawn("sub", RTI_OSAPI_THREAD_PRIORITY_NORMAL, 0x8, 0x150000, (FUNCPTR)subscriber_main, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
}
#endif
| cxx |
rticonnextdds-examples | data/projects/rticonnextdds-examples/polling_querycondition/c/flights_publisher.c | /*******************************************************************************
(c) 2005-2015 Copyright, Real-Time Innovations, Inc. All rights reserved.
RTI grants Licensee a license to use, modify, compile, and create derivative
works of the Software. Licensee has the right to distribute object form only
for use with RTI products. The Software is provided "as is", with no warranty
of any type, including any warranty for fitness for any purpose. RTI is under
no obligation to maintain or support the Software. RTI shall not be liable for
any incidental or consequential damages arising out of the use or inability to
use the software.
******************************************************************************/
#include <stdio.h>
#include <stdlib.h>
#include "ndds/ndds_c.h"
#include "flights.h"
#include "flightsSupport.h"
/* Delete all entities */
static int publisher_shutdown(
DDS_DomainParticipant *participant)
{
DDS_ReturnCode_t retcode;
int status = 0;
if (participant != NULL) {
retcode = DDS_DomainParticipant_delete_contained_entities(participant);
if (retcode != DDS_RETCODE_OK) {
printf("delete_contained_entities error %d\n", retcode);
status = -1;
}
retcode = DDS_DomainParticipantFactory_delete_participant(
DDS_TheParticipantFactory, participant);
if (retcode != DDS_RETCODE_OK) {
printf("delete_participant error %d\n", retcode);
status = -1;
}
}
/* RTI Connext provides finalize_instance() method on
domain participant factory for people who want to release memory used
by the participant factory. Uncomment the following block of code for
clean destruction of the singleton. */
/*
retcode = DDS_DomainParticipantFactory_finalize_instance();
if (retcode != DDS_RETCODE_OK) {
printf("finalize_instance error %d\n", retcode);
status = -1;
}
*/
return status;
}
static int publisher_main(int domain_id, int sample_count)
{
DDS_DomainParticipant *participant = NULL;
DDS_Publisher *publisher = NULL;
DDS_Topic *topic = NULL;
DDS_DataWriter *writer = NULL;
FlightDataWriter *flight_writer = NULL;
DDS_ReturnCode_t retcode;
DDS_InstanceHandle_t instance_handle = DDS_HANDLE_NIL;
const char *type_name = NULL;
int count = 0;
/* Send a new sample every second */
struct DDS_Duration_t send_period = {1,0};
/* Create the flight info samples. */
const int num_flights = 4;
Flight flights_info[4];
flights_info[0].trackId = 1111;
flights_info[0].company = "CompanyA";
flights_info[0].altitude = 15000;
flights_info[1].trackId = 2222;
flights_info[1].company = "CompanyB";
flights_info[1].altitude = 20000;
flights_info[2].trackId = 3333;
flights_info[2].company = "CompanyA";
flights_info[2].altitude = 30000;
flights_info[3].trackId = 4444;
flights_info[3].company = "CompanyB";
flights_info[3].altitude = 25000;
/* Create a Participant. */
participant = DDS_DomainParticipantFactory_create_participant(
DDS_TheParticipantFactory, domain_id, &DDS_PARTICIPANT_QOS_DEFAULT,
NULL /* listener */, DDS_STATUS_MASK_NONE);
if (participant == NULL) {
printf("create_participant error\n");
publisher_shutdown(participant);
return -1;
}
/* Create a Publisher. */
publisher = DDS_DomainParticipant_create_publisher(
participant, &DDS_PUBLISHER_QOS_DEFAULT, NULL /* listener */,
DDS_STATUS_MASK_NONE);
if (publisher == NULL) {
printf("create_publisher error\n");
publisher_shutdown(participant);
return -1;
}
/* Register type before creating the topic. */
type_name = FlightTypeSupport_get_type_name();
retcode = FlightTypeSupport_register_type(
participant, type_name);
if (retcode != DDS_RETCODE_OK) {
printf("register_type error %d\n", retcode);
publisher_shutdown(participant);
return -1;
}
/* Create a Topic. */
topic = DDS_DomainParticipant_create_topic(
participant, "Example Flight",
type_name, &DDS_TOPIC_QOS_DEFAULT, NULL /* listener */,
DDS_STATUS_MASK_NONE);
if (topic == NULL) {
printf("create_topic error\n");
publisher_shutdown(participant);
return -1;
}
/* Create a DataWriter. */
writer = DDS_Publisher_create_datawriter(
publisher, topic,
&DDS_DATAWRITER_QOS_DEFAULT, NULL /* listener */, DDS_STATUS_MASK_NONE);
if (writer == NULL) {
printf("create_datawriter error\n");
publisher_shutdown(participant);
return -1;
}
flight_writer = FlightDataWriter_narrow(writer);
if (flight_writer == NULL) {
printf("DataWriter narrow error\n");
publisher_shutdown(participant);
return -1;
}
/* Main loop */
for (count=0; (sample_count==0)||(count<sample_count); count+=num_flights) {
int i;
/* Update flight info latitude and write */
printf("Updating and sending values\n");
for (i = 0; i < num_flights; i++) {
/* Set the plane altitude lineally
* (usually the max is at 41,000ft).
*/
flights_info[i].altitude += count * 100;
if (flights_info[i].altitude >= 41000) {
flights_info[i].altitude = 41000;
}
printf("\t[trackId: %d, company: %s, altitude: %d]\n",
flights_info[i].trackId, flights_info[i].company,
flights_info[i].altitude);
/* Write the instance */
retcode = FlightDataWriter_write(
flight_writer, &flights_info[i], &instance_handle);
if (retcode != DDS_RETCODE_OK) {
printf("write error %d\n", retcode);
}
}
NDDS_Utility_sleep(&send_period);
}
/* Cleanup and delete delete all entities */
return publisher_shutdown(participant);
}
#if !(defined(RTI_VXWORKS) && !defined(__RTP__)) && !defined(RTI_PSOS)
int main(int argc, char *argv[])
{
int domain_id = 0;
int sample_count = 0; /* Infinite loop */
if (argc >= 2) {
domain_id = atoi(argv[1]);
}
if (argc >= 3) {
sample_count = atoi(argv[2]);
}
/* Uncomment this to turn on additional logging
NDDS_Config_Logger_set_verbosity_by_category(
NDDS_Config_Logger_get_instance(),
NDDS_CONFIG_LOG_CATEGORY_API,
NDDS_CONFIG_LOG_VERBOSITY_STATUS_ALL);
*/
return publisher_main(domain_id, sample_count);
}
#endif
#ifdef RTI_VX653
const unsigned char* __ctype = NULL;
void usrAppInit ()
{
#ifdef USER_APPL_INIT
USER_APPL_INIT; /* for backwards compatibility */
#endif
/* add application specific code here */
taskSpawn("pub", RTI_OSAPI_THREAD_PRIORITY_NORMAL, 0x8, 0x150000, (FUNCPTR)publisher_main, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
}
#endif
| c |
rticonnextdds-examples | data/projects/rticonnextdds-examples/polling_querycondition/c/flights_subscriber.c | /*******************************************************************************
(c) 2005-2015 Copyright, Real-Time Innovations, Inc. All rights reserved.
RTI grants Licensee a license to use, modify, compile, and create derivative
works of the Software. Licensee has the right to distribute object form only
for use with RTI products. The Software is provided "as is", with no warranty
of any type, including any warranty for fitness for any purpose. RTI is under
no obligation to maintain or support the Software. RTI shall not be liable for
any incidental or consequential damages arising out of the use or inability to
use the software.
******************************************************************************/
#include <stdio.h>
#include <stdlib.h>
#include "ndds/ndds_c.h"
#include "flights.h"
#include "flightsSupport.h"
/* We remove all the listener code as we won't use any listener */
/* Delete all entities */
static int subscriber_shutdown(
DDS_DomainParticipant *participant)
{
DDS_ReturnCode_t retcode;
int status = 0;
if (participant != NULL) {
retcode = DDS_DomainParticipant_delete_contained_entities(participant);
if (retcode != DDS_RETCODE_OK) {
printf("delete_contained_entities error %d\n", retcode);
status = -1;
}
retcode = DDS_DomainParticipantFactory_delete_participant(
DDS_TheParticipantFactory, participant);
if (retcode != DDS_RETCODE_OK) {
printf("delete_participant error %d\n", retcode);
status = -1;
}
}
/* RTI Connext provides the finalize_instance() method on
domain participant factory for users who want to release memory used
by the participant factory. Uncomment the following block of code for
clean destruction of the singleton. */
/*
retcode = DDS_DomainParticipantFactory_finalize_instance();
if (retcode != DDS_RETCODE_OK) {
printf("finalize_instance error %d\n", retcode);
status = -1;
}
*/
return status;
}
static int subscriber_main(int domainId, int sample_count)
{
DDS_DomainParticipant *participant = NULL;
DDS_Subscriber *subscriber = NULL;
DDS_Topic *topic = NULL;
DDS_DataReader *reader = NULL;
FlightDataReader *flight_reader = NULL;
DDS_ReturnCode_t retcode;
const char *type_name = NULL;
int count = 0;
/* Poll for new samples every second. */
struct DDS_Duration_t poll_period = {1,0};
/* Query Condition-specific types */
DDS_QueryCondition *query_condition;
struct DDS_StringSeq query_parameters;
const char* param_list[] = { "'CompanyA'", "30000" };
/* Create a Participant. */
participant = DDS_DomainParticipantFactory_create_participant(
DDS_TheParticipantFactory, domainId, &DDS_PARTICIPANT_QOS_DEFAULT,
NULL /* listener */, DDS_STATUS_MASK_NONE);
if (participant == NULL) {
printf("create_participant error\n");
subscriber_shutdown(participant);
return -1;
}
/* Createa a Subscriber. */
subscriber = DDS_DomainParticipant_create_subscriber(
participant, &DDS_SUBSCRIBER_QOS_DEFAULT, NULL /* listener */,
DDS_STATUS_MASK_NONE);
if (subscriber == NULL) {
printf("create_subscriber error\n");
subscriber_shutdown(participant);
return -1;
}
/* Register the type before creating the topic. */
type_name = FlightTypeSupport_get_type_name();
retcode = FlightTypeSupport_register_type(participant, type_name);
if (retcode != DDS_RETCODE_OK) {
printf("register_type error %d\n", retcode);
subscriber_shutdown(participant);
return -1;
}
/* Create a Topic. */
topic = DDS_DomainParticipant_create_topic(
participant, "Example Flight",
type_name, &DDS_TOPIC_QOS_DEFAULT, NULL /* listener */,
DDS_STATUS_MASK_NONE);
if (topic == NULL) {
printf("create_topic error\n");
subscriber_shutdown(participant);
return -1;
}
/* Call create_datareader passing NULL in the listener parameter. */
reader = DDS_Subscriber_create_datareader(
subscriber, DDS_Topic_as_topicdescription(topic),
&DDS_DATAREADER_QOS_DEFAULT, NULL, DDS_STATUS_MASK_ALL);
if (reader == NULL) {
printf("create_datareader error\n");
subscriber_shutdown(participant);
return -1;
}
flight_reader = FlightDataReader_narrow(reader);
if (flight_reader == NULL) {
printf("DataReader narrow error\n");
return -1;
}
/* Query for company named 'CompanyA' and for flights in cruise
* (about 30,000ft). The company parameter will be changed in run-time.
* NOTE: There must be single-quotes in the query parameters around-any
* strings! The single-quote do NOT go in the query condition itself. */
DDS_StringSeq_ensure_length(&query_parameters, 2, 2);
DDS_StringSeq_from_array(&query_parameters, param_list, 2);
printf("Setting parameter to company %s, altitude bigger or equals to %s\n",
DDS_StringSeq_get(&query_parameters, 0),
DDS_StringSeq_get(&query_parameters, 1));
/* Create the query condition with an expession to MATCH the id field in
* the structure and a numeric comparison. Note that you should make a copy
* of the expression string when creating the query condition - beware it
* going out of scope! */
query_condition = DDS_DataReader_create_querycondition(
reader,
DDS_ANY_SAMPLE_STATE, DDS_ANY_VIEW_STATE,
DDS_ALIVE_INSTANCE_STATE,
DDS_String_dup("company MATCH %0 AND altitude >= %1"),
&query_parameters);
/* Main loop */
for (count=0; (sample_count == 0) || (count < sample_count); ++count) {
struct DDS_SampleInfoSeq info_seq;
struct FlightSeq data_seq;
DDS_ReturnCode_t retcode;
int update = 0;
int i = 0;
/* Poll for new samples every second. */
NDDS_Utility_sleep(&poll_period);
/* Change the filter parameter after 5 seconds. */
if ((count + 1) % 10 == 5) {
*DDS_StringSeq_get_reference(&query_parameters, 0) =
DDS_String_dup("'CompanyB'");
update = 1;
} else if ((count + 1) % 10 == 0) {
*DDS_StringSeq_get_reference(&query_parameters, 0) =
DDS_String_dup("'CompanyA'");
update = 1;
}
/* Set new parameters. */
if (update) {
update = 0;
printf("Changing parameter to %s\n",
DDS_StringSeq_get(&query_parameters, 0));
retcode = DDS_QueryCondition_set_query_parameters(
query_condition,
&query_parameters);
if (retcode != DDS_RETCODE_OK) {
printf("Error setting new parameters: %d\n", retcode);
}
}
/* Iterate through the samples read using the read_w_condition method */
retcode = FlightDataReader_read_w_condition(
flight_reader,
&data_seq, &info_seq,
DDS_LENGTH_UNLIMITED,
DDS_QueryCondition_as_readcondition(query_condition));
if (retcode == DDS_RETCODE_NO_DATA) {
/* Not an error */
continue;
} else if (retcode != DDS_RETCODE_OK) {
/* Is an error */
printf("take error: %d\n", retcode);
break;
}
for (i = 0; i < FlightSeq_get_length(&data_seq); ++i) {
if (DDS_SampleInfoSeq_get_reference(&info_seq, i)->valid_data) {
FlightTypeSupport_print_data(
FlightSeq_get_reference(&data_seq, i));
}
}
retcode = FlightDataReader_return_loan(
flight_reader, &data_seq, &info_seq);
if (retcode != DDS_RETCODE_OK) {
printf("return loan error %d\n", retcode);
}
}
/* Cleanup and delete all entities */
return subscriber_shutdown(participant);
}
#if !(defined(RTI_VXWORKS) && !defined(__RTP__)) && !defined(RTI_PSOS)
int main(int argc, char *argv[])
{
int domainId = 0;
int sample_count = 0; /* Infinite loop */
if (argc >= 2) {
domainId = atoi(argv[1]);
}
if (argc >= 3) {
sample_count = atoi(argv[2]);
}
/* Uncomment this to turn on additional logging
NDDS_Config_Logger_set_verbosity_by_category(
NDDS_Config_Logger_get_instance(),
NDDS_CONFIG_LOG_CATEGORY_API,
NDDS_CONFIG_LOG_VERBOSITY_STATUS_ALL); */
return subscriber_main(domainId, sample_count);
}
#endif
#ifdef RTI_VX653
const unsigned char* __ctype = NULL;
void usrAppInit ()
{
#ifdef USER_APPL_INIT
USER_APPL_INIT; /* for backwards compatibility */
#endif
/* add application specific code here */
taskSpawn("sub", RTI_OSAPI_THREAD_PRIORITY_NORMAL, 0x8, 0x150000, (FUNCPTR)subscriber_main, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
}
#endif
| c |
rticonnextdds-examples | data/projects/rticonnextdds-examples/polling_querycondition/c/querycondition_subscriber.c | /*******************************************************************************
(c) 2005-2014 Copyright, Real-Time Innovations, Inc. All rights reserved.
RTI grants Licensee a license to use, modify, compile, and create derivative
works of the Software. Licensee has the right to distribute object form only
for use with RTI products. The Software is provided "as is", with no warranty
of any type, including any warranty for fitness for any purpose. RTI is under
no obligation to maintain or support the Software. RTI shall not be liable for
any incidental or consequential damages arising out of the use or inability to
use the software.
******************************************************************************/
/* querycondition_subscriber.c
A subscription example
This file is derived from code automatically generated by the rtiddsgen
command:
rtiddsgen -language C -example <arch> querycondition.idl
Example subscription of type querycondition automatically generated by
'rtiddsgen'. To test them, follow these steps:
(1) Compile this file and the example publication.
(2) Start the subscription with the command
objs/<arch>/querycondition_subscriber <domain_id> <sample_count>
(3) Start the publication with the command
objs/<arch>/querycondition_publisher <domain_id> <sample_count>
(4) [Optional] Specify the list of discovery initial peers and
multicast receive addresses via an environment variable or a file
(in the current working directory) called NDDS_DISCOVERY_PEERS.
You can run any number of publishers and subscribers programs, and can
add and remove them dynamically from the domain.
Example:
To run the example application on domain <domain_id>:
On UNIX systems:
objs/<arch>/querycondition_publisher <domain_id>
objs/<arch>/querycondition_subscriber <domain_id>
On Windows systems:
objs\<arch>\querycondition_publisher <domain_id>
objs\<arch>\querycondition_subscriber <domain_id>
modification history
------------ -------
*/
#include <stdio.h>
#include <stdlib.h>
#include "ndds/ndds_c.h"
#include "querycondition.h"
#include "queryconditionSupport.h"
/* We remove all the listener code as we won't use any listener */
/* Delete all entities */
static int subscriber_shutdown(
DDS_DomainParticipant *participant)
{
DDS_ReturnCode_t retcode;
int status = 0;
if (participant != NULL) {
retcode = DDS_DomainParticipant_delete_contained_entities(participant);
if (retcode != DDS_RETCODE_OK) {
printf("delete_contained_entities error %d\n", retcode);
status = -1;
}
retcode = DDS_DomainParticipantFactory_delete_participant(
DDS_TheParticipantFactory, participant);
if (retcode != DDS_RETCODE_OK) {
printf("delete_participant error %d\n", retcode);
status = -1;
}
}
/* RTI Connext provides the finalize_instance() method on
domain participant factory for users who want to release memory used
by the participant factory. Uncomment the following block of code for
clean destruction of the singleton. */
/*
retcode = DDS_DomainParticipantFactory_finalize_instance();
if (retcode != DDS_RETCODE_OK) {
printf("finalize_instance error %d\n", retcode);
status = -1;
}
*/
return status;
}
static int subscriber_main(int domainId, int sample_count)
{
DDS_DomainParticipant *participant = NULL;
DDS_Subscriber *subscriber = NULL;
DDS_Topic *topic = NULL;
struct DDS_DataReaderListener reader_listener =
DDS_DataReaderListener_INITIALIZER;
DDS_DataReader *reader = NULL;
queryconditionDataReader *querycondition_reader = NULL;
DDS_ReturnCode_t retcode;
const char *type_name = NULL;
int count = 0;
/* Poll for new samples every 5 seconds */
struct DDS_Duration_t poll_period = {5,0};
/* We need to change the datareader_qos for this example.
* If you want to do it programmatically, you will need to declare to
* use the following struct.*/
struct DDS_DataReaderQos datareader_qos = DDS_DataReaderQos_INITIALIZER;
/* Query Condition-specific types */
/* NOTE: There must be single-quotes in the query parameters around
* any strings! The single-quotes do NOT go in the query condition
* itself.
*/
DDS_QueryCondition *query_for_guid2;
struct DDS_StringSeq query_parameters;
const char* param_list[] = {"'GUID2'"};
/* To customize participant QoS, use
the configuration file USER_QOS_PROFILES.xml */
participant = DDS_DomainParticipantFactory_create_participant(
DDS_TheParticipantFactory, domainId, &DDS_PARTICIPANT_QOS_DEFAULT,
NULL /* listener */, DDS_STATUS_MASK_NONE);
if (participant == NULL) {
printf("create_participant error\n");
subscriber_shutdown(participant);
return -1;
}
/* To customize subscriber QoS, use
the configuration file USER_QOS_PROFILES.xml */
subscriber = DDS_DomainParticipant_create_subscriber(
participant, &DDS_SUBSCRIBER_QOS_DEFAULT, NULL /* listener */,
DDS_STATUS_MASK_NONE);
if (subscriber == NULL) {
printf("create_subscriber error\n");
subscriber_shutdown(participant);
return -1;
}
/* Register the type before creating the topic */
type_name = queryconditionTypeSupport_get_type_name();
retcode = queryconditionTypeSupport_register_type(participant, type_name);
if (retcode != DDS_RETCODE_OK) {
printf("register_type error %d\n", retcode);
subscriber_shutdown(participant);
return -1;
}
/* To customize topic QoS, use
the configuration file USER_QOS_PROFILES.xml */
topic = DDS_DomainParticipant_create_topic(
participant, "Example querycondition",
type_name, &DDS_TOPIC_QOS_DEFAULT, NULL /* listener */,
DDS_STATUS_MASK_NONE);
if (topic == NULL) {
printf("create_topic error\n");
subscriber_shutdown(participant);
return -1;
}
/* Call create_datareader passing NULL in the listener parameter */
reader = DDS_Subscriber_create_datareader(
subscriber, DDS_Topic_as_topicdescription(topic),
&DDS_DATAREADER_QOS_DEFAULT, NULL, DDS_STATUS_MASK_ALL);
if (reader == NULL) {
printf("create_datareader error\n");
subscriber_shutdown(participant);
return -1;
}
/* If you want to change datareader_qos.history programmatically rather
* than using the XML file, you will need to add the following lines to your
* code and comment out the create_datareader call above. */
/*
retcode = DDS_Subscriber_get_default_datareader_qos(subscriber,
&datareader_qos);
if (retcode != DDS_RETCODE_OK) {
printf("get_default_datareader_qos error\n");
return -1;
}
datareader_qos.history.kind = DDS_KEEP_LAST_HISTORY_QOS;
datareader_qos.history.depth = 6;
reader = DDS_Subscriber_create_datareader(
subscriber, DDS_Topic_as_topicdescription(topic),
&datareader_qos, NULL, DDS_STATUS_MASK_NONE);
if (reader == NULL) {
printf("create_datareader error\n");
subscriber_shutdown(participant);
return -1;
}
*/
querycondition_reader = queryconditionDataReader_narrow(reader);
if (querycondition_reader == NULL) {
printf("DataReader narrow error\n");
return -1;
}
/* Query for 'GUID2' This query paramater can be changed at runtime,
* allowing an application to selectively look at subsets of data
* at different times. */
DDS_StringSeq_ensure_length(&query_parameters,1,1);
DDS_StringSeq_from_array(&query_parameters, param_list, 1);
/* Create the query condition with an expession to MATCH the id field in
* the structure. Note that you should make a copy of the expression string
* when creating the query condition - beware it going out of scope! */
query_for_guid2 =
DDS_DataReader_create_querycondition(
reader,
DDS_ANY_SAMPLE_STATE, DDS_ANY_VIEW_STATE,
DDS_ALIVE_INSTANCE_STATE,
DDS_String_dup("id MATCH %0"),
&query_parameters);
/* Main loop */
for (count=0; (sample_count == 0) || (count < sample_count); ++count) {
struct DDS_SampleInfoSeq info_seq;
struct queryconditionSeq data_seq;
int i, len;
double sum;
DDS_ReturnCode_t retcode;
NDDS_Utility_sleep(&poll_period);
/* Iterate through the samples read using the read_w_condition() method,
* accessing only the samples of GUID2. Then, show the number of samples
* received and, adding the value of x on each of them to calculate the
* average afterwards. */
retcode = queryconditionDataReader_read_w_condition(
querycondition_reader,
&data_seq, &info_seq,
DDS_LENGTH_UNLIMITED,
DDS_QueryCondition_as_readcondition(query_for_guid2));
if (retcode == DDS_RETCODE_NO_DATA) {
/* Not an error */
continue;
} else if (retcode != DDS_RETCODE_OK) {
/* Is an error */
printf("take error: %d\n", retcode);
break;
}
sum = 0;
len = 0;
/* Iterate through the samples read using the take() method, getting
* the number of samples got and, adding the value of x on each of
* them to calculate the average afterwards. */
for (i = 0; i < queryconditionSeq_get_length(&data_seq); ++i) {
if (DDS_SampleInfoSeq_get_reference(&info_seq, i)->valid_data) {
len++;
sum += queryconditionSeq_get_reference(&data_seq, i)->value;
printf("Guid = %s\n", queryconditionSeq_get_reference(&data_seq,i)->id);
}
}
if (len > 0)
printf("Got %d samples. Avg = %.1f\n", len, sum/len);
retcode = queryconditionDataReader_return_loan(
querycondition_reader, &data_seq, &info_seq);
if (retcode != DDS_RETCODE_OK) {
printf("return loan error %d\n", retcode);
}
}
/* Cleanup and delete all entities */
return subscriber_shutdown(participant);
}
#if defined(RTI_WINCE)
int wmain(int argc, wchar_t** argv)
{
int domainId = 0;
int sample_count = 0; /* infinite loop */
if (argc >= 2) {
domainId = _wtoi(argv[1]);
}
if (argc >= 3) {
sample_count = _wtoi(argv[2]);
}
/* Uncomment this to turn on additional logging
NDDS_Config_Logger_set_verbosity_by_category(
NDDS_Config_Logger_get_instance(),
NDDS_CONFIG_LOG_CATEGORY_API,
NDDS_CONFIG_LOG_VERBOSITY_STATUS_ALL);
*/
return subscriber_main(domainId, sample_count);
}
#elif !(defined(RTI_VXWORKS) && !defined(__RTP__)) && !defined(RTI_PSOS)
int main(int argc, char *argv[])
{
int domainId = 0;
int sample_count = 0; /* infinite loop */
if (argc >= 2) {
domainId = atoi(argv[1]);
}
if (argc >= 3) {
sample_count = atoi(argv[2]);
}
/* Uncomment this to turn on additional logging
NDDS_Config_Logger_set_verbosity_by_category(
NDDS_Config_Logger_get_instance(),
NDDS_CONFIG_LOG_CATEGORY_API,
NDDS_CONFIG_LOG_VERBOSITY_STATUS_ALL); */
return subscriber_main(domainId, sample_count);
}
#endif
#ifdef RTI_VX653
const unsigned char* __ctype = NULL;
void usrAppInit ()
{
#ifdef USER_APPL_INIT
USER_APPL_INIT; /* for backwards compatibility */
#endif
/* add application specific code here */
taskSpawn("sub", RTI_OSAPI_THREAD_PRIORITY_NORMAL, 0x8, 0x150000, (FUNCPTR)subscriber_main, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
}
#endif
| c |
rticonnextdds-examples | data/projects/rticonnextdds-examples/polling_querycondition/c/querycondition_publisher.c | /*******************************************************************************
(c) 2005-2014 Copyright, Real-Time Innovations, Inc. All rights reserved.
RTI grants Licensee a license to use, modify, compile, and create derivative
works of the Software. Licensee has the right to distribute object form only
for use with RTI products. The Software is provided "as is", with no warranty
of any type, including any warranty for fitness for any purpose. RTI is under
no obligation to maintain or support the Software. RTI shall not be liable for
any incidental or consequential damages arising out of the use or inability to
use the software.
******************************************************************************/
/* querycondition_publisher.c
A publication of data of type querycondition
This file is derived from code automatically generated by the rtiddsgen
command:
rtiddsgen -language C -example <arch> querycondition.idl
Example publication of type querycondition automatically generated by
'rtiddsgen'. To test them follow these steps:
(1) Compile this file and the example subscription.
(2) Start the subscription with the command
objs/<arch>/querycondition_subscriber <domain_id> <sample_count>
(3) Start the publication with the command
objs/<arch>/querycondition_publisher <domain_id> <sample_count>
(4) [Optional] Specify the list of discovery initial peers and
multicast receive addresses via an environment variable or a file
(in the current working directory) called NDDS_DISCOVERY_PEERS.
You can run any number of publishers and subscribers programs, and can
add and remove them dynamically from the domain.
Example:
To run the example application on domain <domain_id>:
On Unix:
objs/<arch>/querycondition_publisher <domain_id>
objs/<arch>/querycondition_subscriber <domain_id>
On Windows:
objs\<arch>\querycondition_publisher <domain_id>
objs\<arch>\querycondition_subscriber <domain_id>
modification history
------------ -------
*/
#include <stdio.h>
#include <stdlib.h>
#include "ndds/ndds_c.h"
#include "querycondition.h"
#include "queryconditionSupport.h"
#include <time.h>
/* Delete all entities */
static int publisher_shutdown(
DDS_DomainParticipant *participant)
{
DDS_ReturnCode_t retcode;
int status = 0;
if (participant != NULL) {
retcode = DDS_DomainParticipant_delete_contained_entities(participant);
if (retcode != DDS_RETCODE_OK) {
printf("delete_contained_entities error %d\n", retcode);
status = -1;
}
retcode = DDS_DomainParticipantFactory_delete_participant(
DDS_TheParticipantFactory, participant);
if (retcode != DDS_RETCODE_OK) {
printf("delete_participant error %d\n", retcode);
status = -1;
}
}
/* RTI Connext provides finalize_instance() method on
domain participant factory for people who want to release memory used
by the participant factory. Uncomment the following block of code for
clean destruction of the singleton. */
/*
retcode = DDS_DomainParticipantFactory_finalize_instance();
if (retcode != DDS_RETCODE_OK) {
printf("finalize_instance error %d\n", retcode);
status = -1;
}
*/
return status;
}
static int publisher_main(int domainId, int sample_count)
{
DDS_DomainParticipant *participant = NULL;
DDS_Publisher *publisher = NULL;
DDS_Topic *topic = NULL;
DDS_DataWriter *writer = NULL;
queryconditionDataWriter *querycondition_writer = NULL;
querycondition *instance = NULL;
DDS_ReturnCode_t retcode;
DDS_InstanceHandle_t instance_handle = DDS_HANDLE_NIL;
const char *type_name = NULL;
int count = 0;
/* Send a new sample every second */
struct DDS_Duration_t send_period = {1,0};
/* Set up some unique IDs that can be used for the data type */
char *myIds[] = {"GUID1", "GUID2", "GUID3"};
/* To customize participant QoS, use
the configuration file USER_QOS_PROFILES.xml */
participant = DDS_DomainParticipantFactory_create_participant(
DDS_TheParticipantFactory, domainId, &DDS_PARTICIPANT_QOS_DEFAULT,
NULL /* listener */, DDS_STATUS_MASK_NONE);
if (participant == NULL) {
printf("create_participant error\n");
publisher_shutdown(participant);
return -1;
}
/* To customize publisher QoS, use
the configuration file USER_QOS_PROFILES.xml */
publisher = DDS_DomainParticipant_create_publisher(
participant, &DDS_PUBLISHER_QOS_DEFAULT, NULL /* listener */,
DDS_STATUS_MASK_NONE);
if (publisher == NULL) {
printf("create_publisher error\n");
publisher_shutdown(participant);
return -1;
}
/* Register type before creating topic */
type_name = queryconditionTypeSupport_get_type_name();
retcode = queryconditionTypeSupport_register_type(
participant, type_name);
if (retcode != DDS_RETCODE_OK) {
printf("register_type error %d\n", retcode);
publisher_shutdown(participant);
return -1;
}
/* To customize topic QoS, use
the configuration file USER_QOS_PROFILES.xml */
topic = DDS_DomainParticipant_create_topic(
participant, "Example querycondition",
type_name, &DDS_TOPIC_QOS_DEFAULT, NULL /* listener */,
DDS_STATUS_MASK_NONE);
if (topic == NULL) {
printf("create_topic error\n");
publisher_shutdown(participant);
return -1;
}
/* To customize data writer QoS, use
the configuration file USER_QOS_PROFILES.xml */
writer = DDS_Publisher_create_datawriter(
publisher, topic,
&DDS_DATAWRITER_QOS_DEFAULT, NULL /* listener */, DDS_STATUS_MASK_NONE);
if (writer == NULL) {
printf("create_datawriter error\n");
publisher_shutdown(participant);
return -1;
}
querycondition_writer = queryconditionDataWriter_narrow(writer);
if (querycondition_writer == NULL) {
printf("DataWriter narrow error\n");
publisher_shutdown(participant);
return -1;
}
/* Create data sample for writing */
instance = queryconditionTypeSupport_create_data_ex(DDS_BOOLEAN_TRUE);
if (instance == NULL) {
printf("queryconditionTypeSupport_create_data error\n");
publisher_shutdown(participant);
return -1;
}
/* For a data type that has a key, if the same instance is going to be
written multiple times, initialize the key here
and register the keyed instance prior to writing */
/*
instance_handle = queryconditionDataWriter_register_instance(
querycondition_writer, instance);
*/
/* Initialize random seed before entering the loop */
srand(time(NULL));
/* Main loop */
for (count=0; (sample_count == 0) || (count < sample_count); ++count) {
/* Modify the data to be written here */
/* Set id to be one of the three options */
sprintf(instance->id, "%s", myIds[count%3]);
/* Set x to a random number between 0 and 9 */
instance->value = (int)(rand()/(RAND_MAX/10.0));
printf("Writing querycondition, count %d, id = %s, value = %d\n", count,
instance->id,
instance->value);
/* Write data */
retcode = queryconditionDataWriter_write(
querycondition_writer, instance, &instance_handle);
if (retcode != DDS_RETCODE_OK) {
printf("write error %d\n", retcode);
}
NDDS_Utility_sleep(&send_period);
}
/*
retcode = queryconditionDataWriter_unregister_instance(
querycondition_writer, instance, &instance_handle);
if (retcode != DDS_RETCODE_OK) {
printf("unregister instance error %d\n", retcode);
}
*/
/* Delete data sample */
retcode = queryconditionTypeSupport_delete_data_ex(instance, DDS_BOOLEAN_TRUE);
if (retcode != DDS_RETCODE_OK) {
printf("queryconditionTypeSupport_delete_data error %d\n", retcode);
}
/* Cleanup and delete delete all entities */
return publisher_shutdown(participant);
}
#if defined(RTI_WINCE)
int wmain(int argc, wchar_t** argv)
{
int domainId = 0;
int sample_count = 0; /* infinite loop */
if (argc >= 2) {
domainId = _wtoi(argv[1]);
}
if (argc >= 3) {
sample_count = _wtoi(argv[2]);
}
/* Uncomment this to turn on additional logging
NDDS_Config_Logger_set_verbosity_by_category(
NDDS_Config_Logger_get_instance(),
NDDS_CONFIG_LOG_CATEGORY_API,
NDDS_CONFIG_LOG_VERBOSITY_STATUS_ALL);
*/
return publisher_main(domainId, sample_count);
}
#elif !(defined(RTI_VXWORKS) && !defined(__RTP__)) && !defined(RTI_PSOS)
int main(int argc, char *argv[])
{
int domainId = 0;
int sample_count = 0; /* infinite loop */
if (argc >= 2) {
domainId = atoi(argv[1]);
}
if (argc >= 3) {
sample_count = atoi(argv[2]);
}
/* Uncomment this to turn on additional logging
NDDS_Config_Logger_set_verbosity_by_category(
NDDS_Config_Logger_get_instance(),
NDDS_CONFIG_LOG_CATEGORY_API,
NDDS_CONFIG_LOG_VERBOSITY_STATUS_ALL);
*/
return publisher_main(domainId, sample_count);
}
#endif
#ifdef RTI_VX653
const unsigned char* __ctype = NULL;
void usrAppInit ()
{
#ifdef USER_APPL_INIT
USER_APPL_INIT; /* for backwards compatibility */
#endif
/* add application specific code here */
taskSpawn("pub", RTI_OSAPI_THREAD_PRIORITY_NORMAL, 0x8, 0x150000, (FUNCPTR)publisher_main, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
}
#endif
| c |
rticonnextdds-examples | data/projects/rticonnextdds-examples/polling_querycondition/c++03/flights_subscriber.cxx | /*******************************************************************************
(c) 2005-2015 Copyright, Real-Time Innovations, Inc. All rights reserved.
RTI grants Licensee a license to use, modify, compile, and create derivative
works of the Software. Licensee has the right to distribute object form only
for use with RTI products. The Software is provided "as is", with no warranty
of any type, including any warranty for fitness for any purpose. RTI is under
no obligation to maintain or support the Software. RTI shall not be liable for
any incidental or consequential damages arising out of the use or inability to
use the software.
******************************************************************************/
#include <iostream>
#include <dds/dds.hpp>
#include "flights.hpp"
using namespace dds::core;
using namespace dds::core::policy;
using namespace dds::domain;
using namespace dds::topic;
using namespace dds::sub;
using namespace dds::sub::cond;
using namespace dds::sub::qos;
using namespace dds::sub::status;
void subscriber_main(int domain_id, int sample_count)
{
// Create a DomainParticipant with default Qos.
DomainParticipant participant(domain_id);
// Create a Topic -- and automatically register the type.
Topic<Flight> topic(participant, "Example Flight");
// Retrieve the default DataWriter QoS, from USER_QOS_PROFILES.xml
DataReaderQos reader_qos = QosProvider::Default().datareader_qos();
// If you want to change the DataReader's QoS programmatically rather than
// using the XML file, uncomment the following lines.
// reader_qos << Reliability::Reliable();
// Create a DataReader.
DataReader<Flight> reader(Subscriber(participant), topic, reader_qos);
// Query for company named 'CompanyA' and for flights in cruise
// (about 30,000ft). The company parameter will be changed in run-time.
// NOTE: There must be single-quotes in the query parameters around-any
// strings! The single-quote do NOT go in the query condition itself.
std::vector<std::string> query_parameters(2);
query_parameters[0] = "'CompanyA'";
query_parameters[1] = "30000";
std::cout << "Setting parameters to company: " << query_parameters[0]
<< " and altitude bigger or equals to " << query_parameters[1]
<< std::endl;
// Create the query condition with an expession to MATCH the id field in
// the structure and a numeric comparison.
QueryCondition query_condition(
Query(reader, "company MATCH %0 AND altitude >= %1", query_parameters),
DataState::any_data());
// Main loop
bool update = false;
for (int count = 0; (sample_count == 0) || (count < sample_count); count++){
// Poll for new samples every second.
rti::util::sleep(Duration(1));
// Change the filter parameter after 5 seconds.
if ((count + 1) % 10 == 5) {
query_parameters[0] = "'CompanyB'";
update = true;
} else if ((count + 1) % 10 == 0) {
query_parameters[0] = "'CompanyA'";
update = true;
}
// Set new parameters.
if (update) {
std::cout << "Changing parameter to " << query_parameters[0]
<< std::endl;
query_condition.parameters(
query_parameters.begin(),
query_parameters.end());
update = false;
}
// Get new samples selecting them with a condition.
LoanedSamples<Flight> samples = reader.select()
.condition(query_condition)
.read();
for (LoanedSamples<Flight>::iterator sampleIt = samples.begin();
sampleIt != samples.end();
++sampleIt) {
if (!sampleIt->info().valid())
continue;
std::cout << "\t" << sampleIt->data() << std::endl;
}
}
}
int main(int argc, char *argv[])
{
int domain_id = 0;
int sample_count = 0; // Infinite loop
if (argc >= 2) {
domain_id = atoi(argv[1]);
}
if (argc >= 3) {
sample_count = atoi(argv[2]);
}
// To turn on additional logging, include <rti/config/Logger.hpp> and
// uncomment the following line:
// rti::config::Logger::instance()l.verbosity(rti::config::Verbosity::STATUS_ALL);
try {
subscriber_main(domain_id, sample_count);
} catch (std::exception ex) {
std::cout << "Exception caught: " << ex.what() << std::endl;
return -1;
}
return 0;
}
| cxx |
rticonnextdds-examples | data/projects/rticonnextdds-examples/polling_querycondition/c++03/flights_publisher.cxx | /*******************************************************************************
(c) 2005-2015 Copyright, Real-Time Innovations, Inc. All rights reserved.
RTI grants Licensee a license to use, modify, compile, and create derivative
works of the Software. Licensee has the right to distribute object form only
for use with RTI products. The Software is provided "as is", with no warranty
of any type, including any warranty for fitness for any purpose. RTI is under
no obligation to maintain or support the Software. RTI shall not be liable for
any incidental or consequential damages arising out of the use or inability to
use the software.
******************************************************************************/
#include <iostream>
#include <dds/dds.hpp>
#include "flights.hpp"
using namespace dds::core;
using namespace dds::core::policy;
using namespace dds::domain;
using namespace dds::topic;
using namespace dds::pub;
using namespace dds::pub::qos;
void publisher_main(int domain_id, int sample_count)
{
// Create a DomainParticipant with default Qos.
DomainParticipant participant (domain_id);
// Create a Topic -- and automatically register the type.
Topic<Flight> topic (participant, "Example Flight");
// Retrieve the default DataWriter QoS, from USER_QOS_PROFILES.xml
DataWriterQos writer_qos = QosProvider::Default().datawriter_qos();
// If you want to change the DataReader's QoS programmatically rather than
// using the XML file, uncomment the following lines.
// writer_qos << Reliability::Reliable();
// Create a DataWriter.
DataWriter<Flight> writer(Publisher(participant), topic, writer_qos);
// Create the flight info samples.
std::vector<Flight> flights_info(4);
flights_info[0] = Flight(1111, "CompanyA", 15000);
flights_info[1] = Flight(2222, "CompanyB", 20000);
flights_info[2] = Flight(3333, "CompanyA", 30000);
flights_info[3] = Flight(4444, "CompanyB", 25000);
// Main loop
for (int count = 0;
(sample_count == 0) || (count < sample_count);
count += flights_info.size()){
// Update flight info latitude
std::cout << "Updating and sending values" << std::endl;
for (std::vector<int>::size_type f = 0; f < flights_info.size(); f++) {
// Set the plane altitude lineally (usually the max is at 41,000ft).
int altitude = flights_info[f].altitude() + count * 100;
flights_info[f].altitude(altitude >= 41000 ? 41000 : altitude);
std::cout << "\t" << flights_info[f] << std::endl;
}
writer.write(flights_info.begin(), flights_info.end());
rti::util::sleep(Duration(1));
}
}
int main(int argc, char *argv[])
{
int domain_id = 0;
int sample_count = 0; // Infinite loop
if (argc >= 2) {
domain_id = atoi(argv[1]);
}
if (argc >= 3) {
sample_count = atoi(argv[2]);
}
// To turn on additional logging, include <rti/config/Logger.hpp> and
// uncomment the following line:
// rti::config::Logger::instance().verbosity(rti::config::Verbosity::STATUS_ALL);
try {
publisher_main(domain_id, sample_count);
} catch (std::exception ex) {
std::cout << "Exception caught: " << ex.what() << std::endl;
return -1;
}
return 0;
}
| cxx |
rticonnextdds-examples | data/projects/rticonnextdds-examples/deadline_contentfilter/c++/deadline_contentfilter_subscriber.cxx | /*******************************************************************************
(c) 2005-2014 Copyright, Real-Time Innovations, Inc. All rights reserved.
RTI grants Licensee a license to use, modify, compile, and create derivative
works of the Software. Licensee has the right to distribute object form only
for use with RTI products. The Software is provided "as is", with no warranty
of any type, including any warranty for fitness for any purpose. RTI is under
no obligation to maintain or support the Software. RTI shall not be liable for
any incidental or consequential damages arising out of the use or inability to
use the software.
******************************************************************************/
/* deadline_contentfilter_subscriber.cxx
A subscription example
This file is derived from code automatically generated by the rtiddsgen
command:
rtiddsgen -language C++ -example <arch> deadline_contentfilter.idl
Example subscription of type deadline_contentfilter automatically generated
by 'rtiddsgen'. To test them follow these steps:
(1) Compile this file and the example publication.
(2) Start the subscription on the same domain used for RTI Data Distribution
Service with the command
objs/<arch>/deadline_contentfilter_subscriber <domain_id> <sample_count>
(3) Start the publication on the same domain used for RTI Data Distribution
with the command
objs/<arch>/deadline_contentfilter_publisher <domain_id> <sample_count>
(4) [Optional] Specify the list of discovery initial peers and
multicast receive addresses via an environment variable or a file
(in the current working directory) called NDDS_DISCOVERY_PEERS.
You can run any number of publishers and subscribers programs, and can
add and remove them dynamically from the domain.
Example:
To run the example application on domain <domain_id>:
On Unix:
objs/<arch>/deadline_contentfilter_publisher <domain_id>
objs/<arch>/deadline_contentfilter_subscriber <domain_id>
On Windows:
objs\<arch>\deadline_contentfilter_publisher <domain_id>
objs\<arch>\deadline_contentfilter_subscriber <domain_id>
modification history
------------ -------
* Create clock to show relative timing of events
* Define listener for requested deadline missed status
* Set deadline QoS
* Create content filter that ignores second instance
after 5 seconds
*/
/* This example sets the deadline period to 2 seconds to trigger a deadline if
the DataWriter does not update often enough, or if the content-filter
filters out data so there is no data available within 2 seconds.
This example starts by filtering out instances >= 2, and changes to later
filter out instances >= 1.
*/
#include <stdio.h>
#include <stdlib.h>
#include "ndds/ndds_cpp.h"
#include "deadline_contentfilter.h"
#include "deadline_contentfilterSupport.h"
//// Changes for Deadline
// For timekeeping
#include <time.h>
clock_t init;
class deadline_contentfilterListener : public DDSDataReaderListener {
public:
virtual void on_requested_deadline_missed(
DDSDataReader* /*reader*/,
const DDS_RequestedDeadlineMissedStatus& /*status*/);
virtual void on_requested_incompatible_qos(
DDSDataReader* /*reader*/,
const DDS_RequestedIncompatibleQosStatus& /*status*/) {}
virtual void on_sample_rejected(
DDSDataReader* /*reader*/,
const DDS_SampleRejectedStatus& /*status*/) {}
virtual void on_liveliness_changed(
DDSDataReader* /*reader*/,
const DDS_LivelinessChangedStatus& /*status*/) {}
virtual void on_sample_lost(
DDSDataReader* /*reader*/,
const DDS_SampleLostStatus& /*status*/) {}
virtual void on_subscription_matched(
DDSDataReader* /*reader*/,
const DDS_SubscriptionMatchedStatus& /*status*/) {}
virtual void on_data_available(DDSDataReader* reader);
};
/* Start changes for Deadline */
void deadline_contentfilterListener::on_requested_deadline_missed(
DDSDataReader* reader, const DDS_RequestedDeadlineMissedStatus& status)
{
double elapsed_ticks = clock() - init;
double elapsed_secs = elapsed_ticks/CLOCKS_PER_SEC;
/* Creates a temporary object of our structure "deadline_contentfilter"
* in order to find out which instance missed its deadline period. The
* get_key_value call only fills in the values of the key fields inside
* the dummy object.
*/
deadline_contentfilter dummy;
DDS_ReturnCode_t retcode =
((deadline_contentfilterDataReader*)reader)->get_key_value(
dummy, status.last_instance_handle);
if (retcode != DDS_RETCODE_OK) {
printf("get_key_value error %d\n", retcode);
return;
}
/* Print out which instance missed its deadline. */
printf("Missed deadline @ t=%.2fs on instance code = %d\n",
elapsed_secs, dummy.code);
}
/* End changes for Deadline */
void deadline_contentfilterListener::on_data_available(DDSDataReader* reader)
{
deadline_contentfilterDataReader *deadline_contentfilter_reader = NULL;
deadline_contentfilterSeq data_seq;
DDS_SampleInfoSeq info_seq;
DDS_ReturnCode_t retcode;
int i;
deadline_contentfilter_reader =
deadline_contentfilterDataReader::narrow(reader);
if (deadline_contentfilter_reader == NULL) {
printf("DataReader narrow error\n");
return;
}
retcode = deadline_contentfilter_reader->take(
data_seq, info_seq, DDS_LENGTH_UNLIMITED,
DDS_ANY_SAMPLE_STATE, DDS_ANY_VIEW_STATE, DDS_ANY_INSTANCE_STATE);
if (retcode == DDS_RETCODE_NO_DATA) {
return;
} else if (retcode != DDS_RETCODE_OK) {
printf("take error %d\n", retcode);
return;
}
for (i = 0; i < data_seq.length(); ++i) {
if (info_seq[i].valid_data) {
/* Start changes for Deadline */
/* print the time we get each sample. */
double elapsed_ticks = clock() - init;
double elapsed_secs = elapsed_ticks/CLOCKS_PER_SEC;
printf("@ t=%.2fs, Instance%d: <%d,%d>\n",
elapsed_secs, data_seq[i].code, data_seq[i].x,
data_seq[i].y);
/* deadlineTypeSupport::print_data(&data_seq[i]); */
/* End changes for Deadline */
}
}
retcode = deadline_contentfilter_reader->return_loan(data_seq, info_seq);
if (retcode != DDS_RETCODE_OK) {
printf("return loan error %d\n", retcode);
}
}
/* Delete all entities */
static int subscriber_shutdown(
DDSDomainParticipant *participant)
{
DDS_ReturnCode_t retcode;
int status = 0;
if (participant != NULL) {
retcode = participant->delete_contained_entities();
if (retcode != DDS_RETCODE_OK) {
printf("delete_contained_entities error %d\n", retcode);
status = -1;
}
retcode = DDSTheParticipantFactory->delete_participant(participant);
if (retcode != DDS_RETCODE_OK) {
printf("delete_participant error %d\n", retcode);
status = -1;
}
}
/* RTI Data Distribution Service provides finalize_instance() method for
people who want to release memory used by the participant factory
singleton. Uncomment the following block of code for clean destruction of
the participant factory singleton. */
/*
retcode = DDSDomainParticipantFactory::finalize_instance();
if (retcode != DDS_RETCODE_OK) {
printf("finalize_instance error %d\n", retcode);
status = -1;
}
*/
return status;
}
extern "C" int subscriber_main(int domainId, int sample_count)
{
DDSDomainParticipant *participant = NULL;
DDSSubscriber *subscriber = NULL;
DDSTopic *topic = NULL;
deadline_contentfilterListener *reader_listener = NULL;
DDSDataReader *reader = NULL;
DDS_ReturnCode_t retcode;
const char *type_name = NULL;
int count = 0;
struct DDS_Duration_t receive_period = {1,0};
int status = 0;
/* Changes for Deadline */
/* for timekeeping */
init = clock();
/* To customize participant QoS, use
DDSTheParticipantFactory->get_default_participant_qos() */
participant = DDSTheParticipantFactory->create_participant(
domainId, DDS_PARTICIPANT_QOS_DEFAULT,
NULL /* listener */, DDS_STATUS_MASK_NONE);
if (participant == NULL) {
printf("create_participant error\n");
subscriber_shutdown(participant);
return -1;
}
/* To customize subscriber QoS, use
participant->get_default_subscriber_qos() */
subscriber = participant->create_subscriber(
DDS_SUBSCRIBER_QOS_DEFAULT, NULL /* listener */, DDS_STATUS_MASK_NONE);
if (subscriber == NULL) {
printf("create_subscriber error\n");
subscriber_shutdown(participant);
return -1;
}
/* Register type before creating topic */
type_name = deadline_contentfilterTypeSupport::get_type_name();
retcode = deadline_contentfilterTypeSupport::register_type(
participant, type_name);
if (retcode != DDS_RETCODE_OK) {
printf("register_type error %d\n", retcode);
subscriber_shutdown(participant);
return -1;
}
/* To customize topic QoS, use
participant->get_default_topic_qos() */
topic = participant->create_topic(
"Example deadline_contentfilter",
type_name, DDS_TOPIC_QOS_DEFAULT, NULL /* listener */,
DDS_STATUS_MASK_NONE);
if (topic == NULL) {
printf("create_topic error\n");
subscriber_shutdown(participant);
return -1;
}
/* Create data reader listener */
reader_listener = new deadline_contentfilterListener();
if (reader_listener == NULL) {
printf("listener instantiation error\n");
subscriber_shutdown(participant);
return -1;
}
/* Start changes for Deadline */
/* Set up content filtered topic to show interaction with deadline */
DDS_StringSeq parameters(1);
const char* param_list[] = {"2"};
parameters.from_array(param_list, 1);
DDSContentFilteredTopic *cft = NULL;
cft = participant->create_contentfilteredtopic(
"ContentFilteredTopic", topic, "code < %0", parameters);
/* Get default datareader QoS to customize */
DDS_DataReaderQos datareader_qos;
retcode = subscriber->get_default_datareader_qos(datareader_qos);
if (retcode != DDS_RETCODE_OK) {
printf("get_default_datareader_qos error\n");
return -1;
}
reader = subscriber->create_datareader(
cft, DDS_DATAREADER_QOS_DEFAULT,
reader_listener,
DDS_STATUS_MASK_ALL);
if (reader == NULL) {
printf("create_datareader error\n");
subscriber_shutdown(participant);
delete reader_listener;
return -1;
}
/* If you want to change the DataReader's QoS programmatically rather than
* using the XML file, you will need to add the following lines to your
* code and comment out the create_datareader call above.
*
* In this case, we set the deadline period to 2 seconds to trigger
* a deadline if the DataWriter does not update often enough, or if
* the content-filter filters out data so there is no data available
* with 2 seconds.
*/
/* Set deadline QoS */
/* DDS_Duration_t deadline_period = {2, 0};
datareader_qos.deadline.period = deadline_period;
reader = subscriber->create_datareader(
cft, datareader_qos, reader_listener,
DDS_STATUS_MASK_ALL);
if (reader == NULL) {
printf("create_datareader error\n");
subscriber_shutdown(participant);
delete reader_listener;
return -1;
}
*/
/* Main loop */
for (count=0; (sample_count == 0) || (count < sample_count); ++count) {
/* printf("deadline_contentfilter subscriber sleeping for %d sec...\n",
receive_period.sec);
*/
/* After 10 seconds, change content filter to accept only instance 0 */
if (count == 10) {
printf("Starting to filter out instance1\n");
parameters[0] = DDS_String_dup("1");
cft->set_expression_parameters(parameters);
}
NDDSUtility::sleep(receive_period);
}
/* End changes for Deadline */
/* Delete all entities */
status = subscriber_shutdown(participant);
delete reader_listener;
return status;
}
#if defined(RTI_WINCE)
int wmain(int argc, wchar_t** argv)
{
int domainId = 0;
int sample_count = 0; /* infinite loop */
if (argc >= 2) {
domainId = _wtoi(argv[1]);
}
if (argc >= 3) {
sample_count = _wtoi(argv[2]);
}
/* Uncomment this to turn on additional logging
NDDSConfigLogger::get_instance()->
set_verbosity_by_category(NDDS_CONFIG_LOG_CATEGORY_API,
NDDS_CONFIG_LOG_VERBOSITY_STATUS_ALL);
*/
return subscriber_main(domainId, sample_count);
}
#elif !(defined(RTI_VXWORKS) && !defined(__RTP__)) && !defined(RTI_PSOS)
int main(int argc, char *argv[])
{
int domainId = 0;
int sample_count = 0; /* infinite loop */
if (argc >= 2) {
domainId = atoi(argv[1]);
}
if (argc >= 3) {
sample_count = atoi(argv[2]);
}
/* Uncomment this to turn on additional logging
NDDSConfigLogger::get_instance()->
set_verbosity_by_category(NDDS_CONFIG_LOG_CATEGORY_API,
NDDS_CONFIG_LOG_VERBOSITY_STATUS_ALL);
*/
return subscriber_main(domainId, sample_count);
}
#endif
| cxx |
rticonnextdds-examples | data/projects/rticonnextdds-examples/deadline_contentfilter/c++/deadline_contentfilter_publisher.cxx | /*******************************************************************************
(c) 2005-2014 Copyright, Real-Time Innovations, Inc. All rights reserved.
RTI grants Licensee a license to use, modify, compile, and create derivative
works of the Software. Licensee has the right to distribute object form only
for use with RTI products. The Software is provided "as is", with no warranty
of any type, including any warranty for fitness for any purpose. RTI is under
no obligation to maintain or support the Software. RTI shall not be liable for
any incidental or consequential damages arising out of the use or inability to
use the software.
******************************************************************************/
/* deadline_contentfilter_publisher.cxx
A publication of data of type deadline_contentfilter
This file is derived from code automatically generated by the rtiddsgen
command:
rtiddsgen -language C++ -example <arch> deadline_contentfilter.idl
Example publication of type deadline_contentfilter automatically generated by
'rtiddsgen'. To test them follow these steps:
(1) Compile this file and the example subscription.
(2) Start the subscription on the same domain used for RTI Data Distribution
with the command
objs/<arch>/deadline_contentfilter_subscriber <domain_id> <sample_count>
(3) Start the publication on the same domain used for RTI Data Distribution
with the command
objs/<arch>/deadline_contentfilter_publisher <domain_id> <sample_count>
(4) [Optional] Specify the list of discovery initial peers and
multicast receive addresses via an environment variable or a file
(in the current working directory) called NDDS_DISCOVERY_PEERS.
You can run any number of publishers and subscribers programs, and can
add and remove them dynamically from the domain.
Example:
To run the example application on domain <domain_id>:
On Unix:
objs/<arch>/deadline_contentfilter_publisher <domain_id> o
objs/<arch>/deadline_contentfilter_subscriber <domain_id>
On Windows:
objs\<arch>\deadline_contentfilter_publisher <domain_id>
objs\<arch>\deadline_contentfilter_subscriber <domain_id>
modification history
------------ -------
* Create and install listener for offered deadline missed status
* Set deadline QoS
*/
/* This example sets the deadline period to 1.5 seconds to trigger a deadline
if the DataWriter does not update often enough. The writer's updates are
dependent on the application code, so the middleware can notify the
application that it has failed to update often enough.
*/
#include <stdio.h>
#include <stdlib.h>
#include "ndds/ndds_cpp.h"
#include "deadline_contentfilter.h"
#include "deadline_contentfilterSupport.h"
/* Start changes for Deadline */
class deadline_contentfilterListener : public DDSDataWriterListener {
public:
virtual void on_offered_deadline_missed(
DDSDataWriter* writer,
const DDS_OfferedDeadlineMissedStatus& status) {
deadline_contentfilter dummy;
DDS_ReturnCode_t retcode =
((deadline_contentfilterDataWriter*) writer)->get_key_value(
dummy, status.last_instance_handle);
if (retcode != DDS_RETCODE_OK) {
printf("get_key_value error %d\n", retcode);
return;
}
printf("Offered deadline missed on instance code = %d\n", dummy.code);
}
};
/* End changes for Deadline */
/* Delete all entities */
static int publisher_shutdown(
DDSDomainParticipant *participant)
{
DDS_ReturnCode_t retcode;
int status = 0;
if (participant != NULL) {
retcode = participant->delete_contained_entities();
if (retcode != DDS_RETCODE_OK) {
printf("delete_contained_entities error %d\n", retcode);
status = -1;
}
retcode = DDSTheParticipantFactory->delete_participant(participant);
if (retcode != DDS_RETCODE_OK) {
printf("delete_participant error %d\n", retcode);
status = -1;
}
}
/* RTI Data Distribution Service provides finalize_instance() method for
people who want to release memory used by the participant factory
singleton. Uncomment the following block of code for clean destruction of
the participant factory singleton. */
/*
retcode = DDSDomainParticipantFactory::finalize_instance();
if (retcode != DDS_RETCODE_OK) {
printf("finalize_instance error %d\n", retcode);
status = -1;
}
*/
return status;
}
extern "C" int publisher_main(int domainId, int sample_count)
{
DDSDomainParticipant *participant = NULL;
DDSPublisher *publisher = NULL;
DDSTopic *topic = NULL;
DDSDataWriter *writer = NULL;
deadline_contentfilterDataWriter * deadline_contentfilter_writer = NULL;
DDS_ReturnCode_t retcode;
const char *type_name = NULL;
int count = 0;
/* To customize participant QoS, use
DDSTheParticipantFactory->get_default_participant_qos() */
participant = DDSTheParticipantFactory->create_participant(
domainId, DDS_PARTICIPANT_QOS_DEFAULT,
NULL /* listener */, DDS_STATUS_MASK_NONE);
if (participant == NULL) {
printf("create_participant error\n");
publisher_shutdown(participant);
return -1;
}
/* To customize publisher QoS, use
participant->get_default_publisher_qos() */
publisher = participant->create_publisher(
DDS_PUBLISHER_QOS_DEFAULT, NULL /* listener */, DDS_STATUS_MASK_NONE);
if (publisher == NULL) {
printf("create_participant error\n");
publisher_shutdown(participant);
return -1;
}
/* Register type before creating topic */
type_name = deadline_contentfilterTypeSupport::get_type_name();
retcode = deadline_contentfilterTypeSupport::register_type(
participant, type_name);
if (retcode != DDS_RETCODE_OK) {
printf("register_type error %d\n", retcode);
publisher_shutdown(participant);
return -1;
}
/* To customize topic QoS, use
participant->get_default_topic_qos() */
topic = participant->create_topic(
"Example deadline_contentfilter",
type_name, DDS_TOPIC_QOS_DEFAULT, NULL /* listener */,
DDS_STATUS_MASK_NONE);
if (topic == NULL) {
printf("create_topic error\n");
publisher_shutdown(participant);
return -1;
}
/* Start changes for Deadline */
/* Create listener */
deadline_contentfilterListener* writer_listener = NULL;
writer_listener = new deadline_contentfilterListener();
if (writer_listener == NULL) {
printf("listener instantiation error\n");
publisher_shutdown(participant);
return -1;
}
writer = publisher->create_datawriter(
topic, DDS_DATAWRITER_QOS_DEFAULT, writer_listener,
DDS_OFFERED_DEADLINE_MISSED_STATUS);
if (writer == NULL) {
printf("create_datawriter error\n");
publisher_shutdown(participant);
return -1;
}
/* If you want to change the DataWriter's QoS programmatically rather than
* using the XML file, you will need to add the following lines to your
* code and comment out the create_datawriter call above.
*
* In this case, we set the deadline period to 1.5 seconds to trigger
* a deadline if the DataWriter does not update often enough.
*/
/*
DDS_DataWriterQos datawriter_qos;
retcode = publisher->get_default_datawriter_qos(datawriter_qos);
if (retcode != DDS_RETCODE_OK) {
printf("get_default_datawriter_qos error\n");
return -1;
}
*/ /* Set deadline QoS */
/* DDS_Duration_t deadline_period = {1, 500000000};
datawriter_qos.deadline.period = deadline_period;
writer = publisher->create_datawriter(
topic, datawriter_qos, writer_listener,
DDS_OFFERED_DEADLINE_MISSED_STATUS);
if (writer == NULL) {
printf("create_datawriter error\n");
publisher_shutdown(participant);
return -1;
}
*/
/* End changes for Deadline */
deadline_contentfilter_writer =
deadline_contentfilterDataWriter::narrow(writer);
if (deadline_contentfilter_writer == NULL) {
printf("DataWriter narrow error\n");
publisher_shutdown(participant);
return -1;
}
/* Start changes for Deadline */
/* Create two instances for writing */
deadline_contentfilter *instance0 = NULL;
deadline_contentfilter *instance1 = NULL;
DDS_InstanceHandle_t handle0 = DDS_HANDLE_NIL;
DDS_InstanceHandle_t handle1 = DDS_HANDLE_NIL;
/* Create data samples for writing */
instance0 = deadline_contentfilterTypeSupport::create_data();
instance1 = deadline_contentfilterTypeSupport::create_data();
if (instance0 == NULL || instance1 == NULL) {
printf("deadline_contentfilterTypeSupport::create_data error\n");
publisher_shutdown(participant);
return -1;
}
/* Set keys -- we specify 'code' as the key field in the .idl*/
instance0->code = 0;
instance1->code = 1;
/* For data type that has key, if the same instance is going to be
written multiple times, initialize the key here
and register the keyed instance prior to writing */
handle0 = deadline_contentfilter_writer->register_instance(*instance0);
handle1 = deadline_contentfilter_writer->register_instance(*instance1);
struct DDS_Duration_t send_period = {1, 0};
instance0->x = instance0->y = instance1->x = instance1->y = 0;
/* Main loop */
for (count=0; (sample_count == 0) || (count < sample_count); ++count) {
NDDSUtility::sleep(send_period);
instance0->x++;
instance0->y++;
instance1->x++;
instance1->y++;
printf("Writing instance0, x = %d, y = %d\n", instance0->x,
instance0->y);
retcode = deadline_contentfilter_writer->write(*instance0, handle0);
if (retcode != DDS_RETCODE_OK) {
printf("write error %d\n", retcode);
publisher_shutdown(participant);
return -1;
}
if (count < 15) {
printf("Writing instance1, x = %d, y = %d\n", instance1->x,
instance1->y);
retcode = deadline_contentfilter_writer->write(*instance1, handle1);
if (retcode != DDS_RETCODE_OK) {
printf("write error %d\n", retcode);
publisher_shutdown(participant);
return -1;
}
} else if (count == 15) {
printf("Stopping writes to instance1\n");
}
}
retcode = deadline_contentfilter_writer->unregister_instance(*instance0,
handle0);
if (retcode != DDS_RETCODE_OK) {
printf("unregister instance error %d\n", retcode);
}
retcode = deadline_contentfilter_writer->unregister_instance(*instance1,
handle1);
if (retcode != DDS_RETCODE_OK) {
printf("unregister instance error %d\n", retcode);
}
/* Delete data sample */
retcode = deadline_contentfilterTypeSupport::delete_data(instance0);
if (retcode != DDS_RETCODE_OK) {
printf("deadline_contentfilterTypeSupport::delete_data error %d\n",
retcode);
}
retcode = deadline_contentfilterTypeSupport::delete_data(instance1);
if (retcode != DDS_RETCODE_OK) {
printf("deadline_contentfilterTypeSupport::delete_data error %d\n",
retcode);
}
/* End changes for Deadline */
/* Delete all entities */
return publisher_shutdown(participant);
}
#if defined(RTI_WINCE)
int wmain(int argc, wchar_t** argv)
{
int domainId = 0;
int sample_count = 0; /* infinite loop */
if (argc >= 2) {
domainId = _wtoi(argv[1]);
}
if (argc >= 3) {
sample_count = _wtoi(argv[2]);
}
/* Uncomment this to turn on additional logging
NDDSConfigLogger::get_instance()->
set_verbosity_by_category(NDDS_CONFIG_LOG_CATEGORY_API,
NDDS_CONFIG_LOG_VERBOSITY_STATUS_ALL);
*/
return publisher_main(domainId, sample_count);
}
#elif !(defined(RTI_VXWORKS) && !defined(__RTP__)) && !defined(RTI_PSOS)
int main(int argc, char *argv[])
{
int domainId = 0;
int sample_count = 0; /* infinite loop */
if (argc >= 2) {
domainId = atoi(argv[1]);
}
if (argc >= 3) {
sample_count = atoi(argv[2]);
}
/* Uncomment this to turn on additional logging
NDDSConfigLogger::get_instance()->
set_verbosity_by_category(NDDS_CONFIG_LOG_CATEGORY_API,
NDDS_CONFIG_LOG_VERBOSITY_STATUS_ALL);
*/
return publisher_main(domainId, sample_count);
}
#endif
| cxx |
rticonnextdds-examples | data/projects/rticonnextdds-examples/deadline_contentfilter/c/deadline_contentfilter_publisher.c | /*******************************************************************************
(c) 2005-2014 Copyright, Real-Time Innovations, Inc. All rights reserved.
RTI grants Licensee a license to use, modify, compile, and create derivative
works of the Software. Licensee has the right to distribute object form only
for use with RTI products. The Software is provided "as is", with no warranty
of any type, including any warranty for fitness for any purpose. RTI is under
no obligation to maintain or support the Software. RTI shall not be liable for
any incidental or consequential damages arising out of the use or inability to
use the software.
******************************************************************************/
/* deadline_contentfilter_publisher.c
A publication of data of type deadline_contentfilter
This file is derived from code automatically generated by the rtiddsgen
command:
rtiddsgen -language C -example <arch> deadline_contentfilter.idl
Example publication of type deadline_contentfilter automatically generated by
'rtiddsgen'. To test them follow these steps:
(1) Compile this file and the example subscription.
(2) Start the subscription with the command
objs/<arch>/deadline_contentfilter_subscriber <domain_id> <sample_count>
(3) Start the publication with the command
objs/<arch>/deadline_contentfilter_publisher <domain_id> <sample_count>
(4) [Optional] Specify the list of discovery initial peers and
multicast receive addresses via an environment variable or a file
(in the current working directory) called NDDS_DISCOVERY_PEERS.
You can run any number of publishers and subscribers programs, and can
add and remove them dynamically from the domain.
Example:
To run the example application on domain <domain_id>:
On Unix:
objs/<arch>/deadline_contentfilter_publisher <domain_id>
objs/<arch>/deadline_contentfilter_subscriber <domain_id>
On Windows:
objs\<arch>\deadline_contentfilter_publisher <domain_id>
objs\<arch>\deadline_contentfilter_subscriber <domain_id>
modification history
------------ -------
* Create and install listener for offered deadline missed status
* Set deadline QoS
*/
#include <stdio.h>
#include <stdlib.h>
#include "ndds/ndds_c.h"
#include "deadline_contentfilter.h"
#include "deadline_contentfilterSupport.h"
/* Start changes for Deadline */
void deadlineListener_on_offered_deadline_missed(
void* listener_data,
DDS_DataWriter* writer,
const struct DDS_OfferedDeadlineMissedStatus *status)
{
deadline_contentfilter dummy;
DDS_ReturnCode_t retcode = deadline_contentfilterDataWriter_get_key_value(
deadline_contentfilterDataWriter_narrow(writer), &dummy, &status->
last_instance_handle);
if (retcode != DDS_RETCODE_OK) {
printf("get_key_value error %d\n", retcode);
return;
}
printf("Offered deadline missed on instance code = %d\n", dummy.code);
}
/* End changes for Deadline */
/* Delete all entities */
static int publisher_shutdown(
DDS_DomainParticipant *participant)
{
DDS_ReturnCode_t retcode;
int status = 0;
if (participant != NULL) {
retcode = DDS_DomainParticipant_delete_contained_entities(participant);
if (retcode != DDS_RETCODE_OK) {
printf("delete_contained_entities error %d\n", retcode);
status = -1;
}
retcode = DDS_DomainParticipantFactory_delete_participant(
DDS_TheParticipantFactory, participant);
if (retcode != DDS_RETCODE_OK) {
printf("delete_participant error %d\n", retcode);
status = -1;
}
}
/* RTI Connext provides finalize_instance() method on
domain participant factory for people who want to release memory used
by the participant factory. Uncomment the following block of code for
clean destruction of the singleton. */
/*
retcode = DDS_DomainParticipantFactory_finalize_instance();
if (retcode != DDS_RETCODE_OK) {
printf("finalize_instance error %d\n", retcode);
status = -1;
}
*/
return status;
}
static int publisher_main(int domainId, int sample_count)
{
DDS_DomainParticipant *participant = NULL;
DDS_Publisher *publisher = NULL;
DDS_Topic *topic = NULL;
DDS_DataWriter *writer = NULL;
deadline_contentfilterDataWriter *deadline_contentfilter_writer = NULL;
DDS_ReturnCode_t retcode;
const char *type_name = NULL;
int count = 0;
struct DDS_Duration_t deadline_period = {1, 500000000}; /* 1.5sec */
struct DDS_Duration_t send_period = {1,0};
deadline_contentfilter *instance0 = NULL;
deadline_contentfilter *instance1 = NULL;
DDS_InstanceHandle_t handle0 = DDS_HANDLE_NIL;
DDS_InstanceHandle_t handle1 = DDS_HANDLE_NIL;
/*struct DDS_DataWriterQos datawriter_qos = DDS_DataWriterQos_INITIALIZER;*/
/* To customize participant QoS, use
the configuration file USER_QOS_PROFILES.xml */
participant = DDS_DomainParticipantFactory_create_participant(
DDS_TheParticipantFactory, domainId, &DDS_PARTICIPANT_QOS_DEFAULT,
NULL /* listener */, DDS_STATUS_MASK_NONE);
if (participant == NULL) {
printf("create_participant error\n");
publisher_shutdown(participant);
return -1;
}
/* To customize publisher QoS, use
the configuration file USER_QOS_PROFILES.xml */
publisher = DDS_DomainParticipant_create_publisher(
participant, &DDS_PUBLISHER_QOS_DEFAULT, NULL /* listener */,
DDS_STATUS_MASK_NONE);
if (publisher == NULL) {
printf("create_publisher error\n");
publisher_shutdown(participant);
return -1;
}
/* Register type before creating topic */
type_name = deadline_contentfilterTypeSupport_get_type_name();
retcode = deadline_contentfilterTypeSupport_register_type(
participant, type_name);
if (retcode != DDS_RETCODE_OK) {
printf("register_type error %d\n", retcode);
publisher_shutdown(participant);
return -1;
}
/* To customize topic QoS, use
the configuration file USER_QOS_PROFILES.xml */
topic = DDS_DomainParticipant_create_topic(
participant, "Example deadline_contentfilter",
type_name, &DDS_TOPIC_QOS_DEFAULT, NULL /* listener */,
DDS_STATUS_MASK_NONE);
if (topic == NULL) {
printf("create_topic error\n");
publisher_shutdown(participant);
return -1;
}
/* To customize data writer QoS, use
the configuration file USER_QOS_PROFILES.xml */
writer = DDS_Publisher_create_datawriter(
publisher, topic,
&DDS_DATAWRITER_QOS_DEFAULT, NULL /* listener */, DDS_STATUS_MASK_NONE);
if (writer == NULL) {
printf("create_datawriter error\n");
publisher_shutdown(participant);
return -1;
}
/* If you want to change the DataWriter's QoS programmatically rather than
* using the XML file, you will need to add the following lines to your
* code and comment out the create_datawriter call above.
*
* In this case, we set the deadline period to 1.5 seconds to trigger
* a deadline if the DataWriter does not update often enough.
*/
/* Start changes for Deadline */
/* writer_listener.on_offered_deadline_missed =
deadlineListener_on_offered_deadline_missed;
retcode = DDS_Publisher_get_default_datawriter_qos(publisher,
&datawriter_qos);
if (retcode != DDS_RETCODE_OK) {
printf("get_default_datawriter_qos error\n");
return -1;
}
*/ /* Set deadline QoS */
/* datawriter_qos.deadline.period = deadline_period;
writer = DDS_Publisher_create_datawriter(
publisher, topic,
&datawriter_qos, &writer_listener, DDS_OFFERED_DEADLINE_MISSED_STATUS);
if (writer == NULL) {
printf("create_datawriter error\n");
publisher_shutdown(participant);
return -1;
}
*/
/* End changes for Deadline */
deadline_contentfilter_writer =
deadline_contentfilterDataWriter_narrow(writer);
if (deadline_contentfilter_writer == NULL) {
printf("DataWriter narrow error\n");
publisher_shutdown(participant);
return -1;
}
/* Start changes for Deadline */
/* Create data sample for writing */
instance0 =
deadline_contentfilterTypeSupport_create_data_ex(DDS_BOOLEAN_TRUE);
instance1 =
deadline_contentfilterTypeSupport_create_data_ex(DDS_BOOLEAN_TRUE);
if (instance0 == NULL || instance1 == NULL) {
printf("deadlineTypeSupport_create_data error\n");
publisher_shutdown(participant);
return -1;
}
/* Set keys -- we specify 'code' as the key field in the .idl */
instance0->code = 0;
instance1->code = 1;
/* For data type that has key, if the same instance is going to be
written multiple times, initialize the key here
and register the keyed instance prior to writing */
handle0 = deadline_contentfilterDataWriter_register_instance(
deadline_contentfilter_writer, instance0);
handle1 = deadline_contentfilterDataWriter_register_instance(
deadline_contentfilter_writer, instance1);
instance0->x = instance0->y = instance1->x = instance1->y = 0;
/* Main loop */
/* for (count=0; (sample_count == 0) || (count < sample_count); ++count) { */
for (count=0; (count < sample_count); ++count) {
NDDS_Utility_sleep(&send_period);
instance0->x++;
instance0->y++;
instance1->x++;
instance1->y++;
printf("Writing instance0, x = %d, y = %d\n", instance0->x,
instance0->y);
retcode = deadline_contentfilterDataWriter_write(
deadline_contentfilter_writer, instance0, &handle0);
if (retcode != DDS_RETCODE_OK) {
printf("write error %d\n", retcode);
}
if (count < 15) {
printf("Writing instance1, x = %d, y = %d\n", instance1->x,
instance1->y);
retcode = deadline_contentfilterDataWriter_write(
deadline_contentfilter_writer, instance1, &handle1);
if (retcode != DDS_RETCODE_OK) {
printf("write error %d\n", retcode);
}
} else if (count == 15) {
printf("Stopping writes to instance1\n");
}
}
retcode = deadline_contentfilterDataWriter_unregister_instance(
deadline_contentfilter_writer, instance0, &handle0);
if (retcode != DDS_RETCODE_OK) {
printf("unregister instance error %d\n", retcode);
}
retcode = deadline_contentfilterDataWriter_unregister_instance(
deadline_contentfilter_writer, instance1, &handle1);
if (retcode != DDS_RETCODE_OK) {
printf("unregister instance error %d\n", retcode);
}
/* Delete data sample */
retcode = deadline_contentfilterTypeSupport_delete_data_ex(instance0,
DDS_BOOLEAN_TRUE);
if (retcode != DDS_RETCODE_OK) {
printf("deadline_contentfilterTypeSupport_delete_data_ex error %d\n",
retcode);
}
retcode = deadline_contentfilterTypeSupport_delete_data_ex(instance1,
DDS_BOOLEAN_TRUE);
if (retcode != DDS_RETCODE_OK) {
printf("deadline_contentfilterTypeSupport_delete_data_ex error %d\n",
retcode);
}
/* End changes for Deadline */
/* Cleanup and delete delete all entities */
return publisher_shutdown(participant);
}
#if defined(RTI_WINCE)
int wmain(int argc, wchar_t** argv)
{
int domainId = 0;
int sample_count = 0; /* infinite loop */
if (argc >= 2) {
domainId = _wtoi(argv[1]);
}
if (argc >= 3) {
sample_count = _wtoi(argv[2]);
}
/* Uncomment this to turn on additional logging
NDDS_Config_Logger_set_verbosity_by_category(
NDDS_Config_Logger_get_instance(),
NDDS_CONFIG_LOG_CATEGORY_API,
NDDS_CONFIG_LOG_VERBOSITY_STATUS_ALL);
*/
return publisher_main(domainId, sample_count);
}
#elif !(defined(RTI_VXWORKS) && !defined(__RTP__)) && !defined(RTI_PSOS)
int main(int argc, char *argv[])
{
int domainId = 0;
int sample_count = 0; /* infinite loop */
if (argc >= 2) {
domainId = atoi(argv[1]);
}
if (argc >= 3) {
sample_count = atoi(argv[2]);
}
/* Uncomment this to turn on additional logging
NDDS_Config_Logger_set_verbosity_by_category(
NDDS_Config_Logger_get_instance(),
NDDS_CONFIG_LOG_CATEGORY_API,
NDDS_CONFIG_LOG_VERBOSITY_STATUS_ALL);
*/
return publisher_main(domainId, sample_count);
}
#endif
#ifdef RTI_VX653
const unsigned char* __ctype = NULL;
void usrAppInit ()
{
#ifdef USER_APPL_INIT
USER_APPL_INIT; /* for backwards compatibility */
#endif
/* add application specific code here */
taskSpawn("pub", RTI_OSAPI_THREAD_PRIORITY_NORMAL, 0x8, 0x150000,
(FUNCPTR)publisher_main, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
}
#endif
| c |
rticonnextdds-examples | data/projects/rticonnextdds-examples/deadline_contentfilter/c/deadline_contentfilter_subscriber.c | /*******************************************************************************
(c) 2005-2014 Copyright, Real-Time Innovations, Inc. All rights reserved.
RTI grants Licensee a license to use, modify, compile, and create derivative
works of the Software. Licensee has the right to distribute object form only
for use with RTI products. The Software is provided "as is", with no warranty
of any type, including any warranty for fitness for any purpose. RTI is under
no obligation to maintain or support the Software. RTI shall not be liable for
any incidental or consequential damages arising out of the use or inability to
use the software.
******************************************************************************/
/* deadline_contentfilter_subscriber.c
A subscription example
This file is derived from code automatically generated by the rtiddsgen
command:
rtiddsgen -language C -example <arch> deadline_contentfilter.idl
Example subscription of type deadline_contentfilter automatically generated
by 'rtiddsgen'. To test them, follow these steps:
(1) Compile this file and the example publication.
(2) Start the subscription with the command
objs/<arch>/deadline_contentfilter_subscriber <domain_id> <sample_count>
(3) Start the publication with the command
objs/<arch>/deadline_contentfilter_publisher <domain_id> <sample_count>
(4) [Optional] Specify the list of discovery initial peers and
multicast receive addresses via an environment variable or a file
(in the current working directory) called NDDS_DISCOVERY_PEERS.
You can run any number of publishers and subscribers programs, and can
add and remove them dynamically from the domain.
Example:
To run the example application on domain <domain_id>:
On UNIX systems:
objs/<arch>/deadline_contentfilter_publisher <domain_id>
objs/<arch>/deadline_contentfilter_subscriber <domain_id>
On Windows systems:
objs\<arch>\deadline_contentfilter_publisher <domain_id>
objs\<arch>\deadline_contentfilter_subscriber <domain_id>
modification history
------------ -------
* Create clock to show relative timing of events
* Define listener for requested deadline missed status
* Set deadline QoS
* Create content filter that ignores second instance
after 10 seconds
*/
#include <stdio.h>
#include <stdlib.h>
#include "ndds/ndds_c.h"
#include "deadline_contentfilter.h"
#include "deadline_contentfilterSupport.h"
/* Start changes for Deadline */
/* For timekeeping */
#include <time.h>
clock_t init;
void deadline_contentfilterListener_on_requested_deadline_missed(
void* listener_data,
DDS_DataReader* reader,
const struct DDS_RequestedDeadlineMissedStatus *status)
{
double elapsed_ticks;
double elapsed_secs;
deadline_contentfilter dummy;
DDS_ReturnCode_t retcode = deadline_contentfilterDataReader_get_key_value(
deadline_contentfilterDataReader_narrow(reader), &dummy,
&status->last_instance_handle);
if (retcode != DDS_RETCODE_OK) {
printf("get_key_value error %d\n", retcode);
return;
}
elapsed_ticks = clock() - init;
elapsed_secs = elapsed_ticks/CLOCKS_PER_SEC;
printf("Missed deadline @ t=%.2fs on instance code = %d\n",
elapsed_secs, dummy.code);
}
/* End changes for Deadline */
void deadline_contentfilterListener_on_requested_incompatible_qos(
void* listener_data,
DDS_DataReader* reader,
const struct DDS_RequestedIncompatibleQosStatus *status)
{
}
void deadline_contentfilterListener_on_sample_rejected(
void* listener_data,
DDS_DataReader* reader,
const struct DDS_SampleRejectedStatus *status)
{
}
void deadline_contentfilterListener_on_liveliness_changed(
void* listener_data,
DDS_DataReader* reader,
const struct DDS_LivelinessChangedStatus *status)
{
}
void deadline_contentfilterListener_on_sample_lost(
void* listener_data,
DDS_DataReader* reader,
const struct DDS_SampleLostStatus *status)
{
}
void deadline_contentfilterListener_on_subscription_matched(
void* listener_data,
DDS_DataReader* reader,
const struct DDS_SubscriptionMatchedStatus *status)
{
}
void deadline_contentfilterListener_on_data_available(
void* listener_data,
DDS_DataReader* reader)
{
deadline_contentfilterDataReader *deadline_contentfilter_reader = NULL;
struct deadline_contentfilterSeq data_seq = DDS_SEQUENCE_INITIALIZER;
struct DDS_SampleInfoSeq info_seq = DDS_SEQUENCE_INITIALIZER;
DDS_ReturnCode_t retcode;
int i;
double elapsed_ticks;
double elapsed_secs;
deadline_contentfilter_reader =
deadline_contentfilterDataReader_narrow(reader);
if (deadline_contentfilter_reader == NULL) {
printf("DataReader narrow error\n");
return;
}
retcode = deadline_contentfilterDataReader_take(
deadline_contentfilter_reader,
&data_seq, &info_seq, DDS_LENGTH_UNLIMITED,
DDS_ANY_SAMPLE_STATE, DDS_ANY_VIEW_STATE, DDS_ANY_INSTANCE_STATE);
if (retcode == DDS_RETCODE_NO_DATA) {
return;
} else if (retcode != DDS_RETCODE_OK) {
printf("take error %d\n", retcode);
return;
}
for (i = 0; i < deadline_contentfilterSeq_get_length(&data_seq); ++i) {
if (DDS_SampleInfoSeq_get_reference(&info_seq, i)->valid_data) {
deadline_contentfilter* data =
deadline_contentfilterSeq_get_reference(&data_seq, i);
/* Start changes for Deadline */
/* print the time we get each sample. */
elapsed_ticks = clock() - init;
elapsed_secs = elapsed_ticks/CLOCKS_PER_SEC;
printf("@ t=%.2fs, Instance%d: <%d,%d>\n",
elapsed_secs, data->code, data->x, data->y);
/* End changes for Deadline */
}
}
retcode = deadline_contentfilterDataReader_return_loan(
deadline_contentfilter_reader,
&data_seq, &info_seq);
if (retcode != DDS_RETCODE_OK) {
printf("return loan error %d\n", retcode);
}
}
/* Delete all entities */
static int subscriber_shutdown(
DDS_DomainParticipant *participant)
{
DDS_ReturnCode_t retcode;
int status = 0;
if (participant != NULL) {
retcode = DDS_DomainParticipant_delete_contained_entities(participant);
if (retcode != DDS_RETCODE_OK) {
printf("delete_contained_entities error %d\n", retcode);
status = -1;
}
retcode = DDS_DomainParticipantFactory_delete_participant(
DDS_TheParticipantFactory, participant);
if (retcode != DDS_RETCODE_OK) {
printf("delete_participant error %d\n", retcode);
status = -1;
}
}
/* RTI Connext provides the finalize_instance() method on
domain participant factory for users who want to release memory used
by the participant factory. Uncomment the following block of code for
clean destruction of the singleton. */
/*
retcode = DDS_DomainParticipantFactory_finalize_instance();
if (retcode != DDS_RETCODE_OK) {
printf("finalize_instance error %d\n", retcode);
status = -1;
}
*/
return status;
}
static int subscriber_main(int domainId, int sample_count)
{
DDS_DomainParticipant *participant = NULL;
DDS_Subscriber *subscriber = NULL;
DDS_Topic *topic = NULL;
struct DDS_DataReaderListener reader_listener =
DDS_DataReaderListener_INITIALIZER;
DDS_DataReader *reader = NULL;
DDS_ReturnCode_t retcode;
const char *type_name = NULL;
int count = 0;
struct DDS_Duration_t poll_period = {1,0};
struct DDS_StringSeq parameters;
const char* param_list[] = {"2"};
DDS_ContentFilteredTopic *cft = NULL;
/* struct DDS_DataReaderQos datareader_qos = DDS_DataReaderQos_INITIALIZER;
struct DDS_Duration_t deadline_period = {2, 0}; */
/* Changes for Deadline */
/* for timekeeping */
init = clock();
/* To customize participant QoS, use
the configuration file USER_QOS_PROFILES.xml */
participant = DDS_DomainParticipantFactory_create_participant(
DDS_TheParticipantFactory, domainId, &DDS_PARTICIPANT_QOS_DEFAULT,
NULL /* listener */, DDS_STATUS_MASK_NONE);
if (participant == NULL) {
printf("create_participant error\n");
subscriber_shutdown(participant);
return -1;
}
/* To customize subscriber QoS, use
the configuration file USER_QOS_PROFILES.xml */
subscriber = DDS_DomainParticipant_create_subscriber(
participant, &DDS_SUBSCRIBER_QOS_DEFAULT, NULL /* listener */,
DDS_STATUS_MASK_NONE);
if (subscriber == NULL) {
printf("create_subscriber error\n");
subscriber_shutdown(participant);
return -1;
}
/* Register the type before creating the topic */
type_name = deadline_contentfilterTypeSupport_get_type_name();
retcode = deadline_contentfilterTypeSupport_register_type(participant,
type_name);
if (retcode != DDS_RETCODE_OK) {
printf("register_type error %d\n", retcode);
subscriber_shutdown(participant);
return -1;
}
/* To customize topic QoS, use
the configuration file USER_QOS_PROFILES.xml */
topic = DDS_DomainParticipant_create_topic(
participant, "Example deadline_contentfilter",
type_name, &DDS_TOPIC_QOS_DEFAULT, NULL /* listener */,
DDS_STATUS_MASK_NONE);
if (topic == NULL) {
printf("create_topic error\n");
subscriber_shutdown(participant);
return -1;
}
/* Set up a data reader listener */
reader_listener.on_requested_deadline_missed =
deadline_contentfilterListener_on_requested_deadline_missed;
reader_listener.on_requested_incompatible_qos =
deadline_contentfilterListener_on_requested_incompatible_qos;
reader_listener.on_sample_rejected =
deadline_contentfilterListener_on_sample_rejected;
reader_listener.on_liveliness_changed =
deadline_contentfilterListener_on_liveliness_changed;
reader_listener.on_sample_lost =
deadline_contentfilterListener_on_sample_lost;
reader_listener.on_subscription_matched =
deadline_contentfilterListener_on_subscription_matched;
reader_listener.on_data_available =
deadline_contentfilterListener_on_data_available;
/* Start changes for Deadline */
/* Set up content filtered topic to show interaction with deadline */
DDS_StringSeq_initialize(¶meters);
DDS_StringSeq_set_maximum(¶meters, 1);
DDS_StringSeq_from_array(¶meters, param_list, 1);
cft = DDS_DomainParticipant_create_contentfilteredtopic(
participant,
"ContentFilteredTopic", topic, "code < %0", ¶meters);
if (cft == NULL) {
printf("create_contentfilteredtopic error\n");
subscriber_shutdown(participant);
return -1;
}
/* To customize data reader QoS, use
the configuration file USER_QOS_PROFILES.xml */
reader = DDS_Subscriber_create_datareader(
subscriber, DDS_Topic_as_topicdescription(cft),
&DDS_DATAREADER_QOS_DEFAULT, &reader_listener, DDS_STATUS_MASK_ALL);
if (reader == NULL) {
printf("create_datareader error\n");
subscriber_shutdown(participant);
return -1;
}
/* If you want to change the DataReader's QoS programmatically rather than
* using the XML file, you will need to add the following lines to your
* code and comment out the create_datareader call above.
*
* In this case, we set the deadline period to 2 seconds to trigger
* a deadline if the DataWriter does not update often enough, or if
* the content-filter filters out data so there is no data available
* with 2 seconds.
*/
/*
retcode = DDS_Subscriber_get_default_datareader_qos(subscriber,
&datareader_qos);
if (retcode != DDS_RETCODE_OK) {
printf("get_default_datareader_qos error\n");
return -1;
}
*/ /* Set deadline QoS */
/* datareader_qos.deadline.period = deadline_period;
reader = DDS_Subscriber_create_datareader(
subscriber, DDS_ContentFilteredTopic_as_topicdescription(cft),
&datareader_qos, &reader_listener, DDS_STATUS_MASK_ALL);
if (reader == NULL) {
printf("create_datareader error\n");
subscriber_shutdown(participant);
return -1;
}
*/
/* Main loop */
for (count=0; (sample_count == 0) || (count < sample_count); ++count) {
if(count == 10) {
printf("Starting to filter out instance1 at time %d\n", count);
DDS_String_free(DDS_StringSeq_get(¶meters, 0));
*DDS_StringSeq_get_reference(¶meters, 0) = DDS_String_dup("1");
DDS_ContentFilteredTopic_set_expression_parameters(cft,
¶meters);
}
NDDS_Utility_sleep(&poll_period);
}
/* End changes for Deadline */
/* Cleanup and delete all entities */
return subscriber_shutdown(participant);
}
#if defined(RTI_WINCE)
int wmain(int argc, wchar_t** argv)
{
int domainId = 0;
int sample_count = 0; /* infinite loop */
if (argc >= 2) {
domainId = _wtoi(argv[1]);
}
if (argc >= 3) {
sample_count = _wtoi(argv[2]);
}
/* Uncomment this to turn on additional logging
NDDS_Config_Logger_set_verbosity_by_category(
NDDS_Config_Logger_get_instance(),
NDDS_CONFIG_LOG_CATEGORY_API,
NDDS_CONFIG_LOG_VERBOSITY_STATUS_ALL);
*/
return subscriber_main(domainId, sample_count);
}
#elif !(defined(RTI_VXWORKS) && !defined(__RTP__)) && !defined(RTI_PSOS)
int main(int argc, char *argv[])
{
int domainId = 0;
int sample_count = 0; /* infinite loop */
if (argc >= 2) {
domainId = atoi(argv[1]);
}
if (argc >= 3) {
sample_count = atoi(argv[2]);
}
/* Uncomment this to turn on additional logging
NDDS_Config_Logger_set_verbosity_by_category(
NDDS_Config_Logger_get_instance(),
NDDS_CONFIG_LOG_CATEGORY_API,
NDDS_CONFIG_LOG_VERBOSITY_STATUS_ALL);
*/
return subscriber_main(domainId, sample_count);
}
#endif
#ifdef RTI_VX653
const unsigned char* __ctype = NULL;
void usrAppInit ()
{
#ifdef USER_APPL_INIT
USER_APPL_INIT; /* for backwards compatibility */
#endif
/* add application specific code here */
taskSpawn("sub", RTI_OSAPI_THREAD_PRIORITY_NORMAL, 0x8, 0x150000,
(FUNCPTR)subscriber_main, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
}
#endif
| c |
rticonnextdds-examples | data/projects/rticonnextdds-examples/deadline_contentfilter/c++03/deadline_contentfilter_subscriber.cxx | /*******************************************************************************
(c) 2005-2015 Copyright, Real-Time Innovations, Inc. All rights reserved.
RTI grants Licensee a license to use, modify, compile, and create derivative
works of the Software. Licensee has the right to distribute object form only
for use with RTI products. The Software is provided "as is", with no warranty
of any type, including any warranty for fitness for any purpose. RTI is under
no obligation to maintain or support the Software. RTI shall not be liable for
any incidental or consequential damages arising out of the use or inability to
use the software.
******************************************************************************/
#include <algorithm>
#include <cstdlib>
#include <iostream>
#include <ctime>
#include <dds/dds.hpp>
#include <rti/core/ListenerBinder.hpp>
#include "deadline_contentfilter.hpp"
using namespace dds::core;
using namespace dds::core::policy;
using namespace dds::core::status;
using namespace dds::domain;
using namespace dds::topic;
using namespace dds::sub;
using namespace dds::sub::qos;
clock_t init_time;
class deadline_contentfilterReaderListener :
public NoOpDataReaderListener<deadline_contentfilter> {
public:
void on_data_available(DataReader<deadline_contentfilter>& reader)
{
// Take all samples
LoanedSamples<deadline_contentfilter> samples = reader.take();
for (LoanedSamples<deadline_contentfilter>::iterator sample_it =
samples.begin();
sample_it != samples.end();
sample_it++) {
if (sample_it->info().valid()){
// Print the time we get each sample.
double elapsed_ticks = clock() - init_time;
double elapsed_secs = elapsed_ticks / CLOCKS_PER_SEC;
const deadline_contentfilter& data = sample_it->data();
std::cout << "@ t=" << elapsed_secs << "s, Instance"
<< data.code() << ": <" << data.x()
<< "," << data.y() << ">" << std::endl;
}
}
}
void on_requested_deadline_missed(
DataReader<deadline_contentfilter>& reader,
const RequestedDeadlineMissedStatus& status)
{
double elapsed_ticks = clock() - init_time;
double elapsed_secs = elapsed_ticks / CLOCKS_PER_SEC;
// Creates a temporary object in order to find out which instance
// missed its deadline period. The 'key_value' call only fills in the
// values of the key fields inside the object.
deadline_contentfilter affected_sample;
reader.key_value(affected_sample, status.last_instance_handle());
// Print out which instance missed its deadline.
std::cout << "Missed deadline @ t=" << elapsed_secs
<< "s on instance code = " << affected_sample.code()
<< std::endl;
}
};
void subscriber_main(int domain_id, int sample_count)
{
// For timekeeping
init_time = clock();
// Create a DomainParticipant with default Qos
DomainParticipant participant(domain_id);
// Create a Topic -- and automatically register the type
Topic<deadline_contentfilter> topic(
participant, "Example deadline_contentfilter");
// Set up a Content Filtered Topic to show interaction with deadline.
std::vector<std::string> parameters(1);
parameters[0] = "2";
ContentFilteredTopic<deadline_contentfilter> cft_topic(
topic,
"ContentFilteredTopic",
Filter("code < %0", parameters));
// Retrieve the default DataReader's QoS, from USER_QOS_PROFILES.xml
DataReaderQos reader_qos = QosProvider::Default().datareader_qos();
// If you want to change the DataReader's QoS programmatically rather than
// using the XML file, uncomment the following lines.
//
// In this case, we set the deadline period to 2 seconds to trigger
// a deadline if the DataWriter does not update often enough, or if
// the content-filter filters out data so there is no data available
// with 2 seconds.
// reader_qos << Deadline(Duration(2));
// Create a DataReader (Subscriber created in-line)
DataReader<deadline_contentfilter> reader(
Subscriber(participant), cft_topic, reader_qos);
// Create a data reader listener using ListenerBinder, a RAII that
// will take care of setting it to NULL on destruction.
rti::core::ListenerBinder<DataReader<deadline_contentfilter> > listener =
rti::core::bind_and_manage_listener(
reader,
new deadline_contentfilterReaderListener,
StatusMask::all());
std::cout << std::fixed;
for (short count=0; (sample_count == 0) || (count < sample_count); ++count){
// After 10 seconds, change filter to accept only instance 0.
if (count == 10) {
std::cout << "Starting to filter out instance1" << std::endl;
parameters[0] = "1";
cft_topic.filter_parameters(parameters.begin(), parameters.end());
}
rti::util::sleep(Duration(1));
}
}
int main(int argc, char *argv[])
{
int domain_id = 0;
int sample_count = 0; // Infinite loop
if (argc >= 2) {
domain_id = atoi(argv[1]);
}
if (argc >= 3) {
sample_count = atoi(argv[2]);
}
// To turn on additional logging, include <rti/config/Logger.hpp> and
// uncomment the following line:
// rti::config::Logger::instance().verbosity(rti::config::Verbosity::STATUS_ALL);
try {
subscriber_main(domain_id, sample_count);
} catch (const std::exception& ex) {
// This will catch DDS exceptions
std::cerr << "Exception in subscriber_main: " << ex.what() << std::endl;
return -1;
}
return 0;
}
| cxx |
rticonnextdds-examples | data/projects/rticonnextdds-examples/deadline_contentfilter/c++03/deadline_contentfilter_publisher.cxx | /*******************************************************************************
(c) 2005-2015 Copyright, Real-Time Innovations, Inc. All rights reserved.
RTI grants Licensee a license to use, modify, compile, and create derivative
works of the Software. Licensee has the right to distribute object form only
for use with RTI products. The Software is provided "as is", with no warranty
of any type, including any warranty for fitness for any purpose. RTI is under
no obligation to maintain or support the Software. RTI shall not be liable for
any incidental or consequential damages arising out of the use or inability to
use the software.
******************************************************************************/
#include <iostream>
#include <dds/dds.hpp>
#include <rti/core/ListenerBinder.hpp>
#include "deadline_contentfilter.hpp"
using namespace dds::core;
using namespace dds::core::policy;
using namespace dds::core::status;
using namespace dds::domain;
using namespace dds::topic;
using namespace dds::pub;
using namespace dds::pub::qos;
class DeadlineWriterListener :
public NoOpDataWriterListener<deadline_contentfilter> {
public:
void on_offered_deadline_missed(
DataWriter<deadline_contentfilter> &writer,
const OfferedDeadlineMissedStatus &status)
{
// Creates a temporary object in order to find out which instance
// missed its deadline period. The 'key_value' call only fills in the
// values of the key fields inside the object.
deadline_contentfilter affected_sample;
writer.key_value(affected_sample, status.last_instance_handle());
// Print out which instance missed its deadline.
std::cout << "Offered deadline missed on instance code = "
<< affected_sample.code() << std::endl;
}
};
void publisher_main(int domain_id, int sample_count)
{
// Create a DomainParticipant with default Qos
DomainParticipant participant (domain_id);
// Create a Topic -- and automatically register the type
Topic<deadline_contentfilter> topic(
participant, "Example deadline_contentfilter");
// Retrieve the default DataWriter QoS, from USER_QOS_PROFILES.xml
DataWriterQos writer_qos = QosProvider::Default().datawriter_qos();
// If you want to change the DataWriter's QoS programmatically rather than
// using the XML file, uncomment the following lines.
// writer_qos << Deadline(Duration::from_millisecs(1500));
// Create a DataWriter (Publisher created in-line)
DataWriter<deadline_contentfilter> writer(Publisher(participant), topic);
// Associate a listener to the DataWriter using ListenerBinder, a RAII that
// will take care of setting it to NULL on destruction.
rti::core::ListenerBinder<DataWriter<deadline_contentfilter> > listener =
rti::core::bind_and_manage_listener(
writer,
new DeadlineWriterListener,
StatusMask::all());
// Create two instances for writing and register them in order to be able
// to recover them from the instance handle in the listener.
deadline_contentfilter sample0(0, 0, 0);
InstanceHandle handle0 = writer.register_instance(sample0);
deadline_contentfilter sample1(1, 0, 0);
InstanceHandle handle1 = writer.register_instance(sample1);
// Main loop.
for (int count = 0; count < sample_count || sample_count == 0; count++) {
rti::util::sleep(Duration(1));
// Update non-key fields.
sample0.x(count);
sample0.y(count);
sample1.x(count);
sample1.y(count);
std::cout << "Writing instance0, x = " << sample0.x() << ", y = "
<< sample0.y() << std::endl;
writer.write(sample0, handle0);
if (count < 15) {
std::cout << "Writing instance1, x = " << sample1.x() << ", y = "
<< sample1.y() << std::endl;
writer.write(sample1, handle1);
} else if (count == 15) {
std::cout << "Stopping writes to instance1" << std::endl;
}
}
// Unregister the instances.
writer.unregister_instance(handle0);
writer.unregister_instance(handle1);
}
int main(int argc, char *argv[])
{
int domain_id = 0;
int sample_count = 0; // Infinite loop
if (argc >= 2) {
domain_id = atoi(argv[1]);
}
if (argc >= 3) {
sample_count = atoi(argv[2]);
}
// To turn on additional logging, include <rti/config/Logger.hpp> and
// uncomment the following line:
// rti::config::Logger::instance().verbosity(rti::config::Verbosity::STATUS_ALL);
try {
publisher_main(domain_id, sample_count);
} catch (const std::exception& ex) {
// This will catch DDS exceptions
std::cerr << "Exception in publisher_main: " << ex.what() << std::endl;
return -1;
}
return 0;
}
| cxx |
rticonnextdds-examples | data/projects/rticonnextdds-examples/keyed_data/c++/keys_publisher.cxx | /*******************************************************************************
(c) 2005-2014 Copyright, Real-Time Innovations, Inc. All rights reserved.
RTI grants Licensee a license to use, modify, compile, and create derivative
works of the Software. Licensee has the right to distribute object form only
for use with RTI products. The Software is provided "as is", with no warranty
of any type, including any warranty for fitness for any purpose. RTI is under
no obligation to maintain or support the Software. RTI shall not be liable for
any incidental or consequential damages arising out of the use or inability to
use the software.
******************************************************************************/
/* keys_publisher.cxx
A publication of data of type keys
This file is derived from code automatically generated by the rtiddsgen
command:
rtiddsgen -language C++ -example <arch> keys.idl
Example publication of type keys automatically generated by
'rtiddsgen'. To test them follow these steps:
(1) Compile this file and the example subscription.
(2) Start the subscription with the command
objs/<arch>/keys_subscriber <domain_id> <sample_count>
(3) Start the publication with the command
objs/<arch>/keys_publisher <domain_id> <sample_count>
(4) [Optional] Specify the list of discovery initial peers and
multicast receive addresses via an environment variable or a file
(in the current working directory) called NDDS_DISCOVERY_PEERS.
You can run any number of publishers and subscribers programs, and can
add and remove them dynamically from the domain.
Example:
To run the example application on domain <domain_id>:
On Unix:
objs/<arch>/keys_publisher <domain_id> o
objs/<arch>/keys_subscriber <domain_id>
On Windows:
objs\<arch>\keys_publisher <domain_id>
objs\<arch>\keys_subscriber <domain_id>
modification history
------------ -------
*/
#include <stdio.h>
#include <stdlib.h>
#ifdef RTI_VX653
#include <vThreadsData.h>
#endif
#include "keys.h"
#include "keysSupport.h"
#include "ndds/ndds_cpp.h"
/* Delete all entities */
static int publisher_shutdown(
DDSDomainParticipant *participant)
{
DDS_ReturnCode_t retcode;
int status = 0;
if (participant != NULL) {
retcode = participant->delete_contained_entities();
if (retcode != DDS_RETCODE_OK) {
printf("delete_contained_entities error %d\n", retcode);
status = -1;
}
retcode = DDSTheParticipantFactory->delete_participant(participant);
if (retcode != DDS_RETCODE_OK) {
printf("delete_participant error %d\n", retcode);
status = -1;
}
}
/* RTI Connext provides finalize_instance() method on
domain participant factory for people who want to release memory used
by the participant factory. Uncomment the following block of code for
clean destruction of the singleton. */
/*
retcode = DDSDomainParticipantFactory::finalize_instance();
if (retcode != DDS_RETCODE_OK) {
printf("finalize_instance error %d\n", retcode);
status = -1;
}
*/
return status;
}
extern "C" int publisher_main(int domainId, int sample_count)
{
DDSDomainParticipant *participant = NULL;
DDSPublisher *publisher = NULL;
DDSTopic *topic = NULL;
DDSDataWriter *writer = NULL;
keysDataWriter * keys_writer = NULL;
/* Creates three instances */
keys* instance[3] = {NULL, NULL, NULL};
/* Creates three handles for managing the registrations */
DDS_InstanceHandle_t handle[3] = {DDS_HANDLE_NIL, DDS_HANDLE_NIL, DDS_HANDLE_NIL};
/* We only will send data over the instances marked as active */
int active[3] = {1, 0, 0};
DDS_ReturnCode_t retcode;
const char *type_name = NULL;
int count = 0;
DDS_Duration_t send_period = {1,0};
/* To customize participant QoS, use
the configuration file USER_QOS_PROFILES.xml */
participant = DDSTheParticipantFactory->create_participant(
domainId, DDS_PARTICIPANT_QOS_DEFAULT,
NULL /* listener */, DDS_STATUS_MASK_NONE);
if (participant == NULL) {
printf("create_participant error\n");
publisher_shutdown(participant);
return -1;
}
/* To customize publisher QoS, use
the configuration file USER_QOS_PROFILES.xml */
publisher = participant->create_publisher(
DDS_PUBLISHER_QOS_DEFAULT, NULL /* listener */, DDS_STATUS_MASK_NONE);
if (publisher == NULL) {
printf("create_publisher error\n");
publisher_shutdown(participant);
return -1;
}
/* Register type before creating topic */
type_name = keysTypeSupport::get_type_name();
retcode = keysTypeSupport::register_type(
participant, type_name);
if (retcode != DDS_RETCODE_OK) {
printf("register_type error %d\n", retcode);
publisher_shutdown(participant);
return -1;
}
/* To customize topic QoS, use
the configuration file USER_QOS_PROFILES.xml */
topic = participant->create_topic(
"Example keys",
type_name, DDS_TOPIC_QOS_DEFAULT, NULL /* listener */,
DDS_STATUS_MASK_NONE);
if (topic == NULL) {
printf("create_topic error\n");
publisher_shutdown(participant);
return -1;
}
/* To customize data writer QoS, use
the configuration file USER_QOS_PROFILES.xml */
writer = publisher->create_datawriter(
topic, DDS_DATAWRITER_QOS_DEFAULT, NULL /* listener */,
DDS_STATUS_MASK_NONE);
if (writer == NULL) {
printf("create_datawriter error\n");
publisher_shutdown(participant);
return -1;
}
/* If you want to set the writer_data_lifecycle QoS settings
* programmatically rather than using the XML, you will need to add
* the following lines to your code and comment out the create_datawriter
* call above.
*/
/*
DDS_DataWriterQos datawriter_qos;
retcode = publisher->get_default_datawriter_qos(datawriter_qos);
if (retcode != DDS_RETCODE_OK) {
printf("get_default_datawriter_qos error\n");
return -1;
}
datawriter_qos.writer_data_lifecycle.autodispose_unregistered_instances = DDS_BOOLEAN_FALSE;
writer = publisher->create_datawriter(
topic, datawriter_qos, NULL,
DDS_STATUS_MASK_NONE);
if (writer == NULL) {
printf("create_datawriter error\n");
publisher_shutdown(participant);
return -1;
}
*/
keys_writer = keysDataWriter::narrow(writer);
if (keys_writer == NULL) {
printf("DataWriter narrow error\n");
publisher_shutdown(participant);
return -1;
}
/* Create data samples for writing */
instance[0] = keysTypeSupport::create_data();
instance[1] = keysTypeSupport::create_data();
instance[2] = keysTypeSupport::create_data();
if (instance[0] == NULL || instance[1] == NULL || instance[2] == NULL) {
printf("keysTypeSupport::create_data error\n");
publisher_shutdown(participant);
return -1;
}
/* RTI Connext could examine the key fields each time it needs to determine
* which data-instance is being modified.
* However, for performance and semantic reasons, it is better
* for your application to declare all the data-instances it intends to
* modify prior to actually writing any samples. This is known as registration.
*/
/* In order to register the instances, we must set their associated keys first */
instance[0]->code = 0;
instance[1]->code = 1;
instance[2]->code = 2;
/* The keys must have been set before making this call */
printf("Registering instance %d\n", instance[0]->code);
handle[0] = keys_writer->register_instance(*instance[0]);
/* Modify the data to be sent here */
instance[0]->x = 1000;
instance[1]->x = 2000;
instance[2]->x = 3000;
/* Main loop */
for (count=0; (sample_count == 0) || (count < sample_count); ++count) {
NDDSUtility::sleep(send_period);
switch (count) {
case 5: { /* Start sending the second and third instances */
printf("----Registering instance %d\n", instance[1]->code);
printf("----Registering instance %d\n", instance[2]->code);
handle[1] = keys_writer->register_instance(*instance[1]);
handle[2] = keys_writer->register_instance(*instance[2]);
active[1] = 1;
active[2] = 1;
} break;
case 10: { /* Unregister the second instance */
printf("----Unregistering instance %d\n", instance[1]->code);
retcode = keys_writer->unregister_instance(*instance[1], handle[1]);
if (retcode != DDS_RETCODE_OK) {
printf("unregister instance error %d\n", retcode);
return -1;
}
active[1] = 0;
} break;
case 15: { /* Dispose the third instance */
printf("----Disposing \\instance %d\n", instance[2]->code);
retcode = keys_writer->dispose(*instance[2], handle[2]);
if (retcode != DDS_RETCODE_OK) {
printf("dispose instance error %d\n", retcode);
return -1;
}
active[2] = 0;
} break;
}
/* Modify the data to be sent here */
instance[0]->y = count;
instance[1]->y = count;
instance[2]->y = count;
for (int i = 0; i < 3; ++i) {
if (active[i]) {
printf("Writing instance %d, x: %d, y: %d\n",
instance[i]->code, instance[i]->x, instance[i]->y);
retcode = keys_writer->write(*instance[i], handle[i]);
if (retcode != DDS_RETCODE_OK) {
printf("write error %d\n", retcode);
return -1;
}
}
}
}
/* Delete data samples */
for (int i = 0; i < 3; ++i) {
retcode = keysTypeSupport::delete_data(instance[i]);
if (retcode != DDS_RETCODE_OK) {
printf("keysTypeSupport::delete_data error %d\n", retcode);
}
}
/* Delete all entities */
return publisher_shutdown(participant);
}
#if defined(RTI_WINCE)
int wmain(int argc, wchar_t** argv)
{
int domainId = 0;
int sample_count = 0; /* infinite loop */
if (argc >= 2) {
domainId = _wtoi(argv[1]);
}
if (argc >= 3) {
sample_count = _wtoi(argv[2]);
}
/* Uncomment this to turn on additional logging
NDDSConfigLogger::get_instance()->
set_verbosity_by_category(NDDS_CONFIG_LOG_CATEGORY_API,
NDDS_CONFIG_LOG_VERBOSITY_STATUS_ALL);
*/
return publisher_main(domainId, sample_count);
}
#elif !(defined(RTI_VXWORKS) && !defined(__RTP__)) && !defined(RTI_PSOS)
int main(int argc, char *argv[])
{
int domainId = 0;
int sample_count = 0; /* infinite loop */
if (argc >= 2) {
domainId = atoi(argv[1]);
}
if (argc >= 3) {
sample_count = atoi(argv[2]);
}
/* Uncomment this to turn on additional logging
NDDSConfigLogger::get_instance()->
set_verbosity_by_category(NDDS_CONFIG_LOG_CATEGORY_API,
NDDS_CONFIG_LOG_VERBOSITY_STATUS_ALL);
*/
return publisher_main(domainId, sample_count);
}
#endif
#ifdef RTI_VX653
const unsigned char* __ctype = *(__ctypePtrGet());
extern "C" void usrAppInit ()
{
#ifdef USER_APPL_INIT
USER_APPL_INIT; /* for backwards compatibility */
#endif
/* add application specific code here */
taskSpawn("pub", RTI_OSAPI_THREAD_PRIORITY_NORMAL, 0x8, 0x150000, (FUNCPTR)publisher_main, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
}
#endif
| cxx |
rticonnextdds-examples | data/projects/rticonnextdds-examples/keyed_data/c++/keys_subscriber.cxx | /*******************************************************************************
(c) 2005-2014 Copyright, Real-Time Innovations, Inc. All rights reserved.
RTI grants Licensee a license to use, modify, compile, and create derivative
works of the Software. Licensee has the right to distribute object form only
for use with RTI products. The Software is provided "as is", with no warranty
of any type, including any warranty for fitness for any purpose. RTI is under
no obligation to maintain or support the Software. RTI shall not be liable for
any incidental or consequential damages arising out of the use or inability to
use the software.
******************************************************************************/
/* keys_subscriber.cxx
A subscription example
This file is derived from code automatically generated by the rtiddsgen
command:
rtiddsgen -language C++ -example <arch> keys.idl
Example subscription of type keys automatically generated by
'rtiddsgen'. To test them follow these steps:
(1) Compile this file and the example publication.
(2) Start the subscription with the command
objs/<arch>/keys_subscriber <domain_id> <sample_count>
(3) Start the publication with the command
objs/<arch>/keys_publisher <domain_id> <sample_count>
(4) [Optional] Specify the list of discovery initial peers and
multicast receive addresses via an environment variable or a file
(in the current working directory) called NDDS_DISCOVERY_PEERS.
You can run any number of publishers and subscribers programs, and can
add and remove them dynamically from the domain.
Example:
To run the example application on domain <domain_id>:
On Unix:
objs/<arch>/keys_publisher <domain_id>
objs/<arch>/keys_subscriber <domain_id>
On Windows:
objs\<arch>\keys_publisher <domain_id>
objs\<arch>\keys_subscriber <domain_id>
modification history
------------ -------
*/
#include <stdio.h>
#include <stdlib.h>
#ifdef RTI_VX653
#include <vThreadsData.h>
#endif
#include "keys.h"
#include "keysSupport.h"
#include "ndds/ndds_cpp.h"
class keysListener : public DDSDataReaderListener {
public:
virtual void on_requested_deadline_missed(
DDSDataReader* /*reader*/,
const DDS_RequestedDeadlineMissedStatus& /*status*/) {}
virtual void on_requested_incompatible_qos(
DDSDataReader* /*reader*/,
const DDS_RequestedIncompatibleQosStatus& /*status*/) {}
virtual void on_sample_rejected(
DDSDataReader* /*reader*/,
const DDS_SampleRejectedStatus& /*status*/) {}
virtual void on_liveliness_changed(
DDSDataReader* /*reader*/,
const DDS_LivelinessChangedStatus& /*status*/) {}
virtual void on_sample_lost(
DDSDataReader* /*reader*/,
const DDS_SampleLostStatus& /*status*/) {}
virtual void on_subscription_matched(
DDSDataReader* /*reader*/,
const DDS_SubscriptionMatchedStatus& /*status*/) {}
virtual void on_data_available(DDSDataReader* reader);
};
void keysListener::on_data_available(DDSDataReader* reader)
{
keysDataReader *keys_reader = NULL;
keysSeq data_seq;
DDS_SampleInfoSeq info_seq;
DDS_ReturnCode_t retcode;
int i;
keys_reader = keysDataReader::narrow(reader);
if (keys_reader == NULL) {
printf("DataReader narrow error\n");
return;
}
retcode = keys_reader->take(
data_seq, info_seq, DDS_LENGTH_UNLIMITED,
DDS_ANY_SAMPLE_STATE, DDS_ANY_VIEW_STATE, DDS_ANY_INSTANCE_STATE);
if (retcode == DDS_RETCODE_NO_DATA) {
return;
} else if (retcode != DDS_RETCODE_OK) {
printf("take error %d\n", retcode);
return;
}
for (i = 0; i < data_seq.length(); ++i) {
/* Start changes for Keyed_Data */
/* We first check if the sample includes valid data */
if (info_seq[i].valid_data) {
if (info_seq[i].view_state == DDS_NEW_VIEW_STATE) {
printf("Found new instance; code = %d\n", data_seq[i].code);
}
printf("Instance %d: x: %d, y: %d\n", data_seq[i].code,
data_seq[i].x, data_seq[i].y);
} else {
/* Since there is not valid data, it may include metadata */
keys dummy;
retcode = keys_reader->get_key_value(dummy, info_seq[i].instance_handle);
if (retcode != DDS_RETCODE_OK) {
printf("get_key_value error %d\n", retcode);
continue;
}
/* Here we print a message if the instance state is ALIVE_NO_WRITERS or ALIVE_DISPOSED */
if (info_seq[i].instance_state == DDS_NOT_ALIVE_NO_WRITERS_INSTANCE_STATE) {
printf("Instance %d has no writers\n", dummy.code);
} else if (info_seq[i].instance_state == DDS_NOT_ALIVE_DISPOSED_INSTANCE_STATE) {
printf("Instance %d disposed\n", dummy.code);
}
}
/* End changes for Keyed_Data */
}
retcode = keys_reader->return_loan(data_seq, info_seq);
if (retcode != DDS_RETCODE_OK) {
printf("return loan error %d\n", retcode);
}
}
/* Delete all entities */
static int subscriber_shutdown(
DDSDomainParticipant *participant)
{
DDS_ReturnCode_t retcode;
int status = 0;
if (participant != NULL) {
retcode = participant->delete_contained_entities();
if (retcode != DDS_RETCODE_OK) {
printf("delete_contained_entities error %d\n", retcode);
status = -1;
}
retcode = DDSTheParticipantFactory->delete_participant(participant);
if (retcode != DDS_RETCODE_OK) {
printf("delete_participant error %d\n", retcode);
status = -1;
}
}
/* RTI Connext provides the finalize_instance() method on
domain participant factory for people who want to release memory used
by the participant factory. Uncomment the following block of code for
clean destruction of the singleton. */
/*
retcode = DDSDomainParticipantFactory::finalize_instance();
if (retcode != DDS_RETCODE_OK) {
printf("finalize_instance error %d\n", retcode);
status = -1;
}
*/
return status;
}
extern "C" int subscriber_main(int domainId, int sample_count)
{
DDSDomainParticipant *participant = NULL;
DDSSubscriber *subscriber = NULL;
DDSTopic *topic = NULL;
keysListener *reader_listener = NULL;
DDSDataReader *reader = NULL;
DDS_ReturnCode_t retcode;
const char *type_name = NULL;
int count = 0;
DDS_Duration_t receive_period = {1,0};
int status = 0;
/* To customize the participant QoS, use
the configuration file USER_QOS_PROFILES.xml */
participant = DDSTheParticipantFactory->create_participant(
domainId, DDS_PARTICIPANT_QOS_DEFAULT,
NULL /* listener */, DDS_STATUS_MASK_NONE);
if (participant == NULL) {
printf("create_participant error\n");
subscriber_shutdown(participant);
return -1;
}
/* To customize the subscriber QoS, use
the configuration file USER_QOS_PROFILES.xml */
subscriber = participant->create_subscriber(
DDS_SUBSCRIBER_QOS_DEFAULT, NULL /* listener */, DDS_STATUS_MASK_NONE);
if (subscriber == NULL) {
printf("create_subscriber error\n");
subscriber_shutdown(participant);
return -1;
}
/* Register the type before creating the topic */
type_name = keysTypeSupport::get_type_name();
retcode = keysTypeSupport::register_type(
participant, type_name);
if (retcode != DDS_RETCODE_OK) {
printf("register_type error %d\n", retcode);
subscriber_shutdown(participant);
return -1;
}
/* To customize the topic QoS, use
the configuration file USER_QOS_PROFILES.xml */
topic = participant->create_topic(
"Example keys",
type_name, DDS_TOPIC_QOS_DEFAULT, NULL /* listener */,
DDS_STATUS_MASK_NONE);
if (topic == NULL) {
printf("create_topic error\n");
subscriber_shutdown(participant);
return -1;
}
/* Create a data reader listener */
reader_listener = new keysListener();
/* To customize the data reader QoS, use
the configuration file USER_QOS_PROFILES.xml */
reader = subscriber->create_datareader(
topic, DDS_DATAREADER_QOS_DEFAULT, reader_listener,
DDS_STATUS_MASK_ALL);
if (reader == NULL) {
printf("create_datareader error\n");
subscriber_shutdown(participant);
delete reader_listener;
return -1;
}
/* Main loop */
for (count=0; (sample_count == 0) || (count < sample_count); ++count) {
//printf("keys subscriber sleeping for %d sec...\n",receive_period.sec);
NDDSUtility::sleep(receive_period);
}
/* Delete all entities */
status = subscriber_shutdown(participant);
delete reader_listener;
return status;
}
#if defined(RTI_WINCE)
int wmain(int argc, wchar_t** argv)
{
int domainId = 0;
int sample_count = 0; /* infinite loop */
if (argc >= 2) {
domainId = _wtoi(argv[1]);
}
if (argc >= 3) {
sample_count = _wtoi(argv[2]);
}
/* Uncomment this to turn on additional logging
NDDSConfigLogger::get_instance()->
set_verbosity_by_category(NDDS_CONFIG_LOG_CATEGORY_API,
NDDS_CONFIG_LOG_VERBOSITY_STATUS_ALL);
*/
return subscriber_main(domainId, sample_count);
}
#elif !(defined(RTI_VXWORKS) && !defined(__RTP__)) && !defined(RTI_PSOS)
int main(int argc, char *argv[])
{
int domainId = 0;
int sample_count = 0; /* infinite loop */
if (argc >= 2) {
domainId = atoi(argv[1]);
}
if (argc >= 3) {
sample_count = atoi(argv[2]);
}
/* Uncomment this to turn on additional logging
NDDSConfigLogger::get_instance()->
set_verbosity_by_category(NDDS_CONFIG_LOG_CATEGORY_API,
NDDS_CONFIG_LOG_VERBOSITY_STATUS_ALL);
*/
return subscriber_main(domainId, sample_count);
}
#endif
#ifdef RTI_VX653
const unsigned char* __ctype = *(__ctypePtrGet());
extern "C" void usrAppInit ()
{
#ifdef USER_APPL_INIT
USER_APPL_INIT; /* for backwards compatibility */
#endif
/* add application specific code here */
taskSpawn("sub", RTI_OSAPI_THREAD_PRIORITY_NORMAL, 0x8, 0x150000, (FUNCPTR)subscriber_main, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
}
#endif
| cxx |
rticonnextdds-examples | data/projects/rticonnextdds-examples/keyed_data/c/keys_publisher.c | /*******************************************************************************
(c) 2005-2014 Copyright, Real-Time Innovations, Inc. All rights reserved.
RTI grants Licensee a license to use, modify, compile, and create derivative
works of the Software. Licensee has the right to distribute object form only
for use with RTI products. The Software is provided "as is", with no warranty
of any type, including any warranty for fitness for any purpose. RTI is under
no obligation to maintain or support the Software. RTI shall not be liable for
any incidental or consequential damages arising out of the use or inability to
use the software.
******************************************************************************/
/* keys_publisher.c
A publication of data of type keys
This file is derived from code automatically generated by the rtiddsgen
command:
rtiddsgen -language C -example <arch> keys.idl
Example publication of type keys automatically generated by
'rtiddsgen'. To test them follow these steps:
(1) Compile this file and the example subscription.
(2) Start the subscription with the command
objs/<arch>/keys_subscriber <domain_id> <sample_count>
(3) Start the publication with the command
objs/<arch>/keys_publisher <domain_id> <sample_count>
(4) [Optional] Specify the list of discovery initial peers and
multicast receive addresses via an environment variable or a file
(in the current working directory) called NDDS_DISCOVERY_PEERS.
You can run any number of publishers and subscribers programs, and can
add and remove them dynamically from the domain.
Example:
To run the example application on domain <domain_id>:
On Unix:
objs/<arch>/keys_publisher <domain_id>
objs/<arch>/keys_subscriber <domain_id>
On Windows:
objs\<arch>\keys_publisher <domain_id>
objs\<arch>\keys_subscriber <domain_id>
modification history
------------ -------
*/
#include <stdio.h>
#include <stdlib.h>
#include "ndds/ndds_c.h"
#include "keys.h"
#include "keysSupport.h"
/* Delete all entities */
static int publisher_shutdown(
DDS_DomainParticipant *participant)
{
DDS_ReturnCode_t retcode;
int status = 0;
if (participant != NULL) {
retcode = DDS_DomainParticipant_delete_contained_entities(participant);
if (retcode != DDS_RETCODE_OK) {
printf("delete_contained_entities error %d\n", retcode);
status = -1;
}
retcode = DDS_DomainParticipantFactory_delete_participant(
DDS_TheParticipantFactory, participant);
if (retcode != DDS_RETCODE_OK) {
printf("delete_participant error %d\n", retcode);
status = -1;
}
}
/* RTI Connext provides finalize_instance() method on
domain participant factory for people who want to release memory used
by the participant factory. Uncomment the following block of code for
clean destruction of the singleton. */
/*
retcode = DDS_DomainParticipantFactory_finalize_instance();
if (retcode != DDS_RETCODE_OK) {
printf("finalize_instance error %d\n", retcode);
status = -1;
}
*/
return status;
}
static int publisher_main(int domainId, int sample_count)
{
DDS_DomainParticipant *participant = NULL;
DDS_Publisher *publisher = NULL;
DDS_Topic *topic = NULL;
DDS_DataWriter *writer = NULL;
keysDataWriter *keys_writer = NULL;
/* Creates three instances */
keys* instance[3] = {NULL, NULL, NULL};
/* Creates three handles for managing the registrations */
DDS_InstanceHandle_t handle[3];
/* We only will send data over the instances marked as active */
int active[3] = {1, 0, 0};
DDS_ReturnCode_t retcode;
const char *type_name = NULL;
int count = 0;
struct DDS_Duration_t send_period = {1,0};
int i = 0;
/* If you want to set the writer_data_lifecycle QoS settings
* programmatically rather than using the XML, you will need to add
* the following line to your code
*/
/* struct DDS_DataWriterQos datawriter_qos = DDS_DataWriterQos_INITIALIZER; */
/* To customize participant QoS, use
the configuration file USER_QOS_PROFILES.xml */
participant = DDS_DomainParticipantFactory_create_participant(
DDS_TheParticipantFactory, domainId, &DDS_PARTICIPANT_QOS_DEFAULT,
NULL /* listener */, DDS_STATUS_MASK_NONE);
if (participant == NULL) {
printf("create_participant error\n");
publisher_shutdown(participant);
return -1;
}
/* To customize publisher QoS, use
the configuration file USER_QOS_PROFILES.xml */
publisher = DDS_DomainParticipant_create_publisher(
participant, &DDS_PUBLISHER_QOS_DEFAULT, NULL /* listener */,
DDS_STATUS_MASK_NONE);
if (publisher == NULL) {
printf("create_publisher error\n");
publisher_shutdown(participant);
return -1;
}
/* Register type before creating topic */
type_name = keysTypeSupport_get_type_name();
retcode = keysTypeSupport_register_type(
participant, type_name);
if (retcode != DDS_RETCODE_OK) {
printf("register_type error %d\n", retcode);
publisher_shutdown(participant);
return -1;
}
/* To customize topic QoS, use
the configuration file USER_QOS_PROFILES.xml */
topic = DDS_DomainParticipant_create_topic(
participant, "Example keys",
type_name, &DDS_TOPIC_QOS_DEFAULT, NULL /* listener */,
DDS_STATUS_MASK_NONE);
if (topic == NULL) {
printf("create_topic error\n");
publisher_shutdown(participant);
return -1;
}
/* To customize data writer QoS, use
the configuration file USER_QOS_PROFILES.xml */
writer = DDS_Publisher_create_datawriter(
publisher, topic,
&DDS_DATAWRITER_QOS_DEFAULT, NULL /* listener */, DDS_STATUS_MASK_NONE);
if (writer == NULL) {
printf("create_datawriter error\n");
publisher_shutdown(participant);
return -1;
}
/* If you want to set the writer_data_lifecycle QoS settings
* programmatically rather than using the XML, you will need to add
* the following lines to your code and comment out the create_datawriter
* call above.
*/
/*
retcode = DDS_Publisher_get_default_datawriter_qos(publisher, &datawriter_qos);
if (retcode != DDS_RETCODE_OK) {
printf("get_default_datawriter_qos error\n");
return -1;
}
datawriter_qos.writer_data_lifecycle.autodispose_unregistered_instances =
DDS_BOOLEAN_FALSE;
writer = DDS_Publisher_create_datawriter(
publisher, topic,
&datawriter_qos, NULL, DDS_STATUS_MASK_NONE);
if (writer == NULL) {
printf("create_datawriter error\n");
publisher_shutdown(participant);
return -1;
}
*/
keys_writer = keysDataWriter_narrow(writer);
if (keys_writer == NULL) {
printf("DataWriter narrow error\n");
publisher_shutdown(participant);
return -1;
}
/* Create data samples for writing */
instance[0] = keysTypeSupport_create_data_ex(DDS_BOOLEAN_TRUE);
instance[1] = keysTypeSupport_create_data_ex(DDS_BOOLEAN_TRUE);
instance[2] = keysTypeSupport_create_data_ex(DDS_BOOLEAN_TRUE);
if (instance[0] == NULL || instance[1] == NULL || instance[2] == NULL) {
printf("keysTypeSupport::create_data error\n");
publisher_shutdown(participant);
return -1;
}
/* RTI Connext could examine the key fields each time it needs to determine
* which data-instance is being modified.
* However, for performance and semantic reasons, it is better
* for your application to declare all the data-instances it intends to
* modify prior to actually writing any samples. This is known as registration.
*/
/* In order to register the instances, we must set their associated keys first */
instance[0]->code = 0;
instance[1]->code = 1;
instance[2]->code = 2;
/* The keys must have been set before making this call */
printf("Registering instance %d\n", instance[0]->code);
handle[0] = keysDataWriter_register_instance(keys_writer, instance[0]);
/* Modify the data to be sent here */
instance[0]->x = 1000;
instance[1]->x = 2000;
instance[2]->x = 3000;
/* Main loop */
for (count=0; (sample_count == 0) || (count < sample_count); ++count) {
NDDS_Utility_sleep(&send_period);
switch (count) {
case 5: { /* Start sending new instances */
printf("----Registering instance %d\n", instance[1]->code);
printf("----Registering instance %d\n", instance[2]->code);
handle[1] = keysDataWriter_register_instance(keys_writer, instance[1]);
handle[2] = keysDataWriter_register_instance(keys_writer, instance[2]);
active[1] = 1;
active[2] = 1;
} break;
case 10: { /* Unregister instance */
printf("----Unregistering instance %d\n", instance[1]->code);
retcode = keysDataWriter_unregister_instance(
keys_writer, instance[1], &handle[1]);
if (retcode != DDS_RETCODE_OK) {
printf("unregister instance error %d\n", retcode);
return -1;
}
active[1] = 0;
} break;
case 15: { /* Dispose of instance */
printf("----Disposing instance %d\n", instance[2]->code);
retcode = keysDataWriter_dispose(keys_writer, instance[2], &handle[2]);
if (retcode != DDS_RETCODE_OK) {
printf("dispose instance error %d\n", retcode);
return -1;
}
active[2] = 0;
} break;
}
/* Modify the data to be sent here */
instance[0]->y = count;
instance[1]->y = count;
instance[2]->y = count;
for (i = 0; i < 3; ++i) {
if (active[i]) {
printf("Writing instance %d, x: %d, y: %d\n",
instance[i]->code, instance[i]->x, instance[i]->y);
retcode = keysDataWriter_write(keys_writer, instance[i], &handle[i]);
if (retcode != DDS_RETCODE_OK) {
printf("write error %d\n", retcode);
return -1;
}
}
}
}
/* Delete data samples */
for (i = 0; i < 3; ++i) {
retcode = keysTypeSupport_delete_data(instance[i]);
if (retcode != DDS_RETCODE_OK) {
printf("keysTypeSupport::delete_data error %d\n", retcode);
}
}
/* Cleanup and delete delete all entities */
return publisher_shutdown(participant);
}
#if defined(RTI_WINCE)
int wmain(int argc, wchar_t** argv)
{
int domainId = 0;
int sample_count = 0; /* infinite loop */
if (argc >= 2) {
domainId = _wtoi(argv[1]);
}
if (argc >= 3) {
sample_count = _wtoi(argv[2]);
}
/* Uncomment this to turn on additional logging
NDDS_Config_Logger_set_verbosity_by_category(
NDDS_Config_Logger_get_instance(),
NDDS_CONFIG_LOG_CATEGORY_API,
NDDS_CONFIG_LOG_VERBOSITY_STATUS_ALL);
*/
return publisher_main(domainId, sample_count);
}
#elif !(defined(RTI_VXWORKS) && !defined(__RTP__)) && !defined(RTI_PSOS)
int main(int argc, char *argv[])
{
int domainId = 0;
int sample_count = 0; /* infinite loop */
if (argc >= 2) {
domainId = atoi(argv[1]);
}
if (argc >= 3) {
sample_count = atoi(argv[2]);
}
/* Uncomment this to turn on additional logging
NDDS_Config_Logger_set_verbosity_by_category(
NDDS_Config_Logger_get_instance(),
NDDS_CONFIG_LOG_CATEGORY_API,
NDDS_CONFIG_LOG_VERBOSITY_STATUS_ALL);
*/
return publisher_main(domainId, sample_count);
}
#endif
#ifdef RTI_VX653
const unsigned char* __ctype = NULL;
void usrAppInit ()
{
#ifdef USER_APPL_INIT
USER_APPL_INIT; /* for backwards compatibility */
#endif
/* add application specific code here */
taskSpawn("pub", RTI_OSAPI_THREAD_PRIORITY_NORMAL, 0x8, 0x150000, (FUNCPTR)publisher_main, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
}
#endif
| c |
rticonnextdds-examples | data/projects/rticonnextdds-examples/keyed_data/c/keys_subscriber.c | /*******************************************************************************
(c) 2005-2014 Copyright, Real-Time Innovations, Inc. All rights reserved.
RTI grants Licensee a license to use, modify, compile, and create derivative
works of the Software. Licensee has the right to distribute object form only
for use with RTI products. The Software is provided "as is", with no warranty
of any type, including any warranty for fitness for any purpose. RTI is under
no obligation to maintain or support the Software. RTI shall not be liable for
any incidental or consequential damages arising out of the use or inability to
use the software.
******************************************************************************/
/* keys_subscriber.c
A subscription example
This file is derived from code automatically generated by the rtiddsgen
command:
rtiddsgen -language C -example <arch> keys.idl
Example subscription of type keys automatically generated by
'rtiddsgen'. To test them, follow these steps:
(1) Compile this file and the example publication.
(2) Start the subscription with the command
objs/<arch>/keys_subscriber <domain_id> <sample_count>
(3) Start the publication with the command
objs/<arch>/keys_publisher <domain_id> <sample_count>
(4) [Optional] Specify the list of discovery initial peers and
multicast receive addresses via an environment variable or a file
(in the current working directory) called NDDS_DISCOVERY_PEERS.
You can run any number of publishers and subscribers programs, and can
add and remove them dynamically from the domain.
Example:
To run the example application on domain <domain_id>:
On UNIX systems:
objs/<arch>/keys_publisher <domain_id>
objs/<arch>/keys_subscriber <domain_id>
On Windows systems:
objs\<arch>\keys_publisher <domain_id>
objs\<arch>\keys_subscriber <domain_id>
modification history
------------ -------
*/
#include <stdio.h>
#include <stdlib.h>
#include "ndds/ndds_c.h"
#include "keys.h"
#include "keysSupport.h"
void keysListener_on_requested_deadline_missed(
void* listener_data,
DDS_DataReader* reader,
const struct DDS_RequestedDeadlineMissedStatus *status)
{
}
void keysListener_on_requested_incompatible_qos(
void* listener_data,
DDS_DataReader* reader,
const struct DDS_RequestedIncompatibleQosStatus *status)
{
}
void keysListener_on_sample_rejected(
void* listener_data,
DDS_DataReader* reader,
const struct DDS_SampleRejectedStatus *status)
{
}
void keysListener_on_liveliness_changed(
void* listener_data,
DDS_DataReader* reader,
const struct DDS_LivelinessChangedStatus *status)
{
}
void keysListener_on_sample_lost(
void* listener_data,
DDS_DataReader* reader,
const struct DDS_SampleLostStatus *status)
{
}
void keysListener_on_subscription_matched(
void* listener_data,
DDS_DataReader* reader,
const struct DDS_SubscriptionMatchedStatus *status)
{
}
void keysListener_on_data_available(
void* listener_data,
DDS_DataReader* reader)
{
keysDataReader *keys_reader = NULL;
struct keysSeq data_seq = DDS_SEQUENCE_INITIALIZER;
struct DDS_SampleInfoSeq info_seq = DDS_SEQUENCE_INITIALIZER;
DDS_ReturnCode_t retcode;
int i;
keys_reader = keysDataReader_narrow(reader);
if (keys_reader == NULL) {
printf("DataReader narrow error\n");
return;
}
retcode = keysDataReader_take(
keys_reader,
&data_seq, &info_seq, DDS_LENGTH_UNLIMITED,
DDS_ANY_SAMPLE_STATE, DDS_ANY_VIEW_STATE, DDS_ANY_INSTANCE_STATE);
if (retcode == DDS_RETCODE_NO_DATA) {
return;
} else if (retcode != DDS_RETCODE_OK) {
printf("take error %d\n", retcode);
return;
}
for (i = 0; i < keysSeq_get_length(&data_seq); ++i) {
/* Start changes for Keyed_Data */
struct DDS_SampleInfo* info = NULL;
keys* data = NULL;
info = DDS_SampleInfoSeq_get_reference(&info_seq, i);
data = keysSeq_get_reference(&data_seq, i);
/* We first check if the sample includes valid data */
if (info->valid_data) {
if (info->view_state == DDS_NEW_VIEW_STATE) {
printf("Found new instance; code = %d\n", data->code);
}
printf("Instance %d: x: %d, y: %d\n", data->code,
data->x, data->y);
} else {
/* Since there is not valid data, it may include metadata */
keys dummy;
retcode = keysDataReader_get_key_value(keys_reader, &dummy, &info->instance_handle);
if (retcode != DDS_RETCODE_OK) {
printf("get_key_value error %d\n", retcode);
continue;
}
/* Here we print a message if the instance state is ALIVE_NO_WRITERS or ALIVE_DISPOSED */
if (info->instance_state == DDS_NOT_ALIVE_NO_WRITERS_INSTANCE_STATE) {
printf("Instance %d has no writers\n", dummy.code);
} else if (info->instance_state == DDS_NOT_ALIVE_DISPOSED_INSTANCE_STATE) {
printf("Instance %d disposed\n", dummy.code);
}
}
/* End changes for Keyed_Data */
}
retcode = keysDataReader_return_loan(
keys_reader,
&data_seq, &info_seq);
if (retcode != DDS_RETCODE_OK) {
printf("return loan error %d\n", retcode);
}
}
/* Delete all entities */
static int subscriber_shutdown(
DDS_DomainParticipant *participant)
{
DDS_ReturnCode_t retcode;
int status = 0;
if (participant != NULL) {
retcode = DDS_DomainParticipant_delete_contained_entities(participant);
if (retcode != DDS_RETCODE_OK) {
printf("delete_contained_entities error %d\n", retcode);
status = -1;
}
retcode = DDS_DomainParticipantFactory_delete_participant(
DDS_TheParticipantFactory, participant);
if (retcode != DDS_RETCODE_OK) {
printf("delete_participant error %d\n", retcode);
status = -1;
}
}
/* RTI Connext provides the finalize_instance() method on
domain participant factory for users who want to release memory used
by the participant factory. Uncomment the following block of code for
clean destruction of the singleton. */
/*
retcode = DDS_DomainParticipantFactory_finalize_instance();
if (retcode != DDS_RETCODE_OK) {
printf("finalize_instance error %d\n", retcode);
status = -1;
}
*/
return status;
}
static int subscriber_main(int domainId, int sample_count)
{
DDS_DomainParticipant *participant = NULL;
DDS_Subscriber *subscriber = NULL;
DDS_Topic *topic = NULL;
struct DDS_DataReaderListener reader_listener =
DDS_DataReaderListener_INITIALIZER;
DDS_DataReader *reader = NULL;
DDS_ReturnCode_t retcode;
const char *type_name = NULL;
int count = 0;
struct DDS_Duration_t poll_period = {1,0};
/* To customize participant QoS, use
the configuration file USER_QOS_PROFILES.xml */
participant = DDS_DomainParticipantFactory_create_participant(
DDS_TheParticipantFactory, domainId, &DDS_PARTICIPANT_QOS_DEFAULT,
NULL /* listener */, DDS_STATUS_MASK_NONE);
if (participant == NULL) {
printf("create_participant error\n");
subscriber_shutdown(participant);
return -1;
}
/* To customize subscriber QoS, use
the configuration file USER_QOS_PROFILES.xml */
subscriber = DDS_DomainParticipant_create_subscriber(
participant, &DDS_SUBSCRIBER_QOS_DEFAULT, NULL /* listener */,
DDS_STATUS_MASK_NONE);
if (subscriber == NULL) {
printf("create_subscriber error\n");
subscriber_shutdown(participant);
return -1;
}
/* Register the type before creating the topic */
type_name = keysTypeSupport_get_type_name();
retcode = keysTypeSupport_register_type(participant, type_name);
if (retcode != DDS_RETCODE_OK) {
printf("register_type error %d\n", retcode);
subscriber_shutdown(participant);
return -1;
}
/* To customize topic QoS, use
the configuration file USER_QOS_PROFILES.xml */
topic = DDS_DomainParticipant_create_topic(
participant, "Example keys",
type_name, &DDS_TOPIC_QOS_DEFAULT, NULL /* listener */,
DDS_STATUS_MASK_NONE);
if (topic == NULL) {
printf("create_topic error\n");
subscriber_shutdown(participant);
return -1;
}
/* Set up a data reader listener */
reader_listener.on_requested_deadline_missed =
keysListener_on_requested_deadline_missed;
reader_listener.on_requested_incompatible_qos =
keysListener_on_requested_incompatible_qos;
reader_listener.on_sample_rejected =
keysListener_on_sample_rejected;
reader_listener.on_liveliness_changed =
keysListener_on_liveliness_changed;
reader_listener.on_sample_lost =
keysListener_on_sample_lost;
reader_listener.on_subscription_matched =
keysListener_on_subscription_matched;
reader_listener.on_data_available =
keysListener_on_data_available;
/* To customize data reader QoS, use
the configuration file USER_QOS_PROFILES.xml */
reader = DDS_Subscriber_create_datareader(
subscriber, DDS_Topic_as_topicdescription(topic),
&DDS_DATAREADER_QOS_DEFAULT, &reader_listener, DDS_STATUS_MASK_ALL);
if (reader == NULL) {
printf("create_datareader error\n");
subscriber_shutdown(participant);
return -1;
}
/* Main loop */
for (count=0; (sample_count == 0) || (count < sample_count); ++count) {
//printf("keys subscriber sleeping for %d sec...\n",poll_period.sec);
NDDS_Utility_sleep(&poll_period);
}
/* Cleanup and delete all entities */
return subscriber_shutdown(participant);
}
#if defined(RTI_WINCE)
int wmain(int argc, wchar_t** argv)
{
int domainId = 0;
int sample_count = 0; /* infinite loop */
if (argc >= 2) {
domainId = _wtoi(argv[1]);
}
if (argc >= 3) {
sample_count = _wtoi(argv[2]);
}
/* Uncomment this to turn on additional logging
NDDS_Config_Logger_set_verbosity_by_category(
NDDS_Config_Logger_get_instance(),
NDDS_CONFIG_LOG_CATEGORY_API,
NDDS_CONFIG_LOG_VERBOSITY_STATUS_ALL);
*/
return subscriber_main(domainId, sample_count);
}
#elif !(defined(RTI_VXWORKS) && !defined(__RTP__)) && !defined(RTI_PSOS)
int main(int argc, char *argv[])
{
int domainId = 0;
int sample_count = 0; /* infinite loop */
if (argc >= 2) {
domainId = atoi(argv[1]);
}
if (argc >= 3) {
sample_count = atoi(argv[2]);
}
/* Uncomment this to turn on additional logging
NDDS_Config_Logger_set_verbosity_by_category(
NDDS_Config_Logger_get_instance(),
NDDS_CONFIG_LOG_CATEGORY_API,
NDDS_CONFIG_LOG_VERBOSITY_STATUS_ALL);
*/
return subscriber_main(domainId, sample_count);
}
#endif
#ifdef RTI_VX653
const unsigned char* __ctype = NULL;
void usrAppInit ()
{
#ifdef USER_APPL_INIT
USER_APPL_INIT; /* for backwards compatibility */
#endif
/* add application specific code here */
taskSpawn("sub", RTI_OSAPI_THREAD_PRIORITY_NORMAL, 0x8, 0x150000, (FUNCPTR)subscriber_main, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
}
#endif
| c |
rticonnextdds-examples | data/projects/rticonnextdds-examples/keyed_data/c++03/keys_publisher.cxx | /*******************************************************************************
(c) 2005-2015 Copyright, Real-Time Innovations, Inc. All rights reserved.
RTI grants Licensee a license to use, modify, compile, and create derivative
works of the Software. Licensee has the right to distribute object form only
for use with RTI products. The Software is provided "as is", with no warranty
of any type, including any warranty for fitness for any purpose. RTI is under
no obligation to maintain or support the Software. RTI shall not be liable for
any incidental or consequential damages arising out of the use or inability to
use the software.
******************************************************************************/
#include <cstdlib>
#include <iostream>
#include <dds/dds.hpp>
#include "keys.hpp"
using namespace dds::core;
using namespace dds::core::policy;
using namespace dds::domain;
using namespace dds::topic;
using namespace dds::pub;
using namespace dds::pub::qos;
void publisher_main(int domain_id, int sample_count)
{
// Create a DomainParticipant with default Qos.
DomainParticipant participant (domain_id);
// Create a Topic -- and automatically register the type.
Topic<keys> topic (participant, "Example keys");
// Retrieve the DataWriter QoS, from USER_QOS_PROFILES.xml
DataWriterQos writer_qos = QosProvider::Default().datawriter_qos();
// If you want to change the DataWriter's QoS programmatically rather
// than using the XML file, you will need to comment out the previous
// writer_qos assignment and uncomment this line.
//writer_qos << WriterDataLifecycle::ManuallyDisposeUnregisteredInstances();
// Create a DataWriter with default Qos (Publisher created in-line).
DataWriter<keys> writer(Publisher(participant), topic, writer_qos);
std::vector<keys> samples;
std::vector<InstanceHandle> instance_handles;
// RTI Connext could examine the key fields each time it needs to determine
// which data-instance is being modified. However, for performance and
// semantic reasons, it is better for your application to declare all the
// data-instances it intends to modify prior to actually writing any
// samples. This is known as registration.
int num_samples = 3;
for (int i = 0; i < num_samples; i++) {
// In order to register the instances, we must set their associated
// keys first.
keys k;
k.code(i);
// Initially, we register only the first sample.
if (i == 0) {
// The keys must have been set before making this call.
std::cout << "Registering instance " << k.code() << std::endl;
instance_handles.push_back(writer.register_instance(k));
} else {
instance_handles.push_back(InstanceHandle::nil());
}
// Finally, we modify the data to be sent.
k.x((i + 1) * 1000);
samples.push_back(k);
}
// Main loop
for (int count = 0; count < sample_count || sample_count == 0; count++) {
rti::util::sleep(Duration(1));
if (count == 5) {
// Start sending the second and third instances.
std::cout << "----Registering instance " << samples[1].code()
<< std::endl;
instance_handles[1] = writer.register_instance(samples[1]);
std::cout << "----Registering instance " << samples[2].code()
<< std::endl;
instance_handles[2] = writer.register_instance(samples[2]);
} else if (count == 10) {
// Unregister the second instance.
std::cout << "----Unregistering instance " << samples[1].code()
<< std::endl;
writer.unregister_instance(instance_handles[1]);
instance_handles[1] = InstanceHandle::nil();
} else if (count == 15) {
// Dispose the third instance.
std::cout << "----Disposing instance " << samples[2].code()
<< std::endl;
writer.dispose_instance(instance_handles[2]);
instance_handles[2] = InstanceHandle::nil();
}
// Update sample data field and send if handle is not nil.
for (int i = 0; i < num_samples; i++) {
if (!instance_handles[i].is_nil()) {
samples[i].y(count);
std::cout << "Writing instance " << samples[i].code()
<< ", x: " << samples[i].x()
<< ", y: " << samples[i].y() << std::endl;
writer.write(samples[i], instance_handles[i]);
}
}
}
}
int main(int argc, char *argv[])
{
int domain_id = 0;
int sample_count = 0; // Infinite loop
if (argc >= 2) {
domain_id = atoi(argv[1]);
}
if (argc >= 3) {
sample_count = atoi(argv[2]);
}
// To turn on additional logging, include <rti/config/Logger.hpp> and
// uncomment the following line:
// rti::config::Logger::instance().verbosity(rti::config::Verbosity::STATUS_ALL);
try {
publisher_main(domain_id, sample_count);
} catch (const std::exception& ex) {
// This will catch DDS exceptions
std::cerr << "Exception in publisher_main: " << ex.what() << std::endl;
return -1;
}
return 0;
}
| cxx |
rticonnextdds-examples | data/projects/rticonnextdds-examples/keyed_data/c++03/keys_subscriber.cxx | /*******************************************************************************
(c) 2005-2015 Copyright, Real-Time Innovations, Inc. All rights reserved.
RTI grants Licensee a license to use, modify, compile, and create derivative
works of the Software. Licensee has the right to distribute object form only
for use with RTI products. The Software is provided "as is", with no warranty
of any type, including any warranty for fitness for any purpose. RTI is under
no obligation to maintain or support the Software. RTI shall not be liable for
any incidental or consequential damages arising out of the use or inability to
use the software.
******************************************************************************/
#include <cstdlib>
#include <iostream>
#include <dds/dds.hpp>
#include <rti/core/ListenerBinder.hpp>
#include "keys.hpp"
using namespace dds::core;
using namespace rti::core;
using namespace dds::domain;
using namespace dds::topic;
using namespace dds::sub;
using namespace dds::sub::status;
class KeysReaderListener : public NoOpDataReaderListener<keys> {
public:
void on_data_available(DataReader<keys>& reader)
{
// Take all samples
LoanedSamples<keys> samples = reader.take();
for (LoanedSamples<keys>::iterator sample_it = samples.begin();
sample_it != samples.end();
sample_it++) {
const SampleInfo& info = sample_it->info();
if (info.valid()) {
ViewState view_state = info.state().view_state();
if (view_state == ViewState::new_view()) {
std::cout << "Found new instance; code = "
<< sample_it->data().code() << std::endl;
}
std::cout << "Instance " << sample_it->data().code()
<< ", x: " << sample_it->data().x()
<< ", y: " << sample_it->data().y() << std::endl;
} else {
// Since there is not valid data, it may include metadata.
keys sample;
reader.key_value(sample, info.instance_handle());
// Here we print a message if the instance state is
// 'not_alive_no_writers' or 'not_alive_disposed'.
const InstanceState& state = info.state().instance_state();
if (state == InstanceState::not_alive_no_writers()) {
std::cout << "Instance " << sample.code()
<< " has no writers" << std::endl;
} else if (state == InstanceState::not_alive_disposed()){
std::cout << "Instance " << sample.code() << " disposed"
<< std::endl;
}
}
}
}
};
void subscriber_main(int domain_id, int sample_count)
{
// Create a DomainParticipant with default Qos
DomainParticipant participant(domain_id);
// Create a Topic -- and automatically register the type
Topic<keys> topic(participant, "Example keys");
// Create a DataReader with default Qos (Subscriber created in-line)
DataReader<keys> reader(Subscriber(participant), topic);
// Associate a listener to the datareader using ListenerBinder, a RAII that
// will take care of setting it to NULL on destruction.
ListenerBinder< DataReader<keys> > reader_listener =
bind_and_manage_listener(
reader,
new KeysReaderListener,
dds::core::status::StatusMask::all());
// Main loop
for (int count = 0; count < sample_count || sample_count == 0; count++) {
rti::util::sleep(Duration(1));
}
}
int main(int argc, char *argv[])
{
int domain_id = 0;
int sample_count = 0; // Infinite loop
if (argc >= 2) {
domain_id = atoi(argv[1]);
}
if (argc >= 3) {
sample_count = atoi(argv[2]);
}
// To turn on additional logging, include <rti/config/Logger.hpp> and
// uncomment the following line:
// rti::config::Logger::instance().verbosity(rti::config::Verbosity::STATUS_ALL);
try {
subscriber_main(domain_id, sample_count);
} catch (const std::exception& ex) {
// This will catch DDS exceptions
std::cerr << "Exception in subscriber_main(): " << ex.what() << std::endl;
return -1;
}
return 0;
}
| cxx |
rticonnextdds-examples | data/projects/rticonnextdds-examples/dynamic_data_access_union_discriminator/c++/dynamic_data_union_example.cxx | /*******************************************************************************
(c) 2005-2014 Copyright, Real-Time Innovations, Inc. All rights reserved.
RTI grants Licensee a license to use, modify, compile, and create derivative
works of the Software. Licensee has the right to distribute object form only
for use with RTI products. The Software is provided "as is", with no warranty
of any type, including any warranty for fitness for any purpose. RTI is under
no obligation to maintain or support the Software. RTI shall not be liable for
any incidental or consequential damages arising out of the use or inability to
use the software.
******************************************************************************/
/* dynamic_data_union_example.cxx
This example
- creates the type code of for a union
- creates a DynamicData instance
- sets one of the members of the union
- shows how to retrieve the discriminator
- access to the value of one member of the union
Example:
To run the example application:
On Unix:
objs/<arch>/union_example
On Windows:
objs\<arch>\union_example
*/
#include <iostream>
#include <ndds_cpp.h>
using namespace std;
DDS_TypeCode *create_type_code(DDS_TypeCodeFactory *tcf) {
static DDS_TypeCode *unionTC = NULL;
struct DDS_UnionMemberSeq members;
DDS_ExceptionCode_t err;
/* First, we create the typeCode for a union */
/* Default-member index refers to which member of the union
* will be the default one. In this example index = 1 refers
* to the the member 'aLong'. Take into account that index
* starts in 0 */
unionTC = tcf->create_union_tc("Foo", DDS_MUTABLE_EXTENSIBILITY,
tcf->get_primitive_tc(DDS_TK_LONG), 1, /* default-member index */
members, /* For now, it does not have any member */
err);
if (err != DDS_NO_EXCEPTION_CODE) {
cerr << "! Unable to create typecode: " << err << endl;
goto fail;
}
/* Case 1 will be a short named aShort */
unionTC->add_member("aShort", DDS_DYNAMIC_DATA_MEMBER_ID_UNSPECIFIED,
tcf->get_primitive_tc(DDS_TK_SHORT), DDS_TYPECODE_NONKEY_MEMBER,
err);
if (err != DDS_NO_EXCEPTION_CODE) {
cerr << "! Unable to add member aShort: " << err << endl;
goto fail;
}
/* Case 2, the default, will be a long named aLong */
unionTC->add_member("aLong", 2, tcf->get_primitive_tc(DDS_TK_LONG),
DDS_TYPECODE_NONKEY_MEMBER, err);
if (err != DDS_NO_EXCEPTION_CODE) {
cerr << "! Unable to add member aLong: " << err << endl;
goto fail;
}
/* Case 3 will be a double named aDouble */
unionTC->add_member("aDouble", 3, tcf->get_primitive_tc(DDS_TK_DOUBLE),
DDS_TYPECODE_NONKEY_MEMBER, err);
if (err != DDS_NO_EXCEPTION_CODE) {
cerr << "! Unable to add member aDouble: " << err << endl;
goto fail;
}
return unionTC;
fail: if (unionTC != NULL) {
tcf->delete_tc(unionTC, err);
}
return NULL;
}
int example() {
/* Creating the union typeCode */
DDS_TypeCodeFactory *tcf = NULL;
tcf = DDS_TypeCodeFactory::get_instance();
if (tcf == NULL) {
cerr << "! Unable to get type code factory singleton" << endl;
return -1;
}
struct DDS_TypeCode *unionTC = create_type_code(tcf);
DDS_ReturnCode_t retcode;
struct DDS_DynamicDataMemberInfo info;
int ret = -1;
DDS_ExceptionCode_t err;
struct DDS_DynamicDataProperty_t myProperty =
DDS_DYNAMIC_DATA_PROPERTY_DEFAULT;
DDS_Short valueTestShort;
/* Creating a new dynamicData instance based on the union type code */
struct DDS_DynamicData data(unionTC, myProperty);
if (!data.is_valid()) {
cerr << "! Unable to create dynamicData" << endl;
goto fail;
}
/* If we get the current discriminator, it will be the default one
* (not the first added) */
retcode = data.get_member_info_by_index(info, 0);
if (retcode != DDS_RETCODE_OK) {
cerr << "! Unable to get member info" << endl;
goto fail;
}
cout << "The member selected is " << info.member_name << endl;
/* When we set a value in one of the members of the union,
* the discriminator updates automatically to point that member. */
retcode = data.set_short("aShort", DDS_DYNAMIC_DATA_MEMBER_ID_UNSPECIFIED,
42);
if (retcode != DDS_RETCODE_OK) {
cerr << "! Unable to set short member " << endl;
goto fail;
}
/* The discriminator should now reflect the new situation */
retcode = data.get_member_info_by_index(info, 0);
if (retcode != DDS_RETCODE_OK) {
cerr << "! Unable to get member info" << endl;
goto fail;
}
cout << "The member selected is " << info.member_name << endl;
/* Getting the value of the target member */
retcode = data.get_short(valueTestShort, "aShort",
DDS_DYNAMIC_DATA_MEMBER_ID_UNSPECIFIED);
if (retcode != DDS_RETCODE_OK) {
cerr << "! Unable to get member value" << endl;
goto fail;
}
cout << "The member selected is " << info.member_name << "with value: "
<< valueTestShort << endl;
ret = 1;
fail:
if (unionTC != NULL) {
tcf->delete_tc(unionTC, err);
}
return ret;
}
int main(int argc, char *argv[]) {
return example();
}
| cxx |
rticonnextdds-examples | data/projects/rticonnextdds-examples/dynamic_data_access_union_discriminator/c/UnionExample.c | /* UnionExample.c
This example
- creates the type code of for a union
- creates a DynamicData instance
- sets one of the fields of the union
- shows how to retrieve the discriminator
Example:
To run the example application:
On Unix:
objs/<arch>/UnionExample
On Windows:
objs\<arch>\UnionExample
*/
#include <stdio.h>
#include <stdlib.h>
#include "ndds/ndds_c.h"
struct DDS_TypeCode *createTypeCode(struct DDS_TypeCodeFactory *factory) {
struct DDS_TypeCode *unionTC = NULL;
DDS_ExceptionCode_t ex;
/* First, we create the typeCode for a union*/
unionTC = DDS_TypeCodeFactory_create_union_tc(
factory,
"Foo",
DDS_TypeCodeFactory_get_primitive_tc(factory, DDS_TK_LONG),
1, /* default index */
NULL, /* For now, it does not have any member */
&ex);
if (ex != DDS_NO_EXCEPTION_CODE) {
fprintf(stderr,"! Unable to create union TC\n");
goto fail;
}
/* Case 1 will be a short named aShort */
DDS_TypeCode_add_member(
unionTC,
"aShort",
-1, /* no default member */
DDS_TypeCodeFactory_get_primitive_tc(factory, DDS_TK_SHORT),
DDS_TYPECODE_NONKEY_MEMBER,
&ex);
if (ex != DDS_NO_EXCEPTION_CODE) {
fprintf(stderr,"! Unable to add member aShort\n");
goto fail;
}
/* Case 2 will be a long named aLong */
DDS_TypeCode_add_member(
unionTC,
"aLong",
2,
DDS_TypeCodeFactory_get_primitive_tc(factory, DDS_TK_LONG),
DDS_TYPECODE_NONKEY_MEMBER,
&ex);
if (ex != DDS_NO_EXCEPTION_CODE) {
fprintf(stderr,"! Unable to add member aLong\n");
goto fail;
}
/* Case 3, the default, will be a double named aDouble */
DDS_TypeCode_add_member(
unionTC,
"aDouble",
3,
DDS_TypeCodeFactory_get_primitive_tc(factory, DDS_TK_DOUBLE),
DDS_TYPECODE_NONKEY_MEMBER,
&ex);
if (ex != DDS_NO_EXCEPTION_CODE) {
fprintf(stderr,"! Unable to add member aDouble\n");
goto fail;
}
return unionTC;
fail:
if (unionTC != NULL) {
DDS_TypeCodeFactory_delete_tc(factory, unionTC,&ex);
}
return NULL;
}
int example () {
struct DDS_TypeCode *unionTC = NULL;
struct DDS_DynamicData data;
DDS_ReturnCode_t retcode;
struct DDS_DynamicDataMemberInfo info;
struct DDS_TypeCodeFactory *factory = NULL;
int ret = -1;
struct DDS_DynamicDataProperty_t myProperty = DDS_DYNAMIC_DATA_PROPERTY_DEFAULT;
/* I get a reference to the type code factory */
factory = DDS_TypeCodeFactory_get_instance();
if (factory == NULL) {
fprintf(stderr, "! Unable to get type code factory singleton\n");
goto fail;
}
/* Creating the union typeCode */
unionTC = createTypeCode(factory);
if (unionTC == NULL) {
fprintf(stderr,"! Unable to create typeCode\n");
goto fail;
}
/* Creating a new dynamicData instance based on the union type code */
if (!DDS_DynamicData_initialize(&data,unionTC,&myProperty)) {
fprintf(stderr,"! Unable to create dynamicData\n");
goto fail;
}
/* If I get the discriminator now, I will get the first one added */
retcode = DDS_DynamicData_get_member_info_by_index(
&data,&info,0);
if (retcode != DDS_RETCODE_OK) {
fprintf(stderr,"! Unable to get member info\n");
goto fail;
}
fprintf(stdout, "The field selected is %s\n", info.member_name);
/* Now I set one of the members */
retcode = DDS_DynamicData_set_short(&data,
"aShort",DDS_DYNAMIC_DATA_MEMBER_ID_UNSPECIFIED, 42);
if (retcode != DDS_RETCODE_OK) {
fprintf(stderr,"! Unable to create dynamicData\n");
goto fail;
}
/* The discriminator should now reflect the new situation */
retcode = DDS_DynamicData_get_member_info_by_index(
&data,&info,0);
if (retcode != DDS_RETCODE_OK) {
fprintf(stderr,"! Unable to get member info\n");
goto fail;
}
fprintf(stdout, "The field selected is %s\n", info.member_name);
ret = 1;
fail:
if (unionTC != NULL) {
DDS_TypeCodeFactory_delete_tc(factory, unionTC,NULL);
}
return ret;
}
int main(int argc, char *argv[]) {
return example();
}
| c |
rticonnextdds-examples | data/projects/rticonnextdds-examples/dynamic_data_access_union_discriminator/c/dynamic_data_union_example.c | /*******************************************************************************
(c) 2005-2014 Copyright, Real-Time Innovations, Inc. All rights reserved.
RTI grants Licensee a license to use, modify, compile, and create derivative
works of the Software. Licensee has the right to distribute object form only
for use with RTI products. The Software is provided "as is", with no warranty
of any type, including any warranty for fitness for any purpose. RTI is under
no obligation to maintain or support the Software. RTI shall not be liable for
any incidental or consequential damages arising out of the use or inability to
use the software.
******************************************************************************/
/* dynamic_data_union_example.c
This example
- creates the type code of for a union
- creates a DynamicData instance
- sets one of the members of the union
- shows how to retrieve the discriminator
- access to the value of one member of the union
Example:
To run the example application:
On Unix:
objs/<arch>/UnionExample
On Windows:
objs\<arch>\UnionExample
*/
#include <stdio.h>
#include <stdlib.h>
#include "ndds/ndds_c.h"
struct DDS_TypeCode *create_type_code(struct DDS_TypeCodeFactory *factory) {
struct DDS_TypeCode *unionTC = NULL;
DDS_ExceptionCode_t ex;
/* First, we create the typeCode for a union */
/* Default-member index refers to which member of the union
* will be the default one. In this example index = 1 refers
* to the the member 'aLong'. Take into account that index
* starts in 0 */
unionTC = DDS_TypeCodeFactory_create_union_tc(factory, "Foo",
DDS_TypeCodeFactory_get_primitive_tc(factory, DDS_TK_LONG),
1, /* default-member index */
NULL, /* For now, it does not have any member */
&ex);
if (ex != DDS_NO_EXCEPTION_CODE) {
fprintf(stderr, "! Unable to create union TC\n");
goto fail;
}
/* Case 1 will be a short named aShort */
DDS_TypeCode_add_member(unionTC, "aShort",
DDS_DYNAMIC_DATA_MEMBER_ID_UNSPECIFIED,
DDS_TypeCodeFactory_get_primitive_tc(factory, DDS_TK_SHORT),
DDS_TYPECODE_NONKEY_MEMBER, &ex);
if (ex != DDS_NO_EXCEPTION_CODE) {
fprintf(stderr, "! Unable to add member aShort\n");
goto fail;
}
/* Case 2, the default, will be a long named aLong */
DDS_TypeCode_add_member(unionTC, "aLong", 2,
DDS_TypeCodeFactory_get_primitive_tc(factory, DDS_TK_LONG),
DDS_TYPECODE_NONKEY_MEMBER, &ex);
if (ex != DDS_NO_EXCEPTION_CODE) {
fprintf(stderr, "! Unable to add member aLong\n");
goto fail;
}
/* Case 3 will be a double named aDouble */
DDS_TypeCode_add_member(unionTC, "aDouble", 3,
DDS_TypeCodeFactory_get_primitive_tc(factory, DDS_TK_DOUBLE),
DDS_TYPECODE_NONKEY_MEMBER, &ex);
if (ex != DDS_NO_EXCEPTION_CODE) {
fprintf(stderr, "! Unable to add member aDouble\n");
goto fail;
}
return unionTC;
fail: if (unionTC != NULL) {
DDS_TypeCodeFactory_delete_tc(factory, unionTC, &ex);
}
return NULL;
}
int example() {
struct DDS_TypeCode *unionTC = NULL;
struct DDS_DynamicData data;
DDS_ReturnCode_t retcode;
struct DDS_DynamicDataMemberInfo info;
struct DDS_TypeCodeFactory *factory = NULL;
int ret = -1;
struct DDS_DynamicDataProperty_t myProperty =
DDS_DYNAMIC_DATA_PROPERTY_DEFAULT;
DDS_Short valueTestShort;
DDS_Boolean dynamicDataIsInitialized = DDS_BOOLEAN_FALSE;
/* Getting a reference to the type code factory */
factory = DDS_TypeCodeFactory_get_instance();
if (factory == NULL) {
fprintf(stderr, "! Unable to get type code factory singleton\n");
goto fail;
}
/* Creating the union typeCode */
unionTC = create_type_code(factory);
if (unionTC == NULL) {
fprintf(stderr, "! Unable to create typeCode\n");
goto fail;
}
/* Creating a new dynamicData instance based on the union type code */
dynamicDataIsInitialized = DDS_DynamicData_initialize(&data, unionTC,
&myProperty);
if (!dynamicDataIsInitialized) {
fprintf(stderr, "! Unable to create dynamicData\n");
goto fail;
}
/* If we get the current discriminator, it will be the default one
(not the first added) */
retcode = DDS_DynamicData_get_member_info_by_index(&data, &info, 0);
if (retcode != DDS_RETCODE_OK) {
fprintf(stderr, "! Unable to get member info\n");
goto fail;
}
printf("The member selected is %s\n", info.member_name);
/* When we set a value in one of the members of the union,
* the discriminator updates automatically to point that member. */
retcode = DDS_DynamicData_set_short(&data, "aShort",
DDS_DYNAMIC_DATA_MEMBER_ID_UNSPECIFIED, 42);
if (retcode != DDS_RETCODE_OK) {
fprintf(stderr, "! Unable to set value to aShort member\n");
goto fail;
}
/* The discriminator should now reflect the new situation */
retcode = DDS_DynamicData_get_member_info_by_index(&data, &info, 0);
if (retcode != DDS_RETCODE_OK) {
fprintf(stderr, "! Unable to get member info\n");
goto fail;
}
printf("The member selected is %s\n", info.member_name);
/* Getting the value of the target member */
retcode = DDS_DynamicData_get_short(&data, &valueTestShort, "aShort",
DDS_DYNAMIC_DATA_MEMBER_ID_UNSPECIFIED);
if (retcode != DDS_RETCODE_OK) {
fprintf(stderr, "! Unable to get member value\n");
goto fail;
}
printf("The member selected is %s with value: %d\n", info.member_name,
valueTestShort);
ret = 1;
fail:
if (unionTC != NULL) {
DDS_TypeCodeFactory_delete_tc(factory, unionTC, NULL);
}
if (dynamicDataIsInitialized) {
DDS_DynamicData_finalize(&data);
}
return ret;
}
int main(int argc, char *argv[]) {
return example();
}
| c |
rticonnextdds-examples | data/projects/rticonnextdds-examples/dynamic_data_access_union_discriminator/c++03/dynamic_data_union_example.cxx | /*******************************************************************************
(c) 2005-2015 Copyright, Real-Time Innovations, Inc. All rights reserved.
RTI grants Licensee a license to use, modify, compile, and create derivative
works of the Software. Licensee has the right to distribute object form only
for use with RTI products. The Software is provided "as is", with no warranty
of any type, including any warranty for fitness for any purpose. RTI is under
no obligation to maintain or support the Software. RTI shall not be liable for
any incidental or consequential damages arising out of the use or inability to
use the software.
******************************************************************************/
#include <cstdlib>
#include <iostream>
#include <dds/dds.hpp>
using namespace dds::core::xtypes;
using namespace rti::core::xtypes;
UnionType create_union_type() {
// First, we create a DynamicType for a union.
UnionType union_type("Foo", primitive_type<int32_t>());
// Case 1 will be a short named aShort.
union_type.add_member(UnionMember(
"aShort", primitive_type<short>(), 0));
// Case 2 will be a long named aLong.
union_type.add_member(UnionMember(
"aLong", primitive_type<int>(), UnionMember::DEFAULT_LABEL));
// Case 3 will be a double named aDouble.
union_type.add_member(UnionMember(
"aDouble", primitive_type<double>(), 3));
return union_type;
}
void example() {
// Create the type of the union
UnionType union_type = create_union_type();
// Create the DynamicData.
DynamicData union_data(union_type);
// Get the current member, it will be the default one.
union_data.value<int>("aLong", 0);
DynamicDataMemberInfo info =
union_data.member_info(union_data.discriminator_value());
std::cout << "The member selected is " << info.member_name() << std::endl;
// When we set a value in one of the members of the union,
// the discriminator updates automatically to point that member.
union_data.value<short>("aShort", 42);
// The discriminator should now reflect the new situation.
info = union_data.member_info(union_data.discriminator_value());
std::cout << "The member selected is " << info.member_name();
// Getting the value of the target member.
short aShort = union_data.value<short>(union_data.discriminator_value());
std::cout << " with value " << aShort << std::endl;
}
int main(int argc, char *argv[]) {
try {
example();
} catch (const std::exception& ex) {
std::cerr << "Caught excetion: " << ex.what() << std::endl;
return -1;
}
return 0;
}
| cxx |
rticonnextdds-examples | data/projects/rticonnextdds-examples/using_typecodes/c++/msg_publisher.cxx | /*******************************************************************************
(c) 2005-2014 Copyright, Real-Time Innovations, Inc. All rights reserved.
RTI grants Licensee a license to use, modify, compile, and create derivative
works of the Software. Licensee has the right to distribute object form only
for use with RTI products. The Software is provided "as is", with no warranty
of any type, including any warranty for fitness for any purpose. RTI is under
no obligation to maintain or support the Software. RTI shall not be liable for
any incidental or consequential damages arising out of the use or inability to
use the software.
******************************************************************************/
/* msg_publisher.cxx
A publication of data of type msg
This file is derived from code automatically generated by the rtiddsgen
command:
rtiddsgen -language C++ -example <arch> msg.idl
Example publication of type msg automatically generated by
'rtiddsgen'. To test them follow these steps:
(1) Compile this file and the example subscription.
(2) Start the subscription with the command
objs/<arch>/msg_subscriber <domain_id> <sample_count>
(3) Start the publication with the command
objs/<arch>/msg_publisher <domain_id> <sample_count>
(4) [Optional] Specify the list of discovery initial peers and
multicast receive addresses via an environment variable or a file
(in the current working directory) called NDDS_DISCOVERY_PEERS.
You can run any number of publishers and subscribers programs, and can
add and remove them dynamically from the domain.
Example:
To run the example application on domain <domain_id>:
On Unix:
objs/<arch>/msg_publisher <domain_id> o
objs/<arch>/msg_subscriber <domain_id>
On Windows:
objs\<arch>\msg_publisher <domain_id>
objs\<arch>\msg_subscriber <domain_id>
modification history
------------ -------
*/
#include <stdio.h>
#include <stdlib.h>
#ifdef RTI_VX653
#include <vThreadsData.h>
#endif
#include "msg.h"
#include "msgSupport.h"
#include "ndds/ndds_cpp.h"
/* Delete all entities */
static int publisher_shutdown(
DDSDomainParticipant *participant)
{
DDS_ReturnCode_t retcode;
int status = 0;
if (participant != NULL) {
retcode = participant->delete_contained_entities();
if (retcode != DDS_RETCODE_OK) {
printf("delete_contained_entities error %d\n", retcode);
status = -1;
}
retcode = DDSTheParticipantFactory->delete_participant(participant);
if (retcode != DDS_RETCODE_OK) {
printf("delete_participant error %d\n", retcode);
status = -1;
}
}
/* RTI Connext provides finalize_instance() method on
domain participant factory for people who want to release memory used
by the participant factory. Uncomment the following block of code for
clean destruction of the singleton. */
/*
retcode = DDSDomainParticipantFactory::finalize_instance();
if (retcode != DDS_RETCODE_OK) {
printf("finalize_instance error %d\n", retcode);
status = -1;
}
*/
return status;
}
extern "C" int publisher_main(int domainId, int sample_count)
{
DDSDomainParticipant *participant = NULL;
DDSPublisher *publisher = NULL;
DDSTopic *topic = NULL;
DDSDataWriter *writer = NULL;
msgDataWriter * msg_writer = NULL;
msg *instance = NULL;
DDS_ReturnCode_t retcode;
DDS_InstanceHandle_t instance_handle = DDS_HANDLE_NIL;
const char *type_name = NULL;
int count = 0;
/* Send a new sample every 4 seconds */
DDS_Duration_t send_period = {4,0};
/* To customize participant QoS, use
the configuration file USER_QOS_PROFILES.xml */
participant = DDSTheParticipantFactory->create_participant(
domainId, DDS_PARTICIPANT_QOS_DEFAULT,
NULL, DDS_STATUS_MASK_NONE);
if (participant == NULL) {
printf("create_participant error\n");
publisher_shutdown(participant);
return -1;
}
/* If you want to change the type_code_max_serialized_length
* programmatically (e.g., to 3070) rather than using the XML file, you
* will need to add the following lines to your code and comment out the
* create_participant call above. */
/*
DDS_DomainParticipantQos participant_qos;
retcode = DDSTheParticipantFactory->get_default_participant_qos(participant_qos);
if (retcode != DDS_RETCODE_OK) {
printf("get_default_participant_qos error\n");
return -1;
}
participant_qos.resource_limits.type_code_max_serialized_length = 3070;
participant = DDSTheParticipantFactory->create_participant(
domainId, participant_qos,
NULL, DDS_STATUS_MASK_NONE);
if (participant == NULL) {
printf("create_participant error\n");
publisher_shutdown(participant);
return -1;
}
*/
/* To customize publisher QoS, use
the configuration file USER_QOS_PROFILES.xml */
publisher = participant->create_publisher(
DDS_PUBLISHER_QOS_DEFAULT, NULL /* listener */, DDS_STATUS_MASK_NONE);
if (publisher == NULL) {
printf("create_publisher error\n");
publisher_shutdown(participant);
return -1;
}
/* Register type before creating topic */
type_name = msgTypeSupport::get_type_name();
retcode = msgTypeSupport::register_type(
participant, type_name);
if (retcode != DDS_RETCODE_OK) {
printf("register_type error %d\n", retcode);
publisher_shutdown(participant);
return -1;
}
/* To customize topic QoS, use
the configuration file USER_QOS_PROFILES.xml */
topic = participant->create_topic(
"Example msg",
type_name, DDS_TOPIC_QOS_DEFAULT, NULL /* listener */,
DDS_STATUS_MASK_NONE);
if (topic == NULL) {
printf("create_topic error\n");
publisher_shutdown(participant);
return -1;
}
/* To customize data writer QoS, use
the configuration file USER_QOS_PROFILES.xml */
writer = publisher->create_datawriter(
topic, DDS_DATAWRITER_QOS_DEFAULT, NULL /* listener */,
DDS_STATUS_MASK_NONE);
if (writer == NULL) {
printf("create_datawriter error\n");
publisher_shutdown(participant);
return -1;
}
msg_writer = msgDataWriter::narrow(writer);
if (msg_writer == NULL) {
printf("DataWriter narrow error\n");
publisher_shutdown(participant);
return -1;
}
/* Create data sample for writing */
instance = msgTypeSupport::create_data();
if (instance == NULL) {
printf("msgTypeSupport::create_data error\n");
publisher_shutdown(participant);
return -1;
}
/* For a data type that has a key, if the same instance is going to be
written multiple times, initialize the key here
and register the keyed instance prior to writing */
/*
instance_handle = msg_writer->register_instance(*instance);
*/
/* Main loop */
for (count=0; (sample_count == 0) || (count < sample_count); ++count) {
printf("Writing msg, count %d\n", count);
/* Modify the data to be sent here */
instance->count = count;
retcode = msg_writer->write(*instance, instance_handle);
if (retcode != DDS_RETCODE_OK) {
printf("write error %d\n", retcode);
}
NDDSUtility::sleep(send_period);
}
/*
retcode = msg_writer->unregister_instance(
*instance, instance_handle);
if (retcode != DDS_RETCODE_OK) {
printf("unregister instance error %d\n", retcode);
}
*/
/* Delete data sample */
retcode = msgTypeSupport::delete_data(instance);
if (retcode != DDS_RETCODE_OK) {
printf("msgTypeSupport::delete_data error %d\n", retcode);
}
/* Delete all entities */
return publisher_shutdown(participant);
}
#if defined(RTI_WINCE)
int wmain(int argc, wchar_t** argv)
{
int domainId = 0;
int sample_count = 0; /* infinite loop */
if (argc >= 2) {
domainId = _wtoi(argv[1]);
}
if (argc >= 3) {
sample_count = _wtoi(argv[2]);
}
/* Uncomment this to turn on additional logging
NDDSConfigLogger::get_instance()->
set_verbosity_by_category(NDDS_CONFIG_LOG_CATEGORY_API,
NDDS_CONFIG_LOG_VERBOSITY_STATUS_ALL);
*/
return publisher_main(domainId, sample_count);
}
#elif !(defined(RTI_VXWORKS) && !defined(__RTP__)) && !defined(RTI_PSOS)
int main(int argc, char *argv[])
{
int domainId = 0;
int sample_count = 0; /* infinite loop */
if (argc >= 2) {
domainId = atoi(argv[1]);
}
if (argc >= 3) {
sample_count = atoi(argv[2]);
}
/* Uncomment this to turn on additional logging
NDDSConfigLogger::get_instance()->
set_verbosity_by_category(NDDS_CONFIG_LOG_CATEGORY_API,
NDDS_CONFIG_LOG_VERBOSITY_STATUS_ALL);
*/
return publisher_main(domainId, sample_count);
}
#endif
#ifdef RTI_VX653
const unsigned char* __ctype = *(__ctypePtrGet());
extern "C" void usrAppInit ()
{
#ifdef USER_APPL_INIT
USER_APPL_INIT; /* for backwards compatibility */
#endif
/* add application specific code here */
taskSpawn("pub", RTI_OSAPI_THREAD_PRIORITY_NORMAL, 0x8, 0x150000, (FUNCPTR)publisher_main, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
}
#endif
| cxx |
rticonnextdds-examples | data/projects/rticonnextdds-examples/using_typecodes/c++/msg_subscriber.cxx | /*******************************************************************************
(c) 2005-2014 Copyright, Real-Time Innovations, Inc. All rights reserved.
RTI grants Licensee a license to use, modify, compile, and create derivative
works of the Software. Licensee has the right to distribute object form only
for use with RTI products. The Software is provided "as is", with no warranty
of any type, including any warranty for fitness for any purpose. RTI is under
no obligation to maintain or support the Software. RTI shall not be liable for
any incidental or consequential damages arising out of the use or inability to
use the software.
******************************************************************************/
/* msg_subscriber.cxx
A subscription example
This file is derived from code automatically generated by the rtiddsgen
command:
rtiddsgen -language C++ -example <arch> msg.idl
Example subscription of type msg automatically generated by
'rtiddsgen'. To test them follow these steps:
(1) Compile this file and the example publication.
(2) Start the subscription with the command
objs/<arch>/msg_subscriber <domain_id> <sample_count>
(3) Start the publication with the command
objs/<arch>/msg_publisher <domain_id> <sample_count>
(4) [Optional] Specify the list of discovery initial peers and
multicast receive addresses via an environment variable or a file
(in the current working directory) called NDDS_DISCOVERY_PEERS.
You can run any number of publishers and subscribers programs, and can
add and remove them dynamically from the domain.
Example:
To run the example application on domain <domain_id>:
On Unix:
objs/<arch>/msg_publisher <domain_id>
objs/<arch>/msg_subscriber <domain_id>
On Windows:
objs\<arch>\msg_publisher <domain_id>
objs\<arch>\msg_subscriber <domain_id>
modification history
------------ -------
*/
#include <stdio.h>
#include <stdlib.h>
#ifdef RTI_VX653
#include <vThreadsData.h>
#endif
#include "msg.h"
/* We use the typecode from built-in listeners, so we don't need to include
* this code*/
/*
#include "msgSupport.h"
#include "ndds/ndds_cpp.h"
*/
/* We are going to use the BuiltinPublicationListener_on_data_available
* to detect the topics that are being published on the domain
*
* Once we have detected a new topic, we will print out the Topic Name,
* Participant ID, DataWriter id, and Data Type.
*/
class BuiltinPublicationListener : public DDSDataReaderListener {
public:
virtual void on_data_available(DDSDataReader* reader);
};
void BuiltinPublicationListener::on_data_available(DDSDataReader* reader)
{
DDSPublicationBuiltinTopicDataDataReader* builtin_reader =
(DDSPublicationBuiltinTopicDataDataReader*) reader;
DDS_PublicationBuiltinTopicDataSeq data_seq;
DDS_SampleInfoSeq info_seq;
DDS_ReturnCode_t retcode;
DDS_ExceptionCode_t exception_code;
DDSSubscriber *subscriber = NULL;
DDSDomainParticipant *participant = NULL;
retcode = builtin_reader->take(data_seq, info_seq, DDS_LENGTH_UNLIMITED,
DDS_ANY_SAMPLE_STATE, DDS_ANY_VIEW_STATE,
DDS_ANY_INSTANCE_STATE);
if (retcode != DDS_RETCODE_OK) {
printf("***Error: failed to access data from the built-in reader\n");
return;
}
for (int i = 0; i < data_seq.length(); ++i) {
if (info_seq[i].valid_data) {
printf("-----\nFound topic \"%s\"\nparticipant: %08x%08x%08x\ndatawriter: %08x%08x%08x\ntype:\n",
data_seq[i].topic_name,
data_seq[i].participant_key.value[0],
data_seq[i].participant_key.value[1],
data_seq[i].participant_key.value[2],
data_seq[i].key.value[0],
data_seq[i].key.value[1],
data_seq[i].key.value[2]);
if (data_seq[i].type_code == NULL) {
printf("No type code received, perhaps increase type_code_max_serialized_length?\n");
continue;
}
/* Using the type_code propagated we print the data type
* with print_IDL(). */
data_seq[i].type_code->print_IDL(2, exception_code);
if (exception_code != DDS_NO_EXCEPTION_CODE) {
printf("Error***: print_IDL returns exception code %d",
exception_code);
}
}
}
builtin_reader->return_loan(data_seq, info_seq);
}
/* Delete all entities */
static int subscriber_shutdown(
DDSDomainParticipant *participant)
{
DDS_ReturnCode_t retcode;
int status = 0;
if (participant != NULL) {
retcode = participant->delete_contained_entities();
if (retcode != DDS_RETCODE_OK) {
printf("delete_contained_entities error %d\n", retcode);
status = -1;
}
retcode = DDSTheParticipantFactory->delete_participant(participant);
if (retcode != DDS_RETCODE_OK) {
printf("delete_participant error %d\n", retcode);
status = -1;
}
}
/* RTI Connext provides the finalize_instance() method on
domain participant factory for people who want to release memory used
by the participant factory. Uncomment the following block of code for
clean destruction of the singleton. */
/*
retcode = DDSDomainParticipantFactory::finalize_instance();
if (retcode != DDS_RETCODE_OK) {
printf("finalize_instance error %d\n", retcode);
status = -1;
}
*/
return status;
}
extern "C" int subscriber_main(int domainId, int sample_count)
{
DDSDomainParticipant *participant = NULL;
DDSSubscriber *subscriber = NULL;
DDSTopic *topic = NULL;
DDS_ReturnCode_t retcode;
const char *type_name = NULL;
int count = 0;
struct DDS_Duration_t receive_period = {1,0};
int status = 0;
/* To customize the participant QoS, use
the configuration file USER_QOS_PROFILES.xml */
participant = DDSTheParticipantFactory->create_participant(
domainId, DDS_PARTICIPANT_QOS_DEFAULT,
NULL, DDS_STATUS_MASK_NONE);
if (participant == NULL) {
printf("create_participant error\n");
subscriber_shutdown(participant);
return -1;
}
/* If you want to change the type_code_max_serialized_length
* programmatically (e.g., to 3070) rather than using the XML file, you
* will need to add the following lines to your code and comment out the
* create_participant call above. */
/*
DDS_DomainParticipantQos participant_qos;
retcode = DDSTheParticipantFactory->get_default_participant_qos(participant_qos);
if (retcode != DDS_RETCODE_OK) {
printf("get_default_participant_qos error\n");
return -1;
}
participant_qos.resource_limits.type_code_max_serialized_length = 3070;
participant = DDSTheParticipantFactory->create_participant(
domainId, participant_qos,
NULL, DDS_STATUS_MASK_NONE);
if (participant == NULL) {
printf("create_participant error\n");
subscriber_shutdown(participant);
return -1;
}
*/
/* We don't actually care about receiving the samples, just the
topic information. To do this, we only need the builtin
datareader for publications.
*/
/* First get the built-in subscriber */
DDSSubscriber *builtin_subscriber = participant->get_builtin_subscriber();
if (builtin_subscriber == NULL) {
printf("***Error: failed to create builtin subscriber\n");
return 0;
}
/* Then get the data reader for the built-in subscriber */
DDSPublicationBuiltinTopicDataDataReader *builtin_publication_datareader =
(DDSPublicationBuiltinTopicDataDataReader*)
builtin_subscriber->lookup_datareader(DDS_PUBLICATION_TOPIC_NAME);
if (builtin_publication_datareader == NULL) {
printf("***Error: failed to create builtin publication data reader\n");
return 0;
}
/* Finally install the listener */
BuiltinPublicationListener *builtin_publication_listener =
new BuiltinPublicationListener();
builtin_publication_datareader->set_listener(builtin_publication_listener,
DDS_DATA_AVAILABLE_STATUS);
/* Main loop */
for (count=0; (sample_count == 0) || (count < sample_count); ++count) {
NDDSUtility::sleep(receive_period);
}
/* Delete all entities */
status = subscriber_shutdown(participant);
return status;
}
#if defined(RTI_WINCE)
int wmain(int argc, wchar_t** argv)
{
int domainId = 0;
int sample_count = 0; /* infinite loop */
if (argc >= 2) {
domainId = _wtoi(argv[1]);
}
if (argc >= 3) {
sample_count = _wtoi(argv[2]);
}
/* Uncomment this to turn on additional logging
NDDSConfigLogger::get_instance()->
set_verbosity_by_category(NDDS_CONFIG_LOG_CATEGORY_API,
NDDS_CONFIG_LOG_VERBOSITY_STATUS_ALL);
*/
return subscriber_main(domainId, sample_count);
}
#elif !(defined(RTI_VXWORKS) && !defined(__RTP__)) && !defined(RTI_PSOS)
int main(int argc, char *argv[])
{
int domainId = 0;
int sample_count = 0; /* infinite loop */
if (argc >= 2) {
domainId = atoi(argv[1]);
}
if (argc >= 3) {
sample_count = atoi(argv[2]);
}
/* Uncomment this to turn on additional logging
NDDSConfigLogger::get_instance()->
set_verbosity_by_category(NDDS_CONFIG_LOG_CATEGORY_API,
NDDS_CONFIG_LOG_VERBOSITY_STATUS_ALL);
*/
return subscriber_main(domainId, sample_count);
}
#endif
#ifdef RTI_VX653
const unsigned char* __ctype = *(__ctypePtrGet());
extern "C" void usrAppInit ()
{
#ifdef USER_APPL_INIT
USER_APPL_INIT; /* for backwards compatibility */
#endif
/* add application specific code here */
taskSpawn("sub", RTI_OSAPI_THREAD_PRIORITY_NORMAL, 0x8, 0x150000, (FUNCPTR)subscriber_main, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
}
#endif
| cxx |
rticonnextdds-examples | data/projects/rticonnextdds-examples/using_typecodes/c/msg_publisher.c | /*******************************************************************************
(c) 2005-2014 Copyright, Real-Time Innovations, Inc. All rights reserved.
RTI grants Licensee a license to use, modify, compile, and create derivative
works of the Software. Licensee has the right to distribute object form only
for use with RTI products. The Software is provided "as is", with no warranty
of any type, including any warranty for fitness for any purpose. RTI is under
no obligation to maintain or support the Software. RTI shall not be liable for
any incidental or consequential damages arising out of the use or inability to
use the software.
******************************************************************************/
/* msg_publisher.c
A publication of data of type msg
This file is derived from code automatically generated by the rtiddsgen
command:
rtiddsgen -language C -example <arch> msg.idl
Example publication of type msg automatically generated by
'rtiddsgen'. To test them follow these steps:
(1) Compile this file and the example subscription.
(2) Start the subscription with the command
objs/<arch>/msg_subscriber <domain_id> <sample_count>
(3) Start the publication with the command
objs/<arch>/msg_publisher <domain_id> <sample_count>
(4) [Optional] Specify the list of discovery initial peers and
multicast receive addresses via an environment variable or a file
(in the current working directory) called NDDS_DISCOVERY_PEERS.
You can run any number of publishers and subscribers programs, and can
add and remove them dynamically from the domain.
Example:
To run the example application on domain <domain_id>:
On Unix:
objs/<arch>/msg_publisher <domain_id>
objs/<arch>/msg_subscriber <domain_id>
On Windows:
objs\<arch>\msg_publisher <domain_id>
objs\<arch>\msg_subscriber <domain_id>
modification history
------------ -------
*/
#include <stdio.h>
#include <stdlib.h>
#include "ndds/ndds_c.h"
#include "msg.h"
#include "msgSupport.h"
/* Delete all entities */
static int publisher_shutdown(
DDS_DomainParticipant *participant)
{
DDS_ReturnCode_t retcode;
int status = 0;
if (participant != NULL) {
retcode = DDS_DomainParticipant_delete_contained_entities(participant);
if (retcode != DDS_RETCODE_OK) {
printf("delete_contained_entities error %d\n", retcode);
status = -1;
}
retcode = DDS_DomainParticipantFactory_delete_participant(
DDS_TheParticipantFactory, participant);
if (retcode != DDS_RETCODE_OK) {
printf("delete_participant error %d\n", retcode);
status = -1;
}
}
/* RTI Connext provides finalize_instance() method on
domain participant factory for people who want to release memory used
by the participant factory. Uncomment the following block of code for
clean destruction of the singleton. */
/*
retcode = DDS_DomainParticipantFactory_finalize_instance();
if (retcode != DDS_RETCODE_OK) {
printf("finalize_instance error %d\n", retcode);
status = -1;
}
*/
return status;
}
static int publisher_main(int domainId, int sample_count)
{
DDS_DomainParticipant *participant = NULL;
DDS_Publisher *publisher = NULL;
DDS_Topic *topic = NULL;
DDS_DataWriter *writer = NULL;
msgDataWriter *msg_writer = NULL;
msg *instance = NULL;
DDS_ReturnCode_t retcode;
DDS_InstanceHandle_t instance_handle = DDS_HANDLE_NIL;
const char *type_name = NULL;
int count = 0;
/* Send a new sample every 4 seconds */
struct DDS_Duration_t send_period = {4,0};
/* If you want to change the type_code_max_serialized_length
* programmatically (e.g., to 3070) rather than using the XML file, you
* will need to add the following lines to your code and comment out the
* create_participant call bellow. */
/*
struct DDS_DomainParticipantQos participant_qos =
DDS_DomainParticipantQos_INITIALIZER;
retcode = DDS_DomainParticipantFactory_get_default_participant_qos(
DDS_TheParticipantFactory, &participant_qos);
if (retcode != DDS_RETCODE_OK) {
printf("get_default_participant_qos error\n");
return -1;
}
participant_qos.resource_limits.type_code_max_serialized_length = 3070;
participant = DDS_DomainParticipantFactory_create_participant(
DDS_TheParticipantFactory, domainId, &participant_qos,
NULL, DDS_STATUS_MASK_NONE);
if (participant == NULL) {
printf("create_participant error\n");
publisher_shutdown(participant);
return -1;
}
*/
/* To customize participant QoS, use
the configuration file USER_QOS_PROFILES.xml */
participant = DDS_DomainParticipantFactory_create_participant(
DDS_TheParticipantFactory, domainId, &DDS_PARTICIPANT_QOS_DEFAULT,
NULL, DDS_STATUS_MASK_NONE);
if (participant == NULL) {
printf("create_participant error\n");
publisher_shutdown(participant);
return -1;
}
/* To customize publisher QoS, use
the configuration file USER_QOS_PROFILES.xml */
publisher = DDS_DomainParticipant_create_publisher(
participant, &DDS_PUBLISHER_QOS_DEFAULT, NULL /* listener */,
DDS_STATUS_MASK_NONE);
if (publisher == NULL) {
printf("create_publisher error\n");
publisher_shutdown(participant);
return -1;
}
/* Register type before creating topic */
type_name = msgTypeSupport_get_type_name();
retcode = msgTypeSupport_register_type(
participant, type_name);
if (retcode != DDS_RETCODE_OK) {
printf("register_type error %d\n", retcode);
publisher_shutdown(participant);
return -1;
}
/* To customize topic QoS, use
the configuration file USER_QOS_PROFILES.xml */
topic = DDS_DomainParticipant_create_topic(
participant, "Example msg",
type_name, &DDS_TOPIC_QOS_DEFAULT, NULL /* listener */,
DDS_STATUS_MASK_NONE);
if (topic == NULL) {
printf("create_topic error\n");
publisher_shutdown(participant);
return -1;
}
/* To customize data writer QoS, use
the configuration file USER_QOS_PROFILES.xml */
writer = DDS_Publisher_create_datawriter(
publisher, topic,
&DDS_DATAWRITER_QOS_DEFAULT, NULL /* listener */, DDS_STATUS_MASK_NONE);
if (writer == NULL) {
printf("create_datawriter error\n");
publisher_shutdown(participant);
return -1;
}
msg_writer = msgDataWriter_narrow(writer);
if (msg_writer == NULL) {
printf("DataWriter narrow error\n");
publisher_shutdown(participant);
return -1;
}
/* Create data sample for writing */
instance = msgTypeSupport_create_data_ex(DDS_BOOLEAN_TRUE);
if (instance == NULL) {
printf("msgTypeSupport_create_data error\n");
publisher_shutdown(participant);
return -1;
}
/* For a data type that has a key, if the same instance is going to be
written multiple times, initialize the key here
and register the keyed instance prior to writing */
/*
instance_handle = msgDataWriter_register_instance(
msg_writer, instance);
*/
/* Main loop */
for (count=0; (sample_count == 0) || (count < sample_count); ++count) {
printf("Writing msg, count %d\n", count);
/* Modify the data to be written here */
instance->count = count;
/* Write data */
retcode = msgDataWriter_write(
msg_writer, instance, &instance_handle);
if (retcode != DDS_RETCODE_OK) {
printf("write error %d\n", retcode);
}
NDDS_Utility_sleep(&send_period);
}
/*
retcode = msgDataWriter_unregister_instance(
msg_writer, instance, &instance_handle);
if (retcode != DDS_RETCODE_OK) {
printf("unregister instance error %d\n", retcode);
}
*/
/* Delete data sample */
retcode = msgTypeSupport_delete_data_ex(instance, DDS_BOOLEAN_TRUE);
if (retcode != DDS_RETCODE_OK) {
printf("msgTypeSupport_delete_data error %d\n", retcode);
}
/* Cleanup and delete delete all entities */
return publisher_shutdown(participant);
}
#if defined(RTI_WINCE)
int wmain(int argc, wchar_t** argv)
{
int domainId = 0;
int sample_count = 0; /* infinite loop */
if (argc >= 2) {
domainId = _wtoi(argv[1]);
}
if (argc >= 3) {
sample_count = _wtoi(argv[2]);
}
/* Uncomment this to turn on additional logging
NDDS_Config_Logger_set_verbosity_by_category(
NDDS_Config_Logger_get_instance(),
NDDS_CONFIG_LOG_CATEGORY_API,
NDDS_CONFIG_LOG_VERBOSITY_STATUS_ALL);
*/
return publisher_main(domainId, sample_count);
}
#elif !(defined(RTI_VXWORKS) && !defined(__RTP__)) && !defined(RTI_PSOS)
int main(int argc, char *argv[])
{
int domainId = 0;
int sample_count = 0; /* infinite loop */
if (argc >= 2) {
domainId = atoi(argv[1]);
}
if (argc >= 3) {
sample_count = atoi(argv[2]);
}
/* Uncomment this to turn on additional logging
NDDS_Config_Logger_set_verbosity_by_category(
NDDS_Config_Logger_get_instance(),
NDDS_CONFIG_LOG_CATEGORY_API,
NDDS_CONFIG_LOG_VERBOSITY_STATUS_ALL);
*/
return publisher_main(domainId, sample_count);
}
#endif
#ifdef RTI_VX653
const unsigned char* __ctype = NULL;
void usrAppInit ()
{
#ifdef USER_APPL_INIT
USER_APPL_INIT; /* for backwards compatibility */
#endif
/* add application specific code here */
taskSpawn("pub", RTI_OSAPI_THREAD_PRIORITY_NORMAL, 0x8, 0x150000, (FUNCPTR)publisher_main, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
}
#endif
| c |
rticonnextdds-examples | data/projects/rticonnextdds-examples/using_typecodes/c/msg_subscriber.c | /*******************************************************************************
(c) 2005-2014 Copyright, Real-Time Innovations, Inc. All rights reserved.
RTI grants Licensee a license to use, modify, compile, and create derivative
works of the Software. Licensee has the right to distribute object form only
for use with RTI products. The Software is provided "as is", with no warranty
of any type, including any warranty for fitness for any purpose. RTI is under
no obligation to maintain or support the Software. RTI shall not be liable for
any incidental or consequential damages arising out of the use or inability to
use the software.
******************************************************************************/
/* msg_subscriber.c
A subscription example
This file is derived from code automatically generated by the rtiddsgen
command:
rtiddsgen -language C -example <arch> msg.idl
Example subscription of type msg automatically generated by
'rtiddsgen'. To test them, follow these steps:
(1) Compile this file and the example publication.
(2) Start the subscription with the command
objs/<arch>/msg_subscriber <domain_id> <sample_count>
(3) Start the publication with the command
objs/<arch>/msg_publisher <domain_id> <sample_count>
(4) [Optional] Specify the list of discovery initial peers and
multicast receive addresses via an environment variable or a file
(in the current working directory) called NDDS_DISCOVERY_PEERS.
You can run any number of publishers and subscribers programs, and can
add and remove them dynamically from the domain.
Example:
To run the example application on domain <domain_id>:
On UNIX systems:
objs/<arch>/msg_publisher <domain_id>
objs/<arch>/msg_subscriber <domain_id>
On Windows systems:
objs\<arch>\msg_publisher <domain_id>
objs\<arch>\msg_subscriber <domain_id>
modification history
------------ -------
*/
#include <stdio.h>
#include <stdlib.h>
#include "ndds/ndds_c.h"
/* We use the typecode from built-in listeners, so we don't need to include
* this code*/
/*
#include "msg.h"
#include "msgSupport.h"
*/
/* We are going to use the BuiltinPublicationListener_on_data_available
* to detect the topics that are being published on the domain
*
* Once we have detected a new topic, we will print out the Topic Name,
* Participant ID, DataWriter id, and Data Type.
*/
void BuiltinPublicationListener_on_data_available(
void* listener_data,
DDS_DataReader* reader)
{
DDS_PublicationBuiltinTopicDataDataReader *builtin_reader = NULL;
struct DDS_PublicationBuiltinTopicDataSeq data_seq = DDS_SEQUENCE_INITIALIZER;
struct DDS_PublicationBuiltinTopicData *data = NULL;
struct DDS_SampleInfoSeq info_seq = DDS_SEQUENCE_INITIALIZER;
DDS_ReturnCode_t retcode;
DDS_ExceptionCode_t exception_code;
int i, len;
builtin_reader = DDS_PublicationBuiltinTopicDataDataReader_narrow(reader);
retcode = DDS_PublicationBuiltinTopicDataDataReader_take(
builtin_reader,
&data_seq, &info_seq, DDS_LENGTH_UNLIMITED,
DDS_ANY_SAMPLE_STATE, DDS_NEW_VIEW_STATE,
DDS_ANY_INSTANCE_STATE);
if (retcode == DDS_RETCODE_NO_DATA)
return;
if (retcode != DDS_RETCODE_OK) {
printf("***Error: failed to access data from the built-in reader\n");
return;
}
len = DDS_PublicationBuiltinTopicDataSeq_get_length(&data_seq);
for (i = 0; i < len; ++i) {
if (DDS_SampleInfoSeq_get_reference(&info_seq, i)->valid_data) {
data = DDS_PublicationBuiltinTopicDataSeq_get_reference(&data_seq, i);
printf("-----\nFound topic \"%s\"\nparticipant: %08x%08x%08x\ndatawriter: %08x%08x%08x\ntype:\n",
data->topic_name,
data->participant_key.value[0],
data->participant_key.value[1],
data->participant_key.value[2],
data->key.value[0],
data->key.value[1],
data->key.value[2]);
if (data->type_code == NULL) {
printf("No type code received, perhaps increase type_code_max_serialized_length?\n");
continue;
}
/* Using the type_code propagated we print the data type
* with print_IDL(). */
DDS_TypeCode_print_IDL(data->type_code, 2, &exception_code);
if (exception_code != DDS_NO_EXCEPTION_CODE) {
printf("Error***: print_IDL returns exception code %d",
exception_code);
}
}
}
DDS_PublicationBuiltinTopicDataDataReader_return_loan(
builtin_reader, &data_seq, &info_seq);
}
/* Delete all entities */
static int subscriber_shutdown(
DDS_DomainParticipant *participant)
{
DDS_ReturnCode_t retcode;
int status = 0;
if (participant != NULL) {
retcode = DDS_DomainParticipant_delete_contained_entities(participant);
if (retcode != DDS_RETCODE_OK) {
printf("delete_contained_entities error %d\n", retcode);
status = -1;
}
retcode = DDS_DomainParticipantFactory_delete_participant(
DDS_TheParticipantFactory, participant);
if (retcode != DDS_RETCODE_OK) {
printf("delete_participant error %d\n", retcode);
status = -1;
}
}
/* RTI Connext provides the finalize_instance() method on
domain participant factory for users who want to release memory used
by the participant factory. Uncomment the following block of code for
clean destruction of the singleton. */
/*
retcode = DDS_DomainParticipantFactory_finalize_instance();
if (retcode != DDS_RETCODE_OK) {
printf("finalize_instance error %d\n", retcode);
status = -1;
}
*/
return status;
}
static int subscriber_main(int domainId, int sample_count)
{
DDS_DomainParticipant *participant = NULL;
int count = 0;
struct DDS_Duration_t poll_period = {4,0};
DDS_ReturnCode_t retcode;
DDS_Subscriber *builtin_subscriber = NULL;
DDS_PublicationBuiltinTopicDataDataReader *builtin_publication_datareader = NULL;
/* Listener for the Built-in Publication Data Reader */
struct DDS_DataReaderListener builtin_publication_listener =
DDS_DataReaderListener_INITIALIZER;
/* If you want to change the type_code_max_serialized_length
* programmatically (e.g., to 3070) rather than using the XML file, you
* will need to add the following lines to your code and comment out the
* create_participant call bellow. */
/*
struct DDS_DomainParticipantQos participant_qos =
DDS_DomainParticipantQos_INITIALIZER;
retcode = DDS_DomainParticipantFactory_get_default_participant_qos(
DDS_TheParticipantFactory, &participant_qos);
if (retcode != DDS_RETCODE_OK) {
printf("get_default_participant_qos error\n");
return -1;
}
participant_qos.resource_limits.type_code_max_serialized_length = 3070;
participant = DDS_DomainParticipantFactory_create_participant(
DDS_TheParticipantFactory, domainId, &participant_qos,
NULL, DDS_STATUS_MASK_NONE);
if (participant == NULL) {
printf("create_participant error\n");
subscriber_shutdown(participant);
return -1;
}
*/
/* To customize participant QoS, use
the configuration file USER_QOS_PROFILES.xml */
participant = DDS_DomainParticipantFactory_create_participant(
DDS_TheParticipantFactory, domainId, &DDS_PARTICIPANT_QOS_DEFAULT,
NULL, DDS_STATUS_MASK_NONE);
if (participant == NULL) {
printf("create_participant error\n");
subscriber_shutdown(participant);
return -1;
}
/* First get the built-in subscriber */
builtin_subscriber = DDS_DomainParticipant_get_builtin_subscriber(participant);
if (builtin_subscriber == NULL) {
printf("***Error: failed to create builtin subscriber\n");
return 0;
}
/* Then get the data reader for the built-in subscriber */
builtin_publication_datareader =
(DDS_PublicationBuiltinTopicDataDataReader*)
DDS_Subscriber_lookup_datareader(builtin_subscriber,
DDS_PUBLICATION_TOPIC_NAME);
if (builtin_publication_datareader == NULL) {
printf("***Error: failed to create builtin publication data reader\n");
return 0;
}
/* Finally install the listener */
builtin_publication_listener.on_data_available =
BuiltinPublicationListener_on_data_available;
DDS_DataReader_set_listener((DDS_DataReader*)builtin_publication_datareader,
&builtin_publication_listener,
DDS_DATA_AVAILABLE_STATUS);
/* Main loop */
for (count=0; (sample_count == 0) || (count < sample_count); ++count) {
NDDS_Utility_sleep(&poll_period);
}
/* Cleanup and delete all entities */
return subscriber_shutdown(participant);
}
#if defined(RTI_WINCE)
int wmain(int argc, wchar_t** argv)
{
int domainId = 0;
int sample_count = 0; /* infinite loop */
if (argc >= 2) {
domainId = _wtoi(argv[1]);
}
if (argc >= 3) {
sample_count = _wtoi(argv[2]);
}
/* Uncomment this to turn on additional logging
NDDS_Config_Logger_set_verbosity_by_category(
NDDS_Config_Logger_get_instance(),
NDDS_CONFIG_LOG_CATEGORY_API,
NDDS_CONFIG_LOG_VERBOSITY_STATUS_ALL);
*/
return subscriber_main(domainId, sample_count);
}
#elif !(defined(RTI_VXWORKS) && !defined(__RTP__)) && !defined(RTI_PSOS)
int main(int argc, char *argv[])
{
int domainId = 0;
int sample_count = 0; /* infinite loop */
if (argc >= 2) {
domainId = atoi(argv[1]);
}
if (argc >= 3) {
sample_count = atoi(argv[2]);
}
/* Uncomment this to turn on additional logging
NDDS_Config_Logger_set_verbosity_by_category(
NDDS_Config_Logger_get_instance(),
NDDS_CONFIG_LOG_CATEGORY_API,
NDDS_CONFIG_LOG_VERBOSITY_STATUS_ALL);
*/
return subscriber_main(domainId, sample_count);
}
#endif
#ifdef RTI_VX653
const unsigned char* __ctype = NULL;
void usrAppInit ()
{
#ifdef USER_APPL_INIT
USER_APPL_INIT; /* for backwards compatibility */
#endif
/* add application specific code here */
taskSpawn("sub", RTI_OSAPI_THREAD_PRIORITY_NORMAL, 0x8, 0x150000, (FUNCPTR)subscriber_main, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
}
#endif
| c |
rticonnextdds-examples | data/projects/rticonnextdds-examples/using_typecodes/c++03/msg_publisher.cxx | /*******************************************************************************
(c) 2005-2015 Copyright, Real-Time Innovations, Inc. All rights reserved.
RTI grants Licensee a license to use, modify, compile, and create derivative
works of the Software. Licensee has the right to distribute object form only
for use with RTI products. The Software is provided "as is", with no warranty
of any type, including any warranty for fitness for any purpose. RTI is under
no obligation to maintain or support the Software. RTI shall not be liable for
any incidental or consequential damages arising out of the use or inability to
use the software.
******************************************************************************/
#include <cstdlib>
#include <iostream>
#include <dds/dds.hpp>
#include "msg.hpp"
using namespace dds::core;
using namespace rti::core::policy;
using namespace dds::domain;
using namespace dds::domain::qos;
using namespace dds::topic;
using namespace dds::pub;
void publisher_main(int domain_id, int sample_count)
{
// Retrieve the Participant QoS, from USER_QOS_PROFILES.xml
DomainParticipantQos participant_qos = QosProvider::Default()->
participant_qos();
// If you want to change the Participant's QoS programmatically rather than
// using the XML file, uncomment the following lines.
// participant_qos << DomainParticipantResourceLimits().
// type_code_max_serialized_length(3070);
// Create a DomainParticipant.
DomainParticipant participant(domain_id, participant_qos);
// Create a Topic -- and automatically register the type
Topic<msg> topic(participant, "Example msg");
// Create a DataWriter with default Qos (Publisher created in-line)
DataWriter<msg> writer(Publisher(participant), topic);
msg sample;
for (int count = 0; count < sample_count || sample_count == 0; count++) {
// Update sample and send it.
std::cout << "Writing msg, count " << count << std::endl;
sample.count(count);
writer.write(sample);
rti::util::sleep(Duration(4));
}
}
int main(int argc, char *argv[])
{
int domain_id = 0;
int sample_count = 0; // Infinite loop
if (argc >= 2) {
domain_id = atoi(argv[1]);
}
if (argc >= 3) {
sample_count = atoi(argv[2]);
}
// To turn on additional logging, include <rti/config/Logger.hpp> and
// uncomment the following line:
// rti::config::Logger::instance().verbosity(rti::config::Verbosity::STATUS_ALL);
try {
publisher_main(domain_id, sample_count);
} catch (const std::exception& ex) {
// This will catch DDS exceptions
std::cerr << "Exception in publisher_main: " << ex.what() << std::endl;
return -1;
}
return 0;
}
| cxx |
rticonnextdds-examples | data/projects/rticonnextdds-examples/using_typecodes/c++03/msg_subscriber.cxx | /*******************************************************************************
(c) 2005-2015 Copyright, Real-Time Innovations, Inc. All rights reserved.
RTI grants Licensee a license to use, modify, compile, and create derivative
works of the Software. Licensee has the right to distribute object form only
for use with RTI products. The Software is provided "as is", with no warranty
of any type, including any warranty for fitness for any purpose. RTI is under
no obligation to maintain or support the Software. RTI shall not be liable for
any incidental or consequential damages arising out of the use or inability to
use the software.
******************************************************************************/
#include <cstdlib>
#include <algorithm>
#include <iostream>
#include <iomanip>
#include <dds/dds.hpp>
#include <rti/core/ListenerBinder.hpp>
#include "msg.hpp"
using namespace dds::core;
using namespace rti::core::policy;
using namespace dds::domain;
using namespace dds::domain::qos;
using namespace dds::topic;
using namespace dds::sub;
class BuiltinPublicationListener :
public NoOpDataReaderListener<PublicationBuiltinTopicData> {
public:
void on_data_available(DataReader<PublicationBuiltinTopicData>& reader)
{
// Take all samples
LoanedSamples<PublicationBuiltinTopicData> samples = reader.take();
typedef LoanedSamples<PublicationBuiltinTopicData>::iterator SampleIter;
for (SampleIter sample_it = samples.begin();
sample_it != samples.end();
sample_it++) {
if (sample_it->info().valid()){
const PublicationBuiltinTopicData& data = sample_it->data();
const BuiltinTopicKey& partKey = data.participant_key();
const BuiltinTopicKey& key = sample_it->data().key();
std::cout << std::hex << std::setw(8) << std::setfill('0');
std::cout << "-----" << std::endl
<< "Found topic \"" << data.topic_name() << "\""
<< std::endl
<< "participant: " << partKey.value()[0]
<< partKey.value()[1] << partKey.value()[2]
<< std::endl
<< "datawriter: " << key.value()[0]
<< key.value()[1] << key.value()[2] << std::endl
<< "type:" << std::endl;
if (!data->type().is_set()) {
std::cout << "No type received, perhaps increase "
<< "type_code_max_serialized_length?"
<< std::endl;
} else {
// Using the type propagated we print the data type
// with print_idl()
rti::core::xtypes::print_idl(data->type().get(), 2);
}
}
}
}
};
void subscriber_main(int domain_id, int sample_count)
{
// Retrieve the Participant QoS, from USER_QOS_PROFILES.xml
DomainParticipantQos participant_qos = QosProvider::Default()->
participant_qos();
// If you want to change the Participant's QoS programmatically rather than
// using the XML file, uncomment the following lines.
// participant_qos << DomainParticipantResourceLimits().
// type_code_max_serialized_length(3070);
// Create a DomainParticipant.
DomainParticipant participant(domain_id, participant_qos);
// First get the builtin subscriber.
Subscriber builtin_subscriber = dds::sub::builtin_subscriber(participant);
// Then get builtin subscriber's DataReader for DataWriters.
DataReader<PublicationBuiltinTopicData> publication_reader =
rti::sub::find_datareader_by_topic_name< DataReader<PublicationBuiltinTopicData> >(
builtin_subscriber,
dds::topic::publication_topic_name());
// Install our listener using ListenerBinder, a RAII that will take care
// of setting it to NULL and deleting it.
rti::core::ListenerBinder< DataReader<PublicationBuiltinTopicData> >
publication_listener = rti::core::bind_and_manage_listener(
publication_reader,
new BuiltinPublicationListener,
dds::core::status::StatusMask::data_available());
for (int count = 0; sample_count == 0 || count < sample_count; ++count) {
rti::util::sleep(Duration(1));
}
}
int main(int argc, char *argv[])
{
int domain_id = 0;
int sample_count = 0; // Infinite loop
if (argc >= 2) {
domain_id = atoi(argv[1]);
}
if (argc >= 3) {
sample_count = atoi(argv[2]);
}
// To turn on additional logging, include <rti/config/Logger.hpp> and
// uncomment the following line:
// rti::config::Logger::instance().verbosity(rti::config::Verbosity::STATUS_ALL);
try {
subscriber_main(domain_id, sample_count);
} catch (const std::exception& ex) {
// This will catch DDS exceptions
std::cerr << "Exception in subscriber_main: " << ex.what() << std::endl;
return -1;
}
return 0;
}
| cxx |
rticonnextdds-examples | data/projects/rticonnextdds-examples/builtin_topics/c++/msg_publisher.cxx | /*******************************************************************************
(c) 2005-2014 Copyright, Real-Time Innovations, Inc. All rights reserved.
RTI grants Licensee a license to use, modify, compile, and create derivative
works of the Software. Licensee has the right to distribute object form only
for use with RTI products. The Software is provided "as is", with no warranty
of any type, including any warranty for fitness for any purpose. RTI is under
no obligation to maintain or support the Software. RTI shall not be liable for
any incidental or consequential damages arising out of the use or inability to
use the software.
******************************************************************************/
/* msg_publisher.cxx
A publication of data of type msg
This file is derived from code automatically generated by the rtiddsgen
command:
rtiddsgen -language C++ -example <arch> msg.idl
Example publication of type msg automatically generated by
'rtiddsgen'. To test them follow these steps:
(1) Compile this file and the example subscription.
(2) Start the subscription on the same domain used for RTI Data Distribution
with the command
objs/<arch>/msg_subscriber <domain_id> <sample_count>
(3) Start the publication on the same domain used for RTI Data Distribution
with the command
objs/<arch>/msg_publisher <domain_id> <sample_count>
(4) [Optional] Specify the list of discovery initial peers and
multicast receive addresses via an environment variable or a file
(in the current working directory) called NDDS_DISCOVERY_PEERS.
You can run any number of publishers and subscribers programs, and can
add and remove them dynamically from the domain.
Example:
To run the example application on domain <domain_id>:
On Unix:
objs/<arch>/msg_publisher <domain_id>
objs/<arch>/msg_subscriber <domain_id>
On Windows:
objs\<arch>\msg_publisher <domain_id>
objs\<arch>\msg_subscriber <domain_id>
modification history
------------ -------
* Add code to store keys of authorized participants
* Define listeners for builtin topics, which get called when
we find a new participant or reader.
* Create disabled participant to ensure our listeners are installed
before anything is processed
* Install listeners
* Uncommented the code that authorized a subscriber that belonged to an authorized participant
* Changed ih to be an array of 6 ints instead of 4. An instance handle is the size of 6 ints.
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "ndds/ndds_cpp.h"
#include "msg.h"
#include "msgSupport.h"
/* Authorization string. */
const char *auth = "password";
/* The builtin subscriber sets participant_qos.user_data and
so we set up listeners for the builtin
DataReaders to access these fields.
*/
class BuiltinParticipantListener : public DDSDataReaderListener {
public:
virtual void on_data_available(DDSDataReader *reader);
};
/* This gets called when a participant has been discovered */
void BuiltinParticipantListener::on_data_available(DDSDataReader *reader)
{
DDSParticipantBuiltinTopicDataDataReader *builtin_reader =
(DDSParticipantBuiltinTopicDataDataReader*) reader;
DDS_ParticipantBuiltinTopicDataSeq data_seq;
DDS_SampleInfoSeq info_seq;
DDS_ReturnCode_t retcode;
char *participant_data;
/* We only process newly seen participants */
retcode = builtin_reader->take(data_seq, info_seq, DDS_LENGTH_UNLIMITED,
DDS_ANY_SAMPLE_STATE, DDS_NEW_VIEW_STATE,
DDS_ANY_INSTANCE_STATE);
/* This happens when we get announcements from participants we
* already know about
*/
if (retcode == DDS_RETCODE_NO_DATA)
return;
if (retcode != DDS_RETCODE_OK) {
printf("***Error: failed to access data from the built-in reader\n");
return;
}
for(int i = 0; i < data_seq.length(); ++i) {
if (!info_seq[i].valid_data)
continue;
participant_data = "nil";
bool is_auth = false;
/* see if there is any participant_data */
if (data_seq[i].user_data.value.length() != 0) {
/* This sequence is guaranteed to be contiguous */
participant_data = (char*)&data_seq[i].user_data.value[0];
is_auth = (strcmp(participant_data, auth) == 0);
}
printf("Built-in Reader: found participant \n");
printf("\tkey->'%08x %08x %08x'\n\tuser_data->'%s'\n",
data_seq[i].key.value[0],
data_seq[i].key.value[1],
data_seq[i].key.value[2],
participant_data);
int ih[6];
memcpy(ih, &info_seq[i].instance_handle,
sizeof(info_seq[i].instance_handle));
printf("instance_handle: %08x%08x %08x%08x %08x%08x \n",
ih[0], ih[1], ih[2], ih[3], ih[4], ih[5]);
if (!is_auth) {
printf("Bad authorization, ignoring participant\n");
DDSDomainParticipant *participant =
reader->get_subscriber()->get_participant();
retcode = participant->ignore_participant(
info_seq[i].instance_handle);
if (retcode != DDS_RETCODE_OK) {
printf("error ignoring participant: %d\n", retcode);
return;
}
}
}
builtin_reader->return_loan(data_seq, info_seq);
}
class BuiltinSubscriberListener : public DDSDataReaderListener {
public:
virtual void on_data_available(DDSDataReader* reader);
};
/* This gets called when a new subscriber has been discovered */
void BuiltinSubscriberListener::on_data_available(DDSDataReader *reader)
{
DDSSubscriptionBuiltinTopicDataDataReader *builtin_reader =
(DDSSubscriptionBuiltinTopicDataDataReader*) reader;
DDS_SubscriptionBuiltinTopicDataSeq data_seq;
DDS_SampleInfoSeq info_seq;
DDS_ReturnCode_t retcode;
/* We only process newly seen subscribers */
retcode = builtin_reader->take(data_seq, info_seq, DDS_LENGTH_UNLIMITED,
DDS_ANY_SAMPLE_STATE, DDS_NEW_VIEW_STATE,
DDS_ANY_INSTANCE_STATE);
if (retcode == DDS_RETCODE_NO_DATA)
return;
if (retcode != DDS_RETCODE_OK) {
printf("***Error: failed to access data from the built-in reader\n");
return;
}
for (int i = 0; i < data_seq.length(); ++i) {
if (!info_seq[i].valid_data)
continue;
printf("Built-in Reader: found subscriber \n");
printf("\tparticipant_key->'%08x %08x %08x'\n",
data_seq[i].participant_key.value[0],
data_seq[i].participant_key.value[1],
data_seq[i].participant_key.value[2]);
printf("\tkey->'%08x %08x %08x'\n",
data_seq[i].key.value[0],
data_seq[i].key.value[1],
data_seq[i].key.value[2]);
int ih[6];
memcpy(ih, &info_seq[i].instance_handle,
sizeof(info_seq[i].instance_handle));
printf("instance_handle: %08x%08x %08x%08x %08x%08x \n",
ih[0], ih[1], ih[2], ih[3], ih[4], ih[5]);
}
builtin_reader->return_loan(data_seq, info_seq);
}
/* End changes for Builtin_Topics */
/* Delete all entities */
static int publisher_shutdown(
DDSDomainParticipant *participant)
{
DDS_ReturnCode_t retcode;
int status = 0;
if (participant != NULL) {
retcode = participant->delete_contained_entities();
if (retcode != DDS_RETCODE_OK) {
printf("delete_contained_entities error %d\n", retcode);
status = -1;
}
retcode = DDSTheParticipantFactory->delete_participant(participant);
if (retcode != DDS_RETCODE_OK) {
printf("delete_participant error %d\n", retcode);
status = -1;
}
}
/* RTI Data Distribution Service provides finalize_instance() method for
people who want to release memory used by the participant factory
singleton. Uncomment the following block of code for clean destruction of
the participant factory singleton. */
/*
retcode = DDSDomainParticipantFactory::finalize_instance();
if (retcode != DDS_RETCODE_OK) {
printf("finalize_instance error %d\n", retcode);
status = -1;
}
*/
return status;
}
extern "C" int publisher_main(int domainId, int sample_count)
{
DDSDomainParticipant *participant = NULL;
DDSPublisher *publisher = NULL;
DDSTopic *topic = NULL;
DDSDataWriter *writer = NULL;
msgDataWriter * msg_writer = NULL;
msg *instance = NULL;
DDS_ReturnCode_t retcode;
DDS_InstanceHandle_t instance_handle = DDS_HANDLE_NIL;
const char *type_name = NULL;
int count = 0;
DDS_Duration_t send_period = {1,0};
/* By default, the participant is enabled upon construction.
* At that time our listeners for the builtin topics have not
* been installed, so we disable the participant until we
* set up the listeners. This is done by default in the
* USER_QOS_PROFILES.xml
* file. If you want to do it programmatically, just uncomment
* the following code.
*/
/*
DDS_DomainParticipantFactoryQos factory_qos;
retcode = DDSTheParticipantFactory->get_qos(factory_qos);
if (retcode != DDS_RETCODE_OK) {
printf("Cannot get factory Qos for domain participant\n");
return -1;
}
factory_qos.entity_factory.autoenable_created_entities = DDS_BOOLEAN_FALSE;
switch(DDSTheParticipantFactory->set_qos(factory_qos)) {
case DDS_RETCODE_OK:
break;
case DDS_RETCODE_IMMUTABLE_POLICY: {
printf("Cannot set factory Qos due to IMMUTABLE_POLICY ");
printf("for domain participant\n");
return -1;
break;
}
case DDS_RETCODE_INCONSISTENT_POLICY: {
printf("Cannot set factory Qos due to INCONSISTENT_POLICY for ");
printf("domain participant\n");
return -1;
break;
}
default: {
printf("Cannot set factory Qos for unknown reason for ");
printf("domain participant\n");
return -1;
break;
}
}
*/
DDS_DomainParticipantQos participant_qos;
retcode = DDSTheParticipantFactory->get_default_participant_qos(
participant_qos);
if (retcode != DDS_RETCODE_OK) {
printf("get_default_participant_qos error\n");
return -1;
}
/* If you want to change the Participant's QoS programmatically rather
* than using the XML file, you will need to uncomment the following line.
*/
/*
participant_qos.resource_limits.participant_user_data_max_length = 1024;
*/
/* To customize participant QoS, use
the configuration file USER_QOS_PROFILES.xml */
participant = DDSTheParticipantFactory->create_participant(
domainId, participant_qos,
NULL /* listener */, DDS_STATUS_MASK_NONE);
if (participant == NULL) {
printf("create_participant error\n");
publisher_shutdown(participant);
return -1;
}
/* Start changes for Builtin_Topics */
/* Installing listeners for the builtin topics requires several steps */
/* First get the builtin subscriber */
DDSSubscriber *builtin_subscriber = participant->get_builtin_subscriber();
if (builtin_subscriber == NULL) {
printf("***Error: failed to create builtin subscriber\n");
return 0;
}
/* Then get builtin subscriber's datareader for participants
The type name is a bit hairy, but can be read right to left:
DDSParticipantBuiltinTopicDataDataReader is a DataReader for
BuiltinTopicData concerning a discovered
Participant
*/
DDSParticipantBuiltinTopicDataDataReader *builtin_participant_datareader =
(DDSParticipantBuiltinTopicDataDataReader*)
builtin_subscriber->lookup_datareader(DDS_PARTICIPANT_TOPIC_NAME);
if (builtin_participant_datareader == NULL) {
printf("***Error: failed to create builtin participant data reader\n");
return 0;
}
/* Install our listener */
BuiltinParticipantListener *builtin_participant_listener =
new BuiltinParticipantListener();
builtin_participant_datareader->set_listener(builtin_participant_listener,
DDS_DATA_AVAILABLE_STATUS);
/* Get builtin subscriber's datareader for subscribers */
DDSSubscriptionBuiltinTopicDataDataReader *builtin_subscription_datareader =
(DDSSubscriptionBuiltinTopicDataDataReader*)
builtin_subscriber->lookup_datareader(DDS_SUBSCRIPTION_TOPIC_NAME);
if (builtin_subscription_datareader == NULL) {
printf("***Error: failed to create builtin subscription data reader\n");
return 0;
}
/* Install our listener */
BuiltinSubscriberListener *builtin_subscriber_listener =
new BuiltinSubscriberListener();
builtin_subscription_datareader->set_listener(builtin_subscriber_listener,
DDS_DATA_AVAILABLE_STATUS);
/* Done! All the listeners are installed, so we can enable the
* participant now.
*/
if (participant->enable() != DDS_RETCODE_OK) {
printf("***Error: Failed to Enable Participant\n");
return 0;
}
/* End changes for Builtin_Topics */
/* To customize publisher QoS, use
the configuration file USER_QOS_PROFILES.xml */
publisher = participant->create_publisher(
DDS_PUBLISHER_QOS_DEFAULT, NULL /* listener */, DDS_STATUS_MASK_NONE);
if (publisher == NULL) {
printf("create_publisher error\n");
publisher_shutdown(participant);
return -1;
}
/* Register the type before creating the topic */
type_name = msgTypeSupport::get_type_name();
retcode = msgTypeSupport::register_type(
participant, type_name);
if (retcode != DDS_RETCODE_OK) {
printf("register_type error %d\n", retcode);
publisher_shutdown(participant);
return -1;
}
/* To customize topic QoS, use
the configuration file USER_QOS_PROFILES.xml */
topic = participant->create_topic(
"Example msg",
type_name, DDS_TOPIC_QOS_DEFAULT, NULL /* listener */,
DDS_STATUS_MASK_NONE);
if (topic == NULL) {
printf("create_topic error\n");
publisher_shutdown(participant);
return -1;
}
/* To customize data writer QoS, use
the configuration file USER_QOS_PROFILES.xml */
writer = publisher->create_datawriter(
topic, DDS_DATAWRITER_QOS_DEFAULT, NULL /* listener */,
DDS_STATUS_MASK_NONE);
if (writer == NULL) {
printf("create_datawriter error\n");
publisher_shutdown(participant);
return -1;
}
msg_writer = msgDataWriter::narrow(writer);
if (msg_writer == NULL) {
printf("DataWriter narrow error\n");
publisher_shutdown(participant);
return -1;
}
/* Create data sample for writing */
instance = msgTypeSupport::create_data();
if (instance == NULL) {
printf("msgTypeSupport::create_data error\n");
publisher_shutdown(participant);
return -1;
}
/* For data type that has key, if the same instance is going to be
written multiple times, initialize the key here
and register the keyed instance prior to writing */
/*
instance_handle = msg_writer->register_instance(*instance);
*/
/* Main loop */
for (count=0; (sample_count == 0) || (count < sample_count); ++count) {
NDDSUtility::sleep(send_period);
printf("Writing msg, count %d\n", count);
/* Modify the data to be sent here */
instance->x = count;
retcode = msg_writer->write(*instance, instance_handle);
if (retcode != DDS_RETCODE_OK) {
printf("write error %d\n", retcode);
}
}
/*
retcode = msg_writer->unregister_instance(
*instance, instance_handle);
if (retcode != DDS_RETCODE_OK) {
printf("unregister instance error %d\n", retcode);
}
*/
/* Delete data sample */
retcode = msgTypeSupport::delete_data(instance);
if (retcode != DDS_RETCODE_OK) {
printf("msgTypeSupport::delete_data error %d\n", retcode);
}
/* Delete all entities */
return publisher_shutdown(participant);
}
int main(int argc, char *argv[])
{
int domain_id = 0;
int sample_count = 0; /* infinite loop */
if (argc >= 2) {
domain_id = atoi(argv[1]);
}
if (argc >= 3) {
sample_count = atoi(argv[2]);
}
/* Uncomment this to turn on additional logging
NDDSConfigLogger::get_instance()->
set_verbosity_by_category(NDDS_CONFIG_LOG_CATEGORY_API,
NDDS_CONFIG_LOG_VERBOSITY_STATUS_ALL);
*/
return publisher_main(domain_id, sample_count);
}
| cxx |
rticonnextdds-examples | data/projects/rticonnextdds-examples/builtin_topics/c++/msg_subscriber.cxx | /*******************************************************************************
(c) 2005-2014 Copyright, Real-Time Innovations, Inc. All rights reserved.
RTI grants Licensee a license to use, modify, compile, and create derivative
works of the Software. Licensee has the right to distribute object form only
for use with RTI products. The Software is provided "as is", with no warranty
of any type, including any warranty for fitness for any purpose. RTI is under
no obligation to maintain or support the Software. RTI shall not be liable for
any incidental or consequential damages arising out of the use or inability to
use the software.
******************************************************************************/
/* msg_subscriber.cxx
A subscription example
This file is derived from code automatically generated by the rtiddsgen
command:
rtiddsgen -language C++ -example <arch> msg.idl
Example subscription of type msg automatically generated by
'rtiddsgen'. To test them follow these steps:
(1) Compile this file and the example publication.
(2) Start the subscription on the same domain used for RTI Data Distribution
Service with the command
objs/<arch>/msg_subscriber <domain_id> <sample_count>
(3) Start the publication on the same domain used for RTI Data Distribution
with the command
objs/<arch>/msg_publisher <domain_id> <sample_count>
(4) [Optional] Specify the list of discovery initial peers and
multicast receive addresses via an environment variable or a file
(in the current working directory) called NDDS_DISCOVERY_PEERS.
You can run any number of publishers and subscribers programs, and can
add and remove them dynamically from the domain.
Example:
To run the example application on domain <domain_id>:
On Unix:
objs/<arch>/msg_publisher <domain_id>
objs/<arch>/msg_subscriber <domain_id>
On Windows:
objs\<arch>\msg_publisher <domain_id>
objs\<arch>\msg_subscriber <domain_id>
modification history
------------ -------
* Set user_data QoS fields in participant and datareader with
strings given on command line
* Updated for 4.1 to 4.2: participant_index changed to participant_id
* Refactor and remove unused variables and classes
* Fix not including null char in participant user_data password.
*/
#include <stdio.h>
#include <stdlib.h>
#include "msg.h"
#include "msgSupport.h"
#include "ndds/ndds_cpp.h"
class msgListener : public DDSDataReaderListener {
public:
virtual void on_requested_deadline_missed(
DDSDataReader* /*reader*/,
const DDS_RequestedDeadlineMissedStatus& /*status*/) {}
virtual void on_requested_incompatible_qos(
DDSDataReader* /*reader*/,
const DDS_RequestedIncompatibleQosStatus& /*status*/) {}
virtual void on_sample_rejected(
DDSDataReader* /*reader*/,
const DDS_SampleRejectedStatus& /*status*/) {}
virtual void on_liveliness_changed(
DDSDataReader* /*reader*/,
const DDS_LivelinessChangedStatus& /*status*/) {}
virtual void on_sample_lost(
DDSDataReader* /*reader*/,
const DDS_SampleLostStatus& /*status*/) {}
virtual void on_subscription_matched(
DDSDataReader* /*reader*/,
const DDS_SubscriptionMatchedStatus& /*status*/) {}
virtual void on_data_available(DDSDataReader* reader);
};
void msgListener::on_data_available(DDSDataReader* reader)
{
msgDataReader *msg_reader = NULL;
msgSeq data_seq;
DDS_SampleInfoSeq info_seq;
DDS_ReturnCode_t retcode;
int i;
msg_reader = msgDataReader::narrow(reader);
if (msg_reader == NULL) {
printf("DataReader narrow error\n");
return;
}
retcode = msg_reader->take(
data_seq, info_seq, DDS_LENGTH_UNLIMITED,
DDS_ANY_SAMPLE_STATE, DDS_ANY_VIEW_STATE, DDS_ANY_INSTANCE_STATE);
if (retcode == DDS_RETCODE_NO_DATA) {
return;
} else if (retcode != DDS_RETCODE_OK) {
printf("take error %d\n", retcode);
return;
}
for (i = 0; i < data_seq.length(); ++i) {
if (info_seq[i].valid_data) {
msgTypeSupport::print_data(&data_seq[i]);
}
}
retcode = msg_reader->return_loan(data_seq, info_seq);
if (retcode != DDS_RETCODE_OK) {
printf("return loan error %d\n", retcode);
}
}
/* Delete all entities */
static int subscriber_shutdown(
DDSDomainParticipant *participant)
{
DDS_ReturnCode_t retcode;
int status = 0;
if (participant != NULL) {
retcode = participant->delete_contained_entities();
if (retcode != DDS_RETCODE_OK) {
printf("delete_contained_entities error %d\n", retcode);
status = -1;
}
retcode = DDSTheParticipantFactory->delete_participant(participant);
if (retcode != DDS_RETCODE_OK) {
printf("delete_participant error %d\n", retcode);
status = -1;
}
}
/* RTI Data Distribution Service provides finalize_instance() method for
people who want to release memory used by the participant factory
singleton. Uncomment the following block of code for clean destruction of
the participant factory singleton. */
/*
retcode = DDSDomainParticipantFactory::finalize_instance();
if (retcode != DDS_RETCODE_OK) {
printf("finalize_instance error %d\n", retcode);
status = -1;
}
*/
return status;
}
extern "C" int subscriber_main(int domain_id, int sample_count,
char *participant_auth)
{
DDSDomainParticipant *participant = NULL;
DDSSubscriber *subscriber = NULL;
DDSTopic *topic = NULL;
msgListener *reader_listener = NULL;
DDSDataReader *reader = NULL;
DDS_ReturnCode_t retcode;
const char *type_name = NULL;
int count = 0;
DDS_Duration_t receive_period = {1,0};
int status = 0;
/* Start changes for Builtin_Topics */
/* Set user_data qos field for participant */
/* Get default participant QoS to customize */
DDS_DomainParticipantQos participant_qos;
retcode = DDSTheParticipantFactory->get_default_participant_qos(
participant_qos);
if (retcode != DDS_RETCODE_OK) {
printf("get_default_participant_qos error\n");
return -1;
}
/* The maximum length for USER_DATA QoS field is set by default
to 256 bytes. To increase it programmatically uncomment the
following line of code. */
/*
participant_qos.resource_limits.participant_user_data_max_length = 1024;
*/
/* user_data is opaque to DDS, so we include trailing \0 for string */
int len = strlen(participant_auth) + 1;
int max = participant_qos.resource_limits.participant_user_data_max_length;
if (len > max) {
printf("error, participant user_data exceeds resource limits\n");
} else {
/* DDS_Octet is defined to be 8 bits. If chars are not 8 bits
* on your system, this will not work.
*/
participant_qos.user_data.value.from_array(
reinterpret_cast<const DDS_Octet*>(participant_auth), len);
}
/* To create participant with default QoS, use DDS_PARTICIPANT_QOS_DEFAULT
instead of participant_qos */
participant = DDSTheParticipantFactory->create_participant(
domain_id, participant_qos,
NULL /* listener */, DDS_STATUS_MASK_NONE);
if (participant == NULL) {
printf("create_participant error\n");
subscriber_shutdown(participant);
return -1;
}
/* The participant is disabled by default. We enable it now */
if (participant->enable() != DDS_RETCODE_OK) {
printf("***Error: Failed to Enable Participant\n");
return 0;
}
/* To customize the subscriber QoS, use
the configuration file USER_QOS_PROFILES.xml */
subscriber = participant->create_subscriber(
DDS_SUBSCRIBER_QOS_DEFAULT, NULL /* listener */, DDS_STATUS_MASK_NONE);
if (subscriber == NULL) {
printf("create_subscriber error\n");
subscriber_shutdown(participant);
return -1;
}
/* Register the type before creating the topic */
type_name = msgTypeSupport::get_type_name();
retcode = msgTypeSupport::register_type(
participant, type_name);
if (retcode != DDS_RETCODE_OK) {
printf("register_type error %d\n", retcode);
subscriber_shutdown(participant);
return -1;
}
/* To customize topic QoS, use
the configuration file USER_QOS_PROFILES.xml */
topic = participant->create_topic(
"Example msg",
type_name, DDS_TOPIC_QOS_DEFAULT, NULL /* listener */,
DDS_STATUS_MASK_NONE);
if (topic == NULL) {
printf("create_topic error\n");
subscriber_shutdown(participant);
return -1;
}
/* Create a data reader listener */
reader_listener = new msgListener();
/* To customize data reader QoS, use
the configuration file USER_QOS_PROFILES.xml */
reader = subscriber->create_datareader(
topic, DDS_DATAREADER_QOS_DEFAULT, reader_listener,
DDS_STATUS_MASK_ALL);
if (reader == NULL) {
printf("create_datareader error\n");
subscriber_shutdown(participant);
delete reader_listener;
return -1;
}
/* Main loop */
for (count=0; (sample_count == 0) || (count < sample_count); ++count) {
NDDSUtility::sleep(receive_period);
}
/* Delete all entities */
status = subscriber_shutdown(participant);
delete reader_listener;
return status;
}
int main(int argc, char *argv[])
{
int domain_id = 0;
int sample_count = 0; /* infinite loop */
char *participant_auth = "password";
if (argc >= 2) {
domain_id = atoi(argv[1]);
}
if (argc >= 3) {
sample_count = atoi(argv[2]);
}
if (argc >= 4) {
participant_auth = argv[3];
}
/* Uncomment this to turn on additional logging
NDDSConfigLogger::get_instance()->
set_verbosity_by_category(NDDS_CONFIG_LOG_CATEGORY_API,
NDDS_CONFIG_LOG_VERBOSITY_STATUS_ALL);
*/
return subscriber_main(domain_id, sample_count, participant_auth);
}
| cxx |
rticonnextdds-examples | data/projects/rticonnextdds-examples/builtin_topics/c/msg_publisher.c | /*******************************************************************************
(c) 2005-2014 Copyright, Real-Time Innovations, Inc. All rights reserved.
RTI grants Licensee a license to use, modify, compile, and create derivative
works of the Software. Licensee has the right to distribute object form only
for use with RTI products. The Software is provided "as is", with no warranty
of any type, including any warranty for fitness for any purpose. RTI is under
no obligation to maintain or support the Software. RTI shall not be liable for
any incidental or consequential damages arising out of the use or inability to
use the software.
******************************************************************************/
/* msg_publisher.c
A publication of data of type msg
This file is derived from code automatically generated by the rtiddsgen
command:
rtiddsgen -language C -example <arch> msg.idl
Example publication of type msg automatically generated by
'rtiddsgen'. To test them follow these steps:
(1) Compile this file and the example subscription.
(2) Start the subscription on the same domain used for RTI Data Distribution
Service with the command
objs/<arch>/msg_subscriber <domain_id> <sample_count>
(3) Start the publication on the same domain used for RTI Data Distribution
Service with the command
objs/<arch>/msg_publisher <domain_id> <sample_count>
(4) [Optional] Specify the list of discovery initial peers and
multicast receive addresses via an environment variable or a file
(in the current working directory) called NDDS_DISCOVERY_PEERS.
You can run any number of publishers and subscribers programs, and can
add and remove them dynamically from the domain.
Example:
To run the example application on domain <domain_id>:
On Unix:
objs/<arch>/msg_publisher <domain_id>
objs/<arch>/msg_subscriber <domain_id>
On Windows:
objs\<arch>\msg_publisher <domain_id>
objs\<arch>\msg_subscriber <domain_id>
modification history
------------ -------
* Add code to store keys of authorized participants
* Define listeners for builtin topics, which get called when
we find a new participant or reader.
* Create disabled participant to ensure our listeners are installed
before anything is processed
* Install listeners
* Do not ignore subscriber since it is a bad security practice.
* Print key and instance_handle info.
*/
#include <stdio.h>
#include <stdlib.h>
#include "ndds/ndds_c.h"
#include "msg.h"
#include "msgSupport.h"
/* Authorization string. */
const char *auth = "password";
/*
* The builtin subscriber sets participant_qos.user_data and
* so we set up listeners for the builtin
* DataReaders to access these fields.
*/
/* This gets called when a participant has been discovered */
void BuiltinParticipantListener_on_data_available(void* listener_data,
DDS_DataReader* reader) {
DDS_ParticipantBuiltinTopicDataDataReader *builtin_reader = NULL;
struct DDS_ParticipantBuiltinTopicDataSeq data_seq =
DDS_SEQUENCE_INITIALIZER;
struct DDS_SampleInfoSeq info_seq = DDS_SEQUENCE_INITIALIZER;
DDS_ReturnCode_t retcode;
int i;
int len;
int ih[6];
builtin_reader = DDS_ParticipantBuiltinTopicDataDataReader_narrow(reader);
/* We only process newly seen participants */
retcode = DDS_ParticipantBuiltinTopicDataDataReader_take(builtin_reader,
&data_seq, &info_seq, DDS_LENGTH_UNLIMITED, DDS_ANY_SAMPLE_STATE,
DDS_NEW_VIEW_STATE, DDS_ANY_INSTANCE_STATE);
/*
* This happens when we get announcements from participants we
* already know about
*/
if (retcode == DDS_RETCODE_NO_DATA)
return;
if (retcode != DDS_RETCODE_OK) {
printf("***Error: failed to access data from the built-in reader\n");
return;
}
len = DDS_ParticipantBuiltinTopicDataSeq_get_length(&data_seq);
for (i = 0; i < len; ++i) {
struct DDS_SampleInfo* info = NULL;
struct DDS_ParticipantBuiltinTopicData* data = NULL;
char* participant_data = "nil";
int is_auth = 0;
info = DDS_SampleInfoSeq_get_reference(&info_seq, i);
data = DDS_ParticipantBuiltinTopicDataSeq_get_reference(&data_seq, i);
if (!info->valid_data)
continue;
/* see if there is any participant_data */
if (DDS_OctetSeq_get_length(&data->user_data.value) != 0) {
/* This sequence is guaranteed to be contiguous */
participant_data = (char*) (DDS_OctetSeq_get_reference(
&data->user_data.value, 0));
is_auth = (strcmp(participant_data, auth) == 0);
}
printf("Built-in Reader: found participant \n");
printf("\tkey->'%08x%08x%08x'\n\tuser_data->'%s'\n",
data->key.value[0], data->key.value[1], data->key.value[2],
participant_data);
memcpy(ih, &info->instance_handle,
sizeof(info->instance_handle));
printf("instance_handle: %08x%08x %08x%08x %08x%08x \n",
ih[0], ih[1], ih[2], ih[3], ih[4], ih[5]);
/* Ignore unauthorized subscribers */
if (!is_auth) {
/* Get the associated participant... */
DDS_DomainParticipant *participant = NULL;
DDS_Subscriber *subscriber = NULL;
subscriber = DDS_DataReader_get_subscriber(reader);
participant = DDS_Subscriber_get_participant(subscriber);
printf("Bad authorization, ignoring participant\n");
/* Ignore the remote reader */
DDS_DomainParticipant_ignore_participant(participant,
&info->instance_handle);
}
}
retcode = DDS_ParticipantBuiltinTopicDataDataReader_return_loan(
builtin_reader, &data_seq, &info_seq);
if (retcode != DDS_RETCODE_OK) {
printf("return loan error %d\n", retcode);
}
}
/* This gets called when a new subscriber has been discovered */
void BuiltinSubscriberListener_on_data_available(void* listener_data,
DDS_DataReader* reader) {
DDS_SubscriptionBuiltinTopicDataDataReader *builtin_reader = NULL;
struct DDS_SubscriptionBuiltinTopicDataSeq data_seq =
DDS_SEQUENCE_INITIALIZER;
struct DDS_SampleInfoSeq info_seq = DDS_SEQUENCE_INITIALIZER;
DDS_ReturnCode_t retcode;
int i;
int len;
int ih[6];
builtin_reader = DDS_SubscriptionBuiltinTopicDataDataReader_narrow(reader);
/* We only process newly seen subscribers */
retcode = DDS_SubscriptionBuiltinTopicDataDataReader_take(builtin_reader,
&data_seq, &info_seq, DDS_LENGTH_UNLIMITED, DDS_ANY_SAMPLE_STATE,
DDS_NEW_VIEW_STATE, DDS_ANY_INSTANCE_STATE);
if (retcode == DDS_RETCODE_NO_DATA)
return;
if (retcode != DDS_RETCODE_OK) {
printf("***Error: failed to access data from the built-in reader\n");
return;
}
len = DDS_SubscriptionBuiltinTopicDataSeq_get_length(&data_seq);
for (i = 0; i < len; ++i) {
struct DDS_SampleInfo* info = NULL;
struct DDS_SubscriptionBuiltinTopicData* data = NULL;
info = DDS_SampleInfoSeq_get_reference(&info_seq, i);
data = DDS_SubscriptionBuiltinTopicDataSeq_get_reference(&data_seq, i);
if (!info->valid_data)
continue;
printf("Built-in Reader: found subscriber \n");
printf("\tparticipant_key->'%08x%08x%08x'\n",
data->participant_key.value[0], data->participant_key.value[1],
data->participant_key.value[2]);
printf("\tkey->'%08x %08x %08x'\n",
data->key.value[0], data->key.value[1],
data->key.value[2]);
memcpy(ih, &info->instance_handle,
sizeof(info->instance_handle));
printf("instance_handle: %08x%08x %08x%08x %08x%08x \n",
ih[0], ih[1], ih[2], ih[3], ih[4], ih[5]);
}
retcode = DDS_SubscriptionBuiltinTopicDataDataReader_return_loan(
builtin_reader, &data_seq, &info_seq);
if (retcode != DDS_RETCODE_OK) {
printf("return loan error %d\n", retcode);
}
}
/* Delete all entities */
static int publisher_shutdown(DDS_DomainParticipant *participant) {
DDS_ReturnCode_t retcode;
int status = 0;
if (participant != NULL) {
retcode = DDS_DomainParticipant_delete_contained_entities(participant);
if (retcode != DDS_RETCODE_OK) {
printf("delete_contained_entities error %d\n", retcode);
status = -1;
}
retcode = DDS_DomainParticipantFactory_delete_participant(
DDS_TheParticipantFactory, participant);
if (retcode != DDS_RETCODE_OK) {
printf("delete_participant error %d\n", retcode);
status = -1;
}
}
/* RTI Data Distribution Service provides finalize_instance() method on
domain participant factory forpeople who want to release memory used
by the participant factory. Uncomment the following block of code for
clean destruction of the singleton. */
/*
retcode = DDS_DomainParticipantFactory_finalize_instance();
if (retcode != DDS_RETCODE_OK) {
printf("finalize_instance error %d\n", retcode);
status = -1;
}
*/
return status;
}
static int publisher_main(int domain_id, int sample_count) {
DDS_DomainParticipant *participant = NULL;
DDS_Publisher *publisher = NULL;
DDS_Topic *topic = NULL;
DDS_DataWriter *writer = NULL;
msgDataWriter *msg_writer = NULL;
msg *instance = NULL;
DDS_ReturnCode_t retcode;
DDS_InstanceHandle_t instance_handle = DDS_HANDLE_NIL;
const char *type_name = NULL;
int count = 0;
struct DDS_Duration_t send_period = { 1, 0 };
struct DDS_DomainParticipantFactoryQos factory_qos =
DDS_DomainParticipantFactoryQos_INITIALIZER;
DDS_DataReader *builtin_participant_datareader = NULL;
struct DDS_DataReaderListener builtin_participant_listener =
DDS_DataReaderListener_INITIALIZER;
DDS_DataReader *builtin_subscriber_datareader = NULL;
struct DDS_DataReaderListener builtin_subscriber_listener =
DDS_DataReaderListener_INITIALIZER;
DDS_Subscriber *builtin_subscriber = NULL;
struct DDS_DomainParticipantQos participant_qos =
DDS_DomainParticipantQos_INITIALIZER;
/* It is recommended to install built-in topic listeners on disabled
* entities (EntityFactoryQoS). For this reason it is necessary to set
* the autoenable_created_entities setting to false. To do this
* programmatically, just uncomment the following code
*/
/*
retcode = DDS_DomainParticipantFactory_get_qos(DDS_TheParticipantFactory,
&factory_qos);
if (retcode != DDS_RETCODE_OK) {
printf("Cannot get factory Qos for domain participant\n");
return -1;
}
factory_qos.entity_factory.autoenable_created_entities = DDS_BOOLEAN_FALSE;
switch(DDS_DomainParticipantFactory_set_qos(DDS_TheParticipantFactory,
&factory_qos)) {
case DDS_RETCODE_OK:
break;
case DDS_RETCODE_IMMUTABLE_POLICY: {
printf("Cannot set factory Qos due to IMMUTABLE_POLICY");
printf(" for domain participant\n");
return -1;
break;
}
case DDS_RETCODE_INCONSISTENT_POLICY: {
printf("Cannot set factory Qos due to INCONSISTENT_POLICY ");
printf("for domain participant\n");
return -1;
break;
}
default: {
printf("Cannot set factory Qos for unknown reason for domain ");
printf("participant\n");
return -1;
break;
}
}
DDS_DomainParticipantFactoryQos_finalize(&factory_qos);
*/
/* The maximum length for USER_DATA QoS field is set by default
to 256 bytes. To increase it programmatically uncomment the
following lines of code and replace DDS_PARTICIPANT_QOS_DEFAULT
with participant_qos in the constructor call. */
/*
retcode = DDS_DomainParticipantFactory_get_default_participant_qos(
DDS_TheParticipantFactory, &participant_qos);
if (retcode != DDS_RETCODE_OK) {
printf("get_default_participant_qos error\n");
return -1;
}
participant_qos.resource_limits.participant_user_data_max_length = 1024;
*/
/* To customize participant QoS, use
the configuration file USER_QOS_PROFILES.xml */
participant = DDS_DomainParticipantFactory_create_participant(
DDS_TheParticipantFactory, domain_id, &DDS_PARTICIPANT_QOS_DEFAULT,
NULL /* listener */, DDS_STATUS_MASK_NONE);
if (participant == NULL) {
printf("create_participant error\n");
publisher_shutdown(participant);
return -1;
}
/* Start changes for Builtin_Topics
Installing listeners for the builtin topics requires several steps:
*/
/*
* First, get the builtin subscriber
*/
builtin_subscriber = DDS_DomainParticipant_get_builtin_subscriber(
participant);
if (builtin_subscriber == NULL) {
printf("***Error: failed to create builtin subscriber\n");
return -1;
}
/*
* Then get builtin subscriber's datareader for participants
*/
builtin_participant_datareader =
DDS_Subscriber_lookup_datareader(builtin_subscriber,
DDS_PARTICIPANT_TOPIC_NAME);
if (builtin_participant_datareader == NULL) {
printf("***Error: failed to create builtin participant data reader\n");
return -1;
}
/*
* Install our listener in the builtin datareader
*/
builtin_participant_listener.on_data_available =
BuiltinParticipantListener_on_data_available;
retcode = DDS_DataReader_set_listener(builtin_participant_datareader,
&builtin_participant_listener,
DDS_DATA_AVAILABLE_STATUS);
if (retcode != DDS_RETCODE_OK) {
printf("set_listener failed %d\n", retcode);
return -1;
}
/* Now we repeat the same procedure for builtin subscription topics. */
/*
* Get builtin subscriber's datareader for subscribers
*/
builtin_subscriber_datareader =
DDS_Subscriber_lookup_datareader(builtin_subscriber,
DDS_SUBSCRIPTION_TOPIC_NAME);
if (builtin_subscriber_datareader == NULL) {
printf("***Error: failed to create builtin subscription data reader\n");
return -1;
}
/* Install our listener */
builtin_subscriber_listener.on_data_available =
BuiltinSubscriberListener_on_data_available;
retcode = DDS_DataReader_set_listener(builtin_subscriber_datareader,
&builtin_subscriber_listener,
DDS_DATA_AVAILABLE_STATUS);
if (retcode != DDS_RETCODE_OK) {
printf("set_listener failed %d\n", retcode);
return -1;
}
if (DDS_Entity_enable((DDS_Entity*)participant) != DDS_RETCODE_OK) {
printf("***Error: Failed to Enable Participant\n");
return -1;
}
/* To customize publisher QoS, use
the configuration file USER_QOS_PROFILES.xml */
publisher = DDS_DomainParticipant_create_publisher(
participant, &DDS_PUBLISHER_QOS_DEFAULT, NULL /* listener */,
DDS_STATUS_MASK_NONE);
if (publisher == NULL) {
printf("create_publisher error\n");
publisher_shutdown(participant);
return -1;
}
/* Register type before creating topic */
type_name = msgTypeSupport_get_type_name();
retcode = msgTypeSupport_register_type(
participant, type_name);
if (retcode != DDS_RETCODE_OK) {
printf("register_type error %d\n", retcode);
publisher_shutdown(participant);
return -1;
}
/* To customize topic QoS, use
the configuration file USER_QOS_PROFILES.xml */
topic = DDS_DomainParticipant_create_topic(
participant, "Example msg",
type_name, &DDS_TOPIC_QOS_DEFAULT, NULL /* listener */,
DDS_STATUS_MASK_NONE);
if (topic == NULL) {
printf("create_topic error\n");
publisher_shutdown(participant);
return -1;
}
/* To customize data writer QoS, use
DDS_Publisher_get_default_datawriter_qos() */
writer = DDS_Publisher_create_datawriter(
publisher, topic,
&DDS_DATAWRITER_QOS_DEFAULT, NULL /* listener */, DDS_STATUS_MASK_NONE);
if (writer == NULL) {
printf("create_datawriter error\n");
publisher_shutdown(participant);
return -1;
}
msg_writer = msgDataWriter_narrow(writer);
if (msg_writer == NULL) {
printf("DataWriter narrow error\n");
publisher_shutdown(participant);
return -1;
}
/* Create data sample for writing */
instance = msgTypeSupport_create_data_ex(DDS_BOOLEAN_TRUE);
if (instance == NULL) {
printf("msgTypeSupport_create_data error\n");
publisher_shutdown(participant);
return -1;
}
/* For a data type that has a key, if the same instance is going to be
written multiple times, initialize the key here
and register the keyed instance prior to writing */
/*
instance_handle = msgDataWriter_register_instance(
msg_writer, instance);
*/
/* Main loop */
for (count=0; (sample_count == 0) || (count < sample_count); ++count) {
printf("Writing msg, count %d\n", count);
/* Modify the data to be written here */
instance->x = count;
/* Write data */
retcode = msgDataWriter_write(
msg_writer, instance, &instance_handle);
if (retcode != DDS_RETCODE_OK) {
printf("write error %d\n", retcode);
}
NDDS_Utility_sleep(&send_period);
}
/*
retcode = msgDataWriter_unregister_instance(
msg_writer, instance, &instance_handle);
if (retcode != DDS_RETCODE_OK) {
printf("unregister instance error %d\n", retcode);
}
*/
/* Delete data sample */
retcode = msgTypeSupport_delete_data_ex(instance, DDS_BOOLEAN_TRUE);
if (retcode != DDS_RETCODE_OK) {
printf("msgTypeSupport_delete_data error %d\n", retcode);
}
/* Cleanup and delete delete all entities */
return publisher_shutdown(participant);
}
int main(int argc, char *argv[])
{
int domain_id = 0;
int sample_count = 0; /* infinite loop */
if (argc >= 2) {
domain_id = atoi(argv[1]);
}
if (argc >= 3) {
sample_count = atoi(argv[2]);
}
/* Uncomment this to turn on additional logging
NDDS_Config_Logger_set_verbosity_by_category(
NDDS_Config_Logger_get_instance(),
NDDS_CONFIG_LOG_CATEGORY_API,
NDDS_CONFIG_LOG_VERBOSITY_STATUS_ALL);
*/
return publisher_main(domain_id, sample_count);
}
| c |
rticonnextdds-examples | data/projects/rticonnextdds-examples/builtin_topics/c/msg_subscriber.c | /*******************************************************************************
(c) 2005-2014 Copyright, Real-Time Innovations, Inc. All rights reserved.
RTI grants Licensee a license to use, modify, compile, and create derivative
works of the Software. Licensee has the right to distribute object form only
for use with RTI products. The Software is provided "as is", with no warranty
of any type, including any warranty for fitness for any purpose. RTI is under
no obligation to maintain or support the Software. RTI shall not be liable for
any incidental or consequential damages arising out of the use or inability to
use the software.
******************************************************************************/
/* msg_subscriber.c
A subscription example
This file is derived from code automatically generated by the rtiddsgen
command:
rtiddsgen -language C -example <arch> msg.idl
Example subscription of type msg automatically generated by
'rtiddsgen'. To test them follow these steps:
(1) Compile this file and the example publication.
(2) Start the subscription on the same domain used for RTI Data Distribution
Service with the command
objs/<arch>/msg_subscriber <domain_id> <sample_count>
(3) Start the publication on the same domain used for RTI Data Distribution
Service with the command
objs/<arch>/msg_publisher <domain_id> <sample_count>
(4) [Optional] Specify the list of discovery initial peers and
multicast receive addresses via an environment variable or a file
(in the current working directory) called NDDS_DISCOVERY_PEERS.
You can run any number of publishers and subscribers programs, and can
add and remove them dynamically from the domain.
Example:
To run the example application on domain <domain_id>:
On Unix:
objs/<arch>/msg_publisher <domain_id>
objs/<arch>/msg_subscriber <domain_id>
On Windows:
objs\<arch>\msg_publisher <domain_id>
objs\<arch>\msg_subscriber <domain_id>
modification history
------------ -------
* Set user_data QoS fields in participant and datareader with
strings given on command line
* Do not ignore data readers since it is a bad security practice.
* Fix null char in participant user_data field.
*/
#include <stdio.h>
#include <stdlib.h>
#include "ndds/ndds_c.h"
#include "msg.h"
#include "msgSupport.h"
void msgListener_on_requested_deadline_missed(void* listener_data,
DDS_DataReader* reader,
const struct DDS_RequestedDeadlineMissedStatus *status) {
}
void msgListener_on_requested_incompatible_qos(void* listener_data,
DDS_DataReader* reader,
const struct DDS_RequestedIncompatibleQosStatus *status) {
}
void msgListener_on_sample_rejected(void* listener_data, DDS_DataReader* reader,
const struct DDS_SampleRejectedStatus *status) {
}
void msgListener_on_liveliness_changed(void* listener_data,
DDS_DataReader* reader,
const struct DDS_LivelinessChangedStatus *status) {
}
void msgListener_on_sample_lost(void* listener_data, DDS_DataReader* reader,
const struct DDS_SampleLostStatus *status) {
}
void msgListener_on_subscription_matched(void* listener_data,
DDS_DataReader* reader,
const struct DDS_SubscriptionMatchedStatus *status) {
}
void msgListener_on_data_available(void* listener_data,
DDS_DataReader* reader) {
msgDataReader *msg_reader = NULL;
struct msgSeq data_seq = DDS_SEQUENCE_INITIALIZER;
struct DDS_SampleInfoSeq info_seq = DDS_SEQUENCE_INITIALIZER;
DDS_ReturnCode_t retcode;
int i;
msg_reader = msgDataReader_narrow(reader);
if (msg_reader == NULL) {
printf("DataReader narrow error\n");
return;
}
retcode = msgDataReader_take(msg_reader, &data_seq, &info_seq,
DDS_LENGTH_UNLIMITED, DDS_ANY_SAMPLE_STATE, DDS_ANY_VIEW_STATE,
DDS_ANY_INSTANCE_STATE);
if (retcode == DDS_RETCODE_NO_DATA) {
return;
} else if (retcode != DDS_RETCODE_OK) {
printf("take error %d\n", retcode);
return;
}
for (i = 0; i < msgSeq_get_length(&data_seq); ++i) {
if (DDS_SampleInfoSeq_get_reference(&info_seq, i)->valid_data) {
msgTypeSupport_print_data(msgSeq_get_reference(&data_seq, i));
}
}
retcode = msgDataReader_return_loan(msg_reader, &data_seq, &info_seq);
if (retcode != DDS_RETCODE_OK) {
printf("return loan error %d\n", retcode);
}
}
/* Delete all entities */
static int subscriber_shutdown(DDS_DomainParticipant *participant) {
DDS_ReturnCode_t retcode;
int status = 0;
if (participant != NULL) {
retcode = DDS_DomainParticipant_delete_contained_entities(participant);
if (retcode != DDS_RETCODE_OK) {
printf("delete_contained_entities error %d\n", retcode);
status = -1;
}
retcode = DDS_DomainParticipantFactory_delete_participant(
DDS_TheParticipantFactory, participant);
if (retcode != DDS_RETCODE_OK) {
printf("delete_participant error %d\n", retcode);
status = -1;
}
}
/* RTI Data Distribution Service provides the finalize_instance() method on
domain participant factory for users who want to release memory used
by the participant factory. Uncomment the following block of code for
clean destruction of the singleton. */
/*
retcode = DDS_DomainParticipantFactory_finalize_instance();
if (retcode != DDS_RETCODE_OK) {
printf("finalize_instance error %d\n", retcode);
status = -1;
}
*/
return status;
}
static int subscriber_main(int domain_id, int sample_count,
char *participant_auth) {
DDS_DomainParticipant *participant = NULL;
DDS_Subscriber *subscriber = NULL;
DDS_Topic *topic = NULL;
struct DDS_DataReaderListener reader_listener =
DDS_DataReaderListener_INITIALIZER;
DDS_DataReader *reader = NULL;
DDS_ReturnCode_t retcode;
const char *type_name = NULL;
int count = 0;
struct DDS_Duration_t poll_period = { 1, 0 };
struct DDS_DomainParticipantQos participant_qos =
DDS_DomainParticipantQos_INITIALIZER;
int len, max;
retcode = DDS_DomainParticipantFactory_get_default_participant_qos(
DDS_TheParticipantFactory, &participant_qos);
if (retcode != DDS_RETCODE_OK) {
printf("get_default_participant_qos error\n");
return -1;
}
/* The maximum length for USER_DATA QoS field is set by default
to 256 bytes. To increase it programmatically uncomment the
following line of code. */
/*
participant_qos.resource_limits.participant_user_data_max_length = 1024;
*/
/* We include the subscriber credentials into de USER_DATA QoS. */
len = strlen(participant_auth) + 1;
max = participant_qos.resource_limits.participant_user_data_max_length;
if (len > max) {
printf("error, participant user_data exceeds resource limits\n");
} else {
/*
* DDS_Octet is defined to be 8 bits. If chars are not 8 bits
* on your system, this will not work.
*/
DDS_OctetSeq_from_array(&participant_qos.user_data.value,
(DDS_Octet*) (participant_auth), len);
}
/* To customize participant QoS, use
the configuration file USER_QOS_PROFILES.xml */
participant = DDS_DomainParticipantFactory_create_participant(
DDS_TheParticipantFactory, domain_id, &participant_qos,
NULL /* listener */, DDS_STATUS_MASK_NONE);
if (participant == NULL) {
printf("create_participant error\n");
subscriber_shutdown(participant);
return -1;
}
/* Done! All the listeners are installed, so we can enable the
* participant now.
*/
if (DDS_Entity_enable((DDS_Entity*) participant) != DDS_RETCODE_OK) {
printf("***Error: Failed to Enable Participant\n");
return -1;
}
/* To customize subscriber QoS, use
the configuration file USER_QOS_PROFILES.xml */
subscriber = DDS_DomainParticipant_create_subscriber(participant,
&DDS_SUBSCRIBER_QOS_DEFAULT, NULL /* listener */,
DDS_STATUS_MASK_NONE);
if (subscriber == NULL) {
printf("create_subscriber error\n");
subscriber_shutdown(participant);
return -1;
}
/* Register the type before creating the topic */
type_name = msgTypeSupport_get_type_name();
retcode = msgTypeSupport_register_type(participant, type_name);
if (retcode != DDS_RETCODE_OK) {
printf("register_type error %d\n", retcode);
subscriber_shutdown(participant);
return -1;
}
/* To customize topic QoS, use
the configuration file USER_QOS_PROFILES.xml */
topic = DDS_DomainParticipant_create_topic(participant, "Example msg",
type_name, &DDS_TOPIC_QOS_DEFAULT, NULL /* listener */,
DDS_STATUS_MASK_NONE);
if (topic == NULL) {
printf("create_topic error\n");
subscriber_shutdown(participant);
return -1;
}
/* Set up a data reader listener */
reader_listener.on_requested_deadline_missed =
msgListener_on_requested_deadline_missed;
reader_listener.on_requested_incompatible_qos =
msgListener_on_requested_incompatible_qos;
reader_listener.on_sample_rejected = msgListener_on_sample_rejected;
reader_listener.on_liveliness_changed = msgListener_on_liveliness_changed;
reader_listener.on_sample_lost = msgListener_on_sample_lost;
reader_listener.on_subscription_matched =
msgListener_on_subscription_matched;
reader_listener.on_data_available = msgListener_on_data_available;
/* To customize data reader QoS, use
the configuration file USER_QOS_PROFILES.xml */
reader = DDS_Subscriber_create_datareader(subscriber,
DDS_Topic_as_topicdescription(topic), &DDS_DATAREADER_QOS_DEFAULT,
&reader_listener, DDS_STATUS_MASK_ALL);
if (reader == NULL) {
printf("create_datareader error\n");
subscriber_shutdown(participant);
return -1;
}
/* Main loop */
for (count = 0; (sample_count == 0) || (count < sample_count); ++count) {
/*
printf("msg subscriber sleeping for %d sec...\n",
poll_period.sec);
*/
NDDS_Utility_sleep(&poll_period);
}
/* Cleanup and delete all entities */
return subscriber_shutdown(participant);
}
int main(int argc, char *argv[]) {
int domain_id = 0;
int sample_count = 0; /* infinite loop */
/*
* Changes for Builtin_Topics
* Get arguments for auth strings and pass to subscriber_main()
*/
char *participant_auth = "password";
if (argc >= 2) {
domain_id = atoi(argv[1]);
}
if (argc >= 3) {
sample_count = atoi(argv[2]);
}
if (argc >= 4) {
participant_auth = argv[3];
}
/* Uncomment this to turn on additional logging
NDDS_Config_Logger_set_verbosity_by_category(
NDDS_Config_Logger_get_instance(),
NDDS_CONFIG_LOG_CATEGORY_API,
NDDS_CONFIG_LOG_VERBOSITY_STATUS_ALL);
*/
subscriber_main(domain_id, sample_count, participant_auth);
return 0;
}
| c |
rticonnextdds-examples | data/projects/rticonnextdds-examples/builtin_topics/c++03/msg_publisher.cxx | /*******************************************************************************
(c) 2005-2015 Copyright, Real-Time Innovations, Inc. All rights reserved.
RTI grants Licensee a license to use, modify, compile, and create derivative
works of the Software. Licensee has the right to distribute object form only
for use with RTI products. The Software is provided "as is", with no warranty
of any type, including any warranty for fitness for any purpose. RTI is under
no obligation to maintain or support the Software. RTI shall not be liable for
any incidental or consequential damages arising out of the use or inability to
use the software.
******************************************************************************/
#include <string>
#include <list>
#include <algorithm>
#include <iostream>
#include <iomanip>
#include "msg.hpp"
#include <dds/dds.hpp>
#include <rti/core/ListenerBinder.hpp>
using namespace dds::core;
using namespace dds::core::policy;
using namespace rti::core::policy;
using namespace dds::domain;
using namespace dds::domain::qos;
using namespace dds::topic;
using namespace dds::sub;
using namespace dds::pub;
// Authorization string
const std::string expected_password = "password";
// The builtin subscriber sets participant_qos.user_data, so we set up listeners
// for the builtin DataReaders to access these fields.
class BuiltinParticipantListener :
public NoOpDataReaderListener<ParticipantBuiltinTopicData> {
public:
// This gets called when a participant has been discovered
void on_data_available(DataReader<ParticipantBuiltinTopicData>& reader)
{
// We only process newly seen participants
LoanedSamples<ParticipantBuiltinTopicData> samples = reader.select()
.state(dds::sub::status::DataState::new_instance())
.take();
for (LoanedSamples<ParticipantBuiltinTopicData>::iterator sampleIt = samples.begin();
sampleIt != samples.end();
++sampleIt) {
if (!sampleIt->info().valid()) {
continue;
}
const ByteSeq& user_data = sampleIt->data().user_data().value();
std::string user_auth (user_data.begin(), user_data.end());
std::ios::fmtflags default_format(std::cout.flags());
std::cout << std::hex << std::setw(8) << std::setfill('0');
const BuiltinTopicKey& key = sampleIt->data().key();
std::cout << "Built-in Reader: found participant" << std::endl
<< "\tkey->'" << key.value()[0] << " " << key.value()[1]
<< " " << key.value()[2] << "'" << std::endl
<< "\tuser_data->'" << user_auth << "'" << std::endl
<< "\tinstance_handle: "
<< sampleIt->info().instance_handle() << std::endl;
std::cout.flags(default_format);
// Check if the password match. Otherwise, ignore the participant.
if (user_auth != expected_password) {
std::cout << "Bad authorization, ignoring participant"
<< std::endl;
// Get the associated participant...
DomainParticipant participant =
reader.subscriber().participant();
// Ignore the remote participant
dds::domain::ignore(
participant,
sampleIt->info().instance_handle());
}
}
}
};
class BuiltinSubscriberListener :
public NoOpDataReaderListener<SubscriptionBuiltinTopicData> {
public:
// This gets called when a subscriber has been discovered
void on_data_available(DataReader<SubscriptionBuiltinTopicData>& reader)
{
// We only process newly seen subscribers
LoanedSamples<SubscriptionBuiltinTopicData> samples = reader.select()
.state(dds::sub::status::DataState::new_instance())
.take();
for (LoanedSamples<SubscriptionBuiltinTopicData>::iterator sampleIt = samples.begin();
sampleIt != samples.end();
++sampleIt) {
if (!sampleIt->info().valid()) {
continue;
}
std::ios::fmtflags default_format(std::cout.flags());
std::cout << std::hex << std::setw(8) << std::setfill('0');
const BuiltinTopicKey& partKey = sampleIt->data().participant_key();
const BuiltinTopicKey& key = sampleIt->data().key();
std::cout << "Built-in Reader: found subscriber" << std::endl
<< "\tparticipant_key->'"
<< partKey.value()[0] << " " << partKey.value()[1] << " "
<< partKey.value()[2] << "'" << std::endl
<< "\tkey->'" << key.value()[0] << " " << key.value()[1]
<< " " << key.value()[2] << "'" << std::endl
<< "\tinstance_handle: "
<< sampleIt->info().instance_handle() << std::endl;
std::cout.flags(default_format);
}
}
};
void publisher_main(int domain_id, int sample_count)
{
// By default, the participant is enabled upon construction.
// At that time our listeners for the builtin topics have not
// been installed, so we disable the participant until we
// set up the listeners. This is done by default in the
// USER_QOS_PROFILES.xml file. If you want to do it programmatically,
// just uncomment the following code.
// DomainParticipantFactoryQos factoryQos =
// DomainParticipant::participant_factory_qos();
// factoryQos << EntityFactory::ManuallyEnable();
// DomainParticipant::participant_factory_qos(factoryQos);
// If you want to change the Participant's QoS programmatically rather than
// using the XML file, you will need to comment out these lines and pass
// the variable participant_qos as second argument in the constructor call.
// DomainParticipantQos participant_qos = QosProvider::Default()
// .participant_qos();
// DomainParticipantResourceLimits resource_limits_qos;
// resource_limits_qos.participant_user_data_max_length(1024);
// participant_qos << resource_limits_qos;
// Create a DomainParticipant with default Qos.
DomainParticipant participant(domain_id);
// Installing listeners for the builtin topics requires several steps
// First get the builtin subscriber.
Subscriber builtin_subscriber = dds::sub::builtin_subscriber(participant);
// Then get builtin subscriber's datareader for participants.
std::vector< DataReader<ParticipantBuiltinTopicData> > participant_reader;
find< DataReader<ParticipantBuiltinTopicData> >(
builtin_subscriber,
dds::topic::participant_topic_name(),
std::back_inserter(participant_reader));
// Install our listener using ListenerBinder, a RAII that will take care
// of setting it to NULL and deleting it.
rti::core::ListenerBinder< DataReader<ParticipantBuiltinTopicData> >
participant_listener = rti::core::bind_and_manage_listener(
participant_reader[0],
new BuiltinParticipantListener,
dds::core::status::StatusMask::data_available());
// Get builtin subscriber's datareader for subscribers.
std::vector< DataReader<SubscriptionBuiltinTopicData> > subscription_reader;
find< DataReader<SubscriptionBuiltinTopicData> >(
builtin_subscriber,
dds::topic::subscription_topic_name(),
std::back_inserter(subscription_reader));
// Install our listener using ListenerBinder.
rti::core::ListenerBinder< DataReader<SubscriptionBuiltinTopicData> >
subscriber_listener = rti::core::bind_and_manage_listener(
subscription_reader[0],
new BuiltinSubscriberListener,
dds::core::status::StatusMask::data_available());
// Done! All the listeners are installed, so we can enable the
// participant now.
participant.enable();
// Create a Topic -- and automatically register the type.
Topic<msg> topic(participant, "Example msg");
// Create a DataWriter
DataWriter<msg> writer(Publisher(participant), topic);
// Create data sample for writing
msg instance;
// For data type that has key, if the same instance is going to be
// written multiple times, initialize the key here
// and register the keyed instance prior to writing
InstanceHandle instance_handle = InstanceHandle::nil();
// instance_handle = writer.register_instance(instance);
// Main loop
for (short count=0; (sample_count == 0) || (count < sample_count); ++count){
rti::util::sleep(Duration(1));
std::cout << "Writing msg, count " << count << std::endl;
// Modify the data to be sent here
instance.x(count);
writer.write(instance, instance_handle);
}
// writer.unregister_instance(instance);
}
int main(int argc, char* argv[])
{
int domain_id = 0;
int sample_count = 0; /* infinite loop */
if (argc >= 2) {
domain_id = atoi(argv[1]);
}
if (argc >= 3) {
sample_count = atoi(argv[2]);
}
// To turn on additional logging, include <rti/config/Logger.hpp> and
// uncomment the following line:
// rti::config::Logger::instance().verbosity(rti::config::Verbosity::STATUS_ALL);
try {
publisher_main(domain_id, sample_count);
} catch (std::exception ex) {
std::cout << "Exception caught: " << ex.what() << std::endl;
return -1;
}
return 0;
}
| cxx |
rticonnextdds-examples | data/projects/rticonnextdds-examples/builtin_topics/c++03/msg_subscriber.cxx | /*******************************************************************************
(c) 2005-2015 Copyright, Real-Time Innovations, Inc. All rights reserved.
RTI grants Licensee a license to use, modify, compile, and create derivative
works of the Software. Licensee has the right to distribute object form only
for use with RTI products. The Software is provided "as is", with no warranty
of any type, including any warranty for fitness for any purpose. RTI is under
no obligation to maintain or support the Software. RTI shall not be liable for
any incidental or consequential damages arising out of the use or inability to
use the software.
******************************************************************************/
#include <string>
#include <iostream>
#include "msg.hpp"
#include <dds/dds.hpp>
#include <rti/core/ListenerBinder.hpp>
using namespace dds::core;
using namespace dds::core::policy;
using namespace rti::core;
using namespace rti::core::policy;
using namespace dds::domain;
using namespace dds::domain::qos;
using namespace dds::topic;
using namespace dds::sub;
using namespace dds::sub::qos;
class MsgListener :
public NoOpDataReaderListener<msg> {
public:
void on_data_available(DataReader<msg>& reader)
{
LoanedSamples<msg> samples = reader.take();
for (LoanedSamples<msg>::iterator sampleIt = samples.begin();
sampleIt != samples.end();
++sampleIt) {
if (sampleIt->info().valid()) {
std::cout << sampleIt->data() << std::endl;
}
}
}
};
void subscriber_main(int domain_id, int sample_count,
std::string participant_auth)
{
// Retrieve the default participant QoS, from USER_QOS_PROFILES.xml
DomainParticipantQos participant_qos = QosProvider::Default()
.participant_qos();
DomainParticipantResourceLimits resource_limits_qos =
participant_qos.policy<DomainParticipantResourceLimits>();
// If you want to change the Participant's QoS programmatically rather
// than using the XML file, you will need to comment out these lines.
// resource_limits_qos.participant_user_data_max_length(1024);
// participant_qos << resource_limits_qos;
unsigned int max_participant_user_data = resource_limits_qos
.participant_user_data_max_length();
if (participant_auth.size() > max_participant_user_data) {
std::cout << "error, participant user_data exceeds resource limits"
<< std::endl;
} else {
participant_qos << UserData(
ByteSeq(participant_auth.begin(), participant_auth.end()));
}
// Create a DomainParticipant.
DomainParticipant participant(domain_id, participant_qos);
// Participant is disabled by default in USER_QOS_PROFILES. We enable it now
participant.enable();
// Create a Topic -- and automatically register the type.
Topic<msg> topic(participant, "Example msg");
// Create a DataReader
DataReader<msg> reader(Subscriber(participant), topic);
// Create a data reader listener using ListenerBinder, a RAII utility that
// will take care of reseting it from the reader and deleting it.
ListenerBinder<DataReader<msg> > scoped_listener = bind_and_manage_listener(
reader,
new MsgListener,
dds::core::status::StatusMask::data_available());
// Main loop
for (int count = 0; (sample_count == 0) || (count < sample_count); ++count){
// Each "sample_count" is one second.
rti::util::sleep(Duration(1));
}
}
int main(int argc, char* argv[])
{
int domain_id = 0;
int sample_count = 0; // Infinite loop
// Changes for Builtin_Topics
// Get arguments for auth strings and pass to subscriber_main()
std::string participant_auth = "password";
if (argc >= 2) {
domain_id = atoi(argv[1]);
}
if (argc >= 3) {
sample_count = atoi(argv[2]);
}
if (argc >= 4) {
participant_auth = argv[3];
}
// To turn on additional logging, include <rti/config/Logger.hpp> and
// uncomment the following line:
// rti::config::Logger::instance().verbosity(rti::config::Verbosity::STATUS_ALL);
try {
subscriber_main(domain_id, sample_count, participant_auth);
} catch (std::exception ex) {
std::cout << "Exception caught: " << ex.what() << std::endl;
return -1;
}
return 0;
}
| cxx |
rticonnextdds-examples | data/projects/rticonnextdds-examples/content_filtered_topic/c++/cft_publisher.cxx | /*******************************************************************************
(c) 2005-2014 Copyright, Real-Time Innovations, Inc. All rights reserved.
RTI grants Licensee a license to use, modify, compile, and create derivative
works of the Software. Licensee has the right to distribute object form only
for use with RTI products. The Software is provided "as is", with no warranty
of any type, including any warranty for fitness for any purpose. RTI is under
no obligation to maintain or support the Software. RTI shall not be liable for
any incidental or consequential damages arising out of the use or inability to
use the software.
******************************************************************************/
/* cft_publisher.cxx
A publication of data of type cft
This file is derived from code automatically generated by the rtiddsgen
command:
rtiddsgen -language C++ -example <arch> cft.idl
Example publication of type cft automatically generated by
'rtiddsgen'. To test them follow these steps:
(1) Compile this file and the example subscription.
(2) Start the subscription with the command
objs/<arch>/cft_subscriber <domain_id> <sample_count>
(3) Start the publication with the command
objs/<arch>/cft_publisher <domain_id> <sample_count>
(4) [Optional] Specify the list of discovery initial peers and
multicast receive addresses via an environment variable or a file
(in the current working directory) called NDDS_DISCOVERY_PEERS.
You can run any number of publishers and subscribers programs, and can
add and remove them dynamically from the domain.
Example:
To run the example application on domain <domain_id>:
On Unix:
objs/<arch>/cft_publisher <domain_id> o
objs/<arch>/cft_subscriber <domain_id>
On Windows:
objs\<arch>\cft_publisher <domain_id>
objs\<arch>\cft_subscriber <domain_id>
modification history
------------ -------
*/
#include <stdio.h>
#include <stdlib.h>
#ifdef RTI_VX653
#include <vThreadsData.h>
#endif
#include "cft.h"
#include "cftSupport.h"
#include "ndds/ndds_cpp.h"
/* Delete all entities */
static int publisher_shutdown(
DDSDomainParticipant *participant)
{
DDS_ReturnCode_t retcode;
int status = 0;
if (participant != NULL) {
retcode = participant->delete_contained_entities();
if (retcode != DDS_RETCODE_OK) {
printf("delete_contained_entities error %d\n", retcode);
status = -1;
}
retcode = DDSTheParticipantFactory->delete_participant(participant);
if (retcode != DDS_RETCODE_OK) {
printf("delete_participant error %d\n", retcode);
status = -1;
}
}
/* RTI Connext provides finalize_instance() method on
domain participant factory for people who want to release memory used
by the participant factory. Uncomment the following block of code for
clean destruction of the singleton. */
/*
retcode = DDSDomainParticipantFactory::finalize_instance();
if (retcode != DDS_RETCODE_OK) {
printf("finalize_instance error %d\n", retcode);
status = -1;
}
*/
return status;
}
extern "C" int publisher_main(int domainId, int sample_count)
{
DDSDomainParticipant *participant = NULL;
DDSPublisher *publisher = NULL;
DDSTopic *topic = NULL;
DDSDataWriter *writer = NULL;
cftDataWriter * cft_writer = NULL;
cft *instance = NULL;
DDS_ReturnCode_t retcode;
DDS_InstanceHandle_t instance_handle = DDS_HANDLE_NIL;
const char *type_name = NULL;
int count = 0;
/* Send a new sample every second */
DDS_Duration_t send_period = {1,0};
/* To customize participant QoS, use
the configuration file USER_QOS_PROFILES.xml */
participant = DDSTheParticipantFactory->create_participant(
domainId, DDS_PARTICIPANT_QOS_DEFAULT,
NULL /* listener */, DDS_STATUS_MASK_NONE);
if (participant == NULL) {
printf("create_participant error\n");
publisher_shutdown(participant);
return -1;
}
/* To customize publisher QoS, use
the configuration file USER_QOS_PROFILES.xml */
publisher = participant->create_publisher(
DDS_PUBLISHER_QOS_DEFAULT, NULL /* listener */, DDS_STATUS_MASK_NONE);
if (publisher == NULL) {
printf("create_publisher error\n");
publisher_shutdown(participant);
return -1;
}
/* Register type before creating topic */
type_name = cftTypeSupport::get_type_name();
retcode = cftTypeSupport::register_type(
participant, type_name);
if (retcode != DDS_RETCODE_OK) {
printf("register_type error %d\n", retcode);
publisher_shutdown(participant);
return -1;
}
/* To customize topic QoS, use
the configuration file USER_QOS_PROFILES.xml */
topic = participant->create_topic(
"Example cft",
type_name, DDS_TOPIC_QOS_DEFAULT, NULL /* listener */,
DDS_STATUS_MASK_NONE);
if (topic == NULL) {
printf("create_topic error\n");
publisher_shutdown(participant);
return -1;
}
/* To customize data writer QoS, use
the configuration file USER_QOS_PROFILES.xml */
writer = publisher->create_datawriter(
topic, DDS_DATAWRITER_QOS_DEFAULT, NULL,
DDS_STATUS_MASK_NONE);
if (writer == NULL) {
printf("create_datawriter error\n");
publisher_shutdown(participant);
return -1;
}
/* If you want to set the reliability and history QoS settings
* programmatically rather than using the XML, you will need to add
* the following lines to your code and comment out the create_datawriter
* call above.
*/
/*
DDS_DataWriterQos datawriter_qos;
retcode = publisher->get_default_datawriter_qos(datawriter_qos);
if (retcode != DDS_RETCODE_OK) {
printf("get_default_datawriter_qos error\n");
return -1;
}
datawriter_qos.reliability.kind = DDS_RELIABLE_RELIABILITY_QOS;
datawriter_qos.durability.kind = DDS_TRANSIENT_LOCAL_DURABILITY_QOS;
datawriter_qos.history.kind = DDS_KEEP_LAST_HISTORY_QOS;
datawriter_qos.history.depth = 20;
writer = publisher->create_datawriter(
topic, datawriter_qos, NULL,
DDS_STATUS_MASK_NONE);
if (writer == NULL) {
printf("create_datawriter error\n");
publisher_shutdown(participant);
return -1;
}
*/
cft_writer = cftDataWriter::narrow(writer);
if (cft_writer == NULL) {
printf("DataWriter narrow error\n");
publisher_shutdown(participant);
return -1;
}
/* Create data sample for writing */
instance = cftTypeSupport::create_data();
if (instance == NULL) {
printf("cftTypeSupport::create_data error\n");
publisher_shutdown(participant);
return -1;
}
/* For a data type that has a key, if the same instance is going to be
written multiple times, initialize the key here
and register the keyed instance prior to writing */
/*
instance_handle = cft_writer->register_instance(*instance);
*/
/* Main loop */
for (count=0; (sample_count == 0) || (count < sample_count); ++count) {
printf("Writing cft, count %d\n", count);
/* Modify the data to be sent here */
/* Our purpose is to increment x every time we send a sample and to
* reset the x counter to 0 every time we send 10 samples (x=0,1,..,9).
* Using the value of count, we can get set x to the appropriate value
* applying % 10 operation to it.
*/
instance->count = count;
instance->x = count%10;
printf("Writing cft, count %d\tx=%d\n", instance->count, instance->x);
retcode = cft_writer->write(*instance, instance_handle);
if (retcode != DDS_RETCODE_OK) {
printf("write error %d\n", retcode);
}
NDDSUtility::sleep(send_period);
}
/*
retcode = cft_writer->unregister_instance(
*instance, instance_handle);
if (retcode != DDS_RETCODE_OK) {
printf("unregister instance error %d\n", retcode);
}
*/
/* Delete data sample */
retcode = cftTypeSupport::delete_data(instance);
if (retcode != DDS_RETCODE_OK) {
printf("cftTypeSupport::delete_data error %d\n", retcode);
}
/* Delete all entities */
return publisher_shutdown(participant);
}
#if defined(RTI_WINCE)
int wmain(int argc, wchar_t** argv)
{
int domainId = 0;
int sample_count = 0; /* infinite loop */
if (argc >= 2) {
domainId = _wtoi(argv[1]);
}
if (argc >= 3) {
sample_count = _wtoi(argv[2]);
}
/* Uncomment this to turn on additional logging
NDDSConfigLogger::get_instance()->
set_verbosity_by_category(NDDS_CONFIG_LOG_CATEGORY_API,
NDDS_CONFIG_LOG_VERBOSITY_STATUS_ALL);
*/
return publisher_main(domainId, sample_count);
}
#elif !(defined(RTI_VXWORKS) && !defined(__RTP__)) && !defined(RTI_PSOS)
int main(int argc, char *argv[])
{
int domainId = 0;
int sample_count = 0; /* infinite loop */
if (argc >= 2) {
domainId = atoi(argv[1]);
}
if (argc >= 3) {
sample_count = atoi(argv[2]);
}
/* Uncomment this to turn on additional logging
NDDSConfigLogger::get_instance()->
set_verbosity_by_category(NDDS_CONFIG_LOG_CATEGORY_API,
NDDS_CONFIG_LOG_VERBOSITY_STATUS_ALL);
*/
return publisher_main(domainId, sample_count);
}
#endif
#ifdef RTI_VX653
const unsigned char* __ctype = *(__ctypePtrGet());
extern "C" void usrAppInit ()
{
#ifdef USER_APPL_INIT
USER_APPL_INIT; /* for backwards compatibility */
#endif
/* add application specific code here */
taskSpawn("pub", RTI_OSAPI_THREAD_PRIORITY_NORMAL, 0x8, 0x150000, (FUNCPTR)publisher_main, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
}
#endif
| cxx |
rticonnextdds-examples | data/projects/rticonnextdds-examples/content_filtered_topic/c++/cft_subscriber.cxx | /*******************************************************************************
(c) 2005-2014 Copyright, Real-Time Innovations, Inc. All rights reserved.
RTI grants Licensee a license to use, modify, compile, and create derivative
works of the Software. Licensee has the right to distribute object form only
for use with RTI products. The Software is provided "as is", with no warranty
of any type, including any warranty for fitness for any purpose. RTI is under
no obligation to maintain or support the Software. RTI shall not be liable for
any incidental or consequential damages arising out of the use or inability to
use the software.
******************************************************************************/
/* cft_subscriber.cxx
A subscription example
This file is derived from code automatically generated by the rtiddsgen
command:
rtiddsgen -language C++ -example <arch> cft.idl
Example subscription of type cft automatically generated by
'rtiddsgen'. To test them follow these steps:
(1) Compile this file and the example publication.
(2) Start the subscription with the command
objs/<arch>/cft_subscriber <domain_id> <sample_count>
(3) Start the publication with the command
objs/<arch>/cft_publisher <domain_id> <sample_count>
(4) [Optional] Specify the list of discovery initial peers and
multicast receive addresses via an environment variable or a file
(in the current working directory) called NDDS_DISCOVERY_PEERS.
You can run any number of publishers and subscribers programs, and can
add and remove them dynamically from the domain.
Example:
To run the example application on domain <domain_id>:
On Unix:
objs/<arch>/cft_publisher <domain_id>
objs/<arch>/cft_subscriber <domain_id>
On Windows:
objs\<arch>\cft_publisher <domain_id>
objs\<arch>\cft_subscriber <domain_id>
modification history
------------ -------
*/
#include <stdio.h>
#include <stdlib.h>
#ifdef RTI_VX653
#include <vThreadsData.h>
#endif
#include "cft.h"
#include "cftSupport.h"
#include "ndds/ndds_cpp.h"
class cftListener : public DDSDataReaderListener {
public:
virtual void on_requested_deadline_missed(
DDSDataReader* /*reader*/,
const DDS_RequestedDeadlineMissedStatus& /*status*/) {}
virtual void on_requested_incompatible_qos(
DDSDataReader* /*reader*/,
const DDS_RequestedIncompatibleQosStatus& /*status*/) {}
virtual void on_sample_rejected(
DDSDataReader* /*reader*/,
const DDS_SampleRejectedStatus& /*status*/) {}
virtual void on_liveliness_changed(
DDSDataReader* /*reader*/,
const DDS_LivelinessChangedStatus& /*status*/) {}
virtual void on_sample_lost(
DDSDataReader* /*reader*/,
const DDS_SampleLostStatus& /*status*/) {}
virtual void on_subscription_matched(
DDSDataReader* /*reader*/,
const DDS_SubscriptionMatchedStatus& /*status*/) {}
virtual void on_data_available(DDSDataReader* reader);
};
void cftListener::on_data_available(DDSDataReader* reader)
{
cftDataReader *cft_reader = NULL;
cftSeq data_seq;
DDS_SampleInfoSeq info_seq;
DDS_ReturnCode_t retcode;
int i;
cft_reader = cftDataReader::narrow(reader);
if (cft_reader == NULL) {
printf("DataReader narrow error\n");
return;
}
retcode = cft_reader->take(
data_seq, info_seq, DDS_LENGTH_UNLIMITED,
DDS_ANY_SAMPLE_STATE, DDS_ANY_VIEW_STATE, DDS_ANY_INSTANCE_STATE);
if (retcode == DDS_RETCODE_NO_DATA) {
return;
} else if (retcode != DDS_RETCODE_OK) {
printf("take error %d\n", retcode);
return;
}
for (i = 0; i < data_seq.length(); ++i) {
if (info_seq[i].valid_data) {
cftTypeSupport::print_data(&data_seq[i]);
}
}
retcode = cft_reader->return_loan(data_seq, info_seq);
if (retcode != DDS_RETCODE_OK) {
printf("return loan error %d\n", retcode);
}
}
/* Delete all entities */
static int subscriber_shutdown(
DDSDomainParticipant *participant)
{
DDS_ReturnCode_t retcode;
int status = 0;
if (participant != NULL) {
retcode = participant->delete_contained_entities();
if (retcode != DDS_RETCODE_OK) {
printf("delete_contained_entities error %d\n", retcode);
status = -1;
}
retcode = DDSTheParticipantFactory->delete_participant(participant);
if (retcode != DDS_RETCODE_OK) {
printf("delete_participant error %d\n", retcode);
status = -1;
}
}
/* RTI Connext provides the finalize_instance() method on
domain participant factory for people who want to release memory used
by the participant factory. Uncomment the following block of code for
clean destruction of the singleton. */
/*
retcode = DDSDomainParticipantFactory::finalize_instance();
if (retcode != DDS_RETCODE_OK) {
printf("finalize_instance error %d\n", retcode);
status = -1;
}
*/
return status;
}
extern "C" int subscriber_main(int domainId, int sample_count, int sel_cft)
{
DDSDomainParticipant *participant = NULL;
DDSSubscriber *subscriber = NULL;
DDSTopic *topic = NULL;
cftListener *reader_listener = NULL;
DDSDataReader *reader = NULL;
DDS_ReturnCode_t retcode;
const char *type_name = NULL;
int count = 0;
DDS_Duration_t receive_period = {1,0};
int status = 0;
/* To customize the participant QoS, use
the configuration file USER_QOS_PROFILES.xml */
participant = DDSTheParticipantFactory->create_participant(
domainId, DDS_PARTICIPANT_QOS_DEFAULT,
NULL /* listener */, DDS_STATUS_MASK_NONE);
if (participant == NULL) {
printf("create_participant error\n");
subscriber_shutdown(participant);
return -1;
}
/* To customize the subscriber QoS, use
the configuration file USER_QOS_PROFILES.xml */
subscriber = participant->create_subscriber(
DDS_SUBSCRIBER_QOS_DEFAULT, NULL /* listener */, DDS_STATUS_MASK_NONE);
if (subscriber == NULL) {
printf("create_subscriber error\n");
subscriber_shutdown(participant);
return -1;
}
/* Register the type before creating the topic */
type_name = cftTypeSupport::get_type_name();
retcode = cftTypeSupport::register_type(
participant, type_name);
if (retcode != DDS_RETCODE_OK) {
printf("register_type error %d\n", retcode);
subscriber_shutdown(participant);
return -1;
}
/* To customize the topic QoS, use
the configuration file USER_QOS_PROFILES.xml */
topic = participant->create_topic(
"Example cft",
type_name, DDS_TOPIC_QOS_DEFAULT, NULL /* listener */,
DDS_STATUS_MASK_NONE);
if (topic == NULL) {
printf("create_topic error\n");
subscriber_shutdown(participant);
return -1;
}
/* Sequence of parameters for the content filter expression */
DDS_StringSeq parameters(2);
/* The default parameter list that we will include in the
* sequence of parameters will be "1","4" (i.e., 1 <= x <= 4). */
const char* param_list[] = {"1", "4"};
parameters.from_array(param_list, 2);
/* Create the content filtered topic in case sel_cft
* is true.
* The Content Filter Expresion has two parameters:
* - %0 -- x must be greater or equal than %0.
* - %1 -- x must be less or equal than %1.
*/
DDSContentFilteredTopic *cft = NULL;
if (sel_cft) {
cft = participant->create_contentfilteredtopic(
"ContentFilteredTopic", topic, "(x >= %0 and x <= %1)", parameters);
if (cft == NULL) {
printf("create_contentfilteredtopic error\n");
subscriber_shutdown(participant);
return -1;
}
}
/* Create a data reader listener */
reader_listener = new cftListener();
/* Here we create the reader either using a Content Filtered Topic or
* a normal topic */
if (sel_cft) {
printf("Using ContentFiltered Topic\n");
reader = subscriber->create_datareader(
cft, DDS_DATAREADER_QOS_DEFAULT, reader_listener,
DDS_STATUS_MASK_ALL);
} else {
printf("Using Normal Topic\n");
reader = subscriber->create_datareader(
topic, DDS_DATAREADER_QOS_DEFAULT, reader_listener,
DDS_STATUS_MASK_ALL);
}
if (reader == NULL) {
printf("create_datareader error\n");
subscriber_shutdown(participant);
delete reader_listener;
return -1;
}
/* If you want to set the reliability and history QoS settings
* programmatically rather than using the XML, you will need to add
* the following lines to your code and comment out the create_datareader
* calls above.
*/
/*
DDS_DataReaderQos datareader_qos;
retcode = subscriber->get_default_datareader_qos(datareader_qos);
if (retcode != DDS_RETCODE_OK) {
printf("get_default_datareader_qos error\n");
return -1;
}
datareader_qos.reliability.kind = DDS_RELIABLE_RELIABILITY_QOS;
datareader_qos.durability.kind = DDS_TRANSIENT_LOCAL_DURABILITY_QOS;
datareader_qos.history.kind = DDS_KEEP_LAST_HISTORY_QOS;
datareader_qos.history.depth = 20;
if (sel_cft) {
printf("Using ContentFiltered Topic\n");
reader = subscriber->create_datareader(
cft, datareader_qos, reader_listener,
DDS_STATUS_MASK_ALL);
} else {
printf("Using Normal Topic\n");
reader = subscriber->create_datareader(
topic, datareader_qos, reader_listener,
DDS_STATUS_MASK_ALL);
}
if (reader == NULL) {
printf("create_datareader error\n");
subscriber_shutdown(participant);
delete reader_listener;
return -1;
}
*/
if (sel_cft) {
printf("\n==========================\n");
printf("Using CFT\nFilter: 1 <= x <= 4\n");
printf("===========================\n");
}
/* Main loop */
for (count=0; (sample_count == 0) || (count < sample_count); ++count) {
/* Receive period of 1 second. */
NDDSUtility::sleep(receive_period);
/* If we are not using CFT, we do not need to change the filter
* parameters */
if (sel_cft == 0) {
continue;
}
if (count == 10) {
printf("\n==========================\n");
printf("Changing filter parameters\n");
printf("Filter: 5 <= x <= 9\n");
printf("===========================\n");
DDS_String_free(parameters[0]);
DDS_String_free(parameters[1]);
parameters[0] = DDS_String_dup("5");
parameters[1] = DDS_String_dup("9");
retcode = cft->set_expression_parameters(parameters);
if (retcode != DDS_RETCODE_OK) {
printf("set_expression_parameters error\n");
subscriber_shutdown(participant);
return -1;
}
} else if (count == 20) {
printf("\n==========================\n");
printf("Changing filter parameters\n");
printf("Filter: 3 <= x <= 9\n");
printf("===========================\n");
DDS_StringSeq oldParameters;
cft->get_expression_parameters(oldParameters);
DDS_String_free(oldParameters[0]);
oldParameters[0] = DDS_String_dup("3");
retcode = cft->set_expression_parameters(oldParameters);
if (retcode != DDS_RETCODE_OK) {
printf("set_expression_parameters error\n");
subscriber_shutdown(participant);
return -1;
}
}
}
/* Delete all entities */
status = subscriber_shutdown(participant);
delete reader_listener;
return status;
}
#if defined(RTI_WINCE)
int wmain(int argc, wchar_t** argv)
{
int domainId = 0;
int sample_count = 0; /* infinite loop */
if (argc >= 2) {
domainId = _wtoi(argv[1]);
}
if (argc >= 3) {
sample_count = _wtoi(argv[2]);
}
/* Uncomment this to turn on additional logging
NDDSConfigLogger::get_instance()->
set_verbosity_by_category(NDDS_CONFIG_LOG_CATEGORY_API,
NDDS_CONFIG_LOG_VERBOSITY_STATUS_ALL);
*/
return subscriber_main(domainId, sample_count);
}
#elif !(defined(RTI_VXWORKS) && !defined(__RTP__)) && !defined(RTI_PSOS)
int main(int argc, char *argv[])
{
int domainId = 0;
int sample_count = 0; /* infinite loop */
int sel_cft = 1; /* Use content filtered topic? */
if (argc >= 2) {
domainId = atoi(argv[1]);
}
if (argc >= 3) {
sample_count = atoi(argv[2]);
}
if (argc >= 4) {
sel_cft = atoi(argv[3]);
}
/* Uncomment this to turn on additional logging
NDDSConfigLogger::get_instance()->
set_verbosity_by_category(NDDS_CONFIG_LOG_CATEGORY_API,
NDDS_CONFIG_LOG_VERBOSITY_STATUS_ALL);
*/
return subscriber_main(domainId, sample_count, sel_cft);
}
#endif
#ifdef RTI_VX653
const unsigned char* __ctype = *(__ctypePtrGet());
extern "C" void usrAppInit ()
{
#ifdef USER_APPL_INIT
USER_APPL_INIT; /* for backwards compatibility */
#endif
/* add application specific code here */
taskSpawn("sub", RTI_OSAPI_THREAD_PRIORITY_NORMAL, 0x8, 0x150000, (FUNCPTR)subscriber_main, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
}
#endif
| cxx |
rticonnextdds-examples | data/projects/rticonnextdds-examples/content_filtered_topic/c/cft_publisher.c | /*******************************************************************************
(c) 2005-2014 Copyright, Real-Time Innovations, Inc. All rights reserved.
RTI grants Licensee a license to use, modify, compile, and create derivative
works of the Software. Licensee has the right to distribute object form only
for use with RTI products. The Software is provided "as is", with no warranty
of any type, including any warranty for fitness for any purpose. RTI is under
no obligation to maintain or support the Software. RTI shall not be liable for
any incidental or consequential damages arising out of the use or inability to
use the software.
******************************************************************************/
/* cft_publisher.c
A publication of data of type cft
This file is derived from code automatically generated by the rtiddsgen
command:
rtiddsgen -language C -example <arch> cft.idl
Example publication of type cft automatically generated by
'rtiddsgen'. To test them follow these steps:
(1) Compile this file and the example subscription.
(2) Start the subscription with the command
objs/<arch>/cft_subscriber <domain_id> <sample_count>
(3) Start the publication with the command
objs/<arch>/cft_publisher <domain_id> <sample_count>
(4) [Optional] Specify the list of discovery initial peers and
multicast receive addresses via an environment variable or a file
(in the current working directory) called NDDS_DISCOVERY_PEERS.
You can run any number of publishers and subscribers programs, and can
add and remove them dynamically from the domain.
Example:
To run the example application on domain <domain_id>:
On Unix:
objs/<arch>/cft_publisher <domain_id>
objs/<arch>/cft_subscriber <domain_id>
On Windows:
objs\<arch>\cft_publisher <domain_id>
objs\<arch>\cft_subscriber <domain_id>
modification history
------------ -------
*/
#include <stdio.h>
#include <stdlib.h>
#include "ndds/ndds_c.h"
#include "cft.h"
#include "cftSupport.h"
/* Delete all entities */
static int publisher_shutdown(
DDS_DomainParticipant *participant)
{
DDS_ReturnCode_t retcode;
int status = 0;
if (participant != NULL) {
retcode = DDS_DomainParticipant_delete_contained_entities(participant);
if (retcode != DDS_RETCODE_OK) {
printf("delete_contained_entities error %d\n", retcode);
status = -1;
}
retcode = DDS_DomainParticipantFactory_delete_participant(
DDS_TheParticipantFactory, participant);
if (retcode != DDS_RETCODE_OK) {
printf("delete_participant error %d\n", retcode);
status = -1;
}
}
/* RTI Connext provides finalize_instance() method on
domain participant factory for people who want to release memory used
by the participant factory. Uncomment the following block of code for
clean destruction of the singleton. */
/*
retcode = DDS_DomainParticipantFactory_finalize_instance();
if (retcode != DDS_RETCODE_OK) {
printf("finalize_instance error %d\n", retcode);
status = -1;
}
*/
return status;
}
static int publisher_main(int domainId, int sample_count)
{
DDS_DomainParticipant *participant = NULL;
DDS_Publisher *publisher = NULL;
DDS_Topic *topic = NULL;
DDS_DataWriter *writer = NULL;
cftDataWriter *cft_writer = NULL;
cft *instance = NULL;
DDS_ReturnCode_t retcode;
DDS_InstanceHandle_t instance_handle = DDS_HANDLE_NIL;
const char *type_name = NULL;
int count = 0;
/* Send a new sample every second */
struct DDS_Duration_t send_period = {1,0};
/* We need this structure in case we want to change the datawriter_qos
* programmatically.*/
struct DDS_DataWriterQos datawriter_qos = DDS_DataWriterQos_INITIALIZER;
/* To customize participant QoS, use
the configuration file USER_QOS_PROFILES.xml */
participant = DDS_DomainParticipantFactory_create_participant(
DDS_TheParticipantFactory, domainId, &DDS_PARTICIPANT_QOS_DEFAULT,
NULL /* listener */, DDS_STATUS_MASK_NONE);
if (participant == NULL) {
printf("create_participant error\n");
publisher_shutdown(participant);
return -1;
}
/* To customize publisher QoS, use
the configuration file USER_QOS_PROFILES.xml */
publisher = DDS_DomainParticipant_create_publisher(
participant, &DDS_PUBLISHER_QOS_DEFAULT, NULL /* listener */,
DDS_STATUS_MASK_NONE);
if (publisher == NULL) {
printf("create_publisher error\n");
publisher_shutdown(participant);
return -1;
}
/* Register type before creating topic */
type_name = cftTypeSupport_get_type_name();
retcode = cftTypeSupport_register_type(
participant, type_name);
if (retcode != DDS_RETCODE_OK) {
printf("register_type error %d\n", retcode);
publisher_shutdown(participant);
return -1;
}
/* To customize topic QoS, use
the configuration file USER_QOS_PROFILES.xml */
topic = DDS_DomainParticipant_create_topic(
participant, "Example cft",
type_name, &DDS_TOPIC_QOS_DEFAULT, NULL /* listener */,
DDS_STATUS_MASK_NONE);
if (topic == NULL) {
printf("create_topic error\n");
publisher_shutdown(participant);
return -1;
}
/* To customize data writer QoS, use
the configuration file USER_QOS_PROFILES.xml */
writer = DDS_Publisher_create_datawriter(
publisher, topic,
&DDS_DATAWRITER_QOS_DEFAULT, NULL, DDS_STATUS_MASK_NONE);
if (writer == NULL) {
printf("create_datawriter error\n");
publisher_shutdown(participant);
return -1;
}
/* If you want to set the reliability and history QoS settings
* programmatically rather than using the XML, you will need to add
* the following lines to your code and comment out the create_datawriter
* call above.
*/
/*
retcode = DDS_Publisher_get_default_datawriter_qos(publisher,
&datawriter_qos);
if (retcode != DDS_RETCODE_OK) {
printf("get_default_datawriter_qos error\n");
return -1;
}
datawriter_qos.reliability.kind = DDS_RELIABLE_RELIABILITY_QOS;
datawriter_qos.durability.kind = DDS_TRANSIENT_LOCAL_DURABILITY_QOS;
datawriter_qos.history.kind = DDS_KEEP_LAST_HISTORY_QOS;
datawriter_qos.history.depth = 20;
writer = DDS_Publisher_create_datawriter(
publisher, topic,
&datawriter_qos, NULL, DDS_STATUS_MASK_NONE);
if (writer == NULL) {
printf("create_datawriter error\n");
publisher_shutdown(participant);
return -1;
}
*/
cft_writer = cftDataWriter_narrow(writer);
if (cft_writer == NULL) {
printf("DataWriter narrow error\n");
publisher_shutdown(participant);
return -1;
}
/* Create data sample for writing */
instance = cftTypeSupport_create_data_ex(DDS_BOOLEAN_TRUE);
if (instance == NULL) {
printf("cftTypeSupport_create_data error\n");
publisher_shutdown(participant);
return -1;
}
/* For a data type that has a key, if the same instance is going to be
written multiple times, initialize the key here
and register the keyed instance prior to writing */
/*
instance_handle = cftDataWriter_register_instance(
cft_writer, instance);
*/
/* Main loop */
for (count=0; (sample_count == 0) || (count < sample_count); ++count) {
/* Modify the data to be written here */
/* Our purpose is to increment x every time we send a sample and to
* reset the x counter to 0 every time we send 10 samples (x=0,1,..,9).
* Using the value of count, we can get set x to the appropriate value
* applying % 10 operation to it.
*/
instance->count = count;
instance->x = count%10;
printf("Writing cft, count %d\tx=%d\n", instance->count, instance->x);
/* Write data */
retcode = cftDataWriter_write(
cft_writer, instance, &instance_handle);
if (retcode != DDS_RETCODE_OK) {
printf("write error %d\n", retcode);
}
NDDS_Utility_sleep(&send_period);
}
/*
retcode = cftDataWriter_unregister_instance(
cft_writer, instance, &instance_handle);
if (retcode != DDS_RETCODE_OK) {
printf("unregister instance error %d\n", retcode);
}
*/
/* Delete data sample */
retcode = cftTypeSupport_delete_data_ex(instance, DDS_BOOLEAN_TRUE);
if (retcode != DDS_RETCODE_OK) {
printf("cftTypeSupport_delete_data error %d\n", retcode);
}
/* Cleanup and delete delete all entities */
return publisher_shutdown(participant);
}
#if defined(RTI_WINCE)
int wmain(int argc, wchar_t** argv)
{
int domainId = 0;
int sample_count = 0; /* infinite loop */
if (argc >= 2) {
domainId = _wtoi(argv[1]);
}
if (argc >= 3) {
sample_count = _wtoi(argv[2]);
}
/* Uncomment this to turn on additional logging
NDDS_Config_Logger_set_verbosity_by_category(
NDDS_Config_Logger_get_instance(),
NDDS_CONFIG_LOG_CATEGORY_API,
NDDS_CONFIG_LOG_VERBOSITY_STATUS_ALL);
*/
return publisher_main(domainId, sample_count);
}
#elif !(defined(RTI_VXWORKS) && !defined(__RTP__)) && !defined(RTI_PSOS)
int main(int argc, char *argv[])
{
int domainId = 0;
int sample_count = 0; /* infinite loop */
if (argc >= 2) {
domainId = atoi(argv[1]);
}
if (argc >= 3) {
sample_count = atoi(argv[2]);
}
/* Uncomment this to turn on additional logging
NDDS_Config_Logger_set_verbosity_by_category(
NDDS_Config_Logger_get_instance(),
NDDS_CONFIG_LOG_CATEGORY_API,
NDDS_CONFIG_LOG_VERBOSITY_STATUS_ALL);
*/
return publisher_main(domainId, sample_count);
}
#endif
#ifdef RTI_VX653
const unsigned char* __ctype = NULL;
void usrAppInit ()
{
#ifdef USER_APPL_INIT
USER_APPL_INIT; /* for backwards compatibility */
#endif
/* add application specific code here */
taskSpawn("pub", RTI_OSAPI_THREAD_PRIORITY_NORMAL, 0x8, 0x150000, (FUNCPTR)publisher_main, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
}
#endif
| c |
rticonnextdds-examples | data/projects/rticonnextdds-examples/content_filtered_topic/c/cft_subscriber.c | /*******************************************************************************
(c) 2005-2014 Copyright, Real-Time Innovations, Inc. All rights reserved.
RTI grants Licensee a license to use, modify, compile, and create derivative
works of the Software. Licensee has the right to distribute object form only
for use with RTI products. The Software is provided "as is", with no warranty
of any type, including any warranty for fitness for any purpose. RTI is under
no obligation to maintain or support the Software. RTI shall not be liable for
any incidental or consequential damages arising out of the use or inability to
use the software.
******************************************************************************/
/* cft_subscriber.c
A subscription example
This file is derived from code automatically generated by the rtiddsgen
command:
rtiddsgen -language C -example <arch> cft.idl
Example subscription of type cft automatically generated by
'rtiddsgen'. To test them, follow these steps:
(1) Compile this file and the example publication.
(2) Start the subscription with the command
objs/<arch>/cft_subscriber <domain_id> <sample_count>
(3) Start the publication with the command
objs/<arch>/cft_publisher <domain_id> <sample_count>
(4) [Optional] Specify the list of discovery initial peers and
multicast receive addresses via an environment variable or a file
(in the current working directory) called NDDS_DISCOVERY_PEERS.
You can run any number of publishers and subscribers programs, and can
add and remove them dynamically from the domain.
Example:
To run the example application on domain <domain_id>:
On UNIX systems:
objs/<arch>/cft_publisher <domain_id>
objs/<arch>/cft_subscriber <domain_id>
On Windows systems:
objs\<arch>\cft_publisher <domain_id>
objs\<arch>\cft_subscriber <domain_id>
modification history
------------ -------
*/
#include <stdio.h>
#include <stdlib.h>
#include "ndds/ndds_c.h"
#include "cft.h"
#include "cftSupport.h"
void cftListener_on_requested_deadline_missed(
void* listener_data,
DDS_DataReader* reader,
const struct DDS_RequestedDeadlineMissedStatus *status)
{
}
void cftListener_on_requested_incompatible_qos(
void* listener_data,
DDS_DataReader* reader,
const struct DDS_RequestedIncompatibleQosStatus *status)
{
}
void cftListener_on_sample_rejected(
void* listener_data,
DDS_DataReader* reader,
const struct DDS_SampleRejectedStatus *status)
{
}
void cftListener_on_liveliness_changed(
void* listener_data,
DDS_DataReader* reader,
const struct DDS_LivelinessChangedStatus *status)
{
}
void cftListener_on_sample_lost(
void* listener_data,
DDS_DataReader* reader,
const struct DDS_SampleLostStatus *status)
{
}
void cftListener_on_subscription_matched(
void* listener_data,
DDS_DataReader* reader,
const struct DDS_SubscriptionMatchedStatus *status)
{
}
void cftListener_on_data_available(
void* listener_data,
DDS_DataReader* reader)
{
cftDataReader *cft_reader = NULL;
struct cftSeq data_seq = DDS_SEQUENCE_INITIALIZER;
struct DDS_SampleInfoSeq info_seq = DDS_SEQUENCE_INITIALIZER;
DDS_ReturnCode_t retcode;
int i;
cft_reader = cftDataReader_narrow(reader);
if (cft_reader == NULL) {
printf("DataReader narrow error\n");
return;
}
retcode = cftDataReader_take(
cft_reader,
&data_seq, &info_seq, DDS_LENGTH_UNLIMITED,
DDS_ANY_SAMPLE_STATE, DDS_ANY_VIEW_STATE, DDS_ANY_INSTANCE_STATE);
if (retcode == DDS_RETCODE_NO_DATA) {
return;
} else if (retcode != DDS_RETCODE_OK) {
printf("take error %d\n", retcode);
return;
}
for (i = 0; i < cftSeq_get_length(&data_seq); ++i) {
if (DDS_SampleInfoSeq_get_reference(&info_seq, i)->valid_data) {
cftTypeSupport_print_data(
cftSeq_get_reference(&data_seq, i));
}
}
retcode = cftDataReader_return_loan(
cft_reader,
&data_seq, &info_seq);
if (retcode != DDS_RETCODE_OK) {
printf("return loan error %d\n", retcode);
}
}
/* Delete all entities */
static int subscriber_shutdown(
DDS_DomainParticipant *participant)
{
DDS_ReturnCode_t retcode;
int status = 0;
if (participant != NULL) {
retcode = DDS_DomainParticipant_delete_contained_entities(participant);
if (retcode != DDS_RETCODE_OK) {
printf("delete_contained_entities error %d\n", retcode);
status = -1;
}
retcode = DDS_DomainParticipantFactory_delete_participant(
DDS_TheParticipantFactory, participant);
if (retcode != DDS_RETCODE_OK) {
printf("delete_participant error %d\n", retcode);
status = -1;
}
}
/* RTI Connext provides the finalize_instance() method on
domain participant factory for users who want to release memory used
by the participant factory. Uncomment the following block of code for
clean destruction of the singleton. */
/*
retcode = DDS_DomainParticipantFactory_finalize_instance();
if (retcode != DDS_RETCODE_OK) {
printf("finalize_instance error %d\n", retcode);
status = -1;
}
*/
return status;
}
/* The subscribrer_main function gets an extra parameter called
* sel_cft that specifies whether to apply content filtering
* or not.
*/
static int subscriber_main(int domainId, int sample_count, int sel_cft)
{
DDS_DomainParticipant *participant = NULL;
DDS_Subscriber *subscriber = NULL;
DDS_Topic *topic = NULL;
struct DDS_DataReaderListener reader_listener =
DDS_DataReaderListener_INITIALIZER;
DDS_DataReader *reader = NULL;
DDS_ReturnCode_t retcode;
const char *type_name = NULL;
int count = 0;
struct DDS_Duration_t poll_period = {1,0};
/* If you want to modify datareader_qos programatically you
* will need to use the following structure. */
struct DDS_DataReaderQos datareader_qos = DDS_DataReaderQos_INITIALIZER;
/* Sequence of parameters for the content filter expression */
struct DDS_StringSeq parameters;
/* The default parameter list that we will include in the
* sequence of parameters will be "1","4" (i.e., 1 <= x <= 4). */
const char* param_list[] = {"1", "4"};
/* Content Filtered Topic */
DDS_ContentFilteredTopic *cft = NULL;
/* To customize participant QoS, use
the configuration file USER_QOS_PROFILES.xml */
participant = DDS_DomainParticipantFactory_create_participant(
DDS_TheParticipantFactory, domainId, &DDS_PARTICIPANT_QOS_DEFAULT,
NULL /* listener */, DDS_STATUS_MASK_NONE);
if (participant == NULL) {
printf("create_participant error\n");
subscriber_shutdown(participant);
return -1;
}
/* To customize subscriber QoS, use
the configuration file USER_QOS_PROFILES.xml */
subscriber = DDS_DomainParticipant_create_subscriber(
participant, &DDS_SUBSCRIBER_QOS_DEFAULT, NULL /* listener */,
DDS_STATUS_MASK_NONE);
if (subscriber == NULL) {
printf("create_subscriber error\n");
subscriber_shutdown(participant);
return -1;
}
/* Register the type before creating the topic */
type_name = cftTypeSupport_get_type_name();
retcode = cftTypeSupport_register_type(participant, type_name);
if (retcode != DDS_RETCODE_OK) {
printf("register_type error %d\n", retcode);
subscriber_shutdown(participant);
return -1;
}
/* To customize topic QoS, use
the configuration file USER_QOS_PROFILES.xml */
topic = DDS_DomainParticipant_create_topic(
participant, "Example cft",
type_name, &DDS_TOPIC_QOS_DEFAULT, NULL /* listener */,
DDS_STATUS_MASK_NONE);
if (topic == NULL) {
printf("create_topic error\n");
subscriber_shutdown(participant);
return -1;
}
/* Create the content filtered topic in case sel_cft
* is true.
* The Content Filter Expresion has two parameters:
* - %0 -- x must be greater or equal than %0.
* - %1 -- x must be less or equal than %1.
*/
DDS_StringSeq_initialize(¶meters);
DDS_StringSeq_set_maximum(¶meters, 2);
/* Here we set the default filter to 1 <= x <= 4 */
DDS_StringSeq_from_array(¶meters, param_list, 2);
if (sel_cft) {
cft = DDS_DomainParticipant_create_contentfilteredtopic(
participant,
"ContentFilteredTopic", topic, "(x >= %0 and x <= %1)", ¶meters);
if (cft == NULL) {
printf("create_contentfilteredtopic error\n");
subscriber_shutdown(participant);
return -1;
}
}
/* Set up a data reader listener */
reader_listener.on_requested_deadline_missed =
cftListener_on_requested_deadline_missed;
reader_listener.on_requested_incompatible_qos =
cftListener_on_requested_incompatible_qos;
reader_listener.on_sample_rejected =
cftListener_on_sample_rejected;
reader_listener.on_liveliness_changed =
cftListener_on_liveliness_changed;
reader_listener.on_sample_lost =
cftListener_on_sample_lost;
reader_listener.on_subscription_matched =
cftListener_on_subscription_matched;
reader_listener.on_data_available =
cftListener_on_data_available;
/* To customize data reader QoS, use
the configuration file USER_QOS_PROFILES.xml */
if (sel_cft) {
printf("Using ContentFiltered Topic\n");
reader = DDS_Subscriber_create_datareader(
subscriber, DDS_ContentFilteredTopic_as_topicdescription(cft),
&DDS_DATAREADER_QOS_DEFAULT, &reader_listener, DDS_STATUS_MASK_ALL);
} else {
printf("Using Normal Topic\n");
reader = DDS_Subscriber_create_datareader(
subscriber, DDS_Topic_as_topicdescription(topic),
&DDS_DATAREADER_QOS_DEFAULT, &reader_listener, DDS_STATUS_MASK_ALL);
}
if (reader == NULL) {
printf("create_datareader error\n");
subscriber_shutdown(participant);
return -1;
}
/* If you want to set the reliability and history QoS settings
* programmatically rather than using the XML, you will need to add
* the following lines to your code and comment out the create_datareader
* calls above.
*/
/*
retcode = DDS_Subscriber_get_default_datareader_qos(subscriber, &datareader_qos);
if (retcode != DDS_RETCODE_OK) {
printf("get_default_datareader_qos error\n");
return -1;
}
datareader_qos.reliability.kind = DDS_RELIABLE_RELIABILITY_QOS;
datareader_qos.durability.kind = DDS_TRANSIENT_LOCAL_DURABILITY_QOS;
datareader_qos.history.kind = DDS_KEEP_LAST_HISTORY_QOS;
datareader_qos.history.depth = 20;
if (sel_cft) {
printf("Using ContentFiltered Topic\n");
reader = DDS_Subscriber_create_datareader(
subscriber, DDS_ContentFilteredTopic_as_topicdescription(cft),
&datareader_qos, &reader_listener, DDS_STATUS_MASK_ALL);
} else {
printf("Using Normal Topic\n");
reader = DDS_Subscriber_create_datareader(
subscriber, DDS_Topic_as_topicdescription(topic),
&datareader_qos, &reader_listener, DDS_STATUS_MASK_ALL);
}
if (reader == NULL) {
printf("create_datareader error\n");
subscriber_shutdown(participant);
return -1;
}
*/
if (sel_cft) {
printf("\n==========================\n");
printf("Using CFT\nFilter: 1 <= x <= 4\n");
printf("===========================\n");
}
/* Main loop */
for (count=0; (sample_count == 0) || (count < sample_count); ++count) {
/* Pool period of 1 second. */
NDDS_Utility_sleep(&poll_period);
/* If we are not using CFT, we do not need to change the filter
* parameters */
if (sel_cft == 0) {
continue;
}
if (count == 10) {
printf("\n==========================\n");
printf("Changing filter parameters\n");
printf("Filter: 5 <= x <= 9\n");
printf("===========================\n");
DDS_String_free(DDS_StringSeq_get(¶meters, 0));
DDS_String_free(DDS_StringSeq_get(¶meters, 1));
*DDS_StringSeq_get_reference(¶meters, 0) = DDS_String_dup("5");
*DDS_StringSeq_get_reference(¶meters, 1) = DDS_String_dup("9");
retcode = DDS_ContentFilteredTopic_set_expression_parameters(
cft, ¶meters);
if (retcode != DDS_RETCODE_OK) {
printf("set_expression_parameters error\n");
subscriber_shutdown(participant);
return -1;
}
} else if (count == 20) {
struct DDS_StringSeq oldParameters;
printf("\n==========================\n");
printf("Changing filter parameters\n");
printf("Filter: 3 <= x <= 9\n");
printf("===========================\n");
DDS_ContentFilteredTopic_get_expression_parameters(
cft, &oldParameters);
DDS_String_free(DDS_StringSeq_get(&oldParameters, 0));
*DDS_StringSeq_get_reference(&oldParameters, 0) = DDS_String_dup("3");
retcode = DDS_ContentFilteredTopic_set_expression_parameters(
cft, &oldParameters);
if (retcode != DDS_RETCODE_OK) {
printf("set_expression_parameters error\n");
subscriber_shutdown(participant);
return -1;
}
}
}
/* Cleanup and delete all entities */
return subscriber_shutdown(participant);
}
#if defined(RTI_WINCE)
int wmain(int argc, wchar_t** argv)
{
int domainId = 0;
int sample_count = 0; /* infinite loop */
if (argc >= 2) {
domainId = _wtoi(argv[1]);
}
if (argc >= 3) {
sample_count = _wtoi(argv[2]);
}
/* Uncomment this to turn on additional logging
NDDS_Config_Logger_set_verbosity_by_category(
NDDS_Config_Logger_get_instance(),
NDDS_CONFIG_LOG_CATEGORY_API,
NDDS_CONFIG_LOG_VERBOSITY_STATUS_ALL);
*/
return subscriber_main(domainId, sample_count);
}
#elif !(defined(RTI_VXWORKS) && !defined(__RTP__)) && !defined(RTI_PSOS)
int main(int argc, char *argv[])
{
int domainId = 0;
int sample_count = 0; /* infinite loop */
int sel_cft = 1; /* Use content filtered topic? */
if (argc >= 2) {
domainId = atoi(argv[1]);
}
if (argc >= 3) {
sample_count = atoi(argv[2]);
}
if (argc >= 4) {
sel_cft = atoi(argv[3]);
}
/* Uncomment this to turn on additional logging
NDDS_Config_Logger_set_verbosity_by_category(
NDDS_Config_Logger_get_instance(),
NDDS_CONFIG_LOG_CATEGORY_API,
NDDS_CONFIG_LOG_VERBOSITY_STATUS_ALL);
*/
return subscriber_main(domainId, sample_count, sel_cft);
}
#endif
#ifdef RTI_VX653
const unsigned char* __ctype = NULL;
void usrAppInit ()
{
#ifdef USER_APPL_INIT
USER_APPL_INIT; /* for backwards compatibility */
#endif
/* add application specific code here */
taskSpawn("sub", RTI_OSAPI_THREAD_PRIORITY_NORMAL, 0x8, 0x150000, (FUNCPTR)subscriber_main, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
}
#endif
| c |
rticonnextdds-examples | data/projects/rticonnextdds-examples/content_filtered_topic/c++03/cft_publisher.cxx | /*******************************************************************************
(c) 2005-2015 Copyright, Real-Time Innovations, Inc. All rights reserved.
RTI grants Licensee a license to use, modify, compile, and create derivative
works of the Software. Licensee has the right to distribute object form only
for use with RTI products. The Software is provided "as is", with no warranty
of any type, including any warranty for fitness for any purpose. RTI is under
no obligation to maintain or support the Software. RTI shall not be liable for
any incidental or consequential damages arising out of the use or inability to
use the software.
******************************************************************************/
#include "cft.hpp"
#include <dds/dds.hpp>
using namespace dds::core;
using namespace dds::core::policy;
using namespace dds::domain;
using namespace dds::topic;
using namespace dds::pub;
using namespace dds::pub::qos;
void publisher_main(int domain_id, int sample_count)
{
// To customize any of the entities QoS, use
// the configuration file USER_QOS_PROFILES.xml
DomainParticipant participant (domain_id);
Topic<cft> topic (participant, "Example cft");
DataWriterQos writer_qos = QosProvider::Default().datawriter_qos();
// If you want to set the reliability and history QoS settings
// programmatically rather than using the XML, you will need to comment out
// the following lines of code.
// writer_qos << Reliability::Reliable()
// << Durability::TransientLocal()
// << History::KeepLast(20);
DataWriter<cft> writer (Publisher(participant), topic, writer_qos);
// Create data sample for writing
cft instance;
// For a data type that has a key, if the same instance is going to be
// written multiple times, initialize the key here
// and register the keyed instance prior to writing.
InstanceHandle instance_handle = InstanceHandle::nil();
// instance_handle = writer.register_instance(instance);
// Main loop
for (int count = 0; (sample_count == 0) || (count < sample_count); ++count) {
// Modify the data to be sent here
// Our purpose is to increment x every time we send a sample and to
// reset the x counter to 0 every time we send 10 samples (x=0,1,..,9).
// Using the value of count, we can get set x to the appropriate value
// applying % 10 operation to it.
instance.count(count);
instance.x(count % 10);
std::cout << "Writing cft, count " << instance.count() << "\t"
<< "x=" << instance.x() << std::endl;
writer.write(instance, instance_handle);
// Send a new sample every second
rti::util::sleep(Duration(1));
}
// writer.unregister_instance(instance_handle);
}
int main(int argc, char *argv[])
{
int domain_id = 0;
int sample_count = 0; /* infinite loop */
if (argc >= 2) {
domain_id = atoi(argv[1]);
}
if (argc >= 3) {
sample_count = atoi(argv[2]);
}
// To turn on additional logging, include <rti/config/Logger.hpp> and
// uncomment the following line:
// rti::config::Logger::instance().verbosity(rti::config::Verbosity::STATUS_ALL);
try {
publisher_main(domain_id, sample_count);
} catch (const std::exception& ex) {
// This will catch DDS exceptions
std::cerr << "Exception in publisher_main(): " << ex.what() << std::endl;
return -1;
}
return 0;
}
| cxx |
rticonnextdds-examples | data/projects/rticonnextdds-examples/content_filtered_topic/c++03/cft_subscriber.cxx | /*******************************************************************************
(c) 2005-2015 Copyright, Real-Time Innovations, Inc. All rights reserved.
RTI grants Licensee a license to use, modify, compile, and create derivative
works of the Software. Licensee has the right to distribute object form only
for use with RTI products. The Software is provided "as is", with no warranty
of any type, including any warranty for fitness for any purpose. RTI is under
no obligation to maintain or support the Software. RTI shall not be liable for
any incidental or consequential damages arising out of the use or inability to
use the software.
******************************************************************************/
#include "cft.hpp"
#include <dds/dds.hpp>
#include <rti/core/ListenerBinder.hpp>
using namespace dds::core;
using namespace dds::core::status;
using namespace dds::core::policy;
using namespace dds::domain;
using namespace dds::topic;
using namespace dds::sub;
using namespace dds::sub::qos;
class CftListener : public NoOpDataReaderListener<cft> {
public:
void on_data_available(DataReader<cft> &reader)
{
// Take the available data
LoanedSamples<cft> samples = reader.take();
// Print samples by copying to std::cout
for (LoanedSamples<cft>::iterator sampleIt = samples.begin();
sampleIt != samples.end();
++sampleIt) {
if (sampleIt->info().valid()) {
std::cout << sampleIt->data() << std::endl;
}
}
}
};
void subscriber_main(int domain_id, int sample_count, bool is_cft)
{
// To customize any of the entities QoS, use
// the configuration file USER_QOS_PROFILES.xml
DomainParticipant participant (domain_id);
Topic<cft> topic (participant, "Example cft");
// Sequence of parameters for the content filter expression
std::vector<std::string> parameters(2);
// The default parameter list that we will include in the
// sequence of parameters will be "1", "4" (i.e., 1 <= x <= 4).
parameters[0] = "1";
parameters[1] = "4";
if (is_cft) {
std::cout << std::endl
<< "==========================" << std::endl
<< "Using CFT" << std::endl
<< "Filter: 1 <= x <= 4" << std::endl
<< "==========================" << std::endl;
}
DataReaderQos reader_qos = QosProvider::Default().datareader_qos();
// If you want to set the reliability and history QoS settings
// programmatically rather than using the XML, you will need to comment out
// the following lines of code.
// reader_qos << Reliability::Reliable()
// << Durability::TransientLocal()
// << History::KeepLast(20);
// Create the content filtered topic in the case sel_cft is true
// The Content Filter Expresion has two parameters:
// - %0 -- x must be greater or equal than %0.
// - %1 -- x must be less or equal than %1.
ContentFilteredTopic<cft> cft_topic = dds::core::null;
DataReader<cft> reader = dds::core::null;
if (is_cft) {
std::cout << "Using ContentFiltered Topic" << std::endl;
cft_topic = ContentFilteredTopic<cft>(
topic,
"ContentFilteredTopic",
Filter("x >= %0 AND x <= %1", parameters));
reader = DataReader<cft>(
Subscriber(participant),
cft_topic,
reader_qos);
} else {
std::cout << "Using Normal Topic" << std::endl;
reader = DataReader<cft>(
Subscriber(participant),
topic,
reader_qos);
}
// Create a data reader listener using ListenerBinder, a RAII that
// will take care of setting it to NULL on destruction.
rti::core::ListenerBinder< DataReader<cft> > scoped_listener =
rti::core::bind_and_manage_listener(
reader,
new CftListener,
StatusMask::data_available());
// Main loop
for (int count = 0; (sample_count == 0) || (count < sample_count); ++count){
// Receive period of 1 second.
rti::util::sleep(Duration(1));
// If we are not using CFT, we do not need to change the filter
// parameters
if (!is_cft) {
continue;
}
if (count == 10) {
std::cout << std::endl
<< "==========================" << std::endl
<< "Changing filter parameters" << std::endl
<< "Filter: 5 <= x <= 9" << std::endl
<< "==========================" << std::endl;
parameters[0] = "5";
parameters[1] = "9";
cft_topic.filter_parameters(parameters.begin(), parameters.end());
} else if (count == 20) {
std::cout << std::endl
<< "==========================" << std::endl
<< "Changing filter parameters" << std::endl
<< "Filter: 3 <= x <= 9" << std::endl
<< "==========================" << std::endl;
parameters[0] = "3";
cft_topic.filter_parameters(parameters.begin(), parameters.end());
}
}
}
int main(int argc, char *argv[])
{
int domain_id = 0;
int sample_count = 0; // Infinite loop
bool is_cft = true; // Use content filtered topic?
if (argc >= 2) {
domain_id = atoi(argv[1]);
}
if (argc >= 3) {
sample_count = atoi(argv[2]);
}
if (argc >= 4) {
is_cft = (argv[3][0] == '1');
}
// To turn on additional logging, include <rti/config/Logger.hpp> and
// uncomment the following line:
// rti::config::Logger::instance().verbosity(rti::config::Verbosity::STATUS_ALL);
try {
subscriber_main(domain_id, sample_count, is_cft);
} catch (const std::exception& ex) {
// This will catch DDS exceptions
std::cerr << "Exception in subscriber_main(): " << ex.what() << std::endl;
return -1;
}
return 0;
}
| cxx |
rticonnextdds-examples | data/projects/rticonnextdds-examples/high_priority_first_flow_controller/c++/hpf_publisher.cxx | /*******************************************************************************
(c) 2005-2014 Copyright, Real-Time Innovations, Inc. All rights reserved.
RTI grants Licensee a license to use, modify, compile, and create derivative
works of the Software. Licensee has the right to distribute object form only
for use with RTI products. The Software is provided "as is", with no warranty
of any type, including any warranty for fitness for any purpose. RTI is under
no obligation to maintain or support the Software. RTI shall not be liable for
any incidental or consequential damages arising out of the use or inability to
use the software.
******************************************************************************/
/* hpf_publisher.cxx
A publication of data of type hpf
This file is derived from code automatically generated by the rtiddsgen
command:
rtiddsgen -language C++ -example <arch> hpf.idl
Example publication of type hpf automatically generated by
'rtiddsgen'. To test them follow these steps:
(1) Compile this file and the example subscription.
(2) Start the subscription with the command
objs/<arch>/hpf_subscriber <domain_id> <sample_count>
(3) Start the publication with the command
objs/<arch>/hpf_publisher <domain_id> <sample_count>
(4) [Optional] Specify the list of discovery initial peers and
multicast receive addresses via an environment variable or a file
(in the current working directory) called NDDS_DISCOVERY_PEERS.
You can run any number of publishers and subscribers programs, and can
add and remove them dynamically from the domain.
Example:
To run the example application on domain <domain_id>:
On Unix:
objs/<arch>/hpf_publisher <domain_id> o
objs/<arch>/hpf_subscriber <domain_id>
On Windows:
objs\<arch>\hpf_publisher <domain_id>
objs\<arch>\hpf_subscriber <domain_id>
modification history
------------ -------
*/
#include <stdio.h>
#include <stdlib.h>
#ifdef RTI_VX653
#include <vThreadsData.h>
#endif
#include "hpf.h"
#include "hpfSupport.h"
#include "ndds/ndds_cpp.h"
/* Delete all entities */
static int publisher_shutdown(
DDSDomainParticipant *participant)
{
DDS_ReturnCode_t retcode;
int status = 0;
if (participant != NULL) {
retcode = participant->delete_contained_entities();
if (retcode != DDS_RETCODE_OK) {
printf("delete_contained_entities error %d\n", retcode);
status = -1;
}
retcode = DDSTheParticipantFactory->delete_participant(participant);
if (retcode != DDS_RETCODE_OK) {
printf("delete_participant error %d\n", retcode);
status = -1;
}
}
/* RTI Connext provides finalize_instance() method on
domain participant factory for people who want to release memory used
by the participant factory. Uncomment the following block of code for
clean destruction of the singleton. */
/*
retcode = DDSDomainParticipantFactory::finalize_instance();
if (retcode != DDS_RETCODE_OK) {
printf("finalize_instance error %d\n", retcode);
status = -1;
}
*/
return status;
}
extern "C" int publisher_main(int domainId, int sample_count)
{
DDSDomainParticipant *participant = NULL;
DDSPublisher *publisher = NULL;
DDSTopic *topic = NULL;
DDSDataWriter *writer = NULL;
hpfDataWriter * hpf_writer = NULL;
hpf *instance = NULL;
DDS_ReturnCode_t retcode;
DDS_InstanceHandle_t instance_handle = DDS_HANDLE_NIL;
const char *type_name = NULL;
int count = 0;
DDS_Duration_t send_period = {4,0};
/* To customize participant QoS, use
the configuration file USER_QOS_PROFILES.xml */
participant = DDSTheParticipantFactory->create_participant(
domainId, DDS_PARTICIPANT_QOS_DEFAULT,
NULL /* listener */, DDS_STATUS_MASK_NONE);
if (participant == NULL) {
printf("create_participant error\n");
publisher_shutdown(participant);
return -1;
}
/* To customize publisher QoS, use
the configuration file USER_QOS_PROFILES.xml */
publisher = participant->create_publisher(
DDS_PUBLISHER_QOS_DEFAULT, NULL /* listener */, DDS_STATUS_MASK_NONE);
if (publisher == NULL) {
printf("create_publisher error\n");
publisher_shutdown(participant);
return -1;
}
/* Register type before creating topic */
type_name = hpfTypeSupport::get_type_name();
retcode = hpfTypeSupport::register_type(
participant, type_name);
if (retcode != DDS_RETCODE_OK) {
printf("register_type error %d\n", retcode);
publisher_shutdown(participant);
return -1;
}
/* To customize topic QoS, use
the configuration file USER_QOS_PROFILES.xml */
topic = participant->create_topic(
"Example hpf",
type_name, DDS_TOPIC_QOS_DEFAULT, NULL /* listener */,
DDS_STATUS_MASK_NONE);
if (topic == NULL) {
printf("create_topic error\n");
publisher_shutdown(participant);
return -1;
}
/* To customize data writer QoS, use
the configuration file USER_QOS_PROFILES.xml */
writer = publisher->create_datawriter(
topic, DDS_DATAWRITER_QOS_DEFAULT, NULL /* listener */,
DDS_STATUS_MASK_NONE);
if (writer == NULL) {
printf("create_datawriter error\n");
publisher_shutdown(participant);
return -1;
}
hpf_writer = hpfDataWriter::narrow(writer);
if (hpf_writer == NULL) {
printf("DataWriter narrow error\n");
publisher_shutdown(participant);
return -1;
}
/* Create data sample for writing */
instance = hpfTypeSupport::create_data();
if (instance == NULL) {
printf("hpfTypeSupport::create_data error\n");
publisher_shutdown(participant);
return -1;
}
/* For a data type that has a key, if the same instance is going to be
written multiple times, initialize the key here
and register the keyed instance prior to writing */
/*
instance_handle = hpf_writer->register_instance(*instance);
*/
instance->payload.ensure_length(HPF_MAX_PAYLOAD_SIZE, HPF_MAX_PAYLOAD_SIZE); //<<HPF>>
/* Main loop */
for (count=0; (sample_count == 0) || (count < sample_count); ++count) {
printf("Writing hpf, count %d\n", count);
/* Modify the data to be sent here */
retcode = hpf_writer->write(*instance, instance_handle);
if (retcode != DDS_RETCODE_OK) {
printf("write error %d\n", retcode);
}
NDDSUtility::sleep(send_period);
}
/*
retcode = hpf_writer->unregister_instance(
*instance, instance_handle);
if (retcode != DDS_RETCODE_OK) {
printf("unregister instance error %d\n", retcode);
}
*/
/* Delete data sample */
retcode = hpfTypeSupport::delete_data(instance);
if (retcode != DDS_RETCODE_OK) {
printf("hpfTypeSupport::delete_data error %d\n", retcode);
}
/* Delete all entities */
return publisher_shutdown(participant);
}
#if defined(RTI_WINCE)
int wmain(int argc, wchar_t** argv)
{
int domainId = 0;
int sample_count = 0; /* infinite loop */
if (argc >= 2) {
domainId = _wtoi(argv[1]);
}
if (argc >= 3) {
sample_count = _wtoi(argv[2]);
}
/* Uncomment this to turn on additional logging
NDDSConfigLogger::get_instance()->
set_verbosity_by_category(NDDS_CONFIG_LOG_CATEGORY_API,
NDDS_CONFIG_LOG_VERBOSITY_STATUS_ALL);
*/
return publisher_main(domainId, sample_count);
}
#elif !(defined(RTI_VXWORKS) && !defined(__RTP__)) && !defined(RTI_PSOS)
int main(int argc, char *argv[])
{
int domainId = 0;
int sample_count = 0; /* infinite loop */
if (argc >= 2) {
domainId = atoi(argv[1]);
}
if (argc >= 3) {
sample_count = atoi(argv[2]);
}
/* Uncomment this to turn on additional logging
NDDSConfigLogger::get_instance()->
set_verbosity_by_category(NDDS_CONFIG_LOG_CATEGORY_API,
NDDS_CONFIG_LOG_VERBOSITY_STATUS_ALL);
*/
return publisher_main(domainId, sample_count);
}
#endif
#ifdef RTI_VX653
const unsigned char* __ctype = *(__ctypePtrGet());
extern "C" void usrAppInit ()
{
#ifdef USER_APPL_INIT
USER_APPL_INIT; /* for backwards compatibility */
#endif
/* add application specific code here */
taskSpawn("pub", RTI_OSAPI_THREAD_PRIORITY_NORMAL, 0x8, 0x150000, (FUNCPTR)publisher_main, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
}
#endif
| cxx |
rticonnextdds-examples | data/projects/rticonnextdds-examples/connext_dds/dynamic_data_sequences/c++/dynamic_data_sequences.cxx | /*******************************************************************************
(c) 2005-2014 Copyright, Real-Time Innovations, Inc. All rights reserved.
RTI grants Licensee a license to use, modify, compile, and create derivative
works of the Software. Licensee has the right to distribute object form only
for use with RTI products. The Software is provided "as is", with no warranty
of any type, including any warranty for fitness for any purpose. RTI is under
no obligation to maintain or support the Software. RTI shall not be liable for
any incidental or consequential damages arising out of the use or inability to
use the software.
******************************************************************************/
/* dynamic_data_sequences.cxx
This example
- creates the type code of a sequence
- creates a DynamicData instance
- writes and reads the values
Example:
To run the example application:
On Unix:
objs/<arch>/SequencesExample
On Windows:
objs\<arch>\SequencesExample
*/
#include <iostream>
#include <ndds_cpp.h>
using namespace std;
/********* IDL representation for this example ************
*
* struct SimpleStruct {
* long a_member;
* };
*
* struct TypeWithSequence {
* sequence<SimpleStruct,5> sequence_member;
* };
*/
#define MAX_SEQ_LEN 5
/*
* Uncomment to use the bind api instead of the get API.
*/
/* #define USE_BIND_API */
DDS_TypeCode *sequence_element_get_typecode(DDS_TypeCodeFactory *tcf)
{
static DDS_TypeCode *tc = NULL;
struct DDS_StructMemberSeq members;
DDS_ExceptionCode_t err;
/* First, we create the typeCode for the simple struct */
tc = tcf->create_struct_tc("SimpleStruct", members, err);
if (err != DDS_NO_EXCEPTION_CODE) {
cerr << stderr << "! Unable to create sequence TC" << endl;
goto fail;
}
tc->add_member(
"a_member",
DDS_TYPECODE_MEMBER_ID_INVALID,
tcf->get_primitive_tc(DDS_TK_LONG),
DDS_TYPECODE_NONKEY_MEMBER,
err);
if (err != DDS_NO_EXCEPTION_CODE) {
cerr << stderr << "! Unable to add a_member to SimpleStruct" << endl;
goto fail;
}
return tc;
fail:
if (tc != NULL) {
tcf->delete_tc(tc, err);
}
return NULL;
}
DDS_TypeCode *sequence_get_typecode(DDS_TypeCodeFactory *tcf)
{
static DDS_TypeCode *tc = NULL;
DDS_TypeCode *seqElementTC = NULL;
DDS_ExceptionCode_t err;
seqElementTC = sequence_element_get_typecode(tcf);
if (seqElementTC == NULL) {
cerr << "! Unable to create TypeCode" << endl;
goto fail;
}
/* We create the typeCode for the sequence */
tc = tcf->create_sequence_tc(MAX_SEQ_LEN, seqElementTC, err);
if (err != DDS_NO_EXCEPTION_CODE) {
cerr << "! Unable to create the sequence TC" << endl;
goto fail;
}
if (seqElementTC != NULL) {
tcf->delete_tc(seqElementTC, err);
}
return tc;
fail:
if (seqElementTC != NULL) {
tcf->delete_tc(seqElementTC, err);
}
if (tc != NULL) {
tcf->delete_tc(tc, err);
}
return NULL;
}
DDS_TypeCode *type_w_sequence_get_typecode(DDS_TypeCodeFactory *tcf)
{
static DDS_TypeCode *tc = NULL;
DDS_TypeCode *sequenceTC = NULL;
struct DDS_StructMemberSeq members;
DDS_ExceptionCode_t err;
sequenceTC = sequence_get_typecode(tcf);
if (sequenceTC == NULL) {
cerr << "! Unable to get sequenceTC" << endl;
goto fail;
}
tc = tcf->create_struct_tc("TypeWithSequence", members, err);
if (tc == NULL) {
cerr << "! Unable to create Type with sequence TC" << endl;
goto fail;
}
tc->add_member(
"sequence_member",
DDS_TYPECODE_MEMBER_ID_INVALID,
sequenceTC,
DDS_TYPECODE_NONKEY_MEMBER,
err);
if (sequenceTC != NULL) {
tcf->delete_tc(sequenceTC, err);
}
return tc;
fail:
if (sequenceTC != NULL) {
tcf->delete_tc(sequenceTC, err);
}
if (tc != NULL) {
tcf->delete_tc(tc, err);
}
return NULL;
}
void write_data(DDS_DynamicData *sample, DDS_TypeCodeFactory *factory)
{
/* Creating typecodes */
DDS_TypeCode *sequenceTC = sequence_get_typecode(factory);
if (sequenceTC == NULL) {
cerr << "! Unable to create sequence typecode " << endl;
return;
}
DDS_TypeCode *sequenceElementTC = sequence_element_get_typecode(factory);
if (sequenceElementTC == NULL) {
cerr << "! Unable to create sequence element typecode " << endl;
return;
}
DDS_ReturnCode_t retcode;
DDS_ExceptionCode_t err;
DDS_DynamicData seqmember(sequenceTC, DDS_DYNAMIC_DATA_PROPERTY_DEFAULT);
DDS_DynamicData seqelement(
sequenceElementTC,
DDS_DYNAMIC_DATA_PROPERTY_DEFAULT);
int i = 0;
for (i = 0; i < MAX_SEQ_LEN; ++i) {
/* To access the elements of a sequence it is necessary
* to use their id. This parameter allows accessing to every element
* of the sequence using a 1-based index.
* There are two ways of doing this: bind API and get API.
* See the NestedStructExample for further details about the
* differences between these two APIs. */
#ifdef USE_BIND_API
retcode = seqmember.bind_complex_member(seqelement, NULL, i + 1);
if (retcode != DDS_RETCODE_OK) {
cerr << "! Unable to bind complex member" << endl;
goto fail;
}
retcode = seqelement.set_long(
"a_member",
DDS_DYNAMIC_DATA_MEMBER_ID_UNSPECIFIED,
i);
if (retcode != DDS_RETCODE_OK) {
cerr << "! Unable to set a_member long" << endl;
goto fail;
}
printf("Writing sequence element #%d : \n", i + 1);
seqelement.print(stdout, 1);
retcode = seqmember.unbind_complex_member(seqelement);
if (retcode != DDS_RETCODE_OK) {
cerr << "! Unable to unbind complex member" << endl;
goto fail;
}
#else
retcode = seqelement.set_long(
"a_member",
DDS_DYNAMIC_DATA_MEMBER_ID_UNSPECIFIED,
i);
if (retcode != DDS_RETCODE_OK) {
cerr << "! Unable to set a_member long" << endl;
goto fail;
}
printf("Writing sequence element #%d : \n", i + 1);
seqelement.print(stdout, 1);
retcode = seqmember.set_complex_member(NULL, i + 1, seqelement);
if (retcode != DDS_RETCODE_OK) {
cerr << "! Unable to set complex member" << endl;
goto fail;
}
#endif
}
retcode = DDS_DynamicData_set_complex_member(
sample,
"sequence_member",
DDS_DYNAMIC_DATA_MEMBER_ID_UNSPECIFIED,
&seqmember);
if (retcode != DDS_RETCODE_OK) {
cerr << "! Unable to set complex member" << endl;
goto fail;
}
fail:
if (sequenceTC != NULL) {
factory->delete_tc(sequenceTC, err);
}
if (sequenceElementTC != NULL) {
factory->delete_tc(sequenceElementTC, err);
}
return;
}
void read_data(DDS_DynamicData *sample, DDS_TypeCodeFactory *factory)
{
DDS_TypeCode *sequenceTC = sequence_get_typecode(factory);
if (sequenceTC == NULL) {
cerr << "! Unable to get sequence type code" << endl;
return;
}
DDS_DynamicData seqmember(sequenceTC, DDS_DYNAMIC_DATA_PROPERTY_DEFAULT);
DDS_DynamicData seqelement(NULL, DDS_DYNAMIC_DATA_PROPERTY_DEFAULT);
DDS_ReturnCode_t retcode;
DDS_ExceptionCode_t err;
DDS_Long value;
struct DDS_DynamicDataInfo info;
int i, seqlen;
sample->get_complex_member(
seqmember,
"sequence_member",
DDS_DYNAMIC_DATA_MEMBER_ID_UNSPECIFIED);
/* Now we get the total amount of elements contained in the array
* by accessing the dynamic data info
*/
cout << "* Getting sequence member info...." << endl;
seqmember.get_info(info);
seqlen = info.member_count;
cout << "* Sequence contains " << seqlen << " elements" << endl;
for (i = 0; i < seqlen; ++i) {
/*
* The same results can be obtained using
* bind_complex_member method. The main difference, is that
* in that case the members are not copied, just referenced
*/
#ifdef USE_BIND_API
retcode = seqmember.bind_complex_member(seqelement, NULL, i + 1);
if (retcode != DDS_RETCODE_OK) {
cerr << "! Unable to bind complex member" << endl;
goto fail;
}
#else
retcode = seqmember.get_complex_member(seqelement, NULL, i + 1);
if (retcode != DDS_RETCODE_OK) {
cerr << "! Unable to bind complex member" << endl;
goto fail;
}
#endif
retcode = seqelement.get_long(
value,
"a_member",
DDS_DYNAMIC_DATA_MEMBER_ID_UNSPECIFIED);
if (retcode != DDS_RETCODE_OK) {
cerr << "! Unable to get long member from seq element" << endl;
goto fail;
}
cout << "Reading sequence element #" << i + 1 << " :" << endl;
seqelement.print(stdout, 1);
#ifdef USE_BIND_API
retcode = seqmember.unbind_complex_member(seqelement);
if (retcode != DDS_RETCODE_OK) {
cerr << "! Unable to u8nbind complex member" << endl;
}
#endif
}
fail:
if (sequenceTC != NULL) {
factory->delete_tc(sequenceTC, err);
}
return;
}
int main()
{
DDS_TypeCodeFactory *factory = NULL;
DDS_TypeCode *wSequenceTC = NULL;
DDS_ExceptionCode_t err;
factory = DDS_TypeCodeFactory::get_instance();
if (factory == NULL) {
cerr << "! Unable to get type code factory singleton" << endl;
return -1;
}
wSequenceTC = type_w_sequence_get_typecode(factory);
if (wSequenceTC == NULL) {
cerr << "! Unable to create wSequence Type Code" << endl;
return -1;
}
DDS_DynamicData sample(wSequenceTC, DDS_DYNAMIC_DATA_PROPERTY_DEFAULT);
cout << "***** Writing a sample *****" << endl;
write_data(&sample, factory);
cout << "***** Reading a sample *****" << endl;
read_data(&sample, factory);
/* Delete the created TC */
if (wSequenceTC != NULL) {
factory->delete_tc(wSequenceTC, err);
}
return 0;
}
| cxx |
rticonnextdds-examples | data/projects/rticonnextdds-examples/connext_dds/dynamic_data_sequences/c++98/dynamic_data_sequences.cxx | /*******************************************************************************
(c) 2005-2014 Copyright, Real-Time Innovations, Inc. All rights reserved.
RTI grants Licensee a license to use, modify, compile, and create derivative
works of the Software. Licensee has the right to distribute object form only
for use with RTI products. The Software is provided "as is", with no warranty
of any type, including any warranty for fitness for any purpose. RTI is under
no obligation to maintain or support the Software. RTI shall not be liable for
any incidental or consequential damages arising out of the use or inability to
use the software.
******************************************************************************/
/* dynamic_data_sequences.cxx
This example
- creates the type code of a sequence
- creates a DynamicData instance
- writes and reads the values
Example:
To run the example application:
On Unix:
objs/<arch>/SequencesExample
On Windows:
objs\<arch>\SequencesExample
*/
#include <iostream>
#include <ndds_cpp.h>
using namespace std;
/********* IDL representation for this example ************
*
* struct SimpleStruct {
* long a_member;
* };
*
* struct TypeWithSequence {
* sequence<SimpleStruct,5> sequence_member;
* };
*/
#define MAX_SEQ_LEN 5
/*
* Uncomment to use the bind api instead of the get API.
*/
/* #define USE_BIND_API */
DDS_TypeCode *sequence_element_get_typecode(DDS_TypeCodeFactory *tcf)
{
static DDS_TypeCode *tc = NULL;
struct DDS_StructMemberSeq members;
DDS_ExceptionCode_t err;
/* First, we create the typeCode for the simple struct */
tc = tcf->create_struct_tc("SimpleStruct", members, err);
if (err != DDS_NO_EXCEPTION_CODE) {
cerr << stderr << "! Unable to create sequence TC" << endl;
goto fail;
}
tc->add_member(
"a_member",
DDS_TYPECODE_MEMBER_ID_INVALID,
tcf->get_primitive_tc(DDS_TK_LONG),
DDS_TYPECODE_NONKEY_MEMBER,
err);
if (err != DDS_NO_EXCEPTION_CODE) {
cerr << stderr << "! Unable to add a_member to SimpleStruct" << endl;
goto fail;
}
return tc;
fail:
if (tc != NULL) {
tcf->delete_tc(tc, err);
}
return NULL;
}
DDS_TypeCode *sequence_get_typecode(DDS_TypeCodeFactory *tcf)
{
static DDS_TypeCode *tc = NULL;
DDS_TypeCode *seqElementTC = NULL;
DDS_ExceptionCode_t err;
seqElementTC = sequence_element_get_typecode(tcf);
if (seqElementTC == NULL) {
cerr << "! Unable to create TypeCode" << endl;
goto fail;
}
/* We create the typeCode for the sequence */
tc = tcf->create_sequence_tc(MAX_SEQ_LEN, seqElementTC, err);
if (err != DDS_NO_EXCEPTION_CODE) {
cerr << "! Unable to create the sequence TC" << endl;
goto fail;
}
if (seqElementTC != NULL) {
tcf->delete_tc(seqElementTC, err);
}
return tc;
fail:
if (seqElementTC != NULL) {
tcf->delete_tc(seqElementTC, err);
}
if (tc != NULL) {
tcf->delete_tc(tc, err);
}
return NULL;
}
DDS_TypeCode *type_w_sequence_get_typecode(DDS_TypeCodeFactory *tcf)
{
static DDS_TypeCode *tc = NULL;
DDS_TypeCode *sequenceTC = NULL;
struct DDS_StructMemberSeq members;
DDS_ExceptionCode_t err;
sequenceTC = sequence_get_typecode(tcf);
if (sequenceTC == NULL) {
cerr << "! Unable to get sequenceTC" << endl;
goto fail;
}
tc = tcf->create_struct_tc("TypeWithSequence", members, err);
if (tc == NULL) {
cerr << "! Unable to create Type with sequence TC" << endl;
goto fail;
}
tc->add_member(
"sequence_member",
DDS_TYPECODE_MEMBER_ID_INVALID,
sequenceTC,
DDS_TYPECODE_NONKEY_MEMBER,
err);
if (sequenceTC != NULL) {
tcf->delete_tc(sequenceTC, err);
}
return tc;
fail:
if (sequenceTC != NULL) {
tcf->delete_tc(sequenceTC, err);
}
if (tc != NULL) {
tcf->delete_tc(tc, err);
}
return NULL;
}
void write_data(DDS_DynamicData *sample, DDS_TypeCodeFactory *factory)
{
/* Creating typecodes */
DDS_TypeCode *sequenceTC = sequence_get_typecode(factory);
if (sequenceTC == NULL) {
cerr << "! Unable to create sequence typecode " << endl;
return;
}
DDS_TypeCode *sequenceElementTC = sequence_element_get_typecode(factory);
if (sequenceElementTC == NULL) {
cerr << "! Unable to create sequence element typecode " << endl;
return;
}
DDS_ReturnCode_t retcode;
DDS_ExceptionCode_t err;
DDS_DynamicData seqmember(sequenceTC, DDS_DYNAMIC_DATA_PROPERTY_DEFAULT);
DDS_DynamicData seqelement(
sequenceElementTC,
DDS_DYNAMIC_DATA_PROPERTY_DEFAULT);
int i = 0;
for (i = 0; i < MAX_SEQ_LEN; ++i) {
/* To access the elements of a sequence it is necessary
* to use their id. This parameter allows accessing to every element
* of the sequence using a 1-based index.
* There are two ways of doing this: bind API and get API.
* See the NestedStructExample for further details about the
* differences between these two APIs. */
#ifdef USE_BIND_API
retcode = seqmember.bind_complex_member(seqelement, NULL, i + 1);
if (retcode != DDS_RETCODE_OK) {
cerr << "! Unable to bind complex member" << endl;
goto fail;
}
retcode = seqelement.set_long(
"a_member",
DDS_DYNAMIC_DATA_MEMBER_ID_UNSPECIFIED,
i);
if (retcode != DDS_RETCODE_OK) {
cerr << "! Unable to set a_member long" << endl;
goto fail;
}
printf("Writing sequence element #%d : \n", i + 1);
seqelement.print(stdout, 1);
retcode = seqmember.unbind_complex_member(seqelement);
if (retcode != DDS_RETCODE_OK) {
cerr << "! Unable to unbind complex member" << endl;
goto fail;
}
#else
retcode = seqelement.set_long(
"a_member",
DDS_DYNAMIC_DATA_MEMBER_ID_UNSPECIFIED,
i);
if (retcode != DDS_RETCODE_OK) {
cerr << "! Unable to set a_member long" << endl;
goto fail;
}
printf("Writing sequence element #%d : \n", i + 1);
seqelement.print(stdout, 1);
retcode = seqmember.set_complex_member(NULL, i + 1, seqelement);
if (retcode != DDS_RETCODE_OK) {
cerr << "! Unable to set complex member" << endl;
goto fail;
}
#endif
}
retcode = DDS_DynamicData_set_complex_member(
sample,
"sequence_member",
DDS_DYNAMIC_DATA_MEMBER_ID_UNSPECIFIED,
&seqmember);
if (retcode != DDS_RETCODE_OK) {
cerr << "! Unable to set complex member" << endl;
goto fail;
}
fail:
if (sequenceTC != NULL) {
factory->delete_tc(sequenceTC, err);
}
if (sequenceElementTC != NULL) {
factory->delete_tc(sequenceElementTC, err);
}
return;
}
void read_data(DDS_DynamicData *sample, DDS_TypeCodeFactory *factory)
{
DDS_TypeCode *sequenceTC = sequence_get_typecode(factory);
if (sequenceTC == NULL) {
cerr << "! Unable to get sequence type code" << endl;
return;
}
DDS_DynamicData seqmember(sequenceTC, DDS_DYNAMIC_DATA_PROPERTY_DEFAULT);
DDS_DynamicData seqelement(NULL, DDS_DYNAMIC_DATA_PROPERTY_DEFAULT);
DDS_ReturnCode_t retcode;
DDS_ExceptionCode_t err;
DDS_Long value;
struct DDS_DynamicDataInfo info;
int i, seqlen;
sample->get_complex_member(
seqmember,
"sequence_member",
DDS_DYNAMIC_DATA_MEMBER_ID_UNSPECIFIED);
/* Now we get the total amount of elements contained in the array
* by accessing the dynamic data info
*/
cout << "* Getting sequence member info...." << endl;
seqmember.get_info(info);
seqlen = info.member_count;
cout << "* Sequence contains " << seqlen << " elements" << endl;
for (i = 0; i < seqlen; ++i) {
/*
* The same results can be obtained using
* bind_complex_member method. The main difference, is that
* in that case the members are not copied, just referenced
*/
#ifdef USE_BIND_API
retcode = seqmember.bind_complex_member(seqelement, NULL, i + 1);
if (retcode != DDS_RETCODE_OK) {
cerr << "! Unable to bind complex member" << endl;
goto fail;
}
#else
retcode = seqmember.get_complex_member(seqelement, NULL, i + 1);
if (retcode != DDS_RETCODE_OK) {
cerr << "! Unable to bind complex member" << endl;
goto fail;
}
#endif
retcode = seqelement.get_long(
value,
"a_member",
DDS_DYNAMIC_DATA_MEMBER_ID_UNSPECIFIED);
if (retcode != DDS_RETCODE_OK) {
cerr << "! Unable to get long member from seq element" << endl;
goto fail;
}
cout << "Reading sequence element #" << i + 1 << " :" << endl;
seqelement.print(stdout, 1);
#ifdef USE_BIND_API
retcode = seqmember.unbind_complex_member(seqelement);
if (retcode != DDS_RETCODE_OK) {
cerr << "! Unable to u8nbind complex member" << endl;
}
#endif
}
fail:
if (sequenceTC != NULL) {
factory->delete_tc(sequenceTC, err);
}
return;
}
int main()
{
DDS_TypeCodeFactory *factory = NULL;
DDS_TypeCode *wSequenceTC = NULL;
DDS_ExceptionCode_t err;
factory = DDS_TypeCodeFactory::get_instance();
if (factory == NULL) {
cerr << "! Unable to get type code factory singleton" << endl;
return -1;
}
wSequenceTC = type_w_sequence_get_typecode(factory);
if (wSequenceTC == NULL) {
cerr << "! Unable to create wSequence Type Code" << endl;
return -1;
}
DDS_DynamicData sample(wSequenceTC, DDS_DYNAMIC_DATA_PROPERTY_DEFAULT);
cout << "***** Writing a sample *****" << endl;
write_data(&sample, factory);
cout << "***** Reading a sample *****" << endl;
read_data(&sample, factory);
/* Delete the created TC */
if (wSequenceTC != NULL) {
factory->delete_tc(wSequenceTC, err);
}
return 0;
}
| cxx |
rticonnextdds-examples | data/projects/rticonnextdds-examples/connext_dds/dynamic_data_sequences/c/dynamic_data_sequences.c | /*******************************************************************************
(c) 2005-2014 Copyright, Real-Time Innovations, Inc. All rights reserved.
RTI grants Licensee a license to use, modify, compile, and create derivative
works of the Software. Licensee has the right to distribute object form only
for use with RTI products. The Software is provided "as is", with no warranty
of any type, including any warranty for fitness for any purpose. RTI is under
no obligation to maintain or support the Software. RTI shall not be liable for
any incidental or consequential damages arising out of the use or inability to
use the software.
******************************************************************************/
/* dynamic_data_sequences.c
This example
- creates the type code of a sequence
- creates a DynamicData instance
- writes and reads the values
Example:
To run the example application:
On Unix:
objs/<arch>/SequencesExample
On Windows:
objs\<arch>\SequencesExample
*/
#include <ndds_c.h>
/********* IDL representation for this example ************
*
* struct SimpleStruct {
* long a_member;
* };
*
* struct TypeWithSequence {
* sequence<SimpleStruct,5> sequence_member;
* };
*/
#define MAX_SEQ_LEN 5
/*
* Uncomment to use the bind api instead of the get API.
*/
/* #define USE_BIND_API */
DDS_TypeCode *sequence_element_get_typecode(DDS_TypeCodeFactory *tcf)
{
static DDS_TypeCode *tc = NULL;
struct DDS_StructMemberSeq members = DDS_SEQUENCE_INITIALIZER;
DDS_ExceptionCode_t err;
/* First, we create the typeCode for the simple struct */
tc = DDS_TypeCodeFactory_create_struct_tc(
tcf,
"SimpleStruct",
&members,
&err);
if (err != DDS_NO_EXCEPTION_CODE) {
fprintf(stderr, "! Unable to create sequence TC\n");
goto fail;
}
DDS_TypeCode_add_member(
tc,
"a_member",
DDS_TYPECODE_MEMBER_ID_INVALID,
DDS_TypeCodeFactory_get_primitive_tc(tcf, DDS_TK_LONG),
DDS_TYPECODE_NONKEY_MEMBER,
&err);
if (err != DDS_NO_EXCEPTION_CODE) {
fprintf(stderr, "! Unable to add a_member to SimpleStruct\n");
goto fail;
}
return tc;
fail:
if (tc != NULL) {
DDS_TypeCodeFactory_delete_tc(tcf, tc, &err);
}
return NULL;
}
DDS_TypeCode *sequence_get_typecode(DDS_TypeCodeFactory *tcf)
{
static DDS_TypeCode *tc = NULL;
DDS_TypeCode *seqElementTC = NULL;
DDS_ExceptionCode_t err;
seqElementTC = sequence_element_get_typecode(tcf);
if (seqElementTC == NULL) {
fprintf(stderr, "! Unable to create typeCode\n");
goto fail;
}
/* We create the typeCode for the sequence */
tc = DDS_TypeCodeFactory_create_sequence_tc(
tcf,
MAX_SEQ_LEN,
seqElementTC,
&err);
if (err != DDS_NO_EXCEPTION_CODE) {
fprintf(stderr, "! Unable to create the sequence TC\n");
goto fail;
}
if (seqElementTC != NULL) {
DDS_TypeCodeFactory_delete_tc(tcf, seqElementTC, &err);
}
return tc;
fail:
if (seqElementTC != NULL) {
DDS_TypeCodeFactory_delete_tc(tcf, seqElementTC, &err);
}
if (tc != NULL) {
DDS_TypeCodeFactory_delete_tc(tcf, tc, &err);
}
return NULL;
}
DDS_TypeCode *type_w_sequence_get_typecode(DDS_TypeCodeFactory *tcf)
{
static DDS_TypeCode *tc = NULL;
struct DDS_TypeCode *sequenceTC = NULL;
struct DDS_StructMemberSeq members = DDS_SEQUENCE_INITIALIZER;
DDS_ExceptionCode_t err;
sequenceTC = sequence_get_typecode(tcf);
if (sequenceTC == NULL) {
fprintf(stderr, "! Unable to get sequenceTC\n");
goto fail;
}
tc = DDS_TypeCodeFactory_create_struct_tc(
tcf,
"TypeWithSequence",
&members,
&err);
if (tc == NULL) {
fprintf(stderr, "! Unable to create Type with sequence TC\n");
goto fail;
}
DDS_TypeCode_add_member(
tc,
"sequence_member",
DDS_TYPECODE_MEMBER_ID_INVALID,
sequenceTC,
DDS_TYPECODE_NONKEY_MEMBER,
&err);
if (sequenceTC != NULL) {
DDS_TypeCodeFactory_delete_tc(tcf, sequenceTC, &err);
}
DDS_StructMemberSeq_finalize(&members);
return tc;
fail:
if (tc != NULL) {
DDS_TypeCodeFactory_delete_tc(tcf, tc, &err);
}
if (sequenceTC != NULL) {
DDS_TypeCodeFactory_delete_tc(tcf, sequenceTC, &err);
}
DDS_StructMemberSeq_finalize(&members);
return NULL;
}
void write_data(DDS_DynamicData *sample, DDS_TypeCodeFactory *factory)
{
DDS_DynamicData seqmember;
DDS_DynamicData seqelement;
DDS_Boolean seqMemberIsInitialized = DDS_BOOLEAN_FALSE;
DDS_Boolean seqElementIsInitialized = DDS_BOOLEAN_FALSE;
DDS_TypeCode *sequenceTC = NULL;
DDS_TypeCode *sequenceElementTC = NULL;
DDS_ExceptionCode_t err;
DDS_ReturnCode_t retcode;
int i = 0;
sequenceTC = sequence_get_typecode(factory);
if (sequenceTC == NULL) {
fprintf(stderr, "! Unable to create typeCode\n");
goto fail;
}
sequenceElementTC = sequence_element_get_typecode(factory);
if (sequenceElementTC == NULL) {
fprintf(stderr, "! Unable to create typeCode\n");
goto fail;
}
seqMemberIsInitialized = DDS_DynamicData_initialize(
&seqmember,
sequenceTC,
&DDS_DYNAMIC_DATA_PROPERTY_DEFAULT);
if (!seqMemberIsInitialized) {
fprintf(stderr, "! Unable to initialize seqMember\n");
goto fail;
}
seqElementIsInitialized = DDS_DynamicData_initialize(
&seqelement,
sequenceElementTC,
&DDS_DYNAMIC_DATA_PROPERTY_DEFAULT);
if (!seqElementIsInitialized) {
fprintf(stderr, "! Unable to initialize seqElement\n");
goto fail;
}
for (i = 0; i < MAX_SEQ_LEN; ++i) {
/* To access the elements of a sequence it is necessary
* to use their id. This parameter allows accessing to every element
* of the sequence using a 1-based index.
* There are two ways of doing this: bind API and get API.
* See the NestedStructExample for further details about the
* differences between these two APIs. */
#ifdef USE_BIND_API
retcode = DDS_DynamicData_bind_complex_member(
&seqmember,
&seqelement,
NULL,
i + 1);
if (retcode != DDS_RETCODE_OK) {
fprintf(stderr, "! Unable to bind complex member\n");
goto fail;
}
retcode = DDS_DynamicData_set_long(
&seqelement,
"a_member",
DDS_DYNAMIC_DATA_MEMBER_ID_UNSPECIFIED,
i);
if (retcode != DDS_RETCODE_OK) {
fprintf(stderr, "! Unable to set a_member long\n");
goto fail;
}
printf("Writing sequence element #%d : \n", i + 1);
DDS_DynamicData_print(&seqelement, stdout, 1);
retcode =
DDS_DynamicData_unbind_complex_member(&seqmember, &seqelement);
if (retcode != DDS_RETCODE_OK) {
fprintf(stderr, "! Unable to unbind complex member\n");
goto fail;
}
#else
retcode = DDS_DynamicData_set_long(
&seqelement,
"a_member",
DDS_DYNAMIC_DATA_MEMBER_ID_UNSPECIFIED,
i);
if (retcode != DDS_RETCODE_OK) {
fprintf(stderr, "! Unable to set a_member long\n");
goto fail;
}
printf("Writing sequence element #%d : \n", i + 1);
DDS_DynamicData_print(&seqelement, stdout, 1);
retcode = DDS_DynamicData_set_complex_member(
&seqmember,
NULL,
i + 1,
&seqelement);
if (retcode != DDS_RETCODE_OK) {
fprintf(stderr, "! Unable to set complex member\n");
goto fail;
}
#endif
}
retcode = DDS_DynamicData_set_complex_member(
sample,
"sequence_member",
DDS_DYNAMIC_DATA_MEMBER_ID_UNSPECIFIED,
&seqmember);
if (retcode != DDS_RETCODE_OK) {
fprintf(stderr, "! Unable to set complex member\n");
goto fail;
}
fail:
if (sequenceTC != NULL) {
DDS_TypeCodeFactory_delete_tc(factory, sequenceTC, &err);
}
if (sequenceElementTC != NULL) {
DDS_TypeCodeFactory_delete_tc(factory, sequenceElementTC, &err);
}
if (seqMemberIsInitialized) {
DDS_DynamicData_finalize(&seqmember);
}
if (seqElementIsInitialized) {
DDS_DynamicData_finalize(&seqelement);
}
return;
}
void read_data(DDS_DynamicData *sample, DDS_TypeCodeFactory *factory)
{
struct DDS_TypeCode *sequenceTC = NULL;
DDS_DynamicData seqmember;
DDS_DynamicData seqelement;
DDS_Boolean seqMemberIsInitialized = DDS_BOOLEAN_FALSE;
DDS_Boolean seqElementIsInitialized = DDS_BOOLEAN_FALSE;
DDS_Long value;
struct DDS_DynamicDataInfo info;
int i, seqlen;
DDS_ReturnCode_t retcode;
DDS_ExceptionCode_t err;
sequenceTC = sequence_get_typecode(factory);
if (sequenceTC == NULL) {
fprintf(stderr, "! Unable to get sequence type code\n");
goto fail;
}
seqMemberIsInitialized = DDS_DynamicData_initialize(
&seqmember,
sequenceTC,
&DDS_DYNAMIC_DATA_PROPERTY_DEFAULT);
if (!seqMemberIsInitialized) {
fprintf(stderr, "! Unable to initialize seqMember\n");
goto fail;
}
seqElementIsInitialized = DDS_DynamicData_initialize(
&seqelement,
NULL,
&DDS_DYNAMIC_DATA_PROPERTY_DEFAULT);
if (!seqElementIsInitialized) {
fprintf(stderr, "! Unable to initialize seqElement\n");
goto fail;
}
retcode = DDS_DynamicData_get_complex_member(
sample,
&seqmember,
"sequence_member",
DDS_DYNAMIC_DATA_MEMBER_ID_UNSPECIFIED);
if (retcode != DDS_RETCODE_OK) {
fprintf(stderr, "! Unable to get complex member from seq member\n");
goto fail;
}
/* Now we get the total amount of elements contained in the sequence
* by accessing the dynamic data info
*/
printf("* Getting sequence member info....\n");
DDS_DynamicData_get_info(&seqmember, &info);
seqlen = info.member_count;
printf("* Sequence contains %d elements\n", seqlen);
for (i = 0; i < seqlen; ++i) {
/*
* The same results can be obtained using
* bind_complex_member method. The main difference, is that
* in that case the members are not copied, just referenced
*/
#ifdef USE_BIND_API
retcode = DDS_DynamicData_bind_complex_member(
&seqmember,
&seqelement,
NULL,
i + 1);
if (retcode != DDS_RETCODE_OK) {
fprintf(stderr, "! Unable to bind complex member\n");
goto fail;
}
#else
retcode = DDS_DynamicData_get_complex_member(
&seqmember,
&seqelement,
NULL,
i + 1);
if (retcode != DDS_RETCODE_OK) {
fprintf(stderr, "! Unable to get complex member\n");
goto fail;
}
#endif
retcode = DDS_DynamicData_get_long(
&seqelement,
&value,
"a_member",
DDS_DYNAMIC_DATA_MEMBER_ID_UNSPECIFIED);
if (retcode != DDS_RETCODE_OK) {
fprintf(stderr, "! Unable to get long member from seq element\n");
goto fail;
}
printf("Reading sequence element #%d : \n", i + 1);
DDS_DynamicData_print(&seqelement, stdout, 1);
#ifdef USE_BIND_API
retcode =
DDS_DynamicData_unbind_complex_member(&seqmember, &seqelement);
if (retcode != DDS_RETCODE_OK) {
fprintf(stderr, "! Unable to unbind complex member\n");
}
#endif
}
fail:
if (sequenceTC != NULL) {
DDS_TypeCodeFactory_delete_tc(factory, sequenceTC, &err);
}
if (seqMemberIsInitialized) {
DDS_DynamicData_finalize(&seqmember);
}
if (seqElementIsInitialized) {
DDS_DynamicData_finalize(&seqelement);
}
return;
}
int main()
{
DDS_DynamicData sample;
DDS_TypeCodeFactory *factory = NULL;
DDS_TypeCode *wSequenceTC = NULL;
DDS_Boolean dynamicDataIsInitialized = DDS_BOOLEAN_FALSE;
factory = DDS_TypeCodeFactory_get_instance();
if (factory == NULL) {
fprintf(stderr, "! Unable to get type code factory singleton\n");
goto fail;
}
wSequenceTC = type_w_sequence_get_typecode(factory);
if (wSequenceTC == NULL) {
fprintf(stderr, "! Unable to create wSequence Type Code\n");
goto fail;
}
dynamicDataIsInitialized = DDS_DynamicData_initialize(
&sample,
wSequenceTC,
&DDS_DYNAMIC_DATA_PROPERTY_DEFAULT);
if (!dynamicDataIsInitialized) {
fprintf(stderr, "! Unable to create dynamicData\n");
goto fail;
}
printf("***** Writing a sample *****\n");
write_data(&sample, factory);
printf("***** Reading a sample *****\n");
read_data(&sample, factory);
fail:
if (wSequenceTC != NULL) {
DDS_TypeCodeFactory_delete_tc(factory, wSequenceTC, NULL);
}
if (dynamicDataIsInitialized) {
DDS_DynamicData_finalize(&sample);
}
return 0;
}
| c |
rticonnextdds-examples | data/projects/rticonnextdds-examples/connext_dds/dynamic_data_sequences/c++03/dynamic_data_sequences.cxx | /*******************************************************************************
(c) 2005-2015 Copyright, Real-Time Innovations, Inc. All rights reserved.
RTI grants Licensee a license to use, modify, compile, and create derivative
works of the Software. Licensee has the right to distribute object form only
for use with RTI products. The Software is provided "as is", with no warranty
of any type, including any warranty for fitness for any purpose. RTI is under
no obligation to maintain or support the Software. RTI shall not be liable for
any incidental or consequential damages arising out of the use or inability to
use the software.
******************************************************************************/
#include <dds/dds.hpp>
#include <iostream>
using namespace dds::core::xtypes;
using namespace rti::core::xtypes;
// IDL representation for this example:
//
// struct SimpleStruct {
// long a_member;
// };
//
// struct TypeWithSequence {
// sequence<SimpleStruct,5> sequence_member;
// };
//
const int MAX_SEQ_LEN = 5;
DynamicType create_dynamictype_simple_struct()
{
// First create the type code for a struct.
StructType simple_struct("SimpleStruct");
// The member will be a integer named "a_member".
simple_struct.add_member(Member("a_member", primitive_type<int32_t>()));
return simple_struct;
}
DynamicType create_dynamictype_sequence_struct()
{
// First create the type code for a struct.
StructType type_with_sequence("TypeWithSequence");
// Add a sequence of type SimpleStruct
DynamicType simple_struct = create_dynamictype_simple_struct();
type_with_sequence.add_member(
Member("sequence_member",
SequenceType(simple_struct, MAX_SEQ_LEN)));
return type_with_sequence;
}
void write_data(DynamicData &sample)
{
// Get the sequence member to set its elements.
DynamicData sequence_member = sample.value<DynamicData>("sequence_member");
// Get the type of the sequence members.
DynamicType simple_struct_dynamic_type =
static_cast<const SequenceType &>(sequence_member.type())
.content_type();
// Write a new struct for each member of the sequence.
for (int i = 0; i < MAX_SEQ_LEN; i++) {
// To access the elements of a sequence it is necessary
// to use their id. This parameter allows accessing every element
// of the sequence using a 1-based index.
//
// The sequence is automatically resized when the index
// is larger than the current lenght.
//
// There are two ways of doing this: loan API and value API.
// See the dynamic_data_nested_structs example for further details
// about the differences between these two APIs.
// **Loan**:
// Get a reference to the i+1 element (1-based index).
LoanedDynamicData loaned_data = sequence_member.loan_value(i + 1);
// We're setting "a_member" whose type is int32_t, the same type as i.
// If the value had a different type (e.g. short) a cast or a explicit
// use of the template parameter would be required to avoid a runtime
// error.
loaned_data.get().value("a_member", i);
// We're returning the loan explicitly; the destructor
// of loaned_data would do it too.
loaned_data.return_loan();
// **Value**:
// Create a simple_struct for this sequence element.
DynamicData simple_struct_element(simple_struct_dynamic_type);
simple_struct_element.value("a_member", i);
// Add to the sequence.
std::cout << "Writing sequence element #" << (i + 1) << " :"
<< std::endl
<< simple_struct_element;
sequence_member.value(i + 1, simple_struct_element);
}
sample.value("sequence_member", sequence_member);
}
void read_data(const DynamicData &sample)
{
// Get the sequence member
DynamicData sequence_member = sample.value<DynamicData>("sequence_member");
// Get the total amount of elements contained in the sequence by accessing
// the dynamic data info.
std::cout << "* Getting sequence member info..." << std::endl;
const DynamicDataInfo &info = sequence_member.info();
int seq_len = info.member_count();
std::cout << "* Sequence contains " << seq_len << " elements" << std::endl;
for (int i = 0; i < seq_len; i++) {
// Value getter:
DynamicData struct_element = sequence_member.value<DynamicData>(i + 1);
// Loan:
// The same results can be obtained using 'loan_value' method.
// The main difference, is that in that case the members are not copied,
// just referenced. To access to the member value call 'get()' method.
// The destructor will unloan the member.
LoanedDynamicData loaned_struct = sequence_member.loan_value(i + 1);
std::cout << "Reading sequence element #" << (i + 1) << " :"
<< std::endl
<< struct_element; // or loaned_struct.get();
}
}
int main()
{
try {
// Create the struct with the sequence member.
DynamicType struct_sequence_type = create_dynamictype_sequence_struct();
DynamicData struct_sequence_data(struct_sequence_type);
std::cout << "***** Writing a sample *****" << std::endl;
write_data(struct_sequence_data);
std::cout << std::endl;
std::cout << "***** Reading a sample *****" << std::endl;
read_data(struct_sequence_data);
} catch (const std::exception &ex) {
// This will catch DDS exceptions.
std::cerr << "Exception: " << ex.what() << std::endl;
return -1;
}
return 0;
}
| cxx |
rticonnextdds-examples | data/projects/rticonnextdds-examples/connext_dds/dynamic_data_sequences/c++11/dynamic_data_sequences.cxx | /*******************************************************************************
(c) 2005-2015 Copyright, Real-Time Innovations, Inc. All rights reserved.
RTI grants Licensee a license to use, modify, compile, and create derivative
works of the Software. Licensee has the right to distribute object form only
for use with RTI products. The Software is provided "as is", with no warranty
of any type, including any warranty for fitness for any purpose. RTI is under
no obligation to maintain or support the Software. RTI shall not be liable for
any incidental or consequential damages arising out of the use or inability to
use the software.
******************************************************************************/
#include <dds/dds.hpp>
#include <iostream>
using namespace dds::core::xtypes;
using namespace rti::core::xtypes;
// IDL representation for this example:
//
// struct SimpleStruct {
// long a_member;
// };
//
// struct TypeWithSequence {
// sequence<SimpleStruct,5> sequence_member;
// };
//
const int MAX_SEQ_LEN = 5;
DynamicType create_dynamictype_simple_struct()
{
// First create the type code for a struct.
StructType simple_struct("SimpleStruct");
// The member will be a integer named "a_member".
simple_struct.add_member(Member("a_member", primitive_type<int32_t>()));
return simple_struct;
}
DynamicType create_dynamictype_sequence_struct()
{
// First create the type code for a struct.
StructType type_with_sequence("TypeWithSequence");
// Add a sequence of type SimpleStruct
DynamicType simple_struct = create_dynamictype_simple_struct();
type_with_sequence.add_member(
Member("sequence_member",
SequenceType(simple_struct, MAX_SEQ_LEN)));
return type_with_sequence;
}
void write_data(DynamicData &sample)
{
// Get the sequence member to set its elements.
DynamicData sequence_member = sample.value<DynamicData>("sequence_member");
// Get the type of the sequence members.
DynamicType simple_struct_dynamic_type =
static_cast<const SequenceType &>(sequence_member.type())
.content_type();
// Write a new struct for each member of the sequence.
for (int i = 0; i < MAX_SEQ_LEN; i++) {
// To access the elements of a sequence it is necessary
// to use their id. This parameter allows accessing every element
// of the sequence using a 1-based index.
//
// The sequence is automatically resized when the index
// is larger than the current lenght.
//
// There are two ways of doing this: loan API and value API.
// See the dynamic_data_nested_structs example for further details
// about the differences between these two APIs.
// **Loan**:
// Get a reference to the i+1 element (1-based index).
LoanedDynamicData loaned_data = sequence_member.loan_value(i + 1);
// We're setting "a_member" whose type is int32_t, the same type as i.
// If the value had a different type (e.g. short) a cast or a explicit
// use of the template parameter would be required to avoid a runtime
// error.
loaned_data.get().value("a_member", i);
// We're returning the loan explicitly; the destructor
// of loaned_data would do it too.
loaned_data.return_loan();
// **Value**:
// Create a simple_struct for this sequence element.
DynamicData simple_struct_element(simple_struct_dynamic_type);
simple_struct_element.value("a_member", i);
// Add to the sequence.
std::cout << "Writing sequence element #" << (i + 1) << " :"
<< std::endl
<< simple_struct_element;
sequence_member.value(i + 1, simple_struct_element);
}
sample.value("sequence_member", sequence_member);
}
void read_data(const DynamicData &sample)
{
// Get the sequence member
DynamicData sequence_member = sample.value<DynamicData>("sequence_member");
// Get the total amount of elements contained in the sequence by accessing
// the dynamic data info.
std::cout << "* Getting sequence member info..." << std::endl;
const DynamicDataInfo &info = sequence_member.info();
int seq_len = info.member_count();
std::cout << "* Sequence contains " << seq_len << " elements" << std::endl;
for (int i = 0; i < seq_len; i++) {
// Value getter:
DynamicData struct_element = sequence_member.value<DynamicData>(i + 1);
// Loan:
// The same results can be obtained using 'loan_value' method.
// The main difference, is that in that case the members are not copied,
// just referenced. To access to the member value call 'get()' method.
// The destructor will unloan the member.
LoanedDynamicData loaned_struct = sequence_member.loan_value(i + 1);
std::cout << "Reading sequence element #" << (i + 1) << " :"
<< std::endl
<< struct_element; // or loaned_struct.get();
}
}
int main()
{
try {
// Create the struct with the sequence member.
DynamicType struct_sequence_type = create_dynamictype_sequence_struct();
DynamicData struct_sequence_data(struct_sequence_type);
std::cout << "***** Writing a sample *****" << std::endl;
write_data(struct_sequence_data);
std::cout << std::endl;
std::cout << "***** Reading a sample *****" << std::endl;
read_data(struct_sequence_data);
} catch (const std::exception &ex) {
// This will catch DDS exceptions.
std::cerr << "Exception: " << ex.what() << std::endl;
return -1;
}
return 0;
}
| cxx |
rticonnextdds-examples | data/projects/rticonnextdds-examples/connext_dds/asynchronous_publication/c++/async_publisher.cxx | /*******************************************************************************
(c) 2005-2014 Copyright, Real-Time Innovations, Inc. All rights reserved.
RTI grants Licensee a license to use, modify, compile, and create derivative
works of the Software. Licensee has the right to distribute object form only
for use with RTI products. The Software is provided "as is", with no warranty
of any type, including any warranty for fitness for any purpose. RTI is under
no obligation to maintain or support the Software. RTI shall not be liable for
any incidental or consequential damages arising out of the use or inability to
use the software.
******************************************************************************/
/* async_publisher.cxx
A publication of data of type async
This file is derived from code automatically generated by the rtiddsgen
command:
rtiddsgen -language C++ -example <arch> async.idl
Example publication of type async automatically generated by
'rtiddsgen'. To test them follow these steps:
(1) Compile this file and the example subscription.
(2) Start the subscription with the command
objs/<arch>/async_subscriber <domain_id> <sample_count>
(3) Start the publication with the command
objs/<arch>/async_publisher <domain_id> <sample_count>
(4) [Optional] Specify the list of discovery initial peers and
multicast receive addresses via an environment variable or a file
(in the current working directory) called NDDS_DISCOVERY_PEERS.
You can run any number of publishers and subscribers programs, and can
add and remove them dynamically from the domain.
Example:
To run the example application on domain <domain_id>:
On Unix:
objs/<arch>/async_publisher <domain_id> o
objs/<arch>/async_subscriber <domain_id>
On Windows:
objs\<arch>\async_publisher <domain_id>
objs\<arch>\async_subscriber <domain_id>
modification history
------------ -------
*/
#include <stdio.h>
#include <stdlib.h>
#ifdef RTI_VX653
#include <vThreadsData.h>
#endif
#include "async.h"
#include "asyncSupport.h"
#include "ndds/ndds_cpp.h"
/* Delete all entities */
static int publisher_shutdown(DDSDomainParticipant *participant)
{
DDS_ReturnCode_t retcode;
int status = 0;
if (participant != NULL) {
retcode = participant->delete_contained_entities();
if (retcode != DDS_RETCODE_OK) {
printf("delete_contained_entities error %d\n", retcode);
status = -1;
}
retcode = DDSTheParticipantFactory->delete_participant(participant);
if (retcode != DDS_RETCODE_OK) {
printf("delete_participant error %d\n", retcode);
status = -1;
}
}
/* RTI Connext provides finalize_instance() method on
domain participant factory for people who want to release memory used
by the participant factory. Uncomment the following block of code for
clean destruction of the singleton. */
/*
retcode = DDSDomainParticipantFactory::finalize_instance();
if (retcode != DDS_RETCODE_OK) {
printf("finalize_instance error %d\n", retcode);
status = -1;
}
*/
return status;
}
extern "C" int publisher_main(int domainId, int sample_count)
{
DDSDomainParticipant *participant = NULL;
DDSPublisher *publisher = NULL;
DDSTopic *topic = NULL;
DDSDataWriter *writer = NULL;
asyncDataWriter *async_writer = NULL;
async *instance = NULL;
DDS_ReturnCode_t retcode;
DDS_InstanceHandle_t instance_handle = DDS_HANDLE_NIL;
const char *type_name = NULL;
int count = 0;
struct DDS_Duration_t send_period = { 0, 100000000 };
/* To customize participant QoS, use
the configuration file USER_QOS_PROFILES.xml */
participant = DDSTheParticipantFactory->create_participant(
domainId,
DDS_PARTICIPANT_QOS_DEFAULT,
NULL /* listener */,
DDS_STATUS_MASK_NONE);
if (participant == NULL) {
printf("create_participant error\n");
publisher_shutdown(participant);
return -1;
}
/* To customize publisher QoS, use
the configuration file USER_QOS_PROFILES.xml */
publisher = participant->create_publisher(
DDS_PUBLISHER_QOS_DEFAULT,
NULL /* listener */,
DDS_STATUS_MASK_NONE);
if (publisher == NULL) {
printf("create_publisher error\n");
publisher_shutdown(participant);
return -1;
}
/* Register type before creating topic */
type_name = asyncTypeSupport::get_type_name();
retcode = asyncTypeSupport::register_type(participant, type_name);
if (retcode != DDS_RETCODE_OK) {
printf("register_type error %d\n", retcode);
publisher_shutdown(participant);
return -1;
}
/* To customize topic QoS, use
the configuration file USER_QOS_PROFILES.xml */
topic = participant->create_topic(
"Example async",
type_name,
DDS_TOPIC_QOS_DEFAULT,
NULL /* listener */,
DDS_STATUS_MASK_NONE);
if (topic == NULL) {
printf("create_topic error\n");
publisher_shutdown(participant);
return -1;
}
/* To customize data writer QoS, use
the configuration file USER_QOS_PROFILES.xml */
writer = publisher->create_datawriter(
topic,
DDS_DATAWRITER_QOS_DEFAULT,
NULL /* listener */,
DDS_STATUS_MASK_NONE);
if (writer == NULL) {
printf("create_datawriter error\n");
publisher_shutdown(participant);
return -1;
}
/* If you want to change the DataWriter's QoS programmatically rather than
* using the XML file, you will need to add the following lines to your
* code and comment out the create_datawriter call above.
*
* In this case, we set the publish mode qos to asynchronous publish mode,
* which enables asynchronous publishing. We also set the flow controller
* to be the fixed rate flow controller, and we increase the history depth.
*/
/* Get default datawriter QoS to customize * /
DDS_DataWriterQos datawriter_qos;
retcode = publisher->get_default_datawriter_qos(datawriter_qos);
if (retcode != DDS_RETCODE_OK) {
printf("get_default_datawriter_qos error\n");
return -1;
}
// Since samples are only being sent once per second, datawriter will need
// to keep them on queue. History defaults to only keeping the last
// sample enqueued, so we increase that here.
datawriter_qos.history.depth = 12;
// Set flowcontroller for datawriter
datawriter_qos.publish_mode.kind = DDS_ASYNCHRONOUS_PUBLISH_MODE_QOS;
datawriter_qos.publish_mode.flow_controller_name =
DDS_FIXED_RATE_FLOW_CONTROLLER_NAME;
/* To create datawriter with default QoS, use DDS_DATAWRITER_QOS_DEFAULT
instead of datawriter_qos * /
writer = publisher->create_datawriter(
topic, datawriter_qos, NULL /* listener * /,
DDS_STATUS_MASK_NONE);
if (writer == NULL) {
printf("create_datawriter error\n");
publisher_shutdown(participant);
return -1;
}
//// End changes for Asynchronous_Publication
*/
async_writer = asyncDataWriter::narrow(writer);
if (async_writer == NULL) {
printf("DataWriter narrow error\n");
publisher_shutdown(participant);
return -1;
}
/* Create data sample for writing */
instance = asyncTypeSupport::create_data();
if (instance == NULL) {
printf("asyncTypeSupport::create_data error\n");
publisher_shutdown(participant);
return -1;
}
/* For a data type that has a key, if the same instance is going to be
written multiple times, initialize the key here
and register the keyed instance prior to writing */
/*
instance_handle = async_writer->register_instance(*instance);
*/
/* Main loop */
for (count = 0; (sample_count == 0) || (count < sample_count); ++count) {
printf("Writing async, count %d\n", count);
// send count as data.
instance->x = count;
retcode = async_writer->write(*instance, instance_handle);
if (retcode != DDS_RETCODE_OK) {
printf("write error %d\n", retcode);
}
NDDSUtility::sleep(send_period);
}
//// Changes for Asynchronous_Publication
// Give time for publisher to send out last few samples
send_period.sec = 1;
NDDSUtility::sleep(send_period);
/*
retcode = async_writer->unregister_instance(
*instance, instance_handle);
if (retcode != DDS_RETCODE_OK) {
printf("unregister instance error %d\n", retcode);
}
*/
/* Delete data sample */
retcode = asyncTypeSupport::delete_data(instance);
if (retcode != DDS_RETCODE_OK) {
printf("asyncTypeSupport::delete_data error %d\n", retcode);
}
/* Delete all entities */
return publisher_shutdown(participant);
}
#if defined(RTI_WINCE)
int wmain(int argc, wchar_t **argv)
{
int domainId = 0;
int sample_count = 0; /* infinite loop */
if (argc >= 2) {
domainId = _wtoi(argv[1]);
}
if (argc >= 3) {
sample_count = _wtoi(argv[2]);
}
/* Uncomment this to turn on additional logging
NDDSConfigLogger::get_instance()->
set_verbosity_by_category(NDDS_CONFIG_LOG_CATEGORY_API,
NDDS_CONFIG_LOG_VERBOSITY_STATUS_ALL);
*/
return publisher_main(domainId, sample_count);
}
#elif !(defined(RTI_VXWORKS) && !defined(__RTP__)) && !defined(RTI_PSOS)
int main(int argc, char *argv[])
{
int domainId = 0;
int sample_count = 0; /* infinite loop */
if (argc >= 2) {
domainId = atoi(argv[1]);
}
if (argc >= 3) {
sample_count = atoi(argv[2]);
}
/* Uncomment this to turn on additional logging
NDDSConfigLogger::get_instance()->
set_verbosity_by_category(NDDS_CONFIG_LOG_CATEGORY_API,
NDDS_CONFIG_LOG_VERBOSITY_STATUS_ALL);
*/
return publisher_main(domainId, sample_count);
}
#endif
#ifdef RTI_VX653
const unsigned char *__ctype = *(__ctypePtrGet());
extern "C" void usrAppInit()
{
#ifdef USER_APPL_INIT
USER_APPL_INIT; /* for backwards compatibility */
#endif
/* add application specific code here */
taskSpawn(
"pub",
RTI_OSAPI_THREAD_PRIORITY_NORMAL,
0x8,
0x150000,
(FUNCPTR) publisher_main,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0);
}
#endif
| cxx |
rticonnextdds-examples | data/projects/rticonnextdds-examples/connext_dds/asynchronous_publication/c++/async_subscriber.cxx | /*******************************************************************************
(c) 2005-2014 Copyright, Real-Time Innovations, Inc. All rights reserved.
RTI grants Licensee a license to use, modify, compile, and create derivative
works of the Software. Licensee has the right to distribute object form only
for use with RTI products. The Software is provided "as is", with no warranty
of any type, including any warranty for fitness for any purpose. RTI is under
no obligation to maintain or support the Software. RTI shall not be liable for
any incidental or consequential damages arising out of the use or inability to
use the software.
******************************************************************************/
/* async_subscriber.cxx
A subscription example
This file is derived from code automatically generated by the rtiddsgen
command:
rtiddsgen -language C++ -example <arch> async.idl
Example subscription of type async automatically generated by
'rtiddsgen'. To test them follow these steps:
(1) Compile this file and the example publication.
(2) Start the subscription with the command
objs/<arch>/async_subscriber <domain_id> <sample_count>
(3) Start the publication with the command
objs/<arch>/async_publisher <domain_id> <sample_count>
(4) [Optional] Specify the list of discovery initial peers and
multicast receive addresses via an environment variable or a file
(in the current working directory) called NDDS_DISCOVERY_PEERS.
You can run any number of publishers and subscribers programs, and can
add and remove them dynamically from the domain.
Example:
To run the example application on domain <domain_id>:
On Unix:
objs/<arch>/async_publisher <domain_id>
objs/<arch>/async_subscriber <domain_id>
On Windows:
objs\<arch>\async_publisher <domain_id>
objs\<arch>\async_subscriber <domain_id>
modification history
------------ -------
*/
#include <stdio.h>
#include <stdlib.h>
#ifdef RTI_VX653
#include <vThreadsData.h>
#endif
#include "async.h"
#include "asyncSupport.h"
#include "ndds/ndds_cpp.h"
//// Changes for Asynchronous_Publication
// For timekeeping
#include <time.h>
clock_t init;
class asyncListener : public DDSDataReaderListener {
public:
virtual void on_requested_deadline_missed(
DDSDataReader * /*reader*/,
const DDS_RequestedDeadlineMissedStatus & /*status*/)
{
}
virtual void on_requested_incompatible_qos(
DDSDataReader * /*reader*/,
const DDS_RequestedIncompatibleQosStatus & /*status*/)
{
}
virtual void on_sample_rejected(
DDSDataReader * /*reader*/,
const DDS_SampleRejectedStatus & /*status*/)
{
}
virtual void on_liveliness_changed(
DDSDataReader * /*reader*/,
const DDS_LivelinessChangedStatus & /*status*/)
{
}
virtual void on_sample_lost(
DDSDataReader * /*reader*/,
const DDS_SampleLostStatus & /*status*/)
{
}
virtual void on_subscription_matched(
DDSDataReader * /*reader*/,
const DDS_SubscriptionMatchedStatus & /*status*/)
{
}
virtual void on_data_available(DDSDataReader *reader);
};
void asyncListener::on_data_available(DDSDataReader *reader)
{
asyncDataReader *async_reader = NULL;
asyncSeq data_seq;
DDS_SampleInfoSeq info_seq;
DDS_ReturnCode_t retcode;
int i;
async_reader = asyncDataReader::narrow(reader);
if (async_reader == NULL) {
printf("DataReader narrow error\n");
return;
}
retcode = async_reader->take(
data_seq,
info_seq,
DDS_LENGTH_UNLIMITED,
DDS_ANY_SAMPLE_STATE,
DDS_ANY_VIEW_STATE,
DDS_ANY_INSTANCE_STATE);
if (retcode == DDS_RETCODE_NO_DATA) {
return;
} else if (retcode != DDS_RETCODE_OK) {
printf("take error %d\n", retcode);
return;
}
for (i = 0; i < data_seq.length(); ++i) {
if (info_seq[i].valid_data) {
//// Start changes for Asynchronous_Publication
// print the time we get each sample.
double elapsed_ticks = clock() - init;
double elapsed_secs = elapsed_ticks / CLOCKS_PER_SEC;
printf("@ t=%.2fs, got x = %d\n", elapsed_secs, data_seq[i].x);
//// End changes for Asynchronous_Publication
}
}
retcode = async_reader->return_loan(data_seq, info_seq);
if (retcode != DDS_RETCODE_OK) {
printf("return loan error %d\n", retcode);
}
}
/* Delete all entities */
static int subscriber_shutdown(DDSDomainParticipant *participant)
{
DDS_ReturnCode_t retcode;
int status = 0;
if (participant != NULL) {
retcode = participant->delete_contained_entities();
if (retcode != DDS_RETCODE_OK) {
printf("delete_contained_entities error %d\n", retcode);
status = -1;
}
retcode = DDSTheParticipantFactory->delete_participant(participant);
if (retcode != DDS_RETCODE_OK) {
printf("delete_participant error %d\n", retcode);
status = -1;
}
}
/* RTI Connext provides the finalize_instance() method on
domain participant factory for people who want to release memory used
by the participant factory. Uncomment the following block of code for
clean destruction of the singleton. */
/*
retcode = DDSDomainParticipantFactory::finalize_instance();
if (retcode != DDS_RETCODE_OK) {
printf("finalize_instance error %d\n", retcode);
status = -1;
}
*/
return status;
}
extern "C" int subscriber_main(int domainId, int sample_count)
{
DDSDomainParticipant *participant = NULL;
DDSSubscriber *subscriber = NULL;
DDSTopic *topic = NULL;
asyncListener *reader_listener = NULL;
DDSDataReader *reader = NULL;
DDS_ReturnCode_t retcode;
const char *type_name = NULL;
int count = 0;
DDS_Duration_t receive_period = { 4, 0 };
int status = 0;
//// Changes for Asynchronous_Publication
// for timekeeping
init = clock();
/* To customize the participant QoS, use
the configuration file USER_QOS_PROFILES.xml */
participant = DDSTheParticipantFactory->create_participant(
domainId,
DDS_PARTICIPANT_QOS_DEFAULT,
NULL /* listener */,
DDS_STATUS_MASK_NONE);
if (participant == NULL) {
printf("create_participant error\n");
subscriber_shutdown(participant);
return -1;
}
/* To customize the subscriber QoS, use
the configuration file USER_QOS_PROFILES.xml */
subscriber = participant->create_subscriber(
DDS_SUBSCRIBER_QOS_DEFAULT,
NULL /* listener */,
DDS_STATUS_MASK_NONE);
if (subscriber == NULL) {
printf("create_subscriber error\n");
subscriber_shutdown(participant);
return -1;
}
/* Register the type before creating the topic */
type_name = asyncTypeSupport::get_type_name();
retcode = asyncTypeSupport::register_type(participant, type_name);
if (retcode != DDS_RETCODE_OK) {
printf("register_type error %d\n", retcode);
subscriber_shutdown(participant);
return -1;
}
/* To customize the topic QoS, use
the configuration file USER_QOS_PROFILES.xml */
topic = participant->create_topic(
"Example async",
type_name,
DDS_TOPIC_QOS_DEFAULT,
NULL /* listener */,
DDS_STATUS_MASK_NONE);
if (topic == NULL) {
printf("create_topic error\n");
subscriber_shutdown(participant);
return -1;
}
/* Create a data reader listener */
reader_listener = new asyncListener();
/* To customize the data reader QoS, use
the configuration file USER_QOS_PROFILES.xml */
reader = subscriber->create_datareader(
topic,
DDS_DATAREADER_QOS_DEFAULT,
reader_listener,
DDS_STATUS_MASK_ALL);
if (reader == NULL) {
printf("create_datareader error\n");
subscriber_shutdown(participant);
delete reader_listener;
return -1;
}
/* Main loop */
for (count = 0; (sample_count == 0) || (count < sample_count); ++count) {
printf("async subscriber sleeping for %d sec...\n", receive_period.sec);
NDDSUtility::sleep(receive_period);
}
/* Delete all entities */
status = subscriber_shutdown(participant);
delete reader_listener;
return status;
}
#if defined(RTI_WINCE)
int wmain(int argc, wchar_t **argv)
{
int domainId = 0;
int sample_count = 0; /* infinite loop */
if (argc >= 2) {
domainId = _wtoi(argv[1]);
}
if (argc >= 3) {
sample_count = _wtoi(argv[2]);
}
/* Uncomment this to turn on additional logging
NDDSConfigLogger::get_instance()->
set_verbosity_by_category(NDDS_CONFIG_LOG_CATEGORY_API,
NDDS_CONFIG_LOG_VERBOSITY_STATUS_ALL);
*/
return subscriber_main(domainId, sample_count);
}
#elif !(defined(RTI_VXWORKS) && !defined(__RTP__)) && !defined(RTI_PSOS)
int main(int argc, char *argv[])
{
int domainId = 0;
int sample_count = 0; /* infinite loop */
if (argc >= 2) {
domainId = atoi(argv[1]);
}
if (argc >= 3) {
sample_count = atoi(argv[2]);
}
/* Uncomment this to turn on additional logging
NDDSConfigLogger::get_instance()->
set_verbosity_by_category(NDDS_CONFIG_LOG_CATEGORY_API,
NDDS_CONFIG_LOG_VERBOSITY_STATUS_ALL);
*/
return subscriber_main(domainId, sample_count);
}
#endif
#ifdef RTI_VX653
const unsigned char *__ctype = *(__ctypePtrGet());
extern "C" void usrAppInit()
{
#ifdef USER_APPL_INIT
USER_APPL_INIT; /* for backwards compatibility */
#endif
/* add application specific code here */
taskSpawn(
"sub",
RTI_OSAPI_THREAD_PRIORITY_NORMAL,
0x8,
0x150000,
(FUNCPTR) subscriber_main,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0);
}
#endif
| cxx |
rticonnextdds-examples | data/projects/rticonnextdds-examples/connext_dds/asynchronous_publication/c++98/async_publisher.cxx | /*******************************************************************************
(c) 2005-2014 Copyright, Real-Time Innovations, Inc. All rights reserved.
RTI grants Licensee a license to use, modify, compile, and create derivative
works of the Software. Licensee has the right to distribute object form only
for use with RTI products. The Software is provided "as is", with no warranty
of any type, including any warranty for fitness for any purpose. RTI is under
no obligation to maintain or support the Software. RTI shall not be liable for
any incidental or consequential damages arising out of the use or inability to
use the software.
******************************************************************************/
#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include "async.h"
#include "asyncSupport.h"
#include "ndds/ndds_cpp.h"
#include "application.h"
using namespace application;
static int shutdown_participant(
DDSDomainParticipant *participant,
const char *shutdown_message,
int status);
int run_publisher_application(unsigned int domainId, unsigned int sample_count)
{
// Start communicating in a domain, usually one participant per application
DDSDomainParticipant *participant =
DDSTheParticipantFactory->create_participant(
domainId,
DDS_PARTICIPANT_QOS_DEFAULT,
NULL /* listener */,
DDS_STATUS_MASK_NONE);
if (participant == NULL) {
return shutdown_participant(
participant,
"create_participant error",
EXIT_FAILURE);
}
// A Publisher allows an application to create one or more DataWriters
DDSPublisher *publisher = participant->create_publisher(
DDS_PUBLISHER_QOS_DEFAULT,
NULL /* listener */,
DDS_STATUS_MASK_NONE);
if (publisher == NULL) {
return shutdown_participant(
participant,
"create_publisher error",
EXIT_FAILURE);
}
// Register the datatype to use when creating the Topic
const char *type_name = asyncTypeSupport::get_type_name();
DDS_ReturnCode_t retcode =
asyncTypeSupport::register_type(participant, type_name);
if (retcode != DDS_RETCODE_OK) {
return shutdown_participant(
participant,
"register_type error",
EXIT_FAILURE);
}
// Create a Topic with a name and a datatype
DDSTopic *topic = participant->create_topic(
"Example async",
type_name,
DDS_TOPIC_QOS_DEFAULT,
NULL /* listener */,
DDS_STATUS_MASK_NONE);
if (topic == NULL) {
return shutdown_participant(
participant,
"create_topic error",
EXIT_FAILURE);
}
// This DataWriter writes data on "Example async" Topic
DDSDataWriter *untyped_writer = publisher->create_datawriter(
topic,
DDS_DATAWRITER_QOS_DEFAULT,
NULL /* listener */,
DDS_STATUS_MASK_NONE);
if (untyped_writer == NULL) {
return shutdown_participant(
participant,
"create_datawriter error",
EXIT_FAILURE);
}
/* If you want to change the DataWriter's QoS programmatically rather than
* using the XML file, you will need to add the following lines to your
* code and comment out the create_datawriter call above.
*
* In this case, we set the publish mode qos to asynchronous publish mode,
* which enables asynchronous publishing. We also set the flow controller
* to be the fixed rate flow controller, and we increase the history depth.
*/
/* Get default datawriter QoS to customize * /
DDS_DataWriterQos datawriter_qos;
retcode = publisher->get_default_datawriter_qos(datawriter_qos);
if (retcode != DDS_RETCODE_OK) {
return shutdown_participant(
participant,
"get_default_datawriter_qos error",
EXIT_FAILURE);
}
// Since samples are only being sent once per second, datawriter will need
// to keep them on queue. History defaults to only keeping the last
// sample enqueued, so we increase that here.
datawriter_qos.history.depth = 12;
// Set flowcontroller for datawriter
datawriter_qos.publish_mode.kind = DDS_ASYNCHRONOUS_PUBLISH_MODE_QOS;
datawriter_qos.publish_mode.flow_controller_name =
DDS_FIXED_RATE_FLOW_CONTROLLER_NAME;
/* To create datawriter with default QoS, use DDS_DATAWRITER_QOS_DEFAULT
instead of datawriter_qos * /
writer = publisher->create_datawriter(
topic, datawriter_qos, NULL /* listener * /,
DDS_STATUS_MASK_NONE);
if (writer == NULL) {
return shutdown_participant(
participant,
"create_datawriter error",
EXIT_FAILURE);
}
//// End changes for Asynchronous_Publication
*/
// Narrow casts from an untyped DataWriter to a writer of your type
asyncDataWriter *typed_writer = asyncDataWriter::narrow(untyped_writer);
if (typed_writer == NULL) {
return shutdown_participant(
participant,
"DataWriter narrow error",
EXIT_FAILURE);
}
// Create data for writing, allocating all members
async *data = asyncTypeSupport::create_data();
if (data == NULL) {
return shutdown_participant(
participant,
"asyncTypeSupport::create_data error",
EXIT_FAILURE);
}
DDS_InstanceHandle_t instance_handle = DDS_HANDLE_NIL;
/* For a data type that has a key, if the same instance is going to be
written multiple times, initialize the key here
and register the keyed instance prior to writing */
/*
instance_handle = typed_writer->register_instance(*data);
*/
// Main loop
for (unsigned int samples_written = 0;
!shutdown_requested && samples_written < sample_count;
++samples_written) {
std::cout << "Writing async, count " << samples_written << std::endl;
// send count as data.
data->x = samples_written;
retcode = typed_writer->write(*data, instance_handle);
if (retcode != DDS_RETCODE_OK) {
std::cerr << "write error " << retcode << std::endl;
}
DDS_Duration_t send_period = { 0, 100000000 };
NDDSUtility::sleep(send_period);
}
/*
retcode = typed_writer->unregister_instance(
*data, instance_handle);
if (retcode != DDS_RETCODE_OK) {
std::cerr << "unregister instance error " << retcode << std::endl;
}
*/
// Delete previously allocated async, including all contained elements
retcode = asyncTypeSupport::delete_data(data);
if (retcode != DDS_RETCODE_OK) {
std::cerr << "asyncTypeSupport::delete_data error " << retcode
<< std::endl;
}
// Delete all entities (DataWriter, Topic, Publisher, DomainParticipant)
return shutdown_participant(participant, "Shutting down", EXIT_SUCCESS);
}
// Delete all entities
static int shutdown_participant(
DDSDomainParticipant *participant,
const char *shutdown_message,
int status)
{
DDS_ReturnCode_t retcode;
std::cout << shutdown_message << std::endl;
if (participant != NULL) {
// Cleanup everything created by this Participant
retcode = participant->delete_contained_entities();
if (retcode != DDS_RETCODE_OK) {
std::cerr << "delete_contained_entities error " << retcode
<< std::endl;
status = EXIT_FAILURE;
}
retcode = DDSTheParticipantFactory->delete_participant(participant);
if (retcode != DDS_RETCODE_OK) {
std::cerr << "delete_participant error " << retcode << std::endl;
status = EXIT_FAILURE;
}
}
return status;
}
int main(int argc, char *argv[])
{
// Parse arguments and handle control-C
ApplicationArguments arguments;
parse_arguments(arguments, argc, argv);
if (arguments.parse_result == PARSE_RETURN_EXIT) {
return EXIT_SUCCESS;
} else if (arguments.parse_result == PARSE_RETURN_FAILURE) {
return EXIT_FAILURE;
}
setup_signal_handlers();
// Sets Connext verbosity to help debugging
NDDSConfigLogger::get_instance()->set_verbosity(arguments.verbosity);
int status = run_publisher_application(
arguments.domain_id,
arguments.sample_count);
// Releases the memory used by the participant factory. Optional at
// application exit
DDS_ReturnCode_t retcode = DDSDomainParticipantFactory::finalize_instance();
if (retcode != DDS_RETCODE_OK) {
std::cerr << "finalize_instance error " << retcode << std::endl;
status = EXIT_FAILURE;
}
return status;
}
| cxx |
rticonnextdds-examples | data/projects/rticonnextdds-examples/connext_dds/asynchronous_publication/c++98/application.h | /*
* (c) Copyright, Real-Time Innovations, 2020. All rights reserved.
* RTI grants Licensee a license to use, modify, compile, and create derivative
* works of the software solely for use with RTI Connext DDS. Licensee may
* redistribute copies of the software provided that all such copies are subject
* to this license. The software is provided "as is", with no warranty of any
* type, including any warranty for fitness for any purpose. RTI is under no
* obligation to maintain or support the software. RTI shall not be liable for
* any incidental or consequential damages arising out of the use or inability
* to use the software.
*/
#ifndef APPLICATION_H
#define APPLICATION_H
#include <iostream>
#include <csignal>
#include <climits>
namespace application {
// Catch control-C and tell application to shut down
bool shutdown_requested = false;
inline void stop_handler(int)
{
shutdown_requested = true;
std::cout << "preparing to shut down..." << std::endl;
}
inline void setup_signal_handlers()
{
signal(SIGINT, stop_handler);
signal(SIGTERM, stop_handler);
}
enum ParseReturn { PARSE_RETURN_OK, PARSE_RETURN_FAILURE, PARSE_RETURN_EXIT };
struct ApplicationArguments {
ParseReturn parse_result;
unsigned int domain_id;
unsigned int sample_count;
NDDS_Config_LogVerbosity verbosity;
};
inline void set_verbosity(ApplicationArguments &arguments, int verbosity)
{
switch (verbosity) {
case 0:
arguments.verbosity = NDDS_CONFIG_LOG_VERBOSITY_SILENT;
break;
case 1:
arguments.verbosity = NDDS_CONFIG_LOG_VERBOSITY_ERROR;
break;
case 2:
arguments.verbosity = NDDS_CONFIG_LOG_VERBOSITY_WARNING;
break;
case 3:
arguments.verbosity = NDDS_CONFIG_LOG_VERBOSITY_STATUS_ALL;
break;
default:
arguments.verbosity = NDDS_CONFIG_LOG_VERBOSITY_ERROR;
break;
}
}
// Parses application arguments for example. Returns whether to exit.
inline void parse_arguments(
ApplicationArguments &arguments,
int argc,
char *argv[])
{
int arg_processing = 1;
bool show_usage = false;
arguments.domain_id = 0;
arguments.sample_count = INT_MAX;
arguments.verbosity = NDDS_CONFIG_LOG_VERBOSITY_ERROR;
arguments.parse_result = PARSE_RETURN_OK;
while (arg_processing < argc) {
if ((argc > arg_processing + 1)
&& (strcmp(argv[arg_processing], "-d") == 0
|| strcmp(argv[arg_processing], "--domain") == 0)) {
arguments.domain_id = atoi(argv[arg_processing + 1]);
arg_processing += 2;
} else if (
(argc > arg_processing + 1)
&& (strcmp(argv[arg_processing], "-s") == 0
|| strcmp(argv[arg_processing], "--sample-count") == 0)) {
arguments.sample_count = atoi(argv[arg_processing + 1]);
arg_processing += 2;
} else if (
(argc > arg_processing + 1)
&& (strcmp(argv[arg_processing], "-v") == 0
|| strcmp(argv[arg_processing], "--verbosity") == 0)) {
set_verbosity(arguments, atoi(argv[arg_processing + 1]));
arg_processing += 2;
} else if (
strcmp(argv[arg_processing], "-h") == 0
|| strcmp(argv[arg_processing], "--help") == 0) {
std::cout << "Example application." << std::endl;
show_usage = true;
arguments.parse_result = PARSE_RETURN_EXIT;
break;
} else {
std::cout << "Bad parameter." << std::endl;
show_usage = true;
arguments.parse_result = PARSE_RETURN_FAILURE;
break;
}
}
if (show_usage) {
std::cout << "Usage:\n"
" -d, --domain <int> Domain ID this "
"application will\n"
" subscribe in. \n"
" Default: 0\n"
" -s, --sample_count <int> Number of samples to "
"receive before\n"
" cleanly shutting down. \n"
" Default: infinite\n"
" -v, --verbosity <int> How much debugging output "
"to show.\n"
" Range: 0-3 \n"
" Default: 1"
<< std::endl;
}
}
} // namespace application
#endif // APPLICATION_H
| h |
rticonnextdds-examples | data/projects/rticonnextdds-examples/connext_dds/asynchronous_publication/c++98/async_subscriber.cxx | /*******************************************************************************
(c) 2005-2014 Copyright, Real-Time Innovations, Inc. All rights reserved.
RTI grants Licensee a license to use, modify, compile, and create derivative
works of the Software. Licensee has the right to distribute object form only
for use with RTI products. The Software is provided "as is", with no warranty
of any type, including any warranty for fitness for any purpose. RTI is under
no obligation to maintain or support the Software. RTI shall not be liable for
any incidental or consequential damages arising out of the use or inability to
use the software.
******************************************************************************/
#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include "async.h"
#include "asyncSupport.h"
#include "ndds/ndds_cpp.h"
#include "application.h"
#include <time.h>
clock_t init;
using namespace application;
static int shutdown_participant(
DDSDomainParticipant *participant,
const char *shutdown_message,
int status);
// Process data. Returns number of samples processed.
unsigned int process_data(asyncDataReader *typed_reader)
{
asyncSeq data_seq; // Sequence of received data
DDS_SampleInfoSeq info_seq; // Metadata associated with samples in data_seq
unsigned int samples_read = 0;
// Take available data from DataReader's queue
typed_reader->take(
data_seq,
info_seq,
DDS_LENGTH_UNLIMITED,
DDS_ANY_SAMPLE_STATE,
DDS_ANY_VIEW_STATE,
DDS_ANY_INSTANCE_STATE);
for (int i = 0; i < data_seq.length(); ++i) {
if (info_seq[i].valid_data) {
samples_read++;
//// Start changes for Asynchronous_Publication
// print the time we get each sample.
double elapsed_ticks = clock() - init;
double elapsed_secs = elapsed_ticks / CLOCKS_PER_SEC;
std::cout << "@ t=" << elapsed_secs << ", got x = " << data_seq[i].x
<< std::endl;
//// End changes for Asynchronous_Publication
}
}
// Data loaned from Connext for performance. Return loan when done.
DDS_ReturnCode_t retcode = typed_reader->return_loan(data_seq, info_seq);
if (retcode != DDS_RETCODE_OK) {
std::cerr << "return loan error " << retcode << std::endl;
}
return samples_read;
}
int run_subscriber_application(
unsigned int domain_id,
unsigned int sample_count)
{
//// Changes for Asynchronous_Publication
// for timekeeping
init = clock();
// To customize the participant QoS, use the configuration file
// 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(
participant,
"create_participant error",
EXIT_FAILURE);
}
// To customize the subscriber QoS, use the configuration file
// USER_QOS_PROFILES.xml
DDSSubscriber *subscriber = participant->create_subscriber(
DDS_SUBSCRIBER_QOS_DEFAULT,
NULL /* listener */,
DDS_STATUS_MASK_NONE);
if (subscriber == NULL) {
return shutdown_participant(
participant,
"create_subscriber error",
EXIT_FAILURE);
}
// Register the datatype to use when creating the Topic
const char *type_name = asyncTypeSupport::get_type_name();
DDS_ReturnCode_t retcode =
asyncTypeSupport::register_type(participant, type_name);
if (retcode != DDS_RETCODE_OK) {
return shutdown_participant(
participant,
"register_type error",
EXIT_FAILURE);
}
// To customize the topic QoS, use the configuration file
// USER_QOS_PROFILES.xml
DDSTopic *topic = participant->create_topic(
"Example async",
type_name,
DDS_TOPIC_QOS_DEFAULT,
NULL /* listener */,
DDS_STATUS_MASK_NONE);
if (topic == NULL) {
return shutdown_participant(
participant,
"create_topic error",
EXIT_FAILURE);
}
// To customize the data reader QoS, use the configuration file
// USER_QOS_PROFILES.xml
DDSDataReader *untyped_reader = subscriber->create_datareader(
topic,
DDS_DATAREADER_QOS_DEFAULT,
NULL,
DDS_STATUS_MASK_NONE);
if (untyped_reader == NULL) {
return shutdown_participant(
participant,
"create_datareader error",
EXIT_FAILURE);
}
// Narrow casts from a untyped DataReader to a reader of your type
asyncDataReader *typed_reader = asyncDataReader::narrow(untyped_reader);
if (typed_reader == NULL) {
return shutdown_participant(
participant,
"DataReader narrow error",
EXIT_FAILURE);
}
// Create ReadCondition that triggers when unread data in reader's queue
DDSReadCondition *read_condition = typed_reader->create_readcondition(
DDS_NOT_READ_SAMPLE_STATE,
DDS_ANY_VIEW_STATE,
DDS_ANY_INSTANCE_STATE);
if (read_condition == NULL) {
return shutdown_participant(
participant,
"create_readcondition error",
EXIT_FAILURE);
}
// WaitSet will be woken when the attached condition is triggered
DDSWaitSet waitset;
retcode = waitset.attach_condition(read_condition);
if (retcode != DDS_RETCODE_OK) {
return shutdown_participant(
participant,
"attach_condition error",
EXIT_FAILURE);
}
// Main loop. Wait for data to arrive, and process when it arrives
unsigned int samples_read = 0;
while (!shutdown_requested && samples_read < sample_count) {
DDSConditionSeq active_conditions_seq;
// Wait for data and report if it does not arrive in 4 seconds
DDS_Duration_t wait_timeout = { 4, 0 };
std::cout << "async subscriber sleeping for " << wait_timeout.sec
<< " sec...\n";
retcode = waitset.wait(active_conditions_seq, wait_timeout);
if (retcode == DDS_RETCODE_OK) {
// If the read condition is triggered, process data
samples_read += process_data(typed_reader);
} else if (retcode == DDS_RETCODE_TIMEOUT) {
std::cout << "No data after 4 seconds" << std::endl;
}
}
// Cleanup
return shutdown_participant(participant, "Shutting down", 0);
}
// Delete all entities
static int shutdown_participant(
DDSDomainParticipant *participant,
const char *shutdown_message,
int status)
{
DDS_ReturnCode_t retcode;
std::cout << shutdown_message << std::endl;
if (participant != NULL) {
// Cleanup everything created by this Participant
retcode = participant->delete_contained_entities();
if (retcode != DDS_RETCODE_OK) {
std::cerr << "delete_contained_entities error" << retcode
<< std::endl;
status = EXIT_FAILURE;
}
retcode = DDSTheParticipantFactory->delete_participant(participant);
if (retcode != DDS_RETCODE_OK) {
std::cerr << "delete_participant error" << retcode << std::endl;
status = EXIT_FAILURE;
}
}
return status;
}
int main(int argc, char *argv[])
{
// Parse arguments and handle control-C
ApplicationArguments arguments;
parse_arguments(arguments, argc, argv);
if (arguments.parse_result == PARSE_RETURN_EXIT) {
return EXIT_SUCCESS;
} else if (arguments.parse_result == PARSE_RETURN_FAILURE) {
return EXIT_FAILURE;
}
setup_signal_handlers();
// Sets Connext verbosity to help debugging
NDDSConfigLogger::get_instance()->set_verbosity(arguments.verbosity);
int status = run_subscriber_application(
arguments.domain_id,
arguments.sample_count);
// Releases the memory used by the participant factory. Optional at
// application exit
DDS_ReturnCode_t retcode = DDSDomainParticipantFactory::finalize_instance();
if (retcode != DDS_RETCODE_OK) {
std::cerr << "finalize_instance error" << retcode << std::endl;
status = EXIT_FAILURE;
}
return status;
}
| cxx |
rticonnextdds-examples | data/projects/rticonnextdds-examples/connext_dds/asynchronous_publication/c/async_publisher.c | /*******************************************************************************
(c) 2005-2014 Copyright, Real-Time Innovations, Inc. All rights reserved.
RTI grants Licensee a license to use, modify, compile, and create derivative
works of the Software. Licensee has the right to distribute object form only
for use with RTI products. The Software is provided "as is", with no warranty
of any type, including any warranty for fitness for any purpose. RTI is under
no obligation to maintain or support the Software. RTI shall not be liable for
any incidental or consequential damages arising out of the use or inability to
use the software.
******************************************************************************/
/* async_publisher.c
A publication of data of type async
This file is derived from code automatically generated by the rtiddsgen
command:
rtiddsgen -language C -example <arch> async.idl
Example publication of type async automatically generated by
'rtiddsgen'. To test them follow these steps:
(1) Compile this file and the example subscription.
(2) Start the subscription with the command
objs/<arch>/async_subscriber <domain_id> <sample_count>
(3) Start the publication with the command
objs/<arch>/async_publisher <domain_id> <sample_count>
(4) [Optional] Specify the list of discovery initial peers and
multicast receive addresses via an environment variable or a file
(in the current working directory) called NDDS_DISCOVERY_PEERS.
You can run any number of publishers and subscribers programs, and can
add and remove them dynamically from the domain.
Example:
To run the example application on domain <domain_id>:
On Unix:
objs/<arch>/async_publisher <domain_id>
objs/<arch>/async_subscriber <domain_id>
On Windows:
objs\<arch>\async_publisher <domain_id>
objs\<arch>\async_subscriber <domain_id>
modification history
------------ -------
*/
#include "async.h"
#include "asyncSupport.h"
#include "ndds/ndds_c.h"
#include <stdio.h>
#include <stdlib.h>
/* Delete all entities */
static int publisher_shutdown(DDS_DomainParticipant *participant)
{
DDS_ReturnCode_t retcode;
int status = 0;
if (participant != NULL) {
retcode = DDS_DomainParticipant_delete_contained_entities(participant);
if (retcode != DDS_RETCODE_OK) {
printf("delete_contained_entities error %d\n", retcode);
status = -1;
}
retcode = DDS_DomainParticipantFactory_delete_participant(
DDS_TheParticipantFactory,
participant);
if (retcode != DDS_RETCODE_OK) {
printf("delete_participant error %d\n", retcode);
status = -1;
}
}
/* RTI Connext provides finalize_instance() method on
domain participant factory for people who want to release memory used
by the participant factory. Uncomment the following block of code for
clean destruction of the singleton. */
/*
retcode = DDS_DomainParticipantFactory_finalize_instance();
if (retcode != DDS_RETCODE_OK) {
printf("finalize_instance error %d\n", retcode);
status = -1;
}
*/
return status;
}
static int publisher_main(int domainId, int sample_count)
{
DDS_DomainParticipant *participant = NULL;
DDS_Publisher *publisher = NULL;
DDS_Topic *topic = NULL;
DDS_DataWriter *writer = NULL;
asyncDataWriter *async_writer = NULL;
async *instance = NULL;
DDS_ReturnCode_t retcode;
DDS_InstanceHandle_t instance_handle = DDS_HANDLE_NIL;
const char *type_name = NULL;
int count = 0;
struct DDS_Duration_t send_period = { 0, 100000000 };
/* struct DDS_DataWriterQos datawriter_qos =
* DDS_DataWriterQos_INITIALIZER;*/
/* To customize participant QoS, use
the configuration file USER_QOS_PROFILES.xml */
participant = DDS_DomainParticipantFactory_create_participant(
DDS_TheParticipantFactory,
domainId,
&DDS_PARTICIPANT_QOS_DEFAULT,
NULL /* listener */,
DDS_STATUS_MASK_NONE);
if (participant == NULL) {
printf("create_participant error\n");
publisher_shutdown(participant);
return -1;
}
/* To customize publisher QoS, use
the configuration file USER_QOS_PROFILES.xml */
publisher = DDS_DomainParticipant_create_publisher(
participant,
&DDS_PUBLISHER_QOS_DEFAULT,
NULL /* listener */,
DDS_STATUS_MASK_NONE);
if (publisher == NULL) {
printf("create_publisher error\n");
publisher_shutdown(participant);
return -1;
}
/* Register type before creating topic */
type_name = asyncTypeSupport_get_type_name();
retcode = asyncTypeSupport_register_type(participant, type_name);
if (retcode != DDS_RETCODE_OK) {
printf("register_type error %d\n", retcode);
publisher_shutdown(participant);
return -1;
}
/* To customize topic QoS, use
the configuration file USER_QOS_PROFILES.xml */
topic = DDS_DomainParticipant_create_topic(
participant,
"Example async",
type_name,
&DDS_TOPIC_QOS_DEFAULT,
NULL /* listener */,
DDS_STATUS_MASK_NONE);
if (topic == NULL) {
printf("create_topic error\n");
publisher_shutdown(participant);
return -1;
}
/* To customize data writer QoS, use
the configuration file USER_QOS_PROFILES.xml */
writer = DDS_Publisher_create_datawriter(
publisher,
topic,
&DDS_DATAWRITER_QOS_DEFAULT,
NULL /* listener */,
DDS_STATUS_MASK_NONE);
if (writer == NULL) {
printf("create_datawriter error\n");
publisher_shutdown(participant);
return -1;
}
/* If you want to change the DataWriter's QoS programmatically rather than
* using the XML file, you will need to add the following lines to your
* code and comment out the create_datawriter call above.
*
* In this case, we set the publish mode qos to asynchronous publish mode,
* which enables asynchronous publishing. We also set the flow controller
* to be the fixed rate flow controller, and we increase the history depth.
*/
/*
/* Start changes for Asynchronous_Publication */
/* Get default datawriter QoS to customize */
/* retcode = DDS_Publisher_get_default_datawriter_qos(publisher,
&datawriter_qos); if (retcode != DDS_RETCODE_OK) {
printf("get_default_datawriter_qos error\n");
return -1;
}
*/ /* Since samples are only being sent once per second, datawriter will need
to keep them on queue. History defaults to only keeping the last
sample enqueued, so we increase that here.
*/
/* datawriter_qos.history.depth = 12;
*/ /* Set flowcontroller for datawriter */
/* datawriter_qos.publish_mode.kind = DDS_ASYNCHRONOUS_PUBLISH_MODE_QOS;
datawriter_qos.publish_mode.flow_controller_name =
DDS_FIXED_RATE_FLOW_CONTROLLER_NAME;
*/ /* To create datawriter with default QoS, use DDS_DATAWRITER_QOS_DEFAULT
instead of datawriter_qos */
/* writer = DDS_Publisher_create_datawriter(
publisher, topic,
&datawriter_qos, NULL, DDS_STATUS_MASK_NONE);
if (writer == NULL) {
printf("create_datawriter error\n");
publisher_shutdown(participant);
return -1;
}
*/
async_writer = asyncDataWriter_narrow(writer);
if (async_writer == NULL) {
printf("DataWriter narrow error\n");
publisher_shutdown(participant);
return -1;
}
/* Create data sample for writing */
instance = asyncTypeSupport_create_data_ex(DDS_BOOLEAN_TRUE);
if (instance == NULL) {
printf("asyncTypeSupport_create_data error\n");
publisher_shutdown(participant);
return -1;
}
/* For a data type that has a key, if the same instance is going to be
written multiple times, initialize the key here
and register the keyed instance prior to writing */
/*
instance_handle = asyncDataWriter_register_instance(
async_writer, instance);
*/
/* Main loop */
for (count = 0; (sample_count == 0) || (count < sample_count); ++count) {
printf("Writing async, count %d\n", count);
/* Modify the data to be written here */
/* send count as data. */
instance->x = count;
/* Write data */
retcode =
asyncDataWriter_write(async_writer, instance, &instance_handle);
if (retcode != DDS_RETCODE_OK) {
printf("write error %d\n", retcode);
}
NDDS_Utility_sleep(&send_period);
}
/* Changes for Asynchronous_Publication */
/* Give time for publisher to send out last few samples */
send_period.sec = 1;
NDDS_Utility_sleep(&send_period);
/*
retcode = asyncDataWriter_unregister_instance(
async_writer, instance, &instance_handle);
if (retcode != DDS_RETCODE_OK) {
printf("unregister instance error %d\n", retcode);
}
*/
/* Delete data sample */
retcode = asyncTypeSupport_delete_data_ex(instance, DDS_BOOLEAN_TRUE);
if (retcode != DDS_RETCODE_OK) {
printf("asyncTypeSupport_delete_data error %d\n", retcode);
}
/* Cleanup and delete delete all entities */
return publisher_shutdown(participant);
}
#if defined(RTI_WINCE)
int wmain(int argc, wchar_t **argv)
{
int domainId = 0;
int sample_count = 0; /* infinite loop */
if (argc >= 2) {
domainId = _wtoi(argv[1]);
}
if (argc >= 3) {
sample_count = _wtoi(argv[2]);
}
/* Uncomment this to turn on additional logging
NDDS_Config_Logger_set_verbosity_by_category(
NDDS_Config_Logger_get_instance(),
NDDS_CONFIG_LOG_CATEGORY_API,
NDDS_CONFIG_LOG_VERBOSITY_STATUS_ALL);
*/
return publisher_main(domainId, sample_count);
}
#elif !(defined(RTI_VXWORKS) && !defined(__RTP__)) && !defined(RTI_PSOS)
int main(int argc, char *argv[])
{
int domainId = 0;
int sample_count = 0; /* infinite loop */
if (argc >= 2) {
domainId = atoi(argv[1]);
}
if (argc >= 3) {
sample_count = atoi(argv[2]);
}
/* Uncomment this to turn on additional logging
NDDS_Config_Logger_set_verbosity_by_category(
NDDS_Config_Logger_get_instance(),
NDDS_CONFIG_LOG_CATEGORY_API,
NDDS_CONFIG_LOG_VERBOSITY_STATUS_ALL);
*/
return publisher_main(domainId, sample_count);
}
#endif
#ifdef RTI_VX653
const unsigned char *__ctype = NULL;
void usrAppInit()
{
#ifdef USER_APPL_INIT
USER_APPL_INIT; /* for backwards compatibility */
#endif
/* add application specific code here */
taskSpawn(
"pub",
RTI_OSAPI_THREAD_PRIORITY_NORMAL,
0x8,
0x150000,
(FUNCPTR) publisher_main,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0);
}
#endif
| c |
rticonnextdds-examples | data/projects/rticonnextdds-examples/connext_dds/asynchronous_publication/c/async_subscriber.c | /*******************************************************************************
(c) 2005-2014 Copyright, Real-Time Innovations, Inc. All rights reserved.
RTI grants Licensee a license to use, modify, compile, and create derivative
works of the Software. Licensee has the right to distribute object form only
for use with RTI products. The Software is provided "as is", with no warranty
of any type, including any warranty for fitness for any purpose. RTI is under
no obligation to maintain or support the Software. RTI shall not be liable for
any incidental or consequential damages arising out of the use or inability to
use the software.
******************************************************************************/
/* async_subscriber.c
A subscription example
This file is derived from code automatically generated by the rtiddsgen
command:
rtiddsgen -language C -example <arch> async.idl
Example subscription of type async automatically generated by
'rtiddsgen'. To test them, follow these steps:
(1) Compile this file and the example publication.
(2) Start the subscription with the command
objs/<arch>/async_subscriber <domain_id> <sample_count>
(3) Start the publication with the command
objs/<arch>/async_publisher <domain_id> <sample_count>
(4) [Optional] Specify the list of discovery initial peers and
multicast receive addresses via an environment variable or a file
(in the current working directory) called NDDS_DISCOVERY_PEERS.
You can run any number of publishers and subscribers programs, and can
add and remove them dynamically from the domain.
Example:
To run the example application on domain <domain_id>:
On UNIX systems:
objs/<arch>/async_publisher <domain_id>
objs/<arch>/async_subscriber <domain_id>
On Windows systems:
objs\<arch>\async_publisher <domain_id>
objs\<arch>\async_subscriber <domain_id>
modification history
------------ -------
*/
#include "async.h"
#include "asyncSupport.h"
#include "ndds/ndds_c.h"
#include <stdio.h>
#include <stdlib.h>
/* Changes for Asynchronous_Publication*/
/* For timekeeping */
#include <time.h>
clock_t init;
void asyncListener_on_requested_deadline_missed(
void *listener_data,
DDS_DataReader *reader,
const struct DDS_RequestedDeadlineMissedStatus *status)
{
}
void asyncListener_on_requested_incompatible_qos(
void *listener_data,
DDS_DataReader *reader,
const struct DDS_RequestedIncompatibleQosStatus *status)
{
}
void asyncListener_on_sample_rejected(
void *listener_data,
DDS_DataReader *reader,
const struct DDS_SampleRejectedStatus *status)
{
}
void asyncListener_on_liveliness_changed(
void *listener_data,
DDS_DataReader *reader,
const struct DDS_LivelinessChangedStatus *status)
{
}
void asyncListener_on_sample_lost(
void *listener_data,
DDS_DataReader *reader,
const struct DDS_SampleLostStatus *status)
{
}
void asyncListener_on_subscription_matched(
void *listener_data,
DDS_DataReader *reader,
const struct DDS_SubscriptionMatchedStatus *status)
{
}
void asyncListener_on_data_available(
void *listener_data,
DDS_DataReader *reader)
{
asyncDataReader *async_reader = NULL;
struct asyncSeq data_seq = DDS_SEQUENCE_INITIALIZER;
struct DDS_SampleInfoSeq info_seq = DDS_SEQUENCE_INITIALIZER;
DDS_ReturnCode_t retcode;
int i;
async_reader = asyncDataReader_narrow(reader);
if (async_reader == NULL) {
printf("DataReader narrow error\n");
return;
}
retcode = asyncDataReader_take(
async_reader,
&data_seq,
&info_seq,
DDS_LENGTH_UNLIMITED,
DDS_ANY_SAMPLE_STATE,
DDS_ANY_VIEW_STATE,
DDS_ANY_INSTANCE_STATE);
if (retcode == DDS_RETCODE_NO_DATA) {
return;
} else if (retcode != DDS_RETCODE_OK) {
printf("take error %d\n", retcode);
return;
}
for (i = 0; i < asyncSeq_get_length(&data_seq); ++i) {
if (DDS_SampleInfoSeq_get_reference(&info_seq, i)->valid_data) {
/* Start changes for Asynchronous_Publication */
/* print the time we get each sample. */
double elapsed_ticks = clock() - init;
double elapsed_secs = elapsed_ticks / CLOCKS_PER_SEC;
printf("@ t=%.2fs, got x = %d\n",
elapsed_secs,
asyncSeq_get_reference(&data_seq, i)->x);
/* End changes for Asynchronous_Publication */
}
}
retcode = asyncDataReader_return_loan(async_reader, &data_seq, &info_seq);
if (retcode != DDS_RETCODE_OK) {
printf("return loan error %d\n", retcode);
}
}
/* Delete all entities */
static int subscriber_shutdown(DDS_DomainParticipant *participant)
{
DDS_ReturnCode_t retcode;
int status = 0;
if (participant != NULL) {
retcode = DDS_DomainParticipant_delete_contained_entities(participant);
if (retcode != DDS_RETCODE_OK) {
printf("delete_contained_entities error %d\n", retcode);
status = -1;
}
retcode = DDS_DomainParticipantFactory_delete_participant(
DDS_TheParticipantFactory,
participant);
if (retcode != DDS_RETCODE_OK) {
printf("delete_participant error %d\n", retcode);
status = -1;
}
}
/* RTI Connext provides the finalize_instance() method on
domain participant factory for users who want to release memory used
by the participant factory. Uncomment the following block of code for
clean destruction of the singleton. */
/*
retcode = DDS_DomainParticipantFactory_finalize_instance();
if (retcode != DDS_RETCODE_OK) {
printf("finalize_instance error %d\n", retcode);
status = -1;
}
*/
return status;
}
static int subscriber_main(int domainId, int sample_count)
{
DDS_DomainParticipant *participant = NULL;
DDS_Subscriber *subscriber = NULL;
DDS_Topic *topic = NULL;
struct DDS_DataReaderListener reader_listener =
DDS_DataReaderListener_INITIALIZER;
DDS_DataReader *reader = NULL;
DDS_ReturnCode_t retcode;
const char *type_name = NULL;
int count = 0;
struct DDS_Duration_t poll_period = { 4, 0 };
/* Changes for Asynchronous_Publication */
/* for timekeeping */
init = clock();
/* To customize participant QoS, use
the configuration file USER_QOS_PROFILES.xml */
participant = DDS_DomainParticipantFactory_create_participant(
DDS_TheParticipantFactory,
domainId,
&DDS_PARTICIPANT_QOS_DEFAULT,
NULL /* listener */,
DDS_STATUS_MASK_NONE);
if (participant == NULL) {
printf("create_participant error\n");
subscriber_shutdown(participant);
return -1;
}
/* To customize subscriber QoS, use
the configuration file USER_QOS_PROFILES.xml */
subscriber = DDS_DomainParticipant_create_subscriber(
participant,
&DDS_SUBSCRIBER_QOS_DEFAULT,
NULL /* listener */,
DDS_STATUS_MASK_NONE);
if (subscriber == NULL) {
printf("create_subscriber error\n");
subscriber_shutdown(participant);
return -1;
}
/* Register the type before creating the topic */
type_name = asyncTypeSupport_get_type_name();
retcode = asyncTypeSupport_register_type(participant, type_name);
if (retcode != DDS_RETCODE_OK) {
printf("register_type error %d\n", retcode);
subscriber_shutdown(participant);
return -1;
}
/* To customize topic QoS, use
the configuration file USER_QOS_PROFILES.xml */
topic = DDS_DomainParticipant_create_topic(
participant,
"Example async",
type_name,
&DDS_TOPIC_QOS_DEFAULT,
NULL /* listener */,
DDS_STATUS_MASK_NONE);
if (topic == NULL) {
printf("create_topic error\n");
subscriber_shutdown(participant);
return -1;
}
/* Set up a data reader listener */
reader_listener.on_requested_deadline_missed =
asyncListener_on_requested_deadline_missed;
reader_listener.on_requested_incompatible_qos =
asyncListener_on_requested_incompatible_qos;
reader_listener.on_sample_rejected = asyncListener_on_sample_rejected;
reader_listener.on_liveliness_changed = asyncListener_on_liveliness_changed;
reader_listener.on_sample_lost = asyncListener_on_sample_lost;
reader_listener.on_subscription_matched =
asyncListener_on_subscription_matched;
reader_listener.on_data_available = asyncListener_on_data_available;
/* To customize data reader QoS, use
the configuration file USER_QOS_PROFILES.xml */
reader = DDS_Subscriber_create_datareader(
subscriber,
DDS_Topic_as_topicdescription(topic),
&DDS_DATAREADER_QOS_DEFAULT,
&reader_listener,
DDS_STATUS_MASK_ALL);
if (reader == NULL) {
printf("create_datareader error\n");
subscriber_shutdown(participant);
return -1;
}
/* Main loop */
for (count = 0; (sample_count == 0) || (count < sample_count); ++count) {
printf("async subscriber sleeping for %d sec...\n", poll_period.sec);
NDDS_Utility_sleep(&poll_period);
}
/* Cleanup and delete all entities */
return subscriber_shutdown(participant);
}
#if defined(RTI_WINCE)
int wmain(int argc, wchar_t **argv)
{
int domainId = 0;
int sample_count = 0; /* infinite loop */
if (argc >= 2) {
domainId = _wtoi(argv[1]);
}
if (argc >= 3) {
sample_count = _wtoi(argv[2]);
}
/* Uncomment this to turn on additional logging
NDDS_Config_Logger_set_verbosity_by_category(
NDDS_Config_Logger_get_instance(),
NDDS_CONFIG_LOG_CATEGORY_API,
NDDS_CONFIG_LOG_VERBOSITY_STATUS_ALL);
*/
return subscriber_main(domainId, sample_count);
}
#elif !(defined(RTI_VXWORKS) && !defined(__RTP__)) && !defined(RTI_PSOS)
int main(int argc, char *argv[])
{
int domainId = 0;
int sample_count = 0; /* infinite loop */
if (argc >= 2) {
domainId = atoi(argv[1]);
}
if (argc >= 3) {
sample_count = atoi(argv[2]);
}
/* Uncomment this to turn on additional logging
NDDS_Config_Logger_set_verbosity_by_category(
NDDS_Config_Logger_get_instance(),
NDDS_CONFIG_LOG_CATEGORY_API,
NDDS_CONFIG_LOG_VERBOSITY_STATUS_ALL);
*/
return subscriber_main(domainId, sample_count);
}
#endif
#ifdef RTI_VX653
const unsigned char *__ctype = NULL;
void usrAppInit()
{
#ifdef USER_APPL_INIT
USER_APPL_INIT; /* for backwards compatibility */
#endif
/* add application specific code here */
taskSpawn(
"sub",
RTI_OSAPI_THREAD_PRIORITY_NORMAL,
0x8,
0x150000,
(FUNCPTR) subscriber_main,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0);
}
#endif
| c |
rticonnextdds-examples | data/projects/rticonnextdds-examples/connext_dds/asynchronous_publication/c++03/async_publisher.cxx | /*******************************************************************************
(c) 2005-2015 Copyright, Real-Time Innovations, Inc. All rights reserved.
RTI grants Licensee a license to use, modify, compile, and create derivative
works of the Software. Licensee has the right to distribute object form only
for use with RTI products. The Software is provided "as is", with no warranty
of any type, including any warranty for fitness for any purpose. RTI is under
no obligation to maintain or support the Software. RTI shall not be liable for
any incidental or consequential damages arising out of the use or inability to
use the software.
******************************************************************************/
#include <iostream>
#include "async.hpp"
#include <dds/dds.hpp>
#include <rti/pub/FlowController.hpp>
using namespace dds::core;
using namespace dds::core::policy;
using namespace rti::core::policy;
using namespace dds::domain;
using namespace dds::topic;
using namespace dds::pub;
using namespace dds::pub::qos;
using namespace rti::pub;
void publisher_main(int domain_id, int sample_count)
{
// To customize participant QoS, use file USER_QOS_PROFILES.xml
DomainParticipant participant(domain_id);
// To customize topic QoS, use file USER_QOS_PROFILES.xml
Topic<async> topic(participant, "Example async");
// Retrieve the default DataWriter QoS, from USER_QOS_PROFILES.xml
DataWriterQos writer_qos = QosProvider::Default().datawriter_qos();
// If you want to change the DataWriter's QoS programmatically rather than
// using the XML file, uncomment the following lines.
//
// In this case, we set the publish mode QoS to asynchronous publish mode,
// which enables asynchronous publishing. We also set the flow controller
// to be the fixed rate flow controller, and we increase the history depth.
// writer_qos << Reliability::Reliable(Duration(60));
// DataWriterProtocol writer_protocol_qos;
// RtpsReliableWriterProtocol rtps_writer_protocol;
// rtps_writer_protocol.min_send_window_size(50);
// rtps_writer_protocol.max_send_window_size(50);
// writer_protocol_qos.rtps_reliable_writer(rtps_writer_protocol);
// writer_qos << writer_protocol_qos;
// Since samples are only being sent once per second, DataWriter will need
// to keep them on queue. History defaults to only keeping the last
// sample enqueued, so we increase that here.
// writer_qos << History::KeepLast(12);
// Set flowcontroller for DataWriter
// writer_qos << PublishMode::Asynchronous(FlowController::FIXED_RATE_NAME);
// Create the DataWriter with a QoS.
DataWriter<async> writer(Publisher(participant), topic, writer_qos);
// Create data sample for writing
async instance;
// For a data type that has a key, if the same instance is going to be
// written multiple times, initialize the key here
// and register the keyed instance prior to writing.
// InstanceHandle instance_handle = writer.register_instance(instance);
// Main loop
for (int count = 0; (sample_count == 0) || (count < sample_count);
++count) {
std::cout << "Writing async, count " << count << std::endl;
// Send count as data
instance.x(count);
// Send it, if using instance_handle:
// writer.write(instance, instance_handle);
writer.write(instance);
rti::util::sleep(Duration(0, 100000000));
}
// If using instance_handle, unregister it.
// writer.unregister_instance(instance_handle);
}
int main(int argc, char *argv[])
{
int domain_id = 0;
int sample_count = 0; /* infinite loop */
if (argc >= 2) {
domain_id = atoi(argv[1]);
}
if (argc >= 3) {
sample_count = atoi(argv[2]);
}
// To turn on additional logging, include <rti/config/Logger.hpp> and
// uncomment the following line:
// rti::config::Logger::instance().verbosity(rti::config::Verbosity::STATUS_ALL);
try {
publisher_main(domain_id, sample_count);
} catch (std::exception ex) {
std::cout << "Exception caught: " << ex.what() << std::endl;
return -1;
}
return 0;
}
| cxx |
rticonnextdds-examples | data/projects/rticonnextdds-examples/connext_dds/asynchronous_publication/c++03/async_subscriber.cxx | /*******************************************************************************
(c) 2005-2015 Copyright, Real-Time Innovations, Inc. All rights reserved.
RTI grants Licensee a license to use, modify, compile, and create derivative
works of the Software. Licensee has the right to distribute object form only
for use with RTI products. The Software is provided "as is", with no warranty
of any type, including any warranty for fitness for any purpose. RTI is under
no obligation to maintain or support the Software. RTI shall not be liable for
any incidental or consequential damages arising out of the use or inability to
use the software.
******************************************************************************/
#include <ctime>
#include <iostream>
#include "async.hpp"
#include <dds/dds.hpp>
#include <rti/core/ListenerBinder.hpp>
using namespace dds::core;
using namespace dds::core::policy;
using namespace dds::domain;
using namespace dds::topic;
using namespace dds::sub;
using namespace dds::sub::qos;
// For timekeeping
clock_t InitTime;
class AsyncListener : public NoOpDataReaderListener<async> {
public:
void on_data_available(DataReader<async> &reader)
{
LoanedSamples<async> samples = reader.take();
for (LoanedSamples<async>::iterator sampleIt = samples.begin();
sampleIt != samples.end();
++sampleIt) {
// Print the time we get each sample.
if (sampleIt->info().valid()) {
double elapsed_ticks = clock() - InitTime;
double elapsed_secs = elapsed_ticks / CLOCKS_PER_SEC;
std::cout << "@ t=" << elapsed_secs << "s"
<< ", got x = " << sampleIt->data().x() << std::endl;
}
}
}
};
void subscriber_main(int domain_id, int sample_count)
{
// For timekeeping
InitTime = clock();
// To customize the paritcipant QoS, use the file USER_QOS_PROFILES.xml
DomainParticipant participant(domain_id);
// To customize the topic QoS, use the file USER_QOS_PROFILES.xml
Topic<async> topic(participant, "Example async");
// Retrieve the default DataReader QoS, from USER_QOS_PROFILES.xml
DataReaderQos reader_qos = QosProvider::Default().datareader_qos();
// If you want to change the DataWriter's QoS programmatically rather than
// using the XML file, uncomment the following lines.
// reader_qos << Reliability::Reliable();
// reader_qos << History::KeepAll();
// Create a DataReader with a QoS
DataReader<async> reader(Subscriber(participant), topic, reader_qos);
// Create a data reader listener using ListenerBinder, a RAII utility that
// will take care of reseting it from the reader and deleting it.
rti::core::ListenerBinder<DataReader<async> > scoped_listener =
rti::core::bind_and_manage_listener(
reader,
new AsyncListener,
dds::core::status::StatusMask::data_available());
// Main loop
for (int count = 0; (sample_count == 0) || (count < sample_count);
++count) {
std::cout << "async subscriber sleeping for 4 sec..." << std::endl;
rti::util::sleep(Duration(4));
}
}
int main(int argc, char *argv[])
{
int domain_id = 0;
int sample_count = 0; // Infinite loop
if (argc >= 2) {
domain_id = atoi(argv[1]);
}
if (argc >= 3) {
sample_count = atoi(argv[2]);
}
// To turn on additional logging, include <rti/config/Logger.hpp> and
// uncomment the following line:
// rti::config::Logger::instance().verbosity(rti::config::Verbosity::STATUS_ALL);
try {
subscriber_main(domain_id, sample_count);
} catch (std::exception ex) {
std::cout << "Exception caught: " << ex.what() << std::endl;
return -1;
}
return 0;
}
| cxx |
rticonnextdds-examples | data/projects/rticonnextdds-examples/connext_dds/asynchronous_publication/c++11/application.hpp | /*
* (c) Copyright, Real-Time Innovations, 2020. All rights reserved.
* RTI grants Licensee a license to use, modify, compile, and create derivative
* works of the software solely for use with RTI Connext DDS. Licensee may
* redistribute copies of the software provided that all such copies are subject
* to this license. The software is provided "as is", with no warranty of any
* type, including any warranty for fitness for any purpose. RTI is under no
* obligation to maintain or support the software. RTI shall not be liable for
* any incidental or consequential damages arising out of the use or inability
* to use the software.
*/
#ifndef APPLICATION_HPP
#define APPLICATION_HPP
#include <iostream>
#include <csignal>
#include <dds/core/ddscore.hpp>
namespace application {
// Catch control-C and tell application to shut down
bool shutdown_requested = false;
inline void stop_handler(int)
{
shutdown_requested = true;
std::cout << "preparing to shut down..." << std::endl;
}
inline void setup_signal_handlers()
{
signal(SIGINT, stop_handler);
signal(SIGTERM, stop_handler);
}
enum class ParseReturn { ok, failure, exit };
struct ApplicationArguments {
ParseReturn parse_result;
unsigned int domain_id;
unsigned int sample_count;
rti::config::Verbosity verbosity;
ApplicationArguments(
ParseReturn parse_result_param,
unsigned int domain_id_param,
unsigned int sample_count_param,
rti::config::Verbosity verbosity_param)
: parse_result(parse_result_param),
domain_id(domain_id_param),
sample_count(sample_count_param),
verbosity(verbosity_param)
{
}
};
inline void set_verbosity(
rti::config::Verbosity &verbosity,
int verbosity_value)
{
switch (verbosity_value) {
case 0:
verbosity = rti::config::Verbosity::SILENT;
break;
case 1:
verbosity = rti::config::Verbosity::EXCEPTION;
break;
case 2:
verbosity = rti::config::Verbosity::WARNING;
break;
case 3:
verbosity = rti::config::Verbosity::STATUS_ALL;
break;
default:
verbosity = rti::config::Verbosity::EXCEPTION;
break;
}
}
// Parses application arguments for example.
inline ApplicationArguments parse_arguments(int argc, char *argv[])
{
int arg_processing = 1;
bool show_usage = false;
ParseReturn parse_result = ParseReturn::ok;
unsigned int domain_id = 0;
unsigned int sample_count = (std::numeric_limits<unsigned int>::max)();
rti::config::Verbosity verbosity(rti::config::Verbosity::EXCEPTION);
while (arg_processing < argc) {
if ((argc > arg_processing + 1)
&& (strcmp(argv[arg_processing], "-d") == 0
|| strcmp(argv[arg_processing], "--domain") == 0)) {
domain_id = atoi(argv[arg_processing + 1]);
arg_processing += 2;
} else if (
(argc > arg_processing + 1)
&& (strcmp(argv[arg_processing], "-s") == 0
|| strcmp(argv[arg_processing], "--sample-count") == 0)) {
sample_count = atoi(argv[arg_processing + 1]);
arg_processing += 2;
} else if (
(argc > arg_processing + 1)
&& (strcmp(argv[arg_processing], "-v") == 0
|| strcmp(argv[arg_processing], "--verbosity") == 0)) {
set_verbosity(verbosity, atoi(argv[arg_processing + 1]));
arg_processing += 2;
} else if (
strcmp(argv[arg_processing], "-h") == 0
|| strcmp(argv[arg_processing], "--help") == 0) {
std::cout << "Example application." << std::endl;
show_usage = true;
parse_result = ParseReturn::exit;
break;
} else {
std::cout << "Bad parameter." << std::endl;
show_usage = true;
parse_result = ParseReturn::failure;
break;
}
}
if (show_usage) {
std::cout << "Usage:\n"
" -d, --domain <int> Domain ID this "
"application will\n"
" subscribe in. \n"
" Default: 0\n"
" -s, --sample_count <int> Number of samples to "
"receive before\n"
" cleanly shutting down. \n"
" Default: infinite\n"
" -v, --verbosity <int> How much debugging output "
"to show.\n"
" Range: 0-3 \n"
" Default: 1"
<< std::endl;
}
return ApplicationArguments(
parse_result,
domain_id,
sample_count,
verbosity);
}
} // namespace application
#endif // APPLICATION_HPP | hpp |
rticonnextdds-examples | data/projects/rticonnextdds-examples/connext_dds/asynchronous_publication/c++11/async_publisher.cxx | /*******************************************************************************
(c) 2005-2015 Copyright, Real-Time Innovations, Inc. All rights reserved.
RTI grants Licensee a license to use, modify, compile, and create derivative
works of the Software. Licensee has the right to distribute object form only
for use with RTI products. The Software is provided "as is", with no warranty
of any type, including any warranty for fitness for any purpose. RTI is under
no obligation to maintain or support the Software. RTI shall not be liable for
any incidental or consequential damages arising out of the use or inability to
use the software.
******************************************************************************/
#include <iostream>
#include <dds/pub/ddspub.hpp>
#include <rti/util/util.hpp> // for sleep()
#include <rti/config/Logger.hpp> // for logging
#include "application.hpp" // for command line parsing and ctrl-c
#include "async.hpp"
void run_publisher_application(
unsigned int domain_id,
unsigned int sample_count)
{
// To customize participant QoS, use file USER_QOS_PROFILES.xml
dds::domain::DomainParticipant participant(domain_id);
// To customize topic QoS, use file USER_QOS_PROFILES.xml
dds::topic::Topic<async> topic(participant, "Example async");
// Retrieve the default DataWriter QoS, from USER_QOS_PROFILES.xml
dds::pub::qos::DataWriterQos writer_qos =
dds::core::QosProvider::Default().datawriter_qos();
// If you want to change the DataWriter's QoS programmatically rather than
// using the XML file, uncomment the following lines.
//
// In this case, we set the publish mode QoS to asynchronous publish mode,
// which enables asynchronous publishing. We also set the flow controller
// to be the fixed rate flow controller, and we increase the history depth.
// writer_qos << Reliability::Reliable(Duration(60));
// DataWriterProtocol writer_protocol_qos;
// RtpsReliableWriterProtocol rtps_writer_protocol;
// rtps_writer_protocol.min_send_window_size(50);
// rtps_writer_protocol.max_send_window_size(50);
// writer_protocol_qos.rtps_reliable_writer(rtps_writer_protocol);
// writer_qos << writer_protocol_qos;
// Since samples are only being sent once per second, DataWriter will need
// to keep them on queue. History defaults to only keeping the last
// sample enqueued, so we increase that here.
// writer_qos << History::KeepLast(12);
// Set flowcontroller for DataWriter
// writer_qos << PublishMode::Asynchronous(FlowController::FIXED_RATE_NAME);
// Create a Publisher
dds::pub::Publisher publisher(participant);
// Create the DataWriter with a QoS.
dds::pub::DataWriter<async> writer(publisher, topic, writer_qos);
// Create data sample for writing
async instance;
// For a data type that has a key, if the same instance is going to be
// written multiple times, initialize the key here
// and register the keyed instance prior to writing.
// InstanceHandle instance_handle = writer.register_instance(instance);
// Main loop
for (unsigned int samples_written = 0;
!application::shutdown_requested && samples_written < sample_count;
samples_written++) {
std::cout << "Writing async, count " << samples_written << std::endl;
// Send count as data
instance.x(samples_written);
// Send it, if using instance_handle:
// writer.write(instance, instance_handle);
writer.write(instance);
rti::util::sleep(dds::core::Duration::from_millisecs(100));
}
// If using instance_handle, unregister it.
// writer.unregister_instance(instance_handle);
}
int main(int argc, char *argv[])
{
using namespace application;
// Parse arguments and handle control-C
auto arguments = parse_arguments(argc, argv);
if (arguments.parse_result == ParseReturn::exit) {
return EXIT_SUCCESS;
} else if (arguments.parse_result == ParseReturn::failure) {
return EXIT_FAILURE;
}
setup_signal_handlers();
// Sets Connext verbosity to help debugging
rti::config::Logger::instance().verbosity(arguments.verbosity);
try {
run_publisher_application(arguments.domain_id, arguments.sample_count);
} catch (const std::exception &ex) {
// This will catch DDS exceptions
std::cerr << "Exception in run_publisher_application(): " << ex.what()
<< std::endl;
return EXIT_FAILURE;
}
// Releases the memory used by the participant factory. Optional at
// application exit
dds::domain::DomainParticipant::finalize_participant_factory();
return EXIT_SUCCESS;
}
| cxx |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.