|
| 1 | +# Written by Antonio Galea - 2010/11/18 |
| 2 | +# Stripped down & modified by Keir Fraser for FlashFloppy project |
| 3 | +# Distributed under Gnu LGPL 3.0 |
| 4 | +# see http://www.gnu.org/licenses/lgpl-3.0.txt |
| 5 | + |
| 6 | +import sys,struct,zlib |
| 7 | +from optparse import OptionParser |
| 8 | +from intelhex import IntelHex |
| 9 | + |
| 10 | +DEFAULT_DEVICE="0x0483:0xdf11" |
| 11 | + |
| 12 | +def compute_crc(data): |
| 13 | + return 0xFFFFFFFF & -zlib.crc32(data) -1 |
| 14 | + |
| 15 | +def build(file,targets,device=DEFAULT_DEVICE): |
| 16 | + data = b'' |
| 17 | + for t,target in enumerate(targets): |
| 18 | + tdata = b'' |
| 19 | + for image in target: |
| 20 | + tdata += struct.pack('<2I',image['address'],len(image['data']))+image['data'] |
| 21 | + tdata = struct.pack('<6sBI255s2I',b'Target',0,1,b'ST...',len(tdata),len(target)) + tdata |
| 22 | + data += tdata |
| 23 | + data = struct.pack('<5sBIB',b'DfuSe',1,len(data)+11,len(targets)) + data |
| 24 | + v,d=map(lambda x: int(x,0) & 0xFFFF, device.split(':',1)) |
| 25 | + data += struct.pack('<4H3sB',0,d,v,0x011a,b'UFD',16) |
| 26 | + crc = compute_crc(data) |
| 27 | + data += struct.pack('<I',crc) |
| 28 | + open(file,'wb').write(data) |
| 29 | + |
| 30 | +if __name__=="__main__": |
| 31 | + usage = """ |
| 32 | +%prog {-i|--ihex} file.hex [-i file.hex ...] [{-D|--device}=vendor:device] outfile.dfu""" |
| 33 | + |
| 34 | + parser = OptionParser(usage=usage) |
| 35 | + parser.add_option("-i", "--ihex", action="append", dest="hexfiles", |
| 36 | + help="build a DFU file from given HEXFILES", metavar="HEXFILES") |
| 37 | + parser.add_option("-D", "--device", action="store", dest="device", |
| 38 | + help="build for DEVICE, defaults to %s" % DEFAULT_DEVICE, metavar="DEVICE") |
| 39 | + (options, args) = parser.parse_args() |
| 40 | + |
| 41 | + if options.hexfiles and len(args)==1: |
| 42 | + target = [] |
| 43 | + |
| 44 | + for h in options.hexfiles: |
| 45 | + ih = IntelHex(h) |
| 46 | + for (s,e) in ih.segments(): |
| 47 | + target.append({ 'address': s, 'data': ih.tobinstr(s,e-1) }) |
| 48 | + |
| 49 | + outfile = args[0] |
| 50 | + device = DEFAULT_DEVICE |
| 51 | + if options.device: |
| 52 | + device=options.device |
| 53 | + try: |
| 54 | + v,d=map(lambda x: int(x,0) & 0xFFFF, device.split(':',1)) |
| 55 | + except: |
| 56 | + print("Invalid device '%s'." % device) |
| 57 | + sys.exit(1) |
| 58 | + build(outfile,[target],device) |
| 59 | + else: |
| 60 | + parser.print_help() |
| 61 | + sys.exit(1) |
0 commit comments