rtcm3-ffi 0.1.0

C FFI bindings for the rtcm3 RTCM3 GNSS RTK correction decoder
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
//! C FFI bindings for the `rtcm3` RTCM3 GNSS RTK correction decoder.
//!
//! Exposes a decode-only subset of `rtcm3`'s API: decode a single frame
//! from a raw byte buffer into an opaque message handle, then read its
//! fields via an `rtcm3_message_as_<type>` function that fills a plain C
//! struct - one call per message type, matching `mavwire-ffi`'s shape.
//! See `include/rtcm3.h` for the generated C declarations.
//!
//! This crate is a plain (non-`no_std`) library: it targets host
//! environments linking a shared or static C library, not the embedded
//! `no_alloc` use case `rtcm3` itself supports. Embedded consumers should
//! use the `rtcm3` Rust crate directly.

use std::ffi::c_char;
use std::ptr;

use rtcm3::Rtcm3Message;
use rtcm3::message::{CellData, GlonassBias, GpsMsm7, SatelliteData, StationArp};

/// Largest number of satellites a single MSM message can describe (the
/// satellite mask is 64 bits wide, per the RTCM3 wire format itself).
pub const RTCM3_FFI_MAX_SATELLITES: usize = 64;
/// Largest number of satellite/signal cells a single MSM message can
/// describe (the cell mask is 64 bits wide, per the RTCM3 wire format
/// itself).
pub const RTCM3_FFI_MAX_CELLS: usize = 64;

/// Opaque handle to a decoded RTCM3 message, owned by the caller until
/// freed with [`rtcm3_message_free`].
pub struct Rtcm3FfiMessage {
    message: Rtcm3Message,
}

/// Error codes returned by [`rtcm3_decode`].
#[repr(u8)]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Rtcm3FfiError {
    /// No error.
    Ok = 0,
    /// The `buf` pointer was NULL.
    NullInput = 1,
    /// The frame itself was malformed (bad preamble, wrong length, bad
    /// CRC-24Q).
    Frame = 2,
    /// A bit-level read failed while decoding the message.
    Bit = 3,
    /// The message type is unknown/undecoded.
    Message = 4,
}

impl From<rtcm3::Rtcm3Error> for Rtcm3FfiError {
    fn from(e: rtcm3::Rtcm3Error) -> Self {
        match e {
            rtcm3::Rtcm3Error::Frame(_) => Self::Frame,
            rtcm3::Rtcm3Error::Bit(_) => Self::Bit,
            // covers Message(_) and any future non_exhaustive variant
            _ => Self::Message,
        }
    }
}

/// Decodes a single RTCM3 frame from the start of `buf` (`len` bytes
/// long). `buf` may contain trailing bytes after the frame (e.g. the
/// start of the next frame in a stream); only the leading frame is
/// parsed.
///
/// On success, returns a non-NULL handle (free it with
/// [`rtcm3_message_free`] when done) and, if `out_error` is non-NULL,
/// writes [`Rtcm3FfiError::Ok`] through it. On failure, returns NULL and,
/// if `out_error` is non-NULL, writes the reason through it.
///
/// # Safety
/// `buf` must be NULL or valid for reads of `len` bytes. `out_error` must
/// be NULL or a pointer valid for a single write.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn rtcm3_decode(
    buf: *const u8,
    len: usize,
    out_error: *mut Rtcm3FfiError,
) -> *mut Rtcm3FfiMessage {
    let set_error = |code: Rtcm3FfiError| {
        if !out_error.is_null() {
            // SAFETY: caller guarantees `out_error` is a valid write target or NULL.
            unsafe {
                out_error.write(code);
            }
        }
    };

    if buf.is_null() {
        set_error(Rtcm3FfiError::NullInput);
        return ptr::null_mut();
    }

    // SAFETY: caller guarantees `buf` is valid for reads of `len` bytes.
    let bytes = unsafe { core::slice::from_raw_parts(buf, len) };

    match rtcm3::decode(bytes) {
        Ok(message) => {
            set_error(Rtcm3FfiError::Ok);
            Box::into_raw(Box::new(Rtcm3FfiMessage { message }))
        }
        Err(e) => {
            set_error(Rtcm3FfiError::from(e));
            ptr::null_mut()
        }
    }
}

/// Frees a message handle returned by [`rtcm3_decode`]. Passing NULL is a
/// no-op.
///
/// # Safety
/// `msg` must be NULL or a pointer previously returned by [`rtcm3_decode`]
/// that has not already been freed.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn rtcm3_message_free(msg: *mut Rtcm3FfiMessage) {
    if !msg.is_null() {
        // SAFETY: caller guarantees `msg` is a live handle from `rtcm3_decode`.
        drop(unsafe { Box::from_raw(msg) });
    }
}

