modbus_core/
error.rs

1use core::fmt;
2
3/// modbus-core Error
4#[derive(Debug, Clone, Copy, PartialEq, Eq)]
5pub enum Error {
6    /// Invalid coil value
7    CoilValue(u16),
8    /// Invalid buffer size
9    BufferSize,
10    /// Invalid function code
11    FnCode(u8),
12    /// Invalid exception code
13    ExceptionCode(u8),
14    /// Invalid exception function code
15    ExceptionFnCode(u8),
16    /// Invalid CRC
17    Crc(u16, u16),
18    /// Invalid byte count
19    ByteCount(u8),
20    /// Length Mismatch
21    LengthMismatch(usize, usize),
22    /// Protocol not Modbus
23    ProtocolNotModbus(u16),
24}
25
26impl fmt::Display for Error {
27    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
28        match self {
29            Self::CoilValue(v) => write!(f, "Invalid coil value: {v}"),
30            Self::BufferSize => write!(f, "Invalid buffer size"),
31            Self::FnCode(fn_code) => write!(f, "Invalid function code: 0x{fn_code:0>2X}"),
32            Self::ExceptionCode(code) => write!(f, "Invalid exception code:0x {code:0>2X}"),
33            Self::ExceptionFnCode(code) => {
34                write!(f, "Invalid exception function code:0x {code:0>2X}")
35            }
36            Self::Crc(expected, actual) => write!(
37                f,
38                "Invalid CRC: expected = 0x{expected:0>4X}, actual = 0x{actual:0>4X}"
39            ),
40            Self::ByteCount(cnt) => write!(f, "Invalid byte count: {cnt}"),
41            Self::LengthMismatch(length_field, pdu_len) => write!(
42                f,
43                "Length Mismatch: Length Field: {length_field}, PDU Len + 1: {pdu_len}"
44            ),
45            Self::ProtocolNotModbus(protocol_id) => {
46                write!(f, "Protocol not Modbus(0), recieved {protocol_id} instead")
47            }
48        }
49    }
50}