-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathexport.rs
More file actions
456 lines (394 loc) · 15.7 KB
/
export.rs
File metadata and controls
456 lines (394 loc) · 15.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
//! Export functionality for BBL data
//!
//! Contains functions for exporting parsed BBL data to various formats
//! including CSV, GPX, and Event files.
use crate::conversion::*;
use crate::types::*;
use anyhow::{Context, Result};
use std::collections::HashMap;
use std::fs::File;
use std::io::{BufWriter, Write};
use std::path::Path;
#[cfg(feature = "serde")]
use serde::{Deserialize, Serialize};
/// Export options for various output formats
#[derive(Debug, Clone, Default)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
pub struct ExportOptions {
pub csv: bool,
pub gpx: bool,
pub event: bool,
pub output_dir: Option<String>,
pub force_export: bool,
}
/// Extract the base filename from an input path with consistent fallback.
/// Used by all export functions and path computation helpers to ensure
/// consistent naming across CSV, GPX, and event exports.
///
/// Always returns "blackbox" as fallback for missing or non-UTF-8 filenames,
/// ensuring compute_export_paths() predictions match actual export filenames.
fn extract_base_name(input_path: &Path) -> &str {
input_path
.file_stem()
.and_then(|s| s.to_str())
.unwrap_or("blackbox")
}
/// Helper to compute export file paths with consistent naming across all export types.
/// Ensures CLI status messages match actual filenames written by export functions.
///
/// # Arguments
/// * `input_path` - Path to the input BBL file (used to extract base filename)
/// * `export_options` - Export configuration with optional output directory
/// * `log_number` - 1-based log number (for .NN suffix when multiple logs)
/// * `total_logs` - Total number of logs in the file
///
/// # Returns
/// Tuple of (csv_path, headers_path, gpx_path, event_path) using consistent naming
pub fn compute_export_paths(
input_path: &Path,
export_options: &ExportOptions,
log_number: usize,
total_logs: usize,
) -> (
std::path::PathBuf,
std::path::PathBuf,
std::path::PathBuf,
std::path::PathBuf,
) {
let base_name = extract_base_name(input_path);
let output_dir = if let Some(ref dir) = export_options.output_dir {
std::path::Path::new(dir)
} else {
input_path.parent().unwrap_or(std::path::Path::new("."))
};
let log_suffix = if total_logs > 1 {
format!(".{:02}", log_number)
} else {
String::new()
};
let csv_path = output_dir.join(format!("{}{}.csv", base_name, log_suffix));
let headers_path = output_dir.join(format!("{}{}.headers.csv", base_name, log_suffix));
let gpx_path = output_dir.join(format!("{}{}.gps.gpx", base_name, log_suffix));
let event_path = output_dir.join(format!("{}{}.event", base_name, log_suffix));
(csv_path, headers_path, gpx_path, event_path)
}
/// Pre-computed CSV field mapping for performance
#[derive(Debug)]
struct CsvFieldMap {
field_name_to_lookup: Vec<(String, String)>, // (csv_name, lookup_name)
}
impl CsvFieldMap {
fn new(header: &BBLHeader) -> Self {
let mut field_name_to_lookup = Vec::new();
// I frame fields
for field_name in &header.i_frame_def.field_names {
let trimmed = field_name.trim();
let csv_name = if trimmed == "time" {
"time (us)".to_string()
} else if trimmed == "vbatLatest" {
"vbatLatest (V)".to_string()
} else if trimmed == "amperageLatest" {
"amperageLatest (A)".to_string()
} else {
trimmed.to_string()
};
field_name_to_lookup.push((csv_name.clone(), trimmed.to_string()));
}
// Add computed fields IMMEDIATELY after I frame fields (like blackbox_decode does)
if field_name_to_lookup
.iter()
.any(|(_, lookup)| lookup == "amperageLatest")
{
field_name_to_lookup.push(("energyCumulative (mAh)".to_string(), "".to_string()));
}
// S frame fields (with flag formatting)
for field_name in &header.s_frame_def.field_names {
let trimmed = field_name.trim();
if trimmed == "time" {
continue;
} // Skip duplicate
let csv_name = if trimmed.contains("Flag") || trimmed == "failsafePhase" {
format!("{trimmed} (flags)")
} else {
trimmed.to_string()
};
field_name_to_lookup.push((csv_name.clone(), trimmed.to_string()));
}
Self {
field_name_to_lookup,
}
}
}
/// Export BBL log to CSV format
pub fn export_to_csv(
log: &BBLLog,
input_path: &Path,
export_options: &ExportOptions,
) -> Result<()> {
let base_name = extract_base_name(input_path);
let output_dir = if let Some(ref dir) = export_options.output_dir {
Path::new(dir)
} else {
input_path.parent().unwrap_or(Path::new("."))
};
// Create output directory if it doesn't exist
if !output_dir.exists() {
std::fs::create_dir_all(output_dir)?;
}
let log_suffix = if log.total_logs > 1 {
format!(".{:02}", log.log_number)
} else {
"".to_string()
};
// Export plaintext headers to separate CSV
let header_csv_path = output_dir.join(format!("{base_name}{log_suffix}.headers.csv"));
export_headers_to_csv(&log.header, &header_csv_path)?;
// Export flight data (I, P, S frames) to main CSV
let flight_csv_path = output_dir.join(format!("{base_name}{log_suffix}.csv"));
export_flight_data_to_csv(log, &flight_csv_path)?;
Ok(())
}
/// Export headers to CSV file
fn export_headers_to_csv(header: &BBLHeader, output_path: &Path) -> Result<()> {
let file = File::create(output_path)
.with_context(|| format!("Failed to create headers CSV file: {output_path:?}"))?;
let mut writer = BufWriter::new(file);
// Write CSV header
writeln!(writer, "Field,Value")?;
// Parse and write all header lines
for header_line in &header.all_headers {
if let Some(content) = header_line.strip_prefix("H ") {
// Remove "H " prefix and find the colon separator
if let Some(colon_pos) = content.find(':') {
let field_name = content[..colon_pos].trim();
let field_value = content[colon_pos + 1..].trim();
// Escape commas in values by wrapping in quotes
let escaped_value = if field_value.contains(',') {
format!("\"{}\"", field_value.replace('"', "\"\""))
} else {
field_value.to_string()
};
writeln!(writer, "{field_name},{escaped_value}")?;
}
}
}
writer
.flush()
.with_context(|| format!("Failed to flush headers CSV file: {output_path:?}"))?;
Ok(())
}
/// Export flight data to CSV file
fn export_flight_data_to_csv(log: &BBLLog, output_path: &Path) -> Result<()> {
let file = File::create(output_path)
.with_context(|| format!("Failed to create flight data CSV file: {output_path:?}"))?;
let mut writer = BufWriter::new(file);
// Build optimized field mapping
let csv_map = CsvFieldMap::new(&log.header);
let field_names: Vec<String> = csv_map
.field_name_to_lookup
.iter()
.map(|(csv_name, _)| csv_name.clone())
.collect();
// Collect all I and P frames in chronological order
let mut all_frames: Vec<(u64, char, &DecodedFrame)> = Vec::new();
// Use log.frames which contains all parsed frames
for frame in &log.frames {
if frame.frame_type == 'I' || frame.frame_type == 'P' {
all_frames.push((frame.timestamp_us, frame.frame_type, frame));
}
}
// Sort by timestamp
all_frames.sort_by_key(|(timestamp, _, _)| *timestamp);
if all_frames.is_empty() {
return Ok(()); // No data to export
}
// Write field names header
for (i, field_name) in field_names.iter().enumerate() {
if i > 0 {
write!(writer, ", ")?;
}
write!(writer, "{field_name}")?;
}
writeln!(writer)?;
// Optimized CSV writing with pre-computed mappings
let mut cumulative_energy_mah = 0f32;
let mut last_timestamp_us = 0u64;
let mut latest_s_frame_data: HashMap<String, i32> = HashMap::new();
for (output_iteration, (timestamp, frame_type, frame)) in all_frames.iter().enumerate() {
// Update latest S-frame data if this is an S frame
if *frame_type == 'S' {
for (key, value) in &frame.data {
latest_s_frame_data.insert(key.clone(), *value);
}
}
// Calculate energyCumulative for this frame
if let Some(current_raw) = frame.data.get("amperageLatest").copied() {
if last_timestamp_us > 0 && *timestamp > last_timestamp_us {
let time_delta_hours = (*timestamp - last_timestamp_us) as f32 / 3_600_000_000.0;
let current_amps = convert_amperage_to_amps(current_raw);
cumulative_energy_mah += current_amps * time_delta_hours * 1000.0;
}
last_timestamp_us = *timestamp;
}
// Write data row using optimized field mapping
for (i, (csv_name, lookup_name)) in csv_map.field_name_to_lookup.iter().enumerate() {
if i > 0 {
write!(writer, ", ")?;
}
// Fast path for special fields using pre-computed indices
if csv_name == "time (us)" {
write!(writer, "{}", *timestamp as i32)?;
} else if csv_name == "loopIteration" {
let value = frame
.data
.get("loopIteration")
.copied()
.unwrap_or(output_iteration as i32);
write!(writer, "{value:4}")?;
} else if csv_name == "vbatLatest (V)" {
let raw_value = frame.data.get("vbatLatest").copied().unwrap_or(0);
write!(
writer,
"{:4.1}",
convert_vbat_to_volts(raw_value, &log.header.firmware_revision)
)?;
} else if csv_name == "amperageLatest (A)" {
let raw_value = frame.data.get("amperageLatest").copied().unwrap_or(0);
write!(writer, "{:4.2}", convert_amperage_to_amps(raw_value))?;
} else if csv_name == "energyCumulative (mAh)" {
write!(writer, "{:5}", cumulative_energy_mah as i32)?;
} else if csv_name.ends_with(" (flags)") {
// Handle flag fields - output text values like blackbox_decode.c
let raw_value = frame
.data
.get(lookup_name)
.copied()
.or_else(|| latest_s_frame_data.get(lookup_name).copied())
.unwrap_or(0);
let formatted = if lookup_name == "flightModeFlags" {
format_flight_mode_flags(raw_value)
} else if lookup_name == "stateFlags" {
format_state_flags(raw_value)
} else if lookup_name == "failsafePhase" {
format_failsafe_phase(raw_value)
} else {
raw_value.to_string()
};
write!(writer, "{formatted}")?;
} else {
// Regular field lookup with S-frame fallback
let value = frame
.data
.get(lookup_name)
.copied()
.or_else(|| latest_s_frame_data.get(lookup_name).copied())
.unwrap_or(0);
write!(writer, "{value:4}")?;
}
}
writeln!(writer)?;
}
writer
.flush()
.with_context(|| format!("Failed to flush flight data CSV file: {output_path:?}"))?;
Ok(())
}
/// Export GPS data to GPX format
///
/// # Arguments
/// * `input_path` - Path to the input BBL file (used for output naming)
/// * `log_index` - Index of the current log (0-based)
/// * `total_logs` - Total number of logs in the file
/// * `gps_coordinates` - GPS coordinate data to export
/// * `_home_coordinates` - Home coordinates (reserved for future use)
/// * `export_options` - Export configuration options
/// * `log_start_datetime` - Optional log start datetime from header for accurate timestamps
///
/// # Performance Notes
/// For very large GPS traces, the `log_start_datetime` is parsed via `generate_gpx_timestamp()`
/// on each trackpoint. Future optimization: consider caching the parsed base epoch once per log
/// to avoid repeated parsing overhead when exporting thousands of GPS points.
pub fn export_to_gpx(
input_path: &Path,
log_index: usize,
total_logs: usize,
gps_coordinates: &[GpsCoordinate],
_home_coordinates: &[GpsHomeCoordinate],
export_options: &ExportOptions,
log_start_datetime: Option<&str>,
) -> Result<()> {
if gps_coordinates.is_empty() {
return Ok(());
}
// Use compute_export_paths to ensure consistent naming with CSV exports
let (_, _, gpx_path, _) =
compute_export_paths(input_path, export_options, log_index + 1, total_logs);
// Create output directory if it doesn't exist (match export_to_csv behavior)
if let Some(parent) = gpx_path.parent() {
if !parent.exists() {
std::fs::create_dir_all(parent)?;
}
}
let mut gpx_file = File::create(&gpx_path)?;
writeln!(gpx_file, r#"<?xml version="1.0" encoding="UTF-8"?>"#)?;
writeln!(
gpx_file,
r#"<gpx creator="BBL Parser (Rust)" version="1.1" xmlns="http://www.topografix.com/GPX/1/1" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.topografix.com/GPX/1/1 http://www.topografix.com/GPX/1/1/gpx.xsd">"#
)?;
writeln!(
gpx_file,
"<metadata><name>Blackbox flight log</name></metadata>"
)?;
writeln!(gpx_file, "<trk><name>Blackbox flight log</name><trkseg>")?;
for coord in gps_coordinates {
// Only include coordinates with sufficient GPS satellite count (minimum 5)
if let Some(num_sats) = coord.num_sats {
if num_sats < 5 {
continue;
}
}
// Generate GPX timestamp from log_start_datetime + frame timestamp
// Following blackbox_decode approach: dateTime + (gpsFrameTime / 1000000)
let timestamp_str = generate_gpx_timestamp(log_start_datetime, coord.timestamp_us);
writeln!(
gpx_file,
r#" <trkpt lat="{:.7}" lon="{:.7}"><ele>{:.2}</ele><time>{}</time></trkpt>"#,
coord.latitude, coord.longitude, coord.altitude, timestamp_str
)?;
}
writeln!(gpx_file, "</trkseg></trk>")?;
writeln!(gpx_file, "</gpx>")?;
Ok(())
}
/// Export event data to file
pub fn export_to_event(
input_path: &Path,
log_index: usize,
total_logs: usize,
event_frames: &[EventFrame],
export_options: &ExportOptions,
) -> Result<()> {
if event_frames.is_empty() {
return Ok(());
}
// Use compute_export_paths to ensure consistent naming with CSV exports
let (_, _, _, event_path) =
compute_export_paths(input_path, export_options, log_index + 1, total_logs);
// Create output directory if it doesn't exist (match export_to_csv behavior)
if let Some(parent) = event_path.parent() {
if !parent.exists() {
std::fs::create_dir_all(parent)?;
}
}
let mut event_file = File::create(&event_path)?;
// Export as JSONL format (individual JSON objects per line) to match blackbox_decode
for event in event_frames.iter() {
writeln!(
event_file,
r#"{{"name":"{}", "time":{}}}"#,
event.event_name.replace('"', "\\\""),
event.timestamp_us
)?;
}
Ok(())
}