Skip to main content

hpr_flightdata/
import.rs

1//! One entry point for every format HPR Sim reads: give [`read`] a file's bytes, and it
2//! recognizes the layout from the content, never the file's name, and reads it into the record
3//! every reader fills ([`FlightLog`]).
4//!
5//! The layouts it recognizes, the raw downloads by their bytes, the GPS logs by their own marks,
6//! the rest by the first line that isn't blank:
7//!
8//! | Format | Recognized by |
9//! |---|---|
10//! | [Raven `.FIPa`](crate::raven_fipa) | its bytes: they open `#Component=Raven`, and a `#den` line within the first 4,096 is followed by a frame's `:`; told before the file is decoded as text |
11//! | [RRC3 `.rff`](crate::rrc3_rff) | its bytes: an MS-NRBF serialization header, version 1.0, and mDACS's `mDACS.AnalysisSupport+FlightRecord` class name within the first 4,096; told before the file is decoded as text |
12//! | [ARTS2 `.odf`](crate::arts2_raw) | its bytes: the length 9, then `Ozark.odf`; told before the file is decoded as text |
13//! | [RTx `.rtx`](crate::rtx) | its bytes: an MS-NRBF serialization header, version 1.0, then the class record of a `List<Int32>`; told before the file is decoded as text |
14//! | [KML](crate::kml) | its root element is `kml`, after any XML declaration and comments |
15//! | [GPX](crate::gpx) | its root element is `gpx`, after any XML declaration and comments |
16//! | [NMEA 0183](crate::nmea) | at least 3 of its first 50 lines that aren't blank open with a sentence whose checksum checks out, such as `$GPGGA,…*hh` |
17//! | [Featherweight GPS CSV](crate::fwgps) | the first line opens `UTCTIME,UNIXTIME,` or `TRACKER,DATE,TIME,` and names the latitude and longitude |
18//! | [Featherweight summary CSV](crate::fwsummary) | the first line names `Rocket Name`, and one of the first 200 names `Max Altitude` or `Launch time UTC` |
19//! | [PerfectFlite `.pf2`](crate::perfectflite) | names PerfectFlite, such as `PerfectFlite Pnut`, in a file with no `**!!Data:` line (a `.pfa`'s) |
20//! | [PerfectFlite `.pfa`](crate::perfectflite::read_pfa) | names PerfectFlite, such as `PerfectFlite Alt15K/WD`, and has a `**!!Data:` line |
21//! | [PerfectFlite CSV and text](crate::perfectflite::read_export) | `Time`, `Altitude` and more of an export's names, by commas or tabs; or, with no header row, four tab-separated numbers, the third a temperature ending in `F` or `C`, in either case |
22//! | [AltOS CSV](crate::altos) | starts `#version,`, or opens with `#` comments before a `#version,` or `version,serial,` header; or, a table cut from an export, its first line names `time`, `state` and `state_name` and only AltOS's own columns, and of its first 100 rows one gives a state as AltOS's exports number and name it, and none contradicts them |
23//! | [Raven FIP CSV](crate::raven) | opens with a time column and holds the Raven's `Axial Accel (Gs)` channel |
24//! | [Blue Raven CSV](crate::blueraven) | opens `Year,Month,Day,Time,Flight_Time_(s),Sync,`, or `Flight_Time_(s),Sync,` in a file with no date |
25//! | [RRC3 CSV](crate::rrc3) | `Time`, `Altitude`, `Pressure`, `Velocity`, then any of `Temperature`, `Events`, `Voltages` |
26//! | [AltimeterCloud CSV](crate::altimetercloud) | a header within the first 65 lines whose first name is `Time(ms)`, in any case, and which also names `acceleration_total(mG)` and `tilt` |
27//! | [Entacore AIM CSV](crate::entacore) | the first line starts with a `time` column, names at least two, and names one of the AIM's own channels, such as `Pressure AGL` |
28//! | [AltOS `.eeprom`](crate::altos_eeprom) | a JSON object naming `log_format` and `product`; or, within the first 1,000 lines, a `Config version:` line and a `manufacturer altusmetrum.org` line |
29//! | [Blue Raven USB download](crate::blueraven_usb) | one of the first 1,000 lines opens `@ LOG_HIR` or `@ LOG_LOW` and closes with a CRC that checks |
30//! | [Teensy data logger, tab-separated](crate::teensy) | its first line that isn't blank is a tag, a whole-number clock and values, by tabs, and one of its first 100 is `Alt`, the clock, `P` and a number, `MSL` and a number |
31//! | [Radio packets](crate::packets) | its first line that isn't blank is a `255:…:254` packet, a whole number or `Gain[…]`, and a packet is one of its first 100 |
32//! | [Radio packets in RTF](crate::packets::read_rtf) | an RTF document, one of whose first 100 lines, its markup taken off, is a `255,…,254` packet |
33//! | [Teensy data logger, named fields](crate::teensy::read_named) | its first line that isn't blank states a tag's units, `ICM data in us, …`, and one of its first 100 is a tag, `t`, a clock and name–value pairs, by commas |
34//! | [MARSA download](crate::marsa) | its first line that isn't blank is a `<NAME> value` setting, such as `<BARO_ZERO 0> 790`, and one of its first 200 is `<MARSA VERSION>` and a value |
35//! | [Console capture](crate::capture) | a start marker, such as `----++++//[[( data start )]]\\++++----`, on a line of its own within the first 1,000; refused, naming its blocks, as its records need the caller's layout ([`capture::read`]) |
36//! | [AltOS telemetry](crate::altos_telem) | the first line that isn't blank is `TELEM`, a space, and an even number of hexadecimal digits |
37//! | [AltOS telemetry CSV](crate::altos_telem_csv) | the first line that isn't blank opens `serial,tick,ptype,` |
38//! | [R-DAS text](crate::rdas) | the first line that isn't blank is `*** Configuration ***`, and a `*** Raw data ***` line comes within the first 200 |
39//! | [ARTS2 CSV](crate::arts2) | a first line of `#` and the names `MET Acc Vel iAlt pAlt`, by spaces, tabs or commas, in any case; tried before AltOS's `#` comments |
40//! | [ARTS2 raw CSV](crate::arts2_raw::read_csv) | the first line that isn't blank is `MET,Acc(HI),Acc/Baro(LO),Baro(HI),State`, the names as written |
41//! | [RTx CSV and text](crate::rtx::read_export) | the first line that isn't blank is `UTC Time,Latitude,Longitude,Altitude,Velocity,VDOP,NavStatus,Sats,SOG,COG`, or its tab-separated text file's `UTC`, `Lat`, an empty name, `Lon`, an empty name, `Alt`, `Vel`, `VDOP`, `Nav`, `Sats`, `SOG`, `COG`, the names as written |
42//! | [SillyGoose text](crate::sillygoose) | the first line, or the one after a `CONFIG` line, starts with `timestampMs` and names `pressurePa` and `altitudeM` |
43//! | [Silicdyne Fluctus CSV](crate::fluctus) | a `sep=` line, or none, then a header starting `time` that names `deltaTime` and `baro-altitude` |
44//! | [Eggtimer text](crate::eggtimer::read_text) | an `Eggtimer … Flight Settings` title before an Eggtimer CSV header, within the first 200 lines that aren't blank |
45//! | [Eggtimer CSV](crate::eggtimer) | `T,Alt,` and more of Eggtimer's column names |
46//! | [A table read by its header](crate::generic) | tried last: a header row within the first 64 lines, past blank lines, `#` comments and a `sep=` line, that names a clock with a unit of time, such as `Time (s)` or `timestamp__ms`, followed by a row with a number in the clock's cell |
47//!
48//! Text is read as UTF-8, or as UTF-16 after its byte-order mark ([`decode`]), with any byte-order
49//! mark dropped; a byte that isn't UTF-8 becomes U+FFFD, as a `.pf2`'s comments may be in another
50//! encoding and no reader uses them.
51//!
52//! ```
53//! use hpr_flightdata::{import, log::LogFormat};
54//!
55//! let text = "Time,Altitude,Velocity\n0.00,0,0\n0.05,1,8\n0.10,3,30\n";
56//! assert_eq!(import::detect(text.as_bytes()), Some(LogFormat::PerfectFliteCsv));
57//! let log = import::read(text.as_bytes())?;
58//! assert_eq!(log.channels.len(), 2); // the altitude and the velocity; the time is their clock
59//! # Ok::<(), hpr_flightdata::error::LogError>(())
60//! ```
61
62use std::borrow::Cow;
63
64use crate::error::LogError;
65use crate::log::{FlightLog, LogFormat};
66use crate::{
67    aerospacenu_fcb, aerospacenu_gs, altimax, altimax_als, altimetercloud, altos, altos_eeprom,
68    altos_telem, altos_telem_csv, archive, arts2, arts2_raw, blueraven, blueraven_usb, capture,
69    eggtimer, entacore, entacore_raw, fluctus, fwgps, fwsummary, generic, gpx, kml, marsa, nmea,
70    packets, perfectflite, phone_launch, raven, raven_fipa, rdas, rrc3, rrc3_rff, rtx, sillygoose,
71    teensy, workbook, xls,
72};
73
74/// The formats [`read`] recognizes, in the order it tries them.
75pub const FORMATS: &[LogFormat] = &[
76    LogFormat::RavenFipa,
77    LogFormat::Rrc3Rff,
78    LogFormat::Arts2Odf,
79    LogFormat::RtxRaw,
80    LogFormat::AltimaxAls,
81    LogFormat::EntacoreXtra,
82    LogFormat::EntacoreDump,
83    LogFormat::RadioPacketRtf,
84    LogFormat::EggtimerRtf,
85    LogFormat::AerospaceNuGroundStationText,
86    LogFormat::BlueRavenUsb,
87    LogFormat::TeensyTabs,
88    LogFormat::TeensyNamed,
89    LogFormat::RadioPacketText,
90    LogFormat::AltimaxXls,
91    LogFormat::Marsa,
92    LogFormat::ConsoleCapture,
93    LogFormat::Kml,
94    LogFormat::Gpx,
95    LogFormat::Nmea0183,
96    LogFormat::FeatherweightGpsCsv,
97    LogFormat::FeatherweightSummaryCsv,
98    LogFormat::RdasText,
99    LogFormat::AltosEeprom,
100    LogFormat::AltosTelemetry,
101    LogFormat::AltosTelemetryCsv,
102    LogFormat::Arts2Csv,
103    LogFormat::Arts2RawCsv,
104    LogFormat::RtxCsv,
105    LogFormat::RtxText,
106    LogFormat::PerfectFlitePf2,
107    LogFormat::PerfectFlitePfa,
108    LogFormat::AltosCsv,
109    LogFormat::RavenFipCsv,
110    LogFormat::BlueRavenCsv,
111    LogFormat::Rrc3Csv,
112    LogFormat::AltimeterCloudCsv,
113    LogFormat::EntacoreAimCsv,
114    LogFormat::SillyGooseText,
115    LogFormat::FluctusCsv,
116    LogFormat::AerospaceNuFcbCsv,
117    LogFormat::PhoneLaunchCsv,
118    LogFormat::EggtimerText,
119    LogFormat::EggtimerCsv,
120    LogFormat::PerfectFliteCsv,
121    LogFormat::PerfectFliteText,
122    LogFormat::GenericTable,
123];
124
125/// A file's bytes as text: UTF-8, or UTF-16 if the file opens with UTF-16's byte-order mark, as
126/// some mDACS exports of an RRC3's flight are; any byte-order mark dropped, and a byte, or a pair
127/// of them, that isn't a character replaced by U+FFFD. One such export, among the project's sample
128/// files, opens after its UTF-16 mark with a UTF-8 mark's three bytes, each written as a UTF-16
129/// character (``): they are dropped too, as the mark they are.
130pub fn decode(bytes: &[u8]) -> Cow<'_, str> {
131    let utf16 = |bytes: &[u8], unit: fn([u8; 2]) -> u16| {
132        let (pairs, odd) = bytes.as_chunks::<2>();
133        // An odd byte at the end is half a character.
134        let odd = (!odd.is_empty()).then_some(char::REPLACEMENT_CHARACTER);
135        let text: String = char::decode_utf16(pairs.iter().map(|pair| unit(*pair)))
136            .map(|c| c.unwrap_or(char::REPLACEMENT_CHARACTER))
137            .chain(odd)
138            .collect();
139        Cow::Owned(match text.strip_prefix("\u{ef}\u{bb}\u{bf}") {
140            Some(rest) => rest.to_owned(),
141            None => text,
142        })
143    };
144    if let Some(rest) = bytes.strip_prefix(b"\xff\xfe") {
145        utf16(rest, u16::from_le_bytes)
146    } else if let Some(rest) = bytes.strip_prefix(b"\xfe\xff") {
147        utf16(rest, u16::from_be_bytes)
148    } else {
149        let bytes = bytes.strip_prefix(b"\xef\xbb\xbf").unwrap_or(bytes);
150        String::from_utf8_lossy(bytes)
151    }
152}
153
154/// The format of a log, recognized from its first line that isn't blank; `None` for a layout HPR
155/// Sim doesn't read.
156pub fn detect(bytes: &[u8]) -> Option<LogFormat> {
157    detect_binary(bytes).or_else(|| detect_text(&decode(bytes)))
158}
159
160/// The binary formats, told by their bytes: their text would be mojibake.
161fn detect_binary(bytes: &[u8]) -> Option<LogFormat> {
162    if raven_fipa::recognizes(bytes) {
163        Some(LogFormat::RavenFipa)
164    } else if rrc3_rff::recognizes(bytes) {
165        Some(LogFormat::Rrc3Rff)
166    } else if arts2_raw::recognizes_odf(bytes) {
167        Some(LogFormat::Arts2Odf)
168    } else if rtx::recognizes_raw(bytes) {
169        Some(LogFormat::RtxRaw)
170    } else if altimax_als::recognizes(bytes) {
171        Some(LogFormat::AltimaxAls)
172    } else if entacore_raw::recognizes_xtra(bytes) {
173        Some(LogFormat::EntacoreXtra)
174    } else if entacore_raw::recognizes_dump(bytes) {
175        Some(LogFormat::EntacoreDump)
176    } else {
177        None
178    }
179}
180
181fn detect_text(text: &str) -> Option<LogFormat> {
182    // Lines end in CR, LF or both, as the readers take them.
183    let mut lines = text
184        .split(['\r', '\n'])
185        .map(str::trim)
186        .filter(|line| !line.is_empty());
187    let first = lines.next()?;
188    // An RTF document is told by its opening group: radio packets by a packet in its first lines,
189    // and otherwise an Eggtimer's download.
190    if packets::recognizes_rtf(text) {
191        return Some(LogFormat::RadioPacketRtf);
192    }
193    if eggtimer::recognizes_rtf(text) {
194        return Some(LogFormat::EggtimerRtf);
195    }
196    if aerospacenu_gs::recognizes(text) {
197        return Some(LogFormat::AerospaceNuGroundStationText);
198    }
199    // A Blue Raven's USB download is told by a record whose CRC checks.
200    if blueraven_usb::recognizes(text) {
201        return Some(LogFormat::BlueRavenUsb);
202    }
203    // A Teensy data logger's file by its `Alt` line, or by its units lines.
204    if teensy::recognizes_tabs(text) {
205        return Some(LogFormat::TeensyTabs);
206    }
207    if teensy::recognizes_named(text) {
208        return Some(LogFormat::TeensyNamed);
209    }
210    // Radio packets by a `255:…:254` packet in the first lines.
211    if packets::recognizes_text(text) {
212        return Some(LogFormat::RadioPacketText);
213    }
214    // An AltiMAX export by its first five columns.
215    if altimax::recognizes(text) {
216        return Some(LogFormat::AltimaxXls);
217    }
218    // A MARSA download by its settings, which open with `<`, before KML's markup.
219    if marsa::recognizes(text) {
220        return Some(LogFormat::Marsa);
221    }
222    // A console capture is told by its block markers, past the shell's own lines.
223    if capture::recognizes(text) {
224        return Some(LogFormat::ConsoleCapture);
225    }
226    // A GPS log is told by its own marks, which need not be on its first line: an NMEA file may
227    // open with the receiver's power-up noise, a KML or GPX file with an XML declaration.
228    if kml::recognizes(text) {
229        return Some(LogFormat::Kml);
230    }
231    if gpx::recognizes(text) {
232        return Some(LogFormat::Gpx);
233    }
234    if nmea::recognizes(text) {
235        return Some(LogFormat::Nmea0183);
236    }
237    if fwgps::recognizes(text) {
238        return Some(LogFormat::FeatherweightGpsCsv);
239    }
240    if fwsummary::recognizes(text) {
241        return Some(LogFormat::FeatherweightSummaryCsv);
242    }
243    if rdas::recognizes(text) {
244        return Some(LogFormat::RdasText);
245    }
246    if altos_eeprom::recognizes(text) {
247        return Some(LogFormat::AltosEeprom);
248    }
249    if altos_telem::recognizes(text) {
250        return Some(LogFormat::AltosTelemetry);
251    }
252    if altos_telem_csv::recognizes(text) {
253        return Some(LogFormat::AltosTelemetryCsv);
254    }
255    let altos_header =
256        |line: &str| line.starts_with("#version,") || line.starts_with("version,serial,");
257    // ARTS2's header opens with `#`, which would otherwise be taken for AltOS's comments.
258    if arts2::recognizes(text) {
259        return Some(LogFormat::Arts2Csv);
260    }
261    if arts2_raw::recognizes_csv(text) {
262        return Some(LogFormat::Arts2RawCsv);
263    }
264    if let Some(format) = rtx::export_format(text) {
265        return Some(format);
266    }
267    if first.to_ascii_lowercase().contains("perfectflite") {
268        // A `.pfa` names PerfectFlite too, but writes its samples after a `**!!Data:` line, one
269        // value a line.
270        let pfa = text
271            .split(['\r', '\n'])
272            .any(|line| line.trim_start().starts_with("**!!"));
273        Some(if pfa {
274            LogFormat::PerfectFlitePfa
275        } else {
276            LogFormat::PerfectFlitePf2
277        })
278    } else if first.starts_with('#') && !altos_header(first) {
279        // Only AltOS's CSV opens with `#` comments, such as `# Comments` or `# product TeleMetrum`,
280        // before its header.
281        std::iter::once(first)
282            .chain(lines)
283            .find(|line| !line.starts_with('#') || altos_header(line))
284            .filter(|line| altos_header(line))
285            .map(|_| LogFormat::AltosCsv)
286    } else if altos_header(first) || altos::recognizes_table(text) {
287        // A table cut from an AltOS export, AltOS's names with no `version` header, is read by
288        // its states.
289        Some(LogFormat::AltosCsv)
290    } else if first.starts_with("Time") && first.contains("Axial Accel (Gs)") {
291        // The Raven's export opens with a time column; a Blue Raven's names the same channel
292        // further along a header that opens with the date.
293        Some(LogFormat::RavenFipCsv)
294    } else if blueraven::recognizes(text) {
295        Some(LogFormat::BlueRavenCsv)
296    } else if rrc3::recognizes(text) {
297        Some(LogFormat::Rrc3Csv)
298    } else if altimetercloud::recognizes(text) {
299        Some(LogFormat::AltimeterCloudCsv)
300    } else if entacore::recognizes(text) {
301        Some(LogFormat::EntacoreAimCsv)
302    } else if sillygoose::recognizes(text) {
303        Some(LogFormat::SillyGooseText)
304    } else if fluctus::recognizes(text) {
305        Some(LogFormat::FluctusCsv)
306    } else if aerospacenu_fcb::recognizes(text) {
307        Some(LogFormat::AerospaceNuFcbCsv)
308    } else if phone_launch::recognizes(text) {
309        Some(LogFormat::PhoneLaunchCsv)
310    } else if eggtimer::recognizes_text(text) {
311        Some(LogFormat::EggtimerText)
312    } else if eggtimer::recognizes(text) {
313        Some(LogFormat::EggtimerCsv)
314    } else if perfectflite::is_headerless_row(first) {
315        Some(LogFormat::PerfectFliteText)
316    } else {
317        match perfectflite::export_separator(first) {
318            Some(',') => Some(LogFormat::PerfectFliteCsv),
319            Some(_) => Some(LogFormat::PerfectFliteText),
320            None => None,
321        }
322    }
323    // A table read by its header is tried after every other layout, so that it never takes a
324    // file another reader knows.
325    .or_else(|| generic::recognizes(text).then_some(LogFormat::GenericTable))
326}
327
328/// Reads a flight log in any format HPR Sim reads.
329///
330/// # Errors
331///
332/// [`LogError::Archive`] for a zip archive, whose files [`archive::unpack`] takes out;
333/// [`LogError::Workbook`] for an `.xls` worksheet's stream, whose sheet [`xls::read`] reads;
334/// [`LogError::Unrecognized`] for a layout HPR Sim doesn't read, naming those it does, or for a
335/// file that is empty or holds only blank space, saying so; otherwise whatever the format's
336/// reader refuses.
337pub fn read(bytes: &[u8]) -> Result<FlightLog, LogError> {
338    if archive::is_archive(bytes) {
339        return Err(LogError::Archive {
340            message: "the file is a zip archive, which holds files rather than a log, or a format \
341                      built on one, such as a spreadsheet's `.xlsx`. An archive's files are read \
342                      one by one once unpacked (`archive::unpack`). A workbook's sheets are read \
343                      one by one (`workbook::read`)"
344                .to_owned(),
345        });
346    }
347    if xls::recognizes(bytes) {
348        return Err(LogError::Workbook {
349            message: "the file is an Excel `.xls` worksheet, which holds a sheet of cells rather \
350                      than a log. Its sheet is read once written out as text (`xls::read`)"
351                .to_owned(),
352        });
353    }
354    // A binary file isn't decoded as text: its bytes are the reader's.
355    let binary = detect_binary(bytes);
356    let text = if binary.is_some() {
357        Cow::Borrowed("")
358    } else {
359        decode(bytes)
360    };
361    match binary.or_else(|| detect_text(&text)) {
362        Some(LogFormat::PerfectFlitePf2) => perfectflite::read(&text),
363        Some(LogFormat::PerfectFlitePfa) => perfectflite::read_pfa(&text),
364        Some(LogFormat::PerfectFliteCsv | LogFormat::PerfectFliteText) => {
365            perfectflite::read_export(&text)
366        }
367        Some(LogFormat::AltosCsv) => altos::read(&text),
368        Some(LogFormat::RavenFipCsv) => raven::read(&text),
369        Some(LogFormat::BlueRavenCsv) => blueraven::read(&text),
370        Some(LogFormat::BlueRavenUsb) => blueraven_usb::read(&text),
371        Some(LogFormat::TeensyTabs) => teensy::read(&text),
372        Some(LogFormat::TeensyNamed) => teensy::read_named(&text),
373        Some(LogFormat::RadioPacketText) => packets::read(&text),
374        Some(LogFormat::RadioPacketRtf) => packets::read_rtf(&text),
375        Some(LogFormat::AltimaxXls) => altimax::read(&text),
376        Some(LogFormat::Marsa) => marsa::read(&text),
377        Some(LogFormat::Rrc3Csv) => rrc3::read(&text),
378        Some(LogFormat::EggtimerCsv) => eggtimer::read(&text),
379        Some(LogFormat::EggtimerText) => eggtimer::read_text(&text),
380        Some(LogFormat::AltimeterCloudCsv) => altimetercloud::read(&text),
381        Some(LogFormat::EntacoreAimCsv) => entacore::read(&text),
382        Some(LogFormat::SillyGooseText) => sillygoose::read(&text),
383        Some(LogFormat::FluctusCsv) => fluctus::read(&text),
384        Some(LogFormat::Arts2Csv) => arts2::read(&text),
385        Some(LogFormat::Arts2RawCsv) => arts2_raw::read_csv(&text),
386        Some(LogFormat::FeatherweightGpsCsv) => fwgps::read(&text),
387        Some(LogFormat::Kml) => kml::read(&text),
388        Some(LogFormat::Gpx) => gpx::read(&text),
389        Some(LogFormat::Nmea0183) => nmea::read(&text),
390        Some(LogFormat::AerospaceNuFcbCsv) => aerospacenu_fcb::read(&text),
391        Some(LogFormat::AerospaceNuGroundStationText) => aerospacenu_gs::read(&text),
392        Some(LogFormat::PhoneLaunchCsv) => phone_launch::read(&text),
393        Some(LogFormat::EggtimerRtf) => eggtimer::read_rtf(&text),
394        Some(LogFormat::RavenFipa) => raven_fipa::read(bytes),
395        Some(LogFormat::Rrc3Rff) => rrc3_rff::read(bytes),
396        Some(LogFormat::Arts2Odf) => arts2_raw::read_odf(bytes),
397        Some(LogFormat::RtxRaw) => rtx::read_raw(bytes),
398        Some(LogFormat::AltimaxAls) => altimax_als::read(bytes),
399        Some(LogFormat::EntacoreXtra) => entacore_raw::read_xtra(bytes),
400        Some(LogFormat::EntacoreDump) => entacore_raw::read_dump_one(bytes),
401        Some(LogFormat::RtxCsv | LogFormat::RtxText) => rtx::read_export(&text),
402        Some(LogFormat::FeatherweightSummaryCsv) => fwsummary::read(&text),
403        Some(LogFormat::RdasText) => rdas::read(&text),
404        Some(LogFormat::AltosTelemetry) => altos_telem::read(&text),
405        Some(LogFormat::AltosTelemetryCsv) => altos_telem_csv::read(&text),
406        Some(LogFormat::AltosEeprom) => altos_eeprom::read(&text),
407        Some(LogFormat::GenericTable) => generic::read(&text),
408        // A capture states no layout for its records: the caller's is needed.
409        Some(LogFormat::ConsoleCapture) => Err(capture::needs_a_layout(&text)),
410        // Never recognized: a file of records has no marks of its own.
411        Some(LogFormat::BinaryRecords) => Err(LogError::Layout {
412            message: "a file of binary records is read by a layout the caller states \
413                      (`records::read`)"
414                .to_owned(),
415        }),
416        // An empty file, or one of blank space only, names no layout, so say that rather than
417        // list every layout it isn't.
418        None if bytes.iter().all(u8::is_ascii_whitespace) => Err(LogError::Unrecognized {
419            message: if bytes.is_empty() {
420                "the file is empty".to_owned()
421            } else {
422                "the file holds only blank space".to_owned()
423            },
424        }),
425        None => {
426            let known: Vec<&str> = FORMATS.iter().map(|format| format.name()).collect();
427            Err(LogError::Unrecognized {
428                message: format!(
429                    "the file is in none of the layouts HPR Sim reads so far: {}",
430                    known.join(", ")
431                ),
432            })
433        }
434    }
435}
436
437/// Reads one record of a file that may hold several: the sheet `sheet` of a spreadsheet's workbook
438/// (`.xlsx` by [`workbook::read`], `.xls` by [`xls::read`]), each sheet read as a file of its own,
439/// or the recording `recording` of an Entacore AIM raw dump ([`entacore_raw::read_dump`]), each
440/// counted from 0. With no choice, a workbook's one sheet, or of several the one that reads as a
441/// log, or the dump's one recording. Any other file is read as [`read`] reads it, and takes
442/// neither choice.
443///
444/// ```
445/// use hpr_flightdata::import;
446///
447/// let csv = b"Time (s),Baro Alt AGL (m)\n0,0\n0.05,0.2\n";
448/// assert_eq!(import::read_one(csv, None, None)?, import::read(csv)?);
449/// assert!(import::read_one(csv, Some(0), None).is_err());
450/// # Ok::<(), hpr_flightdata::error::LogError>(())
451/// ```
452///
453/// # Errors
454///
455/// [`LogError::Choice`] for a choice the file doesn't take or doesn't hold, and for a workbook or
456/// a dump read with none that holds no one record: of several sheets, more than one that reads as
457/// a log, or none, or several recordings; the chosen sheet's, or the one sheet's, own refusal; a
458/// workbook's own refusal, as [`workbook::read`]'s or [`xls::read`]'s; otherwise as [`read`].
459pub fn read_one(
460    bytes: &[u8],
461    sheet: Option<usize>,
462    recording: Option<usize>,
463) -> Result<FlightLog, LogError> {
464    let choice = |message: String| Err(LogError::Choice { message });
465    let sheets = if archive::is_archive(bytes) {
466        match workbook::read(bytes) {
467            Ok(sheets) => Some(sheets),
468            // A zip archive that isn't a workbook is refused as an archive; a workbook that
469            // fails is refused for its own fault.
470            Err(LogError::NotThisFormat { .. }) => return read(bytes),
471            Err(error) => return Err(error),
472        }
473    } else if xls::recognizes(bytes) {
474        Some(xls::read(bytes)?)
475    } else {
476        None
477    };
478    if let Some(sheets) = sheets {
479        if recording.is_some() {
480            return choice(
481                "the file is a spreadsheet's workbook, which holds sheets, not recordings: \
482                 choose a sheet"
483                    .to_owned(),
484            );
485        }
486        let count = sheets.len();
487        if let Some(index) = sheet {
488            return match sheets.into_iter().nth(index) {
489                Some(chosen) => chosen.log,
490                None => choice(format!(
491                    "the workbook has {count} {}, numbered from 0: it has no sheet {index}",
492                    if count == 1 { "sheet" } else { "sheets" }
493                )),
494            };
495        }
496        // A workbook of one sheet is read as that sheet, its refusal its own.
497        if count == 1 {
498            return sheets
499                .into_iter()
500                .next()
501                .map_or(Err(LogError::NoData { format: "workbook" }), |one| one.log);
502        }
503        let mut reading: Vec<(usize, workbook::SheetLog)> = sheets
504            .into_iter()
505            .enumerate()
506            .filter(|(_, sheet)| sheet.log.is_ok())
507            .collect();
508        return match reading.len() {
509            // Invariant: the one sheet's log is the `Ok` the filter kept.
510            1 => reading
511                .pop()
512                .map_or(Err(LogError::NoData { format: "workbook" }), |(_, one)| {
513                    one.log
514                }),
515            0 => choice(format!(
516                "none of the workbook's {count} sheets reads as a log: a table on one is read by \
517                 a column mapping, with its sheet chosen"
518            )),
519            _ => {
520                let named = workbook::listed(
521                    reading
522                        .iter()
523                        .map(|(index, sheet)| (*index, sheet.name.as_str())),
524                    |index, name| format!("{index} ({name})"),
525                );
526                choice(format!(
527                    "{} of the workbook's {count} sheets read as logs, sheets {named}: choose one",
528                    reading.len(),
529                ))
530            }
531        };
532    }
533    if detect(bytes) == Some(LogFormat::EntacoreDump) {
534        if sheet.is_some() {
535            return choice(
536                "the file is an Entacore AIM raw dump, which holds recordings, not sheets: \
537                 choose a recording"
538                    .to_owned(),
539            );
540        }
541        let mut recordings = entacore_raw::read_dump(bytes)?;
542        let count = recordings.len();
543        return match recording {
544            Some(index) if index < count => Ok(recordings.swap_remove(index)),
545            Some(index) => choice(format!(
546                "the dump holds {count} recordings, numbered from 0: it has no recording {index}"
547            )),
548            // Invariant: `read_dump` returns a recording or an error.
549            None if count == 1 => recordings.pop().ok_or(LogError::NoData {
550                format: "Entacore AIM raw dump",
551            }),
552            None => choice(format!(
553                "the dump holds {count} recordings: choose one, numbered from 0"
554            )),
555        };
556    }
557    if sheet.is_some() || recording.is_some() {
558        return choice(
559            "the file holds one record, not a workbook's sheets or a dump's recordings: choose \
560             neither"
561                .to_owned(),
562        );
563    }
564    read(bytes)
565}
566
567#[cfg(test)]
568mod tests {
569    use super::*;
570
571    #[test]
572    fn an_archive_is_refused_as_one_to_unpack() {
573        for bytes in [&b"PK\x03\x04 the rest"[..], b"PK\x05\x06"] {
574            match read(bytes) {
575                Err(LogError::Archive { message }) => {
576                    assert!(message.contains("archive::unpack"), "{message}");
577                }
578                other => panic!("expected an archive refusal, got {other:?}"),
579            }
580        }
581    }
582
583    #[test]
584    fn each_format_is_recognized_by_its_marks() {
585        let cases = [
586            ("PerfectFlite Pnut\n", Some(LogFormat::PerfectFlitePf2)),
587            (
588                "\u{feff}\n\n#version,serial,flight,time\n",
589                Some(LogFormat::AltosCsv),
590            ),
591            (
592                "# Altus Metrum flight log\n# serial 1\nversion,serial,flight,time\n",
593                Some(LogFormat::AltosCsv),
594            ),
595            ("#Component=Raven\n", None),
596            ("# MET Acc Vel iAlt pAlt\n", Some(LogFormat::Arts2Csv)),
597            (
598                "MET,Acc(HI),Acc/Baro(LO),Baro(HI),State\n",
599                Some(LogFormat::Arts2RawCsv),
600            ),
601            ("MET,Acc,Baro,State\n", None),
602            ("\x09\x00\x00\x00Ozark.odf", Some(LogFormat::Arts2Odf)),
603            ("\x09\x00\x00\x00Ozark.od", None),
604            (
605                "UTC Time,Latitude,Longitude,Altitude,Velocity,VDOP,NavStatus,Sats,SOG,COG\r\n",
606                Some(LogFormat::RtxCsv),
607            ),
608            (
609                "\u{feff}UTC\tLat\t\tLon\t\tAlt\tVel\tVDOP\tNav\tSats\tSOG\tCOG\r\n",
610                Some(LogFormat::RtxText),
611            ),
612            ("UTC\tLat\tLon\tAlt\tVel\tVDOP\tNav\tSats\tSOG\tCOG\n", None),
613            ("UTC Time,Latitude,Longitude,Altitude\n", None),
614            (
615                "sep=;\ntime (ms);deltaTime (ms);status;baro-altitude (m)\n",
616                Some(LogFormat::FluctusCsv),
617            ),
618            ("T;Alt;Veloc;FAlt\n", Some(LogFormat::EggtimerCsv)),
619            ("0.00\t3\t71.5F\t9.2\n", Some(LogFormat::PerfectFliteText)),
620            ("0.00\t3\t21.9C\t9.2\n", Some(LogFormat::PerfectFliteText)),
621            ("0.00\t3\t71.5\t9.2\n", None),
622            ("0.00\t3\t71.5F\t9.2\t1\n", None),
623            ("0.00\t3\tF\t9.2\n", None),
624            (
625                "Time,Altitude,Temp,Voltage\n",
626                Some(LogFormat::PerfectFliteCsv),
627            ),
628            (
629                "Flight_Time_(s),Sync,Gyro_X\n",
630                Some(LogFormat::BlueRavenCsv),
631            ),
632            ("Flight_Time_(s),Sync\n", None),
633            ("Sync,Flight_Time_(s),Gyro_X\n", None),
634            (
635                "timestampMs\tpressurePa\ttempK\taltitudeM\n",
636                Some(LogFormat::SillyGooseText),
637            ),
638            (
639                "#foo\n#version,serial,flight,time\n",
640                Some(LogFormat::AltosCsv),
641            ),
642            ("# a note\nTime,Altitude,Velocity\n", None),
643            (
644                "PerfectFlite Alt15K/WD\nApogee: 900\n**!!Data:\n1200\n",
645                Some(LogFormat::PerfectFlitePfa),
646            ),
647            (
648                "Year,Month,Day,Time,Flight_Time_(s),Axial Accel (Gs)\n",
649                None,
650            ),
651            (
652                "Time,Altitude,Velocity\r0.00,0,0\r0.05,1,8\r",
653                Some(LogFormat::PerfectFliteCsv),
654            ),
655            (
656                "Time@Axial Accel (Gs),Axial Accel (Gs),bILBA\n",
657                Some(LogFormat::RavenFipCsv),
658            ),
659            (
660                "Time,LiftOff,Axial Accel (Gs),Baro (Atm)\n",
661                Some(LogFormat::RavenFipCsv),
662            ),
663            (
664                "Time, Altitude, Velocity\n",
665                Some(LogFormat::PerfectFliteCsv),
666            ),
667            (
668                "Time\tAltitude\tTemp.\tVoltage\n",
669                Some(LogFormat::PerfectFliteText),
670            ),
671            // A team's own export in feet: the generic reader's, M7.1c.
672            ("time_s,altitude_ft,temperature,voltage\n", None),
673            ("Time,Pressure\n", None),
674            ("time,altitude\n", None),
675            ("Time,Altitude\n", None),
676            (
677                "Time,Altitude,Pressure,Velocity,Temperature,Events,Voltages\n",
678                Some(LogFormat::Rrc3Csv),
679            ),
680            (
681                "T,Alt,Veloc,FAlt,FVeloc,LDA,LowV,Apogee,N-O,Drogue,Main\r\r\n",
682                Some(LogFormat::EggtimerCsv),
683            ),
684            (
685                "Year,Month,Day,Time,Flight_Time_(s),Sync,Gyro_X\n",
686                Some(LogFormat::BlueRavenCsv),
687            ),
688            (
689                "<?xml version=\"1.0\"?>\n<!-- a track -->\n<kml xmlns=\"http://www.opengis.net/kml/2.2\"></kml>\n",
690                Some(LogFormat::Kml),
691            ),
692            (
693                "<?xml version=\"1.0\"?>\n<gpx></gpx>\n",
694                Some(LogFormat::Gpx),
695            ),
696            (
697                "\u{fffd}\u{fffd}x\r\n\
698                 $GPGGA,120000.00,4807.038,N,01131.000,E,1,08,0.9,545.4,M,46.9,M,,*67\r\n\
699                 $GPRMC,120001.00,A,4807.038,N,01131.000,E,022.4,084.4,230394,003.1,W*4B\r\n\
700                 $GPGSA,A,3,04,05,,09,12,,,24,,,,,2.5,1.3,2.1*39\r\n",
701                Some(LogFormat::Nmea0183),
702            ),
703            // A sentence quoted inside another log's line isn't NMEA.
704            (
705                "t=1 rx $GPGGA,120000.00,4807.038,N,01131.000,E,1,08,0.9,545.4,M,46.9,M,,*67\n",
706                None,
707            ),
708            (
709                "UTCTIME,UNIXTIME,ALT,LAT,LON,#SATS,FIX,HORZV,VERTV,HEAD,FLAGS\n",
710                Some(LogFormat::FeatherweightGpsCsv),
711            ),
712            (
713                "TRACKER,DATE,TIME,LAT,LON,ALT,FIX,HORZV,VERTV,HEAD,FLAGS,#TOT\r\n",
714                Some(LogFormat::FeatherweightGpsCsv),
715            ),
716            ("TRACKER,DATE,TIME,RSSI\n", None),
717            (
718                "{\"log_format\": 14, \"product\": \"EasyMini-v2.0\"}\n46 00",
719                Some(LogFormat::AltosEeprom),
720            ),
721            ("{\"product\": \"EasyMini-v2.0\"}\n", None),
722            (
723                "~\nConfig version: 1.27\nmanufacturer     altusmetrum.org\nA 1 00 00\n",
724                Some(LogFormat::AltosEeprom),
725            ),
726            ("Config version: 1.27\nA 1 00 00\n", None),
727            ("", None),
728        ];
729        for (text, format) in cases {
730            assert_eq!(detect(text.as_bytes()), format, "{text:?}");
731        }
732    }
733
734    #[test]
735    fn utf16_is_read_by_its_byte_order_mark() {
736        let text = "Time\tAltitude é\n";
737        let mut le = vec![0xff, 0xfe];
738        let mut be = vec![0xfe, 0xff];
739        for unit in text.encode_utf16() {
740            le.extend(unit.to_le_bytes());
741            be.extend(unit.to_be_bytes());
742        }
743        assert_eq!(decode(&le), text);
744        assert_eq!(decode(&be), text);
745        // An odd byte at the end, and half a surrogate pair, are each one replaced character.
746        le.push(b'x');
747        assert_eq!(decode(&le), format!("{text}\u{fffd}"));
748        assert_eq!(decode(&[0xff, 0xfe, 0x3d, 0xd8]), "\u{fffd}");
749        assert_eq!(decode(b"\xef\xbb\xbfa\xff"), "a\u{fffd}");
750
751        // A UTF-8 mark's three bytes written as UTF-16 units after the UTF-16 mark are dropped,
752        // once, and only at the start.
753        let mut inner = vec![0xff, 0xfe];
754        for unit in "\u{ef}\u{bb}\u{bf}Time\u{ef}\u{bb}\u{bf}".encode_utf16() {
755            inner.extend(unit.to_le_bytes());
756        }
757        assert_eq!(decode(&inner), "Time\u{ef}\u{bb}\u{bf}");
758    }
759
760    #[test]
761    fn a_layout_no_reader_knows_is_refused_naming_those_that_exist() {
762        let error = read(b"Time,Pressure\n0,101325\n").unwrap_err();
763        let LogError::Unrecognized { message } = &error else {
764            panic!("refused for another reason: {error:?}");
765        };
766        for format in FORMATS {
767            assert!(message.contains(format.name()), "{message}");
768        }
769    }
770
771    #[test]
772    fn an_empty_file_is_refused_as_empty_not_as_every_layout() {
773        for (bytes, said) in [
774            (&b""[..], "the file is empty"),
775            (&b"\n \r\n\t\n"[..], "the file holds only blank space"),
776        ] {
777            let error = read(bytes).unwrap_err();
778            let LogError::Unrecognized { message } = &error else {
779                panic!("refused for another reason: {error:?}");
780            };
781            assert_eq!(message, said);
782        }
783    }
784}