I'm setting up a uart communication with a device, but I can't figure out how to generate the four bytes checksum that is required to validate the data I'm sending. In the instrument manual says that the checksum is "a 32-bit unsigned value that sums all the bytes in Data Header and Data Payload. Checksum overflows are truncated".
I've tried among other things to sum all of the data bytearray and then convert it to bytes. But no matter what I try all I get in response from the device is the error message. Which I believe is due the wrong checksum. I'm trying to use the function below to concatenate all of the bytes needed. Im sending the data using pyserial library.
def empacota(flags, sequence, command, data):
cksumMsg = b""
uart_header = b"\x41\x42\x43\x44"
uart_end = b"\x44\x43\x42\x41"
data_len = bytes(len(data) + 2)
cksumMsg += flags + sequence + data_len + command + data
cksumMsg_array = bytearray(cksumMsg)
checksum_int = sum(cksumMsg_array)
checksum = checksum_int.to_bytes(5, "little")
package_data = uart_header + checksum + cksumMsg + uart_end
return(package_data)
After studying a little about binaries and Bitwise operators I could get the communication going. Here is the working function that generates my package data.
def empacota(flags, sequence, command, data):
cksumMsg = b''
UARTHeader = b"\x41\x42\x43\x44"
UARTTrailer = b"\x44\x43\x42\x41"
data_len = len(data) + 2
cksumMsg += bytes(flags + sequence) + data_len.to_bytes(2,
byteorder='little') + bytes(command + data)
checksum_int = (sum(cksumMsg))
checksum = checksum_int.to_bytes(4, "little")
package_data = UARTHeader + checksum + cksumMsg + UARTTrailer
return(package_data)
For more information: https://wiki.python.org/moin/BitwiseOperators