Skip to main content

hpr_flightdata/
altos_eeprom.rs

1//! AltOS raw flight downloads, as AltosUI saves a flight computer's memory to a `.eeprom` file:
2//! the board's own log, record by record, in a JSON form or an older text form.
3//!
4//! An Altus Metrum flight computer logs its sensors 100 times a second in the climb and 10 times
5//! a second in the descent, in records of 8 bytes (TeleMetrum v1), 16 (TeleMetrum v2 and newer,
6//! EasyMini) or 32 (TeleMega, EasyMega) (*The Altus Metrum System*, Bdale Garbee and Keith
7//! Packard, v1.9.22.2, 2025, Appendix F, Table 11, p. 77). AltosUI saves a flight it downloads as
8//! a `.eeprom` file. Altus Metrum publishes no layout for the records, so this reader's layout was
9//! worked out from the 14 sample files and the AltosUI exports (CSV) of the same flights beside 9
10//! of them, and is held to those exports in the survey (`cargo xtask logs`); no AltOS or AltosUI
11//! source code was read. The manual and *AltOS Telemetry* (v1.9.22.2) are published under CC
12//! BY-SA 3.0; this reader restates facts from them, not their text.
13//!
14//! **Recognition.** The JSON form opens with a JSON object that names `log_format` and `product`;
15//! the text form holds, within its first 1,000 lines, a `Config version:` line and a
16//! `manufacturer altusmetrum.org` line, as the board prints its configuration. No other layout
17//! HPR Sim reads does either.
18//!
19//! **The two forms.** The JSON form is the board's configuration as a JSON object, then the
20//! memory's bytes, two hexadecimal digits each, whitespace between them. The text form is a serial
21//! console's transcript: the configuration as the board prints it, then one record a line, a type
22//! letter, the tick in hexadecimal and the record's other bytes, all but its checksum. In both, a
23//! record is a type byte, a checksum byte, a 16-bit tick (low byte first) and the type's fields.
24//!
25//! - *Record size* follows the log format the configuration states (`log_format`, `log-format`):
26//!   8 bytes for format 1; 16 for 6, 7 and 14; 32 for 15, 16 and 22. Any other number refuses the
27//!   file, by number: read at a wrong size, misaligned bytes would make a plausible flight. A file
28//!   that states no log format, as firmware before 1.0 didn't, is format 1 if its product is a
29//!   TeleMetrum v1, as AltosUI does ("Those ancient versions didn't report the log format, so just
30//!   use the product name instead", the manual's release notes for version 1.4, §H.43.2, p. 128);
31//!   any other product refuses it. Format 1's text prints its four field bytes as two 16-bit words.
32//! - *Checksum.* In the JSON form, every record's bytes sum, with 0x5A, to 0 modulo 256, the seed
33//!   of the line checksum of the TeleDongle, the radio receiver AltosUI listens through (*AltOS
34//!   Telemetry* §4, p. 10): every record of the seven JSON sample files passes (the survey's
35//!   report counts them). One that fails refuses the file ([`LogError::Binary`]). The text form
36//!   prints no checksum.
37//! - *Erased memory.* A record of all 0xFF bytes is erased flash, after the flight's last record,
38//!   and is skipped and counted; a data record after one refuses the file, as the memory's order
39//!   is then unknown. Memory that ends partway through a record is refused, erased or not.
40//! - *A malformed line* in the text form's records refuses the file, but the last line of a file
41//!   that ends without a line break, as a download cut short does, is left out with a note: it may
42//!   be cut mid-value however well it reads.
43//! - *The configuration* may be printed more than once in a transcript; the first copy is read,
44//!   and a later one that differs in the log format, serial number, product, barometer constants
45//!   or accelerometer calibration refuses the file. `2147483647` in the JSON means not set.
46//!
47//! **The clock.** The tick counts 100 a second (*AltOS Companion Port*, v1.9.22.2, Table 1;
48//! Appendix F's 100 samples a second) and turns over every 655.36 s. Each record's tick goes on
49//! the turn nearest the latest tick so far. The file's order isn't time order: the samples from
50//! before boost, kept in a ring buffer, are written after the flight record, a state record ahead
51//! of sensor records with earlier ticks, and a GPS record carries its fix's earlier tick; so the
52//! records are put in tick order, the file's order kept among equal ticks. A record more than
53//! 10 s from the latest tick, a silence no logging rate leaves, ends the flight: it and every
54//! record after it are left out, counted in a note (one sample file ends with another session's
55//! records, more than 10 s later). Records repeated exactly, the same bytes at the same tick, as
56//! old firmware wrote some, are dropped and counted. Time zero is the flight record's tick, the
57//! board's detection of boost, as in AltosUI's exports: the samples from the pad have negative
58//! times. A file needs exactly one flight record (`F`), or it is refused.
59//!
60//! **What is read.** Each field is in SI where a cited conversion and a second check bear the
61//! unit out, and kept as written ([`Quantity::Unrecognized`] for counts, [`Quantity::Number`] for
62//! codes and flags) otherwise:
63//!
64//! | Board (format) | Field | Channel | As read |
65//! |---|---|---|---|
66//! | all with an MS5607, the barometer chip (6, 7, 14, 15, 16, 22) | the barometer's D1 and D2 | `pressure`, `temperature` | Pa and K, by the data sheet's compensation (below); `d1`, `d2` as written without its constants |
67//! | TeleMetrum v1 (1) | pressure count | `pressure` | Pa, by the MP3H6115A's transfer function (below) |
68//! | all but EasyMini | the high-g accelerometer's count | `acceleration` | m/s² along the flight path, from the file's own calibration (below); `accel` as written without one |
69//! | TeleMega v4.0 and v6.0, EasyMega v2.0 (15, 16, 22) | pyro battery, igniters A–D, apogee and main senses (the voltages across the pyro channels that show continuity) | `pyro`, `igniter_a` … `igniter_d`, `drogue_voltage`, `main_voltage` | V, as *AltOS Telemetry* converts a 15 V Mega's: count / 4095 × 3.3 V × 127 / 27 (p. 3); as written on any other Mega |
70//! | every board | battery and other senses | `v_batt`, `sense_a`, `sense_m` | as written: the factors that fit the exports have no source |
71//! | TeleMetrum v1 (1) | the die temperature of the CC1111, the radio microcontroller whose converter reads the board's sensors | `temp` | as written: no document gives the conversion AltosUI uses, and the CC1111 data sheet's constants don't reproduce its export |
72//! | EasyMega v2, TeleMega v6 (16, 22) | the nine words of the IMU, the inertial unit's accelerometer, gyroscope and magnetometer | `imu_accel_0` … `imu_mag_2` | as written: their scales fit the exports but have no source |
73//! | every board | state | `state` | as written; each change an [`Event`] |
74//! | boards with GPS | latitude, longitude | `latitude`, `longitude` | degrees, from ten-millionths, as *AltOS Telemetry*'s GPS packet (Table 15, pp. 6–7); a gap without a valid fix |
75//! | | altitude | `gps_altitude` | m, as the GPS packet's; with the configuration's `altitude-32`, its high 16 bits too |
76//! | | flags, time, date, dilutions, course, speed, climb, satellites | `gps_flags`, `nsat`, `hour` …, `year` …, `pdop` …, `course`, `ground_speed`, `climb_rate`, `svid`, `c_n` | as written: the date is two digits and needn't be the flight's |
77//!
78//! *Pressure and temperature, MS5607.* The data sheet's first-order compensation and, below
79//! 20 °C, its second order (TE Connectivity, *MS5607-02BA03*, 03/2024, Figure 2, p. 8, and Figure
80//! 3, p. 9), in integers, each division by 2ⁿ a floor (an arithmetic shift): truncating instead
81//! gives different pressures below 20 °C, and a unit test pins the floor. Second checks: the pad's
82//! pressure (the median of the samples before boost, or the first sample's) must lie from 10 to
83//! 120 kPa and within 1% of the flight record's ground pressure, the pad's temperature within the
84//! sensor's operating range, −40 to 85 °C (p. 8), or the file is refused: any failing means
85//! misread bytes. On a board with an accelerometer the climb check below holds the pressure and
86//! the acceleration to each other too; failing it keeps the acceleration as counts. A board
87//! without the constants, or whose JSON marks an MS5611, keeps `d1` and `d2` as written.
88//!
89//! *Pressure, TeleMetrum v1.* The MP3H6115A's output is `Vout = Vs (0.009 P − 0.095)`, P in kPa
90//! (Freescale, *MP3H6115A*, rev. 5.1, 2012, "Transfer Function", p. 5), read by the CC1111's
91//! 12-bit converter, whose single-ended result, 0 to 2,047, reaches 2,047 at its reference and is
92//! held in the top bits of its two result registers (TI, *CC1110Fx/CC1111Fx*, SWRS033H,
93//! §12.10.2.6, p. 143, and `ADCH`/`ADCL`, p. 144): full scale is 2,047 × 16 = 32,752. So
94//! `P = (count / 32,752 + 0.095) / 0.009` kPa, the converter's reference being the sensor's own
95//! supply (the board's design, which no document states). Second checks: the pad's pressure must
96//! lie from 10 to 120 kPa, or the file is refused, and the climb check below must pass, or the
97//! counts are kept as written, `pres`, the band alone rejecting almost no count; the export of the
98//! same flight agrees within half its 0.01 Pa print step (the survey's report).
99//!
100//! *Acceleration.* AltosUI calibrates the accelerometer with the board's antenna end up, then down
101//! (the manual, §12.6.20, p. 42), giving its counts at +1 g and −1 g (`accel_cal_plus`,
102//! `accel_cal_minus`, or the text form's `Accel cal +1g: P -1g: M`). The record's
103//! `acceleration` is `(ground − count) / ((minus − plus) / 2) × 9.806 65` m/s², `ground` the
104//! flight record's reading on the pad, 9.806 65 m/s² standard gravity (CGPM, 1901): 0 on the pad,
105//! positive forward along the flight path, gravity out. A board mounted antenna down logs flipped
106//! counts and keeps a flipped calibration (the JSON's `_cooked` values) whose span is the same, so
107//! the result doesn't depend on which pair is read, as long as both counts come from one pair;
108//! the configuration's `pad_orientation` is a stated figure. Without a calibration, with one
109//! outside a 16-bit count's range, with a span that isn't positive, without a ground reading or
110//! without a pressure in pascals to check it against, or failing the climb check below, the counts
111//! are kept as written, `accel`.
112//!
113//! *The climb check.* On a board with an accelerometer, the climb over the first second after
114//! boost by the pressure, its pressure altitude in the U.S. Standard Atmosphere, 1976 (ISO
115//! 2533:1975's below 32 km), must agree with the climb by the acceleration integrated twice from
116//! rest on the pad: their ratio from 0.6 to 5/3. Outside it, or where the samples don't cover that
117//! second or leave a gap in it of more than 0.1 s, neither unit is borne out: the acceleration's
118//! counts are kept as written, and a TeleMetrum v1's pressure's, which has no other check, too (an
119//! MS5607 board's pressure keeps its flight record's check). On 11 of the 12 sample files with an
120//! accelerometer the ratio runs from 0.859 to 1.400; the twelfth reads about 2, so its counts are
121//! kept (the survey's report prints each). The band catches swapped or misplaced fields, a wrong
122//! sign, and a calibration off by 2 or more on a flight whose ratio is near 1. Without a
123//! calibration an MS5607 board's pressure's second checks are the pad's alone, and a TeleMetrum
124//! v1's pressure is kept as written.
125//!
126//! *Not read.* The TeleMega v4's IMU (format 15): its one sample file's IMU never ran, so its
127//! layout is unconfirmed. Any Mega whose flight record's IMU fields are all zero: its records'
128//! IMU bytes are then stale buffer bytes, not readings. Bytes a record type leaves over from the
129//! record before (the tails of state, sense, GPS and satellite records) are never read. A record
130//! type the board's layout doesn't hold is counted in a note.
131//!
132//! *The flight's states.* AltosUI's exports write each state's number beside its name; the
133//! events take the exports' names, 2 `pad`, 3 `boost`, 4 `fast`, 5 `coast`, 6 `drogue`, 7 `main`,
134//! 8 `landed`, and another number `state N`.
135//!
136//! **What the file says about itself.** [`FlightLog::serial_number`] and
137//! [`FlightLog::firmware`] are the configuration's; [`FlightLog::flight_number`] is the flight
138//! record's, not the JSON's `stored_flight` or `flights`, which needn't name the flight the file
139//! holds. [`Stated::figures`] holds the flight record's ground pressure (Pa) and ground
140//! accelerometer reading, the calibration, the pad orientation, the IMU's pad readings and the
141//! configuration's main deployment height and apogee delay, as written, in SI where the text form
142//! names the unit.
143//!
144//! **The primary track.** The file holds no altitude, so [`FlightLog::time_s`] and
145//! [`FlightLog::altitude_m`] are empty, as for the Raven's raw `.FIPa`; every field is a channel
146//! on its records' clock, in tick order.
147//!
148//! An invented record, a TeleMetrum v2's (format 7) flight record in the JSON form: type `F`,
149//! checksum, tick 0x0164 (356), flight 3, ground reading 25 counts, ground pressure 98,000 Pa, and
150//! four unused bytes:
151//!
152//! ```text
153//! 46 90 64 01 03 00 19 00 d0 7e 01 00 00 00 00 00
154//! ```
155//!
156//! The same record in the text form, its checksum not printed and its tick printed as one
157//! hexadecimal number, `164`, while the other bytes keep their order:
158//!
159//! ```text
160//! F 164 03 00 19 00 d0 7e 01 00 00 00 00 00
161//! ```
162
163use std::collections::{BTreeMap, BTreeSet};
164
165use serde_json::{Map, Value};
166
167use crate::error::LogError;
168use crate::log::{Channel, Event, Figure, FlightLog, LogFormat, Quantity, Stated};
169
170/// The format's name in errors.
171const FORMAT: &str = "AltOS .eeprom";
172
173/// The configuration's value for "not set".
174const NOT_SET: i64 = 2_147_483_647;
175
176/// What a JSON record's checksum adds to the sum of its bytes: 0x5A plus every byte, the checksum
177/// byte among them, is 0 modulo 256.
178const CHECKSUM_BASE: u8 = 0x5a;
179
180/// The tick's turn: 2¹⁶ ticks.
181const TURN: i64 = 1 << 16;
182
183/// The ticks in a second: a time is the tick divided by it, correctly rounded.
184const TICKS_PER_S: f64 = 100.0;
185
186/// The farthest a record's tick may lie from the latest so far, ticks: 10 s. The slowest logging
187/// rate is 10 a second (Appendix F), so a silence a hundred times longer isn't the board logging
188/// a flight.
189const SILENCE_TICKS: i64 = 1_000;
190
191/// Standard gravity, m/s² (CGPM, 1901).
192const STANDARD_GRAVITY: f64 = 9.806_65;
193
194/// A 16-bit count's range, signed or not: the records hold the accelerometer's count in 16 bits,
195/// so a calibration outside it isn't one of its counts.
196const SIXTEEN_BITS: std::ops::RangeInclusive<i64> = -32_768..=65_535;
197
198/// The pressures a launch site's pad can have, Pa.
199const PAD_PRESSURE_PA: std::ops::RangeInclusive<f64> = 10_000.0..=120_000.0;
200
201/// How far the pad's pressure may lie from the flight record's ground pressure, as a share of it.
202const GROUND_AGREES: f64 = 0.01;
203
204/// The temperatures the MS5607 works in, K: −40 to 85 °C (*MS5607-02BA03*, operating range,
205/// p. 8 of the 03/2024 issue's specifications). A pad reading outside them is misread bytes.
206const MS5607_OPERATING_K: std::ops::RangeInclusive<f64> = 233.15..=358.15;
207
208/// The climb check's window, ticks: from boost to 1 s after it, early in the motor's burn, where
209/// the rocket is slower and the barometer's ports read nearer the air's pressure than later.
210const CLIMB_WINDOW_TICKS: i64 = 100;
211
212/// The longest gap between two samples the climb check integrates across, ticks: 0.1 s, the
213/// slowest logging rate (Appendix F's 10 a second). A longer one leaves the window unmeasured.
214const CLIMB_GAP_TICKS: i64 = 10;
215
216/// Half the span, ticks, of the samples whose median pressure ends the climb check's window: the
217/// samples within 0.05 s of its last one, so that one noisy sample doesn't decide it.
218const CLIMB_END_TICKS: i64 = 5;
219
220/// The ratios of the climb by the pressure to the climb by the acceleration that the climb check
221/// accepts: 0.6 to 5/3, symmetric about 1 in log terms. On 11 of the 12 sample files with an
222/// accelerometer the ratio lies from 0.859 to 1.400 (the survey's report prints each file's): the
223/// barometer reads the pressure at its ports, which the airflow past them can lower in the climb,
224/// and a high-g accelerometer counts few steps a g. The band leaves those at least a fifth to
225/// spare on either side, and the twelfth, at about 2, outside: its two sensors disagree by a
226/// factor no port or step explains, so neither unit is taken on trust there.
227pub const CLIMB_RATIO: std::ops::RangeInclusive<f64> = 0.6..=(5.0 / 3.0);
228
229/// The CC1111's full-scale count, its 12-bit result's 2,047 in the top bits of 16 (SWRS033H,
230/// p. 143, p. 144).
231const CC1111_FULL_SCALE: f64 = 32_752.0;
232
233/// A Mega's sense divider and converter on a board whose pyro channels take up to 15 V: 12 bits
234/// over 3.3 V, behind 100 kΩ over 27 kΩ (*AltOS Telemetry*, p. 3). The same page gives 100 kΩ
235/// over 12 kΩ for the 30 V boards, so the factor is used only for [`MEGA_15_V_PRODUCTS`].
236const MEGA_SENSE_V: f64 = 3.3 / 4095.0 * (100.0 + 27.0) / 27.0;
237
238/// The Mega products whose senses [`MEGA_SENSE_V`] converts: those whose AltosUI exports among the
239/// sample logs bear the 100 kΩ over 27 kΩ divider out. A later TeleMega takes 30 V on its pyro
240/// channels (the manual's release notes for 1.9.20, TeleMega v7.0), so any other product's senses
241/// are kept as written.
242const MEGA_15_V_PRODUCTS: [&str; 3] = ["TeleMega-v4.0", "TeleMega-v6.0", "EasyMega-v2.0"];
243
244/// The format's resolution ([`LogFormat::altitude_resolution_m`]): the file writes no altitude,
245/// and its coarsest pressure is a TeleMetrum v1's, whose counts step by 4 in the sample files (the
246/// survey's report prints each file's smallest pressure step): 4 / 32,752 / 0.009 kPa, 13.6 Pa,
247/// or 1.13 m near sea level (`Δh = Δp / (ρ₀ g₀)`). An MS5607 board's steps by a whole pascal.
248pub const ALTITUDE_STEP_M: f64 =
249    4.0 / CC1111_FULL_SCALE / 0.009 * 1000.0 / (1.225 * STANDARD_GRAVITY);
250
251/// How many lines, from the first, the text form's marks are looked for in.
252const HEAD_LINES: usize = 1_000;
253
254/// The flight's states by number, as AltosUI's exports name them.
255const STATES: [(u16, &str); 7] = [
256    (2, "pad"),
257    (3, "boost"),
258    (4, "fast"),
259    (5, "coast"),
260    (6, "drogue"),
261    (7, "main"),
262    (8, "landed"),
263];
264
265/// The GPS flags' valid bit (*AltOS Telemetry*, Table 16, p. 7).
266const GPS_VALID: u8 = 0x10;
267
268/// A board's layout, by its log format.
269#[derive(Debug, Clone, Copy, PartialEq, Eq)]
270enum Board {
271    /// Format 1: TeleMetrum v1, 8-byte records.
272    TeleMetrumV1,
273    /// Formats 6 and 14: EasyMini v1 and v2, 16-byte records.
274    EasyMini,
275    /// Format 7: TeleMetrum v2 and newer, 16-byte records.
276    TeleMetrumV2,
277    /// Formats 15, 16 and 22: TeleMega and EasyMega, 32-byte records.
278    Mega,
279}
280
281/// The board and the record size of a log format; `None` for one the samples don't show.
282fn layout(log_format: i64) -> Option<(Board, usize)> {
283    match log_format {
284        1 => Some((Board::TeleMetrumV1, 8)),
285        6 | 14 => Some((Board::EasyMini, 16)),
286        7 => Some((Board::TeleMetrumV2, 16)),
287        15 | 16 | 22 => Some((Board::Mega, 32)),
288        _ => None,
289    }
290}
291
292/// Where in the file a record or a fault is.
293#[derive(Debug, Clone, Copy, PartialEq, Eq)]
294enum At {
295    /// A 1-based line of the text form, or of the JSON form's head.
296    Line(usize),
297    /// A 0-based byte of the JSON form's memory.
298    Offset(usize),
299}
300
301fn refuse(at: At, message: String) -> LogError {
302    match at {
303        At::Line(line) => LogError::Syntax {
304            format: FORMAT,
305            line,
306            message,
307        },
308        At::Offset(offset) => LogError::Binary {
309            format: FORMAT,
310            offset,
311            message,
312        },
313    }
314}
315
316/// One record: its whole bytes, the checksum byte 0 in the text form.
317#[derive(Debug, Clone)]
318struct Record {
319    at: At,
320    bytes: Vec<u8>,
321}
322
323impl Record {
324    fn kind(&self) -> u8 {
325        self.bytes[0]
326    }
327    fn tick(&self) -> u16 {
328        self.u16(2)
329    }
330    fn u8(&self, at: usize) -> f64 {
331        f64::from(self.bytes[at])
332    }
333    fn u16(&self, at: usize) -> u16 {
334        u16::from_le_bytes([self.bytes[at], self.bytes[at + 1]])
335    }
336    fn i16(&self, at: usize) -> i16 {
337        i16::from_le_bytes([self.bytes[at], self.bytes[at + 1]])
338    }
339    fn u24(&self, at: usize) -> u32 {
340        u32::from_le_bytes([self.bytes[at], self.bytes[at + 1], self.bytes[at + 2], 0])
341    }
342    fn u32(&self, at: usize) -> u32 {
343        u32::from_le_bytes([
344            self.bytes[at],
345            self.bytes[at + 1],
346            self.bytes[at + 2],
347            self.bytes[at + 3],
348        ])
349    }
350    fn i32(&self, at: usize) -> i32 {
351        self.u32(at) as i32
352    }
353}
354
355/// The barometer's constants C1 to C6 (*MS5607-02BA03*, p. 8).
356type Prom = [i64; 6];
357
358/// The barometer's constants' keys, C1 to C6, in the JSON's `ms5607` object and the text form's
359/// `ms5607 KEY: N` lines, with the setting's name for a refusal.
360const PROM_KEYS: [(&str, &str); 6] = [
361    ("sens", "barometer's C1"),
362    ("off", "barometer's C2"),
363    ("tcs", "barometer's C3"),
364    ("tco", "barometer's C4"),
365    ("tref", "barometer's C5"),
366    ("tempsens", "barometer's C6"),
367];
368
369/// The configuration, as read from either form.
370#[derive(Debug, Default)]
371struct Config {
372    log_format: Option<i64>,
373    product: Option<String>,
374    serial: Option<i64>,
375    version: Option<String>,
376    prom: Option<Prom>,
377    ms5611: bool,
378    accel_plus: Option<i64>,
379    accel_minus: Option<i64>,
380    pad_orientation: Option<Figure>,
381    altitude_32: bool,
382    main_deploy: Option<Figure>,
383    apogee_delay: Option<Figure>,
384}
385
386/// Whether the text is an AltOS `.eeprom` file, in either form.
387pub fn recognizes(text: &str) -> bool {
388    let trimmed = text.trim_start();
389    if trimmed.starts_with('{') {
390        return json_head(text).is_some_and(|(head, _)| {
391            head.contains_key("log_format") && head.get("product").is_some_and(Value::is_string)
392        });
393    }
394    let (mut config, mut maker) = (false, false);
395    for line in text.lines().take(HEAD_LINES).map(str::trim) {
396        config |= line.starts_with("Config version:");
397        maker |= value_of(line, "manufacturer") == Some("altusmetrum.org");
398        if config && maker {
399            return true;
400        }
401    }
402    false
403}
404
405/// The JSON form's head, the object, and the byte where it ends; `None` if the text doesn't open
406/// with a JSON object.
407fn json_head(text: &str) -> Option<(Map<String, Value>, usize)> {
408    let start = text.len() - text.trim_start().len();
409    let mut stream =
410        serde_json::Deserializer::from_str(&text[start..]).into_iter::<serde_json::Value>();
411    match stream.next() {
412        Some(Ok(Value::Object(head))) => Some((head, start + stream.byte_offset())),
413        _ => None,
414    }
415}
416
417/// A text-form configuration line's value after its key and whitespace, such as `product
418/// TeleMetrum-v2.0`'s.
419fn value_of<'a>(line: &'a str, key: &str) -> Option<&'a str> {
420    let rest = line.strip_prefix(key)?;
421    let value = rest.trim_start();
422    (value.len() < rest.len() && !value.is_empty()).then_some(value)
423}
424
425/// Reads an AltOS `.eeprom` file.
426///
427/// # Errors
428///
429/// - [`LogError::NotThisFormat`] for a file in neither form.
430/// - [`LogError::NoData`] for a file with no records: none after the configuration, or in the
431///   JSON form only erased memory.
432/// - [`LogError::Syntax`], with the line, for a fault in the text form or in the JSON form's head:
433///   a log format the reader doesn't know (named by number) or none for a product other than a
434///   TeleMetrum v1, a malformed line, a configuration whose copies differ, a token in the memory
435///   that isn't two hexadecimal digits.
436/// - [`LogError::Binary`], with the byte, for a fault in the JSON form's memory: a record whose
437///   checksum fails, a record after erased memory, memory that ends partway through a record.
438/// - For a fault in the records themselves, either, at the record (a line of the text form, a
439///   byte of the JSON form's memory): no flight record or two; the pad's pressure outside a
440///   launch site's or away from the flight record's; the pad's temperature outside the
441///   barometer's operating range. The climb check never refuses a file: failing it, or a first
442///   second after boost too short to measure, keeps the acceleration's counts as written (and a
443///   TeleMetrum v1's pressure's), with a note.
444pub fn read(text: &str) -> Result<FlightLog, LogError> {
445    if !recognizes(text) {
446        return Err(LogError::NotThisFormat {
447            format: FORMAT,
448            message: "neither a JSON object naming `log_format` and `product` nor an AltOS \
449                      board's printed configuration"
450                .to_owned(),
451        });
452    }
453    let raw = if text.trim_start().starts_with('{') {
454        json_form(text)?
455    } else {
456        text_form(text)?
457    };
458    decode(raw)
459}
460
461/// What either form gives: the configuration, the records in the file's order, and the counts
462/// the notes need.
463#[derive(Debug)]
464struct Raw {
465    config: Config,
466    board: Board,
467    size: usize,
468    log_format: i64,
469    from_product: bool,
470    json: bool,
471    records: Vec<Record>,
472    erased: usize,
473    last_line_cut: bool,
474}
475
476/// The log format, the board and the record size from the configuration, the product's rule
477/// for firmware before 1.0 included.
478fn format_of(config: &Config, at: At) -> Result<(i64, Board, usize, bool), LogError> {
479    let (log_format, from_product) = match config.log_format {
480        Some(format) => (format, false),
481        None if config
482            .product
483            .as_deref()
484            .is_some_and(|product| product.starts_with("TeleMetrum-v1")) =>
485        {
486            (1, true)
487        }
488        None => {
489            return Err(refuse(
490                at,
491                format!(
492                    "the configuration states no log format, and its product, {:?}, isn't a \
493                     TeleMetrum v1, whose firmware before 1.0 logged format 1",
494                    cut(config.product.as_deref().unwrap_or("none"))
495                ),
496            ));
497        }
498    };
499    let (board, size) = layout(log_format).ok_or_else(|| {
500        refuse(
501            at,
502            format!(
503                "log format {log_format}, which no sample file shows. Its record size is \
504                 unknown, and read at a wrong size the bytes would make a plausible flight"
505            ),
506        )
507    })?;
508    Ok((log_format, board, size, from_product))
509}
510
511/// The JSON form: the head, then the memory in hexadecimal.
512fn json_form(text: &str) -> Result<Raw, LogError> {
513    let (head, end) = json_head(text).ok_or_else(|| {
514        refuse(
515            At::Line(1),
516            "the JSON object at the head doesn't parse".to_owned(),
517        )
518    })?;
519    let int = |key: &str| {
520        head.get(key)
521            .and_then(Value::as_i64)
522            .filter(|value| *value != NOT_SET)
523    };
524    let mut config = Config {
525        log_format: int("log_format"),
526        product: head
527            .get("product")
528            .and_then(Value::as_str)
529            .map(str::to_owned),
530        serial: int("serial"),
531        version: head
532            .get("version")
533            .and_then(Value::as_str)
534            .map(str::to_owned),
535        pad_orientation: int("pad_orientation").map(|value| {
536            Figure::new(
537                "pad_orientation",
538                value.to_string(),
539                Some(Quantity::Number),
540                vec![value as f64],
541            )
542        }),
543        altitude_32: int("altitude_32") == Some(1),
544        main_deploy: int("main_deploy").map(|value| {
545            Figure::new(
546                "main_deploy",
547                value.to_string(),
548                Some(Quantity::Unrecognized),
549                vec![value as f64],
550            )
551        }),
552        apogee_delay: int("apogee_delay").map(|value| {
553            Figure::new(
554                "apogee_delay",
555                value.to_string(),
556                Some(Quantity::Unrecognized),
557                vec![value as f64],
558            )
559        }),
560        ..Config::default()
561    };
562    // The calibration's two counts from one pair, both as calibrated or both flipped for a board
563    // mounted antenna down, never one of each.
564    if let (Some(plus), Some(minus)) = (int("accel_cal_plus"), int("accel_cal_minus")) {
565        (config.accel_plus, config.accel_minus) = (Some(plus), Some(minus));
566    } else if let (Some(plus), Some(minus)) =
567        (int("accel_cal_plus_cooked"), int("accel_cal_minus_cooked"))
568    {
569        (config.accel_plus, config.accel_minus) = (Some(plus), Some(minus));
570    }
571    if let Some(Value::Object(ms5607)) = head.get("ms5607") {
572        config.ms5611 = ms5607.get("ms5611").and_then(Value::as_bool) == Some(true);
573        let constant = |key: &str| {
574            ms5607
575                .get(key)
576                .and_then(Value::as_i64)
577                .filter(|value| (0..=0xffff).contains(value))
578        };
579        if let [Some(c1), Some(c2), Some(c3), Some(c4), Some(c5), Some(c6)] =
580            PROM_KEYS.map(|(key, _)| constant(key))
581        {
582            config.prom = Some([c1, c2, c3, c4, c5, c6]);
583        }
584    }
585    let (log_format, board, size, from_product) = format_of(&config, At::Line(1))?;
586
587    // The memory: two hexadecimal digits a byte.
588    let first_line = text[..end].matches('\n').count() + 1;
589    let mut bytes = Vec::with_capacity((text.len() - end) / 3);
590    for (k, line) in text[end..].split('\n').enumerate() {
591        for token in line.split_ascii_whitespace() {
592            // Two hexadecimal digits exactly: `from_str_radix` alone would take a sign, `+6`.
593            let byte = (token.len() == 2 && token.bytes().all(|b| b.is_ascii_hexdigit()))
594                .then(|| u8::from_str_radix(token, 16).ok())
595                .flatten()
596                .ok_or_else(|| {
597                    refuse(
598                        At::Line(first_line + k),
599                        format!(
600                            "{:?} where the memory's bytes are two hexadecimal digits each",
601                            cut(token)
602                        ),
603                    )
604                })?;
605            bytes.push(byte);
606        }
607    }
608    let mut records = Vec::new();
609    let mut erased = 0usize;
610    let mut first_erased: Option<usize> = None;
611    for (k, chunk) in bytes.chunks(size).enumerate() {
612        let offset = k * size;
613        // A short chunk is refused even if erased: memory is a whole number of records.
614        if chunk.len() < size {
615            return Err(refuse(
616                At::Offset(offset),
617                format!(
618                    "the memory ends in {} bytes, part of a {size}-byte record",
619                    chunk.len()
620                ),
621            ));
622        }
623        if chunk.iter().all(|byte| *byte == 0xff) {
624            erased += 1;
625            first_erased.get_or_insert(offset);
626            continue;
627        }
628        if let Some(erased_at) = first_erased {
629            return Err(refuse(
630                At::Offset(offset),
631                format!(
632                    "a record after the erased memory from byte {erased_at}: the memory's order \
633                     is unknown"
634                ),
635            ));
636        }
637        let sum = chunk
638            .iter()
639            .fold(CHECKSUM_BASE, |sum, byte| sum.wrapping_add(*byte));
640        if sum != 0 {
641            return Err(refuse(
642                At::Offset(offset),
643                format!(
644                    "record {} fails its checksum: 0x5A and its bytes sum to 0x{sum:02X}, not 0, \
645                     modulo 256: the record is damaged",
646                    k + 1
647                ),
648            ));
649        }
650        records.push(Record {
651            at: At::Offset(offset),
652            bytes: chunk.to_vec(),
653        });
654    }
655    Ok(Raw {
656        config,
657        board,
658        size,
659        log_format,
660        from_product,
661        json: true,
662        records,
663        erased,
664        last_line_cut: false,
665    })
666}
667
668/// A text-form line's shape as a record: a type letter, a tick of 1 to 4 hexadecimal digits,
669/// then at least one more token of them.
670fn record_shaped(line: &str) -> bool {
671    let mut tokens = line.split_ascii_whitespace();
672    let hex = |token: &str, most: usize| {
673        (1..=most).contains(&token.len()) && token.bytes().all(|b| b.is_ascii_hexdigit())
674    };
675    matches!(tokens.next(), Some(kind) if kind.len() == 1 && kind.as_bytes()[0].is_ascii_alphabetic())
676        && tokens.next().is_some_and(|tick| hex(tick, 4))
677        && tokens.next().is_some_and(|token| hex(token, 4))
678}
679
680/// A text-form record line read at the record size: `None` if it isn't one.
681fn text_record(line: &str, size: usize) -> Option<Vec<u8>> {
682    let tokens: Vec<&str> = line.split_ascii_whitespace().collect();
683    let digits = |token: &str, least: usize, most: usize| {
684        (least..=most).contains(&token.len()) && token.bytes().all(|b| b.is_ascii_hexdigit())
685    };
686    let (kind, tick, fields) = match tokens.as_slice() {
687        [kind, tick, fields @ ..] => (*kind, *tick, fields),
688        _ => return None,
689    };
690    if kind.len() != 1 || !kind.as_bytes()[0].is_ascii_alphabetic() || !digits(tick, 1, 4) {
691        return None;
692    }
693    let tick = u16::from_str_radix(tick, 16).ok()?;
694    let mut bytes = vec![kind.as_bytes()[0], 0];
695    bytes.extend(tick.to_le_bytes());
696    if size == 8 {
697        // Format 1 prints its four field bytes as two 16-bit words.
698        if fields.len() != 2 || !fields.iter().all(|word| digits(word, 1, 4)) {
699            return None;
700        }
701        for word in fields {
702            bytes.extend(u16::from_str_radix(word, 16).ok()?.to_le_bytes());
703        }
704    } else {
705        if fields.len() != size - 4 || !fields.iter().all(|byte| digits(byte, 2, 2)) {
706            return None;
707        }
708        for byte in fields {
709            bytes.push(u8::from_str_radix(byte, 16).ok()?);
710        }
711    }
712    Some(bytes)
713}
714
715/// The text form: the configuration as printed, then one record a line.
716fn text_form(text: &str) -> Result<Raw, LogError> {
717    let lines: Vec<&str> = text
718        .split('\n')
719        .map(|line| line.trim_end_matches('\r'))
720        .collect();
721    let start = lines
722        .iter()
723        .position(|line| record_shaped(line))
724        .ok_or(LogError::NoData { format: FORMAT })?;
725
726    let mut config = Config::default();
727    // The first copy of each setting, and the line that set it, for a later copy to agree with.
728    let mut seen: BTreeMap<&'static str, (String, usize)> = BTreeMap::new();
729    let mut prom: [Option<i64>; 6] = [None; 6];
730    for (k, line) in lines[..start].iter().enumerate() {
731        let number = k + 1;
732        let line = line.trim();
733        let mut agree = |key: &'static str, value: String| -> Result<bool, LogError> {
734            match seen.get(key) {
735                Some((first, at)) if *first != value => Err(refuse(
736                    At::Line(number),
737                    format!(
738                        "the configuration is printed more than once, and its {key} here, \
739                         {:?}, differs from line {at}'s, {:?}",
740                        cut(&value),
741                        cut(first)
742                    ),
743                )),
744                Some(_) => Ok(false),
745                None => {
746                    seen.insert(key, (value, number));
747                    Ok(true)
748                }
749            }
750        };
751        if let Some(value) = value_of(line, "product") {
752            if agree("product", value.to_owned())? {
753                config.product = Some(value.to_owned());
754            }
755        } else if let Some(value) = value_of(line, "serial-number") {
756            if agree("serial number", value.to_owned())? {
757                config.serial = value.parse().ok();
758            }
759        } else if let Some(value) = value_of(line, "log-format") {
760            if agree("log format", value.to_owned())? {
761                config.log_format = Some(value.parse().map_err(|_| {
762                    refuse(
763                        At::Line(number),
764                        format!("a log format of {:?}", cut(value)),
765                    )
766                })?);
767            }
768        } else if let Some(value) = value_of(line, "software-version") {
769            if agree("firmware", value.to_owned())? {
770                config.version = Some(value.to_owned());
771            }
772        } else if let Some(value) = value_of(line, "altitude-32") {
773            if agree("altitude-32", value.to_owned())? {
774                config.altitude_32 = value == "1";
775            }
776        } else if let Some(rest) = line.strip_prefix("Accel cal +1g:") {
777            if agree("accelerometer calibration", rest.trim().to_owned())? {
778                let words: Vec<&str> = rest.split_whitespace().collect();
779                if let [plus, "-1g:", minus, ..] = words.as_slice() {
780                    config.accel_plus = plus.parse().ok();
781                    config.accel_minus = minus.parse().ok();
782                }
783            }
784        } else if let Some(rest) = line.strip_prefix("ms5607 ") {
785            let constant = rest.split_once(':').and_then(|(key, value)| {
786                let index = PROM_KEYS.iter().position(|(name, _)| *name == key.trim())?;
787                Some((index, value.trim()))
788            });
789            if let Some((index, value)) = constant
790                && agree(PROM_KEYS[index].1, value.to_owned())?
791            {
792                prom[index] = value.parse().ok().filter(|c| (0..=0xffff).contains(c));
793            }
794        } else if let Some(rest) = line.strip_prefix("Pad orientation:") {
795            let written = rest.trim();
796            if agree("pad orientation", written.to_owned())? {
797                let value = written
798                    .split_whitespace()
799                    .next()
800                    .and_then(|word| word.parse::<i64>().ok());
801                config.pad_orientation = Some(match value {
802                    Some(value) => Figure::new(
803                        "pad_orientation",
804                        cut(written),
805                        Some(Quantity::Number),
806                        vec![value as f64],
807                    ),
808                    None => Figure::new("pad_orientation", cut(written), None, Vec::new()),
809                });
810            }
811        } else if let Some(rest) = line.strip_prefix("Main deploy:")
812            && config.main_deploy.is_none()
813        {
814            config.main_deploy = Some(stated_setting(
815                "main_deploy",
816                rest.trim(),
817                "meters",
818                Quantity::AltitudeAboveGround,
819            ));
820        } else if let Some(rest) = line.strip_prefix("Apogee delay:")
821            && config.apogee_delay.is_none()
822        {
823            config.apogee_delay = Some(stated_setting(
824                "apogee_delay",
825                rest.trim(),
826                "seconds",
827                Quantity::Duration,
828            ));
829        }
830    }
831    if let [Some(c1), Some(c2), Some(c3), Some(c4), Some(c5), Some(c6)] = prom {
832        config.prom = Some([c1, c2, c3, c4, c5, c6]);
833    }
834    let (log_format, board, size, from_product) = format_of(&config, At::Line(start + 1))?;
835
836    // A file that ends without a line break may end mid-line, however well that line reads.
837    let ends_cut = !text.ends_with('\n');
838    let last = lines.len() - 1;
839    let mut records = Vec::new();
840    let mut last_line_cut = false;
841    for (k, line) in lines.iter().enumerate().skip(start) {
842        if line.trim().is_empty() {
843            continue;
844        }
845        if k == last && ends_cut {
846            last_line_cut = true;
847            continue;
848        }
849        let bytes = text_record(line, size).ok_or_else(|| {
850            refuse(
851                At::Line(k + 1),
852                format!(
853                    "{:?} isn't a record of log format {log_format}: a type letter, the tick and \
854                     {}",
855                    cut(line),
856                    if size == 8 {
857                        "two 16-bit words in hexadecimal".to_owned()
858                    } else {
859                        format!("{} bytes in hexadecimal", size - 4)
860                    }
861                ),
862            )
863        })?;
864        records.push(Record {
865            at: At::Line(k + 1),
866            bytes,
867        });
868    }
869    Ok(Raw {
870        config,
871        board,
872        size,
873        log_format,
874        from_product,
875        json: false,
876        records,
877        erased: 0,
878        last_line_cut,
879    })
880}
881
882/// A setting the text form prints with its unit, such as `Main deploy: 250 meters`: in SI where
883/// the word after the number is `unit`, kept as written otherwise.
884fn stated_setting(name: &str, written: &str, unit: &str, quantity: Quantity) -> Figure {
885    let mut words = written.split_whitespace();
886    let value = words
887        .next()
888        .and_then(|word| word.parse::<f64>().ok())
889        .filter(|v| v.is_finite());
890    match (value, words.next()) {
891        (Some(value), Some(word)) if word == unit => {
892            Figure::new(name, written, Some(quantity), vec![value])
893        }
894        (Some(value), _) => Figure::new(name, written, Some(Quantity::Unrecognized), vec![value]),
895        _ => Figure::new(name, written, None, Vec::new()),
896    }
897}
898
899/// Each record's tick on the turn nearest the latest so far, and how many records come before
900/// the first one more than [`SILENCE_TICKS`] from it, which ends the flight.
901fn unwind(records: &[Record]) -> (Vec<i64>, usize) {
902    let mut latest: Option<i64> = None;
903    let mut ticks = Vec::with_capacity(records.len());
904    for (k, record) in records.iter().enumerate() {
905        let tick = match latest {
906            None => i64::from(record.tick()),
907            Some(latest) => {
908                // The step to the nearest turn, from −32,768 to 32,767 ticks.
909                #[allow(
910                    clippy::cast_possible_truncation,
911                    reason = "a remainder of a 65,536-tick turn, so the cast is exact"
912                )]
913                let step =
914                    i64::from(record.tick().wrapping_sub(latest.rem_euclid(TURN) as u16) as i16);
915                if step.abs() > SILENCE_TICKS {
916                    return (ticks, k);
917                }
918                latest + step
919            }
920        };
921        latest = Some(latest.map_or(tick, |latest| latest.max(tick)));
922        ticks.push(tick);
923    }
924    let kept = ticks.len();
925    (ticks, kept)
926}
927
928/// The MS5607's pressure, Pa, and temperature, hundredths of a °C, from its counts D1 and D2 and
929/// its constants C1 to C6: the data sheet's first-order compensation (*MS5607-02BA03*, Figure 2,
930/// p. 8) and, below 20 °C, its second order (Figure 3, p. 9), every division by 2ⁿ an arithmetic
931/// shift, a floor. In 128-bit integers, which no 32-bit count or 16-bit constant can overflow.
932fn ms5607(d1: u32, d2: u32, prom: &Prom) -> (i128, i128) {
933    let [c1, c2, c3, c4, c5, c6] = prom.map(i128::from);
934    let (d1, d2) = (i128::from(d1), i128::from(d2));
935    let dt = d2 - (c5 << 8);
936    let mut temp = 2000 + ((dt * c6) >> 23);
937    let mut off = (c2 << 17) + ((c4 * dt) >> 6);
938    let mut sens = (c1 << 16) + ((c3 * dt) >> 7);
939    if temp < 2000 {
940        let t2 = (dt * dt) >> 31;
941        let mut off2 = (61 * (temp - 2000) * (temp - 2000)) >> 4;
942        let mut sens2 = 2 * (temp - 2000) * (temp - 2000);
943        if temp < -1500 {
944            off2 += 15 * (temp + 1500) * (temp + 1500);
945            sens2 += 8 * (temp + 1500) * (temp + 1500);
946        }
947        temp -= t2;
948        off -= off2;
949        sens -= sens2;
950    }
951    let pressure = (((d1 * sens) >> 21) - off) >> 15;
952    (pressure, temp)
953}
954
955/// The TeleMetrum v1's pressure, Pa, from its count: the MP3H6115A's transfer function over the
956/// CC1111's full scale.
957fn mp3h6115a_pa(count: i16) -> f64 {
958    (f64::from(count) / CC1111_FULL_SCALE + 0.095) / 0.009 * 1000.0
959}
960
961/// The channels being built, by name, in the order first met.
962#[derive(Debug, Default)]
963struct Channels {
964    order: Vec<(String, Quantity)>,
965    data: BTreeMap<String, (Vec<f64>, Vec<f64>)>,
966}
967
968impl Channels {
969    fn push(&mut self, name: &str, quantity: Quantity, time_s: f64, value: f64) {
970        if let Some((times, values)) = self.data.get_mut(name) {
971            times.push(time_s);
972            values.push(value);
973            return;
974        }
975        self.order.push((name.to_owned(), quantity));
976        self.data
977            .insert(name.to_owned(), (vec![time_s], vec![value]));
978    }
979
980    fn get(&self, name: &str) -> Option<&(Vec<f64>, Vec<f64>)> {
981        self.data.get(name)
982    }
983
984    fn into_channels(mut self) -> Vec<Channel> {
985        self.order
986            .into_iter()
987            .filter_map(|(column, quantity)| {
988                let (time_s, values) = self.data.remove(&column)?;
989                Some(Channel {
990                    column,
991                    quantity,
992                    time_s,
993                    values,
994                })
995            })
996            .collect()
997    }
998}
999
1000/// The flight record's fields.
1001#[derive(Debug, Default)]
1002struct Flight {
1003    number: u16,
1004    ground_accel: Option<i64>,
1005    ground_pressure: Option<u32>,
1006    imu_accel: [i16; 3],
1007    gyro_sums: [i32; 3],
1008}
1009
1010/// What the accelerometer's counts become: m/s² from the zero and the counts a g, or as written
1011/// for the reason given.
1012#[derive(Debug, Clone, PartialEq)]
1013enum Accel {
1014    Converted { zero: f64, per_g: f64 },
1015    AsWritten(&'static str),
1016}
1017
1018/// From the records to the flight record.
1019fn decode(raw: Raw) -> Result<FlightLog, LogError> {
1020    let Raw {
1021        config,
1022        board,
1023        size,
1024        log_format,
1025        from_product,
1026        json,
1027        records,
1028        erased,
1029        last_line_cut,
1030    } = raw;
1031    if records.is_empty() {
1032        return Err(LogError::NoData { format: FORMAT });
1033    }
1034    let read_in_file = records.len();
1035    let (ticks, kept) = unwind(&records);
1036    let after_silence = read_in_file - kept;
1037
1038    // Exact repeats: the same bytes at the same tick.
1039    let mut seen: BTreeSet<(i64, &[u8])> = BTreeSet::new();
1040    let mut order: Vec<usize> = Vec::with_capacity(kept);
1041    let mut duplicates = 0usize;
1042    for (k, tick) in ticks.iter().enumerate() {
1043        if seen.insert((*tick, records[k].bytes.as_slice())) {
1044            order.push(k);
1045        } else {
1046            duplicates += 1;
1047        }
1048    }
1049    // Tick order, the file's order among equal ticks (the sort is stable).
1050    order.sort_by_key(|&k| ticks[k]);
1051
1052    let flights: Vec<usize> = order
1053        .iter()
1054        .copied()
1055        .filter(|&k| records[k].kind() == b'F')
1056        .collect();
1057    let zero = match flights.as_slice() {
1058        [] => {
1059            return Err(refuse(
1060                records.first().map_or(At::Line(1), |record| record.at),
1061                "no flight record (`F`), whose tick is the flight's zero".to_owned(),
1062            ));
1063        }
1064        [only] => *only,
1065        [first, second, ..] => {
1066            return Err(refuse(
1067                records[*second].at,
1068                format!(
1069                    "a second flight record, after the one at {}: two flights in one file",
1070                    describe(records[*first].at)
1071                ),
1072            ));
1073        }
1074    };
1075    let zero_tick = ticks[zero];
1076    let f = &records[zero];
1077    let flight = match board {
1078        Board::TeleMetrumV1 => Flight {
1079            number: f.u16(6),
1080            ground_accel: Some(i64::from(f.u16(4))),
1081            ..Flight::default()
1082        },
1083        Board::EasyMini => Flight {
1084            number: f.u16(4),
1085            ground_pressure: Some(f.u32(8)),
1086            ..Flight::default()
1087        },
1088        Board::TeleMetrumV2 => Flight {
1089            number: f.u16(4),
1090            ground_accel: Some(i64::from(f.i16(6))),
1091            ground_pressure: Some(f.u32(8)),
1092            ..Flight::default()
1093        },
1094        Board::Mega => Flight {
1095            number: f.u16(4),
1096            ground_accel: Some(i64::from(f.i16(6))),
1097            ground_pressure: Some(f.u32(8)),
1098            imu_accel: [f.i16(12), f.i16(14), f.i16(16)],
1099            gyro_sums: [f.i32(20), f.i32(24), f.i32(28)],
1100        },
1101    };
1102
1103    let prom = match board {
1104        Board::TeleMetrumV1 => None,
1105        _ if config.ms5611 => None,
1106        _ => config.prom,
1107    };
1108    // The pressure in pascals, which the climb check holds the acceleration to.
1109    let pascals = board == Board::TeleMetrumV1 || prom.is_some();
1110    let accel = match (
1111        board,
1112        config.accel_plus,
1113        config.accel_minus,
1114        flight.ground_accel,
1115    ) {
1116        (Board::EasyMini, ..) => Accel::AsWritten("the board has no accelerometer"),
1117        (_, Some(plus), Some(minus), Some(_))
1118            if !SIXTEEN_BITS.contains(&plus) || !SIXTEEN_BITS.contains(&minus) =>
1119        {
1120            Accel::AsWritten("the calibration lies outside a 16-bit count's range")
1121        }
1122        (_, Some(plus), Some(minus), Some(ground)) => match minus.checked_sub(plus) {
1123            Some(span) if span > 0 && pascals => Accel::Converted {
1124                zero: ground as f64,
1125                per_g: span as f64 / 2.0,
1126            },
1127            Some(span) if span > 0 => Accel::AsWritten(
1128                "no pressure in pascals to hold it to, so its unit has no second check",
1129            ),
1130            _ => Accel::AsWritten("the calibration's span isn't positive"),
1131        },
1132        (_, _, _, Some(_)) => Accel::AsWritten("the calibration isn't set"),
1133        _ => Accel::AsWritten("the flight record holds no ground reading"),
1134    };
1135    // A Mega's senses in volts only where the product's divider is the one converted by.
1136    let mega_volts = config
1137        .product
1138        .as_deref()
1139        .is_some_and(|product| MEGA_15_V_PRODUCTS.contains(&product));
1140    let imu_read = match board {
1141        Board::Mega => {
1142            log_format != 15 && (flight.imu_accel != [0; 3] || flight.gyro_sums != [0; 3])
1143        }
1144        _ => false,
1145    };
1146
1147    // The GPS fixes' validity, by tick, for boards whose position records carry no flags.
1148    let valid_at: BTreeSet<i64> = order
1149        .iter()
1150        .filter(|&&k| {
1151            let record = &records[k];
1152            record.kind() == b'G'
1153                && matches!(board, Board::TeleMetrumV1 | Board::TeleMetrumV2)
1154                && record.bytes[7] & GPS_VALID != 0
1155        })
1156        .map(|&k| ticks[k])
1157        .collect();
1158
1159    // The second check of the acceleration's unit and, on a TeleMetrum v1, of the pressure's:
1160    // their climbs over the first second after boost agree. Where they don't, or can't be
1161    // measured, both are kept as written: neither unit is borne out.
1162    let (accel, v1_pascals, climb_note) = match accel {
1163        Accel::Converted { zero, per_g } => {
1164            let samples: Vec<(i64, f64, f64)> = order
1165                .iter()
1166                .filter_map(|&k| {
1167                    let (pa, count) = climb_sample(board, &records[k], prom.as_ref())?;
1168                    let along = (zero - count as f64) / per_g * STANDARD_GRAVITY;
1169                    Some((ticks[k] - zero_tick, pa, along))
1170                })
1171                .collect();
1172            let v1 = if board == Board::TeleMetrumV1 {
1173                ", and the TeleMetrum v1's `pressure`, which has no other check, too"
1174            } else {
1175                ""
1176            };
1177            match climb_over_the_window(&samples) {
1178                // Both climbs upward, and in the band: two downward climbs make a ratio in it too.
1179                Ok(measured)
1180                    if measured.by_acceleration_m > 0.0
1181                        && CLIMB_RATIO.contains(&measured.ratio) =>
1182                {
1183                    let note = format!(
1184                        "`pressure` and `acceleration` held to each other. Over the first second \
1185                         after boost the rocket climbs {:.1} m by the pressure in the standard \
1186                         atmosphere. By the acceleration integrated twice from rest on the pad it \
1187                         climbs {:.1} m. The ratio is {:.3}, within 0.6 to 5/3",
1188                        measured.by_pressure_m, measured.by_acceleration_m, measured.ratio
1189                    );
1190                    (accel, true, Some(note))
1191                }
1192                Ok(measured) => {
1193                    let note = format!(
1194                        "over the first second after boost the rocket climbs {:.1} m by the \
1195                         pressure and {:.1} m by the acceleration. The ratio is {:.3}, outside \
1196                         0.6 to 5/3. The two disagree, so the acceleration's counts are kept as \
1197                         written{v1}",
1198                        measured.by_pressure_m, measured.by_acceleration_m, measured.ratio
1199                    );
1200                    (
1201                        Accel::AsWritten("its climb disagrees with the pressure's"),
1202                        false,
1203                        Some(note),
1204                    )
1205                }
1206                Err(why) => {
1207                    let note = format!(
1208                        "the climb over the first second after boost can't be measured ({why}), \
1209                         so the acceleration's counts are kept as written{v1}"
1210                    );
1211                    (
1212                        Accel::AsWritten("its climb can't be measured"),
1213                        false,
1214                        Some(note),
1215                    )
1216                }
1217            }
1218        }
1219        Accel::AsWritten(why) => {
1220            let note = if board == Board::TeleMetrumV1 {
1221                Some(
1222                    "`pres` kept as written. The acceleration is kept as written, so there is \
1223                     no climb to hold the TeleMetrum v1's pressure to. The pad's band alone \
1224                     rejects almost no count"
1225                        .to_owned(),
1226                )
1227            } else if board != Board::EasyMini && prom.is_some() {
1228                Some(
1229                    "`pressure`'s second check is the pad's alone: the acceleration, kept as \
1230                     written, gives no climb to hold it to"
1231                        .to_owned(),
1232                )
1233            } else {
1234                None
1235            };
1236            (Accel::AsWritten(why), false, note)
1237        }
1238    };
1239
1240    let mut channels = Channels::default();
1241    let mut events: Vec<Event> = Vec::new();
1242    let mut state: Option<u16> = None;
1243    let mut not_read: BTreeMap<u8, usize> = BTreeMap::new();
1244    let mut no_fix = 0usize;
1245    let mut sense_counts_off = 0usize;
1246    let mut satellites_cut = 0usize;
1247    let mut before_boost = 0usize;
1248    let along = |count: i64| match &accel {
1249        Accel::Converted { zero, per_g } => Some((zero - count as f64) / per_g * STANDARD_GRAVITY),
1250        Accel::AsWritten(_) => None,
1251    };
1252    for &k in &order {
1253        let record = &records[k];
1254        let time = (ticks[k] - zero_tick) as f64 / TICKS_PER_S;
1255        if time < 0.0 {
1256            before_boost += 1;
1257        }
1258        let mut push = |name: &str, quantity: Quantity, value: f64| {
1259            channels.push(name, quantity, time, value);
1260        };
1261        let accelerometer =
1262            |push: &mut dyn FnMut(&str, Quantity, f64), count: i64| match along(count) {
1263                Some(value) => push("acceleration", Quantity::Acceleration, value),
1264                None => push("accel", Quantity::Unrecognized, count as f64),
1265            };
1266        let barometer = |push: &mut dyn FnMut(&str, Quantity, f64), d1: u32, d2: u32| match &prom {
1267            Some(prom) => {
1268                let (pa, centi) = ms5607(d1, d2, prom);
1269                push("pressure", Quantity::Pressure, pa as f64);
1270                push(
1271                    "temperature",
1272                    Quantity::Temperature,
1273                    centi as f64 / 100.0 + 273.15,
1274                );
1275            }
1276            None => {
1277                push("d1", Quantity::Unrecognized, f64::from(d1));
1278                push("d2", Quantity::Unrecognized, f64::from(d2));
1279            }
1280        };
1281        let mut position = |push: &mut dyn FnMut(&str, Quantity, f64),
1282                            valid: bool,
1283                            lat: Option<i32>,
1284                            lon: Option<i32>,
1285                            alt: Option<f64>| {
1286            if !valid {
1287                no_fix += 1;
1288            }
1289            let fix = |value: f64| if valid { value } else { f64::NAN };
1290            if let Some(lat) = lat {
1291                push("latitude", Quantity::Latitude, fix(f64::from(lat) / 1e7));
1292            }
1293            if let Some(lon) = lon {
1294                push("longitude", Quantity::Longitude, fix(f64::from(lon) / 1e7));
1295            }
1296            if let Some(alt) = alt {
1297                push("gps_altitude", Quantity::GnssAltitude, fix(alt));
1298            }
1299        };
1300        let altitude = |low: usize, high: usize| {
1301            if config.altitude_32 {
1302                f64::from(record.i16(high)) * 65_536.0 + f64::from(record.u16(low))
1303            } else {
1304                f64::from(record.i16(low))
1305            }
1306        };
1307        match (board, record.kind()) {
1308            (_, b'F') => {}
1309            (_, b'S') => {
1310                let now = record.u16(4);
1311                if state != Some(now) {
1312                    events.push(Event {
1313                        time_s: time,
1314                        name: state_name(now),
1315                    });
1316                    state = Some(now);
1317                }
1318                push("state", Quantity::Number, f64::from(now));
1319            }
1320            (Board::TeleMetrumV1, b'A') => {
1321                let (count, pres) = (i64::from(record.i16(4)), record.i16(6));
1322                accelerometer(&mut push, count);
1323                if v1_pascals {
1324                    push("pressure", Quantity::Pressure, mp3h6115a_pa(pres));
1325                } else {
1326                    push("pres", Quantity::Unrecognized, f64::from(pres));
1327                }
1328            }
1329            (Board::TeleMetrumV1, b'T') => {
1330                push("temp", Quantity::Unrecognized, f64::from(record.i16(4)));
1331                push("v_batt", Quantity::Unrecognized, f64::from(record.i16(6)));
1332            }
1333            (Board::TeleMetrumV1, b'D') => {
1334                push("sense_a", Quantity::Unrecognized, f64::from(record.i16(4)));
1335                push("sense_m", Quantity::Unrecognized, f64::from(record.i16(6)));
1336            }
1337            (Board::TeleMetrumV1 | Board::TeleMetrumV2, b'G') => {
1338                let flags = record.bytes[7];
1339                for (j, name) in ["hour", "minute", "second"].into_iter().enumerate() {
1340                    push(name, Quantity::Number, record.u8(4 + j));
1341                }
1342                push("gps_flags", Quantity::Number, f64::from(flags));
1343                push("nsat", Quantity::Number, f64::from(flags & 0x0f));
1344                if board == Board::TeleMetrumV2 {
1345                    for (j, name) in ["year", "month", "day"].into_iter().enumerate() {
1346                        push(name, Quantity::Number, record.u8(8 + j));
1347                    }
1348                    push("gps_byte_11", Quantity::Unrecognized, record.u8(11));
1349                }
1350            }
1351            (Board::TeleMetrumV1, b'N') => {
1352                let valid = valid_at.contains(&ticks[k]);
1353                position(&mut push, valid, Some(record.i32(4)), None, None);
1354            }
1355            (Board::TeleMetrumV1, b'W') => {
1356                let valid = valid_at.contains(&ticks[k]);
1357                position(&mut push, valid, None, Some(record.i32(4)), None);
1358            }
1359            (Board::TeleMetrumV1, b'H') => {
1360                let valid = valid_at.contains(&ticks[k]);
1361                position(&mut push, valid, None, None, Some(f64::from(record.i16(4))));
1362            }
1363            (Board::TeleMetrumV1, b'Y') => {
1364                for (j, name) in ["year", "month", "day"].into_iter().enumerate() {
1365                    push(name, Quantity::Number, record.u8(4 + j));
1366                }
1367            }
1368            (Board::TeleMetrumV1, b'V') => {
1369                push("svid", Quantity::Number, record.u8(4));
1370                push("c_n", Quantity::Number, record.u8(7));
1371            }
1372            (Board::EasyMini, b'A') => {
1373                barometer(&mut push, record.u24(4), record.u24(7));
1374                push("sense_a", Quantity::Unrecognized, f64::from(record.u16(10)));
1375                push("sense_m", Quantity::Unrecognized, f64::from(record.u16(12)));
1376                push("v_batt", Quantity::Unrecognized, f64::from(record.u16(14)));
1377            }
1378            (Board::TeleMetrumV2, b'A') => {
1379                let (d1, d2, count) = (record.u32(4), record.u32(8), i64::from(record.i16(12)));
1380                barometer(&mut push, d1, d2);
1381                accelerometer(&mut push, count);
1382            }
1383            (Board::TeleMetrumV2, b'T') => {
1384                push("v_batt", Quantity::Unrecognized, f64::from(record.i16(4)));
1385                push("sense_a", Quantity::Unrecognized, f64::from(record.i16(6)));
1386                push("sense_m", Quantity::Unrecognized, f64::from(record.i16(8)));
1387            }
1388            (Board::TeleMetrumV2, b'P') => {
1389                let valid = valid_at.contains(&ticks[k]);
1390                position(
1391                    &mut push,
1392                    valid,
1393                    Some(record.i32(4)),
1394                    Some(record.i32(8)),
1395                    Some(altitude(12, 14)),
1396                );
1397            }
1398            (Board::TeleMetrumV2 | Board::Mega, b'V') => {
1399                let count = usize::from(record.bytes[4]);
1400                let room = (size - 6) / 2;
1401                if count > room {
1402                    satellites_cut += 1;
1403                }
1404                push("sat_count", Quantity::Number, f64::from(record.bytes[4]));
1405                for j in 0..count.min(room) {
1406                    push("svid", Quantity::Number, record.u8(6 + 2 * j));
1407                    push("c_n", Quantity::Number, record.u8(7 + 2 * j));
1408                }
1409            }
1410            (Board::Mega, b'A') => {
1411                let (d1, d2) = (record.u32(4), record.u32(8));
1412                barometer(&mut push, d1, d2);
1413                if imu_read {
1414                    const IMU: [&str; 9] = [
1415                        "imu_accel_0",
1416                        "imu_accel_1",
1417                        "imu_accel_2",
1418                        "imu_gyro_0",
1419                        "imu_gyro_1",
1420                        "imu_gyro_2",
1421                        "imu_mag_0",
1422                        "imu_mag_1",
1423                        "imu_mag_2",
1424                    ];
1425                    for (j, name) in IMU.into_iter().enumerate() {
1426                        push(
1427                            name,
1428                            Quantity::Unrecognized,
1429                            f64::from(record.i16(12 + 2 * j)),
1430                        );
1431                    }
1432                }
1433                let count = i64::from(record.i16(30));
1434                accelerometer(&mut push, count);
1435            }
1436            (Board::Mega, b'T') => {
1437                push("v_batt", Quantity::Unrecognized, f64::from(record.i16(4)));
1438                let volts = |count: i16| {
1439                    if mega_volts {
1440                        (Quantity::Voltage, f64::from(count) * MEGA_SENSE_V)
1441                    } else {
1442                        (Quantity::Unrecognized, f64::from(count))
1443                    }
1444                };
1445                let (quantity, value) = volts(record.i16(6));
1446                push("pyro", quantity, value);
1447                let senses = record.i16(8);
1448                push("n_sense", Quantity::Number, f64::from(senses));
1449                if senses == 6 {
1450                    const SENSES: [&str; 6] = [
1451                        "igniter_a",
1452                        "igniter_b",
1453                        "igniter_c",
1454                        "igniter_d",
1455                        "drogue_voltage",
1456                        "main_voltage",
1457                    ];
1458                    for (j, name) in SENSES.into_iter().enumerate() {
1459                        let (quantity, value) = volts(record.i16(10 + 2 * j));
1460                        push(name, quantity, value);
1461                    }
1462                } else {
1463                    sense_counts_off += 1;
1464                    for j in 0..6 {
1465                        push(
1466                            [
1467                                "sense_0", "sense_1", "sense_2", "sense_3", "sense_4", "sense_5",
1468                            ][j],
1469                            Quantity::Unrecognized,
1470                            f64::from(record.i16(10 + 2 * j)),
1471                        );
1472                    }
1473                }
1474            }
1475            (Board::Mega, b'G') => {
1476                let flags = record.bytes[17];
1477                position(
1478                    &mut push,
1479                    flags & GPS_VALID != 0,
1480                    Some(record.i32(4)),
1481                    Some(record.i32(8)),
1482                    Some(altitude(12, 30)),
1483                );
1484                for (j, name) in ["hour", "minute", "second"].into_iter().enumerate() {
1485                    push(name, Quantity::Number, record.u8(14 + j));
1486                }
1487                push("gps_flags", Quantity::Number, f64::from(flags));
1488                push("nsat", Quantity::Number, f64::from(flags & 0x0f));
1489                for (j, name) in ["year", "month", "day"].into_iter().enumerate() {
1490                    push(name, Quantity::Number, record.u8(18 + j));
1491                }
1492                push("course", Quantity::Unrecognized, record.u8(21));
1493                push(
1494                    "ground_speed",
1495                    Quantity::Unrecognized,
1496                    f64::from(record.u16(22)),
1497                );
1498                push(
1499                    "climb_rate",
1500                    Quantity::Unrecognized,
1501                    f64::from(record.i16(24)),
1502                );
1503                for (j, name) in ["pdop", "hdop", "vdop", "gps_mode"].into_iter().enumerate() {
1504                    push(name, Quantity::Number, record.u8(26 + j));
1505                }
1506            }
1507            (_, kind) => *not_read.entry(kind).or_default() += 1,
1508        }
1509    }
1510    if channels.data.is_empty() {
1511        return Err(LogError::NoData { format: FORMAT });
1512    }
1513
1514    // The second check of the pressure's unit: the pad's.
1515    let pad = channels.get("pressure").and_then(|(times, values)| {
1516        let mut before: Vec<f64> = times
1517            .iter()
1518            .zip(values)
1519            .filter(|(time, value)| **time < 0.0 && value.is_finite())
1520            .map(|(_, value)| *value)
1521            .collect();
1522        crate::filter::median(&mut before).or_else(|| values.first().copied())
1523    });
1524    let mut pad_note = None;
1525    if let Some(pad) = pad {
1526        if !PAD_PRESSURE_PA.contains(&pad) {
1527            return Err(refuse(
1528                f.at,
1529                format!(
1530                    "the pad's pressure reads {pad:.0} Pa, outside every launch site's 10 to \
1531                     120 kPa: the records are misread or damaged"
1532                ),
1533            ));
1534        }
1535        match flight.ground_pressure {
1536            Some(ground) => {
1537                let ground = f64::from(ground);
1538                let off = (pad - ground).abs() / ground;
1539                // A NaN (a ground pressure of 0) fails the check, as it must.
1540                if off.is_nan() || off > GROUND_AGREES {
1541                    return Err(refuse(
1542                        f.at,
1543                        format!(
1544                            "the pad's pressure reads {pad:.0} Pa, {:.1}% from the flight \
1545                             record's ground pressure, {ground:.0} Pa: the records are misread or \
1546                             damaged",
1547                            100.0 * off
1548                        ),
1549                    ));
1550                }
1551                pad_note = Some(format!(
1552                    "`pressure` and `temperature` from the MS5607's counts by its data sheet's \
1553                     compensation, first and second order. The pad's pressure, {pad:.0} Pa, lies \
1554                     from 10 to 120 kPa and within {:.2}% of the flight record's ground pressure, \
1555                     {ground:.0} Pa",
1556                    100.0 * off
1557                ));
1558            }
1559            None => {
1560                pad_note = Some(format!(
1561                    "`pressure` from the MP3H6115A's transfer function over the CC1111's full \
1562                     scale, 32,752: the pad's pressure, {pad:.0} Pa, lies from 10 to 120 kPa"
1563                ));
1564            }
1565        }
1566    }
1567
1568    // The pad's temperature, an MS5607's: within the sensor's operating range.
1569    let pad_temperature = channels.get("temperature").and_then(|(times, values)| {
1570        let mut before: Vec<f64> = times
1571            .iter()
1572            .zip(values)
1573            .filter(|(time, value)| **time < 0.0 && value.is_finite())
1574            .map(|(_, value)| *value)
1575            .collect();
1576        crate::filter::median(&mut before).or_else(|| values.first().copied())
1577    });
1578    if let Some(kelvin) = pad_temperature
1579        && !MS5607_OPERATING_K.contains(&kelvin)
1580    {
1581        return Err(refuse(
1582            f.at,
1583            format!(
1584                "the pad's temperature reads {:.1} °C, outside the MS5607's operating range, −40 \
1585                 to 85 °C: the records are misread or damaged",
1586                kelvin - 273.15
1587            ),
1588        ));
1589    }
1590
1591    let mut notes = Vec::new();
1592    notes.push(if json {
1593        format!(
1594            "{read_in_file} records of {size} bytes, log format {log_format}, from the JSON form: \
1595             every record's checksum checked, all pass"
1596        )
1597    } else {
1598        format!(
1599            "{read_in_file} records of {size} bytes, log format {log_format}, from the text form, \
1600             which prints no checksum"
1601        )
1602    });
1603    if from_product {
1604        notes.push(format!(
1605            "the configuration states no log format, as firmware before 1.0 didn't: format 1, \
1606             from its product, {}",
1607            config.product.as_deref().unwrap_or("")
1608        ));
1609    }
1610    if erased > 0 {
1611        notes.push(format!(
1612            "{erased} erased records (every byte 0xFF) after the last, skipped"
1613        ));
1614    }
1615    if last_line_cut {
1616        notes.push(
1617            "the file ends without a line break, so its last line may be cut short: left out"
1618                .to_owned(),
1619        );
1620    }
1621    if after_silence > 0 {
1622        notes.push(format!(
1623            "{after_silence} records from the first more than 10 s from the latest tick on are \
1624             left out. No logging rate leaves such a silence, so they are not this flight's"
1625        ));
1626    }
1627    if duplicates > 0 {
1628        notes.push(format!(
1629            "{duplicates} records repeated exactly, the same bytes at the same tick, dropped"
1630        ));
1631    }
1632    notes.push(format!(
1633        "the clock is the board's tick, 10 ms, from the flight record's at tick {zero_tick} \
1634         (boost detection). Each tick is on the turn nearest the latest so far, from the file's \
1635         first record. The records are in tick order, as the file's isn't. {before_boost} \
1636         records are before boost, at negative times"
1637    ));
1638    if let Some(note) = pad_note {
1639        notes.push(note);
1640    }
1641    if let Some(kelvin) = pad_temperature {
1642        notes.push(format!(
1643            "`temperature` on the pad, {:.1} °C, within the MS5607's operating range, −40 to 85 °C",
1644            kelvin - 273.15
1645        ));
1646    }
1647    if let Some(note) = climb_note {
1648        notes.push(note);
1649    }
1650    if prom.is_none() && board != Board::TeleMetrumV1 {
1651        notes.push(
1652            if config.ms5611 {
1653                "`d1` and `d2` kept as written: the configuration marks the barometer an MS5611, \
1654                 whose compensation isn't the MS5607's"
1655            } else {
1656                "`d1` and `d2` kept as written: the configuration holds no MS5607 constants"
1657            }
1658            .to_owned(),
1659        );
1660    }
1661    match &accel {
1662        Accel::Converted { zero, per_g } => notes.push(format!(
1663            "`acceleration` along the board's axis, m/s², from the high-g accelerometer's counts. \
1664             It is 0 at the flight record's ground reading, {zero:.0}. A g is {per_g} counts, \
1665             from the calibration's +1 g and −1 g, {} and {}",
1666            config.accel_plus.unwrap_or(0),
1667            config.accel_minus.unwrap_or(0)
1668        )),
1669        Accel::AsWritten(why) if board != Board::EasyMini => {
1670            notes.push(format!("`accel` kept as written: {why}"));
1671        }
1672        Accel::AsWritten(_) => {}
1673    }
1674    let kept: Vec<&str> = [
1675        "v_batt",
1676        "sense_a",
1677        "sense_m",
1678        "temp",
1679        "imu_accel_0",
1680        "gps_byte_11",
1681    ]
1682    .into_iter()
1683    .filter(|name| channels.get(name).is_some())
1684    .collect();
1685    if !kept.is_empty() {
1686        notes.push(format!(
1687            "kept as written, counts with no cited conversion: {}",
1688            kept.iter()
1689                .map(|name| match *name {
1690                    "imu_accel_0" => "the IMU's nine words".to_owned(),
1691                    "temp" => "`temp` (the CC1111's die temperature)".to_owned(),
1692                    "gps_byte_11" =>
1693                        "`gps_byte_11` (a dilution in some firmware, a stale byte in others)"
1694                            .to_owned(),
1695                    name => format!("`{name}`"),
1696                })
1697                .collect::<Vec<_>>()
1698                .join(", ")
1699        ));
1700    }
1701    if channels.get("pyro").is_some() {
1702        notes.push(if mega_volts {
1703            "`pyro`, the igniters' and the apogee and main senses in V, as AltOS Telemetry \
1704             converts a 15 V Mega's: count / 4095 × 3.3 V × 127 / 27"
1705                .to_owned()
1706        } else {
1707            format!(
1708                "`pyro`, the igniters' and the apogee and main senses kept as written. The \
1709                 product, {}, isn't one whose divider the sample exports bear out, and a 30 V \
1710                 board's isn't a 15 V board's",
1711                cut(config.product.as_deref().unwrap_or("not stated"))
1712            )
1713        });
1714    }
1715    if sense_counts_off > 0 {
1716        notes.push(format!(
1717            "{sense_counts_off} sense records name a count of senses other than 6: their six \
1718             words kept as written, `sense_0` to `sense_5`"
1719        ));
1720    }
1721    if board == Board::Mega && !imu_read {
1722        notes.push(
1723            if log_format == 15 {
1724                "the IMU not read: format 15's layout of it is unconfirmed"
1725            } else {
1726                "the IMU not read: the flight record's IMU fields are all zero, so the records' \
1727                 IMU bytes are stale"
1728            }
1729            .to_owned(),
1730        );
1731    }
1732    if channels.get("gps_flags").is_some() {
1733        notes.push(
1734            "GPS: the time, date, dilutions, course, speed, climb, satellite counts and signals \
1735             kept as written. The date has two digits and is not reliably the flight's. The \
1736             dilutions are ten times their value"
1737                .to_owned(),
1738        );
1739    }
1740    if no_fix > 0 {
1741        notes.push(format!(
1742            "{no_fix} GPS position records without a valid fix: their positions read as gaps"
1743        ));
1744    }
1745    if satellites_cut > 0 {
1746        notes.push(format!(
1747            "{satellites_cut} satellite records name more satellites than they hold: those that \
1748             fit are read"
1749        ));
1750    }
1751    for (kind, count) in &not_read {
1752        notes.push(format!(
1753            "{count} records of type {} not read: the board's layout holds no such record",
1754            if kind.is_ascii_graphic() {
1755                format!("`{}`", char::from(*kind))
1756            } else {
1757                format!("0x{kind:02X}")
1758            }
1759        ));
1760    }
1761
1762    let mut figures = Vec::new();
1763    if let Some(ground) = flight.ground_pressure {
1764        figures.push(Figure::new(
1765            "ground_pressure",
1766            ground.to_string(),
1767            Some(Quantity::Pressure),
1768            vec![f64::from(ground)],
1769        ));
1770    }
1771    if let Some(ground) = flight.ground_accel {
1772        figures.push(Figure::new(
1773            "ground_accel",
1774            ground.to_string(),
1775            Some(Quantity::Unrecognized),
1776            vec![ground as f64],
1777        ));
1778    }
1779    if board != Board::EasyMini {
1780        for (name, value) in [
1781            ("accel_cal_plus", config.accel_plus),
1782            ("accel_cal_minus", config.accel_minus),
1783        ] {
1784            if let Some(value) = value {
1785                figures.push(Figure::new(
1786                    name,
1787                    value.to_string(),
1788                    Some(Quantity::Unrecognized),
1789                    vec![value as f64],
1790                ));
1791            }
1792        }
1793    }
1794    if imu_read {
1795        let accel: Vec<f64> = flight.imu_accel.iter().map(|v| f64::from(*v)).collect();
1796        let gyro: Vec<f64> = flight.gyro_sums.iter().map(|v| f64::from(*v)).collect();
1797        figures.push(Figure::new(
1798            "ground_imu_accel",
1799            join(&accel),
1800            Some(Quantity::Unrecognized),
1801            accel,
1802        ));
1803        figures.push(Figure::new(
1804            "ground_gyro_sums",
1805            join(&gyro),
1806            Some(Quantity::Unrecognized),
1807            gyro,
1808        ));
1809    }
1810    figures.extend(config.pad_orientation);
1811    figures.extend(config.main_deploy);
1812    figures.extend(config.apogee_delay);
1813
1814    Ok(FlightLog {
1815        format: LogFormat::AltosEeprom,
1816        logger: match &config.product {
1817            Some(product) => format!("AltOS {product}"),
1818            None => "AltOS".to_owned(),
1819        },
1820        serial_number: config.serial.map(|serial| serial.to_string()),
1821        firmware: config.version,
1822        flight_number: Some(u32::from(flight.number)),
1823        stated: Stated {
1824            figures,
1825            ..Stated::default()
1826        },
1827        time_s: Vec::new(),
1828        altitude_m: Vec::new(),
1829        vertical_speed_m_s: None,
1830        temperature_k: None,
1831        battery_v: None,
1832        channels: channels.into_channels(),
1833        events,
1834        notes,
1835    })
1836}
1837
1838/// What the climb check measured: the climb over the first second after boost by the pressure and
1839/// by the acceleration, m, and the first over the second.
1840#[derive(Debug, Clone, Copy, PartialEq)]
1841struct Climb {
1842    by_pressure_m: f64,
1843    by_acceleration_m: f64,
1844    ratio: f64,
1845}
1846
1847/// A sensor record's pressure in pascals and its along-axis acceleration count, for the climb
1848/// check: the TeleMetrum v1's by its sensor's transfer function, an MS5607 board's by the data
1849/// sheet's compensation; `None` for any other record, or an MS5607 board without its calibration.
1850fn climb_sample(board: Board, record: &Record, prom: Option<&Prom>) -> Option<(f64, i64)> {
1851    if record.kind() != b'A' {
1852        return None;
1853    }
1854    match board {
1855        Board::TeleMetrumV1 => Some((mp3h6115a_pa(record.i16(6)), i64::from(record.i16(4)))),
1856        Board::TeleMetrumV2 => {
1857            let (pa, _) = ms5607(record.u32(4), record.u32(8), prom?);
1858            Some((pa as f64, i64::from(record.i16(12))))
1859        }
1860        Board::Mega => {
1861            let (pa, _) = ms5607(record.u32(4), record.u32(8), prom?);
1862            Some((pa as f64, i64::from(record.i16(30))))
1863        }
1864        Board::EasyMini => None,
1865    }
1866}
1867
1868/// The climb check's measurement over the samples holding both a pressure, Pa, and an
1869/// acceleration along the board's axis, m/s², each with its tick from the flight record's, in tick
1870/// order; `Err` saying why the window can't be measured.
1871///
1872/// The climb by the pressure is the pressure altitude, in the U.S. Standard Atmosphere, 1976
1873/// ([`hpr_atmos::ussa76`]; ISO 2533:1975's below 32 km), at the window's end less the pad's: the
1874/// median pressure of the samples within [`CLIMB_END_TICKS`] of the window's last sample, and of
1875/// the samples before boost. The climb by the acceleration is the acceleration integrated twice by
1876/// the trapezoid rule from the first sample before boost, at rest: zero speed, and zero
1877/// acceleration on the pad by the reading's own zero. The window must start before boost, run to
1878/// [`CLIMB_WINDOW_TICKS`] after it, and hold no gap over [`CLIMB_GAP_TICKS`].
1879fn climb_over_the_window(samples: &[(i64, f64, f64)]) -> Result<Climb, String> {
1880    let seconds = |ticks: i64| ticks as f64 / TICKS_PER_S;
1881    let mut pad: Vec<f64> = samples
1882        .iter()
1883        .filter(|(tick, ..)| *tick < 0)
1884        .map(|(_, pa, _)| *pa)
1885        .collect();
1886    let pad_pa =
1887        crate::filter::median(&mut pad).ok_or("no sample before boost to start from at rest")?;
1888    let last = samples.last().map_or(i64::MIN, |(tick, ..)| *tick);
1889    if last < CLIMB_WINDOW_TICKS {
1890        return Err(format!(
1891            "the samples end {:.2} s after boost, before the window's 1 s",
1892            seconds(last)
1893        ));
1894    }
1895    let mut window = Vec::new();
1896    for pair in samples.windows(2) {
1897        let [(from, ..), (to, ..)] = [pair[0], pair[1]];
1898        if to - from > CLIMB_GAP_TICKS {
1899            return Err(format!(
1900                "no sample for {:.2} s after the one at {:.2} s, more than the slowest logging \
1901                 rate's 0.1 s",
1902                seconds(to - from),
1903                seconds(from)
1904            ));
1905        }
1906        window.push(pair);
1907        if to >= CLIMB_WINDOW_TICKS {
1908            break;
1909        }
1910    }
1911    let mut end = samples.first().map_or(0, |(tick, ..)| *tick);
1912    let (mut speed, mut climb_by_acceleration) = (0.0, 0.0);
1913    for pair in window {
1914        let [(from, _, a0), (to, _, a1)] = [pair[0], pair[1]];
1915        if to > CLIMB_WINDOW_TICKS {
1916            break;
1917        }
1918        let dt = seconds(to - from);
1919        let next = speed + (a0 + a1) / 2.0 * dt;
1920        climb_by_acceleration += (speed + next) / 2.0 * dt;
1921        speed = next;
1922        end = to;
1923    }
1924    let mut near: Vec<f64> = samples
1925        .iter()
1926        .filter(|(tick, ..)| (tick - end).abs() <= CLIMB_END_TICKS)
1927        .map(|(_, pa, _)| *pa)
1928        .collect();
1929    let end_pa = crate::filter::median(&mut near).unwrap_or(f64::NAN);
1930    let atmosphere = hpr_atmos::ussa76::Ussa76::standard();
1931    let height = |pa: f64| atmosphere.pressure_altitude_m(pa).unwrap_or(f64::NAN);
1932    let by_pressure_m = height(end_pa) - height(pad_pa);
1933    Ok(Climb {
1934        by_pressure_m,
1935        by_acceleration_m: climb_by_acceleration,
1936        ratio: by_pressure_m / climb_by_acceleration,
1937    })
1938}
1939
1940/// Numbers joined by commas, as a figure writes a vector.
1941fn join(values: &[f64]) -> String {
1942    values
1943        .iter()
1944        .map(f64::to_string)
1945        .collect::<Vec<_>>()
1946        .join(",")
1947}
1948
1949/// Where a record sits, in words.
1950fn describe(at: At) -> String {
1951    match at {
1952        At::Line(line) => format!("line {line}"),
1953        At::Offset(offset) => format!("byte {offset}"),
1954    }
1955}
1956
1957/// A state's name, as AltosUI's exports write it, or `state N`.
1958fn state_name(number: u16) -> String {
1959    STATES
1960        .iter()
1961        .find(|(known, _)| *known == number)
1962        .map_or_else(|| format!("state {number}"), |(_, name)| (*name).to_owned())
1963}
1964
1965/// Text cut to 80 characters, for an error.
1966fn cut(text: &str) -> String {
1967    text.chars().take(80).collect()
1968}
1969
1970#[cfg(test)]
1971mod tests {
1972    use super::*;
1973
1974    /// The data sheet's own example constants, C1 to C6 (*MS5607-02BA03*, Figure 2, p. 8).
1975    const EXAMPLE_PROM: Prom = [46_372, 43_981, 29_059, 27_842, 31_553, 28_165];
1976
1977    /// The data sheet's example counts, D1 and D2: 1,100.02 mbar at 20.00 °C.
1978    const EXAMPLE_D1: u32 = 6_465_444;
1979    const EXAMPLE_D2: u32 = 8_077_636;
1980
1981    /// An invented TeleMetrum v2's configuration in the JSON form: the data sheet's example
1982    /// constants, and a calibration of 20 counts a g.
1983    const HEAD_V2: &str = r#"{
1984        "accel_cal_minus": 1040, "accel_cal_plus": 1000, "altitude_32": 1, "apogee_delay": 0,
1985        "flight": 2147483647, "log_format": 7, "main_deploy": 250,
1986        "ms5607": {"ms5611": false, "off": 43981, "sens": 46372, "tco": 27842, "tcs": 29059,
1987                   "tempsens": 28165, "tref": 31553},
1988        "product": "TeleMetrum-v2.0", "serial": 1234, "stored_flight": 9, "version": "1.9.22"
1989    }"#;
1990
1991    /// The same configuration as the text form prints it.
1992    const TEXT_HEAD_V2: &[&str] = &[
1993        "~",
1994        "> E 0",
1995        "Config version: 1.27",
1996        "Main deploy: 250 meters",
1997        "Apogee delay: 0 seconds",
1998        "Accel cal +1g: 1000 -1g: 1040",
1999        "ms5607 reserved: 0",
2000        "ms5607 sens: 46372",
2001        "ms5607 off: 43981",
2002        "ms5607 tcs: 29059",
2003        "ms5607 tco: 27842",
2004        "ms5607 tref: 31553",
2005        "ms5607 tempsens: 28165",
2006        "manufacturer     altusmetrum.org",
2007        "product          TeleMetrum-v2.0",
2008        "serial-number    1234",
2009        "log-format       7",
2010        "altitude-32      1",
2011        "software-version 1.9.22",
2012        "done",
2013    ];
2014
2015    /// A record of `size` bytes: its type, its checksum, its tick and its fields, padded with
2016    /// zeros, the checksum making 0x5A and every byte sum to 0 modulo 256.
2017    fn record(size: usize, kind: u8, tick: u16, fields: &[u8]) -> Vec<u8> {
2018        let mut bytes = vec![kind, 0];
2019        bytes.extend(tick.to_le_bytes());
2020        bytes.extend(fields);
2021        bytes.resize(size, 0);
2022        let sum = bytes
2023            .iter()
2024            .fold(CHECKSUM_BASE, |sum, byte| sum.wrapping_add(*byte));
2025        bytes[1] = 0u8.wrapping_sub(sum);
2026        bytes
2027    }
2028
2029    /// A TeleMetrum v2's flight record: flight, ground reading, ground pressure.
2030    fn f7(tick: u16, flight: u16, ground_accel: i16, ground_pa: u32) -> Vec<u8> {
2031        let mut fields = flight.to_le_bytes().to_vec();
2032        fields.extend(ground_accel.to_le_bytes());
2033        fields.extend(ground_pa.to_le_bytes());
2034        record(16, b'F', tick, &fields)
2035    }
2036
2037    /// A TeleMetrum v2's sensor record: D1, D2 and the accelerometer's count.
2038    fn a7(tick: u16, d1: u32, d2: u32, accel: i16) -> Vec<u8> {
2039        let mut fields = d1.to_le_bytes().to_vec();
2040        fields.extend(d2.to_le_bytes());
2041        fields.extend(accel.to_le_bytes());
2042        record(16, b'A', tick, &fields)
2043    }
2044
2045    /// A state record of `size` bytes.
2046    fn s(size: usize, tick: u16, state: u16) -> Vec<u8> {
2047        record(size, b'S', tick, &state.to_le_bytes())
2048    }
2049
2050    /// The JSON form: the head, then the records' bytes, 32 a line.
2051    fn json(head: &str, records: &[Vec<u8>]) -> String {
2052        let bytes = records.concat();
2053        let mut out = format!("{head}\n");
2054        for line in bytes.chunks(32) {
2055            let hex: Vec<String> = line.iter().map(|b| format!("{b:02x}")).collect();
2056            out.push_str(&hex.join(" "));
2057            out.push('\n');
2058        }
2059        out
2060    }
2061
2062    /// The text form: the head's lines, then a record a line, its checksum left out; 8-byte
2063    /// records print their fields as two 16-bit words.
2064    fn text(head: &[&str], records: &[Vec<u8>]) -> String {
2065        let mut out: String = head.iter().map(|line| format!("{line}\n")).collect();
2066        for bytes in records {
2067            let tick = u16::from_le_bytes([bytes[2], bytes[3]]);
2068            let fields: Vec<String> = if bytes.len() == 8 {
2069                vec![
2070                    format!("{:4x}", u16::from_le_bytes([bytes[4], bytes[5]])),
2071                    format!("{:4x}", u16::from_le_bytes([bytes[6], bytes[7]])),
2072                ]
2073            } else {
2074                bytes[4..].iter().map(|b| format!("{b:02x}")).collect()
2075            };
2076            out.push_str(&format!(
2077                "{} {tick:x} {}\n",
2078                char::from(bytes[0]),
2079                fields.join(" ")
2080            ));
2081        }
2082        out
2083    }
2084
2085    /// The pressure, Pa, at a pressure altitude, m, in the standard atmosphere's troposphere: the
2086    /// altimeter formula `H = 44,330.8 m [1 − (P / 101,325 Pa)^0.190263]`
2087    /// ([`hpr_atmos::ussa76::Ussa76::pressure_altitude_m`]'s), turned round.
2088    fn pressure_at(altitude_m: f64) -> f64 {
2089        101_325.0 * (1.0 - altitude_m / 44_330.8).powf(1.0 / 0.190_263)
2090    }
2091
2092    /// The pressure altitude, m, of a pressure, Pa, by the same formula.
2093    fn altitude_of(pressure_pa: f64) -> f64 {
2094        44_330.8 * (1.0 - (pressure_pa / 101_325.0).powf(0.190_263))
2095    }
2096
2097    /// The height, m, the invented flights reach `t` s after boost at 5 g: `x = a t² / 2`.
2098    fn climbed_m(t: f64) -> f64 {
2099        0.5 * 5.0 * STANDARD_GRAVITY * t * t
2100    }
2101
2102    /// The MS5607's D1 that reads `pa` with the data sheet's example constants and D2 (20.00 °C,
2103    /// first order only, OFF 5,764,707,214 and SENS 3,039,050,829, p. 8): the least D1 with
2104    /// `((D1 SENS) >> 21 − OFF) >> 15 = pa`.
2105    fn d1_for(pa: f64) -> u32 {
2106        let (off, sens) = (5_764_707_214_i128, 3_039_050_829_i128);
2107        let wanted = pa.round() as i128;
2108        let d1 = ((((wanted << 15) + off) << 21) + sens - 1) / sens;
2109        let d1 = u32::try_from(d1).unwrap();
2110        assert_eq!(ms5607(d1, EXAMPLE_D2, &EXAMPLE_PROM).0, wanted);
2111        d1
2112    }
2113
2114    /// A TeleMetrum v2's climb from boost at tick `zero` to 1.1 s after it, a sample every
2115    /// 0.1 s: 5 g, 100 counts below the ground reading of 1,000 at 20 counts a g, and the
2116    /// pressure the standard atmosphere gives the height that reaches, from 110,002 Pa on the pad.
2117    fn climb_v2(zero: u16) -> Vec<Vec<u8>> {
2118        let pad_m = altitude_of(110_002.0);
2119        (1..=11u16)
2120            .map(|k| {
2121                let pa = pressure_at(pad_m + climbed_m(f64::from(k) / 10.0));
2122                a7(zero.wrapping_add(10 * k), d1_for(pa), EXAMPLE_D2, 900)
2123            })
2124            .collect()
2125    }
2126
2127    /// An invented flight: the pad's samples written after the flight record, a state record
2128    /// ahead of the samples it follows, the first hundredths of a climb, then the climb a sample
2129    /// every 0.1 s to 1.1 s after boost, for the climb check.
2130    fn flight_v2() -> Vec<Vec<u8>> {
2131        let mut records = vec![
2132            f7(200, 3, 1000, 110_002),
2133            a7(198, EXAMPLE_D1, EXAMPLE_D2, 1000),
2134            a7(199, EXAMPLE_D1, EXAMPLE_D2, 1001),
2135            s(16, 201, 3),
2136            a7(200, EXAMPLE_D1, EXAMPLE_D2, 960),
2137            a7(201, EXAMPLE_D1 - 1000, EXAMPLE_D2, 900),
2138            a7(202, EXAMPLE_D1 - 2000, EXAMPLE_D2, 1040),
2139        ];
2140        records.extend(climb_v2(200));
2141        records
2142    }
2143
2144    /// The records in [`flight_v2`] before its climb every 0.1 s.
2145    const HEAD_RECORDS: usize = 7;
2146
2147    /// A TeleMetrum v1's sample: the accelerometer's count, then the pressure's.
2148    fn a1(tick: u16, accel: i16, pressure: i16) -> Vec<u8> {
2149        let mut fields = accel.to_le_bytes().to_vec();
2150        fields.extend(pressure.to_le_bytes());
2151        record(8, b'A', tick, &fields)
2152    }
2153
2154    /// The MP3H6115A's count for a pressure, Pa: the transfer function turned round.
2155    fn mp3h6115a_count(pa: f64) -> i16 {
2156        ((pa / 1000.0 * 0.009 - 0.095) * CC1111_FULL_SCALE).round() as i16
2157    }
2158
2159    /// A TeleMetrum v1's configuration in the JSON form, its calibration 250 counts a g.
2160    const HEAD_V1: &str = r#"{"log_format": 1, "product": "TeleMetrum-v1.2", "serial": 77,
2161        "accel_cal_plus": 16000, "accel_cal_minus": 16500}"#;
2162
2163    /// A TeleMetrum v1's flight, 8-byte records: the flight record at tick 100 with a ground
2164    /// reading of 16,000, three samples at `pad_count`, two at rest and one at boost, then 5 g, 1,250 counts below it at
2165    /// 250 counts a g, a sample every 0.1 s to 1.1 s after boost, the pressure the standard
2166    /// atmosphere gives the height reached.
2167    fn flight_v1(pad_count: i16) -> Vec<Vec<u8>> {
2168        let pad_m = altitude_of(mp3h6115a_pa(pad_count));
2169        let mut records = vec![
2170            record(8, b'F', 100, &[0x80, 0x3e, 3, 0]),
2171            a1(98, 16_000, pad_count),
2172            a1(99, 16_000, pad_count),
2173            a1(100, 14_750, pad_count),
2174        ];
2175        for k in 1..=11u16 {
2176            let pa = pressure_at(pad_m + climbed_m(f64::from(k) / 10.0));
2177            records.push(a1(100 + 10 * k, 14_750, mp3h6115a_count(pa)));
2178        }
2179        records
2180    }
2181
2182    fn channel<'a>(log: &'a FlightLog, column: &str) -> Option<&'a Channel> {
2183        log.channels.iter().find(|c| c.column == column)
2184    }
2185
2186    fn values(log: &FlightLog, column: &str) -> Vec<f64> {
2187        channel(log, column)
2188            .unwrap_or_else(|| panic!("no {column}: {:#?}", log.notes))
2189            .values
2190            .clone()
2191    }
2192
2193    fn has_note(log: &FlightLog, start: &str) -> bool {
2194        log.notes.iter().any(|note| note.starts_with(start))
2195    }
2196
2197    /// The module's documented example record is what the helpers write, checksum included.
2198    #[test]
2199    fn the_documented_record_is_a_flight_record() {
2200        let written: Vec<String> = f7(0x164, 3, 25, 98_000)
2201            .iter()
2202            .map(|b| format!("{b:02x}"))
2203            .collect();
2204        assert_eq!(
2205            written.join(" "),
2206            "46 90 64 01 03 00 19 00 d0 7e 01 00 00 00 00 00"
2207        );
2208        let line = text(&[], &[f7(0x164, 3, 25, 98_000)]);
2209        assert_eq!(line, "F 164 03 00 19 00 d0 7e 01 00 00 00 00 00\n");
2210    }
2211
2212    #[test]
2213    fn the_layout_is_recognized_in_both_forms() {
2214        assert!(recognizes(&json(HEAD_V2, &flight_v2())));
2215        assert!(recognizes(&text(TEXT_HEAD_V2, &flight_v2())));
2216        assert!(recognizes(
2217            "  {\"log_format\": 7, \"product\": \"EasyMini-v2.0\"}"
2218        ));
2219        assert!(!recognizes("{\"log_format\": 7}"), "no product");
2220        assert!(
2221            !recognizes("{\"product\": \"EasyMini-v2.0\"}"),
2222            "no log format"
2223        );
2224        assert!(!recognizes("{\"log_format\": 7, \"product\": 3}"));
2225        assert!(!recognizes(
2226            "Config version: 1.27\nproduct TeleMetrum-v2.0\n"
2227        ));
2228        assert!(!recognizes("manufacturer     altusmetrum.org\n"));
2229        assert!(!recognizes("TELEM 22ab\n"));
2230        assert!(!recognizes("#version,serial,flight,call,time\n"));
2231    }
2232
2233    /// The data sheet's worked example, first order only at exactly 20.00 °C: dT 68, OFF
2234    /// 5,764,707,214, SENS 3,039,050,829, so P 110,002 (1,100.02 mbar) and TEMP 2,000 (p. 8).
2235    #[test]
2236    fn the_data_sheets_example_reads_to_its_values() {
2237        assert_eq!(
2238            ms5607(EXAMPLE_D1, EXAMPLE_D2, &EXAMPLE_PROM),
2239            (110_002, 2_000)
2240        );
2241    }
2242
2243    /// 300,000 counts of D2 below the example: TEMP 9.92 °C by the first order, so the second
2244    /// applies (p. 9): T2 = dT² / 2³¹ = 41, OFF2 = 61 × 1,008² / 2⁴ = 3,873,744, SENS2 = 2 ×
2245    /// 1,008² = 2,032,128: 9.51 °C and 107,504 Pa, where the first order alone gives 107,577.
2246    /// Below −15 °C the third terms come in too.
2247    #[test]
2248    fn below_20_c_the_second_order_applies() {
2249        let cold = ms5607(EXAMPLE_D1, EXAMPLE_D2 - 300_000, &EXAMPLE_PROM);
2250        assert_eq!(cold, (107_504, 951));
2251        let very_cold = ms5607(EXAMPLE_D1, EXAMPLE_D2 - 1_500_000, &EXAMPLE_PROM);
2252        assert_eq!(very_cold, (95_359, -4_084));
2253    }
2254
2255    /// Every division by 2ⁿ is a floor: in the cold case above, dT is −299,932, and
2256    /// `C4 × dT / 2⁶` and the others truncated toward zero instead give 107,505 Pa and 9.52 °C.
2257    /// The truncating version here is the mutation the test must catch.
2258    #[test]
2259    fn every_division_by_a_power_of_two_is_a_floor() {
2260        fn truncating(d1: u32, d2: u32, prom: &Prom) -> (i128, i128) {
2261            let [c1, c2, c3, c4, c5, c6] = prom.map(i128::from);
2262            let (d1, d2) = (i128::from(d1), i128::from(d2));
2263            let dt = d2 - c5 * 256;
2264            let mut temp = 2000 + dt * c6 / (1 << 23);
2265            let mut off = c2 * (1 << 17) + c4 * dt / (1 << 6);
2266            let mut sens = c1 * (1 << 16) + c3 * dt / (1 << 7);
2267            if temp < 2000 {
2268                off -= 61 * (temp - 2000).pow(2) / (1 << 4);
2269                sens -= 2 * (temp - 2000).pow(2);
2270                temp -= dt * dt / (1 << 31);
2271            }
2272            ((d1 * sens / (1 << 21) - off) / (1 << 15), temp)
2273        }
2274        let d2 = EXAMPLE_D2 - 300_000;
2275        assert_eq!(truncating(EXAMPLE_D1, d2, &EXAMPLE_PROM), (107_505, 952));
2276        assert_ne!(
2277            ms5607(EXAMPLE_D1, d2, &EXAMPLE_PROM),
2278            truncating(EXAMPLE_D1, d2, &EXAMPLE_PROM)
2279        );
2280        // A step just below the example: first order only at 19.90 °C would be 1,991 truncated.
2281        assert_eq!(
2282            ms5607(EXAMPLE_D1, EXAMPLE_D2 - 3_000, &EXAMPLE_PROM),
2283            (109_978, 1_990)
2284        );
2285    }
2286
2287    /// `P = (count / 32,752 + 0.095) / 0.009` kPa: the CC1111's full scale reads 121.67 kPa, a
2288    /// count of 0 the sensor's 10.56 kPa offset.
2289    #[test]
2290    fn the_mp3h6115a_reads_by_its_transfer_function() {
2291        assert!((mp3h6115a_pa(32_752) - 1.095 / 0.009 * 1000.0).abs() < 1e-9);
2292        assert!((mp3h6115a_pa(0) - 0.095 / 0.009 * 1000.0).abs() < 1e-9);
2293        assert!((mp3h6115a_pa(24_000) - 91_975.5).abs() < 0.1);
2294        assert_eq!(CC1111_FULL_SCALE, f64::from(2047 * 16));
2295    }
2296
2297    /// The flight reads: tick order, time from the flight record, the units, the figures.
2298    #[test]
2299    fn a_flight_reads_in_tick_order_from_the_flight_record() {
2300        let log = read(&json(HEAD_V2, &flight_v2())).unwrap();
2301        assert_eq!(log.format, LogFormat::AltosEeprom);
2302        assert_eq!(log.logger, "AltOS TeleMetrum-v2.0");
2303        assert_eq!(log.serial_number.as_deref(), Some("1234"));
2304        assert_eq!(log.firmware.as_deref(), Some("1.9.22"));
2305        // The flight record's number, not the configuration's `stored_flight`.
2306        assert_eq!(log.flight_number, Some(3));
2307        assert!(log.time_s.is_empty() && log.altitude_m.is_empty());
2308        let pressure = channel(&log, "pressure").unwrap();
2309        assert_eq!(pressure.quantity, Quantity::Pressure);
2310        assert_eq!(pressure.time_s[..5], [-0.02, -0.01, 0.0, 0.01, 0.02]);
2311        assert_eq!(pressure.time_s[5..7], [0.1, 0.2]);
2312        assert_eq!(pressure.values[..3], [110_002.0; 3]);
2313        assert!(pressure.values[3] < pressure.values[2]);
2314        assert!((values(&log, "temperature")[0] - 293.15).abs() < 1e-9);
2315        // 20 counts a g, 0 at the ground reading of 1,000.
2316        let g = STANDARD_GRAVITY;
2317        let acceleration = values(&log, "acceleration");
2318        for (got, want) in acceleration
2319            .iter()
2320            .zip([0.0, -0.05 * g, 2.0 * g, 5.0 * g, -2.0 * g])
2321        {
2322            assert!((got - want).abs() < 1e-12, "{acceleration:?}");
2323        }
2324        assert_eq!(log.events.len(), 1);
2325        assert_eq!(
2326            (log.events[0].time_s, log.events[0].name.as_str()),
2327            (0.01, "boost")
2328        );
2329        let figure = |name: &str| log.stated.figures.iter().find(|f| f.name == name).unwrap();
2330        assert_eq!(figure("ground_pressure").values, [110_002.0]);
2331        assert_eq!(figure("ground_pressure").quantity, Some(Quantity::Pressure));
2332        assert_eq!(figure("accel_cal_minus").values, [1040.0]);
2333        assert_eq!(figure("main_deploy").quantity, Some(Quantity::Unrecognized));
2334        assert!(has_note(
2335            &log,
2336            "18 records of 16 bytes, log format 7, from the JSON form"
2337        ));
2338        assert!(has_note(
2339            &log,
2340            "the clock is the board's tick, 10 ms, from the flight record's at tick 200"
2341        ));
2342        let figure = |name: &str| log.stated.figures.iter().find(|f| f.name == name);
2343        assert!(figure("pad_orientation").is_none(), "the head states none");
2344    }
2345
2346    /// The text form of the same records reads to the same channels and events.
2347    #[test]
2348    fn the_text_and_json_forms_of_a_flight_read_alike() {
2349        let from_json = read(&json(HEAD_V2, &flight_v2())).unwrap();
2350        let from_text = read(&text(TEXT_HEAD_V2, &flight_v2())).unwrap();
2351        assert_eq!(from_json.channels, from_text.channels);
2352        assert_eq!(from_json.events, from_text.events);
2353        assert_eq!(from_json.serial_number, from_text.serial_number);
2354        assert_eq!(from_json.flight_number, from_text.flight_number);
2355        assert_eq!(from_json.firmware, from_text.firmware);
2356        assert!(has_note(
2357            &from_text,
2358            "18 records of 16 bytes, log format 7, from the text form"
2359        ));
2360        // The text form names its settings' units, so they are in SI.
2361        let main = from_text
2362            .stated
2363            .figures
2364            .iter()
2365            .find(|f| f.name == "main_deploy")
2366            .unwrap();
2367        assert_eq!(main.quantity, Some(Quantity::AltitudeAboveGround));
2368        assert_eq!(
2369            (main.written.as_str(), main.values.as_slice()),
2370            ("250 meters", &[250.0][..])
2371        );
2372    }
2373
2374    /// One byte changed, the checksum not: refused at the record's byte.
2375    #[test]
2376    fn a_record_failing_its_checksum_refuses_the_file() {
2377        let mut records = flight_v2();
2378        records[2][9] ^= 0x01;
2379        match read(&json(HEAD_V2, &records)) {
2380            Err(LogError::Binary {
2381                offset, message, ..
2382            }) => {
2383                assert_eq!(offset, 32);
2384                assert!(
2385                    message.starts_with("record 3 fails its checksum"),
2386                    "{message}"
2387                );
2388            }
2389            other => panic!("{other:?}"),
2390        }
2391    }
2392
2393    /// A log format the samples don't show is refused by its number, in both forms; one the
2394    /// configuration doesn't state is format 1 only for a TeleMetrum v1.
2395    #[test]
2396    fn a_log_format_no_sample_shows_is_refused_by_number() {
2397        for format in [2, 5, 8, 13, 17, 21, 23] {
2398            let head = HEAD_V2.replace("\"log_format\": 7", &format!("\"log_format\": {format}"));
2399            match read(&json(&head, &flight_v2())) {
2400                Err(LogError::Syntax { line, message, .. }) => {
2401                    assert_eq!(line, 1);
2402                    assert!(
2403                        message.starts_with(&format!("log format {format}, which no sample")),
2404                        "{message}"
2405                    );
2406                }
2407                other => panic!("{format}: {other:?}"),
2408            }
2409        }
2410        let lines: Vec<&str> = TEXT_HEAD_V2
2411            .iter()
2412            .map(|line| {
2413                if line.starts_with("log-format") {
2414                    "log-format       9"
2415                } else {
2416                    line
2417                }
2418            })
2419            .collect();
2420        match read(&text(&lines, &flight_v2())) {
2421            Err(LogError::Syntax { line, message, .. }) => {
2422                assert_eq!(line, TEXT_HEAD_V2.len() + 1);
2423                assert!(
2424                    message.starts_with("log format 9, which no sample"),
2425                    "{message}"
2426                );
2427            }
2428            other => panic!("{other:?}"),
2429        }
2430        // No log format: a TeleMetrum v1 is format 1, an EasyMini refused.
2431        let unstated = HEAD_V2.replace("\"log_format\": 7,", "\"log_format\": 2147483647,");
2432        match read(&json(&unstated, &flight_v2())) {
2433            Err(LogError::Syntax { message, .. }) => {
2434                assert!(
2435                    message.contains("states no log format, and its product, \"TeleMetrum-v2.0\""),
2436                    "{message}"
2437                );
2438            }
2439            other => panic!("{other:?}"),
2440        }
2441        let head_v1 = HEAD_V1
2442            .replace("\"log_format\": 1", "\"log_format\": 2147483647")
2443            .replace("TeleMetrum-v1.2", "TeleMetrum-v1.0");
2444        let log = read(&json(&head_v1, &flight_v1(24_000))).unwrap();
2445        assert!(has_note(
2446            &log,
2447            "the configuration states no log format, as firmware before 1.0"
2448        ));
2449        assert!(has_note(&log, "15 records of 8 bytes, log format 1"));
2450    }
2451
2452    /// Erased memory after the last record is counted; a record after it refuses the file.
2453    #[test]
2454    fn erased_memory_ends_the_records() {
2455        let mut records = flight_v2();
2456        records.push(vec![0xff; 16]);
2457        records.push(vec![0xff; 16]);
2458        let log = read(&json(HEAD_V2, &records)).unwrap();
2459        assert!(has_note(
2460            &log,
2461            "2 erased records (every byte 0xFF) after the last, skipped"
2462        ));
2463        records.push(s(16, 203, 4));
2464        match read(&json(HEAD_V2, &records)) {
2465            Err(LogError::Binary {
2466                offset, message, ..
2467            }) => {
2468                assert_eq!(offset, 20 * 16);
2469                assert!(
2470                    message.starts_with("a record after the erased memory from byte 288"),
2471                    "{message}"
2472                );
2473            }
2474            other => panic!("{other:?}"),
2475        }
2476        // A token that isn't a byte refuses the file, naming its line; so does a sign, which
2477        // `from_str_radix` alone would take.
2478        for token in ["4g", "+6"] {
2479            let damaged = json(HEAD_V2, &flight_v2()).replacen("\n46 ", &format!("\n{token} "), 1);
2480            match read(&damaged) {
2481                Err(LogError::Syntax { message, .. }) => assert!(
2482                    message.starts_with(&format!("\"{token}\" where the memory's bytes")),
2483                    "{message}"
2484                ),
2485                other => panic!("{token}: {other:?}"),
2486            }
2487        }
2488        // A short chunk of erased bytes at the end is a record cut short, not erased memory.
2489        let mut short = json(HEAD_V2, &flight_v2());
2490        short.push_str("ff ff ff ff\n");
2491        match read(&short) {
2492            Err(LogError::Binary {
2493                offset, message, ..
2494            }) => {
2495                assert_eq!(offset, 18 * 16);
2496                assert!(
2497                    message.starts_with("the memory ends in 4 bytes, part of a 16-byte record"),
2498                    "{message}"
2499                );
2500            }
2501            other => panic!("{other:?}"),
2502        }
2503    }
2504
2505    /// A file with no records, in either form, holds no data: no memory, only erased memory, or
2506    /// only a last line cut short.
2507    #[test]
2508    fn a_file_with_no_records_holds_no_data() {
2509        let empty = json(HEAD_V2, &[]);
2510        let erased = json(HEAD_V2, &[vec![0xff; 16], vec![0xff; 16]]);
2511        let cut = text(TEXT_HEAD_V2, &flight_v2()[..1]);
2512        for file in [empty, erased, cut.trim_end().to_owned()] {
2513            assert!(
2514                matches!(read(&file), Err(LogError::NoData { .. })),
2515                "{:?}",
2516                read(&file)
2517            );
2518        }
2519    }
2520
2521    /// The last line of a text file that ends without a line break is left out, however well it
2522    /// reads; a malformed line anywhere else refuses the file.
2523    #[test]
2524    fn a_text_files_last_line_cut_short_is_left_out() {
2525        let whole = text(TEXT_HEAD_V2, &flight_v2());
2526        let cut = &whole[..whole.len() - 7];
2527        let log = read(cut).unwrap();
2528        assert!(has_note(
2529            &log,
2530            "the file ends without a line break, so its last line may be cut short"
2531        ));
2532        assert_eq!(values(&log, "pressure").len(), 15);
2533        // Cut at the line's end, the last record still reads as one, and is still left out.
2534        let log = read(whole.trim_end_matches('\n')).unwrap();
2535        assert_eq!(values(&log, "pressure").len(), 15);
2536        // A short line before the last refuses the file.
2537        let mut lines: Vec<&str> = whole.lines().collect();
2538        let short = "A c8 64 a7 62 00";
2539        lines.insert(TEXT_HEAD_V2.len() + 2, short);
2540        let damaged = lines.join("\n") + "\n";
2541        match read(&damaged) {
2542            Err(LogError::Syntax { line, message, .. }) => {
2543                assert_eq!(line, TEXT_HEAD_V2.len() + 3);
2544                assert!(
2545                    message.contains("isn't a record of log format 7"),
2546                    "{message}"
2547                );
2548            }
2549            other => panic!("{other:?}"),
2550        }
2551    }
2552
2553    /// The 16-bit tick turns over: each record's tick goes on the turn nearest the latest so far,
2554    /// so file order across the turn differs from tick order, and the records are sorted.
2555    #[test]
2556    fn the_ticks_turns_are_unwound_and_the_records_sorted() {
2557        let mut records = vec![
2558            // The flight record just before the turn, the pad's samples written after it.
2559            f7(65_534, 3, 1000, 110_002),
2560            a7(65_533, EXAMPLE_D1, EXAMPLE_D2, 1000),
2561            a7(65_535, EXAMPLE_D1, EXAMPLE_D2, 1000),
2562            // Across the turn: a state record written ahead of a sample with an earlier tick.
2563            s(16, 1, 3),
2564            a7(0, EXAMPLE_D1, EXAMPLE_D2, 990),
2565            a7(1, EXAMPLE_D1, EXAMPLE_D2, 980),
2566            // A GPS record carrying its fix's earlier tick, from before the turn.
2567            record(16, b'G', 65_500, &[12, 0, 1, 0x10 | 6, 26, 10, 14, 40]),
2568            a7(2, EXAMPLE_D1, EXAMPLE_D2, 970),
2569        ];
2570        records.extend(climb_v2(65_534));
2571        let log = read(&json(HEAD_V2, &records)).unwrap();
2572        let pressure = channel(&log, "pressure").unwrap();
2573        assert_eq!(pressure.time_s[..6], [-0.01, 0.01, 0.02, 0.03, 0.04, 0.1]);
2574        let acceleration = values(&log, "acceleration");
2575        assert_eq!(acceleration[..2], [0.0, 0.0]);
2576        assert!((acceleration[2] - 0.5 * STANDARD_GRAVITY).abs() < 1e-12);
2577        assert_eq!(log.events[0].time_s, 0.03);
2578        assert_eq!(channel(&log, "hour").unwrap().time_s, [-0.34]);
2579        assert!(has_note(
2580            &log,
2581            "the clock is the board's tick, 10 ms, from the flight record's at tick 65534"
2582        ));
2583        assert!(
2584            log.notes
2585                .iter()
2586                .any(|n| n.ends_with("2 records are before boost, at negative times"))
2587        );
2588    }
2589
2590    /// The records are put in tick order, the file's order kept among records of one tick: a
2591    /// sample written ahead of one with an earlier tick comes after it, and two samples at one
2592    /// tick keep the file's order. Without the sort, or with an unstable one that swaps them, the
2593    /// times or the accelerations come out in another order.
2594    #[test]
2595    fn records_are_sorted_by_tick_and_stable_among_equal_ticks() {
2596        let mut records = flight_v2();
2597        let late = [
2598            a7(205, EXAMPLE_D1 - 3000, EXAMPLE_D2, 950),
2599            a7(203, EXAMPLE_D1 - 2500, EXAMPLE_D2, 940),
2600            a7(204, EXAMPLE_D1 - 2600, EXAMPLE_D2, 930),
2601            a7(204, EXAMPLE_D1 - 2700, EXAMPLE_D2, 920),
2602        ];
2603        records.splice(HEAD_RECORDS..HEAD_RECORDS, late);
2604        let log = read(&json(HEAD_V2, &records)).unwrap();
2605        let pressure = channel(&log, "pressure").unwrap();
2606        assert_eq!(pressure.time_s[4..10], [0.02, 0.03, 0.04, 0.04, 0.05, 0.1]);
2607        // 20 counts a g below 1,000: 940 is 3 g, 930 3.5 g, 920 4 g, 950 2.5 g.
2608        let g = STANDARD_GRAVITY;
2609        let acceleration = values(&log, "acceleration");
2610        for (got, want) in acceleration[5..9].iter().zip([3.0, 3.5, 4.0, 2.5]) {
2611            assert!((got - want * g).abs() < 1e-12, "{acceleration:?}");
2612        }
2613    }
2614
2615    /// A record more than 10 s from the latest tick ends the flight: it and every record after
2616    /// it are left out. Exactly 10 s is kept.
2617    #[test]
2618    fn a_silence_of_more_than_10_s_ends_the_flight() {
2619        let mut records = flight_v2();
2620        records.push(s(16, 1_202, 8));
2621        let log = read(&json(HEAD_V2, &records)).unwrap();
2622        assert_eq!(log.events.last().map(|e| e.time_s), Some(10.02));
2623        records.push(s(16, 2_203, 2));
2624        records.push(a7(2_204, EXAMPLE_D1, EXAMPLE_D2, 1000));
2625        let log = read(&json(HEAD_V2, &records)).unwrap();
2626        assert_eq!(values(&log, "pressure").len(), 16);
2627        assert!(has_note(
2628            &log,
2629            "2 records from the first more than 10 s from the latest tick on are left out"
2630        ));
2631        // A record more than 10 s behind ends it too.
2632        let mut records = flight_v2();
2633        records.push(a7(60_000, EXAMPLE_D1, EXAMPLE_D2, 1000));
2634        let log = read(&json(HEAD_V2, &records)).unwrap();
2635        assert!(has_note(&log, "1 records from the first more than 10 s"));
2636    }
2637
2638    /// A record repeated exactly is dropped and counted; the same bytes at another tick are not
2639    /// a repeat.
2640    #[test]
2641    fn records_repeated_exactly_are_dropped() {
2642        let mut records = flight_v2();
2643        records.insert(5, records[4].clone());
2644        records.push(s(16, 203, 3));
2645        let log = read(&text(TEXT_HEAD_V2, &records)).unwrap();
2646        assert!(has_note(&log, "1 records repeated exactly"));
2647        assert_eq!(values(&log, "pressure").len(), 16);
2648        assert_eq!(values(&log, "state"), [3.0, 3.0]);
2649    }
2650
2651    #[test]
2652    fn a_file_needs_exactly_one_flight_record() {
2653        let mut records = flight_v2();
2654        records.push(f7(210, 4, 1000, 110_002));
2655        match read(&json(HEAD_V2, &records)) {
2656            Err(LogError::Binary {
2657                offset, message, ..
2658            }) => {
2659                assert_eq!(offset, 18 * 16);
2660                assert!(
2661                    message.starts_with("a second flight record, after the one at byte 0"),
2662                    "{message}"
2663                );
2664            }
2665            other => panic!("{other:?}"),
2666        }
2667        let records: Vec<Vec<u8>> = flight_v2().into_iter().skip(1).collect();
2668        match read(&json(HEAD_V2, &records)) {
2669            Err(LogError::Binary { message, .. }) => {
2670                assert!(message.starts_with("no flight record"))
2671            }
2672            other => panic!("{other:?}"),
2673        }
2674    }
2675
2676    /// The pad's pressure must be a launch site's, 10 to 120 kPa, and an MS5607 board's within
2677    /// 1% of its flight record's ground pressure; otherwise the bytes are misread.
2678    #[test]
2679    fn the_pads_pressure_is_held_to_a_launch_site_and_the_flight_record() {
2680        let v1 = |count: i16| read(&json(HEAD_V1, &flight_v1(count)));
2681        // −163 counts is 10.002 kPa, −164 is 9.999; 32,260 is 119.998, 32,261 is 120.001.
2682        assert!(v1(-163).is_ok() && v1(32_260).is_ok());
2683        for count in [-164, 32_261] {
2684            match v1(count) {
2685                Err(LogError::Binary {
2686                    offset, message, ..
2687                }) => {
2688                    assert_eq!(offset, 0);
2689                    assert!(
2690                        message.contains("outside every launch site's 10 to 120 kPa"),
2691                        "{message}"
2692                    );
2693                }
2694                other => panic!("{count}: {other:?}"),
2695            }
2696        }
2697        // 110,002 Pa on the pad: a ground pressure 0.99% off is kept, 1.01% or more refused.
2698        let with_ground = |ground: u32| {
2699            let mut records = flight_v2();
2700            records[0] = f7(200, 3, 1000, ground);
2701            read(&json(HEAD_V2, &records))
2702        };
2703        assert!(with_ground(111_100).is_ok() && with_ground(108_920).is_ok());
2704        for ground in [111_125, 108_890] {
2705            match with_ground(ground) {
2706                Err(LogError::Binary { message, .. }) => {
2707                    assert!(
2708                        message.contains("from the flight record's ground pressure"),
2709                        "{message}"
2710                    );
2711                }
2712                other => panic!("{ground}: {other:?}"),
2713            }
2714        }
2715    }
2716
2717    /// The acceleration comes from the file's calibration and the flight record's ground
2718    /// reading. A board mounted antenna down keeps its calibration flipped, `plus' = K − minus`
2719    /// and `minus' = K − plus`, with the same span, so either pair reads alike: K = 0 for a
2720    /// signed sensor, 32,767 for a TeleMetrum v1's.
2721    #[test]
2722    fn acceleration_is_from_the_files_own_calibration() {
2723        let cooked = HEAD_V2
2724            .replace("\"accel_cal_minus\": 1040, \"accel_cal_plus\": 1000", "\"accel_cal_minus\": 2147483647, \"accel_cal_plus\": 2147483647, \"accel_cal_minus_cooked\": -1000, \"accel_cal_plus_cooked\": -1040");
2725        let raw = read(&json(HEAD_V2, &flight_v2())).unwrap();
2726        let flipped = read(&json(&cooked, &flight_v2())).unwrap();
2727        assert_eq!(
2728            values(&raw, "acceleration"),
2729            values(&flipped, "acceleration")
2730        );
2731
2732        let v1 = |plus: i64, minus: i64| {
2733            let head = HEAD_V1
2734                .replace("16000", &plus.to_string())
2735                .replace("16500", &minus.to_string());
2736            // Ground reading 16,000; the climb at 14,750.
2737            read(&json(&head, &flight_v1(24_000))).unwrap()
2738        };
2739        let upright = values(&v1(16_000, 16_500), "acceleration");
2740        let down = values(&v1(32_767 - 16_500, 32_767 - 16_000), "acceleration");
2741        assert_eq!(upright, down);
2742        assert_eq!(upright[0], 0.0);
2743        assert!((upright[3] - 5.0 * STANDARD_GRAVITY).abs() < 1e-12);
2744
2745        // The two counts come from one pair: a raw +1 g with no raw −1 g takes the flipped pair
2746        // whole, never the raw +1 g beside the flipped −1 g, whose span would be negative.
2747        let mixed = cooked.replace("\"accel_cal_plus\": 2147483647", "\"accel_cal_plus\": 1000");
2748        let log = read(&json(&mixed, &flight_v2())).unwrap();
2749        assert_eq!(values(&log, "acceleration"), values(&raw, "acceleration"));
2750        assert!(has_note(
2751            &log,
2752            "`acceleration` along the board's axis, m/s², from the high-g accelerometer's counts. \
2753             It is 0 at the flight record's ground reading, 1000. A g is 20 counts, \
2754             from the calibration's +1 g and −1 g, -1040 and -1000"
2755        ));
2756    }
2757
2758    /// A calibration outside a 16-bit count's range, even one whose span would overflow, keeps
2759    /// the counts as written.
2760    #[test]
2761    fn a_calibration_outside_sixteen_bits_keeps_the_counts_as_written() {
2762        for (plus, minus) in [
2763            (i64::MIN.to_string(), i64::MAX.to_string()),
2764            ("-40000".to_owned(), "1040".to_owned()),
2765            ("1000".to_owned(), "65536".to_owned()),
2766        ] {
2767            let head = HEAD_V2
2768                .replace(
2769                    "\"accel_cal_plus\": 1000",
2770                    &format!("\"accel_cal_plus\": {plus}"),
2771                )
2772                .replace(
2773                    "\"accel_cal_minus\": 1040",
2774                    &format!("\"accel_cal_minus\": {minus}"),
2775                );
2776            let log = read(&json(&head, &flight_v2())).unwrap();
2777            assert!(channel(&log, "acceleration").is_none(), "{plus} {minus}");
2778            assert!(has_note(
2779                &log,
2780                "`accel` kept as written: the calibration lies outside a 16-bit count's range"
2781            ));
2782        }
2783        // The range's ends are counts: the calibration is taken, and its span, 49,151.5 counts a
2784        // g, makes the climb's 100 counts almost no acceleration, which the climb check finds
2785        // disagreeing with the pressure, so the counts are kept as written after all.
2786        let head = HEAD_V2
2787            .replace("\"accel_cal_plus\": 1000", "\"accel_cal_plus\": -32768")
2788            .replace("\"accel_cal_minus\": 1040", "\"accel_cal_minus\": 65535");
2789        let log = read(&json(&head, &flight_v2())).unwrap();
2790        assert!(channel(&log, "acceleration").is_none());
2791        assert!(has_note(
2792            &log,
2793            "`accel` kept as written: its climb disagrees"
2794        ));
2795    }
2796
2797    /// Without a calibration, or with a span that isn't positive, the counts are kept as written.
2798    #[test]
2799    fn an_unset_calibration_keeps_the_counts_as_written() {
2800        let unset = HEAD_V2.replace("\"accel_cal_plus\": 1000", "\"accel_cal_plus\": 2147483647");
2801        let log = read(&json(&unset, &flight_v2())).unwrap();
2802        assert!(channel(&log, "acceleration").is_none());
2803        let accel = channel(&log, "accel").unwrap();
2804        assert_eq!(accel.quantity, Quantity::Unrecognized);
2805        assert_eq!(accel.values[..5], [1000.0, 1001.0, 960.0, 900.0, 1040.0]);
2806        assert!(has_note(
2807            &log,
2808            "`accel` kept as written: the calibration isn't set"
2809        ));
2810        // No climb to hold the pressure to: its checks are the pad's, and a file too short for
2811        // the climb check reads.
2812        assert!(has_note(
2813            &log,
2814            "`pressure`'s second check is the pad's alone"
2815        ));
2816        let short = &flight_v2()[..HEAD_RECORDS];
2817        assert!(read(&json(&unset, short)).is_ok());
2818        let reversed = HEAD_V2.replace("\"accel_cal_minus\": 1040", "\"accel_cal_minus\": 1000");
2819        let log = read(&json(&reversed, &flight_v2())).unwrap();
2820        assert!(has_note(
2821            &log,
2822            "`accel` kept as written: the calibration's span isn't positive"
2823        ));
2824    }
2825
2826    /// The climb check's measurement: a sample every tick at a steady 5 g from boost, at rest
2827    /// before it, and the pressures, in whole pascals, the standard atmosphere gives the height
2828    /// reached, 24.52 m at 1 s. The trapezoid spreads the step to 5 g at boost over the tick
2829    /// before it, which adds a quarter of a meter by 1 s; the ratio is 1 within 2%.
2830    #[test]
2831    fn the_climb_check_integrates_from_rest_and_reads_the_standard_atmosphere() {
2832        let pad_m = altitude_of(101_325.0);
2833        let a = 5.0 * STANDARD_GRAVITY;
2834        let samples: Vec<(i64, f64, f64)> = (-30..=120)
2835            .map(|tick: i64| {
2836                let t = tick as f64 / 100.0;
2837                let (x, accel) = if tick < 0 {
2838                    (0.0, 0.0)
2839                } else {
2840                    (climbed_m(t), a)
2841                };
2842                (tick, pressure_at(pad_m + x).round(), accel)
2843            })
2844            .collect();
2845        let climb = climb_over_the_window(&samples).unwrap();
2846        let step = a * 0.01 / 2.0 * 1.0;
2847        assert!(
2848            (climb.by_acceleration_m - climbed_m(1.0) - step).abs() < 0.01,
2849            "{climb:?}"
2850        );
2851        assert!(
2852            (climb.by_pressure_m - climbed_m(1.0)).abs() < 0.1,
2853            "{climb:?}"
2854        );
2855        assert!((climb.ratio - 1.0).abs() < 0.02, "{climb:?}");
2856        // No sample before boost, samples that end before 1 s, a gap over 0.1 s: unmeasured.
2857        let fault = |samples: &[(i64, f64, f64)]| climb_over_the_window(samples).unwrap_err();
2858        assert!(fault(&samples[30..]).starts_with("no sample before boost"));
2859        assert!(fault(&samples[..125]).starts_with("the samples end 0.94 s after boost"));
2860        let mut gapped = samples.clone();
2861        gapped.retain(|(tick, ..)| !(41..=51).contains(tick));
2862        assert!(
2863            fault(&gapped).starts_with("no sample for 0.12 s after the one at 0.40 s"),
2864            "{}",
2865            fault(&gapped)
2866        );
2867        // A gap of exactly 0.1 s, the slowest logging rate, is integrated across.
2868        let mut slow = samples.clone();
2869        slow.retain(|(tick, ..)| *tick < 0 || tick % 10 == 0);
2870        assert!(climb_over_the_window(&slow).is_ok());
2871    }
2872
2873    /// A consistent flight passes the climb check and says so; the pressure and the acceleration
2874    /// out of each other's band keep the acceleration's counts as written, and a TeleMetrum v1's
2875    /// pressure's too: the two words swapped, or a calibration off by 2 or 4 either way.
2876    #[test]
2877    fn the_climb_by_the_pressure_must_agree_with_the_climb_by_the_acceleration() {
2878        let log = read(&json(HEAD_V1, &flight_v1(24_000))).unwrap();
2879        let note = log
2880            .notes
2881            .iter()
2882            .find(|n| n.starts_with("`pressure` and `acceleration` held to each other"))
2883            .unwrap();
2884        let ratio: f64 = note
2885            .split("The ratio is ")
2886            .nth(1)
2887            .and_then(|rest| rest.split(',').next())
2888            .and_then(|n| n.parse().ok())
2889            .unwrap();
2890        assert!((0.95..=1.05).contains(&ratio), "{note}");
2891        let log = read(&json(HEAD_V2, &flight_v2())).unwrap();
2892        assert!(has_note(
2893            &log,
2894            "`pressure` and `acceleration` held to each other"
2895        ));
2896
2897        // The file reads, its acceleration as counts, and the note gives the two climbs.
2898        let refused = |file: &str| -> String {
2899            let log = read(file).unwrap();
2900            assert!(channel(&log, "acceleration").is_none());
2901            assert!(channel(&log, "accel").is_some());
2902            log.notes
2903                .iter()
2904                .find(|n| n.starts_with("over the first second after boost"))
2905                .cloned()
2906                .unwrap_or_else(|| panic!("{:?}", log.notes))
2907        };
2908        // The TeleMetrum v1's words swapped: the pressure from the accelerometer's counts is
2909        // still a launch site's, 64.9 kPa, but the climbs disagree.
2910        let swapped: Vec<Vec<u8>> = flight_v1(24_000)
2911            .into_iter()
2912            .map(|mut bytes| {
2913                if bytes[0] == b'A' {
2914                    let (accel, pressure) = ([bytes[4], bytes[5]], [bytes[6], bytes[7]]);
2915                    bytes[4..6].copy_from_slice(&pressure);
2916                    bytes[6..8].copy_from_slice(&accel);
2917                }
2918                bytes
2919            })
2920            .collect();
2921        let message = refused(&json(HEAD_V1, &swapped));
2922        assert!(
2923            message.contains("by the acceleration. The ratio is")
2924                && message.ends_with("which has no other check, too"),
2925            "{message}"
2926        );
2927        let log = read(&json(HEAD_V1, &swapped)).unwrap();
2928        assert!(channel(&log, "pressure").is_none() && channel(&log, "pres").is_some());
2929        // A calibration of 5 or 10 counts a g, a quarter or half the true 20, or 40 or 80, twice
2930        // or four times it.
2931        for (minus, ratio) in [(1010, 0.25), (1020, 0.5), (1080, 2.0), (1160, 4.0)] {
2932            let head = HEAD_V2.replace("1040", &minus.to_string());
2933            let message = refused(&json(&head, &flight_v2()));
2934            let read_ratio: f64 = message
2935                .split("The ratio is ")
2936                .nth(1)
2937                .and_then(|rest| rest.split(',').next())
2938                .and_then(|n| n.parse().ok())
2939                .unwrap();
2940            assert!(
2941                (read_ratio / ratio - 1.0).abs() < 0.15,
2942                "{minus}: {message}"
2943            );
2944            assert!(message.contains("outside 0.6 to 5/3"), "{message}");
2945        }
2946        // The accelerometer's counts mirrored about the ground reading, the acceleration's sign
2947        // flipped: the climb by it is downward.
2948        let flipped: Vec<Vec<u8>> = flight_v2()
2949            .into_iter()
2950            .map(|bytes| {
2951                if bytes[0] == b'A' {
2952                    let count = i16::from_le_bytes([bytes[12], bytes[13]]);
2953                    let d1 = u32::from_le_bytes([bytes[4], bytes[5], bytes[6], bytes[7]]);
2954                    a7(
2955                        u16::from_le_bytes([bytes[2], bytes[3]]),
2956                        d1,
2957                        EXAMPLE_D2,
2958                        2000 - count,
2959                    )
2960                } else {
2961                    bytes
2962                }
2963            })
2964            .collect();
2965        let message = refused(&json(HEAD_V2, &flipped));
2966        assert!(message.contains(" m by the pressure and -"), "{message}");
2967        // The pressures mirrored about the pad's too: both climbs downward, their ratio near 1,
2968        // still refused.
2969        let both: Vec<Vec<u8>> = flipped
2970            .into_iter()
2971            .map(|bytes| {
2972                if bytes[0] == b'A' {
2973                    let count = i16::from_le_bytes([bytes[12], bytes[13]]);
2974                    let d1 = u32::from_le_bytes([bytes[4], bytes[5], bytes[6], bytes[7]]);
2975                    let tick = u16::from_le_bytes([bytes[2], bytes[3]]);
2976                    a7(tick, 2 * EXAMPLE_D1 - d1, EXAMPLE_D2, count)
2977                } else {
2978                    bytes
2979                }
2980            })
2981            .collect();
2982        let message = refused(&json(HEAD_V2, &both));
2983        assert!(message.contains("m by the pressure and -"), "{message}");
2984        assert!(
2985            message.contains("by the acceleration. The ratio is 1."),
2986            "{message}"
2987        );
2988
2989        // Too short to measure: the climb's samples every 0.1 s left out.
2990        let short = &flight_v2()[..HEAD_RECORDS];
2991        let log = read(&json(HEAD_V2, short)).unwrap();
2992        assert!(channel(&log, "acceleration").is_none() && channel(&log, "accel").is_some());
2993        assert!(
2994            has_note(
2995                &log,
2996                "the climb over the first second after boost can't be measured (the samples end \
2997                 0.02 s"
2998            ),
2999            "{:?}",
3000            log.notes
3001        );
3002    }
3003
3004    /// An MS5607's pad temperature must lie in its operating range, −40 to 85 °C.
3005    #[test]
3006    fn the_pads_temperature_is_held_to_the_barometers_operating_range() {
3007        // D2 raised so the first order reads past 85 °C, the ground pressure set to what the
3008        // compensation then gives, so the pressure's checks pass and the temperature's decides.
3009        let pad = |d2: u32| {
3010            // The D1 that reads near 100 kPa at this D2, by bisection: the pressure rises with D1.
3011            let (mut low, mut high) = (0u32, 16_000_000u32);
3012            while high - low > 1 {
3013                let mid = low + (high - low) / 2;
3014                if ms5607(mid, d2, &EXAMPLE_PROM).0 < 100_000 {
3015                    low = mid;
3016                } else {
3017                    high = mid;
3018                }
3019            }
3020            let (pa, centi) = ms5607(high, d2, &EXAMPLE_PROM);
3021            let records = [
3022                f7(200, 3, 1000, u32::try_from(pa).unwrap()),
3023                a7(198, high, d2, 1000),
3024                a7(199, high, d2, 1000),
3025            ];
3026            (centi, read(&json(HEAD_V2, &records)))
3027        };
3028        let (hot, refused) = pad(EXAMPLE_D2 + 1_940_000);
3029        assert!(hot > 8_500, "{hot}");
3030        match refused {
3031            Err(LogError::Binary { message, .. }) => assert!(
3032                message.contains("outside the MS5607's operating range, −40 to 85 °C"),
3033                "{message}"
3034            ),
3035            other => panic!("{other:?}"),
3036        }
3037        // Just inside: the temperature passes, and the file reads, its climb unmeasured (the
3038        // pad's records only), so its acceleration kept as written.
3039        let (warm, read_warm) = pad(EXAMPLE_D2 + 1_930_000);
3040        assert!((8_000..=8_500).contains(&warm), "{warm}");
3041        let log = read_warm.unwrap();
3042        assert!(channel(&log, "acceleration").is_none());
3043        assert!(has_note(
3044            &log,
3045            "the climb over the first second after boost can't be measured"
3046        ));
3047        let log = read(&json(HEAD_V2, &flight_v2())).unwrap();
3048        assert!(has_note(
3049            &log,
3050            "`temperature` on the pad, 20.0 °C, within the MS5607's operating range"
3051        ));
3052    }
3053
3054    /// The configuration's pad orientation is a stated figure, in either form; text quoted in an
3055    /// error is cut to 80 characters.
3056    #[test]
3057    fn the_pad_orientation_is_stated_and_quoted_text_is_cut() {
3058        let head = HEAD_V2.replace("\"main_deploy\"", "\"pad_orientation\": 1, \"main_deploy\"");
3059        let log = read(&json(&head, &flight_v2())).unwrap();
3060        let figure = |log: &FlightLog| {
3061            log.stated
3062                .figures
3063                .iter()
3064                .find(|f| f.name == "pad_orientation")
3065                .map(|f| (f.written.clone(), f.quantity, f.values.clone()))
3066        };
3067        assert_eq!(
3068            figure(&log),
3069            Some(("1".to_owned(), Some(Quantity::Number), vec![1.0]))
3070        );
3071        let mut lines = TEXT_HEAD_V2.to_vec();
3072        lines.insert(5, "Pad orientation: 0");
3073        let log = read(&text(&lines, &flight_v2())).unwrap();
3074        assert_eq!(
3075            figure(&log),
3076            Some(("0".to_owned(), Some(Quantity::Number), vec![0.0]))
3077        );
3078
3079        let long = "X".repeat(200);
3080        let unstated = HEAD_V2
3081            .replace("\"log_format\": 7,", "\"log_format\": 2147483647,")
3082            .replace("TeleMetrum-v2.0", &long);
3083        match read(&json(&unstated, &flight_v2())) {
3084            Err(LogError::Syntax { message, .. }) => {
3085                assert!(
3086                    message.contains(&format!("\"{}\"", "X".repeat(80))),
3087                    "{message}"
3088                );
3089                assert!(!message.contains(&"X".repeat(81)), "{message}");
3090            }
3091            other => panic!("{other:?}"),
3092        }
3093        let mut lines = TEXT_HEAD_V2.to_vec();
3094        let twice = format!("product          {long}");
3095        lines.push(&twice);
3096        match read(&text(&lines, &flight_v2())) {
3097            Err(LogError::Syntax { message, .. }) => {
3098                assert!(!message.contains(&"X".repeat(81)), "{message}")
3099            }
3100            other => panic!("{other:?}"),
3101        }
3102    }
3103
3104    /// No MS5607 constants, or an MS5611: D1 and D2 kept as written, and no pad check.
3105    #[test]
3106    fn without_the_barometers_constants_its_counts_are_kept() {
3107        let ms5611 = HEAD_V2.replace("\"ms5611\": false", "\"ms5611\": true");
3108        let log = read(&json(&ms5611, &flight_v2())).unwrap();
3109        assert!(channel(&log, "pressure").is_none());
3110        assert_eq!(values(&log, "d1")[0], f64::from(EXAMPLE_D1));
3111        assert!(has_note(
3112            &log,
3113            "`d1` and `d2` kept as written: the configuration marks the barometer an MS5611"
3114        ));
3115        // Nor is the acceleration converted: without a pressure in pascals it has no second check.
3116        assert!(channel(&log, "acceleration").is_none());
3117        assert!(has_note(
3118            &log,
3119            "`accel` kept as written: no pressure in pascals to hold it to"
3120        ));
3121        let no_tref = HEAD_V2.replace("\"tref\": 31553", "\"tref\": 70000");
3122        let log = read(&json(&no_tref, &flight_v2())).unwrap();
3123        assert!(has_note(
3124            &log,
3125            "`d1` and `d2` kept as written: the configuration holds no MS5607 constants"
3126        ));
3127    }
3128
3129    /// A Mega's flight in 32-byte records, as `product` logs it in `format`: the flight record at
3130    /// tick 100 (ground reading 1,000, IMU pad reading `imu`), a sample on the pad at 1 g and
3131    /// one at boost at 0, a sense record, then 5 g a sample every 0.1 s to 1.1 s after boost, the pressure the standard
3132    /// atmosphere gives the height reached.
3133    fn flight_mega(product: &str, format: u32, imu: i16) -> Result<FlightLog, LogError> {
3134        let head = HEAD_V2
3135            .replace("\"log_format\": 7", &format!("\"log_format\": {format}"))
3136            .replace("TeleMetrum-v2.0", product);
3137        let mut flight = 3u16.to_le_bytes().to_vec();
3138        flight.extend(1000i16.to_le_bytes());
3139        flight.extend(110_002u32.to_le_bytes());
3140        flight.extend([imu, 0, 0].iter().flat_map(|v| v.to_le_bytes()));
3141        let sample = |d1: u32, accel: i16| {
3142            let mut fields = d1.to_le_bytes().to_vec();
3143            fields.extend(EXAMPLE_D2.to_le_bytes());
3144            fields.extend((1..=9i16).flat_map(|v| v.to_le_bytes()));
3145            fields.extend(accel.to_le_bytes());
3146            fields
3147        };
3148        let mut sense = 2000i16.to_le_bytes().to_vec();
3149        sense.extend(4095i16.to_le_bytes());
3150        sense.extend(6i16.to_le_bytes());
3151        sense.extend(
3152            [0i16, 4095, 0, 0, 1000, 0]
3153                .iter()
3154                .flat_map(|v| v.to_le_bytes()),
3155        );
3156        let mut records = vec![
3157            record(32, b'F', 100, &flight),
3158            record(32, b'A', 99, &sample(EXAMPLE_D1, 980)),
3159            record(32, b'A', 100, &sample(EXAMPLE_D1, 1000)),
3160            record(32, b'T', 101, &sense),
3161        ];
3162        let pad_m = altitude_of(110_002.0);
3163        for k in 1..=11u16 {
3164            let pa = pressure_at(pad_m + climbed_m(f64::from(k) / 10.0));
3165            records.push(record(32, b'A', 100 + 10 * k, &sample(d1_for(pa), 900)));
3166        }
3167        read(&json(&head, &records))
3168    }
3169
3170    /// A Mega's IMU: read on format 16 and 22 where the flight record's IMU fields aren't all zero;
3171    /// not on format 15, nor where they are.
3172    #[test]
3173    fn a_megas_imu_is_read_only_where_its_layout_is_confirmed() {
3174        let log = flight_mega("TeleMega-v6.0", 16, 5).unwrap();
3175        assert_eq!(values(&log, "imu_gyro_0")[0], 4.0);
3176        assert_eq!(
3177            channel(&log, "imu_mag_2").unwrap().quantity,
3178            Quantity::Unrecognized
3179        );
3180        assert!((values(&log, "acceleration")[0] - STANDARD_GRAVITY).abs() < 1e-12);
3181        // The 15 V boards' sense: 4,095 counts is 3.3 V × 127 / 27.
3182        let full = 3.3 * 127.0 / 27.0;
3183        assert!((values(&log, "pyro")[0] - full).abs() < 1e-12);
3184        assert!((values(&log, "igniter_b")[0] - full).abs() < 1e-12);
3185        assert_eq!(channel(&log, "pyro").unwrap().quantity, Quantity::Voltage);
3186        assert_eq!(values(&log, "v_batt"), [2000.0]);
3187        assert!(values(&log, "drogue_voltage")[0] > 0.0);
3188        let log = flight_mega("TeleMega-v4.0", 15, 5).unwrap();
3189        assert!(channel(&log, "imu_accel_0").is_none());
3190        assert!(has_note(
3191            &log,
3192            "the IMU not read: format 15's layout of it is unconfirmed"
3193        ));
3194        let log = flight_mega("TeleMega-v6.0", 22, 0).unwrap();
3195        assert!(channel(&log, "imu_accel_0").is_none());
3196        assert!(has_note(
3197            &log,
3198            "the IMU not read: the flight record's IMU fields are all zero"
3199        ));
3200    }
3201
3202    /// A Mega's senses become volts only for the products whose divider the exports bear out; a
3203    /// TeleMega v7.0, a 30 V board, keeps its counts as written.
3204    #[test]
3205    fn a_megas_senses_are_volts_only_for_the_15_v_products() {
3206        for product in MEGA_15_V_PRODUCTS {
3207            let log = flight_mega(product, 22, 5).unwrap();
3208            assert_eq!(channel(&log, "pyro").unwrap().quantity, Quantity::Voltage);
3209        }
3210        let log = flight_mega("TeleMega-v7.0", 22, 5).unwrap();
3211        for name in [
3212            "pyro",
3213            "igniter_a",
3214            "igniter_d",
3215            "drogue_voltage",
3216            "main_voltage",
3217        ] {
3218            assert_eq!(
3219                channel(&log, name).unwrap().quantity,
3220                Quantity::Unrecognized,
3221                "{name}"
3222            );
3223        }
3224        assert_eq!(values(&log, "pyro"), [4095.0]);
3225        assert_eq!(values(&log, "drogue_voltage"), [1000.0]);
3226        assert!(has_note(
3227            &log,
3228            "`pyro`, the igniters' and the apogee and main senses kept as written. The product, \
3229             TeleMega-v7.0, isn't one"
3230        ));
3231    }
3232
3233    /// A position without a valid fix at its tick is a gap; with `altitude-32`, the altitude's
3234    /// high 16 bits count.
3235    #[test]
3236    fn gps_positions_need_a_valid_fix() {
3237        let position = |tick: u16, lat: i32, lon: i32, low: u16, high: i16| {
3238            let mut fields = lat.to_le_bytes().to_vec();
3239            fields.extend(lon.to_le_bytes());
3240            fields.extend(low.to_le_bytes());
3241            fields.extend(high.to_le_bytes());
3242            record(16, b'P', tick, &fields)
3243        };
3244        let mut records = flight_v2();
3245        records.extend([
3246            position(150, 450_000_000, -1_220_000_000, 4_464, 1),
3247            record(16, b'G', 150, &[12, 0, 1, 0x10 | 6, 26, 10, 14, 40]),
3248            position(180, 450_000_000, -1_220_000_000, 1_000, 0),
3249            record(16, b'G', 180, &[12, 0, 1, 0x20 | 3, 26, 10, 14, 40]),
3250        ]);
3251        let log = read(&json(HEAD_V2, &records)).unwrap();
3252        let latitude = values(&log, "latitude");
3253        assert_eq!(latitude[0], 45.0);
3254        assert!(latitude[1].is_nan());
3255        assert_eq!(values(&log, "longitude")[0], -122.0);
3256        assert_eq!(values(&log, "gps_altitude")[0], 70_000.0);
3257        assert_eq!(values(&log, "nsat"), [6.0, 3.0]);
3258        assert!(has_note(&log, "1 GPS position records without a valid fix"));
3259    }
3260
3261    /// States are named as AltosUI's exports name them; another number is `state N`.
3262    #[test]
3263    fn states_are_named_and_others_numbered() {
3264        let mut records = flight_v2();
3265        records.extend([s(16, 203, 5), s(16, 204, 5), s(16, 205, 9)]);
3266        let log = read(&json(HEAD_V2, &records)).unwrap();
3267        let names: Vec<&str> = log.events.iter().map(|e| e.name.as_str()).collect();
3268        assert_eq!(names, ["boost", "coast", "state 9"]);
3269    }
3270
3271    /// The text form's configuration printed twice must agree.
3272    #[test]
3273    fn a_configuration_printed_twice_must_agree() {
3274        let mut head: Vec<&str> = TEXT_HEAD_V2.to_vec();
3275        head.extend(TEXT_HEAD_V2);
3276        assert!(read(&text(&head, &flight_v2())).is_ok());
3277        head.push("serial-number    4321");
3278        match read(&text(&head, &flight_v2())) {
3279            Err(LogError::Syntax { line, message, .. }) => {
3280                assert_eq!(line, head.len());
3281                assert!(
3282                    message.contains("its serial number here, \"4321\", differs from line 16's"),
3283                    "{message}"
3284                );
3285            }
3286            other => panic!("{other:?}"),
3287        }
3288    }
3289
3290    /// A record type the board's layout doesn't hold is counted, not read.
3291    #[test]
3292    fn an_unknown_record_type_is_counted() {
3293        let mut records = flight_v2();
3294        records.push(record(16, b'Z', 203, &[1, 2, 3]));
3295        let log = read(&json(HEAD_V2, &records)).unwrap();
3296        assert!(has_note(&log, "1 records of type `Z` not read"));
3297    }
3298}