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