DeaD_EyE

esp32 autoflash firmware

Mar 24th, 2022 (edited)
220
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.92 KB | None | 0 0
  1. #!/usr/bin/env python3
  2.  
  3. import subprocess
  4. import time
  5. from argparse import ArgumentParser, ArgumentDefaultsHelpFormatter
  6. from pathlib import Path
  7. from threading import Thread
  8.  
  9.  
  10. def get_args():
  11.     parser = ArgumentParser(formatter_class=ArgumentDefaultsHelpFormatter)
  12.     parser.add_argument("firmware", help="File for writing to esp32 flash")
  13.     parser.add_argument("-g", "--glob", action="store", default="ttyUSB*", help="Pattern to match port names")
  14.     return parser.parse_args()
  15.    
  16.  
  17. def flash(port, firmware):
  18.     """
  19.    Write firmware at offset 0x1000
  20.    """
  21.     cmd = [
  22.         "esptool.py",
  23.         "-p",
  24.         port,
  25.         "-b",
  26.         "921600",
  27.         "write_flash",
  28.         "-z",
  29.         "0x1000",
  30.         firmware,
  31.     ]
  32.     print("Flashing", port)
  33.     try:
  34.         subprocess.run(
  35.             cmd, stderr=subprocess.DEVNULL, stdout=subprocess.DEVNULL, check=True
  36.         )
  37.     except subprocess.CalledProcessError:
  38.         print("Failed to flash device", port)
  39.     else:
  40.         print("Done with", port)
  41.  
  42.  
  43. def get_tty():
  44.     return set(Path("/dev").glob(GLOB))
  45.  
  46.  
  47. def observer(input_file):
  48.     last_devs = get_tty()
  49.     while True:
  50.         current_devs = get_tty()
  51.         diff = current_devs - last_devs
  52.         last_devs = current_devs
  53.         if diff:
  54.             for port in diff:
  55.                 Thread(target=flash, args=(port, input_file)).start()
  56.         time.sleep(1)
  57.  
  58.  
  59. if __name__ == "__main__":
  60.     args = get_args()
  61.     GLOB = args.glob
  62.  
  63.     try:
  64.         observer(args.firmware)
  65.     except KeyboardInterrupt:
  66.         print("\rExit")
  67.  
  68.  
  69. """
  70. esptool.py esp32 \
  71.    -p /dev/ttyUSB0 \
  72.    -b 460800 \
  73.    --before=default_reset \
  74.    --after=hard_reset write_flash \
  75.    --flash_mode dio \
  76.    --flash_freq 40m \
  77.    --flash_size 4MB \
  78.    0x1000 bootloader/bootloader.bin \
  79.    0x10000 micropython.bin \
  80.    0x8000 partition_table/partition-table.bin
  81. """
Add Comment
Please, Sign In to add comment