squitter-ffi 0.1.1

C FFI bindings for the squitter 1090ES/DF17 (ADS-B extended squitter) 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
//! C FFI bindings for the `squitter` 1090ES/DF17 (ADS-B extended squitter)
//! decoder.
//!
//! Exposes a decode-only subset of `squitter`'s API: decode a single hex
//! frame into an opaque message handle, then read common fields off it
//! (ICAO address, callsign, altitude, raw CPR position fields, ground
//! speed, vertical rate). See `include/squitter.h` for the generated C
//! declarations.
//!
//! A single decoded `squitter` position message never carries a resolved
//! latitude/longitude by itself: CPR position decoding needs one even- and
//! one odd-format frame paired together (see `squitter::message::cpr`).
//! This FFI surface
//! exposes the raw CPR fields (format, encoded latitude/longitude) rather
//! than hiding that pairing requirement; a C caller wanting resolved
//! positions needs to pair frames itself (or, in Rust, use
//! [`squitter::message::AirbornePosition::decode`]'s
//! [`squitter::message::PositionPair`]).
//!
//! 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 `squitter` itself supports. Embedded consumers
//! should use the `squitter` Rust crate directly.

use std::ffi::{CStr, c_char};
use std::ptr;

use squitter::message::{AdsbMessage, Altitude, VelocityData};

/// Opaque handle to a decoded ADS-B message, owned by the caller until
/// freed with [`squitter_message_free`].
pub struct SquitterMessage {
    icao_address: u32,
    message: AdsbMessage,
}

/// Error codes returned by [`squitter_decode_line`].
#[repr(u8)]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum SquitterError {
    /// No error.
    Ok = 0,
    /// The `line` pointer was NULL.
    NullInput = 1,
    /// `line` was not valid UTF-8.
    InvalidUtf8 = 2,
    /// The frame itself was malformed (wrong length, bad checksum,
    /// unsupported downlink format).
    Frame = 3,
    /// The `ME` payload was truncated or otherwise malformed at the bit level.
    Bit = 4,
    /// The message type is unknown/undecoded, or a field held an invalid value.
    Message = 5,
}

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

/// Decodes a single hex-encoded DF17 frame (bare hex or dump1090's
/// `*...;` framing).
///
/// On success, returns a non-NULL handle (free it with
/// [`squitter_message_free`] when done) and, if `out_error` is non-NULL,
/// writes [`SquitterError::Ok`] through it. On failure, returns NULL and,
/// if `out_error` is non-NULL, writes the reason through it.
///
/// # Safety
/// `line` must be NULL or a pointer to a NUL-terminated C string valid for
/// reads for the duration of this call. `out_error` must be NULL or a
/// pointer valid for a single `u8`-sized write.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn squitter_decode_line(
    line: *const c_char,
    out_error: *mut SquitterError,
) -> *mut SquitterMessage {
    let set_error = |code: SquitterError| {
        if !out_error.is_null() {
            // SAFETY: caller guarantees `out_error` is a valid write target or NULL.
            unsafe {
                out_error.write(code);
            }
        }
    };

    if line.is_null() {
        set_error(SquitterError::NullInput);
        return ptr::null_mut();
    }

    // SAFETY: caller guarantees `line` is a valid NUL-terminated C string.
    let Ok(line_str) = unsafe { CStr::from_ptr(line) }.to_str() else {
        set_error(SquitterError::InvalidUtf8);
        return ptr::null_mut();
    };

    let frame = match squitter::Frame::parse(line_str) {
        Ok(frame) => frame,
        Err(e) => {
            set_error(SquitterError::from(squitter::AdsbError::from(e)));
            return ptr::null_mut();
        }
    };

    match frame.decode_message() {
        Ok(message) => {
            set_error(SquitterError::Ok);
            Box::into_raw(Box::new(SquitterMessage {
                icao_address: frame.icao_address(),
                message,
            }))
        }
        Err(e) => {
            set_error(SquitterError::from(e));
            ptr::null_mut()
        }
    }
}

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

/// Which message family this handle holds: `1` = identification, `2` =
/// surface position, `3` = airborne position, `4` = airborne velocity, `0`
/// for a NULL handle.
///
/// # Safety
/// `msg` must be NULL or a valid, non-freed handle from [`squitter_decode_line`].
#[unsafe(no_mangle)]
pub unsafe extern "C" fn squitter_message_kind(msg: *const SquitterMessage) -> u8 {
    // SAFETY: caller guarantees `msg` is a valid handle or NULL.
    match unsafe { msg.as_ref() } {
        Some(m) => match m.message {
            AdsbMessage::Identification(_) => 1,
            AdsbMessage::SurfacePosition(_) => 2,
            AdsbMessage::AirbornePosition(_) => 3,
            AdsbMessage::AirborneVelocity(_) => 4,
            _ => 0,
        },
        None => 0,
    }
}

