1#![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#[cfg(feature = "remoteid")]
47pub use remoteid;
48
49#[cfg(feature = "misb")]
52pub use misb;
53
54#[cfg(feature = "tls")]
58pub use rustls;
59
60#[cfg(all(doctest, feature = "remoteid"))]
61#[doc = include_str!("../docs/integration.md")]
62struct IntegrationDoctests;
63
64pub const UNKNOWN_ERROR: f64 = 9_999_999.0;
66
67#[derive(Clone, Copy, Debug, PartialEq)]
70pub struct Point {
71 pub lat: f64,
73 pub lon: f64,
75 pub hae: f64,
77 pub ce: f64,
79 pub le: f64,
81}
82
83impl Point {
84 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 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#[derive(Clone, Copy, Debug, PartialEq)]
112pub struct Track {
113 pub course: f64,
115 pub speed: f64,
117}
118
119#[derive(Clone, Debug, Default, PartialEq)]
122pub struct Sensor {
123 pub azimuth: Option<f64>,
125 pub elevation: Option<f64>,
127 pub roll: Option<f64>,
129 pub fov: Option<f64>,
131 pub vfov: Option<f64>,
133 pub range: Option<f64>,
135 pub north: Option<f64>,
137 pub model: Option<String>,
139 pub kind: Option<String>,
141}
142
143#[derive(Clone, Debug, PartialEq, Eq)]
146pub struct Link {
147 pub uid: String,
149 pub kind: String,
151 pub relation: String,
153}
154
155#[derive(Clone, Debug, PartialEq)]
157pub struct Event {
158 pub uid: String,
160 pub kind: String,
162 pub how: String,
164 pub time_us: u64,
166 pub start_us: u64,
168 pub stale_us: u64,
170 pub point: Point,
172 pub callsign: Option<String>,
174 pub track: Option<Track>,
176 pub sensor: Option<Sensor>,
178 pub links: Vec<Link>,
180 pub remarks: Option<String>,
182 pub video_url: Option<String>,
184 pub precision_location: Option<(String, String)>,
186}
187
188impl Event {
189 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 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 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
327fn 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; if r >= 360.0 {
332 0.0
333 } else {
334 r
335 }
336}
337
338struct 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("&")?,
347 '<' => f.write_str("<")?,
348 '>' => f.write_str(">")?,
349 '"' => f.write_str(""")?,
350 '\'' => f.write_str("'")?,
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
360pub 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 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
389pub 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"<b>&'c\""));
424 assert!(x.contains("<remarks>line1 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}