use crate::error::MessageError;
#[repr(u8)]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum ExceptionCode {
IllegalFunction = 0x01,
IllegalDataAddress = 0x02,
IllegalDataValue = 0x03,
ServerDeviceFailure = 0x04,
Acknowledge = 0x05,
ServerDeviceBusy = 0x06,
NegativeAcknowledge = 0x07,
MemoryParityError = 0x08,
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,
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct ExceptionResponse {
pub function_code: u8,
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() {
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);
}
}