Files
hexapod-robot/2026-current/dongle/tools/safeboot_flash.py
T

151 lines
5.0 KiB
Python
Raw Normal View History

"""Update the dongle application over USB via the permanent 'safeboot' stage 1.
No BOOT0 wire, no ST-Link, no ROM bootloader. Writes only the app region
(pages 4-15); safeboot itself is never touched.
usage: safeboot_flash.py app.bin [--port COM16] [--knock]
How it enters flash mode:
1) if the app is running, 'b' makes it soft-reset into safeboot flash mode;
2) otherwise (dead/absent app) replug the dongle and this spams 'S' to catch
safeboot's cold-boot knock window.
--knock skips 1) and keeps knocking for 2 minutes, reopening the port as it
comes and goes: start it, then replug. Use it when the app doesn't answer.
"""
import sys, time, serial
APP_BASE = 0x08001000
PORT = "COM16"
def open_port(port, open_timeout=20.0):
"""Retry the open to win the race against programs (SignalRGB) that grab
CH340 COM ports on enumeration. Once held, the handle stays ours."""
t = time.time()
while True:
try:
return serial.Serial(port, 115200, timeout=0.3)
except serial.SerialException:
if time.time() - t > open_timeout:
raise
time.sleep(0.02)
def enter_flash(s):
# path 1: tell a running app to reset into safeboot
s.reset_input_buffer()
s.write(b"b")
t = time.time()
buf = b""
while time.time() - t < 1.5:
buf += s.read(64)
if b"SBF" in buf:
return True
time.sleep(0.05)
# path 2: knock (works during safeboot's cold-boot window, after a replug)
t = time.time()
while time.time() - t < 6.0:
s.write(b"S")
r = s.read(16)
if b"K" in r or b"SBF" in r or b"SB1" in r:
# drain, then confirm we're in flash mode
time.sleep(0.1); s.reset_input_buffer()
s.write(b"V"); time.sleep(0.1)
if b"SBV" in s.read(16):
return True
time.sleep(0.1)
return False
def knock_until_caught(port, timeout=120.0):
"""--knock: for an app that doesn't answer 'b' (dead or deaf). Keeps the
port open and spams 'S' for up to `timeout` s, reopening whenever the port
vanishes, so replugging the dongle at any moment lands in safeboot's 1.5 s
cold-boot knock window. Returns the open port in flash mode, or None."""
t = time.time()
s = None
while time.time() - t < timeout:
try:
if s is None:
s = serial.Serial(port, 115200, timeout=0.02)
s.write(b"S")
r = s.read(16)
if b"K" in r or b"SB1" in r or b"SBR" in r:
time.sleep(0.1); s.reset_input_buffer(); s.timeout = 0.3
s.write(b"V"); time.sleep(0.1)
if b"SBV" in s.read(16):
return s
s.timeout = 0.02
except (serial.SerialException, OSError):
try:
if s is not None:
s.close()
except Exception:
pass
s = None
time.sleep(0.02)
return None
def expect(s, ch, what):
r = s.read(1)
if r != ch:
raise RuntimeError("%s: expected %r got %r" % (what, ch, r))
def main():
args = [a for a in sys.argv[1:] if not a.startswith("--")]
port = sys.argv[sys.argv.index("--port") + 1] if "--port" in sys.argv else PORT
data = open(args[0], "rb").read()
if len(data) % 2:
data += b"\xFF"
print("app %s: %d bytes -> 0x%08X" % (args[0], len(data), APP_BASE))
if "--knock" in sys.argv:
print("knock mode: replug the dongle now (waiting up to 2 min)...")
s = knock_until_caught(port)
if s is None:
print("no knock window caught")
return 1
else:
s = open_port(port)
print("entering safeboot flash mode...")
if not enter_flash(s):
print("could not enter flash mode (app not running? replug and retry with --knock)")
return 1
s.reset_input_buffer()
s.write(b"V"); time.sleep(0.1)
print("safeboot:", s.read(16).decode("ascii", "replace").strip())
print("erasing app region...")
s.write(b"E"); s.timeout = 3.0; expect(s, b"K", "erase"); s.timeout = 0.5
print("writing...")
for off in range(0, len(data), 128):
chunk = data[off:off + 128]
addr = APP_BASE + off
s.write(b"W" + addr.to_bytes(4, "little") + bytes([len(chunk)]) + chunk)
expect(s, b"K", "write @0x%08X" % addr)
print("verifying...")
bad = 0
for off in range(0, len(data), 128):
chunk = data[off:off + 128]
addr = APP_BASE + off
s.write(b"R" + addr.to_bytes(4, "little") + bytes([len(chunk)]))
rb = s.read(len(chunk))
if rb != chunk:
bad += 1
print(" mismatch @0x%08X" % addr)
if bad:
print("VERIFY FAILED (%d blocks)" % bad); return 1
print("verify OK; booting app.")
s.write(b"G"); expect(s, b"K", "go")
time.sleep(0.3)
print(s.read(256).decode("ascii", "replace").strip())
s.close()
return 0
if __name__ == "__main__":
sys.exit(main())