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, Link, Point, Track, UNKNOWN_ERROR};
30use remoteid::{Assessment, OperatorLocationType, TrackedUas, UaType, UasData, Verdict};
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}
282
283/// The ground marker from the System message, labelled by what the position
284/// is. Remote ID sends one ground position and a type that says whether it
285/// is the operator's live GNSS fix, a fixed operator location, or the
286/// takeoff point. [`operator`] calls all three "Operator of ...", which
287/// sends a security team to where the aircraft left from, not to where the
288/// pilot stands. This one keeps them apart:
289///
290/// | Location type | UID | Callsign |
291/// |---|---|---|
292/// | live GNSS | `<prefix>op-<id>` | `Operator of <id>` |
293/// | fixed | `<prefix>op-<id>` | `Operator of <id> (fixed location)` |
294/// | takeoff | `<prefix>takeoff-<id>` | `Takeoff point of <id>` |
295///
296/// A takeoff marker is a separate entity on the TAK map: if the drone later
297/// switches to live operator location, the operator marker appears next to
298/// it instead of moving the takeoff marker.
299///
300/// ```
301/// use uas_cot::remoteid::{BasicId, IdType, Message, OperatorLocationType, System, UaType, UasData};
302/// use uas_cot::rid::{self, Options};
303///
304/// let mut uas = UasData::default();
305/// let id = BasicId::new(IdType::SerialNumber, UaType::HelicopterOrMultirotor, "1596F35074529ABCDEFG").unwrap();
306/// uas.update(&Message::BasicId(id));
307/// let mut sys = System::default();
308/// sys.operator_location_type = OperatorLocationType::Takeoff;
309/// sys.operator_latitude = 45.5470;
310/// sys.operator_longitude = -122.9668;
311/// uas.update(&Message::System(sys));
312///
313/// let e = rid::operator_or_takeoff(&uas, None, 1_700_000_000_000_000, &Options::default()).unwrap();
314/// assert_eq!(e.uid, "rid-takeoff-1596F35074529ABCDEFG");
315/// assert_eq!(e.callsign.as_deref(), Some("Takeoff point of 1596F35074529ABCDEFG"));
316/// ```
317pub fn operator_or_takeoff(
318    data: &UasData,
319    fallback_id: Option<&str>,
320    now_us: u64,
321    opts: &Options,
322) -> Option<Event> {
323    let mut e = operator(data, fallback_id, now_us, opts)?;
324    let id = id_or(data, fallback_id)?;
325    let sys = data.system.as_ref()?;
326    let op = data
327        .operator_id
328        .as_ref()
329        .and_then(|o| o.operator_id_str())
330        .filter(|s| !s.is_empty());
331    match sys.operator_location_type {
332        OperatorLocationType::Takeoff => {
333            e.uid = format!("{}takeoff-{id}", opts.uid_prefix);
334            e.callsign = Some(match op {
335                Some(op) => format!("Takeoff point of {id} (operator {op})"),
336                None => format!("Takeoff point of {id}"),
337            });
338            e.remarks = Some(
339                "Remote ID takeoff point. Not a live operator position: the aircraft \
340                 does not broadcast where its pilot is."
341                    .into(),
342            );
343        }
344        OperatorLocationType::Fixed => {
345            e.callsign = Some(match op {
346                Some(op) => format!("{op} (operator of {id}, fixed location)"),
347                None => format!("Operator of {id} (fixed location)"),
348            });
349            e.remarks =
350                Some("Remote ID operator location (fixed, entered by the operator).".into());
351        }
352        OperatorLocationType::LiveGnss => {
353            e.remarks = Some("Remote ID operator location (live GNSS).".into());
354        }
355        OperatorLocationType::Other(v) => {
356            e.remarks = Some(format!(
357                "Remote ID operator location (reserved location type {v})."
358            ));
359        }
360    }
361    Some(e)
362}
363
364/// How a tracked transmitter's affiliation (the second letter of the CoT
365/// type, `a-?-...`) is chosen from its trust verdict and from a list of
366/// your own aircraft.
367///
368/// The order matters and is fixed:
369///
370/// 1. A `spoofed` verdict gives [`spoofed`](Self::spoofed) (default `'s'`,
371///    suspect), and a `suspicious` verdict gives
372///    [`suspicious`](Self::suspicious) (default: no change). This comes
373///    before the friendly list on purpose: a spoofer that copies the serial
374///    number of one of your drones must not turn into a friendly marker.
375/// 2. A Basic ID or Operator ID in [`friendly_ids`](Self::friendly_ids)
376///    gives [`friendly`](Self::friendly) (default `'f'`), unless the
377///    verdict is `spoofed` or `suspicious`. With
378///    [`friendly_requires_authenticated`](Self::friendly_requires_authenticated)
379///    only an `authenticated` (DRIP signed) transmitter qualifies.
380/// 3. An `authenticated` verdict gives
381///    [`authenticated`](Self::authenticated) (default: no change).
382/// 4. Otherwise the default passed in ([`Options::affiliation`]).
383///
384/// ```
385/// use uas_cot::rid::AffiliationRules;
386///
387/// let rules = AffiliationRules::default()
388///     .friendly_id("1596F35074529ABCDEFG")
389///     .suspicious_as('s')
390///     .spoofed_as('h');
391/// assert_eq!(rules.friendly_ids, ["1596F35074529ABCDEFG"]);
392/// ```
393#[derive(Clone, Debug, PartialEq, Eq)]
394#[non_exhaustive]
395pub struct AffiliationRules {
396    /// Basic IDs (serial numbers, registrations, session IDs) and Operator
397    /// IDs of your own aircraft. Matched exactly, after trimming spaces.
398    pub friendly_ids: Vec<String>,
399    /// Affiliation for a match in `friendly_ids` (default `'f'`).
400    pub friendly: char,
401    /// Only an `authenticated` transmitter counts as friendly (default false:
402    /// most drones do not sign their broadcasts yet).
403    pub friendly_requires_authenticated: bool,
404    /// Affiliation for a `spoofed` verdict (default `Some('s')`, suspect).
405    pub spoofed: Option<char>,
406    /// Affiliation for a `suspicious` verdict (default `None`: unchanged).
407    pub suspicious: Option<char>,
408    /// Affiliation for an `authenticated` verdict that is not on the
409    /// friendly list (default `None`: unchanged).
410    pub authenticated: Option<char>,
411}
412
413impl Default for AffiliationRules {
414    fn default() -> Self {
415        AffiliationRules {
416            friendly_ids: Vec::new(),
417            friendly: 'f',
418            friendly_requires_authenticated: false,
419            spoofed: Some('s'),
420            suspicious: None,
421            authenticated: None,
422        }
423    }
424}
425
426impl AffiliationRules {
427    /// Adds one of your aircraft (Basic ID or Operator ID).
428    pub fn friendly_id(mut self, id: impl Into<String>) -> Self {
429        self.friendly_ids.push(id.into().trim().to_string());
430        self
431    }
432
433    /// Sets [`friendly`](Self::friendly).
434    pub fn friendly_as(mut self, affiliation: char) -> Self {
435        self.friendly = affiliation;
436        self
437    }
438
439    /// Sets [`friendly_requires_authenticated`](Self::friendly_requires_authenticated).
440    pub fn require_authenticated_friendly(mut self, yes: bool) -> Self {
441        self.friendly_requires_authenticated = yes;
442        self
443    }
444
445    /// Sets [`spoofed`](Self::spoofed).
446    pub fn spoofed_as(mut self, affiliation: char) -> Self {
447        self.spoofed = Some(affiliation);
448        self
449    }
450
451    /// Sets [`suspicious`](Self::suspicious).
452    pub fn suspicious_as(mut self, affiliation: char) -> Self {
453        self.suspicious = Some(affiliation);
454        self
455    }
456
457    /// Sets [`authenticated`](Self::authenticated).
458    pub fn authenticated_as(mut self, affiliation: char) -> Self {
459        self.authenticated = Some(affiliation);
460        self
461    }
462
463    /// Clears every verdict rule, so a verdict never changes the
464    /// affiliation; only the friendly list applies (still not to a
465    /// `spoofed` or `suspicious` transmitter).
466    pub fn no_verdict_rules(mut self) -> Self {
467        self.spoofed = None;
468        self.suspicious = None;
469        self.authenticated = None;
470        self
471    }
472
473    fn is_friendly(&self, data: &UasData) -> bool {
474        if self.friendly_ids.is_empty() {
475            return false;
476        }
477        let listed = |s: &str| {
478            let s = s.trim();
479            !s.is_empty() && self.friendly_ids.iter().any(|f| f == s)
480        };
481        data.basic_id
482            .iter()
483            .flatten()
484            .filter_map(|b| b.uas_id_str())
485            .any(listed)
486            || data
487                .operator_id
488                .as_ref()
489                .and_then(|o| o.operator_id_str())
490                .is_some_and(listed)
491    }
492
493    /// The affiliation for `uas`, or `default` when no rule applies.
494    pub fn affiliation(&self, uas: &TrackedUas, default: char) -> char {
495        let verdict = uas.assessment.verdict;
496        let trusted = match verdict {
497            Verdict::Spoofed => return self.spoofed.unwrap_or(default),
498            Verdict::Suspicious => return self.suspicious.unwrap_or(default),
499            Verdict::Authenticated => true,
500            Verdict::Plausible => !self.friendly_requires_authenticated,
501        };
502        if trusted && self.is_friendly(&uas.data) {
503            return self.friendly;
504        }
505        match (verdict, self.authenticated) {
506            (Verdict::Authenticated, Some(c)) => c,
507            _ => default,
508        }
509    }
510}
511
512/// Like [`tracked`], with two differences: the aircraft's affiliation comes
513/// from `rules` (see [`AffiliationRules`]), and the ground marker comes from
514/// [`operator_or_takeoff`], so a takeoff point is not labelled as the
515/// operator. Aircraft first, then the ground marker.
516///
517/// ```
518/// use uas_cot::remoteid::{BasicId, IdType, Location, Message, Tracker, Transmitter, UaType};
519/// use uas_cot::rid::{self, AffiliationRules, Options};
520///
521/// let mut tracker = Tracker::default();
522/// let tx = Transmitter::Ble([0xAA, 0xBB, 0xCC, 0xDD, 0xEE, 0xFF]);
523/// let id = BasicId::new(IdType::SerialNumber, UaType::HelicopterOrMultirotor, "1596F35074529ABCDEFG").unwrap();
524/// let mut loc = Location::default();
525/// loc.latitude = 45.5470818;
526/// loc.longitude = -122.9668346;
527/// tracker.ingest(tx, 1, &Message::BasicId(id).encode().unwrap(), 1_000);
528/// let uas = tracker.ingest(tx, 2, &Message::Location(loc).encode().unwrap(), 1_100);
529///
530/// let rules = AffiliationRules::default().friendly_id("1596F35074529ABCDEFG");
531/// let events = rid::tracked_with(uas, None, 1_100_000, &Options::default(), &rules);
532/// assert_eq!(events[0].kind, "a-f-A-M-F-Q");
533/// ```
534pub fn tracked_with(
535    uas: &TrackedUas,
536    fallback_id: Option<&str>,
537    now_us: u64,
538    opts: &Options,
539    rules: &AffiliationRules,
540) -> Vec<Event> {
541    let air_opts = Options {
542        affiliation: rules.affiliation(uas, opts.affiliation),
543        ..opts.clone()
544    };
545    let mut out = Vec::with_capacity(2);
546    if let Some(mut air) = aircraft(&uas.data, fallback_id, now_us, &air_opts) {
547        let t = trust_remarks(&uas.assessment);
548        air.remarks = Some(match air.remarks.take() {
549            Some(r) => format!("{r} {t}"),
550            None => t,
551        });
552        out.push(air);
553    }
554    out.extend(operator_or_takeoff(&uas.data, fallback_id, now_us, opts));
555    out
556}
557
558/// The manufacturer code of the aircraft's serial number, when its first
559/// Basic ID is an ANSI/CTA-2063-A physical serial number. This is the four
560/// character code ICAO assigns to the maker that built the airframe, decoded
561/// from the serial the aircraft itself broadcast, not a guess from a lookup
562/// table. `None` for a CAA registration, a session id, or any Basic ID that
563/// is not a well formed CTA-2063-A serial.
564pub fn manufacturer_code(data: &UasData) -> Option<&str> {
565    data.basic_id
566        .iter()
567        .flatten()
568        .find_map(|b| b.serial_number())
569        .map(|s| s.manufacturer_code)
570}
571
572/// A one line, plain language headline for the top of a tracked aircraft's
573/// remarks, so an operator reads what the marker is, whether to believe it,
574/// where it launched, and (when a camera ground target is supplied) what it
575/// is filming, without decoding the CoT type or scrolling the detail.
576///
577/// For example, for a plausible multirotor whose serial carries the maker
578/// code `1596`, broadcasting a takeoff point, with a correlated video frame
579/// center:
580///
581/// `HelicopterOrMultirotor 1596F35074529ABCDEFG (maker code 1596 per
582/// CTA-2063-A). Trust: PLAUSIBLE. Launched 45.544388, -122.972687. Camera on
583/// 38.895000, -77.030000.`
584///
585/// Every field is from the broadcast (or, for the camera point, from the
586/// caller): the maker code is decoded from the serial the aircraft sent, the
587/// verdict is the [`remoteid`] assessment, the launch point is the System
588/// message ground position. Nothing is invented.
589pub fn headline(uas: &TrackedUas, camera: Option<Point>) -> String {
590    let data = &uas.data;
591    let ua = ua_type(data);
592    // UaType::None is "the broadcast did not declare a type", so read it as
593    // that rather than the literal word "None".
594    let ua_word = if ua == UaType::None {
595        "Undeclared-type".to_string()
596    } else {
597        format!("{ua:?}")
598    };
599    let mut s = match id_or(data, None) {
600        Some(id) => format!("{ua_word} {id}"),
601        None => format!("{ua_word} aircraft"),
602    };
603    if let Some(code) = manufacturer_code(data) {
604        let _ = write!(s, " (maker code {code} per CTA-2063-A)");
605    }
606    let _ = write!(
607        s,
608        ". Trust: {}.",
609        uas.assessment.verdict.name().to_uppercase()
610    );
611    if let Some(sys) = data.system.as_ref() {
612        if let Some((lat, lon)) = sys.operator_position() {
613            let label = match sys.operator_location_type {
614                OperatorLocationType::Takeoff => "Launched",
615                OperatorLocationType::Fixed => "Operator (fixed)",
616                OperatorLocationType::LiveGnss => "Operator",
617                OperatorLocationType::Other(_) => "Ground position",
618            };
619            let _ = write!(s, " {label} {lat:.6}, {lon:.6}.");
620        }
621    }
622    if let Some(p) = camera {
623        let _ = write!(s, " Camera on {:.6}, {:.6}.", p.lat, p.lon);
624    }
625    s
626}
627
628/// The camera ground target as a sensor point of interest linked to the
629/// aircraft: where the drone's camera is pointed on the ground, for the
630/// operator to read as "filming there" next to the aircraft marker.
631fn camera_spi(
632    id: &str,
633    aircraft_uid: &str,
634    aircraft_kind: &str,
635    target: Point,
636    now_us: u64,
637    opts: &Options,
638) -> Event {
639    let mut e = Event::new(
640        format!("{}spi-{id}", opts.uid_prefix),
641        "b-m-p-s-p-i",
642        now_us,
643        opts.stale_secs,
644    );
645    e.how = "m-i".into();
646    e.point = target;
647    e.callsign = Some(format!("Camera target of {id}"));
648    e.remarks = Some(
649        "Ground point this aircraft's camera is on, from a correlated MISB ST 0601 \
650         video frame center. The pairing of the video feed to this Remote ID aircraft \
651         is the operator's."
652            .into(),
653    );
654    e.links.push(Link {
655        uid: aircraft_uid.to_string(),
656        kind: aircraft_kind.to_string(),
657        relation: "p-p".into(),
658    });
659    e
660}
661
662/// The full operator picture for one tracked aircraft: what it is, whether
663/// it is fake, where it launched, and what it is watching, all on the map
664/// and joined up, instead of a bare marker the operator has to decode.
665///
666/// Like [`tracked_with`] (affiliation from `rules`, ground marker from
667/// [`operator_or_takeoff`], trust verdict in the aircraft remarks), and in
668/// addition:
669///
670/// - the aircraft's remarks open with [`headline`]: the model identity (UA
671///   type, broadcast id, and the CTA-2063-A maker code when the serial
672///   carries one), the trust verdict in capitals, the launch point, and the
673///   camera ground target when one is supplied;
674/// - the ground (operator or takeoff) marker carries a [`Link`] back to the
675///   aircraft (relation `p-s`: its position was derived from the aircraft's
676///   own broadcast), so ATAK draws the launch point joined to the drone
677///   rather than as a stray marker;
678/// - when `camera` is `Some`, a third event, the camera ground target as a
679///   sensor point of interest (`<prefix>spi-<id>`, `b-m-p-s-p-i`) linked to
680///   the aircraft, so the operator sees where it is filming.
681///
682/// `camera` is the ground point the aircraft's camera is on, typically the
683/// frame center of a correlated MISB ST 0601 video feed (`uas_cot::fmv` and
684/// the [`misb`](crate::misb) crate decode it). A Remote ID broadcast does not
685/// carry camera data and the video does not carry the Remote ID serial, so
686/// pairing a feed to this aircraft is the caller's decision, not something
687/// this function guesses. Pass `None` when there is no correlated feed.
688///
689/// Events are aircraft first, then the ground marker, then the camera target.
690///
691/// ```
692/// use uas_cot::Point;
693/// use uas_cot::remoteid::{BasicId, IdType, Location, Message, OperatorLocationType, System, Tracker, Transmitter, UaType};
694/// use uas_cot::rid::{self, AffiliationRules, Options};
695///
696/// let mut tracker = Tracker::default();
697/// let tx = Transmitter::Ble([0xAA, 0xBB, 0xCC, 0xDD, 0xEE, 0xFF]);
698/// let id = BasicId::new(IdType::SerialNumber, UaType::HelicopterOrMultirotor, "1596F35074529ABCDEFG").unwrap();
699/// let mut loc = Location::default();
700/// loc.latitude = 45.5470818;
701/// loc.longitude = -122.9668346;
702/// let mut sys = System::default();
703/// sys.operator_location_type = OperatorLocationType::Takeoff;
704/// sys.operator_latitude = 45.5443876;
705/// sys.operator_longitude = -122.9726866;
706/// tracker.ingest(tx, 1, &Message::BasicId(id).encode().unwrap(), 1_000);
707/// tracker.ingest(tx, 2, &Message::Location(loc).encode().unwrap(), 1_100);
708/// let uas = tracker.ingest(tx, 3, &Message::System(sys).encode().unwrap(), 1_200);
709///
710/// let camera = Some(Point::new(38.8950, -77.0300, 0.0));
711/// let ev = rid::tracked_picture(uas, None, 1_200_000, &Options::default(), &AffiliationRules::default(), camera);
712/// assert_eq!(ev.len(), 3);
713/// assert!(ev[0].remarks.as_deref().unwrap().contains("maker code 1596"));
714/// assert!(ev[0].remarks.as_deref().unwrap().contains("Trust: PLAUSIBLE"));
715/// assert_eq!(ev[2].uid, "rid-spi-1596F35074529ABCDEFG");
716/// assert_eq!(ev[2].links[0].uid, ev[0].uid);
717/// ```
718pub fn tracked_picture(
719    uas: &TrackedUas,
720    fallback_id: Option<&str>,
721    now_us: u64,
722    opts: &Options,
723    rules: &AffiliationRules,
724    camera: Option<Point>,
725) -> Vec<Event> {
726    let air_opts = Options {
727        affiliation: rules.affiliation(uas, opts.affiliation),
728        ..opts.clone()
729    };
730    let mut out = Vec::with_capacity(3);
731    let (aircraft_uid, aircraft_kind) = match aircraft(&uas.data, fallback_id, now_us, &air_opts) {
732        Some(mut air) => {
733            let head = headline(uas, camera);
734            let trust = trust_remarks(&uas.assessment);
735            air.remarks = Some(match air.remarks.take() {
736                Some(detail) => format!("{head} {detail} {trust}"),
737                None => format!("{head} {trust}"),
738            });
739            let ids = (air.uid.clone(), air.kind.clone());
740            out.push(air);
741            ids
742        }
743        None => {
744            out.extend(operator_or_takeoff(&uas.data, fallback_id, now_us, opts));
745            return out;
746        }
747    };
748    if let Some(mut ground) = operator_or_takeoff(&uas.data, fallback_id, now_us, opts) {
749        ground.links.push(Link {
750            uid: aircraft_uid.clone(),
751            kind: aircraft_kind.clone(),
752            relation: "p-s".into(),
753        });
754        out.push(ground);
755    }
756    if let Some(target) = camera {
757        if let Some(id) = id_or(&uas.data, fallback_id) {
758            out.push(camera_spi(
759                id,
760                &aircraft_uid,
761                &aircraft_kind,
762                target,
763                now_us,
764                opts,
765            ));
766        }
767    }
768    out
769}
770
771#[cfg(test)]
772#[allow(clippy::field_reassign_with_default)] // remoteid's message structs are non_exhaustive
773mod tests {
774    use super::*;
775    use remoteid::{BasicId, IdType, Location, Message, OperatorId, System, Tracker, Transmitter};
776
777    const SERIAL: &str = "1596F35074529ABCDEFG";
778
779    fn tracked_uas(loc_type: OperatorLocationType, operator: Option<&str>) -> TrackedUas {
780        let mut tracker = Tracker::default();
781        let tx = Transmitter::Ble([1, 2, 3, 4, 5, 6]);
782        let id =
783            BasicId::new(IdType::SerialNumber, UaType::HelicopterOrMultirotor, SERIAL).unwrap();
784        let mut loc = Location::default();
785        loc.latitude = 45.5470818;
786        loc.longitude = -122.9668346;
787        let mut sys = System::default();
788        sys.operator_location_type = loc_type;
789        sys.operator_latitude = 45.5443876;
790        sys.operator_longitude = -122.9726866;
791        let mut msgs = vec![
792            Message::BasicId(id),
793            Message::Location(loc),
794            Message::System(sys),
795        ];
796        if let Some(op) = operator {
797            msgs.push(Message::OperatorId(OperatorId::new(op).unwrap()));
798        }
799        let mut last = None;
800        for (i, m) in msgs.iter().enumerate() {
801            let t = 1_000 + i as u64 * 100;
802            last = Some(tracker.ingest(tx, i as u8, &m.encode().unwrap(), t).clone());
803        }
804        last.unwrap()
805    }
806
807    fn with_verdict(mut uas: TrackedUas, v: Verdict) -> TrackedUas {
808        uas.assessment.verdict = v;
809        uas
810    }
811
812    #[test]
813    fn takeoff_is_its_own_entity() {
814        let uas = tracked_uas(OperatorLocationType::Takeoff, Some("GBR-OP-123ABCD"));
815        let e = operator_or_takeoff(&uas.data, None, 0, &Options::default()).unwrap();
816        assert_eq!(e.uid, format!("rid-takeoff-{SERIAL}"));
817        assert_eq!(
818            e.callsign.as_deref(),
819            Some(format!("Takeoff point of {SERIAL} (operator GBR-OP-123ABCD)").as_str())
820        );
821        assert!(e
822            .remarks
823            .as_deref()
824            .unwrap()
825            .contains("Not a live operator position"));
826        assert_eq!(e.kind, "b-m-p-s-m");
827        // The old function still calls it the operator, unchanged.
828        let old = operator(&uas.data, None, 0, &Options::default()).unwrap();
829        assert_eq!(old.uid, format!("rid-op-{SERIAL}"));
830    }
831
832    #[test]
833    fn live_and_fixed_operator_positions() {
834        let live = tracked_uas(OperatorLocationType::LiveGnss, None);
835        let e = operator_or_takeoff(&live.data, None, 0, &Options::default()).unwrap();
836        assert_eq!(e.uid, format!("rid-op-{SERIAL}"));
837        assert_eq!(
838            e.callsign.as_deref(),
839            Some(format!("Operator of {SERIAL}").as_str())
840        );
841        assert!(e.remarks.as_deref().unwrap().contains("live GNSS"));
842
843        let fixed = tracked_uas(OperatorLocationType::Fixed, None);
844        let e = operator_or_takeoff(&fixed.data, None, 0, &Options::default()).unwrap();
845        assert_eq!(e.uid, format!("rid-op-{SERIAL}"));
846        assert!(e.callsign.as_deref().unwrap().ends_with("(fixed location)"));
847    }
848
849    #[test]
850    fn spoofed_never_becomes_friendly() {
851        let rules = AffiliationRules::default().friendly_id(SERIAL);
852        let base = tracked_uas(OperatorLocationType::Takeoff, None);
853        assert_eq!(
854            rules.affiliation(&with_verdict(base.clone(), Verdict::Plausible), 'u'),
855            'f'
856        );
857        assert_eq!(
858            rules.affiliation(&with_verdict(base.clone(), Verdict::Spoofed), 'u'),
859            's'
860        );
861        // suspicious with no suspicious rule: the default, never the friendly letter
862        assert_eq!(
863            rules.affiliation(&with_verdict(base.clone(), Verdict::Suspicious), 'u'),
864            'u'
865        );
866        let strict = rules.clone().suspicious_as('s').spoofed_as('h');
867        assert_eq!(
868            strict.affiliation(&with_verdict(base.clone(), Verdict::Suspicious), 'u'),
869            's'
870        );
871        assert_eq!(
872            strict.affiliation(&with_verdict(base.clone(), Verdict::Spoofed), 'u'),
873            'h'
874        );
875        let none = rules.clone().no_verdict_rules();
876        assert_eq!(
877            none.affiliation(&with_verdict(base, Verdict::Spoofed), 'u'),
878            'u'
879        );
880    }
881
882    #[test]
883    fn friendly_by_operator_id_and_auth_requirement() {
884        let uas = tracked_uas(OperatorLocationType::LiveGnss, Some("FIN87astrdge12k8"));
885        let rules = AffiliationRules::default().friendly_id(" FIN87astrdge12k8 ");
886        assert_eq!(rules.affiliation(&uas, 'u'), 'f');
887        let strict = rules.clone().require_authenticated_friendly(true);
888        assert_eq!(
889            strict.affiliation(&with_verdict(uas.clone(), Verdict::Plausible), 'u'),
890            'u'
891        );
892        assert_eq!(
893            strict.affiliation(&with_verdict(uas.clone(), Verdict::Authenticated), 'u'),
894            'f'
895        );
896        let other = AffiliationRules::default().authenticated_as('n');
897        assert_eq!(
898            other.affiliation(&with_verdict(uas.clone(), Verdict::Authenticated), 'u'),
899            'n'
900        );
901        assert_eq!(other.affiliation(&uas, 'u'), 'u');
902    }
903
904    #[test]
905    fn headline_reads_as_one_plain_line() {
906        let uas = tracked_uas(OperatorLocationType::Takeoff, Some("GBR-OP-123ABCD"));
907        // SERIAL is a well formed CTA-2063-A serial: maker code "1596".
908        assert_eq!(manufacturer_code(&uas.data), Some("1596"));
909        let h = headline(&uas, Some(Point::new(38.8950, -77.0300, 0.0)));
910        assert_eq!(
911            h,
912            "HelicopterOrMultirotor 1596F35074529ABCDEFG (maker code 1596 per CTA-2063-A). \
913             Trust: PLAUSIBLE. Launched 45.544388, -122.972687. Camera on 38.895000, -77.030000."
914        );
915        // Spoofed shows in capitals; no camera point drops that clause.
916        let spoofed = with_verdict(uas, Verdict::Spoofed);
917        let h = headline(&spoofed, None);
918        assert!(h.contains("Trust: SPOOFED."), "{h}");
919        assert!(!h.contains("Camera on"), "{h}");
920    }
921
922    #[test]
923    fn picture_joins_aircraft_takeoff_and_camera() {
924        let uas = tracked_uas(OperatorLocationType::Takeoff, Some("GBR-OP-123ABCD"));
925        let camera = Some(Point::new(38.8950, -77.0300, 12.0));
926        let ev = tracked_picture(
927            &uas,
928            None,
929            0,
930            &Options::default(),
931            &AffiliationRules::default(),
932            camera,
933        );
934        assert_eq!(ev.len(), 3, "aircraft, takeoff, camera target");
935
936        // Aircraft: headline, then the detail, then the trust reasons.
937        let air = &ev[0];
938        assert_eq!(air.uid, format!("rid-{SERIAL}"));
939        let r = air.remarks.as_deref().unwrap();
940        assert!(r.starts_with("HelicopterOrMultirotor 1596F35074529ABCDEFG (maker code 1596"));
941        assert!(
942            r.contains("Operator ID: GBR-OP-123ABCD."),
943            "detail kept: {r}"
944        );
945        assert!(r.ends_with("Trust: plausible."), "reasons line kept: {r}");
946
947        // Takeoff marker is joined back to the aircraft.
948        let ground = &ev[1];
949        assert_eq!(ground.uid, format!("rid-takeoff-{SERIAL}"));
950        assert_eq!(ground.links.len(), 1);
951        assert_eq!(ground.links[0].uid, air.uid);
952        assert_eq!(ground.links[0].relation, "p-s");
953        assert_eq!(ground.links[0].kind, air.kind);
954
955        // Camera target: a SPI linked to the aircraft, valid CoT XML.
956        let spi = &ev[2];
957        assert_eq!(spi.uid, format!("rid-spi-{SERIAL}"));
958        assert_eq!(spi.kind, "b-m-p-s-p-i");
959        assert_eq!(spi.point.lat, 38.8950);
960        assert_eq!(
961            spi.callsign.as_deref(),
962            Some(format!("Camera target of {SERIAL}").as_str())
963        );
964        assert_eq!(spi.links[0].uid, air.uid);
965        let xml = spi.to_xml();
966        assert!(xml.contains("type=\"b-m-p-s-p-i\""), "{xml}");
967        assert!(
968            xml.contains(&format!(
969                "<link uid=\"rid-{SERIAL}\" type=\"{}\" relation=\"p-p\"/>",
970                air.kind
971            )),
972            "{xml}"
973        );
974
975        // No camera feed: just aircraft and takeoff, no SPI.
976        let ev = tracked_picture(
977            &uas,
978            None,
979            0,
980            &Options::default(),
981            &AffiliationRules::default(),
982            None,
983        );
984        assert_eq!(ev.len(), 2);
985        assert!(!ev.iter().any(|e| e.uid.starts_with("rid-spi-")));
986    }
987
988    #[test]
989    fn picture_spoofer_stays_suspect_and_flagged() {
990        let uas = with_verdict(
991            tracked_uas(OperatorLocationType::Takeoff, None),
992            Verdict::Spoofed,
993        );
994        let ev = tracked_picture(
995            &uas,
996            None,
997            0,
998            &Options::default(),
999            &AffiliationRules::default().friendly_id(SERIAL),
1000            None,
1001        );
1002        // A spoofer that copies our serial is not drawn friendly, and the
1003        // headline says SPOOFED in the remarks the operator reads.
1004        assert_eq!(ev[0].kind, "a-s-A-M-F-Q");
1005        assert!(ev[0]
1006            .remarks
1007            .as_deref()
1008            .unwrap()
1009            .contains("Trust: SPOOFED."));
1010    }
1011
1012    #[test]
1013    fn tracked_with_sets_type_and_ground_marker() {
1014        let uas = with_verdict(
1015            tracked_uas(OperatorLocationType::Takeoff, None),
1016            Verdict::Spoofed,
1017        );
1018        let ev = tracked_with(
1019            &uas,
1020            None,
1021            0,
1022            &Options::default(),
1023            &AffiliationRules::default(),
1024        );
1025        assert_eq!(ev.len(), 2);
1026        assert_eq!(ev[0].kind, "a-s-A-M-F-Q");
1027        assert!(ev[0].remarks.as_deref().unwrap().contains("Trust: spoofed"));
1028        assert_eq!(ev[1].uid, format!("rid-takeoff-{SERIAL}"));
1029        // tracked() is unchanged: opts.affiliation, operator labelling
1030        let old = tracked(&uas, None, 0, &Options::default());
1031        assert_eq!(old[0].kind, "a-u-A-M-F-Q");
1032        assert_eq!(old[1].uid, format!("rid-op-{SERIAL}"));
1033    }
1034}