test: DDP test finds every device on the subnet and runs animations

- With no arguments, probe the local /24 for devices answering /api/ddp and test each one
  (--subnet picks another subnet; named hosts still override discovery).
- Test all devices at the same time, one thread each.
- Add chase, rainbow and breathe animations; check the last frame of each is shown.
- Compare readback against the output scale (global x master x max brightness) the
  firmware applies, read from /api/status and /api/hardware.
- Check the out-of-range packet and the timeout fallback against the last frame shown.

Co-Authored-By: Claude Haiku 5.5 <noreply@anthropic.com>
This commit is contained in:
jimmyandClaude Haiku 5.5 committed 2026-11-11 12:57:14 +13:00
1 parent d32f3d69cf
commit 47f4eba0d6
1 file changed
+157 -35
+157 -35
View File
@@ -4,12 +4,18 @@ 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 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 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. HTTP API that the pixels were shown, runs a few test animations, and that the pattern comes back once
the pixels stop. Every device is tested at the same time, one thread each.
python3 tools/ddp_test.py 192.168.4.1 python3 tools/ddp_test.py # finds every device on this machine's subnet (/24)
python3 tools/ddp_test.py --subnet=192.168.4 # or pick the subnet
python3 tools/ddp_test.py led1.local led2.local # or name hosts explicitly
python3 tools/ddp_test.py led1.local --serial=/dev/ttyACM0 # also check the serial log (one host only)
""" """
import colorsys
import json import json
import math
import re import re
import socket import socket
import struct import struct
@@ -17,12 +23,14 @@ import sys
import threading import threading
import time import time
import urllib.request import urllib.request
from concurrent.futures import ThreadPoolExecutor
PORT = 4048 PORT = 4048
LEDS = 119 LEDS = 119
PUSH = 0x01 PUSH = 0x01
VER1 = 0x40 VER1 = 0x40
RGB = 0x01 RGB = 0x01
ANIM_FRAMES = 40 # about 1 s at 40 fps
def packet(seq, offset, data, push): def packet(seq, offset, data, push):
@@ -61,21 +69,113 @@ def get(host, path):
return json.loads(r.read().decode()) return json.loads(r.read().decode())
def main(): def local_prefix():
args = [a for a in sys.argv[1:] if not a.startswith("--")] """The first three octets of this machine's IPv4 address (assumes a /24 subnet)."""
serial_port = next((a.split("=", 1)[1] for a in sys.argv[1:] if a.startswith("--serial=")), None) s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
host = args[0] if args else "192.168.4.1" try:
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) s.connect(("8.8.8.8", 80))
ip = s.getsockname()[0]
finally:
s.close()
return ip.rsplit(".", 1)[0]
def find_devices(prefix):
"""Every host on the subnet that answers the driver's /api/ddp endpoint."""
def probe(ip):
try:
with urllib.request.urlopen(f"http://{ip}/api/ddp", timeout=1) as r:
json.loads(r.read().decode())
return ip
except Exception:
return None
ips = [f"{prefix}.{i}" for i in range(1, 255)]
with ThreadPoolExecutor(64) as pool:
return [ip for ip in pool.map(probe, ips) if ip]
# Test animations: each maps (LED index, frame number) to an RGB colour
def anim_chase(i, k):
return (255, 160, 0) if (i - 2 * k) % LEDS < 6 else (0, 0, 0)
def anim_rainbow(i, k):
r, g, b = colorsys.hsv_to_rgb(((i * 3 + k * 5) % 256) / 256, 1, 1)
return (int(r * 255), int(g * 255), int(b * 255))
def anim_breathe(i, k):
v = int(127.5 * (1 - math.cos(k / 6)))
return (v, v, v)
ANIMATIONS = {"chase": anim_chase, "rainbow": anim_rainbow, "breathe": anim_breathe}
def output_scale(host):
"""The factor the driver applies to every pixel before it is shown: global x master x max brightness,
with the same integer steps as the firmware (patterns.cpp)."""
st = get(host, "/api/status")
hw = get(host, "/api/hardware")
return st["global_brightness"] * st["master_brightness"] // 255 * hw["max_brightness"] // 255
def expected(pixels, scale):
"""What the driver shows for a pixel: each channel scaled by the output factor."""
return [[c * scale // 255 for c in px] for px in pixels]
def mismatch_detail(bad):
return "" if not bad else f"first mismatch LED {bad[0][0]}: got {bad[0][1]} want {bad[0][2]}"
def verify_frame(host, sock, pixels, scale):
"""Read every LED back while keeping the frame on the strip (the readback is slower than the DDP
timeout). Returns the LEDs that do not match what the driver should show."""
want_all = expected(pixels, scale)
stop = threading.Event()
def keep_sending():
seq = 100
while not stop.is_set():
send_frame(sock, host, pixels, 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 = want_all[i]
if got != want:
bad.append((i, got, want))
stop.set()
sender.join()
return bad
def run(host, serial_port):
"""Run every check against one device. Returns (failures, output lines)."""
out = []
failures = 0 failures = 0
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
def log(line=""):
out.append(line)
def check(name, ok, detail=""): def check(name, ok, detail=""):
nonlocal failures nonlocal failures
print(("PASS " if ok else "FAIL ") + name + (f" {detail}" if detail else "")) log(("PASS " if ok else "FAIL ") + name + (f" {detail}" if detail else ""))
if not ok: if not ok:
failures += 1 failures += 1
before = get(host, "/api/ddp") before = get(host, "/api/ddp")
print(f"before: active={before['active']} packets={before['packets']}") log(f"before: active={before['active']} packets={before['packets']}")
scale = output_scale(host)
log(f"output scale: {scale}/255")
# A frame: LED i is a colour that depends on i, so every LED is distinguishable # A frame: LED i is a colour that depends on i, so every LED is distinguishable
def frame(k): def frame(k):
@@ -100,28 +200,9 @@ def main():
check("packets counted", mid["packets"] - before["packets"] >= 120, check("packets counted", mid["packets"] - before["packets"] >= 120,
f"+{mid['packets'] - before['packets']}") f"+{mid['packets'] - before['packets']}")
# Keep sending the last frame while reading back: the readback takes longer than the DDP timeout bad = verify_frame(host, sock, last, scale)
stop = threading.Event() check(f"all {LEDS} LEDs show the frame", not bad, mismatch_detail(bad))
shown = last
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: if reader is not None:
reader.join() reader.join()
@@ -140,19 +221,60 @@ def main():
[int(m.group(i)) for i in (5, 6, 7)] == list(sent[-1]), [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)}") f"led0 {m.group(2, 3, 4)} led_last {m.group(5, 6, 7)}")
# Test animations: send each one, then check the last frame is shown
for name, fn in ANIMATIONS.items():
pixels = None
for k in range(ANIM_FRAMES):
pixels = [fn(i, k) for i in range(LEDS)]
send_frame(sock, host, pixels, k)
time.sleep(0.025)
time.sleep(0.2)
bad = verify_frame(host, sock, pixels, scale)
check(f"animation {name} shows its last frame", not bad, mismatch_detail(bad))
shown = pixels
# Pixels past the strip end are ignored and don't break the rest # 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)) sock.sendto(packet(0, LEDS * 3 + 30, b"\xff" * 30, True), (host, PORT))
time.sleep(0.1) time.sleep(0.1)
check("out-of-range packet ignored", get(host, "/api/ddp?led=0")["rgb"] == list(last[0])) check("out-of-range packet ignored", get(host, "/api/ddp?led=0")["rgb"] == expected([shown[0]], scale)[0])
# Stop sending: the pattern should come back after the timeout # Stop sending: the pattern should come back after the timeout
time.sleep(3.0) time.sleep(3.0)
after = get(host, "/api/ddp") after = get(host, "/api/ddp")
check("inactive after pixels stop", not after["active"]) check("inactive after pixels stop", not after["active"])
shown = get(host, "/api/ddp?led=0")["rgb"] now_led0 = get(host, "/api/ddp?led=0")["rgb"]
check("pattern is shown again", shown != list(last[0]), f"LED 0 now {shown}") check("pattern is shown again", now_led0 != expected([shown[0]], scale)[0], f"LED 0 now {now_led0}")
print("\nRESULT:", "all passed" if not failures else f"{failures} failed") return failures, out
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)
subnet = next((a.split("=", 1)[1] for a in sys.argv[1:] if a.startswith("--subnet=")), None)
if args:
hosts = args
else:
prefix = subnet or local_prefix()
hosts = find_devices(prefix)
print(f"found {len(hosts)} device(s) on {prefix}.0/24: {', '.join(hosts) or 'none'}\n")
if not hosts:
sys.exit(1)
if serial_port and len(hosts) > 1:
print("note: --serial is only used when testing one device\n")
serial_port = None
# All devices at the same time, one thread each
with ThreadPoolExecutor(max_workers=len(hosts)) as pool:
results = list(pool.map(lambda h: run(h, serial_port), hosts))
failures = 0
for host, (device_failures, out) in zip(hosts, results):
print(f"== {host}")
print("\n".join(out))
print()
failures += device_failures
print("RESULT:", "all passed" if not failures else f"{failures} failed")
sys.exit(1 if failures else 0) sys.exit(1 if failures else 0)