Skip to main content

hpr_flightdata/
log.rs

1//! The flight record every log reader produces: a clock, the channels the logger recorded on it,
2//! and what the file states about itself.
3//!
4//! Units are SI, converted from the file's own at reading: meters, meters per second, kelvin,
5//! volts. A gap in a channel, such as a row that left a column out, is `NaN`.
6
7use schemars::JsonSchema;
8use serde::{Deserialize, Serialize};
9
10/// A flight log, read.
11#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
12pub struct FlightLog {
13    /// The file format it was read from.
14    pub format: LogFormat,
15    /// The logger, as the file names it, such as `PerfectFlite Pnut`.
16    pub logger: String,
17    /// The logger's serial number, as the file states it.
18    pub serial_number: Option<String>,
19    /// The logger's firmware version, as the file states it.
20    pub firmware: Option<String>,
21    /// The flight's number in the logger's memory, as the file states it.
22    pub flight_number: Option<u32>,
23    /// What the file states about the flight: the logger's own figures, kept beside HPR Sim's
24    /// readings and never in place of them.
25    pub stated: Stated,
26    /// Each sample's time, s, from the logger's own zero. Strictly increasing.
27    pub time_s: Vec<f64>,
28    /// The barometric altitude, m, as the logger converts its pressure, above the logger's own
29    /// zero: for a PerfectFlite, its reading on the pad.
30    #[serde(with = "gaps")]
31    #[schemars(with = "Vec<Option<f64>>")]
32    pub altitude_m: Vec<f64>,
33    /// The vertical speed, m/s, up positive, as the logger computes it; `None` if the file has
34    /// no such column. A barometric logger works it out from its own altitude.
35    #[serde(with = "optional_gaps", default)]
36    #[schemars(with = "Option<Vec<Option<f64>>>")]
37    pub vertical_speed_m_s: Option<Vec<f64>>,
38    /// The logger's temperature sensor, K; `None` if the file has no such column, or if its unit
39    /// can't be told (the column is then kept as written in `channels`). It sits in the
40    /// electronics bay, so it reads the bay, not the air.
41    #[serde(with = "optional_gaps", default)]
42    #[schemars(with = "Option<Vec<Option<f64>>>")]
43    pub temperature_k: Option<Vec<f64>>,
44    /// The logger's battery voltage, V; `None` if the file has no such column.
45    #[serde(with = "optional_gaps", default)]
46    #[schemars(with = "Option<Vec<Option<f64>>>")]
47    pub battery_v: Option<Vec<f64>>,
48    /// Every data column the file holds, in the file's order, each on its own clock and in SI:
49    /// the primary track's columns above included, so that the record keeps every sample the
50    /// logger wrote. A clock column is the time of its channels, not a channel itself. Empty in
51    /// a record written before the field was.
52    #[serde(default)]
53    pub channels: Vec<Channel>,
54    /// What the logger says happened and when, such as an AltOS flight computer's change of
55    /// state: in the file's order, or in time order where the file states them apart from its
56    /// rows, as an Eggtimer's summary does.
57    #[serde(default)]
58    pub events: Vec<Event>,
59    /// What the reader noticed and worked around, such as a sample count that differs from the
60    /// one the file states.
61    pub notes: Vec<String>,
62}
63
64impl Channel {
65    /// A channel from its column's name, its quantity, and each sample's time and value, in SI.
66    ///
67    /// Readers build channels as they read a file; this is for records made another way, such as
68    /// a synthetic flight's log (`hpr_forensics::synthetic`).
69    pub fn new(
70        column: impl Into<String>,
71        quantity: Quantity,
72        time_s: Vec<f64>,
73        values: Vec<f64>,
74    ) -> Self {
75        Self {
76            column: column.into(),
77            quantity,
78            time_s,
79            values,
80        }
81    }
82}
83
84impl FlightLog {
85    /// The channels measuring a quantity, in the file's order.
86    pub fn channels_of(&self, quantity: Quantity) -> impl Iterator<Item = &Channel> {
87        self.channels
88            .iter()
89            .filter(move |channel| channel.quantity == quantity)
90    }
91}
92
93/// One column of a flight log, on its own clock.
94#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
95#[non_exhaustive]
96pub struct Channel {
97    /// The column's name as the file writes it, such as `Axial Accel (Gs)`: it says which axis
98    /// or sensor a quantity came from where the file says so.
99    pub column: String,
100    /// What the column measures, which sets its unit.
101    pub quantity: Quantity,
102    /// Each sample's time, s, from the log's zero, the same zero as [`FlightLog::time_s`]; `NaN`
103    /// where the file gives the sample no time, as a KML path without times does (the GPS logs'
104    /// decision, [ADR-254][adr-254]). In the file's order, so a time may go back where the
105    /// logger's clock did.
106    ///
107    /// [adr-254]: https://github.com/nrdptel/fusionspace-eridanus/blob/main/docs/decisions/0254-gps-tracks-first-among-the-other-importers.md
108    #[serde(with = "gaps")]
109    #[schemars(with = "Vec<Option<f64>>")]
110    pub time_s: Vec<f64>,
111    /// Each sample's value in the quantity's unit ([`Quantity::unit`]); `NaN` where the file left
112    /// the cell empty or wrote something that isn't a number.
113    #[serde(with = "gaps")]
114    #[schemars(with = "Vec<Option<f64>>")]
115    pub values: Vec<f64>,
116}
117
118/// What a channel measures. The unit is SI but for angles, which are in degrees as GNSS
119/// receivers and loggers write them.
120#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize, JsonSchema)]
121#[serde(rename_all = "snake_case")]
122#[non_exhaustive]
123pub enum Quantity {
124    /// A barometric altitude above the logger's own zero, m; in a Featherweight GPS tracker's
125    /// summary ([`LogFormat::FeatherweightSummaryCsv`]), its receiver's altitude above the pad it
126    /// states.
127    AltitudeAboveGround,
128    /// A barometric altitude above mean sea level, m.
129    AltitudeMsl,
130    /// An altitude from GNSS, above mean sea level as the receiver states it, m.
131    GnssAltitude,
132    /// An altitude the logger integrated from its accelerometer, above its zero, m.
133    InertialAltitude,
134    /// An altitude whose sensor or zero the file doesn't state, m: a table read by its header
135    /// ([`LogFormat::GenericTable`]) names an altitude and its unit, and often no more.
136    Altitude,
137    /// Air pressure, Pa.
138    Pressure,
139    /// A speed or velocity the logger computed, m/s; its column says from which sensor and along
140    /// which direction.
141    Speed,
142    /// An acceleration, m/s²; its column says along which axis, and whether gravity is in it.
143    Acceleration,
144    /// A temperature, K.
145    Temperature,
146    /// An electric potential, V, such as a battery's or a pyro channel's.
147    Voltage,
148    /// An electric current, A.
149    Current,
150    /// A latitude, degrees north.
151    Latitude,
152    /// A longitude, degrees east.
153    Longitude,
154    /// An angle, degrees, such as a tilt or a bearing.
155    Angle,
156    /// A rate of turn, degrees per second, such as a gyroscope's about one of its axes.
157    AngularRate,
158    /// A distance, m, such as a GNSS receiver's range from the pad.
159    Distance,
160    /// A time of day on the logger's own clock, s after its midnight, in whatever time zone the
161    /// clock was set to: files state none.
162    TimeOfDay,
163    /// A length of time, s, such as a summary's time from liftoff to an event.
164    Duration,
165    /// A number with no unit, such as a count of satellites, a signal strength, a flag or a
166    /// state code, as the file writes it, or a fraction, such as a percentage the file writes,
167    /// divided by 100.
168    Number,
169    /// A column HPR Sim doesn't know: its values as the file writes them, in a unit HPR Sim
170    /// doesn't know either.
171    Unrecognized,
172}
173
174impl Quantity {
175    /// The unit of a channel's values.
176    pub fn unit(self) -> &'static str {
177        match self {
178            Self::AltitudeAboveGround
179            | Self::AltitudeMsl
180            | Self::GnssAltitude
181            | Self::InertialAltitude
182            | Self::Altitude
183            | Self::Distance => "m",
184            Self::Pressure => "Pa",
185            Self::Speed => "m/s",
186            Self::Acceleration => "m/s²",
187            Self::Temperature => "K",
188            Self::Voltage => "V",
189            Self::Current => "A",
190            Self::Latitude | Self::Longitude | Self::Angle => "°",
191            Self::AngularRate => "°/s",
192            Self::TimeOfDay | Self::Duration => "s",
193            Self::Number | Self::Unrecognized => "",
194        }
195    }
196}
197
198/// Something the logger says happened, at a time on the log's clock.
199#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
200#[non_exhaustive]
201pub struct Event {
202    /// When, s, from the log's zero.
203    pub time_s: f64,
204    /// What, in the logger's own word, such as `boost` or `drogue`.
205    pub name: String,
206}
207
208/// A flight log's file format.
209#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
210#[serde(rename_all = "snake_case")]
211#[non_exhaustive]
212pub enum LogFormat {
213    /// PerfectFlite's `.pf2`, as its software writes a Pnut's, a StratoLogger's or a
214    /// StratoLoggerCF's flights.
215    PerfectFlitePf2,
216    /// PerfectFlite's comma-separated export: a header row such as `Time, Altitude, Velocity,
217    /// Temperature (F), Voltage`, then rows in seconds and feet.
218    PerfectFliteCsv,
219    /// PerfectFlite's tab-separated text export: a header row such as `Time Altitude Temp.
220    /// Voltage`, then rows in seconds and feet.
221    PerfectFliteText,
222    /// AltOS's CSV, as AltosUI exports a TeleMetrum's, TeleMega's, EasyMega's or EasyMini's
223    /// flight: a `#version,serial,flight,…` header, then rows in SI.
224    AltosCsv,
225    /// The Featherweight Raven's FIP CSV, as the Featherweight Interface Program exports it: each
226    /// channel its own `Time@` column, its values, and a status column.
227    RavenFipCsv,
228    /// Missile Works' mDACS export of an RRC3's flight: a header row `Time, Altitude, Pressure,
229    /// Velocity, Temperature, Events, Voltages`, then rows on one clock.
230    Rrc3Csv,
231    /// An Eggtimer's flight data, as its own download writes it: a header row such as `T, Alt,
232    /// VRaw, VFilt`, then rows on one clock.
233    EggtimerCsv,
234    /// The Featherweight Blue Raven's CSV, as its phone app exports a flight: a low-rate file of
235    /// its barometric and inertial figures, or a high-rate file of its inertial sensors, each
236    /// with a header row such as `Year,Month,Day,Time,Flight_Time_(s),…`.
237    BlueRavenCsv,
238    /// A Featherweight GPS tracker's CSV, as its ground station's app or software writes it: the
239    /// tracker's log, with a header row such as `UTCTIME,UNIXTIME,ALT,LAT,LON,#SATS,…`, or the
240    /// ground station's, such as `TRACKER,DATE,TIME,LAT,LON,ALT,…`. Positions only, no barometer.
241    FeatherweightGpsCsv,
242    /// A KML file (OGC 07-147r2) holding a GPS track as a path or a `gx:Track`, as AltOS, Missile
243    /// Works' RTx, Big Red Bee's BeeLine, fw2kml and others write it. Positions only.
244    Kml,
245    /// A GPS receiver's NMEA 0183 sentences as it wrote them, such as `$GPGGA,…*hh`. Positions
246    /// only.
247    Nmea0183,
248    /// PerfectFlite's older `.pfa`, as its software saves an Alt15K/WD's flight: `Ground:`,
249    /// `Apogee:` and `NumSamps:` lines, then `**!!Data:` and one altitude a line.
250    PerfectFlitePfa,
251    /// An Eggtimer TRS's flight as its terminal download prints it: the flight settings and the
252    /// flight summary, then the table the CSV download writes.
253    EggtimerText,
254    /// AltimeterCloud's CSV of a Rocketry Ltd Nano V1's or Mercury's flight, as a flight page on
255    /// altimetercloud.com hands it back: a header row such as `Time(ms),Altitude(m),…`.
256    AltimeterCloudCsv,
257    /// Entacore AIM's CSV, as its software exports a flight: each channel beside its own `time`
258    /// column.
259    EntacoreAimCsv,
260    /// AerospaceNU's SillyGoose flight computer's log, as the board writes it: tab-separated
261    /// text under a header such as `timestampMs pressurePa tempK …`.
262    SillyGooseText,
263    /// Silicdyne's Fluctus flight computer's CSV: a `sep=;` line, then a semicolon-separated
264    /// table whose names carry their units, such as `time (ms);baro-altitude (m);…`.
265    FluctusCsv,
266    /// Ozark Aerospace's ARTS2 interpreted data: a `# MET Acc Vel iAlt pAlt` header, then
267    /// comma-separated rows from launch.
268    Arts2Csv,
269    /// AerospaceNU's flight computer board's CSV, as the club's tools write a flight: a header
270    /// row opening `,packetType,timestamp_ms,…` or `,timestamp_s,…`, then one row a sample.
271    AerospaceNuFcbCsv,
272    /// AerospaceNU's ground station's text, as it parses the flight computer board's downlink: a
273    /// `RUN START` line, then one packet a line, `HH:MM:SS.ffffff: <packet> {…}`.
274    AerospaceNuGroundStationText,
275    /// A phone app's `launch….csv`: a header row opening `Seconds,Timestamp,AltitudeMSLGPS,…`,
276    /// then one row a sample. The app isn't named in its files.
277    PhoneLaunchCsv,
278    /// An Eggtimer TRS's terminal download, as [`LogFormat::EggtimerText`] reads it, saved inside
279    /// an RTF document.
280    EggtimerRtf,
281    /// The Featherweight Raven's raw download, `.FIPa`, as the Featherweight Interface Program
282    /// saves the altimeter's memory: a text header, then checksummed binary frames.
283    RavenFipa,
284    /// Missile Works' RRC3 raw flight file, `.rff`, as mDACS saves a download: a .NET
285    /// `BinaryFormatter` stream holding the altimeter's 16-bit words.
286    Rrc3Rff,
287    /// A Featherweight summary, as the Featherweight UI app exports a Blue Raven's or a GPS
288    /// tracker's flight beside its data: one `name,value` row a figure, such as `Max
289    /// Altitude,2500.25 feet`, and no samples.
290    FeatherweightSummaryCsv,
291    /// AED Electronics' R-DAS raw data, as its Windows software exports a flight to text: a
292    /// `*** Configuration ***` section, then a table of the converters' counts.
293    RdasText,
294    /// AltOS radio telemetry, as AltosUI saves the packets a TeleDongle hears to a `.telem`
295    /// file: one `TELEM` line a packet, its bytes in hexadecimal.
296    AltosTelemetry,
297    /// AltOS's raw flight download, as AltosUI saves a flight computer's memory to an `.eeprom`
298    /// file: a JSON object of the board's configuration then the memory in hexadecimal, or, from
299    /// older versions, the configuration as the board prints it then one record a line.
300    AltosEeprom,
301    /// Ozark Aerospace ARTS2's flight as its PC software saves it to an `.odf` file: the board's
302    /// settings and calibration, then the sensors' counts.
303    Arts2Odf,
304    /// Ozark Aerospace ARTS2's raw data, as its PC software exports a flight: a
305    /// `MET,Acc(HI),Acc/Baro(LO),Baro(HI),State` header, then the sensors' counts.
306    Arts2RawCsv,
307    /// Missile Works' RTx/GPS tracker's fixes, as mDACS saves a download to an `.rtx` file: a
308    /// .NET `BinaryFormatter` stream of one `List<Int32>`, each slot a 16-bit word mapped modulo
309    /// 10⁹. Positions only.
310    RtxRaw,
311    /// The RTx's fixes as mDACS exports them to CSV: a `UTC Time,Latitude,Longitude,Altitude,…`
312    /// header, then one row a fix. Positions only.
313    RtxCsv,
314    /// The RTx's fixes as mDACS exports them to text: a tab-separated `UTC Lat Lon Alt …` header,
315    /// then one row a fix. Positions only.
316    RtxText,
317    /// A table of samples from a logger no other reader knows, read by what its header states: a
318    /// header row naming the columns, the units in the names, such as `Time (s),Alt AGL (ft)`,
319    /// then one row a sample ([`crate::generic`]); or read by a column mapping the caller gives.
320    GenericTable,
321    /// A file of binary records end to end, each a run of fields, read by a layout the caller
322    /// states, since the file states none ([`crate::records`]).
323    BinaryRecords,
324    /// A serial console's capture of a flight computer's shell, its memory dumped as base64
325    /// between marker lines such as `----++++//[[( data start )]]\\++++----`, each block's
326    /// records read by a layout the caller states ([`crate::capture`]).
327    ConsoleCapture,
328    /// The Featherweight Blue Raven's flight data as its USB port downloads it to a serial
329    /// terminal: one `@ LOG_LOW` or `@ LOG_HIR` line a sample, each closed by a CRC
330    /// ([`crate::blueraven_usb`]).
331    BlueRavenUsb,
332    /// A course's Teensy data logger, tab-separated: a sensor's tag, the clock in microseconds,
333    /// then its values, such as `Alt`, the clock, `P` and a pressure, `MSL` and an altitude
334    /// ([`crate::teensy`]).
335    TeensyTabs,
336    /// A course's Teensy data logger with named fields: units lines such as `MS5 data in us, deg
337    /// C, Pa`, then lines such as `MS5, t, 1330004120, T, 32.90, P, 92185` ([`crate::teensy`]).
338    TeensyNamed,
339    /// One team's radio telemetry packets as text, one `255:…:254` packet a line, such as
340    /// `255:T:11:PP:100150:950.12:21.50:3.25:254`: the flight computer's own log, or what a
341    /// receiver heard ([`crate::packets`]).
342    RadioPacketText,
343    /// The same packets in an RTF document a spreadsheet saved as CSV, one `255,…,254` packet a
344    /// line ([`crate::packets::read_rtf`]).
345    RadioPacketRtf,
346    /// Rocketronics' AltiMAX, a flight as its PC software exports it to an `.xls` worksheet
347    /// ([`crate::xls`]), read as a table headed `TIME,PRESS FILTER [hpa],HEIGHT FILTER [m],…`
348    /// ([`crate::altimax`]).
349    AltimaxXls,
350    /// A MARSA altimeter's flight download: its settings as `<NAME> value` lines, such as
351    /// `<BARO_ZERO 0> 790`, then a row a sample of the time, the altitude in feet and the
352    /// acceleration in g, such as `0.1,-29.0,8.65`; the `.dat` the altimeter's software saves, or
353    /// a spreadsheet's re-save of it ([`crate::marsa`]).
354    Marsa,
355    /// AltOS's radio telemetry decoded to a table, one row a packet under a header of the
356    /// packet's fields, `serial,tick,ptype,state,…,height,crc` ([`crate::altos_telem_csv`]).
357    AltosTelemetryCsv,
358    /// Rocketronics' AltiMAX, a flight's `.ALS` file: a header, then a record of 22 bytes a
359    /// sample, its pressures, acceleration, event and one voltage channel's count
360    /// ([`crate::altimax_als`]).
361    AltimaxAls,
362    /// Entacore AIM XTRA, a flight as its software saves it to an `.xtra` file, a Boost binary
363    /// archive of one record a sensor group's sample ([`crate::entacore_raw`]).
364    EntacoreXtra,
365    /// Entacore AIM XTRA, one recording of its memory as its software downloads it, raw: a
366    /// type byte and big-endian fields a record, between bytes that count the clock's ticks
367    /// ([`crate::entacore_raw::read_dump`]).
368    EntacoreDump,
369    /// A GPX file, the GPS Exchange Format, version 1.0 or 1.1 as Topografix publishes it: its
370    /// tracks' points, each segment a GPS track ([`crate::gpx`]). Positions only.
371    Gpx,
372}
373
374/// Serde for a list of values whose gaps are `NaN`: each gap written as `null`, and a `null` read
375/// back as `NaN`, so that a record survives its own JSON.
376mod gaps {
377    use serde::{Deserialize, Deserializer, Serialize, Serializer};
378
379    /// A list written with its gaps as `null`.
380    pub struct Written<'a>(pub &'a [f64]);
381
382    impl Serialize for Written<'_> {
383        fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
384            serializer.collect_seq(
385                self.0
386                    .iter()
387                    .map(|value| (!value.is_nan()).then_some(*value)),
388            )
389        }
390    }
391
392    pub fn serialize<S: Serializer>(values: &[f64], serializer: S) -> Result<S::Ok, S::Error> {
393        Written(values).serialize(serializer)
394    }
395
396    pub fn deserialize<'de, D: Deserializer<'de>>(deserializer: D) -> Result<Vec<f64>, D::Error> {
397        let values: Vec<Option<f64>> = Vec::deserialize(deserializer)?;
398        Ok(values
399            .into_iter()
400            .map(|value| value.unwrap_or(f64::NAN))
401            .collect())
402    }
403}
404
405/// [`gaps`] for a list the file may not have: absent or `null` is `None`.
406mod optional_gaps {
407    use serde::{Deserialize, Deserializer, Serializer};
408
409    pub fn serialize<S: Serializer>(
410        values: &Option<Vec<f64>>,
411        serializer: S,
412    ) -> Result<S::Ok, S::Error> {
413        match values {
414            Some(values) => serializer.serialize_some(&super::gaps::Written(values)),
415            None => serializer.serialize_none(),
416        }
417    }
418
419    pub fn deserialize<'de, D: Deserializer<'de>>(
420        deserializer: D,
421    ) -> Result<Option<Vec<f64>>, D::Error> {
422        let values: Option<Vec<Option<f64>>> = Option::deserialize(deserializer)?;
423        Ok(values.map(|values| {
424            values
425                .into_iter()
426                .map(|value| value.unwrap_or(f64::NAN))
427                .collect()
428        }))
429    }
430}
431
432/// `text` with its first letter in upper case, to start a sentence with a piece written to
433/// follow a lead-in.
434pub(crate) fn capitalized(text: &str) -> String {
435    let mut letters = text.chars();
436    letters.next().map_or_else(String::new, |first| {
437        first.to_uppercase().chain(letters).collect()
438    })
439}
440
441/// Whether a file's rows hold too few of the cells its header names: under a quarter of them,
442/// past the first 65,536. A reader stores a cell a short row leaves out as a gap, so without this
443/// floor a small file with a wide header and short rows could make it allocate far more than the
444/// file holds: the readers refuse such a file instead.
445pub(crate) fn too_sparse(header_columns: usize, rows: usize, cells_written: usize) -> bool {
446    header_columns.saturating_mul(rows) > cells_written.saturating_mul(4).saturating_add(65_536)
447}
448
449/// The altitude step of one pascal at sea level, m: `1 / (ρ₀ g₀)`, with the International Standard
450/// Atmosphere's sea-level density ρ₀ = 1.225 kg/m³ (ISO 2533:1975) and standard gravity
451/// g₀ = 9.806 65 m/s² (CGPM 1901). A logger whose pressure moves in steps of so many pascals
452/// can't tell two altitudes nearer than that many times this apart near the ground, however many
453/// digits its altitude has; aloft, where the air is thinner, the step is larger.
454const ONE_PASCAL_M: f64 = 1.0 / (1.225 * 9.806_65);
455
456/// The smallest step the Raven's pressure moves by, atm: 4 × 10⁻⁵ atm (4.053 Pa), the smallest
457/// step of `Baro (Atm)` in 74 of the 78 distinct Raven files among the project's sample logs
458/// (the others step by 8 to 16 Pa), though the export prints five decimals.
459const RAVEN_PRESSURE_STEP_ATM: f64 = 4.0e-5;
460
461/// The step an RRC3's export writes its pressure in, Pa: 0.1 hPa (10 Pa), the smallest step of
462/// `Pressure` in all 50 RRC3 files among the project's sample logs.
463const RRC3_PRESSURE_STEP_PA: f64 = 10.0;
464
465/// The step the radio packets write their pressure in, Pa: 0.01 hPa ([`crate::packets`]).
466const RADIO_PACKET_PRESSURE_STEP_PA: f64 = 1.0;
467
468/// The Blue Raven's pressure step, atm: 2 × 10⁻⁵ atm (2.0265 Pa), as its USB download writes the
469/// pressure in atmospheres times 50,000 (*Blue Raven User's Guide*, 2026-05-12, p23). The app's
470/// file prints the pressure to 10⁻⁴ atm, but its altitude above the pad steps by 0.5 to 0.6 ft near
471/// the pad, as this finer step makes it.
472const BLUE_RAVEN_PRESSURE_STEP_ATM: f64 = 2.0e-5;
473
474impl LogFormat {
475    /// The altitude's resolution in the format, m: the smallest step between two altitudes the file
476    /// can tell apart near the ground. A PerfectFlite and an Eggtimer write whole feet, an
477    /// Alt15K/WD's `.pfa` too, though that sensor's own resolution is 4 ft at sea level (*Alt15K/WD
478    /// User’s Manual*, p. 10): the step the file writes is taken, not the coarser one, so that a
479    /// tolerance built on it stays tight; AltOS and Entacore AIM write their pressure in whole
480    /// pascals, 0.083 m of altitude at sea level; AltimeterCloud writes its altitude to the
481    /// millimeter, and it steps by that, a SillyGoose to the centimeter, a Fluctus to the whole
482    /// meter, and an ARTS2's barometric altitude moves by its barometer's count, 8.8 m at most
483    /// near the ground among the sample files; AerospaceNU's flight computer board reads whole
484    /// pascals, 0.083 m near sea level, in its CSV and in its ground station's text, where its
485    /// altitude is a filtered estimate with no step of its own; a phone app's `launch` CSV writes
486    /// its pressure as a 32-bit float, in steps of 2⁻¹⁴ hPa between 512 and 1,024 hPa,
487    /// 0.000 51 m at sea level: the barometer's step, as its barometric altitude, the track, is
488    /// written in finer steps of its own, as small as 0.25 mm; the Raven's pressure moves in steps of 4 × 10⁻⁵ atm, 0.337
489    /// m at sea level, the Blue Raven's in steps of 2 × 10⁻⁵ atm, 0.169 m, and an RRC3's export in
490    /// steps of 0.1 hPa, 0.832 m. Aloft, those from a pressure are larger. A GPS log has no
491    /// barometric altitude; its formats give the coarsest step its GNSS altitude is written in
492    /// among the sample files: whole feet in Featherweight's older tracker log, whole meters in
493    /// Missile Works' and Big Red Bee's KML, and a tenth of a meter in NMEA's `GGA`. A receiver's
494    /// own error is far larger. A Featherweight summary has no track: its maximum altitude is
495    /// written to the hundredth of a foot. An R-DAS's raw text has no altitude either, only its
496    /// barometer's counts: one is 0.09 kPa in its maker's manual, 7.49 m near sea level. AltOS's
497    /// telemetry sends the board's height above the pad in whole meters. An AltOS `.eeprom` file
498    /// holds no altitude either: its coarsest pressure is a TeleMetrum v1's, whose counts move by
499    /// 4 in the sample files, 13.6 Pa, 1.13 m near sea level. Nor does an ARTS2's `.odf` or raw
500    /// CSV: its barometer's count is 92.2 Pa, 7.68 m near sea level. Missile Works' RTx writes its
501    /// GPS altitude in whole meters in its `.rtx` file and in whole feet in its exports. A GPX
502    /// file writes its elevation as a decimal of any length, and no sample log is one to show a
503    /// step: 0. A table read by
504    /// its header has no track, and no step: 0; nor do binary records read by a stated layout, or a
505    /// console capture's, which are read as such a table. A Blue Raven's USB download has no
506    /// track either, and its pressure is written in the CSV's steps, 1/50,000 atm: the CSV's step.
507    /// Nor does a Teensy data logger's file, whose pressure is written in whole pascals: 1 Pa,
508    /// 0.083 m near sea level.
509    /// Nor do the radio packets, whose pressure is written to 0.01 hPa, 1 Pa. An AltiMAX's raw
510    /// height follows its raw pressure, written in whole pascals: 1 Pa, 0.083 m near sea level.
511    /// A MARSA writes its altitude to a tenth of a foot, but it moves by its barometer's count,
512    /// 29.3 ft (8.93 m) at most within 300 ft of the pad among the sample files. AltOS's
513    /// telemetry decoded to a table keeps the packet's whole meters of height. An AltiMAX's
514    /// `.ALS` file and Entacore AIM's `.xtra` and raw dump hold no altitude, only pressures in
515    /// whole pascals: 1 Pa, 0.083 m near sea level.
516    pub fn altitude_resolution_m(self) -> f64 {
517        match self {
518            Self::PerfectFlitePf2 | Self::PerfectFliteCsv | Self::PerfectFliteText => {
519                crate::perfectflite::FOOT_M
520            }
521            Self::AltosCsv => ONE_PASCAL_M,
522            Self::RavenFipCsv => RAVEN_PRESSURE_STEP_ATM * 101_325.0 * ONE_PASCAL_M,
523            Self::EggtimerCsv => crate::perfectflite::FOOT_M,
524            Self::Rrc3Csv => RRC3_PRESSURE_STEP_PA * ONE_PASCAL_M,
525            Self::TeensyTabs
526            | Self::TeensyNamed
527            | Self::AltimaxXls
528            | Self::AltimaxAls
529            | Self::EntacoreXtra
530            | Self::EntacoreDump => ONE_PASCAL_M,
531            Self::RadioPacketText | Self::RadioPacketRtf => {
532                RADIO_PACKET_PRESSURE_STEP_PA * ONE_PASCAL_M
533            }
534            Self::BlueRavenCsv | Self::BlueRavenUsb => {
535                BLUE_RAVEN_PRESSURE_STEP_ATM * 101_325.0 * ONE_PASCAL_M
536            }
537            Self::FeatherweightGpsCsv => crate::perfectflite::FOOT_M,
538            Self::Kml => 1.0,
539            Self::Nmea0183 => 0.1,
540            Self::Gpx => 0.0,
541            Self::PerfectFlitePfa | Self::EggtimerText => crate::perfectflite::FOOT_M,
542            Self::AltimeterCloudCsv => 0.001,
543            Self::EntacoreAimCsv => ONE_PASCAL_M,
544            Self::SillyGooseText => crate::sillygoose::ALTITUDE_STEP_M,
545            Self::FluctusCsv => crate::fluctus::ALTITUDE_STEP_M,
546            Self::Arts2Csv => crate::arts2::ALTITUDE_STEP_M,
547            Self::AerospaceNuFcbCsv => crate::aerospacenu_fcb::ALTITUDE_STEP_M,
548            Self::AerospaceNuGroundStationText => crate::aerospacenu_gs::ALTITUDE_STEP_M,
549            Self::PhoneLaunchCsv => crate::phone_launch::ALTITUDE_STEP_M,
550            Self::EggtimerRtf => crate::perfectflite::FOOT_M,
551            Self::RavenFipa => RAVEN_PRESSURE_STEP_ATM * 101_325.0 * ONE_PASCAL_M,
552            Self::Rrc3Rff => RRC3_PRESSURE_STEP_PA * ONE_PASCAL_M,
553            Self::FeatherweightSummaryCsv => 0.01 * crate::perfectflite::FOOT_M,
554            Self::RdasText => crate::rdas::ALTITUDE_STEP_M,
555            Self::AltosTelemetry | Self::AltosTelemetryCsv => 1.0,
556            Self::Marsa => crate::marsa::ALTITUDE_STEP_M,
557            Self::AltosEeprom => crate::altos_eeprom::ALTITUDE_STEP_M,
558            Self::Arts2Odf | Self::Arts2RawCsv => crate::arts2_raw::ALTITUDE_STEP_M,
559            Self::RtxRaw => crate::rtx::ALTITUDE_STEP_M,
560            Self::RtxCsv | Self::RtxText => crate::rtx::EXPORT_ALTITUDE_STEP_M,
561            Self::GenericTable | Self::BinaryRecords | Self::ConsoleCapture => 0.0,
562        }
563    }
564
565    /// The format's usual file extension, with its dot.
566    pub fn extension(self) -> &'static str {
567        match self {
568            Self::PerfectFlitePf2 => ".pf2",
569            Self::PerfectFliteCsv
570            | Self::AltosCsv
571            | Self::RavenFipCsv
572            | Self::Rrc3Csv
573            | Self::EggtimerCsv
574            | Self::BlueRavenCsv
575            | Self::FeatherweightGpsCsv
576            | Self::AltimeterCloudCsv
577            | Self::EntacoreAimCsv
578            | Self::FluctusCsv
579            | Self::Arts2Csv
580            | Self::AerospaceNuFcbCsv
581            | Self::PhoneLaunchCsv
582            | Self::FeatherweightSummaryCsv
583            | Self::Arts2RawCsv
584            | Self::RtxCsv
585            | Self::AltosTelemetryCsv
586            | Self::GenericTable => ".csv",
587            Self::Marsa => ".dat",
588            Self::PerfectFliteText
589            | Self::Nmea0183
590            | Self::EggtimerText
591            | Self::SillyGooseText
592            | Self::AerospaceNuGroundStationText
593            | Self::RdasText
594            | Self::RtxText
595            | Self::BlueRavenUsb
596            | Self::TeensyTabs
597            | Self::TeensyNamed
598            | Self::RadioPacketText => ".txt",
599            Self::EggtimerRtf | Self::RadioPacketRtf => ".rtf",
600            Self::RavenFipa => ".FIPa",
601            Self::AltimaxXls => ".xls",
602            Self::AltimaxAls => ".ALS",
603            Self::EntacoreXtra => ".xtra",
604            Self::EntacoreDump => ".bin",
605            Self::Rrc3Rff => ".rff",
606            Self::PerfectFlitePfa => ".pfa",
607            Self::Kml => ".kml",
608            Self::Gpx => ".gpx",
609            Self::AltosTelemetry => ".telem",
610            Self::AltosEeprom => ".eeprom",
611            Self::Arts2Odf => ".odf",
612            Self::RtxRaw => ".rtx",
613            Self::BinaryRecords => ".bin",
614            Self::ConsoleCapture => ".cap",
615        }
616    }
617
618    /// The format's name for people, such as `AltOS CSV`.
619    pub fn name(self) -> &'static str {
620        match self {
621            Self::PerfectFlitePf2 => "PerfectFlite .pf2",
622            Self::PerfectFliteCsv => "PerfectFlite CSV",
623            Self::PerfectFliteText => "PerfectFlite text",
624            Self::AltosCsv => "AltOS CSV",
625            Self::RavenFipCsv => "Raven FIP CSV",
626            Self::Rrc3Csv => "RRC3 CSV",
627            Self::EggtimerCsv => "Eggtimer CSV",
628            Self::BlueRavenCsv => "Blue Raven CSV",
629            Self::FeatherweightGpsCsv => "Featherweight GPS CSV",
630            Self::Kml => "KML",
631            Self::Nmea0183 => "NMEA 0183",
632            Self::Gpx => "GPX",
633            Self::PerfectFlitePfa => "PerfectFlite .pfa",
634            Self::EggtimerText => "Eggtimer text",
635            Self::AltimeterCloudCsv => "AltimeterCloud CSV",
636            Self::EntacoreAimCsv => "Entacore AIM CSV",
637            Self::SillyGooseText => "SillyGoose text",
638            Self::FluctusCsv => "Silicdyne Fluctus CSV",
639            Self::Arts2Csv => "ARTS2 CSV",
640            Self::AerospaceNuFcbCsv => "AerospaceNU flight computer CSV",
641            Self::AerospaceNuGroundStationText => "AerospaceNU ground station text",
642            Self::PhoneLaunchCsv => "phone app launch CSV",
643            Self::EggtimerRtf => "Eggtimer RTF",
644            Self::RavenFipa => "Raven .FIPa",
645            Self::Rrc3Rff => "RRC3 .rff",
646            Self::FeatherweightSummaryCsv => "Featherweight summary CSV",
647            Self::RdasText => "R-DAS text",
648            Self::AltosTelemetry => "AltOS telemetry",
649            Self::AltosEeprom => "AltOS .eeprom",
650            Self::Arts2Odf => "ARTS2 .odf",
651            Self::Arts2RawCsv => "ARTS2 raw CSV",
652            Self::RtxRaw => "RTx .rtx",
653            Self::RtxCsv => "RTx CSV",
654            Self::RtxText => "RTx text",
655            Self::GenericTable => "a table read by its header",
656            Self::BinaryRecords => "binary records by a stated layout",
657            Self::ConsoleCapture => "console capture of base64 records",
658            Self::BlueRavenUsb => "Blue Raven USB download",
659            Self::TeensyTabs => "Teensy data logger, tab-separated",
660            Self::TeensyNamed => "Teensy data logger, named fields",
661            Self::RadioPacketText => "radio packets",
662            Self::RadioPacketRtf => "radio packets in RTF",
663            Self::AltimaxXls => "AltiMAX Excel export",
664            Self::AltimaxAls => "AltiMAX .ALS",
665            Self::EntacoreXtra => "Entacore AIM .xtra",
666            Self::EntacoreDump => "Entacore AIM raw dump",
667            Self::Marsa => "MARSA download",
668            Self::AltosTelemetryCsv => "AltOS telemetry CSV",
669        }
670    }
671}
672
673/// What a flight log states about the flight, in SI.
674#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize, JsonSchema)]
675pub struct Stated {
676    /// The apogee the logger computed, m above its own zero; `None` if the file states none, or
677    /// states something that isn't a height, such as a PerfectFlite's `PWRLOSS`.
678    pub apogee_m: Option<f64>,
679    /// The launch site's elevation, m above mean sea level, as the logger states it.
680    pub ground_elevation_msl_m: Option<f64>,
681    /// How many samples the file says it holds.
682    pub samples: Option<usize>,
683    /// Every figure a summary file states, in the file's order, such as a Featherweight
684    /// summary's `Max velocity,500.50 feet/sec`, and a GPX file's waypoints and route points,
685    /// places marked or planned, not flown ([`crate::gpx`]); empty for a file of samples, and then
686    /// left out of the record's JSON, so that a record written before the field was reads the
687    /// same.
688    #[serde(default, skip_serializing_if = "Vec::is_empty")]
689    pub figures: Vec<Figure>,
690}
691
692/// A figure a file states once about its flight, such as a summary's `Max Altitude,2500.25
693/// feet`: kept as the file writes it, and in SI where its unit is known.
694#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
695#[non_exhaustive]
696pub struct Figure {
697    /// The figure's name as the file writes it, such as `Max Altitude`.
698    pub name: String,
699    /// The value as the file writes it, unit and all, its cells joined by commas, such as
700    /// `2500.25 feet` or `-1.0000,0.0000,0.0000`.
701    pub written: String,
702    /// What the figure measures, which sets the unit of [`Figure::values`]; `None` for text, such
703    /// as a date, a time of day or a name, and [`Quantity::Unrecognized`] for numbers kept as
704    /// written, in a unit HPR Sim doesn't know or that the figure's name contradicts.
705    pub quantity: Option<Quantity>,
706    /// The value in the quantity's unit ([`Quantity::unit`]), one number for each the file
707    /// writes: three for a vector, such as a direction's components along the logger's axes;
708    /// empty for text. Every one a reader writes is finite: a `NaN` here would be written to JSON
709    /// as `null`, which doesn't read back.
710    pub values: Vec<f64>,
711}
712
713impl Figure {
714    /// A figure, its value in the quantity's unit.
715    pub fn new(
716        name: impl Into<String>,
717        written: impl Into<String>,
718        quantity: Option<Quantity>,
719        values: Vec<f64>,
720    ) -> Self {
721        Self {
722            name: name.into(),
723            written: written.into(),
724            quantity,
725            values,
726        }
727    }
728}
729
730#[cfg(test)]
731mod tests {
732    use super::*;
733
734    /// Each format's resolution against a hand computation: 1 / (1.225 × 9.806 65) =
735    /// 0.083 242 m for a pascal, 4 × 10⁻⁵ × 101 325 = 4.053 Pa for the Raven's step,
736    /// 2 × 10⁻⁵ × 101 325 = 2.0265 Pa for the Blue Raven's, 10 Pa for an RRC3's, and
737    /// 1,000 / (1,024 × 0.010 59) = 92.2165 Pa for an ARTS2's count, and 29.3 × 0.3048 =
738    /// 8.930 64 m for a MARSA's count.
739    #[test]
740    fn each_formats_altitude_resolution_is_its_step() {
741        let cases = [
742            (LogFormat::PerfectFlitePf2, 0.3048),
743            (LogFormat::PerfectFliteCsv, 0.3048),
744            (LogFormat::PerfectFliteText, 0.3048),
745            (LogFormat::AltosCsv, 0.083_242),
746            (LogFormat::RavenFipCsv, 0.337_38),
747            (LogFormat::Rrc3Csv, 0.832_42),
748            (LogFormat::EggtimerCsv, 0.3048),
749            (LogFormat::BlueRavenCsv, 0.168_69),
750            (LogFormat::FeatherweightGpsCsv, 0.3048),
751            (LogFormat::Kml, 1.0),
752            (LogFormat::Nmea0183, 0.1),
753            (LogFormat::Gpx, 0.0),
754            (LogFormat::PerfectFlitePfa, 0.3048),
755            (LogFormat::EggtimerText, 0.3048),
756            (LogFormat::EntacoreAimCsv, 0.083_242),
757            (LogFormat::AltimeterCloudCsv, 0.001),
758            (LogFormat::SillyGooseText, 0.01),
759            (LogFormat::FluctusCsv, 1.0),
760            (LogFormat::Arts2Csv, 8.805_672),
761            (LogFormat::RdasText, 7.491_793),
762            (LogFormat::AltosEeprom, 1.129_595),
763            (LogFormat::Arts2Odf, 7.676_218),
764            (LogFormat::Arts2RawCsv, 7.676_218),
765            (LogFormat::RtxRaw, 1.0),
766            (LogFormat::RtxCsv, 0.3048),
767            (LogFormat::RtxText, 0.3048),
768            (LogFormat::Marsa, 8.930_64),
769            (LogFormat::AltosTelemetryCsv, 1.0),
770            (LogFormat::AltimaxAls, 0.083_242),
771            (LogFormat::EntacoreXtra, 0.083_242),
772            (LogFormat::EntacoreDump, 0.083_242),
773            (LogFormat::GenericTable, 0.0),
774        ];
775        for (format, expected) in cases {
776            let resolution = format.altitude_resolution_m();
777            assert!(
778                (resolution - expected).abs() < 5e-6,
779                "{format:?}: {resolution} m, expected {expected} m"
780            );
781        }
782    }
783}