Skip to content

Instantly share code, notes, and snippets.

@esutton
Last active October 3, 2022 14:26
Show Gist options
  • Save esutton/7d45c713774a8592713d50c85d0609a5 to your computer and use it in GitHub Desktop.
Save esutton/7d45c713774a8592713d50c85d0609a5 to your computer and use it in GitHub Desktop.
Calculate Cypress EZ-Serial BLE Firmware Checksum for a Hex String Input
##########################################
# File: cypress-checksum.py
#
# Calculates EZ Serial checksum from hex string input and appends
# - Hex string input does not require space separated hex bytes
# - Cut & paste output into serial terminal connected to CYBT-483056-EVAL
# - Default Baud 115,200, N, 8, 1
#
# See:
# EZ-Serial BLE Firmware Platform User Guide
# 2.4.2.1 Binary Mode Protocol Characteristics
#
##########################################
import sys
CypressCheckSumSeed = 0x99
CypressHeaderLength = 4
# Binary Message Byte Indexes
ByteType = 0
ByteLength = 1
ByteGroup = 2
ByteId = 3
# Example command:
# gap_get_device_name (GDN, ID=4/16) API command sent to get the configured device name
# C0 00 04 10 6D
# 6D is the checksum
def getCheckSum(hexString):
checkSumLsb = 0
byteArray = bytearray.fromhex(hexString)
byteCount = len(byteArray)
if (byteCount < CypressHeaderLength):
print("*** Error - Message header not found. Expected > %d bytes, found %d" %
(CypressHeaderLength, byteCount))
return checkSumLsb
print("Type.........: 0x%02x" % (byteArray[ByteType]))
print("Length.......: 0x%02x" % (byteArray[ByteLength]))
print("Group........: 0x%02x" % (byteArray[ByteGroup]))
print("Id...........: 0x%02x" % (byteArray[ByteId]))
dataLengthExpected = byteArray[ByteLength]
dataLengthFound = byteCount - CypressHeaderLength
if (dataLengthFound != dataLengthExpected):
print("*** Error - Message length expected %d bytes, found %d, difference %d bytes" %
(dataLengthExpected,
dataLengthFound,
dataLengthFound - dataLengthExpected
))
return checkSumLsb
checkSum = CypressCheckSumSeed
for byteData in byteArray:
checkSum = checkSum + byteData
checkSumLsb = checkSum & 0x00ff
byteArray.append(checkSumLsb)
print("checkSumLsb..: 0x%02x" % (checkSumLsb))
print("checkSum.....: 0x%04x" % (checkSum))
print("byteArray[%02d]: %s" % (byteCount, byteArray.hex()))
return checkSumLsb
def displayUsage(message):
print(message)
print("Usage:")
print("python %s 'C0 00 04 10'" % (sys.argv[0]))
print
if __name__ == '__main__':
argCount = len(sys.argv)
if argCount < 2:
displayUsage("Missing Argument")
sys.exit(0)
hexString = sys.argv[1]
getCheckSum(hexString)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment