Exemple #1
0
 def flash_program(self):
     self.button_flash.config(state=tk.DISABLED)
     flash_command = []
     flash_command.extend(
         ['--baud', '460800', '--port', self.selected_port, 'write_flash'])
     try:
         with open(self.project_directory + '/flash_project_args') as f:
             args = []
             lines = f.read().split('\n')
             for i, line in enumerate(lines):
                 split_line = line.split(' ')
                 if 0 < i < len(lines) - 1:
                     split_line[
                         1] = self.project_directory + '/' + split_line[1]
                     args.extend(split_line)
         flash_command.extend(args)
         esptool.main(flash_command)
     except FileNotFoundError:
         msg = (
             "No flash_project_args found! "
             "Change the project directory for the one that has flash_project_args in it."
         )
         self.show_messagebox("No flash_project_args found", msg)
     # Clear command
     self.button_flash.config(state=tk.ACTIVE)
Exemple #2
0
def get_node_platform_and_mac(esptool, port):
    """
    Get Node Platform and Mac Addres from device

    :param esptool: esptool module
    :type esptool: module

    :param port: Serial Port
    :type port: str

    :return: Node Platform and Mac Address on Success
    :rtype: str
    """
    sys.stdout = mystdout = StringIO()
    command = ['--port', port, 'chip_id']
    log.info("Running esptool command to get node\
    platform and mac from device")
    esptool.main(command)
    sys.stdout = sys.__stdout__
    # Finding chip type from output.
    node_platform = next(
        filter(lambda line: 'Detecting chip type' in line,
               mystdout.getvalue().splitlines()))
    # Finds the first occurence of the line
    # with the MAC Address from the output.
    mac = next(
        filter(lambda line: 'MAC: ' in line,
               mystdout.getvalue().splitlines()))
    mac_addr = mac.split('MAC: ')[1].replace(':', '').upper()
    platform = node_platform.split()[-1].lower()
    return platform, mac_addr
Exemple #3
0
    def run(self):
        try:
            command = []

            if not self._config.port.startswith(__auto_select__):
                command.append("--port")
                command.append(self._config.port)

            #esptool.py esp32 -p /dev/ttyUSB0 -b 460800 --before=default_reset --after=hard_reset write_flash --flash_mode dio
            #--flash_freq 40m --flash_size 4MB 0x8000 partition_table/partition-table.bin 0x1000 bootloader/bootloader.bin 0x10000 alles.bin

            command.extend([
                "--baud",
                str(self._config.baud), "--before", "default_reset", "--after",
                "hard_reset", "write_flash", "--flash_size", "4MB",
                "--flash_mode", "dio", "0x8000", "partition-table.bin",
                "0x1000", "bootloader.bin", "0x10000",
                self._config.firmware_path
            ])

            if self._config.erase_before_flash:
                command.append("--erase-all")

            print("Command: esptool.py %s\n" % " ".join(command))

            esptool.main(command)

            print("\nFirmware successfully flashed.")
        except SerialException as e:
            self._parent.report_error(e.strerror)
            raise e
Exemple #4
0
def get_node_platform_and_mac(port):
    """
    Get Node Platform and Mac Addres from device

    :param port: Serial Port
    :type port: str

    :return: Node Platform and MAC Address on Success
    :rtype: str
    """
    if not port:
        sys.exit(
            "<port> argument not provided. Cannot read MAC address from node.")
    sys.stdout = mystdout = StringIO()
    command = ['--port', port, 'chip_id']
    log.info("Running esptool command to get node\
        platform and mac from device")
    esptool.main(command)
    sys.stdout = sys.__stdout__
    # Finding chip type from output.
    node_platform = next(
        filter(lambda line: 'Detecting chip type' in line,
               mystdout.getvalue().splitlines()))
    # Finds the first occurence of the line
    # with the MAC Address from the output.
    mac = next(
        filter(lambda line: 'MAC: ' in line,
               mystdout.getvalue().splitlines()))
    mac_addr = mac.split('MAC: ')[1].replace(':', '').upper()
    platform = node_platform.split()[-1].lower().replace('-', '')
    print("Node platform detected is: ", platform)
    print("MAC address is: ", mac_addr)
    log.debug("MAC address received: " + mac_addr)
    log.debug("Node platform is: " + platform)
    return platform, mac_addr
