Skip to content

Commit

Permalink
feat(cbus): validate the checksum on read
Browse files Browse the repository at this point in the history
  • Loading branch information
sruehl committed Jul 21, 2022
1 parent 905649e commit cfffc80
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 10 deletions.
17 changes: 12 additions & 5 deletions plc4go/protocols/cbus/readwrite/model/StaticHelper.go
Original file line number Diff line number Diff line change
Expand Up @@ -123,16 +123,23 @@ func readBytesFromHex(logicalName string, readBuffer utils.ReadBuffer, payloadLe
readBuffer.Reset(readBuffer.GetPos() - 1)
hexBytes = hexBytes[:len(hexBytes)-1]
}
if srchk {
// We need to reset the last to hex bytes
readBuffer.Reset(readBuffer.GetPos() - 2)
hexBytes = hexBytes[:len(hexBytes)-2]
}
rawBytes := make([]byte, hex.DecodedLen(len(hexBytes)))
n, err := hex.Decode(rawBytes, hexBytes)
if err != nil {
return nil, err
}
if srchk {
checksum := byte(0x0)
for _, aByte := range rawBytes {
checksum += aByte
}
if checksum != 0x0 {
return nil, errors.New("Checksum validation failed")
}
// We need to reset the last to hex bytes
readBuffer.Reset(readBuffer.GetPos() - 2)
rawBytes = rawBytes[:len(rawBytes)-1]
}
log.Debug().Msgf("%d bytes decoded", n)
return rawBytes, nil
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -102,17 +102,24 @@ private static byte[] readBytesFromHex(String logicalName, ReadBuffer readBuffer
readBuffer.reset(readBuffer.getPos() - 1);
hexBytes = Arrays.copyOf(hexBytes, hexBytes.length - 1);
}
if (srchk) {
// We need to reset the last to hex bytes
readBuffer.reset(readBuffer.getPos() - 2);
hexBytes = Arrays.copyOf(hexBytes, hexBytes.length - 2);
}
byte[] rawBytes;
try {
rawBytes = Hex.decodeHex(new String(hexBytes));
} catch (DecoderException e) {
throw new ParseException("error getting hex", e);
}
if (srchk) {
byte checksum = 0x0;
for (byte aByte : rawBytes) {
checksum+=aByte;
}
if (checksum != 0x0) {
throw new ParseException("Checksum validation failed");
}
// We need to reset the last to hex bytes
readBuffer.reset(readBuffer.getPos() - 2);
rawBytes = Arrays.copyOf(rawBytes, rawBytes.length - 1);
}
return rawBytes;
}

Expand Down

0 comments on commit cfffc80

Please sign in to comment.