Skip to main content

hpr_flightdata/
altos_telem.rs

1//! AltOS radio telemetry, as AltosUI saves the packets a TeleDongle hears to a `.telem` file:
2//! one `TELEM` line a packet, its bytes in hexadecimal.
3//!
4//! An Altus Metrum flight computer sends a 32-byte packet over its radio several times a second;
5//! the ground station's receiver, a TeleDongle, writes each packet it hears to its serial line as
6//! a text line, `TELEM` and then, in hexadecimal, a length byte, the packet, two bytes its radio
7//! adds, the signal strength (RSSI) and a link-quality byte whose top bit says the packet passed
8//! the radio's CRC, and a checksum (*AltOS Telemetry*, Bdale Garbee and Keith Packard,
9//! v1.9.22.2, 2025, §4 "TeleDongle serial packet format", p. 10). AltosUI saves every packet it
10//! receives (*The Altus Metrum System*, v1.9.22.2, 2025, §12.1, p. 27); the manual doesn't show
11//! the file, and both sample files hold `TELEM` lines only, failed packets among them, one a line.
12//! The document is published under CC BY-SA 3.0; this reader restates its facts, not its tables.
13//!
14//! **Recognition.** The first line that isn't blank is `TELEM`, a space, and an even number of
15//! hexadecimal digits; no other layout HPR Sim reads opens so.
16//!
17//! **A line.** Every line that isn't blank must be such a packet, 36 bytes: the length byte 34
18//! (the 32-byte packet and the two bytes the radio adds), the packet, the RSSI, the link-quality
19//! byte and the checksum, which is 0x5A plus every byte after the length byte up to, not
20//! including, the checksum, modulo 256. The document's table puts its byte positions one place early, and its formula taken as
21//! written fails its own example; summing from the byte after the length through the
22//! link-quality byte passes the example and every line of both sample files. A line that isn't a
23//! packet, has another length, or fails its checksum refuses the file ([`LogError::Syntax`]):
24//! the TeleDongle computed the checksum over its own line, so a failure is damage to the file. A
25//! packet whose link-quality byte says it failed the radio's CRC is left out and counted in a
26//! note: its bytes are noise (13.6% and 4.1% of the two sample files' packets).
27//!
28//! **A packet.** The first five bytes are the board's serial number (16 bits), its clock in
29//! ticks of 10 ms (16 bits) and the packet's type, then 27 bytes the type lays out (§2.1, p. 2).
30//! The document doesn't state the byte order; read little-endian, its own example's position is
31//! 45.47° N, 122.74° W, and big-endian it isn't a latitude, so little-endian it is. Every packet
32//! must name the same serial number, or the file is refused: two boards' packets in one file
33//! would make two flights of one. The RSSI is a signed byte, in dBm as `RSSI / 2 − 74` (§4); the
34//! document doesn't say signed, but the manual's receivers hear down to −111 dBm (§12.1, p. 27),
35//! which needs it, and read unsigned the sample files' signals would be stronger than the
36//! transmitter. The link-quality byte's other seven bits are kept as written.
37//!
38//! **The clock.** The tick turns over every 655.36 s. Each packet's tick is placed on the turn
39//! nearest the latest tick so far, so a GPS packet, which carries the earlier tick of its fix, is
40//! placed behind, not a turn ahead. The record's clock is that tick in seconds, counted from the
41//! turn of the first packet heard, not from boost: how long the board had run before is unknown.
42//! A board switched off and on again restarts its tick, so a packet whose tick falls behind the
43//! last one of its own type starts a new power-on (within one, each type's ticks never fall
44//! back). The record holds one power-on: the one whose sensor packets leave the pad (a state
45//! from `boost` to `main`), or, where none does, the last; packets of the others are left out and
46//! counted in a note, and a file in which two power-ons leave the pad is refused. The tick alone
47//! can't tell everything apart: a silence of 327.68 s to 655.36 s, half a turn to a whole one,
48//! reads as a step back, and so as a power-on; a longer one reads as a turn less than it was;
49//! and a restart whose new tick lands ahead of the last, as when a board had run for more than
50//! half a turn before it, reads as a silence, the two power-ons one record.
51//!
52//! **What is read.** The two sample files hold five packet types, and only those are decoded;
53//! the document lays out eleven more, for other boards, and a packet of one is counted in a note
54//! and not read: with no sample to check it, a misread unit wouldn't show (the document's own
55//! pressure unit is wrong, below). Each field is kept in the unit below where a second check bears
56//! it out, and as written otherwise:
57//!
58//! | Packet | Field | Channel | As read |
59//! |---|---|---|---|
60//! | `0x0A`, TeleMetrum v2 and newer, sensors | `state` | `state`, [`Quantity::Number`] | as written; each change an [`Event`] |
61//! | | `pres` | `pressure`, [`Quantity::Pressure`] | Pa: the document says tenths of a pascal, but the files hold pascals (below) |
62//! | | `temp` | `temperature`, [`Quantity::Temperature`] | hundredths of a °C, the document's; K here |
63//! | | `acceleration` | `acceleration`, [`Quantity::Acceleration`] | sixteenths of a m/s², the document's: the board's own estimate along its axis |
64//! | | `speed` | `speed`, [`Quantity::Speed`] | sixteenths of a m/s, the document's: the board's own estimate |
65//! | | `height` | `height`, [`Quantity::AltitudeAboveGround`] | m above the pad, the document's: the board's own estimate |
66//! | | `accel`, `v_batt`, `sense_d`, `sense_m` | the same names, [`Quantity::Unrecognized`] | as written: the document gives them as the converters' counts and no conversion |
67//! | `0x0B`, TeleMetrum v2 and newer, calibration | `ground_pres` | `ground_pressure`, [`Quantity::Pressure`] | Pa, as `pres` |
68//! | | `ground_accel`, `accel_plus_g`, `accel_minus_g` | the same names, [`Quantity::Unrecognized`] | as written: counts |
69//! | `0x05`, GPS position | flags | `nsat` (its low four bits) and `gps_flags` (the byte), [`Quantity::Number`] | as written |
70//! | | latitude, longitude | `latitude`, `longitude` | degrees, from ten-millionths; a gap where the flags' valid bit is clear |
71//! | | altitude | `gps_altitude`, [`Quantity::GnssAltitude`] | m; a gap where the valid bit is clear |
72//! | | year … second, `pdop`, `hdop`, `vdop`, mode | the same names, [`Quantity::Number`] | as written: the year is two digits, the dilutions five times their value in the document |
73//! | | ground speed, climb rate, course | `ground_speed`, `climb_rate`, `course`, [`Quantity::Unrecognized`] | as written: the document's cm/s and "/2" are unchecked |
74//! | `0x06`, GPS satellites | the count, and 12 pairs of a satellite's id and its signal | `sat_channels`, `svid_01` … `svid_12`, `c_n_01` … `c_n_12`, [`Quantity::Number`] | as written |
75//! | `0x04`, configuration | flight number, settings, call sign, firmware | the record's [`FlightLog::flight_number`] and [`FlightLog::firmware`]; each configuration in a note | as written |
76//! | every packet | RSSI, link quality | `rssi` (dBm) and `lqi`, [`Quantity::Number`] | dBm by the document's formula; the link quality as written |
77//!
78//! *Pressure in pascals, not tenths.* The document gives `pres` as "Pa * 10". Read so, both sample
79//! files' pads would be more than 15 km up; read as pascals they are at the height above sea
80//! level the export beside one of them states, and that export's own pressures, in pascals, equal
81//! the telemetry's at every tick where the export holds a fresh sample (the survey's report,
82//! `cargo xtask logs`). So `pres` is read as pascals where the
83//! pressure on the pad, the median of the packets in the pad state or else the first packet's,
84//! lies between 10 and 120 kPa read so, as every launch site's does; otherwise the column is
85//! kept as written, [`Quantity::Unrecognized`], with a note.
86//!
87//! *The flight's states.* The document names no state's number. AltosUI's exports write the
88//! number and the name side by side, and in every one of the sample exports 2 is `pad`, 3
89//! `boost`, 4 `fast`, 5 `coast`, 6 `drogue`, 7 `main` and 8 `landed`; the events take those
90//! names, and another number is `state N`. The board's estimates, `acceleration`, `speed` and
91//! `height`, are checked in the survey against each other and against the export.
92//!
93//! **The primary track.** [`FlightLog::altitude_m`] is `height` on the sensor packets' clock:
94//! the board's own estimate of its height above the pad, which the telemetry sends in place of
95//! a barometric altitude and which may lean on its accelerometer as its `speed` does; the document
96//! doesn't say how it is formed. [`FlightLog::temperature_k`] is the temperature; the vertical speed is absent, as the board's
97//! `speed` leans on its accelerometer (as for [AltOS's CSV](crate::altos)). Every other field is
98//! a channel on its own packets' clock.
99//!
100//! An invented line, a configuration packet: serial 1234 (`d204`), tick 256 (`0001`), type
101//! `04`, then device type 11, flight 3, configuration 1.27, no apogee delay, main at 250 m, a log
102//! of 2,048 kB, call sign `N0CALL` and firmware `1.9.22`; the RSSI byte `f4`, −12, is −80 dBm,
103//! and `a8` sets the CRC bit, with a link quality of 40:
104//!
105//! ```text
106//! TELEM 22d2040001040b0300011b0000fa0000084e3043414c4c0000312e392e32320000f4a8c1
107//! ```
108
109use std::collections::BTreeMap;
110
111use crate::error::LogError;
112use crate::log::{Channel, Event, FlightLog, LogFormat, Quantity, Stated};
113
114/// The format's name in errors.
115const FORMAT: &str = "AltOS telemetry";
116
117/// The word every line opens with.
118const PREFIX: &str = "TELEM";
119
120/// A line's length byte: the 32-byte packet and the radio's two bytes.
121const LENGTH: u8 = 34;
122
123/// A line's bytes: the length byte, then [`LENGTH`] bytes, then the checksum.
124const LINE_BYTES: usize = LENGTH as usize + 2;
125
126/// What the checksum adds to the sum of the bytes it covers (§4).
127const CHECKSUM_BASE: u8 = 0x5a;
128
129/// The link-quality byte's bit that says the packet passed the radio's CRC (§4).
130const CRC_OK: u8 = 0x80;
131
132/// The tick's turn: 2¹⁶ ticks.
133const TURN: i64 = 1 << 16;
134
135/// The ticks in a second (§2.1): a time is the tick divided by it, correctly rounded, where
136/// multiplying by 0.01 would not be (510 × 0.01 is 5.100 000 000 000 000 5).
137const TICKS_PER_S: f64 = 100.0;
138
139/// The pressures a launch site's pad can have, Pa.
140const PAD_PRESSURE_PA: std::ops::RangeInclusive<f64> = 10_000.0..=120_000.0;
141
142/// The flight's states by number, as AltosUI's exports name them.
143pub(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
153/// The pad's state number.
154const PAD: u8 = 2;
155
156/// The states of a flight, boost to main: a power-on in one of them has left the pad. `landed`
157/// isn't among them, so a power-on heard only after landing, such as one that starts after a
158/// silence, isn't taken for a second flight.
159const FLOWN: std::ops::RangeInclusive<u8> = 3..=7;
160
161/// How many distinct configurations a note quotes.
162const QUOTED_CONFIGURATIONS: usize = 8;
163
164/// The packet types the reader decodes.
165const SENSOR: u8 = 0x0a;
166const CALIBRATION: u8 = 0x0b;
167const CONFIGURATION: u8 = 0x04;
168const LOCATION: u8 = 0x05;
169const SATELLITES: u8 = 0x06;
170
171/// The satellite packet's twelve entries' channels: each satellite's id and its signal.
172const 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
181/// The types the document lays out that the reader doesn't decode, with the document's names.
182const 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
196/// Whether the text is AltOS telemetry: its first line that isn't blank is `TELEM`, a space, and
197/// an even number of hexadecimal digits.
198pub 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
206/// A line's hexadecimal digits, if it is `TELEM`, whitespace and an even number of them.
207fn 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
217/// One packet that passed the radio's CRC.
218struct 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    /// A text field: its bytes up to the first NUL, a byte that isn't printable ASCII as `?`.
246    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/// The channels being built, by name, in the order first met.
264#[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        // Names are allocated on a channel's first sample only.
273        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
303/// Reads AltOS telemetry, as AltosUI saves it to a `.telem` file.
304pub 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    // Power-ons: within one, each type's ticks never fall back.
330    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    // The clock: each tick on the turn nearest the latest so far.
366    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(&times) {
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 &not_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
686/// Every line's packet that passed the radio's CRC, and how many didn't; a refusal at a line
687/// that isn't a packet or fails its checksum.
688fn 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            // Checked as hexadecimal digits above, two a byte.
718            *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
762/// The ticks from `from` to `to`, on the nearest turn: from −32,768 to 32,767.
763fn step(from: u16, to: u16) -> i16 {
764    to.wrapping_sub(from) as i16
765}
766
767/// The pad's pressure as written: the median of the sensor packets in the pad state, or else the
768/// first sensor packet's; `None` without one.
769fn 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
787/// A state's name, as AltosUI's exports write it, or `state N`.
788pub(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
795/// A line cut to 80 characters, for an error.
796fn 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    /// A packet's line: `TELEM`, the length, the packet (serial, tick, type, then `data`, padded
813    /// with zeros to 32 bytes), the RSSI byte, the link-quality byte and the checksum.
814    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    /// A packet that passed the radio's CRC, from serial 1234, its RSSI −80 dBm.
831    fn line(tick: u16, kind: u8, data: &[u8]) -> String {
832        line_with(1234, tick, kind, data, (-12i8) as u8, 0x80 | 40)
833    }
834
835    /// A TeleMetrum v2 sensor packet: state, pressure (Pa as written), temperature (hundredths of
836    /// a °C), acceleration and speed (sixteenths), height (m).
837    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    /// The document's own example line passes the checksum as the reader sums it, from the byte
884    /// after the length through the link-quality byte, and fails it summed from the length byte.
885    #[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        // One byte of the packet changed, the checksum not: refused, naming the line.
890        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        // A checksum computed from the length byte instead is off by 0x22.
900        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        // 35 bytes: the checksum missing.
918        let short = &good[..good.len() - 2];
919        assert!(refusal(&file(&[short.to_owned()])).contains("of 35 bytes"));
920        // A length byte of 33 in a 36-byte line.
921        let other_length = good.replacen("TELEM 22", "TELEM 21", 1);
922        assert!(refusal(&file(&[other_length])).contains("length byte of 33"));
923    }
924
925    /// A packet the radio flags as failing its CRC is left out and counted, its bytes unread.
926    #[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    /// The units: pressure in pascals, temperature from hundredths of a °C to K, acceleration and
948    /// speed from sixteenths, height in meters; the counts kept as written; the states named.
949    #[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    /// Read as the document's tenths of a pascal, a pad at 98,000 would be 9.8 kPa: the files
982    /// hold pascals. A pad outside 10–120 kPa read as pascals is kept as written.
983    #[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        // The pad state's median decides, not the flight's lowest pressure.
1002        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    /// The tick turns over at 65,536: each tick on the turn nearest the latest so far, so a
1011    /// GPS packet's earlier tick is placed behind, and a turn adds 655.36 s.
1012    #[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            // Behind the latest by 40 ticks, and across the turn.
1022            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        // A step of 32,750 ticks after a GPS packet 40 behind: forward from the latest tick, so
1048        // within half a turn, though 32,790 from the GPS packet's would read as a step back.
1049        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    /// A GPS packet without the valid bit has its position read as gaps, counted.
1058    #[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    /// A board switched off and on restarts its tick: the record keeps the power-on that leaves
1077    /// the pad, whether first or last, and refuses a file in which two do.
1078    #[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        // The flight first, then a power-on on the pad after landing, its tick behind.
1092        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        // A power-on whose tick lands ahead of the last is a gap, not told apart.
1097        let log = read(&file(&[&flight[..], &earlier[..1]].concat())).unwrap();
1098        assert_eq!(log.time_s, [5.0, 5.1, 50.0]);
1099        // Neither leaves the pad: the last.
1100        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        // Both leave it: refused.
1108        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    /// The configuration gives the flight number and firmware; a type the document lays out but
1114    /// no sample holds, and one it doesn't define, are counted and not read.
1115    #[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        // A file of only unread types holds nothing to read.
1149        let text = file(&[line(101, 0x08, &[0; 27])]);
1150        assert!(matches!(read(&text), Err(LogError::NoData { .. })));
1151    }
1152
1153    /// The document's own example line (*AltOS Telemetry*, §4, p. 10), not built by this file's
1154    /// helpers: its checksum passes as the reader sums it, and read little-endian it is a GPS
1155    /// fix from serial 335 at 45.4696816° N, 122.7376450° W, six satellites, the valid bit set,
1156    /// its RSSI byte 0x3F, 63, so −42.5 dBm, the CRC bit set.
1157    #[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        // The clock: tick 0x0b08, 2,824.
1172        assert_eq!(channel(&log, "latitude").unwrap().time_s[0], 28.24);
1173        // Summed from the length byte, as the document's formula reads, the line fails.
1174        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    /// A power-on heard only in the `landed` state, as after a silence once the rocket is down,
1185    /// isn't a second flight: the one that flew is kept.
1186    #[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            // A step back of 25,536 ticks after a silence of 400 s: read as a power-on.
1193            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    /// Configuration packets naming two firmware versions keep the first, with a note.
1205    #[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    /// The step between two ticks is on the nearest turn.
1229    #[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}