"""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] 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. """ import sys, time, serial APP_BASE = 0x08001000 PORT = "COM16" def open_port(port): return serial.Serial(port, 115200, timeout=0.3) 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 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)) 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)") 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())