/// The message's RTCM3 message type (DF002, e.g. `1005` for a Stationary
/// RTK Reference Station ARP), or `0xFFFF` for a NULL handle or a variant
/// this header doesn't know about yet.
///
/// # Safety
/// `msg` must be NULL or a valid, non-freed handle from [`rtcm3_decode`].
#[unsafe(no_mangle)]
pub unsafe extern "C" fn rtcm3_message_type(msg: *const Rtcm3FfiMessage) -> u16 {
    // SAFETY: caller guarantees `msg` is a valid handle or NULL.
    match unsafe { msg.as_ref() } {
        Some(m) => match m.message {
            Rtcm3Message::StationArp(_) => 1005,
            Rtcm3Message::GlonassBias(_) => 1230,
            Rtcm3Message::GpsMsm7(_) => 1077,
            _ => 0xFFFF,
        },
        None => 0xFFFF,
    }
}

/// Stationary RTK Reference Station ARP (type 1005): the base station's
/// antenna reference point position.
#[repr(C)]
#[derive(Debug, Clone, Copy)]
pub struct Rtcm3StationArp {
    /// Reference station ID (DF003).
    pub reference_station_id: u16,
    /// ITRF realization year (DF021).
    pub itrf_realization_year: u8,
    /// Whether GPS observations are included in this station's stream (DF022).
    pub gps_indicator: bool,
    /// Whether GLONASS observations are included (DF023).
    pub glonass_indicator: bool,
    /// Whether Galileo observations are included (DF024).
    pub galileo_indicator: bool,
    /// Reference-station indicator (DF141).
    pub reference_station_indicator: bool,
    /// Antenna reference point ECEF X, raw units of 0.0001m (DF025).
    pub ecef_x_raw: i64,
    /// Single-receiver oscillator indicator (DF142).
    pub single_oscillator_indicator: bool,
    /// Antenna reference point ECEF Y, raw units of 0.0001m (DF026).
    pub ecef_y_raw: i64,
    /// Quarter-cycle phase shift indicator (DF364).
    pub quarter_cycle_indicator: u8,
    /// Antenna reference point ECEF Z, raw units of 0.0001m (DF027).
    pub ecef_z_raw: i64,
}

impl From<StationArp> for Rtcm3StationArp {
    fn from(m: StationArp) -> Self {
        Self {
            reference_station_id: m.reference_station_id,
            itrf_realization_year: m.itrf_realization_year,
            gps_indicator: m.gps_indicator,
            glonass_indicator: m.glonass_indicator,
            galileo_indicator: m.galileo_indicator,
            reference_station_indicator: m.reference_station_indicator,
            ecef_x_raw: m.ecef_x_raw,
            single_oscillator_indicator: m.single_oscillator_indicator,
            ecef_y_raw: m.ecef_y_raw,
            quarter_cycle_indicator: m.quarter_cycle_indicator,
            ecef_z_raw: m.ecef_z_raw,
        }
    }
}

/// GLONASS Code-Phase Biases (type 1230). Each bias field is only
/// meaningful when its `_present` flag is `true` - the underlying signal
/// wasn't present in the station's stream otherwise, and `_raw` reads `0`.
#[repr(C)]
#[derive(Debug, Clone, Copy)]
pub struct Rtcm3GlonassBias {
    /// Reference station ID (DF003).
    pub reference_station_id: u16,
    /// GLONASS code-phase bias indicator (DF421).
    pub code_phase_bias_indicator: bool,
    /// Whether the L1 C/A bias field is present (DF423).
    pub l1_ca_bias_present: bool,
    /// L1 C/A code-phase bias, raw units of 0.02m, if present.
    pub l1_ca_bias_raw: i32,
    /// Whether the L1 P bias field is present (DF424).
    pub l1_p_bias_present: bool,
    /// L1 P code-phase bias, raw units of 0.02m, if present.
    pub l1_p_bias_raw: i32,
    /// Whether the L2 C/A bias field is present (DF425).
    pub l2_ca_bias_present: bool,
    /// L2 C/A code-phase bias, raw units of 0.02m, if present.
    pub l2_ca_bias_raw: i32,
    /// Whether the L2 P bias field is present (DF426).
    pub l2_p_bias_present: bool,
    /// L2 P code-phase bias, raw units of 0.02m, if present.
    pub l2_p_bias_raw: i32,
}

