nros C++ API
Lightweight ROS 2 client for embedded real-time systems (C++ headers)
Loading...
Searching...
No Matches
publisher.hpp
Go to the documentation of this file.
1// nros-cpp: Publisher class
2// Freestanding C++ — no exceptions, no STL required
3
9
10#ifndef NROS_RCLCPP_PUBLISHER_HPP
11#define NROS_RCLCPP_PUBLISHER_HPP
12
13#include <cstdint>
14#include <cstddef>
15#include <string.h> // memcpy — `<cstring>` isn't in Zephyr's minimal libcpp
16
17#include "rclcpp/detail/traits.hpp"
19#include "rclcpp/detail/std_detect.hpp" // `NROS_CPP_HAS_SHARED_PTR`
20#include "rclcpp/detail/entity_name.hpp" // the one entity-name copy
21#include "rclcpp/executor.hpp" // the graph counter these forward to
22#include "rclcpp/owned.hpp" // `Publisher<M>::SharedPtr` IS `Owned<Publisher<M>>`
23#include "rclcpp/result.hpp"
24#if defined(NROS_CPP_STD) // hosted-family: ported-publish
25#include <rclc/log.h> // `detail::report_failed_publish`
26#endif
27// NROS_CPP_ASSERT_MESSAGE_FORMAT, expanded in the creator below.
29
30#include "rclcpp/detail/nros_cpp_ffi.h"
31#include "rclcpp/event.hpp" // MatchedInfo / IncompatibleTypeInfo
32
33// `get_actual_qos()` returns a `rclcpp::QoS` BY VALUE from an
34// inline body, so the complete type must be here, not only by the time
35// `rclcpp/node.hpp` is pulled in below.
36//
37// AFTER `nros_cpp_ffi.h`, never before: `qos.hpp` defines the four
38// `nros_cpp_qos_*_t` enums ITSELF under `#ifndef NROS_CPP_FFI_H`, so
39// reaching it first makes the cbindgen header a REDEFINITION of all four.
40#include "rclcpp/qos.hpp"
41
42// THIS HEADER NO LONGER DETECTS ANYTHING, and the include that
43// used to sit here is gone with the block it served.
44//
45// `Publisher<M>::SharedPtr` and friends used to be
46// `std::shared_ptr` / `std::unique_ptr`, so they needed `<memory>` — which a
47// MINIMAL freestanding libcpp does not ship (Zephyr's is `<cstddef>`,
48// `<cstdint>`, `<new>`, plus this repo's `zephyr/cxx-compat/`) — and the
49// aliases were therefore ABSENT on exactly the targets ported source needs them
50// on. The predicate that decided it needed three separate corrections to get
51// right.
52//
53// The aliases name `rclcpp::Owned<Publisher<M>>` now, which is ours and exists
54// everywhere, so there is no capability left to probe: the alias is present
55// unconditionally and means the same thing on every target. That is the freestanding-API rule
56// — one API, no shape decided by a toolchain flag — reached by deleting the
57// question rather than by answering it more carefully.
58
59namespace rclcpp {
60
66static constexpr size_t PUBLISHER_TOPIC_NAME_MAX = 256;
67
68} // namespace rclcpp
69
77namespace rclcpp {
78class Node;
79}
80
81// ============================================================================
82// `rclcpp::Publisher<M>` -- DEFINED here (rclcpp:: is the home)
83// ============================================================================
84//
85// The definition moved from `nros::` to `rclcpp::` (the `nros::`
86// alias is gone). The nested `SharedPtr` / `ConstSharedPtr` / `UniquePtr`
87// aliases live on the class itself, so `rclcpp::Publisher<M>::SharedPtr` -- the
88// way rclcpp users index types -- resolves with no wrapper in between.
89namespace rclcpp {
90
146#if defined(NROS_CPP_STD) // hosted-family: ported-publish
147namespace detail {
158class PublishResult : public ::rclcpp::ResultOf<void> {
159 public:
160 constexpr PublishResult(::rclcpp::ResultOf<void> r) : ::rclcpp::ResultOf<void>(r) {}
161};
162
167template <typename M> inline void report_failed_publish(const char* topic, int32_t code) {
168 static unsigned long failures = 0;
169 if ((failures++ % 1024UL) == 0) {
170 RCLC_LOG_ERROR(rclc_log_default_logger(),
171 "rclcpp::Publisher::publish on \"%.64s\" failed: rclcpp::ErrorCode %d "
172 "(%lu failure(s) so far)",
173 topic, static_cast<int>(code), failures);
174 }
175}
176} // namespace detail
177#endif
178
179template <typename M> class Publisher {
180 public:
203 using SharedPtr = ::rclcpp::Owned<Publisher<M>>;
211 using ConstSharedPtr = ::rclcpp::Owned<Publisher<M>>;
218 using UniquePtr = ::rclcpp::Owned<Publisher<M>>;
219
224 static constexpr size_t GID_SIZE = 24;
225
247#if defined(NROS_CPP_STD) // hosted-family: ported-publish
248 ::rclcpp::detail::PublishResult publish(const M& msg) {
249 const Result r = initialized_ ? Result(M::ffi_publish(storage_, &msg))
251 if (!r.ok()) ::rclcpp::detail::report_failed_publish<M>(get_topic_name(), r.raw());
252 return r;
253 }
254#if defined(NROS_CPP_HAS_SHARED_PTR) // hosted-family: shared-ptr-interop
261 template <typename D>::rclcpp::detail::PublishResult publish(::std::unique_ptr<M, D> msg) {
262 if (!msg) {
264 ::rclcpp::detail::report_failed_publish<M>(get_topic_name(), r.raw());
265 return r;
266 }
267 return publish(static_cast<const M&>(*msg));
268 }
269#endif
270#else
271 Result publish(const M& msg) {
272 if (!initialized_) return Result(::rclcpp::ErrorCode::NotInitialized);
273 return Result(M::ffi_publish(storage_, &msg));
274 }
275#endif
276
283 Result publish_serialized(const uint8_t* data, size_t len) {
284 if (!initialized_) return Result(::rclcpp::ErrorCode::NotInitialized);
285 return Result(nros_cpp_publish_raw(storage_, data, len));
286 }
287
289 NROS_CPP_DEPRECATED_MSG("renamed to publish_serialized; call that instead")
290 Result publish_raw(const uint8_t* data, size_t len) { return publish_serialized(data, len); }
291
302 template <typename W> Result publish_streamed(size_t total_len, W&& writer) {
303 if (!initialized_) return Result(::rclcpp::ErrorCode::NotInitialized);
304 struct Ctx {
305 W writer;
306 size_t total;
307 } ctx{static_cast<W&&>(writer), total_len};
308 auto size_cb = [](size_t* out_total, void* user) {
309 auto* c = static_cast<Ctx*>(user);
310 *out_total = c->total;
311 };
312 auto chunk_cb = [](uint8_t* out_buf, size_t cap, size_t* out_written, void* user) {
313 auto* c = static_cast<Ctx*>(user);
314 *out_written = c->writer(out_buf, cap);
315 };
316 return Result(nros_cpp_publisher_publish_streamed(storage_, size_cb, chunk_cb,
317 static_cast<void*>(&ctx)));
318 }
319
320 // ====================================================================
321 // Zero-copy publish (loan / commit / discard)
322 // ====================================================================
323
327 class Loan {
328 public:
329 Loan() : pub_(nullptr), buf_(nullptr), cap_(0), token_(nullptr) {}
330 Loan(Loan&& o) : pub_(o.pub_), buf_(o.buf_), cap_(o.cap_), token_(o.token_) {
331 o.pub_ = nullptr;
332 o.token_ = nullptr;
333 }
335 if (this != &o) {
336 release();
337 pub_ = o.pub_;
338 buf_ = o.buf_;
339 cap_ = o.cap_;
340 token_ = o.token_;
341 o.pub_ = nullptr;
342 o.token_ = nullptr;
343 }
344 return *this;
345 }
346 Loan(const Loan&) = delete;
347 Loan& operator=(const Loan&) = delete;
348 ~Loan() { release(); }
349
351 uint8_t* data() { return buf_; }
352 const uint8_t* data() const { return buf_; }
353 size_t capacity() const { return cap_; }
354
355 bool is_valid() const { return token_ != nullptr; }
356
358 Result commit(size_t actual_len) {
359 if (!token_) return Result(::rclcpp::ErrorCode::NotInitialized);
360 nros_cpp_ret_t ret = nros_cpp_publisher_commit(pub_, token_, actual_len);
361 pub_ = nullptr;
362 token_ = nullptr;
363 buf_ = nullptr;
364 cap_ = 0;
365 return Result(ret);
366 }
367
370 if (!token_) return Result::success();
371 nros_cpp_ret_t ret = nros_cpp_publisher_discard(pub_, token_);
372 pub_ = nullptr;
373 token_ = nullptr;
374 buf_ = nullptr;
375 cap_ = 0;
376 return Result(ret);
377 }
378
381 Loan(void* pub, uint8_t* buf, size_t cap, void* token)
382 : pub_(pub), buf_(buf), cap_(cap), token_(token) {}
383
384 private:
385 void release() {
386 if (token_ && pub_) {
387 nros_cpp_publisher_discard(pub_, token_);
388 token_ = nullptr;
389 }
390 }
391
392 void* pub_;
393 uint8_t* buf_;
394 size_t cap_;
395 void* token_;
396 };
397
406 ::rclcpp::ResultOf<Loan> loan(size_t requested_len) {
407 if (!initialized_)
408 return ::rclcpp::ResultOf<Loan>::error(Result(::rclcpp::ErrorCode::NotInitialized));
409 uint8_t* buf = nullptr;
410 size_t cap = 0;
411 void* token = nullptr;
412 nros_cpp_ret_t ret = nros_cpp_publisher_loan(storage_, requested_len, &buf, &cap, &token);
413 if (ret != 0) return ::rclcpp::ResultOf<Loan>::error(Result(ret));
414 return ::rclcpp::ResultOf<Loan>::ok(Loan{storage_, buf, cap, token});
415 }
416
418 const char* get_topic_name() const { return initialized_ ? topic_name_ : ""; }
419
440 nros_cpp_qos_t f{};
441 if (!initialized_ || nros_cpp_publisher_get_actual_qos(storage_, &f) != 0) {
442 return ::rclcpp::detail::qos_all_unknown();
443 }
444 return ::rclcpp::detail::qos_from_ffi(f);
445 }
446
460
489 Result get_subscription_count(::rclcpp::Executor& executor, size_t* out_count) const {
490 if (!initialized_) return Result(::rclcpp::ErrorCode::NotInitialized);
491 return executor.count_subscribers(topic_name_, out_count);
492 }
493
495 bool is_valid() const { return initialized_; }
496
499 if (initialized_) {
500 nros_cpp_publisher_destroy(storage_);
501 initialized_ = false;
502 }
503 }
504
505 // Move semantics (non-copyable). Relocation goes through the
506 // `nros_cpp_publisher_relocate` runtime call.
507 Publisher(Publisher&& other) : initialized_(other.initialized_) {
508 if (other.initialized_) {
509 nros_cpp_publisher_relocate(other.storage_, storage_);
510 ::memcpy(topic_name_, other.topic_name_, sizeof(topic_name_));
511 other.initialized_ = false;
512 }
513 }
514
516 if (this != &other) {
517 if (initialized_) {
518 nros_cpp_publisher_destroy(storage_);
519 initialized_ = false;
520 }
521 if (other.initialized_) {
522 nros_cpp_publisher_relocate(other.storage_, storage_);
523 ::memcpy(topic_name_, other.topic_name_, sizeof(topic_name_));
524 initialized_ = true;
525 other.initialized_ = false;
526 }
527 }
528 return *this;
529 }
530
533 Publisher() : storage_(), topic_name_{}, initialized_(false) {}
534
535 // ====================================================================
536 // Status events
537 // ====================================================================
538
546 Result on_liveliness_lost(nros_cpp_publisher_count_cb_t cb, void* user_context = nullptr) {
547 if (!initialized_) return Result(::rclcpp::ErrorCode::NotInitialized);
548 return Result(nros_cpp_publisher_set_liveliness_lost(storage_, cb, user_context));
549 }
550
556 Result on_offered_deadline_missed(uint32_t deadline_ms, nros_cpp_publisher_count_cb_t cb,
557 void* user_context = nullptr) {
558 if (!initialized_) return Result(::rclcpp::ErrorCode::NotInitialized);
559 return Result(nros_cpp_publisher_set_offered_deadline_missed(storage_, deadline_ms, cb,
560 user_context));
561 }
562
573 Result on_matched(PublisherMatchedCallbackType cb, void* user_context = nullptr) {
574 if (!initialized_) return Result(::rclcpp::ErrorCode::NotInitialized);
575 return Result(nros_cpp_publisher_set_matched(storage_, cb, user_context));
576 }
577
581 Result on_incompatible_type(IncompatibleTypeCallbackType cb, void* user_context = nullptr) {
582 if (!initialized_) return Result(::rclcpp::ErrorCode::NotInitialized);
583 return Result(nros_cpp_publisher_set_incompatible_type(storage_, cb, user_context));
584 }
585
597 if (!initialized_) return Result(::rclcpp::ErrorCode::NotInitialized);
598 return Result(nros_cpp_publisher_assert_liveliness(storage_));
599 }
600
626 Result get_gid(uint8_t (&out_gid)[GID_SIZE]) const {
627 if (!initialized_) return Result(::rclcpp::ErrorCode::NotInitialized);
628 return Result(nros_cpp_publisher_get_gid(storage_, out_gid, GID_SIZE));
629 }
630
631 private:
632 Publisher(const Publisher&) = delete;
633 Publisher& operator=(const Publisher&) = delete;
634
635 friend class ::rclcpp::Node;
636
637 // The handle plus the monitor cell pointer and the node's lifecycle gate
638 // the runtime stores beside it (`NROS_CPP_PUBLISHER_STORAGE_SIZE`, whose
639 // other half is `CppPublisher`'s compile-time assert in publisher.rs).
640 alignas(8) uint8_t storage_[NROS_CPP_PUBLISHER_STORAGE_SIZE];
641 char topic_name_[::rclcpp::PUBLISHER_TOPIC_NAME_MAX];
642 bool initialized_;
643};
644
645} // namespace rclcpp
646
647// Out-of-line definition of Node::create_publisher<M>().
648// Placed here so consumers only pay for this template when they actually
649// use publishers — including `rclcpp/node.hpp` alone no longer drags in
650// every entity's code path.
651#include "rclcpp/node.hpp"
652
653namespace rclcpp {} // namespace rclcpp
654
655namespace rclcpp {
656template <typename M>
657Result Node::create_publisher(Publisher<M>& out, const char* topic, const ::rclcpp::QoS& qos) {
658 // One image, one backend, one encoding. Compile-time, so a
659 // message the linked backend cannot encode never reaches the wire.
661 if (!initialized_) return Result(::rclcpp::ErrorCode::NotInitialized);
663 nros_cpp_ret_t ret = nros_cpp_publisher_create(&handle_, topic, M::TYPE_NAME, M::TYPE_HASH,
664 ffi_qos, out.storage_);
665 if (ret == 0) {
666 // Topic name lives C++-side; copy + null-terminate into the
667 // fixed-size buffer. Truncation is silent.
668 ::rclcpp::detail::assign_entity_name(out.topic_name_, topic);
669 out.initialized_ = true;
670 }
671 return Result(ret);
672}
673} // namespace rclcpp
674
675namespace rclcpp {
676
682} // namespace rclcpp
683
684namespace rclcpp {
685template <typename M>
686Result Node::create_publisher(Publisher<M>& out, const char* topic, const ::rclcpp::QoS& qos,
687 const ::rclcpp::PublisherOptions& options) {
688 (void)options; // reserved — no live fields today
689 return create_publisher<M>(out, topic, qos);
690}
691} // namespace rclcpp
692
693namespace rclcpp {
694
704template <typename M>
706 const QoS& qos = QoS::default_profile()) {
707 Publisher<M> p;
708 Result r = node.create_publisher<M>(p, topic, qos);
709 if (!r.ok()) return ResultOf<Publisher<M>>::error(r);
710 return ResultOf<Publisher<M>>::ok(::rclcpp::tr::forward_rvalue(p));
711}
712
713} // namespace rclcpp
714
715#endif // NROS_RCLCPP_PUBLISHER_HPP
Definition executor.hpp:119
Result count_subscribers(const char *topic_name, size_t *out_count)
Definition executor.hpp:418
Definition node.hpp:874
typename::rclcpp::Publisher< M >::SharedPtr create_publisher(const char *topic, const ::rclcpp::QoS &qos=::rclcpp::QoS::default_profile())
create_publisher<M>(topic, qos) — available on every target.
Definition publisher.hpp:327
~Loan()
Definition publisher.hpp:348
size_t capacity() const
Definition publisher.hpp:353
const uint8_t * data() const
Definition publisher.hpp:352
Loan(void *pub, uint8_t *buf, size_t cap, void *token)
Definition publisher.hpp:381
Loan(const Loan &)=delete
Result discard()
Abandon without sending. Consumes the loan.
Definition publisher.hpp:369
uint8_t * data()
Writable view of the loaned bytes.
Definition publisher.hpp:351
bool is_valid() const
Definition publisher.hpp:355
Loan(Loan &&o)
Definition publisher.hpp:330
Loan & operator=(Loan &&o)
Definition publisher.hpp:334
Loan & operator=(const Loan &)=delete
Result commit(size_t actual_len)
Send actual_len bytes. Consumes the loan.
Definition publisher.hpp:358
Loan()
Definition publisher.hpp:329
Definition publisher.hpp:179
Result assert_liveliness()
Definition publisher.hpp:596
~Publisher()
Destructor — releases publisher resources.
Definition publisher.hpp:498
::rclcpp::Owned< Publisher< M > > UniquePtr
Definition publisher.hpp:218
::rclcpp::QoS get_actual_qos() const
Definition publisher.hpp:439
Result publish_streamed(size_t total_len, W &&writer)
Definition publisher.hpp:302
Result get_gid(uint8_t(&out_gid)[GID_SIZE]) const
Definition publisher.hpp:626
const char * get_topic_name() const
Get the topic name.
Definition publisher.hpp:418
::rclcpp::ResultOf< Loan > loan(size_t requested_len)
Definition publisher.hpp:406
Result on_matched(PublisherMatchedCallbackType cb, void *user_context=nullptr)
Definition publisher.hpp:573
Result publish_serialized(const uint8_t *data, size_t len)
Definition publisher.hpp:283
Publisher & operator=(Publisher &&other)
Definition publisher.hpp:515
bool is_valid() const
Check if the publisher is initialized and valid.
Definition publisher.hpp:495
Result get_subscription_count(::rclcpp::Executor &executor, size_t *out_count) const
Definition publisher.hpp:489
Result publish_raw(const uint8_t *data, size_t len)
Renamed to publish_serialized; kept one release.
Definition publisher.hpp:290
Result publish(const M &msg)
Definition publisher.hpp:271
Publisher()
Definition publisher.hpp:533
Publisher(Publisher &&other)
Definition publisher.hpp:507
Result on_liveliness_lost(nros_cpp_publisher_count_cb_t cb, void *user_context=nullptr)
Definition publisher.hpp:546
Result on_incompatible_type(IncompatibleTypeCallbackType cb, void *user_context=nullptr)
Definition publisher.hpp:581
Result on_offered_deadline_missed(uint32_t deadline_ms, nros_cpp_publisher_count_cb_t cb, void *user_context=nullptr)
Definition publisher.hpp:556
static constexpr size_t GID_SIZE
Definition publisher.hpp:224
::rclcpp::Owned< Publisher< M > > SharedPtr
Definition publisher.hpp:203
bool is_durability_transient_local() const
Definition publisher.hpp:457
::rclcpp::Owned< Publisher< M > > ConstSharedPtr
Definition publisher.hpp:211
Definition qos.hpp:276
static constexpr QoS default_profile()
Default profile: RELIABLE + VOLATILE + KEEP_LAST(10).
Definition qos.hpp:799
int32_t raw() const
Get the raw integer code (for FFI interop).
Definition result.hpp:236
bool ok() const
Returns true if the operation succeeded.
Definition result.hpp:227
static constexpr ResultOf success()
Named constructors.
Definition result.hpp:239
Definition result.hpp:332
Inline storage-size macros for opaque entity buffers.
#define NROS_CPP_PUBLISHER_STORAGE_SIZE
Definition config.hpp:28
rclcpp::Executor — drives transport I/O and dispatches callbacks.
int nros_cpp_ret_t
Definition future.hpp:25
Definition rclcpp.hpp:437
constexpr nros_cpp_qos_t qos_to_ffi(const QoS &qos)
Definition qos.hpp:719
Definition rclcpp.hpp:75
static constexpr size_t PUBLISHER_TOPIC_NAME_MAX
Definition publisher.hpp:66
bool ok()
Definition node.hpp:3641
ResultOf< Publisher< M > > create_publisher(::rclcpp::Node &node, const char *topic, const QoS &qos=QoS::default_profile())
Definition publisher.hpp:705
@ InvalidArgument
Null pointer, empty topic name, or out-of-range value.
Definition result.hpp:122
@ NotInitialized
Definition result.hpp:131
@ TransientLocal
Definition qos.hpp:165
ResultOf< void > Result
Definition result.hpp:247
rclcpp::Node and global session helpers.
rclcpp::QoS — full DDS-shaped QoS settings.
rclcpp::Result, rclcpp::ErrorCode, and the RCLCPP_TRY macro.
#define NROS_CPP_DEPRECATED_MSG(msg)
Definition result.hpp:101
rclcpp::format_of<M> — a message type's serialization format; rclcpp::linked_format() — the linked ba...
#define NROS_CPP_ASSERT_MESSAGE_FORMAT(M)
Definition serialization_format.hpp:98
Definition qos.hpp:84