1use crate::error::LogError;
147use crate::log::{Channel, Event, FlightLog, LogFormat, Quantity, Stated};
148use crate::table::finite;
149
150const FORMAT: &str = "AltOS CSV";
152
153const MAX_NOTES: usize = 20;
155
156const QUOTED_CHARS: usize = 80;
158
159#[derive(Debug, Clone, Copy, PartialEq)]
161enum Role {
162 Clock,
164 Text,
166 Value(Quantity),
168 Celsius,
170 Pressure,
172}
173
174fn role(name: &str, after_longitude: bool) -> (Role, bool) {
177 use Quantity as Q;
178 let lower = name.to_ascii_lowercase();
179 let value = |quantity| (Role::Value(quantity), true);
180 match lower.as_str() {
181 "time" => (Role::Clock, true),
182 "call" | "state_name" => (Role::Text, true),
183 "height" => value(Q::AltitudeAboveGround),
184 "altitude" if after_longitude => value(Q::GnssAltitude),
185 "altitude" => value(Q::AltitudeMsl),
186 "pressure" => (Role::Pressure, true),
187 "acceleration" | "accel_x" | "accel_y" | "accel_z" => value(Q::Acceleration),
188 "speed" | "accel_speed" | "baro_speed" => value(Q::Speed),
189 "temperature" => (Role::Celsius, true),
190 "battery_voltage" | "drogue_voltage" | "main_voltage" | "pyro" => value(Q::Voltage),
191 "latitude" => value(Q::Latitude),
192 "longitude" => value(Q::Longitude),
193 "tilt" | "pad_az" | "pad_el" => value(Q::Angle),
194 "pad_dist" | "pad_range" => value(Q::Distance),
195 "version" | "serial" | "flight" | "rssi" | "lqi" | "state" | "connected" | "locked"
196 | "nsat" | "year" | "month" | "day" | "hour" | "minute" | "second" | "pdop" | "hdop"
197 | "vdop" => value(Q::Number),
198 "gyro_roll" | "gyro_pitch" | "gyro_yaw" | "mag_x" | "mag_y" | "mag_z" => {
199 value(Q::Unrecognized)
200 }
201 _ if lower.starts_with("igniter_") => value(Q::Voltage),
202 _ if is_satellite(&lower) => value(Q::Number),
203 _ => (Role::Value(Q::Unrecognized), false),
204 }
205}
206
207fn split_unit(cell: &str) -> (&str, Option<&str>) {
211 match cell
212 .strip_suffix(')')
213 .and_then(|rest| rest.rsplit_once(" ("))
214 {
215 Some((name, unit)) if !name.trim().is_empty() => (name.trim(), Some(unit.trim())),
216 _ => (cell, None),
217 }
218}
219
220fn unit_agrees(role: Role, unit: &str) -> bool {
223 use Quantity as Q;
224 let units: &[&str] = match role {
225 Role::Clock => &["s"],
226 Role::Value(Q::AltitudeAboveGround | Q::AltitudeMsl | Q::GnssAltitude | Q::Distance) => {
227 &["m"]
228 }
229 Role::Value(Q::Acceleration) => &["m/s^2", "m/s²", "m/s/s"],
230 Role::Value(Q::Speed) => &["m/s"],
231 Role::Value(Q::Voltage) => &["V"],
232 Role::Value(Q::Latitude | Q::Longitude | Q::Angle) => &["degrees", "deg", "°"],
233 Role::Celsius => &["C", "°C"],
234 Role::Pressure => &["Pa"],
235 _ => &[],
236 };
237 units.contains(&unit)
238}
239
240#[derive(Debug, Clone, Copy, PartialEq)]
242enum Unit {
243 Unwritten,
245 Agrees,
247 Differs,
249}
250
251fn is_satellite(lower: &str) -> bool {
253 lower
254 .strip_prefix("sat")
255 .is_some_and(|digits| digits.len() == 2 && digits.bytes().all(|b| b.is_ascii_digit()))
256}
257
258#[derive(Default)]
261struct Notes {
262 kept: Vec<String>,
263 left_out: usize,
264}
265
266impl Notes {
267 fn push(&mut self, note: String) {
268 if self.kept.len() < MAX_NOTES {
269 self.kept.push(note);
270 } else {
271 self.left_out += 1;
272 }
273 }
274}
275
276#[derive(Default)]
278struct Preamble {
279 product: Option<String>,
280 serial: Option<String>,
281 flight: Option<String>,
282}
283
284pub fn read(text: &str) -> Result<FlightLog, LogError> {
296 let text = text.strip_prefix('\u{feff}').unwrap_or(text);
297 let text = text.replace("\r\n", "\n").replace('\r', "\n");
298 let mut lines = text
299 .lines()
300 .enumerate()
301 .map(|(index, line)| (index + 1, line.trim()));
302
303 let mut preamble = Preamble::default();
304 let mut comments = false;
305 let (header_line, header, bare_table) = loop {
306 match lines.next() {
307 Some((_, "")) => {}
308 Some((number, line)) => {
309 let bare = line.trim_start_matches('#').trim();
310 if is_header(bare) {
311 break (number, bare, false);
312 }
313 if !comments && is_table_header(line) {
314 break (number, line, true);
315 }
316 if line.starts_with('#') {
317 comments = true;
318 preamble.read(bare);
319 continue;
320 }
321 return Err(LogError::NotThisFormat {
322 format: FORMAT,
323 message: format!(
324 "line {number}, {:?}, isn't AltOS's header, `version,serial,flight,…`",
325 short(line)
326 ),
327 });
328 }
329 None => {
330 return Err(LogError::NotThisFormat {
331 format: FORMAT,
332 message: "the file has no `version,serial,flight,…` header".to_owned(),
333 });
334 }
335 }
336 };
337 let names: Vec<String> = header
338 .split(',')
339 .map(|cell| cell.trim().to_owned())
340 .collect();
341 let columns = header_columns(&names, header_line)?;
342
343 let mut notes = Notes::default();
344 let mut table = Table::new(&names, &columns, bare_table);
345 for (number, line) in lines {
346 if line.is_empty() {
347 continue;
348 }
349 if line.starts_with('#') {
350 notes.push(format!(
351 "line {number}, a `#` line among the rows, was skipped"
352 ));
353 continue;
354 }
355 table.row(&columns, line, number, &mut notes)?;
356 }
357 if table.time_s.is_empty() {
358 return Err(LogError::NoData { format: FORMAT });
359 }
360 if bare_table && table.states_checked == 0 {
361 return Err(LogError::Syntax {
362 format: FORMAT,
363 line: header_line,
364 message: "a table of AltOS's columns with no `version,serial,flight` header is read \
365 by its states. No row's `state` and `state_name` are a state AltOS's \
366 exports name"
367 .to_owned(),
368 });
369 }
370 assemble(&names, &columns, table, &preamble, notes, bare_table)
371}
372
373fn is_header(bare: &str) -> bool {
375 let mut cells = bare.split(',').map(str::trim);
376 ["version", "serial", "flight"].iter().all(|expected| {
377 cells
378 .next()
379 .is_some_and(|cell| cell.eq_ignore_ascii_case(expected))
380 })
381}
382
383fn is_table_header(line: &str) -> bool {
387 let names: Vec<&str> = line.split(',').map(str::trim).collect();
388 let mut after_longitude = false;
389 let all_known = names.iter().all(|name| {
390 let known = role(name, after_longitude).1;
391 after_longitude |= name.eq_ignore_ascii_case("longitude");
392 known
393 });
394 all_known
395 && ["time", "state", "state_name"]
396 .iter()
397 .all(|wanted| names.iter().any(|name| name.eq_ignore_ascii_case(wanted)))
398}
399
400pub fn recognizes_table(text: &str) -> bool {
406 let text = text.strip_prefix('\u{feff}').unwrap_or(text);
407 let mut lines = text
408 .split(['\r', '\n'])
409 .map(str::trim)
410 .filter(|line| !line.is_empty());
411 let Some(header) = lines.next().filter(|line| is_table_header(line)) else {
412 return false;
413 };
414 let names: Vec<&str> = header.split(',').map(str::trim).collect();
415 let find = |wanted: &str| {
416 names
417 .iter()
418 .position(|name| name.eq_ignore_ascii_case(wanted))
419 };
420 let (Some(state), Some(state_name)) = (find("state"), find("state_name")) else {
421 return false;
422 };
423 let mut checked = 0;
424 for line in lines.take(100) {
425 let cells: Vec<&str> = line.split(',').map(str::trim).collect();
426 if let (Some(number), Some(name)) = (cells.get(state), cells.get(state_name)) {
427 match state_pair(number, name) {
428 Ok(true) => checked += 1,
429 Ok(false) => {}
430 Err(_) => return false,
431 }
432 }
433 }
434 checked > 0
435}
436
437fn state_pair(number: &str, name: &str) -> Result<bool, String> {
441 use crate::altos_telem::STATES;
442 let by_number = number
444 .parse::<f64>()
445 .ok()
446 .and_then(|number| STATES.iter().find(|(known, _)| f64::from(*known) == number));
447 let by_name = STATES
448 .iter()
449 .find(|(_, known)| known.eq_ignore_ascii_case(name));
450 match (by_number, by_name) {
451 (None, None) => Ok(false),
452 (Some(a), Some(b)) if a == b => Ok(true),
453 (Some((known, partner)), _) => Err(format!(
454 "the row's state {known} is named {:?}, where AltOS names {known} `{partner}`",
455 short(name)
456 )),
457 (None, Some((partner, known))) => Err(format!(
458 "the row's state {:?} is named `{known}`, where AltOS numbers `{known}` {partner}",
459 short(number)
460 )),
461 }
462}
463
464impl Preamble {
465 fn read(&mut self, bare: &str) {
468 let Some((key, value)) = bare.split_once(char::is_whitespace) else {
469 return;
470 };
471 let value = value.trim();
472 if value.is_empty() {
473 return;
474 }
475 let slot = match key.to_ascii_lowercase().as_str() {
476 "product" => &mut self.product,
477 "serial" => &mut self.serial,
478 "flight" => &mut self.flight,
479 _ => return,
480 };
481 slot.get_or_insert_with(|| short(value));
482 }
483}
484
485#[derive(Debug, Clone, Copy)]
488struct Column {
489 role: Role,
490 known: bool,
491 unit: Unit,
492}
493
494fn named(names: &[String], wanted: &str) -> Option<usize> {
496 names
497 .iter()
498 .position(|name| split_unit(name).0.eq_ignore_ascii_case(wanted))
499}
500
501fn header_columns(names: &[String], number: usize) -> Result<Vec<Column>, LogError> {
503 let mut after_longitude = false;
504 let mut altitudes = 0;
505 let columns: Vec<Column> = names
506 .iter()
507 .map(|cell| {
508 let (name, unit) = split_unit(cell);
509 let lower = name.to_ascii_lowercase();
510 let gnss = after_longitude || (lower == "altitude" && altitudes > 0);
512 if lower == "altitude" {
513 altitudes += 1;
514 }
515 if lower == "longitude" {
516 after_longitude = true;
517 }
518 let (role, known) = role(name, gnss);
519 match unit {
520 None => Column {
521 role,
522 known,
523 unit: Unit::Unwritten,
524 },
525 Some(unit) if known && unit_agrees(role, unit) => Column {
526 role,
527 known,
528 unit: Unit::Agrees,
529 },
530 Some(_) => Column {
531 role: if known && role != Role::Text {
532 Role::Value(Quantity::Unrecognized)
533 } else {
534 role
535 },
536 known,
537 unit: Unit::Differs,
538 },
539 }
540 })
541 .collect();
542 match named(names, "time") {
543 Some(index) if columns[index].role == Role::Clock => Ok(columns),
544 Some(_) => Err(LogError::Syntax {
545 format: FORMAT,
546 line: number,
547 message: "the header writes a unit after `time` other than s".to_owned(),
548 }),
549 None => Err(LogError::Syntax {
550 format: FORMAT,
551 line: number,
552 message: "the header names no `time` column".to_owned(),
553 }),
554 }
555}
556
557const MAX_FORMULA_RUNS: usize = 8;
560
561#[derive(Debug, Clone)]
565struct Run {
566 formula: String,
567 first: usize,
568 last: usize,
569}
570
571const FORMULA_CHARS: usize = 200;
573
574const MAX_FORMULA_COLUMNS: usize = 64;
577
578#[derive(Debug, Clone, Default)]
580struct Formulas {
581 cells: usize,
583 runs: Vec<Run>,
585 left_out: usize,
587}
588
589impl Formulas {
590 fn add(&mut self, cell: &str, line: usize) {
593 self.cells += 1;
594 let formula = cut(&own_row(cell, line), FORMULA_CHARS);
595 if let Some(run) = self.runs.last_mut()
596 && self.left_out == 0
597 && run.formula == formula
598 && line == run.last + 1
599 {
600 run.last = line;
601 } else if self.runs.len() < MAX_FORMULA_RUNS && self.left_out == 0 {
602 self.runs.push(Run {
603 formula,
604 first: line,
605 last: line,
606 });
607 } else {
608 self.left_out += 1;
609 }
610 }
611}
612
613fn own_row(formula: &str, row: usize) -> String {
618 let row = row.to_string();
619 let bytes = formula.as_bytes();
620 let mut out = String::with_capacity(formula.len());
621 let mut at = 0;
622 while at < bytes.len() {
623 let letters = bytes[at..]
624 .iter()
625 .take_while(|b| b.is_ascii_uppercase())
626 .count();
627 let starts = at == 0 || !bytes[at - 1].is_ascii_alphanumeric();
628 if letters == 0 {
629 let next = formula[at..].chars().next().map_or(1, char::len_utf8);
631 out.push_str(&formula[at..at + next]);
632 at += next;
633 continue;
634 }
635 if !starts {
636 out.push_str(&formula[at..at + letters]);
640 at += letters;
641 continue;
642 }
643 let mut end = at + letters;
644 let dollar = bytes.get(end) == Some(&b'$');
645 if dollar {
646 end += 1;
647 }
648 let digits = bytes[end..]
649 .iter()
650 .take_while(|b| b.is_ascii_digit())
651 .count();
652 let after = bytes.get(end + digits);
653 let ends = after.is_none_or(|b| !b.is_ascii_alphanumeric() && *b != b'(');
654 if letters <= 3 && digits > 0 && ends && formula[end..end + digits] == row {
655 out.push_str(&formula[at..end]);
656 out.push_str("{row}");
657 } else {
658 out.push_str(&formula[at..end + digits]);
659 }
660 at = end + digits;
661 }
662 out
663}
664
665struct Table {
667 time_s: Vec<f64>,
669 lines: Vec<usize>,
671 values: Vec<Vec<f64>>,
674 gaps: Vec<usize>,
676 formulas: Vec<Formulas>,
678 states: Vec<String>,
680 clock: usize,
682 state: Option<usize>,
684 state_name: Option<usize>,
685 states_checked: usize,
687 bare: bool,
690 states_differing: usize,
693 first_differing: Option<String>,
694 serial: Option<usize>,
696 flight: Option<usize>,
697 first_serial: Option<String>,
699 first_flight: Option<String>,
700 rows: usize,
702 cells_written: usize,
703}
704
705impl Table {
706 fn new(names: &[String], columns: &[Column], bare: bool) -> Self {
707 Self {
708 time_s: Vec::new(),
709 lines: Vec::new(),
710 values: vec![Vec::new(); columns.len()],
711 gaps: vec![0; columns.len()],
712 formulas: vec![Formulas::default(); columns.len()],
713 states: Vec::new(),
714 clock: named(names, "time").unwrap_or(0),
716 state: named(names, "state"),
717 state_name: named(names, "state_name"),
718 states_checked: 0,
719 bare,
720 states_differing: 0,
721 first_differing: None,
722 serial: named(names, "serial"),
723 flight: named(names, "flight"),
724 first_serial: None,
725 first_flight: None,
726 rows: 0,
727 cells_written: 0,
728 }
729 }
730
731 fn row(
733 &mut self,
734 columns: &[Column],
735 line: &str,
736 number: usize,
737 notes: &mut Notes,
738 ) -> Result<(), LogError> {
739 let cells: Vec<&str> = line.split(',').map(str::trim).collect();
740 if cells.len() > columns.len() && cells[columns.len()..].iter().any(|c| !c.is_empty()) {
741 return Err(LogError::Syntax {
742 format: FORMAT,
743 line: number,
744 message: format!(
745 "the row has {} cells and the header names {}",
746 cells.len(),
747 columns.len()
748 ),
749 });
750 }
751 let cell = |index: Option<usize>| index.and_then(|index| cells.get(index).copied());
752 let Some(time) = cell(Some(self.clock)).and_then(number_in) else {
753 notes.push(format!(
754 "line {number} has no time and was left out: {:?}",
755 short(line)
756 ));
757 return Ok(());
758 };
759 if let (Some(state), Some(name)) = (cell(self.state), cell(self.state_name)) {
760 match state_pair(state, name) {
761 Ok(checked) => self.states_checked += usize::from(checked),
762 Err(message) if self.bare => {
763 return Err(LogError::Syntax {
764 format: FORMAT,
765 line: number,
766 message,
767 });
768 }
769 Err(message) => {
770 self.states_differing += 1;
771 self.first_differing
772 .get_or_insert_with(|| format!("line {number}: {message}"));
773 }
774 }
775 }
776 self.rows += 1;
777 self.cells_written += cells.len().min(columns.len());
778 if crate::log::too_sparse(columns.len(), self.rows, self.cells_written) {
779 return Err(LogError::Syntax {
780 format: FORMAT,
781 line: number,
782 message: format!(
783 "{} rows hold {} of the {} cells the header's {} columns name: too few for \
784 the header to be this file's",
785 self.rows,
786 self.cells_written,
787 self.rows.saturating_mul(columns.len()),
788 columns.len()
789 ),
790 });
791 }
792 if cells.len() < columns.len() {
793 notes.push(format!(
794 "line {number} has {} cells of the header's {}; the rest read as gaps",
795 cells.len(),
796 columns.len()
797 ));
798 }
799 if self.time_s.is_empty() {
800 self.first_serial = cell(self.serial).filter(|s| !s.is_empty()).map(short);
801 self.first_flight = cell(self.flight).filter(|s| !s.is_empty()).map(short);
802 }
803 self.time_s.push(time);
804 self.lines.push(number);
805 for (index, column) in columns.iter().enumerate() {
806 if matches!(column.role, Role::Clock | Role::Text) {
807 continue;
808 }
809 let value = match cells.get(index) {
812 Some(cell) if cell.starts_with('=') => {
813 self.formulas[index].add(cell, number);
814 f64::NAN
815 }
816 Some(cell) => number_in(cell).unwrap_or_else(|| {
817 self.gaps[index] += 1;
818 f64::NAN
819 }),
820 None => f64::NAN,
821 };
822 self.values[index].push(value);
823 }
824 if self.state_name.is_some() {
825 self.states
826 .push(cell(self.state_name).map(short).unwrap_or_default());
827 }
828 Ok(())
829 }
830}
831
832fn number_in(cell: &str) -> Option<f64> {
834 cell.parse::<f64>().ok().filter(|value| value.is_finite())
835}
836
837const PASCAL_LOW: f64 = 10_000.0;
840const PASCAL_HIGH: f64 = 120_000.0;
842
843fn pressure_factor(values: &[f64]) -> Option<f64> {
846 let highest = values
847 .iter()
848 .copied()
849 .filter(|value| value.is_finite())
850 .fold(f64::NEG_INFINITY, f64::max);
851 if (PASCAL_LOW..=PASCAL_HIGH).contains(&highest) {
852 Some(1.0)
853 } else if (PASCAL_LOW / 100.0..=PASCAL_HIGH / 100.0).contains(&highest) {
854 Some(100.0)
855 } else {
856 None
857 }
858}
859
860fn formula_runs(formulas: &Formulas) -> String {
863 let mut runs: Vec<String> = formulas
864 .runs
865 .iter()
866 .map(|run| {
867 let cells = run.last - run.first + 1;
868 let lines = if cells == 1 {
869 format!("line {}", run.first)
870 } else {
871 format!("lines {}–{}", run.first, run.last)
872 };
873 format!("`{}` on {lines}", run.formula)
874 })
875 .collect();
876 if formulas.left_out > 0 {
877 runs.push(format!(
878 "{} more past them",
879 count(formulas.left_out, "cell")
880 ));
881 }
882 runs.join("; ")
883}
884
885fn assemble(
891 names: &[String],
892 columns: &[Column],
893 mut table: Table,
894 preamble: &Preamble,
895 line_notes: Notes,
896 bare_table: bool,
897) -> Result<FlightLog, LogError> {
898 let mut notes: Vec<String> = Vec::new();
899 let mut column_notes = Notes::default();
900 let n = table.time_s.len();
901 let find = |wanted: &str, role: Role| {
904 named(names, wanted).filter(|&index| columns[index].role == role)
905 };
906 if let Some(first) = &table.first_differing {
907 notes.push(format!(
908 "{} a `state` and a `state_name` that aren't the pair AltOS's exports write, the \
909 first at {first}; the events take the names as written",
910 match table.states_differing {
911 1 => "1 row gives".to_owned(),
912 n => format!("{n} rows give"),
913 }
914 ));
915 }
916 if bare_table {
917 notes.push(format!(
918 "the header names AltOS's columns with no `version,serial,flight` before them. The \
919 table is read as AltOS's, as {} give a `state` and a `state_name` that AltOS's exports \
920 write for one state, and none contradicts them",
921 count(table.states_checked, "row")
922 ));
923 }
924
925 if let (Some(lat), Some(lon)) = (
927 find("latitude", Role::Value(Quantity::Latitude)),
928 find("longitude", Role::Value(Quantity::Longitude)),
929 ) {
930 let gnss: Vec<usize> = (0..columns.len())
931 .filter(|&index| columns[index].role == Role::Value(Quantity::GnssAltitude))
932 .collect();
933 let mut blanked = 0;
934 for row in 0..n {
935 if table.values[lat][row] == 0.0 && table.values[lon][row] == 0.0 {
936 blanked += 1;
937 for &index in gnss.iter().chain([&lat, &lon]) {
938 table.values[index][row] = f64::NAN;
939 }
940 }
941 }
942 if blanked > 0 {
943 notes.push(format!(
944 "{} placing the GPS at latitude 0, longitude 0 (AltOS's position before its \
945 receiver has a fix). Their latitude, longitude and GPS altitude read as gaps",
946 count(blanked, "row")
947 ));
948 }
949 }
950
951 let mut channels = Vec::with_capacity(columns.len());
952 let mut converted: Vec<Option<Vec<f64>>> = vec![None; columns.len()];
953 let mut units_agreeing = Vec::new();
954 let mut formula_notes: Vec<String> = Vec::new();
955 let mut formula_columns_left_out = 0;
956 let mut formula_note = |note: String| {
957 if formula_notes.len() < MAX_FORMULA_COLUMNS {
958 formula_notes.push(note);
959 } else {
960 formula_columns_left_out += 1;
961 }
962 };
963 for (index, column) in columns.iter().enumerate() {
964 let name = &names[index];
965 let mut values = std::mem::take(&mut table.values[index]);
966 let formulas = &table.formulas[index];
967 if formulas.cells > 0 && formulas.cells == n {
968 formula_note(format!(
970 "the `{}` column's {} a spreadsheet's {}, not {}. The column is not a channel. \
971 Each formula is kept here as text, not worked out. `{{row}}` stands for each \
972 cell's own row: {}",
973 short(name),
974 match formulas.cells {
975 1 => "1 cell is".to_owned(),
976 cells => format!("{cells} cells are"),
977 },
978 if formulas.cells == 1 {
979 "formula"
980 } else {
981 "formulas"
982 },
983 if formulas.cells == 1 {
984 "a value"
985 } else {
986 "values"
987 },
988 formula_runs(formulas)
989 ));
990 continue;
991 }
992 if formulas.cells > 0 {
993 formula_note(format!(
994 "the `{}` column has {} holding a spreadsheet's formula, not a value. The cells \
995 read as gaps, and the formulas are kept here as text. `{{row}}` stands for \
996 each cell's own row: {}",
997 short(name),
998 count(formulas.cells, "cell"),
999 formula_runs(formulas)
1000 ));
1001 }
1002 let quantity = match column.role {
1003 Role::Clock | Role::Text => continue,
1004 Role::Value(quantity) => quantity,
1005 Role::Celsius => {
1006 for value in &mut values {
1007 *value += 273.15;
1008 }
1009 Quantity::Temperature
1010 }
1011 Role::Pressure => match pressure_factor(&values) {
1012 Some(factor) if factor != 1.0 && column.unit == Unit::Agrees => {
1013 notes.push(format!(
1014 "the `{}` column states Pa, but its highest value is a pad's pressure \
1015 in hPa; it is kept as written",
1016 short(name)
1017 ));
1018 Quantity::Unrecognized
1019 }
1020 Some(factor) => {
1021 if factor != 1.0 {
1022 for (value, &line) in values.iter_mut().zip(&table.lines) {
1025 *value = finite(*value * factor, FORMAT, line, name)?;
1026 }
1027 notes.push(format!(
1028 "the `{}` column never reaches 1,200 and was read as hPa, not Pa",
1029 short(name)
1030 ));
1031 }
1032 Quantity::Pressure
1033 }
1034 None => {
1035 notes.push(format!(
1036 "the `{}` column's highest value isn't a pad's pressure in Pa or hPa; it \
1037 is kept as written",
1038 short(name)
1039 ));
1040 Quantity::Unrecognized
1041 }
1042 },
1043 };
1044 match column.unit {
1045 Unit::Unwritten => {}
1046 Unit::Agrees => units_agreeing.push(format!("`{}`", short(name))),
1047 Unit::Differs if column.known => column_notes.push(format!(
1048 "the header writes `{}`, a unit after AltOS's `{}` that isn't the one this \
1049 reader reads it in; its values are kept as written",
1050 short(name),
1051 short(split_unit(name).0)
1052 )),
1053 Unit::Differs => {}
1054 }
1055 if !column.known {
1056 column_notes.push(format!(
1057 "the column `{}` isn't one this reader knows; its values are kept as written",
1058 short(name)
1059 ));
1060 }
1061 if table.gaps[index] > 0 {
1062 column_notes.push(format!(
1063 "the `{}` column has {} empty or not a number (AltosUI writes `NaN` where it \
1064 has no value), read as gaps",
1065 short(name),
1066 count(table.gaps[index], "cell")
1067 ));
1068 }
1069 converted[index] = Some(values.clone());
1070 channels.push(Channel {
1071 column: name.clone(),
1072 quantity,
1073 time_s: table.time_s.clone(),
1074 values,
1075 });
1076 }
1077 if !units_agreeing.is_empty() {
1078 notes.push(format!(
1079 "the header writes a unit after AltOS's name of {}: each the unit this reader reads \
1080 the column in, so read as AltOS's",
1081 units_agreeing.join(", ")
1082 ));
1083 }
1084 if find("acceleration", Role::Value(Quantity::Acceleration)).is_some() {
1085 notes.push(
1086 "AltOS writes `acceleration` with gravity taken out: it reads about 0 at rest, not \
1087 1 g; the channel is kept as written"
1088 .to_owned(),
1089 );
1090 }
1091
1092 let named_height = find("height", Role::Value(Quantity::AltitudeAboveGround));
1095 let height = named_height.filter(|&index| converted[index].is_some());
1096 let mut order: Vec<usize> = (0..n).collect();
1097 order.sort_by(|&a, &b| table.time_s[a].total_cmp(&table.time_s[b]));
1098 let mut latest = f64::NEG_INFINITY;
1099 let out_of_order = table
1100 .time_s
1101 .iter()
1102 .filter(|&&time| {
1103 let early = time < latest;
1104 latest = latest.max(time);
1105 early
1106 })
1107 .count();
1108 let mut kept: Vec<usize> = Vec::with_capacity(n);
1109 for row in order {
1110 match kept.last() {
1111 Some(&last) if table.time_s[last] == table.time_s[row] => {}
1112 _ => kept.push(row),
1113 }
1114 }
1115 if height.is_none() {
1116 kept.clear();
1117 notes.push(if named_height.is_some() {
1118 "the `height` column, AltOS's height above the pad, holds a spreadsheet's formulas \
1119 alone: the record has no primary track, only its channels"
1120 .to_owned()
1121 } else {
1122 "the header names no `height`, AltOS's height above the pad: the record has no \
1123 primary track, only its channels"
1124 .to_owned()
1125 });
1126 } else {
1127 if out_of_order > 0 {
1128 notes.push(format!(
1129 "{} coming before an earlier row's time: the primary track takes the rows in \
1130 time order; the channels keep the file's",
1131 count(out_of_order, "row")
1132 ));
1133 }
1134 if kept.len() < n {
1135 notes.push(format!(
1136 "{} repeating an earlier row's time: the primary track keeps the first row at \
1137 each time; the channels keep every row",
1138 count(n - kept.len(), "row")
1139 ));
1140 }
1141 }
1142 let primary = |index: Option<usize>| {
1143 index
1144 .filter(|_| height.is_some())
1145 .and_then(|index| converted[index].as_ref())
1146 .map(|values| kept.iter().map(|&row| values[row]).collect::<Vec<f64>>())
1147 };
1148 let speed = find("baro_speed", Role::Value(Quantity::Speed));
1151
1152 let mut events: Vec<Event> = Vec::new();
1153 let mut state: Option<&str> = None;
1154 for (row, name) in table.states.iter().enumerate() {
1155 if !name.is_empty() && state != Some(name.as_str()) {
1156 events.push(Event {
1157 time_s: table.time_s[row],
1158 name: name.clone(),
1159 });
1160 state = Some(name.as_str());
1161 }
1162 }
1163
1164 let serial_number = preamble
1165 .serial
1166 .clone()
1167 .or_else(|| table.first_serial.clone());
1168 if let (Some(stated), Some(written)) = (&preamble.serial, &table.first_serial)
1169 && stated != written
1170 {
1171 notes.push(format!(
1172 "the comment lines give the serial number as {stated:?} and the rows as {written:?}; \
1173 the comment lines' is kept"
1174 ));
1175 }
1176 let flight = preamble.flight.as_ref().or(table.first_flight.as_ref());
1177 let flight_number = flight.and_then(|flight| flight.parse().ok());
1178 if flight.is_some() && flight_number.is_none() {
1179 notes.push(format!(
1180 "the flight number {:?} isn't a whole number and was left out",
1181 flight.map(String::as_str).unwrap_or_default()
1182 ));
1183 }
1184
1185 notes.extend(formula_notes);
1186 if formula_columns_left_out > 0 {
1187 notes.push(format!(
1188 "and {} holding formulas, past the {MAX_FORMULA_COLUMNS} whose formulas are given",
1189 count(formula_columns_left_out, "more column")
1190 ));
1191 }
1192 notes.extend(column_notes.kept);
1193 notes.extend(line_notes.kept);
1194 let left_out = column_notes.left_out + line_notes.left_out;
1195 if left_out > 0 {
1196 notes.push(format!(
1197 "and {left_out} more notes about single columns and lines, left out so that a \
1198 broken file's list stays short"
1199 ));
1200 }
1201
1202 Ok(FlightLog {
1203 format: LogFormat::AltosCsv,
1204 logger: match &preamble.product {
1205 Some(product) => format!("AltOS {product}"),
1206 None => "AltOS".to_owned(),
1207 },
1208 serial_number,
1209 firmware: None,
1210 flight_number,
1211 stated: Stated::default(),
1212 time_s: kept.iter().map(|&row| table.time_s[row]).collect(),
1213 altitude_m: primary(height).unwrap_or_default(),
1214 vertical_speed_m_s: primary(speed),
1215 temperature_k: primary(find("temperature", Role::Celsius)),
1216 battery_v: primary(find("battery_voltage", Role::Value(Quantity::Voltage))),
1217 channels,
1218 events,
1219 notes,
1220 })
1221}
1222
1223fn count(n: usize, noun: &str) -> String {
1225 if n == 1 {
1226 format!("1 {noun}")
1227 } else {
1228 format!("{n} {noun}s")
1229 }
1230}
1231
1232fn short(text: &str) -> String {
1235 cut(text, QUOTED_CHARS)
1236}
1237
1238fn cut(text: &str, chars: usize) -> String {
1240 if text.chars().count() <= chars {
1241 text.to_owned()
1242 } else {
1243 let mut cut: String = text.chars().take(chars - 1).collect();
1244 cut.push('…');
1245 cut
1246 }
1247}
1248
1249#[cfg(test)]
1250mod tests {
1251 use super::*;
1252
1253 const HEAD: &str = "#version,serial,flight,call,time,rssi,lqi,state,state_name,acceleration,\
1254 pressure,altitude,height,baro_speed,temperature,battery_voltage\n";
1255
1256 fn row(time: f64, state: &str, height: f64) -> String {
1258 let number = crate::altos_telem::STATES
1259 .iter()
1260 .find(|(_, name)| *name == state)
1261 .map_or(2, |(number, _)| *number);
1262 format!(
1263 "6, 77, 4,N0CALL, {time:8.2}, -80, 40, {number}, {state:>7}, 0.10, 98000.00, \
1264 {:.2}, {height:.2}, 1.50, 20.0, 3.90\n",
1265 250.0 + height
1266 )
1267 }
1268
1269 #[test]
1272 fn reads_columns_and_the_primary_track() {
1273 let text = format!("{HEAD}{}{}", row(-0.5, "pad", 0.0), row(0.0, "boost", 1.25));
1274 let log = read(&text).unwrap();
1275 assert_eq!(log.format, LogFormat::AltosCsv);
1276 assert_eq!(log.logger, "AltOS");
1277 assert_eq!(log.serial_number.as_deref(), Some("77"));
1278 assert_eq!(log.flight_number, Some(4));
1279 assert_eq!(log.firmware, None);
1280 assert_eq!(log.time_s, [-0.5, 0.0]);
1281 assert_eq!(log.altitude_m, [0.0, 1.25]);
1282 assert_eq!(log.vertical_speed_m_s.as_deref(), Some(&[1.5, 1.5][..]));
1283 assert_eq!(log.temperature_k.as_deref(), Some(&[293.15, 293.15][..]));
1284 assert_eq!(log.battery_v.as_deref(), Some(&[3.9, 3.9][..]));
1285 let names: Vec<&str> = log.channels.iter().map(|c| c.column.as_str()).collect();
1286 assert_eq!(
1287 names,
1288 [
1289 "version",
1290 "serial",
1291 "flight",
1292 "rssi",
1293 "lqi",
1294 "state",
1295 "acceleration",
1296 "pressure",
1297 "altitude",
1298 "height",
1299 "baro_speed",
1300 "temperature",
1301 "battery_voltage"
1302 ]
1303 );
1304 let pressure = log.channels_of(Quantity::Pressure).next().unwrap();
1305 assert_eq!(pressure.values, [98000.0, 98000.0]);
1306 assert_eq!(log.channels_of(Quantity::AltitudeMsl).count(), 1);
1307 assert_eq!(
1308 log.events,
1309 [
1310 Event {
1311 time_s: -0.5,
1312 name: "pad".to_owned()
1313 },
1314 Event {
1315 time_s: 0.0,
1316 name: "boost".to_owned()
1317 }
1318 ]
1319 );
1320 assert_eq!(log.notes.len(), 1, "{:?}", log.notes);
1321 assert!(log.notes[0].contains("gravity taken out"));
1322 }
1323
1324 #[test]
1327 fn the_second_altitude_is_the_gps_and_zero_zero_is_no_fix() {
1328 let text = "#version,serial,flight,time,state_name,altitude,height,latitude,longitude,\
1329 altitude,nsat,sat01,pad_dist,pad_az,tilt,gyro_roll\n\
1330 6,1,1,0.0,pad,250,0,0,0,0,0,0,0,0,NaN,1\n\
1331 6,1,1,0.5,pad,250,0,40.5,-105.25,251.5,7,31,3,90,2.5,1\n";
1332 let log = read(text).unwrap();
1333 let quantities: Vec<Quantity> = log.channels.iter().map(|c| c.quantity).collect();
1334 use Quantity as Q;
1335 assert_eq!(
1336 quantities,
1337 [
1338 Q::Number,
1339 Q::Number,
1340 Q::Number,
1341 Q::AltitudeMsl,
1342 Q::AltitudeAboveGround,
1343 Q::Latitude,
1344 Q::Longitude,
1345 Q::GnssAltitude,
1346 Q::Number,
1347 Q::Number,
1348 Q::Distance,
1349 Q::Angle,
1350 Q::Angle,
1351 Q::Unrecognized
1352 ]
1353 );
1354 let gnss = log.channels_of(Q::GnssAltitude).next().unwrap();
1355 assert_eq!(gnss.column, "altitude");
1356 assert!(gnss.values[0].is_nan());
1357 assert_eq!(gnss.values[1], 251.5);
1358 let latitude = log.channels_of(Q::Latitude).next().unwrap();
1359 assert!(latitude.values[0].is_nan());
1360 assert_eq!(latitude.values[1], 40.5);
1361 let baro = log.channels_of(Q::AltitudeMsl).next().unwrap();
1363 assert_eq!(baro.values, [250.0, 250.0]);
1364 assert!(
1365 log.notes
1366 .iter()
1367 .any(|n| n.starts_with("1 row placing the GPS")),
1368 "{:?}",
1369 log.notes
1370 );
1371 assert!(
1372 log.notes
1373 .iter()
1374 .any(|n| n.contains("`tilt` column has 1 cell empty")),
1375 "{:?}",
1376 log.notes
1377 );
1378 assert!(log.vertical_speed_m_s.is_none() && log.temperature_k.is_none());
1380 assert!(log.battery_v.is_none());
1381 }
1382
1383 #[test]
1386 fn repeated_and_reordered_times() {
1387 let text = format!(
1388 "{HEAD}{}{}{}{}",
1389 row(0.0, "pad", 0.0),
1390 row(0.5, "boost", 5.0),
1391 row(0.5, "boost", 6.0),
1392 row(0.25, "boost", 2.0)
1393 );
1394 let log = read(&text).unwrap();
1395 assert_eq!(log.time_s, [0.0, 0.25, 0.5]);
1396 assert_eq!(log.altitude_m, [0.0, 2.0, 5.0]);
1397 let height = log
1398 .channels_of(Quantity::AltitudeAboveGround)
1399 .next()
1400 .unwrap();
1401 assert_eq!(height.time_s, [0.0, 0.5, 0.5, 0.25]);
1402 assert_eq!(height.values, [0.0, 5.0, 6.0, 2.0]);
1403 assert!(
1404 log.notes
1405 .iter()
1406 .any(|n| n.starts_with("1 row coming before")),
1407 "{:?}",
1408 log.notes
1409 );
1410 assert!(
1411 log.notes.iter().any(|n| n.starts_with("1 row repeating")),
1412 "{:?}",
1413 log.notes
1414 );
1415 let names: Vec<&str> = log.events.iter().map(|e| e.name.as_str()).collect();
1417 assert_eq!(names, ["pad", "boost"]);
1418 }
1419
1420 #[test]
1422 fn comment_lines_name_the_logger() {
1423 let text = "\u{feff}# Altus Metrum flight log\r\n# product TeleMetrum\r\n# serial 2001\r\n\
1424 # flight 3\r\n# call N0CALL\r\nversion,serial,flight,time,state_name,height\r\n\
1425 5,2002,3,0.00,pad,0.0\r\n";
1426 let log = read(text).unwrap();
1427 assert_eq!(log.logger, "AltOS TeleMetrum");
1428 assert_eq!(log.serial_number.as_deref(), Some("2001"));
1429 assert_eq!(log.flight_number, Some(3));
1430 assert!(
1431 log.notes
1432 .iter()
1433 .any(|n| n.contains("\"2001\" and the rows as \"2002\"")),
1434 "{:?}",
1435 log.notes
1436 );
1437 }
1438
1439 #[test]
1442 fn a_value_its_conversion_makes_infinite_is_refused() {
1443 let head = "#version,serial,flight,time,state_name,pressure,height\n";
1444 let text = format!("{head}5,1,1,0,pad,983.25,0\n5,1,1,1,pad,-1.7e308,10\n");
1445 assert_eq!(
1446 read(&text).unwrap_err().to_string(),
1447 "AltOS CSV line 3: the column pressure holds a value too large for its unit's \
1448 conversion to SI"
1449 );
1450 }
1451
1452 #[test]
1454 fn pressure_unit_from_its_highest_value() {
1455 let head = "#version,serial,flight,time,state_name,pressure,height\n";
1456 let log = read(&format!(
1457 "{head}5,1,1,0,pad,983.25,0\n5,1,1,1,pad,950.5,10\n"
1458 ))
1459 .unwrap();
1460 let pressure = log.channels_of(Quantity::Pressure).next().unwrap();
1461 assert_eq!(pressure.values, [98325.0, 95050.0]);
1462 assert!(
1463 log.notes.iter().any(|n| n.contains("read as hPa")),
1464 "{:?}",
1465 log.notes
1466 );
1467
1468 let log = read(&format!("{head}5,1,1,0,pad,98.3,0\n")).unwrap();
1469 assert_eq!(log.channels_of(Quantity::Pressure).count(), 0);
1470 let kept = log
1471 .channels
1472 .iter()
1473 .find(|c| c.column == "pressure")
1474 .unwrap();
1475 assert_eq!(
1476 (kept.quantity, kept.values[0]),
1477 (Quantity::Unrecognized, 98.3)
1478 );
1479
1480 assert_eq!(pressure_factor(&[1200.0, f64::NAN]), Some(100.0));
1482 assert_eq!(pressure_factor(&[10_000.0]), Some(1.0));
1483 assert_eq!(pressure_factor(&[120_000.0]), Some(1.0));
1484 assert_eq!(pressure_factor(&[1200.5]), None);
1485 assert_eq!(pressure_factor(&[120_000.5]), None);
1486 assert_eq!(pressure_factor(&[f64::NAN]), None);
1487 }
1488
1489 #[test]
1492 fn odd_rows_and_columns() {
1493 let text = "#version,serial,flight,time,state_name,height,widget\n\
1494 6,1,1,0.0,pad,0,5,,\n\
1495 6,1,1,,pad,0,5\n\
1496 6,1,1,1.0,boost,3\n";
1497 let log = read(text).unwrap();
1498 assert_eq!(log.time_s, [0.0, 1.0]);
1499 let widget = log.channels.iter().find(|c| c.column == "widget").unwrap();
1500 assert_eq!(widget.quantity, Quantity::Unrecognized);
1501 assert_eq!(widget.values[0], 5.0);
1502 assert!(widget.values[1].is_nan());
1503 let expected = [
1504 "the column `widget` isn't one this reader knows",
1505 "line 3 has no time and was left out",
1506 "line 4 has 6 cells of the header's 7",
1507 ];
1508 for text in expected {
1509 assert!(
1510 log.notes.iter().any(|n| n.starts_with(text)),
1511 "{text}: {:?}",
1512 log.notes
1513 );
1514 }
1515 assert_eq!(log.notes.len(), expected.len(), "{:?}", log.notes);
1517 }
1518
1519 #[test]
1521 fn notes_stay_few() {
1522 let text = format!(
1523 "#version,serial,flight,time,height\n{}0,1,1,0,0\n",
1524 "0,1,1,x,0\n".repeat(1000)
1525 );
1526 let log = read(&text).unwrap();
1527 assert_eq!(log.notes.len(), MAX_NOTES + 1);
1528 assert!(
1529 log.notes[MAX_NOTES].starts_with("and 980 more notes"),
1530 "{:?}",
1531 log.notes
1532 );
1533 }
1534
1535 #[test]
1537 fn malformed_files_are_refused() {
1538 let cases = [
1539 ("", "not read as AltOS CSV: the file has no"),
1540 ("# just a comment\n", "has no `version,serial,flight"),
1541 (
1542 "time,height\n0,0\n",
1543 "line 1, \"time,height\", isn't AltOS's header",
1544 ),
1545 ("PerfectFlite Pnut\n", "isn't AltOS's header"),
1546 (
1547 "#version,serial,flight,time (ms)\n0,0,0,0\n",
1548 "line 1: the header writes a unit after `time` other than s",
1549 ),
1550 (
1551 "#version,serial,flight,height\n0,0,0,0\n",
1552 "line 1: the header names no `time`",
1553 ),
1554 ("#version,serial,flight,time,height\n", "no data rows"),
1555 (
1556 "#version,serial,flight,time,height\n0,0,0,x,0\n",
1557 "no data rows",
1558 ),
1559 (
1560 "#version,serial,flight,time,height\n0,0,0,0,0,7\n",
1561 "line 2: the row has 6 cells and the header names 5",
1562 ),
1563 ];
1564 for (text, expected) in cases {
1565 let error = read(text).unwrap_err().to_string();
1566 assert!(error.contains(expected), "{text:?}: {error}");
1567 }
1568 let junk = "\u{fffd}".repeat(100_000);
1569 let error = read(&junk).unwrap_err().to_string();
1570 assert!(error.len() < 400 && error.contains('…'), "{error}");
1571 }
1572
1573 #[test]
1575 fn no_height_no_primary_track() {
1576 let log = read("#version,serial,flight,time,altitude\n6,77,4,0.5,250\n").unwrap();
1577 assert!(log.time_s.is_empty() && log.altitude_m.is_empty());
1578 assert!(log.temperature_k.is_none() && log.battery_v.is_none());
1579 let altitude = log
1580 .channels
1581 .iter()
1582 .find(|c| c.column == "altitude")
1583 .unwrap();
1584 assert_eq!(
1585 (altitude.quantity, altitude.values.as_slice()),
1586 (Quantity::AltitudeMsl, &[250.0][..])
1587 );
1588 assert!(log.notes.iter().any(|n| n.contains("no primary track")));
1589 }
1590
1591 #[test]
1594 fn units_after_the_names() {
1595 let text = "#version,serial,flight,time,height (m),acceleration (m/s^2),accel_x (m/s),\
1596 pressure (Pa)\n6,77,4,0.5,10,1.5,9.8,980\n";
1597 let log = read(text).unwrap();
1598 let quantity = |column: &str| {
1599 log.channels
1600 .iter()
1601 .find(|c| c.column == column)
1602 .map(|c| c.quantity)
1603 };
1604 assert_eq!(log.altitude_m, [10.0]);
1605 assert_eq!(
1606 quantity("acceleration (m/s^2)"),
1607 Some(Quantity::Acceleration)
1608 );
1609 assert_eq!(quantity("accel_x (m/s)"), Some(Quantity::Unrecognized));
1610 assert_eq!(quantity("pressure (Pa)"), Some(Quantity::Unrecognized));
1611 assert!(
1612 log.notes
1613 .iter()
1614 .any(|n| n.contains("`accel_x (m/s)`, a unit"))
1615 );
1616 let feet = read("#version,serial,flight,time,height (ft)\n6,77,4,0.5,10\n").unwrap();
1617 assert!(
1618 feet.altitude_m.is_empty(),
1619 "a height in feet isn't AltOS's height"
1620 );
1621 }
1622
1623 #[test]
1626 fn a_height_of_formulas_alone_is_no_primary_track() {
1627 let text = "#version,serial,flight,time,height,altitude\n\
1628 6,77,4,0.5,=F2-F$2,250\n\
1629 6,77,4,0.6,=F3-F$2,251\n";
1630 let log = read(text).unwrap();
1631 assert!(log.time_s.is_empty() && log.altitude_m.is_empty());
1632 assert!(log.channels.iter().all(|c| c.column != "height"));
1633 assert!(
1634 log.notes.iter().any(|n| n.starts_with(
1635 "the `height` column, AltOS's height above the pad, holds a spreadsheet's \
1636 formulas alone"
1637 )),
1638 "{:#?}",
1639 log.notes
1640 );
1641 }
1642
1643 #[test]
1645 fn one_formula_cell_reads_in_the_singular() {
1646 let log = read("#version,serial,flight,time,height,x\n6,77,4,0.5,0,=E2*2\n").unwrap();
1647 assert!(
1648 log.notes.iter().any(|n| n.starts_with(
1649 "the `x` column's 1 cell is a spreadsheet's formula, not a value. The column"
1650 )),
1651 "{:#?}",
1652 log.notes
1653 );
1654 }
1655
1656 #[test]
1659 fn the_formula_bounds_hold_at_their_limits() {
1660 let runs = |extra: usize| {
1661 let mut text = String::from("#version,serial,flight,time,height,x\n");
1662 for k in 0..MAX_FORMULA_RUNS + extra {
1663 text += &format!("6,77,4,{k}.0,{k},=E{}*{k}\n", k + 2);
1664 }
1665 let log = read(&text).unwrap();
1666 log.notes
1667 .into_iter()
1668 .find(|n| n.starts_with("the `x` column's"))
1669 .unwrap()
1670 };
1671 let at = runs(0);
1672 assert_eq!(at.matches("` on line ").count(), MAX_FORMULA_RUNS, "{at}");
1673 assert!(!at.contains("past them"), "{at}");
1674 let past = runs(2);
1675 assert_eq!(
1676 past.matches("` on line ").count(),
1677 MAX_FORMULA_RUNS,
1678 "{past}"
1679 );
1680 assert!(past.ends_with("; 2 cells more past them"), "{past}");
1681
1682 let columns = |n: usize| {
1683 let names: Vec<String> = (0..n).map(|k| format!("x{k}")).collect();
1684 let cells: Vec<String> = (0..n).map(|k| format!("={k}")).collect();
1685 let text = format!(
1686 "#version,serial,flight,time,height,{}\n6,77,4,0.0,0,{}\n",
1687 names.join(","),
1688 cells.join(",")
1689 );
1690 read(&text).unwrap().notes
1691 };
1692 let given = |notes: &[String]| notes.iter().filter(|n| n.starts_with("the `x")).count();
1693 assert_eq!(given(&columns(MAX_FORMULA_COLUMNS)), MAX_FORMULA_COLUMNS);
1694 let past = columns(MAX_FORMULA_COLUMNS + 3);
1695 assert_eq!(given(&past), MAX_FORMULA_COLUMNS);
1696 assert!(
1697 past.iter()
1698 .any(|n| n.contains("past the 64 whose formulas are given")),
1699 "{past:#?}"
1700 );
1701 }
1702
1703 #[test]
1706 fn a_rewritten_state_and_a_byte_order_mark_still_read() {
1707 let text = "\u{feff}time,state,state_name,height\n0.0,3.0,boost,0\n0.1,5.0,coast,2\n";
1708 assert!(recognizes_table(text));
1709 let log = read(text).unwrap();
1710 let events: Vec<&str> = log.events.iter().map(|e| e.name.as_str()).collect();
1711 assert_eq!(events, ["boost", "coast"]);
1712 }
1713
1714 #[test]
1717 fn formulas_are_kept_as_text() {
1718 let text = "#version,serial,flight,time,height,altitude (ft),(ft/s)\n\
1719 6,77,4,0.0,0,=3.28084*E2,=3.28*E2\n\
1720 6,77,4,0.5,10,=3.28*E3,1.5\n\
1721 6,77,4,1.0,20,=3.28*E4,=3.28*E4\n\
1722 6,77,4,1.5,30,=3.28*E5,=3.28*E5\n";
1723 let log = read(text).unwrap();
1724 assert_eq!(log.altitude_m, [0.0, 10.0, 20.0, 30.0]);
1725 assert!(log.channels.iter().all(|c| c.column != "altitude (ft)"));
1726 let note = |start: &str| {
1727 log.notes
1728 .iter()
1729 .find(|n| n.starts_with(start))
1730 .unwrap_or_else(|| panic!("{start}: {:#?}", log.notes))
1731 };
1732 let all = note("the `altitude (ft)` column's 4 cells are a spreadsheet's formulas");
1733 assert!(
1734 all.ends_with("`=3.28084*E{row}` on line 2; `=3.28*E{row}` on lines 3–5"),
1735 "{all}"
1736 );
1737 let mixed = note("the `(ft/s)` column has 3 cells holding");
1738 assert!(
1739 mixed.ends_with("`=3.28*E{row}` on line 2; `=3.28*E{row}` on lines 4–5"),
1740 "{mixed}"
1741 );
1742 let speed = log.channels.iter().find(|c| c.column == "(ft/s)").unwrap();
1743 assert_eq!(speed.values[1], 1.5);
1744 assert!(speed.values[0].is_nan() && speed.values[3].is_nan());
1745 }
1746
1747 #[test]
1752 #[allow(clippy::disallowed_types, reason = "the clock times the read alone")]
1753 fn a_long_run_of_capitals_in_a_formula_reads_in_linear_time() {
1754 let letters = "A".repeat(600_000);
1755 let text = format!(
1756 "#version,serial,flight,time,height,altitude (ft)\n\
1757 6,77,4,0.0,0,=1{letters}\n\
1758 6,77,4,0.5,10,1\n"
1759 );
1760 let began = std::time::Instant::now();
1761 let log = read(&text).unwrap();
1762 let elapsed = began.elapsed();
1763 assert_eq!(log.altitude_m, [0.0, 10.0]);
1764 let short = "A".repeat(1_000);
1766 assert_eq!(
1767 own_row(&format!("=1{short}+J2"), 2),
1768 format!("=1{short}+J{{row}}")
1769 );
1770 assert!(elapsed.as_secs_f64() < 5.0, "{elapsed:?}");
1771 }
1772
1773 #[test]
1775 fn own_row_rewrites_references_to_the_row_only() {
1776 assert_eq!(own_row("=3.28*J2", 2), "=3.28*J{row}");
1777 assert_eq!(own_row("=AL12-AL$2+J$12", 12), "=AL{row}-AL$2+J${row}");
1778 assert_eq!(own_row("=LOG10(J10)", 10), "=LOG10(J{row})");
1779 assert_eq!(own_row("=ABCD7+A7B", 7), "=ABCD7+A7B");
1780 assert_eq!(own_row("=J22*2", 2), "=J22*2");
1781 assert_eq!(own_row("=é+J3", 3), "=é+J{row}");
1782 }
1783
1784 #[test]
1787 fn a_state_unlike_altoss_is_refused() {
1788 let head = "time,state,state_name,height\n-0.5,2,pad,0\n";
1789 let error = read(&format!("{head}0.0,3,ignition,0\n"))
1790 .unwrap_err()
1791 .to_string();
1792 assert!(
1793 error.contains(
1794 "line 3: the row's state 3 is named \"ignition\", where AltOS names 3 `boost`"
1795 ),
1796 "{error}"
1797 );
1798 let error = read(&format!("{head}0.0,4,boost,0\n"))
1799 .unwrap_err()
1800 .to_string();
1801 assert!(
1802 error.contains("line 3: the row's state 4 is named"),
1803 "{error}"
1804 );
1805 let error = read(&format!("{head}0.0,12,boost,0\n"))
1806 .unwrap_err()
1807 .to_string();
1808 assert!(error.contains("where AltOS numbers `boost` 3"), "{error}");
1809 assert!(read(&format!("{head}0.0,9,invalid,0\n")).is_ok());
1810 }
1811
1812 #[test]
1815 fn an_exports_state_unlike_altoss_is_noted() {
1816 let text = format!(
1817 "{HEAD}{}{}",
1818 row(-0.5, "pad", 0.0).replacen(", 2,", ", 1,", 1),
1819 row(0.0, "boost", 1.25)
1820 );
1821 let log = read(&text).unwrap();
1822 let note = log
1823 .notes
1824 .iter()
1825 .find(|n| n.starts_with("1 row gives a `state`"))
1826 .unwrap_or_else(|| panic!("{:#?}", log.notes));
1827 assert!(
1828 note.contains("the first at line 2: the row's state \"1\" is named `pad`"),
1829 "{note}"
1830 );
1831 let events: Vec<&str> = log.events.iter().map(|e| e.name.as_str()).collect();
1832 assert_eq!(events, ["pad", "boost"]);
1833 }
1834
1835 #[test]
1839 fn a_table_of_altoss_columns_reads_by_its_states() {
1840 let text = "time,state,state_name,acceleration,pressure,altitude,height,speed,temperature\n\
1841 -0.10,3,boost,9.1,95300,512.7,5.2,15.8,23.7\n\
1842 0.00,3,boost,10.0,95290,513.5,6.0,16.8,23.7\n\
1843 0.10,5,coast,-9.8,95200,521.6,14.1,15.0,23.7\n";
1844 assert!(recognizes_table(text));
1845 assert_eq!(
1846 crate::import::detect(text.as_bytes()),
1847 Some(LogFormat::AltosCsv)
1848 );
1849 let log = read(text).unwrap();
1850 assert_eq!(log.altitude_m, [5.2, 6.0, 14.1]);
1851 assert_eq!(log.serial_number, None);
1852 let events: Vec<&str> = log.events.iter().map(|e| e.name.as_str()).collect();
1853 assert_eq!(events, ["boost", "coast"]);
1854 assert!(
1855 log.notes
1856 .iter()
1857 .any(|n| n.starts_with("the header names AltOS's columns"))
1858 );
1859 let unknown = text
1860 .replace("3,boost", "1,idle")
1861 .replace("5,coast", "0,startup");
1862 assert!(!recognizes_table(&unknown));
1863 assert!(
1864 read(&unknown)
1865 .unwrap_err()
1866 .to_string()
1867 .contains("by its states")
1868 );
1869 assert!(!recognizes_table(&text.replace("speed,", "speed (m/s),")));
1870 assert!(!recognizes_table(&text.replace("speed,", "source,")));
1871 assert!(!recognizes_table(&text.replace("5,coast", "5,boost")));
1872 assert!(read(&format!("# product EasyMini\n{text}")).is_err());
1873 }
1874
1875 proptest::proptest! {
1876 #[test]
1879 fn any_text_is_read_or_refused(
1880 text in "(#version,serial,flight,time,height,state_name,altitude,longitude,altitude\n)?\
1881 ([-0-9., NaN#a-z]{0,24}\n){0,12}"
1882 ) {
1883 if let Ok(log) = read(&text) {
1884 proptest::prop_assert!(log.time_s.windows(2).all(|pair| pair[1] > pair[0]));
1885 proptest::prop_assert_eq!(log.time_s.len(), log.altitude_m.len());
1886 for channel in &log.channels {
1887 proptest::prop_assert_eq!(channel.time_s.len(), channel.values.len());
1888 }
1889 }
1890 }
1891 }
1892}