1use 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
114const FORMAT: &str = "Blue Raven USB download";
116
117const RECOGNITION_LINES: usize = 1_000;
119
120pub const MAX_VALUES: usize = 256;
123
124pub const MAX_GROUPS: usize = 16;
128pub const MAX_LABEL_BYTES: usize = 16;
130
131const OPENING: &str = "@ LOG_";
133
134const LINE_END_BYTES: usize = 2;
136
137const HIGH_RATE: &str = "LOG_HIR";
139const LOW_RATE: &str = "LOG_LOW";
140
141const REGISTERS: &str = "FER:";
143
144pub(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
161struct 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
179const ATMOSPHERE_PA: f64 = 101_325.0;
181
182const 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
211const 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
267fn 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#[derive(Debug, PartialEq)]
282enum Piece<'a> {
283 NoCrc,
285 CrcDiffers,
287 Checked(&'a str),
289}
290
291fn 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
314fn 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
335pub(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
348type Layout = Vec<(Option<String>, usize)>;
351
352struct Record {
354 kind: String,
355 layout: Layout,
356 at_ms: i64,
358 year: i64,
359 month: i64,
360 day: i64,
361 time_of_day_ms: i64,
363 sync: i64,
364 values: Vec<f64>,
366}
367
368fn 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
389fn 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
398fn 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
405fn 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 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
438fn record(text: &str, line: usize) -> Result<Record, LogError> {
440 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
598type Column = (String, Quantity, f64, f64);
601
602fn 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
658pub 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 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 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 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 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 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 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 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 let cut = lines[0].rfind(" CRC:").expect("a CRC");
1019 let run_on = format!("{}{}", &lines[0][..cut], lines[1]);
1020 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 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 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}