mbrtu-cli 0.1.2

Command-line decoder for Modbus RTU frames, built on mbrtu
//! Command-line demo decoder for `mbrtu`.
//!
//! Reads hex-encoded Modbus RTU frames from a file (or stdin), one per
//! line, and prints the decoded PDU for each. Modbus RTU has no preamble
//! or length field of its own - real receivers find frame boundaries by
//! inter-character timing, not by anything encoded in the bytes - so
//! unlike a byte-stream decoder for a preamble-based protocol, this reads
//! one already-delimited frame per line rather than resyncing through a
//! continuous byte stream.
//!
//! Because a request and a response can share the same function code and
//! byte length, direction isn't recoverable from a frame's bytes alone -
//! the caller must say which one it's looking at.

use std::fs::File;
use std::io::{self, BufRead, BufReader};
use std::path::PathBuf;

use anyhow::{Context, Result, bail};
use clap::{Parser, ValueEnum};
use mbrtu::{Frame, ModbusRequest, ModbusResponse};

mod print;

#[derive(Clone, Copy, ValueEnum)]
enum Direction {
    Request,
    Response,
}

/// Decode Modbus RTU hex frames from a file or stdin.
#[derive(Parser)]
#[command(version)]
struct Args {
    /// Whether each frame is a request or a response (the two can't be
    /// told apart from the bytes alone).
    #[arg(long, value_enum)]
    direction: Direction,

    /// Path to a file of hex frames, one per line; reads stdin if
    /// omitted.
    file: Option<PathBuf>,

    /// Print a summary line count instead of each decoded message.
    #[arg(long)]
    stats: bool,
}

fn hex_decode(line: &str) -> Result<Vec<u8>> {
    let line = line.trim();
    if !line.len().is_multiple_of(2) {
        bail!("odd number of hex digits");
    }
    (0..line.len())
        .step_by(2)
        .map(|i| u8::from_str_radix(&line[i..i + 2], 16).context("invalid hex digit"))
        .collect()
}

fn run_requests(lines: impl Iterator<Item = io::Result<String>>, stats: bool) -> Result<()> {
    let mut decoded = 0u64;
    let mut skipped = 0u64;

    for line in lines {
        let line = line.context("reading input line")?;
        if line.trim().is_empty() {
            continue;
        }

        let result = hex_decode(&line).and_then(|bytes| {
            let frame = Frame::parse(&bytes).map_err(anyhow::Error::from)?;
            let request = ModbusRequest::decode(frame.function_code(), frame.data())
                .map_err(anyhow::Error::from)?;
            Ok((frame.address(), request))
        });

        match result {
            Ok((address, request)) => {
                decoded += 1;
                if !stats {
                    print::print_request(address, request);
                }
            }
            Err(err) => {
                skipped += 1;
                eprintln!("skipping line ({err}): {line}");
            }
        }
    }

    if stats {
        println!("decoded: {decoded}, skipped: {skipped}");
    }
    Ok(())
}

fn run_responses(lines: impl Iterator<Item = io::Result<String>>, stats: bool) -> Result<()> {
    let mut decoded = 0u64;
    let mut skipped = 0u64;

    for line in lines {
        let line = line.context("reading input line")?;
        if line.trim().is_empty() {
            continue;
        }

        let result = hex_decode(&line).and_then(|bytes| {
            let frame = Frame::parse_response(&bytes).map_err(anyhow::Error::from)?;
            let response = ModbusResponse::decode(frame.function_code(), frame.data())
                .map_err(anyhow::Error::from)?;
            Ok((frame.address(), response))
        });

        match result {
            Ok((address, response)) => {
                decoded += 1;
                if !stats {
                    print::print_response(address, &response);
                }
            }
            Err(err) => {
                skipped += 1;
                eprintln!("skipping line ({err}): {line}");
            }
        }
    }

    if stats {
        println!("decoded: {decoded}, skipped: {skipped}");
    }
    Ok(())
}

fn main() -> Result<()> {
    let args = Args::parse();
    let lines = read_lines(args.file.as_deref())?;
    match args.direction {
        Direction::Request => run_requests(lines, args.stats),
        Direction::Response => run_responses(lines, args.stats),
    }
}

fn read_lines(
    path: Option<&std::path::Path>,
) -> Result<Box<dyn Iterator<Item = io::Result<String>>>> {
    match path {
        Some(path) => {
            let file = File::open(path).with_context(|| format!("opening {}", path.display()))?;
            Ok(Box::new(BufReader::new(file).lines()))
        }
        None => Ok(Box::new(BufReader::new(io::stdin()).lines())),
    }
}