mavwire-cli 0.1.0

Command-line decoder for MAVLink v1/v2 telemetry streams, built on mavwire
//! Command-line demo decoder for `mavwire`.
//!
//! Reads a raw `MAVLink` v1/v2 byte stream from a file (or stdin) and
//! prints each decoded message. `MAVLink` is a binary stream that may
//! contain several frames back-to-back (or garbage between them), so this
//! walks the buffer frame by frame, resyncing one byte at a time on
//! anything that doesn't parse.

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;

/// Decode a `MAVLink` v1/v2 byte stream from a file or stdin.
#[derive(Parser)]
#[command(version)]
struct Args {
    /// Path to a file of raw `MAVLink` frame bytes; reads stdin if omitted.
    file: Option<PathBuf>,

    /// Print a summary count instead of each decoded message.
    #[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})");
                    }
                }
            }
            // Not enough bytes left for even a minimal header/frame: stop
            // rather than resync, since more data might still be coming
            // for that trailing partial frame.
            Err(FrameError::TooShort { .. }) => break,
            // Anything else (bad magic byte, unsupported signing) means
            // this byte isn't the start of a real frame; resync by
            // advancing one byte, the same recovery a streaming MAVLink
            // parser uses on desync.
            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)
}