Files
led-driver/tools/ddp_test.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

161 lines
5.6 KiB
Python

#!/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()