diff --git a/tools/ddp_test.py b/tools/ddp_test.py index ef53b42..53f8231 100644 --- a/tools/ddp_test.py +++ b/tools/ddp_test.py @@ -2,19 +2,26 @@ """ 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, the pixel data split across two -packets, and the PUSH flag on the last packet. After each tick, one broadcast sync ("LSY1" + seq) tells -all devices to show the frame they hold. The devices are driven together, from one sender. Through the +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 pattern comes back once the pixels stop. +test animations, and that the last frame stays up once the pixels stop. 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 --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) + 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 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 random import json import math import re @@ -32,12 +39,24 @@ LEDS = 119 PUSH = 0x01 VER1 = 0x40 RGB = 0x01 -TICK = 0.025 # seconds between ticks (40 fps) -ACK_WAIT = 0.02 # seconds to wait for each device's ack before the sync goes out anyway -ANIM_FRAMES = 40 # about 1 s +FPS = 60 # frames per second (--fps=N) +TICK = 1 / FPS # seconds between ticks +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 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 @@ -51,9 +70,9 @@ def send_frame(sock, host, pixels, seq): sock.sendto(packet(seq, split, raw[split:], True), (host, PORT)) -def send_sync(sock, seq): - """Broadcast a sync: every device shows the frame it holds.""" - sock.sendto(b"LSY1" + struct.pack(">I", seq & 0xFFFFFFFF), ("255.255.255.255", SYNC_PORT)) +def send_sync(sock, seq, broadcast): + """Broadcast a sync to the network's broadcast address: every device shows the frame it holds.""" + sock.sendto(b"LSY1" + struct.pack(">I", seq & 0xFFFFFFFF), (broadcast, SYNC_PORT)) def frame_sum(pixels): @@ -122,9 +141,17 @@ def anim_breathe(i, k): 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 [((i * 7 + k) % 256, (i * 13) % 256, (255 - i * 3) % 256) for i in range(LEDS)] + return [dim(((i * 7 + k) % 256, (i * 13) % 256, (255 - i * 3) % 256)) for i in range(LEDS)] def output_scale(host): @@ -148,17 +175,24 @@ 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): + 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.settimeout(ACK_WAIT) + 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) @@ -166,44 +200,83 @@ class Sender: with self.lock: self.frames.update(pixels_by_host) - def tick(self): + 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 - sent = [h for h in self.hosts if frames[h] is not None] - for h in sent: - send_frame(self.sock, h, frames[h], self.seq) - self.wait_acks(self.seq & 0x0F, sent) - send_sync(self.sock, self.seq) + 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) + 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) - def wait_acks(self, nibble, hosts): + 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} - deadline = time.time() + ACK_WAIT - while waiting and time.time() < deadline: - try: - data, addr = self.sock.recvfrom(64) - except OSError: - continue - if data[:4] == b"LAK1" and len(data) >= 5 and (data[4] & 0x0F) == nibble: - waiting.discard(addr[0]) + + 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} - def _run(self): + 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: - self.tick() + await self.tick(loop) next_tick += TICK delay = next_tick - time.monotonic() if delay > 0: - time.sleep(delay) + 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() @@ -212,7 +285,438 @@ class Sender: self.thread.join() -def run_all(hosts, serial_port): +# 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_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, + "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} + stats = {h: {"samples": 0, "bad": 0, "idle": 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(f[led]) for f in history[h]} for h in hosts} + + def sample(h, led=led): + r = get(h, f"/api/ddp?led={led}") + return h, led, tuple(r["rgb"]), r["active"], wants[h] + + for h, l, got, active, w in pool.map(sample, hosts): + st = stats[h] + 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 = get(h, "/api/ddp") + sy, sb = a["sync"], before[h]["sync"] + st = stats[h] + print(f"== {h}: frames +{sy['frames'] - sb['frames']}, shown +{sy['shown'] - sb['shown']}, " + f"samples {st['samples']}, " + f"mismatches {st['bad']}, 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} @@ -232,7 +736,7 @@ def run_all(hosts, serial_port): 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) + sender = Sender(sock, hosts, broadcast, acks=True) sent = {} # frame checksum -> pixels, for the serial log check stop_serial = threading.Event() serial_lines = [] @@ -262,7 +766,7 @@ def run_all(hosts, serial_port): time.sleep(0.1) waiting = frame(200) sent[frame_sum(waiting)] = waiting - send_sync(sock, sender.seq + 1) # sync mode is on: a sync was sent a moment ago + send_sync(sock, sender.seq + 1, broadcast) # 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) @@ -271,7 +775,7 @@ def run_all(hosts, serial_port): got = 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) + send_sync(sock, sender.seq + 2, broadcast) time.sleep(0.2) for h in hosts: got = get(h, "/api/ddp?led=0")["rgb"] @@ -326,7 +830,7 @@ def run_all(hosts, serial_port): for name, fn in ANIMATIONS.items(): for k in range(ANIM_FRAMES): - px = [fn(i, k) for i in range(LEDS)] + 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) @@ -348,20 +852,24 @@ def run_all(hosts, serial_port): after = get(h, "/api/ddp") check(h, "inactive after pixels stop", not after["active"]) now0 = get(h, "/api/ddp?led=0")["rgb"] - check(h, "pattern is shown again", now0 != expected([shown[0]], scale[h])[0], f"LED 0 now {now0}") + 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("--")] + 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))) + prefix = subnet or local_prefix() + broadcast = f"{prefix}.255" # the sync is broadcast to this network's broadcast address 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: @@ -370,7 +878,15 @@ def main(): print("note: --serial is only used when testing one device\n") serial_port = None - out, fails = run_all(hosts, serial_port) + 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}")