Skip to main content

nros_rmw/
custom_transport.rs

1//! Runtime-pluggable custom transport vtable.
2//!
3//! Defines the platform-side hook that lets users plug a custom
4//! transport (USB-CDC, BLE, RS-485, semihosting bridge, ring-buffer
5//! loopback) at runtime without changing board crate, Cargo features,
6//! or rebuilding.
7//!
8//! The shape mirrors micro-ROS's
9//! `rmw_uros_set_custom_transport(framing, params, open, close, write, read)`
10//! and the C ABI exposed by `nros-c` / `nros-cpp` as
11//! `nros_transport_ops_t`.
12//!
13//! ## Why a fn-pointer vtable, not a Rust trait
14//!
15//! 1. **alloc-free.** A `Box<dyn CustomTransport>` would force the
16//!    `alloc` crate on every no_std backend that wants to use the
17//!    runtime hook. nano-ros's bare-metal / FreeRTOS / NuttX /
18//!    ThreadX targets ship without a global allocator on the default
19//!    feature flags, so `dyn` is a non-starter.
20//! 2. **C ABI parity.** The user-facing surface is `nros_transport_ops_t`
21//!    (a `#[repr(C)]` struct of fn pointers + a `void *`). A
22//!    Rust-side fn-ptr vtable means the `set_custom_transport` C
23//!    entry just memcpys the incoming struct into the static — no
24//!    glue, no shims, no trampolines.
25//! 3. **Matches XRCE's existing shape.** `uxr_set_custom_transport_callbacks`
26//!    already takes 4 raw fn pointers; the Rust wrapper at
27//!    `nros-rmw-xrce::init_transport` likewise. A trait would just
28//!    be an extra layer that has to be type-erased into fn pointers
29//!    anyway.
30//!
31//! ## Threading contract (v1)
32//!
33//! - `read` and `write` may NOT be called concurrently from
34//!   different threads. The active backend serialises them through
35//!   the `drive_io` / spin-once path. Custom transports written
36//!   against this contract can use a single-buffer state machine
37//!   without internal locking.
38//! - Callbacks must NOT be invoked from interrupt context. Wrap
39//!   ISR-driven hardware in a queue + `read` poller.
40//! - `user_data` is opaque to the runtime — its `Send` / `Sync`
41//!   discipline is the caller's responsibility. The vtable struct
42//!   itself is `Send + Sync` because the four fn pointers always
43//!   are.
44
45use core::ffi::c_void;
46
47use crate::sync::Mutex;
48
49/// Current ABI version of [`NrosTransportOps`].
50///
51/// Embedded as the first field of the struct (see § *Versioning*
52/// below). Consumers fill in this exact value before passing the
53/// struct to [`set_custom_transport`]; runtime entry points reject
54/// any other value with [`crate::TransportError::IncompatibleAbi`]
55/// (or `NROS_RMW_RET_INCOMPATIBLE_ABI` at the C boundary).
56///
57/// The version bumps under two rules (per the portable-ABI design
58/// note R5 in `docs/design/0006-portable-rmw-platform-interface.md`):
59///
60/// - **Major** (e.g. `V1` → `V2`): existing fields removed or
61///   reordered. Old consumers fail cleanly via the version check.
62/// - **Minor** (e.g. struct gains an appended fn pointer): version
63///   stays the same. New consumers detect the new fn via the size
64///   of the trailing `_reserved` region. Today there is none — v1 is
65///   the inaugural version.
66pub const NROS_TRANSPORT_OPS_ABI_VERSION_V1: u32 = 1;
67
68/// Runtime-pluggable custom transport. Caller fills in
69/// the four fn pointers, hands the struct to [`set_custom_transport`],
70/// and the active backend treats it as the read / write surface for
71/// every wire frame.
72///
73/// `#[repr(C)]` so this is the SAME struct that
74/// `nros_transport_ops_t` (C) and `nros::TransportOps` (C++) point at
75/// — single layout, no parallel definitions to drift.
76///
77/// # Return-code conventions
78///
79/// `open` / `write` return `NROS_RMW_RET_OK` (== 0) on success and
80/// a negative `rcl_ret_t` (see `nros-rmw-cffi`) on failure. `read`
81/// returns the non-negative byte count on success or a negative
82/// `rcl_ret_t` on error / timeout.
83///
84/// # Safety contract for the four fn pointers
85///
86/// - All callbacks receive `user_data` as their first argument. The
87///   pointer is whatever the caller stored at registration time; the
88///   runtime never dereferences it.
89/// - `buf` / `len` describe a contiguous byte region the callback
90///   may read (`write`) or write (`read`). The callback must NOT
91///   retain pointers across the call.
92/// - `params` (in `open`) is opaque per-transport metadata
93///   threaded through from `set_custom_transport`. May be `NULL`.
94#[repr(C)]
95#[derive(Copy, Clone)]
96pub struct NrosTransportOps {
97    /// ABI version. Consumers MUST fill in
98    /// [`NROS_TRANSPORT_OPS_ABI_VERSION_V1`]; mismatched values are
99    /// rejected at registration time with
100    /// `TransportError::IncompatibleAbi` (`NROS_RMW_RET_INCOMPATIBLE_ABI`
101    /// at the C boundary). Reserved for future minor-version
102    /// detection — see the const's doc-comment.
103    pub abi_version: u32,
104    /// Reserved padding to keep the struct
105    /// alignment-stable across appends. Must be zero.
106    pub _reserved: u32,
107    /// Opaque caller context, threaded back into every callback as
108    /// the first argument. Lifetime: must outlive the transport's
109    /// active period (i.e. until `close` returns).
110    pub user_data: *mut c_void,
111    /// Open the underlying medium. `params` is opaque per-transport
112    /// metadata (e.g. UART baud rate, USB-CDC endpoint id) supplied
113    /// at registration time.
114    pub open: unsafe extern "C" fn(user_data: *mut c_void, params: *const c_void) -> i32,
115    /// Tear the transport down. Complement of `open`. After `close`
116    /// returns, the runtime will not invoke `read` or `write` on this
117    /// transport unless `set_custom_transport` is called again.
118    pub close: unsafe extern "C" fn(user_data: *mut c_void),
119    /// Send `len` bytes from `buf`. Returns 0 on success, negative
120    /// `rcl_ret_t` on failure. Must NOT block beyond a brief
121    /// hardware retry; long blocking should surface as
122    /// `NROS_RMW_RET_TIMEOUT` (-2).
123    pub write: unsafe extern "C" fn(user_data: *mut c_void, buf: *const u8, len: usize) -> i32,
124    /// Receive up to `len` bytes into `buf` within `timeout_ms`.
125    /// Returns the non-negative byte count on success (may be less
126    /// than `len`), or a negative `rcl_ret_t` on error / timeout.
127    pub read: unsafe extern "C" fn(
128        user_data: *mut c_void,
129        buf: *mut u8,
130        len: usize,
131        timeout_ms: u32,
132    ) -> i32,
133}
134
135// SAFETY: the struct is just four fn pointers + a *mut. Send / Sync
136// are sound because (a) fn pointers are always Send+Sync, and (b) the
137// caller owns synchronisation of `user_data` per the threading contract
138// (no concurrent read/write, no ISR invocation). Cross-thread
139// observability of the registered struct is guarded by the surrounding
140// Mutex, not by any property of this struct.
141unsafe impl Send for NrosTransportOps {}
142unsafe impl Sync for NrosTransportOps {}
143
144/// Phase 115.A — single-slot storage for the registered transport.
145///
146/// `set_custom_transport` writes the struct in; backends read it via
147/// [`take_custom_transport`] (during `Rmw::open`) or
148/// [`peek_custom_transport`] (during steady-state for liveliness /
149/// reconnect logic). One transport per process; a second
150/// `set_custom_transport` call before `take` overwrites the slot
151/// (documented as "register early, register once").
152static SLOT: Mutex<Option<NrosTransportOps>> = Mutex::new(None);
153
154/// Register a custom transport vtable. Must be called
155/// **before** the first `Rmw::open` (or
156/// `rclc_support_init` from the C surface). v1 leaves enforcement of
157/// "before init" to backend code, and NO backend enforces it: a call
158/// after `Rmw::open` is implementation-defined, which is also what the
159/// C entry point `rclc_set_custom_transport` documents. This line
160/// used to say backends "reject re-registration with
161/// ALREADY_INIT" — `rmw_ret.h` defines no such code,
162/// so the sentence promised both a behaviour and a
163/// constant that do not exist.
164///
165/// Pass `None` to clear a previously-registered vtable (e.g. for
166/// teardown in tests).
167///
168/// Returns `Err(TransportError::IncompatibleAbi)` when `ops.is_some()`
169/// but `abi_version != NROS_TRANSPORT_OPS_ABI_VERSION_V1`. C / C++
170/// wrappers map this to `NROS_RMW_RET_INCOMPATIBLE_ABI`.
171///
172/// # Safety
173///
174/// The four fn pointers in `ops` must follow the threading contract
175/// documented on [`NrosTransportOps`] — no concurrent read/write, no
176/// ISR invocation, `user_data` outlives the transport's active period.
177pub unsafe fn set_custom_transport(
178    ops: Option<NrosTransportOps>,
179) -> Result<(), crate::TransportError> {
180    if let Some(o) = ops.as_ref()
181        && o.abi_version != NROS_TRANSPORT_OPS_ABI_VERSION_V1
182    {
183        return Err(crate::TransportError::IncompatibleAbi);
184    }
185    SLOT.with(|slot| *slot = ops);
186    Ok(())
187}
188
189/// Peek at the currently-registered transport without
190/// consuming it. Used by backends that need to re-attach on session
191/// reconnect, or by tests that want to verify a registration landed.
192/// Returns `None` if nothing was registered.
193pub fn peek_custom_transport() -> Option<NrosTransportOps> {
194    SLOT.with(|slot| *slot)
195}
196
197/// Drain the registered transport. Returns the
198/// previously-registered vtable (`None` if nothing was registered)
199/// and clears the slot. Backends call this from `Rmw::open` when
200/// `platform-custom` is the active platform; the vtable then lives
201/// inside the session for the rest of the process lifetime.
202pub fn take_custom_transport() -> Option<NrosTransportOps> {
203    SLOT.with(|slot| slot.take())
204}
205
206#[cfg(test)]
207mod tests {
208    use super::*;
209
210    unsafe extern "C" fn stub_open(_ud: *mut c_void, _params: *const c_void) -> i32 {
211        0
212    }
213    unsafe extern "C" fn stub_close(_ud: *mut c_void) {}
214    unsafe extern "C" fn stub_write(_ud: *mut c_void, _buf: *const u8, _len: usize) -> i32 {
215        0
216    }
217    unsafe extern "C" fn stub_read(
218        _ud: *mut c_void,
219        _buf: *mut u8,
220        _len: usize,
221        _timeout_ms: u32,
222    ) -> i32 {
223        0
224    }
225
226    fn make_ops() -> NrosTransportOps {
227        NrosTransportOps {
228            abi_version: NROS_TRANSPORT_OPS_ABI_VERSION_V1,
229            _reserved: 0,
230            user_data: core::ptr::null_mut(),
231            open: stub_open,
232            close: stub_close,
233            write: stub_write,
234            read: stub_read,
235        }
236    }
237
238    /// Lifecycle: register, peek, take, peek-after-take.
239    #[test]
240    fn lifecycle() {
241        // Drain anything a previous test left behind so this test
242        // is order-independent under shared SLOT.
243        let _ = take_custom_transport();
244
245        assert!(peek_custom_transport().is_none());
246
247        unsafe {
248            set_custom_transport(Some(make_ops())).expect("set");
249        }
250
251        let peeked = peek_custom_transport().expect("peek after set");
252        assert!(peeked.user_data.is_null());
253        assert_eq!(peeked.abi_version, NROS_TRANSPORT_OPS_ABI_VERSION_V1);
254
255        // Peek again — slot still occupied.
256        assert!(peek_custom_transport().is_some());
257
258        let taken = take_custom_transport().expect("take");
259        assert!(taken.user_data.is_null());
260
261        // Slot is now empty.
262        assert!(peek_custom_transport().is_none());
263        assert!(take_custom_transport().is_none());
264    }
265
266    /// `set_custom_transport(None)` clears the slot.
267    #[test]
268    fn explicit_clear() {
269        let _ = take_custom_transport();
270        unsafe {
271            set_custom_transport(Some(make_ops())).expect("set");
272            set_custom_transport(None).expect("clear");
273        }
274        assert!(peek_custom_transport().is_none());
275    }
276
277    /// Phase 115.A.2 — abi_version mismatch is rejected with
278    /// `TransportError::IncompatibleAbi`. Slot stays whatever it was
279    /// before the bad call.
280    #[test]
281    fn rejects_unknown_abi_version() {
282        let _ = take_custom_transport();
283        let mut ops = make_ops();
284        ops.abi_version = 0xBAD0_BAD0; // not V1.
285        let err = unsafe { set_custom_transport(Some(ops)) };
286        assert!(matches!(err, Err(crate::TransportError::IncompatibleAbi)));
287        // Bad call did NOT install — slot stays empty.
288        assert!(peek_custom_transport().is_none());
289    }
290
291    /// Struct stays `Copy + Send + Sync` — the static-slot pattern
292    /// relies on these bounds at compile time.
293    #[test]
294    fn ops_is_copy_send_sync() {
295        fn assert_copy_send_sync<T: Copy + Send + Sync>() {}
296        assert_copy_send_sync::<NrosTransportOps>();
297    }
298}