0

I'm trying to check the sum of some data stored in a dictionary of bytes (block variable) and I'm getting this weird behavior.

TypeError: unsupported operand type(s) for +: 'int' and 'bytes'

Here is a snippet.

values = block.values()

if sum(values) == data:
    return True
 
else:
    return False

The block looks like this:

{'V': b'26587\r', 'VS': b'31\r', 'I': b'0\r', 'P': b'0\r', 'CE': b'0\r', 'SOC': b'1000\r', 'TTG': b'-1\r', 'Alarm': b'OFF\r', 'Relay': b'OFF\r', 'AR': b'0\r', 'BMV': b'712 Smart\r', 'FW': b'0408\r', 'MON': b'0\r'}
mkrieger1
  • 19,194
  • 5
  • 54
  • 65
Xu Dank
  • 1
  • 1
  • 1
    What do you mean by "sum"? Do you want to add the numbers in the bytestrings? – wizzwizz4 Jul 21 '22 at 19:57
  • @mkrieger1 I tried using 'bytes()' as the starting value but got an error. The error suggested that I used the 'join()' method so I did and got b'26590\r32\r0\r0\r0\r1000\r-1\rOFF\rOFF\r0\r712 Smart\r0408\r0\r'. – Xu Dank Jul 21 '22 at 20:07
  • 1
    @wizzwizz4 I am trying to sum up the data to compare it with a checksum byte (b'\xf1\r') – Xu Dank Jul 21 '22 at 20:09
  • 1
    @XuDank You're going to have to explain in more detail what you mean to do, then. – wizzwizz4 Jul 21 '22 at 20:13

1 Answers1

0

It looks like you are working with a BMV-712 Smart and their Protocol FAQ says the checksum is calculated by adding all the values together (including the keys and checksum) with the value wrapping at 255.

Turning their pseudo code into Python I get the expected answer for their example:

def create_checksum(msg):
    value = 0x00
    for bite in msg:
        value = (value + bite) % 256
    return value


message = (b'\r\nPID\t0x203\r\nV\t26201\r\nI\t0\r\nP\t0\r\nCE\t0\r\n'
           b'SOC\t1000\r\nTTG\t-1\r\nAlarm\tOFF\r\nRelay\tOFF\r\nAR\t0\r\n'
           b'BMV\t700\r\nFW\t0307\r\nChecksum\t\xd8')
msg1 = create_checksum(message)
print(f"Msg1: Expect 0x0: Got = {hex(msg1)}")
# Msg1: Expect 0x00: Got = 0x0

I've taken your data and manually made it one message and added in the checksum values but it is not working:

def create_checksum(msg):
    value = 0x00
    for bite in msg:
        value = (value + bite) % 256
    return value

data_txt2 = (b'\x0dV\t26587\rVS\t31\rI\t0\rP\t0\r'
             b'CE\t0\rSOC\t1000\rTTG\t-1\r'
             b'Alarm\tOFF\rRelay\tOFF\rAR\t0\r'
             b'BMV\t712 Smart\rFW\t0408\rMON\t0\r'
             b'Checksum\t\xf1\r')

msg2 = create_checksum(data_txt2)
print(f"Msg2: Expect 0x0: Got = {hex(msg2)}")
# Msg2: Expect 0x0: Got = 0x4

This is giving the wrong answer so I suspect the data you have shared is not quite right.

ukBaz
  • 6,985
  • 2
  • 8
  • 31