Implementation of ELK Serial Protocol Checksum in Python

cipherwar

Member
I am having problems getting some python code to properly calculate the checksums for the Elk serial protocol.   
 
I have looked at the serial protocol document and the example C source code in the Appendix.   I have also downloaded the ELK SDK so that I can verify what the SDK is calculating for a checksum vs my code.
 
The way I understand it the checksum is the sum of all of the decimal representation of the ASCII characters in the message taken mod256.   That number is then taken as a twos complement.  
 
Code below.    Using a test string of 00300005000 the SDK outputs a checksum of 74 while the below outputs 19.    Since the SDK doesn't include source I can see what their tool is doing.   Does anyone here have some experience with this?   Any pointers would be very appreciated.
 
Thanks  
 
def calc_checksum (string):
    '''
    Calculcates checksum for sending commands to the ELKM1.  Sums the ASCII character values mod256 and takes
    the Twos complement
    '''
    sum= 0
 
    for i in range(len(string)) :
        sum = sum + ord(string)
 
    temp = sum % 256
    rem = temp ^ 256
    rem = rem + 1
    cc1 = hex(rem)
    cc = cc1.upper()
    p=len(cc)
    return cc[p-2:p]
 
Here is some Ruby code from an M1 Siri project:
 
# Append checksum to M1 message
def m1_add_checksum(message)
  # calc the checksum
  chk = 0
  message.each_byte do |b|
    chk = (chk + b ) & 0xff
  end
  # two's compliment
  chk = 0x100 - chk
  # add leading zero
  #  if chk < 16
  #    chkstr='0'+chk.to_s(16)
  #  else
  #    chkstr=chk.to_s(16)
  #  end
  # format with leading zero
  chkstr = ("0"+chk.to_s(16)).slice(-2,2)
  # return as 2 digit uppercase hex string
  return message+chkstr.upcase
end
 
Niether Ruby or Python are my native programming languages, but it appears you need to MOD 256 inside your For loop.
 
HTH
Mike
 
Here's the two-liner I use in Scala:
https://github.com/JamieEi/elkm1-scala/blob/master/src/main/scala/Message.scala#L10
 
I believe that the Python equivalent on the first line would be (pardon my syntax, I don't know Python):
sumOfChars = reduce(operator.add, msgChars, 0)
 
It sounds like Python also has a sum function that does a limited subset of what fold/reduce does:
http://stackoverflow.com/questions/10366374/what-is-the-pythonic-equivalent-to-the-fold-function-from-functional-program
 
Ahh, ok. The serial spec from elk seemed to indicate to sum the ASCII values and then take mod256. I'll try taking each ASCII value as a mod256 and then doing the sum. Once I get the Python code working ill share here.

Thank you
 
Back
Top