mbrtu 0.1.2

no_std, no_alloc parser and encoder for Modbus RTU PDUs
Documentation
//! Exception responses: a device's way of reporting that it can't service
//! a request. Any function code's response may become an exception -
//! signaled by setting the function code's high bit (e.g. `0x03` becomes
//! `0x83`) - so this isn't tied to a single request-side function code
//! the way the other message modules are.

use crate::error::MessageError;

/// Standard Modbus exception codes (section 7 of the Modbus Application
/// Protocol specification).
#[repr(u8)]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum ExceptionCode {
    /// The function code is not supported by the device.
    IllegalFunction = 0x01,
    /// The requested address is not valid for the device.
    IllegalDataAddress = 0x02,
    /// A value in the request is not valid for the device.
    IllegalDataValue = 0x03,
    /// The device failed while attempting to service the request.
    ServerDeviceFailure = 0x04,
    /// The device accepted the request but needs more time to service it.
    Acknowledge = 0x05,
    /// The device is busy servicing a long-running command.
    ServerDeviceBusy = 0x06,
    /// The device can't perform the requested action.
    NegativeAcknowledge = 0x07,
    /// A memory parity error occurred reading extended memory.
    MemoryParityError = 0x08,
    /// A raw exception code this crate doesn't have a named variant for.
    Other(u8),
}

impl From<u8> for ExceptionCode {
    fn from(code: u8) -> Self {
        match code {
            0x01 => Self::IllegalFunction,
            0x02 => Self::IllegalDataAddress,
            0x03 => Self::IllegalDataValue,
            0x04 => Self::ServerDeviceFailure,
            0x05 => Self::Acknowledge,
            0x06 => Self::ServerDeviceBusy,
            0x07 => Self::NegativeAcknowledge,
            0x08 => Self::MemoryParityError,
            other => Self::Other(other),
        }
    }
}

impl From<ExceptionCode> for u8 {
    fn from(code: ExceptionCode) -> Self {
        match code {
            ExceptionCode::IllegalFunction => 0x01,
            ExceptionCode::IllegalDataAddress => 0x02,
            ExceptionCode::IllegalDataValue => 0x03,
            ExceptionCode::ServerDeviceFailure => 0x04,
            ExceptionCode::Acknowledge => 0x05,
            ExceptionCode::ServerDeviceBusy => 0x06,
            ExceptionCode::NegativeAcknowledge => 0x07,
            ExceptionCode::MemoryParityError => 0x08,
            ExceptionCode::Other(other) => other,
        }
    }
}

/// An exception response: the original request's function code (with its
/// high bit cleared back to the function that failed) and why it failed.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct ExceptionResponse {
    /// The function code that failed, with the high bit already cleared
    /// (e.g. `0x03`, not `0x83`).
    pub function_code: u8,
    /// Why the request failed.
    pub exception_code: ExceptionCode,
}

impl ExceptionResponse {
    pub(crate) fn decode(function_code: u8, data: &[u8]) -> Result<Self, MessageError> {
        let [code, ..] = data else {
            return Err(MessageError::UnexpectedEof);
        };
        Ok(Self {
            function_code: function_code & 0x7F,
            exception_code: ExceptionCode::from(*code),
        })
    }

    pub(crate) fn encode(self, buf: &mut [u8]) -> Result<usize, MessageError> {
        let [d0, ..] = buf else {
            return Err(MessageError::BufferFull);
        };
        *d0 = self.exception_code.into();
        Ok(1)
    }
}

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

    #[test]
    fn decodes_a_reference_frame() {
        // Cross-checked against pymodbus: Read Holding Registers (0x83 =
        // 0x03 | 0x80), Illegal Data Address.
        let data = [0x02];
        let exc = ExceptionResponse::decode(0x83, &data).unwrap();
        assert_eq!(exc.function_code, 0x03);
        assert_eq!(exc.exception_code, ExceptionCode::IllegalDataAddress);
    }

    #[test]
    fn round_trips() {
        let original = ExceptionResponse {
            function_code: 0x06,
            exception_code: ExceptionCode::IllegalDataValue,
        };
        let mut buf = [0u8; 1];
        let n = original.encode(&mut buf).unwrap();
        let decoded = ExceptionResponse::decode(0x06 | 0x80, &buf[..n]).unwrap();
        assert_eq!(decoded, original);
    }
}