Skip to main content

squitter_ffi/
lib.rs

1//! C FFI bindings for the `squitter` 1090ES/DF17 (ADS-B extended squitter)
2//! decoder.
3//!
4//! Exposes a decode-only subset of `squitter`'s API: decode a single hex
5//! frame into an opaque message handle, then read common fields off it
6//! (ICAO address, callsign, altitude, raw CPR position fields, ground
7//! speed, vertical rate). See `include/squitter.h` for the generated C
8//! declarations.
9//!
10//! A single decoded `squitter` position message never carries a resolved
11//! latitude/longitude by itself: CPR position decoding needs one even- and
12//! one odd-format frame paired together (see `squitter::message::cpr`).
13//! This FFI surface
14//! exposes the raw CPR fields (format, encoded latitude/longitude) rather
15//! than hiding that pairing requirement; a C caller wanting resolved
16//! positions needs to pair frames itself (or, in Rust, use
17//! [`squitter::message::AirbornePosition::decode`]'s
18//! [`squitter::message::PositionPair`]).
19//!
20//! This crate is a plain (non-`no_std`) library: it targets host
21//! environments linking a shared or static C library, not the embedded
22//! `no_alloc` use case `squitter` itself supports. Embedded consumers
23//! should use the `squitter` Rust crate directly.
24
25use std::ffi::{CStr, c_char};
26use std::ptr;
27
28use squitter::message::{AdsbMessage, Altitude, VelocityData};
29
30/// Opaque handle to a decoded ADS-B message, owned by the caller until
31/// freed with [`squitter_message_free`].
32pub struct SquitterMessage {
33    icao_address: u32,
34    message: AdsbMessage,
35}
36
37/// Error codes returned by [`squitter_decode_line`].
38#[repr(u8)]
39#[derive(Debug, Clone, Copy, PartialEq, Eq)]
40pub enum SquitterError {
41    /// No error.
42    Ok = 0,
43    /// The `line` pointer was NULL.
44    NullInput = 1,
45    /// `line` was not valid UTF-8.
46    InvalidUtf8 = 2,
47    /// The frame itself was malformed (wrong length, bad checksum,
48    /// unsupported downlink format).
49    Frame = 3,
50    /// The `ME` payload was truncated or otherwise malformed at the bit level.
51    Bit = 4,
52    /// The message type is unknown/undecoded, or a field held an invalid value.
53    Message = 5,
54}
55
56impl From<squitter::AdsbError> for SquitterError {
57    fn from(e: squitter::AdsbError) -> Self {
58        match e {
59            squitter::AdsbError::Frame(_) => Self::Frame,
60            squitter::AdsbError::Bit(_) => Self::Bit,
61            // covers Message(_) and any future non_exhaustive variant
62            _ => Self::Message,
63        }
64    }
65}
66
67/// Decodes a single hex-encoded DF17 frame (bare hex or dump1090's
68/// `*...;` framing).
69///
70/// On success, returns a non-NULL handle (free it with
71/// [`squitter_message_free`] when done) and, if `out_error` is non-NULL,
72/// writes [`SquitterError::Ok`] through it. On failure, returns NULL and,
73/// if `out_error` is non-NULL, writes the reason through it.
74///
75/// # Safety
76/// `line` must be NULL or a pointer to a NUL-terminated C string valid for
77/// reads for the duration of this call. `out_error` must be NULL or a
78/// pointer valid for a single `u8`-sized write.
79#[unsafe(no_mangle)]
80pub unsafe extern "C" fn squitter_decode_line(
81    line: *const c_char,
82    out_error: *mut SquitterError,
83) -> *mut SquitterMessage {
84    let set_error = |code: SquitterError| {
85        if !out_error.is_null() {
86            // SAFETY: caller guarantees `out_error` is a valid write target or NULL.
87            unsafe {
88                out_error.write(code);
89            }
90        }
91    };
92
93    if line.is_null() {
94        set_error(SquitterError::NullInput);
95        return ptr::null_mut();
96    }
97
98    // SAFETY: caller guarantees `line` is a valid NUL-terminated C string.
99    let Ok(line_str) = unsafe { CStr::from_ptr(line) }.to_str() else {
100        set_error(SquitterError::InvalidUtf8);
101        return ptr::null_mut();
102    };
103
104    let frame = match squitter::Frame::parse(line_str) {
105        Ok(frame) => frame,
106        Err(e) => {
107            set_error(SquitterError::from(squitter::AdsbError::from(e)));
108            return ptr::null_mut();
109        }
110    };
111
112    match frame.decode_message() {
113        Ok(message) => {
114            set_error(SquitterError::Ok);
115            Box::into_raw(Box::new(SquitterMessage {
116                icao_address: frame.icao_address(),
117                message,
118            }))
119        }
120        Err(e) => {
121            set_error(SquitterError::from(e));
122            ptr::null_mut()
123        }
124    }
125}
126
127/// Frees a message handle returned by [`squitter_decode_line`]. Passing
128/// NULL is a no-op.
129///
130/// # Safety
131/// `msg` must be NULL or a pointer previously returned by
132/// [`squitter_decode_line`] that has not already been freed.
133#[unsafe(no_mangle)]
134pub unsafe extern "C" fn squitter_message_free(msg: *mut SquitterMessage) {
135    if !msg.is_null() {
136        // SAFETY: caller guarantees `msg` is a live handle from `squitter_decode_line`.
137        drop(unsafe { Box::from_raw(msg) });
138    }
139}
140
141/// Which message family this handle holds: `1` = identification, `2` =
142/// surface position, `3` = airborne position, `4` = airborne velocity, `0`
143/// for a NULL handle.
144///
145/// # Safety
146/// `msg` must be NULL or a valid, non-freed handle from [`squitter_decode_line`].
147#[unsafe(no_mangle)]
148pub unsafe extern "C" fn squitter_message_kind(msg: *const SquitterMessage) -> u8 {
149    // SAFETY: caller guarantees `msg` is a valid handle or NULL.
150    match unsafe { msg.as_ref() } {
151        Some(m) => match m.message {
152            AdsbMessage::Identification(_) => 1,
153            AdsbMessage::SurfacePosition(_) => 2,
154            AdsbMessage::AirbornePosition(_) => 3,
155            AdsbMessage::AirborneVelocity(_) => 4,
156            _ => 0,
157        },
158        None => 0,
159    }
160}
161
162/// The transmitting aircraft's 24-bit ICAO address.
163///
164/// # Safety
165/// `msg` must be NULL or a valid, non-freed handle from [`squitter_decode_line`].
166#[unsafe(no_mangle)]
167pub unsafe extern "C" fn squitter_message_icao_address(msg: *const SquitterMessage) -> u32 {
168    // SAFETY: caller guarantees `msg` is a valid handle or NULL.
169    match unsafe { msg.as_ref() } {
170        Some(m) => m.icao_address,
171        None => 0,
172    }
173}
174
175/// Reads the aircraft callsign into `buf` as a NUL-terminated string.
176///
177/// Returns `true` and fills `buf` if this is an identification message and
178/// `buf_len` is large enough (the callsign is always 8 characters or
179/// fewer, so a 9-byte buffer always suffices); returns `false` (leaving
180/// `buf` untouched) otherwise.
181///
182/// # Safety
183/// `msg` must be NULL or a valid, non-freed handle from
184/// [`squitter_decode_line`]. `buf` must be NULL or valid for writes of
185/// `buf_len` bytes.
186#[unsafe(no_mangle)]
187pub unsafe extern "C" fn squitter_message_callsign(
188    msg: *const SquitterMessage,
189    buf: *mut c_char,
190    buf_len: usize,
191) -> bool {
192    // SAFETY: caller guarantees `msg` is a valid handle or NULL.
193    let Some(m) = (unsafe { msg.as_ref() }) else {
194        return false;
195    };
196    let AdsbMessage::Identification(id) = &m.message else {
197        return false;
198    };
199    let text = id.callsign.as_str().as_bytes();
200    if buf.is_null() || buf_len < text.len() + 1 {
201        return false;
202    }
203    // SAFETY: caller guarantees `buf` is valid for `buf_len` bytes, and we
204    // just checked `buf_len >= text.len() + 1`.
205    unsafe {
206        ptr::copy_nonoverlapping(text.as_ptr().cast::<c_char>(), buf, text.len());
207        buf.add(text.len()).write(0);
208    }
209    true
210}
211
212/// Reads barometric altitude, in feet, off a message.
213///
214/// Returns `true` and writes `*out_feet` if this is an airborne position
215/// message with a modern (non-Gillham) barometric altitude; returns
216/// `false` otherwise (including for the legacy Gillham encoding or GNSS
217/// height - see [`squitter_message_altitude_gnss_meters`]).
218///
219/// # Safety
220/// `msg` must be NULL or a valid, non-freed handle from
221/// [`squitter_decode_line`]. `out_feet` must be a valid pointer to a
222/// writable `i32`.
223#[unsafe(no_mangle)]
224pub unsafe extern "C" fn squitter_message_altitude_feet(
225    msg: *const SquitterMessage,
226    out_feet: *mut i32,
227) -> bool {
228    // SAFETY: caller guarantees `msg` is a valid handle or NULL.
229    let Some(m) = (unsafe { msg.as_ref() }) else {
230        return false;
231    };
232    let AdsbMessage::AirbornePosition(pos) = &m.message else {
233        return false;
234    };
235    let Altitude::BarometricFeet(feet) = pos.altitude else {
236        return false;
237    };
238    // SAFETY: caller guarantees `out_feet` is a valid write target.
239    unsafe {
240        out_feet.write(feet);
241    }
242    true
243}
244
245/// Reads GNSS height, in meters, off a message.
246///
247/// Returns `true` and writes `*out_meters` if this is an airborne position
248/// message with GNSS height (type codes 20-22); returns `false` otherwise.
249///
250/// # Safety
251/// `msg` must be NULL or a valid, non-freed handle from
252/// [`squitter_decode_line`]. `out_meters` must be a valid pointer to a
253/// writable `u16`.
254#[unsafe(no_mangle)]
255pub unsafe extern "C" fn squitter_message_altitude_gnss_meters(
256    msg: *const SquitterMessage,
257    out_meters: *mut u16,
258) -> bool {
259    // SAFETY: caller guarantees `msg` is a valid handle or NULL.
260    let Some(m) = (unsafe { msg.as_ref() }) else {
261        return false;
262    };
263    let AdsbMessage::AirbornePosition(pos) = &m.message else {
264        return false;
265    };
266    let Altitude::GnssMeters(meters) = pos.altitude else {
267        return false;
268    };
269    // SAFETY: caller guarantees `out_meters` is a valid write target.
270    unsafe {
271        out_meters.write(meters);
272    }
273    true
274}
275
276/// Reads the raw CPR-encoded position fields off a message.
277///
278/// Returns `true` and writes the outputs (`*out_odd`: `true` = odd-format,
279/// `false` = even-format; `*out_lat_cpr`/`*out_lon_cpr`: the raw 17-bit
280/// encoded values) if this is a position message (airborne or surface);
281/// returns `false` otherwise. These are *not* a resolved
282/// latitude/longitude - see the module-level docs.
283///
284/// # Safety
285/// `msg` must be NULL or a valid, non-freed handle from
286/// [`squitter_decode_line`]. `out_odd`, `out_lat_cpr`, and `out_lon_cpr`
287/// must each be a valid pointer to writable memory of the matching type.
288#[unsafe(no_mangle)]
289pub unsafe extern "C" fn squitter_message_cpr(
290    msg: *const SquitterMessage,
291    out_odd: *mut bool,
292    out_lat_cpr: *mut u32,
293    out_lon_cpr: *mut u32,
294) -> bool {
295    // SAFETY: caller guarantees `msg` is a valid handle or NULL.
296    let Some(m) = (unsafe { msg.as_ref() }) else {
297        return false;
298    };
299    let (is_odd, lat_cpr, lon_cpr) = match &m.message {
300        AdsbMessage::AirbornePosition(pos) => (
301            pos.cpr_format == squitter::message::CprFormat::Odd,
302            pos.lat_cpr,
303            pos.lon_cpr,
304        ),
305        AdsbMessage::SurfacePosition(pos) => (
306            pos.cpr_format == squitter::message::CprFormat::Odd,
307            pos.lat_cpr,
308            pos.lon_cpr,
309        ),
310        _ => return false,
311    };
312    // SAFETY: caller guarantees these are valid write targets.
313    unsafe {
314        out_odd.write(is_odd);
315        out_lat_cpr.write(lat_cpr);
316        out_lon_cpr.write(lon_cpr);
317    }
318    true
319}
320
321/// Reads ground speed, in knots, off a message.
322///
323/// Returns `true` and writes `*out_knots` if this message carries a
324/// resolvable ground speed (an airborne velocity message with both
325/// east-west and north-south components available, or a surface position
326/// message with movement information); returns `false` otherwise.
327///
328/// # Safety
329/// `msg` must be NULL or a valid, non-freed handle from
330/// [`squitter_decode_line`]. `out_knots` must be a valid pointer to a
331/// writable `f64`.
332#[unsafe(no_mangle)]
333pub unsafe extern "C" fn squitter_message_ground_speed_knots(
334    msg: *const SquitterMessage,
335    out_knots: *mut f64,
336) -> bool {
337    // SAFETY: caller guarantees `msg` is a valid handle or NULL.
338    let Some(m) = (unsafe { msg.as_ref() }) else {
339        return false;
340    };
341    let knots = match &m.message {
342        AdsbMessage::AirborneVelocity(vel) => vel.ground_speed_knots(),
343        AdsbMessage::SurfacePosition(pos) => pos.ground_speed_knots(),
344        _ => None,
345    };
346    let Some(knots) = knots else {
347        return false;
348    };
349    // SAFETY: caller guarantees `out_knots` is a valid write target.
350    unsafe {
351        out_knots.write(knots);
352    }
353    true
354}
355
356/// Reads vertical rate, in feet/minute (positive = climb), off a message.
357///
358/// Returns `true` and writes `*out_fpm` if this is an airborne velocity
359/// message with a known vertical rate; returns `false` otherwise.
360///
361/// # Safety
362/// `msg` must be NULL or a valid, non-freed handle from
363/// [`squitter_decode_line`]. `out_fpm` must be a valid pointer to a
364/// writable `i32`.
365#[unsafe(no_mangle)]
366pub unsafe extern "C" fn squitter_message_vertical_rate_fpm(
367    msg: *const SquitterMessage,
368    out_fpm: *mut i32,
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 AdsbMessage::AirborneVelocity(vel) = &m.message else {
375        return false;
376    };
377    let Some(fpm) = vel.vertical_rate_fpm else {
378        return false;
379    };
380    // SAFETY: caller guarantees `out_fpm` is a valid write target.
381    unsafe {
382        out_fpm.write(fpm);
383    }
384    true
385}
386
387/// True airspeed/indicated airspeed heading, in decimal degrees, off an
388/// airspeed-subtype airborne velocity message.
389///
390/// Returns `true` and writes `*out_degrees` if this is an airborne
391/// velocity message reporting airspeed (not ground speed) with a known
392/// heading; returns `false` otherwise.
393///
394/// # Safety
395/// `msg` must be NULL or a valid, non-freed handle from
396/// [`squitter_decode_line`]. `out_degrees` must be a valid pointer to a
397/// writable `f64`.
398#[unsafe(no_mangle)]
399pub unsafe extern "C" fn squitter_message_heading_degrees(
400    msg: *const SquitterMessage,
401    out_degrees: *mut f64,
402) -> bool {
403    // SAFETY: caller guarantees `msg` is a valid handle or NULL.
404    let Some(m) = (unsafe { msg.as_ref() }) else {
405        return false;
406    };
407    let AdsbMessage::AirborneVelocity(vel) = &m.message else {
408        return false;
409    };
410    let VelocityData::AirSpeed {
411        heading_degrees: Some(degrees),
412        ..
413    } = vel.velocity
414    else {
415        return false;
416    };
417    // SAFETY: caller guarantees `out_degrees` is a valid write target.
418    unsafe {
419        out_degrees.write(degrees);
420    }
421    true
422}
423
424/// The `squitter` crate version, as a NUL-terminated, statically allocated
425/// string (e.g. `"0.1.1"`). Do not free.
426#[unsafe(no_mangle)]
427pub extern "C" fn squitter_version() -> *const c_char {
428    const VERSION: &str = concat!(env!("CARGO_PKG_VERSION"), "\0");
429    VERSION.as_ptr().cast::<c_char>()
430}