#!/usr/bin/env python3 """ Test the LED driver's DDP receiver (UDP port 4048) and its frame sync (UDP broadcast port 4049). Every frame goes to each device as unicast DDP: a version 1 header and the whole frame in one packet, with the PUSH flag set (the one-off checks in the full test still send two packets). After each tick one broadcast ("LSY1" + seq) tells all devices to show the frame they hold. The interactive and soak modes send it a tick after the frames (so even a slow device has its frame by then) and do not wait for acks; the full test (no flags) waits for each device's ack first. The devices are driven together, from one sender. Through the driver's HTTP API the test checks that the pixels were shown, that a frame waits for a sync, runs a few test animations, and that the last frame stays up once the pixels stop. python3 tools/ddp_test.py # the devices in tools/rig.json (their IPs and places in the rig) python3 tools/ddp_test.py --broadcast-only # send the sync only as a broadcast (default: also to each device by unicast) python3 tools/ddp_test.py --discover # finds every device on this machine's subnet (/24) python3 tools/ddp_test.py --subnet=192.168.4 # pick the network: devices are found on it and the sync goes to its broadcast address (192.168.4.255) python3 tools/ddp_test.py --fps=30 # frames per second (default 60, lowered for big rigs: 250 / number of devices) python3 tools/ddp_test.py --brightness=20 # send the colours at 20% (default and maximum 25) python3 tools/ddp_test.py --interactive # pick patterns from a menu and watch them on the rig python3 tools/ddp_test.py --soak=600 # long run: cycle the soak patterns for 600 s, sampling LEDs as it goes python3 tools/ddp_test.py --expect=5 # keep scanning until 5 devices answer (a busy device can be slow) 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 asyncio import colorsys import os import random 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 RIG_FILE = os.path.join(os.path.dirname(os.path.abspath(__file__)), "rig.json") ROW_OF = {} # device index in the soak -> its row in the rig, for the patterns that follow the layout SYNC_PORT = 4049 LEDS = 119 PUSH = 0x01 VER1 = 0x40 RGB = 0x01 FPS = 60 # frames per second (--fps=N) TICK = 1 / FPS # seconds between ticks FRAME_BUDGET = 250 # frames per second the Wi-Fi carried for the whole rig (measured with 16 bars: 15 fps worked, 25+ did not) ACK_WAIT = TICK * 0.6 # seconds to wait for each device's ack before the sync goes out anyway ANIM_FRAMES = 40 # frames of each test animation def set_fps(fps): global FPS, TICK, ACK_WAIT FPS = fps TICK = 1 / fps ACK_WAIT = TICK * 0.6 def load_rig(path=RIG_FILE): """The rig map: {"rows", "columns", "devices": [{name, ip, row, column, reversed, usb?}]}, in the order the soak lays the bars out (row by row, left to right). None if there is no map file.""" try: with open(path) as f: rig = json.load(f) except FileNotFoundError: return None rig["devices"].sort(key=lambda d: (d["row"], d["column"])) return rig def packet(seq, offset, data, push): """Every DDP packet is built here, so this is the hard limit: no byte leaves above the brightness cap, whatever the pattern, the test or a bug upstream put in it.""" top = 255 * MAX_BRIGHTNESS // 100 data = data.translate(bytes(min(i, top) for i in range(256))) 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): """Unicast 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)) UNICAST_SYNC = True # also send each device its own copy of every sync (--broadcast-only turns this off) def send_sync(sock, seq, broadcast, devices=()): """Broadcast a sync to the network's broadcast address: every device shows the frame it holds. A Wi-Fi access point may not deliver broadcasts to every client (one of ours got none), so with UNICAST_SYNC each of `devices` is also sent the sync directly. A device that gets both shows the frame on the first and finds nothing held on the second, which does nothing.""" msg = b"LSY1" + struct.pack(">I", seq & 0xFFFFFFFF) targets = [broadcast] + (list(devices) if UNICAST_SYNC else []) for t in targets: try: sock.sendto(msg, (t, SYNC_PORT)) except BlockingIOError: pass # the socket's send buffer is full: this copy is dropped, as a lost packet would be 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, stop, lines): """Collect the driver's log lines from the USB serial port until stop is set.""" import serial ser = serial.Serial(port, 115200, timeout=0.2) buf = b"" while not stop.is_set(): buf += ser.read(4096) ser.close() lines.extend(buf.decode("utf-8", "replace").splitlines()) def get(host, path, timeout=5, tries=3): """GET a JSON path from a device. A device busy with a stream can miss a request, so a timeout is retried (tries in all) before it is raised; the soak's samples use tries=1 and count a miss instead.""" for n in range(tries): try: with urllib.request.urlopen(f"http://{host}{path}", timeout=timeout) as r: return json.loads(r.read().decode()) except OSError: if n == tries - 1: raise class Missing(dict): """What soft_get returns for a device that did not answer: every field reads as a value that fails its check (rgb is -1, active is False, counters are -1), so one silent device fails its own checks and the test goes on with the rest.""" def __missing__(self, key): return [-1, -1, -1] if key == "rgb" else False if key == "active" else -1 def soft_get(host, path, **kw): """get(), but a device that does not answer gives a Missing instead of ending the whole run.""" try: return get(host, path, **kw) except OSError: return Missing() 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 neighbours(prefix): """Addresses on the subnet that this machine has seen on the LAN (its ARP table), whether or not they answered HTTP: a device that is up but slow to answer shows here.""" import subprocess try: out = subprocess.run(["ip", "-4", "neigh"], capture_output=True, text=True, timeout=5).stdout except Exception: return [] ips = [] for line in out.splitlines(): parts = line.split() if parts and parts[0].startswith(prefix + ".") and "FAILED" not in parts and "INCOMPLETE" not in parts: ips.append(parts[0]) return ips def find_devices(prefix, expect=None): """Every host on the subnet that answers the driver's /api/ddp endpoint. A device that is busy can be slow to answer, so after the full sweep, hosts seen on the LAN that did not answer are retried with a longer timeout (3 times). If fewer than `expect` devices answered, one more full sweep runs.""" def probe(ip, timeout): try: with urllib.request.urlopen(f"http://{ip}/api/ddp", timeout=timeout) as r: json.loads(r.read().decode()) return ip except Exception: return None def sweep(ips, timeout): with ThreadPoolExecutor(64) as pool: return {ip for ip in pool.map(lambda ip: probe(ip, timeout), ips) if ip} all_ips = [f"{prefix}.{i}" for i in range(1, 255)] found = sweep(all_ips, 1.5) for _ in range(3): silent = [ip for ip in neighbours(prefix) if ip not in found] if not silent: break found |= sweep(silent, 3.0) if expect is not None and len(found) < expect: found |= sweep([ip for ip in all_ips if ip not in found], 3.0) return sorted(found, key=lambda ip: int(ip.rsplit(".", 1)[1])) # 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} MAX_BRIGHTNESS = 25 # percent: the test never sends brighter than this, whatever --brightness asks for (the PSU trips above it) BRIGHTNESS = MAX_BRIGHTNESS # percent: the colours the test sends are scaled to this (--brightness=20) def dim(px): return tuple(c * min(BRIGHTNESS, MAX_BRIGHTNESS) // 100 for c in px) def frame(k): """A frame: LED i is a colour that depends on i, so every LED is distinguishable.""" return [dim(((i * 7 + k) % 256, (i * 13) % 256, (255 - i * 3) % 256)) for i in range(LEDS)] 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]}" class Sender: """Drives every device from one thread. Each tick sends each device its current frame (unicast), then one sync broadcast that all devices show their frame on.""" def __init__(self, sock, hosts, broadcast, sync=True, acks=False): self.sync = sync # broadcast a sync after each frame, so every device shows it together (else: on its PUSH) self.acks = acks # also wait for each device's ack before the sync (the full test; costs a wait per tick) self.sock = sock self.hosts = hosts self.broadcast = broadcast self.ip_of = {h: socket.gethostbyname(h) for h in hosts} self.host_of = {ip: h for h, ip in self.ip_of.items()} self.missed = {h: 0 for h in hosts} # frames a device did not ack in time self.sock.setblocking(False) # asyncio drives the socket self.frames = {h: None for h in hosts} self.pending_sync = None # seq of the last frames sent, whose sync goes out at the start of the next tick self.late = set() # devices that did not ack the last frame: skipped once, so their queue can drain self.skipped = {h: 0 for h in hosts} self.seq = 0 self.paused = False self.lock = threading.Lock() self.tick_event = threading.Event() # set at the start of every tick: the pattern thread paces on it self.stop_event = threading.Event() self.thread = threading.Thread(target=self._run, daemon=True) def set_frames(self, pixels_by_host): with self.lock: self.frames.update(pixels_by_host) async def send_host(self, loop, h, pixels, seq): """Send one device its whole frame in one packet, with PUSH set; each device is sent to on its own.""" raw = bytes(c for px in pixels for c in px) await loop.sock_sendto(self.sock, packet(seq, 0, raw, True), (h, PORT)) def wait_tick(self): """Block until the next tick starts. Pattern threads call this instead of sleeping, so exactly one new frame is made per tick: two separate 60 Hz clocks drift against each other and beat, which shows as repeated and skipped frames (judder).""" self.tick_event.wait(1.0) self.tick_event.clear() async def tick(self, loop): t0 = time.monotonic() with self.lock: frames = dict(self.frames) self.tick_event.set() # the frame just taken goes out now; the pattern thread makes the next one self.seq = (self.seq + 1) & 0xFFFFFFFF due = [h for h in self.hosts if frames[h] is not None] if not self.acks: # Without acks the sender can't tell when a frame has landed, and a broadcast goes out at once # while unicast frames queue behind each other and the air, so a sync straight after the frames # can beat the slowest device's frame (it then shows a frame late and falls out of line). So the # sync for the last tick's frames goes out at the start of this tick, a whole tick after them. if self.sync and self.pending_sync is not None: send_sync(self.sock, self.pending_sync, self.broadcast, self.ip_of.values()) await asyncio.gather(*(self.send_host(loop, h, frames[h], self.seq) for h in due)) self.pending_sync = self.seq return sent = [h for h in due if h not in self.late] for h in due: if h in self.late: self.skipped[h] += 1 # still catching up: send it nothing this tick rather than queue more self.late = set() await asyncio.gather(*(self.send_host(loop, h, frames[h], self.seq) for h in sent)) self.late = await self.wait_acks(loop, self.seq & 0x0F, sent) rest = t0 + ACK_WAIT - time.monotonic() if rest > 0: await asyncio.sleep(rest) # sync at a fixed point in the tick, so quick or slow acks don't move it send_sync(self.sock, self.seq, self.broadcast, self.ip_of.values()) async def wait_acks(self, loop, nibble, hosts): """Wait until each device acks this frame (the driver acks a completed frame with "LAK1" and its DDP seq), up to ACK_WAIT. Devices that do not ack in time are counted as missed.""" waiting = {self.ip_of[h] for h in hosts} async def collect(): while waiting: data, addr = await loop.sock_recvfrom(self.sock, 64) if data[:4] == b"LAK1" and len(data) >= 5 and (data[4] & 0x0F) == nibble: waiting.discard(addr[0]) try: await asyncio.wait_for(collect(), ACK_WAIT) except asyncio.TimeoutError: pass for ip in waiting: self.missed[self.host_of[ip]] += 1 return {self.host_of[ip] for ip in waiting} async def _loop(self): # Fixed rate: ticks start every TICK seconds on a schedule, so the ack waits don't stretch the rate loop = asyncio.get_running_loop() next_tick = time.monotonic() while not self.stop_event.is_set(): if not self.paused: await self.tick(loop) next_tick += TICK delay = next_tick - time.monotonic() if delay > 0: await asyncio.sleep(delay) else: next_tick = time.monotonic() # fell behind: start the schedule again from now def _run(self): asyncio.run(self._loop()) def start(self): self.thread.start() def stop(self): self.stop_event.set() self.thread.join() # Long-running patterns for --soak. Each maps (position, frame number, total) to an RGB colour, where # position runs along the whole rig: the bars are laid end to end in host order, `total` LEDs long, so a # pattern travels across the bars and not just along each one. Each is smooth enough that a frame is near # the one before it. def soak_rainbow_scroll(i, k, n): r, g, b = colorsys.hsv_to_rgb((i / n + k / 400) % 1.0, 1, 1) return (int(r * 255), int(g * 255), int(b * 255)) def soak_plasma(i, k, n): v = math.sin(i / 23 + k / 17) + math.sin(i / 9 - k / 11) + math.sin((i + k / 3) / 41) r, g, b = colorsys.hsv_to_rgb((v / 6 + 0.5 + k / 900) % 1.0, 1, 1) return (int(r * 255), int(g * 255), int(b * 255)) def soak_comet(i, k, n): head = (k // 2) % (n * 2) head = head if head < n else 2 * n - 1 - head # bounces from the first bar to the last and back v = max(0, 255 - abs(i - head) * 25) return (v, v // 2, 0) def soak_color_wipe(i, k, n): m = (k // 2) % (n * 2) on = i < m if m <= n else i >= m - n r, g, b = colorsys.hsv_to_rgb(((k // (n * 4)) * 0.17) % 1.0, 1, 1) return (int(r * 255), int(g * 255), int(b * 255)) if on else (0, 0, 0) def soak_sparkle(i, k, n): rng = random.Random(i * 7919 + k // 4) return (255, 255, 255) if rng.random() < 0.06 else (0, 0, 20) def soak_gradient_sweep(i, k, n): t = (i / n * 2 + k / 120) % 1.0 return (int(255 * t), int(255 * (1 - t)), 128) def soak_slow_breathe(i, k, n): v = int(127.5 * (1 - math.cos(k / 40 + i / (n / 6)))) # a slow wave over the rig return (v, v // 3, 255 - v) def soak_bar_chase(i, k, n): bar = (k // 30) % max(1, n // LEDS) # one whole bar lit at a time, 0.75 s each, in order return (0, 200, 255) if i // LEDS == bar else (0, 0, 10) def soak_ripple(i, k, n): d = abs(i - n / 2) # rings out from the middle of the rig, so the two ends mirror each other v = int(127.5 * (1 + math.sin(d / 6 - k / 5))) return (v, 0, 255 - v) def soak_row_sweep(i, k, n): row = ROW_OF.get(i // LEDS, 0) rows = max(ROW_OF.values(), default=0) + 1 lit = (k // 30) % rows # one row of the rig lit at a time, 0.75 s each, top to bottom return (255, 80, 0) if row == lit else (10, 0, 0) def soak_strobe(i, k, n): return (255, 255, 255) if (k // 20) % 2 else (0, 0, 0) # a flash every 0.5 s: a hard test for dropped frames # Rig-shaped patterns. The bars are 2 columns x 8 rows. In host order the left column comes first (hosts # 101-108, top row to bottom), then the right column (109-116): bar b is in column b // rows, row b % rows. # The data-in heads are in the middle, so LED 0 of each bar is at the centre and LED 118 at the outer end: # left bars run out to the left, right bars out to the right. With fewer hosts the rows just run out # sooner (one host is one left bar). ROW_GAP = 10 # LEDs of distance between neighbouring rows, so a diagonal looks about right def rig_rows(n): return max(1, (n // LEDS + 1) // 2) def rig_xy(i, n): """(x, y, rows) of LED i of n: x is LEDs from the centre (negative on the left), y is the row in LEDs.""" rows = rig_rows(n) bar, led = divmod(i, LEDS) x = led + 0.5 return (x if bar // rows else -x), (bar % rows) * ROW_GAP, rows def hsv(h, s=1.0, v=1.0): r, g, b = colorsys.hsv_to_rgb(h % 1.0, s, v) return (int(r * 255), int(g * 255), int(b * 255)) def soak_rig_sweep(i, k, n): x, y, rows = rig_xy(i, n) # a vertical band sweeping from the left end to the right end and back pos = (math.sin(k / 40) * 0.5 + 0.5) * 2 * LEDS - LEDS v = max(0, 255 - int(abs(x - pos) * 12)) return (0, v, v // 3) def soak_rig_row_scan(i, k, n): x, y, rows = rig_xy(i, n) # a horizontal band scanning down the rows and back up span = max(1, rows - 1) * ROW_GAP pos = (math.sin(k / 50) * 0.5 + 0.5) * span v = max(0, 255 - int(abs(y - pos) * 25)) return (v, v // 4, v) def soak_rig_ripple(i, k, n): x, y, rows = rig_xy(i, n) # rings out from the middle of the rig, through the rows d = math.hypot(x, y - (rows - 1) * ROW_GAP / 2) return hsv(0.6 + 0.2 * math.sin(d / 20 - k / 30), 1, 0.5 + 0.5 * math.sin(d / 5 - k / 4)) def soak_rig_converge(i, k, n): x, y, rows = rig_xy(i, n) # pulses run in from both outer ends to the heads, then back out ph = (k // 3) % (LEDS * 2) pos = LEDS - ph if ph < LEDS else ph - LEDS v = max(0, 255 - int(abs(abs(x) - pos) * 20)) return (v, v // 2, 0) def soak_rig_rows_chase(i, k, n): x, y, rows = rig_xy(i, n) # one row lit at a time, 0.5 s each, a different hue per lap row = int(y // ROW_GAP) cur = (k // 20) % rows lap = (k // 20) // rows return hsv(lap * 0.13, 1, 1) if row == cur else (0, 0, 8) def soak_rig_columns(i, k, n): right = (i // LEDS) // rig_rows(n) # left and right columns take turns, 0.5 s each return (255, 40, 0) if right == (k // 20) % 2 else (0, 40, 255) def soak_rig_checker(i, k, n): x, y, rows = rig_xy(i, n) # a checkerboard of 20 LED cells that flips every 0.75 s cell = int(abs(x) // 20) + int(x < 0) + int(y // ROW_GAP) return (255, 255, 255) if (cell + k // 30) % 2 else (0, 0, 30) def soak_rig_diagonal(i, k, n): x, y, rows = rig_xy(i, n) # a rainbow whose bands slant across the rows and both columns return hsv((x + y * 2) / 300 - k / 200) def soak_rig_scanner(i, k, n): x, y, rows = rig_xy(i, n) # a bar across every row that bounces between the outer ends, with a tail ph = (k // 2) % (4 * LEDS) going_right = ph < 2 * LEDS pos = ph - LEDS if going_right else 3 * LEDS - ph behind = (pos - x) if going_right else (x - pos) # positive: this LED is in the tail v = max(0, 255 - int(abs(behind) * (6 if behind > 0 else 40))) return (v, 0, v // 5) def soak_rig_row_rainbow(i, k, n): x, y, rows = rig_xy(i, n) # each row its own hue, the hues turning, brightest at the heads return hsv(y / (ROW_GAP * max(1, rows)) + k / 300, 1, 1 - abs(x) / (LEDS * 1.5)) # 2D patterns: they treat the rig as a flat picture (x across, y down the rows) rather than as separate bars. SLANT = 3 # LEDs of x per row for the diagonals, so a band crosses the rig at roughly 45 degrees on screen def rig_mid(rows): return (rows - 1) * ROW_GAP / 2 def soak_rig_diag_sweep(i, k, n): x, y, rows = rig_xy(i, n) # a slanted band that sweeps from the top-left corner to the bottom-right and wraps lo, hi = -LEDS, LEDS + (rows - 1) * ROW_GAP * SLANT d = x + y * SLANT pos = lo + (k * 1.5) % (hi - lo + 60) v = max(0, 255 - int(abs(d - pos) * 10)) return (v, v // 3, 0) def soak_rig_diag_bounce(i, k, n): x, y, rows = rig_xy(i, n) # the other slant, bouncing back and forth with a soft fade-out behind it lo, hi = -LEDS - (rows - 1) * ROW_GAP * SLANT, LEDS d = x - y * SLANT t = (k * 1.5) % (2 * (hi - lo)) pos = lo + (t if t < hi - lo else 2 * (hi - lo) - t) v = max(0, 255 - int(abs(d - pos) * 9)) return (0, v // 3, v) def soak_rig_radar(i, k, n): x, y, rows = rig_xy(i, n) # a line turning round the middle of the rig like a radar, with a fading tail ang = math.atan2((y - rig_mid(rows)) * 3, x) # y is stretched so the turn looks round sweep = (k / 40) % (2 * math.pi) behind = (sweep - ang) % (2 * math.pi) v = max(0, 255 - int(behind * 70)) return (0, v, v // 6) def soak_rig_spiral(i, k, n): x, y, rows = rig_xy(i, n) # colour arms that wind out from the middle and turn dy = (y - rig_mid(rows)) * 3 ang = math.atan2(dy, x) r = math.hypot(x, dy) return hsv(ang / (2 * math.pi) * 2 + r / 150 - k / 120, 1, 0.5 + 0.5 * math.sin(ang * 3 + r / 10 - k / 8)) def soak_rig_diamond(i, k, n): x, y, rows = rig_xy(i, n) # diamond outlines (taxicab distance) that grow out of the middle d = abs(x) + abs(y - rig_mid(rows)) * 2 behind = (k * 1.2 - d) % 50 # distance behind the nearest ring front v = max(0, 255 - int(behind * 8)) return (v, 0, v // 2) def soak_rig_corners(i, k, n): x, y, rows = rig_xy(i, n) # a spot that runs round the four corners of the rig, one after another corners = [(-LEDS, 0), (LEDS, 0), (LEDS, (rows - 1) * ROW_GAP), (-LEDS, (rows - 1) * ROW_GAP)] t = k / 60 a, b = corners[int(t) % 4], corners[(int(t) + 1) % 4] f = t - int(t) cx, cy = a[0] + (b[0] - a[0]) * f, a[1] + (b[1] - a[1]) * f d = math.hypot(x - cx, (y - cy) * 3) v = max(0, 255 - int(d * 9)) return (v, v, v // 4) def soak_rig_plasma2d(i, k, n): x, y, rows = rig_xy(i, n) # a slow plasma that really varies in both directions v = math.sin(x / 25 + k / 50) + math.sin(y / 6 - k / 70) + math.sin((x + y * 2) / 30 + k / 90) return hsv(0.5 + v / 6, 1, 0.5 + 0.5 * math.sin(v * 1.5)) def soak_rig_bounce(i, k, n): x, y, rows = rig_xy(i, n) # a ball bouncing round the rig, off the edges, with a hue that changes at each bounce w, h = 2 * LEDS, max(1, (rows - 1) * ROW_GAP) def tri(t, size): # triangle wave 0..size..0 t %= 2 * size return t if t < size else 2 * size - t bx = tri(k * 1.7, w) - LEDS by = tri(k * 0.55 + 20, h) hue = int(k * 1.7 / w) * 0.17 + int((k * 0.55 + 20) / h) * 0.31 v = max(0, 255 - int(math.hypot(x - bx, (y - by) * 2.5) * 12)) return hsv(hue, 1, v / 255) def soak_rig_rain(i, k, n): x, y, rows = rig_xy(i, n) # drops falling down the rows at different speeds, one lane per 8 LEDs of x lane = int(x // 8) speed = 0.04 + (lane * 7 % 5) * 0.015 # rows per frame span = rows + 4 head = (k * speed + lane * 3.7) % span - 2 fall = head - y / ROW_GAP # positive: the LED is in the tail above the drop v = max(0, 255 - int(abs(fall) * 160)) if fall >= 0 else 0 return (v // 4, v // 2, v) SOAK = { "rainbow scroll": soak_rainbow_scroll, "plasma": soak_plasma, "comet": soak_comet, "color wipe": soak_color_wipe, "sparkle": soak_sparkle, "gradient sweep": soak_gradient_sweep, "slow breathe": soak_slow_breathe, "bar chase": soak_bar_chase, "row sweep": soak_row_sweep, "ripple": soak_ripple, "strobe": soak_strobe, "rig sweep": soak_rig_sweep, "rig row scan": soak_rig_row_scan, "rig ripple": soak_rig_ripple, "rig converge": soak_rig_converge, "rig rows chase": soak_rig_rows_chase, "rig columns": soak_rig_columns, "rig checker": soak_rig_checker, "rig diagonal": soak_rig_diagonal, "rig scanner": soak_rig_scanner, "rig row rainbow": soak_rig_row_rainbow, "2d diagonal sweep": soak_rig_diag_sweep, "2d diagonal bounce": soak_rig_diag_bounce, "2d radar": soak_rig_radar, "2d spiral": soak_rig_spiral, "2d diamonds": soak_rig_diamond, "2d corners": soak_rig_corners, "2d plasma": soak_rig_plasma2d, "2d bounce": soak_rig_bounce, "2d rain": soak_rig_rain, } SOAK_EACH = 30 # seconds per pattern SOAK_SAMPLE = 0.4 # seconds between LED samples SOAK_HISTORY = 12 # recent frames a sample may match (the sample is read a little after it was sent) def run_soak(hosts, broadcast, seconds): """Stream the soak patterns to every device for `seconds`, sampling one random LED per device now and then. A sample is good if it equals that LED in any recent frame; a sample of the idle pattern while streaming is the flicker this test hunts. Ends with a per-device summary.""" sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) sock.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1) sender = Sender(sock, hosts, broadcast) before = {h: get(h, "/api/ddp") for h in hosts} # The devices apply their max brightness ceiling to DDP frames, so a sample is compared to that scale = {h: get(h, "/api/hardware")["max_brightness"] for h in hosts} stats = {h: {"samples": 0, "bad": 0, "idle": 0, "errors": 0, "examples": []} for h in hosts} names = list(SOAK) sender.start() start = time.time() k = 0 history = {h: [] for h in hosts} next_sample = start + 1.0 # warm-up: the first frames are still reaching the devices pool = ThreadPoolExecutor(len(hosts)) cur = None print(f"soak: {seconds} s, {len(SOAK)} patterns of {SOAK_EACH} s each across {len(hosts)} bars in this order: {', '.join(hosts)}, brightness {BRIGHTNESS}%\n") while time.time() - start < seconds: idx = int((time.time() - start) // SOAK_EACH) % len(names) if names[idx] != cur: cur = names[idx] print(f"[{int(time.time() - start):5d}s] {cur}") fn = SOAK[cur] total = LEDS * len(hosts) frames = {h: [dim(fn(n * LEDS + i, k, total)) for i in range(LEDS)] for n, h in enumerate(hosts)} for h in hosts: history[h] = (history[h] + [frames[h]])[-SOAK_HISTORY:] sender.set_frames(frames) k += 1 if time.time() >= next_sample: next_sample = time.time() + SOAK_SAMPLE led = random.randrange(LEDS) wants = {h: {tuple(expected([f[led]], scale[h])[0]) for f in history[h]} for h in hosts} def sample(h, led=led): # A short timeout: the sender waits for this, so a slow device must not stall the frames try: r = get(h, f"/api/ddp?led={led}", timeout=1.0, tries=1) except OSError: return h, led, None, None, wants[h] return h, led, tuple(r["rgb"]), r["active"], wants[h] for h, l, got, active, w in pool.map(sample, hosts): st = stats[h] if got is None: # no answer in time: counted, but not a mismatch st["errors"] += 1 continue st["samples"] += 1 if got not in w: st["bad"] += 1 if got == (16, 16, 16) and (16, 16, 16) not in w: st["idle"] += 1 if len(st["examples"]) < 3: st["examples"].append(f"[{int(time.time() - start)}s {cur}] LED {l} got {list(got)} active={active}") sender.wait_tick() sender.stop() pool.shutdown() time.sleep(0.3) elapsed = time.time() - start print(f"\nsoak finished: {elapsed:.0f} s, {k} frames sent, {sender.seq} ticks\n") failures = 0 for h in hosts: a = soft_get(h, "/api/ddp") sy, sb = a["sync"], before[h]["sync"] if not isinstance(sy, dict): sy = {"frames": sb["frames"] - 1, "shown": sb["shown"] - 1} st = stats[h] print(f"== {h}: frames +{sy['frames'] - sb['frames']}, shown +{sy['shown'] - sb['shown']}, " f"samples {st['samples']}, " f"mismatches {st['bad']}, no answer {st['errors']}, idle-pattern flickers {st['idle']}") for e in st["examples"]: print(" " + e) if st["idle"]: failures += 1 print("\nRESULT:", "no flicker seen" if not failures else f"{failures} device(s) flickered") return failures def run_interactive(hosts, broadcast): """Stream one pattern at a time to every device, and switch by typing at the prompt: a number or the start of a name picks a pattern, n / p step to the next or previous, b <0-25> sets the brightness, l lists the patterns, q quits. Per-bar animations (chase, rainbow, breathe) are in the menu too.""" global BRIGHTNESS menu = dict(SOAK) for name, fn in ANIMATIONS.items(): menu[name] = lambda i, k, n, fn=fn: fn(i % LEDS, k) names = list(menu) def show_menu(): for num, name in enumerate(names, 1): print(f" {num:2d} {name}") sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) sock.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1) sender = Sender(sock, hosts, broadcast) state = {"cur": 0, "quit": False} cmds = [] def read_stdin(): for line in sys.stdin: cmds.append(line.strip()) cmds.append("q") # end of input threading.Thread(target=read_stdin, daemon=True).start() def handle(cmd): global BRIGHTNESS if not cmd: return low = cmd.lower() if low == "q": state["quit"] = True elif low == "l": show_menu() elif low == "n": state["cur"] = (state["cur"] + 1) % len(names) elif low == "p": state["cur"] = (state["cur"] - 1) % len(names) elif low.startswith("b ") and low[2:].strip().isdigit(): BRIGHTNESS = max(0, min(MAX_BRIGHTNESS, int(low[2:]))) print(f"brightness {BRIGHTNESS}%") elif low.isdigit() and 1 <= int(low) <= len(names): state["cur"] = int(low) - 1 else: hit = [i for i, nm in enumerate(names) if nm.startswith(low)] or [i for i, nm in enumerate(names) if low in nm] if not hit: print(f"no pattern '{cmd}' (l lists them)") return state["cur"] = hit[0] if not state["quit"]: print(f"-> {names[state['cur']]}") print(f"{len(hosts)} bars in this order: {', '.join(hosts)}\n") show_menu() print("\ntype a number or name, n/p next/previous, b <0-25> brightness, l list, q quit\n") print(f"-> {names[state['cur']]}") sender.start() k = 0 total = LEDS * len(hosts) try: while not state["quit"]: while cmds: handle(cmds.pop(0)) fn = menu[names[state["cur"]]] sender.set_frames({h: [dim(fn(n * LEDS + i, k, total)) for i in range(LEDS)] for n, h in enumerate(hosts)}) k += 1 sender.wait_tick() except KeyboardInterrupt: pass sender.stop() sock.close() for h in hosts: print(f"{h}: {sender.seq} frames sent") def run_all(hosts, serial_port, broadcast): """Run every check against every device together. Returns (output lines, failures) per host.""" out = {h: [] for h in hosts} fails = {h: 0 for h in hosts} def check(h, name, ok, detail=""): out[h].append(("PASS " if ok else "FAIL ") + name + (f" {detail}" if detail else "")) if not ok: fails[h] += 1 sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) sock.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1) before, scale = {}, {} for h in hosts: before[h] = soft_get(h, "/api/ddp") # DDP frames ignore the device and master brightness, but the max brightness ceiling still applies scale[h] = soft_get(h, "/api/hardware")["max_brightness"] out[h].append(f"before: active={before[h]['active']} packets={before[h]['packets']}") out[h].append(f"output scale: {scale[h]}/255") sender = Sender(sock, hosts, broadcast, acks=True) sent = {} # frame checksum -> pixels, for the serial log check stop_serial = threading.Event() serial_lines = [] reader = None if serial_port: reader = threading.Thread(target=read_serial, args=(serial_port, stop_serial, serial_lines), daemon=True) reader.start() sender.start() for k in range(60): # about 1.5 s px = frame(k) sent[frame_sum(px)] = px sender.set_frames({h: px for h in hosts}) time.sleep(TICK) time.sleep(0.2) for h in hosts: out[h].append(f"frames not acked in time while streaming: {sender.missed[h]}") for h in hosts: mid = soft_get(h, "/api/ddp") check(h, "receiving while sending", mid["active"], f"packets={mid['packets']}") check(h, "packets counted", mid["packets"] - before[h]["packets"] >= 50, # one packet per frame, 60 frames (a few may be lost) f"+{mid['packets'] - before[h]['packets']}") # A frame waits for a sync: send one by unicast alone, then a sync, and check the strip changes sender.paused = True time.sleep(0.1) waiting = frame(200) sent[frame_sum(waiting)] = waiting send_sync(sock, sender.seq + 1, broadcast, sender.ip_of.values()) # sync mode is on: a sync was sent a moment ago time.sleep(0.06) # later than the devices' 30 ms sync window, so the frame is held for h in hosts: send_frame(sock, h, waiting, sender.seq + 1) time.sleep(0.3) for h in hosts: got = soft_get(h, "/api/ddp?led=0")["rgb"] check(h, "frame waits for a sync", got != expected([waiting[0]], scale[h])[0], f"LED 0 shows {got} before the sync") send_sync(sock, sender.seq + 2, broadcast, sender.ip_of.values()) time.sleep(0.2) for h in hosts: got = soft_get(h, "/api/ddp?led=0")["rgb"] check(h, "frame shows on the sync", got == expected([waiting[0]], scale[h])[0], f"LED 0 {got}") sender.paused = False stop_serial.set() if reader is not None: reader.join() h = hosts[0] 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(h, "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] check(h, "logged checksums are of sent frames", len(matched) == len(summaries), f"{len(matched)}/{len(summaries)} match") for m in summaries[-1:]: px = sent.get(int(m.group(1))) if px is not None: check(h, "serial led0 and last LED match that frame", [int(m.group(i)) for i in (2, 3, 4)] == list(px[0]) and [int(m.group(i)) for i in (5, 6, 7)] == list(px[-1]), f"led0 {m.group(2, 3, 4)} led_last {m.group(5, 6, 7)}") def readback(h, pixels): """Read every LED back and return the ones that do not match what the driver should show.""" want_all = expected(pixels, scale[h]) bad = [] for i in range(LEDS): try: got = get(h, f"/api/ddp?led={i}", timeout=3, tries=2)["rgb"] except OSError: # no answer: this check fails for the device, the run goes on bad.append((i, "no answer", want_all[i])) break if got != want_all[i]: bad.append((i, got, want_all[i])) return bad def check_readback(name, pixels): # Lost frames are expected, and the sender repeats each frame, so give the strips up to 1 s to # settle on it before reading back: the check passes once every LED matches deadline = time.time() + 1.0 while True: with ThreadPoolExecutor(len(hosts)) as pool: bads = list(pool.map(lambda h: readback(h, pixels), hosts)) if all(not bad for bad in bads) or time.time() > deadline: break time.sleep(0.05) for h, bad in zip(hosts, bads): check(h, name, not bad, mismatch_detail(bad)) shown = frame(59) sender.set_frames({h: shown for h in hosts}) time.sleep(0.1) check_readback(f"all {LEDS} LEDs show the frame", shown) for name, fn in ANIMATIONS.items(): for k in range(ANIM_FRAMES): px = [dim(fn(i, k)) for i in range(LEDS)] sender.set_frames({h: px for h in hosts}) time.sleep(TICK) time.sleep(0.1) check_readback(f"animation {name} shows its last frame", px) shown = px # Pixels past the strip end are ignored and don't break the rest for h in hosts: sock.sendto(packet(0, LEDS * 3 + 30, b"\xff" * 30, True), (h, PORT)) time.sleep(0.2) for h in hosts: check(h, "out-of-range packet ignored", soft_get(h, "/api/ddp?led=0")["rgb"] == expected([shown[0]], scale[h])[0]) # Stop sending: the pattern should come back after the timeout sender.stop() time.sleep(3.0) for h in hosts: after = soft_get(h, "/api/ddp") check(h, "inactive after pixels stop", not after["active"]) now0 = soft_get(h, "/api/ddp?led=0")["rgb"] check(h, "last frame stays up", now0 == expected([shown[0]], scale[h])[0], f"LED 0 now {now0}") sock.close() return out, fails 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) global BRIGHTNESS BRIGHTNESS = min(MAX_BRIGHTNESS, int(next((a.split("=", 1)[1] for a in sys.argv[1:] if a.startswith("--brightness=")), MAX_BRIGHTNESS))) set_fps(int(next((a.split("=", 1)[1] for a in sys.argv[1:] if a.startswith("--fps=")), FPS))) global UNICAST_SYNC UNICAST_SYNC = "--broadcast-only" not in sys.argv[1:] expect = next((a.split("=", 1)[1] for a in sys.argv[1:] if a.startswith("--expect=")), None) prefix = subnet or local_prefix() broadcast = f"{prefix}.255" # the sync is broadcast to this network's broadcast address rig = None if "--discover" in sys.argv[1:] else load_rig() if args: hosts = args elif rig: hosts = [d["ip"] for d in rig["devices"]] ROW_OF.update({n: d["row"] - 1 for n, d in enumerate(rig["devices"])}) print(f"rig map {os.path.basename(RIG_FILE)}: {len(hosts)} device(s)") for d in rig["devices"]: print(f" {d['name']} {d['ip']} row {d['row']} column {d['column']}" f"{' reversed' if d.get('reversed') else ''}{' usb ' + d['usb'] if d.get('usb') else ''}") print() if serial_port is None: usb = [d for d in rig["devices"] if d.get("usb")] if len(hosts) == 1 and usb: serial_port = usb[0]["usb"] else: hosts = find_devices(prefix, int(expect) if expect else None) if expect and len(hosts) < int(expect): print(f"warning: expected {expect} device(s), found {len(hosts)}") 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 if not any(a.startswith("--fps=") for a in sys.argv[1:]): # Every bar gets every frame, so the network carries bars x fps frames a second: past FRAME_BUDGET the # devices stop answering HTTP and frames are lost. A big rig runs slower unless --fps says otherwise. fps = max(1, min(FPS, FRAME_BUDGET // len(hosts))) if fps < FPS: set_fps(fps) print(f"{len(hosts)} devices: running at {fps} fps (the Wi-Fi carries about {FRAME_BUDGET} frames a second in all; --fps=N overrides)\n") if "--interactive" in sys.argv[1:] or "-i" in sys.argv[1:]: run_interactive(hosts, broadcast) return soak = next((a.split("=", 1)[1] for a in sys.argv[1:] if a.startswith("--soak=")), None) if soak: sys.exit(1 if run_soak(hosts, broadcast, float(soak)) else 0) out, fails = run_all(hosts, serial_port, broadcast) failures = 0 for h in hosts: print(f"== {h}") print("\n".join(out[h])) print() failures += fails[h] print("RESULT:", "all passed" if not failures else f"{failures} failed") sys.exit(1 if failures else 0) if __name__ == "__main__": main()