remoteid/lib.rs
1//! Drone Remote ID in pure Rust.
2//!
3//! `remoteid` decodes and encodes the broadcast Remote ID messages defined by
4//! ASTM F3411-22a and ASD-STAN EN 4709-002 (the format the
5//! [Open Drone ID](https://github.com/opendroneid) project implements in C),
6//! and pulls them out of the frames receivers actually see:
7//!
8//! * Bluetooth 4 legacy advertising and Bluetooth 5 extended / long range
9//! advertising ([`ble`]),
10//! * Wi-Fi Beacon vendor elements and Wi-Fi NAN service discovery frames
11//! ([`wifi`]), with or without a radiotap header,
12//! * the French "signalement electronique" beacon format ([`france`]).
13//!
14//! Decoded messages can be merged into one record per aircraft ([`UasData`]),
15//! and with the `std` feature a [`Tracker`] keeps those records per
16//! transmitter, counts duplicate and missed frames from the message counters,
17//! and expires aircraft that went quiet.
18//!
19//! The crate has no dependencies and works in `no_std` (turn off the default
20//! `std` feature). It never allocates outside the `std`-only [`Tracker`].
21//!
22//! # Example
23//!
24//! ```
25//! use remoteid::{ble, Frame, Message, UasData};
26//!
27//! // Bluetooth advertising data from a scanner (one AD structure, BT4 legacy).
28//! let adv = [
29//! 0x1e, 0x16, 0xfa, 0xff, 0x0d, 0x07, // length, service data, UUID 0xFFFA, app code, counter
30//! 0x02, 0x12, b'1', b'5', b'9', b'6', b'F', b'3', b'5', b'0', b'7', b'4', b'5', b'2',
31//! 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
32//! ];
33//! let rid = ble::find_in_advertising_data(&adv).expect("Remote ID service data");
34//! let mut uas = UasData::default();
35//! match rid.frame().unwrap() {
36//! Frame::Message(Message::BasicId(id)) => {
37//! assert_eq!(id.uas_id_str(), Some("1596F3507452"));
38//! uas.update(&Message::BasicId(id));
39//! }
40//! other => panic!("unexpected {other:?}"),
41//! }
42//! assert!(uas.basic_id[0].is_some());
43//! ```
44//!
45//! # Accuracy and limits
46//!
47//! Decoding follows the reference C library bit for bit; the test suite
48//! compares every message in the public Open Drone ID sample captures against
49//! that library's output. Encoding quantizes the same way the C library does,
50//! so `decode(encode(x))` is exact for values on the transmitted grid.
51//! Authentication pages are reassembled for every scheme; the [`drip`]
52//! module parses the DRIP formats of RFC 9575 and, with the `verify`
53//! feature, [`auth`] checks their Ed25519 signatures. Other schemes plug in
54//! through `auth::AuthScheme`.
55//!
56//! # Trust
57//!
58//! Remote ID has no authentication in most deployed aircraft, and spoofers
59//! are a few lines of Python. [`trust`] turns decoded frames into a graded
60//! [`Verdict`] (`Authenticated`, `Plausible`, `Suspicious`, `Spoofed`) with
61//! the reasons behind it: kinematic plausibility, timestamp and counter
62//! continuity, Wi-Fi TSF behaviour, agreement between transports and
63//! transmitters, fingerprints of public spoofing tools, and DRIP
64//! signatures. The verdict is advice for a detector, not a filter: nothing
65//! is dropped.
66//!
67//! [`ridf`] defines RIDF v0, a small record format for raw frames with
68//! receiver time, signal strength and receiver position, and
69//! [`aircraft_json`] writes `aircraft.json` in the readsb schema so tar1090
70//! can show drones next to aircraft.
71
72#![cfg_attr(not(feature = "std"), no_std)]
73#![forbid(unsafe_code)]
74#![warn(missing_docs)]
75#![cfg_attr(docsrs, feature(doc_cfg))]
76
77#[cfg(feature = "std")]
78pub mod aircraft_json;
79#[cfg(feature = "verify")]
80pub mod auth;
81pub mod ble;
82#[cfg(feature = "std")]
83pub mod capture;
84pub mod drip;
85mod error;
86pub mod france;
87pub mod geo;
88mod message;
89mod pack;
90#[cfg(feature = "std")]
91pub mod replay;
92pub mod ridf;
93#[cfg(feature = "std")]
94mod tracker;
95pub mod trust;
96mod uas;
97pub mod wifi;
98
99pub use error::Error;
100pub use message::*;
101pub use pack::{MessagePack, MessagePackBuilder, PACK_MAX_MESSAGES};
102#[cfg(feature = "std")]
103pub use tracker::{CounterStats, TrackedUas, Tracker, TrackerConfig};
104pub use trust::{Assessment, Observation, Reason, TrustConfig, TrustState, Verdict};
105pub use uas::UasData;
106
107/// Who sent a frame. Receivers key aircraft by the radio address, because
108/// that is the only thing every frame of one transmitter shares before its
109/// Basic ID has been heard.
110#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
111#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
112pub enum Transmitter {
113 /// Bluetooth advertiser address.
114 Ble([u8; 6]),
115 /// Wi-Fi transmitter address.
116 Wifi([u8; 6]),
117 /// Anything else (for example a MAVLink system ID), chosen by the caller.
118 Other(u64),
119}
120
121/// The radio link a Remote ID frame arrived on.
122#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Default)]
123#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
124#[repr(u8)]
125pub enum Transport {
126 /// Not known.
127 #[default]
128 Unknown = 0,
129 /// Bluetooth 4 legacy advertising (one message per frame).
130 Bluetooth4 = 1,
131 /// Bluetooth 5 extended or long range advertising (message packs).
132 Bluetooth5 = 2,
133 /// Wi-Fi Beacon vendor element.
134 WifiBeacon = 3,
135 /// Wi-Fi NAN service discovery.
136 WifiNan = 4,
137 /// Another source chosen by the caller (for example a serial dongle).
138 Other = 5,
139}
140
141impl Transport {
142 /// All values, in code order.
143 pub const ALL: [Transport; 6] = [
144 Transport::Unknown,
145 Transport::Bluetooth4,
146 Transport::Bluetooth5,
147 Transport::WifiBeacon,
148 Transport::WifiNan,
149 Transport::Other,
150 ];
151
152 /// The numeric code used in RIDF records.
153 pub fn code(self) -> u8 {
154 self as u8
155 }
156
157 /// Inverse of [`Transport::code`]; unknown codes map to `Unknown`.
158 pub fn from_code(c: u8) -> Transport {
159 Transport::ALL
160 .get(c as usize)
161 .copied()
162 .unwrap_or(Transport::Unknown)
163 }
164
165 /// Short lower case name (`bt4`, `bt5`, `wifi_beacon`, `wifi_nan`,
166 /// `other`, `unknown`).
167 pub fn name(self) -> &'static str {
168 match self {
169 Transport::Unknown => "unknown",
170 Transport::Bluetooth4 => "bt4",
171 Transport::Bluetooth5 => "bt5",
172 Transport::WifiBeacon => "wifi_beacon",
173 Transport::WifiNan => "wifi_nan",
174 Transport::Other => "other",
175 }
176 }
177
178 /// Parses [`Transport::name`] output.
179 pub fn from_name(s: &str) -> Option<Transport> {
180 Transport::ALL.iter().copied().find(|t| t.name() == s)
181 }
182}
183
184impl core::fmt::Display for Transport {
185 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
186 f.write_str(self.name())
187 }
188}
189
190#[cfg(doctest)]
191#[doc = include_str!("../README.md")]
192struct ReadmeDoctests;
193
194#[cfg(all(doctest, feature = "std"))]
195#[doc = include_str!("../docs/integration.md")]
196struct IntegrationDoctests;
197
198/// Size in bytes of every single Remote ID message.
199pub const MESSAGE_SIZE: usize = 25;
200
201/// Protocol version this crate writes when encoding (2 = ASTM F3411-22a).
202///
203/// Decoding accepts every version: the standard keeps newer versions
204/// backward compatible, so fields added later simply read as unset.
205pub const PROTOCOL_VERSION: u8 = 2;
206
207/// A decoded Remote ID payload: either one message or a message pack.
208#[derive(Debug, Clone, PartialEq)]
209pub enum Frame<'a> {
210 /// A single 25 byte message (Bluetooth 4 legacy advertising carries these).
211 Message(Message),
212 /// A message pack (Bluetooth 5 and Wi-Fi carry these).
213 Pack(MessagePack<'a>),
214}
215
216impl<'a> Frame<'a> {
217 /// Decodes a Remote ID payload that starts with the message header byte.
218 ///
219 /// A payload whose header says "message pack" (type 0xF) is parsed as a
220 /// pack; anything else must be at least [`MESSAGE_SIZE`] bytes and is
221 /// decoded as a single message.
222 pub fn decode(payload: &'a [u8]) -> Result<Self, Error> {
223 let first = *payload.first().ok_or(Error::TooShort { need: 1, got: 0 })?;
224 if first >> 4 == 0xF {
225 MessagePack::parse(payload).map(Frame::Pack)
226 } else {
227 Message::decode(payload).map(Frame::Message)
228 }
229 }
230
231 /// Calls `f` for every message in this frame (one for a single message,
232 /// each valid one for a pack).
233 pub fn for_each_message(&self, mut f: impl FnMut(Message)) {
234 match self {
235 Frame::Message(m) => f(m.clone()),
236 Frame::Pack(p) => p.messages().filter_map(Result::ok).for_each(f),
237 }
238 }
239}