def _firmware_upload_task(self):
     firmware = (
         '0x1000', os.path.join(gm_firmware_dir(),'bootloader.bin'),
         '0x10000', os.path.join(gm_firmware_dir(), 'NodeMCU.bin'),
         '0x8000', os.path.join(gm_firmware_dir(), 'partitions_singleapp.bin')
     )
     args = FirmwareUploadArgs(self.serial_monitor.port,firmware)
     initial_baud = min(ESPLoader.ESP_ROM_BAUD, args.baud)
     try:
         self.serial_monitor.stop(log=False)
         self.panel_writeln('Firmware Start Update ...')
         esp_set_log(self.panel_writeln)
         esp = ESPLoader.detect_chip(args.port, initial_baud, args.before)
         self.panel_writeln("Chip is %s" % (esp.get_chip_description()))
         esp = esp.run_stub()
         if args.baud > initial_baud:
             try:
                 esp.change_baud(args.baud)
             except NotImplementedInROMError:
                 self.panel_writeln("WARNING: ROM doesn't support changing baud rate. Keeping initial baud rate %d" % initial_baud)
         if hasattr(args, "flash_size"):
             self.panel_writeln("Configuring flash size...")
             detect_flash_size(esp, args)
             esp.flash_set_parameters(flash_size_bytes(args.flash_size))
         write_flash(esp, args)
         esp.hard_reset()
         esp._port.close()
         self.serial_monitor.start()
     except Exception as e:
         self.panel_writeln(str(e)) 
     finally:
         self.serial_monitor.start(log=False)
Exemple #2
0
def write_firmware(esp, platform, firmware, flash=None):
    t = time.time()
    click.secho('Flashing firmware (Please wait)...', fg="green")
    # Detect flash size
    if flash is None:
        click.secho('Auto dectect flash size', fg="yellow")
        flash_id = esp.flash_id()
        flid_lowbyte = (flash_id >> 16) & 0xFF
        flash_size = esptool.DETECTED_FLASH_SIZES.get(flid_lowbyte)
        if flash_size is None:
            flash_size = DEFAULT_FLASH_SIZE[platform]
            click.secho('Size detection failed, set to default: %s'%(flash_size), fg="yellow")
        else:
            click.secho('Size detection successfull: %s'%(flash_size), fg="green")  
    else:
        flash_size = flash      
    # Set flash paraneters
    esp.flash_set_parameters(esptool.flash_size_bytes(flash_size))
    # Write
    with open(firmware, 'rb') as file:
        esptool.write_flash(esp, get_flash_params(platform, flash_size, file))
    click.secho('Hard reset...', fg="green")
    # Rest
    esp.hard_reset()
    click.secho('Flash completed successfully in %.1fs' % (time.time() - t), fg="green")
Exemple #3
0
 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.")
Exemple #4
0
    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
Exemple #5
0
    def write_flash(self, firmware):
        args = Args()
        data = firmware['body']
        args.set_body(0, data)
        args.flash_mode = firmware['mode']
        args.flash_freq = firmware['speed']
        esp = self.esp8266

        if hasattr(args, "flash_size"):
            print("Configuring flash size...")
            detect_flash_size(esp, args)
            if args.flash_size != 'keep':
                esp.flash_set_parameters(flash_size_bytes(args.flash_size))

        print('Args: ', args)
        self._write_flash(esp, args)
Exemple #6
0
    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
Exemple #7
0
    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
Exemple #8
0
def write_flash(esp, args, esprftool):
    flash_params = esptool._get_flash_params(esp, args)
    esprftool._SignalTX.emit('load start')

    # 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
    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 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)

    for address, argfile in args.addr_filename:
        if args.no_stub:
            print('Erasing flash...')
            esprftool._SignalTX.emit('Erasing flash...')
        image = esptool.pad_to(argfile.read(), 4)
        image = esptool._update_image_flash_params(esp, address, flash_params,
                                                   image)
        import hashlib
        calcmd5 = hashlib.md5(image).hexdigest()
        uncsize = len(image)
        if args.compress:
            uncimage = image
            image = zlib.compress(uncimage, 9)
            blocks = esp.flash_defl_begin(uncsize, len(image), address)
        else:
            blocks = esp.flash_begin(uncsize, address)
        argfile.seek(0)  # in case we need it again
        seq = 0
        written = 0
        while len(image) > 0:
            esprftool._Signalprb.emit(100 * (seq + 1) // blocks)
            #print '\rWriting at 0x%08x... (%d %%)' % (address + seq * esp.FLASH_WRITE_SIZE, 100 * (seq + 1) // blocks)
            sys.stdout.flush()
            block = image[0:esp.FLASH_WRITE_SIZE]
            if args.compress:
                esp.flash_defl_block(block, seq)
            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)
        speed_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 FatalError("MD5 of file does not match data in flash!")
            else:
                print('Hash of data verified.')
                esprftool._SignalTX.emit('Hash of data verified.')
        except NotImplementedInROMError:
            pass
    print('\nLeaving...')
    esprftool._SignalTX.emit('load to flash success')

    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.)'
        )
        _verify_flash(esp, args)

    esprftool._SignalTX.emit('load bin success')
    esp._port.close()
    esprftool._Signalprb.emit(100)
