1use std::collections::{BTreeMap, BTreeSet};
164
165use serde_json::{Map, Value};
166
167use crate::error::LogError;
168use crate::log::{Channel, Event, Figure, FlightLog, LogFormat, Quantity, Stated};
169
170const FORMAT: &str = "AltOS .eeprom";
172
173const NOT_SET: i64 = 2_147_483_647;
175
176const CHECKSUM_BASE: u8 = 0x5a;
179
180const TURN: i64 = 1 << 16;
182
183const TICKS_PER_S: f64 = 100.0;
185
186const SILENCE_TICKS: i64 = 1_000;
190
191const STANDARD_GRAVITY: f64 = 9.806_65;
193
194const SIXTEEN_BITS: std::ops::RangeInclusive<i64> = -32_768..=65_535;
197
198const PAD_PRESSURE_PA: std::ops::RangeInclusive<f64> = 10_000.0..=120_000.0;
200
201const GROUND_AGREES: f64 = 0.01;
203
204const MS5607_OPERATING_K: std::ops::RangeInclusive<f64> = 233.15..=358.15;
207
208const CLIMB_WINDOW_TICKS: i64 = 100;
211
212const CLIMB_GAP_TICKS: i64 = 10;
215
216const CLIMB_END_TICKS: i64 = 5;
219
220pub const CLIMB_RATIO: std::ops::RangeInclusive<f64> = 0.6..=(5.0 / 3.0);
228
229const CC1111_FULL_SCALE: f64 = 32_752.0;
232
233const MEGA_SENSE_V: f64 = 3.3 / 4095.0 * (100.0 + 27.0) / 27.0;
237
238const MEGA_15_V_PRODUCTS: [&str; 3] = ["TeleMega-v4.0", "TeleMega-v6.0", "EasyMega-v2.0"];
243
244pub const ALTITUDE_STEP_M: f64 =
249 4.0 / CC1111_FULL_SCALE / 0.009 * 1000.0 / (1.225 * STANDARD_GRAVITY);
250
251const HEAD_LINES: usize = 1_000;
253
254const STATES: [(u16, &str); 7] = [
256 (2, "pad"),
257 (3, "boost"),
258 (4, "fast"),
259 (5, "coast"),
260 (6, "drogue"),
261 (7, "main"),
262 (8, "landed"),
263];
264
265const GPS_VALID: u8 = 0x10;
267
268#[derive(Debug, Clone, Copy, PartialEq, Eq)]
270enum Board {
271 TeleMetrumV1,
273 EasyMini,
275 TeleMetrumV2,
277 Mega,
279}
280
281fn layout(log_format: i64) -> Option<(Board, usize)> {
283 match log_format {
284 1 => Some((Board::TeleMetrumV1, 8)),
285 6 | 14 => Some((Board::EasyMini, 16)),
286 7 => Some((Board::TeleMetrumV2, 16)),
287 15 | 16 | 22 => Some((Board::Mega, 32)),
288 _ => None,
289 }
290}
291
292#[derive(Debug, Clone, Copy, PartialEq, Eq)]
294enum At {
295 Line(usize),
297 Offset(usize),
299}
300
301fn refuse(at: At, message: String) -> LogError {
302 match at {
303 At::Line(line) => LogError::Syntax {
304 format: FORMAT,
305 line,
306 message,
307 },
308 At::Offset(offset) => LogError::Binary {
309 format: FORMAT,
310 offset,
311 message,
312 },
313 }
314}
315
316#[derive(Debug, Clone)]
318struct Record {
319 at: At,
320 bytes: Vec<u8>,
321}
322
323impl Record {
324 fn kind(&self) -> u8 {
325 self.bytes[0]
326 }
327 fn tick(&self) -> u16 {
328 self.u16(2)
329 }
330 fn u8(&self, at: usize) -> f64 {
331 f64::from(self.bytes[at])
332 }
333 fn u16(&self, at: usize) -> u16 {
334 u16::from_le_bytes([self.bytes[at], self.bytes[at + 1]])
335 }
336 fn i16(&self, at: usize) -> i16 {
337 i16::from_le_bytes([self.bytes[at], self.bytes[at + 1]])
338 }
339 fn u24(&self, at: usize) -> u32 {
340 u32::from_le_bytes([self.bytes[at], self.bytes[at + 1], self.bytes[at + 2], 0])
341 }
342 fn u32(&self, at: usize) -> u32 {
343 u32::from_le_bytes([
344 self.bytes[at],
345 self.bytes[at + 1],
346 self.bytes[at + 2],
347 self.bytes[at + 3],
348 ])
349 }
350 fn i32(&self, at: usize) -> i32 {
351 self.u32(at) as i32
352 }
353}
354
355type Prom = [i64; 6];
357
358const PROM_KEYS: [(&str, &str); 6] = [
361 ("sens", "barometer's C1"),
362 ("off", "barometer's C2"),
363 ("tcs", "barometer's C3"),
364 ("tco", "barometer's C4"),
365 ("tref", "barometer's C5"),
366 ("tempsens", "barometer's C6"),
367];
368
369#[derive(Debug, Default)]
371struct Config {
372 log_format: Option<i64>,
373 product: Option<String>,
374 serial: Option<i64>,
375 version: Option<String>,
376 prom: Option<Prom>,
377 ms5611: bool,
378 accel_plus: Option<i64>,
379 accel_minus: Option<i64>,
380 pad_orientation: Option<Figure>,
381 altitude_32: bool,
382 main_deploy: Option<Figure>,
383 apogee_delay: Option<Figure>,
384}
385
386pub fn recognizes(text: &str) -> bool {
388 let trimmed = text.trim_start();
389 if trimmed.starts_with('{') {
390 return json_head(text).is_some_and(|(head, _)| {
391 head.contains_key("log_format") && head.get("product").is_some_and(Value::is_string)
392 });
393 }
394 let (mut config, mut maker) = (false, false);
395 for line in text.lines().take(HEAD_LINES).map(str::trim) {
396 config |= line.starts_with("Config version:");
397 maker |= value_of(line, "manufacturer") == Some("altusmetrum.org");
398 if config && maker {
399 return true;
400 }
401 }
402 false
403}
404
405fn json_head(text: &str) -> Option<(Map<String, Value>, usize)> {
408 let start = text.len() - text.trim_start().len();
409 let mut stream =
410 serde_json::Deserializer::from_str(&text[start..]).into_iter::<serde_json::Value>();
411 match stream.next() {
412 Some(Ok(Value::Object(head))) => Some((head, start + stream.byte_offset())),
413 _ => None,
414 }
415}
416
417fn value_of<'a>(line: &'a str, key: &str) -> Option<&'a str> {
420 let rest = line.strip_prefix(key)?;
421 let value = rest.trim_start();
422 (value.len() < rest.len() && !value.is_empty()).then_some(value)
423}
424
425pub fn read(text: &str) -> Result<FlightLog, LogError> {
445 if !recognizes(text) {
446 return Err(LogError::NotThisFormat {
447 format: FORMAT,
448 message: "neither a JSON object naming `log_format` and `product` nor an AltOS \
449 board's printed configuration"
450 .to_owned(),
451 });
452 }
453 let raw = if text.trim_start().starts_with('{') {
454 json_form(text)?
455 } else {
456 text_form(text)?
457 };
458 decode(raw)
459}
460
461#[derive(Debug)]
464struct Raw {
465 config: Config,
466 board: Board,
467 size: usize,
468 log_format: i64,
469 from_product: bool,
470 json: bool,
471 records: Vec<Record>,
472 erased: usize,
473 last_line_cut: bool,
474}
475
476fn format_of(config: &Config, at: At) -> Result<(i64, Board, usize, bool), LogError> {
479 let (log_format, from_product) = match config.log_format {
480 Some(format) => (format, false),
481 None if config
482 .product
483 .as_deref()
484 .is_some_and(|product| product.starts_with("TeleMetrum-v1")) =>
485 {
486 (1, true)
487 }
488 None => {
489 return Err(refuse(
490 at,
491 format!(
492 "the configuration states no log format, and its product, {:?}, isn't a \
493 TeleMetrum v1, whose firmware before 1.0 logged format 1",
494 cut(config.product.as_deref().unwrap_or("none"))
495 ),
496 ));
497 }
498 };
499 let (board, size) = layout(log_format).ok_or_else(|| {
500 refuse(
501 at,
502 format!(
503 "log format {log_format}, which no sample file shows. Its record size is \
504 unknown, and read at a wrong size the bytes would make a plausible flight"
505 ),
506 )
507 })?;
508 Ok((log_format, board, size, from_product))
509}
510
511fn json_form(text: &str) -> Result<Raw, LogError> {
513 let (head, end) = json_head(text).ok_or_else(|| {
514 refuse(
515 At::Line(1),
516 "the JSON object at the head doesn't parse".to_owned(),
517 )
518 })?;
519 let int = |key: &str| {
520 head.get(key)
521 .and_then(Value::as_i64)
522 .filter(|value| *value != NOT_SET)
523 };
524 let mut config = Config {
525 log_format: int("log_format"),
526 product: head
527 .get("product")
528 .and_then(Value::as_str)
529 .map(str::to_owned),
530 serial: int("serial"),
531 version: head
532 .get("version")
533 .and_then(Value::as_str)
534 .map(str::to_owned),
535 pad_orientation: int("pad_orientation").map(|value| {
536 Figure::new(
537 "pad_orientation",
538 value.to_string(),
539 Some(Quantity::Number),
540 vec![value as f64],
541 )
542 }),
543 altitude_32: int("altitude_32") == Some(1),
544 main_deploy: int("main_deploy").map(|value| {
545 Figure::new(
546 "main_deploy",
547 value.to_string(),
548 Some(Quantity::Unrecognized),
549 vec![value as f64],
550 )
551 }),
552 apogee_delay: int("apogee_delay").map(|value| {
553 Figure::new(
554 "apogee_delay",
555 value.to_string(),
556 Some(Quantity::Unrecognized),
557 vec![value as f64],
558 )
559 }),
560 ..Config::default()
561 };
562 if let (Some(plus), Some(minus)) = (int("accel_cal_plus"), int("accel_cal_minus")) {
565 (config.accel_plus, config.accel_minus) = (Some(plus), Some(minus));
566 } else if let (Some(plus), Some(minus)) =
567 (int("accel_cal_plus_cooked"), int("accel_cal_minus_cooked"))
568 {
569 (config.accel_plus, config.accel_minus) = (Some(plus), Some(minus));
570 }
571 if let Some(Value::Object(ms5607)) = head.get("ms5607") {
572 config.ms5611 = ms5607.get("ms5611").and_then(Value::as_bool) == Some(true);
573 let constant = |key: &str| {
574 ms5607
575 .get(key)
576 .and_then(Value::as_i64)
577 .filter(|value| (0..=0xffff).contains(value))
578 };
579 if let [Some(c1), Some(c2), Some(c3), Some(c4), Some(c5), Some(c6)] =
580 PROM_KEYS.map(|(key, _)| constant(key))
581 {
582 config.prom = Some([c1, c2, c3, c4, c5, c6]);
583 }
584 }
585 let (log_format, board, size, from_product) = format_of(&config, At::Line(1))?;
586
587 let first_line = text[..end].matches('\n').count() + 1;
589 let mut bytes = Vec::with_capacity((text.len() - end) / 3);
590 for (k, line) in text[end..].split('\n').enumerate() {
591 for token in line.split_ascii_whitespace() {
592 let byte = (token.len() == 2 && token.bytes().all(|b| b.is_ascii_hexdigit()))
594 .then(|| u8::from_str_radix(token, 16).ok())
595 .flatten()
596 .ok_or_else(|| {
597 refuse(
598 At::Line(first_line + k),
599 format!(
600 "{:?} where the memory's bytes are two hexadecimal digits each",
601 cut(token)
602 ),
603 )
604 })?;
605 bytes.push(byte);
606 }
607 }
608 let mut records = Vec::new();
609 let mut erased = 0usize;
610 let mut first_erased: Option<usize> = None;
611 for (k, chunk) in bytes.chunks(size).enumerate() {
612 let offset = k * size;
613 if chunk.len() < size {
615 return Err(refuse(
616 At::Offset(offset),
617 format!(
618 "the memory ends in {} bytes, part of a {size}-byte record",
619 chunk.len()
620 ),
621 ));
622 }
623 if chunk.iter().all(|byte| *byte == 0xff) {
624 erased += 1;
625 first_erased.get_or_insert(offset);
626 continue;
627 }
628 if let Some(erased_at) = first_erased {
629 return Err(refuse(
630 At::Offset(offset),
631 format!(
632 "a record after the erased memory from byte {erased_at}: the memory's order \
633 is unknown"
634 ),
635 ));
636 }
637 let sum = chunk
638 .iter()
639 .fold(CHECKSUM_BASE, |sum, byte| sum.wrapping_add(*byte));
640 if sum != 0 {
641 return Err(refuse(
642 At::Offset(offset),
643 format!(
644 "record {} fails its checksum: 0x5A and its bytes sum to 0x{sum:02X}, not 0, \
645 modulo 256: the record is damaged",
646 k + 1
647 ),
648 ));
649 }
650 records.push(Record {
651 at: At::Offset(offset),
652 bytes: chunk.to_vec(),
653 });
654 }
655 Ok(Raw {
656 config,
657 board,
658 size,
659 log_format,
660 from_product,
661 json: true,
662 records,
663 erased,
664 last_line_cut: false,
665 })
666}
667
668fn record_shaped(line: &str) -> bool {
671 let mut tokens = line.split_ascii_whitespace();
672 let hex = |token: &str, most: usize| {
673 (1..=most).contains(&token.len()) && token.bytes().all(|b| b.is_ascii_hexdigit())
674 };
675 matches!(tokens.next(), Some(kind) if kind.len() == 1 && kind.as_bytes()[0].is_ascii_alphabetic())
676 && tokens.next().is_some_and(|tick| hex(tick, 4))
677 && tokens.next().is_some_and(|token| hex(token, 4))
678}
679
680fn text_record(line: &str, size: usize) -> Option<Vec<u8>> {
682 let tokens: Vec<&str> = line.split_ascii_whitespace().collect();
683 let digits = |token: &str, least: usize, most: usize| {
684 (least..=most).contains(&token.len()) && token.bytes().all(|b| b.is_ascii_hexdigit())
685 };
686 let (kind, tick, fields) = match tokens.as_slice() {
687 [kind, tick, fields @ ..] => (*kind, *tick, fields),
688 _ => return None,
689 };
690 if kind.len() != 1 || !kind.as_bytes()[0].is_ascii_alphabetic() || !digits(tick, 1, 4) {
691 return None;
692 }
693 let tick = u16::from_str_radix(tick, 16).ok()?;
694 let mut bytes = vec![kind.as_bytes()[0], 0];
695 bytes.extend(tick.to_le_bytes());
696 if size == 8 {
697 if fields.len() != 2 || !fields.iter().all(|word| digits(word, 1, 4)) {
699 return None;
700 }
701 for word in fields {
702 bytes.extend(u16::from_str_radix(word, 16).ok()?.to_le_bytes());
703 }
704 } else {
705 if fields.len() != size - 4 || !fields.iter().all(|byte| digits(byte, 2, 2)) {
706 return None;
707 }
708 for byte in fields {
709 bytes.push(u8::from_str_radix(byte, 16).ok()?);
710 }
711 }
712 Some(bytes)
713}
714
715fn text_form(text: &str) -> Result<Raw, LogError> {
717 let lines: Vec<&str> = text
718 .split('\n')
719 .map(|line| line.trim_end_matches('\r'))
720 .collect();
721 let start = lines
722 .iter()
723 .position(|line| record_shaped(line))
724 .ok_or(LogError::NoData { format: FORMAT })?;
725
726 let mut config = Config::default();
727 let mut seen: BTreeMap<&'static str, (String, usize)> = BTreeMap::new();
729 let mut prom: [Option<i64>; 6] = [None; 6];
730 for (k, line) in lines[..start].iter().enumerate() {
731 let number = k + 1;
732 let line = line.trim();
733 let mut agree = |key: &'static str, value: String| -> Result<bool, LogError> {
734 match seen.get(key) {
735 Some((first, at)) if *first != value => Err(refuse(
736 At::Line(number),
737 format!(
738 "the configuration is printed more than once, and its {key} here, \
739 {:?}, differs from line {at}'s, {:?}",
740 cut(&value),
741 cut(first)
742 ),
743 )),
744 Some(_) => Ok(false),
745 None => {
746 seen.insert(key, (value, number));
747 Ok(true)
748 }
749 }
750 };
751 if let Some(value) = value_of(line, "product") {
752 if agree("product", value.to_owned())? {
753 config.product = Some(value.to_owned());
754 }
755 } else if let Some(value) = value_of(line, "serial-number") {
756 if agree("serial number", value.to_owned())? {
757 config.serial = value.parse().ok();
758 }
759 } else if let Some(value) = value_of(line, "log-format") {
760 if agree("log format", value.to_owned())? {
761 config.log_format = Some(value.parse().map_err(|_| {
762 refuse(
763 At::Line(number),
764 format!("a log format of {:?}", cut(value)),
765 )
766 })?);
767 }
768 } else if let Some(value) = value_of(line, "software-version") {
769 if agree("firmware", value.to_owned())? {
770 config.version = Some(value.to_owned());
771 }
772 } else if let Some(value) = value_of(line, "altitude-32") {
773 if agree("altitude-32", value.to_owned())? {
774 config.altitude_32 = value == "1";
775 }
776 } else if let Some(rest) = line.strip_prefix("Accel cal +1g:") {
777 if agree("accelerometer calibration", rest.trim().to_owned())? {
778 let words: Vec<&str> = rest.split_whitespace().collect();
779 if let [plus, "-1g:", minus, ..] = words.as_slice() {
780 config.accel_plus = plus.parse().ok();
781 config.accel_minus = minus.parse().ok();
782 }
783 }
784 } else if let Some(rest) = line.strip_prefix("ms5607 ") {
785 let constant = rest.split_once(':').and_then(|(key, value)| {
786 let index = PROM_KEYS.iter().position(|(name, _)| *name == key.trim())?;
787 Some((index, value.trim()))
788 });
789 if let Some((index, value)) = constant
790 && agree(PROM_KEYS[index].1, value.to_owned())?
791 {
792 prom[index] = value.parse().ok().filter(|c| (0..=0xffff).contains(c));
793 }
794 } else if let Some(rest) = line.strip_prefix("Pad orientation:") {
795 let written = rest.trim();
796 if agree("pad orientation", written.to_owned())? {
797 let value = written
798 .split_whitespace()
799 .next()
800 .and_then(|word| word.parse::<i64>().ok());
801 config.pad_orientation = Some(match value {
802 Some(value) => Figure::new(
803 "pad_orientation",
804 cut(written),
805 Some(Quantity::Number),
806 vec![value as f64],
807 ),
808 None => Figure::new("pad_orientation", cut(written), None, Vec::new()),
809 });
810 }
811 } else if let Some(rest) = line.strip_prefix("Main deploy:")
812 && config.main_deploy.is_none()
813 {
814 config.main_deploy = Some(stated_setting(
815 "main_deploy",
816 rest.trim(),
817 "meters",
818 Quantity::AltitudeAboveGround,
819 ));
820 } else if let Some(rest) = line.strip_prefix("Apogee delay:")
821 && config.apogee_delay.is_none()
822 {
823 config.apogee_delay = Some(stated_setting(
824 "apogee_delay",
825 rest.trim(),
826 "seconds",
827 Quantity::Duration,
828 ));
829 }
830 }
831 if let [Some(c1), Some(c2), Some(c3), Some(c4), Some(c5), Some(c6)] = prom {
832 config.prom = Some([c1, c2, c3, c4, c5, c6]);
833 }
834 let (log_format, board, size, from_product) = format_of(&config, At::Line(start + 1))?;
835
836 let ends_cut = !text.ends_with('\n');
838 let last = lines.len() - 1;
839 let mut records = Vec::new();
840 let mut last_line_cut = false;
841 for (k, line) in lines.iter().enumerate().skip(start) {
842 if line.trim().is_empty() {
843 continue;
844 }
845 if k == last && ends_cut {
846 last_line_cut = true;
847 continue;
848 }
849 let bytes = text_record(line, size).ok_or_else(|| {
850 refuse(
851 At::Line(k + 1),
852 format!(
853 "{:?} isn't a record of log format {log_format}: a type letter, the tick and \
854 {}",
855 cut(line),
856 if size == 8 {
857 "two 16-bit words in hexadecimal".to_owned()
858 } else {
859 format!("{} bytes in hexadecimal", size - 4)
860 }
861 ),
862 )
863 })?;
864 records.push(Record {
865 at: At::Line(k + 1),
866 bytes,
867 });
868 }
869 Ok(Raw {
870 config,
871 board,
872 size,
873 log_format,
874 from_product,
875 json: false,
876 records,
877 erased: 0,
878 last_line_cut,
879 })
880}
881
882fn stated_setting(name: &str, written: &str, unit: &str, quantity: Quantity) -> Figure {
885 let mut words = written.split_whitespace();
886 let value = words
887 .next()
888 .and_then(|word| word.parse::<f64>().ok())
889 .filter(|v| v.is_finite());
890 match (value, words.next()) {
891 (Some(value), Some(word)) if word == unit => {
892 Figure::new(name, written, Some(quantity), vec![value])
893 }
894 (Some(value), _) => Figure::new(name, written, Some(Quantity::Unrecognized), vec![value]),
895 _ => Figure::new(name, written, None, Vec::new()),
896 }
897}
898
899fn unwind(records: &[Record]) -> (Vec<i64>, usize) {
902 let mut latest: Option<i64> = None;
903 let mut ticks = Vec::with_capacity(records.len());
904 for (k, record) in records.iter().enumerate() {
905 let tick = match latest {
906 None => i64::from(record.tick()),
907 Some(latest) => {
908 #[allow(
910 clippy::cast_possible_truncation,
911 reason = "a remainder of a 65,536-tick turn, so the cast is exact"
912 )]
913 let step =
914 i64::from(record.tick().wrapping_sub(latest.rem_euclid(TURN) as u16) as i16);
915 if step.abs() > SILENCE_TICKS {
916 return (ticks, k);
917 }
918 latest + step
919 }
920 };
921 latest = Some(latest.map_or(tick, |latest| latest.max(tick)));
922 ticks.push(tick);
923 }
924 let kept = ticks.len();
925 (ticks, kept)
926}
927
928fn ms5607(d1: u32, d2: u32, prom: &Prom) -> (i128, i128) {
933 let [c1, c2, c3, c4, c5, c6] = prom.map(i128::from);
934 let (d1, d2) = (i128::from(d1), i128::from(d2));
935 let dt = d2 - (c5 << 8);
936 let mut temp = 2000 + ((dt * c6) >> 23);
937 let mut off = (c2 << 17) + ((c4 * dt) >> 6);
938 let mut sens = (c1 << 16) + ((c3 * dt) >> 7);
939 if temp < 2000 {
940 let t2 = (dt * dt) >> 31;
941 let mut off2 = (61 * (temp - 2000) * (temp - 2000)) >> 4;
942 let mut sens2 = 2 * (temp - 2000) * (temp - 2000);
943 if temp < -1500 {
944 off2 += 15 * (temp + 1500) * (temp + 1500);
945 sens2 += 8 * (temp + 1500) * (temp + 1500);
946 }
947 temp -= t2;
948 off -= off2;
949 sens -= sens2;
950 }
951 let pressure = (((d1 * sens) >> 21) - off) >> 15;
952 (pressure, temp)
953}
954
955fn mp3h6115a_pa(count: i16) -> f64 {
958 (f64::from(count) / CC1111_FULL_SCALE + 0.095) / 0.009 * 1000.0
959}
960
961#[derive(Debug, Default)]
963struct Channels {
964 order: Vec<(String, Quantity)>,
965 data: BTreeMap<String, (Vec<f64>, Vec<f64>)>,
966}
967
968impl Channels {
969 fn push(&mut self, name: &str, quantity: Quantity, time_s: f64, value: f64) {
970 if let Some((times, values)) = self.data.get_mut(name) {
971 times.push(time_s);
972 values.push(value);
973 return;
974 }
975 self.order.push((name.to_owned(), quantity));
976 self.data
977 .insert(name.to_owned(), (vec![time_s], vec![value]));
978 }
979
980 fn get(&self, name: &str) -> Option<&(Vec<f64>, Vec<f64>)> {
981 self.data.get(name)
982 }
983
984 fn into_channels(mut self) -> Vec<Channel> {
985 self.order
986 .into_iter()
987 .filter_map(|(column, quantity)| {
988 let (time_s, values) = self.data.remove(&column)?;
989 Some(Channel {
990 column,
991 quantity,
992 time_s,
993 values,
994 })
995 })
996 .collect()
997 }
998}
999
1000#[derive(Debug, Default)]
1002struct Flight {
1003 number: u16,
1004 ground_accel: Option<i64>,
1005 ground_pressure: Option<u32>,
1006 imu_accel: [i16; 3],
1007 gyro_sums: [i32; 3],
1008}
1009
1010#[derive(Debug, Clone, PartialEq)]
1013enum Accel {
1014 Converted { zero: f64, per_g: f64 },
1015 AsWritten(&'static str),
1016}
1017
1018fn decode(raw: Raw) -> Result<FlightLog, LogError> {
1020 let Raw {
1021 config,
1022 board,
1023 size,
1024 log_format,
1025 from_product,
1026 json,
1027 records,
1028 erased,
1029 last_line_cut,
1030 } = raw;
1031 if records.is_empty() {
1032 return Err(LogError::NoData { format: FORMAT });
1033 }
1034 let read_in_file = records.len();
1035 let (ticks, kept) = unwind(&records);
1036 let after_silence = read_in_file - kept;
1037
1038 let mut seen: BTreeSet<(i64, &[u8])> = BTreeSet::new();
1040 let mut order: Vec<usize> = Vec::with_capacity(kept);
1041 let mut duplicates = 0usize;
1042 for (k, tick) in ticks.iter().enumerate() {
1043 if seen.insert((*tick, records[k].bytes.as_slice())) {
1044 order.push(k);
1045 } else {
1046 duplicates += 1;
1047 }
1048 }
1049 order.sort_by_key(|&k| ticks[k]);
1051
1052 let flights: Vec<usize> = order
1053 .iter()
1054 .copied()
1055 .filter(|&k| records[k].kind() == b'F')
1056 .collect();
1057 let zero = match flights.as_slice() {
1058 [] => {
1059 return Err(refuse(
1060 records.first().map_or(At::Line(1), |record| record.at),
1061 "no flight record (`F`), whose tick is the flight's zero".to_owned(),
1062 ));
1063 }
1064 [only] => *only,
1065 [first, second, ..] => {
1066 return Err(refuse(
1067 records[*second].at,
1068 format!(
1069 "a second flight record, after the one at {}: two flights in one file",
1070 describe(records[*first].at)
1071 ),
1072 ));
1073 }
1074 };
1075 let zero_tick = ticks[zero];
1076 let f = &records[zero];
1077 let flight = match board {
1078 Board::TeleMetrumV1 => Flight {
1079 number: f.u16(6),
1080 ground_accel: Some(i64::from(f.u16(4))),
1081 ..Flight::default()
1082 },
1083 Board::EasyMini => Flight {
1084 number: f.u16(4),
1085 ground_pressure: Some(f.u32(8)),
1086 ..Flight::default()
1087 },
1088 Board::TeleMetrumV2 => Flight {
1089 number: f.u16(4),
1090 ground_accel: Some(i64::from(f.i16(6))),
1091 ground_pressure: Some(f.u32(8)),
1092 ..Flight::default()
1093 },
1094 Board::Mega => Flight {
1095 number: f.u16(4),
1096 ground_accel: Some(i64::from(f.i16(6))),
1097 ground_pressure: Some(f.u32(8)),
1098 imu_accel: [f.i16(12), f.i16(14), f.i16(16)],
1099 gyro_sums: [f.i32(20), f.i32(24), f.i32(28)],
1100 },
1101 };
1102
1103 let prom = match board {
1104 Board::TeleMetrumV1 => None,
1105 _ if config.ms5611 => None,
1106 _ => config.prom,
1107 };
1108 let pascals = board == Board::TeleMetrumV1 || prom.is_some();
1110 let accel = match (
1111 board,
1112 config.accel_plus,
1113 config.accel_minus,
1114 flight.ground_accel,
1115 ) {
1116 (Board::EasyMini, ..) => Accel::AsWritten("the board has no accelerometer"),
1117 (_, Some(plus), Some(minus), Some(_))
1118 if !SIXTEEN_BITS.contains(&plus) || !SIXTEEN_BITS.contains(&minus) =>
1119 {
1120 Accel::AsWritten("the calibration lies outside a 16-bit count's range")
1121 }
1122 (_, Some(plus), Some(minus), Some(ground)) => match minus.checked_sub(plus) {
1123 Some(span) if span > 0 && pascals => Accel::Converted {
1124 zero: ground as f64,
1125 per_g: span as f64 / 2.0,
1126 },
1127 Some(span) if span > 0 => Accel::AsWritten(
1128 "no pressure in pascals to hold it to, so its unit has no second check",
1129 ),
1130 _ => Accel::AsWritten("the calibration's span isn't positive"),
1131 },
1132 (_, _, _, Some(_)) => Accel::AsWritten("the calibration isn't set"),
1133 _ => Accel::AsWritten("the flight record holds no ground reading"),
1134 };
1135 let mega_volts = config
1137 .product
1138 .as_deref()
1139 .is_some_and(|product| MEGA_15_V_PRODUCTS.contains(&product));
1140 let imu_read = match board {
1141 Board::Mega => {
1142 log_format != 15 && (flight.imu_accel != [0; 3] || flight.gyro_sums != [0; 3])
1143 }
1144 _ => false,
1145 };
1146
1147 let valid_at: BTreeSet<i64> = order
1149 .iter()
1150 .filter(|&&k| {
1151 let record = &records[k];
1152 record.kind() == b'G'
1153 && matches!(board, Board::TeleMetrumV1 | Board::TeleMetrumV2)
1154 && record.bytes[7] & GPS_VALID != 0
1155 })
1156 .map(|&k| ticks[k])
1157 .collect();
1158
1159 let (accel, v1_pascals, climb_note) = match accel {
1163 Accel::Converted { zero, per_g } => {
1164 let samples: Vec<(i64, f64, f64)> = order
1165 .iter()
1166 .filter_map(|&k| {
1167 let (pa, count) = climb_sample(board, &records[k], prom.as_ref())?;
1168 let along = (zero - count as f64) / per_g * STANDARD_GRAVITY;
1169 Some((ticks[k] - zero_tick, pa, along))
1170 })
1171 .collect();
1172 let v1 = if board == Board::TeleMetrumV1 {
1173 ", and the TeleMetrum v1's `pressure`, which has no other check, too"
1174 } else {
1175 ""
1176 };
1177 match climb_over_the_window(&samples) {
1178 Ok(measured)
1180 if measured.by_acceleration_m > 0.0
1181 && CLIMB_RATIO.contains(&measured.ratio) =>
1182 {
1183 let note = format!(
1184 "`pressure` and `acceleration` held to each other. Over the first second \
1185 after boost the rocket climbs {:.1} m by the pressure in the standard \
1186 atmosphere. By the acceleration integrated twice from rest on the pad it \
1187 climbs {:.1} m. The ratio is {:.3}, within 0.6 to 5/3",
1188 measured.by_pressure_m, measured.by_acceleration_m, measured.ratio
1189 );
1190 (accel, true, Some(note))
1191 }
1192 Ok(measured) => {
1193 let note = format!(
1194 "over the first second after boost the rocket climbs {:.1} m by the \
1195 pressure and {:.1} m by the acceleration. The ratio is {:.3}, outside \
1196 0.6 to 5/3. The two disagree, so the acceleration's counts are kept as \
1197 written{v1}",
1198 measured.by_pressure_m, measured.by_acceleration_m, measured.ratio
1199 );
1200 (
1201 Accel::AsWritten("its climb disagrees with the pressure's"),
1202 false,
1203 Some(note),
1204 )
1205 }
1206 Err(why) => {
1207 let note = format!(
1208 "the climb over the first second after boost can't be measured ({why}), \
1209 so the acceleration's counts are kept as written{v1}"
1210 );
1211 (
1212 Accel::AsWritten("its climb can't be measured"),
1213 false,
1214 Some(note),
1215 )
1216 }
1217 }
1218 }
1219 Accel::AsWritten(why) => {
1220 let note = if board == Board::TeleMetrumV1 {
1221 Some(
1222 "`pres` kept as written. The acceleration is kept as written, so there is \
1223 no climb to hold the TeleMetrum v1's pressure to. The pad's band alone \
1224 rejects almost no count"
1225 .to_owned(),
1226 )
1227 } else if board != Board::EasyMini && prom.is_some() {
1228 Some(
1229 "`pressure`'s second check is the pad's alone: the acceleration, kept as \
1230 written, gives no climb to hold it to"
1231 .to_owned(),
1232 )
1233 } else {
1234 None
1235 };
1236 (Accel::AsWritten(why), false, note)
1237 }
1238 };
1239
1240 let mut channels = Channels::default();
1241 let mut events: Vec<Event> = Vec::new();
1242 let mut state: Option<u16> = None;
1243 let mut not_read: BTreeMap<u8, usize> = BTreeMap::new();
1244 let mut no_fix = 0usize;
1245 let mut sense_counts_off = 0usize;
1246 let mut satellites_cut = 0usize;
1247 let mut before_boost = 0usize;
1248 let along = |count: i64| match &accel {
1249 Accel::Converted { zero, per_g } => Some((zero - count as f64) / per_g * STANDARD_GRAVITY),
1250 Accel::AsWritten(_) => None,
1251 };
1252 for &k in &order {
1253 let record = &records[k];
1254 let time = (ticks[k] - zero_tick) as f64 / TICKS_PER_S;
1255 if time < 0.0 {
1256 before_boost += 1;
1257 }
1258 let mut push = |name: &str, quantity: Quantity, value: f64| {
1259 channels.push(name, quantity, time, value);
1260 };
1261 let accelerometer =
1262 |push: &mut dyn FnMut(&str, Quantity, f64), count: i64| match along(count) {
1263 Some(value) => push("acceleration", Quantity::Acceleration, value),
1264 None => push("accel", Quantity::Unrecognized, count as f64),
1265 };
1266 let barometer = |push: &mut dyn FnMut(&str, Quantity, f64), d1: u32, d2: u32| match &prom {
1267 Some(prom) => {
1268 let (pa, centi) = ms5607(d1, d2, prom);
1269 push("pressure", Quantity::Pressure, pa as f64);
1270 push(
1271 "temperature",
1272 Quantity::Temperature,
1273 centi as f64 / 100.0 + 273.15,
1274 );
1275 }
1276 None => {
1277 push("d1", Quantity::Unrecognized, f64::from(d1));
1278 push("d2", Quantity::Unrecognized, f64::from(d2));
1279 }
1280 };
1281 let mut position = |push: &mut dyn FnMut(&str, Quantity, f64),
1282 valid: bool,
1283 lat: Option<i32>,
1284 lon: Option<i32>,
1285 alt: Option<f64>| {
1286 if !valid {
1287 no_fix += 1;
1288 }
1289 let fix = |value: f64| if valid { value } else { f64::NAN };
1290 if let Some(lat) = lat {
1291 push("latitude", Quantity::Latitude, fix(f64::from(lat) / 1e7));
1292 }
1293 if let Some(lon) = lon {
1294 push("longitude", Quantity::Longitude, fix(f64::from(lon) / 1e7));
1295 }
1296 if let Some(alt) = alt {
1297 push("gps_altitude", Quantity::GnssAltitude, fix(alt));
1298 }
1299 };
1300 let altitude = |low: usize, high: usize| {
1301 if config.altitude_32 {
1302 f64::from(record.i16(high)) * 65_536.0 + f64::from(record.u16(low))
1303 } else {
1304 f64::from(record.i16(low))
1305 }
1306 };
1307 match (board, record.kind()) {
1308 (_, b'F') => {}
1309 (_, b'S') => {
1310 let now = record.u16(4);
1311 if state != Some(now) {
1312 events.push(Event {
1313 time_s: time,
1314 name: state_name(now),
1315 });
1316 state = Some(now);
1317 }
1318 push("state", Quantity::Number, f64::from(now));
1319 }
1320 (Board::TeleMetrumV1, b'A') => {
1321 let (count, pres) = (i64::from(record.i16(4)), record.i16(6));
1322 accelerometer(&mut push, count);
1323 if v1_pascals {
1324 push("pressure", Quantity::Pressure, mp3h6115a_pa(pres));
1325 } else {
1326 push("pres", Quantity::Unrecognized, f64::from(pres));
1327 }
1328 }
1329 (Board::TeleMetrumV1, b'T') => {
1330 push("temp", Quantity::Unrecognized, f64::from(record.i16(4)));
1331 push("v_batt", Quantity::Unrecognized, f64::from(record.i16(6)));
1332 }
1333 (Board::TeleMetrumV1, b'D') => {
1334 push("sense_a", Quantity::Unrecognized, f64::from(record.i16(4)));
1335 push("sense_m", Quantity::Unrecognized, f64::from(record.i16(6)));
1336 }
1337 (Board::TeleMetrumV1 | Board::TeleMetrumV2, b'G') => {
1338 let flags = record.bytes[7];
1339 for (j, name) in ["hour", "minute", "second"].into_iter().enumerate() {
1340 push(name, Quantity::Number, record.u8(4 + j));
1341 }
1342 push("gps_flags", Quantity::Number, f64::from(flags));
1343 push("nsat", Quantity::Number, f64::from(flags & 0x0f));
1344 if board == Board::TeleMetrumV2 {
1345 for (j, name) in ["year", "month", "day"].into_iter().enumerate() {
1346 push(name, Quantity::Number, record.u8(8 + j));
1347 }
1348 push("gps_byte_11", Quantity::Unrecognized, record.u8(11));
1349 }
1350 }
1351 (Board::TeleMetrumV1, b'N') => {
1352 let valid = valid_at.contains(&ticks[k]);
1353 position(&mut push, valid, Some(record.i32(4)), None, None);
1354 }
1355 (Board::TeleMetrumV1, b'W') => {
1356 let valid = valid_at.contains(&ticks[k]);
1357 position(&mut push, valid, None, Some(record.i32(4)), None);
1358 }
1359 (Board::TeleMetrumV1, b'H') => {
1360 let valid = valid_at.contains(&ticks[k]);
1361 position(&mut push, valid, None, None, Some(f64::from(record.i16(4))));
1362 }
1363 (Board::TeleMetrumV1, b'Y') => {
1364 for (j, name) in ["year", "month", "day"].into_iter().enumerate() {
1365 push(name, Quantity::Number, record.u8(4 + j));
1366 }
1367 }
1368 (Board::TeleMetrumV1, b'V') => {
1369 push("svid", Quantity::Number, record.u8(4));
1370 push("c_n", Quantity::Number, record.u8(7));
1371 }
1372 (Board::EasyMini, b'A') => {
1373 barometer(&mut push, record.u24(4), record.u24(7));
1374 push("sense_a", Quantity::Unrecognized, f64::from(record.u16(10)));
1375 push("sense_m", Quantity::Unrecognized, f64::from(record.u16(12)));
1376 push("v_batt", Quantity::Unrecognized, f64::from(record.u16(14)));
1377 }
1378 (Board::TeleMetrumV2, b'A') => {
1379 let (d1, d2, count) = (record.u32(4), record.u32(8), i64::from(record.i16(12)));
1380 barometer(&mut push, d1, d2);
1381 accelerometer(&mut push, count);
1382 }
1383 (Board::TeleMetrumV2, b'T') => {
1384 push("v_batt", Quantity::Unrecognized, f64::from(record.i16(4)));
1385 push("sense_a", Quantity::Unrecognized, f64::from(record.i16(6)));
1386 push("sense_m", Quantity::Unrecognized, f64::from(record.i16(8)));
1387 }
1388 (Board::TeleMetrumV2, b'P') => {
1389 let valid = valid_at.contains(&ticks[k]);
1390 position(
1391 &mut push,
1392 valid,
1393 Some(record.i32(4)),
1394 Some(record.i32(8)),
1395 Some(altitude(12, 14)),
1396 );
1397 }
1398 (Board::TeleMetrumV2 | Board::Mega, b'V') => {
1399 let count = usize::from(record.bytes[4]);
1400 let room = (size - 6) / 2;
1401 if count > room {
1402 satellites_cut += 1;
1403 }
1404 push("sat_count", Quantity::Number, f64::from(record.bytes[4]));
1405 for j in 0..count.min(room) {
1406 push("svid", Quantity::Number, record.u8(6 + 2 * j));
1407 push("c_n", Quantity::Number, record.u8(7 + 2 * j));
1408 }
1409 }
1410 (Board::Mega, b'A') => {
1411 let (d1, d2) = (record.u32(4), record.u32(8));
1412 barometer(&mut push, d1, d2);
1413 if imu_read {
1414 const IMU: [&str; 9] = [
1415 "imu_accel_0",
1416 "imu_accel_1",
1417 "imu_accel_2",
1418 "imu_gyro_0",
1419 "imu_gyro_1",
1420 "imu_gyro_2",
1421 "imu_mag_0",
1422 "imu_mag_1",
1423 "imu_mag_2",
1424 ];
1425 for (j, name) in IMU.into_iter().enumerate() {
1426 push(
1427 name,
1428 Quantity::Unrecognized,
1429 f64::from(record.i16(12 + 2 * j)),
1430 );
1431 }
1432 }
1433 let count = i64::from(record.i16(30));
1434 accelerometer(&mut push, count);
1435 }
1436 (Board::Mega, b'T') => {
1437 push("v_batt", Quantity::Unrecognized, f64::from(record.i16(4)));
1438 let volts = |count: i16| {
1439 if mega_volts {
1440 (Quantity::Voltage, f64::from(count) * MEGA_SENSE_V)
1441 } else {
1442 (Quantity::Unrecognized, f64::from(count))
1443 }
1444 };
1445 let (quantity, value) = volts(record.i16(6));
1446 push("pyro", quantity, value);
1447 let senses = record.i16(8);
1448 push("n_sense", Quantity::Number, f64::from(senses));
1449 if senses == 6 {
1450 const SENSES: [&str; 6] = [
1451 "igniter_a",
1452 "igniter_b",
1453 "igniter_c",
1454 "igniter_d",
1455 "drogue_voltage",
1456 "main_voltage",
1457 ];
1458 for (j, name) in SENSES.into_iter().enumerate() {
1459 let (quantity, value) = volts(record.i16(10 + 2 * j));
1460 push(name, quantity, value);
1461 }
1462 } else {
1463 sense_counts_off += 1;
1464 for j in 0..6 {
1465 push(
1466 [
1467 "sense_0", "sense_1", "sense_2", "sense_3", "sense_4", "sense_5",
1468 ][j],
1469 Quantity::Unrecognized,
1470 f64::from(record.i16(10 + 2 * j)),
1471 );
1472 }
1473 }
1474 }
1475 (Board::Mega, b'G') => {
1476 let flags = record.bytes[17];
1477 position(
1478 &mut push,
1479 flags & GPS_VALID != 0,
1480 Some(record.i32(4)),
1481 Some(record.i32(8)),
1482 Some(altitude(12, 30)),
1483 );
1484 for (j, name) in ["hour", "minute", "second"].into_iter().enumerate() {
1485 push(name, Quantity::Number, record.u8(14 + j));
1486 }
1487 push("gps_flags", Quantity::Number, f64::from(flags));
1488 push("nsat", Quantity::Number, f64::from(flags & 0x0f));
1489 for (j, name) in ["year", "month", "day"].into_iter().enumerate() {
1490 push(name, Quantity::Number, record.u8(18 + j));
1491 }
1492 push("course", Quantity::Unrecognized, record.u8(21));
1493 push(
1494 "ground_speed",
1495 Quantity::Unrecognized,
1496 f64::from(record.u16(22)),
1497 );
1498 push(
1499 "climb_rate",
1500 Quantity::Unrecognized,
1501 f64::from(record.i16(24)),
1502 );
1503 for (j, name) in ["pdop", "hdop", "vdop", "gps_mode"].into_iter().enumerate() {
1504 push(name, Quantity::Number, record.u8(26 + j));
1505 }
1506 }
1507 (_, kind) => *not_read.entry(kind).or_default() += 1,
1508 }
1509 }
1510 if channels.data.is_empty() {
1511 return Err(LogError::NoData { format: FORMAT });
1512 }
1513
1514 let pad = channels.get("pressure").and_then(|(times, values)| {
1516 let mut before: Vec<f64> = times
1517 .iter()
1518 .zip(values)
1519 .filter(|(time, value)| **time < 0.0 && value.is_finite())
1520 .map(|(_, value)| *value)
1521 .collect();
1522 crate::filter::median(&mut before).or_else(|| values.first().copied())
1523 });
1524 let mut pad_note = None;
1525 if let Some(pad) = pad {
1526 if !PAD_PRESSURE_PA.contains(&pad) {
1527 return Err(refuse(
1528 f.at,
1529 format!(
1530 "the pad's pressure reads {pad:.0} Pa, outside every launch site's 10 to \
1531 120 kPa: the records are misread or damaged"
1532 ),
1533 ));
1534 }
1535 match flight.ground_pressure {
1536 Some(ground) => {
1537 let ground = f64::from(ground);
1538 let off = (pad - ground).abs() / ground;
1539 if off.is_nan() || off > GROUND_AGREES {
1541 return Err(refuse(
1542 f.at,
1543 format!(
1544 "the pad's pressure reads {pad:.0} Pa, {:.1}% from the flight \
1545 record's ground pressure, {ground:.0} Pa: the records are misread or \
1546 damaged",
1547 100.0 * off
1548 ),
1549 ));
1550 }
1551 pad_note = Some(format!(
1552 "`pressure` and `temperature` from the MS5607's counts by its data sheet's \
1553 compensation, first and second order. The pad's pressure, {pad:.0} Pa, lies \
1554 from 10 to 120 kPa and within {:.2}% of the flight record's ground pressure, \
1555 {ground:.0} Pa",
1556 100.0 * off
1557 ));
1558 }
1559 None => {
1560 pad_note = Some(format!(
1561 "`pressure` from the MP3H6115A's transfer function over the CC1111's full \
1562 scale, 32,752: the pad's pressure, {pad:.0} Pa, lies from 10 to 120 kPa"
1563 ));
1564 }
1565 }
1566 }
1567
1568 let pad_temperature = channels.get("temperature").and_then(|(times, values)| {
1570 let mut before: Vec<f64> = times
1571 .iter()
1572 .zip(values)
1573 .filter(|(time, value)| **time < 0.0 && value.is_finite())
1574 .map(|(_, value)| *value)
1575 .collect();
1576 crate::filter::median(&mut before).or_else(|| values.first().copied())
1577 });
1578 if let Some(kelvin) = pad_temperature
1579 && !MS5607_OPERATING_K.contains(&kelvin)
1580 {
1581 return Err(refuse(
1582 f.at,
1583 format!(
1584 "the pad's temperature reads {:.1} °C, outside the MS5607's operating range, −40 \
1585 to 85 °C: the records are misread or damaged",
1586 kelvin - 273.15
1587 ),
1588 ));
1589 }
1590
1591 let mut notes = Vec::new();
1592 notes.push(if json {
1593 format!(
1594 "{read_in_file} records of {size} bytes, log format {log_format}, from the JSON form: \
1595 every record's checksum checked, all pass"
1596 )
1597 } else {
1598 format!(
1599 "{read_in_file} records of {size} bytes, log format {log_format}, from the text form, \
1600 which prints no checksum"
1601 )
1602 });
1603 if from_product {
1604 notes.push(format!(
1605 "the configuration states no log format, as firmware before 1.0 didn't: format 1, \
1606 from its product, {}",
1607 config.product.as_deref().unwrap_or("")
1608 ));
1609 }
1610 if erased > 0 {
1611 notes.push(format!(
1612 "{erased} erased records (every byte 0xFF) after the last, skipped"
1613 ));
1614 }
1615 if last_line_cut {
1616 notes.push(
1617 "the file ends without a line break, so its last line may be cut short: left out"
1618 .to_owned(),
1619 );
1620 }
1621 if after_silence > 0 {
1622 notes.push(format!(
1623 "{after_silence} records from the first more than 10 s from the latest tick on are \
1624 left out. No logging rate leaves such a silence, so they are not this flight's"
1625 ));
1626 }
1627 if duplicates > 0 {
1628 notes.push(format!(
1629 "{duplicates} records repeated exactly, the same bytes at the same tick, dropped"
1630 ));
1631 }
1632 notes.push(format!(
1633 "the clock is the board's tick, 10 ms, from the flight record's at tick {zero_tick} \
1634 (boost detection). Each tick is on the turn nearest the latest so far, from the file's \
1635 first record. The records are in tick order, as the file's isn't. {before_boost} \
1636 records are before boost, at negative times"
1637 ));
1638 if let Some(note) = pad_note {
1639 notes.push(note);
1640 }
1641 if let Some(kelvin) = pad_temperature {
1642 notes.push(format!(
1643 "`temperature` on the pad, {:.1} °C, within the MS5607's operating range, −40 to 85 °C",
1644 kelvin - 273.15
1645 ));
1646 }
1647 if let Some(note) = climb_note {
1648 notes.push(note);
1649 }
1650 if prom.is_none() && board != Board::TeleMetrumV1 {
1651 notes.push(
1652 if config.ms5611 {
1653 "`d1` and `d2` kept as written: the configuration marks the barometer an MS5611, \
1654 whose compensation isn't the MS5607's"
1655 } else {
1656 "`d1` and `d2` kept as written: the configuration holds no MS5607 constants"
1657 }
1658 .to_owned(),
1659 );
1660 }
1661 match &accel {
1662 Accel::Converted { zero, per_g } => notes.push(format!(
1663 "`acceleration` along the board's axis, m/s², from the high-g accelerometer's counts. \
1664 It is 0 at the flight record's ground reading, {zero:.0}. A g is {per_g} counts, \
1665 from the calibration's +1 g and −1 g, {} and {}",
1666 config.accel_plus.unwrap_or(0),
1667 config.accel_minus.unwrap_or(0)
1668 )),
1669 Accel::AsWritten(why) if board != Board::EasyMini => {
1670 notes.push(format!("`accel` kept as written: {why}"));
1671 }
1672 Accel::AsWritten(_) => {}
1673 }
1674 let kept: Vec<&str> = [
1675 "v_batt",
1676 "sense_a",
1677 "sense_m",
1678 "temp",
1679 "imu_accel_0",
1680 "gps_byte_11",
1681 ]
1682 .into_iter()
1683 .filter(|name| channels.get(name).is_some())
1684 .collect();
1685 if !kept.is_empty() {
1686 notes.push(format!(
1687 "kept as written, counts with no cited conversion: {}",
1688 kept.iter()
1689 .map(|name| match *name {
1690 "imu_accel_0" => "the IMU's nine words".to_owned(),
1691 "temp" => "`temp` (the CC1111's die temperature)".to_owned(),
1692 "gps_byte_11" =>
1693 "`gps_byte_11` (a dilution in some firmware, a stale byte in others)"
1694 .to_owned(),
1695 name => format!("`{name}`"),
1696 })
1697 .collect::<Vec<_>>()
1698 .join(", ")
1699 ));
1700 }
1701 if channels.get("pyro").is_some() {
1702 notes.push(if mega_volts {
1703 "`pyro`, the igniters' and the apogee and main senses in V, as AltOS Telemetry \
1704 converts a 15 V Mega's: count / 4095 × 3.3 V × 127 / 27"
1705 .to_owned()
1706 } else {
1707 format!(
1708 "`pyro`, the igniters' and the apogee and main senses kept as written. The \
1709 product, {}, isn't one whose divider the sample exports bear out, and a 30 V \
1710 board's isn't a 15 V board's",
1711 cut(config.product.as_deref().unwrap_or("not stated"))
1712 )
1713 });
1714 }
1715 if sense_counts_off > 0 {
1716 notes.push(format!(
1717 "{sense_counts_off} sense records name a count of senses other than 6: their six \
1718 words kept as written, `sense_0` to `sense_5`"
1719 ));
1720 }
1721 if board == Board::Mega && !imu_read {
1722 notes.push(
1723 if log_format == 15 {
1724 "the IMU not read: format 15's layout of it is unconfirmed"
1725 } else {
1726 "the IMU not read: the flight record's IMU fields are all zero, so the records' \
1727 IMU bytes are stale"
1728 }
1729 .to_owned(),
1730 );
1731 }
1732 if channels.get("gps_flags").is_some() {
1733 notes.push(
1734 "GPS: the time, date, dilutions, course, speed, climb, satellite counts and signals \
1735 kept as written. The date has two digits and is not reliably the flight's. The \
1736 dilutions are ten times their value"
1737 .to_owned(),
1738 );
1739 }
1740 if no_fix > 0 {
1741 notes.push(format!(
1742 "{no_fix} GPS position records without a valid fix: their positions read as gaps"
1743 ));
1744 }
1745 if satellites_cut > 0 {
1746 notes.push(format!(
1747 "{satellites_cut} satellite records name more satellites than they hold: those that \
1748 fit are read"
1749 ));
1750 }
1751 for (kind, count) in ¬_read {
1752 notes.push(format!(
1753 "{count} records of type {} not read: the board's layout holds no such record",
1754 if kind.is_ascii_graphic() {
1755 format!("`{}`", char::from(*kind))
1756 } else {
1757 format!("0x{kind:02X}")
1758 }
1759 ));
1760 }
1761
1762 let mut figures = Vec::new();
1763 if let Some(ground) = flight.ground_pressure {
1764 figures.push(Figure::new(
1765 "ground_pressure",
1766 ground.to_string(),
1767 Some(Quantity::Pressure),
1768 vec![f64::from(ground)],
1769 ));
1770 }
1771 if let Some(ground) = flight.ground_accel {
1772 figures.push(Figure::new(
1773 "ground_accel",
1774 ground.to_string(),
1775 Some(Quantity::Unrecognized),
1776 vec![ground as f64],
1777 ));
1778 }
1779 if board != Board::EasyMini {
1780 for (name, value) in [
1781 ("accel_cal_plus", config.accel_plus),
1782 ("accel_cal_minus", config.accel_minus),
1783 ] {
1784 if let Some(value) = value {
1785 figures.push(Figure::new(
1786 name,
1787 value.to_string(),
1788 Some(Quantity::Unrecognized),
1789 vec![value as f64],
1790 ));
1791 }
1792 }
1793 }
1794 if imu_read {
1795 let accel: Vec<f64> = flight.imu_accel.iter().map(|v| f64::from(*v)).collect();
1796 let gyro: Vec<f64> = flight.gyro_sums.iter().map(|v| f64::from(*v)).collect();
1797 figures.push(Figure::new(
1798 "ground_imu_accel",
1799 join(&accel),
1800 Some(Quantity::Unrecognized),
1801 accel,
1802 ));
1803 figures.push(Figure::new(
1804 "ground_gyro_sums",
1805 join(&gyro),
1806 Some(Quantity::Unrecognized),
1807 gyro,
1808 ));
1809 }
1810 figures.extend(config.pad_orientation);
1811 figures.extend(config.main_deploy);
1812 figures.extend(config.apogee_delay);
1813
1814 Ok(FlightLog {
1815 format: LogFormat::AltosEeprom,
1816 logger: match &config.product {
1817 Some(product) => format!("AltOS {product}"),
1818 None => "AltOS".to_owned(),
1819 },
1820 serial_number: config.serial.map(|serial| serial.to_string()),
1821 firmware: config.version,
1822 flight_number: Some(u32::from(flight.number)),
1823 stated: Stated {
1824 figures,
1825 ..Stated::default()
1826 },
1827 time_s: Vec::new(),
1828 altitude_m: Vec::new(),
1829 vertical_speed_m_s: None,
1830 temperature_k: None,
1831 battery_v: None,
1832 channels: channels.into_channels(),
1833 events,
1834 notes,
1835 })
1836}
1837
1838#[derive(Debug, Clone, Copy, PartialEq)]
1841struct Climb {
1842 by_pressure_m: f64,
1843 by_acceleration_m: f64,
1844 ratio: f64,
1845}
1846
1847fn climb_sample(board: Board, record: &Record, prom: Option<&Prom>) -> Option<(f64, i64)> {
1851 if record.kind() != b'A' {
1852 return None;
1853 }
1854 match board {
1855 Board::TeleMetrumV1 => Some((mp3h6115a_pa(record.i16(6)), i64::from(record.i16(4)))),
1856 Board::TeleMetrumV2 => {
1857 let (pa, _) = ms5607(record.u32(4), record.u32(8), prom?);
1858 Some((pa as f64, i64::from(record.i16(12))))
1859 }
1860 Board::Mega => {
1861 let (pa, _) = ms5607(record.u32(4), record.u32(8), prom?);
1862 Some((pa as f64, i64::from(record.i16(30))))
1863 }
1864 Board::EasyMini => None,
1865 }
1866}
1867
1868fn climb_over_the_window(samples: &[(i64, f64, f64)]) -> Result<Climb, String> {
1880 let seconds = |ticks: i64| ticks as f64 / TICKS_PER_S;
1881 let mut pad: Vec<f64> = samples
1882 .iter()
1883 .filter(|(tick, ..)| *tick < 0)
1884 .map(|(_, pa, _)| *pa)
1885 .collect();
1886 let pad_pa =
1887 crate::filter::median(&mut pad).ok_or("no sample before boost to start from at rest")?;
1888 let last = samples.last().map_or(i64::MIN, |(tick, ..)| *tick);
1889 if last < CLIMB_WINDOW_TICKS {
1890 return Err(format!(
1891 "the samples end {:.2} s after boost, before the window's 1 s",
1892 seconds(last)
1893 ));
1894 }
1895 let mut window = Vec::new();
1896 for pair in samples.windows(2) {
1897 let [(from, ..), (to, ..)] = [pair[0], pair[1]];
1898 if to - from > CLIMB_GAP_TICKS {
1899 return Err(format!(
1900 "no sample for {:.2} s after the one at {:.2} s, more than the slowest logging \
1901 rate's 0.1 s",
1902 seconds(to - from),
1903 seconds(from)
1904 ));
1905 }
1906 window.push(pair);
1907 if to >= CLIMB_WINDOW_TICKS {
1908 break;
1909 }
1910 }
1911 let mut end = samples.first().map_or(0, |(tick, ..)| *tick);
1912 let (mut speed, mut climb_by_acceleration) = (0.0, 0.0);
1913 for pair in window {
1914 let [(from, _, a0), (to, _, a1)] = [pair[0], pair[1]];
1915 if to > CLIMB_WINDOW_TICKS {
1916 break;
1917 }
1918 let dt = seconds(to - from);
1919 let next = speed + (a0 + a1) / 2.0 * dt;
1920 climb_by_acceleration += (speed + next) / 2.0 * dt;
1921 speed = next;
1922 end = to;
1923 }
1924 let mut near: Vec<f64> = samples
1925 .iter()
1926 .filter(|(tick, ..)| (tick - end).abs() <= CLIMB_END_TICKS)
1927 .map(|(_, pa, _)| *pa)
1928 .collect();
1929 let end_pa = crate::filter::median(&mut near).unwrap_or(f64::NAN);
1930 let atmosphere = hpr_atmos::ussa76::Ussa76::standard();
1931 let height = |pa: f64| atmosphere.pressure_altitude_m(pa).unwrap_or(f64::NAN);
1932 let by_pressure_m = height(end_pa) - height(pad_pa);
1933 Ok(Climb {
1934 by_pressure_m,
1935 by_acceleration_m: climb_by_acceleration,
1936 ratio: by_pressure_m / climb_by_acceleration,
1937 })
1938}
1939
1940fn join(values: &[f64]) -> String {
1942 values
1943 .iter()
1944 .map(f64::to_string)
1945 .collect::<Vec<_>>()
1946 .join(",")
1947}
1948
1949fn describe(at: At) -> String {
1951 match at {
1952 At::Line(line) => format!("line {line}"),
1953 At::Offset(offset) => format!("byte {offset}"),
1954 }
1955}
1956
1957fn state_name(number: u16) -> String {
1959 STATES
1960 .iter()
1961 .find(|(known, _)| *known == number)
1962 .map_or_else(|| format!("state {number}"), |(_, name)| (*name).to_owned())
1963}
1964
1965fn cut(text: &str) -> String {
1967 text.chars().take(80).collect()
1968}
1969
1970#[cfg(test)]
1971mod tests {
1972 use super::*;
1973
1974 const EXAMPLE_PROM: Prom = [46_372, 43_981, 29_059, 27_842, 31_553, 28_165];
1976
1977 const EXAMPLE_D1: u32 = 6_465_444;
1979 const EXAMPLE_D2: u32 = 8_077_636;
1980
1981 const HEAD_V2: &str = r#"{
1984 "accel_cal_minus": 1040, "accel_cal_plus": 1000, "altitude_32": 1, "apogee_delay": 0,
1985 "flight": 2147483647, "log_format": 7, "main_deploy": 250,
1986 "ms5607": {"ms5611": false, "off": 43981, "sens": 46372, "tco": 27842, "tcs": 29059,
1987 "tempsens": 28165, "tref": 31553},
1988 "product": "TeleMetrum-v2.0", "serial": 1234, "stored_flight": 9, "version": "1.9.22"
1989 }"#;
1990
1991 const TEXT_HEAD_V2: &[&str] = &[
1993 "~",
1994 "> E 0",
1995 "Config version: 1.27",
1996 "Main deploy: 250 meters",
1997 "Apogee delay: 0 seconds",
1998 "Accel cal +1g: 1000 -1g: 1040",
1999 "ms5607 reserved: 0",
2000 "ms5607 sens: 46372",
2001 "ms5607 off: 43981",
2002 "ms5607 tcs: 29059",
2003 "ms5607 tco: 27842",
2004 "ms5607 tref: 31553",
2005 "ms5607 tempsens: 28165",
2006 "manufacturer altusmetrum.org",
2007 "product TeleMetrum-v2.0",
2008 "serial-number 1234",
2009 "log-format 7",
2010 "altitude-32 1",
2011 "software-version 1.9.22",
2012 "done",
2013 ];
2014
2015 fn record(size: usize, kind: u8, tick: u16, fields: &[u8]) -> Vec<u8> {
2018 let mut bytes = vec![kind, 0];
2019 bytes.extend(tick.to_le_bytes());
2020 bytes.extend(fields);
2021 bytes.resize(size, 0);
2022 let sum = bytes
2023 .iter()
2024 .fold(CHECKSUM_BASE, |sum, byte| sum.wrapping_add(*byte));
2025 bytes[1] = 0u8.wrapping_sub(sum);
2026 bytes
2027 }
2028
2029 fn f7(tick: u16, flight: u16, ground_accel: i16, ground_pa: u32) -> Vec<u8> {
2031 let mut fields = flight.to_le_bytes().to_vec();
2032 fields.extend(ground_accel.to_le_bytes());
2033 fields.extend(ground_pa.to_le_bytes());
2034 record(16, b'F', tick, &fields)
2035 }
2036
2037 fn a7(tick: u16, d1: u32, d2: u32, accel: i16) -> Vec<u8> {
2039 let mut fields = d1.to_le_bytes().to_vec();
2040 fields.extend(d2.to_le_bytes());
2041 fields.extend(accel.to_le_bytes());
2042 record(16, b'A', tick, &fields)
2043 }
2044
2045 fn s(size: usize, tick: u16, state: u16) -> Vec<u8> {
2047 record(size, b'S', tick, &state.to_le_bytes())
2048 }
2049
2050 fn json(head: &str, records: &[Vec<u8>]) -> String {
2052 let bytes = records.concat();
2053 let mut out = format!("{head}\n");
2054 for line in bytes.chunks(32) {
2055 let hex: Vec<String> = line.iter().map(|b| format!("{b:02x}")).collect();
2056 out.push_str(&hex.join(" "));
2057 out.push('\n');
2058 }
2059 out
2060 }
2061
2062 fn text(head: &[&str], records: &[Vec<u8>]) -> String {
2065 let mut out: String = head.iter().map(|line| format!("{line}\n")).collect();
2066 for bytes in records {
2067 let tick = u16::from_le_bytes([bytes[2], bytes[3]]);
2068 let fields: Vec<String> = if bytes.len() == 8 {
2069 vec![
2070 format!("{:4x}", u16::from_le_bytes([bytes[4], bytes[5]])),
2071 format!("{:4x}", u16::from_le_bytes([bytes[6], bytes[7]])),
2072 ]
2073 } else {
2074 bytes[4..].iter().map(|b| format!("{b:02x}")).collect()
2075 };
2076 out.push_str(&format!(
2077 "{} {tick:x} {}\n",
2078 char::from(bytes[0]),
2079 fields.join(" ")
2080 ));
2081 }
2082 out
2083 }
2084
2085 fn pressure_at(altitude_m: f64) -> f64 {
2089 101_325.0 * (1.0 - altitude_m / 44_330.8).powf(1.0 / 0.190_263)
2090 }
2091
2092 fn altitude_of(pressure_pa: f64) -> f64 {
2094 44_330.8 * (1.0 - (pressure_pa / 101_325.0).powf(0.190_263))
2095 }
2096
2097 fn climbed_m(t: f64) -> f64 {
2099 0.5 * 5.0 * STANDARD_GRAVITY * t * t
2100 }
2101
2102 fn d1_for(pa: f64) -> u32 {
2106 let (off, sens) = (5_764_707_214_i128, 3_039_050_829_i128);
2107 let wanted = pa.round() as i128;
2108 let d1 = ((((wanted << 15) + off) << 21) + sens - 1) / sens;
2109 let d1 = u32::try_from(d1).unwrap();
2110 assert_eq!(ms5607(d1, EXAMPLE_D2, &EXAMPLE_PROM).0, wanted);
2111 d1
2112 }
2113
2114 fn climb_v2(zero: u16) -> Vec<Vec<u8>> {
2118 let pad_m = altitude_of(110_002.0);
2119 (1..=11u16)
2120 .map(|k| {
2121 let pa = pressure_at(pad_m + climbed_m(f64::from(k) / 10.0));
2122 a7(zero.wrapping_add(10 * k), d1_for(pa), EXAMPLE_D2, 900)
2123 })
2124 .collect()
2125 }
2126
2127 fn flight_v2() -> Vec<Vec<u8>> {
2131 let mut records = vec![
2132 f7(200, 3, 1000, 110_002),
2133 a7(198, EXAMPLE_D1, EXAMPLE_D2, 1000),
2134 a7(199, EXAMPLE_D1, EXAMPLE_D2, 1001),
2135 s(16, 201, 3),
2136 a7(200, EXAMPLE_D1, EXAMPLE_D2, 960),
2137 a7(201, EXAMPLE_D1 - 1000, EXAMPLE_D2, 900),
2138 a7(202, EXAMPLE_D1 - 2000, EXAMPLE_D2, 1040),
2139 ];
2140 records.extend(climb_v2(200));
2141 records
2142 }
2143
2144 const HEAD_RECORDS: usize = 7;
2146
2147 fn a1(tick: u16, accel: i16, pressure: i16) -> Vec<u8> {
2149 let mut fields = accel.to_le_bytes().to_vec();
2150 fields.extend(pressure.to_le_bytes());
2151 record(8, b'A', tick, &fields)
2152 }
2153
2154 fn mp3h6115a_count(pa: f64) -> i16 {
2156 ((pa / 1000.0 * 0.009 - 0.095) * CC1111_FULL_SCALE).round() as i16
2157 }
2158
2159 const HEAD_V1: &str = r#"{"log_format": 1, "product": "TeleMetrum-v1.2", "serial": 77,
2161 "accel_cal_plus": 16000, "accel_cal_minus": 16500}"#;
2162
2163 fn flight_v1(pad_count: i16) -> Vec<Vec<u8>> {
2168 let pad_m = altitude_of(mp3h6115a_pa(pad_count));
2169 let mut records = vec![
2170 record(8, b'F', 100, &[0x80, 0x3e, 3, 0]),
2171 a1(98, 16_000, pad_count),
2172 a1(99, 16_000, pad_count),
2173 a1(100, 14_750, pad_count),
2174 ];
2175 for k in 1..=11u16 {
2176 let pa = pressure_at(pad_m + climbed_m(f64::from(k) / 10.0));
2177 records.push(a1(100 + 10 * k, 14_750, mp3h6115a_count(pa)));
2178 }
2179 records
2180 }
2181
2182 fn channel<'a>(log: &'a FlightLog, column: &str) -> Option<&'a Channel> {
2183 log.channels.iter().find(|c| c.column == column)
2184 }
2185
2186 fn values(log: &FlightLog, column: &str) -> Vec<f64> {
2187 channel(log, column)
2188 .unwrap_or_else(|| panic!("no {column}: {:#?}", log.notes))
2189 .values
2190 .clone()
2191 }
2192
2193 fn has_note(log: &FlightLog, start: &str) -> bool {
2194 log.notes.iter().any(|note| note.starts_with(start))
2195 }
2196
2197 #[test]
2199 fn the_documented_record_is_a_flight_record() {
2200 let written: Vec<String> = f7(0x164, 3, 25, 98_000)
2201 .iter()
2202 .map(|b| format!("{b:02x}"))
2203 .collect();
2204 assert_eq!(
2205 written.join(" "),
2206 "46 90 64 01 03 00 19 00 d0 7e 01 00 00 00 00 00"
2207 );
2208 let line = text(&[], &[f7(0x164, 3, 25, 98_000)]);
2209 assert_eq!(line, "F 164 03 00 19 00 d0 7e 01 00 00 00 00 00\n");
2210 }
2211
2212 #[test]
2213 fn the_layout_is_recognized_in_both_forms() {
2214 assert!(recognizes(&json(HEAD_V2, &flight_v2())));
2215 assert!(recognizes(&text(TEXT_HEAD_V2, &flight_v2())));
2216 assert!(recognizes(
2217 " {\"log_format\": 7, \"product\": \"EasyMini-v2.0\"}"
2218 ));
2219 assert!(!recognizes("{\"log_format\": 7}"), "no product");
2220 assert!(
2221 !recognizes("{\"product\": \"EasyMini-v2.0\"}"),
2222 "no log format"
2223 );
2224 assert!(!recognizes("{\"log_format\": 7, \"product\": 3}"));
2225 assert!(!recognizes(
2226 "Config version: 1.27\nproduct TeleMetrum-v2.0\n"
2227 ));
2228 assert!(!recognizes("manufacturer altusmetrum.org\n"));
2229 assert!(!recognizes("TELEM 22ab\n"));
2230 assert!(!recognizes("#version,serial,flight,call,time\n"));
2231 }
2232
2233 #[test]
2236 fn the_data_sheets_example_reads_to_its_values() {
2237 assert_eq!(
2238 ms5607(EXAMPLE_D1, EXAMPLE_D2, &EXAMPLE_PROM),
2239 (110_002, 2_000)
2240 );
2241 }
2242
2243 #[test]
2248 fn below_20_c_the_second_order_applies() {
2249 let cold = ms5607(EXAMPLE_D1, EXAMPLE_D2 - 300_000, &EXAMPLE_PROM);
2250 assert_eq!(cold, (107_504, 951));
2251 let very_cold = ms5607(EXAMPLE_D1, EXAMPLE_D2 - 1_500_000, &EXAMPLE_PROM);
2252 assert_eq!(very_cold, (95_359, -4_084));
2253 }
2254
2255 #[test]
2259 fn every_division_by_a_power_of_two_is_a_floor() {
2260 fn truncating(d1: u32, d2: u32, prom: &Prom) -> (i128, i128) {
2261 let [c1, c2, c3, c4, c5, c6] = prom.map(i128::from);
2262 let (d1, d2) = (i128::from(d1), i128::from(d2));
2263 let dt = d2 - c5 * 256;
2264 let mut temp = 2000 + dt * c6 / (1 << 23);
2265 let mut off = c2 * (1 << 17) + c4 * dt / (1 << 6);
2266 let mut sens = c1 * (1 << 16) + c3 * dt / (1 << 7);
2267 if temp < 2000 {
2268 off -= 61 * (temp - 2000).pow(2) / (1 << 4);
2269 sens -= 2 * (temp - 2000).pow(2);
2270 temp -= dt * dt / (1 << 31);
2271 }
2272 ((d1 * sens / (1 << 21) - off) / (1 << 15), temp)
2273 }
2274 let d2 = EXAMPLE_D2 - 300_000;
2275 assert_eq!(truncating(EXAMPLE_D1, d2, &EXAMPLE_PROM), (107_505, 952));
2276 assert_ne!(
2277 ms5607(EXAMPLE_D1, d2, &EXAMPLE_PROM),
2278 truncating(EXAMPLE_D1, d2, &EXAMPLE_PROM)
2279 );
2280 assert_eq!(
2282 ms5607(EXAMPLE_D1, EXAMPLE_D2 - 3_000, &EXAMPLE_PROM),
2283 (109_978, 1_990)
2284 );
2285 }
2286
2287 #[test]
2290 fn the_mp3h6115a_reads_by_its_transfer_function() {
2291 assert!((mp3h6115a_pa(32_752) - 1.095 / 0.009 * 1000.0).abs() < 1e-9);
2292 assert!((mp3h6115a_pa(0) - 0.095 / 0.009 * 1000.0).abs() < 1e-9);
2293 assert!((mp3h6115a_pa(24_000) - 91_975.5).abs() < 0.1);
2294 assert_eq!(CC1111_FULL_SCALE, f64::from(2047 * 16));
2295 }
2296
2297 #[test]
2299 fn a_flight_reads_in_tick_order_from_the_flight_record() {
2300 let log = read(&json(HEAD_V2, &flight_v2())).unwrap();
2301 assert_eq!(log.format, LogFormat::AltosEeprom);
2302 assert_eq!(log.logger, "AltOS TeleMetrum-v2.0");
2303 assert_eq!(log.serial_number.as_deref(), Some("1234"));
2304 assert_eq!(log.firmware.as_deref(), Some("1.9.22"));
2305 assert_eq!(log.flight_number, Some(3));
2307 assert!(log.time_s.is_empty() && log.altitude_m.is_empty());
2308 let pressure = channel(&log, "pressure").unwrap();
2309 assert_eq!(pressure.quantity, Quantity::Pressure);
2310 assert_eq!(pressure.time_s[..5], [-0.02, -0.01, 0.0, 0.01, 0.02]);
2311 assert_eq!(pressure.time_s[5..7], [0.1, 0.2]);
2312 assert_eq!(pressure.values[..3], [110_002.0; 3]);
2313 assert!(pressure.values[3] < pressure.values[2]);
2314 assert!((values(&log, "temperature")[0] - 293.15).abs() < 1e-9);
2315 let g = STANDARD_GRAVITY;
2317 let acceleration = values(&log, "acceleration");
2318 for (got, want) in acceleration
2319 .iter()
2320 .zip([0.0, -0.05 * g, 2.0 * g, 5.0 * g, -2.0 * g])
2321 {
2322 assert!((got - want).abs() < 1e-12, "{acceleration:?}");
2323 }
2324 assert_eq!(log.events.len(), 1);
2325 assert_eq!(
2326 (log.events[0].time_s, log.events[0].name.as_str()),
2327 (0.01, "boost")
2328 );
2329 let figure = |name: &str| log.stated.figures.iter().find(|f| f.name == name).unwrap();
2330 assert_eq!(figure("ground_pressure").values, [110_002.0]);
2331 assert_eq!(figure("ground_pressure").quantity, Some(Quantity::Pressure));
2332 assert_eq!(figure("accel_cal_minus").values, [1040.0]);
2333 assert_eq!(figure("main_deploy").quantity, Some(Quantity::Unrecognized));
2334 assert!(has_note(
2335 &log,
2336 "18 records of 16 bytes, log format 7, from the JSON form"
2337 ));
2338 assert!(has_note(
2339 &log,
2340 "the clock is the board's tick, 10 ms, from the flight record's at tick 200"
2341 ));
2342 let figure = |name: &str| log.stated.figures.iter().find(|f| f.name == name);
2343 assert!(figure("pad_orientation").is_none(), "the head states none");
2344 }
2345
2346 #[test]
2348 fn the_text_and_json_forms_of_a_flight_read_alike() {
2349 let from_json = read(&json(HEAD_V2, &flight_v2())).unwrap();
2350 let from_text = read(&text(TEXT_HEAD_V2, &flight_v2())).unwrap();
2351 assert_eq!(from_json.channels, from_text.channels);
2352 assert_eq!(from_json.events, from_text.events);
2353 assert_eq!(from_json.serial_number, from_text.serial_number);
2354 assert_eq!(from_json.flight_number, from_text.flight_number);
2355 assert_eq!(from_json.firmware, from_text.firmware);
2356 assert!(has_note(
2357 &from_text,
2358 "18 records of 16 bytes, log format 7, from the text form"
2359 ));
2360 let main = from_text
2362 .stated
2363 .figures
2364 .iter()
2365 .find(|f| f.name == "main_deploy")
2366 .unwrap();
2367 assert_eq!(main.quantity, Some(Quantity::AltitudeAboveGround));
2368 assert_eq!(
2369 (main.written.as_str(), main.values.as_slice()),
2370 ("250 meters", &[250.0][..])
2371 );
2372 }
2373
2374 #[test]
2376 fn a_record_failing_its_checksum_refuses_the_file() {
2377 let mut records = flight_v2();
2378 records[2][9] ^= 0x01;
2379 match read(&json(HEAD_V2, &records)) {
2380 Err(LogError::Binary {
2381 offset, message, ..
2382 }) => {
2383 assert_eq!(offset, 32);
2384 assert!(
2385 message.starts_with("record 3 fails its checksum"),
2386 "{message}"
2387 );
2388 }
2389 other => panic!("{other:?}"),
2390 }
2391 }
2392
2393 #[test]
2396 fn a_log_format_no_sample_shows_is_refused_by_number() {
2397 for format in [2, 5, 8, 13, 17, 21, 23] {
2398 let head = HEAD_V2.replace("\"log_format\": 7", &format!("\"log_format\": {format}"));
2399 match read(&json(&head, &flight_v2())) {
2400 Err(LogError::Syntax { line, message, .. }) => {
2401 assert_eq!(line, 1);
2402 assert!(
2403 message.starts_with(&format!("log format {format}, which no sample")),
2404 "{message}"
2405 );
2406 }
2407 other => panic!("{format}: {other:?}"),
2408 }
2409 }
2410 let lines: Vec<&str> = TEXT_HEAD_V2
2411 .iter()
2412 .map(|line| {
2413 if line.starts_with("log-format") {
2414 "log-format 9"
2415 } else {
2416 line
2417 }
2418 })
2419 .collect();
2420 match read(&text(&lines, &flight_v2())) {
2421 Err(LogError::Syntax { line, message, .. }) => {
2422 assert_eq!(line, TEXT_HEAD_V2.len() + 1);
2423 assert!(
2424 message.starts_with("log format 9, which no sample"),
2425 "{message}"
2426 );
2427 }
2428 other => panic!("{other:?}"),
2429 }
2430 let unstated = HEAD_V2.replace("\"log_format\": 7,", "\"log_format\": 2147483647,");
2432 match read(&json(&unstated, &flight_v2())) {
2433 Err(LogError::Syntax { message, .. }) => {
2434 assert!(
2435 message.contains("states no log format, and its product, \"TeleMetrum-v2.0\""),
2436 "{message}"
2437 );
2438 }
2439 other => panic!("{other:?}"),
2440 }
2441 let head_v1 = HEAD_V1
2442 .replace("\"log_format\": 1", "\"log_format\": 2147483647")
2443 .replace("TeleMetrum-v1.2", "TeleMetrum-v1.0");
2444 let log = read(&json(&head_v1, &flight_v1(24_000))).unwrap();
2445 assert!(has_note(
2446 &log,
2447 "the configuration states no log format, as firmware before 1.0"
2448 ));
2449 assert!(has_note(&log, "15 records of 8 bytes, log format 1"));
2450 }
2451
2452 #[test]
2454 fn erased_memory_ends_the_records() {
2455 let mut records = flight_v2();
2456 records.push(vec![0xff; 16]);
2457 records.push(vec![0xff; 16]);
2458 let log = read(&json(HEAD_V2, &records)).unwrap();
2459 assert!(has_note(
2460 &log,
2461 "2 erased records (every byte 0xFF) after the last, skipped"
2462 ));
2463 records.push(s(16, 203, 4));
2464 match read(&json(HEAD_V2, &records)) {
2465 Err(LogError::Binary {
2466 offset, message, ..
2467 }) => {
2468 assert_eq!(offset, 20 * 16);
2469 assert!(
2470 message.starts_with("a record after the erased memory from byte 288"),
2471 "{message}"
2472 );
2473 }
2474 other => panic!("{other:?}"),
2475 }
2476 for token in ["4g", "+6"] {
2479 let damaged = json(HEAD_V2, &flight_v2()).replacen("\n46 ", &format!("\n{token} "), 1);
2480 match read(&damaged) {
2481 Err(LogError::Syntax { message, .. }) => assert!(
2482 message.starts_with(&format!("\"{token}\" where the memory's bytes")),
2483 "{message}"
2484 ),
2485 other => panic!("{token}: {other:?}"),
2486 }
2487 }
2488 let mut short = json(HEAD_V2, &flight_v2());
2490 short.push_str("ff ff ff ff\n");
2491 match read(&short) {
2492 Err(LogError::Binary {
2493 offset, message, ..
2494 }) => {
2495 assert_eq!(offset, 18 * 16);
2496 assert!(
2497 message.starts_with("the memory ends in 4 bytes, part of a 16-byte record"),
2498 "{message}"
2499 );
2500 }
2501 other => panic!("{other:?}"),
2502 }
2503 }
2504
2505 #[test]
2508 fn a_file_with_no_records_holds_no_data() {
2509 let empty = json(HEAD_V2, &[]);
2510 let erased = json(HEAD_V2, &[vec![0xff; 16], vec![0xff; 16]]);
2511 let cut = text(TEXT_HEAD_V2, &flight_v2()[..1]);
2512 for file in [empty, erased, cut.trim_end().to_owned()] {
2513 assert!(
2514 matches!(read(&file), Err(LogError::NoData { .. })),
2515 "{:?}",
2516 read(&file)
2517 );
2518 }
2519 }
2520
2521 #[test]
2524 fn a_text_files_last_line_cut_short_is_left_out() {
2525 let whole = text(TEXT_HEAD_V2, &flight_v2());
2526 let cut = &whole[..whole.len() - 7];
2527 let log = read(cut).unwrap();
2528 assert!(has_note(
2529 &log,
2530 "the file ends without a line break, so its last line may be cut short"
2531 ));
2532 assert_eq!(values(&log, "pressure").len(), 15);
2533 let log = read(whole.trim_end_matches('\n')).unwrap();
2535 assert_eq!(values(&log, "pressure").len(), 15);
2536 let mut lines: Vec<&str> = whole.lines().collect();
2538 let short = "A c8 64 a7 62 00";
2539 lines.insert(TEXT_HEAD_V2.len() + 2, short);
2540 let damaged = lines.join("\n") + "\n";
2541 match read(&damaged) {
2542 Err(LogError::Syntax { line, message, .. }) => {
2543 assert_eq!(line, TEXT_HEAD_V2.len() + 3);
2544 assert!(
2545 message.contains("isn't a record of log format 7"),
2546 "{message}"
2547 );
2548 }
2549 other => panic!("{other:?}"),
2550 }
2551 }
2552
2553 #[test]
2556 fn the_ticks_turns_are_unwound_and_the_records_sorted() {
2557 let mut records = vec![
2558 f7(65_534, 3, 1000, 110_002),
2560 a7(65_533, EXAMPLE_D1, EXAMPLE_D2, 1000),
2561 a7(65_535, EXAMPLE_D1, EXAMPLE_D2, 1000),
2562 s(16, 1, 3),
2564 a7(0, EXAMPLE_D1, EXAMPLE_D2, 990),
2565 a7(1, EXAMPLE_D1, EXAMPLE_D2, 980),
2566 record(16, b'G', 65_500, &[12, 0, 1, 0x10 | 6, 26, 10, 14, 40]),
2568 a7(2, EXAMPLE_D1, EXAMPLE_D2, 970),
2569 ];
2570 records.extend(climb_v2(65_534));
2571 let log = read(&json(HEAD_V2, &records)).unwrap();
2572 let pressure = channel(&log, "pressure").unwrap();
2573 assert_eq!(pressure.time_s[..6], [-0.01, 0.01, 0.02, 0.03, 0.04, 0.1]);
2574 let acceleration = values(&log, "acceleration");
2575 assert_eq!(acceleration[..2], [0.0, 0.0]);
2576 assert!((acceleration[2] - 0.5 * STANDARD_GRAVITY).abs() < 1e-12);
2577 assert_eq!(log.events[0].time_s, 0.03);
2578 assert_eq!(channel(&log, "hour").unwrap().time_s, [-0.34]);
2579 assert!(has_note(
2580 &log,
2581 "the clock is the board's tick, 10 ms, from the flight record's at tick 65534"
2582 ));
2583 assert!(
2584 log.notes
2585 .iter()
2586 .any(|n| n.ends_with("2 records are before boost, at negative times"))
2587 );
2588 }
2589
2590 #[test]
2595 fn records_are_sorted_by_tick_and_stable_among_equal_ticks() {
2596 let mut records = flight_v2();
2597 let late = [
2598 a7(205, EXAMPLE_D1 - 3000, EXAMPLE_D2, 950),
2599 a7(203, EXAMPLE_D1 - 2500, EXAMPLE_D2, 940),
2600 a7(204, EXAMPLE_D1 - 2600, EXAMPLE_D2, 930),
2601 a7(204, EXAMPLE_D1 - 2700, EXAMPLE_D2, 920),
2602 ];
2603 records.splice(HEAD_RECORDS..HEAD_RECORDS, late);
2604 let log = read(&json(HEAD_V2, &records)).unwrap();
2605 let pressure = channel(&log, "pressure").unwrap();
2606 assert_eq!(pressure.time_s[4..10], [0.02, 0.03, 0.04, 0.04, 0.05, 0.1]);
2607 let g = STANDARD_GRAVITY;
2609 let acceleration = values(&log, "acceleration");
2610 for (got, want) in acceleration[5..9].iter().zip([3.0, 3.5, 4.0, 2.5]) {
2611 assert!((got - want * g).abs() < 1e-12, "{acceleration:?}");
2612 }
2613 }
2614
2615 #[test]
2618 fn a_silence_of_more_than_10_s_ends_the_flight() {
2619 let mut records = flight_v2();
2620 records.push(s(16, 1_202, 8));
2621 let log = read(&json(HEAD_V2, &records)).unwrap();
2622 assert_eq!(log.events.last().map(|e| e.time_s), Some(10.02));
2623 records.push(s(16, 2_203, 2));
2624 records.push(a7(2_204, EXAMPLE_D1, EXAMPLE_D2, 1000));
2625 let log = read(&json(HEAD_V2, &records)).unwrap();
2626 assert_eq!(values(&log, "pressure").len(), 16);
2627 assert!(has_note(
2628 &log,
2629 "2 records from the first more than 10 s from the latest tick on are left out"
2630 ));
2631 let mut records = flight_v2();
2633 records.push(a7(60_000, EXAMPLE_D1, EXAMPLE_D2, 1000));
2634 let log = read(&json(HEAD_V2, &records)).unwrap();
2635 assert!(has_note(&log, "1 records from the first more than 10 s"));
2636 }
2637
2638 #[test]
2641 fn records_repeated_exactly_are_dropped() {
2642 let mut records = flight_v2();
2643 records.insert(5, records[4].clone());
2644 records.push(s(16, 203, 3));
2645 let log = read(&text(TEXT_HEAD_V2, &records)).unwrap();
2646 assert!(has_note(&log, "1 records repeated exactly"));
2647 assert_eq!(values(&log, "pressure").len(), 16);
2648 assert_eq!(values(&log, "state"), [3.0, 3.0]);
2649 }
2650
2651 #[test]
2652 fn a_file_needs_exactly_one_flight_record() {
2653 let mut records = flight_v2();
2654 records.push(f7(210, 4, 1000, 110_002));
2655 match read(&json(HEAD_V2, &records)) {
2656 Err(LogError::Binary {
2657 offset, message, ..
2658 }) => {
2659 assert_eq!(offset, 18 * 16);
2660 assert!(
2661 message.starts_with("a second flight record, after the one at byte 0"),
2662 "{message}"
2663 );
2664 }
2665 other => panic!("{other:?}"),
2666 }
2667 let records: Vec<Vec<u8>> = flight_v2().into_iter().skip(1).collect();
2668 match read(&json(HEAD_V2, &records)) {
2669 Err(LogError::Binary { message, .. }) => {
2670 assert!(message.starts_with("no flight record"))
2671 }
2672 other => panic!("{other:?}"),
2673 }
2674 }
2675
2676 #[test]
2679 fn the_pads_pressure_is_held_to_a_launch_site_and_the_flight_record() {
2680 let v1 = |count: i16| read(&json(HEAD_V1, &flight_v1(count)));
2681 assert!(v1(-163).is_ok() && v1(32_260).is_ok());
2683 for count in [-164, 32_261] {
2684 match v1(count) {
2685 Err(LogError::Binary {
2686 offset, message, ..
2687 }) => {
2688 assert_eq!(offset, 0);
2689 assert!(
2690 message.contains("outside every launch site's 10 to 120 kPa"),
2691 "{message}"
2692 );
2693 }
2694 other => panic!("{count}: {other:?}"),
2695 }
2696 }
2697 let with_ground = |ground: u32| {
2699 let mut records = flight_v2();
2700 records[0] = f7(200, 3, 1000, ground);
2701 read(&json(HEAD_V2, &records))
2702 };
2703 assert!(with_ground(111_100).is_ok() && with_ground(108_920).is_ok());
2704 for ground in [111_125, 108_890] {
2705 match with_ground(ground) {
2706 Err(LogError::Binary { message, .. }) => {
2707 assert!(
2708 message.contains("from the flight record's ground pressure"),
2709 "{message}"
2710 );
2711 }
2712 other => panic!("{ground}: {other:?}"),
2713 }
2714 }
2715 }
2716
2717 #[test]
2722 fn acceleration_is_from_the_files_own_calibration() {
2723 let cooked = HEAD_V2
2724 .replace("\"accel_cal_minus\": 1040, \"accel_cal_plus\": 1000", "\"accel_cal_minus\": 2147483647, \"accel_cal_plus\": 2147483647, \"accel_cal_minus_cooked\": -1000, \"accel_cal_plus_cooked\": -1040");
2725 let raw = read(&json(HEAD_V2, &flight_v2())).unwrap();
2726 let flipped = read(&json(&cooked, &flight_v2())).unwrap();
2727 assert_eq!(
2728 values(&raw, "acceleration"),
2729 values(&flipped, "acceleration")
2730 );
2731
2732 let v1 = |plus: i64, minus: i64| {
2733 let head = HEAD_V1
2734 .replace("16000", &plus.to_string())
2735 .replace("16500", &minus.to_string());
2736 read(&json(&head, &flight_v1(24_000))).unwrap()
2738 };
2739 let upright = values(&v1(16_000, 16_500), "acceleration");
2740 let down = values(&v1(32_767 - 16_500, 32_767 - 16_000), "acceleration");
2741 assert_eq!(upright, down);
2742 assert_eq!(upright[0], 0.0);
2743 assert!((upright[3] - 5.0 * STANDARD_GRAVITY).abs() < 1e-12);
2744
2745 let mixed = cooked.replace("\"accel_cal_plus\": 2147483647", "\"accel_cal_plus\": 1000");
2748 let log = read(&json(&mixed, &flight_v2())).unwrap();
2749 assert_eq!(values(&log, "acceleration"), values(&raw, "acceleration"));
2750 assert!(has_note(
2751 &log,
2752 "`acceleration` along the board's axis, m/s², from the high-g accelerometer's counts. \
2753 It is 0 at the flight record's ground reading, 1000. A g is 20 counts, \
2754 from the calibration's +1 g and −1 g, -1040 and -1000"
2755 ));
2756 }
2757
2758 #[test]
2761 fn a_calibration_outside_sixteen_bits_keeps_the_counts_as_written() {
2762 for (plus, minus) in [
2763 (i64::MIN.to_string(), i64::MAX.to_string()),
2764 ("-40000".to_owned(), "1040".to_owned()),
2765 ("1000".to_owned(), "65536".to_owned()),
2766 ] {
2767 let head = HEAD_V2
2768 .replace(
2769 "\"accel_cal_plus\": 1000",
2770 &format!("\"accel_cal_plus\": {plus}"),
2771 )
2772 .replace(
2773 "\"accel_cal_minus\": 1040",
2774 &format!("\"accel_cal_minus\": {minus}"),
2775 );
2776 let log = read(&json(&head, &flight_v2())).unwrap();
2777 assert!(channel(&log, "acceleration").is_none(), "{plus} {minus}");
2778 assert!(has_note(
2779 &log,
2780 "`accel` kept as written: the calibration lies outside a 16-bit count's range"
2781 ));
2782 }
2783 let head = HEAD_V2
2787 .replace("\"accel_cal_plus\": 1000", "\"accel_cal_plus\": -32768")
2788 .replace("\"accel_cal_minus\": 1040", "\"accel_cal_minus\": 65535");
2789 let log = read(&json(&head, &flight_v2())).unwrap();
2790 assert!(channel(&log, "acceleration").is_none());
2791 assert!(has_note(
2792 &log,
2793 "`accel` kept as written: its climb disagrees"
2794 ));
2795 }
2796
2797 #[test]
2799 fn an_unset_calibration_keeps_the_counts_as_written() {
2800 let unset = HEAD_V2.replace("\"accel_cal_plus\": 1000", "\"accel_cal_plus\": 2147483647");
2801 let log = read(&json(&unset, &flight_v2())).unwrap();
2802 assert!(channel(&log, "acceleration").is_none());
2803 let accel = channel(&log, "accel").unwrap();
2804 assert_eq!(accel.quantity, Quantity::Unrecognized);
2805 assert_eq!(accel.values[..5], [1000.0, 1001.0, 960.0, 900.0, 1040.0]);
2806 assert!(has_note(
2807 &log,
2808 "`accel` kept as written: the calibration isn't set"
2809 ));
2810 assert!(has_note(
2813 &log,
2814 "`pressure`'s second check is the pad's alone"
2815 ));
2816 let short = &flight_v2()[..HEAD_RECORDS];
2817 assert!(read(&json(&unset, short)).is_ok());
2818 let reversed = HEAD_V2.replace("\"accel_cal_minus\": 1040", "\"accel_cal_minus\": 1000");
2819 let log = read(&json(&reversed, &flight_v2())).unwrap();
2820 assert!(has_note(
2821 &log,
2822 "`accel` kept as written: the calibration's span isn't positive"
2823 ));
2824 }
2825
2826 #[test]
2831 fn the_climb_check_integrates_from_rest_and_reads_the_standard_atmosphere() {
2832 let pad_m = altitude_of(101_325.0);
2833 let a = 5.0 * STANDARD_GRAVITY;
2834 let samples: Vec<(i64, f64, f64)> = (-30..=120)
2835 .map(|tick: i64| {
2836 let t = tick as f64 / 100.0;
2837 let (x, accel) = if tick < 0 {
2838 (0.0, 0.0)
2839 } else {
2840 (climbed_m(t), a)
2841 };
2842 (tick, pressure_at(pad_m + x).round(), accel)
2843 })
2844 .collect();
2845 let climb = climb_over_the_window(&samples).unwrap();
2846 let step = a * 0.01 / 2.0 * 1.0;
2847 assert!(
2848 (climb.by_acceleration_m - climbed_m(1.0) - step).abs() < 0.01,
2849 "{climb:?}"
2850 );
2851 assert!(
2852 (climb.by_pressure_m - climbed_m(1.0)).abs() < 0.1,
2853 "{climb:?}"
2854 );
2855 assert!((climb.ratio - 1.0).abs() < 0.02, "{climb:?}");
2856 let fault = |samples: &[(i64, f64, f64)]| climb_over_the_window(samples).unwrap_err();
2858 assert!(fault(&samples[30..]).starts_with("no sample before boost"));
2859 assert!(fault(&samples[..125]).starts_with("the samples end 0.94 s after boost"));
2860 let mut gapped = samples.clone();
2861 gapped.retain(|(tick, ..)| !(41..=51).contains(tick));
2862 assert!(
2863 fault(&gapped).starts_with("no sample for 0.12 s after the one at 0.40 s"),
2864 "{}",
2865 fault(&gapped)
2866 );
2867 let mut slow = samples.clone();
2869 slow.retain(|(tick, ..)| *tick < 0 || tick % 10 == 0);
2870 assert!(climb_over_the_window(&slow).is_ok());
2871 }
2872
2873 #[test]
2877 fn the_climb_by_the_pressure_must_agree_with_the_climb_by_the_acceleration() {
2878 let log = read(&json(HEAD_V1, &flight_v1(24_000))).unwrap();
2879 let note = log
2880 .notes
2881 .iter()
2882 .find(|n| n.starts_with("`pressure` and `acceleration` held to each other"))
2883 .unwrap();
2884 let ratio: f64 = note
2885 .split("The ratio is ")
2886 .nth(1)
2887 .and_then(|rest| rest.split(',').next())
2888 .and_then(|n| n.parse().ok())
2889 .unwrap();
2890 assert!((0.95..=1.05).contains(&ratio), "{note}");
2891 let log = read(&json(HEAD_V2, &flight_v2())).unwrap();
2892 assert!(has_note(
2893 &log,
2894 "`pressure` and `acceleration` held to each other"
2895 ));
2896
2897 let refused = |file: &str| -> String {
2899 let log = read(file).unwrap();
2900 assert!(channel(&log, "acceleration").is_none());
2901 assert!(channel(&log, "accel").is_some());
2902 log.notes
2903 .iter()
2904 .find(|n| n.starts_with("over the first second after boost"))
2905 .cloned()
2906 .unwrap_or_else(|| panic!("{:?}", log.notes))
2907 };
2908 let swapped: Vec<Vec<u8>> = flight_v1(24_000)
2911 .into_iter()
2912 .map(|mut bytes| {
2913 if bytes[0] == b'A' {
2914 let (accel, pressure) = ([bytes[4], bytes[5]], [bytes[6], bytes[7]]);
2915 bytes[4..6].copy_from_slice(&pressure);
2916 bytes[6..8].copy_from_slice(&accel);
2917 }
2918 bytes
2919 })
2920 .collect();
2921 let message = refused(&json(HEAD_V1, &swapped));
2922 assert!(
2923 message.contains("by the acceleration. The ratio is")
2924 && message.ends_with("which has no other check, too"),
2925 "{message}"
2926 );
2927 let log = read(&json(HEAD_V1, &swapped)).unwrap();
2928 assert!(channel(&log, "pressure").is_none() && channel(&log, "pres").is_some());
2929 for (minus, ratio) in [(1010, 0.25), (1020, 0.5), (1080, 2.0), (1160, 4.0)] {
2932 let head = HEAD_V2.replace("1040", &minus.to_string());
2933 let message = refused(&json(&head, &flight_v2()));
2934 let read_ratio: f64 = message
2935 .split("The ratio is ")
2936 .nth(1)
2937 .and_then(|rest| rest.split(',').next())
2938 .and_then(|n| n.parse().ok())
2939 .unwrap();
2940 assert!(
2941 (read_ratio / ratio - 1.0).abs() < 0.15,
2942 "{minus}: {message}"
2943 );
2944 assert!(message.contains("outside 0.6 to 5/3"), "{message}");
2945 }
2946 let flipped: Vec<Vec<u8>> = flight_v2()
2949 .into_iter()
2950 .map(|bytes| {
2951 if bytes[0] == b'A' {
2952 let count = i16::from_le_bytes([bytes[12], bytes[13]]);
2953 let d1 = u32::from_le_bytes([bytes[4], bytes[5], bytes[6], bytes[7]]);
2954 a7(
2955 u16::from_le_bytes([bytes[2], bytes[3]]),
2956 d1,
2957 EXAMPLE_D2,
2958 2000 - count,
2959 )
2960 } else {
2961 bytes
2962 }
2963 })
2964 .collect();
2965 let message = refused(&json(HEAD_V2, &flipped));
2966 assert!(message.contains(" m by the pressure and -"), "{message}");
2967 let both: Vec<Vec<u8>> = flipped
2970 .into_iter()
2971 .map(|bytes| {
2972 if bytes[0] == b'A' {
2973 let count = i16::from_le_bytes([bytes[12], bytes[13]]);
2974 let d1 = u32::from_le_bytes([bytes[4], bytes[5], bytes[6], bytes[7]]);
2975 let tick = u16::from_le_bytes([bytes[2], bytes[3]]);
2976 a7(tick, 2 * EXAMPLE_D1 - d1, EXAMPLE_D2, count)
2977 } else {
2978 bytes
2979 }
2980 })
2981 .collect();
2982 let message = refused(&json(HEAD_V2, &both));
2983 assert!(message.contains("m by the pressure and -"), "{message}");
2984 assert!(
2985 message.contains("by the acceleration. The ratio is 1."),
2986 "{message}"
2987 );
2988
2989 let short = &flight_v2()[..HEAD_RECORDS];
2991 let log = read(&json(HEAD_V2, short)).unwrap();
2992 assert!(channel(&log, "acceleration").is_none() && channel(&log, "accel").is_some());
2993 assert!(
2994 has_note(
2995 &log,
2996 "the climb over the first second after boost can't be measured (the samples end \
2997 0.02 s"
2998 ),
2999 "{:?}",
3000 log.notes
3001 );
3002 }
3003
3004 #[test]
3006 fn the_pads_temperature_is_held_to_the_barometers_operating_range() {
3007 let pad = |d2: u32| {
3010 let (mut low, mut high) = (0u32, 16_000_000u32);
3012 while high - low > 1 {
3013 let mid = low + (high - low) / 2;
3014 if ms5607(mid, d2, &EXAMPLE_PROM).0 < 100_000 {
3015 low = mid;
3016 } else {
3017 high = mid;
3018 }
3019 }
3020 let (pa, centi) = ms5607(high, d2, &EXAMPLE_PROM);
3021 let records = [
3022 f7(200, 3, 1000, u32::try_from(pa).unwrap()),
3023 a7(198, high, d2, 1000),
3024 a7(199, high, d2, 1000),
3025 ];
3026 (centi, read(&json(HEAD_V2, &records)))
3027 };
3028 let (hot, refused) = pad(EXAMPLE_D2 + 1_940_000);
3029 assert!(hot > 8_500, "{hot}");
3030 match refused {
3031 Err(LogError::Binary { message, .. }) => assert!(
3032 message.contains("outside the MS5607's operating range, −40 to 85 °C"),
3033 "{message}"
3034 ),
3035 other => panic!("{other:?}"),
3036 }
3037 let (warm, read_warm) = pad(EXAMPLE_D2 + 1_930_000);
3040 assert!((8_000..=8_500).contains(&warm), "{warm}");
3041 let log = read_warm.unwrap();
3042 assert!(channel(&log, "acceleration").is_none());
3043 assert!(has_note(
3044 &log,
3045 "the climb over the first second after boost can't be measured"
3046 ));
3047 let log = read(&json(HEAD_V2, &flight_v2())).unwrap();
3048 assert!(has_note(
3049 &log,
3050 "`temperature` on the pad, 20.0 °C, within the MS5607's operating range"
3051 ));
3052 }
3053
3054 #[test]
3057 fn the_pad_orientation_is_stated_and_quoted_text_is_cut() {
3058 let head = HEAD_V2.replace("\"main_deploy\"", "\"pad_orientation\": 1, \"main_deploy\"");
3059 let log = read(&json(&head, &flight_v2())).unwrap();
3060 let figure = |log: &FlightLog| {
3061 log.stated
3062 .figures
3063 .iter()
3064 .find(|f| f.name == "pad_orientation")
3065 .map(|f| (f.written.clone(), f.quantity, f.values.clone()))
3066 };
3067 assert_eq!(
3068 figure(&log),
3069 Some(("1".to_owned(), Some(Quantity::Number), vec![1.0]))
3070 );
3071 let mut lines = TEXT_HEAD_V2.to_vec();
3072 lines.insert(5, "Pad orientation: 0");
3073 let log = read(&text(&lines, &flight_v2())).unwrap();
3074 assert_eq!(
3075 figure(&log),
3076 Some(("0".to_owned(), Some(Quantity::Number), vec![0.0]))
3077 );
3078
3079 let long = "X".repeat(200);
3080 let unstated = HEAD_V2
3081 .replace("\"log_format\": 7,", "\"log_format\": 2147483647,")
3082 .replace("TeleMetrum-v2.0", &long);
3083 match read(&json(&unstated, &flight_v2())) {
3084 Err(LogError::Syntax { message, .. }) => {
3085 assert!(
3086 message.contains(&format!("\"{}\"", "X".repeat(80))),
3087 "{message}"
3088 );
3089 assert!(!message.contains(&"X".repeat(81)), "{message}");
3090 }
3091 other => panic!("{other:?}"),
3092 }
3093 let mut lines = TEXT_HEAD_V2.to_vec();
3094 let twice = format!("product {long}");
3095 lines.push(&twice);
3096 match read(&text(&lines, &flight_v2())) {
3097 Err(LogError::Syntax { message, .. }) => {
3098 assert!(!message.contains(&"X".repeat(81)), "{message}")
3099 }
3100 other => panic!("{other:?}"),
3101 }
3102 }
3103
3104 #[test]
3106 fn without_the_barometers_constants_its_counts_are_kept() {
3107 let ms5611 = HEAD_V2.replace("\"ms5611\": false", "\"ms5611\": true");
3108 let log = read(&json(&ms5611, &flight_v2())).unwrap();
3109 assert!(channel(&log, "pressure").is_none());
3110 assert_eq!(values(&log, "d1")[0], f64::from(EXAMPLE_D1));
3111 assert!(has_note(
3112 &log,
3113 "`d1` and `d2` kept as written: the configuration marks the barometer an MS5611"
3114 ));
3115 assert!(channel(&log, "acceleration").is_none());
3117 assert!(has_note(
3118 &log,
3119 "`accel` kept as written: no pressure in pascals to hold it to"
3120 ));
3121 let no_tref = HEAD_V2.replace("\"tref\": 31553", "\"tref\": 70000");
3122 let log = read(&json(&no_tref, &flight_v2())).unwrap();
3123 assert!(has_note(
3124 &log,
3125 "`d1` and `d2` kept as written: the configuration holds no MS5607 constants"
3126 ));
3127 }
3128
3129 fn flight_mega(product: &str, format: u32, imu: i16) -> Result<FlightLog, LogError> {
3134 let head = HEAD_V2
3135 .replace("\"log_format\": 7", &format!("\"log_format\": {format}"))
3136 .replace("TeleMetrum-v2.0", product);
3137 let mut flight = 3u16.to_le_bytes().to_vec();
3138 flight.extend(1000i16.to_le_bytes());
3139 flight.extend(110_002u32.to_le_bytes());
3140 flight.extend([imu, 0, 0].iter().flat_map(|v| v.to_le_bytes()));
3141 let sample = |d1: u32, accel: i16| {
3142 let mut fields = d1.to_le_bytes().to_vec();
3143 fields.extend(EXAMPLE_D2.to_le_bytes());
3144 fields.extend((1..=9i16).flat_map(|v| v.to_le_bytes()));
3145 fields.extend(accel.to_le_bytes());
3146 fields
3147 };
3148 let mut sense = 2000i16.to_le_bytes().to_vec();
3149 sense.extend(4095i16.to_le_bytes());
3150 sense.extend(6i16.to_le_bytes());
3151 sense.extend(
3152 [0i16, 4095, 0, 0, 1000, 0]
3153 .iter()
3154 .flat_map(|v| v.to_le_bytes()),
3155 );
3156 let mut records = vec![
3157 record(32, b'F', 100, &flight),
3158 record(32, b'A', 99, &sample(EXAMPLE_D1, 980)),
3159 record(32, b'A', 100, &sample(EXAMPLE_D1, 1000)),
3160 record(32, b'T', 101, &sense),
3161 ];
3162 let pad_m = altitude_of(110_002.0);
3163 for k in 1..=11u16 {
3164 let pa = pressure_at(pad_m + climbed_m(f64::from(k) / 10.0));
3165 records.push(record(32, b'A', 100 + 10 * k, &sample(d1_for(pa), 900)));
3166 }
3167 read(&json(&head, &records))
3168 }
3169
3170 #[test]
3173 fn a_megas_imu_is_read_only_where_its_layout_is_confirmed() {
3174 let log = flight_mega("TeleMega-v6.0", 16, 5).unwrap();
3175 assert_eq!(values(&log, "imu_gyro_0")[0], 4.0);
3176 assert_eq!(
3177 channel(&log, "imu_mag_2").unwrap().quantity,
3178 Quantity::Unrecognized
3179 );
3180 assert!((values(&log, "acceleration")[0] - STANDARD_GRAVITY).abs() < 1e-12);
3181 let full = 3.3 * 127.0 / 27.0;
3183 assert!((values(&log, "pyro")[0] - full).abs() < 1e-12);
3184 assert!((values(&log, "igniter_b")[0] - full).abs() < 1e-12);
3185 assert_eq!(channel(&log, "pyro").unwrap().quantity, Quantity::Voltage);
3186 assert_eq!(values(&log, "v_batt"), [2000.0]);
3187 assert!(values(&log, "drogue_voltage")[0] > 0.0);
3188 let log = flight_mega("TeleMega-v4.0", 15, 5).unwrap();
3189 assert!(channel(&log, "imu_accel_0").is_none());
3190 assert!(has_note(
3191 &log,
3192 "the IMU not read: format 15's layout of it is unconfirmed"
3193 ));
3194 let log = flight_mega("TeleMega-v6.0", 22, 0).unwrap();
3195 assert!(channel(&log, "imu_accel_0").is_none());
3196 assert!(has_note(
3197 &log,
3198 "the IMU not read: the flight record's IMU fields are all zero"
3199 ));
3200 }
3201
3202 #[test]
3205 fn a_megas_senses_are_volts_only_for_the_15_v_products() {
3206 for product in MEGA_15_V_PRODUCTS {
3207 let log = flight_mega(product, 22, 5).unwrap();
3208 assert_eq!(channel(&log, "pyro").unwrap().quantity, Quantity::Voltage);
3209 }
3210 let log = flight_mega("TeleMega-v7.0", 22, 5).unwrap();
3211 for name in [
3212 "pyro",
3213 "igniter_a",
3214 "igniter_d",
3215 "drogue_voltage",
3216 "main_voltage",
3217 ] {
3218 assert_eq!(
3219 channel(&log, name).unwrap().quantity,
3220 Quantity::Unrecognized,
3221 "{name}"
3222 );
3223 }
3224 assert_eq!(values(&log, "pyro"), [4095.0]);
3225 assert_eq!(values(&log, "drogue_voltage"), [1000.0]);
3226 assert!(has_note(
3227 &log,
3228 "`pyro`, the igniters' and the apogee and main senses kept as written. The product, \
3229 TeleMega-v7.0, isn't one"
3230 ));
3231 }
3232
3233 #[test]
3236 fn gps_positions_need_a_valid_fix() {
3237 let position = |tick: u16, lat: i32, lon: i32, low: u16, high: i16| {
3238 let mut fields = lat.to_le_bytes().to_vec();
3239 fields.extend(lon.to_le_bytes());
3240 fields.extend(low.to_le_bytes());
3241 fields.extend(high.to_le_bytes());
3242 record(16, b'P', tick, &fields)
3243 };
3244 let mut records = flight_v2();
3245 records.extend([
3246 position(150, 450_000_000, -1_220_000_000, 4_464, 1),
3247 record(16, b'G', 150, &[12, 0, 1, 0x10 | 6, 26, 10, 14, 40]),
3248 position(180, 450_000_000, -1_220_000_000, 1_000, 0),
3249 record(16, b'G', 180, &[12, 0, 1, 0x20 | 3, 26, 10, 14, 40]),
3250 ]);
3251 let log = read(&json(HEAD_V2, &records)).unwrap();
3252 let latitude = values(&log, "latitude");
3253 assert_eq!(latitude[0], 45.0);
3254 assert!(latitude[1].is_nan());
3255 assert_eq!(values(&log, "longitude")[0], -122.0);
3256 assert_eq!(values(&log, "gps_altitude")[0], 70_000.0);
3257 assert_eq!(values(&log, "nsat"), [6.0, 3.0]);
3258 assert!(has_note(&log, "1 GPS position records without a valid fix"));
3259 }
3260
3261 #[test]
3263 fn states_are_named_and_others_numbered() {
3264 let mut records = flight_v2();
3265 records.extend([s(16, 203, 5), s(16, 204, 5), s(16, 205, 9)]);
3266 let log = read(&json(HEAD_V2, &records)).unwrap();
3267 let names: Vec<&str> = log.events.iter().map(|e| e.name.as_str()).collect();
3268 assert_eq!(names, ["boost", "coast", "state 9"]);
3269 }
3270
3271 #[test]
3273 fn a_configuration_printed_twice_must_agree() {
3274 let mut head: Vec<&str> = TEXT_HEAD_V2.to_vec();
3275 head.extend(TEXT_HEAD_V2);
3276 assert!(read(&text(&head, &flight_v2())).is_ok());
3277 head.push("serial-number 4321");
3278 match read(&text(&head, &flight_v2())) {
3279 Err(LogError::Syntax { line, message, .. }) => {
3280 assert_eq!(line, head.len());
3281 assert!(
3282 message.contains("its serial number here, \"4321\", differs from line 16's"),
3283 "{message}"
3284 );
3285 }
3286 other => panic!("{other:?}"),
3287 }
3288 }
3289
3290 #[test]
3292 fn an_unknown_record_type_is_counted() {
3293 let mut records = flight_v2();
3294 records.push(record(16, b'Z', 203, &[1, 2, 3]));
3295 let log = read(&json(HEAD_V2, &records)).unwrap();
3296 assert!(has_note(&log, "1 records of type `Z` not read"));
3297 }
3298}