Exemple #5
0
def esp32_create_combined_bin(source, target, env):
    #print("Generating combined binary for serial flashing")

    # The offset from begin of the file where the app0 partition starts
    # This is defined in the partition .csv file
    app_offset = 0x10000

    new_file_name = env.subst("$BUILD_DIR/${PROGNAME}.factory.bin")
    sections = env.subst(env.get("FLASH_EXTRA_IMAGES"))
    firmware_name = env.subst("$BUILD_DIR/${PROGNAME}.bin")
    chip = env.get("BOARD_MCU")
    flash_size = env.BoardConfig().get("upload.flash_size")
    cmd = [
        "--chip",
        chip,
        "merge_bin",
        "-o",
        new_file_name,
        "--flash_size",
        flash_size,
    ]

    print("    Offset | File")
    for section in sections:
        sect_adr, sect_file = section.split(" ", 1)
        print(f" -  {sect_adr} | {sect_file}")
        cmd += [sect_adr, sect_file]

    print(f" - {hex(app_offset)} | {firmware_name}")
    cmd += [hex(app_offset), firmware_name]

    #print('Using esptool.py arguments: %s' % ' '.join(cmd))

    esptool.main(cmd)
    def run(self):
        try:
            command = []

            if not self._config.port.startswith(__auto_select__):
                command.append("--port")
                command.append(self._config.port)

            command.extend(["--baud", str(self._config.baud),
                            "--after", "no_reset",
                            "write_flash",
                            "--flash_mode", self._config.mode,
                            "0x10000", self._config.firmware_path])

            if self._config.erase_before_flash:
                command.append("--erase-all")

            print("Command: esptool.py %s\n" % " ".join(command))

            esptool.main(command)

            # The last line printed by esptool is "Staying in bootloader." -> some indication that the process is
            # done is needed
            print("\nFirmware successfully flashed. Unplug/replug or reset device \nto switch back to normal boot "
                  "mode.")
        except SerialException as e:
            self._parent.report_error(e.strerror)
            raise e
Exemple #7
0
def flashFirmware(firmwarePath=None):
    boardParams = command.detectBoardConfig()

    for referenceName, referenceParams in config.boardTypes.items():
        if all([
                referenceParams[key] == boardParams[key]
                for key in ["manufacturer", "device", "flash_size"]
        ]):
            flashParams = referenceParams
            print("Detected " + referenceName)
            break
    else:
        flashParams = None

    if flashParams is not None:
        params = dict()
        params.update(config.hardwareConfig())
        params.update(config.filesystemConfig())
        params.update(flashSpeedOverride)
        params.update(flashParams)
        if firmwarePath is not None:
            params['local_image_path'] = firmwarePath
        commandPattern = "esptool.py --port ${port} --baud ${baud} write_flash --flash_mode ${flash_mode} --flash_size ${flash_size} 0 ${local_image_path}"
        command.emulateInvocation(commandPattern, params)
        esptool.main()
    else:
        raise Error("Board unrecognised")
Exemple #8
0
def detectBoardConfig():
    import sys
    import re
    import io
    import esptool
    oldOut = sys.stdout
    newOut = io.StringIO()
    emulateInvocation("esptool.py --port ${port} flash_id",
                      config.hardwareConfig())
    try:
        sys.stdout = newOut
        esptool.main()
    finally:
        sys.stdout = oldOut

    printed = newOut.getvalue()

    def extractBackreference(pattern):
        return re.search(pattern, printed, re.MULTILINE).group(1)

    return {
        "chip": extractBackreference("^Chip is (\w+)$"),
        "manufacturer": extractBackreference('^Manufacturer: (\w+)$'),
        "device": extractBackreference('^Device: (\w+)$'),
        "flash_size": extractBackreference('^Detected flash size: (\w+)$'),
    }
