/ tools / flash / flash.py
flash.py
  1  #
  2  # @file from https://github.com/Neutree/c_cpp_project_framework
  3  # @author neucrack
  4  #
  5  
  6  from __future__ import print_function
  7  import argparse
  8  import os, sys, time, re, shutil
  9  import subprocess
 10  from multiprocessing import cpu_count
 11  import json
 12  import serial.tools.miniterm
 13  
 14  
 15  parser = argparse.ArgumentParser(add_help=False, prog="flash.py")
 16  
 17  ############################### Add option here #############################
 18  boards_choices = ["dan", "bit", "bit_mic", "goE", "goD", "maixduino", "kd233", "auto"]
 19  parser.add_argument("-p", "--port", help="[flash] device port", default="")
 20  parser.add_argument("-b", "--baudrate", type=int, help="[flash] baudrate", default=115200)
 21  parser.add_argument("-t", "--terminal", help="[flash] start a terminal after finish (Python miniterm)", default=False, action="store_true")
 22  parser.add_argument("-n", "--noansi", help="[flash] do not use ANSI colors, recommended in Windows CMD", default=False, action="store_true")
 23  parser.add_argument("-s", "--sram", help="[flash] download firmware to SRAM and boot", default=False, action="store_true")
 24  parser.add_argument("-B", "--Board",required=False, type=str, default="auto", help="[flash] select dev board, e.g. -B bit", choices=boards_choices)
 25  parser.add_argument("-S", "--Slow",required=False, help="[flash] slow download mode", default=False, action="store_true")
 26  dict_arg = {"port":"", 
 27              "baudrate": 115200,
 28              "terminal": False,
 29              "noansi": False,
 30              "sram": False,
 31              "Board": "auto",
 32              "Slow": False
 33              }
 34  dict_arg_not_save = ["sram", "terminal", "Slow"]
 35  
 36  def kflash_py_printCallback(*args, **kwargs):
 37      end = kwargs.pop("end", "\n")
 38      msg = ""
 39      for i in args:
 40          msg += str(i)
 41      msg.replace("\n", " ")
 42      print(msg, end=end)
 43  
 44  def kflash_progress(fileTypeStr, current, total, speedStr):
 45      # print("{}/{}".format(current, total))
 46      pass
 47  #############################################################################
 48  
 49  # use project_args created by SDK_PATH/tools/cmake/project.py
 50  
 51  # args = parser.parse_args()
 52  if __name__ == '__main__':
 53      firmware = ""
 54      try:
 55          flash_conf_path = project_path+"/.flash.conf.json"
 56          if project_args.cmd == "clean_conf":
 57              if os.path.exists(flash_conf_path):
 58                  os.remove(flash_conf_path)
 59              exit(0)
 60          if project_args.cmd != "flash":
 61              print("call flash.py error")
 62              exit(1)
 63      except Exception:
 64          print("-- call flash.py directly!")
 65          parser.add_argument("firmware", help="firmware file name")
 66          project_parser = parser
 67          project_args = project_parser.parse_args()
 68          project_path = ""
 69          if not os.path.exists(project_args.firmware):
 70              print("firmware not found:{}".format(project_args.firmware))
 71              exit(1)
 72          firmware = project_args.firmware
 73          sdk_path = ""
 74  
 75      config_old = {}
 76      # load flash config from file
 77      try:
 78          with open(flash_conf_path, "r") as f:
 79              config_old = json.load(f)
 80      except Exception as e:
 81          pass
 82      # update flash config from args
 83      for key in dict_arg.keys():
 84          dict_arg[key] = getattr(project_args, key)
 85      # check if config update, if do, use new and update config file
 86      config = {}
 87      for key in config_old:
 88          config[key] = config_old[key]
 89      for key in dict_arg.keys():
 90          if dict_arg[key] != project_parser.get_default(key): # arg valid, update config
 91              config[key] = dict_arg[key]
 92          else:
 93              if not key in config:
 94                  config[key] = dict_arg[key]
 95      if config != config_old:
 96          print("-- flash config changed, update at {}".format(flash_conf_path))
 97          with open(flash_conf_path, "w+") as f:
 98              json.dump(config, f, indent=4)
 99      # mask options that not read from file
100      for key in config:
101          if key in dict_arg_not_save:
102              config[key] = dict_arg[key]
103      print("-- flash start")
104      ############## Add flash command here ################
105      if project_path != "":
106          firmware = project_path+"/build/"+project_name+".bin"
107      if not os.path.exists(firmware):
108          print("[ERROR] Firmware not found:{}".format(firmware))
109          exit(1)
110      if config["port"] == "":
111          print("[ERROR] Invalid port:{}, set by -p or --port, e.g. -p /dev/ttyUSB0".format(config["port"]))
112          exit(1)
113      print("=============== flash config =============")
114      print("-- flash port    :{}".format(         config["port"]       ))
115      print("-- flash baudrate:{}".format(         config["baudrate"]   ))
116      print("-- flash board:{}".format(            config["Board"]      ))
117      print("-- flash open terminal:{}".format(    config["terminal"]   ))
118      print("-- flash download to sram:{}".format( config["sram"]       ))
119      print("-- flash noansi:{}".format(           config["noansi"]     ))
120      print("-- flash slow mode:{}".format(        config["Slow"]       ))
121      print("-- flash firmware:{}".format( firmware ))
122      print("")
123      print("-- kflash start")
124      # call kflash to burn firmware
125      from kflash_py.kflash import KFlash 
126  
127      kflash = KFlash(print_callback=kflash_py_printCallback)
128      flash_success = True
129      err_msg = ""
130      try:
131          if config["Board"]=="auto":
132              kflash.process(terminal=False, dev=config["port"], baudrate=config["baudrate"], \
133                  sram = config["sram"], file=firmware, callback=kflash_progress, noansi= config["noansi"], \
134                  terminal_auto_size=True, slow_mode = config["Slow"])
135          else:
136              kflash.process(terminal=False, dev=config["port"], baudrate=config["baudrate"], board=config["Board"], \
137                  sram = config["sram"], file=firmware, callback=kflash_progress, noansi= config["noansi"], \
138                  terminal_auto_size=True, slow_mode = config["Slow"])
139      except Exception as e:
140          flash_success = False
141          err_msg = str(e)
142      if not flash_success:
143          print("[ERROR] flash firmware fail:")
144          print("     "+err_msg)
145          exit(1)
146      ######################################################    
147      print("== flash end ==")    
148  
149      ######################################################
150      # open serial tool
151      if config["terminal"]:
152          reset = True
153          if config["sram"]:
154              reset = False
155          sys.argv=[project_path+"/tools/flash/flash.py"]
156          serial.tools.miniterm.main(default_port=config["port"], default_baudrate=115200, default_dtr=reset, default_rts=reset)
157          
158  
159      ######################################################
160      
161