chiark / gitweb /
Skip empty lines for #1010
[cura.git] / Cura / avr_isp / intelHex.py
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 """
6 __copyright__ = "Copyright (C) 2013 David Braam - Released under terms of the AGPLv3 License"
7 import io
8
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         extraAddr = 0
15         f = io.open(filename, "r")
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                 recLen = int(line[1:3], 16)
23                 addr = int(line[3:7], 16) + extraAddr
24                 recType = int(line[7:9], 16)
25                 if len(line) != recLen * 2 + 11:
26                         raise Exception("Error in hex file: " + line)
27                 checkSum = 0
28                 for i in xrange(0, recLen + 5):
29                         checkSum += int(line[i*2+1:i*2+3], 16)
30                 checkSum &= 0xFF
31                 if checkSum != 0:
32                         raise Exception("Checksum error in hex file: " + line)
33                 
34                 if recType == 0:#Data record
35                         while len(data) < addr + recLen:
36                                 data.append(0)
37                         for i in xrange(0, recLen):
38                                 data[addr + i] = int(line[i*2+9:i*2+11], 16)
39                 elif recType == 1:      #End Of File record
40                         pass
41                 elif recType == 2:      #Extended Segment Address Record
42                         extraAddr = int(line[9:13], 16) * 16
43                 else:
44                         print(recType, recLen, addr, checkSum, line)
45         f.close()
46         return data