use std::fs::File;
use std::io::{self, Read};
use std::path::PathBuf;
use anyhow::{Context, Result};
use clap::Parser;
use mavwire::error::FrameError;
use mavwire::{Frame, MavMessage};
mod print;
#[derive(Parser)]
#[command(version)]
struct Args {
file: Option<PathBuf>,
#[arg(long)]
stats: bool,
}
fn main() -> Result<()> {
let args = Args::parse();
let data = read_all(args.file.as_deref())?;
let mut cursor = 0usize;
let mut decoded = 0u64;
let mut skipped = 0u64;
while cursor < data.len() {
match Frame::parse(&data[cursor..]) {
Ok(frame) => {
cursor += frame.byte_len();
match MavMessage::decode(&frame) {
Ok(message) => {
decoded += 1;
if !args.stats {
print::print_message(&frame, &message);
}
}
Err(err) => {
skipped += 1;
eprintln!("skipping frame ({err})");
}
}
}
Err(FrameError::TooShort { .. }) => break,
Err(err) => {
skipped += 1;
eprintln!("skipping byte at offset {cursor} ({err})");
cursor += 1;
}
}
}
if args.stats {
println!("decoded: {decoded}, skipped: {skipped}");
}
Ok(())
}
fn read_all(path: Option<&std::path::Path>) -> Result<Vec<u8>> {
let mut buf = Vec::new();
match path {
Some(path) => {
File::open(path)
.with_context(|| format!("opening {}", path.display()))?
.read_to_end(&mut buf)
.with_context(|| format!("reading {}", path.display()))?;
}
None => {
io::stdin().read_to_end(&mut buf).context("reading stdin")?;
}
}
Ok(buf)
}