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