mbrtu 0.1.2

no_std, no_alloc parser and encoder for Modbus RTU PDUs
Documentation
//! Raw Modbus RTU frame parsing and encoding.
//!
//! Unlike a length-prefixed protocol, Modbus RTU has no length field or
//! preamble byte: a real receiver finds frame boundaries by timing (3.5
//! character times of silence between frames), which a byte-level parser
//! has no access to. [`Frame::parse`] therefore assumes its caller has
//! already delimited one full frame (e.g. from a UART driver's own
//! inter-frame timeout, or one line of a captured log) and treats the
//! entire input slice as that frame, rather than scanning for a frame
//! start the way a preamble-based protocol's parser would.

use crate::crc;
use crate::error::FrameError;

const MIN_FRAME_LEN: usize = 4; // address + function code + 2-byte CRC
const CRC_LEN: usize = 2;

/// Largest PDU data a Modbus RTU frame can carry: the 256-byte RTU ADU
/// limit, minus the 1-byte address, 1-byte function code, and 2-byte CRC.
pub const MAX_DATA_LEN: usize = 252;

/// Largest possible frame: 1-byte address + 1-byte function code +
/// [`MAX_DATA_LEN`]-byte data + 2-byte CRC.
pub const MAX_FRAME_LEN: usize = 1 + 1 + MAX_DATA_LEN + CRC_LEN;

/// A parsed, CRC-validated Modbus RTU frame, borrowed from the caller's
/// buffer.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Frame<'a> {
    address: u8,
    function_code: u8,
    data: &'a [u8],
}

impl<'a> Frame<'a> {
    /// Parses and CRC-validates a single frame, treating all of `buf` as
    /// that frame (see the module docs for why Modbus RTU can't
    /// self-delimit a frame within a longer byte stream the way a
    /// preamble-based protocol can).
    ///
    /// # Errors
    /// Returns a [`FrameError`] if `buf` is shorter than the smallest
    /// possible frame, or the trailing CRC-16 doesn't match.
    pub fn parse(buf: &'a [u8]) -> Result<Self, FrameError> {
        if buf.len() < MIN_FRAME_LEN {
            return Err(FrameError::TooShort {
                needed: MIN_FRAME_LEN,
                got: buf.len(),
            });
        }

        let body_len = buf.len() - CRC_LEN;
        let body = &buf[..body_len];
        let expected = u16::from(buf[body_len]) | (u16::from(buf[body_len + 1]) << 8);
        if crc::checksum(body) != expected {
            return Err(FrameError::ChecksumMismatch);
        }

        Ok(Self {
            address: body[0],
            function_code: body[1],
            data: &body[2..],
        })
    }

    /// Parses and CRC-validates a single frame exactly like [`Frame::parse`],
    /// additionally rejecting the broadcast address (`0`): Modbus RTU
    /// never sends a response to a broadcast request, so a frame with
    /// address `0` in the response direction indicates a transport bug,
    /// not something a compliant device produces.
    ///
    /// # Errors
    /// Returns everything [`Frame::parse`] does, plus
    /// [`FrameError::BroadcastResponse`] if the frame's address is `0`.
    pub fn parse_response(buf: &'a [u8]) -> Result<Self, FrameError> {
        let frame = Self::parse(buf)?;
        if frame.address == 0 {
            return Err(FrameError::BroadcastResponse);
        }
        Ok(frame)
    }

    /// The unit/slave address (`0` is the broadcast address, valid only
    /// on requests; `1..=247` addresses an individual device).
    #[must_use]
    pub const fn address(&self) -> u8 {
        self.address
    }

    /// The function code, with the high bit set if this is an exception
    /// response (see [`crate::message::ModbusResponse`]).
    #[must_use]
    pub const fn function_code(&self) -> u8 {
        self.function_code
    }

    /// The PDU's data bytes, following the function code and preceding
    /// the CRC.
    #[must_use]
    pub const fn data(&self) -> &'a [u8] {
        self.data
    }
}

/// Encodes a frame around `address`, `function_code`, and `data` into
/// `buf`, returning the number of bytes written.
///
/// # Errors
/// Returns a [`FrameError`] if `buf` is too small to hold the encoded
/// frame (size it with [`MAX_FRAME_LEN`] to always be safe).
pub fn encode(
    buf: &mut [u8],
    address: u8,
    function_code: u8,
    data: &[u8],
) -> Result<usize, FrameError> {
    let total = 1 + 1 + data.len() + CRC_LEN;
    if buf.len() < total {
        return Err(FrameError::TooShort {
            needed: total,
            got: buf.len(),
        });
    }

    buf[0] = address;
    buf[1] = function_code;
    let data_end = 2 + data.len();
    buf[2..data_end].copy_from_slice(data);

    let crc = crc::checksum(&buf[..data_end]);
    buf[data_end] = (crc & 0xFF) as u8;
    buf[data_end + 1] = (crc >> 8) as u8;

    Ok(total)
}

