Skip to main content

hpr_flightdata/
blueraven_usb.rs

1//! The Featherweight Blue Raven's flight data as its USB port downloads it: one `@ LOG_LOW` or
2//! `@ LOG_HIR` line a sample, each closed by a CRC, as a terminal program saves them.
3//!
4//! The Blue Raven records a low-rate set of data "recorded at 50 Hz" and a high-rate set
5//! "recorded at 500 Hz" for each flight (Featherweight, *Blue Raven User's Guide*, updated May 12
6//! 2026, p18). Besides the phone app's download ([`crate::blueraven`]), the logger's USB port
7//! sends either set to a serial terminal on a command, `<download l>` or `<download h>`, and the
8//! manual describes the lines it sends (Appendix A, p23–24). Each line "starts with the mnemonic
9//! `@ LOG_LOW` followed by the length of the string, and the time and date of the flight", then
10//! the sync code and the data. The manual ends the low-rate line with a "16b Buypass CRC code for
11//! line of text" (p23) and lists none for the high-rate line (p24), but the high-rate lines in the
12//! sample logs close with a CRC too, of the same kind:
13//!
14//! ```text
15//! @ LOG_HIR  139 2026  5 23 10:15:00.120   20    -15     42     -7     -1      3     98  -3000   1500    -40  29812      0      0 CRC: 7730
16//! @ LOG_LOW  211 2026  5 23 10:15:00.140  40 Bo:  7212 49655 V:  4105    22    21    20    23 Vel:     0     0     0 Pos:     0     0     0 ang:   12    5    0 FER:  400  1c1   c3   c1   c3   0   0   0 CRC: F7EB
17//! ```
18//!
19//! **Recognition.** A file is a download when one of its first 1,000 lines opens with `@ LOG_HIR`
20//! or `@ LOG_LOW`, holds no other `@ LOG_`, and closes with a CRC that checks (below); no other
21//! layout HPR Sim reads opens a line so.
22//!
23//! **Records and their checks.** A terminal saves what the port sends, and the sample logs show
24//! what that costs: a record whose `CRC: XXXX` and line end were lost runs on into the next one, on
25//! one line. So every line is cut before each `@ LOG_`, and each piece is a record only if it holds
26//! two things the logger wrote for it:
27//!
28//! - *Its CRC.* The piece closes with `CRC:` and four hexadecimal digits, the CRC-16 the manual
29//!   calls Buypass (polynomial `0x8005`, starting at 0, no reflection, no final XOR; its check value
30//!   on `123456789` is `0xFEE8`) of the piece's text from its `@` to its last character that
31//!   isn't a space before `CRC:`: the spaces inside the line count, and only the run of spaces
32//!   just before `CRC:` is left out. The example lines' CRCs are `7730` and `F7EB`. The manual says the CRC is "for line of text" but
33//!   not which characters it starts and ends at; this span is the one under which every CRC in
34//!   the sample files checks.
35//! - *Its length.* The number after the mnemonic must be the piece's length in bytes, from `@`
36//!   through the CRC's last digit, plus 2 for the line end the logger sends: `139` for a high-rate
37//!   line of 137 characters.
38//!
39//! A piece with no CRC, or whose CRC differs from its text, is dropped, and a note counts each
40//! kind: it can't be told from a record the capture damaged. So is a line holding no `@ LOG_`
41//! record, such as the live status line, `@ BLR_STAT`, which the port sends five times a second
42//! (p22), or text before a line's first record. A record whose CRC checks is the logger's, so
43//! anything else wrong in it refuses the file ([`LogError::Syntax`]), naming its line: a stated
44//! length that isn't its own, a mnemonic other than these two, a date or time that can't be one, a
45//! value that isn't a whole number (or, in `FER:`, hexadecimal digits), more than
46//! [`MAX_VALUES`] values or [`MAX_GROUPS`] groups, a label longer than [`MAX_LABEL_BYTES`], or a
47//! layout unlike the first record's, its kind or its groups and their
48//! counts, so that a file holding both downloads is refused too.
49//!
50//! **The clock.** Each record states the logger's date and time of day to the millisecond, `2026
51//! 5 23 10:15:00.120`; the record's clock counts from the first record's, and a time that doesn't
52//! increase is refused, naming its line. The manual says the date stamp "starts with the build
53//! time/date and increments from there", to be set by the phone (p22), so the date need not be the
54//! flight's: a note gives the first record's as written. `Year`, `Month`, `Day` and `Sync` are
55//! [`Quantity::Number`] channels and `Time` a [`Quantity::TimeOfDay`] one, as the app's CSV keeps
56//! them. The sync code is "a millisecond counter recorded in both the low-rate and high-rate data
57//! so that the two data sets can be aligned", which "rolls over every 250 msec" (p23).
58//!
59//! **The high-rate record** holds, after the sync code, "[gyro X deg/s x100] [gyro Y deg/s x100]
60//! [gyro Z deg/s x100] [Accel X Gs x100] [Accel Y Gs x100] [Accel Z Gs x100] [Quaternion X x 30000]
61//! [Quaternion Y x 30000] [Quaternion Z x 30000] [Quaternion magnitude x 30000]" (p24). The gyro
62//! rates are "raw data in the sensor axis", and the accelerations come from the ±32 g
63//! accelerometers below 32 g and from the high-range one above it. The quaternion is written "with
64//! the rotation axis first and the magnitude term fourth", "scaled up by a factor of 30,000 to fit
65//! into signed 16-bit integers".
66//!
67//! **The low-rate record** holds labeled groups (p23):
68//!
69//! | Group | The manual's fields, in its order | Read as |
70//! |---|---|---|
71//! | `Bo:` | temperature from the baro sensor; pressure in atm × 50,000 | the temperature as written, [`Quantity::Unrecognized`], as the manual states no unit for it here; the pressure in Pa |
72//! | `V:` | battery, Apo, Main, 3rd and 4th outputs, mV; output current, mA | V; A |
73//! | `Vel:` | upward, down-range and cross-range velocity, ft/s | m/s, [`Quantity::Speed`] |
74//! | `Pos:` | inertial altitude, down-range and cross-range position, ft | m: [`Quantity::InertialAltitude`], then [`Quantity::Distance`] |
75//! | `ang:` | tilt angle, deg × 10; roll angle, deg; future tilt angle, deg × 10 | degrees, [`Quantity::Angle`] |
76//! | `FER:` | the rocket's flight event register, then the Apo, Main, 3rd and 4th outputs' | the registers' bits, [`Quantity::Number`], from hexadecimal |
77//!
78//! The velocities and positions are "ground-relative inertial coordinates (rather than rocket
79//! axes)", and the registers "hex-encoded binary values that use one bit for each event" (p23–24);
80//! the manual doesn't say which bit is which event, so no [`Event`](crate::log::Event) is taken
81//! from them.
82//!
83//! **Counts unlike the manual's.** A logger's firmware need not write what the manual of the day
84//! lists: in the sample logs, a high-rate record holds 12 values where the manual lists 10, `V:` holds 5 where it lists 6, and `FER:` 8 where it lists 5. One rule takes
85//! them: a group holding at least the manual's count is read by the manual, in its order, and the
86//! values past it are kept as written, [`Quantity::Unrecognized`] (in `FER:`, registers of unknown
87//! meaning, [`Quantity::Number`]); a group holding fewer is kept as written whole, as nothing says
88//! which value is missing. A group the manual doesn't list is kept as written too. A value kept as
89//! written is named by its group and its place there, counted from 1, such as `V: 3` or `LOG_HIR
90//! 11`, and a note says so for each group. The maker's forum describes two more 500 Hz fields than
91//! the manual, the "deployment output current" and the "aux analog voltage" (Featherweight,
92//! *Blue Raven development thread*, rocketryforum.com, 2023-03-31), but not their order, so the
93//! high-rate record's 11th and 12th values stay as written.
94//!
95//! The sample logs' survey (`cargo xtask logs`) holds three parts of the reading to the file and
96//! the same rocket's other files: every high-rate record's quaternion, read from the 7th to the
97//! 10th value, has a norm within 2 of 30,000, as a unit quaternion cut to whole numbers must; the
98//! first `FER:` value's lowest bit, the one the app's files call `Liftoff`, first sets within 0.1 s
99//! after the three axes' acceleration first passes 3 g; and the pressure on the pad is within 2 %
100//! of the TeleMega's in the same rocket. The gyro rates, velocities, positions, angles and
101//! voltages are read by the manual's scales with no such check.
102//!
103//! The record has no barometric track, as the download writes the pressure, not an altitude:
104//! [`FlightLog::time_s`] and [`FlightLog::altitude_m`] are empty, as for the Raven's raw `.FIPa`,
105//! and every value is a channel.
106
107use hpr_core::gravity::STANDARD_GRAVITY_MPS2;
108
109use crate::error::LogError;
110use crate::log::{Channel, FlightLog, LogFormat, Quantity, Stated};
111use crate::perfectflite::FOOT_M;
112use crate::table::{numbered_lines, short};
113
114/// The format's name in errors.
115const FORMAT: &str = "Blue Raven USB download";
116
117/// How many of a file's first lines are searched for a record whose CRC checks.
118const RECOGNITION_LINES: usize = 1_000;
119
120/// The most values a record may hold after its sync code, over ten times the 24 of the sample
121/// logs' low-rate record; a file past it isn't a Blue Raven's.
122pub const MAX_VALUES: usize = 256;
123
124/// The most groups a low-rate record may hold, over twice the manual's 6, and the longest a
125/// group's label may be, bytes, four times the manual's longest, `Vel:`: so that a record's
126/// labels can't fill its columns' names, its notes or the time spent checking them.
127pub const MAX_GROUPS: usize = 16;
128/// See [`MAX_GROUPS`].
129pub const MAX_LABEL_BYTES: usize = 16;
130
131/// What opens every record.
132const OPENING: &str = "@ LOG_";
133
134/// The bytes a stated length counts past the record's text: the CR and LF the logger sends.
135const LINE_END_BYTES: usize = 2;
136
137/// The two records' mnemonics.
138const HIGH_RATE: &str = "LOG_HIR";
139const LOW_RATE: &str = "LOG_LOW";
140
141/// The label of the group whose values are hexadecimal.
142const REGISTERS: &str = "FER:";
143
144/// The CRC-16 the manual calls Buypass (also CRC-16/UMTS): polynomial `0x8005`, initial value 0,
145/// no reflection, no final XOR.
146pub(crate) fn crc16_buypass(bytes: &[u8]) -> u16 {
147    let mut crc: u16 = 0;
148    for &byte in bytes {
149        crc ^= u16::from(byte) << 8;
150        for _ in 0..8 {
151            crc = if crc & 0x8000 != 0 {
152                (crc << 1) ^ 0x8005
153            } else {
154                crc << 1
155            };
156        }
157    }
158    crc
159}
160
161/// One value's place in a record: its column's name, what it measures, and how the integer the
162/// file writes becomes the quantity's unit, divided by `per`, then multiplied by `unit`.
163struct Field {
164    column: &'static str,
165    quantity: Quantity,
166    per: f64,
167    unit: f64,
168}
169
170const fn field(column: &'static str, quantity: Quantity, per: f64, unit: f64) -> Field {
171    Field {
172        column,
173        quantity,
174        per,
175        unit,
176    }
177}
178
179/// One standard atmosphere, Pa.
180const ATMOSPHERE_PA: f64 = 101_325.0;
181
182/// The high-rate record's values after the sync code, as the manual lists them (p24).
183const HIGH_RATE_FIELDS: [Field; 10] = [
184    field("Gyro X", Quantity::AngularRate, 100.0, 1.0),
185    field("Gyro Y", Quantity::AngularRate, 100.0, 1.0),
186    field("Gyro Z", Quantity::AngularRate, 100.0, 1.0),
187    field(
188        "Accel X",
189        Quantity::Acceleration,
190        100.0,
191        STANDARD_GRAVITY_MPS2,
192    ),
193    field(
194        "Accel Y",
195        Quantity::Acceleration,
196        100.0,
197        STANDARD_GRAVITY_MPS2,
198    ),
199    field(
200        "Accel Z",
201        Quantity::Acceleration,
202        100.0,
203        STANDARD_GRAVITY_MPS2,
204    ),
205    field("Quaternion X", Quantity::Number, 30_000.0, 1.0),
206    field("Quaternion Y", Quantity::Number, 30_000.0, 1.0),
207    field("Quaternion Z", Quantity::Number, 30_000.0, 1.0),
208    field("Quaternion magnitude", Quantity::Number, 30_000.0, 1.0),
209];
210
211/// The low-rate record's groups, each its label and the manual's fields in its order (p23).
212const LOW_RATE_GROUPS: [(&str, &[Field]); 6] = [
213    (
214        "Bo:",
215        &[
216            field("Bo: temperature", Quantity::Unrecognized, 1.0, 1.0),
217            field("Bo: pressure", Quantity::Pressure, 50_000.0, ATMOSPHERE_PA),
218        ],
219    ),
220    (
221        "V:",
222        &[
223            field("V: battery", Quantity::Voltage, 1_000.0, 1.0),
224            field("V: Apo", Quantity::Voltage, 1_000.0, 1.0),
225            field("V: Main", Quantity::Voltage, 1_000.0, 1.0),
226            field("V: 3rd", Quantity::Voltage, 1_000.0, 1.0),
227            field("V: 4th", Quantity::Voltage, 1_000.0, 1.0),
228            field("V: current", Quantity::Current, 1_000.0, 1.0),
229        ],
230    ),
231    (
232        "Vel:",
233        &[
234            field("Vel: up", Quantity::Speed, 1.0, FOOT_M),
235            field("Vel: down-range", Quantity::Speed, 1.0, FOOT_M),
236            field("Vel: cross-range", Quantity::Speed, 1.0, FOOT_M),
237        ],
238    ),
239    (
240        "Pos:",
241        &[
242            field("Pos: altitude", Quantity::InertialAltitude, 1.0, FOOT_M),
243            field("Pos: down-range", Quantity::Distance, 1.0, FOOT_M),
244            field("Pos: cross-range", Quantity::Distance, 1.0, FOOT_M),
245        ],
246    ),
247    (
248        "ang:",
249        &[
250            field("ang: tilt", Quantity::Angle, 10.0, 1.0),
251            field("ang: roll", Quantity::Angle, 1.0, 1.0),
252            field("ang: future tilt", Quantity::Angle, 10.0, 1.0),
253        ],
254    ),
255    (
256        REGISTERS,
257        &[
258            field("FER: rocket", Quantity::Number, 1.0, 1.0),
259            field("FER: Apo", Quantity::Number, 1.0, 1.0),
260            field("FER: Main", Quantity::Number, 1.0, 1.0),
261            field("FER: 3rd", Quantity::Number, 1.0, 1.0),
262            field("FER: 4th", Quantity::Number, 1.0, 1.0),
263        ],
264    ),
265];
266
267/// The manual's fields for a group, by its label (`None` for the high-rate record's values, which
268/// have none).
269fn manual_fields(kind: &str, label: Option<&str>) -> &'static [Field] {
270    match label {
271        None if kind == HIGH_RATE => &HIGH_RATE_FIELDS,
272        None => &[],
273        Some(label) => LOW_RATE_GROUPS
274            .iter()
275            .find(|(known, _)| *known == label)
276            .map_or(&[], |(_, fields)| fields),
277    }
278}
279
280/// A piece of a line that opens `@ LOG_`, with what the logger wrote to check it.
281#[derive(Debug, PartialEq)]
282enum Piece<'a> {
283    /// No `CRC:` and four hexadecimal digits close it.
284    NoCrc,
285    /// Its CRC differs from its text's.
286    CrcDiffers,
287    /// Its CRC checks: the text from `@` to the CRC's last digit.
288    Checked(&'a str),
289}
290
291/// The pieces of a line, each from an `@ LOG_` to the next or the line's end, and whether text
292/// that isn't blank comes before the first.
293fn pieces(line: &str) -> (bool, impl Iterator<Item = Piece<'_>>) {
294    let starts: Vec<usize> = line.match_indices(OPENING).map(|(at, _)| at).collect();
295    let before = starts
296        .first()
297        .map_or(line, |&first| &line[..first])
298        .trim()
299        .is_empty();
300    let ends = starts
301        .iter()
302        .skip(1)
303        .copied()
304        .chain(std::iter::once(line.len()));
305    let spans: Vec<(usize, usize)> = starts.iter().copied().zip(ends).collect();
306    (
307        !before,
308        spans
309            .into_iter()
310            .map(move |(start, end)| piece(line[start..end].trim_end())),
311    )
312}
313
314/// A piece checked against the CRC that closes it.
315fn piece(text: &str) -> Piece<'_> {
316    let Some(at) = text.rfind("CRC:") else {
317        return Piece::NoCrc;
318    };
319    let digits = text[at + 4..].trim_start();
320    let stated = (digits.len() == 4)
321        .then(|| u16::from_str_radix(digits, 16).ok())
322        .flatten()
323        .filter(|_| digits.bytes().all(|byte| byte.is_ascii_hexdigit()));
324    let Some(stated) = stated else {
325        return Piece::NoCrc;
326    };
327    let body = text[..at].trim_end_matches(' ');
328    if crc16_buypass(body.as_bytes()) == stated {
329        Piece::Checked(text)
330    } else {
331        Piece::CrcDiffers
332    }
333}
334
335/// Whether `text` is a Blue Raven's USB download: one of its first [`RECOGNITION_LINES`] lines
336/// opens with `@ LOG_HIR` or `@ LOG_LOW` and closes with a CRC that checks.
337pub(crate) fn recognizes(text: &str) -> bool {
338    numbered_lines(text)
339        .take(RECOGNITION_LINES)
340        .any(|(_, line)| {
341            let line = line.trim();
342            (line.starts_with("@ LOG_HIR") || line.starts_with("@ LOG_LOW"))
343                && line.match_indices(OPENING).count() == 1
344                && matches!(piece(line), Piece::Checked(_))
345        })
346}
347
348/// A record's groups: each its label (`None` for the high-rate record's values) and its values'
349/// count.
350type Layout = Vec<(Option<String>, usize)>;
351
352/// One record, read.
353struct Record {
354    kind: String,
355    layout: Layout,
356    /// The logger's date and time, ms after 1970-01-01 on its own clock.
357    at_ms: i64,
358    year: i64,
359    month: i64,
360    day: i64,
361    /// The time of day, ms after the logger's midnight.
362    time_of_day_ms: i64,
363    sync: i64,
364    /// The values after the sync code, in the record's order.
365    values: Vec<f64>,
366}
367
368/// Days from 1970-01-01 to a date of the proleptic Gregorian calendar (H. Hinnant,
369/// *chrono-Compatible Low-Level Date Algorithms*, `days_from_civil`, public domain).
370fn days_from_civil(year: i64, month: i64, day: i64) -> i64 {
371    let year = if month <= 2 { year - 1 } else { year };
372    let era = year.div_euclid(400);
373    let year_of_era = year - era * 400;
374    let shifted_month = (month + 9) % 12;
375    let day_of_year = (153 * shifted_month + 2) / 5 + day - 1;
376    let day_of_era = year_of_era * 365 + year_of_era / 4 - year_of_era / 100 + day_of_year;
377    era * 146_097 + day_of_era - 719_468
378}
379
380fn days_in_month(year: i64, month: i64) -> i64 {
381    match month {
382        2 if year % 4 == 0 && (year % 100 != 0 || year % 400 == 0) => 29,
383        2 => 28,
384        4 | 6 | 9 | 11 => 30,
385        _ => 31,
386    }
387}
388
389/// A whole number as the logger writes it: an optional `-`, then at most 15 digits, so that it
390/// is exact as an `f64`.
391fn whole(token: &str) -> Option<i64> {
392    let digits = token.strip_prefix('-').unwrap_or(token);
393    (!digits.is_empty() && digits.len() <= 15 && digits.bytes().all(|byte| byte.is_ascii_digit()))
394        .then(|| token.parse().ok())
395        .flatten()
396}
397
398/// A register as the logger writes it: one to eight hexadecimal digits.
399fn register(token: &str) -> Option<i64> {
400    (!token.is_empty() && token.len() <= 8 && token.bytes().all(|byte| byte.is_ascii_hexdigit()))
401        .then(|| i64::from_str_radix(token, 16).ok())
402        .flatten()
403}
404
405/// A time of day, `H:MM:SS` or `HH:MM:SS` with up to three decimals, as ms after midnight.
406fn time_of_day_ms(token: &str) -> Option<i64> {
407    let mut parts = token.split(':');
408    let (hours, minutes, seconds) = (parts.next()?, parts.next()?, parts.next()?);
409    if parts.next().is_some() {
410        return None;
411    }
412    let (whole_seconds, fraction) = seconds.split_once('.').unwrap_or((seconds, ""));
413    let digits = |text: &str, most: usize| {
414        (!text.is_empty() && text.len() <= most && text.bytes().all(|byte| byte.is_ascii_digit()))
415            .then(|| text.parse::<i64>().ok())
416            .flatten()
417    };
418    let hours = digits(hours, 2).filter(|hours| *hours < 24)?;
419    let minutes = digits(minutes, 2).filter(|minutes| *minutes < 60)?;
420    let whole_seconds = digits(whole_seconds, 2).filter(|seconds| *seconds < 60)?;
421    let milliseconds = if fraction.is_empty() {
422        (!seconds.contains('.')).then_some(0)?
423    } else {
424        // `.5` is 500 ms: padded to three digits.
425        digits(fraction, 3)? * 10_i64.pow(3 - u32::try_from(fraction.len()).ok()?)
426    };
427    Some(((hours * 60 + minutes) * 60 + whole_seconds) * 1_000 + milliseconds)
428}
429
430fn syntax(line: usize, message: String) -> LogError {
431    LogError::Syntax {
432        format: FORMAT,
433        line,
434        message,
435    }
436}
437
438/// Reads a record whose CRC checked; any fault in it refuses the file, as the logger wrote it.
439fn record(text: &str, line: usize) -> Result<Record, LogError> {
440    // The CRC checked, so `CRC:` is in the text.
441    let crc_at = text.rfind("CRC:").unwrap_or(text.len());
442    let tokens: Vec<&str> = text[..crc_at].split_ascii_whitespace().collect();
443    let kind = tokens.get(1).copied().unwrap_or_default();
444    if kind != HIGH_RATE && kind != LOW_RATE {
445        return Err(syntax(
446            line,
447            format!(
448                "a record `{}` whose CRC checks, which the manual doesn't describe: only \
449                 `@ LOG_HIR` and `@ LOG_LOW` are read",
450                short(kind)
451            ),
452        ));
453    }
454    let header = |index: usize, what: &str| {
455        tokens.get(index).copied().ok_or_else(|| {
456            syntax(
457                line,
458                format!("the record ends before its {what}: `{}`", short(text)),
459            )
460        })
461    };
462    let stated = header(2, "length")?;
463    if whole(stated).and_then(|length| usize::try_from(length).ok())
464        != Some(text.len() + LINE_END_BYTES)
465    {
466        return Err(syntax(
467            line,
468            format!(
469                "the record states its length as `{}`, and it is {} bytes with its line end",
470                short(stated),
471                text.len() + LINE_END_BYTES
472            ),
473        ));
474    }
475    let date = |index: usize, what: &str| -> Result<i64, LogError> {
476        let token = header(index, what)?;
477        whole(token).ok_or_else(|| {
478            syntax(
479                line,
480                format!("the record's {what} is `{}`, not a number", short(token)),
481            )
482        })
483    };
484    let (year, month, day) = (date(3, "year")?, date(4, "month")?, date(5, "day")?);
485    if !(1..=9_999).contains(&year)
486        || !(1..=12).contains(&month)
487        || !(1..=days_in_month(year, month)).contains(&day)
488    {
489        return Err(syntax(
490            line,
491            format!("the record's date, {year} {month} {day}, isn't one"),
492        ));
493    }
494    let clock = header(6, "time")?;
495    let time_of_day_ms = time_of_day_ms(clock).ok_or_else(|| {
496        syntax(
497            line,
498            format!(
499                "the record's time is `{}`, not `HH:MM:SS.fff`",
500                short(clock)
501            ),
502        )
503    })?;
504    let sync = date(7, "sync code")?;
505    let mut layout: Layout = Vec::new();
506    let mut values = Vec::new();
507    if kind == HIGH_RATE {
508        layout.push((None, 0));
509    }
510    for &token in &tokens[8..] {
511        if token.ends_with(':') && kind == LOW_RATE {
512            if layout.len() >= MAX_GROUPS {
513                return Err(syntax(
514                    line,
515                    format!(
516                        "the record's group `{}` is past the {MAX_GROUPS} groups a record may \
517                         hold",
518                        short(token)
519                    ),
520                ));
521            }
522            if token.len() > MAX_LABEL_BYTES {
523                return Err(syntax(
524                    line,
525                    format!(
526                        "the record's label `{}` is longer than the {MAX_LABEL_BYTES} bytes a \
527                         label may be",
528                        short(token)
529                    ),
530                ));
531            }
532            if layout
533                .iter()
534                .any(|(label, _)| label.as_deref() == Some(token))
535            {
536                return Err(syntax(
537                    line,
538                    format!("the record holds the group `{}` twice", short(token)),
539                ));
540            }
541            layout.push((Some(token.to_owned()), 0));
542            continue;
543        }
544        let Some((label, count)) = layout.last_mut() else {
545            return Err(syntax(
546                line,
547                format!(
548                    "the low-rate record holds `{}` before its first group's label",
549                    short(token)
550                ),
551            ));
552        };
553        let value = if label.as_deref() == Some(REGISTERS) {
554            register(token)
555        } else {
556            whole(token)
557        };
558        let Some(value) = value else {
559            return Err(syntax(
560                line,
561                format!(
562                    "the record's value `{}`{} isn't {}",
563                    short(token),
564                    label
565                        .as_deref()
566                        .map(|label| format!(" in `{}`", short(label)))
567                        .unwrap_or_default(),
568                    if label.as_deref() == Some(REGISTERS) {
569                        "a register in hexadecimal"
570                    } else {
571                        "a whole number"
572                    }
573                ),
574            ));
575        };
576        *count += 1;
577        values.push(value as f64);
578        if values.len() > MAX_VALUES {
579            return Err(syntax(
580                line,
581                format!("the record holds more than {MAX_VALUES} values"),
582            ));
583        }
584    }
585    Ok(Record {
586        kind: kind.to_owned(),
587        layout,
588        at_ms: days_from_civil(year, month, day) * 86_400_000 + time_of_day_ms,
589        year,
590        month,
591        day,
592        time_of_day_ms,
593        sync,
594        values,
595    })
596}
597
598/// A column's name, its quantity, and the divisor then the factor that take a value the file
599/// writes to the quantity's unit, as a [`Field`]'s.
600type Column = (String, Quantity, f64, f64);
601
602/// A column for each value of a record laid out as `layout`, and a note for each group read
603/// otherwise than by the manual whole.
604fn columns(kind: &str, layout: &Layout) -> (Vec<Column>, Vec<String>) {
605    let mut columns = Vec::new();
606    let mut notes = Vec::new();
607    for (label, count) in layout {
608        let manual = manual_fields(kind, label.as_deref());
609        let named = label.as_deref().unwrap_or(kind);
610        let read = if *count >= manual.len() {
611            manual.len()
612        } else {
613            0
614        };
615        for field in &manual[..read] {
616            columns.push((
617                field.column.to_owned(),
618                field.quantity,
619                field.per,
620                field.unit,
621            ));
622        }
623        let as_written = if label.as_deref() == Some(REGISTERS) {
624            Quantity::Number
625        } else {
626            Quantity::Unrecognized
627        };
628        for place in read + 1..=*count {
629            columns.push((format!("{named} {place}"), as_written, 1.0, 1.0));
630        }
631        let what = if label.is_some() {
632            format!("`{named}` holds")
633        } else {
634            "the high-rate record holds".to_owned()
635        };
636        if manual.is_empty() {
637            notes.push(format!(
638                "{what} {count} values in a group the manual doesn't list: kept as written"
639            ));
640        } else if *count > manual.len() {
641            notes.push(format!(
642                "{what} {count} values where the manual lists {}: the manual's read in its \
643                 order, the other {} kept as written",
644                manual.len(),
645                count - manual.len()
646            ));
647        } else if *count < manual.len() {
648            notes.push(format!(
649                "{what} {count} values where the manual lists {}: kept as written, as nothing \
650                 says which is missing",
651                manual.len()
652            ));
653        }
654    }
655    (columns, notes)
656}
657
658/// Reads a Blue Raven's USB download.
659///
660/// # Errors
661///
662/// [`LogError::Unrecognized`] if no line among the first 1,000 is a record whose CRC checks;
663/// [`LogError::Syntax`] for a record whose CRC checks but which can't be read (see the module's
664/// docs).
665pub fn read(text: &str) -> Result<FlightLog, LogError> {
666    if !recognizes(text) {
667        return Err(LogError::Unrecognized {
668            message: format!(
669                "not a {FORMAT}: none of its first {RECOGNITION_LINES} lines is an `@ LOG_HIR` or \
670                 `@ LOG_LOW` record whose CRC checks"
671            ),
672        });
673    }
674    let mut first: Option<Record> = None;
675    let mut times_ms: Vec<i64> = Vec::new();
676    let mut header_values: [Vec<f64>; 5] = Default::default();
677    let mut values: Vec<Vec<f64>> = Vec::new();
678    let mut first_line = 0;
679    let (mut no_crc, mut crc_differs, mut other_lines) = (0_usize, 0_usize, 0_usize);
680    for (line, text) in numbered_lines(text) {
681        let (text_before, line_pieces) = pieces(text);
682        let mut any = false;
683        for piece in line_pieces {
684            any = true;
685            let record = match piece {
686                Piece::NoCrc => {
687                    no_crc += 1;
688                    continue;
689                }
690                Piece::CrcDiffers => {
691                    crc_differs += 1;
692                    continue;
693                }
694                Piece::Checked(text) => record(text, line)?,
695            };
696            if let Some(first) = &first {
697                if record.kind != first.kind || record.layout != first.layout {
698                    return Err(syntax(
699                        line,
700                        format!(
701                            "a record laid out unlike the first, on line {}: a download holds \
702                             one kind of record, each with the same groups",
703                            first_line
704                        ),
705                    ));
706                }
707                let previous = times_ms.last().copied().unwrap_or(i64::MIN);
708                if record.at_ms <= previous {
709                    return Err(syntax(
710                        line,
711                        format!(
712                            "the record's time, {}, doesn't come after the one before",
713                            clock_text(&record)
714                        ),
715                    ));
716                }
717            } else {
718                values = vec![Vec::new(); record.values.len()];
719            }
720            times_ms.push(record.at_ms);
721            for (column, value) in header_values.iter_mut().zip([
722                record.year as f64,
723                record.month as f64,
724                record.day as f64,
725                record.time_of_day_ms as f64 / 1_000.0,
726                record.sync as f64,
727            ]) {
728                column.push(value);
729            }
730            for (column, value) in values.iter_mut().zip(&record.values) {
731                column.push(*value);
732            }
733            if first.is_none() {
734                first_line = line;
735                first = Some(record);
736            }
737        }
738        if text_before || (!any && !text.trim().is_empty()) {
739            other_lines += 1;
740        }
741    }
742    // Recognition found a record whose CRC checks, which the loop reads or refuses, so a first
743    // record is always there; refused rather than unwrapped all the same.
744    let Some(first) = first else {
745        return Err(LogError::NotThisFormat {
746            format: FORMAT,
747            message: "no record's CRC checks".to_owned(),
748        });
749    };
750    let zero_ms = times_ms[0];
751    let time_s: Vec<f64> = times_ms
752        .iter()
753        .map(|at| (at - zero_ms) as f64 / 1_000.0)
754        .collect();
755    let mut channels = Vec::new();
756    for ((column, quantity), values) in [
757        ("Year", Quantity::Number),
758        ("Month", Quantity::Number),
759        ("Day", Quantity::Number),
760        ("Time", Quantity::TimeOfDay),
761        ("Sync", Quantity::Number),
762    ]
763    .into_iter()
764    .zip(header_values)
765    {
766        channels.push(Channel {
767            column: column.to_owned(),
768            quantity,
769            time_s: time_s.clone(),
770            values,
771        });
772    }
773    let (columns, layout_notes) = columns(&first.kind, &first.layout);
774    for ((column, quantity, per, unit), counts) in columns.into_iter().zip(values) {
775        channels.push(Channel {
776            column,
777            quantity,
778            time_s: time_s.clone(),
779            values: counts.into_iter().map(|count| count / per * unit).collect(),
780        });
781    }
782    let mut notes = vec![format!(
783        "a {} download: the clock counts from the first record's time on the logger's clock, \
784         {}. The manual says that clock's date starts from the firmware's build date unless \
785         the phone has set it",
786        if first.kind == HIGH_RATE {
787            "high-rate"
788        } else {
789            "low-rate"
790        },
791        clock_text(&first)
792    )];
793    notes.extend(layout_notes);
794    let temperature_read = first
795        .layout
796        .iter()
797        .any(|(label, count)| label.as_deref() == Some("Bo:") && *count >= 2);
798    if temperature_read {
799        notes.push(
800            "`Bo: temperature` kept as written: the manual states no unit for it in the download"
801                .to_owned(),
802        );
803    }
804    if no_crc > 0 {
805        notes.push(if no_crc == 1 {
806            "1 piece that opens `@ LOG_` but closes with no CRC, a record the capture cut or ran \
807             into the next, dropped"
808                .to_owned()
809        } else {
810            format!(
811                "{no_crc} pieces that open `@ LOG_` but close with no CRC, records the capture cut \
812                 or ran into the next, dropped"
813            )
814        });
815    }
816    if crc_differs > 0 {
817        notes.push(if crc_differs == 1 {
818            "1 piece whose CRC differs from its text, dropped".to_owned()
819        } else {
820            format!("{crc_differs} pieces whose CRC differs from their text, dropped")
821        });
822    }
823    if other_lines > 0 {
824        notes.push(format!(
825            "{other_lines} {} holding text other than a record, skipped",
826            plural(other_lines, "line")
827        ));
828    }
829    Ok(FlightLog {
830        format: LogFormat::BlueRavenUsb,
831        logger: "Featherweight Blue Raven".to_owned(),
832        serial_number: None,
833        firmware: None,
834        flight_number: None,
835        stated: Stated {
836            apogee_m: None,
837            ground_elevation_msl_m: None,
838            samples: None,
839            figures: Vec::new(),
840        },
841        time_s: Vec::new(),
842        altitude_m: Vec::new(),
843        vertical_speed_m_s: None,
844        temperature_k: None,
845        battery_v: None,
846        channels,
847        events: Vec::new(),
848        notes,
849    })
850}
851
852fn clock_text(record: &Record) -> String {
853    let ms = record.time_of_day_ms;
854    format!(
855        "{} {} {} {:02}:{:02}:{:02}.{:03}",
856        record.year,
857        record.month,
858        record.day,
859        ms / 3_600_000,
860        ms / 60_000 % 60,
861        ms / 1_000 % 60,
862        ms % 1_000
863    )
864}
865
866fn plural(count: usize, word: &str) -> String {
867    if count == 1 {
868        word.to_owned()
869    } else {
870        format!("{word}s")
871    }
872}
873
874#[cfg(test)]
875mod tests {
876    use super::*;
877    use crate::import;
878
879    /// Two invented high-rate records, their CRCs and lengths worked out apart from this reader.
880    const HIGH: &str = "@ LOG_HIR  139 2026  5 23 10:15:00.120   20    -15     42     -7     -1      3     98  -3000   1500    -40  29812      0      0 CRC: 7730\r\n\
881                        @ LOG_HIR  139 2026  5 23 10:15:00.122   22    -12     40     -6     -2      4     99  -3001   1500    -41  29811      0      0 CRC: A68A\r\n";
882
883    /// Two invented low-rate records, laid out as the sample logs' firmware writes them.
884    const LOW: &str = "@ LOG_LOW  211 2026  5 23 10:15:00.140  40 Bo:  7212 49655 V:  4105    22    21    20    23 Vel:     0     0     0 Pos:     0     0     0 ang:   12    5    0 FER:  400  1c1   c3   c1   c3   0   0   0 CRC: F7EB\r\n\
885                       @ LOG_LOW  211 2026  5 23 10:15:00.160  60 Bo:  7212 49654 V:  4105    22    21    20    23 Vel:     1     0     0 Pos:     0     0     0 ang:   12    5    0 FER:  400  1c1   c3   c1   c3   0   0   0 CRC: F1E8\r\n";
886
887    /// A record of `kind` holding `rest`, its length and CRC worked out by this reader's CRC.
888    fn line(kind: &str, rest: &str) -> String {
889        (50..1_000)
890            .find_map(|length| {
891                let body = format!("@ {kind} {length:>4} {rest}");
892                let text = format!("{body} CRC: {:04X}", crc16_buypass(body.as_bytes()));
893                (text.len() + 2 == length).then_some(text)
894            })
895            .expect("a length fits")
896    }
897
898    fn channel<'a>(log: &'a FlightLog, column: &str) -> &'a Channel {
899        log.channels
900            .iter()
901            .find(|channel| channel.column == column)
902            .unwrap_or_else(|| panic!("no channel `{column}`"))
903    }
904
905    fn close(a: f64, b: f64) -> bool {
906        (a - b).abs() <= 1e-12 * b.abs().max(1.0)
907    }
908
909    #[test]
910    fn the_crc_is_buypass() {
911        // The cataloged check value of CRC-16/UMTS, also called BUYPASS.
912        assert_eq!(crc16_buypass(b"123456789"), 0xFEE8);
913    }
914
915    #[test]
916    fn reads_high_rate_records_by_the_manual() {
917        let log = read(HIGH).expect("reads");
918        assert_eq!(log.format, LogFormat::BlueRavenUsb);
919        assert!(log.time_s.is_empty() && log.altitude_m.is_empty());
920        assert_eq!(log.channels.len(), 5 + 12);
921        let gyro = channel(&log, "Gyro X");
922        assert_eq!(gyro.quantity, Quantity::AngularRate);
923        assert_eq!(gyro.time_s, vec![0.0, 0.002]);
924        assert!(close(gyro.values[0], -0.15));
925        let accel = channel(&log, "Accel Z");
926        assert_eq!(accel.quantity, Quantity::Acceleration);
927        assert!(close(accel.values[1], 0.99 * STANDARD_GRAVITY_MPS2));
928        let magnitude = channel(&log, "Quaternion magnitude");
929        assert!(close(magnitude.values[0], 29_812.0 / 30_000.0));
930        let extra = channel(&log, "LOG_HIR 11");
931        assert_eq!(extra.quantity, Quantity::Unrecognized);
932        assert_eq!(extra.values, vec![0.0, 0.0]);
933        assert_eq!(channel(&log, "Sync").values, vec![20.0, 22.0]);
934        assert_eq!(
935            channel(&log, "Time").values,
936            vec![36_900.12, 36_900.122],
937            "10:15:00.120 as seconds after midnight"
938        );
939        assert!(
940            log.notes
941                .iter()
942                .any(|note| note.starts_with("the high-rate record holds 12 values where the manual lists 10: the manual's read in its order, the other 2 kept as written")),
943            "{:?}",
944            log.notes
945        );
946        assert!(log.notes[0].contains("2026 5 23 10:15:00.120"));
947    }
948
949    #[test]
950    fn reads_low_rate_groups_and_keeps_short_ones_as_written() {
951        let log = read(LOW).expect("reads");
952        let pressure = channel(&log, "Bo: pressure");
953        assert_eq!(pressure.quantity, Quantity::Pressure);
954        assert!(close(pressure.values[0], 49_655.0 / 50_000.0 * 101_325.0));
955        let temperature = channel(&log, "Bo: temperature");
956        assert_eq!(temperature.quantity, Quantity::Unrecognized);
957        assert_eq!(temperature.values[0], 7_212.0);
958        // Five voltages where the manual lists six: none read as the manual's.
959        assert!(
960            log.channels
961                .iter()
962                .all(|channel| channel.column != "V: battery")
963        );
964        let first = channel(&log, "V: 1");
965        assert_eq!(first.quantity, Quantity::Unrecognized);
966        assert_eq!(first.values[0], 4_105.0);
967        assert!(log.channels.iter().all(|channel| channel.column != "V: 6"));
968        let up = channel(&log, "Vel: up");
969        assert_eq!(up.quantity, Quantity::Speed);
970        assert!(close(up.values[1], FOOT_M));
971        assert_eq!(
972            channel(&log, "Pos: altitude").quantity,
973            Quantity::InertialAltitude
974        );
975        assert!(close(channel(&log, "ang: tilt").values[0], 1.2));
976        assert!(close(channel(&log, "ang: roll").values[0], 5.0));
977        // Eight registers where the manual lists five: its five, then three kept.
978        let rocket = channel(&log, "FER: rocket");
979        assert_eq!(rocket.quantity, Quantity::Number);
980        assert_eq!(rocket.values[0], f64::from(0x400));
981        assert_eq!(channel(&log, "FER: Apo").values[0], f64::from(0x1c1));
982        assert_eq!(channel(&log, "FER: 8").quantity, Quantity::Number);
983        assert!(
984            log.channels
985                .iter()
986                .all(|channel| channel.column != "FER: 9")
987        );
988        for wanted in [
989            "`V:` holds 5 values where the manual lists 6: kept as written, as nothing says which is missing",
990            "`FER:` holds 8 values where the manual lists 5: the manual's read in its order, the other 3 kept as written",
991            "`Bo: temperature` kept as written",
992        ] {
993            assert!(
994                log.notes.iter().any(|note| note.starts_with(wanted)),
995                "{wanted}: {:?}",
996                log.notes
997            );
998        }
999    }
1000
1001    #[test]
1002    fn a_short_high_rate_record_is_kept_as_written() {
1003        let rest = "2026  5 23 10:15:00.120   20    -15     42     -7     -1      3     98  -3000   1500    -40";
1004        let log = read(&line("LOG_HIR", rest)).expect("reads");
1005        assert!(
1006            log.channels
1007                .iter()
1008                .all(|channel| channel.column != "Gyro X")
1009        );
1010        assert_eq!(channel(&log, "LOG_HIR 1").values[0], -15.0);
1011        assert_eq!(channel(&log, "LOG_HIR 9").quantity, Quantity::Unrecognized);
1012    }
1013
1014    #[test]
1015    fn drops_pieces_whose_crc_is_missing_or_differs() {
1016        let mut lines: Vec<String> = HIGH.lines().map(str::to_owned).collect();
1017        // A record whose CRC and line end the capture lost runs into the next one.
1018        let cut = lines[0].rfind(" CRC:").expect("a CRC");
1019        let run_on = format!("{}{}", &lines[0][..cut], lines[1]);
1020        // A record with one digit changed: its CRC no longer checks.
1021        let damaged = lines[1].replacen("-12", "-13", 1);
1022        let later = line(
1023            "LOG_HIR",
1024            "2026  5 23 10:15:00.124   24    -12     40     -6     -2      4     99  -3001   1500    -41  29811      0      0",
1025        );
1026        lines = vec![run_on, damaged, "@ BLR_STAT and the like".to_owned(), later];
1027        let log = read(&lines.join("\r\n")).expect("reads");
1028        assert_eq!(channel(&log, "Sync").values, vec![22.0, 24.0]);
1029        for wanted in [
1030            "1 piece that opens `@ LOG_` but closes with no CRC",
1031            "1 piece whose CRC differs from its text, dropped",
1032            "1 line holding text other than a record, skipped",
1033        ] {
1034            assert!(
1035                log.notes.iter().any(|note| note.starts_with(wanted)),
1036                "{wanted}: {:?}",
1037                log.notes
1038            );
1039        }
1040    }
1041
1042    fn refusal(text: &str) -> (usize, String) {
1043        match read(text) {
1044            Err(LogError::Syntax { line, message, .. }) => (line, message),
1045            other => panic!("not refused by a line: {other:?}"),
1046        }
1047    }
1048
1049    #[test]
1050    fn refuses_a_checked_record_whose_length_isnt_its_own() {
1051        // Its CRC checks, but it states 140 bytes for a record of 139.
1052        let text = format!(
1053            "{HIGH}@ LOG_HIR  140 2026  5 23 10:15:00.124   24    -12     40     -6     -2      4     99  -3001   1500    -41  29811      0      0 CRC: 8AC7\r\n"
1054        );
1055        let (line, message) = refusal(&text);
1056        assert_eq!(line, 3);
1057        assert!(
1058            message.contains("`140`") && message.contains("139 bytes"),
1059            "{message}"
1060        );
1061    }
1062
1063    #[test]
1064    fn refuses_a_clock_that_doesnt_increase() {
1065        let rest = "2026  5 23 10:15:00.122   24    -12     40     -6     -2      4     99  -3001   1500    -41  29811      0      0";
1066        let (line, message) = refusal(&format!("{HIGH}{}\r\n", line("LOG_HIR", rest)));
1067        assert_eq!(line, 3);
1068        assert!(message.contains("doesn't come after"), "{message}");
1069    }
1070
1071    #[test]
1072    fn a_clock_crosses_midnight_by_its_date() {
1073        let first = line("LOG_LOW", "2026 12 31 23:59:59.990  40 Bo:  7212 49655");
1074        let second = line("LOG_LOW", "2027  1  1 00:00:00.010  60 Bo:  7212 49655");
1075        let log = read(&format!("{first}\n{second}\n")).expect("reads");
1076        let time = &channel(&log, "Bo: pressure").time_s;
1077        assert!(close(time[1], 0.02), "{time:?}");
1078    }
1079
1080    #[test]
1081    fn refuses_a_second_layout_or_kind() {
1082        let (at, message) = refusal(&format!("{HIGH}{LOW}"));
1083        assert_eq!(at, 3);
1084        assert!(message.contains("unlike the first, on line 1"), "{message}");
1085        let fewer = line(
1086            "LOG_LOW",
1087            "2026  5 23 10:15:00.180  80 Bo:  7212 49655 V:  4105    15    14    14",
1088        );
1089        let (at, _) = refusal(&format!("{LOW}{fewer}\r\n"));
1090        assert_eq!(at, 3);
1091    }
1092
1093    #[test]
1094    fn refuses_what_a_checked_record_cant_be() {
1095        let refused = |rest: &str, kind: &str| refusal(&format!("{HIGH}{}\r\n", line(kind, rest)));
1096        let values = "   26    -12     40     -6     -2      4     99  -3001   1500    -41  29811      0      0";
1097        let (_, message) = refused(&format!("2026  2 30 10:15:00.126 {values}"), "LOG_HIR");
1098        assert!(message.contains("isn't one"), "{message}");
1099        let (_, message) = refused(&format!("2026  5 23 10:15:60.126 {values}"), "LOG_HIR");
1100        assert!(message.contains("not `HH:MM:SS.fff`"), "{message}");
1101        let (_, message) = refused(
1102            "2026  5 23 10:15:00.126   26    -12     4.5     -6     -2      4     99  -3001   1500    -41  29811      0      0",
1103            "LOG_HIR",
1104        );
1105        assert!(
1106            message.contains("`4.5`") && message.contains("a whole number"),
1107            "{message}"
1108        );
1109        let (_, message) = refused(&format!("2026  5 23 10:15:00.126 {values}"), "LOG_GPS");
1110        assert!(message.contains("`LOG_GPS`"), "{message}");
1111        let many = " 1".repeat(MAX_VALUES + 1);
1112        let (_, message) = refused(&format!("2026  5 23 10:15:00.126   26{many}"), "LOG_HIR");
1113        assert!(message.contains("more than 256 values"), "{message}");
1114        let (_, message) = refusal(&line(
1115            "LOG_LOW",
1116            "2026  5 23 10:15:00.140  40 7212 Bo: 49655",
1117        ));
1118        assert!(
1119            message.contains("before its first group's label"),
1120            "{message}"
1121        );
1122        let labels: String = (0..=MAX_GROUPS).map(|k| format!(" g{k}: 1")).collect();
1123        let (_, message) = refusal(&line(
1124            "LOG_LOW",
1125            &format!("2026  5 23 10:15:00.140  40{labels}"),
1126        ));
1127        assert!(
1128            message.contains("`g16:` is past the 16 groups"),
1129            "{message}"
1130        );
1131        let long = format!("{}:", "x".repeat(MAX_LABEL_BYTES));
1132        let (_, message) = refusal(&line(
1133            "LOG_LOW",
1134            &format!("2026  5 23 10:15:00.140  40 {long} 1"),
1135        ));
1136        assert!(message.contains("longer than the 16 bytes"), "{message}");
1137        // At the caps, the record is read: 16 groups, the last one's label 16 bytes.
1138        let labels: String = (1..MAX_GROUPS)
1139            .map(|k| format!(" g{k}: 1"))
1140            .chain([format!(" {}: 1", "x".repeat(MAX_LABEL_BYTES - 1))])
1141            .collect();
1142        let log = read(&line(
1143            "LOG_LOW",
1144            &format!("2026  5 23 10:15:00.140  40{labels}"),
1145        ))
1146        .unwrap();
1147        assert!(log.channels.iter().any(|c| c.column.starts_with("xxxx")));
1148        let (_, message) = refusal(&line("LOG_LOW", "2026  5 23 10:15:00.140  40 FER: 60g"));
1149        assert!(message.contains("hexadecimal"), "{message}");
1150    }
1151
1152    #[test]
1153    fn a_file_with_no_checked_record_isnt_one() {
1154        let damaged = HIGH.replace("  1500 ", "  1501 ");
1155        assert!(matches!(read(&damaged), Err(LogError::Unrecognized { .. })));
1156        assert!(!recognizes("@ LOG_HIR  139 no CRC here"));
1157    }
1158
1159    #[test]
1160    fn import_recognizes_a_download() {
1161        let log = import::read(LOW.as_bytes()).expect("reads");
1162        assert_eq!(log.format, LogFormat::BlueRavenUsb);
1163        assert_eq!(log.format.name(), "Blue Raven USB download");
1164    }
1165}