Skip to main content

uas_cot/mavlink_m/
cot.rs

1//! MAVLink-M friendly position reports to CoT events.
2
3use super::dialect::{Dialect, Message, Value};
4use super::{military, scope, PARTICIPANT_POSITION};
5use crate::{Event, Point, Track};
6
7/// How MAVLink-M messages become events.
8#[derive(Clone, Debug, PartialEq)]
9pub struct Options {
10    /// Seconds until stale (default 30).
11    pub stale_secs: u64,
12    /// UID prefix of the events this module makes (default `"mavlink-m-"`).
13    pub uid_prefix: String,
14    /// Drop messages that fail [`super::validate::check_payload`] (default
15    /// true). The dialect requires receivers to reject undefined values of
16    /// its protected enums rather than guess.
17    pub reject_invalid: bool,
18}
19
20impl Default for Options {
21    fn default() -> Self {
22        Options {
23            stale_secs: 30,
24            uid_prefix: "mavlink-m-".into(),
25            reject_invalid: true,
26        }
27    }
28}
29
30/// CoT affiliation letter for a `MAVLINK_M_STANAG_IDENTITY` value
31/// (pending, unknown, assumed friend, friend, neutral, suspect, hostile).
32pub fn affiliation_from_identity(v: u8) -> char {
33    match v {
34        0 => 'p',
35        1 => 'u',
36        2 => 'a',
37        3 => 'f',
38        4 => 'n',
39        5 => 's',
40        6 => 'h',
41        _ => 'u',
42    }
43}
44
45/// CoT dimension for a `MAVLINK_M_PPLI_TYPE`.
46pub fn ppli_dimension(t: u8) -> Option<&'static str> {
47    Some(match t {
48        1 => "A",
49        2 => "G",
50        3 => "S",
51        4 => "U",
52        _ => return None,
53    })
54}
55
56fn get(m: &Message, p: &[u8], name: &str) -> Value {
57    m.get(p, name).unwrap_or(Value::Uint(0))
58}
59fn u(m: &Message, p: &[u8], name: &str) -> u64 {
60    get(m, p, name).as_u64().unwrap_or(0)
61}
62fn i(m: &Message, p: &[u8], name: &str) -> i64 {
63    get(m, p, name).as_i64().unwrap_or(0)
64}
65fn fl(m: &Message, p: &[u8], name: &str) -> f64 {
66    get(m, p, name).as_f64().unwrap_or(f64::NAN)
67}
68fn text(m: &Message, p: &[u8], name: &str) -> String {
69    get(m, p, name).as_str().unwrap_or("").trim().to_string()
70}
71
72fn track_from_ned(vn: f64, ve: f64) -> Option<Track> {
73    if vn.is_finite() && ve.is_finite() {
74        Some(Track {
75            course: ve.atan2(vn).to_degrees().rem_euclid(360.0),
76            speed: vn.hypot(ve),
77        })
78    } else {
79        None
80    }
81}
82
83/// Turns MAVLink-M friendly position reports into CoT events.
84///
85/// Translated: `PARTICIPANT_POSITION` (53003) only, the list in
86/// [`scope::TRANSLATED`]. Vehicle telemetry (`HEARTBEAT`,
87/// `GLOBAL_POSITION_INT`) is [`crate::mavlink`]'s job.
88///
89/// Blocked: every target, track, handover, fires, munition, arming,
90/// weapon, engagement and payload message ([`scope::is_blocked`]) is dropped before
91/// its payload is read, never produces an event, and is counted in
92/// [`Gateway::blocked`]. Every other MAVLink-M message is ignored.
93#[derive(Debug)]
94pub struct Gateway {
95    opts: Options,
96    dialect: &'static Dialect,
97    blocked: u64,
98}
99
100impl Default for Gateway {
101    fn default() -> Self {
102        Gateway::new(Options::default())
103    }
104}
105
106impl Gateway {
107    /// A gateway using the embedded MAVLink-M definition.
108    pub fn new(opts: Options) -> Self {
109        Gateway {
110            opts,
111            dialect: military(),
112            blocked: 0,
113        }
114    }
115
116    /// How many out-of-scope messages this gateway has refused.
117    pub fn blocked(&self) -> u64 {
118        self.blocked
119    }
120
121    /// Handles one message from system `sys_id` and returns the event it
122    /// produces, if any. `now_us` is the receive time (or the log time when
123    /// replaying). Out-of-scope messages always return `None`.
124    pub fn ingest(
125        &mut self,
126        sys_id: u8,
127        msg_id: u32,
128        payload: &[u8],
129        now_us: u64,
130    ) -> Option<Event> {
131        let name = self.dialect.message(msg_id).map(|m| m.name.as_str());
132        if scope::is_blocked(msg_id, name.unwrap_or("")) {
133            self.blocked += 1;
134            return None;
135        }
136        if !scope::is_translated(msg_id) {
137            return None;
138        }
139        let m = self.dialect.message(msg_id)?;
140        if self.opts.reject_invalid
141            && !super::validate::check_payload(self.dialect, msg_id, payload, true).is_ok()
142        {
143            return None;
144        }
145        match msg_id {
146            PARTICIPANT_POSITION => self.participant(m, sys_id, payload, now_us),
147            _ => None,
148        }
149    }
150
151    fn label(&self, en: &str, v: u64) -> String {
152        self.dialect
153            .label(en, v)
154            .unwrap_or_else(|| format!("undefined value {v}"))
155    }
156
157    fn participant(&mut self, m: &Message, sys_id: u8, p: &[u8], now_us: u64) -> Option<Event> {
158        let lat = i(m, p, "lat");
159        let lon = i(m, p, "lon");
160        if lat == 0 && lon == 0 {
161            return None;
162        }
163        let point = Point::new(lat as f64 * 1e-7, lon as f64 * 1e-7, fl(m, p, "alt"));
164        if !point.is_valid() {
165            return None;
166        }
167        let origin = u(m, p, "origin_sysid") as u8;
168        let origin = if origin == 0 { sys_id } else { origin };
169        let mut e = Event::new(
170            format!("{}ppli-{origin}", self.opts.uid_prefix),
171            "a-u-X",
172            now_us,
173            self.opts.stale_secs,
174        );
175        let t = u(m, p, "time_usec");
176        if t != 0 && t <= now_us {
177            e.start_us = t;
178        }
179        e.point = point;
180        if !e.point.hae.is_finite() {
181            e.point.hae = 0.0;
182        }
183        e.precision_location = Some(("GPS".into(), "MSL".into()));
184        let (vn, ve) = (fl(m, p, "vx"), fl(m, p, "vy"));
185        let course = fl(m, p, "course");
186        e.track = match track_from_ned(vn, ve) {
187            Some(mut t) => {
188                if course.is_finite() {
189                    t.course = course;
190                }
191                Some(t)
192            }
193            None => None,
194        };
195        let cs = text(m, p, "callsign");
196        e.callsign = Some(if cs.is_empty() {
197            format!("PPLI {origin}")
198        } else {
199            cs
200        });
201        let aff = affiliation_from_identity(u(m, p, "stanag_identity") as u8);
202        let ppli = u(m, p, "ppli_type") as u8;
203        e.kind = format!("a-{aff}-{}", ppli_dimension(ppli).unwrap_or("X"));
204        let mut r = format!(
205            "MAVLink-M PARTICIPANT_POSITION from system {origin}. Type: {}. Identity: {}.",
206            self.label("MAVLINK_M_PPLI_TYPE", ppli as u64),
207            self.label("MAVLINK_M_STANAG_IDENTITY", u(m, p, "stanag_identity"))
208        );
209        let etn = text(m, p, "external_track_number");
210        if !etn.is_empty() {
211            r.push_str(&format!(
212                " Network participant number {etn} ({}).",
213                self.label(
214                    "MAVLINK_M_TRACK_NUMBER_TYPE",
215                    u(m, p, "external_track_type")
216                )
217            ));
218        }
219        e.remarks = Some(r);
220        Some(e)
221    }
222}