mbrtu 0.1.2

no_std, no_alloc parser and encoder for Modbus RTU PDUs
Documentation
//! Write Single Register (function code 6): writes one 16-bit holding
//! register.
//!
//! A normal (non-exception) response to this function echoes the request
//! back byte-for-byte - the confirmed address and value, not a separate
//! acknowledgement shape - so a single struct serves as both the request
//! and the response; there's no direction-dependent ambiguity to resolve
//! here the way there is for the read functions.

use crate::error::MessageError;

/// This message's function code.
pub const FUNCTION_CODE: u8 = 0x06;

/// A Write Single Register request or response.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct WriteSingleRegister {
    /// Address of the register written.
    pub address: u16,
    /// Value written.
    pub value: u16,
}

impl WriteSingleRegister {
    pub(crate) fn decode(data: &[u8]) -> Result<Self, MessageError> {
        let [a1, a0, v1, v0, ..] = data else {
            return Err(MessageError::UnexpectedEof);
        };
        Ok(Self {
            address: u16::from_be_bytes([*a1, *a0]),
            value: u16::from_be_bytes([*v1, *v0]),
        })
    }

    pub(crate) fn encode(self, buf: &mut [u8]) -> Result<usize, MessageError> {
        let [d0, d1, d2, d3, ..] = buf else {
            return Err(MessageError::BufferFull);
        };
        [*d0, *d1] = self.address.to_be_bytes();
        [*d2, *d3] = self.value.to_be_bytes();
        Ok(4)
    }
}

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

    #[test]
    fn decodes_a_reference_frame() {
        // Cross-checked against pymodbus.
        let data = [0x00, 0x01, 0x00, 0x03];
        let msg = WriteSingleRegister::decode(&data).unwrap();
        assert_eq!(msg.address, 1);
        assert_eq!(msg.value, 3);
    }

    #[test]
    fn round_trips() {
        let original = WriteSingleRegister {
            address: 0x0042,
            value: 0xBEEF,
        };
        let mut buf = [0u8; 4];
        let n = original.encode(&mut buf).unwrap();
        assert_eq!(WriteSingleRegister::decode(&buf[..n]).unwrap(), original);
    }
}