/// The transmitting aircraft's 24-bit ICAO address.
///
/// # Safety
/// `msg` must be NULL or a valid, non-freed handle from [`squitter_decode_line`].
#[unsafe(no_mangle)]
pub unsafe extern "C" fn squitter_message_icao_address(msg: *const SquitterMessage) -> u32 {
    // SAFETY: caller guarantees `msg` is a valid handle or NULL.
    match unsafe { msg.as_ref() } {
        Some(m) => m.icao_address,
        None => 0,
    }
}

/// Reads the aircraft callsign into `buf` as a NUL-terminated string.
///
/// Returns `true` and fills `buf` if this is an identification message and
/// `buf_len` is large enough (the callsign is always 8 characters or
/// fewer, so a 9-byte buffer always suffices); returns `false` (leaving
/// `buf` untouched) otherwise.
///
/// # Safety
/// `msg` must be NULL or a valid, non-freed handle from
/// [`squitter_decode_line`]. `buf` must be NULL or valid for writes of
/// `buf_len` bytes.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn squitter_message_callsign(
    msg: *const SquitterMessage,
    buf: *mut c_char,
    buf_len: usize,
) -> bool {
    // SAFETY: caller guarantees `msg` is a valid handle or NULL.
    let Some(m) = (unsafe { msg.as_ref() }) else {
        return false;
    };
    let AdsbMessage::Identification(id) = &m.message else {
        return false;
    };
    let text = id.callsign.as_str().as_bytes();
    if buf.is_null() || buf_len < text.len() + 1 {
        return false;
    }
    // SAFETY: caller guarantees `buf` is valid for `buf_len` bytes, and we
    // just checked `buf_len >= text.len() + 1`.
    unsafe {
        ptr::copy_nonoverlapping(text.as_ptr().cast::<c_char>(), buf, text.len());
        buf.add(text.len()).write(0);
    }
    true
}

/// Reads barometric altitude, in feet, off a message.
///
/// Returns `true` and writes `*out_feet` if this is an airborne position
/// message with a modern (non-Gillham) barometric altitude; returns
/// `false` otherwise (including for the legacy Gillham encoding or GNSS
/// height - see [`squitter_message_altitude_gnss_meters`]).
///
/// # Safety
/// `msg` must be NULL or a valid, non-freed handle from
/// [`squitter_decode_line`]. `out_feet` must be a valid pointer to a
/// writable `i32`.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn squitter_message_altitude_feet(
    msg: *const SquitterMessage,
    out_feet: *mut i32,
) -> bool {
    // SAFETY: caller guarantees `msg` is a valid handle or NULL.
    let Some(m) = (unsafe { msg.as_ref() }) else {
        return false;
    };
    let AdsbMessage::AirbornePosition(pos) = &m.message else {
        return false;
    };
    let Altitude::BarometricFeet(feet) = pos.altitude else {
        return false;
    };
    // SAFETY: caller guarantees `out_feet` is a valid write target.
    unsafe {
        out_feet.write(feet);
    }
    true
}

/// Reads GNSS height, in meters, off a message.
///
/// Returns `true` and writes `*out_meters` if this is an airborne position
/// message with GNSS height (type codes 20-22); returns `false` otherwise.
///
/// # Safety
/// `msg` must be NULL or a valid, non-freed handle from
/// [`squitter_decode_line`]. `out_meters` must be a valid pointer to a
/// writable `u16`.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn squitter_message_altitude_gnss_meters(
    msg: *const SquitterMessage,
    out_meters: *mut u16,
) -> bool {
    // SAFETY: caller guarantees `msg` is a valid handle or NULL.
    let Some(m) = (unsafe { msg.as_ref() }) else {
        return false;
    };
    let AdsbMessage::AirbornePosition(pos) = &m.message else {
        return false;
    };
    let Altitude::GnssMeters(meters) = pos.altitude else {
        return false;
    };
    // SAFETY: caller guarantees `out_meters` is a valid write target.
    unsafe {
        out_meters.write(meters);
    }
    true
}

