Skip to main content

uas_cot/
rid.rs

1//! Remote ID (ASTM F3411, ASD-STAN EN 4709-002) to CoT, using the
2//! [`remoteid`] crate's merged per-aircraft record ([`remoteid::UasData`],
3//! as kept by [`remoteid::Tracker`]).
4//!
5//! ```
6//! use remoteid::{BasicId, IdType, Location, Message, UaType, UasData};
7//! use uas_cot::rid::{self, Options};
8//!
9//! let mut uas = UasData::default();
10//! let id = BasicId::new(IdType::SerialNumber, UaType::HelicopterOrMultirotor, "1596F35074529ABCDEFG").unwrap();
11//! uas.update(&Message::BasicId(id));
12//! let mut loc = Location::default();
13//! loc.latitude = 45.5470818;
14//! loc.longitude = -122.9668346;
15//! loc.altitude_geo = Some(237.0);
16//! uas.update(&Message::Location(loc));
17//!
18//! let e = rid::aircraft(&uas, None, 1_700_000_000_000_000, &Options::default()).unwrap();
19//! assert_eq!(e.uid, "rid-1596F35074529ABCDEFG");
20//! assert_eq!(e.kind, "a-u-A-M-F-Q");
21//! assert_eq!(e.point.hae, 237.0);
22//! ```
23
24use crate::{Event, Point, Track, UNKNOWN_ERROR};
25use remoteid::{UaType, UasData};
26use std::fmt::Write as _;
27
28/// How Remote ID records become events.
29#[derive(Clone, Debug, PartialEq)]
30pub struct Options {
31    /// Affiliation letter in the CoT type: `'u'` unknown (default), `'n'`
32    /// neutral, `'f'` friend, `'a'` assumed friend, `'s'` suspect, `'h'` hostile.
33    pub affiliation: char,
34    /// Seconds until the marker goes stale. Remote ID broadcasts at 1 Hz or
35    /// faster, so the default is 30.
36    pub stale_secs: u64,
37    /// Prefix of the event UID (default `"rid-"`).
38    pub uid_prefix: String,
39}
40
41impl Default for Options {
42    fn default() -> Self {
43        Options {
44            affiliation: 'u',
45            stale_secs: 30,
46            uid_prefix: "rid-".into(),
47        }
48    }
49}
50
51/// The CoT type for an aircraft category: powered aircraft are drones
52/// (`a-?-A-M-F-Q`, the MIL-STD-2525 "drone" function), lighter-than-air
53/// craft are `a-?-A-C-L`, everything else is a generic air track `a-?-A`.
54pub fn aircraft_type(ua: UaType, affiliation: char) -> String {
55    let tail = match ua {
56        UaType::FreeBalloon | UaType::CaptiveBalloon | UaType::Airship => "A-C-L",
57        UaType::None
58        | UaType::Aeroplane
59        | UaType::HelicopterOrMultirotor
60        | UaType::Gyroplane
61        | UaType::HybridLift
62        | UaType::Ornithopter
63        | UaType::Glider
64        | UaType::TetheredPoweredAircraft => "A-M-F-Q",
65        _ => "A",
66    };
67    format!("a-{affiliation}-{tail}")
68}
69
70fn ua_type(data: &UasData) -> UaType {
71    data.basic_id
72        .iter()
73        .flatten()
74        .map(|b| b.ua_type)
75        .find(|t| *t != UaType::None)
76        .unwrap_or(UaType::None)
77}
78
79fn id_or<'a>(data: &'a UasData, fallback: Option<&'a str>) -> Option<&'a str> {
80    data.primary_id().or(fallback).filter(|s| !s.is_empty())
81}
82
83/// The aircraft as an event, or `None` without a valid position or an id.
84///
85/// The UID is the prefix plus the first Basic ID (serial number,
86/// registration ...), or `fallback_id` (for example the radio address)
87/// when the aircraft has not sent a Basic ID yet. Height is the geodetic
88/// altitude when sent, else the pressure altitude.
89pub fn aircraft(
90    data: &UasData,
91    fallback_id: Option<&str>,
92    now_us: u64,
93    opts: &Options,
94) -> Option<Event> {
95    let id = id_or(data, fallback_id)?;
96    let loc = data.location.as_ref()?;
97    let (lat, lon) = loc.position()?;
98    let mut point = Point::new(lat, lon, 0.0);
99    if !point.is_valid() {
100        return None;
101    }
102    let mut altsrc = "UNKNOWN";
103    if let Some(h) = loc.altitude_geo {
104        point.hae = h as f64;
105        altsrc = "GPS";
106    } else if let Some(h) = loc.altitude_baro {
107        point.hae = h as f64;
108        altsrc = "BARO";
109    }
110    point.ce = loc
111        .horizontal_accuracy
112        .meters()
113        .map_or(UNKNOWN_ERROR, f64::from);
114    point.le = loc
115        .vertical_accuracy
116        .meters()
117        .map_or(UNKNOWN_ERROR, f64::from);
118
119    let mut e = Event::new(
120        format!("{}{id}", opts.uid_prefix),
121        aircraft_type(ua_type(data), opts.affiliation),
122        now_us,
123        opts.stale_secs,
124    );
125    e.point = point;
126    e.callsign = Some(id.to_string());
127    e.precision_location = Some(("GPS".into(), altsrc.into()));
128    if let (Some(course), Some(speed)) = (loc.direction, loc.speed_horizontal) {
129        e.track = Some(Track {
130            course: course as f64,
131            speed: speed as f64,
132        });
133    }
134    let mut r = format!(
135        "Remote ID. UA type: {:?}. Status: {:?}.",
136        ua_type(data),
137        loc.status
138    );
139    if let Some(h) = loc.height {
140        let _ = write!(r, " Height: {h:.1} m ({:?}).", loc.height_type);
141    }
142    if let Some(v) = loc.speed_vertical {
143        let _ = write!(r, " Vertical speed: {v:.1} m/s.");
144    }
145    if let Some(op) = data
146        .operator_id
147        .as_ref()
148        .and_then(|o| o.operator_id_str())
149        .filter(|s| !s.is_empty())
150    {
151        let _ = write!(r, " Operator ID: {op}.");
152    }
153    if let Some(d) = data
154        .self_id
155        .as_ref()
156        .and_then(|s| s.description_str())
157        .filter(|s| !s.is_empty())
158    {
159        let _ = write!(r, " Self ID: {d}.");
160    }
161    e.remarks = Some(r);
162    Some(e)
163}
164
165/// The operator (or takeoff point) from the System message, as a spot
166/// marker `b-m-p-s-m`, or `None` when the System message has no position.
167pub fn operator(
168    data: &UasData,
169    fallback_id: Option<&str>,
170    now_us: u64,
171    opts: &Options,
172) -> Option<Event> {
173    let id = id_or(data, fallback_id)?;
174    let sys = data.system.as_ref()?;
175    let (lat, lon) = sys.operator_position()?;
176    let mut point = Point::new(lat, lon, sys.operator_altitude_geo.map_or(0.0, f64::from));
177    if !point.is_valid() {
178        return None;
179    }
180    point.ce = UNKNOWN_ERROR;
181    let mut e = Event::new(
182        format!("{}op-{id}", opts.uid_prefix),
183        "b-m-p-s-m",
184        now_us,
185        opts.stale_secs,
186    );
187    e.point = point;
188    let op = data
189        .operator_id
190        .as_ref()
191        .and_then(|o| o.operator_id_str())
192        .filter(|s| !s.is_empty());
193    e.callsign = Some(match op {
194        Some(op) => format!("{op} (operator of {id})"),
195        None => format!("Operator of {id}"),
196    });
197    e.remarks = Some(format!(
198        "Remote ID operator location ({:?}).",
199        sys.operator_location_type
200    ));
201    Some(e)
202}
203
204/// Both events for one aircraft (aircraft first), skipping the ones that
205/// cannot be built yet.
206pub fn events(
207    data: &UasData,
208    fallback_id: Option<&str>,
209    now_us: u64,
210    opts: &Options,
211) -> Vec<Event> {
212    aircraft(data, fallback_id, now_us, opts)
213        .into_iter()
214        .chain(operator(data, fallback_id, now_us, opts))
215        .collect()
216}