Skip to content

Commit bbda777

Browse files
committed
micropython/espflash.py: A minimal ESP32 bootloader protocol implementation.
This tool implements a subset of the ESP32 ROM bootloader protocol, and it's mainly intended for updating Nina WiFi firmware from MicroPython, but can be used to flash any ESP32 chip.
1 parent 0c5880d commit bbda777

File tree

3 files changed

+342
-0
lines changed

3 files changed

+342
-0
lines changed

micropython/espflash/espflash.py

Lines changed: 307 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,307 @@
1+
# This file is part of the MicroPython project, http://micropython.org/
2+
#
3+
# The MIT License (MIT)
4+
#
5+
# Copyright (c) 2022 Ibrahim Abdelkader <iabdalkader@openmv.io>
6+
#
7+
# Permission is hereby granted, free of charge, to any person obtaining a copy
8+
# of this software and associated documentation files (the "Software"), to deal
9+
# in the Software without restriction, including without limitation the rights
10+
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
11+
# copies of the Software, and to permit persons to whom the Software is
12+
# furnished to do so, subject to the following conditions:
13+
#
14+
# The above copyright notice and this permission notice shall be included in
15+
# all copies or substantial portions of the Software.
16+
#
17+
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
18+
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
19+
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
20+
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
21+
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
22+
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
23+
# THE SOFTWARE.
24+
#
25+
# A minimal esptool implementation to communicate with ESP32 ROM bootloader.
26+
# Note this tool does Not support advanced features, other ESP chips or stub loading.
27+
# This is only meant to be used for updating the U-blox Nina module firmware.
28+
29+
import os
30+
import struct
31+
from micropython import const
32+
from time import sleep
33+
import binascii
34+
35+
_CMD_SYNC = const(0x08)
36+
_CMD_CHANGE_BAUDRATE = const(0x0F)
37+
38+
_CMD_ESP_READ_REG = const(0x0A)
39+
_CMD_ESP_WRITE_REG = const(0x09)
40+
41+
_CMD_SPI_ATTACH = const(0x0D)
42+
_CMD_SPI_FLASH_MD5 = const(0x13)
43+
_CMD_SPI_FLASH_PARAMS = const(0x0B)
44+
_CMD_SPI_FLASH_BEGIN = const(0x02)
45+
_CMD_SPI_FLASH_DATA = const(0x03)
46+
_CMD_SPI_FLASH_END = const(0x04)
47+
48+
_FLASH_ID = const(0)
49+
_FLASH_REG_BASE = const(0x60002000)
50+
_FLASH_BLOCK_SIZE = const(64 * 1024)
51+
_FLASH_SECTOR_SIZE = const(4 * 1024)
52+
_FLASH_PAGE_SIZE = const(256)
53+
54+
_ESP_ERRORS = {
55+
0x05: "Received message is invalid",
56+
0x06: "Failed to act on received message",
57+
0x07: "Invalid CRC in message",
58+
0x08: "Flash write error",
59+
0x09: "Flash read error",
60+
0x0A: "Flash read length error",
61+
0x0B: "Deflate error",
62+
}
63+
64+
65+
class ESPFlash:
66+
def __init__(self, reset, gpio0, uart, log_enabled=False):
67+
self.uart = uart
68+
self.reset_pin = reset
69+
self.gpio0_pin = gpio0
70+
self.log = log_enabled
71+
self.baudrate = 115200
72+
self.md5sum = None
73+
try:
74+
import hashlib
75+
76+
self.md5sum = hashlib.md5()
77+
except ImportError:
78+
pass
79+
80+
def _log(self, data, out=True):
81+
if self.log:
82+
size = len(data)
83+
print(
84+
f"out({size}) => " if out else f"in({size}) <= ",
85+
"".join("%.2x" % (i) for i in data[0:10]),
86+
)
87+
88+
def _uart_drain(self):
89+
while self.uart.read(1) is not None:
90+
pass
91+
92+
def _read_reg(self, addr):
93+
v, d = self._command(_CMD_ESP_READ_REG, struct.pack("<I", _FLASH_REG_BASE + addr))
94+
if d[0] != 0:
95+
raise Exception("Command ESP_READ_REG failed.")
96+
return v
97+
98+
def _write_reg(self, addr, data, mask=0xFFFFFFFF, delay=0):
99+
v, d = self._command(
100+
_CMD_ESP_WRITE_REG, struct.pack("<IIII", _FLASH_REG_BASE + addr, data, mask, delay)
101+
)
102+
if d[0] != 0:
103+
raise Exception("Command ESP_WRITE_REG failed.")
104+
105+
def _poll_reg(self, addr, flag, retry=10, delay=0.050):
106+
for i in range(0, retry):
107+
reg = self._read_reg(addr)
108+
if (reg & flag) == 0:
109+
break
110+
sleep(delay)
111+
else:
112+
raise Exception(f"Register poll timeout. Addr: 0x{addr:02X} Flag: 0x{flag:02X}.")
113+
114+
def _write_slip(self, pkt):
115+
pkt = pkt.replace(b"\xDB", b"\xdb\xdd").replace(b"\xc0", b"\xdb\xdc")
116+
self.uart.write(b"\xC0" + pkt + b"\xC0")
117+
self._log(pkt)
118+
119+
def _read_slip(self):
120+
pkt = None
121+
# Find the packet start.
122+
if self.uart.read(1) == b"\xC0":
123+
pkt = bytearray()
124+
while True:
125+
b = self.uart.read(1)
126+
if b is None or b == b"\xC0":
127+
break
128+
pkt += b
129+
pkt = pkt.replace(b"\xDB\xDD", b"\xDB").replace(b"\xDB\xDC", b"\xC0")
130+
self._log(b"\xC0" + pkt + b"\xC0", False)
131+
return pkt
132+
133+
def _strerror(self, err):
134+
if err in _ESP_ERRORS:
135+
return _ESP_ERRORS[err]
136+
return "Unknown error"
137+
138+
def _checksum(self, data):
139+
checksum = 0xEF
140+
for i in data:
141+
checksum ^= i
142+
return checksum
143+
144+
def _command(self, cmd, payload=b"", checksum=0):
145+
self._write_slip(struct.pack(b"<BBHI", 0, cmd, len(payload), checksum) + payload)
146+
for i in range(10):
147+
pkt = self._read_slip()
148+
if pkt is not None and len(pkt) >= 8:
149+
(flag, _cmd, size, val) = struct.unpack("<BBHI", pkt[:8])
150+
if flag == 1 and cmd == _cmd:
151+
status = list(pkt[-4:])
152+
if status[0] == 1:
153+
raise Exception(f"Command {cmd} failed {self._strerror(status[1])}")
154+
return val, pkt[8:]
155+
raise Exception(f"Failed to read response to command {cmd}.")
156+
157+
def set_baudrate(self, baudrate, timeout=350):
158+
if not hasattr(self.uart, "init"):
159+
return
160+
if baudrate != self.baudrate:
161+
print(f"Changing baudrate => {baudrate}")
162+
self._uart_drain()
163+
self._command(_CMD_CHANGE_BAUDRATE, struct.pack("<II", baudrate, 0))
164+
self.baudrate = baudrate
165+
self.uart.init(baudrate)
166+
self._uart_drain()
167+
168+
def bootloader(self, retry=6):
169+
for i in range(retry):
170+
self.gpio0_pin(1)
171+
self.reset_pin(0)
172+
sleep(0.1)
173+
self.gpio0_pin(0)
174+
self.reset_pin(1)
175+
sleep(0.1)
176+
self.gpio0_pin(1)
177+
178+
if "POWERON_RESET" not in self.uart.read():
179+
continue
180+
181+
for i in range(10):
182+
self._uart_drain()
183+
try:
184+
# 36 bytes: 0x07 0x07 0x12 0x20, followed by 32 x 0x55
185+
self._command(_CMD_SYNC, b"\x07\x07\x12\x20" + 32 * b"\x55")
186+
self._uart_drain()
187+
return True
188+
except Exception as e:
189+
print(e)
190+
191+
raise Exception("Failed to enter download mode!")
192+
193+
def flash_read_size(self):
194+
SPI_REG_CMD = 0x00
195+
SPI_USR_FLAG = 1 << 18
196+
SPI_REG_USR = 0x1C
197+
SPI_REG_USR2 = 0x24
198+
SPI_REG_W0 = 0x80
199+
SPI_REG_DLEN = 0x2C
200+
201+
# Command bit len | command
202+
SPI_RDID_CMD = ((8 - 1) << 28) | 0x9F
203+
SPI_RDID_LEN = 24 - 1
204+
205+
# Save USR and USR2 registers
206+
reg_usr = self._read_reg(SPI_REG_USR)
207+
reg_usr2 = self._read_reg(SPI_REG_USR2)
208+
209+
# Enable command phase and read phase.
210+
self._write_reg(SPI_REG_USR, (1 << 31) | (1 << 28))
211+
212+
# Configure command.
213+
self._write_reg(SPI_REG_DLEN, SPI_RDID_LEN)
214+
self._write_reg(SPI_REG_USR2, SPI_RDID_CMD)
215+
216+
self._write_reg(SPI_REG_W0, 0)
217+
# Trigger SPI operation.
218+
self._write_reg(SPI_REG_CMD, SPI_USR_FLAG)
219+
220+
# Poll CMD_USER flag.
221+
self._poll_reg(SPI_REG_CMD, SPI_USR_FLAG)
222+
223+
# Restore USR and USR2 registers
224+
self._write_reg(SPI_REG_USR, reg_usr)
225+
self._write_reg(SPI_REG_USR2, reg_usr2)
226+
227+
flash_bits = int(self._read_reg(SPI_REG_W0)) >> 16
228+
if flash_bits < 0x12 or flash_bits > 0x19:
229+
raise Exception(f"Unexpected flash size bits: 0x{flash_bits:02X}.")
230+
231+
flash_size = 2**flash_bits
232+
print(f"Flash size {flash_size/1024/1024} MBytes")
233+
return flash_size
234+
235+
def flash_attach(self):
236+
self._command(_CMD_SPI_ATTACH, struct.pack("<II", 0, 0))
237+
print(f"Flash attached")
238+
239+
def flash_config(self, flash_size=2 * 1024 * 1024):
240+
self._command(
241+
_CMD_SPI_FLASH_PARAMS,
242+
struct.pack(
243+
"<IIIIII",
244+
_FLASH_ID,
245+
flash_size,
246+
_FLASH_BLOCK_SIZE,
247+
_FLASH_SECTOR_SIZE,
248+
_FLASH_PAGE_SIZE,
249+
0xFFFF,
250+
),
251+
)
252+
253+
def flash_write_file(self, path, blksize=0x1000):
254+
size = os.stat(path)[6]
255+
total_blocks = (size + blksize - 1) // blksize
256+
erase_blocks = 1
257+
print(f"Flash write size: {size} total_blocks: {total_blocks} block size: {blksize}")
258+
with open(path, "rb") as f:
259+
seq = 0
260+
subseq = 0
261+
for i in range(total_blocks):
262+
buf = f.read(blksize)
263+
# Update digest
264+
if self.md5sum is not None:
265+
self.md5sum.update(buf)
266+
# The last data block should be padded to the block size with 0xFF bytes.
267+
if len(buf) < blksize:
268+
buf += b"\xFF" * (blksize - len(buf))
269+
checksum = self._checksum(buf)
270+
if seq % erase_blocks == 0:
271+
# print(f"Erasing {seq} -> {seq+erase_blocks}...")
272+
self._command(
273+
_CMD_SPI_FLASH_BEGIN,
274+
struct.pack(
275+
"<IIII", erase_blocks * blksize, erase_blocks, blksize, seq * blksize
276+
),
277+
)
278+
print(f"Writing sequence number {seq}/{total_blocks}...")
279+
self._command(
280+
_CMD_SPI_FLASH_DATA,
281+
struct.pack("<IIII", len(buf), seq % erase_blocks, 0, 0) + buf,
282+
checksum,
283+
)
284+
seq += 1
285+
286+
print("Flash write finished")
287+
288+
def flash_verify_file(self, path, digest=None, offset=0):
289+
if digest is None:
290+
if self.md5sum is None:
291+
raise Exception(f"MD5 checksum missing.")
292+
digest = binascii.hexlify(self.md5sum.digest())
293+
294+
size = os.stat(path)[6]
295+
val, data = self._command(_CMD_SPI_FLASH_MD5, struct.pack("<IIII", offset, size, 0, 0))
296+
297+
print(f"Flash verify: File MD5 {digest}")
298+
print(f"Flash verify: Flash MD5 {bytes(data[0:32])}")
299+
300+
if digest == data[0:32]:
301+
print("Firmware verified.")
302+
else:
303+
raise Exception(f"Firmware verification failed.")
304+
305+
def reboot(self):
306+
payload = struct.pack("<I", 0)
307+
self._write_slip(struct.pack(b"<BBHI", 0, _CMD_SPI_FLASH_END, len(payload), 0) + payload)

