Skip to content

Commit 82f6b18

Browse files
iabdalkaderdpgeorge
authored andcommitted
espflash: Add 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 0e25b10 commit 82f6b18

File tree

3 files changed

+343
-0
lines changed

3 files changed

+343
-0
lines changed

micropython/espflash/espflash.py

Lines changed: 308 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,308 @@
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+
if hasattr(hashlib, "md5"):
77+
self.md5sum = hashlib.md5()
78+
except ImportError:
79+
pass
80+
81+
def _log(self, data, out=True):
82+
if self.log:
83+
size = len(data)
84+
print(
85+
f"out({size}) => " if out else f"in({size}) <= ",
86+
"".join("%.2x" % (i) for i in data[0:10]),
87+
)
88+
89+
def _uart_drain(self):
90+
while self.uart.read(1) is not None:
91+
pass
92+
93+
def _read_reg(self, addr):
94+
v, d = self._command(_CMD_ESP_READ_REG, struct.pack("<I", _FLASH_REG_BASE + addr))
95+
if d[0] != 0:
96+
raise Exception("Command ESP_READ_REG failed.")
97+
return v
98+
99+
def _write_reg(self, addr, data, mask=0xFFFFFFFF, delay=0):
100+
v, d = self._command(
101+
_CMD_ESP_WRITE_REG, struct.pack("<IIII", _FLASH_REG_BASE + addr, data, mask, delay)
102+
)
103+
if d[0] != 0:
104+
raise Exception("Command ESP_WRITE_REG failed.")
105+
106+
def _poll_reg(self, addr, flag, retry=10, delay=0.050):
107+
for i in range(0, retry):
108+
reg = self._read_reg(addr)
109+
if (reg & flag) == 0:
110+
break
111+
sleep(delay)
112+
else:
113+
raise Exception(f"Register poll timeout. Addr: 0x{addr:02X} Flag: 0x{flag:02X}.")
114+
115+
def _write_slip(self, pkt):
116+
pkt = pkt.replace(b"\xDB", b"\xdb\xdd").replace(b"\xc0", b"\xdb\xdc")
117+
self.uart.write(b"\xC0" + pkt + b"\xC0")
118+
self._log(pkt)
119+
120+
def _read_slip(self):
121+
pkt = None
122+
# Find the packet start.
123+
if self.uart.read(1) == b"\xC0":
124+
pkt = bytearray()
125+
while True:
126+
b = self.uart.read(1)
127+
if b is None or b == b"\xC0":
128+
break
129+
pkt += b
130+
pkt = pkt.replace(b"\xDB\xDD", b"\xDB").replace(b"\xDB\xDC", b"\xC0")
131+
self._log(b"\xC0" + pkt + b"\xC0", False)
132+
return pkt
133+
134+
def _strerror(self, err):
135+
if err in _ESP_ERRORS:
136+
return _ESP_ERRORS[err]
137+
return "Unknown error"
138+
139+
def _checksum(self, data):
140+
checksum = 0xEF
141+
for i in data:
142+
checksum ^= i
143+
return checksum
144+
145+
def _command(self, cmd, payload=b"", checksum=0):
146+
self._write_slip(struct.pack(b"<BBHI", 0, cmd, len(payload), checksum) + payload)
147+
for i in range(10):
148+
pkt = self._read_slip()
149+
if pkt is not None and len(pkt) >= 8:
150+
(flag, _cmd, size, val) = struct.unpack("<BBHI", pkt[:8])
151+
if flag == 1 and cmd == _cmd:
152+
status = list(pkt[-4:])
153+
if status[0] == 1:
154+
raise Exception(f"Command {cmd} failed {self._strerror(status[1])}")
155+
return val, pkt[8:]
156+
raise Exception(f"Failed to read response to command {cmd}.")
157+
158+
def set_baudrate(self, baudrate, timeout=350):
159+
if not hasattr(self.uart, "init"):
160+
return
161+
if baudrate != self.baudrate:
162+
print(f"Changing baudrate => {baudrate}")
163+
self._uart_drain()
164+
self._command(_CMD_CHANGE_BAUDRATE, struct.pack("<II", baudrate, 0))
165+
self.baudrate = baudrate
166+
self.uart.init(baudrate)
167+
self._uart_drain()
168+
169+
def bootloader(self, retry=6):
170+
for i in range(retry):
171+
self.gpio0_pin(1)
172+
self.reset_pin(0)
173+
sleep(0.1)
174+
self.gpio0_pin(0)
175+
self.reset_pin(1)
176+
sleep(0.1)
177+
self.gpio0_pin(1)
178+
179+
if "POWERON_RESET" not in self.uart.read():
180+
continue
181+
182+
for i in range(10):
183+
self._uart_drain()
184+
try:
185+
# 36 bytes: 0x07 0x07 0x12 0x20, followed by 32 x 0x55
186+
self._command(_CMD_SYNC, b"\x07\x07\x12\x20" + 32 * b"\x55")
187+
self._uart_drain()
188+
return True
189+
except Exception as e:
190+
print(e)
191+
192+
raise Exception("Failed to enter download mode!")
193+
194+
def flash_read_size(self):
195+
SPI_REG_CMD = 0x00
196+
SPI_USR_FLAG = 1 << 18
197+
SPI_REG_USR = 0x1C
198+
SPI_REG_USR2 = 0x24
199+
SPI_REG_W0 = 0x80
200+
SPI_REG_DLEN = 0x2C
201+
202+
# Command bit len | command
203+
SPI_RDID_CMD = ((8 - 1) << 28) | 0x9F
204+
SPI_RDID_LEN = 24 - 1
205+
206+
# Save USR and USR2 registers
207+
reg_usr = self._read_reg(SPI_REG_USR)
208+
reg_usr2 = self._read_reg(SPI_REG_USR2)
209+
210+
# Enable command phase and read phase.
211+
self._write_reg(SPI_REG_USR, (1 << 31) | (1 << 28))
212+
213+
# Configure command.
214+
self._write_reg(SPI_REG_DLEN, SPI_RDID_LEN)
215+
self._write_reg(SPI_REG_USR2, SPI_RDID_CMD)
216+
217+
self._write_reg(SPI_REG_W0, 0)
218+
# Trigger SPI operation.
219+
self._write_reg(SPI_REG_CMD, SPI_USR_FLAG)
220+
221+
# Poll CMD_USER flag.
222+
self._poll_reg(SPI_REG_CMD, SPI_USR_FLAG)
223+
224+
# Restore USR and USR2 registers
225+
self._write_reg(SPI_REG_USR, reg_usr)
226+
self._write_reg(SPI_REG_USR2, reg_usr2)
227+
228+
flash_bits = int(self._read_reg(SPI_REG_W0)) >> 16
229+
if flash_bits < 0x12 or flash_bits > 0x19:
230+
raise Exception(f"Unexpected flash size bits: 0x{flash_bits:02X}.")
231+
232+
flash_size = 2**flash_bits
233+
print(f"Flash size {flash_size/1024/1024} MBytes")
234+
return flash_size
235+
236+
def flash_attach(self):
237+
self._command(_CMD_SPI_ATTACH, struct.pack("<II", 0, 0))
238+
print(f"Flash attached")
239+
240+
def flash_config(self, flash_size=2 * 1024 * 1024):
241+
self._command(
242+
_CMD_SPI_FLASH_PARAMS,
243+
struct.pack(
244+
"<IIIIII",
245+
_FLASH_ID,
246+
flash_size,
247+
_FLASH_BLOCK_SIZE,
248+
_FLASH_SECTOR_SIZE,
249+
_FLASH_PAGE_SIZE,
250+
0xFFFF,
251+
),
252+
)
253+
254+
def flash_write_file(self, path, blksize=0x1000):
255+
size = os.stat(path)[6]
256+
total_blocks = (size + blksize - 1) // blksize
257+
erase_blocks = 1
258+
print(f"Flash write size: {size} total_blocks: {total_blocks} block size: {blksize}")
259+
with open(path, "rb") as f:
260+
seq = 0
261+
subseq = 0
262+
for i in range(total_blocks):
263+
buf = f.read(blksize)
264+
# Update digest
265+
if self.md5sum is not None:
266+
self.md5sum.update(buf)
267+
# The last data block should be padded to the block size with 0xFF bytes.
268+
if len(buf) < blksize:
269+
buf += b"\xFF" * (blksize - len(buf))
270+
checksum = self._checksum(buf)
271+
if seq % erase_blocks == 0:
272+
# print(f"Erasing {seq} -> {seq+erase_blocks}...")
273+
self._command(
274+
_CMD_SPI_FLASH_BEGIN,
275+
struct.pack(
276+
"<IIII", erase_blocks * blksize, erase_blocks, blksize, seq * blksize
277+
),
278+
)
279+
print(f"Writing sequence number {seq}/{total_blocks}...")
280+
self._command(
281+
_CMD_SPI_FLASH_DATA,
282+
struct.pack("<IIII", len(buf), seq % erase_blocks, 0, 0) + buf,
283+
checksum,
284+
)
285+
seq += 1
286+
287+
print("Flash write finished")
288+
289+
def flash_verify_file(self, path, digest=None, offset=0):
290+
if digest is None:
291+
if self.md5sum is None:
292+
raise Exception(f"MD5 checksum missing.")
293+
digest = binascii.hexlify(self.md5sum.digest())
294+
295+
size = os.stat(path)[6]
296+
val, data = self._command(_CMD_SPI_FLASH_MD5, struct.pack("<IIII", offset, size, 0, 0))
297+
298+
print(f"Flash verify: File MD5 {digest}")
299+
print(f"Flash verify: Flash MD5 {bytes(data[0:32])}")
300+
301+
if digest == data[0:32]:
302+
print("Firmware verified.")
303+
else:
304+
raise Exception(f"Firmware verification failed.")
305+
306+
def reboot(self):
307+
payload = struct.pack("<I", 0)
308+
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