1#! /usr/bin/env python
2
3import os, sys, re, struct, getopt
4from sys import platform
5import array,hashlib,struct
6
7def print_usage():
8	print("")
9	print("Usage:" + sys.argv[0])
10	print(sys.argv[0] + " main_bin mcu_bin offset magic")
11	print(" [-h | --help] Display usage")
12	sys.stdout.flush()
13
14def write_file(file_name, gap_szie, data):
15        if file_name is None:
16                print 'file_name cannot be none\n'
17                sys.exit(0)
18        fp = open(file_name,'ab')
19        if fp:
20		fp.write(data)
21                if gap_szie > 0:
22                        fp.write('\xFF'*gap_szie)
23                fp.close()
24        else:
25                print '%s write fail\n'%(file_name)
26
27def comp_file_md5(input_file, magic_str):
28	magic = int(magic_str, 16)
29	output_file = input_file+".ota"
30	fin = open(input_file, 'rb')
31	data = fin.read()
32	fout = open(output_file, 'wb')
33	fout.write(data)
34	size = os.path.getsize(input_file)
35	fout.write(struct.pack('<I', magic))
36	fout.write(struct.pack('<I', size))
37	fout.write(hashlib.md5(data).digest())
38	print("magic:0x%x size:%d md5:%s" %(magic, size, hashlib.md5(data).hexdigest()))
39	reserve = bytearray([0xFF,0xFF])
40	fout.write(reserve)
41	fout.write(reserve)
42	fin.close()
43	fout.close()
44	os.remove(input_file)
45	os.rename(output_file, input_file)
46
47def main():
48	try:
49        	opts, args = getopt.getopt(sys.argv[1:], "h", ["help"])
50    	except getopt.GetoptError as err:
51		print(str(err))
52		print_usage()
53		sys.exit(2)
54    	magic = "0xefcdefcd"
55	if len(args) < 3:
56		print_usage()
57		sys.exit(2)
58	else:
59		main_file = args[0]
60		mcu_file = args[1]
61		offset = int(args[2], 16)
62
63	if len(args) > 3:
64		magic =  args[3]
65
66	if not os.path.exists(main_file):
67		print("Input a main file.")
68		sys.exit(2)
69
70	output_file = main_file+"_ota.bin"
71	if os.path.exists(output_file):
72		os.remove(output_file)
73
74	gap_szie = offset - os.path.getsize(main_file)
75        fmain = open(main_file, 'rb')
76        main_data = fmain.read()
77	fp = open(output_file,'ab')
78	if fp:
79		fp.write(main_data)
80
81        fmcu = open(mcu_file, 'rb')
82        mcu_data = fmcu.read()
83	print("file main:0x%x  mcu:0x%x  off:0x%x " %(os.path.getsize(main_file), os.path.getsize(mcu_file), offset))
84	if gap_szie > 0:
85		fp.write('\xFF'*gap_szie)
86        if fp:
87                fp.write(mcu_data)
88	fp.close()
89	fmcu.close()
90	fmain.close()
91	comp_file_md5(output_file, magic)
92
93if __name__ == "__main__":
94	try:
95		main()
96	except KeyboardInterrupt:
97		pass
98