Exemple #9
0
def flash_nvs_partition_bin(port, bin_to_flash, address):
    """
    Flash binary onto node

    :param port: Serial Port
    :type port: str

    :param bin_to_flash: Filname of binary to flash
    :type bin_to_flash: str

    :raises Exception: If there is any issue when flashing binary onto node

    :return: None on Success
    :rtype: None
    """
    try:
        if not port:
            sys.exit(
                "If you want to write the claim data to flash, please provide the <port> argument."
            )
        print("Flashing binary onto node")
        log.info("Flashing binary onto node")
        command = ['--port', port, 'write_flash', address, bin_to_flash]
        esptool.main(command)
    except Exception as err:
        log.error(err)
        sys.exit(1)
Exemple #10
0
def burn_firmware(term_port):
    print('Erase Flash...')
    esptool.main(['--port', term_port, 'erase_flash'])
    print('Write Flash...')
    esptool.main(['--port', term_port, 'write_flash', '--flash_size=detect', '0', 'esp8266-20200911-v1.13.bin'])
    print('ok')
    sleep(2)
Exemple #11
0
    def esptoolRunner(self):
        '''Handles the interaction with esptool'''
        self.ESPTOOL_BUSY = True
        self.disableUI()
        self.labelStatusValue.config(text="Upgrading ...")

        cmd = self.esptool_cmd_builder()
        try:
            esptool.main(cmd)
            print('esptool execution completed')
        except esptool.FatalError as e:
            print(e)
            pass
        except serial.SerialException as e:
            print(e)
            pass
        except Exception as e:
            print(e)
            print(
                'unexpected error, maybe you chose invalid files, or files which overlap'
            )
            pass

        self.ESPTOOL_BUSY = False
        self.enableUI()
        self.buttonFlash["state"] = "enabled"
        self.labelStatusValue.config(text="Done")
def updateMorserino(port, rate, path):
    f = io.StringIO()
    with redirect_stdout(f):
        command = getUpdateCommand(port, rate, path)
        esptool.main(command)
    s = f.getvalue().rstrip()
    writeConfirmation = 'Hash of data verified.'
    return s.count(writeConfirmation) == 4, s
Exemple #13
0
def esp_update(fwfile, port, baud):
    esptool.main(argv=[
        "--chip", "esp32", "--port", port, "--baud",
        str(baud), "--before", "default_reset", "--after", "hard_reset",
        "write_flash", "-z", "--flash_mode", "dio", "--flash_freq", "40m",
        "--flash_size", "detect", "0x1000", "bootloader_dio_40m.bin", "0x8000",
        "partitions.bin", "0xe000", "boot_app0.bin", "0x10000", fwfile
    ])
def eraseMorserino(port, rate):
    f = io.StringIO()
    with redirect_stdout(f):
        command = getEraseCommand(port, rate)
        esptool.main(command)
    s = f.getvalue().rstrip()
    writeConfirmation = 'Chip erase completed successfully'
    return s.count(writeConfirmation) == 1, s
Exemple #15
0
 def __do_step_esptool(self):
     if not self.profile["programmer"] == "esptool":
         return
     command = ['--port', '/dev/serial0', '--baud', '921600', 'write_flash']
     for b in self.profile["bins"]:
         command.append(b["addr"])
         command.append("bins/%s.hex" % (b["name"]))
     esptool.main(command)
Exemple #16
0
def flash_micropython(port):
    micropython_bin_file_path = os.path.join(ROOT_DIR,
                                             MICROPYTHON_BIN_FILE_DIR,
                                             MICROPYTHON_BIN_FILE_NAME)

    command = [
        "--chip", "esp32", "--port", port, "--baud", "230400", "--after",
        "hard_reset", "write_flash", "-z", "0x1000", micropython_bin_file_path
    ]
    esptool.main(command)
