Skip to main content

modbus_read/
lib.rs

1//! Read-only Modbus TCP client.
2//!
3//! Modbus TCP is a request/response protocol: an MBAP header sits in front
4//! of a short PDU. This crate encodes a read, decodes the reply, and turns
5//! the 16-bit register words into numbers.
6//!
7//! **A write cannot be spelled.** [`FunctionCode`] has two variants, 3 and 4.
8//! A write function code is not a value this crate refuses at run time; it is
9//! a value that does not exist.
10//!
11//! **The request decodes its own answer.** A device that answered a read the
12//! caller had given up on leaves a whole, well-formed frame behind it. With
13//! the request in hand, the echoed transaction id, unit id, function code and
14//! register count are all checked, and that frame is a typed refusal instead.
15//! Vary the [`TransactionId`] between reads; a constant id makes the echo
16//! check agree with every frame.
17//!
18//! **One action, and it owns no connection.** [`read_registers`] writes a
19//! frame and reads the frame that comes back over anything that is
20//! [`std::io::Read`] and [`std::io::Write`]. It holds no socket.
21//!
22//! Enable the `test-server` feature for a loopback device that serves
23//! synthetic registers and refuses every other function code.
24
25#![deny(missing_docs)]
26
27mod decode;
28mod frame;
29
30#[cfg(feature = "test-server")]
31mod server;
32
33use std::io::{Read, Write};
34
35pub use decode::{RegisterKind, Scale};
36pub use frame::{
37    ExceptionCode, FunctionCode, ModbusError, ReadRequest, RegisterAddress, RegisterCount,
38    TransactionId, UnitId, MAX_REGISTERS,
39};
40
41#[cfg(feature = "test-server")]
42pub use server::TestServer;
43
44use frame::{HEADER_PREFIX_LEN, MAX_LENGTH, MIN_LENGTH};
45
46/// What an exchange refuses: the frame, or the transport under it.
47///
48/// Two enums rather than one, because there are two kinds of code here. The
49/// calculations cannot fail for a reason the operating system invented, and
50/// keeping the I/O variant out of [`ModbusError`] is what says so.
51#[derive(Debug, thiserror::Error)]
52pub enum ExchangeError {
53    /// The bytes were not an answer to this read.
54    #[error(transparent)]
55    Modbus(#[from] ModbusError),
56    /// The transport failed or ended before a whole frame arrived.
57    #[error("the transport failed during a register read: {0}")]
58    Io(#[from] std::io::Error),
59}
60
61/// Ask a device for the registers a read names, and read its answer.
62///
63/// The only action in this crate's default feature set. It writes the
64/// request's own bytes, reads exactly the header, takes the body's length
65/// from it, reads exactly that many more, and hands the whole frame to
66/// [`ReadRequest::decode`]. Reading by the declared length is what makes
67/// this correct over a stream, where a message boundary is not something the
68/// transport preserves — two replies arriving together are two frames, not
69/// one long one.
70///
71/// A device that declares a body no Modbus frame can carry is refused before
72/// a byte of it is read, so a wrong length cannot make this wait for bytes
73/// that are not coming. How long to wait for the bytes that are is the
74/// connection's business.
75///
76/// # Errors
77///
78/// Returns [`ExchangeError::Io`] when the transport fails or ends early, and
79/// [`ExchangeError::Modbus`] when what arrived is not an answer to this
80/// request.
81pub fn read_registers<T: Read + Write>(
82    transport: &mut T,
83    request: &ReadRequest,
84) -> Result<Vec<u16>, ExchangeError> {
85    transport.write_all(&request.encode())?;
86    transport.flush()?;
87
88    let mut header = [0_u8; HEADER_PREFIX_LEN];
89    transport.read_exact(&mut header)?;
90    let [_, _, _, _, length_high, length_low] = header;
91    let declared = u16::from_be_bytes([length_high, length_low]);
92    if !(MIN_LENGTH..=MAX_LENGTH).contains(&declared) {
93        return Err(ModbusError::LengthOutOfRange {
94            declared,
95            min: MIN_LENGTH,
96            max: MAX_LENGTH,
97        }
98        .into());
99    }
100
101    let mut frame = vec![0_u8; HEADER_PREFIX_LEN + usize::from(declared)];
102    let (prefix, body) = frame.split_at_mut(HEADER_PREFIX_LEN);
103    prefix.copy_from_slice(&header);
104    transport.read_exact(body)?;
105    Ok(request.decode(&frame)?)
106}
107
108#[cfg(test)]
109mod tests {
110    use std::io::{Cursor, Read, Write};
111
112    use super::{
113        read_registers, ExceptionCode, ExchangeError, FunctionCode, ModbusError, ReadRequest,
114        RegisterAddress, RegisterCount, TransactionId, UnitId,
115    };
116
117    /// A well-framed reply: Modbus, and as long as it says it is.
118    fn reply(transaction: u16, unit: u8, function: u8, pdu: &[u8]) -> Vec<u8> {
119        let mut tail = vec![unit, function];
120        tail.extend_from_slice(pdu);
121        let declared = u16::try_from(tail.len()).expect("a test's reply is short");
122        let mut frame = Vec::new();
123        frame.extend_from_slice(&transaction.to_be_bytes());
124        frame.extend_from_slice(&0_u16.to_be_bytes());
125        frame.extend_from_slice(&declared.to_be_bytes());
126        frame.extend_from_slice(&tail);
127        frame
128    }
129
130    fn request(
131        transaction: u16,
132        unit: u8,
133        function: FunctionCode,
134        start: u16,
135        count: u16,
136    ) -> ReadRequest {
137        ReadRequest::new(
138            TransactionId::new(transaction),
139            UnitId::new(unit).expect("a test's unit id is addressed"),
140            function,
141            RegisterAddress::new(start),
142            RegisterCount::new(count).expect("a test's register count is within the ceiling"),
143        )
144        .expect("a test's read stays inside the address space")
145    }
146
147    /// A device made of bytes: it keeps what was written to it and answers
148    /// from what a test queued. The bytes are synthetic.
149    #[derive(Debug)]
150    struct Loopback {
151        written: Vec<u8>,
152        answer: Cursor<Vec<u8>>,
153    }
154
155    /// A transport that cannot be written to at all.
156    #[derive(Debug)]
157    struct Deaf;
158
159    impl Loopback {
160        fn answering(answer: Vec<u8>) -> Self {
161            Self {
162                written: Vec::new(),
163                answer: Cursor::new(answer),
164            }
165        }
166    }
167
168    impl Read for Loopback {
169        fn read(&mut self, buf: &mut [u8]) -> std::io::Result<usize> {
170            self.answer.read(buf)
171        }
172    }
173
174    impl Write for Loopback {
175        fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> {
176            self.written.extend_from_slice(buf);
177            Ok(buf.len())
178        }
179
180        fn flush(&mut self) -> std::io::Result<()> {
181            Ok(())
182        }
183    }
184
185    impl Read for Deaf {
186        fn read(&mut self, _buf: &mut [u8]) -> std::io::Result<usize> {
187            Ok(0)
188        }
189    }
190
191    impl Write for Deaf {
192        fn write(&mut self, _buf: &[u8]) -> std::io::Result<usize> {
193            Err(std::io::Error::from(std::io::ErrorKind::BrokenPipe))
194        }
195
196        fn flush(&mut self) -> std::io::Result<()> {
197            Ok(())
198        }
199    }
200
201    #[test]
202    fn an_exchange_writes_the_request_and_returns_what_the_device_answered() {
203        let read = request(1, 1, FunctionCode::ReadHoldingRegisters, 0, 2);
204        let mut device = Loopback::answering(reply(1, 1, 3, &[4, 0x00, 0x2a, 0x01, 0x90]));
205
206        let registers = read_registers(&mut device, &read).expect("the device answered");
207
208        assert_eq!(registers, vec![42, 400]);
209        assert_eq!(device.written, read.encode());
210    }
211
212    /// The frame after the frame: a stream keeps no message boundary, so the
213    /// read stops at the length the header declared and leaves the rest where
214    /// it is.
215    #[test]
216    fn an_exchange_reads_one_frame_and_leaves_what_follows_it() {
217        let read = request(1, 1, FunctionCode::ReadHoldingRegisters, 0, 2);
218        let mut answer = reply(1, 1, 3, &[4, 0x00, 0x2a, 0x01, 0x90]);
219        let trailing = reply(2, 1, 3, &[4, 0x00, 0x01, 0x00, 0x02]);
220        answer.extend_from_slice(&trailing);
221        let mut device = Loopback::answering(answer);
222
223        let registers = read_registers(&mut device, &read).expect("the device answered");
224
225        assert_eq!(registers, vec![42, 400]);
226        let mut left = Vec::new();
227        device
228            .read_to_end(&mut left)
229            .expect("the rest is still there");
230        assert_eq!(left, trailing);
231    }
232
233    #[test]
234    fn a_device_that_stops_mid_frame_is_a_transport_failure() {
235        let read = request(1, 1, FunctionCode::ReadHoldingRegisters, 0, 2);
236        let mut cut = reply(1, 1, 3, &[4, 0x00, 0x2a, 0x01, 0x90]);
237        cut.truncate(9);
238        let mut device = Loopback::answering(cut);
239
240        let refused = read_registers(&mut device, &read);
241
242        assert!(matches!(refused, Err(ExchangeError::Io(_))));
243    }
244
245    #[test]
246    fn a_transport_that_refuses_the_write_is_a_transport_failure() {
247        let read = request(1, 1, FunctionCode::ReadHoldingRegisters, 0, 2);
248
249        let refused = read_registers(&mut Deaf, &read);
250
251        assert!(matches!(refused, Err(ExchangeError::Io(_))));
252    }
253
254    #[test]
255    fn a_devices_refusal_arrives_through_the_exchange_as_a_modbus_error() {
256        let read = request(1, 1, FunctionCode::ReadHoldingRegisters, 0, 2);
257        let mut device = Loopback::answering(reply(1, 1, 0x83, &[2]));
258
259        let refused = read_registers(&mut device, &read);
260
261        assert!(matches!(
262            refused,
263            Err(ExchangeError::Modbus(ModbusError::Exception {
264                code: ExceptionCode::IllegalDataAddress,
265                ..
266            }))
267        ));
268    }
269
270    /// A body no frame can carry is refused on the header alone, so a wrong
271    /// length never makes the read wait for bytes that are not coming.
272    #[test]
273    fn a_body_longer_than_any_frame_is_refused_before_it_is_read() {
274        let read = request(1, 1, FunctionCode::ReadHoldingRegisters, 0, 2);
275        let mut header = Vec::new();
276        header.extend_from_slice(&1_u16.to_be_bytes());
277        header.extend_from_slice(&0_u16.to_be_bytes());
278        header.extend_from_slice(&u16::MAX.to_be_bytes());
279        let mut device = Loopback::answering(header);
280
281        let refused = read_registers(&mut device, &read);
282
283        assert!(matches!(
284            refused,
285            Err(ExchangeError::Modbus(ModbusError::LengthOutOfRange {
286                declared: u16::MAX,
287                ..
288            }))
289        ));
290    }
291
292    #[test]
293    fn a_stale_frame_does_not_become_this_reads_answer() {
294        let read = request(2, 1, FunctionCode::ReadHoldingRegisters, 0, 2);
295        let mut device = Loopback::answering(reply(1, 1, 3, &[4, 0x00, 0x2a, 0x01, 0x90]));
296
297        let refused = read_registers(&mut device, &read);
298
299        assert!(matches!(
300            refused,
301            Err(ExchangeError::Modbus(ModbusError::TransactionMismatch {
302                expected: 2,
303                found: 1,
304            }))
305        ));
306    }
307}