feat(engine): Pi-side animation engine with protocol outputs and sequencer
Add src/engine, modelled on technicalkiwi/portal's player and sequence runner: - Pixel generator: runs the unchanged led-driver patterns under CPython (utime shim + NeoPixel-like buffer) on a per-zone render thread and streams frames to pixel outputs, with keepalive for static frames. - Output drivers: DDP, Art-Net (ArtDMX/ArtSync), sACN/E1.31, USB-DMX (Enttec Pro / Open DMX), plus an ESP32 preset output that reuses the existing preset + select delivery path. Registry in db/output.json, CRUD and test pattern at /outputs. - Sequencer: timed preset chains per zone (portal step shape), deadline scheduling, loop/repeat, resume after restart; legacy sequence records are migrated. Zone play/stop, sequence and scene play/stop endpoints. - CLI (python -m engine.cli), Outputs and Sequences modals, preset tiles drive pixel outputs, API/README docs, engine test suite. ESP32 firmware is unchanged. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
827eb97203
commit
a5a7fc575f
42 files changed
+4117
-75
No files matched your search
@@ -0,0 +1,37 @@
|
||||
"""Output registry validation."""
|
||||
|
||||
import pytest
|
||||
|
||||
from models.output import validate_output
|
||||
|
||||
|
||||
def test_valid_records_are_normalised():
|
||||
doc = validate_output({"name": " wall ", "protocol": "DDP", "host": "10.0.0.5", "pixel_count": "300",
|
||||
"color_order": "GRB"})
|
||||
assert doc["name"] == "wall" and doc["protocol"] == "ddp" and doc["pixel_count"] == 300
|
||||
assert doc["color_order"] == "grb" and doc["enabled"] is True and doc["port"] is None
|
||||
art = validate_output({"name": "a", "protocol": "artnet", "universe": 0, "pixel_count": 170})
|
||||
assert art["universe"] == 0 and art["host"] == ""
|
||||
sacn = validate_output({"name": "s", "protocol": "sacn", "universe": 5})
|
||||
assert sacn["universe"] == 5
|
||||
dmx = validate_output({"name": "d", "protocol": "dmx_serial", "serial_port": "/dev/ttyUSB0",
|
||||
"channel": 1, "pixel_count": 170})
|
||||
assert dmx["dmx_mode"] == "enttec_pro"
|
||||
|
||||
|
||||
@pytest.mark.parametrize("data,message", [
|
||||
({"protocol": "ddp", "host": "x"}, "name"),
|
||||
({"name": "a", "protocol": "foo"}, "protocol"),
|
||||
({"name": "a", "protocol": "ddp"}, "host"),
|
||||
({"name": "a", "protocol": "dmx_serial"}, "serial_port"),
|
||||
({"name": "a", "protocol": "dmx_serial", "serial_port": "/dev/x", "dmx_mode": "bad"}, "dmx_mode"),
|
||||
({"name": "a", "protocol": "dmx_serial", "serial_port": "/dev/x", "channel": 500, "pixel_count": 10}, "pixel_count"),
|
||||
({"name": "a", "protocol": "sacn", "universe": 0}, "universe"),
|
||||
({"name": "a", "protocol": "artnet", "pixel_count": 0}, "pixel_count"),
|
||||
({"name": "a", "protocol": "artnet", "brightness": 300}, "brightness"),
|
||||
({"name": "a", "protocol": "artnet", "color_order": "rgbw"}, "color_order"),
|
||||
({"name": "a", "protocol": "ddp", "host": "h", "port": "abc"}, "port"),
|
||||
])
|
||||
def test_invalid_records(data, message):
|
||||
with pytest.raises(ValueError, match=message):
|
||||
validate_output(data)
|
||||
@@ -0,0 +1,303 @@
|
||||
"""Protocol driver tests: packet layout, universe splitting, frame prep, UDP, DMX, ESP32."""
|
||||
|
||||
import asyncio
|
||||
import json
|
||||
import socket
|
||||
import struct
|
||||
|
||||
import pytest
|
||||
|
||||
from engine.outputs import open_output, parse_output_url
|
||||
from engine.outputs.artnet import ArtNetOutput, build_artdmx, build_artsync
|
||||
from engine.outputs.base import FrameOutput
|
||||
from engine.outputs.ddp import DdpOutput, build_ddp_packets
|
||||
from engine.outputs.dmx_serial import DmxSerialOutput, build_enttec_pro, dmx_universe
|
||||
from engine.outputs.sacn import SacnOutput, build_e131, multicast_address
|
||||
|
||||
|
||||
def frame(pixels, value=None):
|
||||
if value is None:
|
||||
return bytes(i % 256 for i in range(pixels * 3))
|
||||
return bytes(value) * pixels
|
||||
|
||||
|
||||
# -- base -------------------------------------------------------------------
|
||||
|
||||
def test_prepare_pads_truncates_and_scales():
|
||||
out = FrameOutput({"pixel_count": 2})
|
||||
assert out.prepare(b"\x10\x20\x30") == b"\x10\x20\x30\x00\x00\x00"
|
||||
assert out.prepare(bytes(range(9))) == bytes(range(6))
|
||||
half = FrameOutput({"pixel_count": 1, "brightness": 128})
|
||||
assert half.prepare(b"\xff\x80\x00") == bytes((128, 64, 0))
|
||||
assert out.prepare(b"\xff\xff\xff\xff\xff\xff", global_brightness=0) == bytes(6)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("order,expected", [
|
||||
("rgb", b"\x01\x02\x03"), ("grb", b"\x02\x01\x03"), ("bgr", b"\x03\x02\x01"),
|
||||
("brg", b"\x03\x01\x02"), ("rbg", b"\x01\x03\x02"), ("gbr", b"\x02\x03\x01"),
|
||||
])
|
||||
def test_color_order(order, expected):
|
||||
assert FrameOutput({"pixel_count": 1, "color_order": order}).prepare(b"\x01\x02\x03") == expected
|
||||
|
||||
|
||||
def test_reverse():
|
||||
out = FrameOutput({"pixel_count": 2, "reverse": True, "color_order": "grb"})
|
||||
assert out.prepare(b"\x01\x02\x03\x04\x05\x06") == b"\x05\x04\x06\x02\x01\x03"
|
||||
|
||||
|
||||
def test_parse_output_url():
|
||||
cfg = parse_output_url("ddp://10.0.0.5:4049?pixels=300&order=grb")
|
||||
assert cfg["protocol"] == "ddp" and cfg["host"] == "10.0.0.5" and cfg["port"] == 4049
|
||||
assert cfg["pixel_count"] == "300" and cfg["color_order"] == "grb"
|
||||
out = open_output(cfg)
|
||||
assert isinstance(out, DdpOutput) and out.pixel_count == 300 and out.port == 4049
|
||||
dmx = parse_output_url("dmx_serial:///dev/ttyUSB1?mode=open_dmx&channel=4")
|
||||
assert dmx["serial_port"] == "/dev/ttyUSB1" and dmx["dmx_mode"] == "open_dmx"
|
||||
assert isinstance(open_output(parse_output_url("e131://?universe=2")), SacnOutput)
|
||||
with pytest.raises(ValueError):
|
||||
open_output({"protocol": "nope"})
|
||||
|
||||
|
||||
# -- DDP --------------------------------------------------------------------
|
||||
|
||||
def test_ddp_packets_split_and_push():
|
||||
data = frame(600) # 1800 bytes -> 1440 + 360
|
||||
packets = build_ddp_packets(data, sequence=3)
|
||||
assert len(packets) == 2
|
||||
for pkt, (offset, length, push) in zip(packets, [(0, 1440, False), (1440, 360, True)]):
|
||||
flags, seq, dtype, dest, off, ln = struct.unpack(">BBBBIH", pkt[:10])
|
||||
assert flags & 0x40 and bool(flags & 0x01) == push
|
||||
assert seq == 3 and dtype == 0x0B and dest == 1
|
||||
assert off == offset and ln == length == len(pkt) - 10
|
||||
assert b"".join(p[10:] for p in packets) == data
|
||||
|
||||
|
||||
def test_ddp_three_packets_and_sequence_wraps():
|
||||
out = DdpOutput({"host": "127.0.0.1", "pixel_count": 1000})
|
||||
pkts = out.packets_for(frame(1000)) # 3000 bytes -> 3 packets
|
||||
assert [struct.unpack(">I", p[4:8])[0] for p in pkts] == [0, 1440, 2880]
|
||||
assert [p[0] & 0x01 for p in pkts] == [0, 0, 1]
|
||||
seqs = [out.next_sequence() for _ in range(16)]
|
||||
assert seqs[0] == 2 and 0 not in seqs and max(seqs) == 15 and seqs[-1] == 2
|
||||
|
||||
|
||||
# -- Art-Net ----------------------------------------------------------------
|
||||
|
||||
def test_artdmx_header():
|
||||
pkt = build_artdmx(0x1234, b"\x01\x02\x03", sequence=7)
|
||||
assert pkt[:8] == b"Art-Net\x00"
|
||||
assert struct.unpack("<H", pkt[8:10])[0] == 0x5000
|
||||
assert struct.unpack(">H", pkt[10:12])[0] == 14
|
||||
assert pkt[12] == 7 and pkt[13] == 0
|
||||
assert pkt[14] == 0x34 and pkt[15] == 0x12 # SubUni, Net
|
||||
assert struct.unpack(">H", pkt[16:18])[0] == 4 # padded to even
|
||||
assert pkt[18:] == b"\x01\x02\x03\x00"
|
||||
|
||||
|
||||
def test_artnet_universe_split():
|
||||
out = ArtNetOutput({"host": "127.0.0.1", "universe": 3, "pixel_count": 400})
|
||||
pkts = out.packets_for(out.prepare(frame(400)))
|
||||
assert [p[14] for p in pkts] == [3, 4, 5]
|
||||
assert [struct.unpack(">H", p[16:18])[0] for p in pkts] == [510, 510, 180]
|
||||
assert len({p[12] for p in pkts}) == 1
|
||||
|
||||
|
||||
def test_artnet_sequence_wrap_and_sync():
|
||||
out = ArtNetOutput({"host": "127.0.0.1", "sync": True, "pixel_count": 1})
|
||||
seqs = [out.next_sequence() for _ in range(256)]
|
||||
assert seqs[0] == 1 and seqs[254] == 255 and seqs[255] == 1
|
||||
pkts = out.packets_for(out.prepare(frame(1)))
|
||||
assert pkts[-1] == build_artsync()
|
||||
assert struct.unpack("<H", pkts[-1][8:10])[0] == 0x5200
|
||||
|
||||
|
||||
def test_artnet_defaults_to_broadcast():
|
||||
out = ArtNetOutput({})
|
||||
assert out.host == "255.255.255.255" and out.broadcast
|
||||
|
||||
|
||||
# -- sACN -------------------------------------------------------------------
|
||||
|
||||
def test_e131_layout():
|
||||
cid = bytes(range(16))
|
||||
pkt = build_e131(300, b"\x0a\x0b\x0c", sequence=9, cid=cid, source_name="test")
|
||||
assert len(pkt) == 126 + 3
|
||||
assert pkt[4:16] == b"ASC-E1.17\x00\x00\x00"
|
||||
root_fl = struct.unpack(">H", pkt[16:18])[0]
|
||||
assert root_fl >> 12 == 0x7 and root_fl & 0x0FFF == len(pkt) - 16
|
||||
assert struct.unpack(">I", pkt[18:22])[0] == 4
|
||||
assert pkt[22:38] == cid
|
||||
framing_fl = struct.unpack(">H", pkt[38:40])[0]
|
||||
assert framing_fl & 0x0FFF == len(pkt) - 38
|
||||
assert struct.unpack(">I", pkt[40:44])[0] == 2
|
||||
assert pkt[44:48] == b"test"
|
||||
assert pkt[108] == 100 # priority
|
||||
assert pkt[111] == 9 # sequence
|
||||
assert struct.unpack(">H", pkt[113:115])[0] == 300
|
||||
dmp_fl = struct.unpack(">H", pkt[115:117])[0]
|
||||
assert dmp_fl & 0x0FFF == len(pkt) - 115
|
||||
assert pkt[117] == 0x02 and pkt[118] == 0xA1
|
||||
assert struct.unpack(">H", pkt[123:125])[0] == 4 # start code + 3 slots
|
||||
assert pkt[125] == 0 and pkt[126:] == b"\x0a\x0b\x0c"
|
||||
|
||||
|
||||
def test_sacn_multicast_split_and_stable_cid():
|
||||
assert multicast_address(1) == "239.255.0.1"
|
||||
assert multicast_address(300) == "239.255.1.44"
|
||||
out = SacnOutput({"name": "roof", "universe": 1, "pixel_count": 200})
|
||||
pkts = out.packets_for(out.prepare(frame(200)))
|
||||
assert [addr for _p, addr in pkts] == [("239.255.0.1", 5568), ("239.255.0.2", 5568)]
|
||||
again = SacnOutput({"name": "roof", "universe": 1, "pixel_count": 200})
|
||||
assert out.cid == again.cid and len(out.cid) == 16
|
||||
pkts2 = out.packets_for(out.prepare(frame(200)))
|
||||
assert pkts2[0][0][111] == (pkts[0][0][111] + 1) & 0xFF
|
||||
uni = SacnOutput({"host": "10.0.0.9", "universe": 5, "pixel_count": 1})
|
||||
assert uni.packets_for(uni.prepare(frame(1)))[0][1] == ("10.0.0.9", 5568)
|
||||
|
||||
|
||||
# -- UDP round trip ---------------------------------------------------------
|
||||
|
||||
def _udp_receiver():
|
||||
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
|
||||
sock.bind(("127.0.0.1", 0))
|
||||
sock.settimeout(2.0)
|
||||
return sock
|
||||
|
||||
|
||||
@pytest.mark.parametrize("cls,pixels,expected_packets", [(DdpOutput, 600, 2), (ArtNetOutput, 400, 3)])
|
||||
def test_udp_round_trip(cls, pixels, expected_packets):
|
||||
recv = _udp_receiver()
|
||||
port = recv.getsockname()[1]
|
||||
|
||||
async def go():
|
||||
out = cls({"host": "127.0.0.1", "port": port, "pixel_count": pixels})
|
||||
await out.send(frame(pixels))
|
||||
await asyncio.sleep(0.05)
|
||||
if out._transport:
|
||||
out._transport.close()
|
||||
return out
|
||||
|
||||
out = asyncio.run(go())
|
||||
got = [recv.recvfrom(2048)[0] for _ in range(expected_packets)]
|
||||
recv.close()
|
||||
assert out.stats.frames == 1 and out.stats.packets == expected_packets and out.stats.errors == 0
|
||||
if cls is DdpOutput:
|
||||
assert b"".join(p[10:] for p in got) == frame(pixels)
|
||||
else:
|
||||
assert got[0][:8] == b"Art-Net\x00"
|
||||
|
||||
|
||||
# -- USB-DMX ----------------------------------------------------------------
|
||||
|
||||
class FakeSerial:
|
||||
def __init__(self, output):
|
||||
self.writes = []
|
||||
self.breaks = []
|
||||
self.closed = False
|
||||
self._bc = False
|
||||
|
||||
@property
|
||||
def break_condition(self):
|
||||
return self._bc
|
||||
|
||||
@break_condition.setter
|
||||
def break_condition(self, value):
|
||||
self._bc = value
|
||||
self.breaks.append(value)
|
||||
|
||||
def write(self, data):
|
||||
self.writes.append(bytes(data))
|
||||
|
||||
def close(self):
|
||||
self.closed = True
|
||||
|
||||
|
||||
def test_dmx_universe_channel_offset():
|
||||
u = dmx_universe(b"\x01\x02\x03", channel=10)
|
||||
assert len(u) == 512 and u[9:12] == b"\x01\x02\x03" and u[:9] == bytes(9)
|
||||
assert dmx_universe(bytes(600), channel=1) == bytes(512)
|
||||
|
||||
|
||||
def test_enttec_pro_framing():
|
||||
pkt = build_enttec_pro(bytes(512))
|
||||
assert pkt[0] == 0x7E and pkt[1] == 6
|
||||
assert struct.unpack("<H", pkt[2:4])[0] == 513
|
||||
assert pkt[4] == 0 and pkt[-1] == 0xE7 and len(pkt) == 518
|
||||
|
||||
|
||||
@pytest.mark.parametrize("mode", ["enttec_pro", "open_dmx"])
|
||||
def test_dmx_serial_send(mode):
|
||||
holder = {}
|
||||
|
||||
def factory(output):
|
||||
holder["ser"] = FakeSerial(output)
|
||||
return holder["ser"]
|
||||
|
||||
async def go():
|
||||
out = DmxSerialOutput({"serial_port": "/dev/null", "dmx_mode": mode, "channel": 4, "pixel_count": 2},
|
||||
serial_factory=factory)
|
||||
await out.send(b"\x0a\x0b\x0c\x0d\x0e\x0f")
|
||||
await out.close()
|
||||
return out
|
||||
|
||||
out = asyncio.run(go())
|
||||
ser = holder["ser"]
|
||||
assert out.stats.errors == 0 and ser.closed
|
||||
data = ser.writes[0]
|
||||
if mode == "enttec_pro":
|
||||
universe = data[5:-1]
|
||||
assert data[0] == 0x7E and ser.breaks == []
|
||||
else:
|
||||
assert len(data) == 513 and data[0] == 0
|
||||
universe = data[1:]
|
||||
assert ser.breaks[:2] == [True, False]
|
||||
assert universe[3:9] == b"\x0a\x0b\x0c\x0d\x0e\x0f"
|
||||
assert ser.writes[-1].count(0) >= 512 # close() sends black
|
||||
|
||||
|
||||
# -- ESP32 preset output --------------------------------------------------------
|
||||
|
||||
class FakeSender:
|
||||
def __init__(self):
|
||||
self.sent = []
|
||||
|
||||
async def send(self, data, addr=None):
|
||||
self.sent.append((data, addr))
|
||||
return True
|
||||
|
||||
|
||||
class FakeDevices(dict):
|
||||
def read(self, mac):
|
||||
return self.get(mac)
|
||||
|
||||
|
||||
def test_driver_output_matches_presets_push():
|
||||
from engine.outputs.driver import DriverOutput, resolve_device_macs
|
||||
|
||||
devices = FakeDevices({
|
||||
"aaaaaaaaaaaa": {"name": "roof", "transport": "espnow", "address": "aaaaaaaaaaaa"},
|
||||
"bbbbbbbbbbbb": {"name": "roof", "transport": "espnow", "address": "bbbbbbbbbbbb"},
|
||||
"cccccccccccc": {"name": "dj", "transport": "espnow", "address": "cccccccccccc"},
|
||||
})
|
||||
assert resolve_device_macs(["roof", "roof", "nobody"], devices) == [
|
||||
("roof", "aaaaaaaaaaaa"), ("roof", "bbbbbbbbbbbb")]
|
||||
|
||||
sender = FakeSender()
|
||||
out = DriverOutput(["dj"], sender_getter=lambda: sender, devices=devices, delay_s=0)
|
||||
payload = {"p": "rainbow", "c": ["#FF0000"], "d": 100, "b": 32, "a": True,
|
||||
"n1": 2, "n2": 0, "n3": 0, "n4": 0, "n5": 0, "n6": 0}
|
||||
delivered = asyncio.run(out.apply("3", payload))
|
||||
assert delivered == 2
|
||||
msgs = [json.loads(d) for d, _a in sender.sent]
|
||||
assert [a for _d, a in sender.sent] == ["cccccccccccc", "cccccccccccc"]
|
||||
# Same two-message sequence presets.js sends via /presets/push (without save).
|
||||
assert msgs[0] == {"v": "1", "presets": {"3": payload}}
|
||||
assert msgs[1] == {"v": "1", "select": {"dj": ["3"]}}
|
||||
|
||||
|
||||
def test_driver_output_without_sender_records_error():
|
||||
from engine.outputs.driver import DriverOutput
|
||||
|
||||
out = DriverOutput(["dj"], sender_getter=lambda: None, devices=FakeDevices())
|
||||
assert asyncio.run(out.apply("1", {"p": "on"})) == 0
|
||||
assert out.stats.errors == 1
|
||||
@@ -0,0 +1,242 @@
|
||||
"""ZonePlayer + Engine: frames reach pixel outputs, presets reach ESP32 drivers."""
|
||||
|
||||
import asyncio
|
||||
|
||||
import pytest
|
||||
|
||||
from engine.core import Engine, EngineError
|
||||
from engine.outputs.base import FrameOutput
|
||||
from engine.pattern_loader import PatternLibrary
|
||||
from engine.player import ZonePlayer
|
||||
from engine.zone_targets import ZoneTargets, resolve_zone
|
||||
|
||||
LIB = PatternLibrary()
|
||||
|
||||
|
||||
class RecordingOutput(FrameOutput):
|
||||
protocol = "test"
|
||||
keepalive_s = 0.2
|
||||
|
||||
def __init__(self, cfg):
|
||||
super().__init__(cfg)
|
||||
self.sent = []
|
||||
self.levels = []
|
||||
self.closed = False
|
||||
|
||||
async def send(self, rgb, global_brightness=255):
|
||||
self.levels.append(global_brightness)
|
||||
await super().send(rgb, global_brightness)
|
||||
|
||||
async def _send_prepared(self, payload):
|
||||
self.sent.append(payload)
|
||||
|
||||
async def close(self):
|
||||
await super().close()
|
||||
self.closed = True
|
||||
|
||||
|
||||
class RecordingDriver:
|
||||
kind = "preset"
|
||||
|
||||
def __init__(self, names):
|
||||
self.names = names
|
||||
self.applied = []
|
||||
self.closed = False
|
||||
|
||||
async def apply(self, preset_id, payload):
|
||||
self.applied.append((preset_id, payload))
|
||||
|
||||
async def close(self):
|
||||
self.closed = True
|
||||
|
||||
def status(self):
|
||||
return {"name": ",".join(self.names), "kind": "preset", "frames": len(self.applied),
|
||||
"packets": 0, "errors": 0, "last_error": None}
|
||||
|
||||
|
||||
def make_player(cfgs, drivers=(), brightness=255):
|
||||
made = {"outputs": [], "driver": None}
|
||||
|
||||
def output_factory(cfg):
|
||||
out = RecordingOutput(cfg)
|
||||
made["outputs"].append(out)
|
||||
return out
|
||||
|
||||
def driver_factory(names):
|
||||
made["driver"] = RecordingDriver(names)
|
||||
return made["driver"]
|
||||
|
||||
targets = ZoneTargets("z1", cfgs, list(drivers))
|
||||
player = ZonePlayer(targets, LIB, lambda: brightness, output_factory=output_factory,
|
||||
driver_factory=driver_factory)
|
||||
return player, made
|
||||
|
||||
|
||||
def test_frames_split_per_output_offset_and_brightness():
|
||||
async def go():
|
||||
player, made = make_player(
|
||||
[{"name": "a", "pixel_count": 2, "fps": 60},
|
||||
{"name": "b", "pixel_count": 1, "pixel_offset": 2, "color_order": "grb", "fps": 60}],
|
||||
brightness=128,
|
||||
)
|
||||
assert player.targets.frame_length == 3
|
||||
await player.start()
|
||||
await player.apply("1", {"p": "on", "c": ["#ff8000"], "b": 255})
|
||||
await asyncio.sleep(0.15)
|
||||
await player.stop()
|
||||
return made
|
||||
|
||||
made = asyncio.run(go())
|
||||
a, b = made["outputs"]
|
||||
assert a.sent[0] == bytes((128, 64, 0)) * 2
|
||||
assert b.sent[0] == bytes((64, 128, 0)) # grb
|
||||
assert set(a.levels[:-1]) == {128} # last send is the black frame from close()
|
||||
assert a.closed and b.closed and a.sent[-1] == bytes(6) # black on stop
|
||||
|
||||
|
||||
def test_animated_pattern_streams_and_keepalive_resends_static():
|
||||
async def go():
|
||||
player, made = make_player([{"name": "a", "pixel_count": 8, "fps": 60}])
|
||||
await player.start()
|
||||
await player.apply("1", {"p": "rainbow", "c": [], "d": 10, "b": 255, "n1": 8})
|
||||
await asyncio.sleep(0.4)
|
||||
rainbow_frames = len(made["outputs"][0].sent)
|
||||
await player.apply("2", {"p": "on", "c": ["#00ff00"], "b": 255})
|
||||
await asyncio.sleep(0.1)
|
||||
before = len(made["outputs"][0].sent)
|
||||
await asyncio.sleep(0.5) # static frame -> keepalive resends (0.2 s)
|
||||
after = len(made["outputs"][0].sent)
|
||||
await player.stop()
|
||||
return rainbow_frames, before, after, made
|
||||
|
||||
rainbow_frames, before, after, made = asyncio.run(go())
|
||||
assert rainbow_frames >= 10
|
||||
assert after - before >= 2
|
||||
assert made["outputs"][0].sent[before] == bytes((0, 255, 0)) * 8
|
||||
|
||||
|
||||
def test_mixed_zone_drives_esp32_and_pixels_together():
|
||||
async def go():
|
||||
player, made = make_player([{"name": "ddp", "pixel_count": 4}], drivers=["dj"])
|
||||
await player.start()
|
||||
await player.apply("7", {"p": "on", "c": ["#ffffff"], "b": 255})
|
||||
await asyncio.sleep(0.1)
|
||||
status = player.status()
|
||||
await player.stop()
|
||||
return made, status
|
||||
|
||||
made, status = asyncio.run(go())
|
||||
assert made["driver"].applied == [("7", {"p": "on", "c": ["#ffffff"], "b": 255})]
|
||||
assert made["outputs"][0].sent
|
||||
assert status["preset_id"] == "7" and len(status["outputs"]) == 2
|
||||
assert made["driver"].closed
|
||||
|
||||
|
||||
def test_drivers_false_skips_esp32():
|
||||
async def go():
|
||||
player, made = make_player([{"name": "ddp", "pixel_count": 1}], drivers=["dj"])
|
||||
await player.start()
|
||||
await player.apply("1", {"p": "on", "c": ["#ffffff"], "b": 255}, drivers=False)
|
||||
await asyncio.sleep(0.05)
|
||||
await player.stop()
|
||||
return made
|
||||
|
||||
made = asyncio.run(go())
|
||||
assert made["driver"].applied == [] and made["outputs"][0].sent
|
||||
|
||||
|
||||
def test_driver_only_zone_has_no_render_thread():
|
||||
async def go():
|
||||
player, made = make_player([], drivers=["roof"])
|
||||
await player.start()
|
||||
await player.apply("1", {"p": "rainbow"})
|
||||
await player.stop()
|
||||
return player, made
|
||||
|
||||
player, made = asyncio.run(go())
|
||||
assert player.renderer is None and made["driver"].applied
|
||||
|
||||
|
||||
# -- Engine --------------------------------------------------------------------
|
||||
|
||||
class FakeZones(dict):
|
||||
def read(self, id):
|
||||
return self.get(str(id))
|
||||
|
||||
|
||||
class FakeOutputs(dict):
|
||||
def by_name(self, name):
|
||||
return [o for o in self.values() if o.get("name") == name]
|
||||
|
||||
|
||||
def test_resolve_zone_splits_outputs_and_drivers():
|
||||
zones = FakeZones({"1": {"names": ["roof", "wall", "wall", "dj"]}})
|
||||
outputs = FakeOutputs({
|
||||
"1": {"id": "1", "name": "wall", "pixel_count": 100, "enabled": True},
|
||||
"2": {"id": "2", "name": "wall", "pixel_count": 50, "pixel_offset": 100, "enabled": True},
|
||||
"3": {"id": "3", "name": "dj", "pixel_count": 10, "enabled": False},
|
||||
})
|
||||
t = resolve_zone("1", zones, outputs)
|
||||
assert [c["id"] for c in t.frame_cfgs] == ["1", "2"]
|
||||
assert t.driver_names == ["roof", "dj"] # disabled output falls back to device name
|
||||
assert t.frame_length == 150
|
||||
assert resolve_zone("9", zones, outputs) is None
|
||||
|
||||
|
||||
def make_engine(targets_by_zone, payloads):
|
||||
created = []
|
||||
|
||||
def factory(targets, library, brightness):
|
||||
player, made = make_player(targets.frame_cfgs, targets.driver_names)
|
||||
created.append((player, made))
|
||||
return player
|
||||
|
||||
eng = Engine(
|
||||
library=LIB,
|
||||
zone_resolver=lambda zid: targets_by_zone.get(zid),
|
||||
payload_resolver=lambda pid: payloads.get(pid),
|
||||
player_factory=factory,
|
||||
sequences_model=FakeSequences(),
|
||||
)
|
||||
return eng, created
|
||||
|
||||
|
||||
class FakeSequences(dict):
|
||||
def read(self, id):
|
||||
return self.get(str(id))
|
||||
|
||||
def update(self, id, data):
|
||||
if str(id) not in self:
|
||||
return False
|
||||
self[str(id)].update(data)
|
||||
return True
|
||||
|
||||
def list(self):
|
||||
return list(self.keys())
|
||||
|
||||
|
||||
def test_engine_play_reuses_player_and_rebuilds_on_target_change():
|
||||
targets = {"1": ZoneTargets("1", [{"name": "a", "pixel_count": 2}], ["dj"])}
|
||||
payloads = {"10": {"p": "on", "c": ["#ff0000"]}, "11": {"p": "off"}}
|
||||
|
||||
async def go():
|
||||
eng, created = make_engine(targets, payloads)
|
||||
await eng.play("1", "10")
|
||||
await eng.play("1", "11")
|
||||
assert len(created) == 1
|
||||
targets["1"] = ZoneTargets("1", [{"name": "a", "pixel_count": 3}], ["dj"])
|
||||
await eng.play("1", "10")
|
||||
assert len(created) == 2 and created[0][1]["outputs"][0].closed
|
||||
with pytest.raises(EngineError):
|
||||
await eng.play("1", "missing")
|
||||
with pytest.raises(EngineError):
|
||||
await eng.play("nozone", "10")
|
||||
status = eng.status()
|
||||
assert status["zones"]["1"]["preset_id"] == "10"
|
||||
assert await eng.stop("1") is True
|
||||
assert eng.status()["zones"] == {}
|
||||
await eng.stop_all()
|
||||
return created
|
||||
|
||||
created = asyncio.run(go())
|
||||
assert [p for p, _ in created[0][1]["driver"].applied] == ["10", "11"]
|
||||
@@ -0,0 +1,119 @@
|
||||
"""The unchanged led-driver patterns run under the CPython shim."""
|
||||
|
||||
import threading
|
||||
import time
|
||||
|
||||
import pytest
|
||||
|
||||
from engine import mpcompat
|
||||
from engine.pattern_loader import PatternLibrary
|
||||
from engine.renderer import Renderer, RenderThread
|
||||
|
||||
LIB = PatternLibrary()
|
||||
NUM_LEDS = 24
|
||||
|
||||
|
||||
def payload(pattern, **kw):
|
||||
base = {"p": pattern, "c": ["#ff0000", "#00ff00", "#0000ff"], "d": 40, "b": 255, "a": True,
|
||||
"n1": 5, "n2": 5, "n3": 5, "n4": 5, "n5": 0, "n6": 0}
|
||||
base.update(kw)
|
||||
return base
|
||||
|
||||
|
||||
def test_library_loads_every_driver_pattern():
|
||||
assert LIB.errors == {}
|
||||
assert LIB.preset_class.__module__ == "led_driver_preset"
|
||||
assert len(LIB.classes) >= 30
|
||||
assert {"rainbow", "pulse", "chase", "on", "off"} <= set(LIB.ids())
|
||||
|
||||
|
||||
@pytest.mark.parametrize("pattern", sorted(LIB.classes))
|
||||
def test_pattern_renders(pattern):
|
||||
r = Renderer(LIB, NUM_LEDS)
|
||||
frames = r.render_virtual("1", payload(pattern), ticks=200, tick_ms=5)
|
||||
assert r.error is None
|
||||
assert frames, f"{pattern} wrote no frames"
|
||||
assert all(len(f) == NUM_LEDS * 3 for f in frames)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("pattern", ["rainbow", "colour_cycle", "plasma", "aurora", "scanner", "transition"])
|
||||
def test_animated_patterns_change(pattern):
|
||||
frames = Renderer(LIB, NUM_LEDS).render_virtual("1", payload(pattern), ticks=400, tick_ms=5)
|
||||
assert len(set(frames)) > 3
|
||||
|
||||
|
||||
def test_on_and_off_builtins():
|
||||
r = Renderer(LIB, 3)
|
||||
frames = r.render_virtual("1", {"p": "on", "c": ["#ff8000"], "b": 255}, ticks=5)
|
||||
assert frames == [bytes((255, 128, 0)) * 3] and r.generator is None
|
||||
frames = r.render_virtual("2", {"p": "off"}, ticks=5)
|
||||
assert frames == [bytes(9)]
|
||||
|
||||
|
||||
def test_preset_brightness_applies_like_device():
|
||||
frames = Renderer(LIB, 1).render_virtual("1", {"p": "on", "c": ["#ffffff"], "b": 128}, ticks=1)
|
||||
assert frames[-1] == bytes((128, 128, 128))
|
||||
|
||||
|
||||
def test_step_reset_rules_match_presets_select():
|
||||
r = Renderer(LIB, 4)
|
||||
r.render_virtual("1", payload("rainbow", n1=10), ticks=100, tick_ms=50)
|
||||
assert r.driver.step != 0
|
||||
kept = r.driver.step
|
||||
r.set_preset("1", payload("rainbow", n1=10)) # same preset again = beat, keeps step
|
||||
assert r.driver.step == kept
|
||||
r.set_preset("2", payload("rainbow")) # different preset resets
|
||||
assert r.driver.step == 0
|
||||
|
||||
|
||||
def test_unknown_pattern_goes_dark():
|
||||
r = Renderer(LIB, 2)
|
||||
frames = r.render_virtual("1", {"p": "does_not_exist"}, ticks=3)
|
||||
assert r.error and frames == [bytes(6)]
|
||||
|
||||
|
||||
def test_virtual_clock_sleep_does_not_block():
|
||||
started = time.monotonic()
|
||||
frames = Renderer(LIB, 4).render_virtual("1", payload("heartbeat", d=500), ticks=50)
|
||||
assert time.monotonic() - started < 2.0
|
||||
assert len(frames) > 10
|
||||
|
||||
|
||||
def test_render_thread_real_clock_and_hot_swap():
|
||||
got = []
|
||||
lock = threading.Lock()
|
||||
|
||||
def on_frame(f):
|
||||
with lock:
|
||||
got.append(f)
|
||||
|
||||
r = Renderer(LIB, 4, on_frame=on_frame)
|
||||
t = RenderThread(r).start()
|
||||
try:
|
||||
t.apply("1", payload("rainbow", d=10, n1=8))
|
||||
time.sleep(0.3)
|
||||
with lock:
|
||||
n_rainbow = len(got)
|
||||
assert n_rainbow >= 5
|
||||
t.apply("2", {"p": "on", "c": ["#0000ff"], "b": 255})
|
||||
time.sleep(0.1)
|
||||
with lock:
|
||||
assert got[-1] == bytes((0, 0, 255)) * 4
|
||||
assert r.pattern_id == "on"
|
||||
finally:
|
||||
t.stop()
|
||||
assert not t._thread.is_alive()
|
||||
|
||||
|
||||
def test_shim_installed_as_utime():
|
||||
import sys
|
||||
assert getattr(sys.modules["utime"], "__led_controller_shim__", False)
|
||||
clock = mpcompat.VirtualClock(1000)
|
||||
mpcompat.set_thread_clock(clock)
|
||||
try:
|
||||
import utime
|
||||
assert utime.ticks_ms() == 1000
|
||||
utime.sleep_ms(250)
|
||||
assert utime.ticks_diff(utime.ticks_ms(), 1000) == 250
|
||||
finally:
|
||||
mpcompat.set_thread_clock(None)
|
||||
@@ -0,0 +1,214 @@
|
||||
"""Sequence model normalisation/migration and the SequenceRunner."""
|
||||
|
||||
import asyncio
|
||||
|
||||
import pytest
|
||||
|
||||
from engine.core import EngineError
|
||||
from engine.sequence_runner import SequenceRunner
|
||||
from models.squence import _normalize, migrate_legacy
|
||||
|
||||
|
||||
class FakeSequences(dict):
|
||||
def read(self, id):
|
||||
return self.get(str(id))
|
||||
|
||||
def update(self, id, data):
|
||||
if str(id) not in self:
|
||||
return False
|
||||
self[str(id)].update(data)
|
||||
return True
|
||||
|
||||
def list(self):
|
||||
return list(self.keys())
|
||||
|
||||
|
||||
class FakeEngine:
|
||||
def __init__(self):
|
||||
self.plays = []
|
||||
|
||||
async def play(self, zone_id, preset_id, source="manual"):
|
||||
self.plays.append((zone_id, str(preset_id), source))
|
||||
|
||||
|
||||
def seq(zone="1", steps=("a", "b"), duration=0.02, **kw):
|
||||
doc = {"name": "s", "zone_id": zone, "loop": True, "repeat_count": 0, "active": False,
|
||||
"steps": [{"preset_id": p, "duration_s": duration} for p in steps]}
|
||||
doc.update(kw)
|
||||
return doc
|
||||
|
||||
|
||||
# -- model ----------------------------------------------------------------------
|
||||
|
||||
def test_normalize_clamps_and_defaults():
|
||||
doc = _normalize({"name": " x ", "zone_id": 2, "steps": [
|
||||
{"preset_id": 1, "duration_s": 0.01}, {"preset_id": "2", "duration_s": 9999}, {"preset_id": "3"}]})
|
||||
assert doc["name"] == "x" and doc["zone_id"] == "2" and doc["loop"] is True
|
||||
assert [s["duration_s"] for s in doc["steps"]] == [0.5, 600.0, 5.0]
|
||||
assert doc["steps"][0]["preset_id"] == "1"
|
||||
with pytest.raises(ValueError):
|
||||
_normalize({"steps": [{"duration_s": 3}]})
|
||||
|
||||
|
||||
def test_migrate_legacy_record():
|
||||
legacy = {"group_name": "Main Group", "presets": ["1", "2"], "sequence_duration": 3000,
|
||||
"sequence_transition": 500, "sequence_loop": False, "sequence_repeat_count": 2,
|
||||
"sequence_active": True, "sequence_index": 1, "sequence_start_time": 0}
|
||||
doc, migrated = migrate_legacy(legacy)
|
||||
assert migrated
|
||||
assert doc == {"name": "Main Group", "zone_id": None, "loop": False, "repeat_count": 2,
|
||||
"steps": [{"preset_id": "1", "duration_s": 3.0}, {"preset_id": "2", "duration_s": 3.0}],
|
||||
"active": False}
|
||||
same, migrated = migrate_legacy(doc)
|
||||
assert not migrated and same is doc
|
||||
|
||||
|
||||
# -- runner ---------------------------------------------------------------------
|
||||
|
||||
def test_steps_play_in_order_and_repeat_count_ends():
|
||||
async def go():
|
||||
model = FakeSequences({"1": seq(steps=("a", "b", "c"), repeat_count=2)})
|
||||
eng = FakeEngine()
|
||||
runner = SequenceRunner(eng, sequences_model=model)
|
||||
await runner.play("1")
|
||||
assert model["1"]["active"] is True
|
||||
await asyncio.sleep(0.4)
|
||||
return eng, model, runner
|
||||
|
||||
eng, model, runner = asyncio.run(go())
|
||||
assert [p for _z, p, _s in eng.plays] == ["a", "b", "c", "a", "b", "c"]
|
||||
assert all(s == "sequence" for _z, _p, s in eng.plays)
|
||||
assert model["1"]["active"] is False
|
||||
st = runner.status()["1"]
|
||||
assert st["running"] is False and st["pass"] == 2
|
||||
|
||||
|
||||
def test_no_loop_plays_once():
|
||||
async def go():
|
||||
model = FakeSequences({"1": seq(loop=False)})
|
||||
eng = FakeEngine()
|
||||
await SequenceRunner(eng, sequences_model=model).play("1")
|
||||
await asyncio.sleep(0.2)
|
||||
return eng
|
||||
|
||||
assert [p for _z, p, _s in asyncio.run(go()).plays] == ["a", "b"]
|
||||
|
||||
|
||||
def test_infinite_loop_until_stop():
|
||||
async def go():
|
||||
model = FakeSequences({"1": seq()})
|
||||
eng = FakeEngine()
|
||||
runner = SequenceRunner(eng, sequences_model=model)
|
||||
await runner.play("1")
|
||||
await asyncio.sleep(0.25)
|
||||
assert await runner.stop("1") is True
|
||||
n = len(eng.plays)
|
||||
await asyncio.sleep(0.1)
|
||||
return eng, n, model
|
||||
|
||||
eng, n, model = asyncio.run(go())
|
||||
assert n >= 6 and len(eng.plays) == n
|
||||
assert model["1"]["active"] is False
|
||||
|
||||
|
||||
def test_new_sequence_replaces_old_on_same_zone():
|
||||
async def go():
|
||||
model = FakeSequences({"1": seq(steps=("a",)), "2": seq(steps=("z",))})
|
||||
eng = FakeEngine()
|
||||
runner = SequenceRunner(eng, sequences_model=model)
|
||||
await runner.play("1")
|
||||
await asyncio.sleep(0.05)
|
||||
await runner.play("2")
|
||||
await asyncio.sleep(0.05)
|
||||
plays_after_switch = list(eng.plays)
|
||||
await runner.stop_all()
|
||||
return plays_after_switch, model, runner
|
||||
|
||||
plays, model, runner = asyncio.run(go())
|
||||
switch = plays.index(("1", "z", "sequence"))
|
||||
assert all(p == "z" for _z, p, _s in plays[switch:])
|
||||
assert model["1"]["active"] is False
|
||||
assert runner.status()["1"]["running"] is False
|
||||
|
||||
|
||||
def test_stop_all_keeps_active_for_resume():
|
||||
async def go():
|
||||
model = FakeSequences({"1": seq(), "2": seq(zone="2")})
|
||||
eng = FakeEngine()
|
||||
runner = SequenceRunner(eng, sequences_model=model)
|
||||
await runner.play("1")
|
||||
await runner.play("2")
|
||||
await runner.stop_all(persist=False)
|
||||
assert model["1"]["active"] and model["2"]["active"]
|
||||
fresh = SequenceRunner(FakeEngine(), sequences_model=model)
|
||||
resumed = await fresh.resume_active()
|
||||
await fresh.stop_all()
|
||||
return resumed
|
||||
|
||||
assert sorted(asyncio.run(go())) == ["1", "2"]
|
||||
|
||||
|
||||
def test_play_errors():
|
||||
async def go():
|
||||
model = FakeSequences({"nozone": seq(zone=None), "empty": seq(steps=())})
|
||||
runner = SequenceRunner(FakeEngine(), sequences_model=model)
|
||||
for sid in ("missing", "nozone", "empty"):
|
||||
with pytest.raises(EngineError):
|
||||
await runner.play(sid)
|
||||
|
||||
asyncio.run(go())
|
||||
|
||||
|
||||
def test_failing_step_does_not_kill_sequence():
|
||||
class Flaky(FakeEngine):
|
||||
async def play(self, zone_id, preset_id, source="manual"):
|
||||
await super().play(zone_id, preset_id, source)
|
||||
if preset_id == "a":
|
||||
raise EngineError("Preset not found", 404)
|
||||
|
||||
async def go():
|
||||
model = FakeSequences({"1": seq(loop=False)})
|
||||
eng = Flaky()
|
||||
runner = SequenceRunner(eng, sequences_model=model)
|
||||
await runner.play("1")
|
||||
await asyncio.sleep(0.2)
|
||||
return eng, runner
|
||||
|
||||
eng, runner = asyncio.run(go())
|
||||
assert [p for _z, p, _s in eng.plays] == ["a", "b"]
|
||||
assert runner.status()["1"]["error"] == "Preset not found"
|
||||
|
||||
|
||||
def test_manual_engine_play_stops_zone_sequence():
|
||||
from engine.core import Engine
|
||||
from engine.zone_targets import ZoneTargets
|
||||
|
||||
class NullPlayer:
|
||||
def __init__(self, targets, library, brightness):
|
||||
self.targets = targets
|
||||
|
||||
async def start(self):
|
||||
pass
|
||||
|
||||
async def apply(self, preset_id, payload, drivers=True):
|
||||
pass
|
||||
|
||||
async def stop(self):
|
||||
pass
|
||||
|
||||
def status(self):
|
||||
return {}
|
||||
|
||||
async def go():
|
||||
model = FakeSequences({"1": seq(zone="5", steps=("a", "b"))})
|
||||
eng = Engine(library=object(), zone_resolver=lambda z: ZoneTargets(z, [], ["dj"]),
|
||||
payload_resolver=lambda p: {"p": "on"}, player_factory=NullPlayer,
|
||||
sequences_model=model)
|
||||
await eng.sequences.play("1")
|
||||
await asyncio.sleep(0.03)
|
||||
await eng.play("5", "x") # manual pick
|
||||
return eng, model
|
||||
|
||||
eng, model = asyncio.run(go())
|
||||
assert eng.sequences.zone_for("1") is None
|
||||
assert model["1"]["active"] is False
|
||||
Reference in new issue
Block a user