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//!
24//! With a [`remoteid::Tracker`], [`tracked`] also writes the transmitter's
25//! trust verdict (spoofed, suspicious, plausible, authenticated) and its
26//! reasons into the aircraft's remarks, so a TAK user sees why a marker
27//! should not be believed.
28
29use crate::{Event, Point, Track, UNKNOWN_ERROR};
30use remoteid::{Assessment, TrackedUas, UaType, UasData};
31use std::fmt::Write as _;
32
33/// How Remote ID records become events.
34#[derive(Clone, Debug, PartialEq)]
35pub struct Options {
36    /// Affiliation letter in the CoT type: `'u'` unknown (default), `'n'`
37    /// neutral, `'f'` friend, `'a'` assumed friend, `'s'` suspect, `'h'` hostile.
38    pub affiliation: char,
39    /// Seconds until the marker goes stale. Remote ID broadcasts at 1 Hz or
40    /// faster, so the default is 30.
41    pub stale_secs: u64,
42    /// Prefix of the event UID (default `"rid-"`).
43    pub uid_prefix: String,
44}
45
46impl Default for Options {
47    fn default() -> Self {
48        Options {
49            affiliation: 'u',
50            stale_secs: 30,
51            uid_prefix: "rid-".into(),
52        }
53    }
54}
55
56/// The CoT type for an aircraft category: powered aircraft are drones
57/// (`a-?-A-M-F-Q`, the MIL-STD-2525 "drone" function), lighter-than-air
58/// craft are `a-?-A-C-L`, everything else is a generic air track `a-?-A`.
59pub fn aircraft_type(ua: UaType, affiliation: char) -> String {
60    let tail = match ua {
61        UaType::FreeBalloon | UaType::CaptiveBalloon | UaType::Airship => "A-C-L",
62        UaType::None
63        | UaType::Aeroplane
64        | UaType::HelicopterOrMultirotor
65        | UaType::Gyroplane
66        | UaType::HybridLift
67        | UaType::Ornithopter
68        | UaType::Glider
69        | UaType::TetheredPoweredAircraft => "A-M-F-Q",
70        _ => "A",
71    };
72    format!("a-{affiliation}-{tail}")
73}
74
75fn ua_type(data: &UasData) -> UaType {
76    data.basic_id
77        .iter()
78        .flatten()
79        .map(|b| b.ua_type)
80        .find(|t| *t != UaType::None)
81        .unwrap_or(UaType::None)
82}
83
84fn id_or<'a>(data: &'a UasData, fallback: Option<&'a str>) -> Option<&'a str> {
85    data.primary_id().or(fallback).filter(|s| !s.is_empty())
86}
87
88/// The aircraft as an event, or `None` without a valid position or an id.
89///
90/// The UID is the prefix plus the first Basic ID (serial number,
91/// registration ...), or `fallback_id` (for example the radio address)
92/// when the aircraft has not sent a Basic ID yet. Height is the geodetic
93/// altitude when sent, else the pressure altitude.
94pub fn aircraft(
95    data: &UasData,
96    fallback_id: Option<&str>,
97    now_us: u64,
98    opts: &Options,
99) -> Option<Event> {
100    let id = id_or(data, fallback_id)?;
101    let loc = data.location.as_ref()?;
102    let (lat, lon) = loc.position()?;
103    let mut point = Point::new(lat, lon, 0.0);
104    if !point.is_valid() {
105        return None;
106    }
107    let mut altsrc = "UNKNOWN";
108    if let Some(h) = loc.altitude_geo {
109        point.hae = h as f64;
110        altsrc = "GPS";
111    } else if let Some(h) = loc.altitude_baro {
112        point.hae = h as f64;
113        altsrc = "BARO";
114    }
115    point.ce = loc
116        .horizontal_accuracy
117        .meters()
118        .map_or(UNKNOWN_ERROR, f64::from);
119    point.le = loc
120        .vertical_accuracy
121        .meters()
122        .map_or(UNKNOWN_ERROR, f64::from);
123
124    let mut e = Event::new(
125        format!("{}{id}", opts.uid_prefix),
126        aircraft_type(ua_type(data), opts.affiliation),
127        now_us,
128        opts.stale_secs,
129    );
130    e.point = point;
131    e.callsign = Some(id.to_string());
132    e.precision_location = Some(("GPS".into(), altsrc.into()));
133    if let (Some(course), Some(speed)) = (loc.direction, loc.speed_horizontal) {
134        e.track = Some(Track {
135            course: course as f64,
136            speed: speed as f64,
137        });
138    }
139    let mut r = format!(
140        "Remote ID. UA type: {:?}. Status: {:?}.",
141        ua_type(data),
142        loc.status
143    );
144    if let Some(h) = loc.height {
145        let _ = write!(r, " Height: {h:.1} m ({:?}).", loc.height_type);
146    }
147    if let Some(v) = loc.speed_vertical {
148        let _ = write!(r, " Vertical speed: {v:.1} m/s.");
149    }
150    if let Some(op) = data
151        .operator_id
152        .as_ref()
153        .and_then(|o| o.operator_id_str())
154        .filter(|s| !s.is_empty())
155    {
156        let _ = write!(r, " Operator ID: {op}.");
157    }
158    if let Some(d) = data
159        .self_id
160        .as_ref()
161        .and_then(|s| s.description_str())
162        .filter(|s| !s.is_empty())
163    {
164        let _ = write!(r, " Self ID: {d}.");
165    }
166    e.remarks = Some(r);
167    Some(e)
168}
169
170/// The operator (or takeoff point) from the System message, as a spot
171/// marker `b-m-p-s-m`, or `None` when the System message has no position.
172pub fn operator(
173    data: &UasData,
174    fallback_id: Option<&str>,
175    now_us: u64,
176    opts: &Options,
177) -> Option<Event> {
178    let id = id_or(data, fallback_id)?;
179    let sys = data.system.as_ref()?;
180    let (lat, lon) = sys.operator_position()?;
181    let mut point = Point::new(lat, lon, sys.operator_altitude_geo.map_or(0.0, f64::from));
182    if !point.is_valid() {
183        return None;
184    }
185    point.ce = UNKNOWN_ERROR;
186    let mut e = Event::new(
187        format!("{}op-{id}", opts.uid_prefix),
188        "b-m-p-s-m",
189        now_us,
190        opts.stale_secs,
191    );
192    e.point = point;
193    let op = data
194        .operator_id
195        .as_ref()
196        .and_then(|o| o.operator_id_str())
197        .filter(|s| !s.is_empty());
198    e.callsign = Some(match op {
199        Some(op) => format!("{op} (operator of {id})"),
200        None => format!("Operator of {id}"),
201    });
202    e.remarks = Some(format!(
203        "Remote ID operator location ({:?}).",
204        sys.operator_location_type
205    ));
206    Some(e)
207}
208
209/// Both events for one aircraft (aircraft first), skipping the ones that
210/// cannot be built yet.
211pub fn events(
212    data: &UasData,
213    fallback_id: Option<&str>,
214    now_us: u64,
215    opts: &Options,
216) -> Vec<Event> {
217    aircraft(data, fallback_id, now_us, opts)
218        .into_iter()
219        .chain(operator(data, fallback_id, now_us, opts))
220        .collect()
221}
222
223/// The trust verdict as one remarks sentence, for example
224/// `Trust: spoofed (teleport, known_spoofer; tool: jjshoots/RemoteIDSpoofer).`
225/// or `Trust: plausible.` when nothing contradicts the broadcast.
226pub fn trust_remarks(a: &Assessment) -> String {
227    let mut r = format!("Trust: {}", a.verdict.name());
228    let reasons: Vec<&str> = a.reasons.iter().map(|x| x.name()).collect();
229    if !reasons.is_empty() || a.spoofer.is_some() {
230        r.push_str(" (");
231        r.push_str(&reasons.join(", "));
232        if let Some(t) = a.spoofer {
233            if !reasons.is_empty() {
234                r.push_str("; ");
235            }
236            let _ = write!(r, "tool: {}", t.name());
237        }
238        r.push(')');
239    }
240    r.push('.');
241    r
242}
243
244/// [`events`] for a transmitter kept by [`remoteid::Tracker`], with
245/// [`trust_remarks`] for its latest assessment appended to the aircraft's
246/// remarks. Markers and UIDs are the same as from [`events`]; the
247/// affiliation stays `opts.affiliation`, so a caller who wants spoofed
248/// aircraft drawn as suspect sets it from `uas.assessment.verdict`.
249///
250/// ```
251/// use uas_cot::remoteid::{BasicId, IdType, Location, Message, Tracker, Transmitter, UaType};
252/// use uas_cot::rid::{self, Options};
253///
254/// let mut tracker = Tracker::default();
255/// let tx = Transmitter::Ble([0xAA, 0xBB, 0xCC, 0xDD, 0xEE, 0xFF]);
256/// let id = BasicId::new(IdType::SerialNumber, UaType::HelicopterOrMultirotor, "1596F35074529ABCDEFG").unwrap();
257/// let mut loc = Location::default();
258/// loc.latitude = 45.5470818;
259/// loc.longitude = -122.9668346;
260/// tracker.ingest(tx, 1, &Message::BasicId(id).encode().unwrap(), 1_000);
261/// let uas = tracker.ingest(tx, 2, &Message::Location(loc).encode().unwrap(), 1_100);
262///
263/// let events = rid::tracked(uas, None, 1_100_000, &Options::default());
264/// assert!(events[0].remarks.as_deref().unwrap().ends_with("Trust: plausible."));
265/// ```
266pub fn tracked(
267    uas: &TrackedUas,
268    fallback_id: Option<&str>,
269    now_us: u64,
270    opts: &Options,
271) -> Vec<Event> {
272    let mut out = events(&uas.data, fallback_id, now_us, opts);
273    if let Some(air) = out.first_mut().filter(|e| e.kind.starts_with("a-")) {
274        let t = trust_remarks(&uas.assessment);
275        air.remarks = Some(match air.remarks.take() {
276            Some(r) => format!("{r} {t}"),
277            None => t,
278        });
279    }
280    out
281}