1use std::collections::BTreeMap;
110
111use crate::error::LogError;
112use crate::log::{Channel, Event, FlightLog, LogFormat, Quantity, Stated};
113
114const FORMAT: &str = "AltOS telemetry";
116
117const PREFIX: &str = "TELEM";
119
120const LENGTH: u8 = 34;
122
123const LINE_BYTES: usize = LENGTH as usize + 2;
125
126const CHECKSUM_BASE: u8 = 0x5a;
128
129const CRC_OK: u8 = 0x80;
131
132const TURN: i64 = 1 << 16;
134
135const TICKS_PER_S: f64 = 100.0;
138
139const PAD_PRESSURE_PA: std::ops::RangeInclusive<f64> = 10_000.0..=120_000.0;
141
142pub(crate) const STATES: [(u8, &str); 7] = [
144 (2, "pad"),
145 (3, "boost"),
146 (4, "fast"),
147 (5, "coast"),
148 (6, "drogue"),
149 (7, "main"),
150 (8, "landed"),
151];
152
153const PAD: u8 = 2;
155
156const FLOWN: std::ops::RangeInclusive<u8> = 3..=7;
160
161const QUOTED_CONFIGURATIONS: usize = 8;
163
164const SENSOR: u8 = 0x0a;
166const CALIBRATION: u8 = 0x0b;
167const CONFIGURATION: u8 = 0x04;
168const LOCATION: u8 = 0x05;
169const SATELLITES: u8 = 0x06;
170
171const SVID: [&str; 12] = [
173 "svid_01", "svid_02", "svid_03", "svid_04", "svid_05", "svid_06", "svid_07", "svid_08",
174 "svid_09", "svid_10", "svid_11", "svid_12",
175];
176const C_N: [&str; 12] = [
177 "c_n_01", "c_n_02", "c_n_03", "c_n_04", "c_n_05", "c_n_06", "c_n_07", "c_n_08", "c_n_09",
178 "c_n_10", "c_n_11", "c_n_12",
179];
180
181const NOT_READ: [(u8, &str); 11] = [
183 (0x01, "TeleMetrum v1 sensors"),
184 (0x02, "TeleMini v1 sensors"),
185 (0x03, "TeleNano sensors"),
186 (0x07, "companion"),
187 (0x08, "TeleMega sensors"),
188 (0x09, "TeleMega data"),
189 (0x11, "TeleMini v3 sensors"),
190 (0x12, "TeleMega sensors (BMX160)"),
191 (0x13, "TeleMega sensors (MPU6000 and MMC5983)"),
192 (0x14, "TeleMega sensors (BMI088 and MMC5983)"),
193 (0x15, "TeleMega data (30 V)"),
194];
195
196pub fn recognizes(text: &str) -> bool {
199 text.lines()
200 .map(str::trim)
201 .find(|line| !line.is_empty())
202 .and_then(hex_of)
203 .is_some()
204}
205
206fn hex_of(line: &str) -> Option<&str> {
208 let rest = line.strip_prefix(PREFIX)?;
209 let digits = rest.trim_start();
210 (digits.len() < rest.len()
211 && !digits.is_empty()
212 && digits.len() % 2 == 0
213 && digits.bytes().all(|b| b.is_ascii_hexdigit()))
214 .then_some(digits)
215}
216
217struct Packet {
219 line: usize,
220 tick: u16,
221 kind: u8,
222 bytes: [u8; 32],
223 rssi_dbm: f64,
224 lqi: u8,
225}
226
227impl Packet {
228 fn u8(&self, at: usize) -> f64 {
229 f64::from(self.bytes[at])
230 }
231 fn i16(&self, at: usize) -> f64 {
232 f64::from(i16::from_le_bytes([self.bytes[at], self.bytes[at + 1]]))
233 }
234 fn u16(&self, at: usize) -> u16 {
235 u16::from_le_bytes([self.bytes[at], self.bytes[at + 1]])
236 }
237 fn i32(&self, at: usize) -> f64 {
238 f64::from(i32::from_le_bytes([
239 self.bytes[at],
240 self.bytes[at + 1],
241 self.bytes[at + 2],
242 self.bytes[at + 3],
243 ]))
244 }
245 fn text(&self, at: usize, len: usize) -> String {
247 self.bytes[at..at + len]
248 .iter()
249 .take_while(|b| **b != 0)
250 .map(|b| {
251 if b.is_ascii_graphic() || *b == b' ' {
252 char::from(*b)
253 } else {
254 '?'
255 }
256 })
257 .collect::<String>()
258 .trim()
259 .to_owned()
260 }
261}
262
263#[derive(Default)]
265struct Channels {
266 order: Vec<(String, Quantity)>,
267 data: BTreeMap<String, (Vec<f64>, Vec<f64>)>,
268}
269
270impl Channels {
271 fn push(&mut self, name: &str, quantity: Quantity, time_s: f64, value: f64) {
272 if let Some((times, values)) = self.data.get_mut(name) {
274 times.push(time_s);
275 values.push(value);
276 return;
277 }
278 self.order.push((name.to_owned(), quantity));
279 self.data
280 .insert(name.to_owned(), (vec![time_s], vec![value]));
281 }
282
283 fn values(&self, name: &str) -> Option<&[f64]> {
284 self.data.get(name).map(|(_, values)| values.as_slice())
285 }
286
287 fn into_channels(mut self) -> Vec<Channel> {
288 self.order
289 .into_iter()
290 .filter_map(|(column, quantity)| {
291 let (time_s, values) = self.data.remove(&column)?;
292 Some(Channel {
293 column,
294 quantity,
295 time_s,
296 values,
297 })
298 })
299 .collect()
300 }
301}
302
303pub fn read(text: &str) -> Result<FlightLog, LogError> {
305 if !recognizes(text) {
306 return Err(LogError::NotThisFormat {
307 format: FORMAT,
308 message: format!(
309 "the first line that isn't blank isn't `{PREFIX}` and a packet in hexadecimal"
310 ),
311 });
312 }
313 let (all, crc_failed) = packets(text)?;
314 let Some(first) = all.first() else {
315 return Err(LogError::NoData { format: FORMAT });
316 };
317 let serial = first.u16(0);
318 if let Some(other) = all.iter().find(|packet| packet.u16(0) != serial) {
319 return Err(syntax(
320 other.line,
321 format!(
322 "a packet from serial number {}, where the file's first is from {serial}: two \
323 boards' telemetry in one file",
324 other.u16(0)
325 ),
326 ));
327 }
328
329 let mut starts = vec![0usize];
331 let mut last: BTreeMap<u8, u16> = BTreeMap::new();
332 for (index, packet) in all.iter().enumerate() {
333 if let Some(previous) = last.get(&packet.kind)
334 && step(*previous, packet.tick) < 0
335 {
336 starts.push(index);
337 last.clear();
338 }
339 last.insert(packet.kind, packet.tick);
340 }
341 let session = |k: usize| &all[starts[k]..starts.get(k + 1).copied().unwrap_or(all.len())];
342 let flown: Vec<usize> = (0..starts.len())
343 .filter(|&k| {
344 session(k)
345 .iter()
346 .any(|packet| packet.kind == SENSOR && FLOWN.contains(&packet.bytes[5]))
347 })
348 .collect();
349 let chosen = match flown.as_slice() {
350 [] => starts.len() - 1,
351 [only] => *only,
352 [first, second, ..] => {
353 return Err(syntax(
354 session(*second)[0].line,
355 format!(
356 "the board left the pad in two power-ons, from line {} and from this one: \
357 which is the flight is unclear",
358 session(*first)[0].line
359 ),
360 ));
361 }
362 };
363 let packets = session(chosen);
364
365 let mut latest: Option<i64> = None;
367 let times: Vec<f64> = packets
368 .iter()
369 .map(|packet| {
370 #[allow(
371 clippy::cast_possible_truncation,
372 reason = "a remainder of a 65,536-tick turn, so the cast is exact"
373 )]
374 let unwound = match latest {
375 None => i64::from(packet.tick),
376 Some(latest) => {
377 latest + i64::from(step(latest.rem_euclid(TURN) as u16, packet.tick))
378 }
379 };
380 latest = Some(latest.map_or(unwound, |latest| latest.max(unwound)));
381 unwound as f64 / TICKS_PER_S
382 })
383 .collect();
384
385 let pressure_in_pa = pad_pressure(packets).is_some_and(|pa| PAD_PRESSURE_PA.contains(&pa));
386 let pressure = |name: &'static str, raw: &'static str| {
387 if pressure_in_pa {
388 (name, Quantity::Pressure)
389 } else {
390 (raw, Quantity::Unrecognized)
391 }
392 };
393
394 let mut channels = Channels::default();
395 let mut events: Vec<Event> = Vec::new();
396 let mut state: Option<u8> = None;
397 let mut track_time: Vec<f64> = Vec::new();
398 let mut track_height: Vec<f64> = Vec::new();
399 let mut track_temperature: Vec<f64> = Vec::new();
400 let mut repeated_sensor_ticks = 0usize;
401 let mut not_read: BTreeMap<u8, usize> = BTreeMap::new();
402 let mut configurations: Vec<String> = Vec::new();
403 let mut more_configurations = 0usize;
404 let mut flight_number: Option<u16> = None;
405 let mut flight_numbers_differ = false;
406 let mut firmware: Option<String> = None;
407 let mut firmware_differs = false;
408 let mut no_fix = 0usize;
409 for (packet, &time) in packets.iter().zip(×) {
410 let read = matches!(
411 packet.kind,
412 SENSOR | CALIBRATION | CONFIGURATION | LOCATION | SATELLITES
413 );
414 if !read {
415 *not_read.entry(packet.kind).or_default() += 1;
416 continue;
417 }
418 channels.push("rssi", Quantity::Number, time, packet.rssi_dbm);
419 channels.push("lqi", Quantity::Number, time, f64::from(packet.lqi));
420 match packet.kind {
421 SENSOR => {
422 let now = packet.bytes[5];
423 if state != Some(now) {
424 events.push(Event {
425 time_s: time,
426 name: state_name(now),
427 });
428 state = Some(now);
429 }
430 channels.push("state", Quantity::Number, time, f64::from(now));
431 channels.push("accel", Quantity::Unrecognized, time, packet.i16(6));
432 let (name, quantity) = pressure("pressure", "pres");
433 channels.push(name, quantity, time, packet.i32(8));
434 let kelvin = packet.i16(12) / 100.0 + 273.15;
435 channels.push("temperature", Quantity::Temperature, time, kelvin);
436 let acceleration = packet.i16(14) / 16.0;
437 channels.push("acceleration", Quantity::Acceleration, time, acceleration);
438 channels.push("speed", Quantity::Speed, time, packet.i16(16) / 16.0);
439 let height = packet.i16(18);
440 channels.push("height", Quantity::AltitudeAboveGround, time, height);
441 channels.push("v_batt", Quantity::Unrecognized, time, packet.i16(20));
442 channels.push("sense_d", Quantity::Unrecognized, time, packet.i16(22));
443 channels.push("sense_m", Quantity::Unrecognized, time, packet.i16(24));
444 if track_time.last().is_some_and(|last| time <= *last) {
445 repeated_sensor_ticks += 1;
446 } else {
447 track_time.push(time);
448 track_height.push(height);
449 track_temperature.push(kelvin);
450 }
451 }
452 CALIBRATION => {
453 let (name, quantity) = pressure("ground_pressure", "ground_pres");
454 channels.push(name, quantity, time, packet.i32(8));
455 channels.push("ground_accel", Quantity::Unrecognized, time, packet.i16(12));
456 channels.push("accel_plus_g", Quantity::Unrecognized, time, packet.i16(14));
457 channels.push(
458 "accel_minus_g",
459 Quantity::Unrecognized,
460 time,
461 packet.i16(16),
462 );
463 }
464 CONFIGURATION => {
465 let flight = packet.u16(6);
466 if flight_number.is_some_and(|number| number != flight) {
467 flight_numbers_differ = true;
468 }
469 flight_number.get_or_insert(flight);
470 let version = packet.text(24, 8);
471 if !version.is_empty() {
472 if firmware.as_ref().is_some_and(|first| *first != version) {
473 firmware_differs = true;
474 }
475 firmware.get_or_insert_with(|| version.clone());
476 }
477 let configuration = format!(
478 "device type {}, flight {flight}, configuration {}.{}, apogee delay {} s, \
479 main at {} m, log of {} kB, call sign {:?}, firmware {:?}",
480 packet.bytes[5],
481 packet.bytes[8],
482 packet.bytes[9],
483 packet.u16(10),
484 packet.u16(12),
485 packet.u16(14),
486 packet.text(16, 8),
487 version
488 );
489 if !configurations.contains(&configuration) {
490 if configurations.len() < QUOTED_CONFIGURATIONS {
491 configurations.push(configuration);
492 } else {
493 more_configurations += 1;
494 }
495 }
496 }
497 LOCATION => {
498 let flags = packet.bytes[5];
499 channels.push("nsat", Quantity::Number, time, f64::from(flags & 0x0f));
500 channels.push("gps_flags", Quantity::Number, time, f64::from(flags));
501 let valid = flags & 0x10 != 0;
502 if !valid {
503 no_fix += 1;
504 }
505 let fix = |value: f64| if valid { value } else { f64::NAN };
506 channels.push(
507 "latitude",
508 Quantity::Latitude,
509 time,
510 fix(packet.i32(8) / 1e7),
511 );
512 channels.push(
513 "longitude",
514 Quantity::Longitude,
515 time,
516 fix(packet.i32(12) / 1e7),
517 );
518 channels.push(
519 "gps_altitude",
520 Quantity::GnssAltitude,
521 time,
522 fix(packet.i16(6)),
523 );
524 for (k, name) in ["year", "month", "day", "hour", "minute", "second"]
525 .into_iter()
526 .enumerate()
527 {
528 channels.push(name, Quantity::Number, time, packet.u8(16 + k));
529 }
530 for (k, name) in ["pdop", "hdop", "vdop", "mode"].into_iter().enumerate() {
531 channels.push(name, Quantity::Number, time, packet.u8(22 + k));
532 }
533 let ground_speed = f64::from(packet.u16(26));
534 channels.push("ground_speed", Quantity::Unrecognized, time, ground_speed);
535 channels.push("climb_rate", Quantity::Unrecognized, time, packet.i16(28));
536 channels.push("course", Quantity::Unrecognized, time, packet.u8(30));
537 }
538 SATELLITES => {
539 channels.push("sat_channels", Quantity::Number, time, packet.u8(5));
540 for (k, (svid, c_n)) in SVID.iter().zip(C_N).enumerate() {
541 channels.push(svid, Quantity::Number, time, packet.u8(6 + 2 * k));
542 channels.push(c_n, Quantity::Number, time, packet.u8(7 + 2 * k));
543 }
544 }
545 _ => {}
546 }
547 }
548 if channels.data.is_empty() {
549 return Err(LogError::NoData { format: FORMAT });
550 }
551
552 let mut notes = Vec::new();
553 notes.push(format!(
554 "{} packets heard: {crc_failed} failed the radio's CRC and are left out",
555 all.len() + crc_failed
556 ));
557 if starts.len() > 1 {
558 let others: usize = (0..starts.len())
559 .filter(|&k| k != chosen)
560 .map(|k| session(k).len())
561 .sum();
562 notes.push(format!(
563 "the board's tick starts again {} times, a power-on each. The record holds power-on \
564 {} of {} ({}), and {others} packets of the others are left out",
565 starts.len() - 1,
566 chosen + 1,
567 starts.len(),
568 if flown.is_empty() {
569 "the last, as none leaves the pad"
570 } else {
571 "the one that leaves the pad"
572 }
573 ));
574 }
575 notes.push(format!(
576 "the clock is the board's tick, 10 ms, from the turn of the first packet heard. Each \
577 tick is on the turn nearest the latest so far. The clock's first packet is at {:.2} s",
578 times[0]
579 ));
580 match pad_pressure(packets) {
581 Some(pa) if pressure_in_pa => notes.push(format!(
582 "`pres` read in pascals, not the document's tenths of a pascal: the pad's pressure, \
583 {pa:.0}, lies between 10 and 120 kPa read so"
584 )),
585 Some(pa) => notes.push(format!(
586 "`pres` kept as written. The pad's pressure, {pa:.0}, is no launch site's \
587 pressure in pascals. The files read contradict the document's tenths of a pascal"
588 )),
589 None => {}
590 }
591 if channels.values("accel").is_some() {
592 notes.push(
593 "`accel`, `v_batt`, `sense_d` and `sense_m` kept as written: the converters' counts, \
594 which the document gives no conversion for"
595 .to_owned(),
596 );
597 notes.push(
598 "`acceleration`, `speed` and `height` are the board's own estimates, read in the \
599 document's units. The units are sixteenths of a m/s² and of a m/s, and meters above \
600 the pad"
601 .to_owned(),
602 );
603 }
604 if channels.values("ground_accel").is_some() {
605 notes.push(
606 "`ground_accel`, `accel_plus_g` and `accel_minus_g` kept as written: counts".to_owned(),
607 );
608 }
609 if channels.values("nsat").is_some() {
610 notes.push(
611 "GPS: `pdop`, `hdop` and `vdop` kept as written, five times the dilution in the \
612 document. The date and time are as written, the year two digits. `ground_speed`, \
613 `climb_rate` and `course` kept as written, their units unchecked"
614 .to_owned(),
615 );
616 }
617 if no_fix > 0 {
618 notes.push(format!(
619 "{no_fix} GPS packets with the flags' valid bit clear: their position and altitude \
620 read as gaps"
621 ));
622 }
623 if repeated_sensor_ticks > 0 {
624 notes.push(format!(
625 "{repeated_sensor_ticks} sensor packets at a tick no later than the one before: kept \
626 as channels, left off the primary track"
627 ));
628 }
629 if !configurations.is_empty() {
630 let mut quoted = configurations.join(" | ");
631 if more_configurations > 0 {
632 quoted.push_str(&format!(" | and {more_configurations} more"));
633 }
634 notes.push(format!("the configuration, as sent: {quoted}"));
635 }
636 if flight_numbers_differ {
637 notes.push(
638 "the configuration packets name more than one flight number: the record's is the \
639 first"
640 .to_owned(),
641 );
642 }
643 if firmware_differs {
644 notes.push(
645 "the configuration packets name more than one firmware version: the record's is the \
646 first"
647 .to_owned(),
648 );
649 }
650 for (kind, count) in ¬_read {
651 notes.push(match NOT_READ.iter().find(|(known, _)| known == kind) {
652 Some((_, name)) => format!(
653 "{count} packets of type 0x{kind:02X} ({name}) not read: no sample file holds \
654 one to check the document against"
655 ),
656 None => format!(
657 "{count} packets of type 0x{kind:02X} not read: a type the document doesn't lay \
658 out"
659 ),
660 });
661 }
662
663 let has_sensors = !track_time.is_empty();
664 Ok(FlightLog {
665 format: LogFormat::AltosTelemetry,
666 logger: if has_sensors {
667 "AltOS TeleMetrum v2 or newer".to_owned()
668 } else {
669 "AltOS".to_owned()
670 },
671 serial_number: Some(serial.to_string()),
672 firmware,
673 flight_number: flight_number.map(u32::from),
674 stated: Stated::default(),
675 time_s: track_time,
676 altitude_m: track_height,
677 vertical_speed_m_s: None,
678 temperature_k: has_sensors.then_some(track_temperature),
679 battery_v: None,
680 channels: channels.into_channels(),
681 events,
682 notes,
683 })
684}
685
686fn packets(text: &str) -> Result<(Vec<Packet>, usize), LogError> {
689 let mut packets = Vec::new();
690 let mut crc_failed = 0;
691 for (index, line) in text.lines().enumerate() {
692 let number = index + 1;
693 let line = line.trim();
694 if line.is_empty() {
695 continue;
696 }
697 let digits = hex_of(line).ok_or_else(|| {
698 syntax(
699 number,
700 format!(
701 "a line that isn't `{PREFIX}` and a packet in hexadecimal: {:?}",
702 cut(line)
703 ),
704 )
705 })?;
706 if digits.len() != 2 * LINE_BYTES {
707 return Err(syntax(
708 number,
709 format!(
710 "a line of {} bytes, where a TeleDongle's line is {LINE_BYTES}",
711 digits.len() / 2
712 ),
713 ));
714 }
715 let mut bytes = [0u8; LINE_BYTES];
716 for (k, byte) in bytes.iter_mut().enumerate() {
717 *byte = u8::from_str_radix(&digits[2 * k..2 * k + 2], 16).unwrap_or(0);
719 }
720 if bytes[0] != LENGTH {
721 return Err(syntax(
722 number,
723 format!(
724 "a length byte of {}, where a TeleDongle's line holds {LENGTH}: a 32-byte \
725 packet and the radio's two bytes",
726 bytes[0]
727 ),
728 ));
729 }
730 let sum = bytes[1..LINE_BYTES - 1]
731 .iter()
732 .fold(CHECKSUM_BASE, |sum, byte| sum.wrapping_add(*byte));
733 if sum != bytes[LINE_BYTES - 1] {
734 return Err(syntax(
735 number,
736 format!(
737 "the checksum is 0x{:02X} where the line's bytes sum to 0x{sum:02X}: the line \
738 is damaged",
739 bytes[LINE_BYTES - 1]
740 ),
741 ));
742 }
743 let lqi_byte = bytes[34];
744 if lqi_byte & CRC_OK == 0 {
745 crc_failed += 1;
746 continue;
747 }
748 let mut packet = [0u8; 32];
749 packet.copy_from_slice(&bytes[1..33]);
750 packets.push(Packet {
751 line: number,
752 tick: u16::from_le_bytes([packet[2], packet[3]]),
753 kind: packet[4],
754 bytes: packet,
755 rssi_dbm: f64::from(i8::from_le_bytes([bytes[33]])) / 2.0 - 74.0,
756 lqi: lqi_byte & !CRC_OK,
757 });
758 }
759 Ok((packets, crc_failed))
760}
761
762fn step(from: u16, to: u16) -> i16 {
764 to.wrapping_sub(from) as i16
765}
766
767fn pad_pressure(packets: &[Packet]) -> Option<f64> {
770 let sensors = || packets.iter().filter(|packet| packet.kind == SENSOR);
771 let mut pad: Vec<f64> = sensors()
772 .filter(|packet| packet.bytes[5] == PAD)
773 .map(|packet| packet.i32(8))
774 .collect();
775 if pad.is_empty() {
776 return sensors().next().map(|packet| packet.i32(8));
777 }
778 pad.sort_by(f64::total_cmp);
779 let middle = pad.len() / 2;
780 Some(if pad.len() % 2 == 1 {
781 pad[middle]
782 } else {
783 (pad[middle - 1] + pad[middle]) / 2.0
784 })
785}
786
787pub(crate) fn state_name(number: u8) -> String {
789 STATES
790 .iter()
791 .find(|(known, _)| *known == number)
792 .map_or_else(|| format!("state {number}"), |(_, name)| (*name).to_owned())
793}
794
795fn cut(text: &str) -> String {
797 text.chars().take(80).collect()
798}
799
800fn syntax(line: usize, message: String) -> LogError {
801 LogError::Syntax {
802 format: FORMAT,
803 line,
804 message,
805 }
806}
807
808#[cfg(test)]
809mod tests {
810 use super::*;
811
812 fn line_with(serial: u16, tick: u16, kind: u8, data: &[u8], rssi: u8, lqi: u8) -> String {
815 let mut bytes = vec![LENGTH];
816 bytes.extend(serial.to_le_bytes());
817 bytes.extend(tick.to_le_bytes());
818 bytes.push(kind);
819 bytes.extend(data);
820 bytes.resize(33, 0);
821 bytes.extend([rssi, lqi]);
822 let sum = bytes[1..]
823 .iter()
824 .fold(CHECKSUM_BASE, |sum, byte| sum.wrapping_add(*byte));
825 bytes.push(sum);
826 let hex: String = bytes.iter().map(|b| format!("{b:02x}")).collect();
827 format!("TELEM {hex}")
828 }
829
830 fn line(tick: u16, kind: u8, data: &[u8]) -> String {
832 line_with(1234, tick, kind, data, (-12i8) as u8, 0x80 | 40)
833 }
834
835 fn sensor(
838 tick: u16,
839 state: u8,
840 pres: i32,
841 temp: i16,
842 acc: i16,
843 speed: i16,
844 height: i16,
845 ) -> String {
846 let mut data = vec![state];
847 data.extend(100i16.to_le_bytes());
848 data.extend(pres.to_le_bytes());
849 data.extend(temp.to_le_bytes());
850 data.extend(acc.to_le_bytes());
851 data.extend(speed.to_le_bytes());
852 data.extend(height.to_le_bytes());
853 data.extend([1i16, 2, 3].iter().flat_map(|v| v.to_le_bytes()));
854 line(tick, SENSOR, &data)
855 }
856
857 fn file(lines: &[String]) -> String {
858 lines.join("\n") + "\n"
859 }
860
861 fn refusal(text: &str) -> String {
862 match read(text) {
863 Err(LogError::Syntax { message, .. }) => message,
864 other => panic!("not a syntax refusal: {other:?}"),
865 }
866 }
867
868 fn channel<'a>(log: &'a FlightLog, column: &str) -> Option<&'a Channel> {
869 log.channels.iter().find(|c| c.column == column)
870 }
871
872 #[test]
873 fn the_layout_is_recognized_by_its_first_line() {
874 assert!(recognizes(&file(&[sensor(100, 2, 98_000, 2_000, 0, 0, 0)])));
875 assert!(recognizes("\n TELEM 22ab\n"));
876 assert!(!recognizes("TELEM 22a\n"), "an odd count of digits");
877 assert!(!recognizes("TELEM\n"));
878 assert!(!recognizes("TELEMX 22ab\n"));
879 assert!(!recognizes("TELEM 22zz\n"));
880 assert!(!recognizes("#version,serial,flight\n"));
881 }
882
883 #[test]
886 fn the_checksum_covers_the_bytes_after_the_length() {
887 let good = sensor(100, 2, 98_000, 2_000, 0, 0, 0);
888 assert!(read(&file(std::slice::from_ref(&good))).is_ok());
889 let mut damaged = good.clone().into_bytes();
891 damaged[20] = if damaged[20] == b'0' { b'1' } else { b'0' };
892 let damaged = String::from_utf8(damaged).unwrap();
893 let text = file(&[good.clone(), damaged]);
894 assert!(refusal(&text).contains("the line is damaged"));
895 match read(&text) {
896 Err(LogError::Syntax { line, .. }) => assert_eq!(line, 2),
897 other => panic!("{other:?}"),
898 }
899 let hex = good.strip_prefix("TELEM ").unwrap();
901 let mut bytes: Vec<u8> = (0..hex.len() / 2)
902 .map(|k| u8::from_str_radix(&hex[2 * k..2 * k + 2], 16).unwrap())
903 .collect();
904 let last = bytes.len() - 1;
905 bytes[last] = bytes[last].wrapping_add(LENGTH);
906 let hex: String = bytes.iter().map(|b| format!("{b:02x}")).collect();
907 assert!(refusal(&format!("TELEM {hex}\n")).contains("damaged"));
908 }
909
910 #[test]
911 fn a_line_that_isnt_a_packet_refuses_the_file() {
912 let good = sensor(100, 2, 98_000, 2_000, 0, 0, 0);
913 assert!(refusal(&file(&[good.clone(), "TELEM xyz".to_owned()])).contains("isn't `TELEM`"));
914 assert!(
915 refusal(&file(&[good.clone(), "# a comment".to_owned()])).contains("isn't `TELEM`")
916 );
917 let short = &good[..good.len() - 2];
919 assert!(refusal(&file(&[short.to_owned()])).contains("of 35 bytes"));
920 let other_length = good.replacen("TELEM 22", "TELEM 21", 1);
922 assert!(refusal(&file(&[other_length])).contains("length byte of 33"));
923 }
924
925 #[test]
927 fn a_packet_failing_the_radios_crc_is_counted_not_read() {
928 let noise = line_with(9999, 7, 0xee, &[0xff; 27], 0x90, 0x12);
929 let text = file(&[
930 sensor(100, 2, 98_000, 2_000, 0, 0, 0),
931 noise,
932 sensor(110, 2, 98_010, 2_000, 0, 0, 1),
933 ]);
934 let log = read(&text).unwrap();
935 assert_eq!(log.time_s, [1.0, 1.1]);
936 assert!(log.notes[0].starts_with("3 packets heard: 1 failed the radio's CRC"));
937 assert_eq!(log.serial_number.as_deref(), Some("1234"));
938 }
939
940 #[test]
941 fn two_boards_in_one_file_are_refused() {
942 let other = line_with(4321, 105, SENSOR, &[2], (-12i8) as u8, 0x80);
943 let text = file(&[sensor(100, 2, 98_000, 2_000, 0, 0, 0), other]);
944 assert!(refusal(&text).contains("two boards' telemetry"));
945 }
946
947 #[test]
950 fn a_sensor_packet_reads_in_the_units_borne_out() {
951 let text = file(&[
952 sensor(100, 2, 98_000, 2_150, -8, 0, 0),
953 sensor(110, 3, 97_500, 2_160, 1_600, 320, 4),
954 sensor(120, 9, 97_000, 2_170, -160, 640, 12),
955 ]);
956 let log = read(&text).unwrap();
957 let values = |column: &str| channel(&log, column).unwrap().values.clone();
958 assert_eq!(values("pressure"), [98_000.0, 97_500.0, 97_000.0]);
959 assert_eq!(
960 channel(&log, "pressure").unwrap().quantity,
961 Quantity::Pressure
962 );
963 assert!((values("temperature")[0] - (21.5 + 273.15)).abs() < 1e-9);
964 assert_eq!(values("acceleration"), [-0.5, 100.0, -10.0]);
965 assert_eq!(values("speed"), [0.0, 20.0, 40.0]);
966 assert_eq!(log.altitude_m, [0.0, 4.0, 12.0]);
967 assert_eq!(log.time_s, [1.0, 1.1, 1.2]);
968 assert_eq!(values("accel"), [100.0; 3]);
969 assert_eq!(values("sense_m"), [3.0; 3]);
970 assert_eq!(
971 channel(&log, "v_batt").unwrap().quantity,
972 Quantity::Unrecognized
973 );
974 let events: Vec<&str> = log.events.iter().map(|e| e.name.as_str()).collect();
975 assert_eq!(events, ["pad", "boost", "state 9"]);
976 assert_eq!(log.events[1].time_s, 1.1);
977 assert_eq!(values("rssi"), [-80.0; 3]);
978 assert_eq!(values("lqi"), [40.0; 3]);
979 }
980
981 #[test]
984 fn pressure_is_pascals_only_where_the_pad_bears_it_out() {
985 let at = |pres: i32| read(&file(&[sensor(100, 2, pres, 0, 0, 0, 0)])).unwrap();
986 for (pres, pascals) in [
987 (10_000, true),
988 (120_000, true),
989 (9_999, false),
990 (120_001, false),
991 (980_000, false),
992 ] {
993 let log = at(pres);
994 assert_eq!(channel(&log, "pressure").is_some(), pascals, "{pres}");
995 assert_eq!(channel(&log, "pres").is_some(), !pascals, "{pres}");
996 }
997 assert_eq!(
998 channel(&at(980_000), "pres").unwrap().quantity,
999 Quantity::Unrecognized
1000 );
1001 let text = file(&[
1003 sensor(100, 2, 98_000, 0, 0, 0, 0),
1004 sensor(110, 3, 9_000, 0, 0, 0, 0),
1005 sensor(120, 4, 8_000, 0, 0, 0, 0),
1006 ]);
1007 assert!(channel(&read(&text).unwrap(), "pressure").is_some());
1008 }
1009
1010 #[test]
1013 fn the_ticks_turns_are_unwound() {
1014 let mut gps = vec![0x10 | 7];
1015 gps.extend(1000i16.to_le_bytes());
1016 gps.extend(450_000_000i32.to_le_bytes());
1017 gps.extend((-1_220_000_000i32).to_le_bytes());
1018 let text = file(&[
1019 sensor(65_500, 2, 98_000, 0, 0, 0, 0),
1020 sensor(30, 2, 98_000, 0, 0, 0, 0),
1021 line(65_526, LOCATION, &gps),
1023 sensor(32_000, 2, 98_000, 0, 0, 0, 0),
1024 sensor(64_000, 2, 98_000, 0, 0, 0, 0),
1025 sensor(100, 3, 98_000, 0, 0, 0, 0),
1026 ]);
1027 let log = read(&text).unwrap();
1028 let turn = 655.36;
1029 let expected = [
1030 655.0,
1031 turn + 0.30,
1032 turn + 320.0,
1033 turn + 640.0,
1034 2.0 * turn + 1.0,
1035 ];
1036 assert_eq!(log.time_s.len(), expected.len());
1037 for (time, expected) in log.time_s.iter().zip(expected) {
1038 assert!((time - expected).abs() < 1e-9, "{time} {expected}");
1039 }
1040 let latitude = channel(&log, "latitude").unwrap();
1041 assert!((latitude.time_s[0] - 655.26).abs() < 1e-9);
1042 assert!((latitude.values[0] - 45.0).abs() < 1e-12);
1043 assert!((channel(&log, "longitude").unwrap().values[0] + 122.0).abs() < 1e-12);
1044 assert_eq!(channel(&log, "gps_altitude").unwrap().values[0], 1000.0);
1045 assert_eq!(channel(&log, "nsat").unwrap().values[0], 7.0);
1046
1047 let text = file(&[
1050 sensor(1_000, 2, 98_000, 0, 0, 0, 0),
1051 line(960, LOCATION, &gps),
1052 sensor(33_750, 2, 98_000, 0, 0, 0, 0),
1053 ]);
1054 assert_eq!(read(&text).unwrap().time_s, [10.0, 337.5]);
1055 }
1056
1057 #[test]
1059 fn a_position_without_a_fix_is_a_gap() {
1060 let mut gps = vec![0x20 | 3];
1061 gps.extend(1000i16.to_le_bytes());
1062 gps.extend(450_000_000i32.to_le_bytes());
1063 let log = read(&file(&[line(100, LOCATION, &gps)])).unwrap();
1064 assert!(channel(&log, "latitude").unwrap().values[0].is_nan());
1065 assert!(channel(&log, "gps_altitude").unwrap().values[0].is_nan());
1066 assert_eq!(channel(&log, "gps_flags").unwrap().values[0], 35.0);
1067 assert!(
1068 log.notes
1069 .iter()
1070 .any(|n| n.starts_with("1 GPS packets with the flags' valid bit"))
1071 );
1072 assert!(log.time_s.is_empty() && log.temperature_k.is_none());
1073 assert_eq!(log.logger, "AltOS");
1074 }
1075
1076 #[test]
1079 fn the_power_on_that_flies_is_kept() {
1080 let earlier = [
1081 sensor(5_000, 2, 98_000, 0, 0, 0, 0),
1082 sensor(5_100, 2, 98_000, 0, 0, 0, 0),
1083 ];
1084 let flight = [
1085 sensor(500, 2, 98_000, 0, 0, 0, 0),
1086 sensor(510, 3, 97_000, 0, 0, 0, 10),
1087 ];
1088 let log = read(&file(&[&earlier[..], &flight[..]].concat())).unwrap();
1089 assert_eq!(log.time_s, [5.0, 5.1]);
1090 assert!(log.notes.iter().any(|n| n.contains("power-on 2 of 2 (the one that leaves the pad), and 2 packets")));
1091 let after = [sensor(200, 2, 98_000, 0, 0, 0, 0)];
1093 let log = read(&file(&[&flight[..], &after[..]].concat())).unwrap();
1094 assert_eq!(log.time_s, [5.0, 5.1]);
1095 assert!(log.notes.iter().any(|n| n.contains("power-on 1 of 2")));
1096 let log = read(&file(&[&flight[..], &earlier[..1]].concat())).unwrap();
1098 assert_eq!(log.time_s, [5.0, 5.1, 50.0]);
1099 let log = read(&file(&[&earlier[..], &flight[..1]].concat())).unwrap();
1101 assert_eq!(log.time_s, [5.0]);
1102 assert!(
1103 log.notes
1104 .iter()
1105 .any(|n| n.contains("the last, as none leaves the pad"))
1106 );
1107 let flight_again = [sensor(400, 3, 97_000, 0, 0, 0, 10)];
1109 let text = file(&[&flight[..], &flight_again[..]].concat());
1110 assert!(refusal(&text).contains("left the pad in two power-ons"));
1111 }
1112
1113 #[test]
1116 fn the_configuration_and_unread_types() {
1117 let mut config = vec![0x0b];
1118 config.extend(3u16.to_le_bytes());
1119 config.extend([1, 27]);
1120 config.extend(0u16.to_le_bytes());
1121 config.extend(250u16.to_le_bytes());
1122 config.extend(2048u16.to_le_bytes());
1123 config.extend(b"N0CALL\0\0");
1124 config.extend(b"1.9.22\0\0");
1125 let text = file(&[
1126 line(100, CONFIGURATION, &config),
1127 line(101, 0x08, &[0; 27]),
1128 line(102, 0x08, &[0; 27]),
1129 line(103, 0x30, &[0; 27]),
1130 sensor(104, 2, 98_000, 0, 0, 0, 0),
1131 ]);
1132 let log = read(&text).unwrap();
1133 assert_eq!(log.flight_number, Some(3));
1134 assert_eq!(log.firmware.as_deref(), Some("1.9.22"));
1135 assert!(
1136 log.notes
1137 .iter()
1138 .any(|n| n.contains("main at 250 m") && n.contains("\"N0CALL\""))
1139 );
1140 assert!(
1141 log.notes
1142 .iter()
1143 .any(|n| n.starts_with("2 packets of type 0x08 (TeleMega sensors) not read"))
1144 );
1145 assert!(log.notes.iter().any(|n| {
1146 n.starts_with("1 packets of type 0x30 not read: a type the document doesn't lay out")
1147 }));
1148 let text = file(&[line(101, 0x08, &[0; 27])]);
1150 assert!(matches!(read(&text), Err(LogError::NoData { .. })));
1151 }
1152
1153 #[test]
1158 fn the_documents_example_line_reads() {
1159 const EXAMPLE: &str =
1160 "TELEM 224f01080b05765e00701f1a1bbeb8d7b60b070605140c000600000000000000003fa988";
1161 let log = read(EXAMPLE).unwrap();
1162 assert_eq!(log.serial_number.as_deref(), Some("335"));
1163 let value = |column: &str| channel(&log, column).unwrap().values[0];
1164 assert!((value("latitude") - 45.469_681_6).abs() < 1e-12);
1165 assert!((value("longitude") + 122.737_645_0).abs() < 1e-12);
1166 assert_eq!(value("gps_altitude"), 94.0);
1167 assert_eq!(value("nsat"), 6.0);
1168 assert_eq!(value("gps_flags"), f64::from(0x76u8));
1169 assert_eq!(value("rssi"), -42.5);
1170 assert_eq!(value("lqi"), f64::from(0xa9u8 & 0x7f));
1171 assert_eq!(channel(&log, "latitude").unwrap().time_s[0], 28.24);
1173 let hex = EXAMPLE.strip_prefix("TELEM ").unwrap();
1175 let bytes: Vec<u8> = (0..hex.len() / 2)
1176 .map(|k| u8::from_str_radix(&hex[2 * k..2 * k + 2], 16).unwrap())
1177 .collect();
1178 let from_length = bytes[..35]
1179 .iter()
1180 .fold(CHECKSUM_BASE, |sum, b| sum.wrapping_add(*b));
1181 assert_ne!(from_length, bytes[35]);
1182 }
1183
1184 #[test]
1187 fn a_power_on_heard_only_landed_is_no_second_flight() {
1188 let text = file(&[
1189 sensor(500, 2, 98_000, 0, 0, 0, 0),
1190 sensor(510, 3, 97_000, 0, 0, 0, 10),
1191 sensor(520, 7, 97_500, 0, 0, 0, 5),
1192 sensor(40_600, 8, 98_000, 0, 0, 0, 0),
1194 ]);
1195 let log = read(&text).unwrap();
1196 assert_eq!(log.time_s, [5.0, 5.1, 5.2]);
1197 assert!(
1198 log.notes
1199 .iter()
1200 .any(|n| n.contains("power-on 1 of 2 (the one that leaves the pad)"))
1201 );
1202 }
1203
1204 #[test]
1206 fn differing_firmware_keeps_the_first() {
1207 let config = |version: &[u8; 8]| {
1208 let mut data = vec![0x0b];
1209 data.extend(3u16.to_le_bytes());
1210 data.extend([1, 27, 0, 0, 250, 0, 0, 8]);
1211 data.extend(b"N0CALL\0\0");
1212 data.extend(version);
1213 data
1214 };
1215 let text = file(&[
1216 line(100, CONFIGURATION, &config(b"1.9.22\0\0")),
1217 line(200, CONFIGURATION, &config(b"1.9.23\0\0")),
1218 ]);
1219 let log = read(&text).unwrap();
1220 assert_eq!(log.firmware.as_deref(), Some("1.9.22"));
1221 assert!(
1222 log.notes
1223 .iter()
1224 .any(|n| n.starts_with("the configuration packets name more than one firmware"))
1225 );
1226 }
1227
1228 #[test]
1230 fn a_step_is_on_the_nearest_turn() {
1231 assert_eq!(step(65_500, 30), 66);
1232 assert_eq!(step(30, 65_500), -66);
1233 assert_eq!(step(0, 32_767), 32_767);
1234 assert_eq!(step(0, 32_768), -32_768);
1235 }
1236}