#!/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, 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 # 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 math import re import socket import struct import sys import threading import time import urllib.request from concurrent.futures import ThreadPoolExecutor PORT = 4048 LEDS = 119 PUSH = 0x01 VER1 = 0x40 RGB = 0x01 ANIM_FRAMES = 40 # about 1 s at 40 fps 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 local_prefix(): """The first three octets of this machine's IPv4 address (assumes a /24 subnet).""" s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) try: 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 sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) def log(line=""): out.append(line) def check(name, ok, detail=""): nonlocal failures log(("PASS " if ok else "FAIL ") + name + (f" {detail}" if detail else "")) if not ok: failures += 1 before = get(host, "/api/ddp") 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 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']}") bad = verify_frame(host, sock, last, scale) check(f"all {LEDS} LEDs show the frame", not bad, mismatch_detail(bad)) shown = last 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)}") # 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 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"] == expected([shown[0]], scale)[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"]) now_led0 = get(host, "/api/ddp?led=0")["rgb"] check("pattern is shown again", now_led0 != expected([shown[0]], scale)[0], f"LED 0 now {now_led0}") 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) if __name__ == "__main__": main()