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>
This commit is contained in:
1 parent
89f996096c
commit
9a04d28ecf
32 files changed
+6210
-398
No files matched your search
@@ -0,0 +1,160 @@
|
||||
#!/usr/bin/env python3
|
||||
"""
|
||||
Test the LED driver's DDP receiver (UDP port 4048).
|
||||
|
||||
Sends frames of RGB pixels the way a DDP controller does: a version 1 header, the pixel data split
|
||||
across two packets, and the PUSH flag on the last packet of a frame. Then checks through the driver's
|
||||
HTTP API that the pixels were shown, and that the pattern comes back once the pixels stop.
|
||||
|
||||
python3 tools/ddp_test.py 192.168.4.1
|
||||
"""
|
||||
|
||||
import json
|
||||
import re
|
||||
import socket
|
||||
import struct
|
||||
import sys
|
||||
import threading
|
||||
import time
|
||||
import urllib.request
|
||||
|
||||
PORT = 4048
|
||||
LEDS = 119
|
||||
PUSH = 0x01
|
||||
VER1 = 0x40
|
||||
RGB = 0x01
|
||||
|
||||
|
||||
def packet(seq, offset, data, push):
|
||||
flags = VER1 | (PUSH if push else 0)
|
||||
header = struct.pack(">BBBBIH", flags, seq & 0x0F, RGB, 1, offset, len(data))
|
||||
return header + data
|
||||
|
||||
|
||||
def send_frame(sock, host, pixels, seq):
|
||||
"""Send pixels (a list of (r, g, b)) as two packets, PUSH on the second."""
|
||||
raw = bytes(c for px in pixels for c in px)
|
||||
split = (len(pixels) // 2) * 3
|
||||
sock.sendto(packet(seq, 0, raw[:split], False), (host, PORT))
|
||||
sock.sendto(packet(seq, split, raw[split:], True), (host, PORT))
|
||||
|
||||
|
||||
def frame_sum(pixels):
|
||||
"""The driver's checksum of a frame: the sum of its bytes, as an unsigned 32-bit value."""
|
||||
return sum(c for px in pixels for c in px) & 0xFFFFFFFF
|
||||
|
||||
|
||||
def read_serial(port, seconds, lines):
|
||||
"""Collect the driver's log lines from the USB serial port for a few seconds."""
|
||||
import serial
|
||||
ser = serial.Serial(port, 115200, timeout=0.2)
|
||||
end = time.time() + seconds
|
||||
buf = b""
|
||||
while time.time() < end:
|
||||
buf += ser.read(4096)
|
||||
ser.close()
|
||||
lines.extend(buf.decode("utf-8", "replace").splitlines())
|
||||
|
||||
|
||||
def get(host, path):
|
||||
with urllib.request.urlopen(f"http://{host}{path}", timeout=5) as r:
|
||||
return json.loads(r.read().decode())
|
||||
|
||||
|
||||
def main():
|
||||
args = [a for a in sys.argv[1:] if not a.startswith("--")]
|
||||
serial_port = next((a.split("=", 1)[1] for a in sys.argv[1:] if a.startswith("--serial=")), None)
|
||||
host = args[0] if args else "192.168.4.1"
|
||||
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
|
||||
failures = 0
|
||||
|
||||
def check(name, ok, detail=""):
|
||||
nonlocal failures
|
||||
print(("PASS " if ok else "FAIL ") + name + (f" {detail}" if detail else ""))
|
||||
if not ok:
|
||||
failures += 1
|
||||
|
||||
before = get(host, "/api/ddp")
|
||||
print(f"before: active={before['active']} packets={before['packets']}")
|
||||
|
||||
# A frame: LED i is a colour that depends on i, so every LED is distinguishable
|
||||
def frame(k):
|
||||
return [((i * 7 + k) % 256, (i * 13) % 256, (255 - i * 3) % 256) for i in range(LEDS)]
|
||||
|
||||
serial_lines = []
|
||||
reader = None
|
||||
if serial_port:
|
||||
reader = threading.Thread(target=read_serial, args=(serial_port, 3.0, serial_lines), daemon=True)
|
||||
reader.start()
|
||||
sent_sums = {}
|
||||
last = None
|
||||
for k in range(60): # about 1.5 s at 40 fps
|
||||
last = frame(k)
|
||||
sent_sums[frame_sum(last)] = k
|
||||
send_frame(sock, host, last, k)
|
||||
time.sleep(0.025)
|
||||
time.sleep(0.2)
|
||||
|
||||
mid = get(host, "/api/ddp")
|
||||
check("receiving while sending", mid["active"], f"packets={mid['packets']}")
|
||||
check("packets counted", mid["packets"] - before["packets"] >= 120,
|
||||
f"+{mid['packets'] - before['packets']}")
|
||||
|
||||
# Keep sending the last frame while reading back: the readback takes longer than the DDP timeout
|
||||
stop = threading.Event()
|
||||
|
||||
def keep_sending():
|
||||
seq = 100
|
||||
while not stop.is_set():
|
||||
send_frame(sock, host, last, seq)
|
||||
seq += 1
|
||||
time.sleep(0.025)
|
||||
|
||||
sender = threading.Thread(target=keep_sending, daemon=True)
|
||||
sender.start()
|
||||
bad = []
|
||||
for i in range(LEDS):
|
||||
got = get(host, f"/api/ddp?led={i}")["rgb"]
|
||||
want = list(last[i])
|
||||
if got != want:
|
||||
bad.append((i, got, want))
|
||||
stop.set()
|
||||
sender.join()
|
||||
check(f"all {LEDS} LEDs show the frame", not bad,
|
||||
"" if not bad else f"first mismatch LED {bad[0][0]}: got {bad[0][1]} want {bad[0][2]}")
|
||||
|
||||
if reader is not None:
|
||||
reader.join()
|
||||
pat = re.compile(r"DDP frames=\d+ packets=\d+ sum=(\d+) led0=(\d+),(\d+),(\d+) led_last=(\d+),(\d+),(\d+)")
|
||||
summaries = [m for m in (pat.search(line) for line in serial_lines) if m]
|
||||
check("serial log has DDP summaries", len(summaries) > 0, f"{len(summaries)} lines")
|
||||
matched = [m for m in summaries if int(m.group(1)) in sent_sums]
|
||||
check("logged checksums are of sent frames", len(matched) == len(summaries),
|
||||
f"{len(matched)}/{len(summaries)} match")
|
||||
for m in summaries[-1:]:
|
||||
k = sent_sums.get(int(m.group(1)))
|
||||
if k is not None:
|
||||
sent = frame(k)
|
||||
check("serial led0 and last LED match that frame",
|
||||
[int(m.group(i)) for i in (2, 3, 4)] == list(sent[0]) and
|
||||
[int(m.group(i)) for i in (5, 6, 7)] == list(sent[-1]),
|
||||
f"led0 {m.group(2, 3, 4)} led_last {m.group(5, 6, 7)}")
|
||||
|
||||
# Pixels past the strip end are ignored and don't break the rest
|
||||
sock.sendto(packet(0, LEDS * 3 + 30, b"\xff" * 30, True), (host, PORT))
|
||||
time.sleep(0.1)
|
||||
check("out-of-range packet ignored", get(host, "/api/ddp?led=0")["rgb"] == list(last[0]))
|
||||
|
||||
# Stop sending: the pattern should come back after the timeout
|
||||
time.sleep(3.0)
|
||||
after = get(host, "/api/ddp")
|
||||
check("inactive after pixels stop", not after["active"])
|
||||
shown = get(host, "/api/ddp?led=0")["rgb"]
|
||||
check("pattern is shown again", shown != list(last[0]), f"LED 0 now {shown}")
|
||||
|
||||
print("\nRESULT:", "all passed" if not failures else f"{failures} failed")
|
||||
sys.exit(1 if failures else 0)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,91 @@
|
||||
"""
|
||||
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)
|
||||
Reference in new issue
Block a user