1#!/usr/bin/env python
2import os, sys, re, time, json
3from flash_program_ll import burn_bin_files
4
5try:
6    import serial
7    from serial.tools import miniterm
8except:
9    print("\nNot found pyserial, please install it by: \nsudo python%d -m pip install pyserial" % (sys.version_info.major))
10    sys.exit(-1)
11
12#force to ymodem_burn.bin
13def get_bin_file():
14    """ get binary file from sys.argv --bin=/xxx/yyy/zzz.bin """
15    bin_files = []
16    pattern = re.compile(r'--(.*)=(.*)')
17    for arg in sys.argv[1:]:
18        if arg.startswith("--"):
19            match = pattern.match(arg)
20            if match:
21                key = match.group(1)
22                value = match.group(2)
23                if key == 'bin':
24                    bin_files.append(value)
25
26    return bin_files
27
28def read_json(json_file):
29    data = None
30    if os.path.isfile(json_file):
31        with open(json_file, 'r') as f:
32            data = json.load(f)
33    return data
34
35def write_json(json_file, data):
36    with open(json_file, 'w') as f:
37        f.write(json.dumps(data, indent=4, separators=(',', ': ')))
38
39def get_config():
40    """ get configuration from .config_burn file, if it is not existed,
41        generate default configuration of chip_rtl8721d """
42    configs = {}
43    config_file = os.path.join(os.getcwd(), '.config_burn')
44    if os.path.isfile(config_file):
45        configs = read_json(config_file)
46        if not configs:
47            configs = {}
48    if 'chip_rtl8721d' not in configs:
49        configs['chip_rtl8721d'] = {}
50    if 'serialport' not in configs['chip_rtl8721d']:
51        configs['chip_rtl8721d']['serialport'] = ""
52    if 'baudrate' not in configs['chip_rtl8721d']:
53        configs['chip_rtl8721d']['baudrate'] = "115200"
54    if 'binfile' not in configs['chip_rtl8721d']:
55        configs['chip_rtl8721d']['binfile'] = []
56
57    return configs['chip_rtl8721d']
58
59def save_config(config):
60    """ save configuration to .config_burn file, only update chip_rtl8721d portion """
61    if config:
62        configs = {}
63        config_file = os.path.join(os.getcwd(), '.config_burn')
64        if os.path.isfile(config_file):
65            configs = read_json(config_file)
66            if not configs:
67                configs = {}
68        configs['chip_rtl8721d'] = config
69        write_json(config_file, configs)
70
71def check_uart(portnum, baudrate):
72    serialport = serial.Serial()
73    serialport.port = portnum
74    serialport.baudrate = baudrate
75    serialport.parity   = "N"
76    serialport.bytesize = 8
77    serialport.stopbits = 1
78    serialport.timeout  = 1
79
80    try:
81        serialport.open()
82    except Exception as e:
83        print("check_uart open serialport: %s error " % portnum)
84        return False
85
86    serialport.close()
87    return True
88
89def main():
90    # step 1: get binary file
91    needsave = False
92    myconfig = get_config()
93    bin_files = get_bin_file()
94    if bin_files:
95        myconfig["binfile"] = bin_files
96        needsave = True
97    if not myconfig["binfile"]:
98        print("no specified binary file")
99        return
100    print("binary file is %s" % myconfig["binfile"])
101
102    # step 2: get serial port
103    if not myconfig["serialport"]:
104        myconfig["serialport"] = miniterm.ask_for_port()
105        if not myconfig["serialport"]:
106            print("no specified serial port")
107            return
108        else:
109            needsave = True
110
111    while check_uart(myconfig["serialport"], myconfig['baudrate']) == False:
112        myconfig["serialport"] = miniterm.ask_for_port()
113
114    print("serial port is %s" % myconfig["serialport"])
115    print("the settings were restored in the file %s" % os.path.join(os.getcwd(), '.config_burn'))
116
117    # step 3: burn binary file into flash
118    bin_files = []
119    for bin_file in myconfig["binfile"]:
120        filename = bin_file
121        address = "0"
122        if "#" in bin_file:
123            filename = bin_file.split("#", 1)[0]
124            address = bin_file.split("#", 1)[1]
125        if address == "0" or address == "0x0" or address == "0x00":
126            bin_files.append((os.path.join(os.getcwd(), 'binary/ymodem_burn_xz.bin'), address))
127        else:
128            bin_files.append((filename, address))
129    print("bin_files is ", bin_files)
130    burn_bin_files(myconfig["serialport"], myconfig['baudrate'], bin_files)
131    if needsave:
132        save_config(myconfig)
133
134if __name__ == "__main__":
135    main()
136