intelHex.py 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  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. from UM.Logger import Logger
  9. def readHex(filename):
  10. """
  11. Read an verify an intel hex file. Return the data as an list of bytes.
  12. """
  13. data = []
  14. extra_addr = 0
  15. f = io.open(filename, "r", encoding = "utf-8")
  16. for line in f:
  17. line = line.strip()
  18. if len(line) < 1:
  19. continue
  20. if line[0] != ":":
  21. raise Exception("Hex file has a line not starting with ':'")
  22. rec_len = int(line[1:3], 16)
  23. addr = int(line[3:7], 16) + extra_addr
  24. rec_type = int(line[7:9], 16)
  25. if len(line) != rec_len * 2 + 11:
  26. raise Exception("Error in hex file: " + line)
  27. check_sum = 0
  28. for i in range(0, rec_len + 5):
  29. check_sum += int(line[i*2+1:i*2+3], 16)
  30. check_sum &= 0xFF
  31. if check_sum != 0:
  32. raise Exception("Checksum error in hex file: " + line)
  33. if rec_type == 0:#Data record
  34. while len(data) < addr + rec_len:
  35. data.append(0)
  36. for i in range(0, rec_len):
  37. data[addr + i] = int(line[i*2+9:i*2+11], 16)
  38. elif rec_type == 1: #End Of File record
  39. pass
  40. elif rec_type == 2: #Extended Segment Address Record
  41. extra_addr = int(line[9:13], 16) * 16
  42. else:
  43. Logger.log("d", "%s, %s, %s, %s, %s", rec_type, rec_len, addr, check_sum, line)
  44. f.close()
  45. return data