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    /// Bearing of image north, degrees true (ATAK `north`).
129    pub north: Option<f64>,
130    /// Sensor name.
131    pub model: Option<String>,
132    /// Sensor type (`"r-e"` electro-optical, `"r-i"` infrared ...).
133    pub kind: Option<String>,
134}
135
136/// `<link>`: a reference to another event (for example the platform that
137/// produced a sensor point of interest).
138#[derive(Clone, Debug, PartialEq, Eq)]
139pub struct Link {
140    /// UID of the other event.
141    pub uid: String,
142    /// CoT type of the other event.
143    pub kind: String,
144    /// Relation, for example `"p-p"` (parent-producer).
145    pub relation: String,
146}
147
148/// A CoT 2.0 event.
149#[derive(Clone, Debug, PartialEq)]
150pub struct Event {
151    /// Unique, stable id of the thing described.
152    pub uid: String,
153    /// CoT type, for example `"a-u-A-M-F-Q"`.
154    pub kind: String,
155    /// How the position was obtained (`"m-g"` = GPS).
156    pub how: String,
157    /// Event time, microseconds since 1970 UTC.
158    pub time_us: u64,
159    /// Start of validity, microseconds since 1970 UTC.
160    pub start_us: u64,
161    /// End of validity, microseconds since 1970 UTC.
162    pub stale_us: u64,
163    /// Position.
164    pub point: Point,
165    /// `<contact callsign>`.
166    pub callsign: Option<String>,
167    /// `<track>`.
168    pub track: Option<Track>,
169    /// `<sensor>`.
170    pub sensor: Option<Sensor>,
171    /// `<link>` elements.
172    pub links: Vec<Link>,
173    /// `<remarks>` text.
174    pub remarks: Option<String>,
175    /// `<__video url>`: a video stream TAK clients can open from the marker.
176    pub video_url: Option<String>,
177    /// `<precisionlocation geopointsrc altsrc>`, for example `("GPS", "GPS")`.
178    pub precision_location: Option<(String, String)>,
179}
180
181impl Event {
182    /// A new event of `kind` at `time_us`, stale after `stale_secs`
183    /// seconds, with `how = "m-g"`.
184    pub fn new(
185        uid: impl Into<String>,
186        kind: impl Into<String>,
187        time_us: u64,
188        stale_secs: u64,
189    ) -> Self {
190        Event {
191            uid: uid.into(),
192            kind: kind.into(),
193            how: "m-g".into(),
194            time_us,
195            start_us: time_us,
196            stale_us: time_us.saturating_add(stale_secs.saturating_mul(1_000_000)),
197            point: Point::default(),
198            callsign: None,
199            track: None,
200            sensor: None,
201            links: Vec::new(),
202            remarks: None,
203            video_url: None,
204            precision_location: None,
205        }
206    }
207
208    /// The event as a CoT XML document (one line, with XML declaration).
209    pub fn to_xml(&self) -> String {
210        let mut s = String::with_capacity(512);
211        self.write_xml(&mut s)
212            .expect("writing to a String does not fail");
213        s
214    }
215
216    /// Writes the event as a CoT XML document.
217    pub fn write_xml(&self, w: &mut impl fmt::Write) -> fmt::Result {
218        w.write_str("<?xml version=\"1.0\" encoding=\"UTF-8\"?>")?;
219        write!(
220            w,
221            "<event version=\"2.0\" uid=\"{}\" type=\"{}\" how=\"{}\" time=\"{}\" start=\"{}\" stale=\"{}\">",
222            Esc(&self.uid),
223            Esc(&self.kind),
224            Esc(&self.how),
225            Iso8601(self.time_us),
226            Iso8601(self.start_us),
227            Iso8601(self.stale_us)
228        )?;
229        let p = &self.point;
230        write!(
231            w,
232            "<point lat=\"{:.7}\" lon=\"{:.7}\" hae=\"{:.1}\" ce=\"{:.1}\" le=\"{:.1}\"/>",
233            p.lat,
234            p.lon,
235            finite_or(p.hae, 0.0),
236            finite_or(p.ce, UNKNOWN_ERROR).max(0.0),
237            finite_or(p.le, UNKNOWN_ERROR).max(0.0)
238        )?;
239        w.write_str("<detail>")?;
240        if let Some(c) = &self.callsign {
241            write!(w, "<contact callsign=\"{}\"/>", Esc(c))?;
242        }
243        if let Some((g, a)) = &self.precision_location {
244            write!(
245                w,
246                "<precisionlocation geopointsrc=\"{}\" altsrc=\"{}\"/>",
247                Esc(g),
248                Esc(a)
249            )?;
250        }
251        if let Some(t) = &self.track {
252            if t.course.is_finite() && t.speed.is_finite() {
253                write!(
254                    w,
255                    "<track course=\"{:.1}\" speed=\"{:.2}\"/>",
256                    wrap360(t.course, 1),
257                    t.speed.max(0.0)
258                )?;
259            }
260        }
261        if let Some(sn) = &self.sensor {
262            w.write_str("<sensor")?;
263            if let Some(v) = sn.azimuth.filter(|v| v.is_finite()) {
264                write!(w, " azimuth=\"{:.2}\"", wrap360(v, 2))?;
265            }
266            if let Some(v) = sn.elevation.filter(|v| v.is_finite() && v.abs() <= 90.0) {
267                write!(w, " elevation=\"{v:.2}\"")?;
268            }
269            if let Some(v) = sn.roll.filter(|v| v.is_finite()) {
270                let r = wrap360(v, 2);
271                write!(w, " roll=\"{:.2}\"", if r > 180.0 { r - 360.0 } else { r })?;
272            }
273            if let Some(v) = sn.fov.filter(|v| v.is_finite() && *v >= 0.0 && *v < 360.0) {
274                write!(w, " fov=\"{v:.3}\"")?;
275            }
276            if let Some(v) = sn.vfov.filter(|v| v.is_finite() && *v >= 0.0 && *v < 360.0) {
277                write!(w, " vfov=\"{v:.3}\"")?;
278            }
279            if let Some(v) = sn.range.filter(|v| v.is_finite() && *v >= 0.0) {
280                write!(w, " range=\"{v:.1}\"")?;
281            }
282            if let Some(v) = sn.north.filter(|v| v.is_finite()) {
283                write!(w, " north=\"{:.2}\"", wrap360(v, 2))?;
284            }
285            if let Some(v) = &sn.model {
286                write!(w, " model=\"{}\"", Esc(v))?;
287            }
288            if let Some(v) = &sn.kind {
289                write!(w, " type=\"{}\"", Esc(v))?;
290            }
291            w.write_str("/>")?;
292        }
293        for l in &self.links {
294            write!(
295                w,
296                "<link uid=\"{}\" type=\"{}\" relation=\"{}\"/>",
297                Esc(&l.uid),
298                Esc(&l.kind),
299                Esc(&l.relation)
300            )?;
301        }
302        if let Some(u) = &self.video_url {
303            write!(w, "<__video url=\"{}\"/>", Esc(u))?;
304        }
305        if let Some(r) = &self.remarks {
306            write!(w, "<remarks>{}</remarks>", Esc(r))?;
307        }
308        w.write_str("</detail></event>")
309    }
310}
311
312fn finite_or(v: f64, d: f64) -> f64 {
313    if v.is_finite() {
314        v
315    } else {
316        d
317    }
318}
319
320/// Rounds to `decimals` places, then wraps into `0..360`.
321fn wrap360(v: f64, decimals: i32) -> f64 {
322    let p = 10f64.powi(decimals);
323    let r = ((v * p).round() / p).rem_euclid(360.0) + 0.0; // + 0.0 turns -0.0 into 0.0
324    if r >= 360.0 {
325        0.0
326    } else {
327        r
328    }
329}
330
331/// XML attribute and text escaping. Control characters XML 1.0 cannot carry
332/// are dropped.
333struct Esc<'a>(&'a str);
334
335impl fmt::Display for Esc<'_> {
336    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
337        for c in self.0.chars() {
338            match c {
339                '&' => f.write_str("&amp;")?,
340                '<' => f.write_str("&lt;")?,
341                '>' => f.write_str("&gt;")?,
342                '"' => f.write_str("&quot;")?,
343                '\'' => f.write_str("&apos;")?,
344                '\t' | '\n' | '\r' => write!(f, "&#{};", c as u32)?,
345                c if (c as u32) < 0x20 || c == '\u{FFFE}' || c == '\u{FFFF}' => {}
346                c => f.write_char(c)?,
347            }
348        }
349        Ok(())
350    }
351}
352
353/// Formats microseconds since 1970 as `YYYY-MM-DDTHH:MM:SS.mmmZ`.
354pub struct Iso8601(pub u64);
355
356impl fmt::Display for Iso8601 {
357    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
358        let secs = self.0 / 1_000_000;
359        let ms = (self.0 % 1_000_000) / 1000;
360        let days = (secs / 86_400) as i64;
361        let rem = secs % 86_400;
362        // civil_from_days, H. Hinnant
363        let z = days + 719_468;
364        let era = z.div_euclid(146_097);
365        let doe = z - era * 146_097;
366        let yoe = (doe - doe / 1460 + doe / 36_524 - doe / 146_096) / 365;
367        let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
368        let mp = (5 * doy + 2) / 153;
369        let d = doy - (153 * mp + 2) / 5 + 1;
370        let m = if mp < 10 { mp + 3 } else { mp - 9 };
371        let y = yoe + era * 400 + i64::from(m <= 2);
372        write!(
373            f,
374            "{y:04}-{m:02}-{d:02}T{:02}:{:02}:{:02}.{ms:03}Z",
375            rem / 3600,
376            rem % 3600 / 60,
377            rem % 60
378        )
379    }
380}
381
382/// Microseconds since 1970 UTC, from the system clock.
383pub fn now_us() -> u64 {
384    std::time::SystemTime::now()
385        .duration_since(std::time::UNIX_EPOCH)
386        .map(|d| d.as_micros() as u64)
387        .unwrap_or(0)
388}
389
390#[cfg(test)]
391mod tests {
392    use super::*;
393
394    #[test]
395    fn iso8601() {
396        assert_eq!(Iso8601(0).to_string(), "1970-01-01T00:00:00.000Z");
397        assert_eq!(
398            Iso8601(1_231_798_102_000_000).to_string(),
399            "2009-01-12T22:08:22.000Z"
400        );
401        assert_eq!(
402            Iso8601(951_782_400_123_456).to_string(),
403            "2000-02-29T00:00:00.123Z"
404        );
405        assert_eq!(
406            Iso8601(4_102_444_799_999_999).to_string(),
407            "2099-12-31T23:59:59.999Z"
408        );
409    }
410
411    #[test]
412    fn escaping() {
413        let mut e = Event::new("a\"<b>&'c", "a-u-A", 0, 1);
414        e.remarks = Some("line1\nline2\u{1}".into());
415        let x = e.to_xml();
416        assert!(x.contains("uid=\"a&quot;&lt;b&gt;&amp;&apos;c\""));
417        assert!(x.contains("<remarks>line1&#10;line2</remarks>"));
418    }
419
420    #[test]
421    fn angles_are_normalised() {
422        let mut e = Event::new("x", "a-u-A", 0, 1);
423        e.track = Some(Track {
424            course: -0.0000001,
425            speed: -3.0,
426        });
427        e.sensor = Some(Sensor {
428            azimuth: Some(370.0),
429            roll: Some(270.0),
430            elevation: Some(-120.0),
431            ..Default::default()
432        });
433        let x = e.to_xml();
434        assert!(x.contains("<track course=\"0.0\" speed=\"0.00\"/>"), "{x}");
435        assert!(x.contains("azimuth=\"10.00\" roll=\"-90.00\"/>"), "{x}");
436        e.sensor = Some(Sensor {
437            north: Some(-90.0),
438            ..Default::default()
439        });
440        assert!(e.to_xml().contains("<sensor north=\"270.00\"/>"));
441    }
442}