Exemple #17
0
def main():
    try:
        signal.signal(signal.SIGINT, exit_)
    except Exception:
        pass
    args = argparse.ArgumentParser()
    args.add_argument("-b", "--baudrate", help="Port baudrate.")
    stdargs = args.parse_args()
    if stdargs.baudrate:
        commands[baud] = stdargs.baudrate
    else:
        print(
            "===================================================================="
        )
        print("0: basic")
        print("1: atom")
        board = input("Please choice board(default: 0):")
        try:
            board = int(board)
        except Exception:
            board = 0
        if board == 1:
            commands[baud] = "1500000"

    port_str = get_port()
    commands[port] = port_str

    print(
        "====================================================================")
    print("0: choice from local.")
    print("1: choice from remote.")
    c = input("Please firmware localtion(default: 0):")
    try:
        c = int(c)
    except Exception:
        c = 0
    print(f"choice: {c}")
    if c == 0:
        local_option()
    elif c == 1:
        remote_option()

    try:
        esptool.main(commands)
    except OSError as e:
        print(f"Error encountered! {e}")
        print()
        if "Permission denied" in str(e):
            print("Please ensure you part of the `dialout` group. See README "
                  "for more details")
        else:
            print("Please do not disconnect from the device.")
    except esptool.FatalError as e:
        print(e)
Exemple #18
0
def run(com):
    from esptool import main
    import sys, traceback
    sys.argv = [
        'AutoFlash.py', '--port', com, '--baud', '460800', 'erase_flash'
    ]
    try:
        main()
        return None
    except Exception as e:
        return str(e)
    def run_esptool(self, command, content_path="./ESP_Packages"):
        """run esptool

            Parameters:
            command (list): list of esptool parameter
            content_path (str): path to esp binaries
        """
        print(f'Using command {command}')
        os.chdir(content_path)
        esptool.main(command)
        os.chdir(self.root_dir)
Exemple #20
0
def update_morserino(port, rate, path):
    f = io.StringIO()
    command = [
        '--port', port, '--baud', rate, '--before', 'default_reset', '--after',
        'hard_reset', 'write_flash', '0x10000', path
    ]
    with redirect_stdout(f):
        esptool.main(command)
    s = f.getvalue().rstrip()
    suffix = "Hard resetting via RTS pin..."
    return s.endswith(suffix)
Exemple #21
0
 def run(self):
     try:
         command = [
             '--port', self.com, 'write_flash', '0x00010000', self.firmware
         ]
         print('Using command %s' % ' '.join(command))
         esptool.main(command)
         self.finishSignal.emit(1)
     except:
         print('---ESPTOOL ERROR---')
         self.finishSignal.emit(2)
     return
Exemple #22
0
 def run(self):
     command.extend([
         "--baud", "921600", "--after", "no_reset", "write_flash",
         "--flash_mode", "dio", "0x00000", self.dir
     ])
     with open('log.txt', 'w') as f:
         with redirect_stdout(f):
             #print("Command: esptool.py %s\n" % " ".join(command))
             print("Starting HELIOS updater by TheHackLife")
             print("dir is " + globaldir)
             esptool.main(command)
             evt = wxWorkerDone()
             wx.PostEvent(self.se, evt)
Exemple #23
0
def get_firmware(com):
    try:
        import sys
        sys.argv = [
            'AutoFlash.py', '--chip', 'esp32', '--port', com, '--baud',
            '921600', 'read_flash', '0x1000', '0x250000', 'firmware.bin'
        ]

        from esptool import main
        main()
        return None
    except Exception as e:
        print(e)
        return str(e)