/// Reads the raw CPR-encoded position fields off a message.
///
/// Returns `true` and writes the outputs (`*out_odd`: `true` = odd-format,
/// `false` = even-format; `*out_lat_cpr`/`*out_lon_cpr`: the raw 17-bit
/// encoded values) if this is a position message (airborne or surface);
/// returns `false` otherwise. These are *not* a resolved
/// latitude/longitude - see the module-level docs.
///
/// # Safety
/// `msg` must be NULL or a valid, non-freed handle from
/// [`squitter_decode_line`]. `out_odd`, `out_lat_cpr`, and `out_lon_cpr`
/// must each be a valid pointer to writable memory of the matching type.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn squitter_message_cpr(
    msg: *const SquitterMessage,
    out_odd: *mut bool,
    out_lat_cpr: *mut u32,
    out_lon_cpr: *mut u32,
) -> bool {
    // SAFETY: caller guarantees `msg` is a valid handle or NULL.
    let Some(m) = (unsafe { msg.as_ref() }) else {
        return false;
    };
    let (is_odd, lat_cpr, lon_cpr) = match &m.message {
        AdsbMessage::AirbornePosition(pos) => (
            pos.cpr_format == squitter::message::CprFormat::Odd,
            pos.lat_cpr,
            pos.lon_cpr,
        ),
        AdsbMessage::SurfacePosition(pos) => (
            pos.cpr_format == squitter::message::CprFormat::Odd,
            pos.lat_cpr,
            pos.lon_cpr,
        ),
        _ => return false,
    };
    // SAFETY: caller guarantees these are valid write targets.
    unsafe {
        out_odd.write(is_odd);
        out_lat_cpr.write(lat_cpr);
        out_lon_cpr.write(lon_cpr);
    }
    true
}

/// Reads ground speed, in knots, off a message.
///
/// Returns `true` and writes `*out_knots` if this message carries a
/// resolvable ground speed (an airborne velocity message with both
/// east-west and north-south components available, or a surface position
/// message with movement information); returns `false` otherwise.
///
/// # Safety
/// `msg` must be NULL or a valid, non-freed handle from
/// [`squitter_decode_line`]. `out_knots` must be a valid pointer to a
/// writable `f64`.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn squitter_message_ground_speed_knots(
    msg: *const SquitterMessage,
    out_knots: *mut f64,
) -> bool {
    // SAFETY: caller guarantees `msg` is a valid handle or NULL.
    let Some(m) = (unsafe { msg.as_ref() }) else {
        return false;
    };
    let knots = match &m.message {
        AdsbMessage::AirborneVelocity(vel) => vel.ground_speed_knots(),
        AdsbMessage::SurfacePosition(pos) => pos.ground_speed_knots(),
        _ => None,
    };
    let Some(knots) = knots else {
        return false;
    };
    // SAFETY: caller guarantees `out_knots` is a valid write target.
    unsafe {
        out_knots.write(knots);
    }
    true
}

/// Reads vertical rate, in feet/minute (positive = climb), off a message.
///
/// Returns `true` and writes `*out_fpm` if this is an airborne velocity
/// message with a known vertical rate; returns `false` otherwise.
///
/// # Safety
/// `msg` must be NULL or a valid, non-freed handle from
/// [`squitter_decode_line`]. `out_fpm` must be a valid pointer to a
/// writable `i32`.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn squitter_message_vertical_rate_fpm(
    msg: *const SquitterMessage,
    out_fpm: *mut i32,
) -> bool {
    // SAFETY: caller guarantees `msg` is a valid handle or NULL.
    let Some(m) = (unsafe { msg.as_ref() }) else {
        return false;
    };
    let AdsbMessage::AirborneVelocity(vel) = &m.message else {
        return false;
    };
    let Some(fpm) = vel.vertical_rate_fpm else {
        return false;
    };
    // SAFETY: caller guarantees `out_fpm` is a valid write target.
    unsafe {
        out_fpm.write(fpm);
    }
    true
}

/// True airspeed/indicated airspeed heading, in decimal degrees, off an
/// airspeed-subtype airborne velocity message.
///
/// Returns `true` and writes `*out_degrees` if this is an airborne
/// velocity message reporting airspeed (not ground speed) with a known
/// heading; returns `false` otherwise.
///
/// # Safety
/// `msg` must be NULL or a valid, non-freed handle from
/// [`squitter_decode_line`]. `out_degrees` must be a valid pointer to a
/// writable `f64`.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn squitter_message_heading_degrees(
    msg: *const SquitterMessage,
    out_degrees: *mut f64,
) -> bool {
    // SAFETY: caller guarantees `msg` is a valid handle or NULL.
    let Some(m) = (unsafe { msg.as_ref() }) else {
        return false;
    };
    let AdsbMessage::AirborneVelocity(vel) = &m.message else {
        return false;
    };
    let VelocityData::AirSpeed {
        heading_degrees: Some(degrees),
        ..
    } = vel.velocity
    else {
        return false;
    };
    // SAFETY: caller guarantees `out_degrees` is a valid write target.
    unsafe {
        out_degrees.write(degrees);
    }
    true
}

/// The `squitter` crate version, as a NUL-terminated, statically allocated
/// string (e.g. `"0.1.1"`). Do not free.
#[unsafe(no_mangle)]
pub extern "C" fn squitter_version() -> *const c_char {
    const VERSION: &str = concat!(env!("CARGO_PKG_VERSION"), "\0");
    VERSION.as_ptr().cast::<c_char>()
}