12#ifndef RTCTK_STANDALONETOOLS_SHMSUBSCRIBER_H
13#define RTCTK_STANDALONETOOLS_SHMSUBSCRIBER_H
15#include <boost/io/ios_state.hpp>
20#include <ipcq/adapter.hpp>
21#include <ipcq/reader.hpp>
44 int Run(
int argc,
char* argv[]);
115 return m_sample_counter;
127 bool ParseArguments(
int argc,
char* argv[]);
128 void WriteBufferToFile(
const void* buffer,
size_t size);
129 bool TerminateProcess();
131 std::string m_queue_name;
132 std::string m_filename;
133 int64_t m_max_samples;
134 int64_t m_skip_samples;
135 bool m_print_samples;
137 int64_t m_sample_counter;
150template <
typename Topic,
151 class ConditionPolicy = ipcq::BoostConditionPolicy,
152 class ShmTraits = ipcq::detail::BoostInterprocessTraits>
175 boost::io::ios_flags_saver saved_state(std::cout);
177 auto buffer =
reinterpret_cast<const uint8_t*
>(&sample);
178 size_t max_bytes_to_print = 64;
180 max_bytes_to_print = std::numeric_limits<size_t>::max();
182 bool last_was_endl =
false;
183 for (
size_t n = 0; n <
sizeof(Topic) and n < max_bytes_to_print; ++n) {
184 std::cout <<
"0x" << std::setfill(
'0') << std::setw(2) << std::right << std::noshowbase
185 << std::hex << static_cast<unsigned int>(buffer[n]);
186 if ((n + 1) % 16 == 0) {
188 last_was_endl =
true;
191 last_was_endl =
false;
194 if (not last_was_endl) {
197 if (
sizeof(Topic) > max_bytes_to_print) {
198 std::cout <<
"... (data continues) ...\n";
203 using Reader = ipcq::BasicReader<Topic, ConditionPolicy, ShmTraits>;
208 void Initialise()
override {
210 m_reader = std::make_unique<Reader>(
GetQueueName().c_str());
211 }
catch (
const std::exception& error) {
212 std::string msg =
"Failed to create the shared memory reader for queue '" +
214 throw std::runtime_error(msg);
221 void Finalise()
override {
223 m_reader.reset(
nullptr);
224 }
catch (
const std::exception& error) {
225 std::string msg =
"Failed to destroy the shared memory reader for queue '" +
227 throw std::runtime_error(msg);
239 bool ReadSample()
override {
240 if (not m_samples.empty()) {
241 m_samples.pop_front();
243 if (not m_samples.empty()) {
246 using namespace std::chrono_literals;
247 auto count = m_reader->NumAvailable();
248 auto [error, num_elements] = m_reader->Read(ipcq::BackInserter(m_samples), count, 100ms);
250 if (error == ipcq::make_error_code(ipcq::Error::Timeout)) {
252 }
else if (error == ipcq::make_error_code(ipcq::Error::InconsistentState)) {
258 if (!m_reader->Reset()) {
261 std::cerr <<
"Note: SHM reader state reset.\n";
265 std::string msg =
"Failed to read from shared memory: " + error.message();
266 throw std::runtime_error(msg);
269 return num_elements > 0;
276 assert(not m_samples.empty());
283 const void* GetSampleData()
const override {
284 assert(not m_samples.empty());
285 return reinterpret_cast<const void*
>(&m_samples.front());
291 size_t GetSampleSize()
const override {
292 return sizeof(Topic);
295 std::deque<Topic> m_samples;
296 std::unique_ptr<Reader> m_reader;