Exemple #9
0
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)
Exemple #10
0
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'))
Exemple #11
0
    def _write_flash(self, esp, args):
        # 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

        print('before size change:', args)
        # verify file sizes fit in flash
        if args.flash_size != 'keep':  # TODO: check this even with 'keep'
            flash_end = 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 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)

        print('Arguments:[', args, ']')
        for address, argfile in args.addr_filename:
            if args.no_stub:
                print('Erasing flash...')
            image = pad_to(argfile.read(), 32 if args.encrypt else 4)
            if len(image) == 0:
                print('WARNING: File %s is empty' % argfile.name)
                continue
            image = _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:
                QApplication.processEvents()
                if self._is_abort:
                    self.flash_result_sig.emit(1, u'已终止')
                    self.esp8266.close_serial()
                    return

                print_overwrite('Writing at 0x%08x... (%d %%)' % (address + seq * esp.FLASH_WRITE_SIZE, 100 * (seq + 1) // blocks))
                sys.stdout.flush()
                block = image[0:esp.FLASH_WRITE_SIZE]
                if args.compress:
                    esp.flash_defl_block(block, seq, timeout=DEFAULT_TIMEOUT * ratio * 2)
                else:
                    # Pad the last block
                    block = block + b'\xff' * (esp.FLASH_WRITE_SIZE - len(block))
                    if args.encrypt:
                        esp.flash_encrypt_block(block, seq)
                    else:
                        esp.flash_block(block, seq)
                self.flash_progress_sig.emit(written + len(block), len(image))
                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_overwrite('Wrote %d bytes (%d compressed) at 0x%08x in %.1f seconds%s...' % (uncsize, written, address, t, speed_msg), last_line=True)
            else:
                if t > 0.0:
                    speed_msg = " (%.1f kbit/s)" % (written / t * 8 / 1000)
                print_overwrite('Wrote %d bytes at 0x%08x in %.1f seconds%s...' % (written, address, t, speed_msg), last_line=True)

            if not args.encrypt:
                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 FatalError("MD5 of file does not match data in flash!")
                    else:
                        print('Hash of data verified.')
                except 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)
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)
Exemple #13
0
    def run(self):
        esp = None
        args = None
        vargs = None
        ok = False

        try:
            # build the args namespace esptool expects
            args = Namespace()

            # copy all enties from setup file
            for a in self.setup:
                setattr(args, a, self.setup[a])

            # We only verify the app portion as the other portions incl
            # nvm and may/will change during runtime. So we need a special copy
            # of args for verify.
            # verify only if we have a single image that starts at 0x1000
            if len(self.setup["files"]
                   ) == 1 and self.setup["files"][0]["addr"] == 0x1000:
                vargs = Namespace()
                for a in self.setup:
                    setattr(vargs, a, self.setup[a])

            # map files to addr_filename tuples
            args.addr_filename = []
            for f in self.setup["files"]:
                # load file into ram as older python version cannot
                # seek within zip files but esptool expects to be
                # able to seek

                # read "source" if present, otherwise read "filename"
                if "source" in f: fname = f["source"]
                else: fname = f["filename"]

                with self.setup["open"](fname, "rb") as fh:
                    data = fh.read()
                    fh = io.BytesIO(data)
                    setattr(fh, "name", fname)
                    args.addr_filename.append((f["addr"], fh))

            # for verify create a ram copy of the firmware which skips to 0x10000
            if vargs:
                vargs.addr_filename = []
                f = self.setup["files"][0]
                if "source" in f: fname = f["source"]
                else: fname = f["filename"]

                with self.setup["open"](fname, "rb") as fh:
                    # get access to full image data but skip the first
                    # (0x10000 - addr) = 0xf000 bytes
                    data = args.addr_filename[0][1].getbuffer()[0x10000 -
                                                                f["addr"]:]
                    dio = io.BytesIO(data)
                    setattr(dio, "name", "app area of {}".format(fname))
                    vargs.addr_filename.append((0x10000, dio))

            esp = esptool.get_default_connected_device(
                serial_list=[self.port],
                port=self.port,
                initial_baud=ESPROM_BAUD,
                chip=args.chip,
                connect_attempts=args.connect_attempts)

            print("Chip is %s" % (esp.get_chip_description()))
            print("Features: %s" % ", ".join(esp.get_chip_features()))
            print("Crystal is %dMHz" % esp.get_crystal_freq())
            esptool.read_mac(esp, args)
            esp = esp.run_stub()

            if args.baud > ESPROM_BAUD:
                esp.change_baud(args.baud)

            esptool.detect_flash_size(esp, args)
            if args.flash_size != 'keep':
                esp.flash_set_parameters(
                    esptool.flash_size_bytes(args.flash_size))

            do_write = True
            if vargs:
                try:
                    esptool.verify_flash(esp, vargs)
                    do_write = False  # verify successful, no need to write
                except:
                    pass

            if do_write:
                esptool.write_flash(esp, args)
            else:
                print("Firmware verified successfully, skipping flash")

            esp.hard_reset()

            esp._port.close()

            ok = True

        except IOException as e:
            self.alert.emit({
                "title":
                "esptool",
                "message":
                "Esptool error",
                "info":
                "Exception when accessing\n" + str(self.port),
                "detail":
                str(e)
            })

        if esp:
            esp._port.close()

        # since the files are now stored in memory we don't have to
        # close them here anymore

        self.done.emit(ok)