micropython/espflash/example.py

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
import espflash
2+
from machine import Pin
3+
from machine import UART
4+
5+
if __name__ == "__main__":
6+
reset = Pin(3, Pin.OUT)
7+
gpio0 = Pin(2, Pin.OUT)
8+
uart = UART(1, 115200, tx=Pin(8), rx=Pin(9), timeout=350)
9+
10+
md5sum = b"9a6cf1257769c9f1af08452558e4d60e"
11+
path = "NINA_W102-v1.5.0-Nano-RP2040-Connect.bin"
12+
13+
esp = espflash.ESPFlash(reset, gpio0, uart)
14+
# Enter bootloader download mode, at 115200
15+
esp.bootloader()
16+
# Can now chage to higher/lower baudrate
17+
esp.set_baudrate(921600)
18+
# Must call this first before any flash functions.
19+
esp.flash_attach()
20+
# Read flash size
21+
size = esp.flash_read_size()
22+
# Configure flash parameters.
23+
esp.flash_config(size)
24+
# Write firmware image from internal storage.
25+
esp.flash_write_file(path)
26+
# Compares file and flash MD5 checksum.
27+
esp.flash_verify_file(path, md5sum)
28+
# Resets the ESP32 chip.
29+
esp.reboot()

micropython/espflash/manifest.py

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
metadata(
2+
version="0.1",
3+
description="Provides a minimal ESP32 bootloader protocol implementation.",
4+
)
5+
6+
module("espflash.py")

0 commit comments

Comments
 (0)
pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy