1use hpr_core::gravity::STANDARD_GRAVITY_MPS2;
91
92use crate::error::LogError;
93use crate::log::{Channel, FlightLog, LogFormat, Quantity, Stated};
94use crate::perfectflite::FOOT_M;
95
96const FORMAT: &str = "Raven .FIPa";
98
99const OPENING: &[u8] = b"#Component=Raven";
101
102const MAX_HEADER: usize = 4096;
104
105const FRAME: usize = 258;
107
108const WORDS: usize = 32;
110
111const SETTINGS: usize = 5;
113
114const BLOCK_TICKS: u64 = 40;
116
117const SLOW: [Option<&str>; 10] = [
120 Some("Current Draw (A)"),
121 Some("Volts Pyro Apogee (V)"),
122 Some("Volts Pyro Main (V)"),
123 Some("Volts Pyro 3rd (V)"),
124 Some("Volts Pyro 4th (V)"),
125 None,
126 Some("Volts Battery (V)"),
127 Some("Temperature (F)"),
128 Some("Baro (Atm)"),
129 Some("Velocity (Accel-Ft/Sec)"),
130];
131
132const ATM_PA: f64 = 101_325.0;
134
135const BARO_COUNTS_PER_ATM: f64 = 25_000.0;
137
138pub(crate) fn recognizes(bytes: &[u8]) -> bool {
141 bytes.starts_with(OPENING) && header_end(bytes).is_some()
142}
143
144fn header_end(bytes: &[u8]) -> Option<usize> {
146 let head = &bytes[..bytes.len().min(MAX_HEADER)];
147 let mut start = 0;
148 while start < head.len() {
149 let end = head[start..]
150 .iter()
151 .position(|&b| b == b'\n')
152 .map(|at| start + at + 1)?;
153 if head[start..].starts_with(b"#den") {
154 return (bytes.get(end) == Some(&b':')).then_some(end);
155 }
156 if head[start] != b'#' {
157 return None;
158 }
159 start = end;
160 }
161 None
162}
163
164fn header_fields(header: &str) -> Vec<(&str, &str)> {
166 header
167 .lines()
168 .filter_map(|line| {
169 let line = line.trim_end_matches('\r').strip_prefix('#')?;
170 let split = line.find(['=', '\t', ' '])?;
171 Some((line[..split].trim(), line[split + 1..].trim()))
172 })
173 .collect()
174}
175
176fn signed(word: u16) -> i64 {
178 i64::from(word as i16)
179}
180
181struct Calibration {
183 f3: i64,
185 f4: i64,
187 x1: i64,
189 z1: i64,
191 x2: i64,
193 z2: i64,
195}
196
197impl Calibration {
198 fn from_block(block: &[u16; WORDS]) -> Self {
199 let pair = |hi: u16, lo: u16| i64::from(((u32::from(hi) << 16) | u32::from(lo)) as i32);
200 Self {
201 f3: signed(block[0]),
202 f4: signed(block[1]),
203 x1: pair(block[23], block[24]),
204 z1: i64::from(block[25]),
205 x2: pair(block[26], block[27]),
206 z2: i64::from(block[28]),
207 }
208 }
209
210 fn axial_g(&self, count: u16) -> f64 {
212 (scaled(self.x1, i64::from(count) - self.z1) + self.f3) as f64 / 100.0
213 }
214
215 fn lateral_g(&self, count: u16) -> f64 {
217 scaled(self.x2, i64::from(count) - self.z2) as f64 / 100.0
218 }
219}
220
221#[allow(
228 clippy::cast_possible_truncation,
229 reason = "operands below 2³² keep the product inside an i64"
230)]
231fn scaled(gain: i64, counts: i64) -> i64 {
232 ((gain as f64 / 1000.0) * counts as f64).trunc() as i64
233}
234
235struct Filling {
237 column: String,
238 quantity: Quantity,
239 ticks: Vec<u64>,
240 values: Vec<f64>,
241}
242
243impl Filling {
244 fn new(column: &str, quantity: Quantity) -> Self {
245 Self {
246 column: column.to_owned(),
247 quantity,
248 ticks: Vec::new(),
249 values: Vec::new(),
250 }
251 }
252
253 fn push(&mut self, tick: u64, value: f64) {
254 self.ticks.push(tick);
255 self.values.push(value);
256 }
257}
258
259pub fn read(bytes: &[u8]) -> Result<FlightLog, LogError> {
261 if !bytes.starts_with(OPENING) {
262 return Err(LogError::NotThisFormat {
263 format: FORMAT,
264 message: "the file doesn't open `#Component=Raven`".to_owned(),
265 });
266 }
267 let Some(body) = header_end(bytes) else {
268 return Err(binary(
269 0,
270 format!(
271 "the text header has no `#den` line followed by a frame within its first \
272 {MAX_HEADER} bytes"
273 ),
274 ));
275 };
276 let header = String::from_utf8_lossy(&bytes[..body]);
277 let fields = header_fields(&header);
278 let field = |key: &str| {
279 fields
280 .iter()
281 .find(|(k, _)| k.eq_ignore_ascii_case(key))
282 .map(|(_, v)| *v)
283 };
284 if let Some(version) = field("BinaryFormat")
285 && version != "1.0"
286 {
287 return Err(binary(
288 0,
289 format!("the header's `#BinaryFormat` is {version:?}; this reader knows 1.0"),
290 ));
291 }
292 let tick_part = |key: &str| {
293 field(key)
294 .and_then(|value| value.parse::<u32>().ok())
295 .filter(|&value| value > 0)
296 .ok_or_else(|| binary(0, format!("the header has no positive whole `#{key}`")))
297 };
298 let (num, den) = (tick_part("Num")?, tick_part("den")?);
299 let tick_s = f64::from(num) / f64::from(den) / 1000.0;
301
302 let mut blocks: Vec<[u16; WORDS]> = Vec::new();
304 let mut at = body;
305 while bytes.get(at) == Some(&b':') {
306 let Some(frame) = bytes.get(at + 1..at + FRAME) else {
307 return Err(binary(at, "the last frame is cut short".to_owned()));
308 };
309 let (data, checksum) = frame.split_at(256);
310 let sum = data.iter().fold(0u8, |sum, &b| sum.wrapping_add(b));
311 if sum != checksum[0] {
312 return Err(binary(
313 at,
314 format!(
315 "the frame's checksum is {:#04x}, its bytes sum to {sum:#04x}",
316 checksum[0]
317 ),
318 ));
319 }
320 let (pairs, _) = data.as_chunks::<2>();
321 for block in pairs.as_chunks::<WORDS>().0 {
322 blocks.push(block.map(u16::from_be_bytes));
323 }
324 at += FRAME;
325 }
326 let trailer = &bytes[at..];
327 let trailer_ok = trailer
328 .strip_prefix(b"#DONE")
329 .is_some_and(|rest| matches!(rest, b"" | b"\n" | b"\r\n"));
330 if !trailer_ok {
331 return Err(binary(
332 at,
333 "the frames are followed by something other than `#DONE` and a line end".to_owned(),
334 ));
335 }
336 if blocks.len() <= SETTINGS {
337 return Err(LogError::NoData { format: FORMAT });
338 }
339
340 let settings = blocks[SETTINGS];
341 if let Some(state) = field("FlightState") {
342 let listed: Vec<&str> = state.split('\t').skip(2).collect();
343 #[allow(
346 clippy::cast_possible_truncation,
347 clippy::cast_sign_loss,
348 reason = "a value in i16's or u16's range keeps its 16 bits: the word, signed or not"
349 )]
350 let agrees = !listed.is_empty()
351 && listed.len() <= WORDS
352 && listed.iter().zip(settings).all(|(listed, word)| {
353 listed.trim().parse::<i64>().is_ok_and(|value| {
354 (i64::from(i16::MIN)..=i64::from(u16::MAX)).contains(&value)
355 && value as u16 == word
356 })
357 });
358 if !agrees {
359 return Err(binary(
360 body + FRAME * (SETTINGS / 4) + 1 + 2 * WORDS * (SETTINGS % 4),
361 "the settings block's words aren't the ones `#FlightState` lists".to_owned(),
362 ));
363 }
364 }
365 let calibration = Calibration::from_block(&settings);
366 let two_axes = match field("Axis") {
370 None | Some("2") => true,
371 Some("1") => false,
372 Some(other) => {
373 return Err(binary(
374 0,
375 format!("the header's `#Axis` is {other:?}; this reader knows 1 and 2"),
376 ));
377 }
378 };
379
380 let mut axial = Filling::new("Axial Accel (Gs)", Quantity::Acceleration);
381 let mut lateral = if two_axes {
382 Filling::new("Lateral Accel (Gs)", Quantity::Acceleration)
383 } else {
384 Filling::new("lateral counts", Quantity::Unrecognized)
385 };
386 let mut slow: Vec<Filling> = SLOW
387 .iter()
388 .enumerate()
389 .map(|(k, name)| match name {
390 Some(name) => Filling::new(name, quantity_of(name)),
391 None => Filling::new(&format!("slow channel {k}"), Quantity::Unrecognized),
392 })
393 .collect();
394 let mut tails = [
395 Filling::new("block word 30", Quantity::Unrecognized),
396 Filling::new("block word 31", Quantity::Unrecognized),
397 ];
398 let mut data_blocks = 0u64;
399 let mut ended = None;
400 for (index, block) in blocks.iter().enumerate() {
401 if index == SETTINGS {
402 continue;
403 }
404 if block.iter().all(|&word| word == 0xffff) {
405 ended = Some(index);
406 break;
407 }
408 let shift = u64::from(index > SETTINGS);
409 let first = data_blocks * BLOCK_TICKS;
410 data_blocks += 1;
411 for (k, &[a, b, s]) in block[..30].as_chunks::<3>().0.iter().enumerate() {
412 let base = first + 4 * k as u64 + shift;
413 axial.push(base, calibration.axial_g(a >> 5) * STANDARD_GRAVITY_MPS2);
414 let count = ((a & 0x1f) << 5) | (b >> 11);
415 lateral.push(
416 base + 1,
417 if two_axes {
418 calibration.lateral_g(count) * STANDARD_GRAVITY_MPS2
419 } else {
420 f64::from(count)
421 },
422 );
423 axial.push(
424 base + 2,
425 calibration.axial_g(b & 0x7ff) * STANDARD_GRAVITY_MPS2,
426 );
427 slow[k].push(base + 3, slow_si(k, s));
428 }
429 let last = first + BLOCK_TICKS - 1 + shift;
430 tails[0].push(last, f64::from(block[30]));
431 tails[1].push(last, f64::from(block[31]));
432 }
433 if let Some(stop) = ended
434 && let Some(used) = (stop + 1..blocks.len())
435 .filter(|&index| index != SETTINGS)
436 .find(|&index| blocks[index].iter().any(|&word| word != 0xffff))
437 {
438 return Err(binary(
439 body + FRAME * (used / 4),
440 format!("block {used} holds data after block {stop}, which is unused"),
441 ));
442 }
443 if data_blocks <= SETTINGS as u64 {
444 return Err(LogError::NoData { format: FORMAT });
445 }
446
447 let mut notes = vec![
448 "the record's primary track is empty: the Raven records a pressure, not an altitude; the \
449 FIP's export works its altitudes out of the pressure"
450 .to_owned(),
451 format!(
452 "read from the Raven's memory: {data_blocks} blocks of 0.05 s, the first {SETTINGS} \
453 before the launch; a tick is {num}/{den} ms"
454 ),
455 "`slow channel 5` and `block word 30` and `31` are kept as written: the FIP's export \
456 holds neither"
457 .to_owned(),
458 ];
459 if !two_axes {
460 notes.push(
461 "the header's `#Axis` is 1: the Raven records no lateral accelerometer it calibrates, \
462 so the lateral bits are kept as written, as `lateral counts`"
463 .to_owned(),
464 );
465 }
466 if let Some(stop) = ended {
467 notes.push(format!(
468 "the memory is unused from block {stop} of {}",
469 blocks.len()
470 ));
471 }
472 let date = field("DateTime").map(str::to_owned);
473 if let Some(date) = date {
474 notes.push(format!(
475 "the header's `#DateTime` is {date:?}, as written: the file doesn't say which clock \
476 wrote it"
477 ));
478 }
479
480 let mut channels = Vec::new();
481 for filling in [axial, lateral].into_iter().chain(slow).chain(tails) {
482 channels.push(Channel {
483 column: filling.column,
484 quantity: filling.quantity,
485 time_s: filling
486 .ticks
487 .iter()
488 .map(|&tick| tick as f64 * tick_s)
489 .collect(),
490 values: filling.values,
491 });
492 }
493
494 Ok(FlightLog {
495 format: LogFormat::RavenFipa,
496 logger: "Featherweight Raven".to_owned(),
497 serial_number: None,
498 firmware: field("R").map(str::to_owned),
499 flight_number: field("FlightNum").and_then(|n| n.parse().ok()),
500 stated: Stated {
501 ground_elevation_msl_m: Some(calibration.f4 as f64 * FOOT_M),
502 ..Stated::default()
503 },
504 time_s: Vec::new(),
505 altitude_m: Vec::new(),
506 vertical_speed_m_s: None,
507 temperature_k: None,
508 battery_v: None,
509 channels,
510 events: Vec::new(),
511 notes,
512 })
513}
514
515fn quantity_of(name: &str) -> Quantity {
517 match name {
518 "Current Draw (A)" => Quantity::Current,
519 "Temperature (F)" => Quantity::Temperature,
520 "Baro (Atm)" => Quantity::Pressure,
521 "Velocity (Accel-Ft/Sec)" => Quantity::Speed,
522 _ => Quantity::Voltage,
523 }
524}
525
526fn slow_si(k: usize, word: u16) -> f64 {
528 match k {
529 0..=4 | 6 => signed(word) as f64 / 1000.0,
530 7 => (signed(word) as f64 / 100.0 - 32.0) * 5.0 / 9.0 + 273.15,
532 8 => f64::from(word) / BARO_COUNTS_PER_ATM * ATM_PA,
533 9 => signed(word) as f64 / 10.0 * FOOT_M,
534 _ => f64::from(word),
535 }
536}
537
538fn binary(offset: usize, message: String) -> LogError {
540 LogError::Binary {
541 format: FORMAT,
542 offset,
543 message,
544 }
545}