comparison micropython/hexlifyscript.py @ 0:ce6b15e13fa9

Initial commit
author Radomir Dopieralski <sheep-devel@sheep.art.pl>
date Thu, 26 Nov 2015 23:10:14 +0100
parents
children
comparison
equal deleted inserted replaced
-1:000000000000 0:ce6b15e13fa9
1 #!/usr/bin/env python3
2
3 '''
4 Turn a Python script into Intel HEX format to be concatenated at the
5 end of the MicroPython firmware.hex. A simple header is added to the
6 script.
7
8 To execute from command line: ./hexlifyscript.py <script.py>
9 '''
10
11 import sys
12 import struct
13 import binascii
14
15 SCRIPT_ADDR = 0x3e000 # magic start address in flash of script
16
17 def hexlify_script(script):
18 # add header, pad to multiple of 16 bytes
19 data = b'MP' + struct.pack('<H', len(script)) + script
20 data = data + bytes(16 - len(data) % 16)
21 assert len(data) <= 0x2000
22
23 # convert to .hex format
24 output = []
25 addr = SCRIPT_ADDR
26 assert(SCRIPT_ADDR >> 16 == 3) # 0x0003 is hard coded in line below
27 output.append(':020000040003F7') # extended linear address, 0x0003
28 for i in range(0, len(data), 16):
29 chunk = data[i:min(i + 16, len(data))]
30 chunk = struct.pack('>BHB', len(chunk), addr & 0xffff, 0) + chunk
31 checksum = (-(sum(chunk))) & 0xff
32 hexline = ':%s%02X' % (str(binascii.hexlify(chunk), 'utf8').upper(), checksum)
33 output.append(hexline)
34 addr += 16
35
36 return '\n'.join(output)
37
38 if __name__ == '__main__':
39 # read script from a file and print out the hexlified version
40 with open(sys.argv[1], 'rb') as f:
41 print(hexlify_script(f.read()))