impl From<GlonassBias> for Rtcm3GlonassBias {
    fn from(m: GlonassBias) -> Self {
        Self {
            reference_station_id: m.reference_station_id,
            code_phase_bias_indicator: m.code_phase_bias_indicator,
            l1_ca_bias_present: m.l1_ca_bias_raw.is_some(),
            l1_ca_bias_raw: m.l1_ca_bias_raw.unwrap_or(0),
            l1_p_bias_present: m.l1_p_bias_raw.is_some(),
            l1_p_bias_raw: m.l1_p_bias_raw.unwrap_or(0),
            l2_ca_bias_present: m.l2_ca_bias_raw.is_some(),
            l2_ca_bias_raw: m.l2_ca_bias_raw.unwrap_or(0),
            l2_p_bias_present: m.l2_p_bias_raw.is_some(),
            l2_p_bias_raw: m.l2_p_bias_raw.unwrap_or(0),
        }
    }
}

/// One satellite's data block within a [`Rtcm3GpsMsm7`] message.
#[repr(C)]
#[derive(Debug, Clone, Copy)]
pub struct Rtcm3SatelliteData {
    /// Integer milliseconds in the satellite's rough range (DF397).
    pub rough_range_ms_raw: u8,
    /// Extended satellite information (DF419).
    pub extended_info_raw: u8,
    /// Rough range modulo 1 millisecond, raw units of 2^-10 ms (DF398).
    pub rough_range_mod_raw: u16,
    /// Rough phase range rate, m/s (DF399).
    pub rough_phase_range_rate_raw: i16,
}

impl From<SatelliteData> for Rtcm3SatelliteData {
    fn from(s: SatelliteData) -> Self {
        Self {
            rough_range_ms_raw: s.rough_range_ms_raw,
            extended_info_raw: s.extended_info_raw,
            rough_range_mod_raw: s.rough_range_mod_raw,
            rough_phase_range_rate_raw: s.rough_phase_range_rate_raw,
        }
    }
}

/// One satellite/signal cell's data block within a [`Rtcm3GpsMsm7`]
/// message.
#[repr(C)]
#[derive(Debug, Clone, Copy)]
pub struct Rtcm3CellData {
    /// Fine pseudorange, raw units of 2^-29 ms (DF405).
    pub fine_pseudorange_raw: i32,
    /// Fine phase range, raw units of 2^-31 ms (DF406).
    pub fine_phase_range_raw: i32,
    /// Phase range lock time indicator, extended range/resolution (DF407).
    pub lock_time_raw: u16,
    /// Half-cycle ambiguity indicator (DF420).
    pub half_cycle_ambiguity: bool,
    /// Carrier-to-noise ratio, raw units of 2^-4 dB-Hz (DF408).
    pub cnr_raw: u16,
    /// Fine phase range rate, raw units of 0.0001 m/s (DF404).
    pub fine_phase_range_rate_raw: i16,
}

impl From<CellData> for Rtcm3CellData {
    fn from(c: CellData) -> Self {
        Self {
            fine_pseudorange_raw: c.fine_pseudorange_raw,
            fine_phase_range_raw: c.fine_phase_range_raw,
            lock_time_raw: c.lock_time_raw,
            half_cycle_ambiguity: c.half_cycle_ambiguity,
            cnr_raw: c.cnr_raw,
            fine_phase_range_rate_raw: c.fine_phase_range_rate_raw,
        }
    }
}

/// GPS Full Pseudoranges and `PhaseRanges` plus CNR, high resolution
/// (type 1077). `num_satellites`/`num_signals`/`num_cells` say how many
/// entries of `satellites`/`cells` are meaningful; the rest are unused
/// padding, matching the core crate's own mask-derived counts.
#[repr(C)]
#[derive(Debug, Clone, Copy)]
pub struct Rtcm3GpsMsm7 {
    /// Reference station ID (DF003).
    pub reference_station_id: u16,
    /// GPS epoch time (time of week), raw milliseconds (DF004).
    pub gps_epoch_time_tow_ms: u32,
    /// Multiple message bit: more MSM messages follow for this epoch (DF393).
    pub multiple_message_bit: bool,
    /// Issue of data station (DF409).
    pub issue_of_data_station: u8,
    /// Clock steering indicator (DF411).
    pub clock_steering_indicator: u8,
    /// External clock indicator (DF412).
    pub external_clock_indicator: u8,
    /// GNSS divergence-free smoothing indicator (DF417).
    pub smoothing_indicator: bool,
    /// GNSS smoothing interval, raw encoding (DF418).
    pub smoothing_interval_raw: u8,
    /// Satellite mask (DF394).
    pub satellite_mask: u64,
    /// Signal mask (DF395).
    pub signal_mask: u32,
    /// Cell mask (DF396).
    pub cell_mask: u64,
    /// Number of satellites present (popcount of `satellite_mask`).
    pub num_satellites: u32,
    /// Number of signal types present (popcount of `signal_mask`).
    pub num_signals: u32,
    /// Number of satellite/signal cells present (popcount of `cell_mask`).
    pub num_cells: u32,
    /// Per-satellite data blocks, indexed in mask-bit order.
    pub satellites: [Rtcm3SatelliteData; RTCM3_FFI_MAX_SATELLITES],
    /// Per-cell data blocks, indexed in mask-bit order.
    pub cells: [Rtcm3CellData; RTCM3_FFI_MAX_CELLS],
}

