1#!/usr/bin/env python.
2# Copyright (c) 2022 Espressif Systems (Shanghai) PTE LTD.
3# Distributed under the terms of Apache License v2.0 found in the top-level LICENSE file.
4
5import argparse
6import sys
7
8def bin2c_array(data, var_name='esp32_net_fw_array'):
9    out = []
10    out.append('const unsigned char {var_name}[] = {{'.format(var_name=var_name))
11    l = [ data[i:i+12] for i in range(0, len(data), 12) ]
12    for i, x in enumerate(l):
13        line = ', '.join([ '0x{val:02x}'.format(val=c) for c in x ])
14        out.append('  {line}{end_comma}'.format(line=line, end_comma=',' if i<len(l)-1 else ''))
15    out.append('};')
16    out.append('const unsigned int {var_name}_size = {data_len};'.format(var_name=var_name, data_len=len(data)))
17    return '\n'.join(out)
18
19def main():
20    parser = argparse.ArgumentParser(description='Binary to C array generator')
21    parser.add_argument('-i', '--input', required=True , help='.bin input file')
22    parser.add_argument('-o', '--out', required=True , help='c file name')
23    parser.add_argument('-a', '--array', required=True , help='c array variable name')
24
25    args = parser.parse_args()
26    if not args:
27        return 1
28
29    with open(args.input, 'rb') as f:
30        data = f.read()
31
32    out = bin2c_array(data, args.array)
33    with open(args.out, 'w') as f:
34        f.write(out)
35
36    return 0
37
38if __name__ == '__main__':
39    sys.exit(main())
40