def flash(port, firmware_file, erase_flash): # Initialize parameters args = Args() args.port = port args.baud = 460800 # Initialize device initial_baud = min(ESP_ROM_BAUD, args.baud) esp = esptool.ESPROM(args.port, initial_baud) if erase_flash: # Connect to the device esp.connect() # Erase flash esptool.erase_flash(esp, None) # Wait for flash erase for i in xrange(10): print ".", sleep(1) print "\nDone erasing flash." # Reconnect esp.connect() # Prepare arguments for writing flash address = 0 args.flash_size = "8m" args.addr_filename = [(address, open(firmware_file, "rb"))] # Write flash esptool.write_flash(esp, args) print "Done writing new firmware."
def flash(port, firmware_file, erase_flash): # Initialize parameters args = Args() args.port = port args.baud = 460800 # Initialize device initial_baud = min(ESP_ROM_BAUD, args.baud) esp = esptool.ESPROM(args.port, initial_baud) if erase_flash: # Connect to the device esp.connect() # Erase flash esptool.erase_flash(esp, args) if not firmware_file: return # Reconnect esp.connect() # Prepare arguments for writing flash address = 0 args.flash_size = "detect" args.addr_filename = [(address, open(firmware_file, "rb"))] # Write flash esptool.write_flash(esp, args) print("Done writing new firmware.")
def flash(port, firmware_file, erase_flash): # Initialize parameters args = Args() args.port = port args.baud = 460800 # Initialize device initial_baud = min(ESP_ROM_BAUD, args.baud) esp = esptool.ESPROM(args.port, initial_baud) if erase_flash: # Connect to the device esp.connect() # Erase flash esptool.erase_flash(esp, args) if not firmware_file: return # Reconnect esp.connect() # Prepare arguments for writing flash address = 0 args.flash_size = "detect" args.addr_filename = [(address, open(firmware_file, "rb"))] # Write flash esptool.write_flash(esp, args) print "Done writing new firmware."
def flash(self, addr_filename=[]): """ Flash firmware to the board using esptool """ self.on_data.emit("Preparing to flash memory. This can take a while.") # Esptool is a command line tool and expects arguments that can be # emulated by creating manually a `Namespace` object args = Namespace() args.flash_freq = "40m" args.flash_mode = "dio" args.flash_size = "detect" args.no_progress = False args.compress = False args.no_stub = False args.trace = False args.verify = False # This is the most important bit: It must be an list of tuples each # tuple containing the memory address and an file object. Generate # this list with `get_addr_filename` args.addr_filename = addr_filename try: # Detects which board is being used. We already know what bard we # are flashing (ESP32) but this will also does a lot of other # setup automatically for us esp32loader = esptool.ESPLoader.detect_chip( self.port, 115200, False) # Loads the program bootloader to ESP32 internal RAM esp = esp32loader.run_stub() # Change baudrate to flash the board faster esp.change_baud(921600) # We already know the flash size but asking esptool to autodetect # it will save us some more setup esptool.detect_flash_size(esp, args) esp.flash_set_parameters(esptool.flash_size_bytes(args.flash_size)) # Erase the current flash memory first self.on_data.emit('Erasing flash memory.') esptool.erase_flash(esp, args) self.on_data.emit('Writing on flash memory.') # Intercept what esptool prints out by replacing the `sys.stdout` # by old_stdout = sys.stdout sys.stdout = WritingProgressStdout(self.on_progress) # Write to flash memory esptool.write_flash(esp, args) # Restore old `sys.stdout` sys.stdout = old_stdout # Reset the board so we don't have to turn the Pixel Kit on and off # again using its terrible power switch that looks like a button esp.hard_reset() except Exception as ex: logging.error(ex) self.on_flash_fail.emit("Could not write to flash memory.")
def erase_flash(self, port): try: self.esp8266 = ESPLoader.detect_chip(port=port, baud=FLASH_BAUD) read_mac(self.esp8266, None) self.esp8266 = self.esp8266.run_stub() except serial.serialutil.SerialException as _: self.show_log(u'串口读写失败,请检查是否有其他程序占用了指定串口') self.flash_result_sig.emit(1, u'串口读写失败') return erase_flash(self.esp8266, None) self.show_log('flash 清除完毕') self.complete_erase_flash_sig.emit() self.esp8266.close_serial()
def run(self): try: print("esptool.py v%s" % esptool.__version__) initial_baud = min(ESPLoader.ESP_ROM_BAUD, self._config.baud) if self._config.port.startswith(__auto_select__): esp = self.connect_to_esp(initial_baud) else: esp = ESPLoader.detect_chip(self._config.port, initial_baud) print("Chip is %s" % (esp.get_chip_description())) print("Features: %s" % ", ".join(esp.get_chip_features())) esptool.read_mac(esp, Namespace()) esp = esp.run_stub() if self._config.baud > initial_baud: try: esp.change_baud(self._config.baud) except NotImplementedInROMError: print( "WARNING: ROM doesn't support changing baud rate. Keeping initial baud rate %d." % initial_baud) args = Namespace() args.flash_size = "detect" args.flash_mode = self._config.mode args.flash_freq = "40m" args.no_progress = False args.no_stub = False args.verify = False # TRUE is deprecated args.compress = True args.addr_filename = [[ int("0x00000", 0), open(self._config.firmware_path, 'rb') ]] print("Configuring flash size...") esptool.detect_flash_size(esp, args) esp.flash_set_parameters(esptool.flash_size_bytes(args.flash_size)) if self._config.erase_before_flash: esptool.erase_flash(esp, args) esptool.write_flash(esp, args) # The last line printed by esptool is "Leaving..." -> some indication that the process is done is needed print("\nDone. Unplug/replug or reset device.") esp._port.close() except SerialException as e: self._parent.report_error(e.strerror) raise e
def erase_chip_advanced(port): print('Erasing Chip...') esp = esptool.ESPLoader.detect_chip(port=port) print(f'Detected chip: {esp.get_chip_description()}') print("Features: %s" % ", ".join(esp.get_chip_features())) print("Crystal is %dMHz" % esp.get_crystal_freq()) mac = esp.read_mac() print(f"MAC: {':'.join(map(lambda x: '%02x' % x, mac))}") esp.run_stub() esptool.erase_flash(esp, None) print('Hard resetting via RTS pin...') esp.hard_reset()
def run(self): try: initial_baud = min(ESPLoader.ESP_ROM_BAUD, self._config.baud) esp = ESPLoader.detect_chip(self._config.port, initial_baud) print("Chip is %s" % (esp.get_chip_description())) esp = esp.run_stub() if self._config.baud > initial_baud: try: esp.change_baud(self._config.baud) except NotImplementedInROMError: print( "WARNING: ROM doesn't support changing baud rate. Keeping initial baud rate %d" % initial_baud) args = Namespace() args.flash_size = "detect" args.flash_mode = self._config.mode args.flash_freq = "40m" args.no_progress = False args.no_stub = False args.verify = False # TRUE is deprecated args.compress = True args.addr_filename = [[ int("0x00000", 0), open(self._config.firmware_path, 'rb') ]] print("Configuring flash size...") esptool.detect_flash_size(esp, args) esp.flash_set_parameters(esptool.flash_size_bytes(args.flash_size)) if self._config.erase_before_flash: esptool.erase_flash(esp, args) esptool.write_flash(esp, args) self._parent.log_message( "Hard resetting...") # replicate behavior from esptool.py:2111 esp.hard_reset() except SerialException as e: self._parent.report_error(e.strerror) raise e
def run(self): esp = ESPROM(port=self._config.port) args = Namespace() args.flash_size = "detect" args.flash_mode = self._config.mode args.flash_freq = "40m" args.no_progress = False args.verify = True args.baud = self._config.baud args.addr_filename = [[ int("0x00000", 0), open(self._config.firmware_path, 'rb') ]] # needs connect() before each operation, see https://github.com/espressif/esptool/issues/157 if self._config.erase_before_flash: esp.connect() esptool.erase_flash(esp, args) esp.connect() esptool.write_flash(esp, args)
def run(self): try: initial_baud = min(ESPLoader.ESP_ROM_BAUD, self._config.baud) esp = ESPLoader.detect_chip(self._config.port, initial_baud) print("芯片类型: %s" % (esp.get_chip_description())) esp = esp.run_stub() if self._config.baud > initial_baud: try: esp.change_baud(self._config.baud) except NotImplementedInROMError: print("警告: ROM 不支持改变波特率. 请保持初始波特率 %d." % initial_baud) args = Namespace() args.flash_size = "detect" args.flash_mode = self._config.mode args.flash_freq = "40m" args.no_progress = False args.no_stub = False args.verify = False # TRUE is deprecated args.compress = True args.addr_filename = [[ int("0x00000", 0), open(self._config.firmware_path, 'rb') ]] print("Configuring flash size...") esptool.detect_flash_size(esp, args) esp.flash_set_parameters(esptool.flash_size_bytes(args.flash_size)) if self._config.erase_before_flash: esptool.erase_flash(esp, args) esptool.write_flash(esp, args) # The last line printed by esptool is "Leaving..." -> some indication that the process is done is needed print("\nDone.") except SerialException as e: self._parent.report_error(e.strerror) raise e
def run_esphomeflasher(argv): args = parse_args(argv) port = select_port(args) if args.show_logs: serial_port = serial.Serial(port, baudrate=115200) show_logs(serial_port) return try: firmware = open(args.binary, 'rb') except IOError as err: raise EsphomeflasherError("Error opening binary: {}".format(err)) chip = detect_chip(port, args.esp8266, args.esp32) info = read_chip_info(chip) print() print("Chip Info:") print(" - Chip Family: {}".format(info.family)) print(" - Chip Model: {}".format(info.model)) if isinstance(info, ESP32ChipInfo): print(" - Number of Cores: {}".format(info.num_cores)) print(" - Max CPU Frequency: {}".format(info.cpu_frequency)) print(" - Has Bluetooth: {}".format( 'YES' if info.has_bluetooth else 'NO')) print(" - Has Embedded Flash: {}".format( 'YES' if info.has_embedded_flash else 'NO')) print(" - Has Factory-Calibrated ADC: {}".format( 'YES' if info.has_factory_calibrated_adc else 'NO')) else: print(" - Chip ID: {:08X}".format(info.chip_id)) print(" - MAC Address: {}".format(info.mac)) stub_chip = chip_run_stub(chip) flash_size = None if args.upload_baud_rate != 115200: try: stub_chip.change_baud(args.upload_baud_rate) except esptool.FatalError as err: raise EsphomeflasherError( "Error changing ESP upload baud rate: {}".format(err)) # Check if the higher baud rate works try: flash_size = detect_flash_size(stub_chip) except esptool.FatalError as err: # Go back to old baud rate by recreating chip instance print("Chip does not support baud rate {}, changing to 115200". format(args.upload_baud_Rate)) stub_chip._port.close() chip = detect_chip(port, args.esp8266, args.esp32) stub_chip = chip_run_stub(chip) if flash_size is None: flash_size = detect_flash_size(stub_chip) print(" - Flash Size: {}".format(flash_size)) mock_args = configure_write_flash_args(info, firmware, flash_size, args.bootloader, args.partitions, args.otadata) print(" - Flash Mode: {}".format(mock_args.flash_mode)) print(" - Flash Frequency: {}Hz".format(mock_args.flash_freq.upper())) try: stub_chip.flash_set_parameters(esptool.flash_size_bytes(flash_size)) except esptool.FatalError as err: raise EsphomeflasherError( "Error setting flash parameters: {}".format(err)) if not args.no_erase: try: esptool.erase_flash(stub_chip, mock_args) except esptool.FatalError as err: raise EsphomeflasherError( "Error while erasing flash: {}".format(err)) try: esptool.write_flash(stub_chip, mock_args) except esptool.FatalError as err: raise EsphomeflasherError("Error while writing flash: {}".format(err)) print("Hard Resetting...") stub_chip.hard_reset() print("Done! Flashing is complete!") print() if args.upload_baud_rate != 115200: stub_chip._port.baudrate = 115200 time.sleep(0.05) # get rid of crap sent during baud rate change stub_chip._port.flushInput() show_logs(stub_chip._port)
def run_esphomeflasher(argv): args = parse_args(argv) port = select_port(args) if args.show_logs: serial_port = serial.Serial(port, baudrate=115200) show_logs(serial_port) return try: firmware = open(args.binary, 'rb') except IOError as err: raise EsphomeflasherError("Error opening binary: {}".format(err)) chip = detect_chip(port, args.esp8266, args.esp32) info = read_chip_info(chip) print() print("Chip Info:") print(" - Chip Family: {}".format(info.family)) print(" - Chip Model: {}".format(info.model)) if isinstance(info, ESP32ChipInfo): print(" - Number of Cores: {}".format(info.num_cores)) print(" - Max CPU Frequency: {}".format(info.cpu_frequency)) print(" - Has Bluetooth: {}".format( 'YES' if info.has_bluetooth else 'NO')) print(" - Has Embedded Flash: {}".format( 'YES' if info.has_embedded_flash else 'NO')) print(" - Has Factory-Calibrated ADC: {}".format( 'YES' if info.has_factory_calibrated_adc else 'NO')) else: print(" - Chip ID: {:08X}".format(info.chip_id)) print(" - MAC Address: {}".format(info.mac)) stub_chip = chip_run_stub(chip) flash_size = detect_flash_size(stub_chip) print(" - Flash Size: {}".format(flash_size)) mock_args = configure_write_flash_args(info, firmware, flash_size, args.bootloader, args.partitions, args.otadata) print(" - Flash Mode: {}".format(mock_args.flash_mode)) print(" - Flash Frequency: {}Hz".format(mock_args.flash_freq.upper())) try: stub_chip.flash_set_parameters(esptool.flash_size_bytes(flash_size)) except esptool.FatalError as err: raise EsphomeflasherError( "Error setting flash parameters: {}".format(err)) if not args.no_erase: try: esptool.erase_flash(stub_chip, mock_args) except esptool.FatalError as err: raise EsphomeflasherError( "Error while erasing flash: {}".format(err)) try: esptool.write_flash(stub_chip, mock_args) except esptool.FatalError as err: raise EsphomeflasherError("Error while writing flash: {}".format(err)) print("Hard Resetting...") stub_chip.hard_reset() print("Done! Flashing is complete!") print() show_logs(stub_chip._port)
def run_esphomeflasher(argv): args = parse_args(argv) try: firmware = open(args.binary, 'rb') except IOError as err: raise EsphomeflasherError("Error opening binary: {}".format(err)) port = select_port(args) chip = detect_chip(port, args.esp8266, args.esp32) info = read_chip_info(chip) print() print("Chip Info:") print(" - Chip Family: {}".format(info.family)) print(" - Chip Model: {}".format(info.model)) if isinstance(info, ESP32ChipInfo): print(" - Number of Cores: {}".format(info.num_cores)) print(" - Max CPU Frequency: {}".format(info.cpu_frequency)) print(" - Has Bluetooth: {}".format('YES' if info.has_bluetooth else 'NO')) print(" - Has Embedded Flash: {}".format('YES' if info.has_embedded_flash else 'NO')) print(" - Has Factory-Calibrated ADC: {}".format( 'YES' if info.has_factory_calibrated_adc else 'NO')) else: print(" - Chip ID: {:08X}".format(info.chip_id)) print(" - MAC Address: {}".format(info.mac)) stub_chip = chip_run_stub(chip) flash_size = detect_flash_size(stub_chip) print(" - Flash Size: {}".format(flash_size)) mock_args = configure_write_flash_args(info, firmware, flash_size, args.bootloader, args.partitions, args.otadata) print(" - Flash Mode: {}".format(mock_args.flash_mode)) print(" - Flash Frequency: {}Hz".format(mock_args.flash_freq.upper())) try: stub_chip.flash_set_parameters(esptool.flash_size_bytes(flash_size)) except esptool.FatalError as err: raise EsphomeflasherError("Error setting flash parameters: {}".format(err)) if not args.no_erase: try: esptool.erase_flash(stub_chip, mock_args) except esptool.FatalError as err: raise EsphomeflasherError("Error while erasing flash: {}".format(err)) try: esptool.write_flash(stub_chip, mock_args) except esptool.FatalError as err: raise EsphomeflasherError("Error while writing flash: {}".format(err)) print("Hard Resetting...") stub_chip.hard_reset() print("Done! Flashing is complete!") print() print("Showing logs:") with stub_chip._port as ser: while True: try: raw = ser.readline() except serial.SerialException: print("Serial port closed!") return text = raw.decode(errors='ignore') text = ANSI_REGEX.sub('', text) line = text.replace('\r', '').replace('\n', '') time = datetime.now().time().strftime('[%H:%M:%S]') message = time + line try: print(message) except UnicodeEncodeError: print(message.encode('ascii', 'backslashreplace'))
def run_esphomeflasher(argv): args = parse_args(argv) port = select_port(args) if args.show_logs: serial_port = serial.Serial(port, baudrate=921600) show_logs(serial_port) return print("Starting firmware upgrade...") print("Getting latest firmware from fujinet.online..") print(fujinet_version_info(), end='') firmware = open_downloadable_binary(ESP32_DEFAULT_FIRMWARE) chip = detect_chip(port, args.esp8266, args.esp32) info = read_chip_info(chip) print() print("Chip Info:") print(" - Chip Family: {}".format(info.family)) print(" - Chip Model: {}".format(info.model)) if isinstance(info, ESP32ChipInfo): print(" - Number of Cores: {}".format(info.num_cores)) print(" - Max CPU Frequency: {}".format(info.cpu_frequency)) print(" - Has Bluetooth: {}".format( 'YES' if info.has_bluetooth else 'NO')) print(" - Has Embedded Flash: {}".format( 'YES' if info.has_embedded_flash else 'NO')) print(" - Has Factory-Calibrated ADC: {}".format( 'YES' if info.has_factory_calibrated_adc else 'NO')) else: print(" - Chip ID: {:08X}".format(info.chip_id)) print(" - MAC Address: {}".format(info.mac)) stub_chip = chip_run_stub(chip) if args.upload_baud_rate != 115200: try: stub_chip.change_baud(args.upload_baud_rate) except esptool.FatalError as err: raise EsphomeflasherError( "Error changing ESP upload baud rate: {}".format(err)) flash_size = detect_flash_size(stub_chip) print(" - Flash Size: {}".format(flash_size)) mock_args = configure_write_flash_args(info, firmware, flash_size, args.bootloader, args.partitions, args.otadata, args.spiffs) print(" - Flash Mode: {}".format(mock_args.flash_mode)) print(" - Flash Frequency: {}Hz".format(mock_args.flash_freq.upper())) try: stub_chip.flash_set_parameters(esptool.flash_size_bytes(flash_size)) except esptool.FatalError as err: raise EsphomeflasherError( "Error setting flash parameters: {}".format(err)) if not args.no_erase: try: esptool.erase_flash(stub_chip, mock_args) except esptool.FatalError as err: raise EsphomeflasherError( "Error while erasing flash: {}".format(err)) try: esptool.write_flash(stub_chip, mock_args) except esptool.FatalError as err: raise EsphomeflasherError("Error while writing flash: {}".format(err)) print("Hard Resetting...") stub_chip.hard_reset() print("Done! Flashing is complete!") print() if args.upload_baud_rate != 921600: stub_chip._port.baudrate = 921600 time.sleep(0.05) # get rid of crap sent during baud rate change stub_chip._port.flushInput() show_logs(stub_chip._port)
def _esptool_write_flash(self, esp, args): '''Method to write to flash. This method implements the esptool.py v2.6 write_flash(esp, args) function with some modifications. The modifications are to allow the progress of the write_flash(esp, args) to be shown in this GUI class.''' # set args.compress based on default behaviour: # -> if either --compress or --no-compress is set, honour that # -> otherwise, set --compress unless --no-stub is set if args.compress is None and not args.no_compress: args.compress = not args.no_stub # verify file sizes fit in flash msg = 'Verifying file sizes can fit in flash...' self._update_status(msg) print(msg) flash_end = esptool.flash_size_bytes(args.flash_size) for address, argfile in args.addr_filename: argfile.seek(0, 2) # seek to end if address + argfile.tell() > flash_end: raise esptool.FatalError(( "File %s (length %d) at offset %d will not fit in %d bytes of flash. " + "Use --flash-size argument, or change flashing address.") % (argfile.name, argfile.tell(), address, flash_end)) argfile.seek(0) if args.erase_all: msg = 'Erasing flash (this may take a while)...' self._update_status(msg) esptool.erase_flash(esp, args) for address, argfile in args.addr_filename: if args.no_stub: #print( 'Erasing flash...' ) msg = 'Erasing flash...' self._update_status(msg) print(msg) image = esptool.pad_to(argfile.read(), 4) if len(image) == 0: #print( 'WARNING: File %s is empty' % argfile.name ) msg = 'WARNING: File %s is empty' % argfile.name self._update_status(msg) print(msg) continue image = esptool._update_image_flash_params(esp, address, args, image) calcmd5 = hashlib.md5(image).hexdigest() uncsize = len(image) if args.compress: uncimage = image image = zlib.compress(uncimage, 9) ratio = uncsize / len(image) blocks = esp.flash_defl_begin(uncsize, len(image), address) else: ratio = 1.0 blocks = esp.flash_begin(uncsize, address) argfile.seek(0) # in case we need it again seq = 0 written = 0 t = time.time() while len(image) > 0: #print( '\rWriting at 0x%08x... (%d %%)' % ( address + seq * esp.FLASH_WRITE_SIZE, 100 * (seq + 1) // blocks), end='' ) msg = 'Writing at 0x%08x... (%d %%)' % ( address + seq * esp.FLASH_WRITE_SIZE, 100 * (seq + 1) // blocks) self._update_status(msg) print(msg, end='') sys.stdout.flush() block = image[0:esp.FLASH_WRITE_SIZE] if args.compress: esp.flash_defl_block(block, seq, timeout=esptool.DEFAULT_TIMEOUT * ratio * 2) else: # Pad the last block block = block + b'\xff' * (esp.FLASH_WRITE_SIZE - len(block)) esp.flash_block(block, seq) image = image[esp.FLASH_WRITE_SIZE:] seq += 1 written += len(block) t = time.time() - t speed_msg = "" if args.compress: if t > 0.0: speed_msg = " (effective %.1f kbit/s)" % (uncsize / t * 8 / 1000) print( 'Wrote %d bytes (%d compressed) at 0x%08x in %.1f seconds%s...' % (uncsize, written, address, t, speed_msg)) else: if t > 0.0: speed_msg = " (%.1f kbit/s)" % (written / t * 8 / 1000) print('Wrote %d bytes at 0x%08x in %.1f seconds%s...' % (written, address, t, speed_msg)) msg = 'Writing completed in %.1f seconds%s...' % (t, speed_msg) self._update_status(msg) try: res = esp.flash_md5sum(address, uncsize) if res != calcmd5: print('File md5: %s' % calcmd5) print('Flash md5: %s' % res) print('MD5 of 0xFF is %s' % (hashlib.md5(b'\xFF' * uncsize).hexdigest())) raise esptool.FatalError( "MD5 of file does not match data in flash!") else: #print( 'Hash of data verified.' ) msg = 'Hash of data verified.' self._update_status(msg) print(msg) except esptool.NotImplementedInROMError: pass print('\nLeaving...') if esp.IS_STUB: # skip sending flash_finish to ROM loader here, # as it causes the loader to exit and run user code esp.flash_begin(0, 0) if args.compress: esp.flash_defl_finish(False) else: esp.flash_finish(False) if args.verify: print('Verifying just-written flash...') print( '(This option is deprecated, flash contents are now always read back after flashing.)' ) msg = 'Verifying just-written flash...' self._update_status(msg) #print( msg ) esptool.verify_flash(esp, args) msg = '-- verify OK (digest matched)' self._update_status(msg)