Page 1 of 1
Python: Generating checksum
Posted: Thu Nov 26, 2009 1:00 am
by Fiasco
For Mitsu TV's, a checksum ends every command.
Any tips on generating this checksum in Python?
If the command is
DF 80 70 F8 02 00 00
The checksum is the sum of the above (2C9). take the low byte (C9) convert to binary and do ones compliment then return to hex (36H)
This formula (so to speak) for generating the mitsu checksum was posted by Audible Solutions
here
Re: Python: Generating checksum
Posted: Thu Nov 26, 2009 3:48 am
by Fiasco
This is what I have so far
Code: Select all
data = "DF8070F8020000"
pairs = []
for i in range(0,len(data),2):
pairs.append(data[i:i+2])
value = 0
for i in pairs:
value = value + int(i,16)
value = hex(value)
value = (int(value,16) & int('ff',16))
# at this point the value is C9
value = hex(value)
value = (int(value,16) ^ int('11111111',2))
# value is now 36
value = binascii.a2b_hex(data) + hex(value)
self.plugin.serialThread.Write(value)
Is this right?
Now, how do I do one's compliment on C9 to get the final value (0x36)?
This is for the Mitsu LT249 plugin
found here
RS232 docs and plugin available in that thread.
Re: Python: Generating checksum
Posted: Thu Nov 26, 2009 8:40 am
by jinxdone
That looks about right to me Fiasco. Here's another way of doing pretty much the same thing.
- The string.decode("hex") converts the string so that it's the same as if you had input it as "\xDF\x80\x70\xF8\x02\x00\x00", so now we can loop through it easily one character at a time.
- Looping through the string use ord(byte) to get the value of the character as an integer, so we can sum it up.
- After we have the sum then get the low byte by doing a bitwise AND against value 0xFF.
- To get the one's complement invert the bits, which you can do with bitwise XOR against value 0xFF.
- Finally append our checksum byte to the string.
Code: Select all
data = "DF8070F8020000".decode("hex")
sum = 0
for byte in data:
sum += ord(byte)
data += chr((sum & 0xFF) ^ 0xFF)
# Here's how to get the one's complement of the low byte of the sum
print "Sum:", sum, "=", hex(sum)
print "Low byte:", hex(sum & 0xFF)
print "One's complement:", hex((sum & 0xFF) ^ 0xFF)
-jinxdone
Re: Python: Generating checksum
Posted: Thu Nov 26, 2009 7:59 pm
by Fiasco
Thanks Jinx. I knew there would be a much quicker/simpler way to go about doing it.
I am going to have to find some time to squeeze a python book or two in.
Re: Python: Generating checksum
Posted: Fri Nov 27, 2009 6:38 am
by Fiasco
How do I do a two's complement?
I'm doing the same thing but for samsung tv's now.
Re: Python: Generating checksum
Posted: Fri Nov 27, 2009 7:35 am
by Fiasco
Code: Select all
data = value.decode("hex")
sum = 0
for byte in data:
sum += ord(byte)
print "Two's complement:", hex((~sum + 1) & 0xFF)
return hex((~sum + 1) & 0xFF)
[/code]
That gave me the right checksum anway for two's compliment of he sum of the command.