rtcm3-cli 0.1.0

Command-line decoder for RTCM3 GNSS RTK correction streams, built on rtcm3
//! Command-line demo decoder for `rtcm3`.
//!
//! Reads a raw RTCM3 byte stream from a file (or stdin) and prints each
//! decoded message. RTCM3 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 rtcm3::error::FrameError;
use rtcm3::{Frame, Rtcm3Message};

mod print;

/// Decode an RTCM3 byte stream from a file or stdin.
#[derive(Parser)]
#[command(version)]
struct Args {
    /// Path to a file of raw RTCM3 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 Rtcm3Message::decode(frame.payload()) {
                    Ok(message) => {
                        decoded += 1;
                        if !args.stats {
                            print::print_message(&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 preamble, reserved bits set, bad
            // checksum) means this byte isn't the start of a real frame;
            // resync by advancing one byte, the same recovery a streaming
            // RTCM3 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)
}