#!/usr/bin/env python # -*- coding: iso-8859-15 -*- import sys def out(s): sys.stdout.write(s) def die(s): sys.stderr.write(s) sys.exit(1) page_shift = 6 page_size = 1 << page_shift npages = 128 mem = (npages * page_size) * [0xff]; minaddr = 0xffff maxaddr = 0x0000 ok = False CRC16 = 0x11021 # CRC-CCITT = X^16 + X^12 + X^5 + 1 def crc_update(crc, byte): for i in range(8): high = crc & 0x8000 crc = crc << 1 if byte & 0x80: crc += 1 byte = byte << 1 if high: crc = (crc ^ CRC16) & 0xffff return crc for s in sys.stdin.readlines(): if s[:1] != ':': die('Intel hex expected\n') if s[-1:] == '\n': s = s[:-1] if s[-1:] == '\r': s = s[:-1] if s == ':00000001FF': ok = True break bytes = int(s[1:3], 16) if len(s) != 2 * bytes + 11: die('bytes %d, line length %d: not good.\n' % (bytes, len(s))) if s[7:9] == '03': continue if s[7:9] != '00': die('Bad Intel hex record type (must be zero)\n') addr = int(s[3:7], 16) cs = int(s[-2:], 16) + bytes + (addr & 0xff) + (addr >> 8) data = s[9:-2] if addr < minaddr: minaddr = addr while bytes: b = int(data[:2], 16) data = data[2:] cs += b mem[addr] = b addr += 1 bytes -= 1 if addr > maxaddr: maxaddr = addr if cs & 0xff: die('bad checksum: %d\n' % (cs,)) if not ok: die('Missing record type 1.\n') minpage = minaddr / page_size maxpage = (maxaddr - 1) / page_size + 1 program = [] out('prog_uint8_t program[] =\n{\n') for pageno in range(minpage, maxpage): packet = [ 0x0F, pageno, maxpage - minpage ] for i in range(page_size): packet += [mem[(pageno << page_shift) + i]] crc = 0 for i in range(len(packet)): crc = crc_update(crc, packet[i]) crc = crc_update(crc, 0) crc = crc_update(crc, 0) packet += [ crc >> 8, crc & 255 ] tab = '/* %04x */\t' % (pageno << page_shift) for i in range(len(packet)): out('%s%3d,' % (tab, packet[i])) tab = '' if i % 16 == 15: tab = '\n\t\t' out('\n') out('/* END */\t0\n};\n')