// Frame::parse bounds-checks buf.len() before ever slicing, so it never
// panics regardless of buffer size. But both parse and encode call
// crc::checksum, whose outer loop needs an explicit #[kani::unwind] bound
// regardless of caller (see crc.rs) - every harness below needs one
// covering the largest slice checksum could see in that harness.
#[cfg(kani)]
mod kani_proofs {
    use super::{Frame, encode};

    #[kani::proof]
    #[kani::unwind(17)]
    fn parse_never_panics() {
        let buf: [u8; 16] = kani::any();
        let _ = Frame::parse(&buf);
    }

    #[kani::proof]
    #[kani::unwind(17)]
    fn encode_never_panics() {
        let mut buf = [0u8; 32];
        let address: u8 = kani::any();
        let function_code: u8 = kani::any();
        let data: [u8; 8] = kani::any();
        let _ = encode(&mut buf, address, function_code, &data);
    }

    #[kani::proof]
    #[kani::unwind(17)]
    fn encode_then_parse_round_trips() {
        let mut buf = [0u8; 32];
        let address: u8 = kani::any();
        let function_code: u8 = kani::any();
        let data: [u8; 8] = kani::any();
        let n = encode(&mut buf, address, function_code, &data).unwrap();
        let frame = Frame::parse(&buf[..n]).unwrap();
        assert_eq!(frame.address(), address);
        assert_eq!(frame.function_code(), function_code);
        assert_eq!(frame.data(), &data);
    }

    #[kani::proof]
    #[kani::unwind(17)]
    fn parse_response_never_panics() {
        let buf: [u8; 16] = kani::any();
        let _ = Frame::parse_response(&buf);
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn parses_a_reference_read_holding_registers_request() {
        // Cross-checked against pymodbus (the classic Modbus spec
        // example): unit 0x11, Read Holding Registers, address 0x006B,
        // quantity 3.
        let buf = [0x11, 0x03, 0x00, 0x6B, 0x00, 0x03, 0x76, 0x87];
        let frame = Frame::parse(&buf).unwrap();
        assert_eq!(frame.address(), 0x11);
        assert_eq!(frame.function_code(), 0x03);
        assert_eq!(frame.data(), &[0x00, 0x6B, 0x00, 0x03]);
    }

    #[test]
    fn rejects_a_buffer_shorter_than_the_minimum_frame() {
        assert_eq!(
            Frame::parse(&[0x11, 0x03, 0x00]),
            Err(FrameError::TooShort { needed: 4, got: 3 })
        );
    }

    #[test]
    fn rejects_a_bad_checksum() {
        let mut buf = [0x11, 0x03, 0x00, 0x6B, 0x00, 0x03, 0x76, 0x87];
        buf[7] ^= 0xFF;
        assert_eq!(Frame::parse(&buf), Err(FrameError::ChecksumMismatch));
    }

    #[test]
    fn encode_matches_a_reference_frame() {
        let expected = [0x11, 0x03, 0x00, 0x6B, 0x00, 0x03, 0x76, 0x87];
        let mut buf = [0u8; MAX_FRAME_LEN];
        let n = encode(&mut buf, 0x11, 0x03, &[0x00, 0x6B, 0x00, 0x03]).unwrap();
        assert_eq!(&buf[..n], &expected[..]);
    }

    #[test]
    fn encode_round_trips_through_parse() {
        let data = [1u8, 2, 3, 4, 5];
        let mut buf = [0u8; MAX_FRAME_LEN];
        let n = encode(&mut buf, 0x01, 0x03, &data).unwrap();
        let frame = Frame::parse(&buf[..n]).unwrap();
        assert_eq!(frame.address(), 0x01);
        assert_eq!(frame.function_code(), 0x03);
        assert_eq!(frame.data(), &data);
    }

    #[test]
    fn parse_response_rejects_the_broadcast_address() {
        let data = [1u8, 2, 3, 4, 5];
        let mut buf = [0u8; MAX_FRAME_LEN];
        let n = encode(&mut buf, 0x00, 0x03, &data).unwrap();

        // A broadcast-address frame is still a perfectly valid frame in
        // the request direction...
        assert!(Frame::parse(&buf[..n]).is_ok());
        // ...but never a valid one in the response direction.
        assert_eq!(
            Frame::parse_response(&buf[..n]),
            Err(FrameError::BroadcastResponse)
        );
    }

    #[test]
    fn parse_response_accepts_a_non_broadcast_address() {
        let buf = [0x11, 0x03, 0x00, 0x6B, 0x00, 0x03, 0x76, 0x87];
        let frame = Frame::parse_response(&buf).unwrap();
        assert_eq!(frame.address(), 0x11);
    }
}