Files
led-driver/tools/ota.py
T
jimmyandClaude Haiku 5.5 9a04d28ecf feat: web UI with AP, Wi-Fi client, mDNS, presets, OTA and DDP
- Wi-Fi access point led-XXXXXX plus a client network, configurable
  mDNS name and static client address
- Preset tiles with an editor, drag to reorder, default presets,
  global brightness, Run and Edit modes, collapsible menu on phones
- 35 patterns ported from led-driver, up to 512 LEDs, colour order,
  max brightness and data pin settings
- Over-the-air updates (POST /ota) with rollback, and a CLI in tools/ota.py
- DDP receiver on UDP 4048 with tools/ddp_test.py
- LED refresh every 10 ms; lwIP sockets raised to 16 so mDNS, HTTP
  and DDP can run together

Co-Authored-By: Claude Haiku 5.5 <noreply@anthropic.com>
2026-11-11 01:54:32 +13:00

92 lines
3.2 KiB
Python

"""
Over-the-air firmware update for the LED driver (ESP32-C3, Wi-Fi, plain HTTP).
The driver takes the raw app image on POST /ota, writes it to the idle slot and reboots.
"""
import http.client
import json
import os
import time
from typing import Optional
IMAGE_NAME = "led_driver.bin"
# Searched in order when no image is given (relative to where the tool is run, since the
# PyInstaller binary has no useful location of its own)
DEFAULT_IMAGES = [
os.path.join("build", IMAGE_NAME),
]
def _default_image() -> Optional[str]:
return next((p for p in DEFAULT_IMAGES if os.path.isfile(p)), None)
def _info(host: str, port: int) -> Optional[dict]:
try:
conn = http.client.HTTPConnection(host, port, timeout=5)
conn.request("GET", "/ota")
r = conn.getresponse()
return json.loads(r.read().decode()) if r.status == 200 else None
except (OSError, ValueError):
return None
def ota_update(host: str, image: Optional[str] = None, port: int = 80) -> None:
"""Upload image to host and wait for it to come back. Raises RuntimeError on failure."""
image = image or _default_image()
if not image:
raise RuntimeError(f"no image given and {IMAGE_NAME} not found under ./build")
if not os.path.isfile(image):
raise RuntimeError(f"image not found: {image}")
size = os.path.getsize(image)
before = _info(host, port)
if before is None:
raise RuntimeError(f"no OTA endpoint at http://{host}:{port}/ota (is this the LED driver?)")
print(f"Running {before['partition']} (built {before['built']})")
print(f"Uploading {image} ({size} bytes)...")
conn = http.client.HTTPConnection(host, port, timeout=60)
with open(image, "rb") as f:
conn.request("POST", "/ota", body=f, headers={
"Content-Length": str(size),
"Content-Type": "application/octet-stream",
})
r = conn.getresponse()
body = r.read().decode()
if r.status != 200:
try:
body = json.loads(body).get("error", body)
except ValueError:
pass
raise RuntimeError(f"update rejected ({r.status}): {body}")
print("Written, waiting for reboot...")
time.sleep(3)
for _ in range(30):
after = _info(host, port)
if after:
print(f"Back up on {after['partition']} (built {after['built']})")
if after["partition"] == before["partition"]:
raise RuntimeError("driver came back on the same slot: new image was rejected or rolled back")
return
time.sleep(1)
raise RuntimeError("driver did not come back within 30 s")
if __name__ == "__main__":
import argparse
import sys
ap = argparse.ArgumentParser(description="Update the LED driver firmware over Wi-Fi.")
ap.add_argument("host", help="address or name of the driver, e.g. 192.168.4.1 or led.local")
ap.add_argument("image", nargs="?", help=f"firmware image (default: build/{IMAGE_NAME})")
ap.add_argument("--port", type=int, default=80)
args = ap.parse_args()
try:
ota_update(args.host, args.image, args.port)
except RuntimeError as e:
print(f"error: {e}", file=sys.stderr)
sys.exit(1)