Skip to content

Commit

Permalink
Use newtype in RTU header
Browse files Browse the repository at this point in the history
  • Loading branch information
uklotzde committed Oct 13, 2024
1 parent e0410d5 commit 1299c81
Show file tree
Hide file tree
Showing 5 changed files with 34 additions and 27 deletions.
26 changes: 17 additions & 9 deletions src/codec/rtu.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ use tokio_util::codec::{Decoder, Encoder};
use crate::{
bytes::{Buf, BufMut, Bytes, BytesMut},
frame::rtu::*,
slave::SlaveId,
Slave, SlaveId,
};

use super::*;
Expand Down Expand Up @@ -284,7 +284,9 @@ impl Decoder for ClientCodec {
return Ok(None);
};

let hdr = Header { slave_id };
let hdr = Header {
slave: Slave(slave_id),
};

// Decoding of the PDU is unlikely to fail due
// to transmission errors, because the frame's bytes
Expand All @@ -309,7 +311,9 @@ impl Decoder for ServerCodec {
return Ok(None);
};

let hdr = Header { slave_id };
let hdr = Header {
slave: Slave(slave_id),
};

// Decoding of the PDU is unlikely to fail due
// to transmission errors, because the frame's bytes
Expand All @@ -331,7 +335,7 @@ impl<'a> Encoder<RequestAdu<'a>> for ClientCodec {
let RequestAdu { hdr, pdu } = adu;
let pdu_data: Bytes = pdu.try_into()?;
buf.reserve(pdu_data.len() + 3);
buf.put_u8(hdr.slave_id);
buf.put_u8(hdr.slave.into());
buf.put_slice(&pdu_data);
let crc = calc_crc(buf);
buf.put_u16(crc);
Expand All @@ -347,7 +351,7 @@ impl Encoder<ResponseAdu> for ServerCodec {
let ResponseAdu { hdr, pdu } = adu;
let pdu_data: Bytes = pdu.into();
buf.reserve(pdu_data.len() + 3);
buf.put_u8(hdr.slave_id);
buf.put_u8(hdr.slave.into());
buf.put_slice(&pdu_data);
let crc = calc_crc(buf);
buf.put_u16(crc);
Expand Down Expand Up @@ -651,7 +655,7 @@ mod tests {
);
let ResponseAdu { hdr, pdu } = codec.decode(&mut buf).unwrap().unwrap();
assert_eq!(buf.len(), 1);
assert_eq!(hdr.slave_id, 0x01);
assert_eq!(hdr.slave, Slave(0x01));
if let Ok(Response::ReadHoldingRegisters(data)) = pdu.into() {
assert_eq!(data.len(), 2);
assert_eq!(data, vec![0x8902, 0x42C7]);
Expand Down Expand Up @@ -682,7 +686,7 @@ mod tests {
);
let ResponseAdu { hdr, pdu } = codec.decode(&mut buf).unwrap().unwrap();
assert_eq!(buf.len(), 1);
assert_eq!(hdr.slave_id, 0x01);
assert_eq!(hdr.slave, Slave(0x01));
if let Ok(Response::ReadHoldingRegisters(data)) = pdu.into() {
assert_eq!(data.len(), 2);
assert_eq!(data, vec![0x8902, 0x42C7]);
Expand Down Expand Up @@ -720,7 +724,9 @@ mod tests {
let req = Request::ReadHoldingRegisters(0x082b, 2);
let pdu = req.into();
let slave_id = 0x01;
let hdr = Header { slave_id };
let hdr = Header {
slave: Slave(slave_id),
};
let adu = RequestAdu { hdr, pdu };
codec.encode(adu, &mut buf).unwrap();

Expand All @@ -736,7 +742,9 @@ mod tests {
let req = Request::ReadHoldingRegisters(0x082b, 2);
let pdu = req.into();
let slave_id = 0x01;
let hdr = Header { slave_id };
let hdr = Header {
slave: Slave(slave_id),
};
let adu = RequestAdu { hdr, pdu };
let mut buf = BytesMut::with_capacity(40);
#[allow(unsafe_code)]
Expand Down
2 changes: 1 addition & 1 deletion src/frame/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -294,7 +294,7 @@ impl<'a> Request<'a> {
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct SlaveRequest<'a> {
/// Slave Id from the request
pub slave: crate::slave::SlaveId,
pub slave: crate::SlaveId,
/// A `Request` enum
pub request: Request<'a>,
}
Expand Down
17 changes: 9 additions & 8 deletions src/frame/rtu.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@

use super::*;

use crate::{ProtocolError, Result, SlaveId};
use crate::{ProtocolError, Result, Slave};

#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct RequestContext {
Expand All @@ -20,7 +20,7 @@ impl RequestContext {

#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub(crate) struct Header {
pub(crate) slave_id: SlaveId,
pub(crate) slave: Slave,
}

#[derive(Debug, Clone)]
Expand Down Expand Up @@ -92,9 +92,10 @@ impl<'a> From<RequestAdu<'a>> for Request<'a> {
#[cfg(feature = "server")]
impl<'a> From<RequestAdu<'a>> for SlaveRequest<'a> {
fn from(from: RequestAdu<'a>) -> Self {
let RequestAdu { hdr, pdu } = from;
Self {
slave: from.hdr.slave_id,
request: from.pdu.into(),
slave: hdr.slave.into(),
request: pdu.into(),
}
}
}
Expand All @@ -106,8 +107,8 @@ mod tests {
#[test]
fn validate_same_headers() {
// Given
let req_hdr = Header { slave_id: 0 };
let rsp_hdr = Header { slave_id: 0 };
let req_hdr = Header { slave: Slave(0) };
let rsp_hdr = Header { slave: Slave(0) };

// When
let result = verify_response_header(&req_hdr, &rsp_hdr);
Expand All @@ -119,8 +120,8 @@ mod tests {
#[test]
fn invalid_validate_not_same_slave_id() {
// Given
let req_hdr = Header { slave_id: 0 };
let rsp_hdr = Header { slave_id: 5 };
let req_hdr = Header { slave: Slave(0) };
let rsp_hdr = Header { slave: Slave(5) };

// When
let result = verify_response_header(&req_hdr, &rsp_hdr);
Expand Down
4 changes: 1 addition & 3 deletions src/service/rtu.rs
Original file line number Diff line number Diff line change
Expand Up @@ -180,9 +180,7 @@ fn request_adu<'a, R>(server: Slave, request_pdu: R) -> RequestAdu<'a>
where
R: Into<RequestPdu<'a>>,
{
let hdr = Header {
slave_id: server.into(),
};
let hdr = Header { slave: server };
let pdu = request_pdu.into();
RequestAdu { hdr, pdu }
}
Expand Down
12 changes: 6 additions & 6 deletions src/slave.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ use std::{fmt, num::ParseIntError, str::FromStr};
pub type SlaveId = u8;

/// A single byte for addressing Modbus slave devices.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[repr(transparent)]
pub struct Slave(pub SlaveId);

Expand Down Expand Up @@ -101,7 +101,7 @@ impl FromStr for Slave {

impl fmt::Display for Slave {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{} (0x{:0>2X})", self.0, self.0)
write!(f, "{} (0x{:02X})", self.0, self.0)
}
}

Expand Down Expand Up @@ -148,9 +148,9 @@ mod tests {
}

#[test]
fn format() {
assert!(format!("{}", Slave(123)).contains("123"));
assert!(format!("{}", Slave(0x7B)).contains("0x7B"));
assert!(!format!("{}", Slave(0x7B)).contains("0x7b"));
fn display() {
assert_eq!("0 (0x00)", Slave(0).to_string());
assert_eq!("123 (0x7B)", Slave(123).to_string());
assert_eq!("123 (0x7B)", Slave(0x7B).to_string());
}
}

0 comments on commit 1299c81

Please sign in to comment.