Skip to main content

uas_cot/
mavlink.rs

1//! MAVLink to CoT without a MAVLink dependency: decode the two payloads
2//! that matter for a map marker (`HEARTBEAT` for the vehicle type,
3//! `GLOBAL_POSITION_INT` for position and velocity) from raw frame
4//! payloads, as returned by `mavlink-tlog`, rust-mavlink or any parser.
5//!
6//! ```
7//! use uas_cot::mavlink::{self, GlobalPositionInt, Options};
8//!
9//! let pos = GlobalPositionInt { time_boot_ms: 0, lat: 473_977_418, lon: 85_455_939, alt: 488_000,
10//!     relative_alt: 0, vx: 500, vy: 0, vz: 0, hdg: 9000 };
11//! let e = mavlink::vehicle(1, &pos, Some(2), 1_700_000_000_000_000, &Options::default()).unwrap();
12//! assert_eq!(e.uid, "mav-1");
13//! assert!((e.point.lat - 47.3977418).abs() < 1e-9);
14//! assert_eq!(e.track.unwrap().course, 90.0);
15//! ```
16
17use crate::{Event, Point, Track};
18
19/// `GLOBAL_POSITION_INT` message id.
20pub const GLOBAL_POSITION_INT_ID: u32 = 33;
21/// `HEARTBEAT` message id.
22pub const HEARTBEAT_ID: u32 = 0;
23
24/// `GLOBAL_POSITION_INT` (message 33), in wire units.
25#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
26pub struct GlobalPositionInt {
27    /// Time since boot, ms.
28    pub time_boot_ms: u32,
29    /// Latitude, degrees * 1e7.
30    pub lat: i32,
31    /// Longitude, degrees * 1e7.
32    pub lon: i32,
33    /// Altitude above mean sea level, mm.
34    pub alt: i32,
35    /// Altitude above home, mm.
36    pub relative_alt: i32,
37    /// Ground X speed (north), cm/s.
38    pub vx: i16,
39    /// Ground Y speed (east), cm/s.
40    pub vy: i16,
41    /// Ground Z speed (down), cm/s.
42    pub vz: i16,
43    /// Heading, centidegrees; `u16::MAX` if unknown.
44    pub hdg: u16,
45}
46
47impl GlobalPositionInt {
48    /// Decodes a payload. MAVLink 2 trims trailing zero bytes, so shorter
49    /// payloads are zero-padded; longer than 28 bytes is rejected.
50    pub fn parse(payload: &[u8]) -> Option<Self> {
51        if payload.len() > 28 {
52            return None;
53        }
54        let mut b = [0u8; 28];
55        b[..payload.len()].copy_from_slice(payload);
56        let i32_at = |o: usize| i32::from_le_bytes([b[o], b[o + 1], b[o + 2], b[o + 3]]);
57        let i16_at = |o: usize| i16::from_le_bytes([b[o], b[o + 1]]);
58        Some(GlobalPositionInt {
59            time_boot_ms: u32::from_le_bytes([b[0], b[1], b[2], b[3]]),
60            lat: i32_at(4),
61            lon: i32_at(8),
62            alt: i32_at(12),
63            relative_alt: i32_at(16),
64            vx: i16_at(20),
65            vy: i16_at(22),
66            vz: i16_at(24),
67            hdg: u16::from_le_bytes([b[26], b[27]]),
68        })
69    }
70}
71
72/// `MAV_TYPE` from a `HEARTBEAT` payload (byte 4), if the payload is long enough.
73pub fn heartbeat_mav_type(payload: &[u8]) -> Option<u8> {
74    payload.get(4).copied()
75}
76
77/// How MAVLink vehicles become events.
78#[derive(Clone, Debug, PartialEq)]
79pub struct Options {
80    /// Affiliation letter (default `'f'`: vehicles on your own link).
81    pub affiliation: char,
82    /// Seconds until stale (default 15).
83    pub stale_secs: u64,
84    /// UID prefix (default `"mav-"`); the system id is appended.
85    pub uid_prefix: String,
86}
87
88impl Default for Options {
89    fn default() -> Self {
90        Options {
91            affiliation: 'f',
92            stale_secs: 15,
93            uid_prefix: "mav-".into(),
94        }
95    }
96}
97
98/// CoT type for a `MAV_TYPE`: aircraft (fixed wing, multirotors,
99/// helicopters, VTOLs, airships) are drones `a-?-A-M-F-Q`; ground rovers
100/// `a-?-G-E-V`; boats `a-?-S`; submarines `a-?-U`; anything else `a-?-A`.
101pub fn vehicle_type(mav_type: Option<u8>, affiliation: char) -> String {
102    let tail = match mav_type {
103        Some(
104            1 | 2 | 3 | 4 | 7 | 8 | 13 | 14 | 15 | 16 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 28 | 29
105            | 35,
106        ) => "A-M-F-Q",
107        Some(10) => "G-E-V",
108        Some(11) => "S",
109        Some(12) => "U",
110        _ => "A",
111    };
112    format!("a-{affiliation}-{tail}")
113}
114
115/// A vehicle event from `GLOBAL_POSITION_INT` of system `sys_id`, or `None`
116/// if the position is (0, 0) or out of range. Height is the MSL altitude.
117pub fn vehicle(
118    sys_id: u8,
119    pos: &GlobalPositionInt,
120    mav_type: Option<u8>,
121    now_us: u64,
122    opts: &Options,
123) -> Option<Event> {
124    if pos.lat == 0 && pos.lon == 0 {
125        return None;
126    }
127    let point = Point::new(
128        pos.lat as f64 * 1e-7,
129        pos.lon as f64 * 1e-7,
130        pos.alt as f64 / 1000.0,
131    );
132    if !point.is_valid() {
133        return None;
134    }
135    let mut e = Event::new(
136        format!("{}{sys_id}", opts.uid_prefix),
137        vehicle_type(mav_type, opts.affiliation),
138        now_us,
139        opts.stale_secs,
140    );
141    e.point = point;
142    e.callsign = Some(format!("MAV {sys_id}"));
143    e.precision_location = Some(("GPS".into(), "MSL".into()));
144    let (vn, ve) = (pos.vx as f64 / 100.0, pos.vy as f64 / 100.0);
145    let speed = vn.hypot(ve);
146    let course = if pos.hdg != u16::MAX {
147        pos.hdg as f64 / 100.0
148    } else {
149        ve.atan2(vn).to_degrees().rem_euclid(360.0)
150    };
151    e.track = Some(Track { course, speed });
152    e.remarks = Some(format!(
153        "MAVLink system {sys_id}. Height above home: {:.1} m.",
154        pos.relative_alt as f64 / 1000.0
155    ));
156    Some(e)
157}
158
159#[cfg(test)]
160mod tests {
161    use super::*;
162
163    #[test]
164    fn parses_trimmed_payload() {
165        let full = GlobalPositionInt {
166            time_boot_ms: 1,
167            lat: 2,
168            lon: 3,
169            alt: 4,
170            relative_alt: 5,
171            vx: -6,
172            vy: 7,
173            vz: 8,
174            hdg: 0,
175        };
176        let mut b = Vec::new();
177        b.extend_from_slice(&1u32.to_le_bytes());
178        for v in [2i32, 3, 4, 5] {
179            b.extend_from_slice(&v.to_le_bytes());
180        }
181        for v in [-6i16, 7, 8] {
182            b.extend_from_slice(&v.to_le_bytes());
183        }
184        // hdg = 0 trimmed by MAVLink 2
185        assert_eq!(GlobalPositionInt::parse(&b), Some(full));
186        assert_eq!(GlobalPositionInt::parse(&[0; 29]), None);
187    }
188
189    #[test]
190    fn course_from_velocity_when_heading_unknown() {
191        let p = GlobalPositionInt {
192            lat: 1,
193            lon: 1,
194            vx: 0,
195            vy: -300,
196            hdg: u16::MAX,
197            ..Default::default()
198        };
199        let e = vehicle(3, &p, None, 0, &Options::default()).unwrap();
200        let t = e.track.unwrap();
201        assert!((t.course - 270.0).abs() < 1e-9 && (t.speed - 3.0).abs() < 1e-9);
202        assert_eq!(e.kind, "a-f-A");
203    }
204}