pamoja_modbus/error.rs
1//! The error type for Modbus framing.
2
3/// What can go wrong building or reading a Modbus RTU frame.
4#[derive(Clone, Copy, Debug, PartialEq, Eq)]
5pub enum ModbusError {
6 /// A frame is shorter than the smallest valid RTU ADU (address, function, CRC).
7 FrameTooShort,
8 /// A frame or PDU is longer than the 256-byte RTU maximum allows.
9 FrameTooLong,
10 /// A received frame's CRC does not match its contents, so the frame is corrupt.
11 CrcMismatch {
12 /// The CRC computed over the frame's contents.
13 expected: u16,
14 /// The CRC the frame carried.
15 found: u16,
16 },
17 /// A write request named a number of values a single request cannot carry (it must
18 /// be between one and the function's maximum).
19 InvalidValueCount,
20 /// A response PDU is truncated or its declared byte count does not match its data.
21 MalformedResponse,
22}
23
24impl core::fmt::Display for ModbusError {
25 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
26 match self {
27 ModbusError::FrameTooShort => {
28 f.write_str("modbus frame is shorter than a valid RTU ADU")
29 }
30 ModbusError::FrameTooLong => {
31 f.write_str("modbus frame exceeds the 256-byte RTU maximum")
32 }
33 ModbusError::CrcMismatch { expected, found } => {
34 write!(
35 f,
36 "modbus CRC mismatch: expected {expected:#06x}, found {found:#06x}"
37 )
38 }
39 ModbusError::InvalidValueCount => {
40 f.write_str("modbus write request value count is out of range")
41 }
42 ModbusError::MalformedResponse => f.write_str("modbus response PDU is malformed"),
43 }
44 }
45}
46
47// `core::error::Error` rather than `std::error::Error`, so a caller on a
48// microcontroller gets the same trait a caller on a gateway does.
49impl core::error::Error for ModbusError {}