Skip to main content

rtcm3_ffi/
lib.rs

1//! C FFI bindings for the `rtcm3` RTCM3 GNSS RTK correction decoder.
2//!
3//! Exposes a decode-only subset of `rtcm3`'s API: decode a single frame
4//! from a raw byte buffer into an opaque message handle, then read its
5//! fields via an `rtcm3_message_as_<type>` function that fills a plain C
6//! struct - one call per message type, matching `mavwire-ffi`'s shape.
7//! See `include/rtcm3.h` for the generated C declarations.
8//!
9//! This crate is a plain (non-`no_std`) library: it targets host
10//! environments linking a shared or static C library, not the embedded
11//! `no_alloc` use case `rtcm3` itself supports. Embedded consumers should
12//! use the `rtcm3` Rust crate directly.
13
14use std::ffi::c_char;
15use std::ptr;
16
17use rtcm3::Rtcm3Message;
18use rtcm3::message::{CellData, GlonassBias, GpsMsm7, SatelliteData, StationArp};
19
20/// Largest number of satellites a single MSM message can describe (the
21/// satellite mask is 64 bits wide, per the RTCM3 wire format itself).
22pub const RTCM3_FFI_MAX_SATELLITES: usize = 64;
23/// Largest number of satellite/signal cells a single MSM message can
24/// describe (the cell mask is 64 bits wide, per the RTCM3 wire format
25/// itself).
26pub const RTCM3_FFI_MAX_CELLS: usize = 64;
27
28/// Opaque handle to a decoded RTCM3 message, owned by the caller until
29/// freed with [`rtcm3_message_free`].
30pub struct Rtcm3FfiMessage {
31    message: Rtcm3Message,
32}
33
34/// Error codes returned by [`rtcm3_decode`].
35#[repr(u8)]
36#[derive(Debug, Clone, Copy, PartialEq, Eq)]
37pub enum Rtcm3FfiError {
38    /// No error.
39    Ok = 0,
40    /// The `buf` pointer was NULL.
41    NullInput = 1,
42    /// The frame itself was malformed (bad preamble, wrong length, bad
43    /// CRC-24Q).
44    Frame = 2,
45    /// A bit-level read failed while decoding the message.
46    Bit = 3,
47    /// The message type is unknown/undecoded.
48    Message = 4,
49}
50
51impl From<rtcm3::Rtcm3Error> for Rtcm3FfiError {
52    fn from(e: rtcm3::Rtcm3Error) -> Self {
53        match e {
54            rtcm3::Rtcm3Error::Frame(_) => Self::Frame,
55            rtcm3::Rtcm3Error::Bit(_) => Self::Bit,
56            // covers Message(_) and any future non_exhaustive variant
57            _ => Self::Message,
58        }
59    }
60}
61
62/// Decodes a single RTCM3 frame from the start of `buf` (`len` bytes
63/// long). `buf` may contain trailing bytes after the frame (e.g. the
64/// start of the next frame in a stream); only the leading frame is
65/// parsed.
66///
67/// On success, returns a non-NULL handle (free it with
68/// [`rtcm3_message_free`] when done) and, if `out_error` is non-NULL,
69/// writes [`Rtcm3FfiError::Ok`] through it. On failure, returns NULL and,
70/// if `out_error` is non-NULL, writes the reason through it.
71///
72/// # Safety
73/// `buf` must be NULL or valid for reads of `len` bytes. `out_error` must
74/// be NULL or a pointer valid for a single write.
75#[unsafe(no_mangle)]
76pub unsafe extern "C" fn rtcm3_decode(
77    buf: *const u8,
78    len: usize,
79    out_error: *mut Rtcm3FfiError,
80) -> *mut Rtcm3FfiMessage {
81    let set_error = |code: Rtcm3FfiError| {
82        if !out_error.is_null() {
83            // SAFETY: caller guarantees `out_error` is a valid write target or NULL.
84            unsafe {
85                out_error.write(code);
86            }
87        }
88    };
89
90    if buf.is_null() {
91        set_error(Rtcm3FfiError::NullInput);
92        return ptr::null_mut();
93    }
94
95    // SAFETY: caller guarantees `buf` is valid for reads of `len` bytes.
96    let bytes = unsafe { core::slice::from_raw_parts(buf, len) };
97
98    match rtcm3::decode(bytes) {
99        Ok(message) => {
100            set_error(Rtcm3FfiError::Ok);
101            Box::into_raw(Box::new(Rtcm3FfiMessage { message }))
102        }
103        Err(e) => {
104            set_error(Rtcm3FfiError::from(e));
105            ptr::null_mut()
106        }
107    }
108}
109
110/// Frees a message handle returned by [`rtcm3_decode`]. Passing NULL is a
111/// no-op.
112///
113/// # Safety
114/// `msg` must be NULL or a pointer previously returned by [`rtcm3_decode`]
115/// that has not already been freed.
116#[unsafe(no_mangle)]
117pub unsafe extern "C" fn rtcm3_message_free(msg: *mut Rtcm3FfiMessage) {
118    if !msg.is_null() {
119        // SAFETY: caller guarantees `msg` is a live handle from `rtcm3_decode`.
120        drop(unsafe { Box::from_raw(msg) });
121    }
122}
123
124/// The message's RTCM3 message type (DF002, e.g. `1005` for a Stationary
125/// RTK Reference Station ARP), or `0xFFFF` for a NULL handle or a variant
126/// this header doesn't know about yet.
127///
128/// # Safety
129/// `msg` must be NULL or a valid, non-freed handle from [`rtcm3_decode`].
130#[unsafe(no_mangle)]
131pub unsafe extern "C" fn rtcm3_message_type(msg: *const Rtcm3FfiMessage) -> u16 {
132    // SAFETY: caller guarantees `msg` is a valid handle or NULL.
133    match unsafe { msg.as_ref() } {
134        Some(m) => match m.message {
135            Rtcm3Message::StationArp(_) => 1005,
136            Rtcm3Message::GlonassBias(_) => 1230,
137            Rtcm3Message::GpsMsm7(_) => 1077,
138            _ => 0xFFFF,
139        },
140        None => 0xFFFF,
141    }
142}
143
144/// Stationary RTK Reference Station ARP (type 1005): the base station's
145/// antenna reference point position.
146#[repr(C)]
147#[derive(Debug, Clone, Copy)]
148pub struct Rtcm3StationArp {
149    /// Reference station ID (DF003).
150    pub reference_station_id: u16,
151    /// ITRF realization year (DF021).
152    pub itrf_realization_year: u8,
153    /// Whether GPS observations are included in this station's stream (DF022).
154    pub gps_indicator: bool,
155    /// Whether GLONASS observations are included (DF023).
156    pub glonass_indicator: bool,
157    /// Whether Galileo observations are included (DF024).
158    pub galileo_indicator: bool,
159    /// Reference-station indicator (DF141).
160    pub reference_station_indicator: bool,
161    /// Antenna reference point ECEF X, raw units of 0.0001m (DF025).
162    pub ecef_x_raw: i64,
163    /// Single-receiver oscillator indicator (DF142).
164    pub single_oscillator_indicator: bool,
165    /// Antenna reference point ECEF Y, raw units of 0.0001m (DF026).
166    pub ecef_y_raw: i64,
167    /// Quarter-cycle phase shift indicator (DF364).
168    pub quarter_cycle_indicator: u8,
169    /// Antenna reference point ECEF Z, raw units of 0.0001m (DF027).
170    pub ecef_z_raw: i64,
171}
172
173impl From<StationArp> for Rtcm3StationArp {
174    fn from(m: StationArp) -> Self {
175        Self {
176            reference_station_id: m.reference_station_id,
177            itrf_realization_year: m.itrf_realization_year,
178            gps_indicator: m.gps_indicator,
179            glonass_indicator: m.glonass_indicator,
180            galileo_indicator: m.galileo_indicator,
181            reference_station_indicator: m.reference_station_indicator,
182            ecef_x_raw: m.ecef_x_raw,
183            single_oscillator_indicator: m.single_oscillator_indicator,
184            ecef_y_raw: m.ecef_y_raw,
185            quarter_cycle_indicator: m.quarter_cycle_indicator,
186            ecef_z_raw: m.ecef_z_raw,
187        }
188    }
189}
190
191/// GLONASS Code-Phase Biases (type 1230). Each bias field is only
192/// meaningful when its `_present` flag is `true` - the underlying signal
193/// wasn't present in the station's stream otherwise, and `_raw` reads `0`.
194#[repr(C)]
195#[derive(Debug, Clone, Copy)]
196pub struct Rtcm3GlonassBias {
197    /// Reference station ID (DF003).
198    pub reference_station_id: u16,
199    /// GLONASS code-phase bias indicator (DF421).
200    pub code_phase_bias_indicator: bool,
201    /// Whether the L1 C/A bias field is present (DF423).
202    pub l1_ca_bias_present: bool,
203    /// L1 C/A code-phase bias, raw units of 0.02m, if present.
204    pub l1_ca_bias_raw: i32,
205    /// Whether the L1 P bias field is present (DF424).
206    pub l1_p_bias_present: bool,
207    /// L1 P code-phase bias, raw units of 0.02m, if present.
208    pub l1_p_bias_raw: i32,
209    /// Whether the L2 C/A bias field is present (DF425).
210    pub l2_ca_bias_present: bool,
211    /// L2 C/A code-phase bias, raw units of 0.02m, if present.
212    pub l2_ca_bias_raw: i32,
213    /// Whether the L2 P bias field is present (DF426).
214    pub l2_p_bias_present: bool,
215    /// L2 P code-phase bias, raw units of 0.02m, if present.
216    pub l2_p_bias_raw: i32,
217}
218
219impl From<GlonassBias> for Rtcm3GlonassBias {
220    fn from(m: GlonassBias) -> Self {
221        Self {
222            reference_station_id: m.reference_station_id,
223            code_phase_bias_indicator: m.code_phase_bias_indicator,
224            l1_ca_bias_present: m.l1_ca_bias_raw.is_some(),
225            l1_ca_bias_raw: m.l1_ca_bias_raw.unwrap_or(0),
226            l1_p_bias_present: m.l1_p_bias_raw.is_some(),
227            l1_p_bias_raw: m.l1_p_bias_raw.unwrap_or(0),
228            l2_ca_bias_present: m.l2_ca_bias_raw.is_some(),
229            l2_ca_bias_raw: m.l2_ca_bias_raw.unwrap_or(0),
230            l2_p_bias_present: m.l2_p_bias_raw.is_some(),
231            l2_p_bias_raw: m.l2_p_bias_raw.unwrap_or(0),
232        }
233    }
234}
235
236/// One satellite's data block within a [`Rtcm3GpsMsm7`] message.
237#[repr(C)]
238#[derive(Debug, Clone, Copy)]
239pub struct Rtcm3SatelliteData {
240    /// Integer milliseconds in the satellite's rough range (DF397).
241    pub rough_range_ms_raw: u8,
242    /// Extended satellite information (DF419).
243    pub extended_info_raw: u8,
244    /// Rough range modulo 1 millisecond, raw units of 2^-10 ms (DF398).
245    pub rough_range_mod_raw: u16,
246    /// Rough phase range rate, m/s (DF399).
247    pub rough_phase_range_rate_raw: i16,
248}
249
250impl From<SatelliteData> for Rtcm3SatelliteData {
251    fn from(s: SatelliteData) -> Self {
252        Self {
253            rough_range_ms_raw: s.rough_range_ms_raw,
254            extended_info_raw: s.extended_info_raw,
255            rough_range_mod_raw: s.rough_range_mod_raw,
256            rough_phase_range_rate_raw: s.rough_phase_range_rate_raw,
257        }
258    }
259}
260
261/// One satellite/signal cell's data block within a [`Rtcm3GpsMsm7`]
262/// message.
263#[repr(C)]
264#[derive(Debug, Clone, Copy)]
265pub struct Rtcm3CellData {
266    /// Fine pseudorange, raw units of 2^-29 ms (DF405).
267    pub fine_pseudorange_raw: i32,
268    /// Fine phase range, raw units of 2^-31 ms (DF406).
269    pub fine_phase_range_raw: i32,
270    /// Phase range lock time indicator, extended range/resolution (DF407).
271    pub lock_time_raw: u16,
272    /// Half-cycle ambiguity indicator (DF420).
273    pub half_cycle_ambiguity: bool,
274    /// Carrier-to-noise ratio, raw units of 2^-4 dB-Hz (DF408).
275    pub cnr_raw: u16,
276    /// Fine phase range rate, raw units of 0.0001 m/s (DF404).
277    pub fine_phase_range_rate_raw: i16,
278}
279
280impl From<CellData> for Rtcm3CellData {
281    fn from(c: CellData) -> Self {
282        Self {
283            fine_pseudorange_raw: c.fine_pseudorange_raw,
284            fine_phase_range_raw: c.fine_phase_range_raw,
285            lock_time_raw: c.lock_time_raw,
286            half_cycle_ambiguity: c.half_cycle_ambiguity,
287            cnr_raw: c.cnr_raw,
288            fine_phase_range_rate_raw: c.fine_phase_range_rate_raw,
289        }
290    }
291}
292
293/// GPS Full Pseudoranges and `PhaseRanges` plus CNR, high resolution
294/// (type 1077). `num_satellites`/`num_signals`/`num_cells` say how many
295/// entries of `satellites`/`cells` are meaningful; the rest are unused
296/// padding, matching the core crate's own mask-derived counts.
297#[repr(C)]
298#[derive(Debug, Clone, Copy)]
299pub struct Rtcm3GpsMsm7 {
300    /// Reference station ID (DF003).
301    pub reference_station_id: u16,
302    /// GPS epoch time (time of week), raw milliseconds (DF004).
303    pub gps_epoch_time_tow_ms: u32,
304    /// Multiple message bit: more MSM messages follow for this epoch (DF393).
305    pub multiple_message_bit: bool,
306    /// Issue of data station (DF409).
307    pub issue_of_data_station: u8,
308    /// Clock steering indicator (DF411).
309    pub clock_steering_indicator: u8,
310    /// External clock indicator (DF412).
311    pub external_clock_indicator: u8,
312    /// GNSS divergence-free smoothing indicator (DF417).
313    pub smoothing_indicator: bool,
314    /// GNSS smoothing interval, raw encoding (DF418).
315    pub smoothing_interval_raw: u8,
316    /// Satellite mask (DF394).
317    pub satellite_mask: u64,
318    /// Signal mask (DF395).
319    pub signal_mask: u32,
320    /// Cell mask (DF396).
321    pub cell_mask: u64,
322    /// Number of satellites present (popcount of `satellite_mask`).
323    pub num_satellites: u32,
324    /// Number of signal types present (popcount of `signal_mask`).
325    pub num_signals: u32,
326    /// Number of satellite/signal cells present (popcount of `cell_mask`).
327    pub num_cells: u32,
328    /// Per-satellite data blocks, indexed in mask-bit order.
329    pub satellites: [Rtcm3SatelliteData; RTCM3_FFI_MAX_SATELLITES],
330    /// Per-cell data blocks, indexed in mask-bit order.
331    pub cells: [Rtcm3CellData; RTCM3_FFI_MAX_CELLS],
332}
333
334impl From<GpsMsm7> for Rtcm3GpsMsm7 {
335    fn from(m: GpsMsm7) -> Self {
336        Self {
337            reference_station_id: m.reference_station_id,
338            gps_epoch_time_tow_ms: m.gps_epoch_time_tow_ms,
339            multiple_message_bit: m.multiple_message_bit,
340            issue_of_data_station: m.issue_of_data_station,
341            clock_steering_indicator: m.clock_steering_indicator,
342            external_clock_indicator: m.external_clock_indicator,
343            smoothing_indicator: m.smoothing_indicator,
344            smoothing_interval_raw: m.smoothing_interval_raw,
345            satellite_mask: m.satellite_mask,
346            signal_mask: m.signal_mask,
347            cell_mask: m.cell_mask,
348            num_satellites: m.num_satellites(),
349            num_signals: m.num_signals(),
350            num_cells: m.num_cells(),
351            satellites: m.satellites.map(Into::into),
352            cells: m.cells.map(Into::into),
353        }
354    }
355}
356
357/// Reads `msg`'s message as a Stationary RTK Reference Station ARP
358/// (type 1005) into `out`, returning `true` on a match. Returns `false`
359/// without writing to `out` if `msg` is NULL or holds a different message
360/// type.
361///
362/// # Safety
363/// `msg` must be NULL or a valid, non-freed handle from [`rtcm3_decode`].
364/// `out` must be a valid write target.
365#[unsafe(no_mangle)]
366pub unsafe extern "C" fn rtcm3_message_as_station_arp(
367    msg: *const Rtcm3FfiMessage,
368    out: *mut Rtcm3StationArp,
369) -> bool {
370    // SAFETY: caller guarantees `msg` is a valid handle or NULL.
371    let Some(m) = (unsafe { msg.as_ref() }) else {
372        return false;
373    };
374    let Rtcm3Message::StationArp(inner) = m.message else {
375        return false;
376    };
377    // SAFETY: caller guarantees `out` is a valid write target.
378    unsafe {
379        out.write(inner.into());
380    }
381    true
382}
383
384/// Reads `msg`'s message as a GLONASS Code-Phase Biases message
385/// (type 1230) into `out`, returning `true` on a match. Returns `false`
386/// without writing to `out` if `msg` is NULL or holds a different message
387/// type.
388///
389/// # Safety
390/// `msg` must be NULL or a valid, non-freed handle from [`rtcm3_decode`].
391/// `out` must be a valid write target.
392#[unsafe(no_mangle)]
393pub unsafe extern "C" fn rtcm3_message_as_glonass_bias(
394    msg: *const Rtcm3FfiMessage,
395    out: *mut Rtcm3GlonassBias,
396) -> bool {
397    // SAFETY: caller guarantees `msg` is a valid handle or NULL.
398    let Some(m) = (unsafe { msg.as_ref() }) else {
399        return false;
400    };
401    let Rtcm3Message::GlonassBias(inner) = m.message else {
402        return false;
403    };
404    // SAFETY: caller guarantees `out` is a valid write target.
405    unsafe {
406        out.write(inner.into());
407    }
408    true
409}
410
411/// Reads `msg`'s message as a GPS MSM7 message (type 1077) into `out`,
412/// returning `true` on a match. Returns `false` without writing to `out`
413/// if `msg` is NULL or holds a different message type.
414///
415/// # Safety
416/// `msg` must be NULL or a valid, non-freed handle from [`rtcm3_decode`].
417/// `out` must be a valid write target.
418#[unsafe(no_mangle)]
419pub unsafe extern "C" fn rtcm3_message_as_gps_msm7(
420    msg: *const Rtcm3FfiMessage,
421    out: *mut Rtcm3GpsMsm7,
422) -> bool {
423    // SAFETY: caller guarantees `msg` is a valid handle or NULL.
424    let Some(m) = (unsafe { msg.as_ref() }) else {
425        return false;
426    };
427    let Rtcm3Message::GpsMsm7(inner) = m.message else {
428        return false;
429    };
430    // SAFETY: caller guarantees `out` is a valid write target.
431    unsafe {
432        out.write(inner.into());
433    }
434    true
435}
436
437/// This crate's version string, as a NUL-terminated C string with static
438/// lifetime.
439#[unsafe(no_mangle)]
440pub extern "C" fn rtcm3_version() -> *const c_char {
441    const VERSION: &str = concat!(env!("CARGO_PKG_VERSION"), "\0");
442    VERSION.as_ptr().cast::<c_char>()
443}