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
@@ -146,3 +146,28 @@ def test_update_groups(c):
|
||||
assert data["total"] == len(espnow)
|
||||
assert data["sent"] + data["failed"] == data["total"]
|
||||
assert resp.status_code == (200 if data["failed"] == 0 else 503)
|
||||
|
||||
|
||||
def test_layout_saves_and_clears_placement(c, espnow_dev):
|
||||
resp = c.post("/devices/layout", json={"placements": {"aa:bb:cc:dd:ee:ff": {"x0": 100, "y0": 200, "x1": 300, "y1": 200}}})
|
||||
assert resp.status_code == 200, resp.text
|
||||
assert resp.json()["updated"] == 1 and resp.json()["sent"] >= 1 # this driver is placed, so it is sent
|
||||
dev = c.get(f"/devices/{ESPNOW_MAC}").json()
|
||||
assert dev["placement"] == {"x0": 100, "y0": 200, "x1": 300, "y1": 200}
|
||||
resp = c.post("/devices/layout", json={"placements": {ESPNOW_MAC: None}})
|
||||
assert resp.json()["updated"] == 1
|
||||
assert "placement" not in c.get(f"/devices/{ESPNOW_MAC}").json()
|
||||
|
||||
|
||||
def test_layout_needs_placements(c):
|
||||
assert c.post("/devices/layout", json={}).status_code == 400
|
||||
# Unknown devices and bad placements are skipped
|
||||
resp = c.post("/devices/layout", json={"placements": {"010203040506": {"x0": 1, "y0": 1, "x1": 2, "y1": 2},
|
||||
ESPNOW_MAC: {"x0": "a"}}})
|
||||
assert resp.status_code == 200 and resp.json()["updated"] == 0
|
||||
|
||||
|
||||
def test_layout_keeps_rig_center(c, espnow_dev):
|
||||
resp = c.post("/devices/layout", json={"placements": {}, "center": {"x": 500, "y": 350}})
|
||||
assert resp.status_code == 200
|
||||
assert c.get("/settings").json()["rig_center"] == {"x": 500, "y": 350}
|
||||
@@ -75,3 +75,19 @@ def test_push_requires_payload(c):
|
||||
def test_delete(c, preset):
|
||||
assert c.delete(f"/presets/{preset}").status_code == 200
|
||||
assert c.get(f"/presets/{preset}").status_code == 404
|
||||
|
||||
|
||||
def test_fade_and_beat_time_round_trip_and_send(c, preset):
|
||||
resp = c.put(f"/presets/{preset}", json={"pattern": "hit", "fade": 400, "beat_time": True, "n3": 2})
|
||||
assert resp.status_code == 200
|
||||
rec = c.get(f"/presets/{preset}").json()
|
||||
assert rec["fade"] == 400 and rec["beat_time"] is True
|
||||
# Goes out as a v3 frame; made-up driver name, so no real driver applies it
|
||||
resp = c.post("/presets/send", json={"preset_ids": [preset], "save": False, "targets": ["020000000099"]})
|
||||
assert resp.status_code == 200 and resp.json()["presets_sent"] == 1
|
||||
|
||||
|
||||
def test_animation_patterns_have_definitions(c):
|
||||
pats = c.get("/patterns").json()
|
||||
for name in ("hit", "keyframes", "sweep", "ripple", "spin", "grow", "field_wave"):
|
||||
assert name in pats and "n1" in pats[name], name
|
||||
@@ -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}"
|
||||
@@ -135,3 +135,151 @@ def test_editing_stops_playback(c, zone, clock):
|
||||
c.post(f"/sequences/{sid}/play", json={"zone_id": zone})
|
||||
c.put(f"/sequences/{sid}", json={"name": "edited"})
|
||||
assert c.get("/sequences/status").json()["active"] is False
|
||||
|
||||
|
||||
# ---------------------------------------------------------------- multi-driver lanes
|
||||
|
||||
# Made-up groups and drivers, so real drivers ignore every send
|
||||
TARGETS = [
|
||||
{"name": "left", "group_ids": ["pytest-g1"]},
|
||||
{"name": "mid", "group_ids": ["pytest-g2"]},
|
||||
{"name": "right", "devices": ["02:00:00:00:00:01"]},
|
||||
]
|
||||
|
||||
|
||||
def make(c, **rec):
|
||||
rec.setdefault("name", unique("pytest-seq"))
|
||||
return new_id(c.post("/sequences", json=rec))
|
||||
|
||||
|
||||
def wait_for(c, pred, beats=12):
|
||||
deadline = time.monotonic() + beats * BEAT_S
|
||||
st = None
|
||||
while time.monotonic() < deadline:
|
||||
st = c.get("/sequences/status").json()
|
||||
if pred(st):
|
||||
return st
|
||||
time.sleep(BEAT_S / 4)
|
||||
return st
|
||||
|
||||
|
||||
def test_targets_and_lane_opts_round_trip(c, profile):
|
||||
opts = [{"mode": "time", "offset": 1.5, "rate": 2, "targets": [2, 0],
|
||||
"chase": {"order": "bounce", "width": 1, "others": "off"}}]
|
||||
sid = make(c, targets=TARGETS, lane_opts=opts,
|
||||
lanes=[[{"preset_id": "1", "beats": 1, "targets": [0], "others": "off"}, {"rest": True, "beats": 1}]])
|
||||
rec = c.get(f"/sequences/{sid}").json()
|
||||
assert rec["targets"] == TARGETS
|
||||
assert rec["lane_opts"] == opts
|
||||
assert rec["lanes"][0][1]["rest"] is True
|
||||
|
||||
|
||||
def test_old_sequence_status_unchanged(c, zone, clock):
|
||||
a, b = presets(c, 2)
|
||||
sid = make(c, lanes=[[{"preset_id": a, "beats": 2}, {"preset_id": b, "beats": 1}]],
|
||||
lanes_group_ids=[["pytest-g1"]])
|
||||
c.post(f"/sequences/{sid}/play", json={"zone_id": zone})
|
||||
st = c.get("/sequences/status").json()
|
||||
assert st["num_lanes"] == 1 and st["lane0_beats_per_step"] == 2 and st["sequence_beats_per_pass"] == 3
|
||||
assert st["lanes"][0]["mode"] == "beats" and st["lanes"][0]["steps"] == 2
|
||||
|
||||
|
||||
def test_beat_and_time_lanes_together(c, zone, clock):
|
||||
a, b = presets(c, 2)
|
||||
sid = make(c, lanes=[[{"preset_id": a, "beats": 1}, {"preset_id": b, "beats": 1}],
|
||||
[{"preset_id": a, "seconds": 5}, {"preset_id": b, "seconds": 5}]],
|
||||
lane_opts=[{}, {"mode": "time"}])
|
||||
c.post(f"/sequences/{sid}/play", json={"zone_id": zone})
|
||||
st = wait_for(c, lambda s: s["lanes"][0]["step"] == 1)
|
||||
assert st["lanes"][0]["step"] == 1, "the beat lane moves on the beat"
|
||||
assert st["lanes"][1]["mode"] == "time" and st["lanes"][1]["step"] == 0, "the time lane holds its 5 s"
|
||||
assert st["lanes"][1]["duration_ms"] == 5000
|
||||
|
||||
|
||||
def test_offset_lane_starts_late(c, zone, clock):
|
||||
a, = presets(c, 1)
|
||||
sid = make(c, lanes=[[{"preset_id": a, "beats": 1}], [{"preset_id": a, "beats": 1}]],
|
||||
lane_opts=[{}, {"offset": 4}])
|
||||
c.post(f"/sequences/{sid}/play", json={"zone_id": zone})
|
||||
st = c.get("/sequences/status").json()
|
||||
assert st["lanes"][0]["started"] is True and st["lanes"][1]["started"] is False
|
||||
st = wait_for(c, lambda s: s["lanes"][1]["started"])
|
||||
assert st["lanes"][1]["started"] is True
|
||||
|
||||
|
||||
def test_rate_doubles_speed(c, zone, clock):
|
||||
a, b = presets(c, 2)
|
||||
sid = make(c, lanes=[[{"preset_id": a, "beats": 4}], [{"preset_id": a, "beats": 1}, {"preset_id": b, "beats": 1}]],
|
||||
lane_opts=[{}, {"rate": 2}])
|
||||
c.post(f"/sequences/{sid}/play", json={"zone_id": zone})
|
||||
st = c.get("/sequences/status").json()
|
||||
assert st["lanes"][1]["beats_in_step"] == 0.5
|
||||
|
||||
|
||||
def test_chase_moves_and_bounces(c, zone, clock):
|
||||
a, = presets(c, 1)
|
||||
sid = make(c, targets=TARGETS, lanes=[[{"preset_id": a, "beats": 1}]],
|
||||
lane_opts=[{"targets": [0, 1, 2], "chase": {"order": "bounce"}}])
|
||||
c.post(f"/sequences/{sid}/play", json={"zone_id": zone})
|
||||
seen = []
|
||||
deadline = time.monotonic() + 7 * BEAT_S
|
||||
while time.monotonic() < deadline:
|
||||
pos = c.get("/sequences/status").json()["lanes"][0]["pos"]
|
||||
if not seen or seen[-1] != pos:
|
||||
seen.append(pos)
|
||||
time.sleep(BEAT_S / 4)
|
||||
assert seen[:5] == [0, 1, 2, 1, 0][: len(seen[:5])] and len(seen) >= 4
|
||||
|
||||
|
||||
# ------------------------------------------------------------------- animations
|
||||
|
||||
|
||||
def test_animation_plays_once_alone(c, zone, clock):
|
||||
a, = presets(c, 1)
|
||||
aid = make(c, kind="animation", loop=False, targets=TARGETS[:1], lanes=[[{"preset_id": a, "beats": 2}]],
|
||||
lane_opts=[{"targets": [0]}])
|
||||
resp = c.post(f"/sequences/{aid}/fire", json={"zone_id": zone})
|
||||
assert resp.status_code == 200 and resp.json()["wait"] == "now"
|
||||
st = c.get("/sequences/status").json()
|
||||
assert st["active"] is False and st["overlay"]["active"] is True and st["overlay"]["sequence_id"] == aid
|
||||
st = wait_for(c, lambda s: not s["overlay"]["active"])
|
||||
assert st["overlay"]["active"] is False
|
||||
|
||||
|
||||
def test_animation_over_sequence_keeps_time(c, zone, clock):
|
||||
a, b = presets(c, 2)
|
||||
# A 6-beat pass, so the beat count can't wrap round while the animation plays
|
||||
sid = make(c, lanes=[[{"preset_id": a, "beats": 3}, {"preset_id": b, "beats": 3}]],
|
||||
lanes_group_ids=[["pytest-g1"]])
|
||||
aid = make(c, kind="animation", loop=False, lanes=[[{"preset_id": b, "beats": 3}]],
|
||||
targets=[{"group_ids": ["pytest-g1"]}], lane_opts=[{"targets": [0]}])
|
||||
c.post(f"/sequences/{sid}/play", json={"zone_id": zone})
|
||||
c.post(f"/sequences/{aid}/fire", json={}) # the playing sequence's zone
|
||||
st = wait_for(c, lambda s: s["sequence_beat_at"] >= 2, beats=4)
|
||||
assert st["overlay"]["active"] is True and st["active"] is True and st["sequence_id"] == sid
|
||||
assert st["sequence_beat_at"] >= 2, "the sequence keeps counting under the animation"
|
||||
st = wait_for(c, lambda s: not s["overlay"]["active"])
|
||||
assert st["overlay"]["active"] is False and st["active"] is True and st["sequence_id"] == sid
|
||||
|
||||
|
||||
def test_animation_step_fires_overlay(c, zone, clock):
|
||||
a, b = presets(c, 2)
|
||||
aid = make(c, kind="animation", loop=False, lanes=[[{"preset_id": b, "beats": 2}]])
|
||||
sid = make(c, lanes=[[{"preset_id": a, "beats": 1}, {"animation_id": aid, "beats": 1, "length": "animation"}]])
|
||||
c.post(f"/sequences/{sid}/play", json={"zone_id": zone})
|
||||
st = wait_for(c, lambda s: s["overlay"]["active"])
|
||||
assert st["overlay"]["active"] is True and st["overlay"]["sequence_id"] == aid
|
||||
assert st["lanes"][0]["beats_in_step"] == 2, "the step lasts as long as the animation"
|
||||
|
||||
|
||||
def test_overlay_stop_and_fire_errors(c, zone, clock):
|
||||
a, = presets(c, 1)
|
||||
aid = make(c, kind="animation", loop=True, lanes=[[{"preset_id": a, "beats": 1}]])
|
||||
assert c.post("/sequences/999999/fire", json={"zone_id": zone}).status_code == 404
|
||||
c.post("/sequences/stop")
|
||||
assert c.post(f"/sequences/{aid}/fire", json={}).status_code == 400 # no zone, nothing playing
|
||||
c.post(f"/sequences/{aid}/fire", json={"zone_id": zone, "wait": "beat"})
|
||||
st = wait_for(c, lambda s: s["overlay"]["active"], beats=3)
|
||||
assert st["overlay"]["active"] is True
|
||||
assert c.post("/sequences/overlay/stop").json() == {"ok": True}
|
||||
assert c.get("/sequences/status").json()["overlay"]["active"] is False
|
||||
+27
-4
@@ -32,6 +32,10 @@ v2 default blob:
|
||||
u8 target_count
|
||||
each: u8 len; target name utf-8
|
||||
|
||||
v3: as v2, but every preset record is followed by an extension block:
|
||||
u8 ext_len; then entries u8 key, u8 len, value — key 1 fade-in ms (u16), key 2 beat timing (u8, 1 = durations
|
||||
in quarter beats). Readers skip keys they don't know. Only frames whose presets use them are v3.
|
||||
|
||||
Legacy v1: sections are UTF-8 JSON text (see ``parse_binary_envelope_v1``).
|
||||
|
||||
Keep ``5 + lp + ls + ld`` ≤ 245 for a single ESP-NOW frame body.
|
||||
@@ -45,7 +49,22 @@ from typing import Any, Dict, List, Optional, Tuple
|
||||
|
||||
BINARY_ENVELOPE_VERSION_1 = 1
|
||||
BINARY_ENVELOPE_VERSION_2 = 2
|
||||
BINARY_ENVELOPE_VERSION_3 = 3
|
||||
HEADER_LEN = 5
|
||||
EXT_FADE = 1
|
||||
EXT_BEAT = 2
|
||||
|
||||
|
||||
def _preset_ext(preset: Dict[str, Any]) -> bytes:
|
||||
fade = preset.get("f") or preset.get("fade") or 0
|
||||
fade = max(0, min(10000, int(fade)))
|
||||
beat = 1 if (preset.get("tb") or preset.get("beat_time")) else 0
|
||||
body = b""
|
||||
if fade:
|
||||
body += bytes([EXT_FADE, 2]) + struct.pack("<H", fade)
|
||||
if beat:
|
||||
body += bytes([EXT_BEAT, 1, 1])
|
||||
return body
|
||||
|
||||
|
||||
def brightness_wire_from_0_255(value: int) -> int:
|
||||
@@ -126,11 +145,14 @@ def _pack_preset_dict(name: str, preset: Dict[str, Any]) -> bytes:
|
||||
return b"".join(parts)
|
||||
|
||||
|
||||
def _pack_presets_blob(presets: Dict[str, Any]) -> bytes:
|
||||
def _pack_presets_blob(presets: Dict[str, Any], v3: bool = False) -> bytes:
|
||||
items = [(k, v) for k, v in presets.items() if isinstance(v, dict)]
|
||||
out = [bytes([len(items)])]
|
||||
for name, pdata in items:
|
||||
out.append(_pack_preset_dict(str(name), pdata))
|
||||
if v3:
|
||||
ext = _preset_ext(pdata)
|
||||
out.append(bytes([len(ext)]) + ext)
|
||||
return b"".join(out)
|
||||
|
||||
|
||||
@@ -196,9 +218,10 @@ def pack_binary_envelope_v2(
|
||||
default_targets: Optional[list] = None,
|
||||
brightness_0_255: Optional[int] = None,
|
||||
) -> bytes:
|
||||
"""Build a v2 envelope (native binary sections, no JSON)."""
|
||||
"""Build a v2 envelope (native binary sections, no JSON); v3 when a preset has a fade or beat timing."""
|
||||
v3 = bool(presets) and any(isinstance(v, dict) and _preset_ext(v) for v in presets.values())
|
||||
presets_bytes = (
|
||||
_pack_presets_blob(presets) if presets is not None and presets else b""
|
||||
_pack_presets_blob(presets, v3) if presets is not None and presets else b""
|
||||
)
|
||||
select_bytes = (
|
||||
_pack_select_blob(select) if select is not None and select else b""
|
||||
@@ -220,7 +243,7 @@ def pack_binary_envelope_v2(
|
||||
if brightness_0_255 is None
|
||||
else brightness_wire_from_0_255(brightness_0_255)
|
||||
)
|
||||
header = bytes([BINARY_ENVELOPE_VERSION_2, br_wire, lp, ls, ld])
|
||||
header = bytes([BINARY_ENVELOPE_VERSION_3 if v3 else BINARY_ENVELOPE_VERSION_2, br_wire, lp, ls, ld])
|
||||
return header + presets_bytes + select_bytes + default_bytes
|
||||
|
||||
|
||||
|
||||
@@ -4,3 +4,6 @@ p2 = {"pattern":"on","colors":["#102030"],"delay":0,"brightness":0,"auto":True}
|
||||
a = pack_binary_envelope_v2(presets={"7":p,"8":p2}, brightness_0_255=128).hex()
|
||||
b = pack_binary_envelope_v2(select={"mirror":["7"],"roof":["8",12]}).hex()
|
||||
print(a); print(b)
|
||||
p3 = {"p":"hit","c":["#ffffff"],"d":0,"b":255,"a":False,"n1":10,"n3":400,"f":250,"tb":1}
|
||||
p4 = {"pattern":"keyframes","colors":["#ff0000","#0000ff"],"delay":800,"fade":1200}
|
||||
print(pack_binary_envelope_v2(presets={"9":p3,"10":p4}).hex())
|
||||
@@ -23,5 +23,15 @@ int main(void)
|
||||
env_add_select(&sb, "roof", "8", 12);
|
||||
hex(out, env_frame(out, 128, &pb, NULL));
|
||||
hex(out, env_frame(out, -1, NULL, &sb));
|
||||
// v3: presets with a fade or beat timing
|
||||
cJSON *p3 = cJSON_Parse("{\"p\":\"hit\",\"c\":[\"#ffffff\"],\"d\":0,\"b\":255,\"a\":false,\"n1\":10,\"n3\":400,\"f\":250,\"tb\":1}");
|
||||
cJSON *p4 = cJSON_Parse("{\"pattern\":\"keyframes\",\"colors\":[\"#ff0000\",\"#0000ff\"],\"delay\":800,\"fade\":1200}");
|
||||
env_blob_t vb;
|
||||
env_blob_init(&vb);
|
||||
env_add_preset(&vb, "9", p3);
|
||||
env_add_preset(&vb, "10", p4);
|
||||
hex(out, env_frame(out, -1, &vb, NULL));
|
||||
// A v2 preset does not join a v3 blob
|
||||
printf("%d\n", env_add_preset(&vb, "7", p) ? 1 : 0);
|
||||
return 0;
|
||||
}
|
||||
Reference in new issue
Block a user