Skip to main content

hpr_flightdata/
blueraven.rs

1//! The Featherweight Blue Raven's flight logs, as its phone app exports them to comma-separated
2//! files.
3//!
4//! The Blue Raven records three sets of data for each flight: a summary, a low-rate set "recorded
5//! at 50 Hz" and a high-rate set "recorded at 500 Hz" (Featherweight, *Blue Raven User's Guide*,
6//! updated May 12 2026, p18); the Featherweight UI app downloads them over Bluetooth and exports
7//! each as a file (p19). This reader reads the two data files, each on its own: a header line
8//! naming the columns, then one row per sample, every column on the row's time:
9//!
10//! ```text
11//! Year,Month,Day,Time,Flight_Time_(s),Sync,Gyro_X,Gyro_Y,Gyro_Z,Accel_X,Accel_Y,Accel_Z,Quat_1,…
12//! 2026,5,23,10:15:00.120,-2.000,0,0.10,-0.20,0.05,0.01,-0.02,1.00,0.7071,…
13//! ```
14//!
15//! A file is the app's when its first line that isn't blank opens with the six columns
16//! `Year,Month,Day,Time,Flight_Time_(s),Sync`, as both files do, or with `Flight_Time_(s),Sync`
17//! alone: one of the project's sample high-rate files holds no date, and the record notes so. The high-rate file has 18 columns,
18//! the low-rate file 101; columns are mapped by name, not by place, so the low-rate file's
19//! variants read alike (in some, `Axial Accel (Gs),Lateral Accel (Gs)` stand where others have
20//! `3rd_Volts,4th_Volts`, and one names the fifth FER column `Apo_FER_H  ex`, with two spaces).
21//! A name is matched with its spaces taken out and without regard to case, and kept as written.
22//! The low-rate file repeats some names (`Reserved`, and the four output channels' condition
23//! flags such as `LT_AGL1`): each is its own channel, in the file's order.
24//!
25//! **Channels.** Every column but the clock is a channel, read into the record's SI unit
26//! ([`Quantity::unit`]):
27//!
28//! | Column | Quantity | From |
29//! |---|---|---|
30//! | `Flight_Time_(s)` | the clock, s, zero at liftoff | the header |
31//! | `Time` | [`Quantity::TimeOfDay`], s after the logger's midnight | written `HH:MM:SS.fff`; no zone is stated |
32//! | `Year`, `Month`, `Day`, `Sync` | [`Quantity::Number`] | the date the logger's clock gives; `Sync` is "a millisecond counter … recorded in both the low-rate and high-rate data so that the two data sets can be aligned", which "rolls over every 250 msec" (p23) |
33//! | `Temperature_(F)` | [`Quantity::Temperature`] | the header's °F |
34//! | `Baro_Press_(atm)` | [`Quantity::Pressure`] | the header's atm, × 101,325 Pa |
35//! | `Baro_Altitude_AGL_(feet)`, `Baro_Altitude_ASL_(feet)` | [`Quantity::AltitudeAboveGround`], [`Quantity::AltitudeMsl`] | the header's feet |
36//! | `Batt_Volts`, `Apo_Volts`, `Main_Volts`, `3rd_Volts`, `4th_Volts`, `Aux_Volts` | [`Quantity::Voltage`] | the header's volts |
37//! | `Axial Accel (Gs)`, `Lateral Accel (Gs)` | [`Quantity::Acceleration`] | the header's g, × 9.806 65 m/s² (standard gravity) |
38//! | `Velocity_Up`, `Velocity_DR`, `Velocity_CR` | [`Quantity::Speed`] | ft/s: the manual and the summary (below) |
39//! | `Inertial_Altitude` | [`Quantity::InertialAltitude`] | ft: the manual and the summary (below) |
40//! | `Inertial_DR_Position`, `Inertial_CR_position` | [`Quantity::Distance`] | ft: the manual (below) |
41//! | `Tilt_Angle_(deg)`, `Future_Angle_(deg)`, `Roll_Angle_(deg)` | [`Quantity::Angle`] | the header's degrees |
42//! | `Gyro_X`, `Gyro_Y`, `Gyro_Z` | [`Quantity::AngularRate`] | °/s: the manual and the summary (below) |
43//! | `Accel_X`, `Accel_Y`, `Accel_Z` | [`Quantity::Acceleration`] | g, × 9.806 65 m/s²: the manual and the pad (below) |
44//! | `Quat_1` … `Quat_4` | [`Quantity::Number`] | the attitude quaternion, of unit norm, its magnitude term first: the manual writes the USB download's with "the rotation axis first and the magnitude term fourth" (p24, [`crate::blueraven_usb`]), but as of 2026-10-15, in each high-rate file among the sample logs whose first row holds numbers, `Quat_1` is the largest term there, about 1 on the pad |
45//! | `Current` | [`Quantity::Unrecognized`], as written | no source states its unit (below) |
46//! | `Rocket_FER_Hex`, `Apo_FER_Hex` and the other `…_FER_Hex` | [`Quantity::Number`]: the register's bits | hexadecimal in the file (below) |
47//! | `Liftoff`, `Apogee` and the other flags | [`Quantity::Number`], 0 or 1 | below |
48//! | `Reserved`, `Reserved_1` … | [`Quantity::Unrecognized`], as written | the manual describes no reserved column |
49//!
50//! A column the reader doesn't know is kept as written, [`Quantity::Unrecognized`], with a note.
51//!
52//! **Units no header states.** Thirteen columns carry no unit in their names. The manual states
53//! each one's unit for the logger's USB download, which carries the same figures (p23–24):
54//! velocities in ft/sec, the inertial altitude and the down-range and cross-range positions in
55//! feet, gyro rates in deg/s × 100, accelerations in G × 100, current in mA. The app writes the
56//! gyro rates and accelerations unscaled by the hundred, so its file's units are decided from what
57//! the app's own files show. The counts below are, as of 2026-10-12, over the 80 Blue Raven files
58//! among the project's sample logs (45 low-rate, 35 high-rate), most of them in the private
59//! collection of flights this project checks against:
60//!
61//! - *Velocities and the inertial altitude, in feet.* Beside a flight, the app's summary file
62//!   states "Max velocity" in "feet/sec" and "Inertial navigation max alt" in "feet". Of the 32
63//!   summaries that sit beside a low-rate file, 25 state an inertial maximum within 0.5 % of a
64//!   low-rate file's highest `Inertial_Altitude`, and in those the highest `Velocity_Up` is 0.69
65//!   to 1.0 times the summary's maximum velocity, which counts every direction; in meters per
66//!   second it would be 0.3 times. Debrief's public pair agrees: its file's highest speed and
67//!   inertial altitude are within 0.5 % of its summary's, in feet. The barometer agrees too: integrated over
68//!   the climb to the barometer's highest sample, `Velocity_Up` gives 0.90 to 1.20 times the
69//!   rise of `Baro_Altitude_AGL_(feet)` in 43 of the 45 low-rate files. The down-range and
70//!   cross-range positions take the altitude's unit, as the manual gives them.
71//! - *Gyro rates in degrees per second.* The summary states "Pad gyro rates (deg/sec)", and the
72//!   manual gives the gyros' range as ±2000 deg/sec (p23): in 21 of the 35 high-rate files the
73//!   largest rate sits at a common ceiling of 2,292 to 2,294, just past that range, as a
74//!   saturated gyro reads.
75//! - *Accelerations in g.* On the pad, the median magnitude of the three axes is 0.990 to 1.014 in
76//!   34 of the 35 high-rate files, as a logger at rest reads 1 g.
77//! - *Current, kept as written.* No document states the app's unit. The column reads 0 in every
78//!   row of 6 high-rate files, and in the other 29 but for brief runs, peaking at 0.05 to 13, 13
79//!   of them between 2 and 3.5. Amperes would fit the manual's word that the Blue Raven
80//!   "internally limits the current to around 4 Amps" (p5), and the USB download's milliamperes
81//!   would put a firing output's current at a few thousandths of an ampere; but the files show a
82//!   size, not a unit, so the column stays [`Quantity::Unrecognized`] until a source states it,
83//!   with a note giving this file's figures.
84//!
85//! Each file's record carries one note per kind decided this way, the decision and this file's
86//! own evidence, such as `` `Gyro_X`, `Gyro_Y` and `Gyro_Z` read in degrees per second, from the
87//! manual and the summary: … ``.
88//!
89//! **Flags, event registers and events.** The manual's five flight event registers hold "one bit
90//! for each event", written in hexadecimal (p24): the rocket's (`Rocket_FER_Hex`) and each output
91//! channel's (`Apo_FER_Hex`, `Main_FER_Hex`, `3rd_FER_Hex`, `4th_FER_Hex`). The cells are lowercase
92//! hexadecimal digits without `0x`, read as the number they write, `1a5` as 421. The files name
93//! the bits: the 0/1 columns after the registers spell them out, and in every row of the 45
94//! low-rate files read, `Rocket_FER_Hex` equals the 13 flags `Liftoff` … `Reserved` read with
95//! `Liftoff` as bit 0, and each channel's register equals its 14 condition flags `LT_AGL1` …
96//! `Reserved`, `LT_AGL1` as bit 0. Each flag is kept as a channel, 0 or 1. The manual's tables of
97//! deployment settings list the rocket's events as liftoff, apogee, pressure increasing, burnout
98//! coast and each output fired (p26–28); the channel flags are the conditions an output's logic
99//! checks, such as `LT_AGL1`, "AGL < AGL1" (p25).
100//!
101//! Seven flags mark a moment and become an [`Event`], named as the column, at each row where the
102//! flag goes from 0 to 1: `Liftoff`, `Apogee`, `Burnout_Coast`, `Apo_fired`, `Main_fired`,
103//! `3rd_fired` and `4th_fired`. As of 2026-10-12, in the 45 low-rate files among the project's
104//! sample logs, each rises at most 15 times in a file, and in most once or twice (twice in a file
105//! holding two flights, or a stage's second burn). The others stay channels only: `Press_Increasing`,
106//! `Normal_Ascent`, `Accel_Vel_LE_0`, `ECI_Vvel_le_0` and `Tilt Exceeded 90deg` state a condition
107//! that comes and goes (`ECI_Vvel_le_0` rises up to 34 times in a file), and the channel flags
108//! are a deployment logic's conditions, not what happened. A flag already 1 on the first row
109//! rose before the file began, so it gives no event, with a note; past [`MAX_EVENTS_PER_FLAG`]
110//! rises in one column, the rest are counted in a note instead.
111//!
112//! **Clocks.** `Flight_Time_(s)` is the clock: strictly increasing in every file read, from a
113//! negative time on the pad in all but one. A time that doesn't increase is refused, naming its
114//! line. The wall clock `Time` is a channel only: as of 2026-10-12, among the sample logs, it
115//! holds one value for several rows at a time in 5 of the high-rate files, and steps back in 4 of
116//! the low-rate files, from once to hundreds of times, by up to about 14.5 hours. It is kept as
117//! written, and a note says when it goes back. `Sync` steps by 2 a row in the high-rate files and
118//! by 20 in the low-rate ones (40 where the file is logged every 0.04 s), in milliseconds, wrapping
119//! at 250.
120//!
121//! **The primary track.** For a low-rate file, [`FlightLog::time_s`] is `Flight_Time_(s)` and
122//! [`FlightLog::altitude_m`] is `Baro_Altitude_AGL_(feet)`, the barometer's altitude above the
123//! pad; the temperature and battery are `Temperature_(F)` and `Batt_Volts`. The vertical speed is
124//! `None`: `Velocity_Up` is the inertial solution's, which "lose\[s\] track of which way is up"
125//! when the rocket turns faster than the gyros measure (p23), not the barometer's, so it is a
126//! channel only. As of 2026-10-12, in 10 of the 45 low-rate files `Inertial_Altitude` steps by
127//! more than 32,768 ft between two rows, as a 16-bit count of feet does when it wraps; it is kept
128//! as written, with a note. A high-rate file holds no altitude: it is read with an empty primary track and every
129//! column as a channel, with a note that the low-rate file of the same flight holds the altitude.
130//!
131//! **Cells and rows.** A cell that is empty, or isn't a number (or a time of day, or hexadecimal
132//! digits, as its column needs) is a gap, `NaN`, counted per column in a note; none of the files
133//! read has one. A row with fewer cells than the header has the rest as gaps, counted in a note;
134//! a row with more is refused, as is a row whose clock cell isn't a number. A file whose rows, down
135//! to any row, hold under a quarter of the cells its header names (past the first 65,536) is
136//! refused at that row, so a wide header over short rows can't make the reader allocate
137//! far more than the file holds. Blank lines are skipped;
138//! lines may end in CR, LF or both; a byte-order mark is dropped; cells may be padded with spaces.
139//!
140//! **What the file says about itself.** The logger is a `Featherweight Blue Raven`; the data
141//! files state no serial number, firmware, flight number or apogee (the summary file does).
142//!
143//! **Where this comes from.** The layout, from the files themselves and Featherweight's manual as
144//! cited; the column names and the gyro and acceleration units agree with Debrief's reader
145//! (`lib/parsers/blueraven.ts`, MIT, the project owner's own; see `THIRD-PARTY-NOTICES.md`). Where
146//! this reader departs from Debrief's: it keeps every column, where Debrief keeps a chosen few; it
147//! reads a high-rate file on its own, where Debrief refuses it and points to the low-rate file; it
148//! keeps `Inertial_Altitude` whole, with a note, where Debrief cuts it off where it wraps or
149//! leaves the barometer's altitude by more than the flight's height.
150
151use hpr_core::gravity::STANDARD_GRAVITY_MPS2;
152
153use crate::error::LogError;
154use crate::log::{Channel, Event, FlightLog, LogFormat, Quantity, Stated, too_sparse};
155use crate::perfectflite::FOOT_M;
156use crate::table::{Notes, finite, number, numbered_lines, short};
157
158/// The format's name in errors.
159const FORMAT: &str = "Blue Raven CSV";
160
161/// The columns both of the app's files open with, in order.
162const LEAD: [&str; 6] = ["Year", "Month", "Day", "Time", "Flight_Time_(s)", "Sync"];
163
164/// The place of the clock, `Flight_Time_(s)`, among [`LEAD`]'s columns (0-based).
165const CLOCK_INDEX: usize = 4;
166
167/// [`LEAD`] without its date and time of day, as a file holding no date opens.
168const SHORT_LEAD: [&str; 2] = ["Flight_Time_(s)", "Sync"];
169
170/// Pascals in a standard atmosphere, exactly (ISO 2533).
171const ATM_PA: f64 = 101_325.0;
172
173/// The most events one flag column gives; past it, its rises are counted in a note. The files
174/// read rise at most 15 times in a column.
175pub const MAX_EVENTS_PER_FLAG: usize = 16;
176
177/// How far `Inertial_Altitude` may step between two rows, ft, before the step is counted as a
178/// wrap: half the span of a 16-bit count of feet.
179const WRAP_STEP_FT: f64 = 32_768.0;
180
181/// The most rows from the file's start the acceleration's pad magnitude is taken over when the
182/// file has no row before liftoff.
183const PAD_ROWS: usize = 50;
184
185/// Whether the text is in this reader's layout, judged from its header, never the file's name:
186/// its first line that isn't blank opens with [`LEAD`]'s six columns, or [`SHORT_LEAD`]'s two,
187/// and names more.
188pub(crate) fn recognizes(text: &str) -> bool {
189    numbered_lines(text)
190        .map(|(_, line)| line)
191        .find(|line| !line.trim().is_empty())
192        .and_then(clock_index)
193        .is_some()
194}
195
196/// The place of the clock in a header line that opens with [`LEAD`]'s columns ([`CLOCK_INDEX`])
197/// or [`SHORT_LEAD`]'s (0) and names at least one more; `None` for any other line.
198fn clock_index(header: &str) -> Option<usize> {
199    let opens_with = |lead: &[&str]| {
200        let mut cells = header.split(',').map(str::trim);
201        lead.iter().all(|name| cells.next() == Some(*name)) && cells.next().is_some()
202    };
203    if opens_with(&LEAD) {
204        Some(CLOCK_INDEX)
205    } else if opens_with(&SHORT_LEAD) {
206        Some(0)
207    } else {
208        None
209    }
210}
211
212/// How a value becomes SI.
213#[derive(Debug, Clone, Copy, PartialEq)]
214enum Scale {
215    /// Multiplied by a factor.
216    By(f64),
217    /// Degrees Fahrenheit to kelvin.
218    Fahrenheit,
219}
220
221/// What a column is to this reader.
222#[derive(Debug, Clone, Copy, PartialEq)]
223enum Role {
224    /// `Flight_Time_(s)`: the clock.
225    Clock,
226    /// `Time`: the wall clock, `HH:MM:SS.fff`.
227    TimeOfDay,
228    /// A number in a quantity, made SI by a scale.
229    Value(Quantity, Scale),
230    /// An event register, hexadecimal digits.
231    Hex,
232    /// A 0/1 flag; `event` if its rise marks a moment.
233    Flag { event: bool },
234}
235
236/// The kinds of column whose unit no header states, each decided once, with a note.
237#[derive(Debug, Clone, Copy, PartialEq, Eq)]
238enum Decided {
239    Velocity,
240    Inertial,
241    Gyro,
242    Accel,
243}
244
245/// A column's name with its spaces taken out, in lower case, as [`role`] matches it.
246fn key(name: &str) -> String {
247    name.chars()
248        .filter(|c| !c.is_whitespace())
249        .collect::<String>()
250        .to_ascii_lowercase()
251}
252
253/// What a column is, and which decided kind it falls under; `None` for a name the reader doesn't
254/// know. The clock is matched only in its place ([`clock_index`]).
255fn role(name: &str) -> Option<(Role, Option<Decided>)> {
256    use Quantity as Q;
257    let key = key(name);
258    let value = |quantity, scale| Some((Role::Value(quantity, scale), None));
259    let decided = |quantity, scale, kind| Some((Role::Value(quantity, scale), Some(kind)));
260    let feet = Scale::By(FOOT_M);
261    let gravities = Scale::By(STANDARD_GRAVITY_MPS2);
262    let one = Scale::By(1.0);
263    match key.as_str() {
264        "time" => Some((Role::TimeOfDay, None)),
265        "year" | "month" | "day" | "sync" | "quat_1" | "quat_2" | "quat_3" | "quat_4" => {
266            value(Q::Number, one)
267        }
268        "temperature_(f)" => value(Q::Temperature, Scale::Fahrenheit),
269        "baro_press_(atm)" => value(Q::Pressure, Scale::By(ATM_PA)),
270        "baro_altitude_agl_(feet)" => value(Q::AltitudeAboveGround, feet),
271        "baro_altitude_asl_(feet)" => value(Q::AltitudeMsl, feet),
272        "axialaccel(gs)" | "lateralaccel(gs)" => value(Q::Acceleration, gravities),
273        "tilt_angle_(deg)" | "future_angle_(deg)" | "roll_angle_(deg)" => value(Q::Angle, one),
274        "velocity_up" | "velocity_dr" | "velocity_cr" => decided(Q::Speed, feet, Decided::Velocity),
275        "inertial_altitude" => decided(Q::InertialAltitude, feet, Decided::Inertial),
276        "inertial_dr_position" | "inertial_cr_position" => {
277            decided(Q::Distance, feet, Decided::Inertial)
278        }
279        "gyro_x" | "gyro_y" | "gyro_z" => decided(Q::AngularRate, one, Decided::Gyro),
280        "accel_x" | "accel_y" | "accel_z" => decided(Q::Acceleration, gravities, Decided::Accel),
281        "current" => value(Q::Unrecognized, one),
282        "liftoff" | "apogee" | "burnout_coast" | "apo_fired" | "main_fired" | "3rd_fired"
283        | "4th_fired" => Some((Role::Flag { event: true }, None)),
284        "press_increasing" | "normal_ascent" | "accel_vel_le_0" | "eci_vvel_le_0"
285        | "tiltexceeded90deg" | "lt_agl1" | "gt_agl2" | "lt_fang1" | "gt_fang2" | "gt_futang"
286        | "lt_tval1" | "gt_tval2" | "lt_vel1" | "gt_vel2" | "lt_bvel1" | "gt_burn" | "armed" => {
287            Some((Role::Flag { event: false }, None))
288        }
289        _ if key.ends_with("_volts") => value(Q::Voltage, one),
290        _ if key.ends_with("_fer_hex") => Some((Role::Hex, None)),
291        _ => None,
292    }
293}
294
295/// One column of the file, as read so far.
296struct Column {
297    name: String,
298    key: String,
299    role: Role,
300    decided: Option<Decided>,
301    values: Vec<f64>,
302    /// Cells that were empty or not what the column holds, and the first of them as written.
303    gaps: usize,
304    gap_example: Option<String>,
305    /// For an event flag: the events it gave, rises past the cap, and whether the first row was
306    /// already set.
307    events_kept: usize,
308    rises_left_out: usize,
309    set_on_first_row: bool,
310}
311
312impl Column {
313    fn quantity(&self) -> Quantity {
314        match self.role {
315            Role::Value(quantity, _) => quantity,
316            Role::TimeOfDay => Quantity::TimeOfDay,
317            Role::Clock | Role::Hex | Role::Flag { .. } => Quantity::Number,
318        }
319    }
320}
321
322/// Reads a Featherweight Blue Raven's low-rate or high-rate CSV, as its phone app exports it.
323///
324/// # Errors
325///
326/// [`LogError::NotThisFormat`] if the first line isn't the app's header; [`LogError::Syntax`] for
327/// a header column with no name, a row with more cells than the header, a row whose
328/// `Flight_Time_(s)` is missing, isn't a number or doesn't come after the row above's, a value
329/// too large to convert to SI, or rows holding under a quarter of the cells the header names;
330/// [`LogError::NoData`] if no row follows the header.
331pub fn read(text: &str) -> Result<FlightLog, LogError> {
332    let mut lines = numbered_lines(text).filter(|(_, line)| !line.trim().is_empty());
333    let Some((header_line, header)) = lines.next() else {
334        return Err(LogError::NotThisFormat {
335            format: FORMAT,
336            message: "the file is empty".to_owned(),
337        });
338    };
339    let Some(clock) = clock_index(header) else {
340        return Err(LogError::NotThisFormat {
341            format: FORMAT,
342            message: format!(
343                "its first line, {:?}, isn't the app's header, which opens `{}`, or `{}` in a \
344                 file with no date",
345                short(header),
346                LEAD.join(","),
347                SHORT_LEAD.join(",")
348            ),
349        });
350    };
351    // Notes about single columns, capped; notes about the whole file, one each at most.
352    let mut notes = Notes::default();
353    let mut file_notes = Vec::new();
354    if clock == 0 {
355        file_notes.push(format!(
356            "the header opens `{}`, without the app's `Year,Month,Day,Time`: the file holds no \
357             date or time of day",
358            SHORT_LEAD.join(",")
359        ));
360    }
361    let mut columns = header_columns(header, header_line, clock, &mut notes, &mut file_notes)?;
362
363    let mut time_s: Vec<f64> = Vec::new();
364    let mut events: Vec<Event> = Vec::new();
365    let (mut rows, mut cells_written) = (0usize, 0usize);
366    let mut short_rows = 0usize;
367    let mut first_short_row = 0usize;
368    for (number, line) in lines {
369        let cells = read_row(&mut columns, &mut time_s, &mut events, line, number)?;
370        rows += 1;
371        cells_written += cells;
372        // Checked row by row, so that a wide header over short rows is refused before the gaps
373        // it would leave grow past a quarter more than the cells the file holds.
374        if too_sparse(columns.len(), rows, cells_written) {
375            return Err(syntax(
376                number,
377                format!(
378                    "the header names {} columns, and the {rows} rows down to this one hold only \
379                     {cells_written} cells",
380                    columns.len()
381                ),
382            ));
383        }
384        if cells < columns.len() {
385            if short_rows == 0 {
386                first_short_row = number;
387            }
388            short_rows += 1;
389        }
390    }
391    if rows == 0 {
392        return Err(LogError::NoData { format: FORMAT });
393    }
394    if short_rows > 0 {
395        file_notes.push(format!(
396            "{short_rows} rows, the first on line {first_short_row}, have fewer cells than the \
397             header's {}: the cells they leave out are gaps",
398            columns.len()
399        ));
400    }
401    Ok(build(columns, time_s, events, notes, file_notes))
402}
403
404/// The columns the header names, each with its role; unknown names noted.
405fn header_columns(
406    header: &str,
407    line: usize,
408    clock: usize,
409    notes: &mut Notes,
410    file_notes: &mut Vec<String>,
411) -> Result<Vec<Column>, LogError> {
412    let mut columns = Vec::new();
413    let mut reserved = 0usize;
414    for (index, name) in header.split(',').map(str::trim).enumerate() {
415        if name.is_empty() {
416            return Err(syntax(
417                line,
418                format!("the header's column {} has no name", index + 1),
419            ));
420        }
421        let (role, decided) = if index == clock {
422            (Role::Clock, None)
423        } else if key(name).starts_with("reserved") {
424            reserved += 1;
425            (Role::Value(Quantity::Unrecognized, Scale::By(1.0)), None)
426        } else {
427            role(name).unwrap_or_else(|| {
428                notes.push(format!(
429                    "the column {:?} isn't one this reader knows, and was kept as written",
430                    short(name)
431                ));
432                (Role::Value(Quantity::Unrecognized, Scale::By(1.0)), None)
433            })
434        };
435        columns.push(Column {
436            name: name.to_owned(),
437            key: key(name),
438            role,
439            decided,
440            values: Vec::new(),
441            gaps: 0,
442            gap_example: None,
443            events_kept: 0,
444            rises_left_out: 0,
445            set_on_first_row: false,
446        });
447    }
448    if reserved > 0 {
449        file_notes.push(format!(
450            "{reserved} columns named `Reserved…` hold what the manual doesn't describe, and were \
451             kept as written"
452        ));
453    }
454    Ok(columns)
455}
456
457/// Reads one row into the clock and the columns, and any event its flags mark; returns how many
458/// cells it has.
459fn read_row(
460    columns: &mut [Column],
461    time_s: &mut Vec<f64>,
462    events: &mut Vec<Event>,
463    line: &str,
464    number: usize,
465) -> Result<usize, LogError> {
466    let mut cells = line.split(',').map(str::trim);
467    // The clock comes before every flag, so a flag's event takes the row's time.
468    let mut row_time = f64::NAN;
469    let mut count = 0;
470    for (index, column) in columns.iter_mut().enumerate() {
471        let Some(cell) = cells.next() else {
472            if column.role == Role::Clock {
473                return Err(syntax(
474                    number,
475                    format!(
476                        "the row ends after {count} cells, before its {:?}",
477                        short(&column.name)
478                    ),
479                ));
480            }
481            column.values.push(f64::NAN);
482            continue;
483        };
484        count += 1;
485        if column.role == Role::Clock {
486            let time = number_cell(cell).ok_or_else(|| {
487                syntax(
488                    number,
489                    format!(
490                        "the time {:?} in cell {} isn't a finite number",
491                        short(cell),
492                        index + 1
493                    ),
494                )
495            })?;
496            if let Some(&last) = time_s.last()
497                && time <= last
498            {
499                return Err(syntax(
500                    number,
501                    format!("the time {time} s doesn't come after the one above it, {last} s"),
502                ));
503            }
504            row_time = time;
505            time_s.push(time);
506            continue;
507        }
508        let value = match column.role {
509            // A finite cell that its unit's conversion makes infinite, such as `1.7e308` g or °F,
510            // is refused on its line (ADR-258 §3).
511            Role::Value(_, scale) => number_cell(cell)
512                .map(|value| finite(si(scale, value), FORMAT, number, &column.name))
513                .transpose()?,
514            Role::TimeOfDay => time_of_day(cell),
515            Role::Hex => hex(cell),
516            Role::Flag { .. } => number_cell(cell),
517            Role::Clock => None,
518        };
519        let value = value.unwrap_or_else(|| {
520            column.gaps += 1;
521            if column.gap_example.is_none() {
522                column.gap_example = Some(short(cell));
523            }
524            f64::NAN
525        });
526        if let Role::Flag { event: true } = column.role {
527            flag_event(column, value, row_time, events);
528        }
529        column.values.push(value);
530    }
531    if cells.next().is_some() {
532        return Err(syntax(
533            number,
534            format!(
535                "the row has {} cells, more than the header's {}",
536                line.split(',').count(),
537                columns.len()
538            ),
539        ));
540    }
541    Ok(count)
542}
543
544/// An event when a flag rises from 0 to 1, up to [`MAX_EVENTS_PER_FLAG`] per column; a flag set
545/// on the first row is marked instead. Called before the value is stored.
546fn flag_event(column: &mut Column, value: f64, time_s: f64, events: &mut Vec<Event>) {
547    let risen = value == 1.0;
548    match column.values.last() {
549        None => column.set_on_first_row = risen,
550        Some(&before) if before == 0.0 && risen => {
551            if column.events_kept < MAX_EVENTS_PER_FLAG {
552                column.events_kept += 1;
553                events.push(Event {
554                    time_s,
555                    name: column.name.clone(),
556                });
557            } else {
558                column.rises_left_out += 1;
559            }
560        }
561        Some(_) => {}
562    }
563}
564
565/// A cell as a finite number, `None` if it isn't one.
566fn number_cell(cell: &str) -> Option<f64> {
567    number(cell, false)
568}
569
570/// A value in SI.
571fn si(scale: Scale, value: f64) -> f64 {
572    match scale {
573        Scale::By(factor) => value * factor,
574        Scale::Fahrenheit => (value - 32.0) * 5.0 / 9.0 + 273.15,
575    }
576}
577
578/// A wall-clock cell, `H:MM:SS` or `HH:MM:SS` with any decimals, as seconds after midnight;
579/// `None` for anything else, or a time past 23:59:60.999….
580fn time_of_day(cell: &str) -> Option<f64> {
581    let mut parts = cell.split(':');
582    let (hours, minutes, seconds) = (parts.next()?, parts.next()?, parts.next()?);
583    if parts.next().is_some() {
584        return None;
585    }
586    let digits = |text: &str| !text.is_empty() && text.bytes().all(|b| b.is_ascii_digit());
587    let (whole, fraction) = seconds.split_once('.').unwrap_or((seconds, "0"));
588    if !(digits(hours) && hours.len() <= 2)
589        || !(digits(minutes) && minutes.len() == 2)
590        || !(digits(whole) && whole.len() == 2)
591        || !digits(fraction)
592    {
593        return None;
594    }
595    let hours: u32 = hours.parse().ok()?;
596    let minutes: u32 = minutes.parse().ok()?;
597    let seconds: f64 = seconds.parse().ok()?;
598    (hours < 24 && minutes < 60 && seconds < 61.0)
599        .then(|| f64::from(hours * 3_600 + minutes * 60) + seconds)
600}
601
602/// An event register's cell, hexadecimal digits with or without `0x`, as the number they write;
603/// `None` for anything else, or more digits than an `f64` holds exactly.
604fn hex(cell: &str) -> Option<f64> {
605    let digits = cell
606        .strip_prefix("0x")
607        .or_else(|| cell.strip_prefix("0X"))
608        .unwrap_or(cell);
609    if digits.is_empty() || digits.len() > 13 || !digits.bytes().all(|b| b.is_ascii_hexdigit()) {
610        return None;
611    }
612    // At most 13 hexadecimal digits, 52 bits, so the value is below 2⁵² and exact as an f64.
613    u64::from_str_radix(digits, 16).ok().map(|bits| bits as f64)
614}
615
616/// The record from the columns read: every channel, the primary track, the events and the notes.
617fn build(
618    columns: Vec<Column>,
619    time_s: Vec<f64>,
620    events: Vec<Event>,
621    mut notes: Notes,
622    mut file_notes: Vec<String>,
623) -> FlightLog {
624    let mut log = FlightLog {
625        format: LogFormat::BlueRavenCsv,
626        logger: "Featherweight Blue Raven".to_owned(),
627        serial_number: None,
628        firmware: None,
629        flight_number: None,
630        stated: Stated::default(),
631        time_s: Vec::new(),
632        altitude_m: Vec::new(),
633        vertical_speed_m_s: None,
634        temperature_k: None,
635        battery_v: None,
636        channels: Vec::new(),
637        events,
638        notes: decided_notes(&columns, &time_s),
639    };
640
641    for column in &columns {
642        if column.gaps > 0 {
643            notes.push(format!(
644                "the column {:?} holds {} cells that are empty or not what it holds, such as \
645                 {:?}: they are gaps",
646                short(&column.name),
647                column.gaps,
648                column.gap_example.as_deref().unwrap_or_default()
649            ));
650        }
651        if column.set_on_first_row {
652            notes.push(format!(
653                "the flag {:?} is already 1 on the first row: it rose before the file begins, so \
654                 the file doesn't say when",
655                short(&column.name)
656            ));
657        }
658        if column.rises_left_out > 0 {
659            notes.push(format!(
660                "the flag {:?} rises {} more times than the {MAX_EVENTS_PER_FLAG} kept as events",
661                short(&column.name),
662                column.rises_left_out
663            ));
664        }
665        match column.role {
666            Role::TimeOfDay => {
667                let (backs, largest) = steps_back(&column.values);
668                if backs > 0 {
669                    notes.push(format!(
670                        "the logger's time of day, {:?}, goes back {backs} times, by up to \
671                         {largest:.3} s: it is kept as written, and `Flight_Time_(s)` is the clock",
672                        short(&column.name)
673                    ));
674                }
675            }
676            Role::Value(Quantity::InertialAltitude, _) => {
677                let wraps = column
678                    .values
679                    .windows(2)
680                    .filter(|pair| (pair[1] - pair[0]).abs() / FOOT_M > WRAP_STEP_FT)
681                    .count();
682                if wraps > 0 {
683                    notes.push(format!(
684                        "{:?} steps by more than 32,768 ft between two rows {wraps} times, as a \
685                         16-bit count of feet does when it wraps. It is kept as written",
686                        short(&column.name)
687                    ));
688                }
689            }
690            _ => {}
691        }
692    }
693
694    let altitude = columns.iter().find(|c| c.key == "baro_altitude_agl_(feet)");
695    if let Some(altitude) = altitude {
696        log.time_s.clone_from(&time_s);
697        log.altitude_m.clone_from(&altitude.values);
698        log.temperature_k = columns
699            .iter()
700            .find(|c| c.key == "temperature_(f)")
701            .map(|c| c.values.clone());
702        log.battery_v = columns
703            .iter()
704            .find(|c| c.key == "batt_volts")
705            .map(|c| c.values.clone());
706    } else {
707        file_notes.push(
708            "the file has no `Baro_Altitude_AGL_(feet)`, so the record's altitude track is empty. \
709             A Blue Raven's high-rate file holds its inertial sensors only, and the low-rate file \
710             of the same flight holds the altitude"
711                .to_owned(),
712        );
713    }
714
715    for column in columns {
716        if column.role == Role::Clock {
717            continue;
718        }
719        log.channels.push(Channel {
720            quantity: column.quantity(),
721            column: column.name,
722            time_s: time_s.clone(),
723            values: column.values,
724        });
725    }
726    log.notes.extend(file_notes);
727    log.notes.extend(notes.into_vec());
728    log
729}
730
731/// How many times a list of times of day goes back, and the largest step back, s.
732fn steps_back(values: &[f64]) -> (usize, f64) {
733    values
734        .windows(2)
735        .map(|pair| pair[0] - pair[1])
736        .filter(|back| *back > 0.0)
737        .fold((0, 0.0), |(count, largest), back| {
738            (count + 1, f64::max(largest, back))
739        })
740}
741
742/// The notes on units no header states: one per decided kind the file holds, its columns, the
743/// decision, and this file's evidence.
744fn decided_notes(columns: &[Column], time_s: &[f64]) -> Vec<String> {
745    let find = |key: &str| columns.iter().find(|c| c.key == key);
746    let altitude = find("baro_altitude_agl_(feet)");
747    let kinds = [
748        (
749            Decided::Velocity,
750            "feet per second",
751            "the manual and the summary",
752        ),
753        (Decided::Inertial, "feet", "the manual and the summary"),
754        (
755            Decided::Gyro,
756            "degrees per second",
757            "the manual and the summary",
758        ),
759        (
760            Decided::Accel,
761            "standard gravities",
762            "the manual and the pad",
763        ),
764    ];
765    let mut notes = Vec::new();
766    for (kind, unit, source) in kinds {
767        let names: Vec<String> = columns
768            .iter()
769            .filter(|c| c.decided == Some(kind))
770            .map(|c| format!("`{}`", short(&c.name)))
771            .collect();
772        if names.is_empty() {
773            continue;
774        }
775        let evidence = match kind {
776            Decided::Velocity => velocity_evidence(find("velocity_up"), altitude, time_s),
777            Decided::Inertial => inertial_evidence(find("inertial_altitude"), altitude),
778            Decided::Gyro => gyro_evidence(columns),
779            Decided::Accel => {
780                accel_evidence([find("accel_x"), find("accel_y"), find("accel_z")], time_s)
781            }
782        };
783        notes.push(format!(
784            "{} read in {unit}, from {source}: {evidence}",
785            list(&names)
786        ));
787    }
788    if let Some(current) = find("current") {
789        notes.push(current_note(current));
790    }
791    notes
792}
793
794/// The most names a decided-unit note lists; past it, the rest are counted.
795const MAX_LISTED: usize = 6;
796
797/// Names joined as `a`, `a and b`, or `a, b and c`; past [`MAX_LISTED`], the first few and a
798/// count of the rest, so that a header repeating a name many times keeps its note short.
799fn list(names: &[String]) -> String {
800    if names.len() > MAX_LISTED {
801        let shown = MAX_LISTED - 1;
802        return format!(
803            "{} and {} more columns",
804            names[..shown].join(", "),
805            names.len() - shown
806        );
807    }
808    match names {
809        [] => String::new(),
810        [only] => only.clone(),
811        [rest @ .., last] => format!("{} and {last}", rest.join(", ")),
812    }
813}
814
815/// The highest finite value of a list and its place.
816fn highest(values: &[f64]) -> Option<(usize, f64)> {
817    values
818        .iter()
819        .copied()
820        .enumerate()
821        .filter(|(_, value)| value.is_finite())
822        .fold(None, |best, (index, value)| match best {
823            Some((_, top)) if top >= value => best,
824            _ => Some((index, value)),
825        })
826}
827
828/// `Velocity_Up` integrated over the climb to the barometer's highest sample, against the
829/// barometer's rise over the same rows, both in feet.
830fn velocity_evidence(up: Option<&Column>, altitude: Option<&Column>, time_s: &[f64]) -> String {
831    let manual = "the manual gives the USB download's velocities in ft/sec";
832    let (Some(up), Some(altitude)) = (up, altitude) else {
833        return format!(
834            "{manual}; the file has no `Velocity_Up` and barometric altitude to compare"
835        );
836    };
837    let Some((peak, top)) = highest(&altitude.values) else {
838        return format!("{manual}; the file's barometric altitude has no value");
839    };
840    let first = altitude.values.iter().find(|value| value.is_finite());
841    let rise_ft = first.map_or(f64::NAN, |first| (top - first) / FOOT_M);
842    let climbed_ft: f64 = (1..=peak)
843        .filter_map(|index| {
844            let (v0, v1) = (up.values.get(index - 1)?, up.values.get(index)?);
845            let dt = time_s.get(index)? - time_s.get(index - 1)?;
846            (v0.is_finite() && v1.is_finite()).then(|| 0.5 * (v0 + v1) * dt / FOOT_M)
847        })
848        .sum();
849    if rise_ft.is_finite() && rise_ft > 0.0 {
850        format!(
851            "over the climb to the barometer's highest sample, `Velocity_Up` integrates to \
852             {climbed_ft:.0} ft against the barometer's rise of {rise_ft:.0} ft, a ratio of {:.2}",
853            climbed_ft / rise_ft
854        )
855    } else {
856        format!("{manual}; the barometric altitude doesn't rise to compare with")
857    }
858}
859
860/// `Inertial_Altitude`'s peak against the barometer's, both in feet.
861fn inertial_evidence(inertial: Option<&Column>, altitude: Option<&Column>) -> String {
862    let manual = "the manual gives the USB download's inertial altitude and ranges in feet";
863    let peaks = inertial
864        .and_then(|c| highest(&c.values))
865        .zip(altitude.and_then(|c| highest(&c.values)));
866    match peaks {
867        Some(((_, inertial), (_, baro))) => format!(
868            "`Inertial_Altitude` peaks at {:.0} ft against the barometric altitude's {:.0} ft",
869            inertial / FOOT_M,
870            baro / FOOT_M
871        ),
872        None => format!("{manual}; the file has no inertial and barometric peaks to compare"),
873    }
874}
875
876/// The largest gyro rate in the file, against the gyros' stated range.
877fn gyro_evidence(columns: &[Column]) -> String {
878    let largest = columns
879        .iter()
880        .filter(|c| c.decided == Some(Decided::Gyro))
881        .flat_map(|c| c.values.iter())
882        .filter(|value| value.is_finite())
883        .fold(0.0_f64, |largest, value| largest.max(value.abs()));
884    format!(
885        "the largest rate in the file is {largest:.0}, against the gyros' range of ±2000 deg/sec \
886         the manual gives"
887    )
888}
889
890/// The median magnitude of the three accelerations on the pad, in g: over the rows before
891/// liftoff (a negative `Flight_Time_(s)`), or the first [`PAD_ROWS`] rows if there are none.
892fn accel_evidence(axes: [Option<&Column>; 3], time_s: &[f64]) -> String {
893    let [Some(x), Some(y), Some(z)] = axes else {
894        return "the file lacks an axis to take the magnitude from; the manual gives the USB \
895                download's accelerations in G"
896            .to_owned();
897    };
898    let before = time_s.iter().take_while(|time| **time < 0.0).count();
899    let (rows, which) = if before > 0 {
900        (before, format!("the {before} rows before liftoff"))
901    } else {
902        let rows = time_s.len().min(PAD_ROWS);
903        (rows, format!("the first {rows} rows"))
904    };
905    let mut magnitudes: Vec<f64> = (0..rows)
906        .filter_map(|i| {
907            let g =
908                (x.values.get(i)?.powi(2) + y.values.get(i)?.powi(2) + z.values.get(i)?.powi(2))
909                    .sqrt()
910                    / STANDARD_GRAVITY_MPS2;
911            g.is_finite().then_some(g)
912        })
913        .collect();
914    magnitudes.sort_by(f64::total_cmp);
915    match magnitudes.get(magnitudes.len() / 2) {
916        Some(median) => format!(
917            "the median magnitude of the three axes over {which} is {median:.3}, where a logger \
918             at rest reads 1 g"
919        ),
920        None => format!("the three axes have no value over {which} to take the magnitude from"),
921    }
922}
923
924/// The note on `Current`, kept as written: how often it reads other than 0, and its largest value.
925fn current_note(current: &Column) -> String {
926    let values = &current.values[..];
927    let finite = values.iter().filter(|value| value.is_finite()).count();
928    let nonzero = values
929        .iter()
930        .filter(|value| value.is_finite() && **value != 0.0)
931        .count();
932    let largest = values
933        .iter()
934        .filter(|value| value.is_finite())
935        .fold(0.0_f64, |largest, value| largest.max(value.abs()));
936    format!(
937        "`{}` kept as written, in a unit no source states. It is other than 0 in {nonzero} of \
938         {finite} rows, at most {largest:.3}. Amperes would fit the manual's limit of about 4 A on \
939         the board's current. The USB download's milliamperes would not",
940        short(&current.name)
941    )
942}
943
944fn syntax(line: usize, message: String) -> LogError {
945    LogError::Syntax {
946        format: FORMAT,
947        line,
948        message,
949    }
950}
951
952#[cfg(test)]
953mod tests {
954    use super::*;
955
956    /// The low-rate file's first 45 columns, with the fifth register's name as most files write it.
957    const LOW_LEAD: &str = "Year,Month,Day,Time,Flight_Time_(s),Sync,Temperature_(F),Baro_Press_(atm),\
958        Baro_Altitude_ASL_(feet),Baro_Altitude_AGL_(feet),Batt_Volts,Apo_Volts,Main_Volts,3rd_Volts,\
959        4th_Volts,Velocity_Up,Velocity_DR,Velocity_CR,Inertial_Altitude,Inertial_DR_Position,\
960        Inertial_CR_position,Tilt_Angle_(deg),Future_Angle_(deg),Roll_Angle_(deg),Reserved_1,\
961        Reserved_2,Reserved_3,Rocket_FER_Hex,Apo_FER_H  ex,Main_FER_Hex,3rd_FER_Hex,4th_FER_Hex,\
962        Liftoff,Apogee,Press_Increasing,Burnout_Coast,Apo_fired,Main_fired,3rd_fired,4th_fired,\
963        Normal_Ascent,Accel_Vel_LE_0,ECI_Vvel_le_0,Tilt Exceeded 90deg,Reserved";
964
965    /// One output channel's condition flags, repeated for each of the four.
966    const CHANNEL_FLAGS: &str = "LT_AGL1,GT_AGL2,LT_FANG1,GT_FANG2,GT_FUTANG,LT_TVAL1,GT_TVAL2,\
967        LT_VEL1,GT_VEL2,LT_BVEL1,GT_BURN,Armed,Reserved,Reserved";
968
969    const HIGH_HEADER: &str = "Year,Month,Day,Time,Flight_Time_(s),Sync,Gyro_X,Gyro_Y,Gyro_Z,\
970        Accel_X,Accel_Y,Accel_Z,Quat_1,Quat_2,Quat_3,Quat_4,Aux_Volts,Current";
971
972    fn low_header() -> String {
973        format!("{LOW_LEAD}{}", format!(",{CHANNEL_FLAGS}").repeat(4))
974    }
975
976    /// A low-rate row: its time, time of day, altitude above the pad in feet, upward velocity in
977    /// ft/s, and the rocket's 13 flags, `Liftoff` first; the registers written from the flags.
978    fn low_row(time: f64, of_day: &str, agl_ft: f64, up_ft_s: f64, flags: [u8; 13]) -> String {
979        let register: u32 = flags
980            .iter()
981            .enumerate()
982            .map(|(bit, flag)| u32::from(*flag) << bit)
983            .sum();
984        let flags: Vec<String> = flags.iter().map(u8::to_string).collect();
985        format!(
986            "2026,4,18,{of_day},{time},0,50,0.95,{},{agl_ft},4.1,4.0,4.0,0,0,{up_ft_s},2,-1,{agl_ft},\
987             10,-3,2.5,3,40,0,0,0,{register:x},0,0,0,0,{}{}",
988            1000.0 + agl_ft,
989            flags.join(","),
990            ",0".repeat(56)
991        )
992    }
993
994    fn high_row(time: f64, of_day: &str, current: &str) -> String {
995        format!("2026,4,18,{of_day},{time},0,1.5,-2,300,0.6,0,0.8,0,0,0.6,0.8,0.02,{current}")
996    }
997
998    fn close(a: f64, b: f64) -> bool {
999        (a - b).abs() <= 1e-9 * b.abs().max(1.0)
1000    }
1001
1002    fn channel<'a>(log: &'a FlightLog, column: &str) -> &'a Channel {
1003        log.channels
1004            .iter()
1005            .find(|channel| channel.column == column)
1006            .unwrap()
1007    }
1008
1009    const NO_FLAGS: [u8; 13] = [0; 13];
1010    const LIFTOFF: [u8; 13] = [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0];
1011    const APOGEE: [u8; 13] = [1, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0];
1012
1013    #[test]
1014    fn the_app_header_is_recognized_by_its_six_first_columns() {
1015        assert!(recognizes(&format!("\u{feff}\r\n{}\n", low_header())));
1016        assert!(recognizes(HIGH_HEADER));
1017        assert!(recognizes(
1018            "Year, Month, Day, Time, Flight_Time_(s), Sync, Gyro_X\n"
1019        ));
1020        for other in [
1021            "",
1022            "Year,Month,Day,Time,Flight_Time_(s),Sync\n",
1023            "Year,Month,Day,Time,Flight_Time_(s),Axial Accel (Gs)\n",
1024            "Time@Axial Accel (Gs),Axial Accel (Gs),bILBA\n",
1025            "Time,Altitude,Velocity\n",
1026            "year,month,day,time,flight_time_(s),sync,x\n",
1027        ] {
1028            assert!(!recognizes(other), "{other:?}");
1029        }
1030    }
1031
1032    /// The Raven's FIP check runs first in the importer, on a header that opens with `Time` and
1033    /// names `Axial Accel (Gs)`: a Blue Raven low-rate header naming that column still reads as
1034    /// a Blue Raven's.
1035    #[test]
1036    fn a_low_rate_header_naming_the_ravens_axial_accel_is_a_blue_ravens() {
1037        let header =
1038            low_header().replace("3rd_Volts,4th_Volts", "Axial Accel (Gs),Lateral Accel (Gs)");
1039        let text = format!(
1040            "{header}\n{}\n",
1041            low_row(0.0, "10:00:00.000", 0.0, 0.0, NO_FLAGS)
1042        );
1043        assert_eq!(
1044            crate::import::detect(text.as_bytes()),
1045            Some(LogFormat::BlueRavenCsv)
1046        );
1047        let log = crate::import::read(text.as_bytes()).unwrap();
1048        let axial = channel(&log, "Axial Accel (Gs)");
1049        assert_eq!(axial.quantity, Quantity::Acceleration);
1050        assert_eq!(axial.values, [0.0]);
1051    }
1052
1053    /// The low-rate file: every column but the clock a channel in the file's order and in SI,
1054    /// the primary track the barometer's, the registers read as hexadecimal, and events where
1055    /// a moment's flag rises.
1056    #[test]
1057    fn reads_a_low_rate_file() {
1058        let text = format!(
1059            "{}\n{}\n{}\n{}\n{}\n",
1060            low_header(),
1061            low_row(-0.04, "10:00:00.000", 0.0, 0.0, NO_FLAGS),
1062            low_row(-0.02, "10:00:00.020", 0.5, 0.0, NO_FLAGS),
1063            low_row(0.0, "10:00:00.040", 1.0, 30.0, LIFTOFF),
1064            low_row(0.02, "10:00:00.060", 2.0, 60.0, APOGEE),
1065        );
1066        let log = read(&text).unwrap();
1067        assert_eq!(log.format, LogFormat::BlueRavenCsv);
1068        assert_eq!(log.logger, "Featherweight Blue Raven");
1069        assert_eq!(log.channels.len(), 100);
1070        assert_eq!(log.channels[4].column, "Sync", "the clock is no channel");
1071        assert_eq!(log.time_s, [-0.04, -0.02, 0.0, 0.02]);
1072        assert!(close(log.altitude_m[3], 2.0 * FOOT_M));
1073        assert!(log.vertical_speed_m_s.is_none());
1074        assert!(close(log.temperature_k.as_ref().unwrap()[0], 283.15));
1075        assert_eq!(log.battery_v.as_deref(), Some(&[4.1; 4][..]));
1076
1077        let of_day = channel(&log, "Time");
1078        assert_eq!(of_day.quantity, Quantity::TimeOfDay);
1079        assert!(close(of_day.values[1], 36_000.02));
1080        assert!(close(
1081            channel(&log, "Baro_Press_(atm)").values[0],
1082            0.95 * 101_325.0
1083        ));
1084        let up = channel(&log, "Velocity_Up");
1085        assert_eq!(up.quantity, Quantity::Speed);
1086        assert!(close(up.values[3], 60.0 * FOOT_M));
1087        assert_eq!(
1088            channel(&log, "Inertial_DR_Position").quantity,
1089            Quantity::Distance
1090        );
1091        assert_eq!(channel(&log, "Roll_Angle_(deg)").values[0], 40.0);
1092        assert_eq!(channel(&log, "Reserved_1").quantity, Quantity::Unrecognized);
1093        // `1` | `2` | `16` = 0x13: Liftoff, Apogee and Apo_fired.
1094        let register = channel(&log, "Rocket_FER_Hex");
1095        assert_eq!(register.quantity, Quantity::Number);
1096        assert_eq!(register.values, [0.0, 0.0, 1.0, 19.0]);
1097        assert_eq!(channel(&log, "Apo_FER_H  ex").quantity, Quantity::Number);
1098        let names: Vec<(&str, f64)> = log
1099            .events
1100            .iter()
1101            .map(|event| (event.name.as_str(), event.time_s))
1102            .collect();
1103        assert_eq!(
1104            names,
1105            [("Liftoff", 0.0), ("Apogee", 0.02), ("Apo_fired", 0.02)]
1106        );
1107        assert_eq!(
1108            log.channels
1109                .iter()
1110                .filter(|c| c.column == "LT_AGL1")
1111                .count(),
1112            4
1113        );
1114
1115        assert!(
1116            log.notes[0].starts_with(
1117                "`Velocity_Up`, `Velocity_DR` and `Velocity_CR` read in feet per second, from the \
1118                 manual and the summary: over the climb to the barometer's highest sample, \
1119                 `Velocity_Up` integrates to 1 ft against the barometer's rise of 2 ft"
1120            ),
1121            "{:?}",
1122            log.notes
1123        );
1124        assert!(log.notes[1].starts_with(
1125            "`Inertial_Altitude`, `Inertial_DR_Position` and `Inertial_CR_position` read in feet, \
1126             from the manual and the summary: `Inertial_Altitude` peaks at 2 ft against the \
1127             barometric altitude's 2 ft"
1128        ));
1129        assert_eq!(
1130            log.notes[2],
1131            "12 columns named `Reserved…` hold what the manual doesn't describe, and were kept as \
1132             written"
1133        );
1134        assert_eq!(log.notes.len(), 3, "{:?}", log.notes);
1135    }
1136
1137    /// The high-rate file: no altitude, so an empty primary track with a note, and the inertial
1138    /// sensors in SI with a note on each kind's unit.
1139    #[test]
1140    fn reads_a_high_rate_file_with_an_empty_track() {
1141        let text = format!(
1142            "{HIGH_HEADER}\r\n{}\r\n{}\r\n{}\r\n",
1143            high_row(-0.004, "10:00:00.000", "0.000"),
1144            high_row(-0.002, "10:00:00.000", "0.000"),
1145            high_row(0.0, "10:00:00.004", "2.5"),
1146        );
1147        let log = read(&text).unwrap();
1148        assert!(log.time_s.is_empty() && log.altitude_m.is_empty());
1149        assert!(log.temperature_k.is_none() && log.battery_v.is_none());
1150        assert_eq!(log.channels.len(), 17);
1151        let gyro = channel(&log, "Gyro_Z");
1152        assert_eq!(gyro.quantity, Quantity::AngularRate);
1153        assert_eq!(gyro.time_s, [-0.004, -0.002, 0.0]);
1154        assert_eq!(gyro.values, [300.0; 3]);
1155        let accel = channel(&log, "Accel_Z");
1156        assert!(close(accel.values[0], 0.8 * STANDARD_GRAVITY_MPS2));
1157        assert_eq!(channel(&log, "Quat_4").quantity, Quantity::Number);
1158        assert_eq!(channel(&log, "Aux_Volts").quantity, Quantity::Voltage);
1159        let current = channel(&log, "Current");
1160        assert_eq!(current.quantity, Quantity::Unrecognized);
1161        assert_eq!(current.values, [0.0, 0.0, 2.5]);
1162        assert_eq!(
1163            log.notes,
1164            [
1165                "`Gyro_X`, `Gyro_Y` and `Gyro_Z` read in degrees per second, from the manual and \
1166                 the summary: the largest rate in the file is 300, against the gyros' range of \
1167                 ±2000 deg/sec the manual gives",
1168                "`Accel_X`, `Accel_Y` and `Accel_Z` read in standard gravities, from the manual \
1169                 and the pad: the median magnitude of the three axes over the 2 rows before \
1170                 liftoff is 1.000, where a logger at rest reads 1 g",
1171                "`Current` kept as written, in a unit no source states. It is other than 0 in 1 of \
1172                 3 rows, at most 2.500. Amperes would fit the manual's limit of about 4 A on the \
1173                 board's current. The USB download's milliamperes would not",
1174                "the file has no `Baro_Altitude_AGL_(feet)`, so the record's altitude track is \
1175                 empty. A Blue Raven's high-rate file holds its inertial sensors only, and the \
1176                 low-rate file of the same flight holds the altitude",
1177            ]
1178        );
1179        assert!(log.events.is_empty());
1180        // The readings withhold on a Blue Raven's record, so an empty track reaches nothing that
1181        // would index it.
1182        let readings = crate::readings::read(&log);
1183        assert!(readings.apogee.value().is_none());
1184    }
1185
1186    /// Each decided kind's note keeps the same words before its colon whatever the file's
1187    /// numbers, so a survey can count them; without the rows to compare, the note says so.
1188    #[test]
1189    fn decided_notes_keep_their_prefix() {
1190        let text = format!("{HIGH_HEADER}\n{}\n", high_row(0.5, "10:00:00.000", "0"));
1191        let log = read(&text).unwrap();
1192        assert!(log.notes[1].starts_with(
1193            "`Accel_X`, `Accel_Y` and `Accel_Z` read in standard gravities, from the manual and \
1194             the pad: the median magnitude of the three axes over the first 1 rows is 1.000"
1195        ));
1196        let header =
1197            "Year,Month,Day,Time,Flight_Time_(s),Sync,Velocity_Up,Inertial_Altitude,Accel_X";
1198        let log = read(&format!("{header}\n2026,1,1,0:00:00,0,0,1,1,1\n")).unwrap();
1199        assert_eq!(
1200            log.notes[..3],
1201            [
1202                "`Velocity_Up` read in feet per second, from the manual and the summary: the \
1203                 manual gives the USB download's velocities in ft/sec; the file has no \
1204                 `Velocity_Up` and barometric altitude to compare",
1205                "`Inertial_Altitude` read in feet, from the manual and the summary: the manual \
1206                 gives the USB download's inertial altitude and ranges in feet; the file has no \
1207                 inertial and barometric peaks to compare",
1208                "`Accel_X` read in standard gravities, from the manual and the pad: the file lacks \
1209                 an axis to take the magnitude from; the manual gives the USB download's \
1210                 accelerations in G",
1211            ]
1212        );
1213    }
1214
1215    /// A flag already set on the first row gives no event, with a note; a flag that rises more
1216    /// often than the cap gives the first [`MAX_EVENTS_PER_FLAG`] and counts the rest; a
1217    /// condition flag gives none.
1218    #[test]
1219    fn flags_give_events_only_where_they_rise() {
1220        let mut text = low_header();
1221        let mut main = [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0];
1222        for row in 0..40 {
1223            main[5] = u8::from(row % 2 == 1);
1224            main[10] = u8::from(row % 2 == 1);
1225            text.push('\n');
1226            text.push_str(&low_row(f64::from(row), "10:00:00", 0.0, 0.0, main));
1227        }
1228        let log = read(&text).unwrap();
1229        assert_eq!(log.events.len(), MAX_EVENTS_PER_FLAG);
1230        assert!(log.events.iter().all(|event| event.name == "Main_fired"));
1231        assert_eq!(log.events[0].time_s, 1.0);
1232        assert_eq!(log.events[15].time_s, 31.0);
1233        let notes = log.notes.join("\n");
1234        assert!(
1235            notes.contains("the flag \"Liftoff\" is already 1 on the first row"),
1236            "{notes}"
1237        );
1238        assert!(
1239            notes.contains("the flag \"Main_fired\" rises 4 more times than the 16 kept"),
1240            "{notes}"
1241        );
1242    }
1243
1244    #[test]
1245    fn a_time_of_day_that_goes_back_is_kept_with_a_note() {
1246        let text = format!(
1247            "{HIGH_HEADER}\n{}\n{}\n{}\n{}\n",
1248            high_row(0.0, "23:59:59.990", "0"),
1249            high_row(0.1, "0:00:00.000", "0"),
1250            high_row(0.2, "0:00:00.010", "0"),
1251            high_row(0.3, "0:00:00.005", "0"),
1252        );
1253        let log = read(&text).unwrap();
1254        let of_day = channel(&log, "Time");
1255        assert!(close(of_day.values[0], 86_399.99));
1256        assert_eq!(of_day.values[1], 0.0);
1257        assert!(
1258            log.notes.contains(
1259                &"the logger's time of day, \"Time\", goes back 2 times, by up to 86399.990 s: it \
1260                  is kept as written, and `Flight_Time_(s)` is the clock"
1261                    .to_owned()
1262            ),
1263            "{:?}",
1264            log.notes
1265        );
1266    }
1267
1268    #[test]
1269    fn a_note_lists_a_few_names() {
1270        let names: Vec<String> = (0..9).map(|i| format!("`g{i}`")).collect();
1271        assert_eq!(list(&names[..1]), "`g0`");
1272        assert_eq!(list(&names[..3]), "`g0`, `g1` and `g2`");
1273        assert_eq!(list(&names[..6]), "`g0`, `g1`, `g2`, `g3`, `g4` and `g5`");
1274        assert_eq!(
1275            list(&names),
1276            "`g0`, `g1`, `g2`, `g3`, `g4` and 4 more columns"
1277        );
1278    }
1279
1280    #[test]
1281    fn times_of_day_and_registers_are_read_strictly() {
1282        assert_eq!(time_of_day("00:00:00"), Some(0.0));
1283        assert!(close(time_of_day("9:05:07.25").unwrap(), 32_707.25));
1284        assert!(close(time_of_day("23:59:60.5").unwrap(), 86_400.5));
1285        for bad in [
1286            "",
1287            "12:00",
1288            "12:00:00:00",
1289            "24:00:00",
1290            "12:60:00",
1291            "12:5:00",
1292            "12:00:61",
1293            "123:00:00",
1294            "12:00:00.",
1295            "12:00:00.x",
1296            "-1:00:00",
1297            "12:00:+1",
1298            "1e1:00:00",
1299        ] {
1300            assert_eq!(time_of_day(bad), None, "{bad:?}");
1301        }
1302        assert_eq!(hex("0"), Some(0.0));
1303        assert_eq!(hex("1a5"), Some(421.0));
1304        assert_eq!(hex("0x1A5"), Some(421.0));
1305        assert_eq!(hex("fffffffffffff"), Some(4_503_599_627_370_495.0));
1306        for bad in ["", "0x", "g", "-1", "1.5", "ffffffffffffff"] {
1307            assert_eq!(hex(bad), None, "{bad:?}");
1308        }
1309    }
1310
1311    /// An empty cell, or one that isn't what its column holds, is a gap counted in a note; a
1312    /// short row's missing cells are gaps, counted.
1313    #[test]
1314    fn gaps_and_short_rows_are_counted() {
1315        let text = format!(
1316            "{HIGH_HEADER}\n\
1317             2026,4,18,noon,0,0,x,,300,0.6,0,0.8,0,0,0.6,0.8,0.02,0\n\
1318             2026,4,18,10:00:00,0.002,0,1,2,3\n\
1319             2026,4,18,10:00:00,0.004\n"
1320        );
1321        let log = read(&text).unwrap();
1322        assert!(channel(&log, "Time").values[0].is_nan());
1323        let gyro_x = channel(&log, "Gyro_X");
1324        assert!(gyro_x.values[0].is_nan());
1325        assert_eq!(gyro_x.values[1], 1.0);
1326        assert!(gyro_x.values[2].is_nan());
1327        assert!(channel(&log, "Current").values[1].is_nan());
1328        let notes = log.notes.join("\n");
1329        for expected in [
1330            "the column \"Time\" holds 1 cells that are empty or not what it holds, such as \
1331             \"noon\": they are gaps",
1332            "the column \"Gyro_X\" holds 1 cells that are empty or not what it holds, such as \
1333             \"x\"",
1334            "the column \"Gyro_Y\" holds 1 cells that are empty or not what it holds, such as \
1335             \"\"",
1336            "2 rows, the first on line 3, have fewer cells than the header's 18: the cells they \
1337             leave out are gaps",
1338        ] {
1339            assert!(notes.contains(expected), "{expected}\n{notes}");
1340        }
1341    }
1342
1343    /// `Inertial_Altitude` stepping by more than half a 16-bit span of feet is noted, and kept.
1344    #[test]
1345    fn an_inertial_wrap_is_noted() {
1346        let header = "Year,Month,Day,Time,Flight_Time_(s),Sync,Inertial_Altitude";
1347        let text = format!("{header}\n2026,1,1,0:00:00,0,0,32767\n2026,1,1,0:00:00,1,0,-32768\n");
1348        let log = read(&text).unwrap();
1349        assert!(close(
1350            channel(&log, "Inertial_Altitude").values[1],
1351            -32_768.0 * FOOT_M
1352        ));
1353        assert!(log.notes.contains(
1354            &"\"Inertial_Altitude\" steps by more than 32,768 ft between two rows 1 times, as a \
1355              16-bit count of feet does when it wraps. It is kept as written"
1356                .to_owned()
1357        ));
1358    }
1359
1360    /// Each refusal names its line and what is wrong.
1361    #[test]
1362    fn malformed_files_are_refused_where_they_go_wrong() {
1363        let row = |time: &str| format!("2026,4,18,10:00:00,{time},0,1,1,1,1,1,1,0,0,0,1,0,0");
1364        let cases = [
1365            (String::new(), "the file is empty"),
1366            ("\n\r\n".to_owned(), "the file is empty"),
1367            ("Time,Altitude\n0,0\n".to_owned(), "isn't the app's header"),
1368            (format!("{HIGH_HEADER}\n"), "no data rows"),
1369            (
1370                "Year,Month,Day,Time,Flight_Time_(s),Sync,,x\n".to_owned(),
1371                "line 1: the header's column 7 has no name",
1372            ),
1373            (
1374                format!("{HIGH_HEADER}\n{},9\n", row("0")),
1375                "line 2: the row has 19 cells, more than the header's 18",
1376            ),
1377            (
1378                format!("{HIGH_HEADER}\n{}\nx,y\n", row("0")),
1379                "line 3: the row ends after 2 cells, before its \"Flight_Time_(s)\"",
1380            ),
1381            (
1382                format!("{HIGH_HEADER}\n{}\n", row("soon")),
1383                "line 2: the time \"soon\" in cell 5 isn't a finite number",
1384            ),
1385            (
1386                format!("{HIGH_HEADER}\n{}\n", row("")),
1387                "line 2: the time \"\" in cell 5",
1388            ),
1389            (
1390                format!("{HIGH_HEADER}\n{}\n\n{}\n", row("1"), row("1")),
1391                "line 4: the time 1 s doesn't come after the one above it, 1 s",
1392            ),
1393            (
1394                format!("{HIGH_HEADER}\n{}\n{}\n", row("1"), row("0.5")),
1395                "line 3: the time 0.5 s doesn't come after",
1396            ),
1397        ];
1398        for (text, expected) in cases {
1399            let error = read(&text).unwrap_err().to_string();
1400            assert!(error.contains(expected), "{text:?}: {error}");
1401        }
1402        let LogError::NotThisFormat { format, .. } = read("x").unwrap_err() else {
1403            panic!("refused for another reason");
1404        };
1405        assert_eq!(format, FORMAT);
1406    }
1407
1408    /// A value near the largest `f64` is finite as written and infinite once converted: in g to
1409    /// m/s², in atmospheres to pascals. Each is refused on its line (ADR-258 §3).
1410    #[test]
1411    fn a_value_its_conversion_makes_infinite_is_refused() {
1412        let high = format!(
1413            "{HIGH_HEADER}\n{}\n{}\n",
1414            high_row(0.0, "10:00:00", "0.1"),
1415            high_row(0.002, "10:00:00", "0.1").replacen(",300,0.6,", ",300,1.7e308,", 1)
1416        );
1417        assert_eq!(
1418            read(&high).unwrap_err().to_string(),
1419            "Blue Raven CSV line 3: the column Accel_X holds a value too large for its unit's \
1420             conversion to SI"
1421        );
1422        let low = format!(
1423            "{}\n{}\n",
1424            low_header(),
1425            low_row(0.0, "10:00:00", 0.0, 0.0, NO_FLAGS).replacen(",50,0.95,", ",50,-1.7e308,", 1)
1426        );
1427        assert_eq!(
1428            read(&low).unwrap_err().to_string(),
1429            "Blue Raven CSV line 2: the column Baro_Press_(atm) holds a value too large for its \
1430             unit's conversion to SI"
1431        );
1432    }
1433
1434    /// A header naming far more columns than its rows fill is refused before the reader allocates
1435    /// a gap for every cell left out.
1436    #[test]
1437    fn a_wide_header_over_short_rows_is_refused() {
1438        let wide: String = (0..20_000).map(|i| format!(",c{i}")).collect();
1439        let header = format!("Year,Month,Day,Time,Flight_Time_(s),Sync{wide}");
1440        let rows: String = (0..100).map(|i| format!("0,0,0,0,{i},0\n")).collect();
1441        let error = read(&format!("{header}\n{rows}")).unwrap_err().to_string();
1442        assert!(
1443            error.contains("line 5: the header names 20006 columns, and the 4 rows down to this one hold only 24 cells"),
1444            "{error}"
1445        );
1446    }
1447
1448    /// Lines end in CR, LF or both; a byte-order mark is dropped; blank lines are skipped.
1449    #[test]
1450    fn line_ends_and_marks() {
1451        let rows = [
1452            high_row(0.0, "10:00:00", "0"),
1453            high_row(0.002, "10:00:00", "0"),
1454        ];
1455        for end in ["\r", "\n", "\r\n"] {
1456            let text = format!(
1457                "\u{feff}{end}{HIGH_HEADER}{end}{}{end}{end}{}{end}",
1458                rows[0], rows[1]
1459            );
1460            let log = read(&text).unwrap();
1461            assert_eq!(log.channels[0].time_s, [0.0, 0.002], "{end:?}");
1462        }
1463    }
1464
1465    /// A header of many unknown columns keeps a short list of notes and counts the rest; the
1466    /// unit notes stay outside the cap.
1467    #[test]
1468    fn notes_stay_few() {
1469        let unknown: String = (0..100).map(|i| format!(",u{i}")).collect();
1470        let header = format!("Year,Month,Day,Time,Flight_Time_(s),Sync,Gyro_X{unknown}");
1471        let row = format!("2026,1,1,0:00:00,0,0,1{}", ",1".repeat(100));
1472        let log = read(&format!("{header}\n{row}\n")).unwrap();
1473        assert!(log.notes[0].starts_with("`Gyro_X` read in degrees per second"));
1474        assert_eq!(log.notes.len(), 1 + 1 + 20 + 1, "{:?}", log.notes);
1475        assert!(log.notes[1].starts_with("the file has no `Baro_Altitude_AGL_(feet)`"));
1476        assert!(
1477            log.notes[22].starts_with("and 80 more notes"),
1478            "{:?}",
1479            log.notes
1480        );
1481        assert_eq!(log.channels.len(), 106);
1482        assert_eq!(log.channels[105].quantity, Quantity::Unrecognized);
1483    }
1484
1485    proptest::proptest! {
1486        /// Any text is read or refused, never a panic; what is read has increasing times and a
1487        /// value for each on every channel.
1488        #[test]
1489        fn any_text_is_read_or_refused(
1490            rows in proptest::collection::vec("[-0-9.,:xaf ]{0,40}", 0..10),
1491            low in proptest::bool::ANY,
1492        ) {
1493            let header = if low { low_header() } else { HIGH_HEADER.to_owned() };
1494            let text = format!("{header}\n{}", rows.join("\n"));
1495            if let Ok(log) = read(&text) {
1496                proptest::prop_assert_eq!(log.time_s.len(), log.altitude_m.len());
1497                for channel in &log.channels {
1498                    proptest::prop_assert!(channel.time_s.windows(2).all(|pair| pair[1] > pair[0]));
1499                    proptest::prop_assert_eq!(channel.time_s.len(), channel.values.len());
1500                }
1501                for event in &log.events {
1502                    proptest::prop_assert!(event.time_s.is_finite());
1503                }
1504            }
1505        }
1506    }
1507}