1use std::fmt;
8
9#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
15pub enum ModbusError {
16 #[error("unit id 0 is a broadcast, which no device answers; a read needs an addressed unit")]
18 BroadcastUnit,
19 #[error("unit id {unit} is reserved by the specification (248-254)")]
21 ReservedUnit {
22 unit: u8,
24 },
25 #[error("a read of no registers asks a device for nothing")]
27 EmptyRead,
28 #[error("a read of {count} registers is above the {max} this function code can answer")]
30 TooManyRegisters {
31 count: u16,
33 max: u16,
35 },
36 #[error("a read of {count} registers from {start} runs past the end of the address space")]
38 PastEndOfAddressSpace {
39 start: u16,
41 count: u16,
43 },
44 #[error("the reply is {found} bytes, too few for the {expected} this frame needs")]
46 TooShort {
47 expected: usize,
49 found: usize,
51 },
52 #[error("the reply carries protocol id {found}, so it is not Modbus")]
54 ProtocolId {
55 found: u16,
57 },
58 #[error("the reply declares {declared} bytes, outside the {min} to {max} a frame can carry")]
60 LengthOutOfRange {
61 declared: u16,
63 min: u16,
65 max: u16,
67 },
68 #[error("the reply declares {declared} bytes and carries {found}")]
70 LengthMismatch {
71 declared: u16,
73 found: u16,
75 },
76 #[error("the reply answers transaction {found}, and this read is transaction {expected}")]
78 TransactionMismatch {
79 expected: u16,
81 found: u16,
83 },
84 #[error("the reply comes from unit {found}, and this read went to unit {expected}")]
86 UnitMismatch {
87 expected: u8,
89 found: u8,
91 },
92 #[error("the reply carries function code {found}, and this read used {expected}")]
94 FunctionMismatch {
95 expected: u8,
97 found: u8,
99 },
100 #[error("the device refused function code {function}: {code}")]
102 Exception {
103 function: u8,
105 code: ExceptionCode,
107 },
108 #[error("the reply carries {declared} bytes of registers, and this read asked for {expected}")]
110 ByteCountMismatch {
111 declared: u16,
113 expected: u16,
115 },
116 #[error(
118 "the reply's header declares {declared} bytes and its byte count implies {byte_count}"
119 )]
120 InconsistentLength {
121 declared: u16,
123 byte_count: u8,
125 },
126 #[error("a {kind} reads {expected} registers and was handed {found}")]
128 WordCount {
129 kind: &'static str,
131 expected: u16,
133 found: usize,
135 },
136 #[error("a register scale is a finite number")]
138 NonFiniteScale,
139 #[error("a scale of zero reads every register as nothing")]
141 ZeroScale,
142}
143
144#[derive(Debug, Clone, Copy, PartialEq, Eq)]
149pub enum ExceptionCode {
150 IllegalFunction,
152 IllegalDataAddress,
154 IllegalDataValue,
156 ServerDeviceFailure,
158 Acknowledge,
160 ServerDeviceBusy,
162 NegativeAcknowledge,
164 MemoryParityError,
166 GatewayPathUnavailable,
168 GatewayTargetNoResponse,
170 Other(u8),
172}
173
174#[derive(Debug, Clone, Copy, PartialEq, Eq)]
180pub enum FunctionCode {
181 ReadHoldingRegisters,
183 ReadInputRegisters,
185}
186
187#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
193pub struct TransactionId(u16);
194
195#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
202pub struct UnitId(u8);
203
204#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
206pub struct RegisterAddress(u16);
207
208#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
213pub struct RegisterCount(u16);
214
215#[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
226pub const MAX_REGISTERS: u16 = 125;
228
229const PROTOCOL_ID: u16 = 0;
231
232const REQUEST_LENGTH: u16 = 6;
235
236pub(crate) const HEADER_PREFIX_LEN: usize = 6;
239
240const REQUEST_FRAME_LEN: usize = HEADER_PREFIX_LEN + REQUEST_LENGTH as usize;
242
243pub(crate) const MIN_LENGTH: u16 = 2;
245
246pub(crate) const MAX_LENGTH: u16 = 254;
249
250const MIN_FRAME_LEN: usize = HEADER_PREFIX_LEN + MIN_LENGTH as usize;
252
253const EXCEPTION_BIT: u8 = 0x80;
255
256const 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#[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 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
289fn 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
295fn 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 #[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 #[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 #[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
402impl 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 #[must_use]
431 pub const fn new(id: u16) -> Self {
432 Self(id)
433 }
434
435 #[must_use]
437 pub const fn get(self) -> u16 {
438 self.0
439 }
440}
441
442impl UnitId {
443 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 #[must_use]
459 pub const fn get(self) -> u8 {
460 self.0
461 }
462}
463
464impl RegisterAddress {
465 #[must_use]
467 pub const fn new(address: u16) -> Self {
468 Self(address)
469 }
470
471 #[must_use]
473 pub const fn get(self) -> u16 {
474 self.0
475 }
476}
477
478impl RegisterCount {
479 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 #[must_use]
500 pub const fn get(self) -> u16 {
501 self.0
502 }
503
504 #[must_use]
506 pub const fn byte_count(self) -> u16 {
507 self.0 * 2
508 }
509}
510
511impl ReadRequest {
512 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 #[must_use]
545 pub const fn transaction(&self) -> TransactionId {
546 self.transaction
547 }
548
549 #[must_use]
551 pub const fn unit(&self) -> UnitId {
552 self.unit
553 }
554
555 #[must_use]
557 pub const fn function(&self) -> FunctionCode {
558 self.function
559 }
560
561 #[must_use]
563 pub const fn start(&self) -> RegisterAddress {
564 self.start
565 }
566
567 #[must_use]
570 pub const fn count(&self) -> RegisterCount {
571 self.count
572 }
573
574 #[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 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 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 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 Ok(words
661 .chunks_exact(2)
662 .map(|pair| u16::from_be_bytes([pair[0], pair[1]]))
663 .collect())
664 }
665}
666
667fn 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 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 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 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 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 #[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 #[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 #[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 #[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 #[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 #[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 #[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 #[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}