Skip to main content

uas_cot/
lib.rs

1//! Turn drone telemetry into Cursor on Target (CoT) events for TAK (ATAK,
2//! WinTAK, iTAK, TAK Server, FreeTAKServer, OpenTAKServer).
3//!
4//! | Source | Module | Events |
5//! |---|---|---|
6//! | Drone Remote ID (ASTM F3411 / EN 4709-002) via the [`remoteid`](https://docs.rs/remoteid) crate | [`rid`] | the aircraft, and its operator |
7//! | MISB ST 0601 KLV from drone video via the [`misb`](https://docs.rs/misb) crate | [`fmv`] | the platform with its sensor field of view, and the sensor point of interest |
8//! | MAVLink `GLOBAL_POSITION_INT` / `HEARTBEAT` payloads | [`mavlink`] | the vehicle |
9//! | MAVLink-M (`military.xml`) `TRACK_IDENTITY`, `TARGET_HANDOVER`, `PARTICIPANT_POSITION`, `TARGET`, feature `mavlink-m` | `mavlink_m` | shared tracks and friendly position reports, plus a conformance checker |
10//!
11//! [`Event`] is the CoT 2.0 event model; [`Event::to_xml`] writes the XML
12//! that TAK clients and servers accept (validated against the MITRE public
13//! release schemas in the tests). [`net`] sends events to the SA multicast
14//! group or a TAK Server TCP input.
15//!
16//! ```
17//! use uas_cot::{Event, Point, Track};
18//!
19//! let mut e = Event::new("rid-1596F35074529ABCDEFG", "a-u-A-M-F-Q", 1_700_000_000_000_000, 30);
20//! e.point = Point::new(38.8895, -77.0353, 120.0);
21//! e.callsign = Some("1596F35074529ABCDEFG".into());
22//! e.track = Some(Track { course: 92.0, speed: 11.5 });
23//! let xml = e.to_xml();
24//! assert!(xml.starts_with("<?xml version=\"1.0\" encoding=\"UTF-8\"?><event version=\"2.0\""));
25//! assert!(xml.contains("<point lat=\"38.8895000\" lon=\"-77.0353000\" hae=\"120.0\""));
26//! ```
27#![forbid(unsafe_code)]
28#![warn(missing_docs)]
29
30use std::fmt::{self, Write as _};
31
32#[cfg(feature = "misb")]
33pub mod fmv;
34pub mod mavlink;
35#[cfg(feature = "mavlink-m")]
36pub mod mavlink_m;
37pub mod net;
38#[cfg(feature = "remoteid")]
39pub mod rid;
40
41/// "Unknown" circular and linear error, as CoT defines it.
42pub const UNKNOWN_ERROR: f64 = 9_999_999.0;
43
44/// A WGS84 point. `hae` is metres above the ellipsoid; `ce` and `le` are
45/// the 1-sigma horizontal and vertical errors in metres.
46#[derive(Clone, Copy, Debug, PartialEq)]
47pub struct Point {
48    /// Latitude, degrees.
49    pub lat: f64,
50    /// Longitude, degrees.
51    pub lon: f64,
52    /// Height above the WGS84 ellipsoid, metres.
53    pub hae: f64,
54    /// Circular error, metres.
55    pub ce: f64,
56    /// Linear (vertical) error, metres.
57    pub le: f64,
58}
59
60impl Point {
61    /// A point with unknown errors.
62    pub fn new(lat: f64, lon: f64, hae: f64) -> Self {
63        Point {
64            lat,
65            lon,
66            hae,
67            ce: UNKNOWN_ERROR,
68            le: UNKNOWN_ERROR,
69        }
70    }
71
72    /// True if latitude and longitude are finite and in range.
73    pub fn is_valid(&self) -> bool {
74        self.lat.is_finite()
75            && self.lon.is_finite()
76            && self.lat.abs() <= 90.0
77            && self.lon.abs() <= 180.0
78    }
79}
80
81impl Default for Point {
82    fn default() -> Self {
83        Point::new(0.0, 0.0, 0.0)
84    }
85}
86
87/// `<track>`: course over ground (degrees true) and speed (m/s).
88#[derive(Clone, Copy, Debug, PartialEq)]
89pub struct Track {
90    /// Course, degrees clockwise from true north.
91    pub course: f64,
92    /// Speed, metres per second.
93    pub speed: f64,
94}
95
96/// `<sensor>`: where a camera on the platform is looking. ATAK draws it as
97/// a field of view wedge.
98#[derive(Clone, Debug, Default, PartialEq)]
99pub struct Sensor {
100    /// Azimuth of the line of sight, degrees true.
101    pub azimuth: Option<f64>,
102    /// Elevation of the line of sight, degrees (-90 to 90).
103    pub elevation: Option<f64>,
104    /// Roll, degrees (-180 to 180).
105    pub roll: Option<f64>,
106    /// Horizontal field of view, degrees.
107    pub fov: Option<f64>,
108    /// Vertical field of view, degrees.
109    pub vfov: Option<f64>,
110    /// Range to the scene, metres.
111    pub range: Option<f64>,
112    /// Sensor name.
113    pub model: Option<String>,
114    /// Sensor type (`"r-e"` electro-optical, `"r-i"` infrared ...).
115    pub kind: Option<String>,
116}
117
118/// `<link>`: a reference to another event (for example the platform that
119/// produced a sensor point of interest).
120#[derive(Clone, Debug, PartialEq, Eq)]
121pub struct Link {
122    /// UID of the other event.
123    pub uid: String,
124    /// CoT type of the other event.
125    pub kind: String,
126    /// Relation, for example `"p-p"` (parent-producer).
127    pub relation: String,
128}
129
130/// A CoT 2.0 event.
131#[derive(Clone, Debug, PartialEq)]
132pub struct Event {
133    /// Unique, stable id of the thing described.
134    pub uid: String,
135    /// CoT type, for example `"a-u-A-M-F-Q"`.
136    pub kind: String,
137    /// How the position was obtained (`"m-g"` = GPS).
138    pub how: String,
139    /// Event time, microseconds since 1970 UTC.
140    pub time_us: u64,
141    /// Start of validity, microseconds since 1970 UTC.
142    pub start_us: u64,
143    /// End of validity, microseconds since 1970 UTC.
144    pub stale_us: u64,
145    /// Position.
146    pub point: Point,
147    /// `<contact callsign>`.
148    pub callsign: Option<String>,
149    /// `<track>`.
150    pub track: Option<Track>,
151    /// `<sensor>`.
152    pub sensor: Option<Sensor>,
153    /// `<link>` elements.
154    pub links: Vec<Link>,
155    /// `<remarks>` text.
156    pub remarks: Option<String>,
157    /// `<__video url>`: a video stream TAK clients can open from the marker.
158    pub video_url: Option<String>,
159    /// `<precisionlocation geopointsrc altsrc>`, for example `("GPS", "GPS")`.
160    pub precision_location: Option<(String, String)>,
161}
162
163impl Event {
164    /// A new event of `kind` at `time_us`, stale after `stale_secs`
165    /// seconds, with `how = "m-g"`.
166    pub fn new(
167        uid: impl Into<String>,
168        kind: impl Into<String>,
169        time_us: u64,
170        stale_secs: u64,
171    ) -> Self {
172        Event {
173            uid: uid.into(),
174            kind: kind.into(),
175            how: "m-g".into(),
176            time_us,
177            start_us: time_us,
178            stale_us: time_us.saturating_add(stale_secs.saturating_mul(1_000_000)),
179            point: Point::default(),
180            callsign: None,
181            track: None,
182            sensor: None,
183            links: Vec::new(),
184            remarks: None,
185            video_url: None,
186            precision_location: None,
187        }
188    }
189
190    /// The event as a CoT XML document (one line, with XML declaration).
191    pub fn to_xml(&self) -> String {
192        let mut s = String::with_capacity(512);
193        self.write_xml(&mut s)
194            .expect("writing to a String does not fail");
195        s
196    }
197
198    /// Writes the event as a CoT XML document.
199    pub fn write_xml(&self, w: &mut impl fmt::Write) -> fmt::Result {
200        w.write_str("<?xml version=\"1.0\" encoding=\"UTF-8\"?>")?;
201        write!(
202            w,
203            "<event version=\"2.0\" uid=\"{}\" type=\"{}\" how=\"{}\" time=\"{}\" start=\"{}\" stale=\"{}\">",
204            Esc(&self.uid),
205            Esc(&self.kind),
206            Esc(&self.how),
207            Iso8601(self.time_us),
208            Iso8601(self.start_us),
209            Iso8601(self.stale_us)
210        )?;
211        let p = &self.point;
212        write!(
213            w,
214            "<point lat=\"{:.7}\" lon=\"{:.7}\" hae=\"{:.1}\" ce=\"{:.1}\" le=\"{:.1}\"/>",
215            p.lat,
216            p.lon,
217            finite_or(p.hae, 0.0),
218            finite_or(p.ce, UNKNOWN_ERROR).max(0.0),
219            finite_or(p.le, UNKNOWN_ERROR).max(0.0)
220        )?;
221        w.write_str("<detail>")?;
222        if let Some(c) = &self.callsign {
223            write!(w, "<contact callsign=\"{}\"/>", Esc(c))?;
224        }
225        if let Some((g, a)) = &self.precision_location {
226            write!(
227                w,
228                "<precisionlocation geopointsrc=\"{}\" altsrc=\"{}\"/>",
229                Esc(g),
230                Esc(a)
231            )?;
232        }
233        if let Some(t) = &self.track {
234            if t.course.is_finite() && t.speed.is_finite() {
235                write!(
236                    w,
237                    "<track course=\"{:.1}\" speed=\"{:.2}\"/>",
238                    wrap360(t.course, 1),
239                    t.speed.max(0.0)
240                )?;
241            }
242        }
243        if let Some(sn) = &self.sensor {
244            w.write_str("<sensor")?;
245            if let Some(v) = sn.azimuth.filter(|v| v.is_finite()) {
246                write!(w, " azimuth=\"{:.2}\"", wrap360(v, 2))?;
247            }
248            if let Some(v) = sn.elevation.filter(|v| v.is_finite() && v.abs() <= 90.0) {
249                write!(w, " elevation=\"{v:.2}\"")?;
250            }
251            if let Some(v) = sn.roll.filter(|v| v.is_finite()) {
252                let r = wrap360(v, 2);
253                write!(w, " roll=\"{:.2}\"", if r > 180.0 { r - 360.0 } else { r })?;
254            }
255            if let Some(v) = sn.fov.filter(|v| v.is_finite() && *v >= 0.0 && *v < 360.0) {
256                write!(w, " fov=\"{v:.3}\"")?;
257            }
258            if let Some(v) = sn.vfov.filter(|v| v.is_finite() && *v >= 0.0 && *v < 360.0) {
259                write!(w, " vfov=\"{v:.3}\"")?;
260            }
261            if let Some(v) = sn.range.filter(|v| v.is_finite() && *v >= 0.0) {
262                write!(w, " range=\"{v:.1}\"")?;
263            }
264            if let Some(v) = &sn.model {
265                write!(w, " model=\"{}\"", Esc(v))?;
266            }
267            if let Some(v) = &sn.kind {
268                write!(w, " type=\"{}\"", Esc(v))?;
269            }
270            w.write_str("/>")?;
271        }
272        for l in &self.links {
273            write!(
274                w,
275                "<link uid=\"{}\" type=\"{}\" relation=\"{}\"/>",
276                Esc(&l.uid),
277                Esc(&l.kind),
278                Esc(&l.relation)
279            )?;
280        }
281        if let Some(u) = &self.video_url {
282            write!(w, "<__video url=\"{}\"/>", Esc(u))?;
283        }
284        if let Some(r) = &self.remarks {
285            write!(w, "<remarks>{}</remarks>", Esc(r))?;
286        }
287        w.write_str("</detail></event>")
288    }
289}
290
291fn finite_or(v: f64, d: f64) -> f64 {
292    if v.is_finite() {
293        v
294    } else {
295        d
296    }
297}
298
299/// Rounds to `decimals` places, then wraps into `0..360`.
300fn wrap360(v: f64, decimals: i32) -> f64 {
301    let p = 10f64.powi(decimals);
302    let r = ((v * p).round() / p).rem_euclid(360.0) + 0.0; // + 0.0 turns -0.0 into 0.0
303    if r >= 360.0 {
304        0.0
305    } else {
306        r
307    }
308}
309
310/// XML attribute and text escaping. Control characters XML 1.0 cannot carry
311/// are dropped.
312struct Esc<'a>(&'a str);
313
314impl fmt::Display for Esc<'_> {
315    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
316        for c in self.0.chars() {
317            match c {
318                '&' => f.write_str("&amp;")?,
319                '<' => f.write_str("&lt;")?,
320                '>' => f.write_str("&gt;")?,
321                '"' => f.write_str("&quot;")?,
322                '\'' => f.write_str("&apos;")?,
323                '\t' | '\n' | '\r' => write!(f, "&#{};", c as u32)?,
324                c if (c as u32) < 0x20 || c == '\u{FFFE}' || c == '\u{FFFF}' => {}
325                c => f.write_char(c)?,
326            }
327        }
328        Ok(())
329    }
330}
331
332/// Formats microseconds since 1970 as `YYYY-MM-DDTHH:MM:SS.mmmZ`.
333pub struct Iso8601(pub u64);
334
335impl fmt::Display for Iso8601 {
336    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
337        let secs = self.0 / 1_000_000;
338        let ms = (self.0 % 1_000_000) / 1000;
339        let days = (secs / 86_400) as i64;
340        let rem = secs % 86_400;
341        // civil_from_days, H. Hinnant
342        let z = days + 719_468;
343        let era = z.div_euclid(146_097);
344        let doe = z - era * 146_097;
345        let yoe = (doe - doe / 1460 + doe / 36_524 - doe / 146_096) / 365;
346        let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
347        let mp = (5 * doy + 2) / 153;
348        let d = doy - (153 * mp + 2) / 5 + 1;
349        let m = if mp < 10 { mp + 3 } else { mp - 9 };
350        let y = yoe + era * 400 + i64::from(m <= 2);
351        write!(
352            f,
353            "{y:04}-{m:02}-{d:02}T{:02}:{:02}:{:02}.{ms:03}Z",
354            rem / 3600,
355            rem % 3600 / 60,
356            rem % 60
357        )
358    }
359}
360
361/// Microseconds since 1970 UTC, from the system clock.
362pub fn now_us() -> u64 {
363    std::time::SystemTime::now()
364        .duration_since(std::time::UNIX_EPOCH)
365        .map(|d| d.as_micros() as u64)
366        .unwrap_or(0)
367}
368
369#[cfg(test)]
370mod tests {
371    use super::*;
372
373    #[test]
374    fn iso8601() {
375        assert_eq!(Iso8601(0).to_string(), "1970-01-01T00:00:00.000Z");
376        assert_eq!(
377            Iso8601(1_231_798_102_000_000).to_string(),
378            "2009-01-12T22:08:22.000Z"
379        );
380        assert_eq!(
381            Iso8601(951_782_400_123_456).to_string(),
382            "2000-02-29T00:00:00.123Z"
383        );
384        assert_eq!(
385            Iso8601(4_102_444_799_999_999).to_string(),
386            "2099-12-31T23:59:59.999Z"
387        );
388    }
389
390    #[test]
391    fn escaping() {
392        let mut e = Event::new("a\"<b>&'c", "a-u-A", 0, 1);
393        e.remarks = Some("line1\nline2\u{1}".into());
394        let x = e.to_xml();
395        assert!(x.contains("uid=\"a&quot;&lt;b&gt;&amp;&apos;c\""));
396        assert!(x.contains("<remarks>line1&#10;line2</remarks>"));
397    }
398
399    #[test]
400    fn angles_are_normalised() {
401        let mut e = Event::new("x", "a-u-A", 0, 1);
402        e.track = Some(Track {
403            course: -0.0000001,
404            speed: -3.0,
405        });
406        e.sensor = Some(Sensor {
407            azimuth: Some(370.0),
408            roll: Some(270.0),
409            elevation: Some(-120.0),
410            ..Default::default()
411        });
412        let x = e.to_xml();
413        assert!(x.contains("<track course=\"0.0\" speed=\"0.00\"/>"), "{x}");
414        assert!(x.contains("azimuth=\"10.00\" roll=\"-90.00\"/>"), "{x}");
415    }
416}