hpr_flightdata/altimax_als.rs
1//! Rocketronics' AltiMAX altimeters: a flight's `.ALS` file, the samples as the altimeter stores
2//! them, before the PC software works heights and a speed out of them.
3//!
4//! An AltiMAX with a memory card writes each flight to it as an `.als` file, which the maker's PC
5//! software reads directly (*AltiMAX G2 Handbuch*, Louis Schreyer, 2010, p. 12). No manual
6//! describes the bytes, so the layout here was worked out from the one sample file, decoded
7//! against the software's Excel export of the same flight ([`altimax`](crate::altimax)): the file
8//! holds one record for each of the export's rows, and every value it stores is the export's, to
9//! the export's 15 significant digits.
10//!
11//! **Layout.** Little-endian throughout: a header of 32 bytes, then one record of 22 bytes a
12//! sample, then a trailer.
13//!
14//! | Bytes | Field | Read as |
15//! |---|---|---|
16//! | header 4–7 | u32 | the zero pressure, Pa: every height in the export is the standard atmosphere's height of a pressure less that of this one |
17//! | header 8–11 | u32 | the apogee's pressure, Pa: the least filtered pressure, to the pascal |
18//! | header 26–27 | u16 | the index of the last record: the records are one more |
19//! | record 0 | u8 | the record's kind: bit 0 always set, bit 1 never; bit 2 set when the record was stored 25 ms after the one before, clear when 5 ms; bits 3–7 the voltage channel the record's count is, 1 to 5 in turn |
20//! | record 1 | u8 | the event's code, 0 for none |
21//! | record 2–5 | f32 | the filtered pressure, Pa |
22//! | record 6–9 | u32 | the raw pressure, Pa |
23//! | record 10–11 | i16 | the acceleration, in counts of 0.01 g along an axis down the rocket |
24//! | record 12–13 | u16 | the voltage channel's count |
25//! | record 14–21 | 8 bytes | zero in every sample record |
26//!
27//! The header's other bytes, and the trailer, aren't read: in the sample, the trailer is 2,616
28//! bytes, nearly all zero.
29//!
30//! **The clock** isn't stored: each record is 5 ms or 25 ms after the one before, as its kind's
31//! bit 2 says, and the first is at 5 ms, as in the export. The maker's table gives storage rates of
32//! 200 and 40 samples a second (*AltiMAX G4 Manual*, Rocketronics, 2021, p. 10); its text says the
33//! rate drops to 50 a second 500 ms after the peak (p. 8), but the sample's slower records are 25
34//! ms apart, the table's 40 a second. The clock is the running sum of the steps, as the export's
35//! `TIME`.
36//!
37//! **Channels**, each on that clock, named as the export names the column each becomes:
38//!
39//! | Channel | Quantity | Unit |
40//! |---|---|---|
41//! | `PRESS FILTER`, `PRESS RAW` | [`Quantity::Pressure`] | Pa, as stored; the export's header says hPa, but its values are these pascals |
42//! | `ACCEL` | [`Quantity::Acceleration`] | m/s²: each count 0.0981 m/s², 0.01 g with g taken as 9.81 m/s², the export's own factor; the axis points down the rocket, so the pad reads about −1 g |
43//! | `EVENT` | [`Quantity::Number`] | the event's code, as written |
44//! | `VOLT. CHANNEL` | [`Quantity::Number`] | the record's voltage channel, 1 to 5 |
45//! | `VOLTAGE count (channel N)` | [`Quantity::Unrecognized`], as written | each channel's count, on the records that hold it |
46//!
47//! The counts are kept as written. The export turns them into volts by one factor for channels 1
48//! and 5 and another for 2 to 4, but no document states either, and the software lists five
49//! voltages without saying which channel is which (*AltiMAX G4 Manual*, p. 42).
50//!
51//! **Events.** A record whose event code isn't 0 is an event, named as the export names its code:
52//!
53//! | Code | Name | Code | Name |
54//! |---:|---|---:|---|
55//! | 3 | `BARO-LIFTOFF` | 14 | `LAND` |
56//! | 5 | `MACHDELAY` | 20, 21 | `PYRO1 ON`, `PYRO1 OFF` |
57//! | 6, 7, 8 | `TIMER1 END`, `TIMER2 END`, `TIMER3 END` | 22, 23 | `PYRO2 ON`, `PYRO2 OFF` |
58//! | 9 | `APOGEE PRESSURE` | 28, 29, 30 | `TIMER1 START`, `TIMER2 START`, `TIMER3 START` |
59//! | 10, 11 | `HEIGHT ASCEND`, `HEIGHT DESCEND` | | |
60//!
61//! Any other code, which the sample doesn't show, is named `event N`.
62//!
63//! **Stated.** The record count, and the zero and apogee pressures as figures, `zero pressure`
64//! and `apogee pressure`.
65//!
66//! **No primary track.** The file holds no height and no clock, so [`FlightLog::time_s`] and
67//! [`FlightLog::altitude_m`] are empty, as for the Raven's raw `.FIPa`, and every value is a
68//! channel. The export's heights are the software's: the standard atmosphere's height of each
69//! pressure, less that of the zero pressure.
70//!
71//! **Recognition.** [`recognizes`] takes a file whose header states at least one record and a
72//! zero pressure of 50,000 to 110,000 Pa, a pad's, and whose first records, up to 1,000, are each a kind with bit 0 set and bit 1 clear and a voltage
73//! channel one past the record before's (1 after 5). It doesn't read the eight zero bytes, so a
74//! file that differs only there is refused by [`read`], naming the byte, not left unrecognized.
75//!
76//! **Refused**, naming the byte: a record whose kind or zero bytes aren't as above; a raw
77//! pressure on the first record that isn't a pad's, 50,000 to 110,000 Pa; a filtered pressure
78//! that isn't finite; and a record past the header's count, as a flight of more than 65,536
79//! records, whose count 16 bits can't hold, would have. A file shorter than its header and one
80//! record isn't this format. A file that ends before its header's count is read to its last
81//! whole record, with a note.
82//!
83//! ```
84//! use hpr_flightdata::altimax_als;
85//!
86//! // An invented file: two records, the second an event, then no trailer.
87//! let mut bytes = vec![0_u8; 32];
88//! bytes[4..8].copy_from_slice(&98_000_u32.to_le_bytes());
89//! bytes[26..28].copy_from_slice(&1_u16.to_le_bytes());
90//! for (channel, event, pressure) in [(1_u8, 0_u8, 98_000.0_f32), (2, 3, 97_990.0)] {
91//! bytes.push(channel << 3 | 1);
92//! bytes.push(event);
93//! bytes.extend(pressure.to_le_bytes());
94//! bytes.extend((pressure as u32).to_le_bytes());
95//! bytes.extend((-100_i16).to_le_bytes());
96//! bytes.extend(512_u16.to_le_bytes());
97//! bytes.extend([0; 8]);
98//! }
99//! let log = altimax_als::read(&bytes)?;
100//! assert_eq!(log.events[0].name, "BARO-LIFTOFF");
101//! assert_eq!(log.events[0].time_s, 0.01);
102//! # Ok::<(), hpr_flightdata::error::LogError>(())
103//! ```
104
105use crate::error::LogError;
106use crate::log::{Channel, Event, Figure, FlightLog, LogFormat, Quantity, Stated};
107
108const FORMAT: &str = "AltiMAX .ALS";
109
110/// The header's length, bytes.
111const HEADER_BYTES: usize = 32;
112
113/// A record's length, bytes.
114const RECORD_BYTES: usize = 22;
115
116/// Where the header holds the zero pressure, the apogee's pressure and the last record's index.
117const ZERO_PRESSURE_AT: usize = 4;
118const APOGEE_PRESSURE_AT: usize = 8;
119const LAST_INDEX_AT: usize = 26;
120
121/// A record's step from the one before, s: 200 samples a second, or 40 where the kind's bit 2 is
122/// set (*AltiMAX G4 Manual*, p. 10).
123const FAST_STEP_S: f64 = 0.005;
124const SLOW_STEP_S: f64 = 0.025;
125
126/// Where a record's eight zero bytes start.
127const ZEROS_AT: usize = 14;
128
129/// The kind's bits: bit 0 always set, bit 1 never, bit 2 the slower step.
130const KIND_SET: u8 = 0b001;
131const KIND_CLEAR: u8 = 0b010;
132const KIND_SLOW: u8 = 0b100;
133
134/// The voltage channels, 1 to 5 in turn.
135const VOLT_CHANNELS: u8 = 5;
136
137/// The export's factor for an acceleration count, m/s²: 0.01 g with g taken as 9.81 m/s².
138const ACCEL_M_S2_PER_COUNT: f64 = 0.0981;
139
140/// A pad's pressure, Pa: 500 to 1,100 hPa, the band the other readers hold a pressure to.
141const PAD_PA: std::ops::RangeInclusive<f64> = 50_000.0..=110_000.0;
142
143/// The records [`recognizes`] reads.
144const RECOGNIZED_RECORDS: usize = 1_000;
145
146/// Each event code the sample export names, and its name there.
147const EVENT_NAMES: [(u8, &str); 16] = [
148 (3, "BARO-LIFTOFF"),
149 (5, "MACHDELAY"),
150 (6, "TIMER1 END"),
151 (7, "TIMER2 END"),
152 (8, "TIMER3 END"),
153 (9, "APOGEE PRESSURE"),
154 (10, "HEIGHT ASCEND"),
155 (11, "HEIGHT DESCEND"),
156 (14, "LAND"),
157 (20, "PYRO1 ON"),
158 (21, "PYRO1 OFF"),
159 (22, "PYRO2 ON"),
160 (23, "PYRO2 OFF"),
161 (28, "TIMER1 START"),
162 (29, "TIMER2 START"),
163 (30, "TIMER3 START"),
164];
165
166/// One record, as stored.
167#[derive(Clone, Copy)]
168struct Record {
169 kind: u8,
170 event: u8,
171 filtered_pa: f32,
172 raw_pa: u32,
173 accel_counts: i16,
174 volt_count: u16,
175}
176
177/// The record at `index`, if the file holds all its bytes.
178fn record(bytes: &[u8], index: usize) -> Option<(Record, &[u8])> {
179 let at = HEADER_BYTES.checked_add(index.checked_mul(RECORD_BYTES)?)?;
180 let data: &[u8; RECORD_BYTES] = bytes
181 .get(at..at.checked_add(RECORD_BYTES)?)?
182 .try_into()
183 .ok()?;
184 let record = Record {
185 kind: data[0],
186 event: data[1],
187 filtered_pa: f32::from_le_bytes([data[2], data[3], data[4], data[5]]),
188 raw_pa: u32::from_le_bytes([data[6], data[7], data[8], data[9]]),
189 accel_counts: i16::from_le_bytes([data[10], data[11]]),
190 volt_count: u16::from_le_bytes([data[12], data[13]]),
191 };
192 Some((record, &data[ZEROS_AT..]))
193}
194
195/// The header's u32 at `at`.
196fn header_u32(bytes: &[u8], at: usize) -> Option<u32> {
197 Some(u32::from_le_bytes(bytes.get(at..at + 4)?.try_into().ok()?))
198}
199
200/// The records the header states: the last record's index, plus one.
201fn stated_records(bytes: &[u8]) -> Option<usize> {
202 let last = u16::from_le_bytes(
203 bytes
204 .get(LAST_INDEX_AT..LAST_INDEX_AT + 2)?
205 .try_into()
206 .ok()?,
207 );
208 Some(usize::from(last) + 1)
209}
210
211/// Why the record at `index` isn't one, given the voltage channel of the record before, if any.
212/// The kind's bits and the channels' turns are the layout's pattern, which [`recognizes`] reads;
213/// the zero bytes are held to the sample, which only [`read`] checks, so that a file differing
214/// there is refused by name, not left unrecognized.
215fn fault(record: &Record, zeros: &[u8], before: Option<u8>, held: bool) -> Option<(usize, String)> {
216 let channel = record.kind >> 3;
217 if record.kind & KIND_SET == 0 || record.kind & KIND_CLEAR != 0 {
218 return Some((
219 0,
220 format!(
221 "its kind, {:#04x}, has bit 0 clear or bit 1 set, which no sample record has",
222 record.kind
223 ),
224 ));
225 }
226 if !(1..=VOLT_CHANNELS).contains(&channel) {
227 return Some((
228 0,
229 format!(
230 "its kind, {:#04x}, names voltage channel {channel}, where the channels are 1 \
231 to {VOLT_CHANNELS}",
232 record.kind
233 ),
234 ));
235 }
236 if let Some(before) = before {
237 let next = before % VOLT_CHANNELS + 1;
238 if channel != next {
239 return Some((
240 0,
241 format!(
242 "its voltage channel is {channel}, where the channels take turns and {next} \
243 follows {before}"
244 ),
245 ));
246 }
247 }
248 if let Some(at) = zeros.iter().position(|&byte| byte != 0).filter(|_| held) {
249 return Some((
250 ZEROS_AT + at,
251 "its last 8 bytes aren't zero, as they are in every sample record: the reader \
252 doesn't know what they hold"
253 .to_owned(),
254 ));
255 }
256 None
257}
258
259/// Whether `bytes` are an AltiMAX `.ALS` file: a header stating at least one record and a zero
260/// pressure a pad's, 50,000 to 110,000 Pa, and the first records, up to 1,000, each with its kind's bit 0 set and bit 1 clear and its voltage
261/// channel the one after the record before's. The bytes held to the sample aren't read here:
262/// [`read`] refuses a file that differs there, naming the byte.
263pub fn recognizes(bytes: &[u8]) -> bool {
264 let Some(stated) = stated_records(bytes) else {
265 return false;
266 };
267 // A pad's zero pressure: no text passes, as four printable bytes are at least 0x20202020.
268 if !header_u32(bytes, ZERO_PRESSURE_AT).is_some_and(|pa| PAD_PA.contains(&f64::from(pa))) {
269 return false;
270 }
271 let mut before = None;
272 for index in 0..stated.min(RECOGNIZED_RECORDS) {
273 let Some((record, zeros)) = record(bytes, index) else {
274 return index > 0;
275 };
276 if fault(&record, zeros, before, false).is_some() {
277 return false;
278 }
279 before = Some(record.kind >> 3);
280 }
281 true
282}
283
284/// The byte where record `index` starts.
285fn offset(index: usize) -> usize {
286 HEADER_BYTES + index * RECORD_BYTES
287}
288
289fn binary(offset: usize, message: String) -> LogError {
290 LogError::Binary {
291 format: FORMAT,
292 offset,
293 message,
294 }
295}
296
297/// Reads an AltiMAX `.ALS` file.
298///
299/// # Errors
300///
301/// [`LogError::NotThisFormat`] when the file is shorter than a header and one record;
302/// [`LogError::Binary`], naming the byte, when a record's kind or zero bytes aren't as the
303/// module describes, the first raw pressure isn't a pad's, a filtered pressure isn't finite, or a
304/// record follows the header's count.
305pub fn read(bytes: &[u8]) -> Result<FlightLog, LogError> {
306 let Some(stated) = stated_records(bytes).filter(|_| bytes.len() >= offset(1)) else {
307 return Err(LogError::NotThisFormat {
308 format: FORMAT,
309 message: format!(
310 "{} bytes, shorter than a header of {HEADER_BYTES} and a record of {RECORD_BYTES}",
311 bytes.len()
312 ),
313 });
314 };
315 let mut records = Vec::new();
316 let mut before = None;
317 for index in 0..stated {
318 let Some((record, zeros)) = record(bytes, index) else {
319 break;
320 };
321 if let Some((at, message)) = fault(&record, zeros, before, true) {
322 return Err(binary(
323 offset(index) + at,
324 format!("record {}: {message}", index + 1),
325 ));
326 }
327 if !record.filtered_pa.is_finite() {
328 return Err(binary(
329 offset(index) + 2,
330 format!("record {}: its filtered pressure isn't a number", index + 1),
331 ));
332 }
333 if index == 0 && !PAD_PA.contains(&f64::from(record.raw_pa)) {
334 return Err(binary(
335 offset(index) + 6,
336 format!(
337 "the first record's raw pressure, {} Pa, isn't a pad's, 50,000 to 110,000 Pa",
338 record.raw_pa
339 ),
340 ));
341 }
342 before = Some(record.kind >> 3);
343 records.push(record);
344 }
345 // A record past the header's count: a flight longer than 16 bits can count.
346 if let Some((next, zeros)) = record(bytes, records.len())
347 && records.len() == stated
348 && fault(&next, zeros, before, true).is_none()
349 {
350 return Err(binary(
351 offset(stated),
352 format!(
353 "a record follows the {stated} the header states: a flight of more records than \
354 its 16-bit count holds, which no sample shows"
355 ),
356 ));
357 }
358
359 let mut time_s = Vec::with_capacity(records.len());
360 let mut clock = 0.0;
361 for record in &records {
362 clock += if record.kind & KIND_SLOW == 0 {
363 FAST_STEP_S
364 } else {
365 SLOW_STEP_S
366 };
367 time_s.push(clock);
368 }
369 let column = |values: Vec<f64>, name: &str, quantity| Channel {
370 column: name.to_owned(),
371 quantity,
372 time_s: time_s.clone(),
373 values,
374 };
375 let mut channels = vec![
376 column(
377 records.iter().map(|r| f64::from(r.filtered_pa)).collect(),
378 "PRESS FILTER",
379 Quantity::Pressure,
380 ),
381 column(
382 records.iter().map(|r| f64::from(r.raw_pa)).collect(),
383 "PRESS RAW",
384 Quantity::Pressure,
385 ),
386 column(
387 records
388 .iter()
389 .map(|r| f64::from(r.accel_counts) * ACCEL_M_S2_PER_COUNT)
390 .collect(),
391 "ACCEL",
392 Quantity::Acceleration,
393 ),
394 column(
395 records.iter().map(|r| f64::from(r.event)).collect(),
396 "EVENT",
397 Quantity::Number,
398 ),
399 column(
400 records.iter().map(|r| f64::from(r.kind >> 3)).collect(),
401 "VOLT. CHANNEL",
402 Quantity::Number,
403 ),
404 ];
405 for channel in 1..=VOLT_CHANNELS {
406 let (times, values) = records
407 .iter()
408 .zip(&time_s)
409 .filter(|(record, _)| record.kind >> 3 == channel)
410 .map(|(record, time)| (*time, f64::from(record.volt_count)))
411 .unzip();
412 channels.push(Channel {
413 column: format!("VOLTAGE count (channel {channel})"),
414 quantity: Quantity::Unrecognized,
415 time_s: times,
416 values,
417 });
418 }
419 let events = records
420 .iter()
421 .zip(&time_s)
422 .filter(|(record, _)| record.event != 0)
423 .map(|(record, time)| Event {
424 time_s: *time,
425 name: EVENT_NAMES
426 .iter()
427 .find(|(code, _)| *code == record.event)
428 .map_or_else(
429 || format!("event {}", record.event),
430 |(_, name)| (*name).to_owned(),
431 ),
432 })
433 .collect();
434
435 let mut stated_figures = Stated {
436 samples: Some(stated),
437 ..Stated::default()
438 };
439 for (name, at) in [
440 ("zero pressure", ZERO_PRESSURE_AT),
441 ("apogee pressure", APOGEE_PRESSURE_AT),
442 ] {
443 if let Some(pa) = header_u32(bytes, at) {
444 stated_figures.figures.push(Figure::new(
445 name,
446 format!("{pa} Pa"),
447 Some(Quantity::Pressure),
448 vec![f64::from(pa)],
449 ));
450 }
451 }
452
453 let end = offset(records.len());
454 let mut notes = vec![format!(
455 "the clock isn't stored. Each record is {FAST_STEP_S} s after the one before, or \
456 {SLOW_STEP_S} s where its kind's bit 2 is set. Those are the 200 and 40 samples a \
457 second the maker's manual gives"
458 )];
459 if records.len() < stated {
460 notes.push(format!(
461 "the header states {stated} records, but the file ends after {}: read those",
462 records.len()
463 ));
464 } else if bytes.len() > end {
465 notes.push(format!(
466 "{} bytes after the records, a trailer, aren't read",
467 bytes.len() - end
468 ));
469 }
470 notes.push(
471 "the voltage counts are kept as written: no document states their factor to volts"
472 .to_owned(),
473 );
474 Ok(FlightLog {
475 format: LogFormat::AltimaxAls,
476 logger: "Rocketronics AltiMAX".to_owned(),
477 serial_number: None,
478 firmware: None,
479 flight_number: None,
480 stated: stated_figures,
481 time_s: Vec::new(),
482 altitude_m: Vec::new(),
483 vertical_speed_m_s: None,
484 temperature_k: None,
485 battery_v: None,
486 channels,
487 events,
488 notes,
489 })
490}