Skip to main content

modbus_read/
frame.rs

1//! Modbus TCP frames: the MBAP header plus the two read PDUs.
2//!
3//! Building a frame is arithmetic on a dozen bytes. [`ReadRequest::encode`]
4//! turns five values into a frame and [`ReadRequest::decode`] turns a frame
5//! back into register words. Neither opens a socket.
6
7use std::fmt;
8
9/// What a Modbus read refuses, on the way out and on the way back.
10///
11/// Every variant names what was expected beside what was found, because the
12/// reader of this error is an operator holding a register map and a device
13/// manual, and "length mismatch" alone sends them to a packet capture.
14#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
15pub enum ModbusError {
16    /// Unit id 0 is a broadcast. No device answers a broadcast read.
17    #[error("unit id 0 is a broadcast, which no device answers; a read needs an addressed unit")]
18    BroadcastUnit,
19    /// Unit ids 248 to 254 are reserved by the specification.
20    #[error("unit id {unit} is reserved by the specification (248-254)")]
21    ReservedUnit {
22        /// The reserved unit id that was refused.
23        unit: u8,
24    },
25    /// A read of zero registers asks a device for nothing.
26    #[error("a read of no registers asks a device for nothing")]
27    EmptyRead,
28    /// Function codes 3 and 4 answer at most [`MAX_REGISTERS`] words.
29    #[error("a read of {count} registers is above the {max} this function code can answer")]
30    TooManyRegisters {
31        /// How many registers were asked for.
32        count: u16,
33        /// The protocol ceiling for this function code.
34        max: u16,
35    },
36    /// The last register asked for sits past address 65 535.
37    #[error("a read of {count} registers from {start} runs past the end of the address space")]
38    PastEndOfAddressSpace {
39        /// Where the read started.
40        start: u16,
41        /// How many registers were asked for.
42        count: u16,
43    },
44    /// The byte slice is shorter than a Modbus TCP reply needs.
45    #[error("the reply is {found} bytes, too few for the {expected} this frame needs")]
46    TooShort {
47        /// How many bytes this step needed.
48        expected: usize,
49        /// How many bytes were present.
50        found: usize,
51    },
52    /// The protocol id is not zero, so the frame is not Modbus.
53    #[error("the reply carries protocol id {found}, so it is not Modbus")]
54    ProtocolId {
55        /// The protocol id the frame carried.
56        found: u16,
57    },
58    /// The length field is outside what a Modbus TCP frame can carry.
59    #[error("the reply declares {declared} bytes, outside the {min} to {max} a frame can carry")]
60    LengthOutOfRange {
61        /// The length field from the header.
62        declared: u16,
63        /// The smallest legal length.
64        min: u16,
65        /// The largest legal length.
66        max: u16,
67    },
68    /// The length field does not match the bytes that follow it.
69    #[error("the reply declares {declared} bytes and carries {found}")]
70    LengthMismatch {
71        /// The length field from the header.
72        declared: u16,
73        /// How many bytes followed the header.
74        found: u16,
75    },
76    /// The reply echoed a different transaction id than this read used.
77    #[error("the reply answers transaction {found}, and this read is transaction {expected}")]
78    TransactionMismatch {
79        /// The transaction id this read used.
80        expected: u16,
81        /// The transaction id the reply echoed.
82        found: u16,
83    },
84    /// The reply came from a different unit than this read addressed.
85    #[error("the reply comes from unit {found}, and this read went to unit {expected}")]
86    UnitMismatch {
87        /// The unit id this read addressed.
88        expected: u8,
89        /// The unit id the reply named.
90        found: u8,
91    },
92    /// The reply carried a function code this read did not use.
93    #[error("the reply carries function code {found}, and this read used {expected}")]
94    FunctionMismatch {
95        /// The function code this read used.
96        expected: u8,
97        /// The function code the reply carried.
98        found: u8,
99    },
100    /// The device refused the read and named a reason.
101    #[error("the device refused function code {function}: {code}")]
102    Exception {
103        /// The function code that was refused.
104        function: u8,
105        /// The reason the device gave.
106        code: ExceptionCode,
107    },
108    /// The reply's byte count is not twice the register count that was asked.
109    #[error("the reply carries {declared} bytes of registers, and this read asked for {expected}")]
110    ByteCountMismatch {
111        /// The byte count the reply declared.
112        declared: u16,
113        /// The byte count this read is owed.
114        expected: u16,
115    },
116    /// The header length and the PDU byte count do not describe the same body.
117    #[error(
118        "the reply's header declares {declared} bytes and its byte count implies {byte_count}"
119    )]
120    InconsistentLength {
121        /// The length field from the header.
122        declared: u16,
123        /// The byte-count field from the PDU.
124        byte_count: u8,
125    },
126    /// A decoder was handed the wrong number of 16-bit words.
127    #[error("a {kind} reads {expected} registers and was handed {found}")]
128    WordCount {
129        /// The decoder's name.
130        kind: &'static str,
131        /// How many words that decoder needs.
132        expected: u16,
133        /// How many words were supplied.
134        found: usize,
135    },
136    /// A scale factor must be a finite number.
137    #[error("a register scale is a finite number")]
138    NonFiniteScale,
139    /// A scale of zero would turn every register into nothing.
140    #[error("a scale of zero reads every register as nothing")]
141    ZeroScale,
142}
143
144/// Why a device refused a read, in its own words.
145///
146/// The specification numbers these. A reply of 2 means the register the
147/// caller's map points at is not on this device. "2" does not say that.
148#[derive(Debug, Clone, Copy, PartialEq, Eq)]
149pub enum ExceptionCode {
150    /// Exception code 1. The function is not supported.
151    IllegalFunction,
152    /// Exception code 2. The address is not on this device.
153    IllegalDataAddress,
154    /// Exception code 3. A value in the request is not allowed.
155    IllegalDataValue,
156    /// Exception code 4. The device failed while handling the request.
157    ServerDeviceFailure,
158    /// Exception code 5. The device accepted the request and needs time.
159    Acknowledge,
160    /// Exception code 6. The device is busy.
161    ServerDeviceBusy,
162    /// Exception code 7. The device refused the request.
163    NegativeAcknowledge,
164    /// Exception code 8. A memory parity error.
165    MemoryParityError,
166    /// Exception code 10. A gateway could not path the request.
167    GatewayPathUnavailable,
168    /// Exception code 11. A gateway got no response from the target.
169    GatewayTargetNoResponse,
170    /// A code the specification does not name.
171    Other(u8),
172}
173
174/// The Modbus function codes this crate can express. There are two.
175///
176/// A two-variant enum is the read-only rule written where the compiler reads
177/// it: a write function code is not a value this crate refuses, it is a
178/// value nobody can name.
179#[derive(Debug, Clone, Copy, PartialEq, Eq)]
180pub enum FunctionCode {
181    /// Function code 3. Read holding registers.
182    ReadHoldingRegisters,
183    /// Function code 4. Read input registers.
184    ReadInputRegisters,
185}
186
187/// The number a device uses to tell one request from another.
188///
189/// Any value is legal, and the device echoes it back. Choose a new id for
190/// each read. [`ReadRequest::decode`] rejects a late answer to an earlier
191/// read by its id, and a constant id makes that check agree with every frame.
192#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
193pub struct TransactionId(u16);
194
195/// Which device on the far side of the connection is being asked.
196///
197/// Zero is a broadcast — a frame nobody answers, which on a read-only client
198/// can only be a mistake — and 248 to 254 are reserved. 255 is what the
199/// specification tells a device with no serial line behind it to use, so it
200/// is accepted.
201#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
202pub struct UnitId(u8);
203
204/// Where in a device's register map a read starts.
205#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
206pub struct RegisterAddress(u16);
207
208/// How many 16-bit registers a read asks for.
209///
210/// Function codes 3 and 4 answer with a byte count in a single byte, so 125
211/// registers is the protocol's own ceiling and not a limit chosen here.
212#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
213pub struct RegisterCount(u16);
214
215/// One read, complete enough to be a frame and to judge the frame that comes
216/// back.
217#[derive(Debug, Clone, PartialEq, Eq)]
218pub struct ReadRequest {
219    transaction: TransactionId,
220    unit: UnitId,
221    function: FunctionCode,
222    start: RegisterAddress,
223    count: RegisterCount,
224}
225
226/// The most registers function codes 3 and 4 can answer in one frame.
227pub const MAX_REGISTERS: u16 = 125;
228
229/// The protocol id that says a frame is Modbus. It has one value.
230const PROTOCOL_ID: u16 = 0;
231
232/// What an MBAP length counts for a read request: unit id, function code,
233/// start address, register count.
234const REQUEST_LENGTH: u16 = 6;
235
236/// The bytes ahead of the length field's own subject: transaction id,
237/// protocol id, length.
238pub(crate) const HEADER_PREFIX_LEN: usize = 6;
239
240/// A request frame: the prefix, the length's own subject, and nothing else.
241const REQUEST_FRAME_LEN: usize = HEADER_PREFIX_LEN + REQUEST_LENGTH as usize;
242
243/// The least a reply can declare: a unit id and a function code.
244pub(crate) const MIN_LENGTH: u16 = 2;
245
246/// The most a reply can declare: a unit id and the largest PDU the protocol
247/// allows.
248pub(crate) const MAX_LENGTH: u16 = 254;
249
250/// The shortest frame that can be read as a reply at all.
251const MIN_FRAME_LEN: usize = HEADER_PREFIX_LEN + MIN_LENGTH as usize;
252
253/// The bit a device sets on the function code to say it is refusing.
254const EXCEPTION_BIT: u8 = 0x80;
255
256/// Where the fields of a reply sit.
257const TRANSACTION_AT: usize = 0;
258const PROTOCOL_AT: usize = 2;
259const LENGTH_AT: usize = 4;
260const UNIT_AT: usize = 6;
261const FUNCTION_AT: usize = 7;
262const PDU_AT: usize = 8;
263
264/// A reply, taken apart but not yet believed.
265///
266/// Every field is a byte that was there; whether the device answered *this*
267/// read is [`ReadRequest::decode`]'s question, not this type's. `pdu` is what
268/// follows the function code: a byte count and the registers, or the code of
269/// a refusal.
270#[derive(Debug, Clone, Copy, PartialEq, Eq)]
271struct Reply<'a> {
272    declared: u16,
273    transaction: u16,
274    unit: u8,
275    function: u8,
276    pdu: &'a [u8],
277}
278
279impl Reply<'_> {
280    /// This reply, said to be a byte short of what any answer needs.
281    fn too_short(&self) -> ModbusError {
282        ModbusError::TooShort {
283            expected: MIN_FRAME_LEN + 1,
284            found: MIN_FRAME_LEN + self.pdu.len(),
285        }
286    }
287}
288
289/// The big-endian pair at `at`, when the frame is long enough to hold one.
290fn word_at(frame: &[u8], at: usize) -> Option<u16> {
291    let pair: [u8; 2] = frame.get(at..at + 2)?.try_into().ok()?;
292    Some(u16::from_be_bytes(pair))
293}
294
295/// What a frame must be before anything in it is read as an answer, whoever
296/// asked: long enough to hold a header, Modbus, and as long as it says it is.
297///
298/// # Errors
299///
300/// Returns [`ModbusError::TooShort`], [`ModbusError::ProtocolId`],
301/// [`ModbusError::LengthOutOfRange`] or [`ModbusError::LengthMismatch`].
302fn parse_reply(frame: &[u8]) -> Result<Reply<'_>, ModbusError> {
303    let (
304        Some(transaction),
305        Some(protocol),
306        Some(declared),
307        Some(&unit),
308        Some(&function),
309        Some(pdu),
310    ) = (
311        word_at(frame, TRANSACTION_AT),
312        word_at(frame, PROTOCOL_AT),
313        word_at(frame, LENGTH_AT),
314        frame.get(UNIT_AT),
315        frame.get(FUNCTION_AT),
316        frame.get(PDU_AT..),
317    )
318    else {
319        return Err(ModbusError::TooShort {
320            expected: MIN_FRAME_LEN,
321            found: frame.len(),
322        });
323    };
324    if protocol != PROTOCOL_ID {
325        return Err(ModbusError::ProtocolId { found: protocol });
326    }
327    if !(MIN_LENGTH..=MAX_LENGTH).contains(&declared) {
328        return Err(ModbusError::LengthOutOfRange {
329            declared,
330            min: MIN_LENGTH,
331            max: MAX_LENGTH,
332        });
333    }
334    let carried = u16::try_from(frame.len() - HEADER_PREFIX_LEN).unwrap_or(u16::MAX);
335    if carried != declared {
336        return Err(ModbusError::LengthMismatch {
337            declared,
338            found: carried,
339        });
340    }
341    Ok(Reply {
342        declared,
343        transaction,
344        unit,
345        function,
346        pdu,
347    })
348}
349
350impl FunctionCode {
351    /// The byte this function code puts on the wire.
352    ///
353    /// Exhaustive by construction: a third variant does not compile until
354    /// someone writes here what it would send.
355    #[must_use]
356    pub const fn code(self) -> u8 {
357        match self {
358            Self::ReadHoldingRegisters => 3,
359            Self::ReadInputRegisters => 4,
360        }
361    }
362}
363
364impl ExceptionCode {
365    /// What an operator should read in a log line.
366    #[must_use]
367    pub const fn name(self) -> &'static str {
368        match self {
369            Self::IllegalFunction => "illegal function",
370            Self::IllegalDataAddress => "illegal data address",
371            Self::IllegalDataValue => "illegal data value",
372            Self::ServerDeviceFailure => "server device failure",
373            Self::Acknowledge => "acknowledge",
374            Self::ServerDeviceBusy => "server device busy",
375            Self::NegativeAcknowledge => "negative acknowledge",
376            Self::MemoryParityError => "memory parity error",
377            Self::GatewayPathUnavailable => "gateway path unavailable",
378            Self::GatewayTargetNoResponse => "gateway target device failed to respond",
379            Self::Other(_) => "an exception this specification does not define",
380        }
381    }
382
383    /// The byte a device sends for this refusal.
384    #[must_use]
385    pub const fn byte(self) -> u8 {
386        match self {
387            Self::IllegalFunction => 1,
388            Self::IllegalDataAddress => 2,
389            Self::IllegalDataValue => 3,
390            Self::ServerDeviceFailure => 4,
391            Self::Acknowledge => 5,
392            Self::ServerDeviceBusy => 6,
393            Self::NegativeAcknowledge => 7,
394            Self::MemoryParityError => 8,
395            Self::GatewayPathUnavailable => 10,
396            Self::GatewayTargetNoResponse => 11,
397            Self::Other(byte) => byte,
398        }
399    }
400}
401
402/// Every byte is an exception of some kind: a device that invents one is
403/// reported as itself rather than mistaken for a code with a meaning.
404impl From<u8> for ExceptionCode {
405    fn from(byte: u8) -> Self {
406        match byte {
407            1 => Self::IllegalFunction,
408            2 => Self::IllegalDataAddress,
409            3 => Self::IllegalDataValue,
410            4 => Self::ServerDeviceFailure,
411            5 => Self::Acknowledge,
412            6 => Self::ServerDeviceBusy,
413            7 => Self::NegativeAcknowledge,
414            8 => Self::MemoryParityError,
415            10 => Self::GatewayPathUnavailable,
416            11 => Self::GatewayTargetNoResponse,
417            other => Self::Other(other),
418        }
419    }
420}
421
422impl fmt::Display for ExceptionCode {
423    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
424        write!(f, "{} ({})", self.name(), self.byte())
425    }
426}
427
428impl TransactionId {
429    /// The id a read will carry, and the id its answer must echo.
430    #[must_use]
431    pub const fn new(id: u16) -> Self {
432        Self(id)
433    }
434
435    /// The number itself, for the two bytes it becomes.
436    #[must_use]
437    pub const fn get(self) -> u16 {
438        self.0
439    }
440}
441
442impl UnitId {
443    /// An addressed unit.
444    ///
445    /// # Errors
446    ///
447    /// Returns [`ModbusError::BroadcastUnit`] for 0 and
448    /// [`ModbusError::ReservedUnit`] for 248 to 254.
449    pub const fn new(unit: u8) -> Result<Self, ModbusError> {
450        match unit {
451            0 => Err(ModbusError::BroadcastUnit),
452            248..=254 => Err(ModbusError::ReservedUnit { unit }),
453            _ => Ok(Self(unit)),
454        }
455    }
456
457    /// The byte the frame carries for this unit.
458    #[must_use]
459    pub const fn get(self) -> u8 {
460        self.0
461    }
462}
463
464impl RegisterAddress {
465    /// An address in a device's map, as its register map spells it.
466    #[must_use]
467    pub const fn new(address: u16) -> Self {
468        Self(address)
469    }
470
471    /// The address itself, for the two bytes it becomes.
472    #[must_use]
473    pub const fn get(self) -> u16 {
474        self.0
475    }
476}
477
478impl RegisterCount {
479    /// A register count this protocol can answer.
480    ///
481    /// # Errors
482    ///
483    /// Returns [`ModbusError::EmptyRead`] for 0 and
484    /// [`ModbusError::TooManyRegisters`] above [`MAX_REGISTERS`].
485    pub const fn new(count: u16) -> Result<Self, ModbusError> {
486        if count == 0 {
487            return Err(ModbusError::EmptyRead);
488        }
489        if count > MAX_REGISTERS {
490            return Err(ModbusError::TooManyRegisters {
491                count,
492                max: MAX_REGISTERS,
493            });
494        }
495        Ok(Self(count))
496    }
497
498    /// The count itself, for the two bytes it becomes.
499    #[must_use]
500    pub const fn get(self) -> u16 {
501        self.0
502    }
503
504    /// How many bytes a device owes in answer to this many registers.
505    #[must_use]
506    pub const fn byte_count(self) -> u16 {
507        self.0 * 2
508    }
509}
510
511impl ReadRequest {
512    /// A read a device could answer.
513    ///
514    /// # Errors
515    ///
516    /// Returns [`ModbusError::PastEndOfAddressSpace`] when the last register
517    /// asked for is past the end of the 16-bit address space — a request no
518    /// device can answer, caught where it is written rather than later in an
519    /// exception reply.
520    pub fn new(
521        transaction: TransactionId,
522        unit: UnitId,
523        function: FunctionCode,
524        start: RegisterAddress,
525        count: RegisterCount,
526    ) -> Result<Self, ModbusError> {
527        let last = u32::from(start.get()) + u32::from(count.get());
528        if last > u32::from(u16::MAX) + 1 {
529            return Err(ModbusError::PastEndOfAddressSpace {
530                start: start.get(),
531                count: count.get(),
532            });
533        }
534        Ok(Self {
535            transaction,
536            unit,
537            function,
538            start,
539            count,
540        })
541    }
542
543    /// The id this read carries, and the id its answer must echo.
544    #[must_use]
545    pub const fn transaction(&self) -> TransactionId {
546        self.transaction
547    }
548
549    /// The device this read is addressed to.
550    #[must_use]
551    pub const fn unit(&self) -> UnitId {
552        self.unit
553    }
554
555    /// Which of the two read tables this read asks about.
556    #[must_use]
557    pub const fn function(&self) -> FunctionCode {
558        self.function
559    }
560
561    /// Where in the map this read starts.
562    #[must_use]
563    pub const fn start(&self) -> RegisterAddress {
564        self.start
565    }
566
567    /// How many registers this read asks for, and so how many bytes its
568    /// answer owes.
569    #[must_use]
570    pub const fn count(&self) -> RegisterCount {
571        self.count
572    }
573
574    /// This read, as the bytes that go on the wire.
575    ///
576    /// Big-endian throughout, which is the protocol's order and not a choice.
577    #[must_use]
578    pub fn encode(&self) -> Vec<u8> {
579        let mut frame = Vec::with_capacity(REQUEST_FRAME_LEN);
580        frame.extend_from_slice(&self.transaction.get().to_be_bytes());
581        frame.extend_from_slice(&PROTOCOL_ID.to_be_bytes());
582        frame.extend_from_slice(&REQUEST_LENGTH.to_be_bytes());
583        frame.push(self.unit.get());
584        frame.push(self.function.code());
585        frame.extend_from_slice(&self.start.get().to_be_bytes());
586        frame.extend_from_slice(&self.count.get().to_be_bytes());
587        frame
588    }
589
590    /// What a device sent back, as the registers this read asked for.
591    ///
592    /// The frame is the whole reply, header included, exactly as many bytes
593    /// as its length field declares. Everything the device echoed is checked
594    /// against this request before a single register is believed, which is
595    /// what keeps a late answer to a previous read from being taken as this
596    /// one's.
597    ///
598    /// # Errors
599    ///
600    /// Returns [`ModbusError::Exception`] when the device refused the read,
601    /// and one of the framing or echo variants when the frame is not an
602    /// answer to this request. No reply produces a panic and none produces
603    /// registers the device did not send.
604    pub fn decode(&self, frame: &[u8]) -> Result<Vec<u16>, ModbusError> {
605        let reply = parse_reply(frame)?;
606        self.check_echo(&reply)?;
607        let expected = self.function.code();
608        if reply.function == expected {
609            return self.registers(&reply);
610        }
611        if reply.function == expected | EXCEPTION_BIT {
612            return Err(exception(expected, &reply));
613        }
614        Err(ModbusError::FunctionMismatch {
615            expected,
616            found: reply.function,
617        })
618    }
619
620    /// That the device answering is the device that was asked, about the read
621    /// it was asked.
622    fn check_echo(&self, reply: &Reply<'_>) -> Result<(), ModbusError> {
623        if reply.transaction != self.transaction.get() {
624            return Err(ModbusError::TransactionMismatch {
625                expected: self.transaction.get(),
626                found: reply.transaction,
627            });
628        }
629        if reply.unit != self.unit.get() {
630            return Err(ModbusError::UnitMismatch {
631                expected: self.unit.get(),
632                found: reply.unit,
633            });
634        }
635        Ok(())
636    }
637
638    /// A successful reply's registers, big-endian pairs, in the order the
639    /// device sent them.
640    fn registers(&self, reply: &Reply<'_>) -> Result<Vec<u16>, ModbusError> {
641        let (Some(&byte_count), Some(words)) = (reply.pdu.first(), reply.pdu.get(1..)) else {
642            return Err(reply.too_short());
643        };
644        let expected = self.count.byte_count();
645        if u16::from(byte_count) != expected {
646            return Err(ModbusError::ByteCountMismatch {
647                declared: u16::from(byte_count),
648                expected,
649            });
650        }
651        if words.len() != usize::from(byte_count) {
652            return Err(ModbusError::InconsistentLength {
653                declared: reply.declared,
654                byte_count,
655            });
656        }
657        // `chunks_exact(2)` yields slices of exactly two, and the byte count
658        // is even, so there is no remainder and neither index can be out of
659        // range.
660        Ok(words
661            .chunks_exact(2)
662            .map(|pair| u16::from_be_bytes([pair[0], pair[1]]))
663            .collect())
664    }
665}
666
667/// A refusal, as the reason the device gave for it.
668fn exception(function: u8, reply: &Reply<'_>) -> ModbusError {
669    match reply.pdu.first() {
670        Some(&byte) => ModbusError::Exception {
671            function,
672            code: ExceptionCode::from(byte),
673        },
674        None => reply.too_short(),
675    }
676}
677
678#[cfg(test)]
679mod tests {
680    use super::{
681        ExceptionCode, FunctionCode, ModbusError, ReadRequest, RegisterAddress, RegisterCount,
682        TransactionId, UnitId, MAX_REGISTERS,
683    };
684
685    /// Every named exception code, so a test can walk them all.
686    const NAMED_EXCEPTIONS: [ExceptionCode; 10] = [
687        ExceptionCode::IllegalFunction,
688        ExceptionCode::IllegalDataAddress,
689        ExceptionCode::IllegalDataValue,
690        ExceptionCode::ServerDeviceFailure,
691        ExceptionCode::Acknowledge,
692        ExceptionCode::ServerDeviceBusy,
693        ExceptionCode::NegativeAcknowledge,
694        ExceptionCode::MemoryParityError,
695        ExceptionCode::GatewayPathUnavailable,
696        ExceptionCode::GatewayTargetNoResponse,
697    ];
698
699    /// A frame with the header a test names, however wrong.
700    fn framed(transaction: u16, protocol: u16, declared: u16, tail: &[u8]) -> Vec<u8> {
701        let mut frame = Vec::new();
702        frame.extend_from_slice(&transaction.to_be_bytes());
703        frame.extend_from_slice(&protocol.to_be_bytes());
704        frame.extend_from_slice(&declared.to_be_bytes());
705        frame.extend_from_slice(tail);
706        frame
707    }
708
709    /// A well-framed reply: Modbus, and as long as it says it is.
710    fn reply(transaction: u16, unit: u8, function: u8, pdu: &[u8]) -> Vec<u8> {
711        let mut tail = vec![unit, function];
712        tail.extend_from_slice(pdu);
713        let declared = u16::try_from(tail.len()).expect("a test's reply is short");
714        framed(transaction, 0, declared, &tail)
715    }
716
717    /// A request built from values a test names, so each test says only what
718    /// it is about.
719    fn request(
720        transaction: u16,
721        unit: u8,
722        function: FunctionCode,
723        start: u16,
724        count: u16,
725    ) -> ReadRequest {
726        ReadRequest::new(
727            TransactionId::new(transaction),
728            UnitId::new(unit).expect("a test's unit id is addressed"),
729            function,
730            RegisterAddress::new(start),
731            RegisterCount::new(count).expect("a test's register count is within the ceiling"),
732        )
733        .expect("a test's read stays inside the address space")
734    }
735
736    /// Synthetic holding-register read: function code 3, unit 1, address 0,
737    /// count 2. The bytes are invented; they are not a capture from a device.
738    #[test]
739    fn a_holding_register_read_encodes_to_the_named_frame() {
740        let read = request(1, 1, FunctionCode::ReadHoldingRegisters, 0, 2);
741
742        let frame = read.encode();
743
744        assert_eq!(
745            frame,
746            vec![0x00, 0x01, 0x00, 0x00, 0x00, 0x06, 0x01, 0x03, 0x00, 0x00, 0x00, 0x02]
747        );
748    }
749
750    /// Input registers are the same read of a different table, so the frames
751    /// differ in the function code and nowhere else.
752    #[test]
753    fn an_input_register_read_differs_from_a_holding_read_in_one_byte() {
754        let holding = request(1, 1, FunctionCode::ReadHoldingRegisters, 0, 2).encode();
755        let input = request(1, 1, FunctionCode::ReadInputRegisters, 0, 2).encode();
756
757        let differing: Vec<usize> = holding
758            .iter()
759            .zip(input.iter())
760            .enumerate()
761            .filter(|(_, (left, right))| left != right)
762            .map(|(index, _)| index)
763            .collect();
764
765        assert_eq!(differing, vec![7]);
766        assert_eq!((holding[7], input[7]), (3, 4));
767    }
768
769    #[test]
770    fn a_read_high_in_the_map_encodes_its_transaction_address_and_count() {
771        let read = request(0x1234, 17, FunctionCode::ReadInputRegisters, 0x0100, 125);
772
773        let frame = read.encode();
774
775        assert_eq!(
776            frame,
777            vec![0x12, 0x34, 0x00, 0x00, 0x00, 0x06, 0x11, 0x04, 0x01, 0x00, 0x00, 0x7d]
778        );
779    }
780
781    #[test]
782    fn the_two_function_codes_are_three_and_four() {
783        assert_eq!(FunctionCode::ReadHoldingRegisters.code(), 3);
784        assert_eq!(FunctionCode::ReadInputRegisters.code(), 4);
785    }
786
787    #[test]
788    fn a_broadcast_unit_is_refused() {
789        let refused = UnitId::new(0);
790
791        assert_eq!(refused, Err(ModbusError::BroadcastUnit));
792    }
793
794    #[test]
795    fn a_reserved_unit_is_refused_by_number() {
796        let refused = UnitId::new(250);
797
798        assert_eq!(refused, Err(ModbusError::ReservedUnit { unit: 250 }));
799    }
800
801    /// 255 is the specification's own value for a device that has no serial
802    /// line behind it, and 247 is the top of the addressable range.
803    #[test]
804    fn an_addressed_unit_is_accepted_including_the_edges() {
805        for unit in [1, 247, 255] {
806            assert_eq!(UnitId::new(unit).map(UnitId::get), Ok(unit));
807        }
808    }
809
810    #[test]
811    fn a_read_of_no_registers_is_refused() {
812        let refused = RegisterCount::new(0);
813
814        assert_eq!(refused, Err(ModbusError::EmptyRead));
815    }
816
817    #[test]
818    fn a_read_above_the_protocols_ceiling_is_refused_naming_it() {
819        let refused = RegisterCount::new(126);
820
821        assert_eq!(
822            refused,
823            Err(ModbusError::TooManyRegisters {
824                count: 126,
825                max: MAX_REGISTERS,
826            })
827        );
828    }
829
830    #[test]
831    fn a_read_at_the_ceiling_is_accepted() {
832        let count = RegisterCount::new(MAX_REGISTERS);
833
834        assert_eq!(count.map(RegisterCount::get), Ok(MAX_REGISTERS));
835    }
836
837    #[test]
838    fn a_register_count_says_how_many_bytes_it_is_owed() {
839        let count = RegisterCount::new(2).expect("two registers");
840
841        assert_eq!(count.byte_count(), 4);
842    }
843
844    #[test]
845    fn a_read_running_past_the_end_of_the_address_space_is_refused() {
846        let refused = ReadRequest::new(
847            TransactionId::new(1),
848            UnitId::new(1).expect("an addressed unit"),
849            FunctionCode::ReadHoldingRegisters,
850            RegisterAddress::new(u16::MAX),
851            RegisterCount::new(2).expect("two registers"),
852        );
853
854        assert_eq!(
855            refused,
856            Err(ModbusError::PastEndOfAddressSpace {
857                start: u16::MAX,
858                count: 2,
859            })
860        );
861    }
862
863    /// The last two registers in the map are a read, not an overrun: the
864    /// boundary is the end of the space, not the last address.
865    #[test]
866    fn a_read_ending_on_the_last_register_is_accepted() {
867        let read = ReadRequest::new(
868            TransactionId::new(1),
869            UnitId::new(1).expect("an addressed unit"),
870            FunctionCode::ReadHoldingRegisters,
871            RegisterAddress::new(u16::MAX - 1),
872            RegisterCount::new(2).expect("two registers"),
873        );
874
875        assert!(read.is_ok());
876    }
877
878    #[test]
879    fn a_normal_reply_decodes_to_its_register_words() {
880        let read = request(1, 1, FunctionCode::ReadHoldingRegisters, 0, 2);
881        let frame = reply(1, 1, 3, &[4, 0x00, 0x2a, 0x01, 0x90]);
882
883        let registers = read.decode(&frame);
884
885        assert_eq!(registers, Ok(vec![42, 400]));
886    }
887
888    /// Synthetic exception reply: unit 1, function code 3 refused, illegal
889    /// data address. Invented bytes; not a capture from a device.
890    #[test]
891    fn the_named_exception_reply_is_an_illegal_data_address() {
892        let read = request(1, 1, FunctionCode::ReadHoldingRegisters, 0, 2);
893        let frame = reply(1, 1, 0x83, &[2]);
894
895        let refused = read.decode(&frame);
896
897        assert_eq!(
898            refused,
899            Err(ModbusError::Exception {
900                function: 3,
901                code: ExceptionCode::IllegalDataAddress,
902            })
903        );
904        assert!(refused
905            .unwrap_err()
906            .to_string()
907            .contains("illegal data address"));
908    }
909
910    #[test]
911    fn an_input_register_read_reports_its_own_exception() {
912        let read = request(1, 1, FunctionCode::ReadInputRegisters, 0, 2);
913        let frame = reply(1, 1, 0x84, &[11]);
914
915        let refused = read.decode(&frame);
916
917        assert_eq!(
918            refused,
919            Err(ModbusError::Exception {
920                function: 4,
921                code: ExceptionCode::GatewayTargetNoResponse,
922            })
923        );
924    }
925
926    #[test]
927    fn an_exception_code_the_specification_does_not_define_is_reported_as_itself() {
928        let read = request(1, 1, FunctionCode::ReadHoldingRegisters, 0, 2);
929        let frame = reply(1, 1, 0x83, &[99]);
930
931        let refused = read.decode(&frame);
932
933        assert_eq!(
934            refused,
935            Err(ModbusError::Exception {
936                function: 3,
937                code: ExceptionCode::Other(99),
938            })
939        );
940    }
941
942    #[test]
943    fn every_named_exception_code_round_trips_through_its_byte() {
944        for code in NAMED_EXCEPTIONS {
945            assert_eq!(ExceptionCode::from(code.byte()), code);
946            assert!(!code.name().is_empty());
947        }
948
949        assert_eq!(ExceptionCode::Other(99).byte(), 99);
950    }
951
952    #[test]
953    fn an_empty_frame_is_too_short() {
954        let read = request(1, 1, FunctionCode::ReadHoldingRegisters, 0, 2);
955
956        let refused = read.decode(&[]);
957
958        assert_eq!(
959            refused,
960            Err(ModbusError::TooShort {
961                expected: 8,
962                found: 0,
963            })
964        );
965    }
966
967    #[test]
968    fn a_header_with_no_body_is_too_short() {
969        let read = request(1, 1, FunctionCode::ReadHoldingRegisters, 0, 2);
970        let frame = framed(1, 0, 2, &[]);
971
972        let refused = read.decode(&frame);
973
974        assert_eq!(
975            refused,
976            Err(ModbusError::TooShort {
977                expected: 8,
978                found: 6,
979            })
980        );
981    }
982
983    #[test]
984    fn a_frame_that_is_not_modbus_is_refused_by_its_protocol_id() {
985        let read = request(1, 1, FunctionCode::ReadHoldingRegisters, 0, 2);
986        let frame = framed(1, 1, 2, &[1, 3]);
987
988        let refused = read.decode(&frame);
989
990        assert_eq!(refused, Err(ModbusError::ProtocolId { found: 1 }));
991    }
992
993    #[test]
994    fn a_declared_length_outside_what_a_frame_can_carry_is_refused() {
995        let read = request(1, 1, FunctionCode::ReadHoldingRegisters, 0, 2);
996        let too_small = framed(1, 0, 1, &[1, 3]);
997        let too_large = framed(1, 0, 255, &[1, 3]);
998
999        let refusals = [read.decode(&too_small), read.decode(&too_large)];
1000
1001        assert_eq!(
1002            refusals,
1003            [
1004                Err(ModbusError::LengthOutOfRange {
1005                    declared: 1,
1006                    min: 2,
1007                    max: 254,
1008                }),
1009                Err(ModbusError::LengthOutOfRange {
1010                    declared: 255,
1011                    min: 2,
1012                    max: 254,
1013                }),
1014            ]
1015        );
1016    }
1017
1018    /// A frame cut short in transit declares more than it carries. Decoding
1019    /// what arrived would report registers the device never sent.
1020    #[test]
1021    fn a_reply_that_declares_more_than_it_carries_is_refused() {
1022        let read = request(1, 1, FunctionCode::ReadHoldingRegisters, 0, 2);
1023        let frame = framed(1, 0, 7, &[1, 3, 4, 0x00, 0x2a]);
1024
1025        let refused = read.decode(&frame);
1026
1027        assert_eq!(
1028            refused,
1029            Err(ModbusError::LengthMismatch {
1030                declared: 7,
1031                found: 5,
1032            })
1033        );
1034    }
1035
1036    /// The frame a device left behind after the caller gave up on it: whole,
1037    /// well-formed, and an answer to the previous read.
1038    #[test]
1039    fn a_reply_to_another_transaction_is_refused_rather_than_decoded() {
1040        let read = request(2, 1, FunctionCode::ReadHoldingRegisters, 0, 2);
1041        let stale = reply(1, 1, 3, &[4, 0x00, 0x2a, 0x01, 0x90]);
1042
1043        let refused = read.decode(&stale);
1044
1045        assert_eq!(
1046            refused,
1047            Err(ModbusError::TransactionMismatch {
1048                expected: 2,
1049                found: 1,
1050            })
1051        );
1052    }
1053
1054    #[test]
1055    fn a_reply_from_another_unit_is_refused() {
1056        let read = request(1, 1, FunctionCode::ReadHoldingRegisters, 0, 2);
1057        let frame = reply(1, 9, 3, &[4, 0x00, 0x2a, 0x01, 0x90]);
1058
1059        let refused = read.decode(&frame);
1060
1061        assert_eq!(
1062            refused,
1063            Err(ModbusError::UnitMismatch {
1064                expected: 1,
1065                found: 9,
1066            })
1067        );
1068    }
1069
1070    #[test]
1071    fn a_reply_carrying_another_function_code_is_refused() {
1072        let read = request(1, 1, FunctionCode::ReadInputRegisters, 0, 2);
1073        let frame = reply(1, 1, 3, &[4, 0x00, 0x2a, 0x01, 0x90]);
1074
1075        let refused = read.decode(&frame);
1076
1077        assert_eq!(
1078            refused,
1079            Err(ModbusError::FunctionMismatch {
1080                expected: 4,
1081                found: 3,
1082            })
1083        );
1084    }
1085
1086    #[test]
1087    fn a_reply_with_fewer_registers_than_were_asked_for_is_refused() {
1088        let read = request(1, 1, FunctionCode::ReadHoldingRegisters, 0, 2);
1089        let frame = reply(1, 1, 3, &[2, 0x00, 0x2a]);
1090
1091        let refused = read.decode(&frame);
1092
1093        assert_eq!(
1094            refused,
1095            Err(ModbusError::ByteCountMismatch {
1096                declared: 2,
1097                expected: 4,
1098            })
1099        );
1100    }
1101
1102    #[test]
1103    fn a_reply_whose_header_and_byte_count_disagree_is_refused() {
1104        let read = request(1, 1, FunctionCode::ReadHoldingRegisters, 0, 2);
1105        let frame = reply(1, 1, 3, &[4, 0x00, 0x2a, 0x01, 0x90, 0x00]);
1106
1107        let refused = read.decode(&frame);
1108
1109        assert_eq!(
1110            refused,
1111            Err(ModbusError::InconsistentLength {
1112                declared: 8,
1113                byte_count: 4,
1114            })
1115        );
1116    }
1117
1118    #[test]
1119    fn a_reply_with_no_byte_count_is_too_short() {
1120        let read = request(1, 1, FunctionCode::ReadHoldingRegisters, 0, 2);
1121        let frame = reply(1, 1, 3, &[]);
1122
1123        let refused = read.decode(&frame);
1124
1125        assert_eq!(
1126            refused,
1127            Err(ModbusError::TooShort {
1128                expected: 9,
1129                found: 8,
1130            })
1131        );
1132    }
1133
1134    #[test]
1135    fn an_exception_reply_with_no_code_is_too_short() {
1136        let read = request(1, 1, FunctionCode::ReadHoldingRegisters, 0, 2);
1137        let frame = reply(1, 1, 0x83, &[]);
1138
1139        let refused = read.decode(&frame);
1140
1141        assert_eq!(
1142            refused,
1143            Err(ModbusError::TooShort {
1144                expected: 9,
1145                found: 8,
1146            })
1147        );
1148    }
1149
1150    /// The whole ceiling, decoded: 125 registers is the largest answer this
1151    /// protocol can give, and it arrives as 125 words.
1152    #[test]
1153    fn a_reply_at_the_register_ceiling_decodes_to_every_word() {
1154        let read = request(1, 1, FunctionCode::ReadInputRegisters, 0, MAX_REGISTERS);
1155        let mut pdu = vec![250];
1156        for word in 0..MAX_REGISTERS {
1157            pdu.extend_from_slice(&word.to_be_bytes());
1158        }
1159        let frame = reply(1, 1, 4, &pdu);
1160
1161        let registers = read.decode(&frame);
1162
1163        assert_eq!(registers, Ok((0..MAX_REGISTERS).collect::<Vec<u16>>()));
1164    }
1165
1166    #[test]
1167    fn a_request_keeps_the_values_it_was_built_from() {
1168        let read = request(7, 9, FunctionCode::ReadInputRegisters, 100, 4);
1169
1170        assert_eq!(read.transaction().get(), 7);
1171        assert_eq!(read.unit().get(), 9);
1172        assert_eq!(read.function(), FunctionCode::ReadInputRegisters);
1173        assert_eq!(read.start().get(), 100);
1174        assert_eq!(read.count().get(), 4);
1175    }
1176}