def write_flash(esp, args):
    flash_params = esptool._get_flash_params(esp, args)

    if args.compress is None and not args.no_compress:
        args.compress = not args.no_stub

    # verify file sizes fit in flash
    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 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)

    for address, argfile in args.addr_filename:
        if args.no_stub:
            if(DEBUG): print('Erasing flash...')
        image = esptool.pad_to(argfile.read(), 4)
        image = esptool._update_image_flash_params(esp, address, flash_params, image)
        calcmd5 = esptool.hashlib.md5(image).hexdigest()
        uncsize = len(image)
        if args.compress:
            uncimage = image
            image = zlib.compress(uncimage, 9)
            blocks = esp.flash_defl_begin(uncsize, len(image), address)
        else:
            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:
            if(DEBUG): print('\rWriting at 0x%08x... (%d %%)' % (address + seq * esp.FLASH_WRITE_SIZE, 100 * (seq + 1) // blocks))
            sys.stdout.flush()
            block = image[0:esp.FLASH_WRITE_SIZE]
            if args.compress:
                esp.flash_defl_block(block, seq)
            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)
            if(DEBUG): print('\rWrote %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)
            if(DEBUG): print('\rWrote %d bytes at 0x%08x in %.1f seconds%s...' % (written, address, t, speed_msg))
        try:
            res = esp.flash_md5sum(address, uncsize)
            if res != calcmd5:
                if(DEBUG): print('File  md5: %s' % calcmd5)
                if(DEBUG): print('Flash md5: %s' % res)
                if(DEBUG): print('MD5 of 0xFF is %s' % (hashlib.md5(b'\xFF' * uncsize).hexdigest()))
                raise FatalError("MD5 of file does not match data in flash!")
            else:
                if(DEBUG): print('Hash of data verified.')
        except NotImplementedInROMError:
            pass
    if(DEBUG): 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:
        if(DEBUG): print('Verifying just-written flash...')
        if(DEBUG): print('(This option is deprecated, flash contents are now always read back after flashing.)')
        esptool._verify_flash(esp, args)
Exemple #15
0
    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)
Exemple #16
0
    def _write_flash(self):
        #1.Setup widgets
        #self._status_color = 'blue'
        self.style.configure('write.TLabel', foreground='blue')
        self._write['state'] = 'disable'
        if self.device:
            self.device.ports['state'] = 'disable'
        self._update_status('Preprocessing....')

        #2. Create agrs
        if not self._create_args():
            print("\nFlashFirmware: Failed to create args.\n")
            self._post_write_flash_sop()
            return False
        args = self.args

        #3. Setup esp
        #3.1 Use "stub loader" program instead of the UART bootloader in the ESP32 ROM.
        if self.device.esp:
            esp = self.device.esp
            if not esp.IS_STUB:
                try:
                    esp = esp.run_stub()
                except esptool.FatalError as err:
                    self._post_write_flash_sop()
                    self._update_status(err.__str__())
                    print(err)
                    return False
        else:
            self._post_write_flash_sop()
            print("\nFlashFirmware: esp needs to be connected first.\n")
            print(' -- ', err.__str__())
            return False

        #3.2 Use a different baud to write flash if avaialble
        if args.baud != esptool.ESPLoader.ESP_ROM_BAUD:
            self._change_baud(esp, args.baud)

        #3.3 Use esptool.py "Default SPI flash interface" to write to flash chip.
        #    Commented code is useful if the option of having non-default SPI is preferred.
        #     https://github.com/espressif/esptool/wiki/Serial-Protocol#spi-attach-command
        '''if hasattr( args, "spi_connection" ) and args.spi_connection is not None:
            if esp.CHIP_NAME != "ESP32":
                self._post_write_flash_sop()
                raise FatalError( "Chip %s does not support --spi-connection option." % esp.CHIP_NAME )
            print( "Configuring SPI flash mode..." )
            esp.flash_spi_attach( args.spi_connection )
        elif args.no_stub:
            print( "Enabling default SPI flash mode..." )
            # ROM loader doesn't enable flash unless we explicitly do it
            esp.flash_spi_attach( 0 )'''

        #3.4 Set some parameters of the SPI flash chip
        if hasattr(args, "flash_size"):
            print("Configuring flash size...")
            esptool.detect_flash_size(esp, args)
            esp.flash_set_parameters(esptool.flash_size_bytes(args.flash_size))

        #print('\nargs = '); pprint( args.__dict__ )
        #print('\nesp = '); pprint( esp.__dict__ )
        #print('\nesp._port = '); pprint( esp._port.__dict__ )

        #4. Start writing
        self._writing = True
        self._completed = False
        self._update_status('Writing....')
        try:
            #esptool.write_flash( esp, args )      #original
            self._esptool_write_flash(
                esp, args
            )  #allow more detailed display of the write to flash progress.
        except esptool.FatalError:
            self._post_write_flash_sop()
            raise
        else:
            print('\nRevert to default Baud...')
            self._change_baud(esp, esptool.ESPLoader.ESP_ROM_BAUD)
        finally:
            try:
                # Clean up AddrFilenamePairAction files
                for address, argfile in args.addr_filename:
                    argfile.close()
            except AttributeError:
                pass

        #5. Post writing setups
        self._update_status('Completed writing Firmware to Flash.')
        self._post_write_flash_sop()
        self.device.esp = esp
        print()
        return True
Exemple #17
0
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 _write_flash(self):
        #1.Setup widgets
        self._status_color = 'blue'
        self.style.configure('write.TLabel', foreground='blue')
        self._write['state'] = 'disable'
        self.update_status('Preprocessing....')

        #2. Create agrs
        if not self._create_args():
            print("\nFlashFirmware: Failed to create args.")

        #3. Setup esp
        args = self.args
        if not self.device.esp:
            self.device._connect_esp()
            esp = self.device.esp
        else:
            esp = self.device.esp
            esp.flush_input()
            #esp.connect()
            #esp._slip_reader = esptool.slip_reader(esp._port, esp.trace)

        if not args.no_stub:
            print('if not args.no_stub:')
            esp = esp.run_stub()

        if args.baud != esptool.ESPLoader.ESP_ROM_BAUD:
            try:
                esp.change_baud(args.baud)
            except NotImplementedInROMError:
                print(
                    "WARNING: ROM doesn't support changing baud rate. Keeping initial baud rate %d"
                    % initial_baud)

        # override common SPI flash parameter stuff if configured to do so
        if hasattr(args, "spi_connection") and args.spi_connection is not None:
            if esp.CHIP_NAME != "ESP32":
                raise FatalError(
                    "Chip %s does not support --spi-connection option." %
                    esp.CHIP_NAME)
            print("Configuring SPI flash mode...")
            esp.flash_spi_attach(args.spi_connection)
        elif args.no_stub:
            print("Enabling default SPI flash mode...")
            # ROM loader doesn't enable flash unless we explicitly do it
            esp.flash_spi_attach(0)

        if hasattr(args, "flash_size"):
            print("Configuring flash size...")
            esptool.detect_flash_size(esp, args)
            esp.flash_set_parameters(esptool.flash_size_bytes(args.flash_size))

        print('\nargs = ')
        pprint(args.__dict__)
        print('\nesp = ')
        pprint(esp.__dict__)
        print('\nesp._port = ')
        pprint(esp._port.__dict__)

        #4. Start writing
        self._writing = True
        self._completed = False
        self.update_status('Writing....')
        try:
            esptool.write_flash(esp, args)
        except esptool.FatalError:
            raise
        else:
            print('Hard resetting via RTS pin...')
            esp.hard_reset()
        finally:
            try:  # Clean up AddrFilenamePairAction files
                for address, argfile in args.addr_filename:
                    argfile.close()
            except AttributeError:
                pass

        #esp._port.close()

        #5. Post writing setups
        self.update_status('Written Firmware to Flash.')
        self._writing = False
        self._completed = True
        self._write['state'] = 'normal'