feat: sequences v2, bridges, and sim-controller
Rework sequences (engine, seqplay, envelope, API, web UI), add bridge support, add the host sim-controller and rig simulation tests, and update docs, presets and project tooling config. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
d664026ee5
commit
2543673bd8
68 files changed
+5761
-460
No files matched your search
@@ -0,0 +1,356 @@
|
||||
"""The whole rig, simulated: led-controller's host build (sim-controller/) bridged to led-simulator's 16
|
||||
drivers (2 columns x 8 rows, data-in heads in the middle). Checks what the bars actually show.
|
||||
|
||||
make sim # simulator + controller on this computer
|
||||
make test-sim # this file against them
|
||||
|
||||
Skipped unless the controller reports "sim": true in /status and the simulator answers on LED_SIM_URL
|
||||
(default http://localhost:8765).
|
||||
"""
|
||||
|
||||
import os
|
||||
import sys
|
||||
import time
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
import requests
|
||||
|
||||
from helpers import new_id, unique
|
||||
|
||||
SIM_URL = os.environ.get("LED_SIM_URL", "http://localhost:8765")
|
||||
ROWS, COLS, LEDS = 8, 2, 119
|
||||
BARS = list(range(1, ROWS * COLS + 1)) # strip n: row (n-1)//2, column (n-1)%2 (0 left, 1 right)
|
||||
|
||||
|
||||
def mac(n):
|
||||
return "02514d0000%02x" % n
|
||||
|
||||
|
||||
def row_of(n):
|
||||
return (n - 1) // COLS
|
||||
|
||||
|
||||
def col_of(n):
|
||||
return (n - 1) % COLS
|
||||
|
||||
|
||||
GROUPS = {"Left": [n for n in BARS if col_of(n) == 0], "Right": [n for n in BARS if col_of(n) == 1]}
|
||||
GROUPS.update({f"Row {r + 1}": [n for n in BARS if row_of(n) == r] for r in range(ROWS)})
|
||||
GROUPS.update({f"Bar {n:02d}": [n] for n in BARS})
|
||||
|
||||
# The rig layout is the simulator's (led-simulator/layout.py rig_placements); it sends it to the controller
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parents[2] / "led-simulator"))
|
||||
from layout import rig_placements # noqa: E402
|
||||
|
||||
|
||||
def places():
|
||||
"""{bar: [x0, y0, x1, y1]}: where each driver was told it sits (rig units, centre 0, y up)."""
|
||||
d = requests.get(SIM_URL + "/api/pixels", timeout=5).json()
|
||||
return {s["n"]: s.get("place") for s in d["strips"]}
|
||||
|
||||
|
||||
def led_x(place, i):
|
||||
x0, _, x1, _ = place
|
||||
return x0 + (x1 - x0) * (i + 0.5) / LEDS
|
||||
|
||||
|
||||
def frames():
|
||||
"""{bar: [(r, g, b), ...]} as the simulator's strips show them now."""
|
||||
d = requests.get(SIM_URL + "/api/pixels", timeout=5).json()
|
||||
out = {}
|
||||
for s in d["strips"]:
|
||||
b = bytes.fromhex(s["rgb"])
|
||||
out[s["n"]] = [tuple(b[i:i + 3]) for i in range(0, len(b), 3)]
|
||||
return out
|
||||
|
||||
|
||||
def lit(px, floor=8):
|
||||
return [i for i, c in enumerate(px) if max(c) > floor]
|
||||
|
||||
|
||||
def wait_for(check, timeout=6.0, every=0.1):
|
||||
"""Poll check() until it returns a truthy value; return its last value."""
|
||||
end = time.monotonic() + timeout
|
||||
while True:
|
||||
v = check()
|
||||
if v or time.monotonic() > end:
|
||||
return v
|
||||
time.sleep(every)
|
||||
|
||||
|
||||
def sample(seconds, every=0.04):
|
||||
out = []
|
||||
end = time.monotonic() + seconds
|
||||
while time.monotonic() < end:
|
||||
out.append(frames())
|
||||
time.sleep(every)
|
||||
return out
|
||||
|
||||
|
||||
@pytest.fixture(scope="module", autouse=True)
|
||||
def need_sim(c):
|
||||
try:
|
||||
st = c.get("/status").json()
|
||||
requests.get(SIM_URL + "/api/pixels", timeout=3).raise_for_status()
|
||||
except (requests.RequestException, ValueError):
|
||||
pytest.skip(f"no simulated rig (controller host build + led-simulator at {SIM_URL})")
|
||||
if not st.get("sim"):
|
||||
pytest.skip("the controller is not the simulator build")
|
||||
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
def rig(c, need_sim):
|
||||
"""All 16 bars registered and placed, a profile, the 26 groups and a zone over the whole rig."""
|
||||
want = {mac(n) for n in BARS}
|
||||
|
||||
def registered():
|
||||
return want <= set(c.get("/devices").json())
|
||||
|
||||
if not wait_for(registered, timeout=3):
|
||||
c.post("/devices/ping", json={"timeout_s": 2})
|
||||
assert wait_for(registered, timeout=15), "the simulator's 16 drivers did not register"
|
||||
|
||||
pid = new_id(c.post("/profiles", json={"name": unique("pytest-rig")}))
|
||||
assert c.post(f"/profiles/{pid}/apply").status_code == 200
|
||||
gids = {}
|
||||
for name, bars in GROUPS.items():
|
||||
r = c.post("/groups", json={"name": name, "devices": [mac(n) for n in bars]})
|
||||
assert r.status_code == 201, r.text
|
||||
gids[name] = new_id(r)
|
||||
zid = new_id(c.post("/zones", json={"name": unique("pytest-rig"), "group_ids": [gids["Left"], gids["Right"]]}))
|
||||
# Start unplaced, so the simulator sends its whole layout (it never overwrites a placed bar)
|
||||
c.post("/devices/layout", json={"placements": {mac(n): None for n in BARS}})
|
||||
seeded = requests.post(SIM_URL + "/api/seed-layout", timeout=60).json()
|
||||
yield {"profile": pid, "groups": gids, "zone": zid, "layout": seeded.get("sent")}
|
||||
c.post("/sequences/stop")
|
||||
c.post(f"/zones/{zid}/stop")
|
||||
c.delete(f"/zones/{zid}")
|
||||
for gid in gids.values():
|
||||
c.delete(f"/groups/{gid}")
|
||||
c.delete(f"/profiles/{pid}")
|
||||
|
||||
|
||||
def make_preset(c, **fields):
|
||||
body = {"name": unique("pytest-rig"), "brightness": 255, "colors": ["#ff0000"], "pattern": "on"}
|
||||
body.update(fields)
|
||||
r = c.post("/presets", json=body)
|
||||
assert r.status_code == 201, r.text
|
||||
return new_id(r)
|
||||
|
||||
|
||||
def all_dark(c, rig):
|
||||
c.post("/sequences/stop")
|
||||
c.put(f"/zones/{rig['zone']}", json={"group_ids": [rig["groups"]["Left"], rig["groups"]["Right"]]})
|
||||
c.post(f"/zones/{rig['zone']}/stop")
|
||||
assert wait_for(lambda: not any(lit(px) for px in frames().values())), "the rig did not go dark"
|
||||
|
||||
|
||||
def play_all(c, rig, preset_id):
|
||||
c.put(f"/zones/{rig['zone']}", json={"group_ids": [rig["groups"]["Left"], rig["groups"]["Right"]]})
|
||||
r = c.post(f"/zones/{rig['zone']}/play", json={"preset_id": preset_id})
|
||||
assert r.status_code == 200, r.text
|
||||
|
||||
|
||||
# --- the rig and its groups ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
def test_all_bars_registered(c, rig):
|
||||
devs = c.get("/devices").json()
|
||||
names = {devs[mac(n)]["name"] for n in BARS}
|
||||
assert names == {f"sim-{n:02d}" for n in BARS}
|
||||
assert all(devs[mac(n)]["transport"] == "espnow" for n in BARS)
|
||||
|
||||
|
||||
def test_simulator_gives_controller_its_layout(c, rig):
|
||||
assert rig["layout"] == {"updated": 16, "sent": 16, "failed": 0}
|
||||
want, centre = rig_placements({"rows": ROWS, "columns": COLS, "leds_per_strip": LEDS})
|
||||
devs = c.get("/devices").json()
|
||||
for n in BARS:
|
||||
got = devs[mac(n)]["placement"]
|
||||
assert all(abs(got[k] - want[n - 1][k]) < 0.01 for k in ("x0", "y0", "x1", "y1")), (n, got)
|
||||
assert c.get("/settings").json()["rig_center"] == centre
|
||||
|
||||
|
||||
def test_drivers_place_heads_in_the_middle(rig):
|
||||
"""Each driver's place (as the controller normalised it) starts next to the centre line and runs out."""
|
||||
pl = wait_for(lambda: (lambda p: p if all(p.values()) else None)(places()))
|
||||
assert pl, "drivers did not all get a place"
|
||||
for n in BARS:
|
||||
x0, y0, x1, y1 = pl[n]
|
||||
assert abs(x0) < 0.1 and abs(x1) > 0.8, (n, pl[n]) # far corners are diagonal: x1 is about 0.84
|
||||
assert (x1 < 0) == (col_of(n) == 0), (n, pl[n])
|
||||
assert y0 == y1
|
||||
ys = [pl[2 * r + 1][1] for r in range(ROWS)]
|
||||
assert ys == sorted(ys, reverse=True), "row 1 should be at the top"
|
||||
|
||||
|
||||
def test_seed_keeps_a_moved_bar(c, rig):
|
||||
moved = {"x0": 480, "y0": 600, "x1": 100, "y1": 300}
|
||||
c.post("/devices/layout", json={"placements": {mac(1): moved}})
|
||||
assert requests.post(SIM_URL + "/api/seed-layout", timeout=60).json()["sent"] is None
|
||||
assert c.get(f"/devices/{mac(1)}").json()["placement"] == moved
|
||||
want, _ = rig_placements({"rows": ROWS, "columns": COLS, "leds_per_strip": LEDS})
|
||||
c.post("/devices/layout", json={"placements": {mac(1): want[0]}})
|
||||
|
||||
|
||||
def test_bridge_status(c):
|
||||
st = c.get("/status").json()
|
||||
assert st["bridge"].endswith(":8766")
|
||||
assert st["espnow"]["bulk_failed"] == 0
|
||||
|
||||
|
||||
def test_all_26_groups_stored(c, rig):
|
||||
listing = c.get("/groups").json()
|
||||
assert len(GROUPS) == 26
|
||||
for name, gid in rig["groups"].items():
|
||||
g = c.get(f"/groups/{gid}").json()
|
||||
assert g["name"] == name
|
||||
assert sorted(g["devices"]) == sorted(mac(n) for n in GROUPS[name])
|
||||
assert gid in listing
|
||||
|
||||
|
||||
def test_driver_group_membership(c, rig):
|
||||
"""Every driver is told its groups; the controller waits for all 16 acks."""
|
||||
r = c.post("/devices/groups")
|
||||
assert r.status_code == 200, r.text
|
||||
assert r.json()["failed"] == 0 and r.json()["sent"] >= 16
|
||||
|
||||
|
||||
def test_group_edit_and_delete(c, rig):
|
||||
gid = new_id(c.post("/groups", json={"name": unique("pytest-tmp"), "devices": [mac(1)]}))
|
||||
assert c.put(f"/groups/{gid}", json={"name": "Renamed", "devices": [mac(2), mac(3).upper()]}).status_code == 200
|
||||
g = c.get(f"/groups/{gid}").json()
|
||||
assert g["name"] == "Renamed" and sorted(g["devices"]) == [mac(2), mac(3)]
|
||||
assert c.delete(f"/groups/{gid}").status_code == 200
|
||||
assert c.get(f"/groups/{gid}").status_code == 404
|
||||
|
||||
|
||||
@pytest.mark.parametrize("name", list(GROUPS))
|
||||
def test_group_lights_only_its_bars(c, rig, name):
|
||||
all_dark(c, rig)
|
||||
red = make_preset(c, pattern="on", colors=["#ff0000"])
|
||||
c.put(f"/zones/{rig['zone']}", json={"group_ids": [rig["groups"][name]]})
|
||||
assert c.post(f"/zones/{rig['zone']}/play", json={"preset_id": red}).status_code == 200
|
||||
want = set(GROUPS[name])
|
||||
|
||||
def shown():
|
||||
f = frames()
|
||||
on = {n for n, px in f.items() if px and all(c_[0] > 200 and c_[1] < 20 and c_[2] < 20 for c_ in px)}
|
||||
dark = {n for n, px in f.items() if not lit(px)}
|
||||
return on == want and dark == set(BARS) - want
|
||||
|
||||
assert wait_for(shown), f"{name}: expected bars {sorted(want)} red and the rest dark"
|
||||
c.delete(f"/presets/{red}")
|
||||
|
||||
|
||||
# --- the field patterns follow the bridge layout --------------------------------------------------------
|
||||
# A driver restarts its pattern on every beat and the controller's clock beats every 0.5 s (120 BPM),
|
||||
# so the delays here are shorter than a beat.
|
||||
|
||||
FIELD = ["sweep", "ripple", "spin", "grow", "field_wave"]
|
||||
|
||||
|
||||
@pytest.mark.parametrize("pattern", FIELD)
|
||||
def test_field_pattern_animates_across_rig(c, rig, pattern):
|
||||
all_dark(c, rig)
|
||||
pid = make_preset(c, pattern=pattern, colors=["#ff0000", "#0000ff"], delay=400, auto=True)
|
||||
play_all(c, rig, pid)
|
||||
shots = sample(1.5)
|
||||
seen = {n for f in shots for n, px in f.items() if lit(px)}
|
||||
changes = sum(1 for a, b in zip(shots, shots[1:]) if a != b)
|
||||
assert len(seen) == 16, f"{pattern}: bars never lit: {sorted(set(BARS) - seen)}"
|
||||
assert changes > len(shots) // 3, f"{pattern}: the frames hardly change ({changes} of {len(shots)})"
|
||||
c.delete(f"/presets/{pid}")
|
||||
|
||||
|
||||
def test_ripple_is_mirrored_about_the_centre(c, rig):
|
||||
"""Heads meet in the middle, so a ring from the centre lights the same LEDs on both bars of a row.
|
||||
|
||||
Each simulated driver sends frames on its own 30 fps clock, so single samples of a fast ring differ
|
||||
by a frame or two; the ring's position must agree on average and in most samples."""
|
||||
all_dark(c, rig)
|
||||
pid = make_preset(c, pattern="ripple", colors=["#ffffff"], delay=400, auto=True, n1=200)
|
||||
play_all(c, rig, pid)
|
||||
diffs, shifts = [], []
|
||||
for f in sample(2.0, every=0.02):
|
||||
for r in range(ROWS):
|
||||
a, b = lit(f[2 * r + 1]), lit(f[2 * r + 2])
|
||||
if a and b:
|
||||
diffs.append(len(set(a) ^ set(b)))
|
||||
shifts.append((min(a) + max(a)) / 2 - (min(b) + max(b)) / 2)
|
||||
c.delete(f"/presets/{pid}")
|
||||
assert len(diffs) > 50
|
||||
diffs.sort()
|
||||
mean_shift = sum(shifts) / len(shifts)
|
||||
assert diffs[len(diffs) // 2] <= 12, f"left and right bars differ by a median {diffs[len(diffs) // 2]} LEDs"
|
||||
assert abs(mean_shift) <= 3, f"the ring sits {mean_shift:.1f} LEDs further out on one side"
|
||||
|
||||
|
||||
def test_ripple_reaches_inner_rows_before_outer_rows(c, rig):
|
||||
all_dark(c, rig)
|
||||
pid = make_preset(c, pattern="ripple", colors=["#ffffff"], delay=450, auto=True)
|
||||
play_all(c, rig, pid)
|
||||
# Mean distance from the centre of the lit LEDs at their nearest point: rows 4 and 5 (index 3, 4) are
|
||||
# nearest the centre, so their heads light first in each ring.
|
||||
first_lit = {}
|
||||
t0 = time.monotonic()
|
||||
while time.monotonic() - t0 < 1.0 and len(first_lit) < 8:
|
||||
f = frames()
|
||||
for r in range(ROWS):
|
||||
if r not in first_lit and lit(f[2 * r + 1]) and min(lit(f[2 * r + 1])) < 5:
|
||||
first_lit[r] = time.monotonic() - t0
|
||||
time.sleep(0.01)
|
||||
assert {3, 4} <= set(first_lit), f"middle rows never lit at their heads: {first_lit}"
|
||||
c.delete(f"/presets/{pid}")
|
||||
|
||||
|
||||
def test_sweep_band_is_one_place_across_both_columns(c, rig):
|
||||
"""A left-to-right sweep is a vertical band: its lit LEDs share one x on every row, so it must not
|
||||
show on both columns at the same index (it would, if the drivers ignored their placements)."""
|
||||
all_dark(c, rig)
|
||||
pid = make_preset(c, pattern="sweep", colors=["#00ff00"], delay=450, auto=True, n1=0, n2=150)
|
||||
play_all(c, rig, pid)
|
||||
spreads = []
|
||||
pl = places()
|
||||
for f in sample(1.5):
|
||||
xs = [led_x(pl[n], i) for n, px in f.items() for i in lit(px, floor=60)]
|
||||
if len(xs) > 10:
|
||||
spreads.append(max(xs) - min(xs))
|
||||
assert len(spreads) > 10
|
||||
spreads.sort()
|
||||
median = spreads[len(spreads) // 2]
|
||||
assert median < 0.7, f"sweep band spans {median:.2f} of the rig's 1.9 width: placements not applied"
|
||||
c.delete(f"/presets/{pid}")
|
||||
|
||||
|
||||
# --- sequences over the row groups ---------------------------------------------------------------------
|
||||
|
||||
|
||||
def test_time_sequence_walks_down_the_rows(c, rig):
|
||||
all_dark(c, rig)
|
||||
red = make_preset(c, pattern="on", colors=["#ff0000"])
|
||||
g = rig["groups"]
|
||||
targets = [{"name": f"Row {r + 1}", "group_ids": [g[f"Row {r + 1}"]]} for r in range(ROWS)]
|
||||
steps = [{"preset_id": red, "seconds": 0.6, "targets": [r], "others": "off"} for r in range(ROWS)]
|
||||
seq = c.post("/sequences", json={
|
||||
"name": unique("pytest-rows"), "targets": targets, "lanes": [steps],
|
||||
"lane_opts": [{"mode": "time", "targets": list(range(ROWS))}], "advance_mode": "time", "loop": False,
|
||||
})
|
||||
assert seq.status_code == 201, seq.text
|
||||
sid = new_id(seq)
|
||||
assert c.post(f"/sequences/{sid}/play", json={"zone_id": rig["zone"]}).status_code == 200
|
||||
order = []
|
||||
end = time.monotonic() + 0.6 * ROWS + 1.5
|
||||
while time.monotonic() < end:
|
||||
f = frames()
|
||||
rows = {row_of(n) for n, px in f.items() if lit(px)}
|
||||
if len(rows) == 1:
|
||||
r = rows.pop()
|
||||
if not order or order[-1] != r:
|
||||
order.append(r)
|
||||
time.sleep(0.05)
|
||||
c.post("/sequences/stop")
|
||||
c.delete(f"/sequences/{sid}")
|
||||
c.delete(f"/presets/{red}")
|
||||
assert order == list(range(ROWS)), f"rows lit in order {order}"
|
||||
Reference in new issue
Block a user