1#![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
41pub const UNKNOWN_ERROR: f64 = 9_999_999.0;
43
44#[derive(Clone, Copy, Debug, PartialEq)]
47pub struct Point {
48 pub lat: f64,
50 pub lon: f64,
52 pub hae: f64,
54 pub ce: f64,
56 pub le: f64,
58}
59
60impl Point {
61 pub fn new(lat: f64, lon: f64, hae: f64) -> Self {
63 Point {
64 lat,
65 lon,
66 hae,
67 ce: UNKNOWN_ERROR,
68 le: UNKNOWN_ERROR,
69 }
70 }
71
72 pub fn is_valid(&self) -> bool {
74 self.lat.is_finite()
75 && self.lon.is_finite()
76 && self.lat.abs() <= 90.0
77 && self.lon.abs() <= 180.0
78 }
79}
80
81impl Default for Point {
82 fn default() -> Self {
83 Point::new(0.0, 0.0, 0.0)
84 }
85}
86
87#[derive(Clone, Copy, Debug, PartialEq)]
89pub struct Track {
90 pub course: f64,
92 pub speed: f64,
94}
95
96#[derive(Clone, Debug, Default, PartialEq)]
99pub struct Sensor {
100 pub azimuth: Option<f64>,
102 pub elevation: Option<f64>,
104 pub roll: Option<f64>,
106 pub fov: Option<f64>,
108 pub vfov: Option<f64>,
110 pub range: Option<f64>,
112 pub model: Option<String>,
114 pub kind: Option<String>,
116}
117
118#[derive(Clone, Debug, PartialEq, Eq)]
121pub struct Link {
122 pub uid: String,
124 pub kind: String,
126 pub relation: String,
128}
129
130#[derive(Clone, Debug, PartialEq)]
132pub struct Event {
133 pub uid: String,
135 pub kind: String,
137 pub how: String,
139 pub time_us: u64,
141 pub start_us: u64,
143 pub stale_us: u64,
145 pub point: Point,
147 pub callsign: Option<String>,
149 pub track: Option<Track>,
151 pub sensor: Option<Sensor>,
153 pub links: Vec<Link>,
155 pub remarks: Option<String>,
157 pub video_url: Option<String>,
159 pub precision_location: Option<(String, String)>,
161}
162
163impl Event {
164 pub fn new(
167 uid: impl Into<String>,
168 kind: impl Into<String>,
169 time_us: u64,
170 stale_secs: u64,
171 ) -> Self {
172 Event {
173 uid: uid.into(),
174 kind: kind.into(),
175 how: "m-g".into(),
176 time_us,
177 start_us: time_us,
178 stale_us: time_us.saturating_add(stale_secs.saturating_mul(1_000_000)),
179 point: Point::default(),
180 callsign: None,
181 track: None,
182 sensor: None,
183 links: Vec::new(),
184 remarks: None,
185 video_url: None,
186 precision_location: None,
187 }
188 }
189
190 pub fn to_xml(&self) -> String {
192 let mut s = String::with_capacity(512);
193 self.write_xml(&mut s)
194 .expect("writing to a String does not fail");
195 s
196 }
197
198 pub fn write_xml(&self, w: &mut impl fmt::Write) -> fmt::Result {
200 w.write_str("<?xml version=\"1.0\" encoding=\"UTF-8\"?>")?;
201 write!(
202 w,
203 "<event version=\"2.0\" uid=\"{}\" type=\"{}\" how=\"{}\" time=\"{}\" start=\"{}\" stale=\"{}\">",
204 Esc(&self.uid),
205 Esc(&self.kind),
206 Esc(&self.how),
207 Iso8601(self.time_us),
208 Iso8601(self.start_us),
209 Iso8601(self.stale_us)
210 )?;
211 let p = &self.point;
212 write!(
213 w,
214 "<point lat=\"{:.7}\" lon=\"{:.7}\" hae=\"{:.1}\" ce=\"{:.1}\" le=\"{:.1}\"/>",
215 p.lat,
216 p.lon,
217 finite_or(p.hae, 0.0),
218 finite_or(p.ce, UNKNOWN_ERROR).max(0.0),
219 finite_or(p.le, UNKNOWN_ERROR).max(0.0)
220 )?;
221 w.write_str("<detail>")?;
222 if let Some(c) = &self.callsign {
223 write!(w, "<contact callsign=\"{}\"/>", Esc(c))?;
224 }
225 if let Some((g, a)) = &self.precision_location {
226 write!(
227 w,
228 "<precisionlocation geopointsrc=\"{}\" altsrc=\"{}\"/>",
229 Esc(g),
230 Esc(a)
231 )?;
232 }
233 if let Some(t) = &self.track {
234 if t.course.is_finite() && t.speed.is_finite() {
235 write!(
236 w,
237 "<track course=\"{:.1}\" speed=\"{:.2}\"/>",
238 wrap360(t.course, 1),
239 t.speed.max(0.0)
240 )?;
241 }
242 }
243 if let Some(sn) = &self.sensor {
244 w.write_str("<sensor")?;
245 if let Some(v) = sn.azimuth.filter(|v| v.is_finite()) {
246 write!(w, " azimuth=\"{:.2}\"", wrap360(v, 2))?;
247 }
248 if let Some(v) = sn.elevation.filter(|v| v.is_finite() && v.abs() <= 90.0) {
249 write!(w, " elevation=\"{v:.2}\"")?;
250 }
251 if let Some(v) = sn.roll.filter(|v| v.is_finite()) {
252 let r = wrap360(v, 2);
253 write!(w, " roll=\"{:.2}\"", if r > 180.0 { r - 360.0 } else { r })?;
254 }
255 if let Some(v) = sn.fov.filter(|v| v.is_finite() && *v >= 0.0 && *v < 360.0) {
256 write!(w, " fov=\"{v:.3}\"")?;
257 }
258 if let Some(v) = sn.vfov.filter(|v| v.is_finite() && *v >= 0.0 && *v < 360.0) {
259 write!(w, " vfov=\"{v:.3}\"")?;
260 }
261 if let Some(v) = sn.range.filter(|v| v.is_finite() && *v >= 0.0) {
262 write!(w, " range=\"{v:.1}\"")?;
263 }
264 if let Some(v) = &sn.model {
265 write!(w, " model=\"{}\"", Esc(v))?;
266 }
267 if let Some(v) = &sn.kind {
268 write!(w, " type=\"{}\"", Esc(v))?;
269 }
270 w.write_str("/>")?;
271 }
272 for l in &self.links {
273 write!(
274 w,
275 "<link uid=\"{}\" type=\"{}\" relation=\"{}\"/>",
276 Esc(&l.uid),
277 Esc(&l.kind),
278 Esc(&l.relation)
279 )?;
280 }
281 if let Some(u) = &self.video_url {
282 write!(w, "<__video url=\"{}\"/>", Esc(u))?;
283 }
284 if let Some(r) = &self.remarks {
285 write!(w, "<remarks>{}</remarks>", Esc(r))?;
286 }
287 w.write_str("</detail></event>")
288 }
289}
290
291fn finite_or(v: f64, d: f64) -> f64 {
292 if v.is_finite() {
293 v
294 } else {
295 d
296 }
297}
298
299fn wrap360(v: f64, decimals: i32) -> f64 {
301 let p = 10f64.powi(decimals);
302 let r = ((v * p).round() / p).rem_euclid(360.0) + 0.0; if r >= 360.0 {
304 0.0
305 } else {
306 r
307 }
308}
309
310struct Esc<'a>(&'a str);
313
314impl fmt::Display for Esc<'_> {
315 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
316 for c in self.0.chars() {
317 match c {
318 '&' => f.write_str("&")?,
319 '<' => f.write_str("<")?,
320 '>' => f.write_str(">")?,
321 '"' => f.write_str(""")?,
322 '\'' => f.write_str("'")?,
323 '\t' | '\n' | '\r' => write!(f, "&#{};", c as u32)?,
324 c if (c as u32) < 0x20 || c == '\u{FFFE}' || c == '\u{FFFF}' => {}
325 c => f.write_char(c)?,
326 }
327 }
328 Ok(())
329 }
330}
331
332pub struct Iso8601(pub u64);
334
335impl fmt::Display for Iso8601 {
336 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
337 let secs = self.0 / 1_000_000;
338 let ms = (self.0 % 1_000_000) / 1000;
339 let days = (secs / 86_400) as i64;
340 let rem = secs % 86_400;
341 let z = days + 719_468;
343 let era = z.div_euclid(146_097);
344 let doe = z - era * 146_097;
345 let yoe = (doe - doe / 1460 + doe / 36_524 - doe / 146_096) / 365;
346 let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
347 let mp = (5 * doy + 2) / 153;
348 let d = doy - (153 * mp + 2) / 5 + 1;
349 let m = if mp < 10 { mp + 3 } else { mp - 9 };
350 let y = yoe + era * 400 + i64::from(m <= 2);
351 write!(
352 f,
353 "{y:04}-{m:02}-{d:02}T{:02}:{:02}:{:02}.{ms:03}Z",
354 rem / 3600,
355 rem % 3600 / 60,
356 rem % 60
357 )
358 }
359}
360
361pub fn now_us() -> u64 {
363 std::time::SystemTime::now()
364 .duration_since(std::time::UNIX_EPOCH)
365 .map(|d| d.as_micros() as u64)
366 .unwrap_or(0)
367}
368
369#[cfg(test)]
370mod tests {
371 use super::*;
372
373 #[test]
374 fn iso8601() {
375 assert_eq!(Iso8601(0).to_string(), "1970-01-01T00:00:00.000Z");
376 assert_eq!(
377 Iso8601(1_231_798_102_000_000).to_string(),
378 "2009-01-12T22:08:22.000Z"
379 );
380 assert_eq!(
381 Iso8601(951_782_400_123_456).to_string(),
382 "2000-02-29T00:00:00.123Z"
383 );
384 assert_eq!(
385 Iso8601(4_102_444_799_999_999).to_string(),
386 "2099-12-31T23:59:59.999Z"
387 );
388 }
389
390 #[test]
391 fn escaping() {
392 let mut e = Event::new("a\"<b>&'c", "a-u-A", 0, 1);
393 e.remarks = Some("line1\nline2\u{1}".into());
394 let x = e.to_xml();
395 assert!(x.contains("uid=\"a"<b>&'c\""));
396 assert!(x.contains("<remarks>line1 line2</remarks>"));
397 }
398
399 #[test]
400 fn angles_are_normalised() {
401 let mut e = Event::new("x", "a-u-A", 0, 1);
402 e.track = Some(Track {
403 course: -0.0000001,
404 speed: -3.0,
405 });
406 e.sensor = Some(Sensor {
407 azimuth: Some(370.0),
408 roll: Some(270.0),
409 elevation: Some(-120.0),
410 ..Default::default()
411 });
412 let x = e.to_xml();
413 assert!(x.contains("<track course=\"0.0\" speed=\"0.00\"/>"), "{x}");
414 assert!(x.contains("azimuth=\"10.00\" roll=\"-90.00\"/>"), "{x}");
415 }
416}