diff --git a/Cargo.lock b/Cargo.lock index b9257de..2e622a9 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -480,6 +480,12 @@ version = "0.8.11" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d6f6ff9a378485b298a5286656da665ba74413d36db0979633275d2e708145d4" +[[package]] +name = "remoteid" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "265f4316fa34247037d01a935a715e49397cbd3a2312dedc2e03e4ba31026d8b" + [[package]] name = "rustix" version = "1.1.6" @@ -523,6 +529,7 @@ dependencies = [ "insta", "miniz_oxide", "proptest", + "remoteid", "serde", "serde_json", "thiserror", diff --git a/Cargo.toml b/Cargo.toml index 9cf12b4..be3376c 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -25,6 +25,8 @@ ureq = { version = "3.5", default-features = false } sha2 = "0.10" # Raw deflate, for the bundled aircraft registry's blocks. miniz_oxide = "0.8" +# Drone Remote ID (ASTM F3411) decoding, no_std. +remoteid = { version = "0.3.2", default-features = false } insta = { version = "1", features = ["json"] } proptest = "1" diff --git a/crates/sensio-core/Cargo.toml b/crates/sensio-core/Cargo.toml index 91c0f5c..cb46c30 100644 --- a/crates/sensio-core/Cargo.toml +++ b/crates/sensio-core/Cargo.toml @@ -10,6 +10,7 @@ publish.workspace = true [dependencies] miniz_oxide.workspace = true +remoteid.workspace = true serde.workspace = true serde_json.workspace = true thiserror.workspace = true diff --git a/crates/sensio-core/src/remote_id.rs b/crates/sensio-core/src/remote_id.rs index f6b8a03..02a9218 100644 --- a/crates/sensio-core/src/remote_id.rs +++ b/crates/sensio-core/src/remote_id.rs @@ -3,27 +3,14 @@ //! 0xFFFA. A pure function of the advert's bytes, like the other advert //! formats. //! -//! Sources (all read 2026-11-09, Apache-2.0): -//! - The wrapper: Open Drone ID's Android receiver filters service data -//! under `0000fffa-0000-1000-8000-00805f9b34fb` whose first byte is the -//! application code 0x0D (`OPEN_DRONE_ID_AD_CODE`), reads a message -//! counter, then the 25-byte message, little-endian -//! (`BluetoothScanner.java`, `OpenDroneIdParser.java`, github.com/opendroneid/receiver-android). -//! - The messages: `opendroneid.h` and `opendroneid.c`, github.com/opendroneid/opendroneid-core-c: -//! the header byte's high nibble is the message type (Basic ID 0, Location -//! 1, System 4, Operator ID 5, Message Pack 0xF), and the field offsets, -//! scalings and invalid values below. +//! The decoding is the `remoteid` crate's (MIT, `no_std`, no dependencies), +//! which follows `opendroneid-core-c` field for field and checks message +//! packs by the reference library's rules. This module maps its messages to +//! what the describe layer reads. //! //! Authentication and Self ID messages (free text an operator types) aren't //! read. -/// The application code that opens Open Drone ID's service data. -const APP_CODE: u8 = 0x0d; -/// Every message's size, bytes. -const MESSAGE_SIZE: usize = 25; -/// The most messages in a pack. -const MAX_PACK: usize = 9; - /// One Remote ID message, as far as the describe layer reads it. #[derive(Debug, Clone, PartialEq)] pub(crate) enum Message { @@ -76,101 +63,60 @@ pub(crate) enum Message { /// Remote ID. `uuid` is the entry's 16-bit UUID, lowercase, and `data` the /// bytes after it. pub(crate) fn messages(uuid: &str, data: &[u8]) -> Option> { - if uuid != "fffa" || data.first() != Some(&APP_CODE) { + if uuid != "fffa" { return None; } - // After the application code and the message counter. - let body = data.get(2..)?; - let first = body.get(..MESSAGE_SIZE)?; - if first[0] >> 4 == 0xf { - // A pack: the message size, the count, then the messages. - let (&size, &count) = (body.get(1)?, body.get(2)?); - if usize::from(size) != MESSAGE_SIZE || usize::from(count) > MAX_PACK { - return Some(Vec::new()); - } - let packed = body.get(3..3 + usize::from(count) * MESSAGE_SIZE)?; - return Some( - packed - .chunks_exact(MESSAGE_SIZE) - .filter_map(message) - .collect(), - ); - } - Some(message(first).into_iter().collect()) + let frame = match remoteid::ble::parse_service_data(data).ok()?.frame() { + Ok(frame) => frame, + Err(remoteid::Error::TooShort { .. }) => return None, + // Remote ID, but a pack the reference library rejects. + Err(_) => return Some(Vec::new()), + }; + let mut out = Vec::new(); + frame.for_each_message(|m| out.extend(message(m))); + Some(out) } -/// One 25-byte message, or none for a type that isn't read. -fn message(m: &[u8]) -> Option { - match m.first()? >> 4 { - 0 => Some(Message::BasicId { - id_type: m.get(1)? >> 4, - ua_type: m.get(1)? & 0x0f, - uas_id: text(m.get(2..22)?), +/// One decoded message, or none for a type that isn't read. +fn message(m: remoteid::Message) -> Option { + use remoteid::Message as M; + match m { + M::BasicId(b) => Some(Message::BasicId { + id_type: b.id_type.into(), + ua_type: b.ua_type.into(), + uas_id: text(b.uas_id_str()), + }), + M::Location(l) => Some(Message::Location { + status: Some(u8::from(l.status)).filter(|s| *s <= 4), + direction_deg: l.direction.filter(|d| *d < 360.0).map(f64::from), + speed_mps: l.speed_horizontal.map(f64::from), + vertical_speed_mps: l.speed_vertical.map(f64::from), + position: in_range(l.position()), + alt_baro_m: l.altitude_baro.map(f64::from), + alt_geo_m: l.altitude_geo.map(f64::from), + height_m: l.height.map(f64::from), }), - 1 => location(m), - 4 => Some(Message::System { - operator_location_type: m.get(1)? & 0x03, - operator_position: position(m.get(2..6)?, m.get(6..10)?), - operator_alt_geo_m: altitude(m.get(18..20)?), + M::System(s) => Some(Message::System { + operator_location_type: s.operator_location_type.into(), + operator_position: in_range(s.operator_position()), + operator_alt_geo_m: s.operator_altitude_geo.map(f64::from), }), - 5 => Some(Message::OperatorId { - operator_id: text(m.get(2..22)?), + M::OperatorId(o) => Some(Message::OperatorId { + operator_id: text(o.operator_id_str()), }), _ => None, } } -fn location(m: &[u8]) -> Option { - let flags = *m.get(1)?; - let status = Some(flags >> 4).filter(|s| *s <= 4); - let direction = u16::from(*m.get(2)?) + if flags & 0x02 != 0 { 180 } else { 0 }; - let speed = *m.get(3)?; - let speed_mps = (speed != 255).then(|| { - if flags & 0x01 == 0 { - f64::from(speed) * 0.25 - } else { - f64::from(speed).mul_add(0.75, 63.75) - } - }); - let vertical = i8::from_le_bytes([*m.get(4)?]); - Some(Message::Location { - status, - direction_deg: (direction < 360).then(|| f64::from(direction)), - speed_mps, - // 63 m/s is the encoding's own "unknown". - vertical_speed_mps: (vertical != 126).then(|| f64::from(vertical) * 0.5), - position: position(m.get(5..9)?, m.get(9..13)?), - alt_baro_m: altitude(m.get(13..15)?), - alt_geo_m: altitude(m.get(15..17)?), - height_m: altitude(m.get(17..19)?), - }) +/// A position, none when either coordinate is out of range. +fn in_range(p: Option<(f64, f64)>) -> Option<(f64, f64)> { + p.filter(|(lat, lon)| (-90.0..=90.0).contains(lat) && (-180.0..=180.0).contains(lon)) } -/// A latitude and longitude, each int32 x 1e-7 degrees; none when both are 0 -/// (the encoding's "invalid") or either is out of range. -fn position(lat: &[u8], lon: &[u8]) -> Option<(f64, f64)> { - let int = |b: &[u8]| Some(i32::from_le_bytes(b.try_into().ok()?)); - let (lat, lon) = (int(lat)?, int(lon)?); - if lat == 0 && lon == 0 { - return None; - } - let (lat, lon) = (f64::from(lat) * 1e-7, f64::from(lon) * 1e-7); - ((-90.0..=90.0).contains(&lat) && (-180.0..=180.0).contains(&lon)).then_some((lat, lon)) -} - -/// An altitude, uint16 x 0.5 - 1000 meters; none for 0, the encoding's -/// "invalid" (-1000 m). -fn altitude(b: &[u8]) -> Option { - let raw = u16::from_le_bytes(b.try_into().ok()?); - (raw != 0).then(|| f64::from(raw).mul_add(0.5, -1000.0)) -} - -/// An ID field: printable ASCII up to its first NUL, trimmed; none when that -/// leaves nothing or holds anything else. -fn text(b: &[u8]) -> Option { - let end = b.iter().position(|&c| c == 0).unwrap_or(b.len()); - let s = std::str::from_utf8(b.get(..end)?).ok()?.trim(); - (!s.is_empty() && s.bytes().all(|c| c.is_ascii_graphic() || c == b' ')).then(|| s.to_owned()) +/// An ID field, trimmed; none when that leaves nothing. +fn text(s: Option<&str>) -> Option { + let s = s?.trim(); + (!s.is_empty()).then(|| s.to_owned()) } #[cfg(test)] @@ -210,4 +156,14 @@ mod tests { "a message cut short" ); } + + #[test] + fn a_pack_with_two_locations_is_rejected() { + let mut location = [0u8; 25]; + location[0] = 0x12; // Location, protocol 2. + let mut pack = vec![0xf2, 25, 2]; + pack.extend_from_slice(&location); + pack.extend_from_slice(&location); + assert_eq!(messages("fffa", &wrap(&pack)), Some(Vec::new())); + } }