impl From<GpsMsm7> for Rtcm3GpsMsm7 {
    fn from(m: GpsMsm7) -> Self {
        Self {
            reference_station_id: m.reference_station_id,
            gps_epoch_time_tow_ms: m.gps_epoch_time_tow_ms,
            multiple_message_bit: m.multiple_message_bit,
            issue_of_data_station: m.issue_of_data_station,
            clock_steering_indicator: m.clock_steering_indicator,
            external_clock_indicator: m.external_clock_indicator,
            smoothing_indicator: m.smoothing_indicator,
            smoothing_interval_raw: m.smoothing_interval_raw,
            satellite_mask: m.satellite_mask,
            signal_mask: m.signal_mask,
            cell_mask: m.cell_mask,
            num_satellites: m.num_satellites(),
            num_signals: m.num_signals(),
            num_cells: m.num_cells(),
            satellites: m.satellites.map(Into::into),
            cells: m.cells.map(Into::into),
        }
    }
}

/// Reads `msg`'s message as a Stationary RTK Reference Station ARP
/// (type 1005) into `out`, returning `true` on a match. Returns `false`
/// without writing to `out` if `msg` is NULL or holds a different message
/// type.
///
/// # Safety
/// `msg` must be NULL or a valid, non-freed handle from [`rtcm3_decode`].
/// `out` must be a valid write target.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn rtcm3_message_as_station_arp(
    msg: *const Rtcm3FfiMessage,
    out: *mut Rtcm3StationArp,
) -> bool {
    // SAFETY: caller guarantees `msg` is a valid handle or NULL.
    let Some(m) = (unsafe { msg.as_ref() }) else {
        return false;
    };
    let Rtcm3Message::StationArp(inner) = m.message else {
        return false;
    };
    // SAFETY: caller guarantees `out` is a valid write target.
    unsafe {
        out.write(inner.into());
    }
    true
}

/// Reads `msg`'s message as a GLONASS Code-Phase Biases message
/// (type 1230) into `out`, returning `true` on a match. Returns `false`
/// without writing to `out` if `msg` is NULL or holds a different message
/// type.
///
/// # Safety
/// `msg` must be NULL or a valid, non-freed handle from [`rtcm3_decode`].
/// `out` must be a valid write target.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn rtcm3_message_as_glonass_bias(
    msg: *const Rtcm3FfiMessage,
    out: *mut Rtcm3GlonassBias,
) -> bool {
    // SAFETY: caller guarantees `msg` is a valid handle or NULL.
    let Some(m) = (unsafe { msg.as_ref() }) else {
        return false;
    };
    let Rtcm3Message::GlonassBias(inner) = m.message else {
        return false;
    };
    // SAFETY: caller guarantees `out` is a valid write target.
    unsafe {
        out.write(inner.into());
    }
    true
}

/// Reads `msg`'s message as a GPS MSM7 message (type 1077) into `out`,
/// returning `true` on a match. Returns `false` without writing to `out`
/// if `msg` is NULL or holds a different message type.
///
/// # Safety
/// `msg` must be NULL or a valid, non-freed handle from [`rtcm3_decode`].
/// `out` must be a valid write target.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn rtcm3_message_as_gps_msm7(
    msg: *const Rtcm3FfiMessage,
    out: *mut Rtcm3GpsMsm7,
) -> bool {
    // SAFETY: caller guarantees `msg` is a valid handle or NULL.
    let Some(m) = (unsafe { msg.as_ref() }) else {
        return false;
    };
    let Rtcm3Message::GpsMsm7(inner) = m.message else {
        return false;
    };
    // SAFETY: caller guarantees `out` is a valid write target.
    unsafe {
        out.write(inner.into());
    }
    true
}

/// This crate's version string, as a NUL-terminated C string with static
/// lifetime.
#[unsafe(no_mangle)]
pub extern "C" fn rtcm3_version() -> *const c_char {
    const VERSION: &str = concat!(env!("CARGO_PKG_VERSION"), "\0");
    VERSION.as_ptr().cast::<c_char>()
}