11.. _scripting :
22
33Embedding into Custom Scripts
4- =============================
4+ -----------------------------
55
66``esptool.py ``, ``espefuse.py ``, and ``espsecure.py `` can easily be integrated into Python applications or called from other Python scripts.
77
@@ -12,3 +12,54 @@ While it currently does have a poor Python API, something which `#208 <https://g
1212 command = [' --baud' , ' 460800' , ' read_flash' , ' 0' , ' 0x200000' , ' flash_contents.bin' ]
1313 print (' Using command %s ' % ' ' .join(command))
1414 esptool.main(command)
15+
16+
17+ Using Esptool as a Python Module
18+ --------------------------------
19+
20+ The following is an example on how to use esptool as a Python module and leverage its Python API to flash the {IDF_TARGET_NAME}:
21+
22+ .. note ::
23+
24+ This example code functionally equivalent to ``esptool.py -p /dev/ttyACM0 write_flash 0x10000 firmware.bin ``
25+
26+
27+ .. code-block :: python
28+
29+ from esptool.cmds import detect_chip
30+
31+ # The port of the connected ESP
32+ PORT = " /dev/ttyACM0"
33+ # The binary file
34+ BIN_FILE = " ./firmware.bin"
35+ # Flash offset to flash the binary to
36+ FLASH_ADDRESS = 0x 10000
37+
38+ def progress_callback (percent ):
39+ print (f " Wrote: { int (percent)} % " )
40+
41+ with detect_chip(PORT ) as esp:
42+ description = esp.get_chip_description()
43+ features = esp.get_chip_features()
44+ print (f " Detected ESP on port { PORT } : { description} " )
45+ print (f " Features: { " , " .join(features)} " )
46+
47+ esp = esp.run_stub()
48+ with open (BIN_FILE , ' rb' ) as binary:
49+ # Load the binary
50+ binary_data = binary.read()
51+ total_size = len (binary_data)
52+ print (f " Binary size: { total_size} bytes " )
53+
54+ # Write binary blocks
55+ esp.flash_begin(total_size, FLASH_ADDRESS )
56+ for i in range (0 , total_size, esp.FLASH_WRITE_SIZE ):
57+ block = binary_data[i:i + esp.FLASH_WRITE_SIZE ]
58+ # Pad the last block
59+ block = block + bytes ([0x FF ]) * (esp.FLASH_WRITE_SIZE - len (block))
60+ esp.flash_block(block, i + FLASH_ADDRESS )
61+ progress_callback(float (i + len (block)) / total_size * 100 )
62+ esp.flash_finish()
63+
64+ # Reset the chip out of bootloader mode
65+ esp.hard_reset()
0 commit comments