intelHex.py 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. """
  2. Module to read intel hex files into binary data blobs.
  3. IntelHex files are commonly used to distribute firmware
  4. See: http://en.wikipedia.org/wiki/Intel_HEX
  5. This is a python 3 conversion of the code created by David Braam for the Cura project.
  6. """
  7. import io
  8. def readHex(filename):
  9. """
  10. Read an verify an intel hex file. Return the data as an list of bytes.
  11. """
  12. data = []
  13. extra_addr = 0
  14. f = io.open(filename, "r")
  15. for line in f:
  16. line = line.strip()
  17. if len(line) < 1:
  18. continue
  19. if line[0] != ":":
  20. raise Exception("Hex file has a line not starting with ':'")
  21. rec_len = int(line[1:3], 16)
  22. addr = int(line[3:7], 16) + extra_addr
  23. rec_type = int(line[7:9], 16)
  24. if len(line) != rec_len * 2 + 11:
  25. raise Exception("Error in hex file: " + line)
  26. check_sum = 0
  27. for i in range(0, rec_len + 5):
  28. check_sum += int(line[i*2+1:i*2+3], 16)
  29. check_sum &= 0xFF
  30. if check_sum != 0:
  31. raise Exception("Checksum error in hex file: " + line)
  32. if rec_type == 0:#Data record
  33. while len(data) < addr + rec_len:
  34. data.append(0)
  35. for i in range(0, rec_len):
  36. data[addr + i] = int(line[i*2+9:i*2+11], 16)
  37. elif rec_type == 1: #End Of File record
  38. pass
  39. elif rec_type == 2: #Extended Segment Address Record
  40. extra_addr = int(line[9:13], 16) * 16
  41. else:
  42. print(rec_type, rec_len, addr, check_sum, line)
  43. f.close()
  44. return data