Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 16 additions & 0 deletions rtuclient.go
Original file line number Diff line number Diff line change
Expand Up @@ -90,6 +90,22 @@ func (mb *rtuPackager) Verify(aduRequest []byte, aduResponse []byte) (err error)
// Decode extracts PDU from RTU frame and verify CRC.
func (mb *rtuPackager) Decode(adu []byte) (pdu *ProtocolDataUnit, err error) {
length := len(adu)

if length > 1 && adu[1] < 5 {
// adjust real length
if length < 3 {
err = fmt.Errorf("modbus: response length less than min '%v'", length)
return
} else {
real_len := int(adu[2]) + 5
if real_len > length {
err = fmt.Errorf("modbus: response length '%v' less than real length '%v'", length, real_len)
return
} else {
length = real_len
}
}
}
// Calculate checksum
var crc crc
crc.reset().pushBytes(adu[0 : length-2])
Expand Down
11 changes: 6 additions & 5 deletions rtuclient_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -29,17 +29,17 @@ func TestRTUEncoding(t *testing.T) {

func TestRTUDecoding(t *testing.T) {
decoder := rtuPackager{}
adu := []byte{0x01, 0x10, 0x8A, 0x00, 0x00, 0x03, 0xAA, 0x10}
adu := []byte{0x05, 0x03, 0x02, 0x00, 0xAA, 0xC9, 0xFB, 0xFF, 0xFF, 0xFF, 0xFF}

pdu, err := decoder.Decode(adu)
if err != nil {
t.Fatal(err)
}

if 16 != pdu.FunctionCode {
t.Fatalf("Function code: expected %v, actual %v", 16, pdu.FunctionCode)
if 3 != pdu.FunctionCode {
t.Fatalf("Function code: expected %v, actual %v", 3, pdu.FunctionCode)
}
expected := []byte{0x8A, 0x00, 0x00, 0x03}
expected := []byte{0x02, 0x00, 0xAA}
if !bytes.Equal(expected, pdu.Data) {
t.Fatalf("Data: expected %v, actual %v", expected, pdu.Data)
}
Expand Down Expand Up @@ -88,7 +88,8 @@ func BenchmarkRTUDecoder(b *testing.B) {
decoder := rtuPackager{
SlaveId: 10,
}
adu := []byte{0x01, 0x10, 0x8A, 0x00, 0x00, 0x03, 0xAA, 0x10}
// adu := []byte{0x01, 0x10, 0x8A, 0x00, 0x00, 0x03, 0xAA, 0x10}
adu := []byte{0x05, 0x03, 0x02, 0x00, 0xAA, 0xC9, 0xFB, 0xFF, 0xFF, 0xFF}
for i := 0; i < b.N; i++ {
_, err := decoder.Decode(adu)
if err != nil {
Expand Down