Exemple #24
0
def upload_firmware(updater, esp, firmware):
    # serial_port = esp._port.portstr
    try:
        start = timer()

        # esp = esptool.find_port([esp._port.portstr])
        updater(f"Uploading firmware to device on {esp._port.portstr}...")

        # esptool.write_flash(esp, ('0x00000', firmware))   <=== what are args?
        esptool.main(["write_flash", "0x00000", firmware], esp)

        # run(["python", "-u", "esptool.py", '--port', serial_port, 'write_flash', '0x00000', firmware])
        # print("ret " + str(ret))

        elapsed = timer() - start  # in seconds

        if elapsed < 3:
            updater(
                f"The firmware upload process went suspcisiously fast, meaning something went wrong.  Run time: {elapsed:0.1f} seconds."
            )
            print("Aborting!")
            return False

        updater("Upload complete")
    except esptool.FatalError as ex:
        updater(f"Problem: {ex}")
        traceback.print_exc()
        return False

    except subprocess.CalledProcessError as ex:
        output = ex.output

        # Check for specific known failure modes
        search = re.search(r"error: Failed to open (COM\d+)", output)
        updater(f"Failed to upload firmware: {output}")

        if search:
            port = search.group(1)
            updater()
            updater(
                f"Could not open {port}: it appears to be in use by another process!"
            )
        return False

    updater("Firmware loaded and device successfully configured.")
    return True
Exemple #25
0
    def run(self):
        try:
            spiffs_image_path = self.create_spiffs_image()

            command = []

            if not self._config.port.startswith(__auto_select__):
                command.append("--port")
                command.append(self._config.port)

            command.extend([
                "--baud",
                str(self._config.baud),
                # these are the default values
                # "--before", "default_reset",
                # "--after", "hard_reset",
                "write_flash",
                # https://github.com/espressif/esptool/issues/599
                "--flash_size",
                "detect",
                "--flash_mode",
                self._config.device_type.flash_mode,
                "0x00000",
                self._config.app_path,
                self._config.spiffs.offset,
                spiffs_image_path
            ])

            if self._config.erase_before_flash:
                command.append("--erase-all")

            print("\nInstalling application...")
            print("Command: esptool.py %s\n" % " ".join(command))

            esptool.main(command)

            # The "success" message depends on the esptool post-write behavior. This one is in line with the
            # --after hard_reset configuration about.
            print("\nApplication successfully installed. Device will reset.")
        except SerialException as e:
            self._parent.report_error(e.strerror)
            raise e
        finally:
            self._callback()
Exemple #26
0
def flash_esp(bootloader_path,
              firmware_path,
              partition_table_path,
              port=None,
              callback=None):
    try:
        command = []
        if port:
            command.append("--port")
            command.append(port)

        command.extend([
            "--chip",
            "esp32",
            "--baud",
            "921600",
            "--before",
            "default_reset",
            "--after",
            "hard_reset",
            "write_flash",
            "--flash_size",
            "detect",
            "--flash_mode",
            "dio",
            "0x1000",
            bootloader_path,
            "0x10000",
            firmware_path,
            "0x8000",
            partition_table_path,
        ])

        print("Command: esptool.py %s\n" % " ".join(command))

        esptool.main(command)
        if callback:
            callback(100)
        return True
    except serial.SerialException as e:
        print(e)
        return False
Exemple #27
0
 def program(self):
     command = [
         "--port",
         SERIAL_PORT,
         "--baud",
         str(self.comm_speed),
         "write_flash",
     ]
     for b in self.profile["bins"]:
         command.append(b["addr"])
         command.append("bins/%s.hex" % (b["name"]))
     try:
         self.__reset_device()
         self.app.detail(command)
         esptool.main(command)
         self.__reset_device()
     except Exception as e:
         self.app.error(e)
         return False
     return True
