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