1use 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
158const FORMAT: &str = "Blue Raven CSV";
160
161const LEAD: [&str; 6] = ["Year", "Month", "Day", "Time", "Flight_Time_(s)", "Sync"];
163
164const CLOCK_INDEX: usize = 4;
166
167const SHORT_LEAD: [&str; 2] = ["Flight_Time_(s)", "Sync"];
169
170const ATM_PA: f64 = 101_325.0;
172
173pub const MAX_EVENTS_PER_FLAG: usize = 16;
176
177const WRAP_STEP_FT: f64 = 32_768.0;
180
181const PAD_ROWS: usize = 50;
184
185pub(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
196fn 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#[derive(Debug, Clone, Copy, PartialEq)]
214enum Scale {
215 By(f64),
217 Fahrenheit,
219}
220
221#[derive(Debug, Clone, Copy, PartialEq)]
223enum Role {
224 Clock,
226 TimeOfDay,
228 Value(Quantity, Scale),
230 Hex,
232 Flag { event: bool },
234}
235
236#[derive(Debug, Clone, Copy, PartialEq, Eq)]
238enum Decided {
239 Velocity,
240 Inertial,
241 Gyro,
242 Accel,
243}
244
245fn key(name: &str) -> String {
247 name.chars()
248 .filter(|c| !c.is_whitespace())
249 .collect::<String>()
250 .to_ascii_lowercase()
251}
252
253fn 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
295struct Column {
297 name: String,
298 key: String,
299 role: Role,
300 decided: Option<Decided>,
301 values: Vec<f64>,
302 gaps: usize,
304 gap_example: Option<String>,
305 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
322pub 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 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 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
404fn 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
457fn 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 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 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
544fn 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
565fn number_cell(cell: &str) -> Option<f64> {
567 number(cell, false)
568}
569
570fn 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
578fn 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
602fn 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 u64::from_str_radix(digits, 16).ok().map(|bits| bits as f64)
614}
615
616fn 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
731fn 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
742fn 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
794const MAX_LISTED: usize = 6;
796
797fn 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
815fn 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
828fn 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
860fn 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
876fn 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
890fn 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
924fn current_note(current: &Column) -> String {
926 let values = ¤t.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(¤t.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 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 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 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 #[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 #[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 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 #[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 let readings = crate::readings::read(&log);
1183 assert!(readings.apogee.value().is_none());
1184 }
1185
1186 #[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 #[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 #[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 #[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 #[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 #[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 #[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 #[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 #[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 #[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}