Exemple #28
0
def flash(com):
    FLASH_START = "0x1000"
    FLASH_MODE = "dio"
    FLASH_FREQ = "40m"

    import sys
    sys.argv = [
        'AutoFlash.py', '--chip', 'esp32', '--port', com, '--baud', '460800',
        'write_flash', '-z', '--flash_mode', FLASH_MODE, '--flash_size', '4MB',
        '--flash_freq', FLASH_FREQ, FLASH_START,
        os.getcwd() + '\\firmware.bin'
    ]

    try:
        from esptool import main
        main()
        return None
    except Exception as e:
        print(e)
        return str(e)
Exemple #29
0
def uploadBin(signals, port, binFile, deviceInfo):
    command = []
    command.append("--chip")
    command.append(deviceInfo["chip"])
    command.append("--port")
    command.append(port)
    command.append("--baud")
    command.append(str(deviceInfo["speed"]))
    command.append("write_flash")
    command.append("-z")
    command.append("--erase-all")
    command.extend(shlex.split(deviceInfo["flag"]))
    command.append("0x1000" if deviceInfo["chip"] == "esp32" else "0x0000")
    command.append(binFile)

    try:
        esptool.main(command)
        return None
    except Exception as e:
        return str(e)
def asyncFlash(command):  # command for asynchronously flashing the binaries.
    global flashing, running, modifiedT
    try:
        flashing = True
        esptool.main(command)

    except esptool.FatalError:
        status.configure(fg='red', text=connectionErrorMessage)
        # print("the board doesn't seem to be connected")
        running = False
        modifiedT = -1

    except SystemExit:
        status.configure(fg='red', text=missingFileErrorMessage)
        # print("the board doesn't seem to be connected")
        # e = sys.exc_info()[0]
        # xprint( "<p>Error: %s</p>" % e )
        running = False
        modifiedT = -1

    flashing = False
#
# Trivial wrapper program to run esptool.py using the just-compiled
# flasher stub in the build/ subdirectory
#
# For use when developing new flasher_stubs, not important otherwise.
#
# Copyright (C) 2014-2016 Fredrik Ahlberg, Angus Gratton, other contributors as noted.
#
# This program is free software; you can redistribute it and/or modify it under
# the terms of the GNU General Public License as published by the Free Software
# Foundation; either version 2 of the License, or (at your option) any later version.
#
import os.path
import sys

THIS_DIR=os.path.dirname(sys.argv[0])

sys.path.append("..")
import esptool
# Python hackiness: evaluate the snippet in the context of the esptool module, so it
# edits the esptool's global variables
exec(open("%s/build/stub_flasher_snippet.py" % THIS_DIR).read(), esptool.__dict__, esptool.__dict__)

if __name__ == "__main__":
    try:
        esptool.main()
    except esptool.FatalError as e:
        print('\nA fatal error occurred: %s' % e)
        sys.exit(2)

Exemple #32
0
# First parameter is pyserial path, second is esptool path, then a series of command arguments separated with --end
# i.e. upload.py tools/pyserial tools/esptool erase_flash --end write_flash file 0x0 --end

import sys
import os

sys.argv.pop(0) # Remove executable name
toolspath = os.path.dirname(os.path.realpath(__file__)).replace('\\', '/') # CWD in UNIX format
try:
    sys.path.append(toolspath + "/pyserial") # Add pyserial dir to search path
    sys.path.append(toolspath + "/esptool") # Add esptool dir to search path
    import esptool # If this fails, we can't continue and will bomb below
except:
    sys.stderr.write("Error in command line, need pyserial path as 1st arg and esptool path as 2nd.\n")
    sys.exit(1)

fakeargs = [];
while len(sys.argv):
    if sys.argv[0] == '--end':
        esptool.main(fakeargs)
        sys.argv.pop(0) # Remove --end
        fakeargs = []
    else:
        # We silently replace the 921kbaud setting with 460k to enable backward
        # compatibility with the old esptool-ck.exe.  Esptool.py doesn't seem
        # work reliably at 921k, but is still significantly faster at 460kbaud.
        thisarg = sys.argv.pop(0)
        if thisarg == "921600":
            thisarg = "460800"
        fakeargs = fakeargs + [thisarg]